]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/bscan.c
Make btape fill/unfill work
[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->VolFirstIndex = 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    /* Win32 Data stream */
630    } else if (rec->Stream == STREAM_WIN32_DATA) {
631       mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
632       if (!mjcr) {
633          if (mr.VolJobs > 0) {
634             Pmsg2(000, _("Could not find Job SessId=%d SessTime=%d for Win32 Data record.\n"),
635                          rec->VolSessionId, rec->VolSessionTime);
636          } else {
637             ignored_msgs++;
638          }
639          return;
640       }
641       mjcr->JobBytes += rec->data_len;
642       free_jcr(mjcr);                 /* done using JCR */
643
644    /* Win32 GZIP stream */
645    } else if (rec->Stream == STREAM_WIN32_GZIP_DATA) {
646       mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
647       if (!mjcr) {
648          if (mr.VolJobs > 0) {
649             Pmsg2(000, _("Could not find Job SessId=%d SessTime=%d for Win32 GZIP Data record.\n"),
650                          rec->VolSessionId, rec->VolSessionTime);
651          } else {
652             ignored_msgs++;
653          }
654          return;
655       }
656       mjcr->JobBytes += rec->data_len;
657       free_jcr(mjcr);                 /* done using JCR */
658
659    } else if (rec->Stream == STREAM_MD5_SIGNATURE) {
660       char MD5buf[50];
661       bin_to_base64(MD5buf, (char *)rec->data, 16); /* encode 16 bytes */
662       if (verbose > 1) {
663          Pmsg1(000, _("Got MD5 record: %s\n"), MD5buf);
664       }
665       update_SIG_record(db, MD5buf, rec, MD5_SIG);
666
667    } else if (rec->Stream == STREAM_SHA1_SIGNATURE) {
668       char SIGbuf[50];
669       bin_to_base64(SIGbuf, (char *)rec->data, 20); /* encode 20 bytes */
670       if (verbose > 1) {
671          Pmsg1(000, _("Got SHA1 record: %s\n"), SIGbuf);
672       }
673       update_SIG_record(db, SIGbuf, rec, SHA1_SIG);
674
675
676    } else if (rec->Stream == STREAM_PROGRAM_NAMES) {
677       if (verbose) {
678          Pmsg1(000, _("Got Prog Names Stream: %s\n"), rec->data);
679       }
680    } else if (rec->Stream == STREAM_PROGRAM_DATA) {
681       if (verbose > 1) {
682          Pmsg0(000, _("Got Prog Data Stream record.\n"));
683       }
684    } else {
685       Pmsg2(0, _("Unknown stream type!!! stream=%d data=%s\n"), rec->Stream, rec->data);
686    }
687    return;
688 }
689
690 /*
691  * Free the Job Control Record if no one is still using it.
692  *  Called from main free_jcr() routine in src/lib/jcr.c so
693  *  that we can do our Director specific cleanup of the jcr.
694  */
695 static void dird_free_jcr(JCR *jcr)
696 {
697    Dmsg0(200, "Start dird free_jcr\n");
698
699    if (jcr->file_bsock) {
700       Dmsg0(200, "Close File bsock\n");
701       bnet_close(jcr->file_bsock);
702    }
703    if (jcr->store_bsock) {
704       Dmsg0(200, "Close Store bsock\n");
705       bnet_close(jcr->store_bsock);
706    }
707    if (jcr->RestoreBootstrap) {
708       free(jcr->RestoreBootstrap);
709    }
710    Dmsg0(200, "End dird free_jcr\n");
711 }
712
713 /*
714  * We got a File Attributes record on the tape.  Now, lookup the Job
715  *   record, and then create the attributes record.
716  */
717 static int create_file_attributes_record(B_DB *db, JCR *mjcr,
718                                char *fname, char *lname, int type,
719                                char *ap, DEV_RECORD *rec)
720 {
721
722    ar.fname = fname;
723    ar.link = lname;
724    ar.ClientId = mjcr->ClientId;
725    ar.JobId = mjcr->JobId;
726    ar.Stream = rec->Stream;
727    ar.FileIndex = rec->FileIndex;
728    ar.attr = ap;
729    if (mjcr->VolFirstIndex == 0) {
730       mjcr->VolFirstIndex = rec->FileIndex;
731    }
732    mjcr->FileIndex = rec->FileIndex;
733    mjcr->JobFiles++;
734
735    if (!update_db) {
736       return 1;
737    }
738
739    if (!db_create_file_attributes_record(bjcr, db, &ar)) {
740       Pmsg1(0, _("Could not create File Attributes record. ERR=%s\n"), db_strerror(db));
741       return 0;
742    }
743    mjcr->FileId = ar.FileId;
744
745    if (verbose > 1) {
746       Pmsg1(000, _("Created File record: %s\n"), fname);   
747    }
748    return 1;
749 }
750
751 /*
752  * For each Volume we see, we create a Medium record
753  */
754 static int create_media_record(B_DB *db, MEDIA_DBR *mr, VOLUME_LABEL *vl)
755 {
756    struct date_time dt;
757    struct tm tm;
758
759    strcpy(mr->VolStatus, "Full");
760    mr->VolRetention = 365 * 3600 * 24; /* 1 year */
761    if (vl->VerNum >= 11) {
762       mr->FirstWritten = btime_to_utime(vl->write_btime);
763       mr->LabelDate    = btime_to_utime(vl->label_btime);
764    } else {
765       /* DEPRECATED DO NOT USE */
766       dt.julian_day_number = vl->write_date;
767       dt.julian_day_fraction = vl->write_time;
768       tm_decode(&dt, &tm);
769       mr->FirstWritten = mktime(&tm);
770       dt.julian_day_number = vl->label_date;
771       dt.julian_day_fraction = vl->label_time;
772       tm_decode(&dt, &tm);
773       mr->LabelDate = mktime(&tm);
774    }
775    lasttime = mr->LabelDate;
776
777    if (!update_db) {
778       return 1;
779    }
780
781    if (!db_create_media_record(bjcr, db, mr)) {
782       Pmsg1(0, _("Could not create media record. ERR=%s\n"), db_strerror(db));
783       return 0;
784    }
785    if (!db_update_media_record(bjcr, db, mr)) {
786       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
787       return 0;
788    }
789    if (verbose) {
790       Pmsg1(000, _("Created Media record for Volume: %s\n"), mr->VolumeName);
791    }
792    return 1;
793
794 }
795
796 /*
797  * Called at end of media to update it
798  */
799 static int update_media_record(B_DB *db, MEDIA_DBR *mr)
800 {
801    if (!update_db && !update_vol_info) {
802       return 1;
803    }
804
805    mr->LastWritten = lasttime;
806    if (!db_update_media_record(bjcr, db, mr)) {
807       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
808       return 0;
809    }
810    if (verbose) {
811       Pmsg1(000, _("Updated Media record at end of Volume: %s\n"), mr->VolumeName);
812    }
813    return 1;
814
815 }
816
817
818 static int create_pool_record(B_DB *db, POOL_DBR *pr)
819 {
820    pr->NumVols++;
821    pr->UseCatalog = 1;
822    pr->VolRetention = 355 * 3600 * 24; /* 1 year */
823
824    if (!update_db) {
825       return 1;
826    }
827    if (!db_create_pool_record(bjcr, db, pr)) {
828       Pmsg1(0, _("Could not create pool record. ERR=%s\n"), db_strerror(db));
829       return 0;
830    }
831    if (verbose) {
832       Pmsg1(000, _("Created Pool record for Pool: %s\n"), pr->Name);
833    }
834    return 1;
835
836 }
837
838
839 /*
840  * Called from SOS to create a client for the current Job 
841  */
842 static int create_client_record(B_DB *db, CLIENT_DBR *cr)
843 {
844    if (!update_db) {
845       return 1;
846    }
847    if (!db_create_client_record(bjcr, db, cr)) {
848       Pmsg1(0, _("Could not create Client record. ERR=%s\n"), db_strerror(db));
849       return 0;
850    }
851    if (verbose) {
852       Pmsg1(000, _("Created Client record for Client: %s\n"), cr->Name);
853    }
854    return 1;
855 }
856
857 static int create_fileset_record(B_DB *db, FILESET_DBR *fsr)
858 {
859    if (!update_db) {
860       return 1;
861    }
862    fsr->FileSetId = 0;
863    if (fsr->MD5[0] == 0) {
864       fsr->MD5[0] = ' ';              /* Equivalent to nothing */
865       fsr->MD5[1] = 0;
866    }
867    if (db_get_fileset_record(bjcr, db, fsr)) {
868       if (verbose) {
869          Pmsg1(000, _("Fileset \"%s\" already exists.\n"), fsr->FileSet);
870       }
871    } else {
872       if (!db_create_fileset_record(bjcr, db, fsr)) {
873          Pmsg2(0, _("Could not create FileSet record \"%s\". ERR=%s\n"), 
874             fsr->FileSet, db_strerror(db));
875          return 0;
876       }
877       if (verbose) {
878          Pmsg1(000, _("Created FileSet record \"%s\"\n"), fsr->FileSet);
879       }
880    }
881    return 1;
882 }
883
884 /*
885  * Simulate the two calls on the database to create
886  *  the Job record and to update it when the Job actually
887  *  begins running.
888  */
889 static JCR *create_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *label, 
890                              DEV_RECORD *rec)
891 {
892    JCR *mjcr;
893    struct date_time dt;
894    struct tm tm;
895
896    jr->JobId = label->JobId;
897    jr->Type = label->JobType;
898    jr->Level = label->JobLevel;
899    jr->JobStatus = JS_Created;
900    strcpy(jr->Name, label->JobName);
901    strcpy(jr->Job, label->Job);
902    if (label->VerNum >= 11) {
903       jr->SchedTime = btime_to_unix(label->write_btime);
904    } else {
905       dt.julian_day_number = label->write_date;
906       dt.julian_day_fraction = label->write_time;
907       tm_decode(&dt, &tm);
908       jr->SchedTime = mktime(&tm);
909    }
910
911    jr->StartTime = jr->SchedTime;
912    jr->JobTDate = (utime_t)jr->SchedTime;
913    jr->VolSessionId = rec->VolSessionId;
914    jr->VolSessionTime = rec->VolSessionTime;
915
916    /* Now create a JCR as if starting the Job */
917    mjcr = create_jcr(jr, rec, label->JobId);
918
919    if (!update_db) {
920       return mjcr;
921    }
922
923    /* This creates the bare essentials */
924    if (!db_create_job_record(bjcr, db, jr)) {
925       Pmsg1(0, _("Could not create JobId record. ERR=%s\n"), db_strerror(db));
926       return mjcr;
927    }
928
929    /* This adds the client, StartTime, JobTDate, ... */
930    if (!db_update_job_start_record(bjcr, db, jr)) {
931       Pmsg1(0, _("Could not update job start record. ERR=%s\n"), db_strerror(db));
932       return mjcr;
933    }
934    Pmsg2(000, _("Created new JobId=%u record for original JobId=%u\n"), jr->JobId, 
935          label->JobId);
936    mjcr->JobId = jr->JobId;           /* set new JobId */
937    return mjcr;
938 }
939
940 /* 
941  * Simulate the database call that updates the Job 
942  *  at Job termination time.
943  */
944 static int update_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *elabel,
945                               DEV_RECORD *rec)
946 {
947    struct date_time dt;
948    struct tm tm;
949    JCR *mjcr;
950
951    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
952    if (!mjcr) {
953       Pmsg2(000, _("Could not find SessId=%d SessTime=%d for EOS record.\n"),
954                    rec->VolSessionId, rec->VolSessionTime);
955       return 0;
956    }
957    if (elabel->VerNum >= 11) {
958       jr->EndTime = btime_to_unix(elabel->write_btime);
959    } else {
960       dt.julian_day_number = elabel->write_date;
961       dt.julian_day_fraction = elabel->write_time;
962       tm_decode(&dt, &tm);
963       jr->EndTime = mktime(&tm);
964    }
965    lasttime = jr->EndTime;
966    mjcr->end_time = jr->EndTime;
967
968    jr->JobId = mjcr->JobId;
969    jr->JobStatus = elabel->JobStatus;
970    mjcr->JobStatus = elabel->JobStatus;
971    jr->JobFiles = elabel->JobFiles;
972    jr->JobBytes = elabel->JobBytes;
973    jr->VolSessionId = rec->VolSessionId;
974    jr->VolSessionTime = rec->VolSessionTime;
975    jr->JobTDate = (utime_t)mjcr->start_time;
976    jr->ClientId = mjcr->ClientId;
977
978    if (!update_db) {
979       free_jcr(mjcr);
980       return 1;
981    }
982    
983    if (!db_update_job_end_record(bjcr, db, jr)) {
984       Pmsg2(0, _("Could not update JobId=%u record. ERR=%s\n"), jr->JobId,  db_strerror(db));
985       free_jcr(mjcr);
986       return 0;
987    }
988    if (verbose) {
989       Pmsg1(000, _("Updated Job termination record for new JobId=%u\n"), jr->JobId);
990    }
991    if (verbose > 1) {
992       char *term_msg;
993       static char term_code[70];
994       char sdt[50], edt[50];
995       char ec1[30], ec2[30], ec3[30];
996
997       switch (mjcr->JobStatus) {
998       case JS_Terminated:
999          term_msg = _("Backup OK");
1000          break;
1001       case JS_FatalError:
1002       case JS_ErrorTerminated:
1003          term_msg = _("*** Backup Error ***");
1004          break;
1005       case JS_Canceled:
1006          term_msg = _("Backup Canceled");
1007          break;
1008       default:
1009          term_msg = term_code;
1010          sprintf(term_code, _("Job Termination code: %d"), mjcr->JobStatus);
1011          break;
1012       }
1013       bstrftime(sdt, sizeof(sdt), mjcr->start_time);
1014       bstrftime(edt, sizeof(edt), mjcr->end_time);
1015       Pmsg14(000,  _("%s\n\
1016 JobId:                  %d\n\
1017 Job:                    %s\n\
1018 FileSet:                %s\n\
1019 Backup Level:           %s\n\
1020 Client:                 %s\n\
1021 Start time:             %s\n\
1022 End time:               %s\n\
1023 Files Written:          %s\n\
1024 Bytes Written:          %s\n\
1025 Volume Session Id:      %d\n\
1026 Volume Session Time:    %d\n\
1027 Last Volume Bytes:      %s\n\
1028 Termination:            %s\n\n"),
1029         edt,
1030         mjcr->JobId,
1031         mjcr->Job,
1032         mjcr->fileset_name,
1033         job_level_to_str(mjcr->JobLevel),
1034         mjcr->client_name,
1035         sdt,
1036         edt,
1037         edit_uint64_with_commas(mjcr->JobFiles, ec1),
1038         edit_uint64_with_commas(mjcr->JobBytes, ec2),
1039         mjcr->VolSessionId,
1040         mjcr->VolSessionTime,
1041         edit_uint64_with_commas(mr.VolBytes, ec3),
1042         term_msg);
1043    }
1044    free_jcr(mjcr);
1045    return 1;
1046 }
1047
1048 static int create_jobmedia_record(B_DB *db, JCR *mjcr)
1049 {
1050    JOBMEDIA_DBR jmr;
1051
1052    if (dev->state & ST_TAPE) {
1053       mjcr->EndBlock = dev->EndBlock;
1054       mjcr->EndFile  = dev->EndFile;
1055    } else {
1056       mjcr->EndBlock = (uint32_t)dev->file_addr;
1057       mjcr->EndFile = (uint32_t)(dev->file_addr >> 32);
1058    }
1059
1060    memset(&jmr, 0, sizeof(jmr));
1061    jmr.JobId = mjcr->JobId;
1062    jmr.MediaId = mr.MediaId;
1063    jmr.FirstIndex = mjcr->VolFirstIndex;
1064    jmr.LastIndex = mjcr->FileIndex;
1065    jmr.StartFile = mjcr->StartFile;
1066    jmr.EndFile = mjcr->EndFile;
1067    jmr.StartBlock = mjcr->StartBlock;
1068    jmr.EndBlock = mjcr->EndBlock;
1069
1070
1071    if (!update_db) {
1072       return 1;
1073    }
1074
1075    if (!db_create_jobmedia_record(bjcr, db, &jmr)) {
1076       Pmsg1(0, _("Could not create JobMedia record. ERR=%s\n"), db_strerror(db));
1077       return 0;
1078    }
1079    if (verbose) {
1080       Pmsg2(000, _("Created JobMedia record JobId %d, MediaId %d\n"), 
1081                 jmr.JobId, jmr.MediaId);
1082    }
1083    return 1;
1084 }
1085
1086 /* 
1087  * Simulate the database call that updates the MD5/SHA1 record
1088  */
1089 static int update_SIG_record(B_DB *db, char *SIGbuf, DEV_RECORD *rec, int type)
1090 {
1091    JCR *mjcr;
1092
1093    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
1094    if (!mjcr) {
1095       if (mr.VolJobs > 0) {
1096          Pmsg2(000, _("Could not find SessId=%d SessTime=%d for MD5/SHA1 record.\n"),
1097                       rec->VolSessionId, rec->VolSessionTime);
1098       } else {
1099          ignored_msgs++;
1100       }
1101       return 0;
1102    }
1103
1104    if (!update_db) {
1105       free_jcr(mjcr);
1106       return 1;
1107    }
1108    
1109    if (!db_add_SIG_to_file_record(bjcr, db, mjcr->FileId, SIGbuf, type)) {
1110       Pmsg1(0, _("Could not add MD5/SHA1 to File record. ERR=%s\n"), db_strerror(db));
1111       free_jcr(mjcr);
1112       return 0;
1113    }
1114    if (verbose > 1) {
1115       Pmsg0(000, _("Updated MD5/SHA1 record\n"));
1116    }
1117    free_jcr(mjcr);
1118    return 1;
1119 }
1120
1121
1122 /* 
1123  * Create a JCR as if we are really starting the job
1124  */
1125 static JCR *create_jcr(JOB_DBR *jr, DEV_RECORD *rec, uint32_t JobId)
1126 {
1127    JCR *jobjcr;
1128    /*
1129     * Transfer as much as possible to the Job JCR. Most important is
1130     *   the JobId and the ClientId.
1131     */
1132    jobjcr = new_jcr(sizeof(JCR), dird_free_jcr);
1133    jobjcr->JobType = jr->Type;
1134    jobjcr->JobLevel = jr->Level;
1135    jobjcr->JobStatus = jr->JobStatus;
1136    strcpy(jobjcr->Job, jr->Job);
1137    jobjcr->JobId = JobId;      /* this is JobId on tape */
1138    jobjcr->sched_time = jr->SchedTime;
1139    jobjcr->start_time = jr->StartTime;
1140    jobjcr->VolSessionId = rec->VolSessionId;
1141    jobjcr->VolSessionTime = rec->VolSessionTime;
1142    jobjcr->ClientId = jr->ClientId;
1143    attach_jcr_to_device(dev, jobjcr);
1144    return jobjcr;
1145 }
1146
1147 /* Dummies to replace askdir.c */
1148 int     dir_get_volume_info(JCR *jcr, int writing) { return 1;}
1149 int     dir_find_next_appendable_volume(JCR *jcr) { return 1;}
1150 int     dir_update_volume_info(JCR *jcr, VOLUME_CAT_INFO *vol, int relabel) { return 1; }
1151 int     dir_create_jobmedia_record(JCR *jcr) { return 1; }
1152 int     dir_ask_sysop_to_mount_next_volume(JCR *jcr, DEVICE *dev) { return 1; }
1153 int     dir_update_file_attributes(JCR *jcr, DEV_RECORD *rec) { return 1;}
1154 int     dir_send_job_status(JCR *jcr) {return 1;}
1155
1156
1157 int dir_ask_sysop_to_mount_volume(JCR *jcr, DEVICE *dev)
1158 {
1159    /*  
1160     * We are at the end of reading a tape. Now, we simulate handling
1161     *   the end of writing a tape by wiffling through the attached
1162     *   jcrs creating jobmedia records.
1163     */
1164    Dmsg1(100, "Walk attached jcrs. Volume=%s\n", dev->VolCatInfo.VolCatName);
1165    for (JCR *mjcr=NULL; (mjcr=next_attached_jcr(dev, mjcr)); ) {
1166       if (verbose) {
1167          Pmsg1(000, _("Create JobMedia for Job %s\n"), mjcr->Job);
1168       }
1169       if (dev->state & ST_TAPE) {
1170          mjcr->EndBlock = dev->EndBlock;
1171          mjcr->EndFile = dev->EndFile;
1172       } else {
1173          mjcr->EndBlock = (uint32_t)dev->file_addr;
1174          mjcr->StartBlock = (uint32_t)(dev->file_addr >> 32);
1175       }
1176       if (!create_jobmedia_record(db, mjcr)) {
1177          Pmsg2(000, _("Could not create JobMedia record for Volume=%s Job=%s\n"),
1178             dev->VolCatInfo.VolCatName, mjcr->Job);
1179       }
1180    }
1181
1182    fprintf(stderr, _("Mount Volume %s on device %s and press return when ready: "),
1183       jcr->VolumeName, dev_name(dev));
1184    getchar();   
1185    return 1;
1186 }