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