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