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