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