]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/bscan.c
Add more DCRs
[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 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 #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 int update_db = 0;
89 static int update_vol_info = 0;
90 static int list_records = 0;
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 = 1;
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 = 1;
181          break;
182
183       case 's':
184          update_db = 1;
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 added to catalog:\n%7d Media\n%7d Pool\n%7d Job\n%7d File\n",
265       num_media, num_pools, num_jobs, num_files);
266
267    free_jcr(bjcr);
268    return 0;
269 }
270   
271 /*  
272  * We are at the end of reading a tape. Now, we simulate handling
273  *   the end of writing a tape by wiffling through the attached
274  *   jcrs creating jobmedia records.
275  */
276 static bool bscan_mount_next_read_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
277 {
278    Dmsg1(100, "Walk attached jcrs. Volume=%s\n", dev->VolCatInfo.VolCatName);
279    for (JCR *mjcr=NULL; (mjcr=next_attached_jcr(dev, mjcr)); ) {
280       DCR *dcr = mjcr->dcr;
281       if (verbose) {
282          Pmsg1(000, _("Create JobMedia for Job %s\n"), mjcr->Job);
283       }
284       if (dev->state & ST_TAPE) {
285          dcr->EndBlock = dev->EndBlock;
286          dcr->EndFile = dev->EndFile;
287       } else {
288          dcr->EndBlock = (uint32_t)dev->file_addr;
289          dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
290       }
291       if (!create_jobmedia_record(db, mjcr)) {
292          Pmsg2(000, _("Could not create JobMedia record for Volume=%s Job=%s\n"),
293             dev->VolCatInfo.VolCatName, mjcr->Job);
294       }
295    }  
296    /* Now let common read routine get up next tape. Note,
297     * we call mount_next... with bscan's jcr because that is where we
298     * have the Volume list, but we get attached.
299     */
300    bool stat = mount_next_read_volume(jcr, dev, block);
301    /* we must once more detach ourselves (attached by mount_next ...) */
302    detach_jcr_from_device(dev, jcr); /* detach bscan jcr */
303    return stat;
304 }
305
306 static void do_scan()             
307 {
308    attr = new_attr();
309
310    memset(&ar, 0, sizeof(ar));
311    memset(&pr, 0, sizeof(pr));
312    memset(&jr, 0, sizeof(jr));
313    memset(&cr, 0, sizeof(cr));
314    memset(&fsr, 0, sizeof(fsr));
315    memset(&fr, 0, sizeof(fr));
316
317    /* Detach bscan's jcr as we are not a real Job on the tape */
318    detach_jcr_from_device(dev, bjcr);
319
320    read_records(bjcr, dev, record_cb, bscan_mount_next_read_volume);
321    release_device(bjcr);
322
323    free_attr(attr);
324    term_dev(dev);
325 }
326
327 /*
328  * Returns: true if OK
329  *          false if error
330  */
331 static bool record_cb(JCR *bjcr, DEVICE *dev, DEV_BLOCK *block, DEV_RECORD *rec)
332 {
333    JCR *mjcr;
334    DCR *dcr;
335    char ec1[30];
336
337    if (rec->data_len > 0) {
338       mr.VolBytes += rec->data_len + WRITE_RECHDR_LENGTH; /* Accumulate Volume bytes */
339    }
340    if (list_records) {
341       Pmsg5(000, _("Record: SessId=%u SessTim=%u FileIndex=%d Stream=%d len=%u\n"),
342             rec->VolSessionId, rec->VolSessionTime, rec->FileIndex, 
343             rec->Stream, rec->data_len);
344    }
345    /* 
346     * Check for Start or End of Session Record 
347     *
348     */
349    if (rec->FileIndex < 0) {
350       int save_update_db = update_db;
351
352       if (verbose > 1) {
353          dump_label_record(dev, rec, 1);
354       }
355       switch (rec->FileIndex) {
356       case PRE_LABEL:
357          Pmsg0(000, _("Volume is prelabeled. This tape cannot be scanned.\n"));
358          return false;
359          break;
360
361       case VOL_LABEL:
362          unser_volume_label(dev, rec);
363          /* Check Pool info */
364          bstrncpy(pr.Name, dev->VolHdr.PoolName, sizeof(pr.Name));
365          bstrncpy(pr.PoolType, dev->VolHdr.PoolType, sizeof(pr.PoolType));
366          num_pools++;
367          if (db_get_pool_record(bjcr, db, &pr)) {
368             if (verbose) {
369                Pmsg1(000, _("Pool record for %s found in DB.\n"), pr.Name);
370             }
371          } else {
372             if (!update_db) {
373                Pmsg1(000, _("VOL_LABEL: Pool record not found for Pool: %s\n"),
374                   pr.Name);
375             }
376             create_pool_record(db, &pr);
377          }
378          if (strcmp(pr.PoolType, dev->VolHdr.PoolType) != 0) {
379             Pmsg2(000, _("VOL_LABEL: PoolType mismatch. DB=%s Vol=%s\n"),
380                pr.PoolType, dev->VolHdr.PoolType);
381             return true;
382          } else if (verbose) {
383             Pmsg1(000, _("Pool type \"%s\" is OK.\n"), pr.PoolType);
384          }
385
386          /* Check Media Info */
387          memset(&mr, 0, sizeof(mr));
388          bstrncpy(mr.VolumeName, dev->VolHdr.VolName, sizeof(mr.VolumeName));
389          mr.PoolId = pr.PoolId;
390          num_media++;
391          if (db_get_media_record(bjcr, db, &mr)) {
392             if (verbose) {
393                Pmsg1(000, _("Media record for %s found in DB.\n"), mr.VolumeName);
394             }
395             /* Clear out some volume statistics that will be updated */
396             mr.VolJobs = mr.VolFiles = mr.VolBlocks = 0;
397             mr.VolBytes = rec->data_len + 20;
398          } else {
399             if (!update_db) {
400                Pmsg1(000, _("VOL_LABEL: Media record not found for Volume: %s\n"),
401                   mr.VolumeName);
402             }
403             bstrncpy(mr.MediaType, dev->VolHdr.MediaType, sizeof(mr.MediaType));
404             create_media_record(db, &mr, &dev->VolHdr);
405          }
406          if (strcmp(mr.MediaType, dev->VolHdr.MediaType) != 0) {
407             Pmsg2(000, _("VOL_LABEL: MediaType mismatch. DB=%s Vol=%s\n"),
408                mr.MediaType, dev->VolHdr.MediaType);
409             return true;              /* ignore error */
410          } else if (verbose) {
411             Pmsg1(000, _("Media type \"%s\" is OK.\n"), mr.MediaType);
412          }
413          /* Reset some JCR variables */
414          for (mjcr=NULL; (mjcr=next_attached_jcr(dev, mjcr)); ) {
415             dcr = mjcr->dcr;
416             dcr->VolFirstIndex = dcr->FileIndex = 0;
417             dcr->StartBlock = dcr->EndBlock = 0;
418             dcr->StartFile = dcr->EndFile = 0;
419          }
420
421          Pmsg1(000, _("VOL_LABEL: OK for Volume: %s\n"), mr.VolumeName);
422          break;
423
424       case SOS_LABEL:
425          mr.VolJobs++;
426          num_jobs++;
427          if (ignored_msgs > 0) {
428             Pmsg1(000, _("%d \"errors\" ignored before first Start of Session record.\n"), 
429                   ignored_msgs);
430             ignored_msgs = 0;
431          }
432          unser_session_label(&label, rec);
433          memset(&jr, 0, sizeof(jr));
434          jr.JobId = label.JobId;
435          if (db_get_job_record(bjcr, db, &jr)) {
436             /* Job record already exists in DB */
437             update_db = 0;  /* don't change db in create_job_record */
438             if (verbose) {
439                Pmsg1(000, _("SOS_LABEL: Found Job record for JobId: %d\n"), jr.JobId);
440             }
441          } else {
442             /* Must create a Job record in DB */
443             if (!update_db) {
444                Pmsg1(000, _("SOS_LABEL: Job record not found for JobId: %d\n"),
445                   jr.JobId);
446             }
447          }
448          /* Create Client record if not already there */
449             bstrncpy(cr.Name, label.ClientName, sizeof(cr.Name));
450             create_client_record(db, &cr);
451             jr.ClientId = cr.ClientId;
452
453          /* process label, if Job record exists don't update db */
454          mjcr = create_job_record(db, &jr, &label, rec);
455          dcr = mjcr->dcr;
456          update_db = save_update_db;
457
458          jr.PoolId = pr.PoolId;
459          /* Set start positions into JCR */
460          if (dev->state & ST_TAPE) {
461             /*
462              * Note, we have already advanced past current block,
463              *  so the correct number is block_num - 1 
464              */ 
465             dcr->StartBlock = dev->block_num - 1;
466             dcr->StartFile = dev->file;
467          } else {
468             dcr->StartBlock = (uint32_t)dev->file_addr;
469             dcr->StartFile = (uint32_t)(dev->file_addr >> 32);
470          }
471          mjcr->start_time = jr.StartTime;
472          mjcr->JobLevel = jr.JobLevel;
473
474          mjcr->client_name = get_pool_memory(PM_FNAME);
475          pm_strcpy(&mjcr->client_name, label.ClientName);
476          mjcr->pool_type = get_pool_memory(PM_FNAME);
477          pm_strcpy(&mjcr->pool_type, label.PoolType);
478          mjcr->fileset_name = get_pool_memory(PM_FNAME);
479          pm_strcpy(&mjcr->fileset_name, label.FileSetName);
480          mjcr->pool_name = get_pool_memory(PM_FNAME);
481          pm_strcpy(&mjcr->pool_name, label.PoolName);
482
483          if (rec->VolSessionId != jr.VolSessionId) {
484             Pmsg3(000, _("SOS_LABEL: VolSessId mismatch for JobId=%u. DB=%d Vol=%d\n"),
485                jr.JobId,
486                jr.VolSessionId, rec->VolSessionId);
487             return true;              /* ignore error */
488          }
489          if (rec->VolSessionTime != jr.VolSessionTime) {
490             Pmsg3(000, _("SOS_LABEL: VolSessTime mismatch for JobId=%u. DB=%d Vol=%d\n"),
491                jr.JobId,
492                jr.VolSessionTime, rec->VolSessionTime);
493             return true;              /* ignore error */
494          }
495          if (jr.PoolId != pr.PoolId) {
496             Pmsg3(000, _("SOS_LABEL: PoolId mismatch for JobId=%u. DB=%d Vol=%d\n"),
497                jr.JobId,
498                jr.PoolId, pr.PoolId);
499             return true;              /* ignore error */
500          }
501          break;
502
503       case EOS_LABEL:
504          unser_session_label(&elabel, rec);
505
506          /* Create FileSet record */
507          bstrncpy(fsr.FileSet, label.FileSetName, sizeof(fsr.FileSet));
508          bstrncpy(fsr.MD5, label.FileSetMD5, sizeof(fsr.MD5));
509          create_fileset_record(db, &fsr);
510          jr.FileSetId = fsr.FileSetId;
511
512          mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
513          if (!mjcr) {
514             Pmsg2(000, _("Could not find SessId=%d SessTime=%d for EOS record.\n"),
515                   rec->VolSessionId, rec->VolSessionTime);
516             break;
517          }
518
519          /* Do the final update to the Job record */
520          update_job_record(db, &jr, &elabel, rec);
521
522          mjcr->end_time = jr.EndTime;
523          mjcr->JobStatus = JS_Terminated;
524
525          /* Create JobMedia record */
526          create_jobmedia_record(db, mjcr);
527          detach_jcr_from_device(dev, mjcr);
528          free_jcr(mjcr);
529
530          break;
531
532       case EOM_LABEL:
533          break;
534
535       case EOT_LABEL:              /* end of all tapes */
536          /* 
537           * Wiffle through all jobs still open and close
538           *   them.
539           */
540          if (update_db) {
541             mjcr=next_attached_jcr(dev, NULL);
542             for ( ; mjcr; ) {
543                JCR *njcr; 
544                jr.JobId = mjcr->JobId;
545                jr.JobStatus = JS_ErrorTerminated;
546                jr.JobFiles = mjcr->JobFiles;
547                jr.JobBytes = mjcr->JobBytes;
548                jr.VolSessionId = mjcr->VolSessionId;
549                jr.VolSessionTime = mjcr->VolSessionTime;
550                jr.JobTDate = (utime_t)mjcr->start_time;
551                jr.ClientId = mjcr->ClientId;
552                if (!db_update_job_end_record(bjcr, db, &jr)) {
553                   Pmsg1(0, _("Could not update job record. ERR=%s\n"), db_strerror(db));
554                }
555                njcr = mjcr->next_dev;
556                free_jcr(mjcr);
557                mjcr = njcr;
558             }
559          }
560          mr.VolFiles = rec->File;
561          mr.VolBlocks = rec->Block;
562          mr.VolBytes += mr.VolBlocks * WRITE_BLKHDR_LENGTH; /* approx. */
563          mr.VolMounts++;
564          update_media_record(db, &mr);
565          Pmsg3(0, _("End of all Volumes. VolFiles=%u VolBlocks=%u VolBytes=%s\n"), mr.VolFiles,
566                     mr.VolBlocks, edit_uint64_with_commas(mr.VolBytes, ec1));
567          break;
568       default:
569          break;
570       } /* end switch */
571       return true;
572    }
573
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 for SessId=%d SessTime=%d record.\n"),
578                       rec->VolSessionId, rec->VolSessionTime);
579       } else {
580          ignored_msgs++;
581       }
582       return true;
583    }
584    dcr = mjcr->dcr;
585    if (dcr->VolFirstIndex == 0) {
586       dcr->VolFirstIndex = block->FirstIndex;
587    }
588
589    /* File Attributes stream */
590    switch (rec->Stream) {
591    case STREAM_UNIX_ATTRIBUTES:   
592    case STREAM_UNIX_ATTRIBUTES_EX:  
593
594       if (!unpack_attributes_record(bjcr, rec->Stream, rec->data, attr)) {
595          Emsg0(M_ERROR_TERM, 0, _("Cannot continue.\n"));
596       }
597
598       if (attr->file_index != rec->FileIndex) {
599          Emsg2(M_ERROR_TERM, 0, _("Record header file index %ld not equal record index %ld\n"),
600             rec->FileIndex, attr->file_index);
601       }
602        
603       if (verbose > 1) {
604          decode_stat(attr->attr, &attr->statp, &attr->LinkFI);
605          build_attr_output_fnames(bjcr, attr);
606          print_ls_output(bjcr, attr);
607       }
608       fr.JobId = mjcr->JobId;
609       fr.FileId = 0;
610       num_files++;
611       if (db_get_file_attributes_record(bjcr, db, attr->fname, NULL, &fr)) {
612          if (verbose > 1) {
613             Pmsg1(000, _("File record already exists for: %s\n"), attr->fname);
614          }
615       } else {
616          create_file_attributes_record(db, mjcr, attr->fname, attr->lname, 
617             attr->type, attr->attr, rec);
618       }
619       free_jcr(mjcr);
620       break;
621
622    /* Data stream */
623    case STREAM_WIN32_DATA:
624    case STREAM_FILE_DATA:
625    case STREAM_SPARSE_DATA:
626       mjcr->JobBytes += rec->data_len;
627       if (rec->Stream == STREAM_SPARSE_DATA) {
628          mjcr->JobBytes -= sizeof(uint64_t);
629       }
630          
631       free_jcr(mjcr);                 /* done using JCR */
632       break;
633
634    case STREAM_GZIP_DATA:
635       mjcr->JobBytes += rec->data_len; /* No correct, we should expand it */
636       free_jcr(mjcr);                 /* done using JCR */
637       break;
638
639    case STREAM_SPARSE_GZIP_DATA:
640       mjcr->JobBytes += rec->data_len - sizeof(uint64_t); /* No correct, we should expand it */
641       free_jcr(mjcr);                 /* done using JCR */
642       break;
643
644    /* Win32 GZIP stream */
645    case STREAM_WIN32_GZIP_DATA:
646       mjcr->JobBytes += rec->data_len;
647       free_jcr(mjcr);                 /* done using JCR */
648       break;
649
650    case STREAM_MD5_SIGNATURE:
651       char MD5buf[50];
652       bin_to_base64(MD5buf, (char *)rec->data, 16); /* encode 16 bytes */
653       if (verbose > 1) {
654          Pmsg1(000, _("Got MD5 record: %s\n"), MD5buf);
655       }
656       update_SIG_record(db, MD5buf, rec, MD5_SIG);
657       break;
658
659    case STREAM_SHA1_SIGNATURE:
660       char SIGbuf[50];
661       bin_to_base64(SIGbuf, (char *)rec->data, 20); /* encode 20 bytes */
662       if (verbose > 1) {
663          Pmsg1(000, _("Got SHA1 record: %s\n"), SIGbuf);
664       }
665       update_SIG_record(db, SIGbuf, rec, SHA1_SIG);
666       break;
667
668
669    case STREAM_PROGRAM_NAMES:
670       if (verbose) {
671          Pmsg1(000, _("Got Prog Names Stream: %s\n"), rec->data);
672       }
673       break;
674
675    case STREAM_PROGRAM_DATA:
676       if (verbose > 1) {
677          Pmsg0(000, _("Got Prog Data Stream record.\n"));
678       }
679       break;
680    default:
681       Pmsg2(0, _("Unknown stream type!!! stream=%d data=%s\n"), rec->Stream, rec->data);
682       break;
683    }
684    return true;
685 }
686
687 /*
688  * Free the Job Control Record if no one is still using it.
689  *  Called from main free_jcr() routine in src/lib/jcr.c so
690  *  that we can do our Director specific cleanup of the jcr.
691  */
692 static void bscan_free_jcr(JCR *jcr)
693 {
694    Dmsg0(200, "Start dird free_jcr\n");
695
696    if (jcr->file_bsock) {
697       Dmsg0(200, "Close File bsock\n");
698       bnet_close(jcr->file_bsock);
699    }
700    if (jcr->store_bsock) {
701       Dmsg0(200, "Close Store bsock\n");
702       bnet_close(jcr->store_bsock);
703    }
704    if (jcr->RestoreBootstrap) {
705       free(jcr->RestoreBootstrap);
706    }
707    if (jcr->dcr) {
708       free_dcr(jcr->dcr);
709       jcr->dcr = NULL;
710    }
711    Dmsg0(200, "End dird free_jcr\n");
712 }
713
714 /*
715  * We got a File Attributes record on the tape.  Now, lookup the Job
716  *   record, and then create the attributes record.
717  */
718 static int create_file_attributes_record(B_DB *db, JCR *mjcr,
719                                char *fname, char *lname, int type,
720                                char *ap, DEV_RECORD *rec)
721 {
722    DCR *dcr = mjcr->dcr;
723    ar.fname = fname;
724    ar.link = lname;
725    ar.ClientId = mjcr->ClientId;
726    ar.JobId = mjcr->JobId;
727    ar.Stream = rec->Stream;
728    ar.FileIndex = rec->FileIndex;
729    ar.attr = ap;
730    if (dcr->VolFirstIndex == 0) {
731       dcr->VolFirstIndex = rec->FileIndex;
732    }
733    dcr->FileIndex = rec->FileIndex;
734    mjcr->JobFiles++;
735
736    if (!update_db) {
737       return 1;
738    }
739
740    if (!db_create_file_attributes_record(bjcr, db, &ar)) {
741       Pmsg1(0, _("Could not create File Attributes record. ERR=%s\n"), db_strerror(db));
742       return 0;
743    }
744    mjcr->FileId = ar.FileId;
745
746    if (verbose > 1) {
747       Pmsg1(000, _("Created File record: %s\n"), fname);   
748    }
749    return 1;
750 }
751
752 /*
753  * For each Volume we see, we create a Medium record
754  */
755 static int create_media_record(B_DB *db, MEDIA_DBR *mr, VOLUME_LABEL *vl)
756 {
757    struct date_time dt;
758    struct tm tm;
759
760    /* We mark Vols as Archive to keep them from being re-written */
761    bstrncpy(mr->VolStatus, "Archive", sizeof(mr->VolStatus));
762    mr->VolRetention = 365 * 3600 * 24; /* 1 year */
763    if (vl->VerNum >= 11) {
764       mr->FirstWritten = btime_to_utime(vl->write_btime);
765       mr->LabelDate    = btime_to_utime(vl->label_btime);
766    } else {
767       /* DEPRECATED DO NOT USE */
768       dt.julian_day_number = vl->write_date;
769       dt.julian_day_fraction = vl->write_time;
770       tm_decode(&dt, &tm);
771       mr->FirstWritten = mktime(&tm);
772       dt.julian_day_number = vl->label_date;
773       dt.julian_day_fraction = vl->label_time;
774       tm_decode(&dt, &tm);
775       mr->LabelDate = mktime(&tm);
776    }
777    lasttime = mr->LabelDate;
778
779    if (!update_db) {
780       return 1;
781    }
782
783    if (!db_create_media_record(bjcr, db, mr)) {
784       Pmsg1(0, _("Could not create media record. ERR=%s\n"), db_strerror(db));
785       return 0;
786    }
787    if (!db_update_media_record(bjcr, db, mr)) {
788       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
789       return 0;
790    }
791    if (verbose) {
792       Pmsg1(000, _("Created Media record for Volume: %s\n"), mr->VolumeName);
793    }
794    return 1;
795
796 }
797
798 /*
799  * Called at end of media to update it
800  */
801 static int update_media_record(B_DB *db, MEDIA_DBR *mr)
802 {
803    if (!update_db && !update_vol_info) {
804       return 1;
805    }
806
807    mr->LastWritten = lasttime;
808    if (!db_update_media_record(bjcr, db, mr)) {
809       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
810       return 0;
811    }
812    if (verbose) {
813       Pmsg1(000, _("Updated Media record at end of Volume: %s\n"), mr->VolumeName);
814    }
815    return 1;
816
817 }
818
819
820 static int create_pool_record(B_DB *db, POOL_DBR *pr)
821 {
822    pr->NumVols++;
823    pr->UseCatalog = 1;
824    pr->VolRetention = 355 * 3600 * 24; /* 1 year */
825
826    if (!update_db) {
827       return 1;
828    }
829    if (!db_create_pool_record(bjcr, db, pr)) {
830       Pmsg1(0, _("Could not create pool record. ERR=%s\n"), db_strerror(db));
831       return 0;
832    }
833    if (verbose) {
834       Pmsg1(000, _("Created Pool record for Pool: %s\n"), pr->Name);
835    }
836    return 1;
837
838 }
839
840
841 /*
842  * Called from SOS to create a client for the current Job 
843  */
844 static int create_client_record(B_DB *db, CLIENT_DBR *cr)
845 {
846    if (!update_db) {
847       return 1;
848    }
849    if (!db_create_client_record(bjcr, db, cr)) {
850       Pmsg1(0, _("Could not create Client record. ERR=%s\n"), db_strerror(db));
851       return 0;
852    }
853    if (verbose) {
854       Pmsg1(000, _("Created Client record for Client: %s\n"), cr->Name);
855    }
856    return 1;
857 }
858
859 static int create_fileset_record(B_DB *db, FILESET_DBR *fsr)
860 {
861    if (!update_db) {
862       return 1;
863    }
864    fsr->FileSetId = 0;
865    if (fsr->MD5[0] == 0) {
866       fsr->MD5[0] = ' ';              /* Equivalent to nothing */
867       fsr->MD5[1] = 0;
868    }
869    if (db_get_fileset_record(bjcr, db, fsr)) {
870       if (verbose) {
871          Pmsg1(000, _("Fileset \"%s\" already exists.\n"), fsr->FileSet);
872       }
873    } else {
874       if (!db_create_fileset_record(bjcr, db, fsr)) {
875          Pmsg2(0, _("Could not create FileSet record \"%s\". ERR=%s\n"), 
876             fsr->FileSet, db_strerror(db));
877          return 0;
878       }
879       if (verbose) {
880          Pmsg1(000, _("Created FileSet record \"%s\"\n"), fsr->FileSet);
881       }
882    }
883    return 1;
884 }
885
886 /*
887  * Simulate the two calls on the database to create
888  *  the Job record and to update it when the Job actually
889  *  begins running.
890  */
891 static JCR *create_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *label, 
892                              DEV_RECORD *rec)
893 {
894    JCR *mjcr;
895    struct date_time dt;
896    struct tm tm;
897
898    jr->JobId = label->JobId;
899    jr->JobType = label->JobType;
900    jr->JobLevel = label->JobLevel;
901    jr->JobStatus = JS_Created;
902    bstrncpy(jr->Name, label->JobName, sizeof(jr->Name));
903    bstrncpy(jr->Job, label->Job, sizeof(jr->Job));
904    if (label->VerNum >= 11) {
905       jr->SchedTime = btime_to_unix(label->write_btime);
906    } else {
907       dt.julian_day_number = label->write_date;
908       dt.julian_day_fraction = label->write_time;
909       tm_decode(&dt, &tm);
910       jr->SchedTime = mktime(&tm);
911    }
912
913    jr->StartTime = jr->SchedTime;
914    jr->JobTDate = (utime_t)jr->SchedTime;
915    jr->VolSessionId = rec->VolSessionId;
916    jr->VolSessionTime = rec->VolSessionTime;
917
918    /* Now create a JCR as if starting the Job */
919    mjcr = create_jcr(jr, rec, label->JobId);
920
921    if (!update_db) {
922       return mjcr;
923    }
924
925    /* This creates the bare essentials */
926    if (!db_create_job_record(bjcr, db, jr)) {
927       Pmsg1(0, _("Could not create JobId record. ERR=%s\n"), db_strerror(db));
928       return mjcr;
929    }
930
931    /* This adds the client, StartTime, JobTDate, ... */
932    if (!db_update_job_start_record(bjcr, db, jr)) {
933       Pmsg1(0, _("Could not update job start record. ERR=%s\n"), db_strerror(db));
934       return mjcr;
935    }
936    Pmsg2(000, _("Created new JobId=%u record for original JobId=%u\n"), jr->JobId, 
937          label->JobId);
938    mjcr->JobId = jr->JobId;           /* set new JobId */
939    return mjcr;
940 }
941
942 /* 
943  * Simulate the database call that updates the Job 
944  *  at Job termination time.
945  */
946 static int update_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *elabel,
947                               DEV_RECORD *rec)
948 {
949    struct date_time dt;
950    struct tm tm;
951    JCR *mjcr;
952
953    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
954    if (!mjcr) {
955       Pmsg2(000, _("Could not find SessId=%d SessTime=%d for EOS record.\n"),
956                    rec->VolSessionId, rec->VolSessionTime);
957       return 0;
958    }
959    if (elabel->VerNum >= 11) {
960       jr->EndTime = btime_to_unix(elabel->write_btime);
961    } else {
962       dt.julian_day_number = elabel->write_date;
963       dt.julian_day_fraction = elabel->write_time;
964       tm_decode(&dt, &tm);
965       jr->EndTime = mktime(&tm);
966    }
967    lasttime = jr->EndTime;
968    mjcr->end_time = jr->EndTime;
969
970    jr->JobId = mjcr->JobId;
971    jr->JobStatus = elabel->JobStatus;
972    mjcr->JobStatus = elabel->JobStatus;
973    jr->JobFiles = elabel->JobFiles;
974    jr->JobBytes = elabel->JobBytes;
975    jr->VolSessionId = rec->VolSessionId;
976    jr->VolSessionTime = rec->VolSessionTime;
977    jr->JobTDate = (utime_t)mjcr->start_time;
978    jr->ClientId = mjcr->ClientId;
979
980    if (!update_db) {
981       free_jcr(mjcr);
982       return 1;
983    }
984    
985    if (!db_update_job_end_record(bjcr, db, jr)) {
986       Pmsg2(0, _("Could not update JobId=%u record. ERR=%s\n"), jr->JobId,  db_strerror(db));
987       free_jcr(mjcr);
988       return 0;
989    }
990    if (verbose) {
991       Pmsg1(000, _("Updated Job termination record for new JobId=%u\n"), jr->JobId);
992    }
993    if (verbose > 1) {
994       const char *term_msg;
995       static char term_code[70];
996       char sdt[50], edt[50];
997       char ec1[30], ec2[30], ec3[30];
998
999       switch (mjcr->JobStatus) {
1000       case JS_Terminated:
1001          term_msg = _("Backup OK");
1002          break;
1003       case JS_FatalError:
1004       case JS_ErrorTerminated:
1005          term_msg = _("*** Backup Error ***");
1006          break;
1007       case JS_Canceled:
1008          term_msg = _("Backup Canceled");
1009          break;
1010       default:
1011          term_msg = term_code;
1012          sprintf(term_code, _("Job Termination code: %d"), mjcr->JobStatus);
1013          break;
1014       }
1015       bstrftime(sdt, sizeof(sdt), mjcr->start_time);
1016       bstrftime(edt, sizeof(edt), mjcr->end_time);
1017       Pmsg14(000,  _("%s\n\
1018 JobId:                  %d\n\
1019 Job:                    %s\n\
1020 FileSet:                %s\n\
1021 Backup Level:           %s\n\
1022 Client:                 %s\n\
1023 Start time:             %s\n\
1024 End time:               %s\n\
1025 Files Written:          %s\n\
1026 Bytes Written:          %s\n\
1027 Volume Session Id:      %d\n\
1028 Volume Session Time:    %d\n\
1029 Last Volume Bytes:      %s\n\
1030 Termination:            %s\n\n"),
1031         edt,
1032         mjcr->JobId,
1033         mjcr->Job,
1034         mjcr->fileset_name,
1035         job_level_to_str(mjcr->JobLevel),
1036         mjcr->client_name,
1037         sdt,
1038         edt,
1039         edit_uint64_with_commas(mjcr->JobFiles, ec1),
1040         edit_uint64_with_commas(mjcr->JobBytes, ec2),
1041         mjcr->VolSessionId,
1042         mjcr->VolSessionTime,
1043         edit_uint64_with_commas(mr.VolBytes, ec3),
1044         term_msg);
1045    }
1046    free_jcr(mjcr);
1047    return 1;
1048 }
1049
1050 static int create_jobmedia_record(B_DB *db, JCR *mjcr)
1051 {
1052    JOBMEDIA_DBR jmr;
1053    DCR *dcr = mjcr->dcr;
1054
1055    if (dev->state & ST_TAPE) {
1056       dcr->EndBlock = dev->EndBlock;
1057       dcr->EndFile  = dev->EndFile;
1058    } else {
1059       dcr->EndBlock = (uint32_t)dev->file_addr;
1060       dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
1061    }
1062
1063    memset(&jmr, 0, sizeof(jmr));
1064    jmr.JobId = mjcr->JobId;
1065    jmr.MediaId = mr.MediaId;
1066    jmr.FirstIndex = dcr->VolFirstIndex;
1067    jmr.LastIndex = dcr->FileIndex;
1068    jmr.StartFile = dcr->StartFile;
1069    jmr.EndFile = dcr->EndFile;
1070    jmr.StartBlock = dcr->StartBlock;
1071    jmr.EndBlock = dcr->EndBlock;
1072
1073
1074    if (!update_db) {
1075       return 1;
1076    }
1077
1078    if (!db_create_jobmedia_record(bjcr, db, &jmr)) {
1079       Pmsg1(0, _("Could not create JobMedia record. ERR=%s\n"), db_strerror(db));
1080       return 0;
1081    }
1082    if (verbose) {
1083       Pmsg2(000, _("Created JobMedia record JobId %d, MediaId %d\n"), 
1084                 jmr.JobId, jmr.MediaId);
1085    }
1086    return 1;
1087 }
1088
1089 /* 
1090  * Simulate the database call that updates the MD5/SHA1 record
1091  */
1092 static int update_SIG_record(B_DB *db, char *SIGbuf, DEV_RECORD *rec, int type)
1093 {
1094    JCR *mjcr;
1095
1096    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
1097    if (!mjcr) {
1098       if (mr.VolJobs > 0) {
1099          Pmsg2(000, _("Could not find SessId=%d SessTime=%d for MD5/SHA1 record.\n"),
1100                       rec->VolSessionId, rec->VolSessionTime);
1101       } else {
1102          ignored_msgs++;
1103       }
1104       return 0;
1105    }
1106
1107    if (!update_db) {
1108       free_jcr(mjcr);
1109       return 1;
1110    }
1111    
1112    if (!db_add_SIG_to_file_record(bjcr, db, mjcr->FileId, SIGbuf, type)) {
1113       Pmsg1(0, _("Could not add MD5/SHA1 to File record. ERR=%s\n"), db_strerror(db));
1114       free_jcr(mjcr);
1115       return 0;
1116    }
1117    if (verbose > 1) {
1118       Pmsg0(000, _("Updated MD5/SHA1 record\n"));
1119    }
1120    free_jcr(mjcr);
1121    return 1;
1122 }
1123
1124
1125 /* 
1126  * Create a JCR as if we are really starting the job
1127  */
1128 static JCR *create_jcr(JOB_DBR *jr, DEV_RECORD *rec, uint32_t JobId)
1129 {
1130    JCR *jobjcr;
1131    /*
1132     * Transfer as much as possible to the Job JCR. Most important is
1133     *   the JobId and the ClientId.
1134     */
1135    jobjcr = new_jcr(sizeof(JCR), bscan_free_jcr);
1136    jobjcr->JobType = jr->JobType;
1137    jobjcr->JobLevel = jr->JobLevel;
1138    jobjcr->JobStatus = jr->JobStatus;
1139    bstrncpy(jobjcr->Job, jr->Job, sizeof(jobjcr->Job));
1140    jobjcr->JobId = JobId;      /* this is JobId on tape */
1141    jobjcr->sched_time = jr->SchedTime;
1142    jobjcr->start_time = jr->StartTime;
1143    jobjcr->VolSessionId = rec->VolSessionId;
1144    jobjcr->VolSessionTime = rec->VolSessionTime;
1145    jobjcr->ClientId = jr->ClientId;
1146    attach_jcr_to_device(dev, jobjcr);
1147    new_dcr(jobjcr, dev);
1148    return jobjcr;
1149 }
1150
1151 /* Dummies to replace askdir.c */
1152 int     dir_get_volume_info(JCR *jcr, enum get_vol_info_rw  writing) { return 1;}
1153 int     dir_find_next_appendable_volume(JCR *jcr) { return 1;}
1154 int     dir_update_volume_info(JCR *jcr, DEVICE *dev, int relabel) { return 1; }
1155 int     dir_create_jobmedia_record(JCR *jcr) { return 1; }
1156 int     dir_ask_sysop_to_create_appendable_volume(JCR *jcr, DEVICE *dev) { return 1; }
1157 int     dir_update_file_attributes(JCR *jcr, DEV_RECORD *rec) { return 1;}
1158 int     dir_send_job_status(JCR *jcr) {return 1;}
1159
1160
1161 int dir_ask_sysop_to_mount_volume(JCR *jcr, DEVICE *dev)
1162 {
1163    fprintf(stderr, _("Mount Volume \"%s\" on device \"%s\" and press return when ready: "),
1164       jcr->VolumeName, dev_name(dev));
1165    getchar();   
1166    return 1;
1167 }