]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/bscan.c
Update/enhance copyright/license + add .backups for Nicolas
[bacula/bacula] / bacula / src / stored / bscan.c
1 /*
2  *
3  *  Program to scan a Bacula Volume and compare it with
4  *    the catalog and optionally synchronize the catalog
5  *    with the tape.
6  *
7  *   Kern E. Sibbald, December 2001
8  *
9  *
10  *   Version $Id$
11  */
12 /*
13    Copyright (C) 2001-2004 Kern Sibbald and John Walker
14
15    This program is free software; you can redistribute it and/or
16    modify it under the terms of the GNU General Public License as
17    published by the Free Software Foundation; either version 2 of
18    the License, or (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23    General Public License for more details.
24
25    You should have received a copy of the GNU General Public
26    License along with this program; if not, write to the Free
27    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28    MA 02111-1307, USA.
29
30  */
31
32 #include "bacula.h"
33 #include "stored.h"
34 #include "findlib/find.h"
35 #include "cats/cats.h"
36
37 /* Forward referenced functions */
38 static void do_scan(void);
39 static bool record_cb(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, DEV_RECORD *rec);
40 static int  create_file_attributes_record(B_DB *db, JCR *mjcr, 
41                                char *fname, char *lname, int type,
42                                char *ap, DEV_RECORD *rec);
43 static int  create_media_record(B_DB *db, MEDIA_DBR *mr, VOLUME_LABEL *vl);
44 static bool update_media_record(B_DB *db, MEDIA_DBR *mr);
45 static int  create_pool_record(B_DB *db, POOL_DBR *pr);
46 static JCR *create_job_record(B_DB *db, JOB_DBR *mr, SESSION_LABEL *label, DEV_RECORD *rec);
47 static int  update_job_record(B_DB *db, JOB_DBR *mr, SESSION_LABEL *elabel, 
48                               DEV_RECORD *rec);
49 static int  create_client_record(B_DB *db, CLIENT_DBR *cr);
50 static int  create_fileset_record(B_DB *db, FILESET_DBR *fsr);
51 static int  create_jobmedia_record(B_DB *db, JCR *jcr);
52 static JCR *create_jcr(JOB_DBR *jr, DEV_RECORD *rec, uint32_t JobId);
53 static int update_SIG_record(B_DB *db, char *SIGbuf, DEV_RECORD *rec, int type);
54
55
56 /* Global variables */
57 STORES *me;
58 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
59 int win32_client = 1;
60 #else
61 int win32_client = 0;
62 #endif
63
64
65 /* Local variables */
66 static DEVICE *dev = NULL;
67 static B_DB *db;
68 static JCR *bjcr;                     /* jcr for bscan */
69 static BSR *bsr = NULL;
70 static MEDIA_DBR mr;
71 static POOL_DBR pr;
72 static JOB_DBR jr;
73 static CLIENT_DBR cr;
74 static FILESET_DBR fsr;
75 static ATTR_DBR ar;
76 static FILE_DBR fr;
77 static SESSION_LABEL label;
78 static SESSION_LABEL elabel;
79 static ATTR *attr;
80
81 static time_t lasttime = 0;
82
83 static const char *db_name = "bacula";
84 static const char *db_user = "bacula";
85 static const char *db_password = "";
86 static const char *db_host = NULL;
87 static const char *wd = NULL;
88 static bool update_db = false;
89 static bool update_vol_info = false;
90 static bool list_records = false;
91 static int ignored_msgs = 0;
92
93 static int num_jobs = 0;
94 static int num_pools = 0;
95 static int num_media = 0;
96 static int num_files = 0;
97
98 #define CONFIG_FILE "bacula-sd.conf"
99 char *configfile;
100 bool forge_on = false;
101
102
103 static void usage()
104 {
105    fprintf(stderr, _(
106 "Copyright (C) 2001-2004 Kern Sibbald and John Walker.\n"
107 "\nVersion: " VERSION " (" BDATE ")\n\n"
108 "Usage: bscan [ options ] <bacula-archive>\n"
109 "       -b bootstrap      specify a bootstrap file\n"
110 "       -c <file>         specify configuration file\n"
111 "       -d <nn>           set debug level to nn\n"
112 "       -m                update media info in database\n"
113 "       -n <name>         specify the database name (default bacula)\n"
114 "       -u <user>         specify database user name (default bacula)\n"
115 "       -P <password      specify database password (default none)\n"
116 "       -h <host>         specify database host (default NULL)\n"
117 "       -p                proceed inspite of I/O errors\n"
118 "       -r                list records\n"
119 "       -s                synchronize or store in database\n"
120 "       -v                verbose\n"
121 "       -V <Volumes>      specify Volume names (separated by |)\n"
122 "       -w <dir>          specify working directory (default from conf file)\n"
123 "       -?                print this message\n\n"));
124    exit(1);
125 }
126
127 int main (int argc, char *argv[])
128 {
129    int ch;
130    struct stat stat_buf;
131    char *VolumeName = NULL;
132
133    my_name_is(argc, argv, "bscan");
134    init_msg(NULL, NULL);
135
136
137    while ((ch = getopt(argc, argv, "b:c:d:h:mn:pP:rsu:vV:w:?")) != -1) {
138       switch (ch) {
139       case 'b':
140          bsr = parse_bsr(NULL, optarg);
141          break;
142
143       case 'c':                    /* specify config file */
144          if (configfile != NULL) {
145             free(configfile);
146          }
147          configfile = bstrdup(optarg);
148          break;
149
150       case 'd':                    /* debug level */
151          debug_level = atoi(optarg);
152          if (debug_level <= 0)
153             debug_level = 1; 
154          break;
155
156       case 'h':
157          db_host = optarg;
158          break;
159
160       case 'm':
161          update_vol_info = true;
162          break;
163
164       case 'n':
165          db_name = optarg;
166          break;
167
168       case 'u':
169          db_user = optarg;
170          break;
171
172       case 'P':
173          db_password = optarg;
174          break;
175
176       case 'p':
177          forge_on = true;
178          break;
179
180       case 'r':
181          list_records = true;
182          break;
183
184       case 's':
185          update_db = true;
186          break;
187
188       case 'v':
189          verbose++;
190          break;
191
192       case 'V':                    /* Volume name */
193          VolumeName = optarg;
194          break;
195
196       case 'w':
197          wd = optarg;
198          break;
199
200       case '?':
201       default:
202          usage();
203
204       }  
205    }
206    argc -= optind;
207    argv += optind;
208
209    if (argc != 1) {
210       Pmsg0(0, _("Wrong number of arguments: \n"));
211       usage();
212    }
213
214    if (configfile == NULL) {
215       configfile = bstrdup(CONFIG_FILE);
216    }
217
218    parse_config(configfile);
219    LockRes();
220    me = (STORES *)GetNextRes(R_STORAGE, NULL);
221    if (!me) {
222       UnlockRes();
223       Emsg1(M_ERROR_TERM, 0, _("No Storage resource defined in %s. Cannot continue.\n"), 
224          configfile);
225    }
226    UnlockRes();
227    /* Check if -w option given, otherwise use resource for working directory */
228    if (wd) { 
229       working_directory = wd;
230    } else if (!me->working_directory) {
231       Emsg1(M_ERROR_TERM, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
232          configfile);
233    } else {
234       working_directory = me->working_directory;
235    }
236
237    /* Check that working directory is good */
238    if (stat(working_directory, &stat_buf) != 0) {
239       Emsg1(M_ERROR_TERM, 0, _("Working Directory: %s not found. Cannot continue.\n"),
240          working_directory);
241    }
242    if (!S_ISDIR(stat_buf.st_mode)) {
243       Emsg1(M_ERROR_TERM, 0, _("Working Directory: %s is not a directory. Cannot continue.\n"),
244          working_directory);
245    }
246
247    bjcr = setup_jcr("bscan", argv[0], bsr, VolumeName);
248    dev = setup_to_access_device(bjcr, 1);   /* read device */
249    if (!dev) { 
250       exit(1);
251    }
252
253    if ((db=db_init_database(NULL, db_name, db_user, db_password, db_host, 0, NULL)) == NULL) {
254       Emsg0(M_ERROR_TERM, 0, _("Could not init Bacula database\n"));
255    }
256    if (!db_open_database(NULL, db)) {
257       Emsg0(M_ERROR_TERM, 0, db_strerror(db));
258    }
259    Dmsg0(200, "Database opened\n");
260    if (verbose) {
261       Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user);
262    }
263
264    do_scan();
265    printf("Records %sadded to catalog:\n%7d Media\n%7d Pool\n%7d Job\n%7d File\n",
266       update_db?"":"would have been ",
267       num_media, num_pools, num_jobs, num_files);
268
269    free_jcr(bjcr);
270    term_dev(dev);
271    return 0;
272 }
273   
274 /*  
275  * We are at the end of reading a tape. Now, we simulate handling
276  *   the end of writing a tape by wiffling through the attached
277  *   jcrs creating jobmedia records.
278  */
279 static bool bscan_mount_next_read_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
280 {
281    Dmsg1(100, "Walk attached jcrs. Volume=%s\n", dev->VolCatInfo.VolCatName);
282    DCR *dcr;
283    foreach_dlist(dcr, dev->attached_dcrs) {
284       JCR *mjcr = dcr->jcr;
285       if (mjcr->JobId == 0) {
286          continue;
287       }
288       if (verbose) {
289          Pmsg1(000, _("Create JobMedia for Job %s\n"), mjcr->Job);
290       }
291       if (dev->state & ST_TAPE) {
292          dcr->EndBlock = dev->EndBlock;
293          dcr->EndFile = dev->EndFile;
294       } else {
295          dcr->EndBlock = (uint32_t)dev->file_addr;
296          dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
297       }
298       if (!create_jobmedia_record(db, mjcr)) {
299          Pmsg2(000, _("Could not create JobMedia record for Volume=%s Job=%s\n"),
300             dev->VolCatInfo.VolCatName, mjcr->Job);
301       }
302    }  
303    /* Now let common read routine get up next tape. Note,
304     * we call mount_next... with bscan's jcr because that is where we
305     * have the Volume list, but we get attached.
306     */
307    bool stat = mount_next_read_volume(jcr, dev, block);
308    return stat;
309 }
310
311 static void do_scan()             
312 {
313    attr = new_attr();
314
315    memset(&ar, 0, sizeof(ar));
316    memset(&pr, 0, sizeof(pr));
317    memset(&jr, 0, sizeof(jr));
318    memset(&cr, 0, sizeof(cr));
319    memset(&fsr, 0, sizeof(fsr));
320    memset(&fr, 0, sizeof(fr));
321
322    /* Detach bscan's jcr as we are not a real Job on the tape */
323
324    read_records(bjcr->dcr, record_cb, bscan_mount_next_read_volume);
325 // release_device(bjcr);
326
327    free_attr(attr);
328 }
329
330 /*
331  * Returns: true  if OK
332  *          false if error
333  */
334 static bool record_cb(JCR *bjcr, DEVICE *dev, DEV_BLOCK *block, DEV_RECORD *rec)
335 {
336    JCR *mjcr;
337    DCR *dcr;
338    char ec1[30];
339
340    if (rec->data_len > 0) {
341       mr.VolBytes += rec->data_len + WRITE_RECHDR_LENGTH; /* Accumulate Volume bytes */
342    }
343    if (list_records) {
344       Pmsg5(000, _("Record: SessId=%u SessTim=%u FileIndex=%d Stream=%d len=%u\n"),
345             rec->VolSessionId, rec->VolSessionTime, rec->FileIndex, 
346             rec->Stream, rec->data_len);
347    }
348    /* 
349     * Check for Start or End of Session Record 
350     *
351     */
352    if (rec->FileIndex < 0) {
353       bool save_update_db = update_db;
354
355       if (verbose > 1) {
356          dump_label_record(dev, rec, 1);
357       }
358       switch (rec->FileIndex) {
359       case PRE_LABEL:
360          Pmsg0(000, _("Volume is prelabeled. This tape cannot be scanned.\n"));
361          return false;
362          break;
363
364       case VOL_LABEL:
365          unser_volume_label(dev, rec);
366          /* Check Pool info */
367          bstrncpy(pr.Name, dev->VolHdr.PoolName, sizeof(pr.Name));
368          bstrncpy(pr.PoolType, dev->VolHdr.PoolType, sizeof(pr.PoolType));
369          num_pools++;
370          if (db_get_pool_record(bjcr, db, &pr)) {
371             if (verbose) {
372                Pmsg1(000, _("Pool record for %s found in DB.\n"), pr.Name);
373             }
374          } else {
375             if (!update_db) {
376                Pmsg1(000, _("VOL_LABEL: Pool record not found for Pool: %s\n"),
377                   pr.Name);
378             }
379             create_pool_record(db, &pr);
380          }
381          if (strcmp(pr.PoolType, dev->VolHdr.PoolType) != 0) {
382             Pmsg2(000, _("VOL_LABEL: PoolType mismatch. DB=%s Vol=%s\n"),
383                pr.PoolType, dev->VolHdr.PoolType);
384             return true;
385          } else if (verbose) {
386             Pmsg1(000, _("Pool type \"%s\" is OK.\n"), pr.PoolType);
387          }
388
389          /* Check Media Info */
390          memset(&mr, 0, sizeof(mr));
391          bstrncpy(mr.VolumeName, dev->VolHdr.VolName, sizeof(mr.VolumeName));
392          mr.PoolId = pr.PoolId;
393          num_media++;
394          if (db_get_media_record(bjcr, db, &mr)) {
395             if (verbose) {
396                Pmsg1(000, _("Media record for %s found in DB.\n"), mr.VolumeName);
397             }
398             /* Clear out some volume statistics that will be updated */
399             mr.VolJobs = mr.VolFiles = mr.VolBlocks = 0;
400             mr.VolBytes = rec->data_len + 20;
401          } else {
402             if (!update_db) {
403                Pmsg1(000, _("VOL_LABEL: Media record not found for Volume: %s\n"),
404                   mr.VolumeName);
405             }
406             bstrncpy(mr.MediaType, dev->VolHdr.MediaType, sizeof(mr.MediaType));
407             create_media_record(db, &mr, &dev->VolHdr);
408          }
409          if (strcmp(mr.MediaType, dev->VolHdr.MediaType) != 0) {
410             Pmsg2(000, _("VOL_LABEL: MediaType mismatch. DB=%s Vol=%s\n"),
411                mr.MediaType, dev->VolHdr.MediaType);
412             return true;              /* ignore error */
413          } else if (verbose) {
414             Pmsg1(000, _("Media type \"%s\" is OK.\n"), mr.MediaType);
415          }
416          /* Reset some JCR variables */
417          foreach_dlist(dcr, dev->attached_dcrs) {
418             dcr->VolFirstIndex = dcr->FileIndex = 0;
419             dcr->StartBlock = dcr->EndBlock = 0;
420             dcr->StartFile = dcr->EndFile = 0;
421          }
422
423          Pmsg1(000, _("VOL_LABEL: OK for Volume: %s\n"), mr.VolumeName);
424          break;
425
426       case SOS_LABEL:
427          mr.VolJobs++;
428          num_jobs++;
429          if (ignored_msgs > 0) {
430             Pmsg1(000, _("%d \"errors\" ignored before first Start of Session record.\n"), 
431                   ignored_msgs);
432             ignored_msgs = 0;
433          }
434          unser_session_label(&label, rec);
435          memset(&jr, 0, sizeof(jr));
436          jr.JobId = label.JobId;
437          if (db_get_job_record(bjcr, db, &jr)) {
438             /* Job record already exists in DB */
439             update_db = false;  /* don't change db in create_job_record */
440             if (verbose) {
441                Pmsg1(000, _("SOS_LABEL: Found Job record for JobId: %d\n"), jr.JobId);
442             }
443          } else {
444             /* Must create a Job record in DB */
445             if (!update_db) {
446                Pmsg1(000, _("SOS_LABEL: Job record not found for JobId: %d\n"),
447                   jr.JobId);
448             }
449          }
450          /* Create Client record if not already there */
451             bstrncpy(cr.Name, label.ClientName, sizeof(cr.Name));
452             create_client_record(db, &cr);
453             jr.ClientId = cr.ClientId;
454
455          /* process label, if Job record exists don't update db */
456          mjcr = create_job_record(db, &jr, &label, rec);
457          dcr = mjcr->dcr;
458          update_db = save_update_db;
459
460          jr.PoolId = pr.PoolId;
461          /* Set start positions into JCR */
462          if (dev->state & ST_TAPE) {
463             /*
464              * Note, we have already advanced past current block,
465              *  so the correct number is block_num - 1 
466              */ 
467             dcr->StartBlock = dev->block_num - 1;
468             dcr->StartFile = dev->file;
469          } else {
470             dcr->StartBlock = (uint32_t)dev->file_addr;
471             dcr->StartFile = (uint32_t)(dev->file_addr >> 32);
472          }
473          mjcr->start_time = jr.StartTime;
474          mjcr->JobLevel = jr.JobLevel;
475
476          mjcr->client_name = get_pool_memory(PM_FNAME);
477          pm_strcpy(&mjcr->client_name, label.ClientName);
478          mjcr->pool_type = get_pool_memory(PM_FNAME);
479          pm_strcpy(&mjcr->pool_type, label.PoolType);
480          mjcr->fileset_name = get_pool_memory(PM_FNAME);
481          pm_strcpy(&mjcr->fileset_name, label.FileSetName);
482          mjcr->pool_name = get_pool_memory(PM_FNAME);
483          pm_strcpy(&mjcr->pool_name, label.PoolName);
484
485          if (rec->VolSessionId != jr.VolSessionId) {
486             Pmsg3(000, _("SOS_LABEL: VolSessId mismatch for JobId=%u. DB=%d Vol=%d\n"),
487                jr.JobId,
488                jr.VolSessionId, rec->VolSessionId);
489             return true;              /* ignore error */
490          }
491          if (rec->VolSessionTime != jr.VolSessionTime) {
492             Pmsg3(000, _("SOS_LABEL: VolSessTime mismatch for JobId=%u. DB=%d Vol=%d\n"),
493                jr.JobId,
494                jr.VolSessionTime, rec->VolSessionTime);
495             return true;              /* ignore error */
496          }
497          if (jr.PoolId != pr.PoolId) {
498             Pmsg3(000, _("SOS_LABEL: PoolId mismatch for JobId=%u. DB=%d Vol=%d\n"),
499                jr.JobId,
500                jr.PoolId, pr.PoolId);
501             return true;              /* ignore error */
502          }
503          break;
504
505       case EOS_LABEL:
506          unser_session_label(&elabel, rec);
507
508          /* Create FileSet record */
509          bstrncpy(fsr.FileSet, label.FileSetName, sizeof(fsr.FileSet));
510          bstrncpy(fsr.MD5, label.FileSetMD5, sizeof(fsr.MD5));
511          create_fileset_record(db, &fsr);
512          jr.FileSetId = fsr.FileSetId;
513
514          mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
515          if (!mjcr) {
516             Pmsg2(000, _("Could not find SessId=%d SessTime=%d for EOS record.\n"),
517                   rec->VolSessionId, rec->VolSessionTime);
518             break;
519          }
520
521          /* Do the final update to the Job record */
522          update_job_record(db, &jr, &elabel, rec);
523
524          mjcr->end_time = jr.EndTime;
525          mjcr->JobStatus = JS_Terminated;
526
527          /* Create JobMedia record */
528          create_jobmedia_record(db, mjcr);
529          dev->attached_dcrs->remove(mjcr->dcr);
530          free_jcr(mjcr);
531
532          break;
533
534       case EOM_LABEL:
535          break;
536
537       case EOT_LABEL:              /* end of all tapes */
538          /* 
539           * Wiffle through all jobs still open and close
540           *   them.
541           */
542          if (update_db) {
543             DCR *mdcr;
544             foreach_dlist(mdcr, dev->attached_dcrs) {
545                JCR *mjcr = mdcr->jcr;
546                if (!mjcr || mjcr->JobId == 0) {
547                   continue;
548                }
549                jr.JobId = mjcr->JobId;
550                /* Mark Job as Error Terimined */
551                jr.JobStatus = JS_ErrorTerminated;
552                jr.JobFiles = mjcr->JobFiles;
553                jr.JobBytes = mjcr->JobBytes;
554                jr.VolSessionId = mjcr->VolSessionId;
555                jr.VolSessionTime = mjcr->VolSessionTime;
556                jr.JobTDate = (utime_t)mjcr->start_time;
557                jr.ClientId = mjcr->ClientId;
558                if (!db_update_job_end_record(bjcr, db, &jr)) {
559                   Pmsg1(0, _("Could not update job record. ERR=%s\n"), db_strerror(db));
560                }
561                mjcr->dcr = NULL;
562                free_jcr(mjcr);
563             }
564          }
565          mr.VolFiles = rec->File;
566          mr.VolBlocks = rec->Block;
567          mr.VolBytes += mr.VolBlocks * WRITE_BLKHDR_LENGTH; /* approx. */
568          mr.VolMounts++;
569          update_media_record(db, &mr);
570          Pmsg3(0, _("End of all Volumes. VolFiles=%u VolBlocks=%u VolBytes=%s\n"), mr.VolFiles,
571                     mr.VolBlocks, edit_uint64_with_commas(mr.VolBytes, ec1));
572          break;
573       default:
574          break;
575       } /* end switch */
576       return true;
577    }
578
579    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
580    if (!mjcr) {
581       if (mr.VolJobs > 0) {
582          Pmsg2(000, _("Could not find Job for SessId=%d SessTime=%d record.\n"),
583                       rec->VolSessionId, rec->VolSessionTime);
584       } else {
585          ignored_msgs++;
586       }
587       return true;
588    }
589    dcr = mjcr->dcr;
590    if (dcr->VolFirstIndex == 0) {
591       dcr->VolFirstIndex = block->FirstIndex;
592    }
593
594    /* File Attributes stream */
595    switch (rec->Stream) {
596    case STREAM_UNIX_ATTRIBUTES:   
597    case STREAM_UNIX_ATTRIBUTES_EX:  
598
599       if (!unpack_attributes_record(bjcr, rec->Stream, rec->data, attr)) {
600          Emsg0(M_ERROR_TERM, 0, _("Cannot continue.\n"));
601       }
602
603       if (attr->file_index != rec->FileIndex) {
604          Emsg2(M_ERROR_TERM, 0, _("Record header file index %ld not equal record index %ld\n"),
605             rec->FileIndex, attr->file_index);
606       }
607        
608       if (verbose > 1) {
609          decode_stat(attr->attr, &attr->statp, &attr->LinkFI);
610          build_attr_output_fnames(bjcr, attr);
611          print_ls_output(bjcr, attr);
612       }
613       fr.JobId = mjcr->JobId;
614       fr.FileId = 0;
615       num_files++;
616       if (verbose && (num_files & 0x7FFF) == 0) {
617          char ed1[30], ed2[30], ed3[30], ed4[30];
618          Pmsg4(000, _("%s file records. At file:blk=%s:%s bytes=%s\n"),
619                      edit_uint64_with_commas(num_files, ed1),
620                      edit_uint64_with_commas(rec->File, ed2),
621                      edit_uint64_with_commas(rec->Block, ed3),
622                      edit_uint64_with_commas(mr.VolBytes, ed4));
623       } 
624       if (db_get_file_attributes_record(bjcr, db, attr->fname, NULL, &fr)) {
625          if (verbose > 1) {
626             Pmsg1(000, _("File record already exists for: %s\n"), attr->fname);
627          }
628       } else {
629          create_file_attributes_record(db, mjcr, attr->fname, attr->lname, 
630             attr->type, attr->attr, rec);
631       }
632       free_jcr(mjcr);
633       break;
634
635    /* Data stream */
636    case STREAM_WIN32_DATA:
637    case STREAM_FILE_DATA:
638    case STREAM_SPARSE_DATA:
639       mjcr->JobBytes += rec->data_len;
640       if (rec->Stream == STREAM_SPARSE_DATA) {
641          mjcr->JobBytes -= sizeof(uint64_t);
642       }
643          
644       free_jcr(mjcr);                 /* done using JCR */
645       break;
646
647    case STREAM_GZIP_DATA:
648       mjcr->JobBytes += rec->data_len; /* No correct, we should expand it */
649       free_jcr(mjcr);                 /* done using JCR */
650       break;
651
652    case STREAM_SPARSE_GZIP_DATA:
653       mjcr->JobBytes += rec->data_len - sizeof(uint64_t); /* No correct, we should expand it */
654       free_jcr(mjcr);                 /* done using JCR */
655       break;
656
657    /* Win32 GZIP stream */
658    case STREAM_WIN32_GZIP_DATA:
659       mjcr->JobBytes += rec->data_len;
660       free_jcr(mjcr);                 /* done using JCR */
661       break;
662
663    case STREAM_MD5_SIGNATURE:
664       char MD5buf[50];
665       bin_to_base64(MD5buf, (char *)rec->data, 16); /* encode 16 bytes */
666       if (verbose > 1) {
667          Pmsg1(000, _("Got MD5 record: %s\n"), MD5buf);
668       }
669       update_SIG_record(db, MD5buf, rec, MD5_SIG);
670       break;
671
672    case STREAM_SHA1_SIGNATURE:
673       char SIGbuf[50];
674       bin_to_base64(SIGbuf, (char *)rec->data, 20); /* encode 20 bytes */
675       if (verbose > 1) {
676          Pmsg1(000, _("Got SHA1 record: %s\n"), SIGbuf);
677       }
678       update_SIG_record(db, SIGbuf, rec, SHA1_SIG);
679       break;
680
681
682    case STREAM_PROGRAM_NAMES:
683       if (verbose) {
684          Pmsg1(000, _("Got Prog Names Stream: %s\n"), rec->data);
685       }
686       break;
687
688    case STREAM_PROGRAM_DATA:
689       if (verbose > 1) {
690          Pmsg0(000, _("Got Prog Data Stream record.\n"));
691       }
692       break;
693    default:
694       Pmsg2(0, _("Unknown stream type!!! stream=%d data=%s\n"), rec->Stream, rec->data);
695       break;
696    }
697    return true;
698 }
699
700 /*
701  * Free the Job Control Record if no one is still using it.
702  *  Called from main free_jcr() routine in src/lib/jcr.c so
703  *  that we can do our Director specific cleanup of the jcr.
704  */
705 static void bscan_free_jcr(JCR *jcr)
706 {
707    Dmsg0(200, "Start dird free_jcr\n");
708
709    if (jcr->file_bsock) {
710       Dmsg0(200, "Close File bsock\n");
711       bnet_close(jcr->file_bsock);
712    }
713    if (jcr->store_bsock) {
714       Dmsg0(200, "Close Store bsock\n");
715       bnet_close(jcr->store_bsock);
716    }
717    if (jcr->RestoreBootstrap) {
718       free(jcr->RestoreBootstrap);
719    }
720    if (jcr->dcr) {
721       free_dcr(jcr->dcr);
722       jcr->dcr = NULL;
723    }
724    Dmsg0(200, "End dird free_jcr\n");
725 }
726
727 /*
728  * We got a File Attributes record on the tape.  Now, lookup the Job
729  *   record, and then create the attributes record.
730  */
731 static int create_file_attributes_record(B_DB *db, JCR *mjcr,
732                                char *fname, char *lname, int type,
733                                char *ap, DEV_RECORD *rec)
734 {
735    DCR *dcr = mjcr->dcr;
736    ar.fname = fname;
737    ar.link = lname;
738    ar.ClientId = mjcr->ClientId;
739    ar.JobId = mjcr->JobId;
740    ar.Stream = rec->Stream;
741    ar.FileIndex = rec->FileIndex;
742    ar.attr = ap;
743    if (dcr->VolFirstIndex == 0) {
744       dcr->VolFirstIndex = rec->FileIndex;
745    }
746    dcr->FileIndex = rec->FileIndex;
747    mjcr->JobFiles++;
748
749    if (!update_db) {
750       return 1;
751    }
752
753    if (!db_create_file_attributes_record(bjcr, db, &ar)) {
754       Pmsg1(0, _("Could not create File Attributes record. ERR=%s\n"), db_strerror(db));
755       return 0;
756    }
757    mjcr->FileId = ar.FileId;
758
759    if (verbose > 1) {
760       Pmsg1(000, _("Created File record: %s\n"), fname);   
761    }
762    return 1;
763 }
764
765 /*
766  * For each Volume we see, we create a Medium record
767  */
768 static int create_media_record(B_DB *db, MEDIA_DBR *mr, VOLUME_LABEL *vl)
769 {
770    struct date_time dt;
771    struct tm tm;
772
773    /* We mark Vols as Archive to keep them from being re-written */
774    bstrncpy(mr->VolStatus, "Archive", sizeof(mr->VolStatus));
775    mr->VolRetention = 365 * 3600 * 24; /* 1 year */
776    if (vl->VerNum >= 11) {
777       mr->FirstWritten = btime_to_utime(vl->write_btime);
778       mr->LabelDate    = btime_to_utime(vl->label_btime);
779    } else {
780       /* DEPRECATED DO NOT USE */
781       dt.julian_day_number = vl->write_date;
782       dt.julian_day_fraction = vl->write_time;
783       tm_decode(&dt, &tm);
784       mr->FirstWritten = mktime(&tm);
785       dt.julian_day_number = vl->label_date;
786       dt.julian_day_fraction = vl->label_time;
787       tm_decode(&dt, &tm);
788       mr->LabelDate = mktime(&tm);
789    }
790    lasttime = mr->LabelDate;
791
792    if (!update_db) {
793       return 1;
794    }
795
796    if (!db_create_media_record(bjcr, db, mr)) {
797       Pmsg1(0, _("Could not create media record. ERR=%s\n"), db_strerror(db));
798       return 0;
799    }
800    if (!db_update_media_record(bjcr, db, mr)) {
801       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
802       return 0;
803    }
804    if (verbose) {
805       Pmsg1(000, _("Created Media record for Volume: %s\n"), mr->VolumeName);
806    }
807    return 1;
808
809 }
810
811 /*
812  * Called at end of media to update it
813  */
814 static bool update_media_record(B_DB *db, MEDIA_DBR *mr)
815 {
816    if (!update_db && !update_vol_info) {
817       return true;
818    }
819
820    mr->LastWritten = lasttime;
821    if (!db_update_media_record(bjcr, db, mr)) {
822       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
823       return false;;
824    }
825    if (verbose) {
826       Pmsg1(000, _("Updated Media record at end of Volume: %s\n"), mr->VolumeName);
827    }
828    return true;
829
830 }
831
832
833 static int create_pool_record(B_DB *db, POOL_DBR *pr)
834 {
835    pr->NumVols++;
836    pr->UseCatalog = 1;
837    pr->VolRetention = 355 * 3600 * 24; /* 1 year */
838
839    if (!update_db) {
840       return 1;
841    }
842    if (!db_create_pool_record(bjcr, db, pr)) {
843       Pmsg1(0, _("Could not create pool record. ERR=%s\n"), db_strerror(db));
844       return 0;
845    }
846    if (verbose) {
847       Pmsg1(000, _("Created Pool record for Pool: %s\n"), pr->Name);
848    }
849    return 1;
850
851 }
852
853
854 /*
855  * Called from SOS to create a client for the current Job 
856  */
857 static int create_client_record(B_DB *db, CLIENT_DBR *cr)
858 {
859    if (!update_db) {
860       return 1;
861    }
862    if (!db_create_client_record(bjcr, db, cr)) {
863       Pmsg1(0, _("Could not create Client record. ERR=%s\n"), db_strerror(db));
864       return 0;
865    }
866    if (verbose) {
867       Pmsg1(000, _("Created Client record for Client: %s\n"), cr->Name);
868    }
869    return 1;
870 }
871
872 static int create_fileset_record(B_DB *db, FILESET_DBR *fsr)
873 {
874    if (!update_db) {
875       return 1;
876    }
877    fsr->FileSetId = 0;
878    if (fsr->MD5[0] == 0) {
879       fsr->MD5[0] = ' ';              /* Equivalent to nothing */
880       fsr->MD5[1] = 0;
881    }
882    if (db_get_fileset_record(bjcr, db, fsr)) {
883       if (verbose) {
884          Pmsg1(000, _("Fileset \"%s\" already exists.\n"), fsr->FileSet);
885       }
886    } else {
887       if (!db_create_fileset_record(bjcr, db, fsr)) {
888          Pmsg2(0, _("Could not create FileSet record \"%s\". ERR=%s\n"), 
889             fsr->FileSet, db_strerror(db));
890          return 0;
891       }
892       if (verbose) {
893          Pmsg1(000, _("Created FileSet record \"%s\"\n"), fsr->FileSet);
894       }
895    }
896    return 1;
897 }
898
899 /*
900  * Simulate the two calls on the database to create
901  *  the Job record and to update it when the Job actually
902  *  begins running.
903  */
904 static JCR *create_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *label, 
905                              DEV_RECORD *rec)
906 {
907    JCR *mjcr;
908    struct date_time dt;
909    struct tm tm;
910
911    jr->JobId = label->JobId;
912    jr->JobType = label->JobType;
913    jr->JobLevel = label->JobLevel;
914    jr->JobStatus = JS_Created;
915    bstrncpy(jr->Name, label->JobName, sizeof(jr->Name));
916    bstrncpy(jr->Job, label->Job, sizeof(jr->Job));
917    if (label->VerNum >= 11) {
918       jr->SchedTime = btime_to_unix(label->write_btime);
919    } else {
920       dt.julian_day_number = label->write_date;
921       dt.julian_day_fraction = label->write_time;
922       tm_decode(&dt, &tm);
923       jr->SchedTime = mktime(&tm);
924    }
925
926    jr->StartTime = jr->SchedTime;
927    jr->JobTDate = (utime_t)jr->SchedTime;
928    jr->VolSessionId = rec->VolSessionId;
929    jr->VolSessionTime = rec->VolSessionTime;
930
931    /* Now create a JCR as if starting the Job */
932    mjcr = create_jcr(jr, rec, label->JobId);
933
934    if (!update_db) {
935       return mjcr;
936    }
937
938    /* This creates the bare essentials */
939    if (!db_create_job_record(bjcr, db, jr)) {
940       Pmsg1(0, _("Could not create JobId record. ERR=%s\n"), db_strerror(db));
941       return mjcr;
942    }
943
944    /* This adds the client, StartTime, JobTDate, ... */
945    if (!db_update_job_start_record(bjcr, db, jr)) {
946       Pmsg1(0, _("Could not update job start record. ERR=%s\n"), db_strerror(db));
947       return mjcr;
948    }
949    Pmsg2(000, _("Created new JobId=%u record for original JobId=%u\n"), jr->JobId, 
950          label->JobId);
951    mjcr->JobId = jr->JobId;           /* set new JobId */
952    return mjcr;
953 }
954
955 /* 
956  * Simulate the database call that updates the Job 
957  *  at Job termination time.
958  */
959 static int update_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *elabel,
960                               DEV_RECORD *rec)
961 {
962    struct date_time dt;
963    struct tm tm;
964    JCR *mjcr;
965
966    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
967    if (!mjcr) {
968       Pmsg2(000, _("Could not find SessId=%d SessTime=%d for EOS record.\n"),
969                    rec->VolSessionId, rec->VolSessionTime);
970       return 0;
971    }
972    if (elabel->VerNum >= 11) {
973       jr->EndTime = btime_to_unix(elabel->write_btime);
974    } else {
975       dt.julian_day_number = elabel->write_date;
976       dt.julian_day_fraction = elabel->write_time;
977       tm_decode(&dt, &tm);
978       jr->EndTime = mktime(&tm);
979    }
980    lasttime = jr->EndTime;
981    mjcr->end_time = jr->EndTime;
982
983    jr->JobId = mjcr->JobId;
984    jr->JobStatus = elabel->JobStatus;
985    mjcr->JobStatus = elabel->JobStatus;
986    jr->JobFiles = elabel->JobFiles;
987    jr->JobBytes = elabel->JobBytes;
988    jr->VolSessionId = rec->VolSessionId;
989    jr->VolSessionTime = rec->VolSessionTime;
990    jr->JobTDate = (utime_t)mjcr->start_time;
991    jr->ClientId = mjcr->ClientId;
992
993    if (!update_db) {
994       free_jcr(mjcr);
995       return 1;
996    }
997    
998    if (!db_update_job_end_record(bjcr, db, jr)) {
999       Pmsg2(0, _("Could not update JobId=%u record. ERR=%s\n"), jr->JobId,  db_strerror(db));
1000       free_jcr(mjcr);
1001       return 0;
1002    }
1003    if (verbose) {
1004       Pmsg2(000, _("Updated Job termination record for JobId=%u TermStat=%c\n"), jr->JobId,
1005          jr->JobStatus);
1006    }
1007    if (verbose > 1) {
1008       const char *term_msg;
1009       static char term_code[70];
1010       char sdt[50], edt[50];
1011       char ec1[30], ec2[30], ec3[30];
1012
1013       switch (mjcr->JobStatus) {
1014       case JS_Terminated:
1015          term_msg = _("Backup OK");
1016          break;
1017       case JS_FatalError:
1018       case JS_ErrorTerminated:
1019          term_msg = _("*** Backup Error ***");
1020          break;
1021       case JS_Canceled:
1022          term_msg = _("Backup Canceled");
1023          break;
1024       default:
1025          term_msg = term_code;
1026          sprintf(term_code, _("Job Termination code: %d"), mjcr->JobStatus);
1027          break;
1028       }
1029       bstrftime(sdt, sizeof(sdt), mjcr->start_time);
1030       bstrftime(edt, sizeof(edt), mjcr->end_time);
1031       Pmsg14(000,  _("%s\n\
1032 JobId:                  %d\n\
1033 Job:                    %s\n\
1034 FileSet:                %s\n\
1035 Backup Level:           %s\n\
1036 Client:                 %s\n\
1037 Start time:             %s\n\
1038 End time:               %s\n\
1039 Files Written:          %s\n\
1040 Bytes Written:          %s\n\
1041 Volume Session Id:      %d\n\
1042 Volume Session Time:    %d\n\
1043 Last Volume Bytes:      %s\n\
1044 Termination:            %s\n\n"),
1045         edt,
1046         mjcr->JobId,
1047         mjcr->Job,
1048         mjcr->fileset_name,
1049         job_level_to_str(mjcr->JobLevel),
1050         mjcr->client_name,
1051         sdt,
1052         edt,
1053         edit_uint64_with_commas(mjcr->JobFiles, ec1),
1054         edit_uint64_with_commas(mjcr->JobBytes, ec2),
1055         mjcr->VolSessionId,
1056         mjcr->VolSessionTime,
1057         edit_uint64_with_commas(mr.VolBytes, ec3),
1058         term_msg);
1059    }
1060    free_jcr(mjcr);
1061    return 1;
1062 }
1063
1064 static int create_jobmedia_record(B_DB *db, JCR *mjcr)
1065 {
1066    JOBMEDIA_DBR jmr;
1067    DCR *dcr = mjcr->dcr;
1068
1069    if (dev->state & ST_TAPE) {
1070       dcr->EndBlock = dev->EndBlock;
1071       dcr->EndFile  = dev->EndFile;
1072    } else {
1073       dcr->EndBlock = (uint32_t)dev->file_addr;
1074       dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
1075    }
1076
1077    memset(&jmr, 0, sizeof(jmr));
1078    jmr.JobId = mjcr->JobId;
1079    jmr.MediaId = mr.MediaId;
1080    jmr.FirstIndex = dcr->VolFirstIndex;
1081    jmr.LastIndex = dcr->FileIndex;
1082    jmr.StartFile = dcr->StartFile;
1083    jmr.EndFile = dcr->EndFile;
1084    jmr.StartBlock = dcr->StartBlock;
1085    jmr.EndBlock = dcr->EndBlock;
1086
1087
1088    if (!update_db) {
1089       return 1;
1090    }
1091
1092    if (!db_create_jobmedia_record(bjcr, db, &jmr)) {
1093       Pmsg1(0, _("Could not create JobMedia record. ERR=%s\n"), db_strerror(db));
1094       return 0;
1095    }
1096    if (verbose) {
1097       Pmsg2(000, _("Created JobMedia record JobId %d, MediaId %d\n"), 
1098                 jmr.JobId, jmr.MediaId);
1099    }
1100    return 1;
1101 }
1102
1103 /* 
1104  * Simulate the database call that updates the MD5/SHA1 record
1105  */
1106 static int update_SIG_record(B_DB *db, char *SIGbuf, DEV_RECORD *rec, int type)
1107 {
1108    JCR *mjcr;
1109
1110    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
1111    if (!mjcr) {
1112       if (mr.VolJobs > 0) {
1113          Pmsg2(000, _("Could not find SessId=%d SessTime=%d for MD5/SHA1 record.\n"),
1114                       rec->VolSessionId, rec->VolSessionTime);
1115       } else {
1116          ignored_msgs++;
1117       }
1118       return 0;
1119    }
1120
1121    if (!update_db) {
1122       free_jcr(mjcr);
1123       return 1;
1124    }
1125    
1126    if (!db_add_SIG_to_file_record(bjcr, db, mjcr->FileId, SIGbuf, type)) {
1127       Pmsg1(0, _("Could not add MD5/SHA1 to File record. ERR=%s\n"), db_strerror(db));
1128       free_jcr(mjcr);
1129       return 0;
1130    }
1131    if (verbose > 1) {
1132       Pmsg0(000, _("Updated MD5/SHA1 record\n"));
1133    }
1134    free_jcr(mjcr);
1135    return 1;
1136 }
1137
1138
1139 /* 
1140  * Create a JCR as if we are really starting the job
1141  */
1142 static JCR *create_jcr(JOB_DBR *jr, DEV_RECORD *rec, uint32_t JobId)
1143 {
1144    JCR *jobjcr;
1145    /*
1146     * Transfer as much as possible to the Job JCR. Most important is
1147     *   the JobId and the ClientId.
1148     */
1149    jobjcr = new_jcr(sizeof(JCR), bscan_free_jcr);
1150    jobjcr->JobType = jr->JobType;
1151    jobjcr->JobLevel = jr->JobLevel;
1152    jobjcr->JobStatus = jr->JobStatus;
1153    bstrncpy(jobjcr->Job, jr->Job, sizeof(jobjcr->Job));
1154    jobjcr->JobId = JobId;      /* this is JobId on tape */
1155    jobjcr->sched_time = jr->SchedTime;
1156    jobjcr->start_time = jr->StartTime;
1157    jobjcr->VolSessionId = rec->VolSessionId;
1158    jobjcr->VolSessionTime = rec->VolSessionTime;
1159    jobjcr->ClientId = jr->ClientId;
1160 // attach_jcr_to_device(dev, jobjcr);
1161    new_dcr(jobjcr, dev);
1162    return jobjcr;
1163 }
1164
1165 /* Dummies to replace askdir.c */
1166 bool    dir_get_volume_info(DCR *dcr, enum get_vol_info_rw  writing) { return 1;}
1167 bool    dir_find_next_appendable_volume(DCR *dcr) { return 1;}
1168 bool    dir_update_volume_info(DCR *dcr, bool relabel) { return 1; }
1169 bool    dir_create_jobmedia_record(DCR *dcr) { return 1; }
1170 bool    dir_ask_sysop_to_create_appendable_volume(DCR *dcr) { return 1; }
1171 bool    dir_update_file_attributes(DCR *dcr, DEV_RECORD *rec) { return 1;}
1172 bool    dir_send_job_status(JCR *jcr) {return 1;}
1173
1174
1175 bool dir_ask_sysop_to_mount_volume(DCR *dcr)
1176 {
1177    DEVICE *dev = dcr->dev;
1178    JCR *jcr = dcr->jcr;
1179    fprintf(stderr, _("Mount Volume \"%s\" on device \"%s\" and press return when ready: "),
1180       jcr->VolumeName, dev_name(dev));
1181    getchar();   
1182    return 1;
1183 }