Duply-code

From duply
Jump to: navigation, search

duply sourcecode

duply's svn repository is not the most recent source for the code. Usually the svn only gets updated on releases. But not always. Development snapshots are taken daily. These are not guaranteed to work, but might contain unreleased fixes. Check the snapshot's changelog header accordingly.

SVN access

Browse the repository

http://ftplicity.svn.sourceforge.net/viewvc/ftplicity/duply/trunk/

SVN access

svn co https://ftplicity.svn.sourceforge.net/svnroot/ftplicity/duply/trunk duply

SVN Log

http://ftplicity.svn.sourceforge.net/viewvc/ftplicity/duply/?view=log

Latest Development Snapshot

mod time 2017-03-29

plain/text -> http://duply.net/tmp/duply.sh

  1. #!/usr/bin/env bash
  2. #
  3. ################################################################################
  4. # duply (grown out of ftplicity), is a shell front end to duplicity that #
  5. # simplifies the usage by managing settings for backup jobs in profiles. #
  6. # It supports executing multiple commands in a batch mode to enable single #
  7. # line cron entries and executes pre/post backup scripts. #
  8. # Since version 1.5.0 all duplicity backends are supported. Hence the name #
  9. # changed from ftplicity to duply. #
  10. # See http://duply.net or http://ftplicity.sourceforge.net/ for more info. #
  11. # (c) 2006 Christiane Ruetten, Heise Zeitschriften Verlag, Germany #
  12. # (c) 2008-2016 Edgar Soldin (changes since version 1.3) #
  13. ################################################################################
  14. # LICENSE: #
  15. # This program is licensed under GPLv2. #
  16. # Please read the accompanying license information in gpl.txt. #
  17. ################################################################################
  18. # TODO/IDEAS/KNOWN PROBLEMS:
  19. # - possibility to restore time frames (incl. deleted files)
  20. # realizable by listing each backup and restore from
  21. # oldest to the newest, problem: not performant
  22. # - search file in all backups function and show available
  23. # versions with backups date (list old avail since 0.6.06)
  24. # - edit profile opens conf file in vi
  25. # - implement log-fd interpretation
  26. # - add a duplicity option check against the options pending
  27. # deprecation since 0.5.10 namely --time-separator
  28. # --short-filenames
  29. # --old-filenames
  30. # - add 'exclude_<command>' list usage eg. exclude_verify
  31. # - featreq 25: a download/install duplicity option
  32. # - hint on install software if a piece is missing
  33. # - import/export profile from/to .tgz function !!!
  34. #
  35. # CHANGELOG:
  36. # - bugfix: never insert creds into file:// targets
  37. # - bugfix: avail profiles hint sometimes shortend the names by one char
  38. #
  39. # 2.0.1 (16.11.2016)
  40. # - bugfix 104: Duply 2.0 sets wrong archive dir, --name always 'duply_'
  41. #
  42. # 2.0 (27.10.2016)
  43. # made this a major version change, as we broke backward compatibility anyway
  44. # (see last change in v1.10). got complaints that rightfully pointed out
  45. # that should only come w/ a major version change. so, here we go ;)
  46. # if your backend stops working w/ this version create a new profile and
  47. # export the env vars needed as described in the comments of the conf file
  48. # directly above the SOURCE setting.
  49. # Changes:
  50. # - making sure multi spaces in TARGET survive awk processing
  51. # - new env var PROFILE exported to scripts
  52. # - fix 102: expose a unique timestamp variable for pre/post scripts
  53. # actually a featreq. exporting RUN_START nanosec unix timestamp
  54. # - fix 101: GPG_AGENT_INFO is 'bogus' (thx Thomas Harning Jr.)
  55. # - fix 96: duply cannot handle two consecutive spaces in paths
  56. #
  57. # 1.11.3 (29.5.2016)
  58. # - fix wrong "WARNING: No running gpg-agent ..." when sign key was not set
  59. #
  60. # 1.11.2 (11.2.2016)
  61. # - fix "gpg: unsafe" version print out
  62. # - bugfix 91: v1.11 [r47] broke asymmetric encryption when using GPG_KEYS_ENC
  63. # - bugfix 90: S3: TARGET_USER/PASS have no effect, added additional
  64. # documentation about needed env vars to template conf file
  65. #
  66. # 1.11.1 (18.12.2015)
  67. # - bugfix 89: "Duply has trouble with PYTHON-interpreter" on OSX homebrew
  68. # - reverted duply's default PYTHON to 'python'
  69. #
  70. # 1.11 (24.11.2015)
  71. # - remove obsolete --ssh-askpass routine
  72. # - add PYTHON conf var to allow global override of used python interpreter
  73. # - enforced usage of "python2" in PATH as default interpreter for internal
  74. # use _and_ to run duplicity (setup.py changed the shebang to the fixed
  75. # path /usr/bin/python until 0.7.05, which we circumvent this way)
  76. # - featreq 36: support gpg-connect-agent as a means to detect if an agent is
  77. # running (thx Thomas Harning Jr.), used gpg-agent for detection though
  78. # - quotewrapped run_cmd parameters to protect it from spaces eg. in TMP path
  79. # - key export routine respects gpg-agent usage now
  80. #
  81. # 1.10.1 (19.8.2015)
  82. # - bugfix 86: Duply+Swift outputs warning
  83. # - bugfix 87: Swift fails without BACKEND_URL
  84. #
  85. # 1.10 (31.7.2015)
  86. # - featreq 37: busybox issues - fix awk, grep version detection,
  87. # fix grep failure because --color=never switch is unsupported
  88. # (thx Thomas Harning Jr. for reporting and helping to debug/fix it)
  89. # - bugfix 81: --exclude-globbing-filelist is deprecated since 0.7.03
  90. # (thx Joachim Wiedorn, also for maintaining the debian package)
  91. # - implemented base-/dirname as bash functions
  92. # - featreq 31 " Support for duplicity Azure backend " - ignored a
  93. # contributed patch by Scott McKenzie and instead opted for removing almost
  94. # all code that deals with special env vars required by backends.
  95. # adding and modifying these results in too much overhead so i dropped this
  96. # feature. the future alternative for users is to consult the duplicity
  97. # manpage and add the needed export definitions to the conf file.
  98. # appended a commented example to the template conf below the auth section.
  99. #
  100. # 1.9.2 (21.6.2015)
  101. # - bugfix: exporting keys with gpg2.1 works now (thx Philip Jocks)
  102. # - documented GPG_OPTS needed for gpg2.1 to conf template (thx Troy Engel)
  103. # - bugfix 82: GREP_OPTIONS=--color=always disrupted time calculation
  104. # - added GPG conf var (see conf template for details)
  105. # - added grep version output as it is an integral needed binary
  106. # - added PYTHONPATH printout in version output
  107. #
  108. # 1.9.1 (13.10.2014)
  109. # - export CMD_ERR now for scripts to detect if CMD_PREV failed/succeeded
  110. # - bugfix: CMD_PREV contained command even if it was skipped
  111. #
  112. # 1.9.0 (24.8.2014)
  113. # - bugfix: env vars were not exported when external script was executable
  114. # - rework GPG_KEY handling, allow virtually anything now (uid, keyid etc.)
  115. # see gpg manpage, section "How to specify a user ID"
  116. # let gpg complain when the delivered values are invalid for whatever reason
  117. # - started to rework tmp space checking, exposed folder & writable check
  118. # TODO: reimplement enough file space available checking
  119. #
  120. # 1.8.0 (13.7.2014)
  121. # - add command verifyPath to expose 'verify --file-to-restore' action
  122. # - add time parameter support to verify command
  123. # - add section time formats to usage output
  124. #
  125. # 1.7.4 (24.6.2014)
  126. # - remove ubuntu one support, service is discontinued
  127. # - featreq 31: add authenticated swift (contributed by Justus Seifert)
  128. #
  129. # 1.7.3 (3.4.2014)
  130. # - bugfix: test routines, gpg2 asked for passphrase although GPG_PW was set
  131. #
  132. # 1.7.2 (1.4.2014 "April,April")
  133. # - bugfix: debian Bug#743190 "duply no longer allows restoration without
  134. # gpg passphrase in conf file"
  135. # GPG_AGENT_INFO env var is now needed to trigger --use-agent
  136. # - bugfix: gpg keyenc test routines didn't work if GPG_PW was not set
  137. #
  138. # 1.7.1 (30.3.2014)
  139. # - bugfix: purge-* commands renamed to purgeFull, purgeIncr due to
  140. # incompatibility with new minus batch separator
  141. #
  142. # 1.7.0 (20.3.2014)
  143. # - disabled gpg key id plausibility check, too many valid possibilities
  144. # - featreq 7 "Halt if precondition fails":
  145. # added and(+), or(-) batch command(separator) support
  146. # - featreq 26 "pre/post script with shebang line":
  147. # if a script is flagged executable it's executed in a subshell
  148. # now as opposed to sourced to bash, which is the default
  149. # - bugfix: do not check if dpbx, swift credentials are set anymore
  150. # - bugfix: properly escape profile name, archdir if used as arguments
  151. # - add DUPL_PRECMD conf setting for use with e.g. trickle
  152. #
  153. # 1.6.0 (1.1.2014)
  154. # - support gs backend
  155. # - support dropbox backend
  156. # - add gpg-agent support to gpg test routines
  157. # - autoenable --use-agent if passwords were not defined in config
  158. # - GPG_OPTS are now honored everywhere, keyrings or complete gpg
  159. # homedir can thus be configured to be located anywhere
  160. # - always import both secret and public key if avail from config profile
  161. # - new explanatory comments in initial exclude file
  162. # - bugfix 7: Duply only imports one key at a time
  163. #
  164. # 1.5.11 (19.07.2013)
  165. # - purge-incr command for remove-all-inc-of-but-n-full feature added
  166. # patch provided by Moritz Augsburger, thanks!
  167. # - documented version command in man page
  168. #
  169. # 1.5.10 (26.03.2013)
  170. # - minor indent and documentation fixes
  171. # - bugfix: exclude filter failed on ubuntu, mawk w/o posix char class support
  172. # - bugfix: fix url_decoding generally and for python3
  173. # - bugfix 3609075: wrong script results in status line (thx David Epping)
  174. #
  175. # 1.5.9 (22.11.2012)
  176. # - bugfix 3588926: filter --exclude* params for restore/fetch ate too much
  177. # - restore/fetch now also ignores --include* or --exclude='foobar'
  178. #
  179. # 1.5.8 (26.10.2012)
  180. # - bugfix 3575487: implement proper cloud files support
  181. #
  182. # 1.5.7 (10.06.2012)
  183. # - bugfix 3531450: Cannot use space in target URL (file:///) anymore
  184. #
  185. # 1.5.6 (24.5.2012)
  186. # - commands purge, purge-full have no default value anymore for security
  187. # reasons; instead max value can be given via cmd line or must be set
  188. # in profile; else an error is shown.
  189. # - minor man page modifications
  190. #
  191. # versioning scheme will be simplified to [major].[minor].[patch] version
  192. # with the next version raise
  193. #
  194. # 1.5.5.5 (4.2.2012)
  195. # - bugfix 3479605: SEL context confused profile folder's permission check
  196. # - colon ':' in url passphrase got ignored, added python driven url_decoding
  197. # for user & pass to better process special chars
  198. #
  199. # 1.5.5.4 (16.10.2011)
  200. # - bugfix 3421268: SFTP passwords from conf ignored and always prompted for
  201. # - add support for separate sign passphrase (needs duplicity 0.6.14+)
  202. #
  203. # 1.5.5.3 (1.10.2011)
  204. # - bugfix 3416690: preview threw echo1 error
  205. # - fix unknown cmds error usage & friends if more than 2 params were given
  206. #
  207. # 1.5.5.2 (23.9.2011)
  208. # - bugfix 3409643: ssh key auth did ask for passphrase (--ssh-askpass ?)
  209. # - bugfix: mawk does not support \W and did not split multikey definitions
  210. # - all parameters should survive single (') and double (") quotes now
  211. #
  212. # 1.5.5.1 (7.6.2011)
  213. # - featreq 3311881: add ftps as supported by duplicity 0.6.13 (thx mape2k)
  214. # - bugfix 3312208: signing detection broke symmetric gpg test routine
  215. #
  216. # 1.5.5 (2.5.2011)
  217. # - bugfix: fetch problem with space char in path, escape all params
  218. # containing non word chars
  219. # - list available profiles, if given profile cannot be found
  220. # - added --use-agent configuration hint
  221. # - bugfix 3174133: --exclude* params in conf DUPL_PARAMS broke
  222. # fetch/restore
  223. # - version command now prints out 'using installed' info
  224. # - featreq 3166169: autotrust imported keys, based on code submitted by
  225. # Martin Ellis - imported keys are now automagically trusted ultimately
  226. # - new txt2man feature to create manpages for package maintainers
  227. #
  228. # 1.5.4.2 (6.1.2011)
  229. # - new command changelog
  230. # - bugfix 3109884: freebsd awk segfaulted on printf '%*', use print again
  231. # - bugfix: freebsd awk hangs on 'awk -W version'
  232. # - bugfix 3150244: mawk does not know '--version'
  233. # - minor help text improvements
  234. # - new env vars CMD_PREV,CMD_NEXT replacing CMD env var for scripts
  235. #
  236. # 1.5.4.1 (4.12.2010)
  237. # - output awk, python, bash version now in prolog
  238. # - shebang uses /usr/bin/env now for freebsd compatibility,
  239. # bash not in /bin/bash
  240. # - new --disable-encryption parameter,
  241. # to override profile encr settings for one run
  242. # - added exclude-if-present setting to conf template
  243. # - bug 3126972: GPG_PW only needed for signing/symmetric encryption
  244. # (even though duplicity still needs it)
  245. #
  246. # 1.5.4 (15.11.2010)
  247. # - as of 1.5.3 already, new ARCH_DIR config option
  248. # - multiple key support
  249. # - ftplicity-Feature Requests-2994929: separate encryption and signing key
  250. # - key signing of symmetric encryption possible (duplicity patch committed)
  251. # - gpg tests disable switch
  252. # - gpg tests now previewable and more intelligent
  253. #
  254. # 1.5.3 (1.11.2010)
  255. # - bugfix 3056628: improve busybox compatibility, grep did not have -m param
  256. # - bugfix 2995408: allow empty password for PGP key
  257. # - bugfix 2996459: Duply erroneously escapes '-' symbol in username
  258. # - url_encode function is now pythonized
  259. # - rsync uses FTP_PASSWORD now if duplicity 0.6.10+ , else issue warning
  260. # - feature 3059262: Make pre and post aware of parameters,
  261. # internal parameters + CMD of pre or post
  262. #
  263. # 1.5.2.3 (16.4.2010)
  264. # - bugfix: date again, should now work virtually anywhere
  265. #
  266. # 1.5.2.2 (3.4.2010)
  267. # - minor bugfix: duplicity 0.6.8b version string now parsable
  268. # - added INSTALL.txt
  269. #
  270. # 1.5.2.1 (23.3.2010)
  271. # - bugfix: date formatting is awked now and should work on all platforms
  272. #
  273. # 1.5.2 (2.3.2010)
  274. # - bugfix: errors print to STD_ERR now, failed tasks print an error message
  275. # - added --name=duply_<profile> for duplicity 0.6.01+ to name cache folder
  276. # - simplified & cleaned profileless commands, removed second instance
  277. # - generalized separator time routines
  278. # - added support for --no-encryption (GPG_KEY='disabled'), see conf examples
  279. # - minor fixes
  280. #
  281. # 1.5.1.5 (5.2.2010)
  282. # - bugfix: added special handling of credentials for rsync, imap(s)
  283. #
  284. # 1.5.1.4 (7.1.2010)
  285. # - bugfix: nsecs defaults now to zeroes if date does not deliver [0-9]{9}
  286. # - check if ncftp binary is available if url protocol is ftp
  287. # - bugfix: duplicity output is now printed to screen directly to resolve
  288. # 'mem alloc problem' bug report
  289. # - bugfix: passwords will not be in the url anymore to solve the 'duply shows
  290. # sensitive data in process listing' bug report
  291. #
  292. # 1.5.1.3 (24.12.2009) 'merry xmas'
  293. # - bugfix: gpg pass now apostrophed to allow space and friends
  294. # - bugfix: credentials are now url encoded to allow special chars in them
  295. # a note about url encoding has been added to the conf template
  296. #
  297. # 1.5.1.2 (1.11.2009)
  298. # - bugfix: open parenthesis in password broke duplicity execution
  299. # - bugfix: ssh/scp backend does not always need credentials e.g. key auth
  300. #
  301. # 1.5.1.1 (21.09.2009)
  302. # - bugfix: fixed s3[+http] TARGET_PASS not needed routine
  303. # - bugfix: TYPO in duply 1.5.1 prohibited the use of /etc/duply
  304. # see https://sourceforge.net/tracker/index.php?func=detail&
  305. # aid=2864410&group_id=217745&atid=1041147
  306. #
  307. # 1.5.1 (21.09.2009) - duply (fka. ftplicity)
  308. # - first things first: ftplicity (being able to support all backends since
  309. # some time) will be called duply (fka. ftplicity) from now on. The addendum
  310. # is for the time being to circumvent confusion.
  311. # - bugfix: exit code is 1 (error) not 0 (success), if at least on duplicity
  312. # command failed
  313. # - s3[+http] now supported natively by translating user/pass to access_key/
  314. # secret_key environment variables needed by duplicity s3 boto backend
  315. # - bugfix: additional output lines do not confuse version check anymore
  316. # - list command supports now age parameter (patch by stefan on feature
  317. # request tracker)
  318. # - bugfix: option/param pairs are now correctly passed on to duplicity
  319. # - bugfix: s3[+http] needs no TARGET_PASS if command is read only
  320. #
  321. # 1.5.0.2 (31.07.1009)
  322. # - bugfix: insert password in target url didn't work with debian mawk
  323. # related to previous bug report
  324. #
  325. # 1.5.0.1 (23.07.2009)
  326. # - bugfix: gawk gensub dependency raised an error on debian's default mawk
  327. # replaced with match/substr command combination (bug report)
  328. # https://sf.net/tracker/?func=detail&atid=1041147&aid=2825388&
  329. # group_id=217745
  330. #
  331. # 1.5.0 (01.07.2009)
  332. # - removed ftp limitation, all duplicity backends should work now
  333. # - bugfix: date for separator failed on openwrt busybox date, added a
  334. # detecting workaround, milliseconds are not available w/ busybox date
  335. #
  336. # 1.4.2.1 (14.05.2009)
  337. # - bugfix: free temp space detection failed with lvm, fixed awk parse routine
  338. #
  339. # 1.4.2 (22.04.2009)
  340. # - gpg keys are now exported as gpgkey.[id].asc , the suffix reflects the
  341. # armored ascii nature, the id helps if the key is switched for some reason
  342. # im/export routines are updated accordingly (import is backward compatible
  343. # to the old profile/gpgkey files)
  344. # - profile argument is treated as path if it contains slashes
  345. # (for details see usage)
  346. # - non-ftplicity options (all but --preview currently) are now passed
  347. # on to duplicity
  348. # - removed need for stat in secure_conf, it is ls based now
  349. # - added profile folder readable check
  350. # - added gpg version & home info output
  351. # - awk utility availability is now checked, because it was mandatory already
  352. # - tmp space is now checked on writability and space requirement
  353. # test fails on less than 25MB or configured $VOLSIZE,
  354. # test warns if there is less than two times $VOLSIZE because
  355. # that's required for --asynchronous-upload option
  356. # - gpg functionality is tested now before executing duplicity
  357. # test drive contains encryption, decryption, comparison, cleanup
  358. # this is meant to detect non trusted or other gpg errors early
  359. # - added possibility of doing symmetric encryption with duplicity
  360. # set GPG_KEY="" or simply comment it out
  361. # - added hints in config template on the depreciation of
  362. # --short-filenames, --time-separator duplicity options
  363. #
  364. # new versioning scheme 1.4.2b => 1.4.2,
  365. # beta b's are replaced by a patch count number e.g. 1.4.2.1 will be assigned
  366. # to the first bug fixing version and 1.4.2.2 to the second and so on
  367. # also the releases will now have a release date formatted (Day.Month.Year)
  368. #
  369. # 1.4.1b1 - bugfix: ftplicity changed filesystem permission of a folder
  370. # named exactly as the profile if existing in executing dir
  371. # - improved plausibility checking of config and profile folder
  372. # - secure_conf only acts if needed and prints a warning now
  373. #
  374. # 1.4.1b - introduce status (duplicity collection-status) command
  375. # - pre/post script output printed always now, not only on errors
  376. # - new config parameter GPG_OPTS to pass gpg options
  377. # added examples & comments to profile template conf
  378. # - reworked separator times, added duration display
  379. # - added --preview switch, to preview generated command lines
  380. # - disabled MAX_AGE, MAX_FULL_BACKUPS, VERBOSITY in generated
  381. # profiles because they have reasonable defaults now if not set
  382. #
  383. # 1.4.0b1 - bugfix: incr forces incremental backups on duplicity,
  384. # therefore backup translates to pre_bkp_post now
  385. # - bugfix: new command bkp, which represents duplicity's
  386. # default action (incr or full if full_if_older matches
  387. # or no earlier backup chain is found)
  388. #
  389. # new versioning scheme 1.4 => 1.4.0, added new minor revision number
  390. # this is meant to slow down the rapid version growing but still keep
  391. # versions cleanly separated.
  392. # only additional features will raise the new minor revision number.
  393. # all releases start as beta, each bugfix release will raise the beta
  394. # count, usually new features arrive before a version 'ripes' to stable
  395. #
  396. # 1.4.0b
  397. # 1.4b - added startup info on version, time, selected profile
  398. # - added time output to separation lines
  399. # - introduced: command purge-full implements duplicity's
  400. # remove-all-but-n-full functionality (patch by unknown),
  401. # uses config variable $MAX_FULL_BACKUPS (default = 1)
  402. # - purge config var $MAX_AGE defaults to 1M (month) now
  403. # - command full does not execute pre/post anymore
  404. # use batch command pre_full_post if needed
  405. # - introduced batch mode cmd1_cmd2_etc
  406. # (in turn removed the bvp command)
  407. # - unknown/undefined command issues a warning/error now
  408. # - bugfix: version check works with 0.4.2 and older now
  409. # 1.3b3 - introduced pre/post commands to execute/debug scripts
  410. # - introduced bvp (backup, verify, purge)
  411. # - bugfix: removed need for awk gensub, now mawk compatible
  412. # 1.3b2 - removed pre/post need executable bit set
  413. # - profiles now under ~/.ftplicity as folders
  414. # - root can keep profiles in /etc/ftplicity, folder must be
  415. # created by hand, existing profiles must be moved there
  416. # - removed ftplicity in path requirement
  417. # - bugfix: bash < v.3 did not know '=~'
  418. # - bugfix: purge works again
  419. # 1.3 - introduces multiple profiles support
  420. # - modified some script errors/docs
  421. # - reordered gpg key check import routine
  422. # - added 'gpg key id not set' check
  423. # - added error_gpg (adds how to setup gpg key howto)
  424. # - bugfix: duplicity 0.4.4RC4+ parameter syntax changed
  425. # - duplicity_version_check routine introduced
  426. # - added time separator, shortnames, volsize, full_if_older
  427. # duplicity options to config file (inspired by stevie
  428. # from http://weareroot.de)
  429. # 1.1.1 - bugfix: encryption reactivated
  430. # 1.1 - introduced config directory
  431. # 1.0 - first release
  432. ################################################################################
  433.  
  434. # utility functions overriding binaries
  435.  
  436. # wrap grep to override possible env set GREP_OPTIONS=--color=always
  437. function grep {
  438. command env -u GREP_OPTIONS grep "$@"
  439. }
  440.  
  441. # implement basename in plain bash
  442. function basename {
  443. local stripped="${1%/}"
  444. echo "${stripped##*/}"
  445. }
  446.  
  447. # implement dirname in plain bash
  448. function dirname {
  449. echo ${1%/*}
  450. }
  451.  
  452. # implement basic which in plain bash
  453. function which {
  454. type -p "$@"
  455. }
  456.  
  457. # check availability of executables via file name or file paths
  458. function lookup {
  459. local bin="$1"
  460. # look for file names in path via bash hash OR
  461. # look for executables at given relative/absolute location
  462. ( [ "${bin##*/}" == "$bin" ] && hash "$bin" 2>/dev/null ) || [ -x "$bin" ]
  463. }
  464.  
  465. # important definitions #######################################################
  466.  
  467. ME_LONG="$0"
  468. ME="$(basename $0)"
  469. ME_NAME="${ME%%.*}"
  470. ME_VERSION="2.0.2dev"
  471. ME_WEBSITE="http://duply.net"
  472.  
  473. # default config values
  474. DEFAULT_SOURCE='/path/of/source'
  475. DEFAULT_TARGET='scheme://user[:password]@host[:port]/[/]path'
  476. DEFAULT_TARGET_USER='_backend_username_'
  477. DEFAULT_TARGET_PASS='_backend_password_'
  478. DEFAULT_GPG='gpg'
  479. DEFAULT_GPG_KEY='_KEY_ID_'
  480. DEFAULT_GPG_PW='_GPG_PASSWORD_'
  481. DEFAULT_PYTHON='python'
  482.  
  483. # function definitions ##########################
  484.  
  485. function set_config { # sets global config vars
  486. local CONFHOME_COMPAT="$HOME/.ftplicity"
  487. local CONFHOME="$HOME/.duply"
  488. local CONFHOME_ETC_COMPAT="/etc/ftplicity"
  489. local CONFHOME_ETC="/etc/duply"
  490.  
  491. # confdir can be delivered as path (must contain /)
  492. if [ `echo $FTPLCFG | grep /` ] ; then
  493. CONFDIR=$(readlink -f $FTPLCFG 2>/dev/null || \
  494. ( echo $FTPLCFG|grep -v '^/' 1>/dev/null 2>&1 \
  495. && echo $(pwd)/${FTPLCFG} ) || \
  496. echo ${FTPLCFG})
  497. # or DEFAULT in home/.duply folder (NEW)
  498. elif [ -d "${CONFHOME}" ]; then
  499. CONFDIR="${CONFHOME}/${FTPLCFG}"
  500. # or in home/.ftplicity folder (OLD)
  501. elif [ -d "${CONFHOME_COMPAT}" ]; then
  502. CONFDIR="${CONFHOME_COMPAT}/${FTPLCFG}"
  503. warning_oldhome "${CONFHOME_COMPAT}" "${CONFHOME}"
  504. # root can put profiles under /etc/duply (NEW) if path exists
  505. elif [ -d "${CONFHOME_ETC}" ] && [ "$EUID" -eq 0 ]; then
  506. CONFDIR="${CONFHOME_ETC}/${FTPLCFG}"
  507. # root can keep profiles under /etc/ftplicity (OLD) if path exists
  508. elif [ -d "${CONFHOME_ETC_COMPAT}" ] && [ "$EUID" -eq 0 ]; then
  509. CONFDIR="${CONFHOME_ETC_COMPAT}/${FTPLCFG}"
  510. warning_oldhome "${CONFHOME_ETC_COMPAT}" "${CONFHOME_ETC}"
  511. # hmm no profile folder there, then use default for error later
  512. else
  513. CONFDIR="${CONFHOME}/${FTPLCFG}" # continue, will fail later in main
  514. fi
  515.  
  516. # remove trailing slash, get profile name etc.
  517. CONFDIR="${CONFDIR%/}"
  518. PROFILE="${CONFDIR##*/}"
  519. CONF="$CONFDIR/conf"
  520. PRE="$CONFDIR/pre"
  521. POST="$CONFDIR/post"
  522. EXCLUDE="$CONFDIR/exclude"
  523. KEYFILE="$CONFDIR/gpgkey.asc"
  524. }
  525.  
  526. function version_info { # print version information
  527. cat <<END
  528.   $ME_NAME version $ME_VERSION
  529.   ($ME_WEBSITE)
  530. END
  531. }
  532.  
  533. function version_info_using {
  534. cat <<END
  535. $(version_info)
  536.  
  537.   $(using_info)
  538. END
  539. }
  540.  
  541. function python_binary {
  542. echo "${PYTHON-$DEFAULT_PYTHON}"
  543. }
  544.  
  545. function using_info {
  546. lookup duplicity && duplicity_version_get
  547. local NOTFOUND="MISSING"
  548. # freebsd awk (--version only), debian mawk (-W version only), deliver '' so awk does not wait for input
  549. local AWK_VERSION=$( lookup awk && (awk --version 2>/dev/null || awk -W version 2>&1) | awk 'NR<=2&&tolower($0)~/(busybox|awk)/{success=1;print;exit} END{if(success<1) print "unknown"}' || echo "$NOTFOUND" )
  550. local GREP_VERSION=$( lookup grep && grep --version 2>&1 | awk 'NR<=2&&tolower($0)~/(busybox|grep.*[0-9]+\.[0-9]+)/{success=1;print;exit} END{if(success<1) print "unknown"}' || echo "$NOTFOUND" )
  551. local PYTHON_RUNNER=$(python_binary)
  552. local PYTHON_VERSION=$(lookup "$PYTHON_RUNNER" && "$PYTHON_RUNNER" -V 2>&1| awk '{print tolower($0);exit}' || echo "'$PYTHON_RUNNER' $NOTFOUND" )
  553. local GPG_INFO=$(gpg_avail && gpg --version 2>&1| awk '/^gpg.*[0-9\.]+$/&&length(v)<1{v=$1" "$3}/^Home:/{h=" ("$0")"}END{print v""h}' || echo "gpg $NOTFOUND")
  554. local BASH_VERSION=$(bash --version | awk 'NR==1{IGNORECASE=1;sub(/GNU bash, version[ ]+/,"",$0);print $0}')
  555. echo -e "Using installed duplicity version ${DUPL_VERSION:-$NOTFOUND}\
  556. ${PYTHON_VERSION+, $PYTHON_VERSION${PYTHONPATH:+ 'PYTHONPATH=$PYTHONPATH'}}\
  557. ${GPG_INFO:+, $GPG_INFO}${AWK_VERSION:+, awk '${AWK_VERSION}'}${GREP_VERSION:+, grep '${GREP_VERSION}'}\
  558. ${BASH_VERSION:+, bash '${BASH_VERSION}'}."
  559. }
  560.  
  561. function usage_info { # print usage information
  562.  
  563. cat <<USAGE_EOF
  564. VERSION:
  565. $(version_info)
  566.  
  567. DESCRIPTION:
  568. Duply deals as a wrapper for the mighty duplicity magic.
  569. It simplifies running duplicity with cron or on command line by:
  570.  
  571. - keeping recurring settings in profiles per backup job
  572. - enabling batch operations eg. backup_verify+purge
  573. - executing pre/post scripts (different actions possible
  574. depending on previous or next command or it's exit status)
  575. - precondition checking for flawless duplicity operation
  576.  
  577. For each backup job one configuration profile must be created.
  578. The profile folder will be stored under '~/.${ME_NAME}/<profile>'
  579. (where ~ is the current users home directory).
  580. Hint:
  581. If the folder '/etc/${ME_NAME}' exists, the profiles for the super
  582. user root will be searched & created there.
  583.  
  584. USAGE:
  585. first time usage (profile creation):
  586. $ME <profile> create
  587.  
  588. general usage in single or batch mode (see EXAMPLES):
  589. $ME <profile> <command>[[_|+|-]<command>[_|+|-]...] [<options> ...]
  590.  
  591. For batches the conditional separators can also be written as pseudo commands
  592. and(+), or(-). See SEPARATORS for details.
  593.  
  594. Non $ME options are passed on to duplicity (see OPTIONS).
  595. All conf parameters can also be defined in the environment instead.
  596.  
  597. PROFILE:
  598. Indicated by a path or a profile name (<profile>), which is resolved
  599. to '~/.${ME_NAME}/<profile>' (~ expands to environment variable \$HOME).
  600.  
  601. Superuser root can place profiles under '/etc/${ME_NAME}'. Simply create
  602. the folder manually before running $ME_NAME as superuser.
  603. Note:
  604. Already existing profiles in root's home folder will cease to work
  605. unless they are moved to the new location manually.
  606.  
  607. example 1: $ME humbug backup
  608.  
  609. Alternatively a _path_ might be used e.g. useful for quick testing,
  610. restoring or exotic locations. Shell expansion should work as usual.
  611. Hint:
  612. The path must contain at least one path separator '/',
  613. e.g. './test' instead of only 'test'.
  614.  
  615. example 2: $ME ~/.${ME_NAME}/humbug backup
  616.  
  617. SEPARATORS:
  618. _ (underscore)
  619. neutral separator
  620. + (plus sign), _and_
  621. conditional AND
  622. the next command will only be executed if the previous succeeded
  623. - (minus sign), _or_
  624. conditional OR
  625. the next command will only be executed if the previous failed
  626.  
  627. example:
  628. 'pre+bkp-verify_post' translates to 'pre_and_bkp_or_verify_post'
  629.  
  630. COMMANDS:
  631. usage get usage help text
  632.  
  633. and/or pseudo commands for better batch cmd readability (see SEPARATORS)
  634. create creates a configuration profile
  635. backup backup with pre/post script execution (batch: pre_bkp_post),
  636. full (if full_if_older matches or no earlier backup is found)
  637. incremental (in all other cases)
  638. pre/post execute '<profile>/$(basename "$PRE")', '<profile>/$(basename "$POST")' scripts
  639. bkp as above but without executing pre/post scripts
  640. full force full backup
  641. incr force incremental backup
  642. list [<age>]
  643. list all files in backup (as it was at <age>, default: now)
  644. status prints backup sets and chains currently in repository
  645. verify [<age>] [--compare-data]
  646. list files changed, since age if given
  647. verifyPath <rel_path_in_bkp> <local_path> [<age>] [--compare-data]
  648. list changes of a file or folder path in backup compared to a
  649. local path, since age if given
  650. restore <target_path> [<age>]
  651. restore the complete backup to <target_path> [as it was at <age>]
  652. fetch <src_path> <target_path> [<age>]
  653. fetch single file/folder from backup [as it was at <age>]
  654. purge [<max_age>] [--force]
  655. list outdated backup files (older than \$MAX_AGE)
  656. [use --force to actually delete these files]
  657. purgeFull [<max_full_backups>] [--force]
  658. list outdated backup files (\$MAX_FULL_BACKUPS being the number of
  659. full backups and associated incrementals to keep, counting in
  660. reverse chronological order)
  661. [use --force to actually delete these files]
  662. purgeIncr [<max_fulls_with_incrs>] [--force]
  663. list outdated incremental backups (\$MAX_FULLS_WITH_INCRS being
  664. the number of full backups which associated incrementals will be
  665. kept, counting in reverse chronological order)
  666. [use --force to actually delete these files]
  667. cleanup [--force]
  668. list broken backup chain files archives (e.g. after unfinished run)
  669. [use --force to actually delete these files]
  670.  
  671. changelog print changelog / todo list
  672. txt2man feature for package maintainers - create a manpage based on the
  673. usage output. download txt2man from http://mvertes.free.fr/, put
  674. it in the PATH and run '$ME txt2man' to create a man page.
  675. version show version information of $ME_NAME and needed programs
  676.  
  677. OPTIONS:
  678. --force passed to duplicity (see commands: purge, purge-full, cleanup)
  679. --preview do nothing but print out generated duplicity command lines
  680. --disable-encryption
  681. disable encryption, overrides profile settings
  682.  
  683. TIME FORMATS:
  684. For all time related parameters like age, max_age etc.
  685. Refer to the duplicity manpage for all available formats. Here some examples:
  686. 2002-01-25T07:00:00+02:00 (full date time format string)
  687. 2002/3/5 (date string YYYY/MM/DD)
  688. 12D (interval, 12 days ago)
  689. 1h78m (interval, 1 hour 78 minutes ago)
  690.  
  691. PRE/POST SCRIPTS:
  692. Useful internal duply variables will be readable in the scripts.
  693. Some of interest may be
  694.  
  695. PROFILE, CONFDIR, SOURCE, TARGET_URL_<PROT|HOSTPATH|USER|PASS>,
  696. GPG_<KEYS_ENC|KEY_SIGN|PW>, CMD_<PREV|NEXT>, CMD_ERR, RUN_START
  697.  
  698. The CMD_* variables were introduced to allow different actions according to
  699. the command the scripts were attached to e.g. 'pre_bkp_post_pre_verify_post'
  700. will call the pre script two times, with CMD_NEXT variable set to 'bkp'
  701. on the first and to 'verify' on the second run.
  702. CMD_ERR holds the exit code of the CMD_PREV .
  703.  
  704. EXAMPLES:
  705. create profile 'humbug':
  706. $ME humbug create (don't forget to edit this new conf file)
  707. backup 'humbug' now:
  708. $ME humbug backup
  709. list available backup sets of profile 'humbug':
  710. $ME humbug status
  711. list and delete outdated backups of 'humbug':
  712. $ME humbug purge --force
  713. restore latest backup of 'humbug' to /mnt/restore:
  714. $ME humbug restore /mnt/restore
  715. restore /etc/passwd of 'humbug' from 4 days ago to /root/pw:
  716. $ME humbug fetch etc/passwd /root/pw 4D
  717. (see "duplicity manpage", section TIME FORMATS)
  718. a one line batch job on 'humbug' for cron execution:
  719. $ME humbug backup_verify_purge --force
  720. batch job to run a full backup with pre/post scripts:
  721. $ME humbug pre_full_post
  722.  
  723. FILES:
  724. in profile folder '~/.${ME_NAME}/<profile>' or '/etc/${ME_NAME}'
  725. conf profile configuration file
  726. pre,post pre/post scripts (see above for details)
  727. gpgkey.*.asc exported GPG key files
  728. exclude a globbing list of included or excluded files/folders
  729. (see "duplicity manpage", section FILE SELECTION)
  730.  
  731. $(hint_profile)
  732.  
  733. SEE ALSO:
  734. duplicity man page:
  735. duplicity(1) or http://duplicity.nongnu.org/duplicity.1.html
  736. USAGE_EOF
  737. }
  738.  
  739. # to check call 'duply txt2man | man -l -'
  740. function usage_txt2man {
  741. usage_info | \
  742. awk '/^^[^[:lower:][:space:]][^[:lower:]]+$/{gsub(/[^[:upper:]]/," ",$0)}{print}' |\
  743. txt2man -t"$(toupper "${ME_NAME}")" -s1 -r"${ME_NAME}-${ME_VERSION}" -v'User Manuals'
  744. }
  745.  
  746. function changelog {
  747. cat $ME_LONG | awk '/^#####/{on=on+1}(on==3){sub(/^#( )?/,"",$0);print}'
  748. }
  749.  
  750. function create_config {
  751. if [ ! -d "$CONFDIR" ] ; then
  752. mkdir -p "$CONFDIR" || error "Couldn't create config '$CONFDIR'."
  753. # create initial config file
  754. cat <<EOF >"$CONF"
  755. # gpg encryption settings, simple settings:
  756. # GPG_KEY='disabled' - disables encryption alltogether
  757. # GPG_KEY='<key1>[,<key2>]'; GPG_PW='pass' - encrypt with keys,
  758. # sign if secret key of key1 is available use GPG_PW for sign & decrypt
  759. # Note: you can specify keys via all methods described in gpg manpage,
  760. # section "How to specify a user ID", escape commas (,) via backslash (\)
  761. # e.g. 'Mueller, Horst', 'Bernd' -> 'Mueller\, Horst, Bernd'
  762. # as they are used to separate the entries
  763. # GPG_PW='passphrase' - symmetric encryption using passphrase only
  764. GPG_KEY='${DEFAULT_GPG_KEY}'
  765. GPG_PW='${DEFAULT_GPG_PW}'
  766. # gpg encryption settings in detail (extended settings)
  767. # the above settings translate to the following more specific settings
  768. # GPG_KEYS_ENC='<keyid1>[,<keyid2>,...]' - list of pubkeys to encrypt to
  769. # GPG_KEY_SIGN='<keyid1>|disabled' - a secret key for signing
  770. # GPG_PW='<passphrase>' - needed for signing, decryption and symmetric
  771. # encryption. If you want to deliver different passphrases for e.g.
  772. # several keys or symmetric encryption plus key signing you can use
  773. # gpg-agent. Simply make sure that GPG_AGENT_INFO is set in environment.
  774. # also see "A NOTE ON SYMMETRIC ENCRYPTION AND SIGNING" in duplicity manpage
  775. # notes on en/decryption
  776. # private key and passphrase will only be needed for decryption or signing.
  777. # decryption happens on restore and incrementals (compare archdir contents).
  778. # for security reasons it makes sense to separate the signing key from the
  779. # encryption keys. https://answers.launchpad.net/duplicity/+question/107216
  780. #GPG_KEYS_ENC='<pubkey1>,<pubkey2>,...'
  781. #GPG_KEY_SIGN='<prvkey>'
  782. # set if signing key passphrase differs from encryption (key) passphrase
  783. # NOTE: available since duplicity 0.6.14, translates to SIGN_PASSPHRASE
  784. #GPG_PW_SIGN='<signpass>'
  785.  
  786. # uncomment and set a file path or name force duply to use this gpg executable
  787. # available in duplicity 0.7.04 and above (currently unreleased 06/2015)
  788. #GPG='/usr/local/gpg-2.1/bin/gpg'
  789.  
  790. # gpg options passed from duplicity to gpg process (default='')
  791. # e.g. "--trust-model pgp|classic|direct|always"
  792. # or "--compress-algo=bzip2 --bzip2-compress-level=9"
  793. # or "--personal-cipher-preferences AES256,AES192,AES..."
  794. # or "--homedir ~/.duply" - keep keyring and gpg settings duply specific
  795. # or "--pinentry-mode loopback" - needed for GPG 2.1+ _and_
  796. # also enable allow-loopback-pinentry in your .gnupg/gpg-agent.conf
  797. #GPG_OPTS=''
  798.  
  799. # disable preliminary tests with the following setting
  800. #GPG_TEST='disabled'
  801.  
  802. # backend, credentials & location of the backup target (URL-Format)
  803. # generic syntax is
  804. # scheme://[user[:password]@]host[:port]/[/]path
  805. # eg.
  806. # sftp://bob:secret@backupserver.com//home/bob/dupbkp
  807. # for details and available backends see duplicity manpage, section URL Format
  808. # http://duplicity.nongnu.org/duplicity.1.html#sect7
  809. # BE AWARE:
  810. # some backends (cloudfiles, S3 etc.) need additional env vars to be set to
  811. # work properly, read after the TARGET definition for more details.
  812. # ATTENTION:
  813. # characters other than A-Za-z0-9.-_.~ in the URL have to be
  814. # replaced by their url encoded pendants, see
  815. # http://en.wikipedia.org/wiki/Url_encoding
  816. # if you define the credentials as TARGET_USER, TARGET_PASS below $ME
  817. # will try to url_encode them for you if the need arises.
  818. TARGET='${DEFAULT_TARGET}'
  819. # optionally the username/password can be defined as extra variables
  820. # setting them here _and_ in TARGET results in an error
  821. # ATTENTION:
  822. # there are backends that do not support the user/pass auth scheme.
  823. # prominent examples are S3, Azure, Cloudfiles. when in doubt consult the
  824. # duplicity manpage. usually there is a NOTE section explaining if and which
  825. # env vars should be set.
  826. #TARGET_USER='${DEFAULT_TARGET_USER}'
  827. #TARGET_PASS='${DEFAULT_TARGET_PASS}'
  828. # eg. for cloud files backend it might look like this (uncomment for use!)
  829. #export CLOUDFILES_USERNAME='someuser'
  830. #export CLOUDFILES_APIKEY='somekey'
  831. #export CLOUDFILES_AUTHURL ='someurl'
  832. # the following is an incomplete list (<backend>: comma separated env vars list)
  833. # Azure: AZURE_ACCOUNT_NAME, AZURE_ACCOUNT_KEY
  834. # Cloudfiles: CLOUDFILES_USERNAME, CLOUDFILES_APIKEY, CLOUDFILES_AUTHURL
  835. # Google Cloud Storage: GS_ACCESS_KEY_ID, GS_SECRET_ACCESS_KEY
  836. # Pydrive: GOOGLE_DRIVE_ACCOUNT_KEY, GOOGLE_DRIVE_SETTINGS
  837. # S3: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  838. # Swift: SWIFT_USERNAME, SWIFT_PASSWORD, SWIFT_AUTHURL,
  839. # SWIFT_TENANTNAME OR SWIFT_PREAUTHURL, SWIFT_PREAUTHTOKEN
  840.  
  841. # base directory to backup
  842. SOURCE='${DEFAULT_SOURCE}'
  843.  
  844. # a command that runs duplicity e.g.
  845. # shape bandwidth use via trickle
  846. # "trickle -s -u 640 -d 5120" # 5Mb up, 40Mb down"
  847. #DUPL_PRECMD=""
  848.  
  849. # override the used python interpreter, defaults to "python"
  850. # e.g. "python2" or "/usr/bin/python2.7"
  851. #PYTHON="python"
  852.  
  853. # exclude folders containing exclusion file (since duplicity 0.5.14)
  854. # Uncomment the following two lines to enable this setting.
  855. #FILENAME='.duplicity-ignore'
  856. #DUPL_PARAMS="\$DUPL_PARAMS --exclude-if-present '\$FILENAME'"
  857.  
  858. # Time frame for old backups to keep, Used for the "purge" command.
  859. # see duplicity man page, chapter TIME_FORMATS)
  860. #MAX_AGE=1M
  861.  
  862. # Number of full backups to keep. Used for the "purge-full" command.
  863. # See duplicity man page, action "remove-all-but-n-full".
  864. #MAX_FULL_BACKUPS=1
  865.  
  866. # Number of full backups for which incrementals will be kept for.
  867. # Used for the "purge-incr" command.
  868. # See duplicity man page, action "remove-all-inc-of-but-n-full".
  869. #MAX_FULLS_WITH_INCRS=1
  870.  
  871. # activates duplicity --full-if-older-than option (since duplicity v0.4.4.RC3)
  872. # forces a full backup if last full backup reaches a specified age, for the
  873. # format of MAX_FULLBKP_AGE see duplicity man page, chapter TIME_FORMATS
  874. # Uncomment the following two lines to enable this setting.
  875. #MAX_FULLBKP_AGE=1M
  876. #DUPL_PARAMS="\$DUPL_PARAMS --full-if-older-than \$MAX_FULLBKP_AGE "
  877.  
  878. # sets duplicity --volsize option (available since v0.4.3.RC7)
  879. # set the size of backup chunks to VOLSIZE MB instead of the default 25MB.
  880. # VOLSIZE must be number of MB's to set the volume size to.
  881. # Uncomment the following two lines to enable this setting.
  882. #VOLSIZE=50
  883. #DUPL_PARAMS="\$DUPL_PARAMS --volsize \$VOLSIZE "
  884.  
  885. # verbosity of output (error 0, warning 1-2, notice 3-4, info 5-8, debug 9)
  886. # default is 4, if not set
  887. #VERBOSITY=5
  888.  
  889. # temporary file space. at least the size of the biggest file in backup
  890. # for a successful restoration process. (default is '/tmp', if not set)
  891. #TEMP_DIR=/tmp
  892.  
  893. # Modifies archive-dir option (since 0.6.0) Defines a folder that holds
  894. # unencrypted meta data of the backup, enabling new incrementals without the
  895. # need to decrypt backend metadata first. If empty or deleted somehow, the
  896. # private key and it's password are needed.
  897. # NOTE: This is confidential data. Put it somewhere safe. It can grow quite
  898. # big over time so you might want to put it not in the home dir.
  899. # default '~/.cache/duplicity/duply_<profile>/'
  900. # if set '\${ARCH_DIR}/<profile>'
  901. #ARCH_DIR=/some/space/safe/.duply-cache
  902.  
  903. # DEPRECATED setting
  904. # sets duplicity --time-separator option (since v0.4.4.RC2) to allow users
  905. # to change the time separator from ':' to another character that will work
  906. # on their system. HINT: For Windows SMB shares, use --time-separator='_'.
  907. # NOTE: '-' is not valid as it conflicts with date separator.
  908. # ATTENTION: only use this with duplicity < 0.5.10, since then default file
  909. # naming is compatible and this option is pending depreciation
  910. #DUPL_PARAMS="\$DUPL_PARAMS --time-separator _ "
  911.  
  912. # DEPRECATED setting
  913. # activates duplicity --short-filenames option, when uploading to a file
  914. # system that can't have filenames longer than 30 characters (e.g. Mac OS 8)
  915. # or have problems with ':' as part of the filename (e.g. Microsoft Windows)
  916. # ATTENTION: only use this with duplicity < 0.5.10, later versions default file
  917. # naming is compatible and this option is pending depreciation
  918. #DUPL_PARAMS="\$DUPL_PARAMS --short-filenames "
  919.  
  920. # more duplicity command line options can be added in the following way
  921. # don't forget to leave a separating space char at the end
  922. #DUPL_PARAMS="\$DUPL_PARAMS --put_your_options_here "
  923.  
  924. EOF
  925.  
  926. # create initial exclude file
  927. cat <<EOF >"$EXCLUDE"
  928. # although called exclude, this file is actually a globbing file list
  929. # duplicity accepts some globbing patterns, even including ones here
  930. # here is an example, this incl. only 'dir/bar' except it's subfolder 'foo'
  931. # - dir/bar/foo
  932. # + dir/bar
  933. # - **
  934. # for more details see duplicity manpage, section File Selection
  935. # http://duplicity.nongnu.org/duplicity.1.html#sect9
  936.  
  937. EOF
  938.  
  939. # Hints on first usage
  940. cat <<EOF
  941.  
  942. Congratulations. You just created the profile '$FTPLCFG'.
  943. The initial config file has been created as
  944. '$CONF'.
  945. You should now adjust this config file to your needs.
  946.  
  947. $(hint_profile)
  948.  
  949. EOF
  950. fi
  951.  
  952. }
  953.  
  954. # used in usage AND create_config
  955. function hint_profile {
  956. cat <<EOF
  957. IMPORTANT:
  958.   Copy the _whole_ profile folder after the first backup to a safe place.
  959.   It contains everything needed to restore your backups. You will need
  960.   it if you have to restore the backup from another system (e.g. after a
  961.   system crash). Keep access to these files restricted as they contain
  962.   _all_ informations (gpg data, ftp data) to access and modify your backups.
  963.  
  964.   Repeat this step after _all_ configuration changes. Some configuration
  965.   options are crucial for restoration.
  966.  
  967. EOF
  968. }
  969.  
  970. function separator {
  971. echo "--- $@ ---"
  972. }
  973.  
  974. function inform {
  975. echo -e "\nINFO:\n\n$@\n"
  976. }
  977.  
  978. function warning {
  979. echo -e "\nWARNING:\n\n$@\n"
  980. }
  981.  
  982. function warning_oldhome {
  983. local old=$1 new=$2
  984. warning " ftplicity changed name to duply since you created your profiles.
  985. Please rename the old folder
  986. '$old'
  987. to
  988. '$new'
  989. and this warning will disappear.
  990. If you decide not to do so profiles will _only_ work from the old location."
  991. }
  992.  
  993. function error_print {
  994. echo -e "$@" >&2
  995. }
  996.  
  997. function error {
  998. error_print "\nSorry. A fatal ERROR occured:\n\n$@\n"
  999. exit -1
  1000. }
  1001.  
  1002. function error_gpg {
  1003. [ -n "$2" ] && local hint="\n $2\n\n "
  1004.  
  1005. error "$1
  1006.  
  1007. Hint${hint:+s}:
  1008. ${hint}Maybe you have not created a gpg key yet (e.g. gpg --gen-key)?
  1009. Don't forget the used _password_ as you will need it.
  1010. When done enter the 8 digit id & the password in the profile conf file.
  1011.  
  1012. The key id can be found doing a 'gpg --list-keys'. In the example output
  1013. below the key id would be FFFFFFFF for the public key.
  1014.  
  1015. pub 1024D/FFFFFFFF 2007-12-17
  1016. uid duplicity
  1017. sub 2048g/899FE27F 2007-12-17
  1018. "
  1019. }
  1020.  
  1021. function error_gpg_key {
  1022. local KEY_ID="$1"
  1023. local KIND="$2"
  1024. error_gpg "${KIND} gpg key '${KEY_ID}' cannot be found." \
  1025. "Doublecheck if the above key is listed by 'gpg --list-keys' or available
  1026. as gpg key file '$(basename "$(gpg_keyfile "${KEY_ID}")")' in the profile folder.
  1027. If not you can put it there and $ME_NAME will autoimport it on the next run.
  1028. Alternatively import it manually as the user you plan to run $ME_NAME with."
  1029. }
  1030.  
  1031. function error_gpg_test {
  1032. [ -n "$2" ] && local hint="\n $2\n\n "
  1033.  
  1034. error "$1
  1035.  
  1036. Hint${hint:+s}:
  1037. ${hint}This error means that gpg is probably misconfigured or not working
  1038. correctly. The error message above should help to solve the problem.
  1039. However, if for some reason $ME_NAME should misinterpret the situation you
  1040. can define GPG_TEST='disabled' in the conf file to bypass the test.
  1041. Please do not forget to report the bug in order to resolve the problem
  1042. in future versions of $ME_NAME.
  1043. "
  1044. }
  1045.  
  1046. function error_path {
  1047. error "$@
  1048. PATH='$PATH'
  1049. "
  1050. }
  1051.  
  1052. function error_to_string {
  1053. [ -n "$1" ] && [ "$1" -eq 0 ] && echo "OK" || echo "FAILED 'code $1'"
  1054. }
  1055.  
  1056. function duplicity_version_get {
  1057. var_isset DUPL_VERSION && return
  1058. DUPL_VERSION=`duplicity --version 2>&1 | awk '/^duplicity /{print $2; exit;}'`
  1059. #DUPL_VERSION='0.7.03' #'0.6.08b' #,0.4.4.RC4,0.6.08b
  1060. DUPL_VERSION_VALUE=0
  1061. DUPL_VERSION_AWK=$(awk -v v="$DUPL_VERSION" 'BEGIN{
  1062. if (match(v,/[^\.0-9]+[0-9]*$/)){
  1063. rest=substr(v,RSTART,RLENGTH);v=substr(v,0,RSTART-1);}
  1064. if (pos=match(rest,/RC([0-9]+)$/)) rc=substr(rest,pos+2)
  1065. split(v,f,"[. ]"); if(f[1]f[2]f[3]~/^[0-9]+$/) vvalue=f[1]*10000+f[2]*100+f[3]; else vvalue=0
  1066. print "#"v"_"rest"("rc"):"f[1]"-"f[2]"-"f[3]
  1067. print "DUPL_VERSION_VALUE=\047"vvalue"\047"
  1068. print "DUPL_VERSION_RC=\047"rc"\047"
  1069. print "DUPL_VERSION_SUFFIX=\047"rest"\047"
  1070. }')
  1071. eval "$DUPL_VERSION_AWK"
  1072. #echo -e ",$DUPL_VERSION,$DUPL_VERSION_VALUE,$DUPL_VERSION_RC,$DUPL_VERSION_SUFFIX,"
  1073. }
  1074.  
  1075. function duplicity_version_check {
  1076. if [ $DUPL_VERSION_VALUE -eq 0 ]; then
  1077. inform "duplicity version check failed (please report, this is a bug)"
  1078. elif [ $DUPL_VERSION_VALUE -le 404 ] && [ ${DUPL_VERSION_RC:-4} -lt 4 ]; then
  1079. error "The installed version $DUPL_VERSION is incompatible with $ME_NAME v$ME_VERSION.
  1080. You should upgrade your version of duplicity to at least v0.4.4RC4 or
  1081. use the older ftplicity version 1.1.1 from $ME_WEBSITE."
  1082. fi
  1083. }
  1084.  
  1085. function duplicity_version_ge {
  1086. [ "$DUPL_VERSION_VALUE" -ge "$1" ]
  1087. }
  1088.  
  1089. function duplicity_version_lt {
  1090.  ! duplicity_version_ge "$1"
  1091. }
  1092.  
  1093. function run_script { # run pre/post scripts
  1094. local ERR=0
  1095. local SCRIPT="$1"
  1096. if [ ! -z "$PREVIEW" ] ; then
  1097. echo "$([ ! -x "$SCRIPT" ] && echo ". ")$SCRIPT"
  1098. elif [ -r "$SCRIPT" ] ; then
  1099. echo -n "Running '$SCRIPT' "
  1100. if [ -x "$SCRIPT" ]; then
  1101. OUT=$("$SCRIPT" 2>&1)
  1102. ERR=$?
  1103. else
  1104. OUT=$(. "$SCRIPT" 2>&1)
  1105. ERR=$?
  1106. fi
  1107. [ $ERR -eq "0" ] && echo "- OK" || echo "- FAILED (code $ERR)"
  1108. echo -en ${OUT:+"Output: $OUT\n"} ;
  1109. else
  1110. echo "Skipping n/a script '$SCRIPT'."
  1111. fi
  1112. return $ERR
  1113. }
  1114.  
  1115. function run_cmd {
  1116. # run or print escaped cmd string
  1117. local CMD_ERR=0
  1118. if [ -n "$PREVIEW" ]; then
  1119. CMD_OUT=$( echo "$@ 2>&1" )
  1120. CMD_MSG="-- Run cmd -- $CMD_MSG --\n$CMD_OUT"
  1121. elif [ -n "$CMD_DISABLED" ]; then
  1122. CMD_MSG="$CMD_MSG (DISABLED) - $CMD_DISABLED"
  1123. else
  1124. echo -n -e "$CMD_MSG"
  1125. CMD_OUT=` eval "$@" 2>&1 `
  1126. CMD_ERR=$?
  1127. if [ "$CMD_ERR" = "0" ]; then
  1128. CMD_MSG=" (OK)"
  1129. else
  1130. CMD_MSG=" (FAILED)"
  1131. fi
  1132. fi
  1133. echo -e "$CMD_MSG"
  1134. # reset
  1135. unset CMD_DISABLED CMD_MSG
  1136. return $CMD_ERR
  1137. }
  1138.  
  1139. function qw { quotewrap "$@"; }
  1140.  
  1141. function quotewrap {
  1142. local param="$@"
  1143. # quote strings having non word chars (e.g. spaces)
  1144. if echo "$param" | awk '/[^A-Za-z0-9_\.\-]/{exit 0}{exit 1}'; then
  1145. echo "$param" | awk '{\
  1146. gsub(/[\047]/,"\047\\\047\047",$0);\
  1147. gsub(/[\042]/,"\047\\\042\047",$0);\
  1148. print "\047"$0"\047"}'
  1149. return
  1150. fi
  1151. echo $param
  1152. }
  1153.  
  1154. function duplicity_params_global {
  1155. # already done? return
  1156. var_isset 'DUPL_PARAMS_GLOBAL' && return
  1157. local DUPL_ARG_ENC
  1158.  
  1159. # use key only if set in config, else leave it to symmetric encryption
  1160. if gpg_disabled; then
  1161. local DUPL_PARAM_ENC='--no-encryption'
  1162. else
  1163. local DUPL_PARAM_ENC=$(gpg_prefix_keyset '--encrypt-key' "${GPG_KEYS_ENC_ARRAY[@]}")
  1164. gpg_signing && local DUPL_PARAM_SIGN=$(gpg_prefix_keyset '--sign-key' "$GPG_KEY_SIGN")
  1165. # interpret password settings
  1166. var_isset 'GPG_PW' && DUPL_ARG_ENC="PASSPHRASE=$(qw "${GPG_PW}")"
  1167. var_isset 'GPG_PW_SIGN' && DUPL_ARG_ENC="${DUPL_ARG_ENC} SIGN_PASSPHRASE=$(qw "${GPG_PW_SIGN}")"
  1168. fi
  1169.  
  1170. local GPG_OPTS=${GPG_OPTS:+"--gpg-options $(qw "${GPG_OPTS}")"}
  1171.  
  1172. # set name for dupl archive folder, since 0.6.0
  1173. if duplicity_version_ge 601; then
  1174. local DUPL_ARCHDIR=''
  1175. if var_isset 'ARCH_DIR'; then
  1176. DUPL_ARCHDIR="--archive-dir $(qw "${ARCH_DIR}")"
  1177. fi
  1178. DUPL_ARCHDIR="${DUPL_ARCHDIR} --name $(qw "duply_${PROFILE}")"
  1179. fi
  1180.  
  1181. DUPL_PARAMS_GLOBAL="${DUPL_ARCHDIR} ${DUPL_PARAM_ENC} \
  1182. ${DUPL_PARAM_SIGN} --verbosity '${VERBOSITY:-4}' \
  1183. ${GPG_OPTS}"
  1184.  
  1185. DUPL_VARS_GLOBAL="TMPDIR='$TEMP_DIR' \
  1186. ${DUPL_ARG_ENC}"
  1187. }
  1188.  
  1189.  
  1190. # function to filter the DUPL_PARAMS var from user conf
  1191. function duplicity_params_conf {
  1192. # reuse cmd var from main loop
  1193. ## in/exclude parameters are currently not supported on restores
  1194. if [ "$cmd" = "fetch" ] || [ "$cmd" = "restore" ] || [ "$cmd" = "status" ]; then
  1195. # filter exclude params from fetch/restore
  1196. echo "$DUPL_PARAMS" | awk '{gsub(/--(ex|in)clude[a-z-]*(([ \t]+|=)[^-][^ \t]+)?/,"");print}'
  1197. return
  1198. fi
  1199.  
  1200. echo "$DUPL_PARAMS"
  1201. }
  1202.  
  1203. function duplify { # the actual wrapper function
  1204. local PARAMSNOW DUPL_CMD DUPL_CMD_PARAMS
  1205.  
  1206. # put command (with params) first in duplicity parameters
  1207. for param in "$@" ; do
  1208. # split cmd from params (everything before splitchar --)
  1209. if [ "$param" == "--" ] ; then
  1210. PARAMSNOW=1
  1211. else
  1212. # wrap in quotes to protect from spaces
  1213. [ ! $PARAMSNOW ] && \
  1214. DUPL_CMD="$DUPL_CMD $(qw "$param")" \
  1215. || \
  1216. DUPL_CMD_PARAMS="$DUPL_CMD_PARAMS $(qw "$param")"
  1217. fi
  1218. done
  1219.  
  1220. # init global duplicity parameters same for all tasks
  1221. duplicity_params_global
  1222.  
  1223. local RUN=eval BIN=duplicity DUPL_BIN
  1224. # run in cmd line preview mode if requested
  1225. var_isset 'PREVIEW' && RUN=echo
  1226. # try to resolve duplicity path for usage with python interpreter
  1227. DUPL_BIN=$(which "$BIN") || DUPL_BIN="$BIN"
  1228. # only run with a user specific python if configured (running by default
  1229. # breaks homebrew as they place a shell wrapper for duplicity in path)
  1230. [ -n "$PYTHON" ] && [ "$PYTHON" != "$DEFAULT_PYTHON" ] &&\
  1231. BIN="$(qw "$(python_binary)") $(qw "$DUPL_BIN")"
  1232.  
  1233. $RUN "${DUPL_VARS_GLOBAL} ${BACKEND_PARAMS} \
  1234. ${DUPL_PRECMD} $BIN $DUPL_CMD $DUPL_PARAMS_GLOBAL $(duplicity_params_conf)\
  1235. $GPG_USEAGENT $(gpg_custom_binary) $DUPL_CMD_PARAMS"
  1236.  
  1237. local ERR=$?
  1238. return $ERR
  1239. }
  1240.  
  1241. function secureconf { # secure the configuration dir
  1242. #PERMS=$(ls -la $(dirname $CONFDIR) | grep -e " $(basename $CONFDIR)\$" | awk '{print $1}')
  1243. local PERMS="$(ls -la "$CONFDIR/." | awk 'NR==2{print $1}')"
  1244. if [ "${PERMS/#drwx------*/OK}" != 'OK' ] ; then
  1245. chmod u+rwX,go= "$CONFDIR"; local ERR=$?
  1246. warning "The profile's folder
  1247. '$CONFDIR'
  1248. permissions are not safe ($PERMS). Secure them now. - ($(error_to_string $ERR))"
  1249. fi
  1250. }
  1251.  
  1252. # params are $1=timeformatstring (default like date output), $2=epoch seconds since 1.1.1970 (default now)
  1253. function date_fix {
  1254. local DEFAULTFORMAT='%a %b %d %H:%M:%S %Z %Y'
  1255. # gnu date with -d @epoch
  1256. date=$(date ${2:+-d @$2} ${1:++"$1"} 2> /dev/null) && \
  1257. echo $date && return
  1258. # date bsd,osx with -r epoch
  1259. date=$(date ${2:+-r $2} ${1:++"$1"} 2> /dev/null) && \
  1260. echo $date && return
  1261. # date busybox with -d epoch -D %s
  1262. date=$(date ${2:+-d $2 -D %s} ${1:++"$1"} 2> /dev/null) && \
  1263. echo $date && return
  1264. ## some date commands do not support giving a time w/o setting it systemwide (irix,solaris,others?)
  1265. # python fallback
  1266. date=$("$(python_binary)" -c "import time;print time.strftime('${1:-$DEFAULTFORMAT}',time.localtime(${2}))" 2> /dev/null) && \
  1267. echo $date && return
  1268. # awk fallback
  1269. date=$(awk "BEGIN{print strftime(\"${1:-$DEFAULTFORMAT}\"${2:+,$2})}" 2> /dev/null) && \
  1270. echo $date && return
  1271. # perl fallback
  1272. date=$(perl -e "use POSIX qw(strftime);\$date = strftime(\"${1:-$DEFAULTFORMAT}\",localtime(${2}));print \"\$date\n\";" 2> /dev/null) && \
  1273. echo $date && return
  1274. # error
  1275. echo "ERROR"
  1276. return 1
  1277. }
  1278.  
  1279. function nsecs {
  1280. # only 9 digit returns, e.g. not all date(s) deliver nsecs
  1281. local NSECS=$(date +%N 2> /dev/null | head -1 |grep -e "^[[:digit:]]\{9\}$")
  1282. echo ${NSECS:-000000000}
  1283. }
  1284.  
  1285. function nsecs_to_sec {
  1286. echo $(($1/1000000000)).$(printf "%03d" $(($1/1000000%1000)) )
  1287. }
  1288.  
  1289. function datefull_from_nsecs {
  1290. date_from_nsecs $1 '%F %T'
  1291. }
  1292.  
  1293. function date_from_nsecs {
  1294. local FORMAT=${2:-%T}
  1295. local TIME=$(nsecs_to_sec $1)
  1296. local SECS=${TIME%.*}
  1297. local DATE=$(date_fix "%T" ${SECS:-0})
  1298. echo $DATE.${TIME#*.}
  1299. }
  1300.  
  1301. function var_isset {
  1302. if [ -z "$1" ]; then
  1303. echo "ERROR: function var_isset needs a string as parameter"
  1304. elif eval "[ \"\${$1}\" == 'not_set' ]" || eval "[ \"\${$1-not_set}\" != 'not_set' ]"; then
  1305. return 0
  1306. fi
  1307. return 1
  1308. }
  1309.  
  1310. function url_encode {
  1311. # utilize python, silently do nothing on error - because no python no duplicity
  1312. OUT=$("$(python_binary)" -c "
  1313. try: import urllib.request as urllib
  1314. except ImportError: import urllib
  1315. print(urllib.${2}quote('$1'));
  1316. " 2>/dev/null ); ERR=$?
  1317. [ "$ERR" -eq 0 ] && echo $OUT || echo $1
  1318. }
  1319.  
  1320. function url_decode {
  1321. # reuse function above with a simple string param hack
  1322. url_encode "$1" "un"
  1323. }
  1324.  
  1325. function toupper {
  1326. echo "$@"|awk '$0=toupper($0)'
  1327. }
  1328.  
  1329. function tolower {
  1330. echo "$@"|awk '$0=tolower($0)'
  1331. }
  1332.  
  1333. function isnumber {
  1334. case "$*" in
  1335. ''|*[!0-9]*) return 1;;
  1336. *) return 0;;
  1337. esac
  1338. }
  1339.  
  1340. #function tmp_space {
  1341. #
  1342. # if ! isnumber $VOLSIZE; then
  1343. # inform "failed to determine free space (please report, this is a bug)"
  1344. # return
  1345. # fi
  1346. #
  1347. # get free temp space
  1348. # TEMP_FREE="$(df -P -k "$TEMP_DIR" 2>/dev/null | awk 'END{pos=(NF-2);if(pos>0) print $pos;}')"
  1349. # # check for free space or FAIL
  1350. # if [ $((${TEMP_FREE:-0}-${VOLSIZE:-0}*1024)) -lt 0-lt 0 ]; then
  1351. # error "Temporary file space '$TEMP_DIR' free space is smaller ($((TEMP_FREE/1024))MB)
  1352. #than one duplicity volume (${VOLSIZE}MB).
  1353. #
  1354. # Hint: Free space or change TEMP_DIR setting."
  1355. #fi
  1356. #
  1357. #}
  1358.  
  1359. function gpg_disabled {
  1360. echo "${GPG_KEY}" | grep -iq -e '^disabled$'
  1361. }
  1362.  
  1363. # usage: join SEPARATOR "entry1" "entry2"
  1364. function join {
  1365. local SEP="$1" ENTRY OUT; shift;
  1366. for ENTRY in "$@"; do
  1367. ENTRY=${ENTRY//$SEP/\\$SEP}
  1368. [ -z "$OUT" ] && OUT=$ENTRY || OUT="$OUT$SEP$ENTRY"
  1369. done
  1370. echo $OUT
  1371. }
  1372.  
  1373. function gpg_signing {
  1374. echo ${GPG_KEY_SIGN} | grep -v -q -e '^disabled$'
  1375. }
  1376.  
  1377. # parameter key id, key_type
  1378. function gpg_keyfile {
  1379. local GPG_KEY=$(gpg_key_legalize $1) TYPE="$2"
  1380. local KEYFILE="${KEYFILE//.asc/${GPG_KEY:+.$GPG_KEY}.asc}"
  1381. echo "${KEYFILE//.asc/${TYPE:+.$(tolower $TYPE)}.asc}"
  1382. }
  1383.  
  1384. # parameter key id
  1385. function gpg_import {
  1386. local i FILE FOUND=0 KEY_ID="$1" KEY_TYPE="$2" KEY_FP="" ERR=0
  1387. # create a list of legacy key file names and current naming scheme
  1388. # we always import pub and sec if they are avail in conf folder
  1389. local KEYFILES=( "$CONFDIR/gpgkey" $(gpg_keyfile "$KEY_ID") \
  1390. $(gpg_keyfile "$KEY_ID" PUB) $(gpg_keyfile "$KEY_ID" SEC))
  1391.  
  1392. # Try autoimport from existing old gpgkey files
  1393. # and new gpgkey.XXX.asc files (since v1.4.2)
  1394. # and even newer gpgkey.XXX.[pub|sec].asc
  1395. for (( i = 0 ; i < ${#KEYFILES[@]} ; i++ )); do
  1396. FILE=${KEYFILES[$i]}
  1397. if [ -f "$FILE" ]; then
  1398. FOUND=1
  1399.  
  1400. CMD_MSG="Import keyfile '$FILE' to keyring"
  1401. run_cmd gpg $GPG_OPTS --batch --import $(qw "$FILE")
  1402. if [ "$?" != "0" ]; then
  1403. warning "Import failed.${CMD_OUT:+\n$CMD_OUT}"
  1404. ERR=1
  1405. # continue with next
  1406. continue
  1407. fi
  1408. fi
  1409. done
  1410.  
  1411. if [ "$FOUND" -eq 0 ]; then
  1412. warning "No keyfile for '$KEY_ID' found in profile\n'$CONFDIR'."
  1413. fi
  1414.  
  1415. # try to set trust automagically
  1416. CMD_MSG="Autoset trust of key '$KEY_ID' to ultimate"
  1417. run_cmd echo $(gpg_fingerprint "$KEY_ID"):6: \| gpg $GPG_OPTS --import-ownertrust --batch --logger-fd 1
  1418. if [ "$?" = "0" ] && [ -z "$PREVIEW" ]; then
  1419. # success on all levels, we're done
  1420. return $ERR
  1421. fi
  1422.  
  1423. # failover: user has to set trust manually
  1424. echo -e "For $ME_NAME to work you have to set the trust level
  1425. with the command \"trust\" to \"ultimate\" (5) now.
  1426. Exit the edit mode of gpg with \"quit\"."
  1427. CMD_MSG="Running gpg to manually edit key '$KEY_ID'"
  1428. run_cmd sleep 5\; gpg $GPG_OPTS --edit-key $(qw "$KEY_ID")
  1429.  
  1430. return $ERR
  1431. }
  1432.  
  1433. # see 'How to specify a user ID' on gpg manpage
  1434. function gpg_fingerprint {
  1435. local PRINT=$(gpg $GPG_OPTS --fingerprint "$1" 2>&1|awk -F= 'NR==2{gsub(/ /,"",$2);$2=toupper($2); if ( $2 ~ /^[A-F0-9]+$/ && length($2) == 40 ) print $2; else exit 1}') \
  1436. && [ -n "$PRINT" ] && echo $PRINT && return 0
  1437. return 1
  1438. }
  1439.  
  1440. function gpg_export_if_needed {
  1441. local SUCCESS FILE KEY_TYPE
  1442. local TMPFILE="$TEMP_DIR/${ME_NAME}.$$.$(date_fix %s).gpgexp"
  1443. for KEY_ID in "$@"; do
  1444. # check if already exported, do it if not
  1445. for KEY_TYPE in PUB SEC; do
  1446. FILE="$(gpg_keyfile "$KEY_ID" $KEY_TYPE)"
  1447. if [ ! -f "$FILE" ] && eval gpg_$(tolower $KEY_TYPE)_avail \"$KEY_ID\"; then
  1448. # exporting
  1449. CMD_MSG="Backup $KEY_TYPE key '$KEY_ID' to profile."
  1450. # gpg2.1 insists on passphrase here, gpg2.0- happily exports w/o it
  1451. # we pipe an empty string when GPG_PW is not set to avoid gpg silently waiting for input
  1452. run_cmd $(gpg_pass_pipein GPG_PW_SIGN GPG_PW) gpg $GPG_OPTS $GPG_USEAGENT $(gpg_param_passwd GPG_PW_SIGN GPG_PW) --armor --export"$(test "SEC" = "$KEY_TYPE" && echo -secret-keys)" $(qw "$KEY_ID") '>>' $(qw "$TMPFILE")
  1453. CMD_ERR=$?
  1454.  
  1455. if [ "$CMD_ERR" = "0" ]; then
  1456. CMD_MSG="Write file '"$(basename "$FILE")"'"
  1457. run_cmd mv $(qw "$TMPFILE") $(qw "$FILE")
  1458. fi
  1459.  
  1460. if [ "$CMD_ERR" != "0" ]; then
  1461. warning "Backup failed.${CMD_OUT:+\n$CMD_OUT}"
  1462. else
  1463. SUCCESS=1
  1464. fi
  1465.  
  1466. # cleanup
  1467. rm $(qw "$TMPFILE") 1>/dev/null 2>&1
  1468. fi
  1469. done
  1470. done
  1471.  
  1472. [ -n "$SUCCESS" ] && inform "$ME_NAME exported new keys to your profile.
  1473. You should backup your changed profile folder now and store it in a safe place."
  1474. }
  1475.  
  1476. # replace all non-alnum chars with underscore (for file operations)
  1477. function gpg_key_legalize {
  1478. echo $* | awk '{gsub(/[^a-zA-Z0-9]/,"_",$0); print}'
  1479. }
  1480.  
  1481. function gpg_key_cache {
  1482. local RES
  1483. local MODE=$1
  1484. shift
  1485. local PREFIX="GPG_KEY"
  1486. local SUFFIX=$(gpg_key_legalize "$@")
  1487. local KEYID="$*"
  1488. local CACHE="${PREFIX}_${MODE}_${SUFFIX}"
  1489. if [ "$MODE" = "RESET" ]; then
  1490. eval unset ${PREFIX}_PUB_$SUFFIX ${PREFIX}_SEC_$SUFFIX
  1491. return 255
  1492. elif ! var_isset "$CACHE"; then
  1493. if [ "$MODE" = "PUB" ]; then
  1494. RES=$(gpg $GPG_OPTS --list-key "$KEYID" > /dev/null 2>&1; echo -n $?)
  1495. elif [ "$MODE" = "SEC" ]; then
  1496. RES=$(gpg $GPG_OPTS --list-secret-key "$KEYID" > /dev/null 2>&1; echo -n $?)
  1497. else
  1498. return 255
  1499. fi
  1500. eval $CACHE=$RES
  1501. fi
  1502. eval return \$$CACHE
  1503. }
  1504.  
  1505. function gpg_pub_avail {
  1506. gpg_key_cache PUB "$@"
  1507. }
  1508.  
  1509. function gpg_sec_avail {
  1510. gpg_key_cache SEC "$@"
  1511. }
  1512.  
  1513. function gpg_key_format {
  1514. echo $1 | grep -q '^[0-9a-fA-F]\{8\}$'
  1515. }
  1516.  
  1517. # splits a comma separated line into lines, respects escaped commas
  1518. function gpg_split_keyset {
  1519. local LIST
  1520. LIST=$(echo "$@" | awk '{ gsub(/,/,"\n",$0); gsub(/\\\n/,",",$0); print $0 }')
  1521. echo -e "$LIST"
  1522. }
  1523.  
  1524. function gpg_prefix_keyset {
  1525. local PREFIX="$1" OUT=""
  1526. shift
  1527. for KEY_ID in "$@"; do
  1528. OUT="${OUT} $PREFIX $(qw ${KEY_ID})"
  1529. done
  1530. echo $OUT
  1531. }
  1532.  
  1533. # grep a variable from conf text file (currently not used)
  1534. function gpg_passwd {
  1535. [ -r "$CONF" ] && \
  1536. awk '/^[ \t]*GPG_PW[ \t=]/{\
  1537. sub(/^[ \t]*GPG_PW[ \t]*=*/,"",$0);\
  1538. gsub(/^[ \t]*[\047"]|[\047"][ \t]*$/,"",$0);\
  1539. print $0; exit}' "$CONF"
  1540. }
  1541.  
  1542. # return success if at least one secret key is available
  1543. function gpg_key_decryptable {
  1544. local KEY_ID
  1545. for KEY_ID in "${GPG_KEYS_ENC_ARRAY[@]}"; do
  1546. gpg_sec_avail "$KEY_ID" && return 0
  1547. done
  1548. return 1
  1549. }
  1550.  
  1551. function gpg_symmetric {
  1552. [ -z "${GPG_KEY}${GPG_KEYS_ENC_ARRAY}" ]
  1553. }
  1554.  
  1555. # checks for max two params if they are set, typically GPG_PW & GPG_PW_SIGN
  1556. function gpg_param_passwd {
  1557. var_isset GPG_USEAGENT && exit 1
  1558.  
  1559. if ( [ -n "$1" ] && var_isset "$1" ) || ( [ -n "$2" ] && var_isset "$2" ); then
  1560. echo "--passphrase-fd 0 --batch"
  1561. fi
  1562. }
  1563.  
  1564. # select the earlist defined and create an "echo <value> |" string
  1565. function gpg_pass_pipein {
  1566. var_isset GPG_USEAGENT && exit 1
  1567.  
  1568. for var in "$@"
  1569. do
  1570. if var_isset "$var"; then
  1571. echo "echo $(qw $(eval echo \$$var)) |"
  1572. return 0
  1573. fi
  1574. done
  1575.  
  1576. return 1
  1577. }
  1578.  
  1579. # checks if gpg-agent is available, returns error code
  1580. # 0 on success
  1581. # 1 if GPG_AGENT_INFO is not set (unused, should probably be merged w/ 3)
  1582. # 2 if GPG_AGENT_INFO is stale
  1583. # 3 cannot connect to gpg-agent
  1584. function gpg_agent_avail {
  1585. # GPG_AGENT_INFO is deprecated in gpg2.1,
  1586. # first try to connect to a possibly running agent here
  1587. local ERR=3
  1588. gpg-agent > /dev/null 2>&1 && return 0
  1589.  
  1590. # detect stale pid in legacy GPG_AGENT_INFO env var
  1591. if var_isset GPG_AGENT_INFO; then
  1592. # check if a pid matching process is running at all
  1593. local GPG_AGENT_PID=$(echo $GPG_AGENT_INFO|awk -F: '{print $2}')
  1594. if isnumber "$GPG_AGENT_PID"; then
  1595. ps -p "$GPG_AGENT_PID" > /dev/null 2>&1 || ERR=2
  1596. fi
  1597. fi
  1598.  
  1599. return $ERR
  1600. }
  1601.  
  1602. function gpg_custom_binary {
  1603. var_isset GPG && [ "$GPG" != "$DEFAULT_GPG" ] &&\
  1604. echo "--gpg-binary $(qw "$GPG")"
  1605. }
  1606.  
  1607. function gpg_binary {
  1608. local BIN
  1609. var_isset GPG && BIN="$GPG" || BIN="$DEFAULT_GPG"
  1610. echo "$BIN"
  1611. }
  1612.  
  1613. function gpg_avail {
  1614. lookup "$(gpg_binary)"
  1615. }
  1616.  
  1617. # enforce the use our selected gpg binary
  1618. function gpg {
  1619. command "$(gpg_binary)" "$@"
  1620. }
  1621. export -f gpg
  1622.  
  1623. # start of script #######################################################################
  1624.  
  1625. # confidentiality first, all we create is only readable by us
  1626. umask 077
  1627.  
  1628. # check if ftplicity is there & executable
  1629. [ -n "$ME_LONG" ] && [ -x "$ME_LONG" ] || error "$ME missing. Executable & available in path? ($ME_LONG)"
  1630.  
  1631. if [ ${#@} -eq 1 ]; then
  1632. cmd="${1}"
  1633. else
  1634. FTPLCFG="${1}" ; cmd="${2}"
  1635. fi
  1636.  
  1637. # deal with command before profile validation calls
  1638. # show requested version
  1639. # OR requested usage info
  1640. # OR create a profile
  1641. # OR fall through
  1642. ##if [ ${#@} -le 2 ]; then
  1643. case "$cmd" in
  1644. changelog)
  1645. changelog
  1646. exit 0
  1647. ;;
  1648. create)
  1649. set_config
  1650. if [ -d "$CONFDIR" ]; then
  1651. error "The profile '$FTPLCFG' already exists in
  1652. '$CONFDIR'.
  1653.  
  1654. Hint:
  1655. If you _really_ want to create a new profile by this name you will
  1656. have to manually delete the existing profile folder first."
  1657. exit 1
  1658. else
  1659. create_config
  1660. exit 0
  1661. fi
  1662. ;;
  1663. txt2man)
  1664. set_config
  1665. usage_txt2man
  1666. exit 0
  1667. ;;
  1668. usage|-help|--help|-h|-H)
  1669. set_config
  1670. usage_info
  1671. exit 0
  1672. ;;
  1673. version|-version|--version|-v|-V)
  1674. # profile can override GPG, so import it if it was given
  1675. var_isset FTPLCFG && {
  1676. set_config
  1677. [ -r "$CONF" ] && . "$CONF" || warning "Cannot import config '$CONF'."
  1678. }
  1679. version_info_using
  1680. exit 0
  1681. ;;
  1682. # fallthrough.. we got a command that needs an existing profile
  1683. *)
  1684. # if we reach here, user either forgot profile or chose wrong profileless command
  1685. if [ ${#@} -le 1 ]; then
  1686. error "\
  1687. Missing or wrong parameters.
  1688. Only the commands
  1689. changelog, create, usage, txt2man, version
  1690. can be called without selecting an existing profile first.
  1691. Your command was '$cmd'.
  1692.  
  1693. Hint: Run '$ME usage' to get help."
  1694. fi
  1695. esac
  1696.  
  1697.  
  1698. # Hello world
  1699. echo "Start $ME v$ME_VERSION, time is $(date_fix '%F %T')."
  1700.  
  1701. # check system environment
  1702.  
  1703. # is duplicity avail
  1704. lookup duplicity || error_path "duplicity missing. installed und available in path?"
  1705. # init, exec duplicity version check info
  1706. duplicity_version_get
  1707. duplicity_version_check
  1708.  
  1709. # check for certain important helper programs
  1710. for f in awk grep "$(python_binary)"; do
  1711. lookup "$f" || \
  1712. error_path "$f missing. installed und available in path?"
  1713. done
  1714.  
  1715. ### read configuration
  1716. set_config
  1717. # check validity
  1718. if [ ! -d "$CONFDIR" ]; then
  1719. error "Selected profile '$FTPLCFG' does not resolve to a profile folder in
  1720. '$CONFDIR'.
  1721.  
  1722. Hints:
  1723. Select one of the available profiles: $(for d in "$(dirname "$CONFDIR")"/*/; do [ -e "$d" ] || [ -L "$d" ] || continue; printf "$sep'$(basename "$d")'"; sep=",";done)
  1724. Use '$ME <name> create' to create a new profile.
  1725. Use '$ME usage' to get usage help."
  1726. elif [ ! -x "$CONFDIR" ]; then
  1727. error "\
  1728. Profile folder in '$CONFDIR' cannot be accessed.
  1729.  
  1730. Hint:
  1731. Check the filesystem permissions and set directory accessible e.g. 'chmod 700'."
  1732. elif [ ! -f "$CONF" ] ; then
  1733. error "'$CONF' not found."
  1734. elif [ ! -r "$CONF" ] ; then
  1735. error "'$CONF' not readable."
  1736. else
  1737. . "$CONF"
  1738. #KEYFILE="${KEYFILE//.asc/${GPG_KEY:+.$GPG_KEY}.asc}"
  1739. TEMP_DIR=${TEMP_DIR:-'/tmp'}
  1740. # backward compatibility: old TARGET_PW overrides silently new TARGET_PASS if set
  1741. if var_isset 'TARGET_PW'; then
  1742. TARGET_PASS="${TARGET_PW}"
  1743. fi
  1744. fi
  1745. echo "Using profile '$CONFDIR'."
  1746.  
  1747. # secure config dir, if needed w/ warning
  1748. secureconf
  1749.  
  1750. # split TARGET in handy variables
  1751. TARGET_SPLIT_URL=$(echo "$TARGET" | awk '{ \
  1752. target=$0; match(target,/^([^\/:]+):\/\//); \
  1753. prot=substr(target,RSTART,RLENGTH);\
  1754. rest=substr(target,RSTART+RLENGTH); \
  1755. if (credsavail=match(rest,/^[^@]*@/)){\
  1756. creds=substr(rest,RSTART,RLENGTH-1);\
  1757. credcount=split(creds,cred,":");\
  1758. rest=substr(rest,RLENGTH+1);\
  1759. # split creds with regexp\
  1760. match(creds,/^([^:]+)/);\
  1761. user=substr(creds,RSTART,RLENGTH);\
  1762. pass=substr(creds,RSTART+1+RLENGTH);\
  1763. };\
  1764. # filter quotes or escape them\
  1765. gsub(/[\047\042]/,"",prot);\
  1766. gsub(/[\047\042]/,"",rest);\
  1767. gsub(/[\047]/,"\047\\\047\047",creds);\
  1768. print "TARGET_URL_PROT=\047"prot"\047\n"\
  1769. "TARGET_URL_HOSTPATH=\047"rest"\047\n"\
  1770. "TARGET_URL_CREDS=\047"creds"\047\n";\
  1771. if(user){\
  1772. gsub(/[\047]/,"\047\\\047\047",user);\
  1773. print "TARGET_URL_USER=\047"user"\047\n"}\
  1774. if(pass){\
  1775. gsub(/[\047]/,"\047\\\047\047",pass);\
  1776. print "TARGET_URL_PASS=$(url_decode \047"pass"\047)\n"}\
  1777. }')
  1778. eval "${TARGET_SPLIT_URL}"
  1779.  
  1780. # fetch commmand from parameters ########################################################
  1781. # Hint: cmds is also used to check if authentification info sufficient in the next step
  1782. cmds="$2"; shift 2
  1783.  
  1784. # translate backup to batch command
  1785. cmds=${cmds//backup/pre_bkp_post}
  1786.  
  1787. # complain if command(s) missing
  1788. [ -z $cmds ] && error " No command given.
  1789.  
  1790. Hint:
  1791. Use '$ME usage' to get usage help."
  1792.  
  1793. # process params
  1794. for param in "$@"; do
  1795. #echo !$param!
  1796. case "$param" in
  1797. # enable ftplicity preview mode
  1798. '--preview')
  1799. PREVIEW=1
  1800.  ;;
  1801. # interpret duplicity disable encr switch
  1802. '--disable-encryption')
  1803. GPG_KEY='disabled'
  1804.  ;;
  1805. *)
  1806. if [ `echo "$param" | grep -e "^-"` ] || \
  1807. [ `echo "$last_param" | grep -e "^-"` ] ; then
  1808. # forward parameter[/option pairs] to duplicity
  1809. dupl_opts["${#dupl_opts[@]}"]=${param}
  1810. else
  1811. # anything else must be a parameter (eg. for fetch, ...)
  1812. ftpl_pars["${#ftpl_pars[@]}"]=${param}
  1813. fi
  1814. last_param=${param}
  1815.  ;;
  1816. esac
  1817. done
  1818.  
  1819. # plausibility check config - VARS & KEY ################################################
  1820. # check if src, trg, trg pw
  1821. # auth info sufficient
  1822. # gpg key, gpg pwd (might be empty) set in config
  1823. # OR key in local gpg db
  1824. # OR key can be imported from keyfile
  1825. # OR fail
  1826. if [ -z "$SOURCE" ] || [ "$SOURCE" == "${DEFAULT_SOURCE}" ]; then
  1827. error " Source Path (setting SOURCE) not set or still default value in conf file
  1828. '$CONF'."
  1829.  
  1830. elif [ -z "$TARGET" ] || [ "$TARGET" == "${DEFAULT_TARGET}" ]; then
  1831. error " Backup Target (setting TARGET) not set or still default value in conf file
  1832. '$CONF'."
  1833.  
  1834. elif var_isset 'TARGET_USER' && var_isset 'TARGET_URL_USER' && \
  1835. [ "${TARGET_USER}" != "${TARGET_URL_USER}" ]; then
  1836. error " TARGET_USER ('${TARGET_USER}') _and_ user in TARGET url ('${TARGET_URL_USER}')
  1837. are configured with different values. There can be only one.
  1838.  
  1839. Hint: Remove conflicting setting."
  1840.  
  1841. elif var_isset 'TARGET_PASS' && var_isset 'TARGET_URL_PASS' && \
  1842. [ "${TARGET_PASS}" != "${TARGET_URL_PASS}" ]; then
  1843. error " TARGET_PASS ('${TARGET_PASS}') _and_ password in TARGET url ('${TARGET_URL_PASS}')
  1844. are configured with different values. There can be only one.
  1845.  
  1846. Hint: Remove conflicting setting."
  1847. fi
  1848.  
  1849. # GPG config plausibility check1 (disabled check) #############################
  1850. if gpg_disabled; then
  1851.  : # encryption disabled, all is well
  1852. elif [ -z "${GPG_KEY}${GPG_KEYS_ENC}${GPG_KEY_SIGN}" ] && ! var_isset 'GPG_PW'; then
  1853. warning "GPG_KEY, GPG_KEYS_ENC, GPG_KEY_SIGN and GPG_PW are empty/not set in conf file
  1854. '$CONF'.
  1855. Will disable encryption for duplicity now.
  1856.  
  1857. Hint:
  1858. If you really want to use _no_ encryption you can disable this warning by
  1859. setting GPG_KEY='disabled' in conf file."
  1860. GPG_KEY='disabled'
  1861. fi
  1862.  
  1863. # GPG availability check (now we know if gpg is really needed)#################
  1864. if ! gpg_disabled; then
  1865. gpg_avail || error_path "gpg '$(gpg_binary)' missing. installed und available in path?"
  1866. fi
  1867.  
  1868. # Output versions info ########################################################
  1869. using_info
  1870.  
  1871. # GPG create key settings, config check2 (needs gpg) ##########################
  1872. if gpg_disabled; then
  1873.  : # the following tests are not necessary
  1874. else
  1875.  
  1876. # we test this early as any invocation gpg2.1+ starts gpg-agent automatically
  1877. GPG_AGENT_ERR=$(gpg_agent_avail ; echo $?)
  1878.  
  1879. # enc key still default?
  1880. if [ "$GPG_KEY" == "${DEFAULT_GPG_KEY}" ]; then
  1881. error_gpg "Encryption Key GPG_KEY still default in conf file
  1882. '$CONF'."
  1883. fi
  1884.  
  1885. # create array of gpg encr keys, for further processing
  1886. OIFS="$IFS" IFS=$'\n'
  1887. GPG_KEYS_ENC_ARRAY=( $( gpg_split_keyset ${GPG_KEY},${GPG_KEYS_ENC} ) )
  1888. IFS="$OIFS"
  1889.  
  1890. # pw set?
  1891. # symmetric needs one, always
  1892. if gpg_symmetric && ( [ -z "$GPG_PW" ] || [ "$GPG_PW" == "${DEFAULT_GPG_PW}" ] ) \
  1893.  ; then
  1894. error_gpg "Encryption passphrase GPG_PW (needed for symmetric encryption)
  1895. is empty/not set or still default value in conf file
  1896. '$CONF'."
  1897. fi
  1898. # this is a technicality, we can only pump one pass via pipe into gpg
  1899. # but symmetric already always needs one for encryption
  1900. if gpg_symmetric && var_isset GPG_PW && var_isset GPG_PW_SIGN &&\
  1901. [ -n "$GPG_PW_SIGN" ] && [ "$GPG_PW" != "$GPG_PW_SIGN" ]; then
  1902. error_gpg "GPG_PW _and_ GPG_PW_SIGN are defined but not identical in config
  1903. '$CONF'.
  1904. This is unfortunately impossible. For details see duplicity manpage,
  1905. section 'A Note On Symmetric Encryption And Signing'.
  1906.  
  1907. Tip: Separate signing keys may have empty passwords e.g. GPG_PW_SIGN=''.
  1908. Tip2: Use gpg-agent."
  1909. fi
  1910.  
  1911. # check gpg encr public keys availability
  1912. for (( i = 0 ; i < ${#GPG_KEYS_ENC_ARRAY[@]} ; i++ )); do
  1913. KEY_ID="${GPG_KEYS_ENC_ARRAY[$i]}"
  1914. # test availability, try to import, retest
  1915. if ! gpg_pub_avail "${KEY_ID}"; then
  1916. echo "Encryption public key '${KEY_ID}' not found."
  1917. gpg_import "${KEY_ID}" PUB
  1918. gpg_key_cache RESET "${KEY_ID}"
  1919. gpg_pub_avail "${KEY_ID}" || error_gpg_key "${KEY_ID}" "Public"
  1920. fi
  1921. done
  1922.  
  1923. # gpg secret sign key availability
  1924. # if none set, autoset first encryption key as sign key
  1925. if ! gpg_signing; then
  1926. echo "Signing disabled per configuration."
  1927. # try first key, if one set
  1928. elif ! var_isset 'GPG_KEY_SIGN'; then
  1929. KEY_ID="${GPG_KEYS_ENC_ARRAY[0]}"
  1930. if [ -z "${KEY_ID}" ]; then
  1931. echo "Signing disabled. Not GPG_KEY entries in config."
  1932. GPG_KEY_SIGN='disabled'
  1933. else
  1934. # use avail OR try import OR fail
  1935. if gpg_sec_avail "${KEY_ID}"; then
  1936. GPG_KEY_SIGN="${KEY_ID}"
  1937. else
  1938. gpg_import "${KEY_ID}" SEC
  1939. gpg_key_cache RESET "${KEY_ID}"
  1940. if gpg_sec_avail "${KEY_ID}"; then
  1941. GPG_KEY_SIGN="${KEY_ID}"
  1942. fi
  1943. fi
  1944.  
  1945. # interpret sign key setting
  1946. if var_isset 'GPG_KEY_SIGN'; then
  1947. echo "Autoset found secret key of first GPG_KEY entry '${KEY_ID}' for signing."
  1948. else
  1949. echo "Signing disabled. First GPG_KEY entry's '${KEY_ID}' private key is missing."
  1950. GPG_KEY_SIGN='disabled'
  1951. fi
  1952. fi
  1953. else
  1954. KEY_ID="${GPG_KEY_SIGN}"
  1955. if ! gpg_sec_avail "${KEY_ID}"; then
  1956. inform "Secret signing key defined in setting GPG_KEY_SIGN='${KEY_ID}' not found.\nTry to import."
  1957. gpg_import "${KEY_ID}" SEC
  1958. gpg_key_cache RESET "${KEY_ID}"
  1959. gpg_sec_avail "${KEY_ID}" || error_gpg_key "${KEY_ID}" "Private"
  1960. fi
  1961. fi
  1962.  
  1963. # using GPG_AGENT_ERR set early above, try to autoenable gpg-agent or issue some warnings
  1964. # key enc can deal without, but might profit from gpg-agent
  1965. # if GPG_PW is not set alltogether
  1966. # if signing key is different from first (main) enc key (we can only pipe one pass into gpg)
  1967. if ! gpg_symmetric && \
  1968. ( ! var_isset GPG_PW || \
  1969. ( gpg_signing && ! var_isset GPG_PW_SIGN && [ "$GPG_KEY_SIGN" != "${GPG_KEYS_ENC_ARRAY[0]}" ] ) ); then
  1970.  
  1971. if [ "$GPG_AGENT_ERR" -eq 1 ]; then
  1972. warning "Cannot use gpg-agent. GPG_AGENT_INFO not set."
  1973. elif [ "$GPG_AGENT_ERR" -eq 2 ]; then
  1974. warning "Cannot use gpg-agent! GPG_AGENT_INFO contains stale pid."
  1975. elif [ "$GPG_AGENT_ERR" -eq 3 ]; then
  1976. warning "No running gpg-agent found although GPG_PW or GPG_PW_SIGN (enc != sign key) not set."
  1977. else
  1978. echo "Enable gpg-agent usage. Running gpg-agent instance found and GPG_PW or GPG_PW_SIGN (enc != sign key) not set."
  1979. GPG_USEAGENT="--use-agent"
  1980. fi
  1981. fi
  1982.  
  1983. # end GPG config plausibility check2
  1984. fi
  1985.  
  1986. # config plausibility check - SPACE ###########################################
  1987.  
  1988. # is tmp is a folder and writable
  1989. CMD_MSG="Checking TEMP_DIR '${TEMP_DIR}' is a folder and writable"
  1990. run_cmd test -d $(qw "$TEMP_DIR") '&&' test -w $(qw "$TEMP_DIR")
  1991. if [ "$?" != "0" ]; then
  1992. error "Temporary file space '$TEMP_DIR' is not a directory or writable."
  1993. fi
  1994.  
  1995.  
  1996. # get volsize, default duplicity volume size is 25MB since v0.5.07
  1997. VOLSIZE=${VOLSIZE:-25}
  1998. # double if asynch is on
  1999. echo $@ $DUPL_PARAMS | grep -q -e '--asynchronous-upload' && FACTOR=2 || FACTOR=1
  2000.  
  2001. # TODO: check for enough (async= upload space and WARN only
  2002. # use function tmp_space
  2003. #echo TODO: reimplent tmp space check
  2004.  
  2005.  
  2006. # test - GPG SANITY #####################################################################
  2007. # if encryption is disabled, skip this whole section
  2008. if gpg_disabled; then
  2009. echo -e "Test - En/Decryption skipped. (GPG disabled)"
  2010. elif [ "$GPG_TEST" = "disabled" ]; then
  2011. echo -e "Test - En/Decryption skipped. (Testing disabled)"
  2012. else
  2013.  
  2014. GPG_TEST="$TEMP_DIR/${ME_NAME}.$$.$(date_fix %s)"
  2015. function cleanup_gpgtest {
  2016. echo -en "Cleanup - Delete '${GPG_TEST}_*'"
  2017. rm "${GPG_TEST}"_* 2>/dev/null && echo "(OK)" || echo "(FAILED)"
  2018. }
  2019.  
  2020. # signing enabled?
  2021. if gpg_signing; then
  2022. CMD_PARAM_SIGN="--sign --default-key $(qw ${GPG_KEY_SIGN})"
  2023. CMD_MSG_SIGN="Sign with '${GPG_KEY_SIGN}'"
  2024. fi
  2025.  
  2026. # using keys
  2027. if [ ${#GPG_KEYS_ENC_ARRAY[@]} -gt 0 ]; then
  2028.  
  2029. for KEY_ID in "${GPG_KEYS_ENC_ARRAY[@]}"; do
  2030. CMD_PARAMS="$CMD_PARAMS -r $(qw ${KEY_ID})"
  2031. done
  2032. # check encrypting
  2033. CMD_MSG="Test - Encrypt to '$(join "','" "${GPG_KEYS_ENC_ARRAY[@]}")'${CMD_MSG_SIGN:+ & $CMD_MSG_SIGN}"
  2034. run_cmd $(gpg_pass_pipein GPG_PW_SIGN GPG_PW) gpg $CMD_PARAM_SIGN $(gpg_param_passwd GPG_PW_SIGN GPG_PW) $CMD_PARAMS $GPG_USEAGENT --status-fd 1 $GPG_OPTS -o $(qw "${GPG_TEST}_ENC") -e $(qw "$ME_LONG")
  2035. CMD_ERR=$?
  2036.  
  2037. if [ "$CMD_ERR" != "0" ]; then
  2038. KEY_NOTRUST=$(echo "$CMD_OUT"|awk '/^\[GNUPG:\] INV_RECP 10/ { print $4 }')
  2039. [ -n "$KEY_NOTRUST" ] && HINT="Key '${KEY_NOTRUST}' seems to be untrusted. If you really trust this key try to
  2040. 'gpg --edit-key "$KEY_NOTRUST"' and raise the trust level to ultimate. If you
  2041. can trust all of your keys set GPG_OPTS='--trust-model always' in conf file."
  2042. error_gpg_test "Encryption failed (Code $CMD_ERR).${CMD_OUT:+\n$CMD_OUT}" "$HINT"
  2043. fi
  2044.  
  2045. # check decrypting
  2046. CMD_MSG="Test - Decrypt"
  2047. gpg_key_decryptable || CMD_DISABLED="No matching secret key available."
  2048. run_cmd $(gpg_pass_pipein GPG_PW) gpg $(gpg_param_passwd GPG_PW) $GPG_OPTS -o $(qw "${GPG_TEST}_DEC") $GPG_USEAGENT -d $(qw "${GPG_TEST}_ENC")
  2049. CMD_ERR=$?
  2050.  
  2051. if [ "$CMD_ERR" != "0" ]; then
  2052. error_gpg_test "Decryption failed.${CMD_OUT:+\n$CMD_OUT}"
  2053. fi
  2054.  
  2055. # symmetric only
  2056. else
  2057. # check encrypting
  2058. CMD_MSG="Test - Encryption with passphrase${CMD_MSG_SIGN:+ & $CMD_MSG_SIGN}"
  2059. run_cmd $(gpg_pass_pipein GPG_PW) gpg $GPG_OPTS $CMD_PARAM_SIGN --passphrase-fd 0 -o $(qw "${GPG_TEST}_ENC") --batch -c $(qw "$ME_LONG")
  2060. CMD_ERR=$?
  2061. if [ "$CMD_ERR" != "0" ]; then
  2062. error_gpg_test "Encryption failed.${CMD_OUT:+\n$CMD_OUT}"
  2063. fi
  2064.  
  2065. # check decrypting
  2066. CMD_MSG="Test - Decryption with passphrase"
  2067. run_cmd $(gpg_pass_pipein GPG_PW) gpg $GPG_OPTS --passphrase-fd 0 -o $(qw "${GPG_TEST}_DEC") --batch -d $(qw "${GPG_TEST}_ENC")
  2068. CMD_ERR=$?
  2069. if [ "$CMD_ERR" != "0" ]; then
  2070. error_gpg_test "Decryption failed.${CMD_OUT:+\n$CMD_OUT}"
  2071. fi
  2072. fi
  2073.  
  2074. # compare original w/ decryptginal
  2075. CMD_MSG="Test - Compare"
  2076. [ -r "${GPG_TEST}_DEC" ] || CMD_DISABLED="File not found. Nothing to compare."
  2077. run_cmd "test \"\$(cat '$ME_LONG')\" = \"\$(cat '${GPG_TEST}_DEC')\""
  2078. CMD_ERR=$?
  2079. if [ "$CMD_ERR" = "0" ]; then
  2080. cleanup_gpgtest
  2081. else
  2082. error_gpg_test "Comparision failed.${CMD_OUT:+\n$CMD_OUT}"
  2083. fi
  2084.  
  2085. fi # end disabled
  2086.  
  2087. ## an empty line
  2088. #echo
  2089.  
  2090. # Exclude file is needed, create it if necessary
  2091. [ -f "$EXCLUDE" ] || touch "$EXCLUDE"
  2092.  
  2093. # export only used keys, if bkp not already exists ######################################
  2094. gpg_export_if_needed "${GPG_KEYS_ENC_ARRAY[@]}" "$(gpg_signing && echo $GPG_KEY_SIGN)"
  2095.  
  2096.  
  2097. # command execution #####################################################################
  2098.  
  2099. # urldecode url vars into plain text
  2100. var_isset 'TARGET_URL_USER' && TARGET_URL_USER="$(url_decode "$TARGET_URL_USER")"
  2101. var_isset 'TARGET_URL_PASS' && TARGET_URL_PASS="$(url_decode "$TARGET_URL_PASS")"
  2102.  
  2103. # defined TARGET_USER&PASS vars replace their URL pendants
  2104. # (double defs already dealt with)
  2105. var_isset 'TARGET_USER' && TARGET_URL_USER="$TARGET_USER"
  2106. var_isset 'TARGET_PASS' && TARGET_URL_PASS="$TARGET_PASS"
  2107.  
  2108. TARGET_URL_PROT_lowercase="$(tolower "${TARGET_URL_PROT%%:*}")"
  2109.  
  2110. # issue some warnings
  2111. case "$TARGET_URL_PROT_lowercase" in
  2112. 'cf+http')
  2113. # info on missing AUTH_URL
  2114. if ! var_isset 'CLOUDFILES_AUTHURL'; then
  2115. inform "No CLOUDFILES_AUTHURL exported (in conf).
  2116. Will use default which is probably rackspace."
  2117. fi
  2118.  ;;
  2119. 'swift')
  2120. # info on possibly missing AUTH_URL
  2121. var_isset 'SWIFT_AUTHURL' ||\
  2122. warning "\
  2123. Swift will probably fail because the conf var SWIFT_AUTHURL was not exported!"
  2124.  ;;
  2125. 'rsync')
  2126. # everything in url (this backend does not support pass in env var)
  2127. # this is obsolete from version 0.6.10 (buggy), hopefully fixed in 0.6.11
  2128. # print warning older version is detected
  2129. duplicity_version_lt 610 &&
  2130. warning "\
  2131. Duplicity version '$DUPL_VERSION' does not support providing the password as
  2132. env var for rsync backend. For security reasons you should consider to
  2133. update to a version greater than '0.6.10' of duplicity."
  2134.  ;;
  2135. esac
  2136.  
  2137.  
  2138. # for all protocols we put username in url and pass into env var
  2139. # for secúrity reasons, we url_encode username to protect special chars
  2140. # first sortout backends with special ways to handle password
  2141. case "$TARGET_URL_PROT_lowercase" in
  2142. 'imap'|'imaps')
  2143. var_isset 'TARGET_URL_PASS' && BACKEND_PARAMS="IMAP_PASSWORD=$(qw "${TARGET_URL_PASS}")"
  2144.  ;;
  2145. *)
  2146. # rest uses FTP_PASS var
  2147. var_isset 'TARGET_URL_PASS' && \
  2148. BACKEND_PARAMS="FTP_PASSWORD=$(qw "${TARGET_URL_PASS}")"
  2149.  ;;
  2150. esac
  2151. # insert url encoded username into target url if needed
  2152. if var_isset 'TARGET_URL_USER' && [ "$TARGET_URL_PROT_lowercase" != "file" ]; then
  2153. BACKEND_URL="${TARGET_URL_PROT}$(url_encode "${TARGET_URL_USER}")@${TARGET_URL_HOSTPATH}"
  2154. else
  2155. BACKEND_URL="$TARGET"
  2156. fi
  2157.  
  2158.  
  2159. # protect eval from special chars in url (e.g. open ')' in password,
  2160. # spaces in path, quotes) happens above in duplify() via quotewrap()
  2161. SOURCE="$SOURCE"
  2162. BACKEND_URL="$BACKEND_URL"
  2163. EXCLUDE="$EXCLUDE"
  2164. # since 0.7.03 --exclude-globbing-filelist is deprecated
  2165. EXCLUDE_PARAM="--exclude$(duplicity_version_lt 703 && echo -globbing)-filelist"
  2166.  
  2167. # replace magic separators to condition command equivalents (+=and,-=or)
  2168. cmds=$(awk -v cmds="$cmds" "BEGIN{ gsub(/\+/,\"_and_\",cmds); gsub(/\-/,\"_or_\",cmds); print cmds}")
  2169. # convert cmds to array, lowercase for safety
  2170. CMDS=( $(awk "BEGIN{ cmds=tolower(\"$cmds\"); gsub(/_/,\" \",cmds); print cmds }") )
  2171.  
  2172. # run cmds
  2173. for cmd in ${CMDS[*]};
  2174. do
  2175.  
  2176. ## init
  2177. # raise index in cmd array for pre/post param
  2178. var_isset 'CMD_NO' && CMD_NO=$((++CMD_NO)) || CMD_NO=0
  2179.  
  2180. # deal with condition "commands"
  2181. unset SKIP_NOW
  2182. if var_isset 'CMD_SKIP' && [ $CMD_SKIP -gt 0 ]; then
  2183. echo -e "\n--- Skipping command $(toupper $cmd) ! ---"
  2184. CMD_SKIP=$(($CMD_SKIP - 1))
  2185. SKIP_NOW="yes"
  2186. elif [ "$cmd" == 'and' ] && [ "$CMD_ERR" -ne "0" ]; then
  2187. CMD_SKIP=1
  2188. SKIP_NOW="yes"
  2189. elif [ "$cmd" == 'or' ] && [ "$CMD_ERR" -eq "0" ]; then
  2190. CMD_SKIP=1
  2191. SKIP_NOW="yes"
  2192. elif [ "$cmd" == 'and' ] || [ "$cmd" == 'or' ]; then
  2193. unset 'CMD_SKIP';
  2194. SKIP_NOW="yes"
  2195. fi
  2196.  
  2197. # sum up how many commands we skip and actually skip
  2198. if [ -n "$SKIP_NOW" ]; then
  2199. CMD_SKIPPED=$((${CMD_SKIPPED-0} + 1))
  2200. continue
  2201. fi
  2202.  
  2203. # get prev/nextcmd vars
  2204. nextno=$(($CMD_NO+1))
  2205. [ "$nextno" -lt "${#CMDS[@]}" ] && CMD_NEXT=${CMDS[$nextno]} || CMD_NEXT='END'
  2206. # get previous command minus skipped commands
  2207. prevno=$(( $CMD_NO - ${CMD_SKIPPED-0} - 1 )); unset CMD_SKIPPED
  2208. [ "$prevno" -ge 0 ] && CMD_PREV=${CMDS[$prevno]} || CMD_PREV='START'
  2209.  
  2210. # save start time
  2211. RUN_START=$(date_fix %s)$(nsecs)
  2212.  
  2213. # export some useful env vars for external scripts/programs to use
  2214. export PROFILE CONFDIR SOURCE TARGET_URL_PROT TARGET_URL_HOSTPATH \
  2215. TARGET_URL_USER TARGET_URL_PASS \
  2216. GPG_KEYS_ENC=$(join "\n" "${GPG_KEYS_ENC_ARRAY[@]}") GPG_KEY_SIGN \
  2217. GPG_PW CMD_PREV CMD_NEXT CMD_ERR \
  2218. RUN_START
  2219.  
  2220. # user info
  2221. echo; separator "Start running command $(toupper $cmd) at $(date_from_nsecs $RUN_START)"
  2222.  
  2223. case "$(tolower $cmd)" in
  2224. 'pre'|'post')
  2225. if [ "$cmd" == 'pre' ]; then
  2226. script=$PRE
  2227. else
  2228. script=$POST
  2229. fi
  2230. # script execution in a subshell, protect us from failures/var overwrites
  2231. ( run_script "$script" )
  2232.  ;;
  2233. 'bkp')
  2234. duplify -- "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2235. "$SOURCE" "$BACKEND_URL"
  2236.  ;;
  2237. 'incr')
  2238. duplify incr -- "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2239. "$SOURCE" "$BACKEND_URL"
  2240.  ;;
  2241. 'full')
  2242. duplify full -- "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2243. "$SOURCE" "$BACKEND_URL"
  2244.  ;;
  2245. 'verify')
  2246. TIME="${ftpl_pars[0]:+"-t ${ftpl_pars[0]}"}"
  2247. duplify verify -- $TIME "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2248. "$BACKEND_URL" "$SOURCE"
  2249.  ;;
  2250. 'verifypath')
  2251. TIME="${ftpl_pars[2]:+"-t ${ftpl_pars[2]}"}"
  2252. IN_PATH="${ftpl_pars[0]}"; OUT_PATH="${ftpl_pars[1]}";
  2253. ( [ -z "$IN_PATH" ] || [ -z "$OUT_PATH" ] ) && error " Missing parameter <rel_bkp_path> or <local_path> for verifyPath.
  2254.  
  2255. Hint:
  2256. Syntax is -> $ME <profile> verifyPath <rel_bkp_path> <local_path> [<age>]"
  2257.  
  2258. duplify verify -- $TIME "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2259. --file-to-restore "$IN_PATH" "$BACKEND_URL" "$OUT_PATH"
  2260.  ;;
  2261. 'list')
  2262. # time param exists since 0.5.10+
  2263. TIME="${ftpl_pars[0]:+"-t ${ftpl_pars[0]}"}"
  2264. duplify list-current-files -- $TIME "${dupl_opts[@]}" "$BACKEND_URL"
  2265.  ;;
  2266. 'cleanup')
  2267. duplify cleanup -- "${dupl_opts[@]}" "$BACKEND_URL"
  2268.  ;;
  2269. 'purge')
  2270. MAX_AGE=${ftpl_pars[0]:-$MAX_AGE}
  2271. [ -z "$MAX_AGE" ] && error " Missing parameter <max_age>. Can be set in profile or as command line parameter."
  2272.  
  2273. duplify remove-older-than "${MAX_AGE}" \
  2274. -- "${dupl_opts[@]}" "$BACKEND_URL"
  2275.  ;;
  2276. 'purgefull')
  2277. MAX_FULL_BACKUPS=${ftpl_pars[0]:-$MAX_FULL_BACKUPS}
  2278. [ -z "$MAX_FULL_BACKUPS" ] && error " Missing parameter <max_full_backups>. Can be set in profile or as command line parameter."
  2279.  
  2280. duplify remove-all-but-n-full "${MAX_FULL_BACKUPS}" \
  2281. -- "${dupl_opts[@]}" "$BACKEND_URL"
  2282.  ;;
  2283. 'purgeincr')
  2284. MAX_FULLS_WITH_INCRS=${ftpl_pars[0]:-$MAX_FULLS_WITH_INCRS}
  2285. [ -z "$MAX_FULLS_WITH_INCRS" ] && error " Missing parameter <max_fulls_with_incrs>. Can be set in profile or as command line parameter."
  2286.  
  2287. duplify remove-all-inc-of-but-n-full "${MAX_FULLS_WITH_INCRS}" \
  2288. -- "${dupl_opts[@]}" "$BACKEND_URL"
  2289.  ;;
  2290. 'restore')
  2291. OUT_PATH="${ftpl_pars[0]}"; TIME="${ftpl_pars[1]:-now}";
  2292. [ -z "$OUT_PATH" ] && error " Missing parameter target_path for restore.
  2293.  
  2294. Hint:
  2295. Syntax is -> $ME <profile> restore <target_path> [<age>]"
  2296.  
  2297. duplify -- -t "$TIME" "${dupl_opts[@]}" "$BACKEND_URL" "$OUT_PATH"
  2298.  ;;
  2299. 'fetch')
  2300. IN_PATH="${ftpl_pars[0]}"; OUT_PATH="${ftpl_pars[1]}";
  2301. TIME="${ftpl_pars[2]:-now}";
  2302. ( [ -z "$IN_PATH" ] || [ -z "$OUT_PATH" ] ) && error " Missing parameter <src_path> or <target_path> for fetch.
  2303.  
  2304. Hint:
  2305. Syntax is -> $ME <profile> fetch <src_path> <target_path> [<age>]"
  2306.  
  2307. # duplicity 0.4.7 doesnt like cmd restore in combination with --file-to-restore
  2308. duplify -- --restore-time "$TIME" "${dupl_opts[@]}" \
  2309. --file-to-restore "$IN_PATH" "$BACKEND_URL" "$OUT_PATH"
  2310.  ;;
  2311. 'status')
  2312. duplify collection-status -- "${dupl_opts[@]}" "$BACKEND_URL"
  2313.  ;;
  2314. *)
  2315. warning "Unknown command '$cmd'."
  2316.  ;;
  2317. esac
  2318.  
  2319. CMD_ERR=$?
  2320. RUN_END=$(date_fix %s)$(nsecs)
  2321. RUNTIME=$(( $RUN_END - $RUN_START ))
  2322.  
  2323. # print message on error; set error code
  2324. if [ "$CMD_ERR" -ne 0 ]; then
  2325. error_print "$(datefull_from_nsecs $RUN_END) Task '$(echo $cmd|awk '$0=toupper($0)')' failed with exit code '$CMD_ERR'."
  2326. FTPL_ERR=1
  2327. fi
  2328.  
  2329. separator "Finished state $(error_to_string $CMD_ERR) at $(date_from_nsecs $RUN_END) - \
  2330. Runtime $(printf "%02d:%02d:%02d.%03d" $((RUNTIME/1000000000/60/60)) $((RUNTIME/1000000000/60%60)) $((RUNTIME/1000000000%60)) $((RUNTIME/1000000%1000)) )"
  2331.  
  2332. done
  2333.  
  2334. exit ${FTPL_ERR}
  2335.