Welcome to mirror list, hosted at ThFree Co, Russian Federation.

fd_cmds.cc « dird « src « core - github.com/bareos/bareos.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 422d3effadb30a6101dfd93af2dc59a36d3947b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
/*
   BAREOS® - Backup Archiving REcovery Open Sourced

   Copyright (C) 2000-2010 Free Software Foundation Europe e.V.
   Copyright (C) 2011-2016 Planets Communications B.V.
   Copyright (C) 2013-2022 Bareos GmbH & Co. KG

   This program is Free Software; you can redistribute it and/or
   modify it under the terms of version three of the GNU Affero General Public
   License as published by the Free Software Foundation and included
   in the file LICENSE.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
   Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301, USA.
*/
// Kern Sibbald, October MM
/**
 * fd_cmds.c -- send commands to File daemon
 *
 * This routine is run as a separate thread.  There may be more
 * work to be done to make it totally reentrant!!!!
 *
 * Utility functions for sending info to File Daemon.
 * These functions are used by both backup and verify.
 */

#include "include/bareos.h"
#include "cats/cats.h"
#include "dird.h"
#include "dird/dird_globals.h"
#include "dird/jcr_private.h"
#include "findlib/find.h"
#include "dird/authenticate.h"
#include "dird/fd_cmds.h"
#include "dird/getmsg.h"
#include "dird/jcr_private.h"
#include "dird/msgchan.h"
#include "dird/run_on_incoming_connect_interval.h"
#include "dird/scheduler.h"
#include "lib/berrno.h"
#include "lib/bsock_tcp.h"
#include "lib/bnet.h"
#include "lib/edit.h"
#include "lib/parse_conf.h"
#include "lib/runscript.h"
#include "lib/util.h"
#include "lib/watchdog.h"

#include <algorithm>


namespace directordaemon {

const int debuglevel = 400;

/* Commands sent to File daemon */
static char filesetcmd[] = "fileset%s\n"; /* set full fileset */
static char jobcmd[] = "JobId=%s Job=%s SDid=%u SDtime=%u Authorization=%s\n";
static char jobcmdssl[]
    = "JobId=%s Job=%s SDid=%u SDtime=%u Authorization=%s ssl=%d\n";
/* Note, mtime_only is not used here -- implemented as file option */
static char levelcmd[] = "level = %s%s%s mtime_only=%d %s%s\n";
static char runscriptcmd[]
    = "Run OnSuccess=%u OnFailure=%u AbortOnError=%u When=%u Command=%s\n";
static char runbeforenowcmd[] = "RunBeforeNow\n";
static char restoreobjectendcmd[] = "restoreobject end\n";
static char bandwidthcmd[] = "setbandwidth=%lld Job=%s\n";
static char pluginoptionscmd[] = "pluginoptions %s\n";
static char getSecureEraseCmd[] = "getSecureEraseCmd\n";

/* Responses received from File daemon */
static char OKinc[] = "2000 OK include\n";
static char OKjob[] = "2000 OK Job";
static char OKlevel[] = "2000 OK level\n";
static char OKRunScript[] = "2000 OK RunScript\n";
static char OKRunBeforeNow[] = "2000 OK RunBeforeNow\n";
static char OKRestoreObject[] = "2000 OK ObjectRestored\n";
static char OKBandwidth[] = "2000 OK Bandwidth\n";
static char OKPluginOptions[] = "2000 OK PluginOptions\n";
static char OKgetSecureEraseCmd[] = "2000 OK FDSecureEraseCmd %s\n";

/* Forward referenced functions */
static bool SendListItem(JobControlRecord* jcr,
                         const char* code,
                         char* item,
                         BareosSocket* fd);

/* External functions */
extern DirectorResource* director;

#define INC_LIST 0
#define EXC_LIST 1

static utime_t get_heartbeat_interval(ClientResource* res)
{
  utime_t heartbeat;

  if (res->heartbeat_interval) {
    heartbeat = res->heartbeat_interval;
  } else {
    heartbeat = me->heartbeat_interval;
  }

  return heartbeat;
}

/**
 * Open connection to File daemon.
 *
 * Try connecting every retry_interval (default 10 sec), and
 * give up after max_retry_time (default 30 mins).
 */
static bool connect_outbound_to_file_daemon(JobControlRecord* jcr,
                                            int retry_interval,
                                            int max_retry_time,
                                            bool verbose)
{
  bool result = false;
  BareosSocket* fd = NULL;
  utime_t heart_beat;

  if (!IsConnectingToClientAllowed(jcr)) {
    Dmsg1(120, "Connection to client \"%s\" is not allowed.\n",
          jcr->impl->res.client->resource_name_);
    return false;
  }

  fd = new BareosSocketTCP;
  heart_beat = get_heartbeat_interval(jcr->impl->res.client);

  char name[MAX_NAME_LENGTH + 100];
  bstrncpy(name, _("Client: "), sizeof(name));
  bstrncat(name, jcr->impl->res.client->resource_name_, sizeof(name));

  fd->SetSourceAddress(me->DIRsrc_addr);
  if (!fd->connect(jcr, retry_interval, max_retry_time, heart_beat, name,
                   jcr->impl->res.client->address, NULL,
                   jcr->impl->res.client->FDport, verbose)) {
    delete fd;
    fd = NULL;
    jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated);
  } else {
    jcr->file_bsock = fd;
    jcr->authenticated = false;
    Dmsg0(10, "Opened connection with File daemon\n");
    result = true;
  }

  return result;
}

static void OutputMessageForConnectionTry(JobControlRecord* jcr, UaContext* ua)
{
  std::string m;

  if (jcr->impl->res.client->connection_successful_handshake_
          == ClientConnectionHandshakeMode::kUndefined
      || jcr->impl->res.client->connection_successful_handshake_
             == ClientConnectionHandshakeMode::kFailed) {
    m = "Probing client protocol... (result will be saved until config reload)";
  } else {
    return;
  }

  if (jcr && jcr->JobId != 0) {
    std::string m1 = m + "\n";
    Jmsg(jcr, M_INFO, 0, m1.c_str());
  }
  if (ua) { ua->SendMsg(m.c_str()); }
}

static void SendInfoChosenCipher(JobControlRecord* jcr, UaContext* ua)
{
  std::string str;
  jcr->file_bsock->GetCipherMessageString(str);
  str += '\n';
  if (jcr->JobId != 0) { Jmsg(jcr, M_INFO, 0, str.c_str()); }
  if (ua) { /* only whith console connection */
    ua->SendRawMsg(str.c_str());
  }
}

static void SendInfoSuccess(JobControlRecord* jcr, UaContext* ua)
{
  std::string m;
  if (jcr->impl->res.client->connection_successful_handshake_
      == ClientConnectionHandshakeMode::kUndefined) {
    m = "\r\v";
  }
  switch (jcr->impl->connection_handshake_try_) {
    case ClientConnectionHandshakeMode::kTlsFirst:
      m += " Handshake: Immediate TLS,";
      break;
    case ClientConnectionHandshakeMode::kCleartextFirst:
      m += " Handshake: Cleartext,";
      break;
    default:
      m += " Handshake: Unknown mode";
      break;
  }

  if (jcr && jcr->JobId != 0) {
    std::string m1 = m;
    std::replace(m1.begin(), m1.end(), '\r', ' ');
    std::replace(m1.begin(), m1.end(), '\v', ' ');
    std::replace(m1.begin(), m1.end(), ',', ' ');
    m1 += std::string("\n");
    Jmsg(jcr, M_INFO, 0, m1.c_str());
  }
  if (ua) { /* only whith console connection */
    ua->SendRawMsg(m.c_str());
  }
}

bool ConnectToFileDaemon(JobControlRecord* jcr,
                         int retry_interval,
                         int max_retry_time,
                         bool verbose,
                         UaContext* ua)
{
  if (!IsConnectingToClientAllowed(jcr) && !IsConnectFromClientAllowed(jcr)) {
    Emsg1(M_WARNING, 0, _("Connecting to %s is not allowed.\n"),
          jcr->impl->res.client->resource_name_);
    return false;
  }
  bool success = false;
  bool tcp_connect_failed = false;
  int connect_tries
      = 3; /* as a finish-hook for the UseWaitingClient mechanism */

  /* try the connection modes starting with tls directly,
   * in case there is a client that cannot do Tls immediately then
   * fall back to cleartext md5-handshake */
  OutputMessageForConnectionTry(jcr, ua);
  if (jcr->impl->res.client->connection_successful_handshake_
          == ClientConnectionHandshakeMode::kUndefined
      || jcr->impl->res.client->connection_successful_handshake_
             == ClientConnectionHandshakeMode::kFailed) {
    if (jcr->impl->res.client->IsTlsConfigured()) {
      jcr->impl->connection_handshake_try_
          = ClientConnectionHandshakeMode::kTlsFirst;
    } else {
      jcr->impl->connection_handshake_try_
          = ClientConnectionHandshakeMode::kCleartextFirst;
    }
    jcr->is_passive_client_connection_probing = true;
  } else {
    /* if there is a stored mode from a previous connection then use this */
    jcr->impl->connection_handshake_try_
        = jcr->impl->res.client->connection_successful_handshake_;
    jcr->is_passive_client_connection_probing = false;
  }

  do { /* while (tcp_connect_failed ...) */
    /* connect the tcp socket */
    if (!jcr->file_bsock) {
      if (!UseWaitingClient(jcr, 0)) {
        if (!connect_outbound_to_file_daemon(jcr, retry_interval,
                                             max_retry_time, verbose)) {
          if (!UseWaitingClient(
                  jcr,
                  max_retry_time)) { /* will set jcr->file_bsock accordingly */
            tcp_connect_failed = true;
          }
        }
      }
    }

    if (jcr->file_bsock) {
      jcr->setJobStatusWithPriorityCheck(JS_Running);
      if (AuthenticateWithFileDaemon(jcr)) {
        success = true;
        SendInfoSuccess(jcr, ua);
        SendInfoChosenCipher(jcr, ua);
        jcr->is_passive_client_connection_probing = false;
        jcr->impl->res.client->connection_successful_handshake_
            = jcr->impl->connection_handshake_try_;
      } else {
        /* authentication failed due to
         * - tls mismatch or
         * - if an old client cannot do tls- before md5-handshake
         * */
        switch (jcr->impl->connection_handshake_try_) {
          case ClientConnectionHandshakeMode::kTlsFirst:
            if (jcr->file_bsock) {
              jcr->file_bsock->close();
              delete jcr->file_bsock;
              jcr->file_bsock = nullptr;
            }
            jcr->setJobStatus(JS_Running);
            jcr->impl->connection_handshake_try_
                = ClientConnectionHandshakeMode::kCleartextFirst;
            break;
          case ClientConnectionHandshakeMode::kCleartextFirst:
            jcr->impl->connection_handshake_try_
                = ClientConnectionHandshakeMode::kFailed;
            break;
          case ClientConnectionHandshakeMode::kFailed:
          default: /* should bei one of class ClientConnectionHandshakeMode */
            ASSERT(false);
            break;
        }
      }
    } else {
      Jmsg(jcr, M_FATAL, 0, "\nFailed to connect to client \"%s\".\n",
           jcr->impl->res.client->resource_name_);
    }
    connect_tries--;
  } while (!tcp_connect_failed && connect_tries && !success
           && jcr->impl->connection_handshake_try_
                  != ClientConnectionHandshakeMode::kFailed);

  if (!success) { jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated); }

  return success;
}

int SendJobInfoToFileDaemon(JobControlRecord* jcr)
{
  BareosSocket* fd = jcr->file_bsock;

  if (jcr->sd_auth_key == NULL) { jcr->sd_auth_key = strdup("dummy"); }

  if (jcr->impl->res.client->connection_successful_handshake_
      == ClientConnectionHandshakeMode::kTlsFirst) {
    /* client protocol onwards Bareos 18.2 */
    TlsPolicy tls_policy = kBnetTlsUnknown;
    int JobLevel = jcr->getJobLevel();
    switch (JobLevel) {
      case L_VERIFY_INIT:
      case L_VERIFY_CATALOG:
      case L_VERIFY_DISK_TO_CATALOG:
        tls_policy = kBnetTlsUnknown;
        break;
      default:
        StorageResource* storage = nullptr;
        if (jcr->impl->res.write_storage) {
          storage = jcr->impl->res.write_storage;
        } else if (jcr->impl->res.read_storage) {
          storage = jcr->impl->res.read_storage;
        } else {
          Jmsg(jcr, M_FATAL, 0, _("No read or write storage defined\n"));
          jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated);
          return 0;
        }
        if (storage) {
          tls_policy = storage->IsTlsConfigured() ? TlsPolicy::kBnetTlsAuto
                                                  : TlsPolicy::kBnetTlsNone;
        }
        break;
    }
    char ed1[30];
    fd->fsend(jobcmdssl, edit_int64(jcr->JobId, ed1), jcr->Job,
              jcr->VolSessionId, jcr->VolSessionTime, jcr->sd_auth_key,
              tls_policy);
  } else { /* jcr->impl_->res.client->connection_successful_handshake_ !=
              ClientConnectionHandshakeMode::kTlsFirst */
    /* client protocol before Bareos 18.2 */
    char ed1[30];
    fd->fsend(jobcmd, edit_int64(jcr->JobId, ed1), jcr->Job, jcr->VolSessionId,
              jcr->VolSessionTime, jcr->sd_auth_key);
  } /* if (jcr->impl_->res.client->connection_successful_handshake_ ==
       ClientConnectionHandshakeMode::kTlsFirst) */

  if (!jcr->impl->keep_sd_auth_key && !bstrcmp(jcr->sd_auth_key, "dummy")) {
    memset(jcr->sd_auth_key, 0, strlen(jcr->sd_auth_key));
  }

  Dmsg1(100, ">filed: %s", fd->msg);
  if (BgetDirmsg(fd) > 0) {
    Dmsg1(110, "<filed: %s", fd->msg);
    if (!bstrncmp(fd->msg, OKjob, strlen(OKjob))) {
      Jmsg(jcr, M_FATAL, 0, _("File daemon \"%s\" rejected Job command: %s\n"),
           jcr->impl->res.client->resource_name_, fd->msg);
      jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated);
      return 0;
    } else if (jcr->db) {
      ClientDbRecord cr;

      bstrncpy(cr.Name, jcr->impl->res.client->resource_name_, sizeof(cr.Name));
      cr.AutoPrune = jcr->impl->res.client->AutoPrune;
      cr.FileRetention = jcr->impl->res.client->FileRetention;
      cr.JobRetention = jcr->impl->res.client->JobRetention;
      bstrncpy(cr.Uname, fd->msg + strlen(OKjob) + 1, sizeof(cr.Uname));
      if (!jcr->db->UpdateClientRecord(jcr, &cr)) {
        Jmsg(jcr, M_WARNING, 0, _("Error updating Client record. ERR=%s\n"),
             jcr->db->strerror());
      }
    }
  } else {
    Jmsg(jcr, M_FATAL, 0, _("FD gave bad response to JobId command: %s\n"),
         BnetStrerror(fd));
    jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated);
    return 0;
  }

  return 1;
}

bool SendPreviousRestoreObjects(JobControlRecord* jcr)
{
  int JobLevel;

  JobLevel = jcr->getJobLevel();
  switch (JobLevel) {
    case L_DIFFERENTIAL:
    case L_INCREMENTAL:
      if (jcr->impl->previous_jr.JobId > 0) {
        if (!SendRestoreObjects(jcr, jcr->impl->previous_jr.JobId, false)) {
          return false;
        }
      }
      break;
    default:
      break;
  }

  return true;
}

bool SendBwlimitToFd(JobControlRecord* jcr, const char* Job)
{
  BareosSocket* fd = jcr->file_bsock;

  if (jcr->impl->FDVersion >= FD_VERSION_4) {
    fd->fsend(bandwidthcmd, jcr->max_bandwidth, Job);
    if (!response(jcr, fd, OKBandwidth, "Bandwidth", DISPLAY_ERROR)) {
      jcr->max_bandwidth = 0; /* can't set bandwidth limit */
      return false;
    }
  }

  return true;
}

bool SendSecureEraseReqToFd(JobControlRecord* jcr)
{
  int32_t n;
  BareosSocket* fd = jcr->file_bsock;

  if (!jcr->impl->FDSecureEraseCmd) {
    jcr->impl->FDSecureEraseCmd = GetPoolMemory(PM_NAME);
  }

  if (jcr->impl->FDVersion > FD_VERSION_53) {
    fd->fsend(getSecureEraseCmd);
    while ((n = BgetDirmsg(fd)) >= 0) {
      jcr->impl->FDSecureEraseCmd = CheckPoolMemorySize(
          jcr->impl->FDSecureEraseCmd, fd->message_length);
      if (sscanf(fd->msg, OKgetSecureEraseCmd, jcr->impl->FDSecureEraseCmd)
          == 1) {
        Dmsg1(400, "Got FD Secure Erase Cmd: %s\n",
              jcr->impl->FDSecureEraseCmd);
        break;
      } else {
        Jmsg(jcr, M_WARNING, 0, _("Unexpected Client Secure Erase Cmd: %s\n"),
             fd->msg);
        PmStrcpy(jcr->impl->FDSecureEraseCmd, "*None*");
        return false;
      }
    }
  } else {
    PmStrcpy(jcr->impl->FDSecureEraseCmd, "*None*");
  }

  return true;
}

static void SendSinceTime(JobControlRecord* jcr)
{
  char ed1[50];
  utime_t stime;
  BareosSocket* fd = jcr->file_bsock;

  stime = StrToUtime(jcr->starttime_string);
  fd->fsend(levelcmd, "", NT_("since_utime "), edit_uint64(stime, ed1), 0,
            NT_("prev_job="), jcr->impl->PrevJob);

  while (BgetDirmsg(fd) >= 0) { /* allow him to poll us to sync clocks */
    Jmsg(jcr, M_INFO, 0, "%s\n", fd->msg);
  }
}

/**
 * Send level command to FD.
 * Used for backup jobs and estimate command.
 */
bool SendLevelCommand(JobControlRecord* jcr)
{
  int JobLevel;
  BareosSocket* fd = jcr->file_bsock;
  const char* accurate = jcr->accurate ? "accurate_" : "";
  const char* not_accurate = "";
  const char* rerunning = jcr->rerunning ? " rerunning " : " ";

  // Send Level command to File daemon
  JobLevel = jcr->getJobLevel();
  switch (JobLevel) {
    case L_BASE:
      fd->fsend(levelcmd, not_accurate, "base", rerunning, 0, "", "");
      break;
    case L_NONE: /* L_NONE is the console, sending something off to the FD */
    case L_FULL:
      fd->fsend(levelcmd, not_accurate, "full", rerunning, 0, "", "");
      break;
    case L_DIFFERENTIAL:
      fd->fsend(levelcmd, accurate, "differential", rerunning, 0, "", "");
      SendSinceTime(jcr);
      break;
    case L_INCREMENTAL:
      fd->fsend(levelcmd, accurate, "incremental", rerunning, 0, "", "");
      SendSinceTime(jcr);
      break;
    case L_SINCE:
      Jmsg2(jcr, M_FATAL, 0, _("Unimplemented backup level %d %c\n"), JobLevel,
            JobLevel);
      break;
    default:
      Jmsg2(jcr, M_FATAL, 0, _("Unimplemented backup level %d %c\n"), JobLevel,
            JobLevel);
      return 0;
  }

  Dmsg1(120, ">filed: %s", fd->msg);

  if (!response(jcr, fd, OKlevel, "Level", DISPLAY_ERROR)) { return false; }

  return true;
}

// Send either an Included or an Excluded list to FD
static bool SendFileset(JobControlRecord* jcr)
{
  FilesetResource* fileset = jcr->impl->res.fileset;
  BareosSocket* fd = jcr->file_bsock;
  StorageResource* store = jcr->impl->res.write_storage;
  int num;
  bool include = true;

  while (1) {
    if (include) {
      num = fileset->include_items.size();
    } else {
      num = fileset->exclude_items.size();
    }
    for (int i = 0; i < num; i++) {
      char* item;
      IncludeExcludeItem* ie;

      if (include) {
        ie = fileset->include_items[i];
        fd->fsend("I\n");
      } else {
        ie = fileset->exclude_items[i];
        fd->fsend("E\n");
      }

      for (int j = 0; j < ie->ignoredir.size(); j++) {
        fd->fsend("Z %s\n", ie->ignoredir.get(j));
      }

      for (std::size_t j = 0; j < ie->file_options_list.size(); j++) {
        FileOptions* fo = ie->file_options_list[j];
        bool enhanced_wild = false;

        for (int k = 0; fo->opts[k] != '\0'; k++) {
          if (fo->opts[k] == 'W') {
            enhanced_wild = true;
            break;
          }
        }

        // Strip out compression option Zn if disallowed for this Storage
        if (store && !store->AllowCompress) {
          char newopts[MAX_FOPTS];
          bool done
              = false; /* print warning only if compression enabled in FS */
          int l = 0;

          for (int k = 0; fo->opts[k] != '\0'; k++) {
            /*
             * Z compress option is followed by the single-digit compress level
             * or 'o' For fastlz its Zf with a single char selecting the actual
             * compression algo.
             */
            if (fo->opts[k] == 'Z' && fo->opts[k + 1] == 'f') {
              done = true;
              k += 2; /* skip option */
            } else if (fo->opts[k] == 'Z') {
              done = true;
              k++; /* skip option and level */
            } else {
              newopts[l] = fo->opts[k];
              l++;
            }
          }
          newopts[l] = '\0';

          if (done) {
            Jmsg(jcr, M_INFO, 0,
                 _("FD compression disabled for this Job because "
                   "AllowCompress=No in Storage resource.\n"));
          }

          // Send the new trimmed option set without overwriting fo->opts
          fd->fsend("O %s\n", newopts);
        } else {
          // Send the original options
          fd->fsend("O %s\n", fo->opts);
        }

        for (int k = 0; k < fo->regex.size(); k++) {
          fd->fsend("R %s\n", fo->regex.get(k));
        }

        for (int k = 0; k < fo->regexdir.size(); k++) {
          fd->fsend("RD %s\n", fo->regexdir.get(k));
        }

        for (int k = 0; k < fo->regexfile.size(); k++) {
          fd->fsend("RF %s\n", fo->regexfile.get(k));
        }

        for (int k = 0; k < fo->wild.size(); k++) {
          fd->fsend("W %s\n", fo->wild.get(k));
        }

        for (int k = 0; k < fo->wilddir.size(); k++) {
          fd->fsend("WD %s\n", fo->wilddir.get(k));
        }

        for (int k = 0; k < fo->wildfile.size(); k++) {
          fd->fsend("WF %s\n", fo->wildfile.get(k));
        }

        for (int k = 0; k < fo->wildbase.size(); k++) {
          fd->fsend("W%c %s\n", enhanced_wild ? 'B' : 'F', fo->wildbase.get(k));
        }

        for (int k = 0; k < fo->base.size(); k++) {
          fd->fsend("B %s\n", fo->base.get(k));
        }

        for (int k = 0; k < fo->fstype.size(); k++) {
          fd->fsend("X %s\n", fo->fstype.get(k));
        }

        for (int k = 0; k < fo->Drivetype.size(); k++) {
          fd->fsend("XD %s\n", fo->Drivetype.get(k));
        }

        if (fo->plugin) { fd->fsend("G %s\n", fo->plugin); }

        if (fo->reader) { fd->fsend("D %s\n", fo->reader); }

        if (fo->writer) { fd->fsend("T %s\n", fo->writer); }

        fd->fsend("N\n");
      }

      for (int j = 0; j < ie->name_list.size(); j++) {
        item = (char*)ie->name_list.get(j);
        if (!SendListItem(jcr, "F ", item, fd)) { goto bail_out; }
      }
      fd->fsend("N\n");

      for (int j = 0; j < ie->plugin_list.size(); j++) {
        item = (char*)ie->plugin_list.get(j);
        if (!SendListItem(jcr, "P ", item, fd)) { goto bail_out; }
      }
      fd->fsend("N\n");
    }

    if (!include) { /* If we just did excludes */
      break;        /*   all done */
    }

    include = false; /* Now do excludes */
  }

  fd->signal(BNET_EOD); /* end of data */
  if (!response(jcr, fd, OKinc, "Include", DISPLAY_ERROR)) { goto bail_out; }
  return true;

bail_out:
  jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated);
  return false;
}

static bool SendListItem(JobControlRecord* jcr,
                         const char* code,
                         char* item,
                         BareosSocket* fd)
{
  Bpipe* bpipe;
  FILE* ffd;
  char buf[2000];
  int optlen, status;
  char* p = item;

  switch (*p) {
    case '|':
      p++; /* skip over the | */
      fd->msg = edit_job_codes(jcr, fd->msg, p, "");
      bpipe = OpenBpipe(fd->msg, 0, "r");
      if (!bpipe) {
        BErrNo be;
        Jmsg(jcr, M_FATAL, 0, _("Cannot run program: %s. ERR=%s\n"), p,
             be.bstrerror());
        return false;
      }
      bstrncpy(buf, code, sizeof(buf));
      Dmsg1(500, "code=%s\n", buf);
      optlen = strlen(buf);
      while (fgets(buf + optlen, sizeof(buf) - optlen, bpipe->rfd)) {
        fd->message_length = Mmsg(fd->msg, "%s", buf);
        Dmsg2(500, "Inc/exc len=%d: %s", fd->message_length, fd->msg);
        if (!BnetSend(fd)) {
          Jmsg(jcr, M_FATAL, 0, _(">filed: write error on socket\n"));
          return false;
        }
      }
      if ((status = CloseBpipe(bpipe)) != 0) {
        BErrNo be;
        Jmsg(jcr, M_FATAL, 0, _("Error running program: %s. ERR=%s\n"), p,
             be.bstrerror(status));
        return false;
      }
      break;
    case '<':
      p++; /* skip over < */
      if ((ffd = fopen(p, "rb")) == NULL) {
        BErrNo be;
        Jmsg(jcr, M_FATAL, 0, _("Cannot open included file: %s. ERR=%s\n"), p,
             be.bstrerror());
        return false;
      }
      bstrncpy(buf, code, sizeof(buf));
      Dmsg1(500, "code=%s\n", buf);
      optlen = strlen(buf);
      while (fgets(buf + optlen, sizeof(buf) - optlen, ffd)) {
        fd->message_length = Mmsg(fd->msg, "%s", buf);
        if (!BnetSend(fd)) {
          Jmsg(jcr, M_FATAL, 0, _(">filed: write error on socket\n"));
          fclose(ffd);
          return false;
        }
      }
      fclose(ffd);
      break;
    case '\\':
      p++; /* skip over \ */
      [[fallthrough]];
    default:
      PmStrcpy(fd->msg, code);
      fd->message_length = PmStrcat(fd->msg, p);
      Dmsg1(500, "Inc/Exc name=%s\n", fd->msg);
      if (!fd->send()) {
        Jmsg(jcr, M_FATAL, 0, _(">filed: write error on socket\n"));
        return false;
      }
      break;
  }
  return true;
}

// Send include list to File daemon
bool SendIncludeList(JobControlRecord* jcr)
{
  BareosSocket* fd = jcr->file_bsock;
  if (jcr->impl->res.fileset->new_include) {
    fd->fsend(filesetcmd, jcr->impl->res.fileset->enable_vss ? " vss=1" : "");
    return SendFileset(jcr);
  }
  return true;
}

/**
 * Send exclude list to File daemon
 *   Under the new scheme, the Exclude list
 *   is part of the FileSet sent with the
 *   "include_list" above.
 */
bool SendExcludeList(JobControlRecord*) { return true; }

// This checks to see if there are any non local runscripts for this job.
static bool HaveClientRunscripts(alist<RunScript*>* RunScripts)
{
  RunScript* cmd = nullptr;
  bool retval = false;

  if (RunScripts->empty()) { return false; }

  foreach_alist (cmd, RunScripts) {
    if (!cmd->IsLocal()) { retval = true; }
  }

  return retval;
}

/**
 * Send RunScripts to File daemon
 * 1) We send all runscript to FD, they can be executed Before, After, or twice
 * 2) Then, we send a "RunBeforeNow" command to the FD to tell him to do the
 *    first run_script() call. (ie ClientRunBeforeJob)
 */
int SendRunscriptsCommands(JobControlRecord* jcr)
{
  int result;
  RunScript* cmd = nullptr;
  POOLMEM *msg, *ehost;
  BareosSocket* fd = jcr->file_bsock;
  bool has_before_jobs = false;

  // See if there are any runscripts that need to be ran on the client.
  if (!HaveClientRunscripts(jcr->impl->res.job->RunScripts)) { return 1; }

  Dmsg0(120, "dird: sending runscripts to fd\n");

  msg = GetPoolMemory(PM_FNAME);
  ehost = GetPoolMemory(PM_FNAME);
  foreach_alist (cmd, jcr->impl->res.job->RunScripts) {
    if (!cmd->target.empty()) {
      ehost = edit_job_codes(jcr, ehost, cmd->target.c_str(), "");
      Dmsg2(200, "dird: runscript %s -> %s\n", cmd->target.c_str(), ehost);

      if (bstrcmp(ehost, jcr->impl->res.client->resource_name_)) {
        PmStrcpy(msg, cmd->command.c_str());
        BashSpaces(msg);

        Dmsg1(120, "dird: sending runscripts to fd '%s'\n",
              cmd->command.c_str());

        fd->fsend(runscriptcmd, cmd->on_success, cmd->on_failure,
                  cmd->fail_on_error, cmd->when, msg);

        result = response(jcr, fd, OKRunScript, "RunScript", DISPLAY_ERROR);

        if (!result) { goto bail_out; }
      }
      /* TODO : we have to play with other client */
      /*
        else {
        send command to another client
        }
      */
    }

    // See if this is a ClientRunBeforeJob.
    if (cmd->when & SCRIPT_Before || cmd->when & SCRIPT_AfterVSS) {
      has_before_jobs = true;
    }
  }

  // Tell the FD to execute the ClientRunBeforeJob
  if (has_before_jobs) {
    fd->fsend(runbeforenowcmd);
    if (!response(jcr, fd, OKRunBeforeNow, "RunBeforeNow", DISPLAY_ERROR)) {
      goto bail_out;
    }
  }

  FreePoolMemory(msg);
  FreePoolMemory(ehost);

  return 1;

bail_out:
  Jmsg(jcr, M_FATAL, 0, _("Client \"%s\" RunScript failed.\n"), ehost);
  FreePoolMemory(msg);
  FreePoolMemory(ehost);

  return 0;
}

struct RestoreObjectContext {
  JobControlRecord* jcr;
  int count;
};

// RestoreObjectHandler is called for each file found
static int RestoreObjectHandler(void* ctx, int, char** row)
{
  BareosSocket* fd;
  bool is_compressed;
  RestoreObjectContext* octx = (RestoreObjectContext*)ctx;
  JobControlRecord* jcr = octx->jcr;

  fd = jcr->file_bsock;
  if (jcr->IsJobCanceled()) { return 1; }

  // Old File Daemon doesn't handle restore objects
  if (jcr->impl->FDVersion < FD_VERSION_3) {
    Jmsg(jcr, M_WARNING, 0,
         _("Client \"%s\" may not be used to restore "
           "this job. Please upgrade your client.\n"),
         jcr->impl->res.client->resource_name_);
    return 1;
  }

  if (jcr->impl->FDVersion
      < FD_VERSION_5) { /* Old version without PluginName */
    fd->fsend("restoreobject JobId=%s %s,%s,%s,%s,%s,%s\n", row[0], row[1],
              row[2], row[3], row[4], row[5], row[6]);
  } else {
    // bash spaces from PluginName
    BashSpaces(row[9]);
    fd->fsend("restoreobject JobId=%s %s,%s,%s,%s,%s,%s,%s\n", row[0], row[1],
              row[2], row[3], row[4], row[5], row[6], row[9]);
  }
  Dmsg1(010, "Send obj hdr=%s", fd->msg);

  fd->message_length = PmStrcpy(fd->msg, row[7]);
  fd->send(); /* send Object name */

  Dmsg1(010, "Send obj: %s\n", fd->msg);

  jcr->db->UnescapeObject(jcr, row[8],           /* Object  */
                          str_to_uint64(row[1]), /* Object length */
                          fd->msg, &fd->message_length);
  fd->send(); /* send object */
  octx->count++;

  // Don't try to print compressed objects.
  is_compressed = str_to_uint64(row[5]) > 0;
  if (debug_level >= 100 && !is_compressed) {
    for (int i = 0; i < fd->message_length; i++) {
      if (!fd->msg[i]) { fd->msg[i] = ' '; }
    }

    Dmsg1(100, "Send obj: %s\n", fd->msg);
  }

  return 0;
}

bool SendPluginOptions(JobControlRecord* jcr)
{
  BareosSocket* fd = jcr->file_bsock;
  int i;
  PoolMem cur_plugin_options(PM_MESSAGE);
  const char* plugin_options;
  POOLMEM* msg;

  if (jcr->impl->plugin_options) {
    msg = GetPoolMemory(PM_FNAME);
    PmStrcpy(msg, jcr->impl->plugin_options);
    BashSpaces(msg);

    fd->fsend(pluginoptionscmd, msg);
    FreePoolMemory(msg);

    if (!response(jcr, fd, OKPluginOptions, "PluginOptions", DISPLAY_ERROR)) {
      Jmsg(jcr, M_FATAL, 0, _("Plugin options failed.\n"));
      return false;
    }
  }
  if (jcr->impl->res.job && jcr->impl->res.job->FdPluginOptions
      && jcr->impl->res.job->FdPluginOptions->size()) {
    Dmsg2(200, "dird: sendpluginoptions found FdPluginOptions in res.job\n");
    foreach_alist_index (i, plugin_options,
                         jcr->impl->res.job->FdPluginOptions) {
      PmStrcpy(cur_plugin_options, plugin_options);
      BashSpaces(cur_plugin_options.c_str());

      fd->fsend(pluginoptionscmd, cur_plugin_options.c_str());
      if (!response(jcr, fd, OKPluginOptions, "PluginOptions", DISPLAY_ERROR)) {
        Jmsg(jcr, M_FATAL, 0, _("Plugin options failed.\n"));
        return false;
      }
    }
  }

  return true;
}

static void SendGlobalRestoreObjects(JobControlRecord* jcr,
                                     RestoreObjectContext* octx)
{
  char ed1[50];
  PoolMem query(PM_MESSAGE);

  if (!jcr->JobIds || !jcr->JobIds[0]) { return; }

  // Send restore objects for all jobs involved
  jcr->db->FillQuery(query, BareosDb::SQL_QUERY::get_restore_objects,
                     jcr->JobIds, FT_RESTORE_FIRST);
  jcr->db->SqlQuery(query.c_str(), RestoreObjectHandler, (void*)octx);

  jcr->db->FillQuery(query, BareosDb::SQL_QUERY::get_restore_objects,
                     jcr->JobIds, FT_PLUGIN_CONFIG);
  jcr->db->SqlQuery(query.c_str(), RestoreObjectHandler, (void*)octx);

  // Send config objects for the current restore job
  jcr->db->FillQuery(query, BareosDb::SQL_QUERY::get_restore_objects,
                     edit_uint64(jcr->JobId, ed1), FT_PLUGIN_CONFIG_FILLED);
  jcr->db->SqlQuery(query.c_str(), RestoreObjectHandler, (void*)octx);
}

static void SendJobSpecificRestoreObjects(JobControlRecord* jcr,
                                          JobId_t JobId,
                                          RestoreObjectContext* octx)
{
  char ed1[50];
  PoolMem query(PM_MESSAGE);

  // Send restore objects for specific JobId.
  jcr->db->FillQuery(query, BareosDb::SQL_QUERY::get_restore_objects,
                     edit_uint64(JobId, ed1), FT_RESTORE_FIRST);
  jcr->db->SqlQuery(query.c_str(), RestoreObjectHandler, (void*)octx);

  jcr->db->FillQuery(query, BareosDb::SQL_QUERY::get_restore_objects,
                     edit_uint64(JobId, ed1), FT_PLUGIN_CONFIG);
  jcr->db->SqlQuery(query.c_str(), RestoreObjectHandler, (void*)octx);
}

bool SendRestoreObjects(JobControlRecord* jcr, JobId_t JobId, bool send_global)
{
  BareosSocket* fd;
  RestoreObjectContext octx;

  octx.jcr = jcr;
  octx.count = 0;

  if (send_global) {
    SendGlobalRestoreObjects(jcr, &octx);
  } else {
    SendJobSpecificRestoreObjects(jcr, JobId, &octx);
  }

  /*
   * Send to FD only if we have at least one restore object.
   * This permits backward compatibility with older FDs.
   */
  if (octx.count > 0) {
    fd = jcr->file_bsock;
    fd->fsend(restoreobjectendcmd);
    if (!response(jcr, fd, OKRestoreObject, "RestoreObject", DISPLAY_ERROR)) {
      Jmsg(jcr, M_FATAL, 0, _("RestoreObject failed.\n"));
      return false;
    }
  }

  return true;
}

/**
 * Read the attributes from the File daemon for
 * a Verify job and store them in the catalog.
 */
int GetAttributesAndPutInCatalog(JobControlRecord* jcr)
{
  BareosSocket* fd;
  int n = 0;
  AttributesDbRecord* ar = NULL;
  PoolMem digest(PM_MESSAGE);

  fd = jcr->file_bsock;
  jcr->impl->jr.FirstIndex = 1;
  jcr->impl->FileIndex = 0;

  // Start transaction allocates jcr->attr and jcr->ar if needed
  jcr->db->StartTransaction(jcr); /* start transaction if not already open */
  ar = jcr->ar;

  Dmsg0(120, "dird: waiting to receive file attributes\n");

  // Pickup file attributes and digest
  while (!fd->errors && (n = BgetDirmsg(fd)) > 0) {
    uint32_t file_index;
    int stream, len;
    char *p, *fn;
    PoolMem Digest(PM_MESSAGE); /* Either Verify opts or MD5/SHA1 digest */
    Digest.check_size(fd->message_length);
    if ((len
         = sscanf(fd->msg, "%ld %d %s", &file_index, &stream, Digest.c_str()))
        != 3) {
      Jmsg(jcr, M_FATAL, 0,
           _("<filed: bad attributes, expected 3 fields got %d\n"
             "message_length=%d msg=%s\n"),
           len, fd->message_length, fd->msg);
      jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated);
      return 0;
    }
    p = fd->msg;

    // The following three fields were sscanf'ed above so skip them
    SkipNonspaces(&p); /* skip FileIndex */
    SkipSpaces(&p);
    SkipNonspaces(&p); /* skip Stream */
    SkipSpaces(&p);
    SkipNonspaces(&p); /* skip Opts_Digest */
    p++;               /* skip space */
    Dmsg1(debuglevel, "Stream=%d\n", stream);
    if (stream == STREAM_UNIX_ATTRIBUTES
        || stream == STREAM_UNIX_ATTRIBUTES_EX) {
      if (jcr->cached_attribute) {
        Dmsg3(debuglevel, "Cached attr. Stream=%d fname=%s\n", ar->Stream,
              ar->fname, ar->attr);
        if (!jcr->db->CreateFileAttributesRecord(jcr, ar)) {
          Jmsg1(jcr, M_FATAL, 0, _("Attribute create error. %s"),
                jcr->db->strerror());
        }
      }

      // Any cached attr is flushed so we can reuse jcr->attr and jcr->ar
      fn = jcr->impl->fname
          = CheckPoolMemorySize(jcr->impl->fname, fd->message_length);
      while (*p != 0) { *fn++ = *p++; /* copy filename */ }
      *fn = *p++;             /* term filename and point p to attribs */
      PmStrcpy(jcr->attr, p); /* save attributes */
      jcr->JobFiles++;
      jcr->impl->FileIndex = file_index;
      ar->attr = jcr->attr;
      ar->fname = jcr->impl->fname;
      ar->FileIndex = file_index;
      ar->Stream = stream;
      ar->link = NULL;
      ar->JobId = jcr->JobId;
      ar->ClientId = jcr->ClientId;
      ar->PathId = 0;
      ar->Digest = NULL;
      ar->DigestType = CRYPTO_DIGEST_NONE;
      ar->DeltaSeq = 0;
      jcr->cached_attribute = true;

      Dmsg2(debuglevel, "dird<filed: stream=%d %s\n", stream, jcr->impl->fname);
      Dmsg1(debuglevel, "dird<filed: attr=%s\n", ar->attr);
      jcr->FileId = ar->FileId;
    } else if (CryptoDigestStreamType(stream) != CRYPTO_DIGEST_NONE) {
      size_t length;

      /*
       * First, get STREAM_UNIX_ATTRIBUTES and fill AttributesDbRecord structure
       * Next, we CAN have a CRYPTO_DIGEST, so we fill AttributesDbRecord with
       * it (or not) When we get a new STREAM_UNIX_ATTRIBUTES, we known that we
       * can add file to the catalog At the end, we have to add the last file
       */
      if (jcr->impl->FileIndex != (uint32_t)file_index) {
        Jmsg3(jcr, M_ERROR, 0, _("%s index %d not same as attributes %d\n"),
              stream_to_ascii(stream), file_index, jcr->impl->FileIndex);
        continue;
      }

      ar->Digest = digest.c_str();
      ar->DigestType = CryptoDigestStreamType(stream);
      length = strlen(Digest.c_str());
      digest.check_size(length * 2 + 1);
      jcr->db->EscapeString(jcr, digest.c_str(), Digest.c_str(), length);
      Dmsg4(debuglevel, "stream=%d DigestLen=%d Digest=%s type=%d\n", stream,
            strlen(digest.c_str()), digest.c_str(), ar->DigestType);
    }
    jcr->impl->jr.JobFiles = jcr->JobFiles = file_index;
    jcr->impl->jr.LastIndex = file_index;
  }

  if (IsBnetError(fd)) {
    Jmsg1(jcr, M_FATAL, 0,
          _("<filed: Network error getting attributes. ERR=%s\n"),
          fd->bstrerror());
    return 0;
  }

  if (jcr->cached_attribute) {
    Dmsg3(debuglevel, "Cached attr with digest. Stream=%d fname=%s attr=%s\n",
          ar->Stream, ar->fname, ar->attr);
    if (!jcr->db->CreateFileAttributesRecord(jcr, ar)) {
      Jmsg1(jcr, M_FATAL, 0, _("Attribute create error. %s"),
            jcr->db->strerror());
    }
    jcr->cached_attribute = false;
  }

  jcr->setJobStatusWithPriorityCheck(JS_Terminated);

  return 1;
}

// Cancel a job running in the File daemon
bool CancelFileDaemonJob(UaContext* ua, JobControlRecord* jcr)
{
  BareosSocket* fd;

  ua->jcr->impl->res.client = jcr->impl->res.client;
  if (!ConnectToFileDaemon(ua->jcr, 10, me->FDConnectTimeout, true, ua)) {
    ua->ErrorMsg(_("\nFailed to connect to File daemon.\n"));
    return false;
  }
  Dmsg0(200, "Connected to file daemon\n");
  fd = ua->jcr->file_bsock;
  fd->fsend("cancel Job=%s\n", jcr->Job);
  while (fd->recv() >= 0) { ua->SendMsg("%s", fd->msg); }
  fd->signal(BNET_TERMINATE);
  fd->close();
  delete ua->jcr->file_bsock;
  ua->jcr->file_bsock = NULL;
  jcr->file_bsock->SetTerminated();
  jcr->MyThreadSendSignal(TIMEOUT_SIGNAL);
  return true;
}

// Get the status of a remote File Daemon.
void DoNativeClientStatus(UaContext* ua, ClientResource* client, char* cmd)
{
  BareosSocket* fd;

  // Connect to File daemon
  ua->jcr->impl->res.client = client;

  // Try to connect for 15 seconds
  if (!ua->api) {
    ua->SendMsg(_("Connecting to Client %s at %s:%d\n"), client->resource_name_,
                client->address, client->FDport);
  }

  if (!ConnectToFileDaemon(ua->jcr, 1, 15, false, ua)) {
    ua->SendMsg(_("\nFailed to connect to Client %s.\n====\n"),
                client->resource_name_);
    if (ua->jcr->file_bsock) {
      ua->jcr->file_bsock->close();
      delete ua->jcr->file_bsock;
      ua->jcr->file_bsock = NULL;
    }
    return;
  }

  Dmsg0(20, _("Connected to file daemon\n"));
  fd = ua->jcr->file_bsock;
  if (cmd) {
    fd->fsend(".status %s", cmd);
  } else {
    fd->fsend("status");
  }

  while (fd->recv() >= 0) { ua->SendMsg("%s", fd->msg); }

  fd->signal(BNET_TERMINATE);
  fd->close();
  delete ua->jcr->file_bsock;
  ua->jcr->file_bsock = NULL;

  return;
}

// resolve a host on a filedaemon
void DoClientResolve(UaContext* ua, ClientResource* client)
{
  BareosSocket* fd;

  // Connect to File daemon
  ua->jcr->impl->res.client = client;

  // Try to connect for 15 seconds
  if (!ua->api) {
    ua->SendMsg(_("Connecting to Client %s at %s:%d\n"), client->resource_name_,
                client->address, client->FDport);
  }

  if (!ConnectToFileDaemon(ua->jcr, 1, 15, false, ua)) {
    ua->SendMsg(_("\nFailed to connect to Client %s.\n====\n"),
                client->resource_name_);
    if (ua->jcr->file_bsock) {
      ua->jcr->file_bsock->close();
      delete ua->jcr->file_bsock;
      ua->jcr->file_bsock = NULL;
    }
    return;
  }

  Dmsg0(20, _("Connected to file daemon\n"));
  fd = ua->jcr->file_bsock;

  for (int i = 1; i < ua->argc; i++) {
    if (!*ua->argk[i]) { continue; }

    fd->fsend("resolve %s", ua->argk[i]);
    while (fd->recv() >= 0) { ua->SendMsg("%s", fd->msg); }
  }

  fd->signal(BNET_TERMINATE);
  fd->close();
  delete ua->jcr->file_bsock;
  ua->jcr->file_bsock = NULL;

  return;
}

class SocketGuard {
 public:
  ~SocketGuard()
  {
    if (owns_) {
      fd_->close();
      delete fd_;
    }
  }

  explicit SocketGuard(BareosSocket* fd) : fd_{fd} {}
  void Release() { owns_ = false; }

 private:
  bool owns_{true};
  BareosSocket* fd_;
};

void* HandleFiledConnection(ConnectionPool* connections,
                            BareosSocket* fd,
                            char* client_name,
                            int fd_protocol_version)
{
  ClientResource* client_resource;
  Connection* connection = NULL;
  SocketGuard socket_guard{fd};

  client_resource
      = (ClientResource*)my_config->GetResWithName(R_CLIENT, client_name);
  if (!client_resource) {
    Emsg1(M_WARNING, 0,
          "Client \"%s\" tries to connect, "
          "but no matching resource is defined.\n",
          client_name);
    return NULL;
  }

  if (!IsConnectFromClientAllowed(client_resource)) {
    Emsg1(M_WARNING, 0,
          "Connection from client \"%s\" to director is not allowed.\n",
          client_name);
    return NULL;
  }

  if (!AuthenticateFileDaemon(fd, client_name)) { return NULL; }

  Dmsg1(20, "Connected to file daemon %s\n", client_name);

  connection
      = connections->add_connection(client_name, fd_protocol_version, fd, true);
  if (!connection) {
    Emsg0(M_ERROR, 0, "Failed to add connection to pool.\n");
    return NULL;
  }

  RunOnIncomingConnectInterval(client_name).Run();

  /*
   * The connection is now kept in the connection_pool.
   * This thread is no longer required and will end now.
   */
  socket_guard.Release();
  return NULL;
}
} /* namespace directordaemon */