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