]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/bscan.c
d0c111cc5524bb99bdd273a33b9fab8168b98283
[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 "\nVersion: " VERSION " (" BDATE ")\n\n"
107 "Usage: bscan [ options ] <bacula-archive>\n"
108 "       -b bootstrap      specify a bootstrap file\n"
109 "       -c <file>         specify configuration file\n"
110 "       -d <nn>           set debug level to nn\n"
111 "       -m                update media info in database\n"
112 "       -n <name>         specify the database name (default bacula)\n"
113 "       -u <user>         specify database user name (default bacula)\n"
114 "       -P <password      specify database password (default none)\n"
115 "       -h <host>         specify database host (default NULL)\n"
116 "       -p                proceed inspite of I/O errors\n"
117 "       -r                list records\n"
118 "       -s                synchronize or store in database\n"
119 "       -v                verbose\n"
120 "       -V <Volumes>      specify Volume names (separated by |)\n"
121 "       -w <dir>          specify working directory (default from conf file)\n"
122 "       -?                print this message\n\n"));
123    exit(1);
124 }
125
126 int main (int argc, char *argv[])
127 {
128    int ch;
129    struct stat stat_buf;
130    char *VolumeName = NULL;
131
132    my_name_is(argc, argv, "bscan");
133    init_msg(NULL, NULL);
134
135
136    while ((ch = getopt(argc, argv, "b:c:d:h:mn:pP:rsu:vV:w:?")) != -1) {
137       switch (ch) {
138       case 'b':
139          bsr = parse_bsr(NULL, optarg);
140          break;
141
142       case 'c':                    /* specify config file */
143          if (configfile != NULL) {
144             free(configfile);
145          }
146          configfile = bstrdup(optarg);
147          break;
148
149       case 'd':                    /* debug level */
150          debug_level = atoi(optarg);
151          if (debug_level <= 0)
152             debug_level = 1; 
153          break;
154
155       case 'h':
156          db_host = optarg;
157          break;
158
159       case 'm':
160          update_vol_info = true;
161          break;
162
163       case 'n':
164          db_name = optarg;
165          break;
166
167       case 'u':
168          db_user = optarg;
169          break;
170
171       case 'P':
172          db_password = optarg;
173          break;
174
175       case 'p':
176          forge_on = true;
177          break;
178
179       case 'r':
180          list_records = true;
181          break;
182
183       case 's':
184          update_db = true;
185          break;
186
187       case 'v':
188          verbose++;
189          break;
190
191       case 'V':                    /* Volume name */
192          VolumeName = optarg;
193          break;
194
195       case 'w':
196          wd = optarg;
197          break;
198
199       case '?':
200       default:
201          usage();
202
203       }  
204    }
205    argc -= optind;
206    argv += optind;
207
208    if (argc != 1) {
209       Pmsg0(0, _("Wrong number of arguments: \n"));
210       usage();
211    }
212
213    if (configfile == NULL) {
214       configfile = bstrdup(CONFIG_FILE);
215    }
216
217    parse_config(configfile);
218    LockRes();
219    me = (STORES *)GetNextRes(R_STORAGE, NULL);
220    if (!me) {
221       UnlockRes();
222       Emsg1(M_ERROR_TERM, 0, _("No Storage resource defined in %s. Cannot continue.\n"), 
223          configfile);
224    }
225    UnlockRes();
226    /* Check if -w option given, otherwise use resource for working directory */
227    if (wd) { 
228       working_directory = wd;
229    } else if (!me->working_directory) {
230       Emsg1(M_ERROR_TERM, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
231          configfile);
232    } else {
233       working_directory = me->working_directory;
234    }
235
236    /* Check that working directory is good */
237    if (stat(working_directory, &stat_buf) != 0) {
238       Emsg1(M_ERROR_TERM, 0, _("Working Directory: %s not found. Cannot continue.\n"),
239          working_directory);
240    }
241    if (!S_ISDIR(stat_buf.st_mode)) {
242       Emsg1(M_ERROR_TERM, 0, _("Working Directory: %s is not a directory. Cannot continue.\n"),
243          working_directory);
244    }
245
246    bjcr = setup_jcr("bscan", argv[0], bsr, VolumeName);
247    dev = setup_to_access_device(bjcr, 1);   /* read device */
248    if (!dev) { 
249       exit(1);
250    }
251
252    if ((db=db_init_database(NULL, db_name, db_user, db_password, db_host, 0, NULL)) == NULL) {
253       Emsg0(M_ERROR_TERM, 0, _("Could not init Bacula database\n"));
254    }
255    if (!db_open_database(NULL, db)) {
256       Emsg0(M_ERROR_TERM, 0, db_strerror(db));
257    }
258    Dmsg0(200, "Database opened\n");
259    if (verbose) {
260       Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user);
261    }
262
263    do_scan();
264    printf("Records %sadded to catalog:\n%7d Media\n%7d Pool\n%7d Job\n%7d File\n",
265       update_db?"":"would have been ",
266       num_media, num_pools, num_jobs, num_files);
267
268    free_jcr(bjcr);
269    term_dev(dev);
270    return 0;
271 }
272   
273 /*  
274  * We are at the end of reading a tape. Now, we simulate handling
275  *   the end of writing a tape by wiffling through the attached
276  *   jcrs creating jobmedia records.
277  */
278 static bool bscan_mount_next_read_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
279 {
280    Dmsg1(100, "Walk attached jcrs. Volume=%s\n", dev->VolCatInfo.VolCatName);
281 #ifdef xxx
282    for (JCR *mjcr=NULL; (mjcr=next_attached_jcr(dev, mjcr)); ) {
283       DCR *dcr = mjcr->dcr;
284 #endif
285    DCR *dcr;
286    foreach_dlist(dcr, dev->attached_dcrs) {
287       JCR *mjcr = dcr->jcr;
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    /* we must once more detach ourselves (attached by mount_next ...) */
309    detach_jcr_from_device(dev, jcr); /* detach bscan jcr */
310    return stat;
311 }
312
313 static void do_scan()             
314 {
315    attr = new_attr();
316
317    memset(&ar, 0, sizeof(ar));
318    memset(&pr, 0, sizeof(pr));
319    memset(&jr, 0, sizeof(jr));
320    memset(&cr, 0, sizeof(cr));
321    memset(&fsr, 0, sizeof(fsr));
322    memset(&fr, 0, sizeof(fr));
323
324    /* Detach bscan's jcr as we are not a real Job on the tape */
325    detach_jcr_from_device(dev, bjcr);
326
327    read_records(bjcr->dcr, record_cb, bscan_mount_next_read_volume);
328    release_device(bjcr);
329
330    free_attr(attr);
331 }
332
333 /*
334  * Returns: true if OK
335  *          false if error
336  */
337 static bool record_cb(JCR *bjcr, DEVICE *dev, DEV_BLOCK *block, DEV_RECORD *rec)
338 {
339    JCR *mjcr;
340    DCR *dcr;
341    char ec1[30];
342
343    if (rec->data_len > 0) {
344       mr.VolBytes += rec->data_len + WRITE_RECHDR_LENGTH; /* Accumulate Volume bytes */
345    }
346    if (list_records) {
347       Pmsg5(000, _("Record: SessId=%u SessTim=%u FileIndex=%d Stream=%d len=%u\n"),
348             rec->VolSessionId, rec->VolSessionTime, rec->FileIndex, 
349             rec->Stream, rec->data_len);
350    }
351    /* 
352     * Check for Start or End of Session Record 
353     *
354     */
355    if (rec->FileIndex < 0) {
356       bool save_update_db = update_db;
357
358       if (verbose > 1) {
359          dump_label_record(dev, rec, 1);
360       }
361       switch (rec->FileIndex) {
362       case PRE_LABEL:
363          Pmsg0(000, _("Volume is prelabeled. This tape cannot be scanned.\n"));
364          return false;
365          break;
366
367       case VOL_LABEL:
368          unser_volume_label(dev, rec);
369          /* Check Pool info */
370          bstrncpy(pr.Name, dev->VolHdr.PoolName, sizeof(pr.Name));
371          bstrncpy(pr.PoolType, dev->VolHdr.PoolType, sizeof(pr.PoolType));
372          num_pools++;
373          if (db_get_pool_record(bjcr, db, &pr)) {
374             if (verbose) {
375                Pmsg1(000, _("Pool record for %s found in DB.\n"), pr.Name);
376             }
377          } else {
378             if (!update_db) {
379                Pmsg1(000, _("VOL_LABEL: Pool record not found for Pool: %s\n"),
380                   pr.Name);
381             }
382             create_pool_record(db, &pr);
383          }
384          if (strcmp(pr.PoolType, dev->VolHdr.PoolType) != 0) {
385             Pmsg2(000, _("VOL_LABEL: PoolType mismatch. DB=%s Vol=%s\n"),
386                pr.PoolType, dev->VolHdr.PoolType);
387             return true;
388          } else if (verbose) {
389             Pmsg1(000, _("Pool type \"%s\" is OK.\n"), pr.PoolType);
390          }
391
392          /* Check Media Info */
393          memset(&mr, 0, sizeof(mr));
394          bstrncpy(mr.VolumeName, dev->VolHdr.VolName, sizeof(mr.VolumeName));
395          mr.PoolId = pr.PoolId;
396          num_media++;
397          if (db_get_media_record(bjcr, db, &mr)) {
398             if (verbose) {
399                Pmsg1(000, _("Media record for %s found in DB.\n"), mr.VolumeName);
400             }
401             /* Clear out some volume statistics that will be updated */
402             mr.VolJobs = mr.VolFiles = mr.VolBlocks = 0;
403             mr.VolBytes = rec->data_len + 20;
404          } else {
405             if (!update_db) {
406                Pmsg1(000, _("VOL_LABEL: Media record not found for Volume: %s\n"),
407                   mr.VolumeName);
408             }
409             bstrncpy(mr.MediaType, dev->VolHdr.MediaType, sizeof(mr.MediaType));
410             create_media_record(db, &mr, &dev->VolHdr);
411          }
412          if (strcmp(mr.MediaType, dev->VolHdr.MediaType) != 0) {
413             Pmsg2(000, _("VOL_LABEL: MediaType mismatch. DB=%s Vol=%s\n"),
414                mr.MediaType, dev->VolHdr.MediaType);
415             return true;              /* ignore error */
416          } else if (verbose) {
417             Pmsg1(000, _("Media type \"%s\" is OK.\n"), mr.MediaType);
418          }
419          /* Reset some JCR variables */
420          for (mjcr=NULL; (mjcr=next_attached_jcr(dev, mjcr)); ) {
421             dcr = mjcr->dcr;
422             dcr->VolFirstIndex = dcr->FileIndex = 0;
423             dcr->StartBlock = dcr->EndBlock = 0;
424             dcr->StartFile = dcr->EndFile = 0;
425          }
426
427          Pmsg1(000, _("VOL_LABEL: OK for Volume: %s\n"), mr.VolumeName);
428          break;
429
430       case SOS_LABEL:
431          mr.VolJobs++;
432          num_jobs++;
433          if (ignored_msgs > 0) {
434             Pmsg1(000, _("%d \"errors\" ignored before first Start of Session record.\n"), 
435                   ignored_msgs);
436             ignored_msgs = 0;
437          }
438          unser_session_label(&label, rec);
439          memset(&jr, 0, sizeof(jr));
440          jr.JobId = label.JobId;
441          if (db_get_job_record(bjcr, db, &jr)) {
442             /* Job record already exists in DB */
443             update_db = false;  /* don't change db in create_job_record */
444             if (verbose) {
445                Pmsg1(000, _("SOS_LABEL: Found Job record for JobId: %d\n"), jr.JobId);
446             }
447          } else {
448             /* Must create a Job record in DB */
449             if (!update_db) {
450                Pmsg1(000, _("SOS_LABEL: Job record not found for JobId: %d\n"),
451                   jr.JobId);
452             }
453          }
454          /* Create Client record if not already there */
455             bstrncpy(cr.Name, label.ClientName, sizeof(cr.Name));
456             create_client_record(db, &cr);
457             jr.ClientId = cr.ClientId;
458
459          /* process label, if Job record exists don't update db */
460          mjcr = create_job_record(db, &jr, &label, rec);
461          dcr = mjcr->dcr;
462          update_db = save_update_db;
463
464          jr.PoolId = pr.PoolId;
465          /* Set start positions into JCR */
466          if (dev->state & ST_TAPE) {
467             /*
468              * Note, we have already advanced past current block,
469              *  so the correct number is block_num - 1 
470              */ 
471             dcr->StartBlock = dev->block_num - 1;
472             dcr->StartFile = dev->file;
473          } else {
474             dcr->StartBlock = (uint32_t)dev->file_addr;
475             dcr->StartFile = (uint32_t)(dev->file_addr >> 32);
476          }
477          mjcr->start_time = jr.StartTime;
478          mjcr->JobLevel = jr.JobLevel;
479
480          mjcr->client_name = get_pool_memory(PM_FNAME);
481          pm_strcpy(&mjcr->client_name, label.ClientName);
482          mjcr->pool_type = get_pool_memory(PM_FNAME);
483          pm_strcpy(&mjcr->pool_type, label.PoolType);
484          mjcr->fileset_name = get_pool_memory(PM_FNAME);
485          pm_strcpy(&mjcr->fileset_name, label.FileSetName);
486          mjcr->pool_name = get_pool_memory(PM_FNAME);
487          pm_strcpy(&mjcr->pool_name, label.PoolName);
488
489          if (rec->VolSessionId != jr.VolSessionId) {
490             Pmsg3(000, _("SOS_LABEL: VolSessId mismatch for JobId=%u. DB=%d Vol=%d\n"),
491                jr.JobId,
492                jr.VolSessionId, rec->VolSessionId);
493             return true;              /* ignore error */
494          }
495          if (rec->VolSessionTime != jr.VolSessionTime) {
496             Pmsg3(000, _("SOS_LABEL: VolSessTime mismatch for JobId=%u. DB=%d Vol=%d\n"),
497                jr.JobId,
498                jr.VolSessionTime, rec->VolSessionTime);
499             return true;              /* ignore error */
500          }
501          if (jr.PoolId != pr.PoolId) {
502             Pmsg3(000, _("SOS_LABEL: PoolId mismatch for JobId=%u. DB=%d Vol=%d\n"),
503                jr.JobId,
504                jr.PoolId, pr.PoolId);
505             return true;              /* ignore error */
506          }
507          break;
508
509       case EOS_LABEL:
510          unser_session_label(&elabel, rec);
511
512          /* Create FileSet record */
513          bstrncpy(fsr.FileSet, label.FileSetName, sizeof(fsr.FileSet));
514          bstrncpy(fsr.MD5, label.FileSetMD5, sizeof(fsr.MD5));
515          create_fileset_record(db, &fsr);
516          jr.FileSetId = fsr.FileSetId;
517
518          mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
519          if (!mjcr) {
520             Pmsg2(000, _("Could not find SessId=%d SessTime=%d for EOS record.\n"),
521                   rec->VolSessionId, rec->VolSessionTime);
522             break;
523          }
524
525          /* Do the final update to the Job record */
526          update_job_record(db, &jr, &elabel, rec);
527
528          mjcr->end_time = jr.EndTime;
529          mjcr->JobStatus = JS_Terminated;
530
531          /* Create JobMedia record */
532          create_jobmedia_record(db, mjcr);
533          detach_jcr_from_device(dev, mjcr);
534          free_jcr(mjcr);
535
536          break;
537
538       case EOM_LABEL:
539          break;
540
541       case EOT_LABEL:              /* end of all tapes */
542          /* 
543           * Wiffle through all jobs still open and close
544           *   them.
545           */
546          if (update_db) {
547             mjcr=next_attached_jcr(dev, NULL);
548             for ( ; mjcr; ) {
549                JCR *njcr; 
550                jr.JobId = mjcr->JobId;
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                njcr = mjcr->next_dev;
562                free_jcr(mjcr);
563                mjcr = njcr;
564             }
565          }
566          mr.VolFiles = rec->File;
567          mr.VolBlocks = rec->Block;
568          mr.VolBytes += mr.VolBlocks * WRITE_BLKHDR_LENGTH; /* approx. */
569          mr.VolMounts++;
570          update_media_record(db, &mr);
571          Pmsg3(0, _("End of all Volumes. VolFiles=%u VolBlocks=%u VolBytes=%s\n"), mr.VolFiles,
572                     mr.VolBlocks, edit_uint64_with_commas(mr.VolBytes, ec1));
573          break;
574       default:
575          break;
576       } /* end switch */
577       return true;
578    }
579
580    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
581    if (!mjcr) {
582       if (mr.VolJobs > 0) {
583          Pmsg2(000, _("Could not find Job for SessId=%d SessTime=%d record.\n"),
584                       rec->VolSessionId, rec->VolSessionTime);
585       } else {
586          ignored_msgs++;
587       }
588       return true;
589    }
590    dcr = mjcr->dcr;
591    if (dcr->VolFirstIndex == 0) {
592       dcr->VolFirstIndex = block->FirstIndex;
593    }
594
595    /* File Attributes stream */
596    switch (rec->Stream) {
597    case STREAM_UNIX_ATTRIBUTES:   
598    case STREAM_UNIX_ATTRIBUTES_EX:  
599
600       if (!unpack_attributes_record(bjcr, rec->Stream, rec->data, attr)) {
601          Emsg0(M_ERROR_TERM, 0, _("Cannot continue.\n"));
602       }
603
604       if (attr->file_index != rec->FileIndex) {
605          Emsg2(M_ERROR_TERM, 0, _("Record header file index %ld not equal record index %ld\n"),
606             rec->FileIndex, attr->file_index);
607       }
608        
609       if (verbose > 1) {
610          decode_stat(attr->attr, &attr->statp, &attr->LinkFI);
611          build_attr_output_fnames(bjcr, attr);
612          print_ls_output(bjcr, attr);
613       }
614       fr.JobId = mjcr->JobId;
615       fr.FileId = 0;
616       num_files++;
617       if (verbose && (num_files & 0x7FFF) == 0) {
618          char ed1[30], ed2[30], ed3[30], ed4[30];
619          Pmsg4(000, _("%s file records. At file:blk=%s:%s bytes=%s\n"),
620                      edit_uint64_with_commas(num_files, ed1),
621                      edit_uint64_with_commas(rec->File, ed2),
622                      edit_uint64_with_commas(rec->Block, ed3),
623                      edit_uint64_with_commas(mr.VolBytes, ed4));
624       } 
625       if (db_get_file_attributes_record(bjcr, db, attr->fname, NULL, &fr)) {
626          if (verbose > 1) {
627             Pmsg1(000, _("File record already exists for: %s\n"), attr->fname);
628          }
629       } else {
630          create_file_attributes_record(db, mjcr, attr->fname, attr->lname, 
631             attr->type, attr->attr, rec);
632       }
633       free_jcr(mjcr);
634       break;
635
636    /* Data stream */
637    case STREAM_WIN32_DATA:
638    case STREAM_FILE_DATA:
639    case STREAM_SPARSE_DATA:
640       mjcr->JobBytes += rec->data_len;
641       if (rec->Stream == STREAM_SPARSE_DATA) {
642          mjcr->JobBytes -= sizeof(uint64_t);
643       }
644          
645       free_jcr(mjcr);                 /* done using JCR */
646       break;
647
648    case STREAM_GZIP_DATA:
649       mjcr->JobBytes += rec->data_len; /* No correct, we should expand it */
650       free_jcr(mjcr);                 /* done using JCR */
651       break;
652
653    case STREAM_SPARSE_GZIP_DATA:
654       mjcr->JobBytes += rec->data_len - sizeof(uint64_t); /* No correct, we should expand it */
655       free_jcr(mjcr);                 /* done using JCR */
656       break;
657
658    /* Win32 GZIP stream */
659    case STREAM_WIN32_GZIP_DATA:
660       mjcr->JobBytes += rec->data_len;
661       free_jcr(mjcr);                 /* done using JCR */
662       break;
663
664    case STREAM_MD5_SIGNATURE:
665       char MD5buf[50];
666       bin_to_base64(MD5buf, (char *)rec->data, 16); /* encode 16 bytes */
667       if (verbose > 1) {
668          Pmsg1(000, _("Got MD5 record: %s\n"), MD5buf);
669       }
670       update_SIG_record(db, MD5buf, rec, MD5_SIG);
671       break;
672
673    case STREAM_SHA1_SIGNATURE:
674       char SIGbuf[50];
675       bin_to_base64(SIGbuf, (char *)rec->data, 20); /* encode 20 bytes */
676       if (verbose > 1) {
677          Pmsg1(000, _("Got SHA1 record: %s\n"), SIGbuf);
678       }
679       update_SIG_record(db, SIGbuf, rec, SHA1_SIG);
680       break;
681
682
683    case STREAM_PROGRAM_NAMES:
684       if (verbose) {
685          Pmsg1(000, _("Got Prog Names Stream: %s\n"), rec->data);
686       }
687       break;
688
689    case STREAM_PROGRAM_DATA:
690       if (verbose > 1) {
691          Pmsg0(000, _("Got Prog Data Stream record.\n"));
692       }
693       break;
694    default:
695       Pmsg2(0, _("Unknown stream type!!! stream=%d data=%s\n"), rec->Stream, rec->data);
696       break;
697    }
698    return true;
699 }
700
701 /*
702  * Free the Job Control Record if no one is still using it.
703  *  Called from main free_jcr() routine in src/lib/jcr.c so
704  *  that we can do our Director specific cleanup of the jcr.
705  */
706 static void bscan_free_jcr(JCR *jcr)
707 {
708    Dmsg0(200, "Start dird free_jcr\n");
709
710    if (jcr->file_bsock) {
711       Dmsg0(200, "Close File bsock\n");
712       bnet_close(jcr->file_bsock);
713    }
714    if (jcr->store_bsock) {
715       Dmsg0(200, "Close Store bsock\n");
716       bnet_close(jcr->store_bsock);
717    }
718    if (jcr->RestoreBootstrap) {
719       free(jcr->RestoreBootstrap);
720    }
721    if (jcr->dcr) {
722       free_dcr(jcr->dcr);
723       jcr->dcr = NULL;
724    }
725    Dmsg0(200, "End dird free_jcr\n");
726 }
727
728 /*
729  * We got a File Attributes record on the tape.  Now, lookup the Job
730  *   record, and then create the attributes record.
731  */
732 static int create_file_attributes_record(B_DB *db, JCR *mjcr,
733                                char *fname, char *lname, int type,
734                                char *ap, DEV_RECORD *rec)
735 {
736    DCR *dcr = mjcr->dcr;
737    ar.fname = fname;
738    ar.link = lname;
739    ar.ClientId = mjcr->ClientId;
740    ar.JobId = mjcr->JobId;
741    ar.Stream = rec->Stream;
742    ar.FileIndex = rec->FileIndex;
743    ar.attr = ap;
744    if (dcr->VolFirstIndex == 0) {
745       dcr->VolFirstIndex = rec->FileIndex;
746    }
747    dcr->FileIndex = rec->FileIndex;
748    mjcr->JobFiles++;
749
750    if (!update_db) {
751       return 1;
752    }
753
754    if (!db_create_file_attributes_record(bjcr, db, &ar)) {
755       Pmsg1(0, _("Could not create File Attributes record. ERR=%s\n"), db_strerror(db));
756       return 0;
757    }
758    mjcr->FileId = ar.FileId;
759
760    if (verbose > 1) {
761       Pmsg1(000, _("Created File record: %s\n"), fname);   
762    }
763    return 1;
764 }
765
766 /*
767  * For each Volume we see, we create a Medium record
768  */
769 static int create_media_record(B_DB *db, MEDIA_DBR *mr, VOLUME_LABEL *vl)
770 {
771    struct date_time dt;
772    struct tm tm;
773
774    /* We mark Vols as Archive to keep them from being re-written */
775    bstrncpy(mr->VolStatus, "Archive", sizeof(mr->VolStatus));
776    mr->VolRetention = 365 * 3600 * 24; /* 1 year */
777    if (vl->VerNum >= 11) {
778       mr->FirstWritten = btime_to_utime(vl->write_btime);
779       mr->LabelDate    = btime_to_utime(vl->label_btime);
780    } else {
781       /* DEPRECATED DO NOT USE */
782       dt.julian_day_number = vl->write_date;
783       dt.julian_day_fraction = vl->write_time;
784       tm_decode(&dt, &tm);
785       mr->FirstWritten = mktime(&tm);
786       dt.julian_day_number = vl->label_date;
787       dt.julian_day_fraction = vl->label_time;
788       tm_decode(&dt, &tm);
789       mr->LabelDate = mktime(&tm);
790    }
791    lasttime = mr->LabelDate;
792
793    if (!update_db) {
794       return 1;
795    }
796
797    if (!db_create_media_record(bjcr, db, mr)) {
798       Pmsg1(0, _("Could not create media record. ERR=%s\n"), db_strerror(db));
799       return 0;
800    }
801    if (!db_update_media_record(bjcr, db, mr)) {
802       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
803       return 0;
804    }
805    if (verbose) {
806       Pmsg1(000, _("Created Media record for Volume: %s\n"), mr->VolumeName);
807    }
808    return 1;
809
810 }
811
812 /*
813  * Called at end of media to update it
814  */
815 static bool update_media_record(B_DB *db, MEDIA_DBR *mr)
816 {
817    if (!update_db && !update_vol_info) {
818       return true;
819    }
820
821    mr->LastWritten = lasttime;
822    if (!db_update_media_record(bjcr, db, mr)) {
823       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
824       return false;;
825    }
826    if (verbose) {
827       Pmsg1(000, _("Updated Media record at end of Volume: %s\n"), mr->VolumeName);
828    }
829    return true;
830
831 }
832
833
834 static int create_pool_record(B_DB *db, POOL_DBR *pr)
835 {
836    pr->NumVols++;
837    pr->UseCatalog = 1;
838    pr->VolRetention = 355 * 3600 * 24; /* 1 year */
839
840    if (!update_db) {
841       return 1;
842    }
843    if (!db_create_pool_record(bjcr, db, pr)) {
844       Pmsg1(0, _("Could not create pool record. ERR=%s\n"), db_strerror(db));
845       return 0;
846    }
847    if (verbose) {
848       Pmsg1(000, _("Created Pool record for Pool: %s\n"), pr->Name);
849    }
850    return 1;
851
852 }
853
854
855 /*
856  * Called from SOS to create a client for the current Job 
857  */
858 static int create_client_record(B_DB *db, CLIENT_DBR *cr)
859 {
860    if (!update_db) {
861       return 1;
862    }
863    if (!db_create_client_record(bjcr, db, cr)) {
864       Pmsg1(0, _("Could not create Client record. ERR=%s\n"), db_strerror(db));
865       return 0;
866    }
867    if (verbose) {
868       Pmsg1(000, _("Created Client record for Client: %s\n"), cr->Name);
869    }
870    return 1;
871 }
872
873 static int create_fileset_record(B_DB *db, FILESET_DBR *fsr)
874 {
875    if (!update_db) {
876       return 1;
877    }
878    fsr->FileSetId = 0;
879    if (fsr->MD5[0] == 0) {
880       fsr->MD5[0] = ' ';              /* Equivalent to nothing */
881       fsr->MD5[1] = 0;
882    }
883    if (db_get_fileset_record(bjcr, db, fsr)) {
884       if (verbose) {
885          Pmsg1(000, _("Fileset \"%s\" already exists.\n"), fsr->FileSet);
886       }
887    } else {
888       if (!db_create_fileset_record(bjcr, db, fsr)) {
889          Pmsg2(0, _("Could not create FileSet record \"%s\". ERR=%s\n"), 
890             fsr->FileSet, db_strerror(db));
891          return 0;
892       }
893       if (verbose) {
894          Pmsg1(000, _("Created FileSet record \"%s\"\n"), fsr->FileSet);
895       }
896    }
897    return 1;
898 }
899
900 /*
901  * Simulate the two calls on the database to create
902  *  the Job record and to update it when the Job actually
903  *  begins running.
904  */
905 static JCR *create_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *label, 
906                              DEV_RECORD *rec)
907 {
908    JCR *mjcr;
909    struct date_time dt;
910    struct tm tm;
911
912    jr->JobId = label->JobId;
913    jr->JobType = label->JobType;
914    jr->JobLevel = label->JobLevel;
915    jr->JobStatus = JS_Created;
916    bstrncpy(jr->Name, label->JobName, sizeof(jr->Name));
917    bstrncpy(jr->Job, label->Job, sizeof(jr->Job));
918    if (label->VerNum >= 11) {
919       jr->SchedTime = btime_to_unix(label->write_btime);
920    } else {
921       dt.julian_day_number = label->write_date;
922       dt.julian_day_fraction = label->write_time;
923       tm_decode(&dt, &tm);
924       jr->SchedTime = mktime(&tm);
925    }
926
927    jr->StartTime = jr->SchedTime;
928    jr->JobTDate = (utime_t)jr->SchedTime;
929    jr->VolSessionId = rec->VolSessionId;
930    jr->VolSessionTime = rec->VolSessionTime;
931
932    /* Now create a JCR as if starting the Job */
933    mjcr = create_jcr(jr, rec, label->JobId);
934
935    if (!update_db) {
936       return mjcr;
937    }
938
939    /* This creates the bare essentials */
940    if (!db_create_job_record(bjcr, db, jr)) {
941       Pmsg1(0, _("Could not create JobId record. ERR=%s\n"), db_strerror(db));
942       return mjcr;
943    }
944
945    /* This adds the client, StartTime, JobTDate, ... */
946    if (!db_update_job_start_record(bjcr, db, jr)) {
947       Pmsg1(0, _("Could not update job start record. ERR=%s\n"), db_strerror(db));
948       return mjcr;
949    }
950    Pmsg2(000, _("Created new JobId=%u record for original JobId=%u\n"), jr->JobId, 
951          label->JobId);
952    mjcr->JobId = jr->JobId;           /* set new JobId */
953    return mjcr;
954 }
955
956 /* 
957  * Simulate the database call that updates the Job 
958  *  at Job termination time.
959  */
960 static int update_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *elabel,
961                               DEV_RECORD *rec)
962 {
963    struct date_time dt;
964    struct tm tm;
965    JCR *mjcr;
966
967    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
968    if (!mjcr) {
969       Pmsg2(000, _("Could not find SessId=%d SessTime=%d for EOS record.\n"),
970                    rec->VolSessionId, rec->VolSessionTime);
971       return 0;
972    }
973    if (elabel->VerNum >= 11) {
974       jr->EndTime = btime_to_unix(elabel->write_btime);
975    } else {
976       dt.julian_day_number = elabel->write_date;
977       dt.julian_day_fraction = elabel->write_time;
978       tm_decode(&dt, &tm);
979       jr->EndTime = mktime(&tm);
980    }
981    lasttime = jr->EndTime;
982    mjcr->end_time = jr->EndTime;
983
984    jr->JobId = mjcr->JobId;
985    jr->JobStatus = elabel->JobStatus;
986    mjcr->JobStatus = elabel->JobStatus;
987    jr->JobFiles = elabel->JobFiles;
988    jr->JobBytes = elabel->JobBytes;
989    jr->VolSessionId = rec->VolSessionId;
990    jr->VolSessionTime = rec->VolSessionTime;
991    jr->JobTDate = (utime_t)mjcr->start_time;
992    jr->ClientId = mjcr->ClientId;
993
994    if (!update_db) {
995       free_jcr(mjcr);
996       return 1;
997    }
998    
999    if (!db_update_job_end_record(bjcr, db, jr)) {
1000       Pmsg2(0, _("Could not update JobId=%u record. ERR=%s\n"), jr->JobId,  db_strerror(db));
1001       free_jcr(mjcr);
1002       return 0;
1003    }
1004    if (verbose) {
1005       Pmsg1(000, _("Updated Job termination record for new JobId=%u\n"), jr->JobId);
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 }