Duply-code

From duply
Revision as of 12:14, 17 December 2015 by Edso (Talk | contribs)

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