]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/filed/job.c
Add const for Solaris' C++ compiler
[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-2004 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, const 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, const 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 %s,%s,%s";
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 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
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_with_commas(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, HOST_OS, DISTNAME, DISTVER);
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, const 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, *q;
420    BPIPE *bpipe;
421    POOLMEM *fn;
422    FILE *ffd;
423    char buf[1000];
424    int optlen;
425    int stat;
426
427    /* Skip leading options -- currently ignored */
428    for (p=fname; *p && *p != ' '; p++)
429       { }
430    /* Skip spaces, and q points to first space */
431    for (q=NULL; *p && *p == ' '; p++) {
432       if (!q) {
433          q = p;
434       }
435    }
436
437    switch (*p) {
438    case '|':
439       p++;                            /* skip over | */
440       fn = get_pool_memory(PM_FNAME);
441       fn = edit_job_codes(jcr, fn, p, "");
442       bpipe = open_bpipe(fn, 0, "r");
443       free_pool_memory(fn);
444       if (!bpipe) {
445          Jmsg(jcr, M_FATAL, 0, _("Cannot run program: %s. ERR=%s\n"),
446             p, strerror(errno));
447          return;
448       }
449       /* Copy File options */
450       if (list == INC_LIST) {
451          *q = 0;                      /* terminate options */
452          strcpy(buf, fname);
453          strcat(buf, " ");
454          optlen = strlen(buf);
455       } else {
456          optlen = 0;
457       }
458       while (fgets(buf+optlen, sizeof(buf)-optlen, bpipe->rfd)) {
459          strip_trailing_junk(buf);
460          if (list == INC_LIST) {
461             add_fname_to_include_list((FF_PKT *)jcr->ff, 1, buf);
462          } else {
463             add_fname_to_exclude_list((FF_PKT *)jcr->ff, buf);
464          }
465       }
466       if ((stat=close_bpipe(bpipe)) != 0) {
467          Jmsg(jcr, M_FATAL, 0, _("Error running program: %s. RtnStat=%d ERR=%s\n"),
468             p, stat, strerror(errno));
469          return;
470       }
471       break;
472    case '<':
473       p++;                      /* skip over < */
474       if ((ffd = fopen(p, "r")) == NULL) {
475          Jmsg(jcr, M_FATAL, 0, _("Cannot open %s file: %s. ERR=%s\n"),
476             list==INC_LIST?"included":"excluded", p, strerror(errno));
477          return;
478       }
479       /* Copy File options */
480       if (list == INC_LIST) {
481          *q = 0;                      /* terminate options */
482          strcpy(buf, fname);
483          strcat(buf, " ");
484          optlen = strlen(buf);
485       } else {
486          optlen = 0;
487       }
488       while (fgets(buf+optlen, sizeof(buf)-optlen, ffd)) {
489          strip_trailing_junk(buf);
490          if (list == INC_LIST) {
491             add_fname_to_include_list((FF_PKT *)jcr->ff, 1, buf);
492          } else {
493             add_fname_to_exclude_list((FF_PKT *)jcr->ff, buf);
494          }
495       }
496       fclose(ffd);
497       break;
498    default:
499       if (list == INC_LIST) {
500          add_fname_to_include_list((FF_PKT *)jcr->ff, 1, fname);
501       } else {
502          add_fname_to_exclude_list((FF_PKT *)jcr->ff, p);
503       }
504       break;
505    }
506 }
507
508 /* 
509  * 
510  * Get list of files/directories to include from Director
511  *
512  */
513 static int include_cmd(JCR *jcr)
514 {
515    BSOCK *dir = jcr->dir_bsock;
516
517    while (bnet_recv(dir) >= 0) {
518       dir->msg[dir->msglen] = 0;
519       strip_trailing_junk(dir->msg);
520       Dmsg1(010, "include file: %s\n", dir->msg);
521       add_fname_to_list(jcr, dir->msg, INC_LIST);
522    }
523
524    return bnet_fsend(dir, OKinc);
525 }
526
527 /*
528  * Get list of files to exclude from Director
529  *
530  */
531 static int exclude_cmd(JCR *jcr)
532 {
533    BSOCK *dir = jcr->dir_bsock;
534
535    while (bnet_recv(dir) >= 0) {
536       dir->msg[dir->msglen] = 0;
537       strip_trailing_junk(dir->msg);
538       add_fname_to_list(jcr, dir->msg, EXC_LIST);
539       Dmsg1(110, "<dird: exclude file %s\n", dir->msg);
540    }
541
542    return bnet_fsend(dir, OKexc);
543 }
544
545
546 static int bootstrap_cmd(JCR *jcr)
547 {
548    BSOCK *dir = jcr->dir_bsock;
549    POOLMEM *fname = get_pool_memory(PM_FNAME);
550    FILE *bs;
551
552    if (jcr->RestoreBootstrap) {
553       unlink(jcr->RestoreBootstrap);
554       free_pool_memory(jcr->RestoreBootstrap);
555    }
556    Mmsg(&fname, "%s/%s.%s.bootstrap", me->working_directory, me->hdr.name,
557       jcr->Job);
558    Dmsg1(400, "bootstrap=%s\n", fname);
559    jcr->RestoreBootstrap = fname;
560    bs = fopen(fname, "a+");           /* create file */
561    if (!bs) {
562       /* 
563        * Suck up what he is sending to us so that he will then
564        *   read our error message.
565        */
566       while (bnet_recv(dir) >= 0)
567         {  }
568
569       Jmsg(jcr, M_FATAL, 0, _("Could not create bootstrap file %s: ERR=%s\n"),
570          jcr->RestoreBootstrap, strerror(errno));
571       free_pool_memory(jcr->RestoreBootstrap);
572       jcr->RestoreBootstrap = NULL;
573       set_jcr_job_status(jcr, JS_ErrorTerminated);
574       return 0;
575    }
576
577    while (bnet_recv(dir) >= 0) {
578        Dmsg1(200, "filed<dird: bootstrap file %s\n", dir->msg);
579        fputs(dir->msg, bs);
580    }
581    fclose(bs);
582
583    return bnet_fsend(dir, OKbootstrap);
584 }
585
586
587 /*
588  * Get backup level from Director
589  *
590  */
591 static int level_cmd(JCR *jcr)
592 {
593    BSOCK *dir = jcr->dir_bsock;
594    POOLMEM *level, *buf = NULL;
595    struct tm tm;
596    time_t mtime;
597    int mtime_only;
598
599    level = get_memory(dir->msglen+1);
600    Dmsg1(110, "level_cmd: %s", dir->msg);
601    if (sscanf(dir->msg, "level = %s ", level) != 1) {
602       goto bail_out;
603    }
604    /* Base backup requested? */
605    if (strcmp(level, "base") == 0) {
606       jcr->JobLevel = L_BASE;
607    /* Full backup requested? */ 
608    } else if (strcmp(level, "full") == 0) {
609       jcr->JobLevel = L_FULL;
610    /* 
611     * Backup requested since <date> <time>
612     *  This form is also used for incremental and differential
613     *  This code is deprecated.  See since_utime for new code.
614     */
615    } else if (strcmp(level, "since") == 0) {
616       jcr->JobLevel = L_SINCE;
617       if (sscanf(dir->msg, "level = since %d-%d-%d %d:%d:%d mtime_only=%d", 
618                  &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
619                  &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &mtime_only) != 7) {
620          goto bail_out;
621       }
622       tm.tm_year -= 1900;
623       tm.tm_mon  -= 1;
624       tm.tm_wday = tm.tm_yday = 0;              
625       tm.tm_isdst = -1;
626       mtime = mktime(&tm);
627       Dmsg2(100, "Got since time: %s mtime_only=%d\n", ctime(&mtime), mtime_only);
628       jcr->incremental = 1;           /* set incremental or decremental backup */
629       jcr->mtime = mtime;             /* set since time */
630       jcr->mtime_only = mtime_only;   /* and what to compare */
631    /*
632     * We get his UTC since time, then sync the clocks and correct it
633     *   to agree with our clock.
634     */
635    } else if (strcmp(level, "since_utime") == 0) {
636       buf = get_memory(dir->msglen+1);
637       utime_t since_time, adj;
638       btime_t his_time, bt_start, rt=0, bt_adj=0;
639       jcr->JobLevel = L_SINCE;
640       if (sscanf(dir->msg, "level = since_utime %s mtime_only=%d", 
641                  buf, &mtime_only) != 2) { 
642          goto bail_out;
643       }
644       since_time = str_to_uint64(buf);  /* this is the since time */
645       char ed1[50], ed2[50];
646       /* 
647        * Sync clocks by polling him for the time. We take        
648        *   10 samples of his time throwing out the first two.
649        */
650       for (int i=0; i<10; i++) {
651          bt_start = get_current_btime();
652          bnet_sig(dir, BNET_BTIME);   /* poll for time */
653          if (bnet_recv(dir) <= 0) {   /* get response */
654             goto bail_out;
655          }
656          if (sscanf(dir->msg, "btime %s", buf) != 1) {
657             goto bail_out;
658          }
659          if (i < 2) {                 /* toss first two results */
660             continue;
661          }
662          his_time = str_to_uint64(buf);
663          rt = get_current_btime() - bt_start; /* compute round trip time */
664          bt_adj -= his_time - bt_start - rt/2;
665          Dmsg2(100, "rt=%s adj=%s\n", edit_uint64(rt, ed1), edit_uint64(bt_adj, ed2));
666       }
667
668       bt_adj = bt_adj / 8;            /* compute average time */
669       Dmsg2(100, "rt=%s adj=%s\n", edit_uint64(rt, ed1), edit_uint64(bt_adj, ed2));
670       adj = btime_to_utime(bt_adj);
671       since_time += adj;              /* adjust for clock difference */
672       if (adj != 0) {
673          Jmsg(jcr, M_INFO, 0, _("Since time adjusted by %d seconds.\n"), adj);
674       }
675       bnet_sig(dir, BNET_EOD);
676
677       Dmsg2(100, "adj = %d since_time=%d\n", (int)adj, (int)since_time);
678       jcr->incremental = 1;           /* set incremental or decremental backup */
679       jcr->mtime = since_time;        /* set since time */
680       jcr->mtime_only = mtime_only;   /* and what to compare */
681    } else {
682       Jmsg1(jcr, M_FATAL, 0, "Unknown backup level: %s\n", level);
683       free_memory(level);
684       return 0;
685    }
686    free_memory(level);
687    if (buf) {
688       free_memory(buf);
689    }
690    return bnet_fsend(dir, OKlevel);
691
692 bail_out:
693    pm_strcpy(&jcr->errmsg, dir->msg);
694    Jmsg1(jcr, M_FATAL, 0, _("Bad level command: %s\n"), jcr->errmsg);
695    free_memory(level);
696    if (buf) {
697       free_memory(buf);
698    }
699    return 0;
700 }
701
702 /*
703  * Get session parameters from Director -- this is for a Restore command
704  */
705 static int session_cmd(JCR *jcr)
706 {
707    BSOCK *dir = jcr->dir_bsock;
708
709    Dmsg1(100, "SessionCmd: %s", dir->msg);
710    if (sscanf(dir->msg, sessioncmd, jcr->VolumeName,
711               &jcr->VolSessionId, &jcr->VolSessionTime,
712               &jcr->StartFile, &jcr->EndFile, 
713               &jcr->StartBlock, &jcr->EndBlock) != 7) {
714       pm_strcpy(&jcr->errmsg, dir->msg);
715       Jmsg(jcr, M_FATAL, 0, "Bad session command: %s", jcr->errmsg);
716       return 0;
717    }
718
719    return bnet_fsend(dir, OKsession);
720 }
721
722 /*
723  * Get address of storage daemon from Director
724  *
725  */
726 static int storage_cmd(JCR *jcr)
727 {
728    int stored_port;                /* storage daemon port */
729    int enable_ssl;                 /* enable ssl to sd */
730    BSOCK *dir = jcr->dir_bsock;
731    BSOCK *sd;                         /* storage daemon bsock */
732
733    Dmsg1(100, "StorageCmd: %s", dir->msg);
734    if (sscanf(dir->msg, storaddr, &jcr->stored_addr, &stored_port, &enable_ssl) != 3) {
735       pm_strcpy(&jcr->errmsg, dir->msg);
736       Jmsg(jcr, M_FATAL, 0, _("Bad storage command: %s"), jcr->errmsg);
737       return 0;
738    }
739    Dmsg3(110, "Open storage: %s:%d ssl=%d\n", jcr->stored_addr, stored_port, enable_ssl);
740    /* Open command communications with Storage daemon */
741    /* Try to connect for 1 hour at 10 second intervals */
742    sd = bnet_connect(jcr, 10, me->SDConnectTimeout, _("Storage daemon"), 
743                      jcr->stored_addr, NULL, stored_port, 1);
744    if (sd == NULL) {
745       Jmsg(jcr, M_FATAL, 0, _("Failed to connect to Storage daemon: %s:%d\n"),
746           jcr->stored_addr, stored_port);
747       return 0;
748    }
749
750    jcr->store_bsock = sd;
751
752    bnet_fsend(sd, "Hello Start Job %s\n", jcr->Job);
753    if (!authenticate_storagedaemon(jcr)) {
754       Jmsg(jcr, M_FATAL, 0, _("Failed to authenticate Storage daemon.\n"));
755       return 0;
756    }
757    Dmsg0(110, "Authenticated with SD.\n");
758
759    /* Send OK to Director */
760    return bnet_fsend(dir, OKstore);
761 }
762
763
764 /*  
765  * Do a backup. For now, we handle only Full and Incremental.
766  */
767 static int backup_cmd(JCR *jcr)
768
769    BSOCK *dir = jcr->dir_bsock;
770    BSOCK *sd = jcr->store_bsock;
771    int ok = 0;
772    int SDJobStatus;
773    char ed1[50], ed2[50];
774
775    set_jcr_job_status(jcr, JS_Blocked);
776    jcr->JobType = JT_BACKUP;
777    Dmsg1(100, "begin backup ff=%p\n", (FF_PKT *)jcr->ff);
778
779    if (sd == NULL) {
780       Jmsg(jcr, M_FATAL, 0, _("Cannot contact Storage daemon\n"));
781       goto cleanup;
782    }
783
784    bnet_fsend(dir, OKbackup);
785    Dmsg1(110, "bfiled>dird: %s", dir->msg);
786
787    /* 
788     * Send Append Open Session to Storage daemon
789     */
790    bnet_fsend(sd, append_open);
791    Dmsg1(110, ">stored: %s", sd->msg);
792    /* 
793     * Expect to receive back the Ticket number
794     */
795    if (bget_msg(sd) >= 0) {
796       Dmsg1(110, "<stored: %s", sd->msg);
797       if (sscanf(sd->msg, OK_open, &jcr->Ticket) != 1) {
798          Jmsg(jcr, M_FATAL, 0, _("Bad response to append open: %s\n"), sd->msg);
799          goto cleanup;
800       }
801       Dmsg1(110, "Got Ticket=%d\n", jcr->Ticket);
802    } else {
803       Jmsg(jcr, M_FATAL, 0, _("Bad response from stored to open command\n"));
804       goto cleanup;
805    }
806
807    /* 
808     * Send Append data command to Storage daemon
809     */
810    bnet_fsend(sd, append_data, jcr->Ticket);
811    Dmsg1(110, ">stored: %s", sd->msg);
812
813    /* 
814     * Expect to get OK data 
815     */
816    Dmsg1(110, "<stored: %s", sd->msg);
817    if (!response(jcr, sd, OK_data, "Append Data")) {
818       goto cleanup;
819    }
820       
821    /*
822     * Send Files to Storage daemon
823     */
824    Dmsg1(110, "begin blast ff=%p\n", (FF_PKT *)jcr->ff);
825    if (!blast_data_to_storage_daemon(jcr, NULL)) {
826       set_jcr_job_status(jcr, JS_ErrorTerminated);
827       bnet_suppress_error_messages(sd, 1);
828    } else {
829       set_jcr_job_status(jcr, JS_Terminated);
830       if (jcr->JobStatus != JS_Terminated) {
831          bnet_suppress_error_messages(sd, 1);
832          goto cleanup;                /* bail out now */
833       }
834       /* 
835        * Expect to get response to append_data from Storage daemon
836        */
837       if (!response(jcr, sd, OK_append, "Append Data")) {
838          set_jcr_job_status(jcr, JS_ErrorTerminated);
839          goto cleanup;
840       }
841      
842       /* 
843        * Send Append End Data to Storage daemon
844        */
845       bnet_fsend(sd, append_end, jcr->Ticket);
846       /* Get end OK */
847       if (!response(jcr, sd, OK_end, "Append End")) {
848          set_jcr_job_status(jcr, JS_ErrorTerminated);
849          goto cleanup;
850       }
851
852       /*
853        * Send Append Close to Storage daemon
854        */
855       bnet_fsend(sd, append_close, jcr->Ticket);
856       while (bget_msg(sd) >= 0) {    /* stop on signal or error */
857          if (sscanf(sd->msg, OK_close, &SDJobStatus) == 1) {
858             ok = 1;
859             Dmsg2(200, "SDJobStatus = %d %c\n", SDJobStatus, (char)SDJobStatus);
860          }
861       }
862       if (!ok) {
863          Jmsg(jcr, M_FATAL, 0, _("Append Close with SD failed.\n"));
864          goto cleanup;
865       }
866       if (SDJobStatus != JS_Terminated) {
867          Jmsg(jcr, M_FATAL, 0, _("Bad status %d returned from Storage Daemon.\n"),
868             SDJobStatus);
869       }
870    }
871
872 cleanup:
873
874    bnet_fsend(dir, EndJob, jcr->JobStatus, jcr->JobFiles, 
875       edit_uint64(jcr->ReadBytes, ed1), 
876       edit_uint64(jcr->JobBytes, ed2), jcr->Errors);    
877
878    return 0;                          /* return and stop command loop */
879 }
880
881 /*  
882  * Do a Verify for Director
883  *
884  */
885 static int verify_cmd(JCR *jcr)
886
887    BSOCK *dir = jcr->dir_bsock;
888    BSOCK *sd  = jcr->store_bsock;
889    char level[100], ed1[50], ed2[50];
890
891    jcr->JobType = JT_VERIFY;
892    if (sscanf(dir->msg, verifycmd, level) != 1) {
893       bnet_fsend(dir, "2994 Bad verify command: %s\n", dir->msg);
894       return 0;   
895    }
896    if (strcasecmp(level, "init") == 0) {
897       jcr->JobLevel = L_VERIFY_INIT;
898    } else if (strcasecmp(level, "catalog") == 0){
899       jcr->JobLevel = L_VERIFY_CATALOG;
900    } else if (strcasecmp(level, "volume") == 0){
901       jcr->JobLevel = L_VERIFY_VOLUME_TO_CATALOG;
902    } else if (strcasecmp(level, "data") == 0){
903       jcr->JobLevel = L_VERIFY_DATA;
904    } else if (strcasecmp(level, "disk_to_catalog") == 0) {
905       jcr->JobLevel = L_VERIFY_DISK_TO_CATALOG;
906    } else {   
907       bnet_fsend(dir, "2994 Bad verify level: %s\n", dir->msg);
908       return 0;   
909    }
910
911    bnet_fsend(dir, OKverify);
912    Dmsg1(110, "bfiled>dird: %s", dir->msg);
913
914    switch (jcr->JobLevel) {
915    case L_VERIFY_INIT:
916    case L_VERIFY_CATALOG:
917       do_verify(jcr);
918       break;
919    case L_VERIFY_VOLUME_TO_CATALOG:
920       if (!open_sd_read_session(jcr)) {
921          return 0;
922       }
923       start_dir_heartbeat(jcr);
924       do_verify_volume(jcr);
925       stop_dir_heartbeat(jcr);
926       /* 
927        * Send Close session command to Storage daemon
928        */
929       bnet_fsend(sd, read_close, jcr->Ticket);
930       Dmsg1(130, "bfiled>stored: %s", sd->msg);
931
932       /* ****FIXME**** check response */
933       bget_msg(sd);                      /* get OK */
934
935       /* Inform Storage daemon that we are done */
936       bnet_sig(sd, BNET_TERMINATE);
937
938       break;
939    case L_VERIFY_DISK_TO_CATALOG:
940       do_verify(jcr);
941       break;
942    default:
943       bnet_fsend(dir, "2994 Bad verify level: %s\n", dir->msg);
944       return 0; 
945    }
946
947    bnet_sig(dir, BNET_EOD);
948
949    /* Send termination status back to Dir */
950    bnet_fsend(dir, EndJob, jcr->JobStatus, jcr->JobFiles, 
951       edit_uint64(jcr->ReadBytes, ed1), 
952       edit_uint64(jcr->JobBytes, ed2), jcr->Errors);    
953
954    /* Inform Director that we are done */
955    bnet_sig(dir, BNET_TERMINATE);
956    return 0;                          /* return and terminate command loop */
957 }
958
959 /*  
960  * Do a Restore for Director
961  *
962  */
963 static int restore_cmd(JCR *jcr)
964
965    BSOCK *dir = jcr->dir_bsock;
966    BSOCK *sd = jcr->store_bsock;
967    POOLMEM *where;
968    int prefix_links;
969    char replace;
970    char ed1[50], ed2[50];
971
972    /*
973     * Scan WHERE (base directory for restore) from command
974     */
975    Dmsg0(150, "restore command\n");
976    /* Pickup where string */
977    where = get_memory(dir->msglen+1);
978    *where = 0;
979
980    if (sscanf(dir->msg, restorecmd, &replace, &prefix_links, where) != 3) {
981       if (sscanf(dir->msg, restorecmd1, &replace, &prefix_links) != 2) {
982          pm_strcpy(&jcr->errmsg, dir->msg);
983          Jmsg(jcr, M_FATAL, 0, _("Bad replace command. CMD=%s\n"), jcr->errmsg);
984          return 0;
985       }
986       *where = 0;
987    }
988    /* Turn / into nothing */
989    if (where[0] == '/' && where[1] == 0) {
990       where[0] = 0;
991    }
992       
993    Dmsg2(150, "Got replace %c, where=%s\n", replace, where);
994    unbash_spaces(where);
995    jcr->where = bstrdup(where);
996    free_pool_memory(where);
997    jcr->replace = replace;
998    jcr->prefix_links = prefix_links;
999
1000    bnet_fsend(dir, OKrestore);
1001    Dmsg1(110, "bfiled>dird: %s", dir->msg);
1002
1003    jcr->JobType = JT_RESTORE;
1004
1005    set_jcr_job_status(jcr, JS_Blocked);
1006    if (!open_sd_read_session(jcr)) {
1007       set_jcr_job_status(jcr, JS_ErrorTerminated);
1008       goto bail_out;
1009    }
1010
1011    set_jcr_job_status(jcr, JS_Running);
1012
1013    /* 
1014     * Do restore of files and data
1015     */
1016    start_dir_heartbeat(jcr);
1017    do_restore(jcr);
1018    stop_dir_heartbeat(jcr);
1019    
1020    set_jcr_job_status(jcr, JS_Terminated);
1021    if (jcr->JobStatus != JS_Terminated) {
1022       bnet_suppress_error_messages(sd, 1);
1023    }
1024
1025    /* 
1026     * Send Close session command to Storage daemon
1027     */
1028    bnet_fsend(sd, read_close, jcr->Ticket);
1029    Dmsg1(130, "bfiled>stored: %s", sd->msg);
1030
1031    bget_msg(sd);                      /* get OK */
1032
1033    /* Inform Storage daemon that we are done */
1034    bnet_sig(sd, BNET_TERMINATE);
1035
1036 bail_out:
1037
1038    if (jcr->Errors) {
1039       set_jcr_job_status(jcr, JS_ErrorTerminated);
1040    }
1041    /* Send termination status back to Dir */
1042    bnet_fsend(dir, EndJob, jcr->JobStatus, jcr->JobFiles, 
1043       edit_uint64(jcr->ReadBytes, ed1), 
1044       edit_uint64(jcr->JobBytes, ed2), jcr->Errors);    
1045
1046    /* Inform Director that we are done */
1047    bnet_sig(dir, BNET_TERMINATE);
1048
1049    Dmsg0(130, "Done in job.c\n");
1050    return 0;                          /* return and terminate command loop */
1051 }
1052
1053 static int open_sd_read_session(JCR *jcr)
1054 {
1055    BSOCK *sd = jcr->store_bsock;
1056
1057    if (!sd) {
1058       Jmsg(jcr, M_FATAL, 0, _("Improper calling sequence.\n"));
1059       return 0;
1060    }
1061    Dmsg4(120, "VolSessId=%ld VolsessT=%ld SF=%ld EF=%ld\n",
1062       jcr->VolSessionId, jcr->VolSessionTime, jcr->StartFile, jcr->EndFile);
1063    Dmsg2(120, "JobId=%d vol=%s\n", jcr->JobId, "DummyVolume");
1064    /* 
1065     * Open Read Session with Storage daemon
1066     */
1067    bnet_fsend(sd, read_open, jcr->VolumeName,
1068       jcr->VolSessionId, jcr->VolSessionTime, jcr->StartFile, jcr->EndFile, 
1069       jcr->StartBlock, jcr->EndBlock);
1070    Dmsg1(110, ">stored: %s", sd->msg);
1071
1072    /* 
1073     * Get ticket number
1074     */
1075    if (bget_msg(sd) >= 0) {
1076       Dmsg1(110, "bfiled<stored: %s", sd->msg);
1077       if (sscanf(sd->msg, OK_open, &jcr->Ticket) != 1) {
1078          Jmsg(jcr, M_FATAL, 0, _("Bad response to SD read open: %s\n"), sd->msg);
1079          return 0;
1080       }
1081       Dmsg1(110, "bfiled: got Ticket=%d\n", jcr->Ticket);
1082    } else {
1083       Jmsg(jcr, M_FATAL, 0, _("Bad response from stored to read open command\n"));
1084       return 0;
1085    }
1086
1087    if (!send_bootstrap_file(jcr)) {
1088       return 0;
1089    }
1090
1091    /* 
1092     * Start read of data with Storage daemon
1093     */
1094    bnet_fsend(sd, read_data, jcr->Ticket);
1095    Dmsg1(110, ">stored: %s", sd->msg);
1096
1097    /* 
1098     * Get OK data
1099     */
1100    if (!response(jcr, sd, OK_data, "Read Data")) {
1101       return 0;
1102    }
1103    return 1;
1104 }
1105
1106 /* 
1107  * Destroy the Job Control Record and associated
1108  * resources (sockets).
1109  */
1110 static void filed_free_jcr(JCR *jcr) 
1111 {
1112    if (jcr->store_bsock) {
1113       bnet_close(jcr->store_bsock);
1114    }
1115    if (jcr->RestoreBootstrap) {
1116       unlink(jcr->RestoreBootstrap);
1117       free_pool_memory(jcr->RestoreBootstrap);
1118       jcr->RestoreBootstrap = NULL;
1119    }
1120    if (jcr->last_fname) {
1121       free_pool_memory(jcr->last_fname);
1122    }
1123    if (jcr->RunAfterJob) {
1124       free_pool_memory(jcr->RunAfterJob);
1125    }
1126    return;
1127 }
1128
1129 /*
1130  * Get response from Storage daemon to a command we
1131  * sent. Check that the response is OK.
1132  *
1133  *  Returns: 0 on failure
1134  *           1 on success
1135  */
1136 int response(JCR *jcr, BSOCK *sd, char *resp, const char *cmd)
1137 {
1138    if (sd->errors) {
1139       return 0;
1140    }
1141    if (bget_msg(sd) > 0) {
1142       Dmsg0(110, sd->msg);
1143       if (strcmp(sd->msg, resp) == 0) {
1144          return 1;
1145       }
1146    } 
1147    if (job_canceled(jcr)) {
1148       return 0;                       /* if canceled avoid useless error messages */
1149    }
1150    if (is_bnet_error(sd)) {
1151       Jmsg2(jcr, M_FATAL, 0, _("Comm error with SD. bad response to %s. ERR=%s\n"),
1152          cmd, bnet_strerror(sd));
1153    } else {
1154       Jmsg3(jcr, M_FATAL, 0, _("Bad response to %s command. Wanted %s, got %s\n"),
1155          cmd, resp, sd->msg);
1156    }
1157    return 0;
1158 }
1159
1160 static int send_bootstrap_file(JCR *jcr)
1161 {
1162    FILE *bs;
1163    char buf[2000];
1164    BSOCK *sd = jcr->store_bsock;
1165    char *bootstrap = "bootstrap\n";
1166    int stat = 0;
1167
1168    Dmsg1(400, "send_bootstrap_file: %s\n", jcr->RestoreBootstrap);
1169    if (!jcr->RestoreBootstrap) {
1170       return 1;
1171    }
1172    bs = fopen(jcr->RestoreBootstrap, "r");
1173    if (!bs) {
1174       Jmsg(jcr, M_FATAL, 0, _("Could not open bootstrap file %s: ERR=%s\n"), 
1175          jcr->RestoreBootstrap, strerror(errno));
1176       set_jcr_job_status(jcr, JS_ErrorTerminated);
1177       goto bail_out;
1178    }
1179    pm_strcpy(&sd->msg, bootstrap);  
1180    sd->msglen = strlen(sd->msg);
1181    bnet_send(sd);
1182    while (fgets(buf, sizeof(buf), bs)) {
1183       sd->msglen = Mmsg(&sd->msg, "%s", buf);
1184       bnet_send(sd);       
1185    }
1186    bnet_sig(sd, BNET_EOD);
1187    fclose(bs);
1188    if (!response(jcr, sd, OKSDbootstrap, "Bootstrap")) {
1189       set_jcr_job_status(jcr, JS_ErrorTerminated);
1190       goto bail_out;
1191    }
1192    stat = 1;
1193
1194 bail_out:
1195    if (jcr->RestoreBootstrap) {
1196       unlink(jcr->RestoreBootstrap);
1197       free_pool_memory(jcr->RestoreBootstrap);
1198       jcr->RestoreBootstrap = NULL;
1199    }
1200
1201    return stat;
1202 }