]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/filed/backup.c
080e4cf2e9f55c44d3740ef934ff1e8871a8b102
[bacula/bacula] / bacula / src / filed / backup.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2011 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version three of the GNU Affero General Public
10    License as published by the Free Software Foundation and included
11    in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU Affero General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of Kern Sibbald.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /**
29  *  Bacula File Daemon  backup.c  send file attributes and data
30  *   to the Storage daemon.
31  *
32  *    Kern Sibbald, March MM
33  *
34  */
35
36 #include "bacula.h"
37 #include "filed.h"
38 #include "ch.h"
39
40 #ifdef HAVE_DARWIN_OS
41 const bool have_darwin_os = true;
42 #else
43 const bool have_darwin_os = false;
44 #endif
45
46 #if defined(HAVE_ACL)
47 const bool have_acl = true;
48 #else
49 const bool have_acl = false;
50 #endif
51
52 #if defined(HAVE_XATTR)
53 const bool have_xattr = true;
54 #else
55 const bool have_xattr = false;
56 #endif
57
58 /* Forward referenced functions */
59 int save_file(JCR *jcr, FF_PKT *ff_pkt, bool top_level);
60 static int send_data(JCR *jcr, int stream, FF_PKT *ff_pkt, DIGEST *digest, DIGEST *signature_digest);
61 bool encode_and_send_attributes(JCR *jcr, FF_PKT *ff_pkt, int &data_stream);
62 static bool crypto_session_start(JCR *jcr);
63 static void crypto_session_end(JCR *jcr);
64 static bool crypto_session_send(JCR *jcr, BSOCK *sd);
65 static void close_vss_backup_session(JCR *jcr);
66
67 /**
68  * Find all the requested files and send them
69  * to the Storage daemon.
70  *
71  * Note, we normally carry on a one-way
72  * conversation from this point on with the SD, simply blasting
73  * data to him.  To properly know what is going on, we
74  * also run a "heartbeat" monitor which reads the socket and
75  * reacts accordingly (at the moment it has nothing to do
76  * except echo the heartbeat to the Director).
77  *
78  */
79 bool blast_data_to_storage_daemon(JCR *jcr, char *addr)
80 {
81    BSOCK *sd;
82    bool ok = true;
83    // TODO landonf: Allow user to specify encryption algorithm
84
85    sd = jcr->store_bsock;
86
87    jcr->setJobStatus(JS_Running);
88
89    Dmsg1(300, "bfiled: opened data connection %d to stored\n", sd->m_fd);
90
91    LockRes();
92    CLIENT *client = (CLIENT *)GetNextRes(R_CLIENT, NULL);
93    UnlockRes();
94    uint32_t buf_size;
95    if (client) {
96       buf_size = client->max_network_buffer_size;
97    } else {
98       buf_size = 0;                   /* use default */
99    }
100    if (!sd->set_buffer_size(buf_size, BNET_SETBUF_WRITE)) {
101       jcr->setJobStatus(JS_ErrorTerminated);
102       Jmsg(jcr, M_FATAL, 0, _("Cannot set buffer size FD->SD.\n"));
103       return false;
104    }
105
106    jcr->buf_size = sd->msglen;
107    /**
108     * Adjust for compression so that output buffer is
109     *  12 bytes + 0.1% larger than input buffer plus 18 bytes.
110     *  This gives a bit extra plus room for the sparse addr if any.
111     *  Note, we adjust the read size to be smaller so that the
112     *  same output buffer can be used without growing it.
113     *
114     *  For LZO1X compression the recommended value is :
115     *                  output_block_size = input_block_size + (input_block_size / 16) + 64 + 3 + sizeof(comp_stream_header)
116     *
117     * The zlib compression workset is initialized here to minimize
118     *  the "per file" load. The jcr member is only set, if the init 
119     *  was successful.
120     *
121     *  For the same reason, lzo compression is initialized here.
122     */
123 #ifdef HAVE_LZO
124    jcr->compress_buf_size = MAX(jcr->buf_size + (jcr->buf_size / 16) + 67 + (int)sizeof(comp_stream_header), jcr->buf_size + ((jcr->buf_size+999) / 1000) + 30);
125    jcr->compress_buf = get_memory(jcr->compress_buf_size);
126 #else
127    jcr->compress_buf_size = jcr->buf_size + ((jcr->buf_size+999) / 1000) + 30;
128    jcr->compress_buf = get_memory(jcr->compress_buf_size);
129 #endif
130    
131 #ifdef HAVE_LIBZ
132    z_stream *pZlibStream = (z_stream*)malloc(sizeof(z_stream));  
133    if (pZlibStream) {
134       pZlibStream->zalloc = Z_NULL;      
135       pZlibStream->zfree = Z_NULL;
136       pZlibStream->opaque = Z_NULL;
137       pZlibStream->state = Z_NULL;
138
139       if (deflateInit(pZlibStream, Z_DEFAULT_COMPRESSION) == Z_OK) {
140          jcr->pZLIB_compress_workset = pZlibStream;
141       } else {
142          free (pZlibStream);
143       }
144    }
145 #endif
146
147 #ifdef HAVE_LZO
148    lzo_voidp pLzoMem = (lzo_voidp) malloc(LZO1X_1_MEM_COMPRESS);
149    if (pLzoMem) {
150       if (lzo_init() == LZO_E_OK) {
151          jcr->LZO_compress_workset = pLzoMem;
152       } else {
153          free (pLzoMem);
154       }
155    }
156 #endif
157
158    if (!crypto_session_start(jcr)) {
159       return false;
160    }
161
162    set_find_options((FF_PKT *)jcr->ff, jcr->incremental, jcr->mtime);
163
164    /** in accurate mode, we overload the find_one check function */
165    if (jcr->accurate) {
166       set_find_changed_function((FF_PKT *)jcr->ff, accurate_check_file);
167    } 
168    
169    start_heartbeat_monitor(jcr);
170
171    if (have_acl) {
172       jcr->acl_data = (acl_data_t *)malloc(sizeof(acl_data_t));
173       memset(jcr->acl_data, 0, sizeof(acl_data_t));
174       jcr->acl_data->u.build = (acl_build_data_t *)malloc(sizeof(acl_build_data_t));
175       memset(jcr->acl_data->u.build, 0, sizeof(acl_build_data_t));
176       jcr->acl_data->u.build->content = get_pool_memory(PM_MESSAGE);
177    }
178
179    if (have_xattr) {
180       jcr->xattr_data = (xattr_data_t *)malloc(sizeof(xattr_data_t));
181       memset(jcr->xattr_data, 0, sizeof(xattr_data_t));
182       jcr->xattr_data->u.build = (xattr_build_data_t *)malloc(sizeof(xattr_build_data_t));
183       memset(jcr->xattr_data->u.build, 0, sizeof(xattr_build_data_t));
184       jcr->xattr_data->u.build->content = get_pool_memory(PM_MESSAGE);
185    }
186
187    /** Subroutine save_file() is called for each file */
188    if (!find_files(jcr, (FF_PKT *)jcr->ff, save_file, plugin_save)) {
189       ok = false;                     /* error */
190       jcr->setJobStatus(JS_ErrorTerminated);
191    }
192
193    if (have_acl && jcr->acl_data->u.build->nr_errors > 0) {
194       Jmsg(jcr, M_WARNING, 0, _("Encountered %ld acl errors while doing backup\n"),
195            jcr->acl_data->u.build->nr_errors);
196    }
197    if (have_xattr && jcr->xattr_data->u.build->nr_errors > 0) {
198       Jmsg(jcr, M_WARNING, 0, _("Encountered %ld xattr errors while doing backup\n"),
199            jcr->xattr_data->u.build->nr_errors);
200    }
201
202    close_vss_backup_session(jcr);
203
204    accurate_finish(jcr);              /* send deleted or base file list to SD */
205
206    stop_heartbeat_monitor(jcr);
207
208    sd->signal(BNET_EOD);            /* end of sending data */
209
210    if (have_acl && jcr->acl_data) {
211       free_pool_memory(jcr->acl_data->u.build->content);
212       free(jcr->acl_data->u.build);
213       free(jcr->acl_data);
214       jcr->acl_data = NULL;
215    }
216    if (have_xattr && jcr->xattr_data) {
217       free_pool_memory(jcr->xattr_data->u.build->content);
218       free(jcr->xattr_data->u.build);
219       free(jcr->xattr_data);
220       jcr->xattr_data = NULL;
221    }
222    if (jcr->big_buf) {
223       free(jcr->big_buf);
224       jcr->big_buf = NULL;
225    }
226    if (jcr->compress_buf) {
227       free_pool_memory(jcr->compress_buf);
228       jcr->compress_buf = NULL;
229    }
230    if (jcr->pZLIB_compress_workset) {
231       /* Free the zlib stream */
232 #ifdef HAVE_LIBZ
233       deflateEnd((z_stream *)jcr->pZLIB_compress_workset);
234 #endif
235       free (jcr->pZLIB_compress_workset);
236       jcr->pZLIB_compress_workset = NULL;
237    }
238    if (jcr->LZO_compress_workset) {
239       free (jcr->LZO_compress_workset);
240       jcr->LZO_compress_workset = NULL;
241    }
242
243    crypto_session_end(jcr);
244
245
246    Dmsg1(100, "end blast_data ok=%d\n", ok);
247    return ok;
248 }
249
250 static bool crypto_session_start(JCR *jcr)
251 {
252    crypto_cipher_t cipher = CRYPTO_CIPHER_AES_128_CBC;
253
254    /**
255     * Create encryption session data and a cached, DER-encoded session data
256     * structure. We use a single session key for each backup, so we'll encode
257     * the session data only once.
258     */
259    if (jcr->crypto.pki_encrypt) {
260       uint32_t size = 0;
261
262       /** Create per-job session encryption context */
263       jcr->crypto.pki_session = crypto_session_new(cipher, jcr->crypto.pki_recipients);
264
265       /** Get the session data size */
266       if (!crypto_session_encode(jcr->crypto.pki_session, (uint8_t *)0, &size)) {
267          Jmsg(jcr, M_FATAL, 0, _("An error occurred while encrypting the stream.\n"));
268          return false;
269       }
270
271       /** Allocate buffer */
272       jcr->crypto.pki_session_encoded = get_memory(size);
273
274       /** Encode session data */
275       if (!crypto_session_encode(jcr->crypto.pki_session, (uint8_t *)jcr->crypto.pki_session_encoded, &size)) {
276          Jmsg(jcr, M_FATAL, 0, _("An error occurred while encrypting the stream.\n"));
277          return false;
278       }
279
280       /** ... and store the encoded size */
281       jcr->crypto.pki_session_encoded_size = size;
282
283       /** Allocate the encryption/decryption buffer */
284       jcr->crypto.crypto_buf = get_memory(CRYPTO_CIPHER_MAX_BLOCK_SIZE);
285    }
286    return true;
287 }
288
289 static void crypto_session_end(JCR *jcr)
290 {
291    if (jcr->crypto.crypto_buf) {
292       free_pool_memory(jcr->crypto.crypto_buf);
293       jcr->crypto.crypto_buf = NULL;
294    }
295    if (jcr->crypto.pki_session) {
296       crypto_session_free(jcr->crypto.pki_session);
297    }
298    if (jcr->crypto.pki_session_encoded) {
299       free_pool_memory(jcr->crypto.pki_session_encoded);
300       jcr->crypto.pki_session_encoded = NULL;
301    }
302 }
303
304 static bool crypto_session_send(JCR *jcr, BSOCK *sd)
305 {
306    POOLMEM *msgsave;
307
308    /** Send our header */
309    Dmsg2(100, "Send hdr fi=%ld stream=%d\n", jcr->JobFiles, STREAM_ENCRYPTED_SESSION_DATA);
310    sd->fsend("%ld %d 0", jcr->JobFiles, STREAM_ENCRYPTED_SESSION_DATA);
311
312    msgsave = sd->msg;
313    sd->msg = jcr->crypto.pki_session_encoded;
314    sd->msglen = jcr->crypto.pki_session_encoded_size;
315    jcr->JobBytes += sd->msglen;
316
317    Dmsg1(100, "Send data len=%d\n", sd->msglen);
318    sd->send();
319    sd->msg = msgsave;
320    sd->signal(BNET_EOD);
321    return true;
322 }
323
324
325 /**
326  * Called here by find() for each file included.
327  *   This is a callback. The original is find_files() above.
328  *
329  *  Send the file and its data to the Storage daemon.
330  *
331  *  Returns: 1 if OK
332  *           0 if error
333  *          -1 to ignore file/directory (not used here)
334  */
335 int save_file(JCR *jcr, FF_PKT *ff_pkt, bool top_level)
336 {
337    bool do_read = false;
338    bool plugin_started = false;
339    bool do_plugin_set = false;
340    int stat, data_stream; 
341    int rtnstat = 0;
342    DIGEST *digest = NULL;
343    DIGEST *signing_digest = NULL;
344    int digest_stream = STREAM_NONE;
345    SIGNATURE *sig = NULL;
346    bool has_file_data = false;
347    struct save_pkt sp;          /* use by option plugin */
348    // TODO landonf: Allow the user to specify the digest algorithm
349 #ifdef HAVE_SHA2
350    crypto_digest_t signing_algorithm = CRYPTO_DIGEST_SHA256;
351 #else
352    crypto_digest_t signing_algorithm = CRYPTO_DIGEST_SHA1;
353 #endif
354    BSOCK *sd = jcr->store_bsock;
355
356    if (jcr->is_canceled() || jcr->is_incomplete()) {
357       return 0;
358    }
359
360    jcr->num_files_examined++;         /* bump total file count */
361
362    switch (ff_pkt->type) {
363    case FT_LNKSAVED:                  /* Hard linked, file already saved */
364       Dmsg2(130, "FT_LNKSAVED hard link: %s => %s\n", ff_pkt->fname, ff_pkt->link);
365       break;
366    case FT_REGE:
367       Dmsg1(130, "FT_REGE saving: %s\n", ff_pkt->fname);
368       has_file_data = true;
369       break;
370    case FT_REG:
371       Dmsg1(130, "FT_REG saving: %s\n", ff_pkt->fname);
372       has_file_data = true;
373       break;
374    case FT_LNK:
375       Dmsg2(130, "FT_LNK saving: %s -> %s\n", ff_pkt->fname, ff_pkt->link);
376       break;
377    case FT_RESTORE_FIRST:
378       Dmsg1(100, "FT_RESTORE_FIRST saving: %s\n", ff_pkt->fname);
379       break;
380    case FT_PLUGIN_CONFIG:
381       Dmsg1(100, "FT_PLUGIN_CONFIG saving: %s\n", ff_pkt->fname);
382       break;
383    case FT_DIRBEGIN:
384       jcr->num_files_examined--;      /* correct file count */
385       return 1;                       /* not used */
386    case FT_NORECURSE:
387       Jmsg(jcr, M_INFO, 1, _("     Recursion turned off. Will not descend from %s into %s\n"),
388            ff_pkt->top_fname, ff_pkt->fname);
389       ff_pkt->type = FT_DIREND;       /* Backup only the directory entry */
390       break;
391    case FT_NOFSCHG:
392       /* Suppress message for /dev filesystems */
393       if (!is_in_fileset(ff_pkt)) {
394          Jmsg(jcr, M_INFO, 1, _("     %s is a different filesystem. Will not descend from %s into it.\n"),
395               ff_pkt->fname, ff_pkt->top_fname);
396       }
397       ff_pkt->type = FT_DIREND;       /* Backup only the directory entry */
398       break;
399    case FT_INVALIDFS:
400       Jmsg(jcr, M_INFO, 1, _("     Disallowed filesystem. Will not descend from %s into %s\n"),
401            ff_pkt->top_fname, ff_pkt->fname);
402       ff_pkt->type = FT_DIREND;       /* Backup only the directory entry */
403       break;
404    case FT_INVALIDDT:
405       Jmsg(jcr, M_INFO, 1, _("     Disallowed drive type. Will not descend into %s\n"),
406            ff_pkt->fname);
407       break;
408    case FT_REPARSE:
409    case FT_JUNCTION:
410    case FT_DIREND:
411       Dmsg1(130, "FT_DIREND: %s\n", ff_pkt->link);
412       break;
413    case FT_SPEC:
414       Dmsg1(130, "FT_SPEC saving: %s\n", ff_pkt->fname);
415       if (S_ISSOCK(ff_pkt->statp.st_mode)) {
416         Jmsg(jcr, M_SKIPPED, 1, _("     Socket file skipped: %s\n"), ff_pkt->fname);
417         return 1;
418       }
419       break;
420    case FT_RAW:
421       Dmsg1(130, "FT_RAW saving: %s\n", ff_pkt->fname);
422       has_file_data = true;
423       break;
424    case FT_FIFO:
425       Dmsg1(130, "FT_FIFO saving: %s\n", ff_pkt->fname);
426       break;
427    case FT_NOACCESS: {
428       berrno be;
429       Jmsg(jcr, M_NOTSAVED, 0, _("     Could not access \"%s\": ERR=%s\n"), ff_pkt->fname,
430          be.bstrerror(ff_pkt->ff_errno));
431       jcr->JobErrors++;
432       return 1;
433    }
434    case FT_NOFOLLOW: {
435       berrno be;
436       Jmsg(jcr, M_NOTSAVED, 0, _("     Could not follow link \"%s\": ERR=%s\n"), 
437            ff_pkt->fname, be.bstrerror(ff_pkt->ff_errno));
438       jcr->JobErrors++;
439       return 1;
440    }
441    case FT_NOSTAT: {
442       berrno be;
443       Jmsg(jcr, M_NOTSAVED, 0, _("     Could not stat \"%s\": ERR=%s\n"), ff_pkt->fname,
444          be.bstrerror(ff_pkt->ff_errno));
445       jcr->JobErrors++;
446       return 1;
447    }
448    case FT_DIRNOCHG:
449    case FT_NOCHG:
450       Jmsg(jcr, M_SKIPPED, 1, _("     Unchanged file skipped: %s\n"), ff_pkt->fname);
451       return 1;
452    case FT_ISARCH:
453       Jmsg(jcr, M_NOTSAVED, 0, _("     Archive file not saved: %s\n"), ff_pkt->fname);
454       return 1;
455    case FT_NOOPEN: {
456       berrno be;
457       Jmsg(jcr, M_NOTSAVED, 0, _("     Could not open directory \"%s\": ERR=%s\n"), 
458            ff_pkt->fname, be.bstrerror(ff_pkt->ff_errno));
459       jcr->JobErrors++;
460       return 1;
461    }
462    default:
463       Jmsg(jcr, M_NOTSAVED, 0,  _("     Unknown file type %d; not saved: %s\n"), 
464            ff_pkt->type, ff_pkt->fname);
465       jcr->JobErrors++;
466       return 1;
467    }
468
469    Dmsg1(130, "bfiled: sending %s to stored\n", ff_pkt->fname);
470
471    /** Digests and encryption are only useful if there's file data */
472    if (has_file_data) {
473       /**
474        * Setup for digest handling. If this fails, the digest will be set to NULL
475        * and not used. Note, the digest (file hash) can be any one of the four
476        * algorithms below.
477        *
478        * The signing digest is a single algorithm depending on
479        * whether or not we have SHA2.              
480        *   ****FIXME****  the signing algoritm should really be
481        *   determined a different way!!!!!!  What happens if
482        *   sha2 was available during backup but not restore?
483        */
484       if (ff_pkt->flags & FO_MD5) {
485          digest = crypto_digest_new(jcr, CRYPTO_DIGEST_MD5);
486          digest_stream = STREAM_MD5_DIGEST;
487
488       } else if (ff_pkt->flags & FO_SHA1) {
489          digest = crypto_digest_new(jcr, CRYPTO_DIGEST_SHA1);
490          digest_stream = STREAM_SHA1_DIGEST;
491
492       } else if (ff_pkt->flags & FO_SHA256) {
493          digest = crypto_digest_new(jcr, CRYPTO_DIGEST_SHA256);
494          digest_stream = STREAM_SHA256_DIGEST;
495
496       } else if (ff_pkt->flags & FO_SHA512) {
497          digest = crypto_digest_new(jcr, CRYPTO_DIGEST_SHA512);
498          digest_stream = STREAM_SHA512_DIGEST;
499       }
500
501       /** Did digest initialization fail? */
502       if (digest_stream != STREAM_NONE && digest == NULL) {
503          Jmsg(jcr, M_WARNING, 0, _("%s digest initialization failed\n"),
504             stream_to_ascii(digest_stream));
505       }
506
507       /**
508        * Set up signature digest handling. If this fails, the signature digest
509        * will be set to NULL and not used.
510        */
511       /* TODO landonf: We should really only calculate the digest once, for
512        * both verification and signing.
513        */
514       if (jcr->crypto.pki_sign) {
515          signing_digest = crypto_digest_new(jcr, signing_algorithm);
516
517          /** Full-stop if a failure occurred initializing the signature digest */
518          if (signing_digest == NULL) {
519             Jmsg(jcr, M_NOTSAVED, 0, _("%s signature digest initialization failed\n"),
520                stream_to_ascii(signing_algorithm));
521             jcr->JobErrors++;
522             goto good_rtn;
523          }
524       }
525
526       /** Enable encryption */
527       if (jcr->crypto.pki_encrypt) {
528          ff_pkt->flags |= FO_ENCRYPT;
529       }
530    }
531
532    /** Initialize the file descriptor we use for data and other streams. */
533    binit(&ff_pkt->bfd);
534    if (ff_pkt->flags & FO_PORTABLE) {
535       set_portable_backup(&ff_pkt->bfd); /* disable Win32 BackupRead() */
536    }
537
538    if (ff_pkt->cmd_plugin) {
539       do_plugin_set = true;
540
541    /* option and cmd plugin are not compatible together */
542    } else if (ff_pkt->opt_plugin) {
543       
544       /* ask the option plugin what to do with this file */
545       switch (plugin_option_handle_file(jcr, ff_pkt, &sp)) {
546       case bRC_OK:
547          Dmsg2(10, "Option plugin %s will be used to backup %s\n",
548                ff_pkt->plugin, ff_pkt->fname);
549          do_plugin_set = true;
550          break;
551       case bRC_Skip:
552          Dmsg2(10, "Option plugin %s decided to skip %s\n",
553                ff_pkt->plugin, ff_pkt->fname);
554          goto good_rtn;
555       default:
556          Dmsg2(10, "Option plugin %s decided to let bacula handle %s\n",
557                ff_pkt->plugin, ff_pkt->fname);
558          break;
559       }
560    }
561
562    if (do_plugin_set) {
563       /* Tell bfile that it needs to call plugin */
564       if (!set_cmd_plugin(&ff_pkt->bfd, jcr)) {
565          goto bail_out;
566       }
567       send_plugin_name(jcr, sd, true);      /* signal start of plugin data */
568       plugin_started = true;
569    }
570
571    /** Send attributes -- must be done after binit() */
572    if (!encode_and_send_attributes(jcr, ff_pkt, data_stream)) {
573       goto bail_out;
574    }
575    /** Meta data only for restore object */
576    if (IS_FT_OBJECT(ff_pkt->type)) {
577       goto good_rtn;
578    }
579
580    /** Set up the encryption context and send the session data to the SD */
581    if (has_file_data && jcr->crypto.pki_encrypt) {
582       if (!crypto_session_send(jcr, sd)) {
583          goto bail_out;
584       }
585    }
586
587    /**
588     * Open any file with data that we intend to save, then save it.
589     *
590     * Note, if is_win32_backup, we must open the Directory so that
591     * the BackupRead will save its permissions and ownership streams.
592     */
593    if (ff_pkt->type != FT_LNKSAVED && S_ISREG(ff_pkt->statp.st_mode)) {
594 #ifdef HAVE_WIN32
595       do_read = !is_portable_backup(&ff_pkt->bfd) || ff_pkt->statp.st_size > 0;
596 #else
597       do_read = ff_pkt->statp.st_size > 0;  
598 #endif
599    } else if (ff_pkt->type == FT_RAW || ff_pkt->type == FT_FIFO ||
600               ff_pkt->type == FT_REPARSE || ff_pkt->type == FT_JUNCTION ||
601          (!is_portable_backup(&ff_pkt->bfd) && ff_pkt->type == FT_DIREND)) {
602       do_read = true;
603    }
604
605    if (ff_pkt->cmd_plugin && !ff_pkt->no_read) {
606       do_read = true;
607    }
608
609    Dmsg2(150, "type=%d do_read=%d\n", ff_pkt->type, do_read);
610    if (do_read) {
611       btimer_t *tid;
612
613       if (ff_pkt->type == FT_FIFO) {
614          tid = start_thread_timer(jcr, pthread_self(), 60);
615       } else {
616          tid = NULL;
617       }
618       int noatime = ff_pkt->flags & FO_NOATIME ? O_NOATIME : 0;
619       ff_pkt->bfd.reparse_point = (ff_pkt->type == FT_REPARSE || 
620                                    ff_pkt->type == FT_JUNCTION);
621       if (bopen(&ff_pkt->bfd, ff_pkt->fname, O_RDONLY | O_BINARY | noatime, 0) < 0) {
622          ff_pkt->ff_errno = errno;
623          berrno be;
624          Jmsg(jcr, M_NOTSAVED, 0, _("     Cannot open \"%s\": ERR=%s.\n"), ff_pkt->fname,
625               be.bstrerror());
626          jcr->JobErrors++;
627          if (tid) {
628             stop_thread_timer(tid);
629             tid = NULL;
630          }
631          goto good_rtn;
632       }
633       if (tid) {
634          stop_thread_timer(tid);
635          tid = NULL;
636       }
637
638       stat = send_data(jcr, data_stream, ff_pkt, digest, signing_digest);
639
640       if (ff_pkt->flags & FO_CHKCHANGES) {
641          has_file_changed(jcr, ff_pkt);
642       }
643
644       bclose(&ff_pkt->bfd);
645       
646       if (!stat) {
647          goto bail_out;
648       }
649    }
650
651    if (have_darwin_os) {
652       /** Regular files can have resource forks and Finder Info */
653       if (ff_pkt->type != FT_LNKSAVED && (S_ISREG(ff_pkt->statp.st_mode) &&
654           ff_pkt->flags & FO_HFSPLUS)) {
655          if (ff_pkt->hfsinfo.rsrclength > 0) {
656             int flags;
657             int rsrc_stream;
658             if (!bopen_rsrc(&ff_pkt->bfd, ff_pkt->fname, O_RDONLY | O_BINARY, 0) < 0) {
659                ff_pkt->ff_errno = errno;
660                berrno be;
661                Jmsg(jcr, M_NOTSAVED, -1, _("     Cannot open resource fork for \"%s\": ERR=%s.\n"),
662                     ff_pkt->fname, be.bstrerror());
663                jcr->JobErrors++;
664                if (is_bopen(&ff_pkt->bfd)) {
665                   bclose(&ff_pkt->bfd);
666                }
667                goto good_rtn;
668             }
669             flags = ff_pkt->flags;
670             ff_pkt->flags &= ~(FO_COMPRESS|FO_SPARSE|FO_OFFSETS);
671             if (flags & FO_ENCRYPT) {
672                rsrc_stream = STREAM_ENCRYPTED_MACOS_FORK_DATA;
673             } else {
674                rsrc_stream = STREAM_MACOS_FORK_DATA;
675             }
676             stat = send_data(jcr, rsrc_stream, ff_pkt, digest, signing_digest);
677             ff_pkt->flags = flags;
678             bclose(&ff_pkt->bfd);
679             if (!stat) {
680                goto bail_out;
681             }
682          }
683
684          Dmsg1(300, "Saving Finder Info for \"%s\"\n", ff_pkt->fname);
685          sd->fsend("%ld %d 0", jcr->JobFiles, STREAM_HFSPLUS_ATTRIBUTES);
686          Dmsg1(300, "bfiled>stored:header %s\n", sd->msg);
687          pm_memcpy(sd->msg, ff_pkt->hfsinfo.fndrinfo, 32);
688          sd->msglen = 32;
689          if (digest) {
690             crypto_digest_update(digest, (uint8_t *)sd->msg, sd->msglen);
691          }
692          if (signing_digest) {
693             crypto_digest_update(signing_digest, (uint8_t *)sd->msg, sd->msglen);
694          }
695          sd->send();
696          sd->signal(BNET_EOD);
697       }
698    }
699
700    /**
701     * Save ACLs when requested and available for anything not being a symlink
702     * and not being a plugin.
703     */
704    if (have_acl) {
705       if (ff_pkt->flags & FO_ACL && ff_pkt->type != FT_LNK && !ff_pkt->cmd_plugin) {
706          switch (build_acl_streams(jcr, ff_pkt)) {
707          case bacl_exit_fatal:
708             goto bail_out;
709          case bacl_exit_error:
710             /**
711              * Non-fatal errors, count them and when the number is under
712              * ACL_REPORT_ERR_MAX_PER_JOB print the error message set by the
713              * lower level routine in jcr->errmsg.
714              */
715             if (jcr->acl_data->u.build->nr_errors < ACL_REPORT_ERR_MAX_PER_JOB) {
716                Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);
717             }
718             jcr->acl_data->u.build->nr_errors++;
719             break;
720          case bacl_exit_ok:
721             break;
722          }
723       }
724    }
725
726    /**
727     * Save Extended Attributes when requested and available for all files not
728     * being a plugin.
729     */
730    if (have_xattr) {
731       if (ff_pkt->flags & FO_XATTR && !ff_pkt->cmd_plugin) {
732          switch (build_xattr_streams(jcr, ff_pkt)) {
733          case bxattr_exit_fatal:
734             goto bail_out;
735          case bxattr_exit_error:
736             /**
737              * Non-fatal errors, count them and when the number is under
738              * XATTR_REPORT_ERR_MAX_PER_JOB print the error message set by the
739              * lower level routine in jcr->errmsg.
740              */
741             if (jcr->xattr_data->u.build->nr_errors < XATTR_REPORT_ERR_MAX_PER_JOB) {
742                Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);
743             }
744             jcr->xattr_data->u.build->nr_errors++;
745             break;
746          case bxattr_exit_ok:
747             break;
748          }
749       }
750    }
751
752    /** Terminate the signing digest and send it to the Storage daemon */
753    if (signing_digest) {
754       uint32_t size = 0;
755
756       if ((sig = crypto_sign_new(jcr)) == NULL) {
757          Jmsg(jcr, M_FATAL, 0, _("Failed to allocate memory for crypto signature.\n"));
758          goto bail_out;
759       }
760
761       if (!crypto_sign_add_signer(sig, signing_digest, jcr->crypto.pki_keypair)) {
762          Jmsg(jcr, M_FATAL, 0, _("An error occurred while signing the stream.\n"));
763          goto bail_out;
764       }
765
766       /** Get signature size */
767       if (!crypto_sign_encode(sig, NULL, &size)) {
768          Jmsg(jcr, M_FATAL, 0, _("An error occurred while signing the stream.\n"));
769          goto bail_out;
770       }
771
772       /** Grow the bsock buffer to fit our message if necessary */
773       if (sizeof_pool_memory(sd->msg) < (int32_t)size) {
774          sd->msg = realloc_pool_memory(sd->msg, size);
775       }
776
777       /** Send our header */
778       sd->fsend("%ld %ld 0", jcr->JobFiles, STREAM_SIGNED_DIGEST);
779       Dmsg1(300, "bfiled>stored:header %s\n", sd->msg);
780
781       /** Encode signature data */
782       if (!crypto_sign_encode(sig, (uint8_t *)sd->msg, &size)) {
783          Jmsg(jcr, M_FATAL, 0, _("An error occurred while signing the stream.\n"));
784          goto bail_out;
785       }
786
787       sd->msglen = size;
788       sd->send();
789       sd->signal(BNET_EOD);              /* end of checksum */
790    }
791
792    /** Terminate any digest and send it to Storage daemon */
793    if (digest) {
794       uint32_t size;
795
796       sd->fsend("%ld %d 0", jcr->JobFiles, digest_stream);
797       Dmsg1(300, "bfiled>stored:header %s\n", sd->msg);
798
799       size = CRYPTO_DIGEST_MAX_SIZE;
800
801       /** Grow the bsock buffer to fit our message if necessary */
802       if (sizeof_pool_memory(sd->msg) < (int32_t)size) {
803          sd->msg = realloc_pool_memory(sd->msg, size);
804       }
805
806       if (!crypto_digest_finalize(digest, (uint8_t *)sd->msg, &size)) {
807          Jmsg(jcr, M_FATAL, 0, _("An error occurred finalizing signing the stream.\n"));
808          goto bail_out;
809       }
810
811       /* Keep the checksum if this file is a hardlink */
812       if (ff_pkt->linked) {
813          ff_pkt_set_link_digest(ff_pkt, digest_stream, sd->msg, size);
814       }
815
816       sd->msglen = size;
817       sd->send();
818       sd->signal(BNET_EOD);              /* end of checksum */
819    }
820
821    /* Check if original file has a digest, and send it */
822    if (ff_pkt->type == FT_LNKSAVED && ff_pkt->digest) {
823       Dmsg2(300, "Link %s digest %d\n", ff_pkt->fname, ff_pkt->digest_len);
824       sd->fsend("%ld %d 0", jcr->JobFiles, ff_pkt->digest_stream);
825
826       sd->msg = check_pool_memory_size(sd->msg, ff_pkt->digest_len);
827       memcpy(sd->msg, ff_pkt->digest, ff_pkt->digest_len);
828       sd->msglen = ff_pkt->digest_len;
829       sd->send();
830
831       sd->signal(BNET_EOD);              /* end of hardlink record */
832    }
833
834 good_rtn:
835    rtnstat = jcr->is_canceled() ? 0 : 1; /* good return if not canceled */
836
837 bail_out:
838    if (jcr->is_incomplete() || jcr->is_canceled()) {
839       rtnstat = 0;
840    }
841    if (plugin_started) {
842       send_plugin_name(jcr, sd, false); /* signal end of plugin data */
843    }
844    if (ff_pkt->opt_plugin) {
845       jcr->plugin_sp = NULL;    /* sp is local to this function */
846       jcr->plugin_ctx = NULL;
847       jcr->plugin = NULL;
848       jcr->opt_plugin = false;
849    }
850    if (digest) {
851       crypto_digest_free(digest);
852    }
853    if (signing_digest) {
854       crypto_digest_free(signing_digest);
855    }
856    if (sig) {
857       crypto_sign_free(sig);        
858    }
859    return rtnstat;
860 }
861
862 /**
863  * Send data read from an already open file descriptor.
864  *
865  * We return 1 on sucess and 0 on errors.
866  *
867  * ***FIXME***
868  * We use ff_pkt->statp.st_size when FO_SPARSE to know when to stop
869  *  reading.
870  * Currently this is not a problem as the only other stream, resource forks,
871  * are not handled as sparse files.
872  */
873 static int send_data(JCR *jcr, int stream, FF_PKT *ff_pkt, DIGEST *digest, 
874                      DIGEST *signing_digest)
875 {
876    BSOCK *sd = jcr->store_bsock;
877    uint64_t fileAddr = 0;             /* file address */
878    char *rbuf, *wbuf;
879    int32_t rsize = jcr->buf_size;      /* read buffer size */
880    POOLMEM *msgsave;
881    CIPHER_CONTEXT *cipher_ctx = NULL; /* Quell bogus uninitialized warnings */
882    const uint8_t *cipher_input;
883    uint32_t cipher_input_len;
884    uint32_t cipher_block_size;
885    uint32_t encrypted_len;
886 #ifdef FD_NO_SEND_TEST
887    return 1;
888 #endif
889
890    msgsave = sd->msg;
891    rbuf = sd->msg;                    /* read buffer */
892    wbuf = sd->msg;                    /* write buffer */
893    cipher_input = (uint8_t *)rbuf;    /* encrypt uncompressed data */
894
895    Dmsg1(300, "Saving data, type=%d\n", ff_pkt->type);
896
897 #if defined(HAVE_LIBZ) || defined(HAVE_LZO)
898    uLong compress_len = 0;
899    uLong max_compress_len = 0;
900    const Bytef *cbuf = NULL;
901  #ifdef HAVE_LIBZ
902    int zstat;
903
904    if ((ff_pkt->flags & FO_COMPRESS) && ff_pkt->Compress_algo == COMPRESS_GZIP) {
905       if ((ff_pkt->flags & FO_SPARSE) || (ff_pkt->flags & FO_OFFSETS)) {
906          cbuf = (Bytef *)jcr->compress_buf + OFFSET_FADDR_SIZE;
907          max_compress_len = jcr->compress_buf_size - OFFSET_FADDR_SIZE;
908       } else {
909          cbuf = (Bytef *)jcr->compress_buf;
910          max_compress_len = jcr->compress_buf_size; /* set max length */
911       }
912       wbuf = jcr->compress_buf;    /* compressed output here */
913       cipher_input = (uint8_t *)jcr->compress_buf; /* encrypt compressed data */
914
915       /**
916        * Only change zlib parameters if there is no pending operation.
917        * This should never happen as deflatereset is called after each
918        * deflate.
919        */
920
921       if (((z_stream*)jcr->pZLIB_compress_workset)->total_in == 0) {
922          /** set gzip compression level - must be done per file */
923          if ((zstat=deflateParams((z_stream*)jcr->pZLIB_compress_workset, 
924               ff_pkt->Compress_level, Z_DEFAULT_STRATEGY)) != Z_OK) {
925             Jmsg(jcr, M_FATAL, 0, _("Compression deflateParams error: %d\n"), zstat);
926             jcr->setJobStatus(JS_ErrorTerminated);
927             goto err;
928          }
929       }
930    }
931  #endif
932  #ifdef HAVE_LZO
933    Bytef *cbuf2;
934    int lzores;
935    comp_stream_header ch;
936
937    memset(&ch, 0, sizeof(comp_stream_header));
938    cbuf2 = NULL;
939
940    if ((ff_pkt->flags & FO_COMPRESS) && ff_pkt->Compress_algo == COMPRESS_LZO1X) {
941       if ((ff_pkt->flags & FO_SPARSE) || (ff_pkt->flags & FO_OFFSETS)) {
942          cbuf = (Bytef *)jcr->compress_buf + OFFSET_FADDR_SIZE;
943          cbuf2 = (Bytef *)jcr->compress_buf + OFFSET_FADDR_SIZE + sizeof(comp_stream_header);
944          max_compress_len = jcr->compress_buf_size - OFFSET_FADDR_SIZE;
945       } else {
946          cbuf = (Bytef *)jcr->compress_buf;
947          cbuf2 = (Bytef *)jcr->compress_buf + sizeof(comp_stream_header);
948          max_compress_len = jcr->compress_buf_size; /* set max length */
949       }
950       ch.magic = COMPRESS_LZO1X;
951       ch.version = COMP_HEAD_VERSION;
952       wbuf = jcr->compress_buf;    /* compressed output here */
953       cipher_input = (uint8_t *)jcr->compress_buf; /* encrypt compressed data */
954    }
955  #endif
956 #else
957    const uint32_t max_compress_len = 0;
958 #endif
959
960    if (ff_pkt->flags & FO_ENCRYPT) {
961       if ((ff_pkt->flags & FO_SPARSE) || (ff_pkt->flags & FO_OFFSETS)) {
962          Jmsg0(jcr, M_FATAL, 0, _("Encrypting sparse or offset data not supported.\n"));
963          goto err;
964       }
965       /** Allocate the cipher context */
966       if ((cipher_ctx = crypto_cipher_new(jcr->crypto.pki_session, true, 
967            &cipher_block_size)) == NULL) {
968          /* Shouldn't happen! */
969          Jmsg0(jcr, M_FATAL, 0, _("Failed to initialize encryption context.\n"));
970          goto err;
971       }
972
973       /**
974        * Grow the crypto buffer, if necessary.
975        * crypto_cipher_update() will buffer up to (cipher_block_size - 1).
976        * We grow crypto_buf to the maximum number of blocks that
977        * could be returned for the given read buffer size.
978        * (Using the larger of either rsize or max_compress_len)
979        */
980       jcr->crypto.crypto_buf = check_pool_memory_size(jcr->crypto.crypto_buf, 
981            (MAX(rsize + (int)sizeof(uint32_t), (int32_t)max_compress_len) + 
982             cipher_block_size - 1) / cipher_block_size * cipher_block_size);
983
984       wbuf = jcr->crypto.crypto_buf; /* Encrypted, possibly compressed output here. */
985    }
986
987    /**
988     * Send Data header to Storage daemon
989     *    <file-index> <stream> <info>
990     */
991    if (!sd->fsend("%ld %d 0", jcr->JobFiles, stream)) {
992       if (!jcr->is_job_canceled()) {
993          Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
994                sd->bstrerror());
995       }
996       goto err;
997    }
998    Dmsg1(300, ">stored: datahdr %s\n", sd->msg);
999
1000    /**
1001     * Make space at beginning of buffer for fileAddr because this
1002     *   same buffer will be used for writing if compression is off.
1003     */
1004    if ((ff_pkt->flags & FO_SPARSE) || (ff_pkt->flags & FO_OFFSETS)) {
1005       rbuf += OFFSET_FADDR_SIZE;
1006       rsize -= OFFSET_FADDR_SIZE;
1007 #ifdef HAVE_FREEBSD_OS
1008       /**
1009        * To read FreeBSD partitions, the read size must be
1010        *  a multiple of 512.
1011        */
1012       rsize = (rsize/512) * 512;
1013 #endif
1014    }
1015
1016    /** a RAW device read on win32 only works if the buffer is a multiple of 512 */
1017 #ifdef HAVE_WIN32
1018    if (S_ISBLK(ff_pkt->statp.st_mode))
1019       rsize = (rsize/512) * 512;
1020 #endif
1021    
1022    /**
1023     * Read the file data
1024     */
1025    while ((sd->msglen=(uint32_t)bread(&ff_pkt->bfd, rbuf, rsize)) > 0) {
1026
1027       /** Check for sparse blocks */
1028       if (ff_pkt->flags & FO_SPARSE) {
1029          ser_declare;
1030          bool allZeros = false;
1031          if ((sd->msglen == rsize &&
1032               fileAddr+sd->msglen < (uint64_t)ff_pkt->statp.st_size) ||
1033              ((ff_pkt->type == FT_RAW || ff_pkt->type == FT_FIFO) &&
1034                (uint64_t)ff_pkt->statp.st_size == 0)) {
1035             allZeros = is_buf_zero(rbuf, rsize);
1036          }
1037          if (!allZeros) {
1038             /** Put file address as first data in buffer */
1039             ser_begin(wbuf, OFFSET_FADDR_SIZE);
1040             ser_uint64(fileAddr);     /* store fileAddr in begin of buffer */
1041          }
1042          fileAddr += sd->msglen;      /* update file address */
1043          /** Skip block of all zeros */
1044          if (allZeros) {
1045             continue;                 /* skip block of zeros */
1046          }
1047       } else if (ff_pkt->flags & FO_OFFSETS) {
1048          ser_declare;
1049          ser_begin(wbuf, OFFSET_FADDR_SIZE);
1050          ser_uint64(ff_pkt->bfd.offset);     /* store offset in begin of buffer */
1051       }
1052
1053       jcr->ReadBytes += sd->msglen;         /* count bytes read */
1054
1055       /** Uncompressed cipher input length */
1056       cipher_input_len = sd->msglen;
1057
1058       /** Update checksum if requested */
1059       if (digest) {
1060          crypto_digest_update(digest, (uint8_t *)rbuf, sd->msglen);
1061       }
1062
1063       /** Update signing digest if requested */
1064       if (signing_digest) {
1065          crypto_digest_update(signing_digest, (uint8_t *)rbuf, sd->msglen);
1066       }
1067
1068 #ifdef HAVE_LIBZ
1069       /** Do compression if turned on */
1070       if (ff_pkt->flags & FO_COMPRESS && ff_pkt->Compress_algo == COMPRESS_GZIP && jcr->pZLIB_compress_workset) {
1071          Dmsg3(400, "cbuf=0x%x rbuf=0x%x len=%u\n", cbuf, rbuf, sd->msglen);
1072          
1073          ((z_stream*)jcr->pZLIB_compress_workset)->next_in   = (Bytef *)rbuf;
1074                 ((z_stream*)jcr->pZLIB_compress_workset)->avail_in  = sd->msglen;
1075          ((z_stream*)jcr->pZLIB_compress_workset)->next_out  = (Bytef *)cbuf;
1076                 ((z_stream*)jcr->pZLIB_compress_workset)->avail_out = max_compress_len;
1077
1078          if ((zstat=deflate((z_stream*)jcr->pZLIB_compress_workset, Z_FINISH)) != Z_STREAM_END) {
1079             Jmsg(jcr, M_FATAL, 0, _("Compression deflate error: %d\n"), zstat);
1080             jcr->setJobStatus(JS_ErrorTerminated);
1081             goto err;
1082          }
1083          compress_len = ((z_stream*)jcr->pZLIB_compress_workset)->total_out;
1084          /** reset zlib stream to be able to begin from scratch again */
1085          if ((zstat=deflateReset((z_stream*)jcr->pZLIB_compress_workset)) != Z_OK) {
1086             Jmsg(jcr, M_FATAL, 0, _("Compression deflateReset error: %d\n"), zstat);
1087             jcr->setJobStatus(JS_ErrorTerminated);
1088             goto err;
1089          }
1090
1091          Dmsg2(400, "GZIP compressed len=%d uncompressed len=%d\n", compress_len, 
1092                sd->msglen);
1093
1094          sd->msglen = compress_len;      /* set compressed length */
1095          cipher_input_len = compress_len;
1096       }
1097 #endif
1098 #ifdef HAVE_LZO
1099       /** Do compression if turned on */
1100       if (ff_pkt->flags & FO_COMPRESS && ff_pkt->Compress_algo == COMPRESS_LZO1X && jcr->LZO_compress_workset) {
1101          lzo_uint len;          /* TODO: See with the latest patch how to handle lzo_uint with 64bit */
1102
1103          ser_declare;
1104          ser_begin(cbuf, sizeof(comp_stream_header));
1105
1106          Dmsg3(400, "cbuf=0x%x rbuf=0x%x len=%u\n", cbuf, rbuf, sd->msglen);
1107
1108          lzores = lzo1x_1_compress((const unsigned char*)rbuf, sd->msglen, cbuf2, 
1109                                    &len, jcr->LZO_compress_workset);
1110          compress_len = len;
1111          if (lzores == LZO_E_OK && compress_len <= max_compress_len)
1112          {
1113             /* complete header */
1114             ser_uint32(COMPRESS_LZO1X);
1115             ser_uint32(compress_len);
1116             ser_uint16(ch.level);
1117             ser_uint16(ch.version);
1118          } else {
1119             /** this should NEVER happen */
1120             Jmsg(jcr, M_FATAL, 0, _("Compression LZO error: %d\n"), lzores);
1121             jcr->setJobStatus(JS_ErrorTerminated);
1122             goto err;
1123          }
1124
1125          Dmsg2(400, "LZO compressed len=%d uncompressed len=%d\n", compress_len, 
1126                sd->msglen);
1127
1128          compress_len += sizeof(comp_stream_header); /* add size of header */
1129          sd->msglen = compress_len;      /* set compressed length */
1130          cipher_input_len = compress_len;
1131       }
1132 #endif
1133
1134       /**
1135        * Note, here we prepend the current record length to the beginning
1136        *  of the encrypted data. This is because both sparse and compression
1137        *  restore handling want records returned to them with exactly the
1138        *  same number of bytes that were processed in the backup handling.
1139        *  That is, both are block filters rather than a stream.  When doing
1140        *  compression, the compression routines may buffer data, so that for
1141        *  any one record compressed, when it is decompressed the same size
1142        *  will not be obtained. Of course, the buffered data eventually comes
1143        *  out in subsequent crypto_cipher_update() calls or at least
1144        *  when crypto_cipher_finalize() is called.  Unfortunately, this
1145        *  "feature" of encryption enormously complicates the restore code.
1146        */
1147       if (ff_pkt->flags & FO_ENCRYPT) {
1148          uint32_t initial_len = 0;
1149          ser_declare;
1150
1151          if ((ff_pkt->flags & FO_SPARSE) || (ff_pkt->flags & FO_OFFSETS)) {
1152             cipher_input_len += OFFSET_FADDR_SIZE;
1153          }
1154
1155          /** Encrypt the length of the input block */
1156          uint8_t packet_len[sizeof(uint32_t)];
1157
1158          ser_begin(packet_len, sizeof(uint32_t));
1159          ser_uint32(cipher_input_len);    /* store data len in begin of buffer */
1160          Dmsg1(20, "Encrypt len=%d\n", cipher_input_len);
1161
1162          if (!crypto_cipher_update(cipher_ctx, packet_len, sizeof(packet_len),
1163              (uint8_t *)jcr->crypto.crypto_buf, &initial_len)) {
1164             /** Encryption failed. Shouldn't happen. */
1165             Jmsg(jcr, M_FATAL, 0, _("Encryption error\n"));
1166             goto err;
1167          }
1168
1169          /** Encrypt the input block */
1170          if (crypto_cipher_update(cipher_ctx, cipher_input, cipher_input_len, 
1171              (uint8_t *)&jcr->crypto.crypto_buf[initial_len], &encrypted_len)) {
1172             if ((initial_len + encrypted_len) == 0) {
1173                /** No full block of data available, read more data */
1174                continue;
1175             }
1176             Dmsg2(400, "encrypted len=%d unencrypted len=%d\n", encrypted_len, 
1177                   sd->msglen);
1178             sd->msglen = initial_len + encrypted_len; /* set encrypted length */
1179          } else {
1180             /** Encryption failed. Shouldn't happen. */
1181             Jmsg(jcr, M_FATAL, 0, _("Encryption error\n"));
1182             goto err;
1183          }
1184       }
1185
1186       /* Send the buffer to the Storage daemon */
1187       if ((ff_pkt->flags & FO_SPARSE) || (ff_pkt->flags & FO_OFFSETS)) {
1188          sd->msglen += OFFSET_FADDR_SIZE; /* include fileAddr in size */
1189       }
1190       sd->msg = wbuf;              /* set correct write buffer */
1191       if (!sd->send()) {
1192          if (!jcr->is_job_canceled()) {
1193             Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
1194                   sd->bstrerror());
1195          }
1196          goto err;
1197       }
1198       Dmsg1(130, "Send data to SD len=%d\n", sd->msglen);
1199       /*          #endif */
1200       jcr->JobBytes += sd->msglen;      /* count bytes saved possibly compressed/encrypted */
1201       sd->msg = msgsave;                /* restore read buffer */
1202
1203    } /* end while read file data */
1204
1205    if (sd->msglen < 0) {                 /* error */
1206       berrno be;
1207       Jmsg(jcr, M_ERROR, 0, _("Read error on file %s. ERR=%s\n"),
1208          ff_pkt->fname, be.bstrerror(ff_pkt->bfd.berrno));
1209       if (jcr->JobErrors++ > 1000) {       /* insanity check */
1210          Jmsg(jcr, M_FATAL, 0, _("Too many errors. JobErrors=%d.\n"), jcr->JobErrors);
1211       }
1212    } else if (ff_pkt->flags & FO_ENCRYPT) {
1213       /** 
1214        * For encryption, we must call finalize to push out any
1215        *  buffered data.
1216        */
1217       if (!crypto_cipher_finalize(cipher_ctx, (uint8_t *)jcr->crypto.crypto_buf, 
1218            &encrypted_len)) {
1219          /* Padding failed. Shouldn't happen. */
1220          Jmsg(jcr, M_FATAL, 0, _("Encryption padding error\n"));
1221          goto err;
1222       }
1223
1224       /** Note, on SSL pre-0.9.7, there is always some output */
1225       if (encrypted_len > 0) {
1226          sd->msglen = encrypted_len;      /* set encrypted length */
1227          sd->msg = jcr->crypto.crypto_buf;       /* set correct write buffer */
1228          if (!sd->send()) {
1229             if (!jcr->is_job_canceled()) {
1230                Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
1231                      sd->bstrerror());
1232             }
1233             goto err;
1234          }
1235          Dmsg1(130, "Send data to SD len=%d\n", sd->msglen);
1236          jcr->JobBytes += sd->msglen;     /* count bytes saved possibly compressed/encrypted */
1237          sd->msg = msgsave;               /* restore bnet buffer */
1238       }
1239    }
1240
1241    if (!sd->signal(BNET_EOD)) {        /* indicate end of file data */
1242       if (!jcr->is_job_canceled()) {
1243          Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
1244                sd->bstrerror());
1245       }
1246       goto err;
1247    }
1248
1249    /** Free the cipher context */
1250    if (cipher_ctx) {
1251       crypto_cipher_free(cipher_ctx);
1252    }
1253    return 1;
1254
1255 err:
1256    /** Free the cipher context */
1257    if (cipher_ctx) {
1258       crypto_cipher_free(cipher_ctx);
1259    }
1260
1261    sd->msg = msgsave; /* restore bnet buffer */
1262    sd->msglen = 0;
1263    return 0;
1264 }
1265
1266 bool encode_and_send_attributes(JCR *jcr, FF_PKT *ff_pkt, int &data_stream) 
1267 {
1268    BSOCK *sd = jcr->store_bsock;
1269    char attribs[MAXSTRING];
1270    char attribsExBuf[MAXSTRING];
1271    char *attribsEx = NULL;
1272    int attr_stream;
1273    int comp_len;
1274    bool stat;
1275    int hangup = get_hangup();
1276 #ifdef FD_NO_SEND_TEST
1277    return true;
1278 #endif
1279
1280    Dmsg1(300, "encode_and_send_attrs fname=%s\n", ff_pkt->fname);
1281    /** Find what data stream we will use, then encode the attributes */
1282    if ((data_stream = select_data_stream(ff_pkt)) == STREAM_NONE) {
1283       /* This should not happen */
1284       Jmsg0(jcr, M_FATAL, 0, _("Invalid file flags, no supported data stream type.\n"));
1285       return false;
1286    }
1287    encode_stat(attribs, &ff_pkt->statp, sizeof(ff_pkt->statp), ff_pkt->LinkFI, data_stream);
1288
1289    /** Now possibly extend the attributes */
1290    if (IS_FT_OBJECT(ff_pkt->type)) {
1291       attr_stream = STREAM_RESTORE_OBJECT;
1292    } else {
1293       attribsEx = attribsExBuf;
1294       attr_stream = encode_attribsEx(jcr, attribsEx, ff_pkt);
1295    }
1296
1297    Dmsg3(300, "File %s\nattribs=%s\nattribsEx=%s\n", ff_pkt->fname, attribs, attribsEx);
1298
1299    jcr->lock();
1300    jcr->JobFiles++;                    /* increment number of files sent */
1301    ff_pkt->FileIndex = jcr->JobFiles;  /* return FileIndex */
1302    pm_strcpy(jcr->last_fname, ff_pkt->fname);
1303    jcr->unlock();
1304
1305    /* Debug code: check if we must hangup */
1306    if (hangup && (jcr->JobFiles > (uint32_t)hangup)) {
1307       jcr->setJobStatus(JS_Incomplete);
1308       Jmsg1(jcr, M_FATAL, 0, "Debug hangup requested after %d files.\n", hangup);
1309       set_hangup(0);
1310       return false;
1311    }
1312
1313    /**
1314     * Send Attributes header to Storage daemon
1315     *    <file-index> <stream> <info>
1316     */
1317    if (!sd->fsend("%ld %d 0", jcr->JobFiles, attr_stream)) {
1318       if (!jcr->is_canceled() && !jcr->is_incomplete()) {
1319          Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
1320                sd->bstrerror());
1321       }
1322       return false;
1323    }
1324    Dmsg1(300, ">stored: attrhdr %s\n", sd->msg);
1325
1326    /**
1327     * Send file attributes to Storage daemon
1328     *   File_index
1329     *   File type
1330     *   Filename (full path)
1331     *   Encoded attributes
1332     *   Link name (if type==FT_LNK or FT_LNKSAVED)
1333     *   Encoded extended-attributes (for Win32)
1334     *
1335     * or send Restore Object to Storage daemon
1336     *   File_index
1337     *   File_type
1338     *   Object_index
1339     *   Object_len  (possibly compressed)
1340     *   Object_full_len (not compressed)
1341     *   Object_compression
1342     *   Plugin_name
1343     *   Object_name
1344     *   Binary Object data
1345     *
1346     * For a directory, link is the same as fname, but with trailing
1347     * slash. For a linked file, link is the link.
1348     */
1349    if (ff_pkt->type != FT_DELETED) { /* already stripped */
1350       strip_path(ff_pkt);
1351    }
1352    switch (ff_pkt->type) {
1353    case FT_LNK:
1354    case FT_LNKSAVED:
1355       Dmsg3(300, "Link %d %s to %s\n", jcr->JobFiles, ff_pkt->fname, ff_pkt->link);
1356       stat = sd->fsend("%ld %d %s%c%s%c%s%c%s%c%u%c", jcr->JobFiles,
1357                        ff_pkt->type, ff_pkt->fname, 0, attribs, 0, 
1358                        ff_pkt->link, 0, attribsEx, 0, ff_pkt->delta_seq, 0);
1359       break;
1360    case FT_DIREND:
1361    case FT_REPARSE:
1362    case FT_JUNCTION:
1363       /* Here link is the canonical filename (i.e. with trailing slash) */
1364       stat = sd->fsend("%ld %d %s%c%s%c%c%s%c%u%c", jcr->JobFiles,
1365                        ff_pkt->type, ff_pkt->link, 0, attribs, 0, 0, 
1366                        attribsEx, 0, ff_pkt->delta_seq, 0);
1367       break;
1368    case FT_PLUGIN_CONFIG:
1369    case FT_RESTORE_FIRST:
1370       comp_len = ff_pkt->object_len;
1371       ff_pkt->object_compression = 0;
1372       if (ff_pkt->object_len > 1000) {
1373          /* Big object, compress it */
1374          comp_len = ff_pkt->object_len + 1000;
1375          POOLMEM *comp_obj = get_memory(comp_len);
1376          /* *** FIXME *** check Zdeflate error */
1377          Zdeflate(ff_pkt->object, ff_pkt->object_len, comp_obj, comp_len);
1378          if (comp_len < ff_pkt->object_len) {
1379             ff_pkt->object = comp_obj;
1380             ff_pkt->object_compression = 1;    /* zlib level 9 compression */
1381          } else {
1382             /* Uncompressed object smaller, use it */
1383             comp_len = ff_pkt->object_len;
1384          }
1385          Dmsg2(100, "Object compressed from %d to %d bytes\n", ff_pkt->object_len, comp_len);
1386       }
1387       sd->msglen = Mmsg(sd->msg, "%d %d %d %d %d %d %s%c%s%c",
1388                         jcr->JobFiles, ff_pkt->type, ff_pkt->object_index,
1389                         comp_len, ff_pkt->object_len, ff_pkt->object_compression,
1390                         ff_pkt->fname, 0, ff_pkt->object_name, 0);
1391       sd->msg = check_pool_memory_size(sd->msg, sd->msglen + comp_len + 2);
1392       memcpy(sd->msg + sd->msglen, ff_pkt->object, comp_len);
1393       /* Note we send one extra byte so Dir can store zero after object */
1394       sd->msglen += comp_len + 1;
1395       stat = sd->send();
1396       if (ff_pkt->object_compression) {
1397          free_and_null_pool_memory(ff_pkt->object);
1398       }
1399       break;
1400    case FT_REG:
1401       stat = sd->fsend("%ld %d %s%c%s%c%c%s%c%d%c", jcr->JobFiles,
1402                ff_pkt->type, ff_pkt->fname, 0, attribs, 0, 0, attribsEx, 0,
1403                ff_pkt->delta_seq, 0);
1404       break;
1405    default:
1406       stat = sd->fsend("%ld %d %s%c%s%c%c%s%c%u%c", jcr->JobFiles,
1407                        ff_pkt->type, ff_pkt->fname, 0, attribs, 0, 0,
1408                        attribsEx, 0, ff_pkt->delta_seq, 0);
1409       break;
1410    }
1411    if (ff_pkt->type != FT_DELETED) {
1412       unstrip_path(ff_pkt);
1413    }
1414
1415    Dmsg2(300, ">stored: attr len=%d: %s\n", sd->msglen, sd->msg);
1416    if (!stat && !jcr->is_job_canceled()) {
1417       Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
1418             sd->bstrerror());
1419    }
1420    sd->signal(BNET_EOD);            /* indicate end of attributes data */
1421    return stat;
1422 }
1423
1424 /**
1425  * Do in place strip of path
1426  */
1427 static bool do_strip(int count, char *in)
1428 {
1429    char *out = in;
1430    int stripped;
1431    int numsep = 0;
1432
1433    /** Copy to first path separator -- Win32 might have c: ... */
1434    while (*in && !IsPathSeparator(*in)) {    
1435       out++; in++;
1436    }
1437    out++; in++;
1438    numsep++;                     /* one separator seen */
1439    for (stripped=0; stripped<count && *in; stripped++) {
1440       while (*in && !IsPathSeparator(*in)) {
1441          in++;                   /* skip chars */
1442       }
1443       if (*in) {
1444          numsep++;               /* count separators seen */
1445          in++;                   /* skip separator */
1446       }
1447    }
1448    /* Copy to end */
1449    while (*in) {                /* copy to end */
1450       if (IsPathSeparator(*in)) {
1451          numsep++;
1452       }
1453       *out++ = *in++;
1454    }
1455    *out = 0;
1456    Dmsg4(500, "stripped=%d count=%d numsep=%d sep>count=%d\n", 
1457          stripped, count, numsep, numsep>count);
1458    return stripped==count && numsep>count;
1459 }
1460
1461 /**
1462  * If requested strip leading components of the path so that we can
1463  *   save file as if it came from a subdirectory.  This is most useful
1464  *   for dealing with snapshots, by removing the snapshot directory, or
1465  *   in handling vendor migrations where files have been restored with
1466  *   a vendor product into a subdirectory.
1467  */
1468 void strip_path(FF_PKT *ff_pkt)
1469 {
1470    if (!(ff_pkt->flags & FO_STRIPPATH) || ff_pkt->strip_path <= 0) {
1471       Dmsg1(200, "No strip for %s\n", ff_pkt->fname);
1472       return;
1473    }
1474    if (!ff_pkt->fname_save) {
1475      ff_pkt->fname_save = get_pool_memory(PM_FNAME); 
1476      ff_pkt->link_save = get_pool_memory(PM_FNAME);
1477    }
1478    pm_strcpy(ff_pkt->fname_save, ff_pkt->fname);
1479    if (ff_pkt->type != FT_LNK && ff_pkt->fname != ff_pkt->link) {
1480       pm_strcpy(ff_pkt->link_save, ff_pkt->link);
1481       Dmsg2(500, "strcpy link_save=%d link=%d\n", strlen(ff_pkt->link_save),
1482          strlen(ff_pkt->link));
1483       Dsm_check(200);
1484    }
1485
1486    /**
1487     * Strip path.  If it doesn't succeed put it back.  If
1488     *  it does, and there is a different link string,
1489     *  attempt to strip the link. If it fails, back them
1490     *  both back.
1491     * Do not strip symlinks.
1492     * I.e. if either stripping fails don't strip anything.
1493     */
1494    if (!do_strip(ff_pkt->strip_path, ff_pkt->fname)) {
1495       unstrip_path(ff_pkt);
1496       goto rtn;
1497    } 
1498    /** Strip links but not symlinks */
1499    if (ff_pkt->type != FT_LNK && ff_pkt->fname != ff_pkt->link) {
1500       if (!do_strip(ff_pkt->strip_path, ff_pkt->link)) {
1501          unstrip_path(ff_pkt);
1502       }
1503    }
1504
1505 rtn:
1506    Dmsg3(100, "fname=%s stripped=%s link=%s\n", ff_pkt->fname_save, ff_pkt->fname, 
1507        ff_pkt->link);
1508 }
1509
1510 void unstrip_path(FF_PKT *ff_pkt)
1511 {
1512    if (!(ff_pkt->flags & FO_STRIPPATH) || ff_pkt->strip_path <= 0) {
1513       return;
1514    }
1515    strcpy(ff_pkt->fname, ff_pkt->fname_save);
1516    if (ff_pkt->type != FT_LNK && ff_pkt->fname != ff_pkt->link) {
1517       Dmsg2(500, "strcpy link=%s link_save=%s\n", ff_pkt->link,
1518           ff_pkt->link_save);
1519       strcpy(ff_pkt->link, ff_pkt->link_save);
1520       Dmsg2(500, "strcpy link=%d link_save=%d\n", strlen(ff_pkt->link),
1521           strlen(ff_pkt->link_save));
1522       Dsm_check(200);
1523    }
1524 }
1525
1526 static void close_vss_backup_session(JCR *jcr)
1527 {
1528 #if defined(WIN32_VSS)
1529    /* STOP VSS ON WIN32 */
1530    /* tell vss to close the backup session */
1531    if (jcr->VSS) {
1532       if (g_pVSSClient->CloseBackup()) {             
1533          /* inform user about writer states */
1534          for (int i=0; i<(int)g_pVSSClient->GetWriterCount(); i++) {
1535             int msg_type = M_INFO;
1536             if (g_pVSSClient->GetWriterState(i) < 1) {
1537                msg_type = M_WARNING;
1538                jcr->JobErrors++;
1539             }
1540             Jmsg(jcr, msg_type, 0, _("VSS Writer (BackupComplete): %s\n"), g_pVSSClient->GetWriterInfo(i));
1541          }
1542       }
1543       /* Generate Job global writer metadata */
1544       WCHAR *metadata = g_pVSSClient->GetMetadata();
1545       if (metadata) {
1546          FF_PKT *ff_pkt = jcr->ff;
1547          ff_pkt->fname = (char *)"*all*"; /* for all plugins */
1548          ff_pkt->type = FT_RESTORE_FIRST;
1549          ff_pkt->LinkFI = 0;
1550          ff_pkt->object_name = (char *)"job_metadata.xml";
1551          ff_pkt->object = (char *)metadata;
1552          ff_pkt->object_len = (wcslen(metadata) + 1) * sizeof(WCHAR);
1553          ff_pkt->object_index = (int)time(NULL);
1554          save_file(jcr, ff_pkt, true);
1555      }
1556    }
1557 #endif
1558 }