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