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-08-17

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