]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/fd_cmds.c
Make out of freespace non-fatal for removable devices -- i.e. behaves like tape
[bacula/bacula] / bacula / src / dird / fd_cmds.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2017 Kern Sibbald
5
6    The original author of Bacula is Kern Sibbald, with contributions
7    from many others, a complete list can be found in the file AUTHORS.
8
9    You may use this file and others of this release according to the
10    license defined in the LICENSE file, which includes the Affero General
11    Public License, v3.0 ("AGPLv3") and some additional permissions and
12    terms pursuant to its AGPLv3 Section 7.
13
14    This notice must be preserved when any source code is 
15    conveyed and/or propagated.
16
17    Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20  *
21  *   Bacula Director -- fd_cmds.c -- send commands to File daemon
22  *
23  *     Kern Sibbald, October MM
24  *
25  *    This routine is run as a separate thread.  There may be more
26  *    work to be done to make it totally reentrant!!!!
27  *
28  *  Utility functions for sending info to File Daemon.
29  *   These functions are used by both backup and verify.
30  *
31  */
32
33 #include "bacula.h"
34 #include "dird.h"
35 #include "findlib/find.h"
36
37 const int dbglvl = 400;
38
39 /* Commands sent to File daemon */
40 static char filesetcmd[]  = "fileset%s%s\n"; /* set full fileset */
41 static char jobcmd[]      = "JobId=%s Job=%s SDid=%u SDtime=%u Authorization=%s\n";
42 /* Note, mtime_only is not used here -- implemented as file option */
43 static char levelcmd[]    = "level = %s%s%s mtime_only=%d %s%s\n";
44 static char runscript[]   = "Run OnSuccess=%u OnFailure=%u AbortOnError=%u When=%u Command=%s\n";
45 static char runbeforenow[]= "RunBeforeNow\n";
46 static char bandwidthcmd[] = "setbandwidth=%lld Job=%s\n";
47 static char component_info[] = "component_info\n";
48
49 /* Responses received from File daemon */
50 static char OKinc[]          = "2000 OK include\n";
51 static char OKjob[]          = "2000 OK Job";
52 static char OKlevel[]        = "2000 OK level\n";
53 static char OKRunScript[]    = "2000 OK RunScript\n";
54 static char OKRunBeforeNow[] = "2000 OK RunBeforeNow\n";
55 static char OKRestoreObject[] = "2000 OK ObjectRestored\n";
56 static char OKComponentInfo[] = "2000 OK ComponentInfo\n";
57 static char OKBandwidth[]    = "2000 OK Bandwidth\n";
58
59 /* Forward referenced functions */
60 static bool send_list_item(JCR *jcr, const char *code, char *item, BSOCK *fd);
61
62 /* External functions */
63 extern DIRRES *director;
64 extern int FDConnectTimeout;
65
66 #define INC_LIST 0
67 #define EXC_LIST 1
68
69 /*
70  * Open connection with File daemon.
71  * Try connecting every retry_interval (default 10 sec), and
72  *   give up after max_retry_time (default 30 mins).
73  */
74
75 int connect_to_file_daemon(JCR *jcr, int retry_interval, int max_retry_time,
76                            int verbose)
77 {
78    BSOCK   *fd = jcr->file_bsock;
79    char ed1[30];
80    utime_t heart_beat;
81
82    if (!jcr->client) {
83       Jmsg(jcr, M_FATAL, 0, _("File daemon not defined for current Job\n"));
84       Dmsg0(10, "No Client defined for the job.\n");
85       return 0;
86    }
87
88    if (jcr->client->heartbeat_interval) {
89       heart_beat = jcr->client->heartbeat_interval;
90    } else {
91       heart_beat = director->heartbeat_interval;
92    }
93
94    if (!is_bsock_open(jcr->file_bsock)) {
95       char name[MAX_NAME_LENGTH + 100];
96       POOL_MEM buf;
97
98       if (!fd) {
99          fd = jcr->file_bsock = new_bsock();
100       }
101       bstrncpy(name, _("Client: "), sizeof(name));
102       bstrncat(name, jcr->client->name(), sizeof(name));
103
104       fd->set_source_address(director->DIRsrc_addr);
105       if (!fd->connect(jcr,retry_interval,
106                        max_retry_time,
107                        heart_beat, name,
108                        jcr->client->address(buf.addr()),
109                        NULL,
110                        jcr->client->FDport,
111                        verbose)) {
112          fd->close();
113          jcr->setJobStatus(JS_ErrorTerminated);
114          return 0;
115       }
116       Dmsg0(10, "Opened connection with File daemon\n");
117    }
118    fd->res = (RES *)jcr->client;      /* save resource in BSOCK */
119    jcr->setJobStatus(JS_Running);
120
121    if (!authenticate_file_daemon(jcr)) {
122       jcr->setJobStatus(JS_ErrorTerminated);
123       Dmsg0(10, "Authentication error with FD.\n");
124       return 0;
125    }
126
127    /*
128     * Now send JobId and authorization key
129     */
130    if (jcr->sd_auth_key == NULL) {
131       jcr->sd_auth_key = bstrdup("dummy");
132    }
133    fd->fsend(jobcmd, edit_int64(jcr->JobId, ed1), jcr->Job, jcr->VolSessionId,
134              jcr->VolSessionTime, jcr->sd_auth_key);
135    if (!jcr->keep_sd_auth_key && strcmp(jcr->sd_auth_key, "dummy")) {
136       memset(jcr->sd_auth_key, 0, strlen(jcr->sd_auth_key));
137    }
138    Dmsg1(100, ">filed: %s", fd->msg);
139    if (bget_dirmsg(fd) > 0) {
140        Dmsg1(110, "<filed: %s", fd->msg);
141        if (strncmp(fd->msg, OKjob, strlen(OKjob)) != 0) {
142           Jmsg(jcr, M_FATAL, 0, _("File daemon \"%s\" rejected Job command: %s\n"),
143              jcr->client->hdr.name, fd->msg);
144           jcr->setJobStatus(JS_ErrorTerminated);
145           return 0;
146        } else if (jcr->db) {
147           CLIENT_DBR cr;
148           memset(&cr, 0, sizeof(cr));
149           bstrncpy(cr.Name, jcr->client->hdr.name, sizeof(cr.Name));
150           cr.AutoPrune = jcr->client->AutoPrune;
151           cr.FileRetention = jcr->client->FileRetention;
152           cr.JobRetention = jcr->client->JobRetention;
153           bstrncpy(cr.Uname, fd->msg+strlen(OKjob)+1, sizeof(cr.Uname));
154           if (!db_update_client_record(jcr, jcr->db, &cr)) {
155              Jmsg(jcr, M_WARNING, 0, _("Error updating Client record. ERR=%s\n"),
156                 db_strerror(jcr->db));
157           }
158        }
159    } else {
160       Jmsg(jcr, M_FATAL, 0, _("FD gave bad response to JobId command: %s\n"),
161          fd->bstrerror());
162       jcr->setJobStatus(JS_ErrorTerminated);
163       return 0;
164    }
165    return 1;
166 }
167
168 /*
169  * This subroutine edits the last job start time into a
170  *   "since=date/time" buffer that is returned in the
171  *   variable since.  This is used for display purposes in
172  *   the job report.  The time in jcr->stime is later
173  *   passed to tell the File daemon what to do.
174  */
175 void get_level_since_time(JCR *jcr, char *since, int since_len)
176 {
177    int JobLevel;
178    bool have_full;
179    bool do_full = false;
180    bool do_vfull = false;
181    bool do_diff = false;
182    utime_t now;
183    utime_t last_full_time = 0;
184    utime_t last_diff_time;
185    char prev_job[MAX_NAME_LENGTH];
186
187    since[0] = 0;
188    /* If job cloned and a since time already given, use it */
189    if (jcr->cloned && jcr->stime && jcr->stime[0]) {
190       bstrncpy(since, _(", since="), since_len);
191       bstrncat(since, jcr->stime, since_len);
192       return;
193    }
194    /* Make sure stime buffer is allocated */
195    if (!jcr->stime) {
196       jcr->stime = get_pool_memory(PM_MESSAGE);
197    }
198    jcr->PrevJob[0] = jcr->stime[0] = 0;
199    /*
200     * Lookup the last FULL backup job to get the time/date for a
201     * differential or incremental save.
202     */
203    switch (jcr->getJobLevel()) {
204    case L_DIFFERENTIAL:
205    case L_INCREMENTAL:
206       POOLMEM *stime = get_pool_memory(PM_MESSAGE);
207       /* Look up start time of last Full job */
208       now = (utime_t)time(NULL);
209       jcr->jr.JobId = 0;     /* flag to return since time */
210       /*
211        * This is probably redundant, but some of the code below
212        * uses jcr->stime, so don't remove unless you are sure.
213        */
214       if (!db_find_job_start_time(jcr, jcr->db, &jcr->jr, &jcr->stime, jcr->PrevJob)) {
215          do_full = true;
216       }
217       have_full = db_find_last_job_start_time(jcr, jcr->db, &jcr->jr,
218                                               &stime, prev_job, L_FULL);
219       if (have_full) {
220          last_full_time = str_to_utime(stime);
221       } else {
222          do_full = true;               /* No full, upgrade to one */
223       }
224       Dmsg4(50, "have_full=%d do_full=%d now=%lld full_time=%lld\n", have_full,
225             do_full, now, last_full_time);
226       /* Make sure the last diff is recent enough */
227       if (have_full && jcr->getJobLevel() == L_INCREMENTAL && jcr->job->MaxDiffInterval > 0) {
228          /* Lookup last diff job */
229          if (db_find_last_job_start_time(jcr, jcr->db, &jcr->jr,
230                                          &stime, prev_job, L_DIFFERENTIAL)) {
231             last_diff_time = str_to_utime(stime);
232             /* If no Diff since Full, use Full time */
233             if (last_diff_time < last_full_time) {
234                last_diff_time = last_full_time;
235             }
236             Dmsg2(50, "last_diff_time=%lld last_full_time=%lld\n", last_diff_time,
237                   last_full_time);
238          } else {
239             /* No last differential, so use last full time */
240             last_diff_time = last_full_time;
241             Dmsg1(50, "No last_diff_time setting to full_time=%lld\n", last_full_time);
242          }
243          do_diff = ((now - last_diff_time) >= jcr->job->MaxDiffInterval);
244          Dmsg2(50, "do_diff=%d diffInter=%lld\n", do_diff, jcr->job->MaxDiffInterval);
245       }
246       /* Note, do_full takes precedence over do_vfull and do_diff */
247       if (have_full && jcr->job->MaxFullInterval > 0) {
248          do_full = ((now - last_full_time) >= jcr->job->MaxFullInterval);
249       }
250       else
251       if (have_full && jcr->job->MaxVirtualFullInterval > 0) {
252          do_vfull = ((now - last_full_time) >= jcr->job->MaxVirtualFullInterval);
253       }
254       
255       free_pool_memory(stime);
256
257       if (do_full) {
258          /* No recent Full job found, so upgrade this one to Full */
259          Jmsg(jcr, M_INFO, 0, "%s", db_strerror(jcr->db));
260          Jmsg(jcr, M_INFO, 0, _("No prior or suitable Full backup found in catalog. Doing FULL backup.\n"));
261          bsnprintf(since, since_len, _(" (upgraded from %s)"),
262             level_to_str(jcr->getJobLevel()));
263          jcr->setJobLevel(jcr->jr.JobLevel = L_FULL);
264       } else if (do_vfull) {
265          /* No recent Full job found, and MaxVirtualFull is set so upgrade this one to Virtual Full */
266          Jmsg(jcr, M_INFO, 0, "%s", db_strerror(jcr->db));
267          Jmsg(jcr, M_INFO, 0, _("No prior or suitable Full backup found in catalog. Doing Virtual FULL backup.\n"));
268          bsnprintf(since, since_len, _(" (upgraded from %s)"),
269             level_to_str(jcr->getJobLevel()));
270          jcr->setJobLevel(jcr->jr.JobLevel = L_VIRTUAL_FULL);
271       } else if (do_diff) {
272          /* No recent diff job found, so upgrade this one to Diff */
273          Jmsg(jcr, M_INFO, 0, _("No prior or suitable Differential backup found in catalog. Doing Differential backup.\n"));
274          bsnprintf(since, since_len, _(" (upgraded from %s)"),
275             level_to_str(jcr->getJobLevel()));
276          jcr->setJobLevel(jcr->jr.JobLevel = L_DIFFERENTIAL);
277       } else {
278          if (jcr->job->rerun_failed_levels) {
279
280             POOLMEM *etime = get_pool_memory(PM_MESSAGE);
281
282             /* Get the end time of our most recent successfull backup for this job */
283             /* This will be used to see if there have been any failures since then */
284             if (db_find_last_job_end_time(jcr, jcr->db, &jcr->jr, &etime, prev_job)) {
285
286                /* See if there are any failed Differential/Full backups since the completion */
287                /* of our last successful backup for this job                                 */
288                if (db_find_failed_job_since(jcr, jcr->db, &jcr->jr,
289                                          etime, JobLevel)) {
290                  /* If our job is an Incremental and we have a failed job then upgrade.              */
291                  /* If our job is a Differential and the failed job is a Full then upgrade.          */
292                  /* Otherwise there is no reason to upgrade.                                         */
293                  if ((jcr->getJobLevel() == L_INCREMENTAL) || 
294                      ((jcr->getJobLevel() == L_DIFFERENTIAL) && (JobLevel == L_FULL))) {
295                     Jmsg(jcr, M_INFO, 0, _("Prior failed job found in catalog. Upgrading to %s.\n"),
296                        level_to_str(JobLevel));
297                     bsnprintf(since, since_len, _(" (upgraded from %s)"),
298                              level_to_str(jcr->getJobLevel()));
299                     jcr->setJobLevel(jcr->jr.JobLevel = JobLevel);
300                     jcr->jr.JobId = jcr->JobId;
301                     break;
302                  }
303                }
304             }
305             free_pool_memory(etime);
306          }
307          bstrncpy(since, _(", since="), since_len);
308          bstrncat(since, jcr->stime, since_len);
309       }
310       jcr->jr.JobId = jcr->JobId;
311       break;
312    }
313    Dmsg3(100, "Level=%c last start time=%s job=%s\n",
314          jcr->getJobLevel(), jcr->stime, jcr->PrevJob);
315 }
316
317 static void send_since_time(JCR *jcr)
318 {
319    BSOCK   *fd = jcr->file_bsock;
320    utime_t stime;
321    char ed1[50];
322
323    stime = str_to_utime(jcr->stime);
324    fd->fsend(levelcmd, "", NT_("since_utime "), edit_uint64(stime, ed1), 0,
325              NT_("prev_job="), jcr->PrevJob);
326    while (bget_dirmsg(fd) >= 0) {  /* allow him to poll us to sync clocks */
327       Jmsg(jcr, M_INFO, 0, "%s\n", fd->msg);
328    }
329 }
330
331 bool send_bwlimit(JCR *jcr, const char *Job)
332 {
333    BSOCK *fd = jcr->file_bsock;
334    if (jcr->FDVersion >= 4) {
335       fd->fsend(bandwidthcmd, jcr->max_bandwidth, Job);
336       if (!response(jcr, fd, OKBandwidth, "Bandwidth", DISPLAY_ERROR)) {
337          jcr->max_bandwidth = 0;      /* can't set bandwidth limit */
338          return false;
339       }
340    }
341    return true;
342 }
343
344 /*
345  * Send level command to FD.
346  * Used for backup jobs and estimate command.
347  */
348 bool send_level_command(JCR *jcr)
349 {
350    BSOCK   *fd = jcr->file_bsock;
351    const char *accurate = jcr->accurate?"accurate_":"";
352    const char *not_accurate = "";
353    const char *rerunning = jcr->rerunning?" rerunning ":" ";
354    /*
355     * Send Level command to File daemon
356     */
357    switch (jcr->getJobLevel()) {
358    case L_BASE:
359       fd->fsend(levelcmd, not_accurate, "base", rerunning, 0, "", "");
360       break;
361    /* L_NONE is the console, sending something off to the FD */
362    case L_NONE:
363    case L_FULL:
364       fd->fsend(levelcmd, not_accurate, "full", rerunning, 0, "", "");
365       break;
366    case L_DIFFERENTIAL:
367       fd->fsend(levelcmd, accurate, "differential", rerunning, 0, "", "");
368       send_since_time(jcr);
369       break;
370    case L_INCREMENTAL:
371       fd->fsend(levelcmd, accurate, "incremental", rerunning, 0, "", "");
372       send_since_time(jcr);
373       break;
374    case L_SINCE:
375    default:
376       Jmsg2(jcr, M_FATAL, 0, _("Unimplemented backup level %d %c\n"),
377          jcr->getJobLevel(), jcr->getJobLevel());
378       return 0;
379    }
380    Dmsg1(120, ">filed: %s", fd->msg);
381    if (!response(jcr, fd, OKlevel, "Level", DISPLAY_ERROR)) {
382       return false;
383    }
384    return true;
385 }
386
387 /*
388  * Send either an Included or an Excluded list to FD
389  */
390 static bool send_fileset(JCR *jcr)
391 {
392    FILESET *fileset = jcr->fileset;
393    BSOCK   *fd = jcr->file_bsock;
394    STORE   *store = jcr->wstore;
395    int num;
396    bool include = true;
397
398    for ( ;; ) {
399       if (include) {
400          num = fileset->num_includes;
401       } else {
402          num = fileset->num_excludes;
403       }
404       for (int i=0; i<num; i++) {
405          char *item;
406          INCEXE *ie;
407          int j, k;
408
409          if (include) {
410             ie = fileset->include_items[i];
411             fd->fsend("I\n");
412          } else {
413             ie = fileset->exclude_items[i];
414             fd->fsend("E\n");
415          }
416          if (ie->ignoredir) {
417             fd->fsend("Z %s\n", ie->ignoredir);
418          }
419          for (j=0; j<ie->num_opts; j++) {
420             FOPTS *fo = ie->opts_list[j];
421             bool enhanced_wild = false;
422             bool stripped_opts = false;
423             bool compress_disabled = false;
424             char newopts[MAX_FOPTS];
425
426             for (k=0; fo->opts[k]!='\0'; k++) {
427                if (fo->opts[k]=='W') {
428                   enhanced_wild = true;
429                   break;
430                }
431             }
432
433             /*
434              * Strip out compression option Zn if disallowed
435              *  for this Storage.
436              * Strip out dedup option dn if old FD
437              */
438             bool strip_compress = store && !store->AllowCompress;
439             if (strip_compress || jcr->FDVersion >= 11) {
440                int j = 0;
441                for (k=0; fo->opts[k]!='\0'; k++) {
442                   /* Z compress option is followed by the single-digit compress level or 'o' */
443                   if (strip_compress && fo->opts[k]=='Z') {
444                      stripped_opts = true;
445                      compress_disabled = true;
446                      k++;                /* skip level */
447                   } else if (jcr->FDVersion < 11 && fo->opts[k]=='d') {
448                      stripped_opts = true;
449                      k++;              /* skip level */
450                   } else {
451                      newopts[j] = fo->opts[k];
452                      j++;
453                   }
454                }
455                newopts[j] = '\0';
456                if (compress_disabled) {
457                   Jmsg(jcr, M_INFO, 0,
458                       _("FD compression disabled for this Job because AllowCompression=No in Storage resource.\n") );
459                }
460             }
461             if (stripped_opts) {
462                /* Send the new trimmed option set without overwriting fo->opts */
463                fd->fsend("O %s\n", newopts);
464             } else {
465                /* Send the original options */
466                fd->fsend("O %s\n", fo->opts);
467             }
468             for (k=0; k<fo->regex.size(); k++) {
469                fd->fsend("R %s\n", fo->regex.get(k));
470             }
471             for (k=0; k<fo->regexdir.size(); k++) {
472                fd->fsend("RD %s\n", fo->regexdir.get(k));
473             }
474             for (k=0; k<fo->regexfile.size(); k++) {
475                fd->fsend("RF %s\n", fo->regexfile.get(k));
476             }
477             for (k=0; k<fo->wild.size(); k++) {
478                fd->fsend("W %s\n", fo->wild.get(k));
479             }
480             for (k=0; k<fo->wilddir.size(); k++) {
481                fd->fsend("WD %s\n", fo->wilddir.get(k));
482             }
483             for (k=0; k<fo->wildfile.size(); k++) {
484                fd->fsend("WF %s\n", fo->wildfile.get(k));
485             }
486             for (k=0; k<fo->wildbase.size(); k++) {
487                fd->fsend("W%c %s\n", enhanced_wild ? 'B' : 'F', fo->wildbase.get(k));
488             }
489             for (k=0; k<fo->base.size(); k++) {
490                fd->fsend("B %s\n", fo->base.get(k));
491             }
492             for (k=0; k<fo->fstype.size(); k++) {
493                fd->fsend("X %s\n", fo->fstype.get(k));
494             }
495             for (k=0; k<fo->drivetype.size(); k++) {
496                fd->fsend("XD %s\n", fo->drivetype.get(k));
497             }
498             if (fo->plugin) {
499                fd->fsend("G %s\n", fo->plugin);
500             }
501             if (fo->reader) {
502                fd->fsend("D %s\n", fo->reader);
503             }
504             if (fo->writer) {
505                fd->fsend("T %s\n", fo->writer);
506             }
507             fd->fsend("N\n");
508          }
509
510          for (j=0; j<ie->name_list.size(); j++) {
511             item = (char *)ie->name_list.get(j);
512             if (!send_list_item(jcr, "F ", item, fd)) {
513                goto bail_out;
514             }
515          }
516          fd->fsend("N\n");
517          for (j=0; j<ie->plugin_list.size(); j++) {
518             item = (char *)ie->plugin_list.get(j);
519             if (!send_list_item(jcr, "P ", item, fd)) {
520                goto bail_out;
521             }
522          }
523          fd->fsend("N\n");
524       }
525       if (!include) {                 /* If we just did excludes */
526          break;                       /*   all done */
527       }
528       include = false;                /* Now do excludes */
529    }
530
531    fd->signal(BNET_EOD);              /* end of data */
532    if (!response(jcr, fd, OKinc, "Include", DISPLAY_ERROR)) {
533       goto bail_out;
534    }
535    return true;
536
537 bail_out:
538    jcr->setJobStatus(JS_ErrorTerminated);
539    return false;
540
541 }
542
543 static bool send_list_item(JCR *jcr, const char *code, char *item, BSOCK *fd)
544 {
545    BPIPE *bpipe;
546    FILE *ffd;
547    char buf[2000];
548    int optlen, stat;
549    char *p = item;
550
551    switch (*p) {
552    case '|':
553       p++;                      /* skip over the | */
554       fd->msg = edit_job_codes(jcr, fd->msg, p, "");
555       bpipe = open_bpipe(fd->msg, 0, "r");
556       if (!bpipe) {
557          berrno be;
558          Jmsg(jcr, M_FATAL, 0, _("Cannot run program: %s. ERR=%s\n"),
559             p, be.bstrerror());
560          return false;
561       }
562       bstrncpy(buf, code, sizeof(buf));
563       Dmsg1(500, "code=%s\n", buf);
564       optlen = strlen(buf);
565       while (fgets(buf+optlen, sizeof(buf)-optlen, bpipe->rfd)) {
566          fd->msglen = Mmsg(fd->msg, "%s", buf);
567          Dmsg2(500, "Inc/exc len=%d: %s", fd->msglen, fd->msg);
568          if (!fd->send()) {
569             close_bpipe(bpipe);
570             Jmsg(jcr, M_FATAL, 0, _(">filed: write error on socket\n"));
571             return false;
572          }
573       }
574       if ((stat=close_bpipe(bpipe)) != 0) {
575          berrno be;
576          Jmsg(jcr, M_FATAL, 0, _("Error running program: %s. ERR=%s\n"),
577             p, be.bstrerror(stat));
578          return false;
579       }
580       break;
581    case '<':
582       p++;                      /* skip over < */
583       if ((ffd = bfopen(p, "rb")) == NULL) {
584          berrno be;
585          Jmsg(jcr, M_FATAL, 0, _("Cannot open included file: %s. ERR=%s\n"),
586             p, be.bstrerror());
587          return false;
588       }
589       bstrncpy(buf, code, sizeof(buf));
590       Dmsg1(500, "code=%s\n", buf);
591       optlen = strlen(buf);
592       while (fgets(buf+optlen, sizeof(buf)-optlen, ffd)) {
593          fd->msglen = Mmsg(fd->msg, "%s", buf);
594          if (!fd->send()) {
595             fclose(ffd);
596             Jmsg(jcr, M_FATAL, 0, _(">filed: write error on socket\n"));
597             return false;
598          }
599       }
600       fclose(ffd);
601       break;
602    case '\\':
603       p++;                      /* skip over \ */
604       /* Note, fall through wanted */
605    default:
606       pm_strcpy(fd->msg, code);
607       fd->msglen = pm_strcat(fd->msg, p);
608       Dmsg1(500, "Inc/Exc name=%s\n", fd->msg);
609       if (!fd->send()) {
610          Jmsg(jcr, M_FATAL, 0, _(">filed: write error on socket\n"));
611          return false;
612       }
613       break;
614    }
615    return true;
616 }
617
618
619 /*
620  * Send include list to File daemon
621  */
622 bool send_include_list(JCR *jcr)
623 {
624    BSOCK *fd = jcr->file_bsock;
625    if (jcr->fileset->new_include) {
626       fd->fsend(filesetcmd,
627                 jcr->fileset->enable_vss ? " vss=1" : "",
628                 jcr->fileset->enable_snapshot ? " snap=1" : "");
629       return send_fileset(jcr);
630    }
631    return true;
632 }
633
634 /*
635  *
636  * Send a include list with only one directory and recurse=no
637  * TODO: Need to display the plugin somewhere
638  *       The main point is that we don't introduce any protocol change
639  */
640 bool send_ls_fileset(JCR *jcr, const char *path)
641 {
642    BSOCK *fd = jcr->file_bsock;
643    fd->fsend(filesetcmd, "" /* no vss */, "" /* no snapshot */);
644
645    fd->fsend("I\n");
646    fd->fsend("O h\n");         /* Limit recursion to one directory */
647    fd->fsend("N\n");
648    fd->fsend("F %s\n", path);
649    fd->fsend("N\n");
650    fd->signal(BNET_EOD);              /* end of data */
651
652    if (!response(jcr, fd, OKinc, "Include", DISPLAY_ERROR)) {
653       return false;
654    }
655    return true;
656 }
657
658 /*
659  * Send exclude list to File daemon
660  *   Under the new scheme, the Exclude list
661  *   is part of the FileSet sent with the
662  *   "include_list" above.
663  */
664 bool send_exclude_list(JCR *jcr)
665 {
666    return true;
667 }
668
669 /* TODO: drop this with runscript.old_proto in bacula 1.42 */
670 static char runbefore[]   = "RunBeforeJob %s\n";
671 static char runafter[]    = "RunAfterJob %s\n";
672 static char OKRunBefore[] = "2000 OK RunBefore\n";
673 static char OKRunAfter[]  = "2000 OK RunAfter\n";
674
675 int send_runscript_with_old_proto(JCR *jcr, int when, POOLMEM *msg)
676 {
677    int ret;
678    Dmsg1(120, "bdird: sending old runcommand to fd '%s'\n",msg);
679    if (when & SCRIPT_Before) {
680       jcr->file_bsock->fsend(runbefore, msg);
681       ret = response(jcr, jcr->file_bsock, OKRunBefore, "ClientRunBeforeJob", DISPLAY_ERROR);
682    } else {
683       jcr->file_bsock->fsend(runafter, msg);
684       ret = response(jcr, jcr->file_bsock, OKRunAfter, "ClientRunAfterJob", DISPLAY_ERROR);
685    }
686    return ret;
687 } /* END OF TODO */
688
689 /*
690  * Send RunScripts to File daemon
691  * 1) We send all runscript to FD, they can be executed Before, After, or twice
692  * 2) Then, we send a "RunBeforeNow" command to the FD to tell him to do the
693  *    first run_script() call. (ie ClientRunBeforeJob)
694  */
695 int send_runscripts_commands(JCR *jcr)
696 {
697    POOLMEM *msg = get_pool_memory(PM_FNAME);
698    BSOCK *fd = jcr->file_bsock;
699    RUNSCRIPT *cmd;
700    bool launch_before_cmd = false;
701    POOLMEM *ehost = get_pool_memory(PM_FNAME);
702    int result;
703
704    Dmsg0(120, "bdird: sending runscripts to fd\n");
705    if (!jcr->job->RunScripts) {
706       goto norunscript;
707    }
708    foreach_alist(cmd, jcr->job->RunScripts) {
709       if (cmd->can_run_at_level(jcr->getJobLevel()) && cmd->target) {
710          ehost = edit_job_codes(jcr, ehost, cmd->target, "");
711          Dmsg2(200, "bdird: runscript %s -> %s\n", cmd->target, ehost);
712
713          if (strcmp(ehost, jcr->client->name()) == 0) {
714             pm_strcpy(msg, cmd->command);
715             bash_spaces(msg);
716
717             Dmsg1(120, "bdird: sending runscripts to fd '%s'\n", cmd->command);
718
719             /* TODO: remove this with bacula 1.42 */
720             if (cmd->old_proto) {
721                result = send_runscript_with_old_proto(jcr, cmd->when, msg);
722
723             } else {
724                fd->fsend(runscript, cmd->on_success,
725                                     cmd->on_failure,
726                                     cmd->fail_on_error,
727                                     cmd->when,
728                                     msg);
729
730                result = response(jcr, fd, OKRunScript, "RunScript", DISPLAY_ERROR);
731                launch_before_cmd = true;
732             }
733
734             if (!result) {
735                goto bail_out;
736             }
737          }
738          /* TODO : we have to play with other client */
739          /*
740            else {
741            send command to an other client
742            }
743          */
744       }
745    }
746
747    /* Tell the FD to execute the ClientRunBeforeJob */
748    if (launch_before_cmd) {
749       fd->fsend(runbeforenow);
750       if (!response(jcr, fd, OKRunBeforeNow, "RunBeforeNow", DISPLAY_ERROR)) {
751         goto bail_out;
752       }
753    }
754 norunscript:
755    free_pool_memory(msg);
756    free_pool_memory(ehost);
757    return 1;
758
759 bail_out:
760    Jmsg(jcr, M_FATAL, 0, _("Client \"%s\" RunScript failed.\n"), ehost);
761    free_pool_memory(msg);
762    free_pool_memory(ehost);
763    return 0;
764 }
765
766 struct OBJ_CTX {
767    JCR *jcr;
768    int count;
769 };
770
771 static int restore_object_handler(void *ctx, int num_fields, char **row)
772 {
773    OBJ_CTX *octx = (OBJ_CTX *)ctx;
774    JCR *jcr = octx->jcr;
775    BSOCK *fd;
776
777    fd = jcr->file_bsock;
778    if (jcr->is_job_canceled()) {
779       return 1;
780    }
781    /* Old File Daemon doesn't handle restore objects */
782    if (jcr->FDVersion < 3) {
783       Jmsg(jcr, M_WARNING, 0, _("Client \"%s\" may not be used to restore "
784                                 "this job. Please upgrade your client.\n"),
785            jcr->client->name());
786       return 1;
787    }
788
789    if (jcr->FDVersion < 5) {    /* Old version without PluginName */
790       fd->fsend("restoreobject JobId=%s %s,%s,%s,%s,%s,%s\n",
791                 row[0], row[1], row[2], row[3], row[4], row[5], row[6]);
792    } else {
793       /* bash spaces from PluginName */
794       bash_spaces(row[9]);
795       fd->fsend("restoreobject JobId=%s %s,%s,%s,%s,%s,%s,%s\n",
796                 row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[9]);
797    }
798    Dmsg1(010, "Send obj hdr=%s", fd->msg);
799
800    fd->msglen = pm_strcpy(fd->msg, row[7]);
801    fd->send();                            /* send Object name */
802
803    Dmsg1(010, "Send obj: %s\n", fd->msg);
804
805 //   fd->msglen = str_to_uint64(row[1]);   /* object length */
806 //   Dmsg1(000, "obj size: %lld\n", (uint64_t)fd->msglen);
807
808    /* object */
809    db_unescape_object(jcr, jcr->db,
810                       row[8],                /* Object  */
811                       str_to_uint64(row[1]), /* Object length */
812                       &fd->msg, &fd->msglen);
813    fd->send();                           /* send object */
814    octx->count++;
815
816    if (debug_level > 100) {
817       for (int i=0; i < fd->msglen; i++)
818          if (!fd->msg[i])
819             fd->msg[i] = ' ';
820       Dmsg1(000, "Send obj: %s\n", fd->msg);
821    }
822
823    return 0;
824 }
825
826 /*
827  * Send the plugin Restore Objects, which allow the
828  *  plugin to get information early in the restore
829  *  process.  The RestoreObjects were created during
830  *  the backup by the plugin.
831  */
832 bool send_restore_objects(JCR *jcr)
833 {
834    char ed1[50];
835    POOL_MEM query(PM_MESSAGE);
836    BSOCK *fd;
837    OBJ_CTX octx;
838
839    if (!jcr->JobIds || !jcr->JobIds[0]) {
840       return true;
841    }
842    octx.jcr = jcr;
843    octx.count = 0;
844
845    /* restore_object_handler is called for each file found */
846
847    /* send restore objects for all jobs involved  */
848    Mmsg(query, get_restore_objects, jcr->JobIds, FT_RESTORE_FIRST);
849    db_sql_query(jcr->db, query.c_str(), restore_object_handler, (void *)&octx);
850
851    /* send config objects for the current restore job */
852    Mmsg(query, get_restore_objects,
853         edit_uint64(jcr->JobId, ed1), FT_PLUGIN_CONFIG_FILLED);
854    db_sql_query(jcr->db, query.c_str(), restore_object_handler, (void *)&octx);
855
856    /*
857     * Send to FD only if we have at least one restore object.
858     * This permits backward compatibility with older FDs.
859     */
860    if (octx.count > 0) {
861       fd = jcr->file_bsock;
862       fd->fsend("restoreobject end\n");
863       if (!response(jcr, fd, OKRestoreObject, "RestoreObject", DISPLAY_ERROR)) {
864          Jmsg(jcr, M_FATAL, 0, _("RestoreObject failed.\n"));
865          return false;
866       }
867    }
868    return true;
869 }
870
871 /*
872  * Send the plugin a list of component info files.  These
873  *  were files that were created during the backup for
874  *  the VSS plugin.  The list is a list of those component
875  *  files that have been chosen for restore.  We
876  *  send them before the Restore Objects.
877  */
878 bool send_component_info(JCR *jcr)
879 {
880    BSOCK *fd;
881    char buf[2000];
882    bool ok = true;
883
884    if (!jcr->component_fd) {
885       return true;           /* nothing to send */
886    }
887    /* Don't send if old version FD */
888    if (jcr->FDVersion < 6) {
889       goto bail_out;
890    }
891
892    rewind(jcr->component_fd);
893    fd = jcr->file_bsock;
894    fd->fsend(component_info);
895    while (fgets(buf, sizeof(buf), jcr->component_fd)) {
896       fd->fsend("%s", buf);
897       Dmsg1(050, "Send component_info to FD: %s\n", buf);
898    }
899    fd->signal(BNET_EOD);
900    if (!response(jcr, fd, OKComponentInfo, "ComponentInfo", DISPLAY_ERROR)) {
901       Jmsg(jcr, M_FATAL, 0, _("ComponentInfo failed.\n"));
902       ok = false;
903    }
904
905 bail_out:
906    fclose(jcr->component_fd);
907    jcr->component_fd = NULL;
908    unlink(jcr->component_fname);
909    free_and_null_pool_memory(jcr->component_fname);
910    return ok;
911 }
912
913 /*
914  * Read the attributes from the File daemon for
915  * a Verify job and store them in the catalog.
916  */
917 int get_attributes_and_put_in_catalog(JCR *jcr)
918 {
919    BSOCK   *fd;
920    int n = 0;
921    ATTR_DBR *ar = NULL;
922    char digest[MAXSTRING];
923
924    fd = jcr->file_bsock;
925    jcr->jr.FirstIndex = 1;
926    jcr->FileIndex = 0;
927    /* Start transaction allocates jcr->attr and jcr->ar if needed */
928    db_start_transaction(jcr, jcr->db);     /* start transaction if not already open */
929    ar = jcr->ar;
930
931    Dmsg0(120, "bdird: waiting to receive file attributes\n");
932    /* Pickup file attributes and digest */
933    while (!fd->errors && (n = bget_dirmsg(fd)) > 0) {
934       uint32_t file_index;
935       int stream, len;
936       char *p, *fn;
937       char Digest[MAXSTRING];      /* either Verify opts or MD5/SHA1 digest */
938
939       /* Stop here if canceled */
940       if (jcr->is_job_canceled()) {
941          jcr->cached_attribute = false;
942          return 0;
943       }
944
945       if ((len = sscanf(fd->msg, "%ld %d %s", &file_index, &stream, Digest)) != 3) {
946          Jmsg(jcr, M_FATAL, 0, _("<filed: bad attributes, expected 3 fields got %d\n"
947 "msglen=%d msg=%s\n"), len, fd->msglen, fd->msg);
948          jcr->setJobStatus(JS_ErrorTerminated);
949          jcr->cached_attribute = false;
950          return 0;
951       }
952       p = fd->msg;
953       /* The following three fields were sscanf'ed above so skip them */
954       skip_nonspaces(&p);             /* skip FileIndex */
955       skip_spaces(&p);
956       skip_nonspaces(&p);             /* skip Stream */
957       skip_spaces(&p);
958       skip_nonspaces(&p);             /* skip Opts_Digest */
959       p++;                            /* skip space */
960       Dmsg1(dbglvl, "Stream=%d\n", stream);
961       if (stream == STREAM_UNIX_ATTRIBUTES || stream == STREAM_UNIX_ATTRIBUTES_EX) {
962          if (jcr->cached_attribute) {
963             Dmsg3(dbglvl, "Cached attr. Stream=%d fname=%s\n", ar->Stream, ar->fname,
964                ar->attr);
965             if (!db_create_file_attributes_record(jcr, jcr->db, ar)) {
966                Jmsg1(jcr, M_FATAL, 0, _("Attribute create error. %s"), db_strerror(jcr->db));
967             }
968             jcr->cached_attribute = false;
969          }
970          /* Any cached attr is flushed so we can reuse jcr->attr and jcr->ar */
971          fn = jcr->fname = check_pool_memory_size(jcr->fname, fd->msglen);
972          while (*p != 0) {
973             *fn++ = *p++;                /* copy filename */
974          }
975          *fn = *p++;                     /* term filename and point p to attribs */
976          pm_strcpy(jcr->attr, p);        /* save attributes */
977          jcr->JobFiles++;
978          jcr->FileIndex = file_index;
979          ar->attr = jcr->attr;
980          ar->fname = jcr->fname;
981          ar->FileIndex = file_index;
982          ar->Stream = stream;
983          ar->link = NULL;
984          ar->JobId = jcr->JobId;
985          ar->ClientId = jcr->ClientId;
986          ar->PathId = 0;
987          ar->FilenameId = 0;
988          ar->Digest = NULL;
989          ar->DigestType = CRYPTO_DIGEST_NONE;
990          ar->DeltaSeq = 0;
991          jcr->cached_attribute = true;
992
993          Dmsg2(dbglvl, "dird<filed: stream=%d %s\n", stream, jcr->fname);
994          Dmsg1(dbglvl, "dird<filed: attr=%s\n", ar->attr);
995          jcr->FileId = ar->FileId;
996       /*
997        * First, get STREAM_UNIX_ATTRIBUTES and fill ATTR_DBR structure
998        * Next, we CAN have a CRYPTO_DIGEST, so we fill ATTR_DBR with it (or not)
999        * When we get a new STREAM_UNIX_ATTRIBUTES, we known that we can add file to the catalog
1000        * At the end, we have to add the last file
1001        */
1002       } else if (crypto_digest_stream_type(stream) != CRYPTO_DIGEST_NONE) {
1003          if (jcr->FileIndex != (uint32_t)file_index) {
1004             Jmsg3(jcr, M_ERROR, 0, _("%s index %d not same as attributes %d\n"),
1005                stream_to_ascii(stream), file_index, jcr->FileIndex);
1006             continue;
1007          }
1008          ar->Digest = digest;
1009          ar->DigestType = crypto_digest_stream_type(stream);
1010          db_escape_string(jcr, jcr->db, digest, Digest, strlen(Digest));
1011          Dmsg4(dbglvl, "stream=%d DigestLen=%d Digest=%s type=%d\n", stream,
1012                strlen(digest), digest, ar->DigestType);
1013       }
1014       jcr->jr.JobFiles = jcr->JobFiles = file_index;
1015       jcr->jr.LastIndex = file_index;
1016    }
1017    if (fd->is_error()) {
1018       Jmsg1(jcr, M_FATAL, 0, _("<filed: Network error getting attributes. ERR=%s\n"),
1019             fd->bstrerror());
1020       jcr->cached_attribute = false;
1021       return 0;
1022    }
1023    if (jcr->cached_attribute) {
1024       Dmsg3(dbglvl, "Cached attr with digest. Stream=%d fname=%s attr=%s\n", ar->Stream,
1025          ar->fname, ar->attr);
1026       if (!db_create_file_attributes_record(jcr, jcr->db, ar)) {
1027          Jmsg1(jcr, M_FATAL, 0, _("Attribute create error. %s"), db_strerror(jcr->db));
1028       }
1029       jcr->cached_attribute = false;
1030    }
1031    jcr->setJobStatus(JS_Terminated);
1032    return 1;
1033 }