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