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