]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/filed/restore.c
kes Start implementing bstrerror() in place of strerror().
[bacula/bacula] / bacula / src / filed / restore.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2007 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 two of the GNU General Public
10    License as published by the Free Software Foundation plus additions
11    that are listed 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 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 John Walker.
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  restore.c Restorefiles.
30  *
31  *    Kern Sibbald, November MM
32  *
33  *   Version $Id$
34  *
35  */
36
37 #include "bacula.h"
38 #include "filed.h"
39
40 #ifdef HAVE_DARWIN_OS
41 #include <sys/attr.h>
42 #endif
43
44 #if defined(HAVE_CRYPTO)
45 const bool have_crypto = true;
46 #else
47 const bool have_crypto = false;
48 #endif
49
50 /* Data received from Storage Daemon */
51 static char rec_header[] = "rechdr %ld %ld %ld %ld %ld";
52
53 /* Forward referenced functions */
54 #if   defined(HAVE_LIBZ)
55 static const char *zlib_strerror(int stat);
56 const bool have_libz = true;
57 #else
58 const bool have_libz = false;
59 #endif
60
61 typedef struct restore_cipher_ctx {
62    CIPHER_CONTEXT *cipher;
63    uint32_t block_size;
64
65    POOLMEM *buf;       /* Pointer to descryption buffer */
66    int32_t buf_len;    /* Count of bytes currently in buf */ 
67    int32_t packet_len; /* Total bytes in packet */
68 } RESTORE_CIPHER_CTX;
69
70 static bool verify_signature(JCR *jcr, SIGNATURE *sig);
71 int32_t extract_data(JCR *jcr, BFILE *bfd, POOLMEM *buf, int32_t buflen,
72       uint64_t *addr, int flags, RESTORE_CIPHER_CTX *cipher_ctx);
73 bool flush_cipher(JCR *jcr, BFILE *bfd, uint64_t *addr, int flags, RESTORE_CIPHER_CTX *cipher_ctx);
74
75 #define RETRY 10                      /* retry wait time */
76
77 /*
78  * Close a bfd check that we are at the expected file offset.
79  * Makes some code in set_attributes().
80  */
81 int bclose_chksize(JCR *jcr, BFILE *bfd, boffset_t osize)
82 {
83    char ec1[50], ec2[50];
84    boffset_t fsize;
85
86    fsize = blseek(bfd, 0, SEEK_CUR);
87    bclose(bfd);                              /* first close file */
88    if (fsize > 0 && fsize != osize) {
89       Qmsg3(jcr, M_ERROR, 0, _("Size of data or stream of %s not correct. Original %s, restored %s.\n"),
90             jcr->last_fname, edit_uint64(osize, ec1),
91             edit_uint64(fsize, ec2));
92       return -1;
93    }
94    return 0;
95 }
96
97 /*
98  * Restore the requested files.
99  *
100  */
101 void do_restore(JCR *jcr)
102 {
103    BSOCK *sd;
104    int32_t stream = 0;
105    int32_t prev_stream;
106    uint32_t VolSessionId, VolSessionTime;
107    bool extract = false;
108    int32_t file_index;
109    char ec1[50];                       /* Buffer printing huge values */
110    BFILE bfd;                          /* File content */
111    uint64_t fileAddr = 0;              /* file write address */
112    uint32_t size;                      /* Size of file */
113    BFILE altbfd;                       /* Alternative data stream */
114    uint64_t alt_addr = 0;              /* Write address for alternative stream */
115    intmax_t alt_size = 0;              /* Size of alternate stream */
116    SIGNATURE *sig = NULL;              /* Cryptographic signature (if any) for file */
117    CRYPTO_SESSION *cs = NULL;          /* Cryptographic session data (if any) for file */
118    RESTORE_CIPHER_CTX cipher_ctx;     /* Cryptographic restore context (if any) for file */
119    RESTORE_CIPHER_CTX alt_cipher_ctx; /* Cryptographic restore context (if any) for alternative stream */
120    int flags = 0;                      /* Options for extract_data() */
121    int alt_flags = 0;                  /* Options for extract_data() */
122    int stat;
123    ATTR *attr;
124
125    /* The following variables keep track of "known unknowns" */
126    int non_support_data = 0;
127    int non_support_attr = 0;
128    int non_support_rsrc = 0;
129    int non_support_finfo = 0;
130    int non_support_acl = 0;
131    int non_support_progname = 0;
132
133    /* Finally, set up for special configurations */
134 #ifdef HAVE_DARWIN_OS
135    intmax_t rsrc_len = 0;             /* Original length of resource fork */
136    struct attrlist attrList;
137
138    memset(&attrList, 0, sizeof(attrList));
139    attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
140    attrList.commonattr = ATTR_CMN_FNDRINFO;
141 #endif
142
143    sd = jcr->store_bsock;
144    set_jcr_job_status(jcr, JS_Running);
145
146    LockRes();
147    CLIENT *client = (CLIENT *)GetNextRes(R_CLIENT, NULL);
148    UnlockRes();
149    uint32_t buf_size;
150    if (client) {
151       buf_size = client->max_network_buffer_size;
152    } else {
153       buf_size = 0;                   /* use default */
154    }
155    if (!bnet_set_buffer_size(sd, buf_size, BNET_SETBUF_WRITE)) {
156       set_jcr_job_status(jcr, JS_ErrorTerminated);
157       return;
158    }
159    jcr->buf_size = sd->msglen;
160
161 #ifdef stbernard_implemented
162 /  #if defined(HAVE_WIN32)
163    bool        bResumeOfmOnExit = FALSE;
164    if (isOpenFileManagerRunning()) {
165        if ( pauseOpenFileManager() ) {
166           Jmsg(jcr, M_INFO, 0, _("Open File Manager paused\n") );
167           bResumeOfmOnExit = TRUE;
168        }
169        else {
170           Jmsg(jcr, M_ERROR, 0, _("FAILED to pause Open File Manager\n") );
171        }
172    }
173    {
174        char username[UNLEN+1];
175        DWORD usize = sizeof(username);
176        int privs = enable_backup_privileges(NULL, 1);
177        if (GetUserName(username, &usize)) {
178           Jmsg2(jcr, M_INFO, 0, _("Running as '%s'. Privmask=%#08x\n"), username,
179        } else {
180           Jmsg(jcr, M_WARNING, 0, _("Failed to retrieve current UserName\n"));
181        }
182    }
183 #endif
184
185    if (have_libz) {
186       uint32_t compress_buf_size = jcr->buf_size + 12 + ((jcr->buf_size+999) / 1000) + 100;
187       jcr->compress_buf = (char *)bmalloc(compress_buf_size);
188       jcr->compress_buf_size = compress_buf_size;
189    }
190
191    cipher_ctx.cipher = NULL;
192    alt_cipher_ctx.cipher = NULL;
193    if (have_crypto) {
194       cipher_ctx.buf = get_memory(CRYPTO_CIPHER_MAX_BLOCK_SIZE);
195       cipher_ctx.buf_len = 0;
196       cipher_ctx.packet_len = 0;
197
198       alt_cipher_ctx.buf = get_memory(CRYPTO_CIPHER_MAX_BLOCK_SIZE);
199       alt_cipher_ctx.buf_len = 0;
200       alt_cipher_ctx.packet_len = 0;
201    } else {
202       cipher_ctx.buf = NULL;
203       alt_cipher_ctx.buf = NULL;
204    }
205    
206    /*
207     * Get a record from the Storage daemon. We are guaranteed to
208     *   receive records in the following order:
209     *   1. Stream record header
210     *   2. Stream data
211     *        a. Attributes (Unix or Win32)
212     *        b. Possibly stream encryption session data (e.g., symmetric session key)
213     *    or  c. File data for the file
214     *    or  d. Alternate data stream (e.g. Resource Fork)
215     *    or  e. Finder info
216     *    or  f. ACLs
217     *    or  g. Possibly a cryptographic signature
218     *    or  h. Possibly MD5 or SHA1 record
219     *   3. Repeat step 1
220     *
221     * NOTE: We keep track of two bacula file descriptors:
222     *   1. bfd for file data.
223     *      This fd is opened for non empty files when an attribute stream is
224     *      encountered and closed when we find the next attribute stream.
225     *   2. alt_bfd for alternate data streams
226     *      This fd is opened every time we encounter a new alternate data
227     *      stream for the current file. When we find any other stream, we
228     *      close it again.
229     *      The expected size of the stream, alt_len, should be set when
230     *      opening the fd.
231     */
232    binit(&bfd);
233    binit(&altbfd);
234    attr = new_attr();
235    jcr->acl_text = get_pool_memory(PM_MESSAGE);
236
237    while (bget_msg(sd) >= 0 && !job_canceled(jcr)) {
238       /* Remember previous stream type */
239       prev_stream = stream;
240
241       /* First we expect a Stream Record Header */
242       if (sscanf(sd->msg, rec_header, &VolSessionId, &VolSessionTime, &file_index,
243           &stream, &size) != 5) {
244          Jmsg1(jcr, M_FATAL, 0, _("Record header scan error: %s\n"), sd->msg);
245          goto bail_out;
246       }
247       Dmsg4(30, "Got hdr: Files=%d FilInx=%d Stream=%d, %s.\n", 
248             jcr->JobFiles, file_index, stream, stream_to_ascii(stream));
249
250       /* * Now we expect the Stream Data */
251       if (bget_msg(sd) < 0) {
252          Jmsg1(jcr, M_FATAL, 0, _("Data record error. ERR=%s\n"), bnet_strerror(sd));
253          goto bail_out;
254       }
255       if (size != (uint32_t)sd->msglen) {
256          Jmsg2(jcr, M_FATAL, 0, _("Actual data size %d not same as header %d\n"), sd->msglen, size);
257          goto bail_out;
258       }
259       Dmsg3(30, "Got stream: %s len=%d extract=%d\n", stream_to_ascii(stream), 
260             sd->msglen, extract);
261
262       /* If we change streams, close and reset alternate data streams */
263       if (prev_stream != stream) {
264          if (is_bopen(&altbfd)) {
265             if (alt_cipher_ctx.cipher) {
266                flush_cipher(jcr, &altbfd, &alt_addr, alt_flags, &alt_cipher_ctx);
267                crypto_cipher_free(alt_cipher_ctx.cipher);
268                alt_cipher_ctx.cipher = NULL;
269             }
270             bclose_chksize(jcr, &altbfd, alt_size);
271          }
272          alt_size = -1; /* Use an impossible value and set a proper one below */
273          alt_addr = 0;
274       }
275
276       /* File Attributes stream */
277       switch (stream) {
278       case STREAM_UNIX_ATTRIBUTES:
279       case STREAM_UNIX_ATTRIBUTES_EX:
280          /*
281           * If extracting, it was from previous stream, so
282           * close the output file and validate the signature.
283           */
284          if (extract) {
285             if (size > 0 && !is_bopen(&bfd)) {
286                Jmsg0(jcr, M_ERROR, 0, _("Logic error: output file should be open\n"));
287             }
288             /* Flush and deallocate previous stream's cipher context */
289             if (cipher_ctx.cipher && prev_stream != STREAM_ENCRYPTED_SESSION_DATA) {
290                flush_cipher(jcr, &bfd, &fileAddr, flags, &cipher_ctx);
291                crypto_cipher_free(cipher_ctx.cipher);
292                cipher_ctx.cipher = NULL;
293             }
294
295             /* Flush and deallocate previous stream's alt cipher context */
296             if (alt_cipher_ctx.cipher && prev_stream != STREAM_ENCRYPTED_SESSION_DATA) {
297                flush_cipher(jcr, &altbfd, &alt_addr, alt_flags, &alt_cipher_ctx);
298                crypto_cipher_free(alt_cipher_ctx.cipher);
299                alt_cipher_ctx.cipher = NULL;
300             }
301             set_attributes(jcr, attr, &bfd);
302             extract = false;
303
304             /* Verify the cryptographic signature, if any */
305             verify_signature(jcr, sig);
306
307             /* Free Signature */
308             if (sig) {
309                crypto_sign_free(sig);
310                sig = NULL;
311             }
312             if (cs) {
313                crypto_session_free(cs);
314                cs = NULL;
315             }
316             jcr->ff->flags = 0;
317             Dmsg0(30, "Stop extracting.\n");
318          } else if (is_bopen(&bfd)) {
319             Jmsg0(jcr, M_ERROR, 0, _("Logic error: output file should not be open\n"));
320             bclose(&bfd);
321          }
322
323          /*
324           * Unpack and do sanity check fo attributes.
325           */
326          if (!unpack_attributes_record(jcr, stream, sd->msg, attr)) {
327             goto bail_out;
328          }
329          if (file_index != attr->file_index) {
330             Jmsg(jcr, M_FATAL, 0, _("Record header file index %ld not equal record index %ld\n"),
331                  file_index, attr->file_index);
332             Dmsg0(100, "File index error\n");
333             goto bail_out;
334          }
335
336          Dmsg3(200, "File %s\nattrib=%s\nattribsEx=%s\n", attr->fname,
337                attr->attr, attr->attrEx);
338
339          attr->data_stream = decode_stat(attr->attr, &attr->statp, &attr->LinkFI);
340
341          if (!is_restore_stream_supported(attr->data_stream)) {
342             if (!non_support_data++) {
343                Jmsg(jcr, M_ERROR, 0, _("%s stream not supported on this Client.\n"),
344                   stream_to_ascii(attr->data_stream));
345             }
346             continue;
347          }
348
349          build_attr_output_fnames(jcr, attr);
350
351          /*
352           * Now determine if we are extracting or not.
353           */
354          jcr->num_files_examined++;
355          extract = false;
356          stat = create_file(jcr, attr, &bfd, jcr->replace);
357          Dmsg2(30, "Outfile=%s create_file stat=%d\n", attr->ofname, stat);
358          switch (stat) {
359          case CF_ERROR:
360          case CF_SKIP:
361             break;
362          case CF_EXTRACT:        /* File created and we expect file data */
363             extract = true;
364             /* FALLTHROUGH */
365          case CF_CREATED:        /* File created, but there is no content */
366             jcr->lock();  
367             pm_strcpy(jcr->last_fname, attr->ofname);
368             jcr->last_type = attr->type;
369             jcr->JobFiles++;
370             jcr->unlock();
371             fileAddr = 0;
372             print_ls_output(jcr, attr);
373
374 #ifdef HAVE_DARWIN_OS
375             /* Only restore the resource fork for regular files */
376             from_base64(&rsrc_len, attr->attrEx);
377             if (attr->type == FT_REG && rsrc_len > 0) {
378                extract = true;
379             }
380 #endif
381             if (!extract) {
382                /* set attributes now because file will not be extracted */
383                set_attributes(jcr, attr, &bfd);
384             }
385             break;
386          }
387          break;
388
389       /* Data stream */
390       case STREAM_ENCRYPTED_SESSION_DATA:
391          crypto_error_t cryptoerr;
392
393          /* Is this an unexpected session data entry? */
394          if (cs) {
395             Jmsg0(jcr, M_ERROR, 0, _("Unexpected cryptographic session data stream.\n"));
396             extract = false;
397             bclose(&bfd);
398             continue;
399          }
400
401          /* Do we have any keys at all? */
402          if (!jcr->pki_recipients) {
403             Jmsg(jcr, M_ERROR, 0, _("No private decryption keys have been defined to decrypt encrypted backup data.\n"));
404             extract = false;
405             bclose(&bfd);
406             break;
407          }
408
409          /* Decode and save session keys. */
410          cryptoerr = crypto_session_decode((uint8_t *)sd->msg, (uint32_t)sd->msglen, jcr->pki_recipients, &cs);
411          switch(cryptoerr) {
412          case CRYPTO_ERROR_NONE:
413             /* Success */
414             break;
415          case CRYPTO_ERROR_NORECIPIENT:
416             Jmsg(jcr, M_ERROR, 0, _("Missing private key required to decrypt encrypted backup data.\n"));
417             break;
418          case CRYPTO_ERROR_DECRYPTION:
419             Jmsg(jcr, M_ERROR, 0, _("Decrypt of the session key failed.\n"));
420             break;
421          default:
422             /* Shouldn't happen */
423             Jmsg1(jcr, M_ERROR, 0, _("An error occurred while decoding encrypted session data stream: %s\n"), crypto_strerror(cryptoerr));
424             break;
425          }
426
427          if (cryptoerr != CRYPTO_ERROR_NONE) {
428             extract = false;
429             bclose(&bfd);
430             continue;
431          }
432
433          break;
434
435       case STREAM_FILE_DATA:
436       case STREAM_SPARSE_DATA:
437       case STREAM_WIN32_DATA:
438       case STREAM_GZIP_DATA:
439       case STREAM_SPARSE_GZIP_DATA:
440       case STREAM_WIN32_GZIP_DATA:
441       case STREAM_ENCRYPTED_FILE_DATA:
442       case STREAM_ENCRYPTED_WIN32_DATA:
443       case STREAM_ENCRYPTED_FILE_GZIP_DATA:
444       case STREAM_ENCRYPTED_WIN32_GZIP_DATA:
445          /* Force an expected, consistent stream type here */
446          if (extract && (prev_stream == stream || prev_stream == STREAM_UNIX_ATTRIBUTES
447                   || prev_stream == STREAM_UNIX_ATTRIBUTES_EX
448                   || prev_stream == STREAM_ENCRYPTED_SESSION_DATA)) {
449             flags = 0;
450
451             if (stream == STREAM_SPARSE_DATA || stream == STREAM_SPARSE_GZIP_DATA) {
452                flags |= FO_SPARSE;
453             }
454
455             if (stream == STREAM_GZIP_DATA || stream == STREAM_SPARSE_GZIP_DATA
456                   || stream == STREAM_WIN32_GZIP_DATA || stream == STREAM_ENCRYPTED_FILE_GZIP_DATA
457                   || stream == STREAM_ENCRYPTED_WIN32_GZIP_DATA) {
458                flags |= FO_GZIP;
459             }
460
461             if (stream == STREAM_ENCRYPTED_FILE_DATA
462                   || stream == STREAM_ENCRYPTED_FILE_GZIP_DATA
463                   || stream == STREAM_ENCRYPTED_WIN32_DATA
464                   || stream == STREAM_ENCRYPTED_WIN32_GZIP_DATA) {               
465                /* Set up a decryption context */
466                if (!cipher_ctx.cipher) {
467                   if (!cs) {
468                      Jmsg1(jcr, M_ERROR, 0, _("Missing encryption session data stream for %s\n"), jcr->last_fname);
469                      extract = false;
470                      bclose(&bfd);
471                      continue;
472                   }
473
474                   if ((cipher_ctx.cipher = crypto_cipher_new(cs, false, &cipher_ctx.block_size)) == NULL) {
475                      Jmsg1(jcr, M_ERROR, 0, _("Failed to initialize decryption context for %s\n"), jcr->last_fname);
476                      crypto_session_free(cs);
477                      cs = NULL;
478                      extract = false;
479                      bclose(&bfd);
480                      continue;
481                   }
482                }
483                flags |= FO_ENCRYPT;
484             }
485
486             if (is_win32_stream(stream) && !have_win32_api()) {
487                set_portable_backup(&bfd);
488                flags |= FO_WIN32DECOMP;    /* "decompose" BackupWrite data */
489             }
490
491             if (extract_data(jcr, &bfd, sd->msg, sd->msglen, &fileAddr, flags,
492                              &cipher_ctx) < 0) {
493                extract = false;
494                bclose(&bfd);
495                continue;
496             }
497          }
498          break;
499
500       /* Resource fork stream - only recorded after a file to be restored */
501       /* Silently ignore if we cannot write - we already reported that */
502       case STREAM_ENCRYPTED_MACOS_FORK_DATA:
503       case STREAM_MACOS_FORK_DATA:
504 #ifdef HAVE_DARWIN_OS
505          alt_flags = 0;
506          jcr->ff->flags |= FO_HFSPLUS;
507
508          if (stream == STREAM_ENCRYPTED_MACOS_FORK_DATA) {
509             alt_flags |= FO_ENCRYPT;
510
511             /* Set up a decryption context */
512             if (extract && !alt_cipher_ctx.cipher) {
513                if (!cs) {
514                   Jmsg1(jcr, M_ERROR, 0, _("Missing encryption session data stream for %s\n"), jcr->last_fname);
515                   extract = false;
516                   bclose(&bfd);
517                   continue;
518                }
519
520                if ((alt_cipher_ctx.cipher = crypto_cipher_new(cs, false, &alt_cipher_ctx.block_size)) == NULL) {
521                   Jmsg1(jcr, M_ERROR, 0, _("Failed to initialize decryption context for %s\n"), jcr->last_fname);
522                   crypto_session_free(cs);
523                   cs = NULL;
524                   extract = false;
525                   bclose(&bfd);
526                   continue;
527                }
528             }
529          }
530
531          if (extract) {
532             if (prev_stream != stream) {
533                if (bopen_rsrc(&altbfd, jcr->last_fname, O_WRONLY | O_TRUNC | O_BINARY, 0) < 0) {
534                   Jmsg(jcr, M_ERROR, 0, _("     Cannot open resource fork for %s.\n"), jcr->last_fname);
535                   extract = false;
536                   continue;
537                }
538
539                alt_size = rsrc_len;
540                Dmsg0(30, "Restoring resource fork\n");
541             }
542
543             if (extract_data(jcr, &altbfd, sd->msg, sd->msglen, &alt_addr, alt_flags, 
544                              &alt_cipher_ctx) < 0) {
545                extract = false;
546                bclose(&altbfd);
547                continue;
548             }
549          }
550 #else
551          non_support_rsrc++;
552 #endif
553          break;
554
555       case STREAM_HFSPLUS_ATTRIBUTES:
556 #ifdef HAVE_DARWIN_OS
557          Dmsg0(30, "Restoring Finder Info\n");
558          jcr->ff->flags |= FO_HFSPLUS;
559          if (sd->msglen != 32) {
560             Jmsg(jcr, M_ERROR, 0, _("     Invalid length of Finder Info (got %d, not 32)\n"), sd->msglen);
561             continue;
562          }
563          if (setattrlist(jcr->last_fname, &attrList, sd->msg, sd->msglen, 0) != 0) {
564             Jmsg(jcr, M_ERROR, 0, _("     Could not set Finder Info on %s\n"), jcr->last_fname);
565             continue;
566          }
567 #else
568          non_support_finfo++;
569 #endif
570          break;
571
572       case STREAM_UNIX_ATTRIBUTES_ACCESS_ACL:
573 #ifdef HAVE_ACL
574          pm_strcpy(jcr->acl_text, sd->msg);
575          Dmsg2(400, "Restoring ACL type 0x%2x <%s>\n", BACL_TYPE_ACCESS, jcr->acl_text);
576          if (bacl_set(jcr, BACL_TYPE_ACCESS) != 0) {
577                Qmsg1(jcr, M_WARNING, 0, _("Can't restore ACL of %s\n"), jcr->last_fname);
578          }
579 #else 
580          non_support_acl++;
581 #endif
582          break;
583
584       case STREAM_UNIX_ATTRIBUTES_DEFAULT_ACL:
585 #ifdef HAVE_ACL
586          pm_strcpy(jcr->acl_text, sd->msg);
587          Dmsg2(400, "Restoring ACL type 0x%2x <%s>\n", BACL_TYPE_DEFAULT, jcr->acl_text);
588          if (bacl_set(jcr, BACL_TYPE_DEFAULT) != 0) {
589                Qmsg1(jcr, M_WARNING, 0, _("Can't restore default ACL of %s\n"), jcr->last_fname);
590          }
591 #else 
592          non_support_acl++;
593 #endif
594          break;
595
596       case STREAM_SIGNED_DIGEST:
597
598          /* Is this an unexpected signature? */
599          if (sig) {
600             Jmsg0(jcr, M_ERROR, 0, _("Unexpected cryptographic signature data stream.\n"));
601             crypto_sign_free(sig);
602             sig = NULL;
603             continue;
604          }
605
606          /* Save signature. */
607          if (extract && (sig = crypto_sign_decode(jcr, (uint8_t *)sd->msg, (uint32_t)sd->msglen)) == NULL) {
608             Jmsg1(jcr, M_ERROR, 0, _("Failed to decode message signature for %s\n"), jcr->last_fname);
609          }
610          break;
611
612       case STREAM_MD5_DIGEST:
613       case STREAM_SHA1_DIGEST:
614       case STREAM_SHA256_DIGEST:
615       case STREAM_SHA512_DIGEST:
616          break;
617
618       case STREAM_PROGRAM_NAMES:
619       case STREAM_PROGRAM_DATA:
620          if (!non_support_progname) {
621             Pmsg0(000, "Got Program Name or Data Stream. Ignored.\n");
622             non_support_progname++;
623          }
624          break;
625
626       default:
627          /* If extracting, wierd stream (not 1 or 2), close output file anyway */
628          if (extract) {
629             Dmsg1(30, "Found wierd stream %d\n", stream);
630             if (size > 0 && !is_bopen(&bfd)) {
631                Jmsg0(jcr, M_ERROR, 0, _("Logic error: output file should be open\n"));
632             }
633             /* Flush and deallocate cipher context */
634             if (cipher_ctx.cipher) {
635                flush_cipher(jcr, &bfd, &fileAddr, flags, &cipher_ctx);
636                crypto_cipher_free(cipher_ctx.cipher);
637                cipher_ctx.cipher = NULL;
638             }
639
640             /* Flush and deallocate alt cipher context */
641             if (alt_cipher_ctx.cipher) {
642                flush_cipher(jcr, &altbfd, &alt_addr, alt_flags, &alt_cipher_ctx);
643                crypto_cipher_free(alt_cipher_ctx.cipher);
644                alt_cipher_ctx.cipher = NULL;
645             }
646
647             set_attributes(jcr, attr, &bfd);
648
649             /* Verify the cryptographic signature if any */
650             verify_signature(jcr, sig);
651             extract = false;
652          } else if (is_bopen(&bfd)) {
653             Jmsg0(jcr, M_ERROR, 0, _("Logic error: output file should not be open\n"));
654             bclose(&bfd);
655          }
656          Jmsg(jcr, M_ERROR, 0, _("Unknown stream=%d ignored. This shouldn't happen!\n"), stream);
657          Dmsg2(0, "None of above!!! stream=%d data=%s\n", stream,sd->msg);
658          break;
659       } /* end switch(stream) */
660
661    } /* end while get_msg() */
662
663    /* If output file is still open, it was the last one in the
664     * archive since we just hit an end of file, so close the file.
665     */
666    if (is_bopen(&altbfd)) {
667       bclose_chksize(jcr, &altbfd, alt_size);
668    }
669    if (extract) {
670       /* Flush and deallocate cipher context */
671       if (cipher_ctx.cipher) {
672          flush_cipher(jcr, &bfd, &fileAddr, flags, &cipher_ctx);
673          crypto_cipher_free(cipher_ctx.cipher);
674          cipher_ctx.cipher = NULL;
675       }
676
677       /* Flush and deallocate alt cipher context */
678       if (alt_cipher_ctx.cipher) {
679          flush_cipher(jcr, &altbfd, &alt_addr, alt_flags, &alt_cipher_ctx);
680          crypto_cipher_free(alt_cipher_ctx.cipher);
681          alt_cipher_ctx.cipher = NULL;
682       }
683
684       set_attributes(jcr, attr, &bfd);
685
686       /* Verify the cryptographic signature on the last file, if any */
687       verify_signature(jcr, sig);
688    }
689
690    if (is_bopen(&bfd)) {
691       bclose(&bfd);
692    }
693
694    set_jcr_job_status(jcr, JS_Terminated);
695    goto ok_out;
696
697 bail_out:
698    set_jcr_job_status(jcr, JS_ErrorTerminated);
699
700 ok_out:
701    /* Free Signature & Crypto Data */
702    if (sig) {
703       crypto_sign_free(sig);
704       sig = NULL;
705    }
706    if (cs) {
707       crypto_session_free(cs);
708       cs = NULL;
709    }
710
711    /* Free file cipher restore context */
712    if (cipher_ctx.cipher) {
713       crypto_cipher_free(cipher_ctx.cipher);
714       cipher_ctx.cipher = NULL;
715    }
716    if (cipher_ctx.buf) {
717       free_pool_memory(cipher_ctx.buf);
718       cipher_ctx.buf = NULL;
719    }
720
721    /* Free alternate stream cipher restore context */
722    if (alt_cipher_ctx.cipher) {
723       crypto_cipher_free(alt_cipher_ctx.cipher);
724       alt_cipher_ctx.cipher = NULL;
725    }
726    if (alt_cipher_ctx.buf) {
727       free_pool_memory(alt_cipher_ctx.buf);
728       alt_cipher_ctx.buf = NULL;
729    }
730
731    if (jcr->compress_buf) {
732       free(jcr->compress_buf);
733       jcr->compress_buf = NULL;
734       jcr->compress_buf_size = 0;
735    }
736    bclose(&altbfd);
737    bclose(&bfd);
738    free_attr(attr);
739    free_pool_memory(jcr->acl_text);
740    Dmsg2(10, "End Do Restore. Files=%d Bytes=%s\n", jcr->JobFiles,
741       edit_uint64(jcr->JobBytes, ec1));
742    if (non_support_data > 1 || non_support_attr > 1) {
743       Jmsg(jcr, M_ERROR, 0, _("%d non-supported data streams and %d non-supported attrib streams ignored.\n"),
744          non_support_data, non_support_attr);
745    }
746    if (non_support_rsrc) {
747       Jmsg(jcr, M_INFO, 0, _("%d non-supported resource fork streams ignored.\n"), non_support_rsrc);
748    }
749    if (non_support_finfo) {
750       Jmsg(jcr, M_INFO, 0, _("%d non-supported Finder Info streams ignored.\n"), non_support_rsrc);
751    }
752    if (non_support_acl) {
753       Jmsg(jcr, M_INFO, 0, _("%d non-supported acl streams ignored.\n"), non_support_acl);
754    }
755
756 }
757
758 #ifdef HAVE_LIBZ
759 /*
760  * Convert ZLIB error code into an ASCII message
761  */
762 static const char *zlib_strerror(int stat)
763 {
764    if (stat >= 0) {
765       return _("None");
766    }
767    switch (stat) {
768    case Z_ERRNO:
769       return _("Zlib errno");
770    case Z_STREAM_ERROR:
771       return _("Zlib stream error");
772    case Z_DATA_ERROR:
773       return _("Zlib data error");
774    case Z_MEM_ERROR:
775       return _("Zlib memory error");
776    case Z_BUF_ERROR:
777       return _("Zlib buffer error");
778    case Z_VERSION_ERROR:
779       return _("Zlib version error");
780    default:
781       return _("*none*");
782    }
783 }
784 #endif
785
786 static int do_file_digest(FF_PKT *ff_pkt, void *pkt, bool top_level) 
787 {
788    JCR *jcr = (JCR *)pkt;
789    Dmsg1(50, "do_file_digest jcr=%p\n", jcr);
790    return (digest_file(jcr, ff_pkt, jcr->digest));
791 }
792
793 /*
794  * Verify the signature for the last restored file
795  * Return value is either true (signature correct)
796  * or false (signature could not be verified).
797  * TODO landonf: Implement without using find_one_file and
798  * without re-reading the file.
799  */
800 static bool verify_signature(JCR *jcr, SIGNATURE *sig)
801 {
802    X509_KEYPAIR *keypair;
803    DIGEST *digest = NULL;
804    crypto_error_t err;
805    uint64_t saved_bytes;
806
807    if (!jcr->pki_sign) {
808       return true;                    /* no signature OK */
809    }
810    if (!sig) {
811       Jmsg1(jcr, M_ERROR, 0, _("Missing cryptographic signature for %s\n"), 
812             jcr->last_fname);
813    }
814
815    /* Iterate through the trusted signers */
816    foreach_alist(keypair, jcr->pki_signers) {
817       err = crypto_sign_get_digest(sig, jcr->pki_keypair, &digest);
818       switch (err) {
819       case CRYPTO_ERROR_NONE:
820          Dmsg0(50, "== Got digest\n");
821          /* Signature found, digest allocated */
822          jcr->digest = digest;
823
824          /* Checksum the entire file */
825          /* Make sure we don't modify JobBytes by saving and restoring it */
826          saved_bytes = jcr->JobBytes;                     
827          if (find_one_file(jcr, jcr->ff, do_file_digest, jcr, jcr->last_fname, (dev_t)-1, 1) != 0) {
828             Jmsg(jcr, M_ERROR, 0, _("Digest one file failed for file: %s\n"), 
829                  jcr->last_fname);
830             jcr->JobBytes = saved_bytes;
831             goto bail_out;
832          }
833          jcr->JobBytes = saved_bytes;
834
835          /* Verify the signature */
836          if ((err = crypto_sign_verify(sig, keypair, digest)) != CRYPTO_ERROR_NONE) {
837             Dmsg1(50, "Bad signature on %s\n", jcr->last_fname);
838             Jmsg2(jcr, M_ERROR, 0, _("Signature validation failed for file %s: ERR=%s\n"), 
839                   jcr->last_fname, crypto_strerror(err));
840             goto bail_out;
841          }
842
843          /* Valid signature */
844          Dmsg1(50, "Signature good on %s\n", jcr->last_fname);
845          crypto_digest_free(digest);
846          jcr->digest = NULL;
847          return true;
848
849       case CRYPTO_ERROR_NOSIGNER:
850          /* Signature not found, try again */
851          if (digest) {
852             crypto_digest_free(digest);
853             jcr->digest = NULL;
854          }
855          continue;
856       default:
857          /* Something strange happened (that shouldn't happen!)... */
858          Qmsg2(jcr, M_ERROR, 0, _("Signature validation failed for %s: %s\n"), jcr->last_fname, crypto_strerror(err));
859          goto bail_out;
860       }
861    }
862
863    /* No signer */
864    Dmsg1(50, "Could not find a valid public key for signature on %s\n", jcr->last_fname);
865
866 bail_out:
867    if (digest) {
868       crypto_digest_free(digest);
869       jcr->digest = NULL;
870    }
871    return false;
872 }
873
874 bool sparse_data(JCR *jcr, BFILE *bfd, uint64_t *addr, char **data, uint32_t *length)
875 {
876       unser_declare;
877       uint64_t faddr;
878       char ec1[50];
879       unser_begin(*data, SPARSE_FADDR_SIZE);
880       unser_uint64(faddr);
881       if (*addr != faddr) {
882          *addr = faddr;
883          if (blseek(bfd, (boffset_t)*addr, SEEK_SET) < 0) {
884             berrno be;
885             Jmsg3(jcr, M_ERROR, 0, _("Seek to %s error on %s: ERR=%s\n"),
886                   edit_uint64(*addr, ec1), jcr->last_fname, 
887                   be.bstrerror(bfd->berrno));
888             return false;
889          }
890       }
891       *data += SPARSE_FADDR_SIZE;
892       *length -= SPARSE_FADDR_SIZE;
893       return true;
894 }
895
896 bool decompress_data(JCR *jcr, char **data, uint32_t *length)
897 {
898 #ifdef HAVE_LIBZ
899    uLong compress_len;
900    int stat;
901    char ec1[50];                      /* Buffer printing huge values */
902
903    /* 
904     * NOTE! We only use uLong and Byte because they are
905     *  needed by the zlib routines, they should not otherwise
906     *  be used in Bacula.
907     */
908    compress_len = jcr->compress_buf_size;
909    Dmsg2(100, "Comp_len=%d msglen=%d\n", compress_len, *length);
910    if ((stat=uncompress((Byte *)jcr->compress_buf, &compress_len,
911                (const Byte *)*data, (uLong)*length)) != Z_OK) {
912       Qmsg(jcr, M_ERROR, 0, _("Uncompression error on file %s. ERR=%s\n"),
913             jcr->last_fname, zlib_strerror(stat));
914       return false;
915    }
916    *data = jcr->compress_buf;
917    *length = compress_len;
918    Dmsg2(100, "Write uncompressed %d bytes, total before write=%s\n", compress_len, edit_uint64(jcr->JobBytes, ec1));
919    return true;
920 #else
921    Qmsg(jcr, M_ERROR, 0, _("GZIP data stream found, but GZIP not configured!\n"));
922    return false;
923 #endif
924 }
925
926 static void unser_crypto_packet_len(RESTORE_CIPHER_CTX *ctx)
927 {
928    unser_declare;
929    if (ctx->packet_len == 0 && ctx->buf_len >= CRYPTO_LEN_SIZE) {
930       unser_begin(&ctx->buf[0], CRYPTO_LEN_SIZE);
931       unser_uint32(ctx->packet_len);
932       ctx->packet_len += CRYPTO_LEN_SIZE;
933    }
934 }
935
936 bool store_data(JCR *jcr, BFILE *bfd, char *data, const int32_t length, bool win32_decomp)
937 {
938    if (win32_decomp) {
939       if (!processWin32BackupAPIBlock(bfd, data, length)) {
940          berrno be;
941          Jmsg2(jcr, M_ERROR, 0, _("Write error in Win32 Block Decomposition on %s: %s\n"), 
942                jcr->last_fname, be.bstrerror(bfd->berrno));
943          return false;
944       }
945    } else if (bwrite(bfd, data, length) != (ssize_t)length) {
946       berrno be;
947       Jmsg2(jcr, M_ERROR, 0, _("Write error on %s: %s\n"), 
948             jcr->last_fname, be.bstrerror(bfd->berrno));
949       return false;
950    }
951
952    return true;
953 }
954
955 /*
956  * In the context of jcr, write data to bfd.
957  * We write buflen bytes in buf at addr. addr is updated in place.
958  * The flags specify whether to use sparse files or compression.
959  * Return value is the number of bytes written, or -1 on errors.
960  */
961 int32_t extract_data(JCR *jcr, BFILE *bfd, POOLMEM *buf, int32_t buflen,
962       uint64_t *addr, int flags, RESTORE_CIPHER_CTX *cipher_ctx)
963 {
964    char *wbuf;                        /* write buffer */
965    uint32_t wsize;                    /* write size */
966    uint32_t rsize;                    /* read size */
967    uint32_t decrypted_len = 0;        /* Decryption output length */
968    char ec1[50];                      /* Buffer printing huge values */
969
970    rsize = buflen;
971    jcr->ReadBytes += rsize;
972    wsize = rsize;
973    wbuf = buf;
974
975    if (flags & FO_ENCRYPT) {
976       ASSERT(cipher_ctx->cipher);
977
978       /* NOTE: We must implement block preserving semantics for the
979        * non-streaming compression and sparse code. */
980
981       /*
982        * Grow the crypto buffer, if necessary.
983        * crypto_cipher_update() will process only whole blocks,
984        * buffering the remaining input.
985        */
986       cipher_ctx->buf = check_pool_memory_size(cipher_ctx->buf, 
987                         cipher_ctx->buf_len + wsize + cipher_ctx->block_size);
988
989       /* Decrypt the input block */
990       if (!crypto_cipher_update(cipher_ctx->cipher, 
991                                 (const u_int8_t *)wbuf, 
992                                 wsize, 
993                                 (u_int8_t *)&cipher_ctx->buf[cipher_ctx->buf_len], 
994                                 &decrypted_len)) {
995          /* Decryption failed. Shouldn't happen. */
996          Jmsg(jcr, M_FATAL, 0, _("Decryption error\n"));
997          return -1;
998       }
999
1000       if (decrypted_len == 0) {
1001          /* No full block of encrypted data available, write more data */
1002          return 0;
1003       }
1004
1005       Dmsg2(100, "decrypted len=%d encrypted len=%d\n", decrypted_len, wsize);
1006
1007       cipher_ctx->buf_len += decrypted_len;
1008       wbuf = cipher_ctx->buf;
1009
1010       /* If one full preserved block is available, write it to disk,
1011        * and then buffer any remaining data. This should be effecient
1012        * as long as Bacula's block size is not significantly smaller than the
1013        * encryption block size (extremely unlikely!) */
1014       unser_crypto_packet_len(cipher_ctx);
1015       Dmsg1(500, "Crypto unser block size=%d\n", cipher_ctx->packet_len - CRYPTO_LEN_SIZE);
1016
1017       if (cipher_ctx->packet_len == 0 || cipher_ctx->buf_len < cipher_ctx->packet_len) {
1018          /* No full preserved block is available. */
1019          return 0;
1020       }
1021
1022       /* We have one full block, set up the filter input buffers */
1023       wsize = cipher_ctx->packet_len - CRYPTO_LEN_SIZE;
1024       wbuf = &wbuf[CRYPTO_LEN_SIZE]; /* Skip the block length header */
1025       cipher_ctx->buf_len -= cipher_ctx->packet_len;
1026       Dmsg2(30, "Encryption writing full block, %u bytes, remaining %u bytes in buffer\n", wsize, cipher_ctx->buf_len);
1027    }
1028
1029    if (flags & FO_SPARSE) {
1030       if (!sparse_data(jcr, bfd, addr, &wbuf, &wsize)) {
1031          return -1;
1032       }
1033    }
1034
1035    if (flags & FO_GZIP) {
1036       if (!decompress_data(jcr, &wbuf, &wsize)) {
1037          return -1;
1038       }
1039    }
1040
1041    if (!store_data(jcr, bfd, wbuf, wsize, (flags & FO_WIN32DECOMP) != 0)) {
1042       return -1;
1043    }
1044    jcr->JobBytes += wsize;
1045    *addr += wsize;
1046    Dmsg2(30, "Write %u bytes, JobBytes=%s\n", wsize, edit_uint64(jcr->JobBytes, ec1));
1047
1048    /* Clean up crypto buffers */
1049    if (flags & FO_ENCRYPT) {
1050       /* Move any remaining data to start of buffer */
1051       if (cipher_ctx->buf_len > 0) {
1052          Dmsg1(30, "Moving %u buffered bytes to start of buffer\n", cipher_ctx->buf_len);
1053          memmove(cipher_ctx->buf, &cipher_ctx->buf[cipher_ctx->packet_len], 
1054             cipher_ctx->buf_len);
1055       }
1056       /* The packet was successfully written, reset the length so that the next
1057        * packet length may be re-read by unser_crypto_packet_len() */
1058       cipher_ctx->packet_len = 0;
1059    }
1060
1061    return wsize;
1062 }
1063
1064 /*
1065  * In the context of jcr, flush any remaining data from the cipher context,
1066  * writing it to bfd.
1067  * Return value is true on success, false on failure.
1068  */
1069 bool flush_cipher(JCR *jcr, BFILE *bfd, uint64_t *addr, int flags,
1070                   RESTORE_CIPHER_CTX *cipher_ctx)
1071 {
1072    uint32_t decrypted_len = 0;
1073    char *wbuf;                        /* write buffer */
1074    uint32_t wsize;                    /* write size */
1075    char ec1[50];                      /* Buffer printing huge values */
1076    bool second_pass = false;
1077
1078 again:
1079    /* Write out the remaining block and free the cipher context */
1080    cipher_ctx->buf = check_pool_memory_size(cipher_ctx->buf, cipher_ctx->buf_len + 
1081                      cipher_ctx->block_size);
1082
1083    if (!crypto_cipher_finalize(cipher_ctx->cipher, (uint8_t *)&cipher_ctx->buf[cipher_ctx->buf_len],
1084         &decrypted_len)) {
1085       /* Writing out the final, buffered block failed. Shouldn't happen. */
1086       Jmsg3(jcr, M_ERROR, 0, _("Decryption error. buf_len=%d decrypt_len=%d on file %s\n"), 
1087             cipher_ctx->buf_len, decrypted_len, jcr->last_fname);
1088    }
1089
1090    Dmsg2(30, "Flush decrypt len=%d buf_len=%d\n", decrypted_len, cipher_ctx->buf_len);
1091    /* If nothing new was decrypted, and our output buffer is empty, return */
1092    if (decrypted_len == 0 && cipher_ctx->buf_len == 0) {
1093       return true;
1094    }
1095
1096    cipher_ctx->buf_len += decrypted_len;
1097
1098    unser_crypto_packet_len(cipher_ctx);
1099    Dmsg1(500, "Crypto unser block size=%d\n", cipher_ctx->packet_len - CRYPTO_LEN_SIZE);
1100    wsize = cipher_ctx->packet_len - CRYPTO_LEN_SIZE;
1101    wbuf = &cipher_ctx->buf[CRYPTO_LEN_SIZE]; /* Decrypted, possibly decompressed output here. */
1102    cipher_ctx->buf_len -= cipher_ctx->packet_len;
1103    Dmsg2(30, "Encryption writing full block, %u bytes, remaining %u bytes in buffer\n", wsize, cipher_ctx->buf_len);
1104
1105    if (flags & FO_SPARSE) {
1106       if (!sparse_data(jcr, bfd, addr, &wbuf, &wsize)) {
1107          return false;
1108       }
1109    }
1110
1111    if (flags & FO_GZIP) {
1112       if (!decompress_data(jcr, &wbuf, &wsize)) {
1113          return false;
1114       }
1115    }
1116
1117    Dmsg0(30, "Call store_data\n");
1118    if (!store_data(jcr, bfd, wbuf, wsize, (flags & FO_WIN32DECOMP) != 0)) {
1119       return false;
1120    }
1121    jcr->JobBytes += wsize;
1122    Dmsg2(30, "Flush write %u bytes, JobBytes=%s\n", wsize, edit_uint64(jcr->JobBytes, ec1));
1123
1124    /* Move any remaining data to start of buffer */
1125    if (cipher_ctx->buf_len > 0) {
1126       Dmsg1(30, "Moving %u buffered bytes to start of buffer\n", cipher_ctx->buf_len);
1127       memmove(cipher_ctx->buf, &cipher_ctx->buf[cipher_ctx->packet_len], 
1128          cipher_ctx->buf_len);
1129    }
1130    /* The packet was successfully written, reset the length so that the next
1131     * packet length may be re-read by unser_crypto_packet_len() */
1132    cipher_ctx->packet_len = 0;
1133
1134    if (cipher_ctx->buf_len >0 && !second_pass) {
1135       second_pass = true;
1136       goto again;
1137    }
1138
1139    /* Stop decryption */
1140    cipher_ctx->buf_len = 0;
1141    cipher_ctx->packet_len = 0;
1142
1143    return true;
1144 }