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-09-23

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