]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/filed/job.c
Use rentrant mysql lib, eliminate race in sql_list, Win32 streams, misc see kes-1.31
[bacula/bacula] / bacula / src / filed / job.c
1 /*
2  *  Bacula File Daemon Job processing
3  *
4  *    Kern Sibbald, October MM
5  *
6  *   Version $Id$
7  *
8  */
9 /*
10    Copyright (C) 2000-2003 Kern Sibbald and John Walker
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License as
14    published by the Free Software Foundation; either version 2 of
15    the License, or (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20    General Public License for more details.
21
22    You should have received a copy of the GNU General Public
23    License along with this program; if not, write to the Free
24    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25    MA 02111-1307, USA.
26
27  */
28
29 #include "bacula.h"
30 #include "filed.h"
31 #include "host.h"
32
33 extern char my_name[];
34 extern CLIENT *me;                    /* our client resource */
35                         
36 /* Imported functions */
37 extern int status_cmd(JCR *jcr);
38                                    
39 /* Forward referenced functions */
40 static int backup_cmd(JCR *jcr);
41 static int bootstrap_cmd(JCR *jcr);
42 static int cancel_cmd(JCR *jcr);
43 static int setdebug_cmd(JCR *jcr);
44 static int estimate_cmd(JCR *jcr);
45 static int exclude_cmd(JCR *jcr);
46 static int hello_cmd(JCR *jcr);
47 static int job_cmd(JCR *jcr);
48 static int include_cmd(JCR *jcr);
49 static int level_cmd(JCR *jcr);
50 static int verify_cmd(JCR *jcr);
51 static int restore_cmd(JCR *jcr);
52 static int storage_cmd(JCR *jcr);
53 static int session_cmd(JCR *jcr);
54 static int response(JCR *jcr, BSOCK *sd, char *resp, char *cmd);
55 static void filed_free_jcr(JCR *jcr);
56 static int open_sd_read_session(JCR *jcr);
57 static int send_bootstrap_file(JCR *jcr);
58
59
60 /* Exported functions */
61
62 struct s_cmds {
63    char *cmd;
64    int (*func)(JCR *);
65 };
66
67 /*  
68  * The following are the recognized commands from the Director. 
69  */
70 static struct s_cmds cmds[] = {
71    {"backup",   backup_cmd},
72    {"cancel",   cancel_cmd},
73    {"setdebug=", setdebug_cmd},
74    {"estimate", estimate_cmd},
75    {"exclude",  exclude_cmd},
76    {"Hello",    hello_cmd},
77    {"include",  include_cmd},
78    {"JobId=",   job_cmd},
79    {"level = ", level_cmd},
80    {"restore",  restore_cmd},
81    {"session",  session_cmd},
82    {"status",   status_cmd},
83    {"storage ", storage_cmd},
84    {"verify",   verify_cmd},
85    {"bootstrap",bootstrap_cmd},
86    {NULL,       NULL}                  /* list terminator */
87 };
88
89 /* Commands received from director that need scanning */
90 static char jobcmd[]      = "JobId=%d Job=%127s SDid=%d SDtime=%d Authorization=%100s";
91 static char storaddr[]    = "storage address=%s port=%d ssl=%d\n";
92 static char sessioncmd[]  = "session %127s %ld %ld %ld %ld %ld %ld\n";
93 static char restorecmd[]  = "restore replace=%c where=%s\n";
94 static char restorecmd1[] = "restore replace=%c where=\n";
95 static char verifycmd[]   = "verify level=%30s\n";
96
97 /* Responses sent to Director */
98 static char errmsg[]      = "2999 Invalid command\n";
99 static char no_auth[]     = "2998 No Authorization\n";
100 static char OKinc[]       = "2000 OK include\n";
101 static char OKest[]       = "2000 OK estimate files=%ld bytes=%ld\n";
102 static char OKexc[]       = "2000 OK exclude\n";
103 static char OKlevel[]     = "2000 OK level\n";
104 static char OKbackup[]    = "2000 OK backup\n";
105 static char OKbootstrap[] = "2000 OK bootstrap\n";
106 static char OKverify[]    = "2000 OK verify\n";
107 static char OKrestore[]   = "2000 OK restore\n";
108 static char OKsession[]   = "2000 OK session\n";
109 static char OKstore[]     = "2000 OK storage\n";
110 static char OKjob[]       = "2000 OK Job " FDHOST "," DISTNAME "," DISTVER;
111 static char OKsetdebug[]  = "2000 OK setdebug=%d\n";
112 static char BADjob[]      = "2901 Bad Job\n";
113 static char EndRestore[]  = "2800 End Job TermCode=%d JobFiles=%u JobBytes=%" lld "\n";
114 static char EndBackup[]   = "2801 End Backup Job TermCode=%d JobFiles=%u ReadBytes=%" lld " JobBytes=%" lld "\n";
115
116 /* Responses received from Storage Daemon */
117 static char OK_end[]       = "3000 OK end\n";
118 static char OK_close[]     = "3000 OK close Status = %d\n";
119 static char OK_open[]      = "3000 OK open ticket = %d\n";
120 static char OK_data[]      = "3000 OK data\n";
121 static char OK_append[]    = "3000 OK append data\n";
122 static char OKSDbootstrap[] = "3000 OK bootstrap\n";
123
124
125 /* Commands sent to Storage Daemon */
126 static char append_open[]  = "append open session\n";
127 static char append_data[]  = "append data %d\n";
128 static char append_end[]   = "append end session %d\n";
129 static char append_close[] = "append close session %d\n";
130 static char read_open[]    = "read open session = %s %ld %ld %ld %ld %ld %ld\n";
131 static char read_data[]    = "read data %d\n";
132 static char read_close[]   = "read close session %d\n";
133
134 /* 
135  * Accept requests from a Director
136  *
137  * NOTE! We are running as a separate thread
138  *
139  * Send output one line
140  * at a time followed by a zero length transmission.
141  *
142  * Return when the connection is terminated or there
143  * is an error.
144  *
145  * Basic task here is:
146  *   Authenticate Director (during Hello command).
147  *   Accept commands one at a time from the Director
148  *     and execute them.
149  *
150  */
151 void *handle_client_request(void *dirp)
152 {
153    int i, found, quit;
154    JCR *jcr;
155    BSOCK *dir = (BSOCK *)dirp;
156
157    jcr = new_jcr(sizeof(JCR), filed_free_jcr); /* create JCR */
158    jcr->dir_bsock = dir;
159    jcr->ff = init_find_files();
160    jcr->start_time = time(NULL);
161    jcr->last_fname = get_pool_memory(PM_FNAME);
162    jcr->last_fname[0] = 0;
163    jcr->client_name = get_memory(strlen(my_name) + 1);
164    pm_strcpy(&jcr->client_name, my_name);
165    dir->jcr = (void *)jcr;
166
167    /**********FIXME******* add command handler error code */
168
169    for (quit=0; !quit;) {
170
171       /* Read command */
172       if (bnet_recv(dir) < 0) {
173          break;                       /* connection terminated */
174       }
175       dir->msg[dir->msglen] = 0;
176       Dmsg1(100, "<dird: %s", dir->msg);
177       found = FALSE;
178       for (i=0; cmds[i].cmd; i++) {
179          if (strncmp(cmds[i].cmd, dir->msg, strlen(cmds[i].cmd)) == 0) {
180             if (!jcr->authenticated && cmds[i].func != hello_cmd) {
181                bnet_fsend(dir, no_auth);
182                break;
183             }
184             found = TRUE;                /* indicate command found */
185             if (!cmds[i].func(jcr)) {    /* do command */
186                quit = TRUE;              /* error or fully terminated,  get out */
187                Pmsg0(20, "Command error or Job done.\n");
188             }
189             break;
190          }
191       }
192       if (!found) {                   /* command not found */
193          bnet_fsend(dir, errmsg);
194          quit = TRUE;
195          break;
196       }
197    }
198
199    /* Inform Storage daemon that we are done */
200    if (jcr->store_bsock) {
201       bnet_sig(jcr->store_bsock, BNET_TERMINATE);
202    }
203
204    /* Inform Director that we are done */
205    bnet_sig(dir, BNET_TERMINATE);
206
207    Dmsg0(100, "Calling term_find_files\n");
208    term_find_files((FF_PKT *)jcr->ff);
209    Dmsg0(100, "Done with term_find_files\n");
210    free_jcr(jcr);                     /* destroy JCR record */
211    Dmsg0(100, "Done with free_jcr\n");
212    return NULL;
213 }
214
215 /*
216  * Hello from Director he must identify himself and provide his 
217  *  password.
218  */
219 static int hello_cmd(JCR *jcr)
220 {
221    Dmsg0(120, "Calling Authenticate\n");
222    if (!authenticate_director(jcr)) {
223       return 0;
224    }
225    Dmsg0(120, "OK Authenticate\n");
226    jcr->authenticated = TRUE;
227    return 1;
228 }
229
230 /*
231  * Cancel a Job
232  */
233 static int cancel_cmd(JCR *jcr)
234 {
235    BSOCK *dir = jcr->dir_bsock;
236    char Job[MAX_NAME_LENGTH];
237    JCR *cjcr;
238
239    if (sscanf(dir->msg, "cancel Job=%127s", Job) == 1) {
240       if (!(cjcr=get_jcr_by_full_name(Job))) {
241          bnet_fsend(dir, "2901 Job %s not found.\n", Job);
242       } else {
243          set_jcr_job_status(cjcr, JS_Canceled);
244          free_jcr(cjcr);
245          bnet_fsend(dir, "2001 Job %s marked to be canceled.\n", Job);
246       }
247    } else {
248       bnet_fsend(dir, "2902 Error scanning cancel command.\n");
249    }
250    bnet_sig(dir, BNET_EOD);
251    return 1;
252 }
253
254
255 /*
256  * Set debug level as requested by the Director
257  *
258  */
259 static int setdebug_cmd(JCR *jcr)
260 {
261    BSOCK *dir = jcr->dir_bsock;
262    int level;
263
264    Dmsg1(110, "setdebug_cmd: %s", dir->msg);
265    if (sscanf(dir->msg, "setdebug=%d", &level) != 1 || level < 0) {
266       bnet_fsend(dir, "2991 Bad setdebug command: %s\n", dir->msg);
267       return 0;   
268    }
269    debug_level = level;
270    return bnet_fsend(dir, OKsetdebug, level);
271 }
272
273
274 static int estimate_cmd(JCR *jcr)
275 {
276    BSOCK *dir = jcr->dir_bsock;
277    make_estimate(jcr);
278    return bnet_fsend(dir, OKest, jcr->num_files_examined, jcr->JobBytes);
279 }
280
281 /*
282  * Get JobId and Storage Daemon Authorization key from Director
283  */
284 static int job_cmd(JCR *jcr)
285 {
286    BSOCK *dir = jcr->dir_bsock;
287    POOLMEM *sd_auth_key;
288
289    sd_auth_key = get_memory(dir->msglen);
290    if (sscanf(dir->msg, jobcmd,  &jcr->JobId, jcr->Job,  
291               &jcr->VolSessionId, &jcr->VolSessionTime,
292               sd_auth_key) != 5) {
293       bnet_fsend(dir, BADjob);
294       Jmsg(jcr, M_FATAL, 0, _("Bad Job Command: %s\n"), dir->msg);
295       free_pool_memory(sd_auth_key);
296       return 0;
297    }
298    jcr->sd_auth_key = bstrdup(sd_auth_key);
299    free_pool_memory(sd_auth_key);
300    get_backup_privileges(jcr, 1 /* ignore_errors */);
301    Dmsg2(120, "JobId=%d Auth=%s\n", jcr->JobId, jcr->sd_auth_key);
302    return bnet_fsend(dir, OKjob);
303 }
304
305 #define INC_LIST 0
306 #define EXC_LIST 1
307
308 static void add_fname_to_list(JCR *jcr, char *fname, int list)
309 {
310    char *p;  
311    if (list == INC_LIST) {
312       add_fname_to_include_list((FF_PKT *)jcr->ff, 1, fname);
313    } else {
314       /* Skip leading options -- currently ignored */
315       for (p=fname; *p && *p != ' '; p++)
316          { }
317       /* Skip spaces */
318       for ( ; *p && *p == ' '; p++)
319          { }
320       add_fname_to_exclude_list((FF_PKT *)jcr->ff, p);
321    }
322 }
323
324 /* 
325  * 
326  * Get list of files/directories to include from Director
327  *
328  */
329 static int include_cmd(JCR *jcr)
330 {
331    BSOCK *dir = jcr->dir_bsock;
332
333    while (bnet_recv(dir) >= 0) {
334       dir->msg[dir->msglen] = 0;
335       strip_trailing_junk(dir->msg);
336       Dmsg1(010, "include file: %s\n", dir->msg);
337       add_fname_to_list(jcr, dir->msg, INC_LIST);
338    }
339
340    return bnet_fsend(dir, OKinc);
341 }
342
343 /*
344  * Get list of files to exclude from Director
345  *
346  */
347 static int exclude_cmd(JCR *jcr)
348 {
349    BSOCK *dir = jcr->dir_bsock;
350
351    while (bnet_recv(dir) >= 0) {
352       dir->msg[dir->msglen] = 0;
353       strip_trailing_junk(dir->msg);
354       add_fname_to_list(jcr, dir->msg, EXC_LIST);
355       Dmsg1(110, "<dird: exclude file %s\n", dir->msg);
356    }
357
358    return bnet_fsend(dir, OKexc);
359 }
360
361
362 static int bootstrap_cmd(JCR *jcr)
363 {
364    BSOCK *dir = jcr->dir_bsock;
365    POOLMEM *fname = get_pool_memory(PM_FNAME);
366    FILE *bs;
367
368    if (jcr->RestoreBootstrap) {
369       unlink(jcr->RestoreBootstrap);
370       free_pool_memory(jcr->RestoreBootstrap);
371    }
372    Mmsg(&fname, "%s/%s.%s.bootstrap", me->working_directory, me->hdr.name,
373       jcr->Job);
374    Dmsg1(400, "bootstrap=%s\n", fname);
375    jcr->RestoreBootstrap = fname;
376    bs = fopen(fname, "a+");           /* create file */
377    if (!bs) {
378       Jmsg(jcr, M_FATAL, 0, _("Could not create bootstrap file %s: ERR=%s\n"),
379          jcr->RestoreBootstrap, strerror(errno));
380       free_pool_memory(jcr->RestoreBootstrap);
381       jcr->RestoreBootstrap = NULL;
382       set_jcr_job_status(jcr, JS_ErrorTerminated);
383       return 0;
384    }
385
386    while (bnet_recv(dir) >= 0) {
387        Dmsg1(200, "filed<dird: bootstrap file %s\n", dir->msg);
388        fputs(dir->msg, bs);
389    }
390    fclose(bs);
391
392    return bnet_fsend(dir, OKbootstrap);
393 }
394
395
396 /*
397  * Get backup level from Director
398  *
399  */
400 static int level_cmd(JCR *jcr)
401 {
402    BSOCK *dir = jcr->dir_bsock;
403    POOLMEM *level;
404    struct tm tm;
405    time_t mtime;
406
407    level = get_memory(dir->msglen+1);
408    Dmsg1(110, "level_cmd: %s", dir->msg);
409    if (sscanf(dir->msg, "level = %s ", level) != 1) {
410       Jmsg1(jcr, M_FATAL, 0, _("Bad level command: %s\n"), dir->msg);
411       free_memory(level);
412       return 0;
413    }
414    /* Base backup requested? */
415    if (strcmp(level, "base") == 0) {
416       jcr->save_level = L_BASE;
417    /* Full backup requested? */ 
418    } else if (strcmp(level, "full") == 0) {
419       jcr->save_level = L_FULL;
420    /* 
421     * Backup requested since <date> <time>
422     *  This form is also used for incremental and differential
423     */
424    } else if (strcmp(level, "since") == 0) {
425       jcr->save_level = L_SINCE;
426       if (sscanf(dir->msg, "level = since %d-%d-%d %d:%d:%d", 
427                  &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
428                  &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
429          Jmsg1(jcr, M_FATAL, 0, _("Bad scan of date/time: %s\n"), dir->msg);
430          free_memory(level);
431          return 0;
432       }
433       tm.tm_year -= 1900;
434       tm.tm_mon  -= 1;
435       tm.tm_wday = tm.tm_yday = 0;              
436       tm.tm_isdst = -1;
437       mtime = mktime(&tm);
438       Dmsg1(100, "Got since time: %s", ctime(&mtime));
439       jcr->incremental = 1;           /* set incremental or decremental backup */
440       jcr->mtime = mtime;             /* set since time */
441    } else {
442       Jmsg1(jcr, M_FATAL, 0, "Unknown backup level: %s\n", level);
443       free_memory(level);
444       return 0;
445    }
446    free_memory(level);
447    return bnet_fsend(dir, OKlevel);
448 }
449
450 /*
451  * Get session parameters from Director -- this is for a Restore command
452  */
453 static int session_cmd(JCR *jcr)
454 {
455    BSOCK *dir = jcr->dir_bsock;
456
457    Dmsg1(100, "SessionCmd: %s", dir->msg);
458    if (sscanf(dir->msg, sessioncmd, jcr->VolumeName,
459               &jcr->VolSessionId, &jcr->VolSessionTime,
460               &jcr->StartFile, &jcr->EndFile, 
461               &jcr->StartBlock, &jcr->EndBlock) != 7) {
462       Jmsg(jcr, M_FATAL, 0, "Bad session command: %s", dir->msg);
463       return 0;
464    }
465
466    return bnet_fsend(dir, OKsession);
467 }
468
469 /*
470  * Get address of storage daemon from Director
471  *
472  */
473 static int storage_cmd(JCR *jcr)
474 {
475    int stored_port;                /* storage daemon port */
476    int enable_ssl;                 /* enable ssl to sd */
477    BSOCK *dir = jcr->dir_bsock;
478    BSOCK *sd;                         /* storage daemon bsock */
479
480    Dmsg1(100, "StorageCmd: %s", dir->msg);
481    if (sscanf(dir->msg, storaddr, &jcr->stored_addr, &stored_port, &enable_ssl) != 3) {
482       Jmsg(jcr, M_FATAL, 0, _("Bad storage command: %s"), dir->msg);
483       return 0;
484    }
485    Dmsg3(110, "Open storage: %s:%d ssl=%d\n", jcr->stored_addr, stored_port, enable_ssl);
486    /* Open command communications with Storage daemon */
487    /* Try to connect for 1 hour at 10 second intervals */
488    sd = bnet_connect(jcr, 10, 3600, _("Storage daemon"), 
489                      jcr->stored_addr, NULL, stored_port, 1);
490    if (sd == NULL) {
491       Jmsg(jcr, M_FATAL, 0, _("Failed to connect to Storage daemon: %s:%d\n"),
492           jcr->stored_addr, stored_port);
493       return 0;
494    }
495
496    jcr->store_bsock = sd;
497
498    bnet_fsend(sd, "Hello Start Job %s\n", jcr->Job);
499    if (!authenticate_storagedaemon(jcr)) {
500       Jmsg(jcr, M_FATAL, 0, _("Failed to authenticate Storage daemon.\n"));
501       return 0;
502    }
503    Dmsg0(110, "Authenticated with SD.\n");
504
505    /* Send OK to Director */
506    return bnet_fsend(dir, OKstore);
507 }
508
509
510 /*  
511  * Do a backup. For now, we handle only Full and Incremental.
512  */
513 static int backup_cmd(JCR *jcr)
514
515    BSOCK *dir = jcr->dir_bsock;
516    BSOCK *sd = jcr->store_bsock;
517    int ok = 0;
518    int SDJobStatus;
519
520    set_jcr_job_status(jcr, JS_Blocked);
521    jcr->JobType = JT_BACKUP;
522    Dmsg1(100, "begin backup ff=%p\n", (FF_PKT *)jcr->ff);
523
524    if (sd == NULL) {
525       Jmsg(jcr, M_FATAL, 0, _("Cannot contact Storage daemon\n"));
526       set_jcr_job_status(jcr, JS_ErrorTerminated);
527       goto cleanup;
528    }
529
530    bnet_fsend(dir, OKbackup);
531    Dmsg1(110, "bfiled>dird: %s", dir->msg);
532
533    /* 
534     * Send Append Open Session to Storage daemon
535     */
536    bnet_fsend(sd, append_open);
537    Dmsg1(110, ">stored: %s", sd->msg);
538    /* 
539     * Expect to receive back the Ticket number
540     */
541    if (bget_msg(sd) >= 0) {
542       Dmsg1(110, "<stored: %s", sd->msg);
543       if (sscanf(sd->msg, OK_open, &jcr->Ticket) != 1) {
544          Jmsg(jcr, M_FATAL, 0, _("Bad response to append open: %s\n"), sd->msg);
545          set_jcr_job_status(jcr, JS_ErrorTerminated);
546          goto cleanup;
547       }
548       Dmsg1(110, "Got Ticket=%d\n", jcr->Ticket);
549    } else {
550       Jmsg(jcr, M_FATAL, 0, _("Bad response from stored to open command\n"));
551       set_jcr_job_status(jcr, JS_ErrorTerminated);
552       goto cleanup;
553    }
554
555    /* 
556     * Send Append data command to Storage daemon
557     */
558    bnet_fsend(sd, append_data, jcr->Ticket);
559    Dmsg1(110, ">stored: %s", sd->msg);
560
561    /* 
562     * Expect to get OK data 
563     */
564    Dmsg1(110, "<stored: %s", sd->msg);
565    if (!response(jcr, sd, OK_data, "Append Data")) {
566       set_jcr_job_status(jcr, JS_ErrorTerminated);
567       goto cleanup;
568    }
569       
570    /*
571     * Send Files to Storage daemon
572     */
573    Dmsg1(110, "begin blast ff=%p\n", (FF_PKT *)jcr->ff);
574    if (!blast_data_to_storage_daemon(jcr, NULL)) {
575       set_jcr_job_status(jcr, JS_ErrorTerminated);
576       bnet_suppress_error_messages(sd, 1);
577    } else {
578       set_jcr_job_status(jcr, JS_Terminated);
579       if (jcr->JobStatus != JS_Terminated) {
580          bnet_suppress_error_messages(sd, 1);
581          goto cleanup;                /* bail out now */
582       }
583       /* 
584        * Expect to get response to append_data from Storage daemon
585        */
586       if (!response(jcr, sd, OK_append, "Append Data")) {
587          set_jcr_job_status(jcr, JS_ErrorTerminated);
588          goto cleanup;
589       }
590      
591       /* 
592        * Send Append End Data to Storage daemon
593        */
594       bnet_fsend(sd, append_end, jcr->Ticket);
595       /* Get end OK */
596       if (!response(jcr, sd, OK_end, "Append End")) {
597          set_jcr_job_status(jcr, JS_ErrorTerminated);
598          goto cleanup;
599       }
600
601       /*
602        * Send Append Close to Storage daemon
603        */
604       bnet_fsend(sd, append_close, jcr->Ticket);
605       while (bget_msg(sd) >= 0) {    /* stop on signal or error */
606          if (sscanf(sd->msg, OK_close, &SDJobStatus) == 1) {
607             ok = 1;
608             Dmsg2(200, "SDJobStatus = %d %c\n", SDJobStatus, (char)SDJobStatus);
609          }
610       }
611       if (!ok) {
612          Jmsg(jcr, M_FATAL, 0, _("Append Close with SD failed.\n"));
613          set_jcr_job_status(jcr, JS_ErrorTerminated);
614          goto cleanup;
615       }
616       if (SDJobStatus != JS_Terminated) {
617          Jmsg(jcr, M_FATAL, 0, _("Bad status %d returned from Storage Daemon.\n"),
618             SDJobStatus);
619          set_jcr_job_status(jcr, JS_ErrorTerminated);
620       }
621    }
622
623 cleanup:
624
625    bnet_fsend(dir, EndBackup, jcr->JobStatus, jcr->JobFiles, jcr->ReadBytes, jcr->JobBytes);
626
627    return 0;                          /* return and stop command loop */
628 }
629
630 /*  
631  * Do a Verify for Director
632  *
633  */
634 static int verify_cmd(JCR *jcr)
635
636    BSOCK *dir = jcr->dir_bsock;
637    BSOCK *sd  = jcr->store_bsock;
638    char level[100];
639
640    jcr->JobType = JT_VERIFY;
641    if (sscanf(dir->msg, verifycmd, level) != 1) {
642       bnet_fsend(dir, "2994 Bad verify command: %s\n", dir->msg);
643       return 0;   
644    }
645    if (strcasecmp(level, "init") == 0) {
646       jcr->JobLevel = L_VERIFY_INIT;
647    } else if (strcasecmp(level, "catalog") == 0){
648       jcr->JobLevel = L_VERIFY_CATALOG;
649    } else if (strcasecmp(level, "volume") == 0){
650       jcr->JobLevel = L_VERIFY_VOLUME_TO_CATALOG;
651    } else if (strcasecmp(level, "data") == 0){
652       jcr->JobLevel = L_VERIFY_DATA;
653    } else {   
654       bnet_fsend(dir, "2994 Bad verify level: %s\n", dir->msg);
655       return 0;   
656    }
657
658    bnet_fsend(dir, OKverify);
659    Dmsg1(110, "bfiled>dird: %s", dir->msg);
660
661    switch (jcr->JobLevel) {
662    case L_VERIFY_INIT:
663    case L_VERIFY_CATALOG:
664       do_verify(jcr);
665       break;
666    case L_VERIFY_VOLUME_TO_CATALOG:
667       if (!open_sd_read_session(jcr)) {
668          return 0;
669       }
670       start_dir_heartbeat(jcr);
671       do_verify_volume(jcr);
672       stop_dir_heartbeat(jcr);
673       /* 
674        * Send Close session command to Storage daemon
675        */
676       bnet_fsend(sd, read_close, jcr->Ticket);
677       Dmsg1(130, "bfiled>stored: %s", sd->msg);
678
679       /* ****FIXME**** check response */
680       bget_msg(sd);                      /* get OK */
681
682       /* Inform Storage daemon that we are done */
683       bnet_sig(sd, BNET_TERMINATE);
684
685       break;
686    default:
687       bnet_fsend(dir, "2994 Bad verify level: %s\n", dir->msg);
688       return 0; 
689    }
690
691    /* Inform Director that we are done */
692    bnet_sig(dir, BNET_TERMINATE);
693    return 0;                          /* return and terminate command loop */
694 }
695
696 /*  
697  * Do a Restore for Director
698  *
699  */
700 static int restore_cmd(JCR *jcr)
701
702    BSOCK *dir = jcr->dir_bsock;
703    BSOCK *sd = jcr->store_bsock;
704    POOLMEM *where;
705    char replace;
706
707    /*
708     * Scan WHERE (base directory for restore) from command
709     */
710    Dmsg0(150, "restore command\n");
711    /* Pickup where string */
712    where = get_memory(dir->msglen+1);
713    *where = 0;
714
715    if (sscanf(dir->msg, restorecmd, &replace, where) != 2) {
716       if (sscanf(dir->msg, restorecmd1, &replace) != 1) {
717          Jmsg(jcr, M_FATAL, 0, _("Bad replace command. CMD=%s\n"), dir->msg);
718          return 0;
719       }
720       *where = 0;
721    }
722    /* Turn / into nothing */
723    if (where[0] == '/' && where[1] == 0) {
724       where[0] = 0;
725    }
726       
727    Dmsg2(150, "Got replace %c, where=%s\n", replace, where);
728    unbash_spaces(where);
729    jcr->where = where;
730    jcr->replace = replace;
731
732    bnet_fsend(dir, OKrestore);
733    Dmsg1(110, "bfiled>dird: %s", dir->msg);
734
735    jcr->JobType = JT_RESTORE;
736
737    set_jcr_job_status(jcr, JS_Blocked);
738    if (!open_sd_read_session(jcr)) {
739       set_jcr_job_status(jcr, JS_ErrorTerminated);
740       goto bail_out;
741    }
742
743    set_jcr_job_status(jcr, JS_Running);
744
745    /* 
746     * Do restore of files and data
747     */
748    start_dir_heartbeat(jcr);
749    do_restore(jcr);
750    stop_dir_heartbeat(jcr);
751    
752    set_jcr_job_status(jcr, JS_Terminated);
753    if (jcr->JobStatus != JS_Terminated) {
754       bnet_suppress_error_messages(sd, 1);
755    }
756
757    /* 
758     * Send Close session command to Storage daemon
759     */
760    bnet_fsend(sd, read_close, jcr->Ticket);
761    Dmsg1(130, "bfiled>stored: %s", sd->msg);
762
763    bget_msg(sd);                      /* get OK */
764
765    /* Inform Storage daemon that we are done */
766    bnet_sig(sd, BNET_TERMINATE);
767
768 bail_out:
769    /* Send termination status back to Dir */
770    bnet_fsend(dir, EndRestore, jcr->JobStatus, jcr->num_files_examined, 
771               jcr->JobBytes);
772
773    /* Inform Director that we are done */
774    bnet_sig(dir, BNET_TERMINATE);
775
776    Dmsg0(130, "Done in job.c\n");
777    return 0;                          /* return and terminate command loop */
778 }
779
780 static int open_sd_read_session(JCR *jcr)
781 {
782    BSOCK *sd = jcr->store_bsock;
783
784    if (!sd) {
785       Jmsg(jcr, M_FATAL, 0, _("Improper calling sequence.\n"));
786       return 0;
787    }
788    Dmsg4(120, "VolSessId=%ld VolsessT=%ld SF=%ld EF=%ld\n",
789       jcr->VolSessionId, jcr->VolSessionTime, jcr->StartFile, jcr->EndFile);
790    Dmsg2(120, "JobId=%d vol=%s\n", jcr->JobId, "DummyVolume");
791    /* 
792     * Open Read Session with Storage daemon
793     */
794    bnet_fsend(sd, read_open, jcr->VolumeName,
795       jcr->VolSessionId, jcr->VolSessionTime, jcr->StartFile, jcr->EndFile, 
796       jcr->StartBlock, jcr->EndBlock);
797    Dmsg1(110, ">stored: %s", sd->msg);
798
799    /* 
800     * Get ticket number
801     */
802    if (bget_msg(sd) >= 0) {
803       Dmsg1(110, "bfiled<stored: %s", sd->msg);
804       if (sscanf(sd->msg, OK_open, &jcr->Ticket) != 1) {
805          Jmsg(jcr, M_FATAL, 0, _("Bad response to SD read open: %s\n"), sd->msg);
806          return 0;
807       }
808       Dmsg1(110, "bfiled: got Ticket=%d\n", jcr->Ticket);
809    } else {
810       Jmsg(jcr, M_FATAL, 0, _("Bad response from stored to read open command\n"));
811       return 0;
812    }
813
814    if (!send_bootstrap_file(jcr)) {
815       return 0;
816    }
817
818    /* 
819     * Start read of data with Storage daemon
820     */
821    bnet_fsend(sd, read_data, jcr->Ticket);
822    Dmsg1(110, ">stored: %s", sd->msg);
823
824    /* 
825     * Get OK data
826     */
827    if (!response(jcr, sd, OK_data, "Read Data")) {
828       return 0;
829    }
830    return 1;
831 }
832
833 /* 
834  * Destroy the Job Control Record and associated
835  * resources (sockets).
836  */
837 static void filed_free_jcr(JCR *jcr) 
838 {
839    if (jcr->store_bsock) {
840       bnet_close(jcr->store_bsock);
841    }
842    if (jcr->where) {
843       free_pool_memory(jcr->where);
844    }
845    if (jcr->RestoreBootstrap) {
846       unlink(jcr->RestoreBootstrap);
847       free_pool_memory(jcr->RestoreBootstrap);
848    }
849    if (jcr->last_fname) {
850       free_pool_memory(jcr->last_fname);
851    }
852    return;
853 }
854
855 /*
856  * Get response from Storage daemon to a command we
857  * sent. Check that the response is OK.
858  *
859  *  Returns: 0 on failure
860  *           1 on success
861  */
862 int response(JCR *jcr, BSOCK *sd, char *resp, char *cmd)
863 {
864    int n;
865
866    if (sd->errors) {
867       return 0;
868    }
869    if ((n = bget_msg(sd)) > 0) {
870       Dmsg0(110, sd->msg);
871       if (strcmp(sd->msg, resp) == 0) {
872          return 1;
873       }
874    } 
875    if (is_bnet_error(sd)) {
876       Jmsg2(jcr, M_FATAL, 0, _("Comm error with SD. bad response to %s. ERR=%s\n"),
877          cmd, bnet_strerror(sd));
878    } else {
879       Jmsg3(jcr, M_FATAL, 0, _("Bad response to %s command. Wanted %s, got %s\n"),
880          cmd, resp, sd->msg);
881    }
882    return 0;
883 }
884
885 static int send_bootstrap_file(JCR *jcr)
886 {
887    FILE *bs;
888    char buf[2000];
889    BSOCK *sd = jcr->store_bsock;
890    char *bootstrap = "bootstrap\n";
891
892    Dmsg1(400, "send_bootstrap_file: %s\n", jcr->RestoreBootstrap);
893    if (!jcr->RestoreBootstrap) {
894       return 1;
895    }
896    bs = fopen(jcr->RestoreBootstrap, "r");
897    if (!bs) {
898       Jmsg(jcr, M_FATAL, 0, _("Could not open bootstrap file %s: ERR=%s\n"), 
899          jcr->RestoreBootstrap, strerror(errno));
900       set_jcr_job_status(jcr, JS_ErrorTerminated);
901       return 0;
902    }
903    strcpy(sd->msg, bootstrap);  
904    sd->msglen = strlen(sd->msg);
905    bnet_send(sd);
906    while (fgets(buf, sizeof(buf), bs)) {
907       sd->msglen = Mmsg(&sd->msg, "%s", buf);
908       bnet_send(sd);       
909    }
910    bnet_sig(sd, BNET_EOD);
911    fclose(bs);
912    if (!response(jcr, sd, OKSDbootstrap, "Bootstrap")) {
913       set_jcr_job_status(jcr, JS_ErrorTerminated);
914       return 0;
915    }
916    return 1;
917 }