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