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 #$system:stat -c%y tmp/duply.sh| awk '{print $1}'#

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