]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/filed/backup.c
Fixed problems with encryption when combined with compression or sparse files. Unfor...
[bacula/bacula] / bacula / src / filed / backup.c
1 /*
2  *  Bacula File Daemon  backup.c  send file attributes and data
3  *   to the Storage daemon.
4  *
5  *    Kern Sibbald, March MM
6  *
7  *   Version $Id$
8  *
9  */
10 /*
11    Copyright (C) 2000-2006 Kern Sibbald
12
13    This program is free software; you can redistribute it and/or
14    modify it under the terms of the GNU General Public License
15    version 2 as amended with additional clauses defined in the
16    file LICENSE in the main source directory.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
21    the file LICENSE for additional details.
22
23  */
24
25 #include "bacula.h"
26 #include "filed.h"
27
28 /* Forward referenced functions */
29 static int save_file(FF_PKT *ff_pkt, void *pkt, bool top_level);
30 static int send_data(JCR *jcr, int stream, FF_PKT *ff_pkt, DIGEST *digest, DIGEST *signature_digest);
31 static bool encode_and_send_attributes(JCR *jcr, FF_PKT *ff_pkt, int &data_stream);
32 static bool read_and_send_acl(JCR *jcr, int acltype, int stream);
33
34 /*
35  * Find all the requested files and send them
36  * to the Storage daemon.
37  *
38  * Note, we normally carry on a one-way
39  * conversation from this point on with the SD, simply blasting
40  * data to him.  To properly know what is going on, we
41  * also run a "heartbeat" monitor which reads the socket and
42  * reacts accordingly (at the moment it has nothing to do
43  * except echo the heartbeat to the Director).
44  *
45  */
46 bool blast_data_to_storage_daemon(JCR *jcr, char *addr)
47 {
48    BSOCK *sd;
49    bool ok = true;
50    // TODO landonf: Allow user to specify encryption algorithm
51    crypto_cipher_t cipher = CRYPTO_CIPHER_AES_128_CBC;
52
53    sd = jcr->store_bsock;
54
55    set_jcr_job_status(jcr, JS_Running);
56
57    Dmsg1(300, "bfiled: opened data connection %d to stored\n", sd->fd);
58
59    LockRes();
60    CLIENT *client = (CLIENT *)GetNextRes(R_CLIENT, NULL);
61    UnlockRes();
62    uint32_t buf_size;
63    if (client) {
64       buf_size = client->max_network_buffer_size;
65    } else {
66       buf_size = 0;                   /* use default */
67    }
68    if (!bnet_set_buffer_size(sd, buf_size, BNET_SETBUF_WRITE)) {
69       set_jcr_job_status(jcr, JS_ErrorTerminated);
70       Jmsg(jcr, M_FATAL, 0, _("Cannot set buffer size FD->SD.\n"));
71       return false;
72    }
73
74    jcr->buf_size = sd->msglen;
75    /* Adjust for compression so that output buffer is
76     * 12 bytes + 0.1% larger than input buffer plus 18 bytes.
77     * This gives a bit extra plus room for the sparse addr if any.
78     * Note, we adjust the read size to be smaller so that the
79     * same output buffer can be used without growing it.
80     *
81     * The zlib compression workset is initialized here to minimise
82     * the "per file" load. The jcr member is only set, if the init was successful.
83     */
84    jcr->compress_buf_size = jcr->buf_size + ((jcr->buf_size+999) / 1000) + 30;
85    jcr->compress_buf = get_memory(jcr->compress_buf_size);
86
87 #ifdef HAVE_LIBZ
88    z_stream *pZlibStream = (z_stream*)malloc(sizeof(z_stream));  
89    if (pZlibStream) {
90       pZlibStream->zalloc = Z_NULL;      
91       pZlibStream->zfree = Z_NULL;
92       pZlibStream->opaque = Z_NULL;
93       pZlibStream->state = Z_NULL;
94
95       if (deflateInit(pZlibStream, Z_DEFAULT_COMPRESSION) == Z_OK)
96          jcr->pZLIB_compress_workset = pZlibStream;
97       else
98          free (pZlibStream);
99    }
100 #endif
101
102    /* Create encryption session data and a cached, DER-encoded session data
103     * structure. We use a single session key for each backup, so we'll encode
104     * the session data only once. */
105    if (jcr->pki_encrypt) {
106       uint32_t size = 0;
107
108       /* Create per-job session encryption context */
109       jcr->pki_session = crypto_session_new(cipher, jcr->pki_recipients);
110
111       /* Get the session data size */
112       if (crypto_session_encode(jcr->pki_session, (uint8_t *)0, &size) == false) {
113          Jmsg(jcr, M_FATAL, 0, _("An error occured while encrypting the stream.\n"));
114          return 0;
115       }
116
117       /* Allocate buffer */
118       jcr->pki_session_encoded = (uint8_t *)malloc(size);
119       if (!jcr->pki_session_encoded) {
120          return 0;
121       }
122
123       /* Encode session data */
124       if (crypto_session_encode(jcr->pki_session, jcr->pki_session_encoded, &size) == false) {
125          Jmsg(jcr, M_FATAL, 0, _("An error occured while encrypting the stream.\n"));
126          return 0;
127       }
128
129       /* ... and store the encoded size */
130       jcr->pki_session_encoded_size = size;
131
132       /* Allocate the encryption/decryption buffer */
133       jcr->crypto_buf = get_memory(CRYPTO_CIPHER_MAX_BLOCK_SIZE);
134    }
135
136    Dmsg1(300, "set_find_options ff=%p\n", jcr->ff);
137    set_find_options((FF_PKT *)jcr->ff, jcr->incremental, jcr->mtime);
138    Dmsg0(300, "start find files\n");
139
140    start_heartbeat_monitor(jcr);
141
142    jcr->acl_text = get_pool_memory(PM_MESSAGE);
143
144    /* Subroutine save_file() is called for each file */
145    if (!find_files(jcr, (FF_PKT *)jcr->ff, save_file, (void *)jcr)) {
146       ok = false;                     /* error */
147       set_jcr_job_status(jcr, JS_ErrorTerminated);
148 //    Jmsg(jcr, M_FATAL, 0, _("Find files error.\n"));
149    }
150
151    free_pool_memory(jcr->acl_text);
152
153    stop_heartbeat_monitor(jcr);
154
155    bnet_sig(sd, BNET_EOD);            /* end of sending data */
156
157    if (jcr->big_buf) {
158       free(jcr->big_buf);
159       jcr->big_buf = NULL;
160    }
161    if (jcr->compress_buf) {
162       free_pool_memory(jcr->compress_buf);
163       jcr->compress_buf = NULL;
164    }
165    if (jcr->pZLIB_compress_workset) {
166       /* Free the zlib stream */
167 #ifdef HAVE_LIBZ
168       deflateEnd((z_stream *)jcr->pZLIB_compress_workset);
169 #endif
170       free (jcr->pZLIB_compress_workset);
171       jcr->pZLIB_compress_workset = NULL;
172    }
173    if (jcr->crypto_buf) {
174       free_pool_memory(jcr->crypto_buf);
175       jcr->crypto_buf = NULL;
176    }
177    if (jcr->pki_session) {
178       crypto_session_free(jcr->pki_session);
179    }
180    if (jcr->pki_session_encoded) {
181       free(jcr->pki_session_encoded);
182    }
183
184    Dmsg1(100, "end blast_data ok=%d\n", ok);
185    return ok;
186 }
187
188 /*
189  * Called here by find() for each file included.
190  *   This is a callback. The original is find_files() above.
191  *
192  *  Send the file and its data to the Storage daemon.
193  *
194  *  Returns: 1 if OK
195  *           0 if error
196  *          -1 to ignore file/directory (not used here)
197  */
198 static int save_file(FF_PKT *ff_pkt, void *vjcr, bool top_level)
199 {
200    int stat, data_stream;
201    DIGEST *digest = NULL;
202    DIGEST *signing_digest = NULL;
203    int digest_stream = STREAM_NONE;
204    // TODO landonf: Allow the user to specify the digest algorithm
205 #ifdef HAVE_SHA2
206    crypto_digest_t signing_algorithm = CRYPTO_DIGEST_SHA256;
207 #else
208    crypto_digest_t signing_algorithm = CRYPTO_DIGEST_SHA1;
209 #endif
210    JCR *jcr = (JCR *)vjcr;
211    BSOCK *sd = jcr->store_bsock;
212
213    if (job_canceled(jcr)) {
214       return 0;
215    }
216
217    jcr->num_files_examined++;         /* bump total file count */
218
219    switch (ff_pkt->type) {
220    case FT_LNKSAVED:                  /* Hard linked, file already saved */
221       Dmsg2(130, "FT_LNKSAVED hard link: %s => %s\n", ff_pkt->fname, ff_pkt->link);
222       break;
223    case FT_REGE:
224       Dmsg1(130, "FT_REGE saving: %s\n", ff_pkt->fname);
225       break;
226    case FT_REG:
227       Dmsg1(130, "FT_REG saving: %s\n", ff_pkt->fname);
228       break;
229    case FT_LNK:
230       Dmsg2(130, "FT_LNK saving: %s -> %s\n", ff_pkt->fname, ff_pkt->link);
231       break;
232    case FT_DIRBEGIN:
233       jcr->num_files_examined--;      /* correct file count */
234       return 1;                       /* not used */
235    case FT_NORECURSE:
236       Jmsg(jcr, M_INFO, 1, _("     Recursion turned off. Will not descend from %s into %s\n"),
237            ff_pkt->top_fname, ff_pkt->fname);
238       ff_pkt->type = FT_DIREND;       /* Backup only the directory entry */
239       break;
240    case FT_NOFSCHG:
241       /* Suppress message for /dev filesystems */
242       if (strncmp(ff_pkt->fname, "/dev/", 5) != 0) {
243          Jmsg(jcr, M_INFO, 1, _("     %s is a different filesystem. Will not descend from %s into %s\n"),
244               ff_pkt->fname, ff_pkt->top_fname, ff_pkt->fname);
245       }
246       ff_pkt->type = FT_DIREND;       /* Backup only the directory entry */
247       break;
248    case FT_INVALIDFS:
249       Jmsg(jcr, M_INFO, 1, _("     Disallowed filesystem. Will not descend from %s into %s\n"),
250            ff_pkt->top_fname, ff_pkt->fname);
251       ff_pkt->type = FT_DIREND;       /* Backup only the directory entry */
252       break;
253    case FT_INVALIDDT:
254       Jmsg(jcr, M_INFO, 1, _("     Disallowed drive type. Will not descend into %s\n"),
255            ff_pkt->fname);
256       break;
257    case FT_DIREND:
258       Dmsg1(130, "FT_DIREND: %s\n", ff_pkt->link);
259       break;
260    case FT_SPEC:
261       Dmsg1(130, "FT_SPEC saving: %s\n", ff_pkt->fname);
262       break;
263    case FT_RAW:
264       Dmsg1(130, "FT_RAW saving: %s\n", ff_pkt->fname);
265       break;
266    case FT_FIFO:
267       Dmsg1(130, "FT_FIFO saving: %s\n", ff_pkt->fname);
268       break;
269    case FT_NOACCESS: {
270       berrno be;
271       Jmsg(jcr, M_NOTSAVED, 0, _("     Could not access %s: ERR=%s\n"), ff_pkt->fname,
272          be.strerror(ff_pkt->ff_errno));
273       jcr->Errors++;
274       return 1;
275    }
276    case FT_NOFOLLOW: {
277       berrno be;
278       Jmsg(jcr, M_NOTSAVED, 0, _("     Could not follow link %s: ERR=%s\n"), ff_pkt->fname,
279          be.strerror(ff_pkt->ff_errno));
280       jcr->Errors++;
281       return 1;
282    }
283    case FT_NOSTAT: {
284       berrno be;
285       Jmsg(jcr, M_NOTSAVED, 0, _("     Could not stat %s: ERR=%s\n"), ff_pkt->fname,
286          be.strerror(ff_pkt->ff_errno));
287       jcr->Errors++;
288       return 1;
289    }
290    case FT_DIRNOCHG:
291    case FT_NOCHG:
292       Jmsg(jcr, M_SKIPPED, 1, _("     Unchanged file skipped: %s\n"), ff_pkt->fname);
293       return 1;
294    case FT_ISARCH:
295       Jmsg(jcr, M_NOTSAVED, 0, _("     Archive file not saved: %s\n"), ff_pkt->fname);
296       return 1;
297    case FT_NOOPEN: {
298       berrno be;
299       Jmsg(jcr, M_NOTSAVED, 0, _("     Could not open directory %s: ERR=%s\n"), ff_pkt->fname,
300          be.strerror(ff_pkt->ff_errno));
301       jcr->Errors++;
302       return 1;
303    }
304    default:
305       Jmsg(jcr, M_NOTSAVED, 0,  _("     Unknown file type %d; not saved: %s\n"), ff_pkt->type, ff_pkt->fname);
306       jcr->Errors++;
307       return 1;
308    }
309
310    Dmsg1(130, "bfiled: sending %s to stored\n", ff_pkt->fname);
311
312    /*
313     * Setup for digest handling. If this fails, the digest will be set to NULL
314     * and not used.
315     */
316    if (ff_pkt->flags & FO_MD5) {
317       digest = crypto_digest_new(CRYPTO_DIGEST_MD5);
318       digest_stream = STREAM_MD5_DIGEST;
319
320    } else if (ff_pkt->flags & FO_SHA1) {
321       digest = crypto_digest_new(CRYPTO_DIGEST_SHA1);
322       digest_stream = STREAM_SHA1_DIGEST;
323
324    } else if (ff_pkt->flags & FO_SHA256) {
325       digest = crypto_digest_new(CRYPTO_DIGEST_SHA256);
326       digest_stream = STREAM_SHA256_DIGEST;
327
328    } else if (ff_pkt->flags & FO_SHA512) {
329       digest = crypto_digest_new(CRYPTO_DIGEST_SHA512);
330       digest_stream = STREAM_SHA512_DIGEST;
331    }
332
333    /* Did digest initialization fail? */
334    if (digest_stream != STREAM_NONE && digest == NULL) {
335       Jmsg(jcr, M_WARNING, 0, _("%s digest initialization failed\n"),
336          stream_to_ascii(digest_stream));
337    }
338
339    /*
340     * Set up signature digest handling. If this fails, the signature digest will be set to
341     * NULL and not used.
342     */
343    // TODO landonf: We should really only calculate the digest once, for both verification and signing.
344    if (jcr->pki_sign) {
345       signing_digest = crypto_digest_new(signing_algorithm);
346
347       /* Full-stop if a failure occured initializing the signature digest */
348       if (signing_digest == NULL) {
349          Jmsg(jcr, M_NOTSAVED, 0, _("%s signature digest initialization failed\n"),
350             stream_to_ascii(signing_algorithm));
351          jcr->Errors++;
352          return 1;
353       }
354    }
355
356    /* Enable encryption */
357    if (jcr->pki_encrypt) {
358       ff_pkt->flags |= FO_ENCRYPT;
359    }
360
361    /* Initialise the file descriptor we use for data and other streams. */
362    binit(&ff_pkt->bfd);
363    if (ff_pkt->flags & FO_PORTABLE) {
364       set_portable_backup(&ff_pkt->bfd); /* disable Win32 BackupRead() */
365    }
366    if (ff_pkt->reader) {
367       if (!set_prog(&ff_pkt->bfd, ff_pkt->reader, jcr)) {
368          Jmsg(jcr, M_FATAL, 0, _("Python reader program \"%s\" not found.\n"), 
369             ff_pkt->reader);
370          return 0;
371       }
372    }
373
374    /* Send attributes -- must be done after binit() */
375    if (!encode_and_send_attributes(jcr, ff_pkt, data_stream)) {
376       return 0;
377    }
378
379    /*
380     * Open any file with data that we intend to save, then save it.
381     *
382     * Note, if is_win32_backup, we must open the Directory so that
383     * the BackupRead will save its permissions and ownership streams.
384     */
385    if (ff_pkt->type != FT_LNKSAVED && (S_ISREG(ff_pkt->statp.st_mode) &&
386          ff_pkt->statp.st_size > 0) ||
387          ff_pkt->type == FT_RAW || ff_pkt->type == FT_FIFO ||
388          (!is_portable_backup(&ff_pkt->bfd) && ff_pkt->type == FT_DIREND)) {
389       btimer_t *tid;
390       if (ff_pkt->type == FT_FIFO) {
391          tid = start_thread_timer(pthread_self(), 60);
392       } else {
393          tid = NULL;
394       }
395       int noatime = ff_pkt->flags & FO_NOATIME ? O_NOATIME : 0;
396       if (bopen(&ff_pkt->bfd, ff_pkt->fname, O_RDONLY | O_BINARY | noatime, 0) < 0) {
397          ff_pkt->ff_errno = errno;
398          berrno be;
399          Jmsg(jcr, M_NOTSAVED, 0, _("     Cannot open %s: ERR=%s.\n"), ff_pkt->fname,
400               be.strerror());
401          jcr->Errors++;
402          if (tid) {
403             stop_thread_timer(tid);
404             tid = NULL;
405          }
406          return 1;
407       }
408       if (tid) {
409          stop_thread_timer(tid);
410          tid = NULL;
411       }
412
413       /* Set up the encryption context, send the session data to the SD */
414       if (jcr->pki_encrypt) {
415          /* Send our header */
416          bnet_fsend(sd, "%ld %d 0", jcr->JobFiles, STREAM_ENCRYPTED_SESSION_DATA);
417
418          /* Grow the bsock buffer to fit our message if necessary */
419          if (sizeof_pool_memory(sd->msg) < jcr->pki_session_encoded_size) {
420             sd->msg = realloc_pool_memory(sd->msg, jcr->pki_session_encoded_size);
421          }
422
423          /* Copy our message over and send it */
424          memcpy(sd->msg, jcr->pki_session_encoded, jcr->pki_session_encoded_size);
425          sd->msglen = jcr->pki_session_encoded_size;
426          jcr->JobBytes += sd->msglen;
427
428          bnet_send(sd);
429          bnet_sig(sd, BNET_EOD);
430       }
431
432       stat = send_data(jcr, data_stream, ff_pkt, digest, signing_digest);
433       bclose(&ff_pkt->bfd);
434       if (!stat) {
435          return 0;
436       }
437    }
438
439 #ifdef HAVE_DARWIN_OS
440    /* Regular files can have resource forks and Finder Info */
441    if (ff_pkt->type != FT_LNKSAVED && (S_ISREG(ff_pkt->statp.st_mode) &&
442             ff_pkt->flags & FO_HFSPLUS)) {
443       if (ff_pkt->hfsinfo.rsrclength > 0) {
444          int flags;
445          if (!bopen_rsrc(&ff_pkt->bfd, ff_pkt->fname, O_RDONLY | O_BINARY, 0) < 0) {
446             ff_pkt->ff_errno = errno;
447             berrno be;
448             Jmsg(jcr, M_NOTSAVED, -1, _("     Cannot open resource fork for %s: ERR=%s.\n"), ff_pkt->fname,
449                   be.strerror());
450             jcr->Errors++;
451             if (is_bopen(&ff_pkt->bfd)) {
452                bclose(&ff_pkt->bfd);
453             }
454             return 1;
455          }
456          flags = ff_pkt->flags;
457          ff_pkt->flags &= ~(FO_GZIP|FO_SPARSE);
458          stat = send_data(jcr, STREAM_MACOS_FORK_DATA, ff_pkt, digest, signing_digest);
459          ff_pkt->flags = flags;
460          bclose(&ff_pkt->bfd);
461          if (!stat) {
462             return 0;
463          }
464       }
465
466       Dmsg1(300, "Saving Finder Info for \"%s\"\n", ff_pkt->fname);
467       bnet_fsend(sd, "%ld %d 0", jcr->JobFiles, STREAM_HFSPLUS_ATTRIBUTES);
468       Dmsg1(300, "bfiled>stored:header %s\n", sd->msg);
469       memcpy(sd->msg, ff_pkt->hfsinfo.fndrinfo, 32);
470       sd->msglen = 32;
471       if (digest) {
472          crypto_digest_update(digest, (uint8_t *)sd->msg, sd->msglen);
473       }
474       if (signing_digest) {
475          crypto_digest_update(signing_digest, (uint8_t *)sd->msg, sd->msglen);
476       }
477       bnet_send(sd);
478       bnet_sig(sd, BNET_EOD);
479    }
480 #endif
481
482    if (ff_pkt->flags & FO_ACL) {
483       /* Read access ACLs for files, dirs and links */
484       if (!read_and_send_acl(jcr, BACL_TYPE_ACCESS, STREAM_UNIX_ATTRIBUTES_ACCESS_ACL)) {
485          return 0;
486       }
487       /* Directories can have default ACLs too */
488       if (ff_pkt->type == FT_DIREND && (BACL_CAP & BACL_CAP_DEFAULTS_DIR)) {
489          if (!read_and_send_acl(jcr, BACL_TYPE_DEFAULT, STREAM_UNIX_ATTRIBUTES_DEFAULT_ACL)) {
490             return 0;
491          }
492       }
493    }
494
495    /* Terminate the signing digest and send it to the Storage daemon */
496    if (signing_digest) {
497       SIGNATURE *sig;
498       uint32_t size = 0;
499       uint8_t *buf;
500
501       if ((sig = crypto_sign_new()) == NULL) {
502          Jmsg(jcr, M_FATAL, 0, _("Failed to allocate memory for stream signature.\n"));
503          return 0;
504       }
505
506       if (crypto_sign_add_signer(sig, signing_digest, jcr->pki_keypair) == false) {
507          Jmsg(jcr, M_FATAL, 0, _("An error occured while signing the stream.\n"));
508          return 0;
509       }
510
511       /* Get signature size */
512       if (crypto_sign_encode(sig, NULL, &size) == false) {
513          Jmsg(jcr, M_FATAL, 0, _("An error occured while signing the stream.\n"));
514          return 0;
515       }
516
517       /* Allocate signature data buffer */
518       buf = (uint8_t *)malloc(size);
519       if (!buf) {
520          crypto_sign_free(sig);
521          return 0;
522       }
523
524       /* Encode signature data */
525       if (crypto_sign_encode(sig, buf, &size) == false) {
526          Jmsg(jcr, M_FATAL, 0, _("An error occured while signing the stream.\n"));
527          return 0;
528       }
529
530       /* Send our header */
531       bnet_fsend(sd, "%ld %d 0", jcr->JobFiles, STREAM_SIGNED_DIGEST);
532       Dmsg1(300, "bfiled>stored:header %s\n", sd->msg);
533
534       /* Grow the bsock buffer to fit our message if necessary */
535       if (sizeof_pool_memory(sd->msg) < (int32_t)size) {
536          sd->msg = realloc_pool_memory(sd->msg, size);
537       }
538
539       /* Copy our message over and send it */
540       memcpy(sd->msg, buf, size);
541       sd->msglen = size;
542       bnet_send(sd);
543       bnet_sig(sd, BNET_EOD);              /* end of checksum */
544
545       crypto_digest_free(signing_digest);
546       crypto_sign_free(sig);        
547       free(buf);
548    }
549
550    /* Terminate any digest and send it to Storage daemon and the Director */
551    if (digest) {
552       uint8_t md[CRYPTO_DIGEST_MAX_SIZE];
553       uint32_t size;
554
555       size = sizeof(md);
556
557       if (crypto_digest_finalize(digest, md, &size)) {
558          bnet_fsend(sd, "%ld %d 0", jcr->JobFiles, digest_stream);
559          Dmsg1(300, "bfiled>stored:header %s\n", sd->msg);
560          memcpy(sd->msg, md, size);
561          sd->msglen = size;
562          bnet_send(sd);
563          bnet_sig(sd, BNET_EOD);              /* end of checksum */
564       }
565
566       crypto_digest_free(digest);
567    }
568
569    return 1;
570 }
571
572 /*
573  * Send data read from an already open file descriptor.
574  *
575  * We return 1 on sucess and 0 on errors.
576  *
577  * ***FIXME***
578  * We use ff_pkt->statp.st_size when FO_SPARSE.
579  * Currently this is not a problem as the only other stream, resource forks,
580  * are not handled as sparse files.
581  */
582 int send_data(JCR *jcr, int stream, FF_PKT *ff_pkt, DIGEST *digest, DIGEST *signing_digest)
583 {
584    BSOCK *sd = jcr->store_bsock;
585    uint64_t fileAddr = 0;             /* file address */
586    char *rbuf, *wbuf;
587    int32_t rsize = jcr->buf_size;      /* read buffer size */
588    POOLMEM *msgsave;
589    CIPHER_CONTEXT *cipher_ctx = NULL; /* Quell bogus uninitialized warnings */
590    const uint8_t *cipher_input;
591    uint32_t cipher_input_len;
592    uint32_t cipher_block_size;
593    uint32_t encrypted_len;
594 #ifdef FD_NO_SEND_TEST
595    return 1;
596 #endif
597
598    msgsave = sd->msg;
599    rbuf = sd->msg;                    /* read buffer */
600    wbuf = sd->msg;                    /* write buffer */
601    cipher_input = (uint8_t *)rbuf;    /* encrypt uncompressed data */
602
603    Dmsg1(300, "Saving data, type=%d\n", ff_pkt->type);
604
605 #ifdef HAVE_LIBZ
606    uLong compress_len, max_compress_len = 0;
607    const Bytef *cbuf = NULL;
608    int zstat;
609
610    if (ff_pkt->flags & FO_GZIP) {
611       if (ff_pkt->flags & FO_SPARSE) {
612          cbuf = (Bytef *)jcr->compress_buf + SPARSE_FADDR_SIZE;
613          max_compress_len = jcr->compress_buf_size - SPARSE_FADDR_SIZE;
614       } else {
615          cbuf = (Bytef *)jcr->compress_buf;
616          max_compress_len = jcr->compress_buf_size; /* set max length */
617       }
618       wbuf = jcr->compress_buf;    /* compressed output here */
619       cipher_input = (uint8_t *)jcr->compress_buf; /* encrypt compressed data */
620
621       /* 
622        * Only change zlib parameters if there is no pending operation.
623        * This should never happen as deflatereset is called after each
624        * deflate.
625        */
626
627       if (((z_stream*)jcr->pZLIB_compress_workset)->total_in == 0) {
628          /* set gzip compression level - must be done per file */
629          if ((zstat=deflateParams((z_stream*)jcr->pZLIB_compress_workset, ff_pkt->GZIP_level, Z_DEFAULT_STRATEGY)) != Z_OK) {
630             Jmsg(jcr, M_FATAL, 0, _("Compression deflateParams error: %d\n"), zstat);
631             set_jcr_job_status(jcr, JS_ErrorTerminated);
632             goto err;
633          }
634       }
635    }
636 #else
637    const uint32_t max_compress_len = 0;
638 #endif
639
640    if (ff_pkt->flags & FO_ENCRYPT) {
641       /* Allocate the cipher context */
642       if ((cipher_ctx = crypto_cipher_new(jcr->pki_session, true, &cipher_block_size)) == NULL) {
643          /* Shouldn't happen! */
644          Jmsg0(jcr, M_FATAL, 0, _("Failed to initialize encryption context\n"));
645          goto err;
646       }
647
648       /*
649        * Grow the crypto buffer, if necessary.
650        * crypto_cipher_update() will buffer up to (cipher_block_size - 1).
651        * We grow crypto_buf to the maximum number of blocks that
652        * could be returned for the given read buffer size.
653        * (Using the larger of either rsize or max_compress_len)
654        */
655       jcr->crypto_buf = check_pool_memory_size(jcr->crypto_buf, (MAX(rsize + sizeof(uint32_t), (int32_t)max_compress_len) + cipher_block_size - 1) / cipher_block_size * cipher_block_size);
656
657       wbuf = jcr->crypto_buf; /* Encrypted, possibly compressed output here. */
658    }
659
660    /*
661     * Send Data header to Storage daemon
662     *    <file-index> <stream> <info>
663     */
664    if (!bnet_fsend(sd, "%ld %d 0", jcr->JobFiles, stream)) {
665       Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
666             bnet_strerror(sd));
667       goto err;
668    }
669    Dmsg1(300, ">stored: datahdr %s\n", sd->msg);
670
671    /*
672     * Make space at beginning of buffer for fileAddr because this
673     *   same buffer will be used for writing if compression is off.
674     */
675    if (ff_pkt->flags & FO_SPARSE) {
676       rbuf += SPARSE_FADDR_SIZE;
677       rsize -= SPARSE_FADDR_SIZE;
678 #ifdef HAVE_FREEBSD_OS
679       /*
680        * To read FreeBSD partitions, the read size must be
681        *  a multiple of 512.
682        */
683       rsize = (rsize/512) * 512;
684 #endif
685    }
686
687    /* a RAW device read on win32 only works if the buffer is a multiple of 512 */
688 #ifdef HAVE_WIN32
689    if (S_ISBLK(ff_pkt->statp.st_mode))
690       rsize = (rsize/512) * 512;
691 #endif
692    
693    /*
694     * Read the file data
695     */
696    while ((sd->msglen=(uint32_t)bread(&ff_pkt->bfd, rbuf, rsize)) > 0) {
697       int sparseBlock = 0;
698
699       /* Check for sparse blocks */
700       if (ff_pkt->flags & FO_SPARSE) {
701          ser_declare;
702          if (sd->msglen == rsize &&
703              fileAddr+sd->msglen < (uint64_t)ff_pkt->statp.st_size ||
704              ((ff_pkt->type == FT_RAW || ff_pkt->type == FT_FIFO) &&
705                (uint64_t)ff_pkt->statp.st_size == 0)) {
706             sparseBlock = is_buf_zero(rbuf, rsize);
707          }
708          if (!sparseBlock) {
709             ser_begin(wbuf, SPARSE_FADDR_SIZE);
710             ser_uint64(fileAddr);     /* store fileAddr in begin of buffer */
711          }
712       }
713
714       jcr->ReadBytes += sd->msglen;         /* count bytes read */
715       fileAddr += sd->msglen;
716
717       /* Uncompressed cipher input length */
718       cipher_input_len = sd->msglen;
719
720       /* Update checksum if requested */
721       if (digest) {
722          crypto_digest_update(digest, (uint8_t *)rbuf, sd->msglen);
723       }
724
725       /* Update signing digest if requested */
726       if (signing_digest) {
727          crypto_digest_update(signing_digest, (uint8_t *)rbuf, sd->msglen);
728       }
729
730 #ifdef HAVE_LIBZ
731       /* Do compression if turned on */
732       if (!sparseBlock && (ff_pkt->flags & FO_GZIP) && jcr->pZLIB_compress_workset) {
733          Dmsg4(400, "cbuf=0x%x len=%u rbuf=0x%x len=%u\n", cbuf, compress_len,
734             rbuf, sd->msglen);
735          
736          ((z_stream*)jcr->pZLIB_compress_workset)->next_in   = (Bytef *)rbuf;
737                         ((z_stream*)jcr->pZLIB_compress_workset)->avail_in  = sd->msglen;
738          ((z_stream*)jcr->pZLIB_compress_workset)->next_out  = (Bytef *)cbuf;
739                         ((z_stream*)jcr->pZLIB_compress_workset)->avail_out = max_compress_len;
740
741          if ((zstat=deflate((z_stream*)jcr->pZLIB_compress_workset, Z_FINISH)) != Z_STREAM_END) {
742             Jmsg(jcr, M_FATAL, 0, _("Compression deflate error: %d\n"), zstat);
743             set_jcr_job_status(jcr, JS_ErrorTerminated);
744             goto err;
745          }
746          compress_len = ((z_stream*)jcr->pZLIB_compress_workset)->total_out;
747          /* reset zlib stream to be able to begin from scratch again */
748          if ((zstat=deflateReset((z_stream*)jcr->pZLIB_compress_workset)) != Z_OK) {
749             Jmsg(jcr, M_FATAL, 0, _("Compression deflateReset error: %d\n"), zstat);
750             set_jcr_job_status(jcr, JS_ErrorTerminated);
751             goto err;
752          }
753
754          Dmsg2(400, "compressed len=%d uncompressed len=%d\n", compress_len, sd->msglen);
755
756          sd->msglen = compress_len;      /* set compressed length */
757          cipher_input_len = compress_len;
758       }
759 #endif
760
761       if (!sparseBlock && (ff_pkt->flags & FO_ENCRYPT)) {
762          uint32_t initial_len = 0;
763
764          if (ff_pkt->flags & FO_SPARSE) {
765             cipher_input_len += SPARSE_FADDR_SIZE;
766          }
767
768          /* Encrypt the length of the input block */
769          uint32_t packet_len = htonl(cipher_input_len);
770
771          if (!crypto_cipher_update(cipher_ctx, (const u_int8_t *)&packet_len, sizeof(packet_len), (u_int8_t *)jcr->crypto_buf, &initial_len)) {
772             /* Encryption failed. Shouldn't happen. */
773             Jmsg(jcr, M_FATAL, 0, _("Encryption error\n"));
774             goto err;
775          }
776
777          /* Encrypt the input block */
778          if (crypto_cipher_update(cipher_ctx, cipher_input, cipher_input_len, (u_int8_t *)&jcr->crypto_buf[initial_len], &encrypted_len)) {
779             if ((initial_len + encrypted_len) == 0) {
780                /* No full block of data available, read more data */
781                continue;
782             }
783             Dmsg2(400, "encrypted len=%d unencrypted len=%d\n", encrypted_len, sd->msglen);
784             sd->msglen = initial_len + encrypted_len; /* set encrypted length */
785          } else {
786             /* Encryption failed. Shouldn't happen. */
787             Jmsg(jcr, M_FATAL, 0, _("Encryption error\n"));
788             goto err;
789          }
790       }
791
792       /* Send the buffer to the Storage daemon */
793       if (!sparseBlock) {
794          if (ff_pkt->flags & FO_SPARSE) {
795             sd->msglen += SPARSE_FADDR_SIZE; /* include fileAddr in size */
796          }
797          sd->msg = wbuf;              /* set correct write buffer */
798          if (!bnet_send(sd)) {
799             Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
800                   bnet_strerror(sd));
801             goto err;
802          }
803       }
804       Dmsg1(130, "Send data to SD len=%d\n", sd->msglen);
805       /*          #endif */
806       jcr->JobBytes += sd->msglen;      /* count bytes saved possibly compressed/encrypted */
807       sd->msg = msgsave;                /* restore read buffer */
808
809    } /* end while read file data */
810
811    /* Send any remaining encrypted data + padding */
812    if (sd->msglen >= 0) {
813       if (ff_pkt->flags & FO_ENCRYPT) {
814          if (!crypto_cipher_finalize(cipher_ctx, (uint8_t *)jcr->crypto_buf, &encrypted_len)) {
815             /* Padding failed. Shouldn't happen. */
816             Jmsg(jcr, M_FATAL, 0, _("Encryption padding error\n"));
817             goto err;
818          }
819
820          if (encrypted_len > 0) {
821             sd->msglen = encrypted_len;      /* set encrypted length */
822
823             sd->msg = jcr->crypto_buf;       /* set correct write buffer */
824             if (!bnet_send(sd)) {
825                Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
826                      bnet_strerror(sd));
827                goto err;
828             }
829             Dmsg1(130, "Send data to SD len=%d\n", sd->msglen);
830             jcr->JobBytes += sd->msglen;     /* count bytes saved possibly compressed/encrypted */
831             sd->msg = msgsave;               /* restore bnet buffer */
832          }
833       }
834    } else {
835       berrno be;
836       Jmsg(jcr, M_ERROR, 0, _("Read error on file %s. ERR=%s\n"),
837          ff_pkt->fname, be.strerror(ff_pkt->bfd.berrno));
838       if (jcr->Errors++ > 1000) {       /* insanity check */
839          Jmsg(jcr, M_FATAL, 0, _("Too many errors.\n"));
840       }
841    }
842
843    if (!bnet_sig(sd, BNET_EOD)) {        /* indicate end of file data */
844       Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
845             bnet_strerror(sd));
846       goto err;
847    }
848
849    /* Free the cipher context */
850    if (cipher_ctx) {
851       crypto_cipher_free(cipher_ctx);
852    }
853    return 1;
854
855 err:
856    /* Free the cipher context */
857    if (cipher_ctx) {
858       crypto_cipher_free(cipher_ctx);
859    }
860
861    sd->msg = msgsave; /* restore bnet buffer */
862    sd->msglen = 0;
863    return 0;
864 }
865
866 /*
867  * Read and send an ACL for the last encountered file.
868  */
869 static bool read_and_send_acl(JCR *jcr, int acltype, int stream)
870 {
871 #ifdef HAVE_ACL
872    BSOCK *sd = jcr->store_bsock;
873    POOLMEM *msgsave;
874    int len;
875 #ifdef FD_NO_SEND_TEST
876    return true;
877 #endif
878
879    len = bacl_get(jcr, acltype);
880    if (len < 0) {
881       Jmsg1(jcr, M_WARNING, 0, _("Error reading ACL of %s\n"), jcr->last_fname);
882       return true; 
883    }
884    if (len == 0) {
885       return true;                    /* no ACL */
886    }
887
888    /* Send header */
889    if (!bnet_fsend(sd, "%ld %d 0", jcr->JobFiles, stream)) {
890       Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
891             bnet_strerror(sd));
892       return false;
893    }
894
895    /* Send the buffer to the storage deamon */
896    Dmsg2(400, "Backing up ACL type 0x%2x <%s>\n", acltype, jcr->acl_text);
897    msgsave = sd->msg;
898    sd->msg = jcr->acl_text;
899    sd->msglen = len + 1;
900    if (!bnet_send(sd)) {
901       sd->msg = msgsave;
902       sd->msglen = 0;
903       Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
904             bnet_strerror(sd));
905       return false;
906    }
907
908    jcr->JobBytes += sd->msglen;
909    sd->msg = msgsave;
910    if (!bnet_sig(sd, BNET_EOD)) {
911       Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
912             bnet_strerror(sd));
913       return false;
914    }
915
916    Dmsg1(200, "ACL of file: %s successfully backed up!\n", jcr->last_fname);
917 #endif
918    return true;
919 }
920
921 static bool encode_and_send_attributes(JCR *jcr, FF_PKT *ff_pkt, int &data_stream) 
922 {
923    BSOCK *sd = jcr->store_bsock;
924    char attribs[MAXSTRING];
925    char attribsEx[MAXSTRING];
926    int attr_stream;
927    int stat;
928 #ifdef FD_NO_SEND_TEST
929    return true;
930 #endif
931
932    /* Find what data stream we will use, then encode the attributes */
933    if ((data_stream = select_data_stream(ff_pkt)) == STREAM_NONE) {
934       /* This should not happen */
935       Jmsg0(jcr, M_FATAL, 0, _("Invalid file flags, no supported data stream type.\n"));
936       return false;
937    }
938    encode_stat(attribs, ff_pkt, data_stream);
939
940    /* Now possibly extend the attributes */
941    attr_stream = encode_attribsEx(jcr, attribsEx, ff_pkt);
942
943    Dmsg3(300, "File %s\nattribs=%s\nattribsEx=%s\n", ff_pkt->fname, attribs, attribsEx);
944
945    jcr->lock();
946    jcr->JobFiles++;                    /* increment number of files sent */
947    ff_pkt->FileIndex = jcr->JobFiles;  /* return FileIndex */
948    pm_strcpy(jcr->last_fname, ff_pkt->fname);
949    jcr->unlock();
950
951    /*
952     * Send Attributes header to Storage daemon
953     *    <file-index> <stream> <info>
954     */
955    if (!bnet_fsend(sd, "%ld %d 0", jcr->JobFiles, attr_stream)) {
956       Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
957             bnet_strerror(sd));
958       return false;
959    }
960    Dmsg1(300, ">stored: attrhdr %s\n", sd->msg);
961
962    /*
963     * Send file attributes to Storage daemon
964     *   File_index
965     *   File type
966     *   Filename (full path)
967     *   Encoded attributes
968     *   Link name (if type==FT_LNK or FT_LNKSAVED)
969     *   Encoded extended-attributes (for Win32)
970     *
971     * For a directory, link is the same as fname, but with trailing
972     * slash. For a linked file, link is the link.
973     */
974    if (ff_pkt->type == FT_LNK || ff_pkt->type == FT_LNKSAVED) {
975       Dmsg2(300, "Link %s to %s\n", ff_pkt->fname, ff_pkt->link);
976       stat = bnet_fsend(sd, "%ld %d %s%c%s%c%s%c%s%c", jcr->JobFiles,
977                ff_pkt->type, ff_pkt->fname, 0, attribs, 0, ff_pkt->link, 0,
978                attribsEx, 0);
979    } else if (ff_pkt->type == FT_DIREND) {
980       /* Here link is the canonical filename (i.e. with trailing slash) */
981       stat = bnet_fsend(sd, "%ld %d %s%c%s%c%c%s%c", jcr->JobFiles,
982                ff_pkt->type, ff_pkt->link, 0, attribs, 0, 0, attribsEx, 0);
983    } else {
984       stat = bnet_fsend(sd, "%ld %d %s%c%s%c%c%s%c", jcr->JobFiles,
985                ff_pkt->type, ff_pkt->fname, 0, attribs, 0, 0, attribsEx, 0);
986    }
987
988    Dmsg2(300, ">stored: attr len=%d: %s\n", sd->msglen, sd->msg);
989    if (!stat) {
990       Jmsg1(jcr, M_FATAL, 0, _("Network send error to SD. ERR=%s\n"),
991             bnet_strerror(sd));
992       return false;
993    }
994    bnet_sig(sd, BNET_EOD);            /* indicate end of attributes data */
995    return true;
996 }