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

dir_cmd.cc « stored « src « core - github.com/bareos/bareos.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2047de07edfcdff935ccccb5ea4174ce31995d68 (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
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
/*
   BAREOS® - Backup Archiving REcovery Open Sourced

   Copyright (C) 2001-2012 Free Software Foundation Europe e.V.
   Copyright (C) 2011-2012 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, May MMI
/**
 * @file
 * This file handles accepting Director Commands
 *
 * Most Director commands are handled here, with the
 * exception of the Job command command and subsequent
 * subcommands that are handled
 * in job.c.
 *
 * N.B. in this file, in general we must use lock_mutex(dev->mutex) rather
 * than dev->r_lock() so that we can examine the blocked
 * state rather than blocking ourselves because a Job
 * thread has the device blocked. In some "safe" cases,
 * we can do things to a blocked device. CAREFUL!!!!
 *
 * File daemon commands are handled in fd_cmds.c
 */

#include "include/bareos.h"
#include "stored/append.h"
#include "stored/stored.h"
#include "stored/acquire.h"
#include "stored/authenticate.h"
#include "stored/autochanger.h"
#include "stored/blocksize_boundaries.h"
#include "stored/bsr.h"
#include "stored/device_control_record.h"
#include "stored/sd_device_control_record.h"
#include "stored/fd_cmds.h"
#include "stored/stored_jcr_impl.h"
#include "stored/job.h"
#include "stored/label.h"
#include "stored/ndmp_tape.h"
#include "stored/reserve.h"
#include "stored/sd_cmds.h"
#include "stored/status.h"
#include "stored/sd_stats.h"
#include "stored/stored_globals.h"
#include "stored/wait.h"
#include "stored/job.h"
#include "stored/mac.h"
#include "include/protocol_types.h"
#include "lib/berrno.h"
#include "lib/bnet.h"
#include "lib/bsock.h"
#include "lib/bsock_tcp.h"
#include "lib/edit.h"
#include "lib/parse_bsr.h"
#include "lib/parse_conf.h"
#include "lib/thread_specific_data.h"
#include "lib/util.h"
#include "lib/watchdog.h"
#include "lib/qualified_resource_name_type_converter.h"
#include "include/jcr.h"

#include <memory>

/* Imported variables */
extern void terminate_child();

namespace storagedaemon {

/* Commands received from director that need scanning */
static char setbandwidth[] = "setbandwidth=%lld Job=%127s";
static char setdebugv0cmd[] = "setdebug=%d trace=%d";
static char setdebugv1cmd[] = "setdebug=%d trace=%d timestamp=%d";
static char cancelcmd[] = "cancel Job=%127s";
static char relabelcmd[]
    = "relabel %127s OldName=%127s NewName=%127s PoolName=%127s "
      "MediaType=%127s Slot=%hd drive=%hd MinBlocksize=%d MaxBlocksize=%d";
static char labelcmd[]
    = "label %127s VolumeName=%127s PoolName=%127s "
      "MediaType=%127s Slot=%hd drive=%hd MinBlocksize=%d MaxBlocksize=%d";
static char mountslotcmd[] = "mount %127s drive=%hd slot=%hd";
static char mountcmd[] = "mount %127s drive=%hd";
static char unmountcmd[] = "unmount %127s drive=%hd";
static char releasecmd[] = "release %127s drive=%hd";
static char readlabelcmd[] = "readlabel %127s Slot=%hd drive=%hd";
static char replicatecmd[]
    = "replicate JobId=%d Job=%127s address=%s port=%d ssl=%d "
      "Authorization=%100s";
static char passiveclientcmd[] = "passive client address=%s port=%d ssl=%d";
static char resolvecmd[] = "resolve %s";
static char pluginoptionscmd[] = "pluginoptions %s";

/* Responses sent to Director */
static char derrmsg[] = "3900 Invalid command:";
static char OKsetdebugv0[] = "3000 OK setdebug=%d tracefile=%s\n";
static char OKsetdebugv1[]
    = "3000 OK setdebug=%d trace=%d timestamp=%d tracefile=%s\n";
static char OKsetdevice[] = "3000 OK setdevice=%s autoselect=%d\n";
static char invalid_cmd[]
    = "3997 Invalid command for a Director with Monitor directive enabled.\n";
static char OK_bootstrap[] = "3000 OK bootstrap\n";
static char ERROR_bootstrap[] = "3904 Error bootstrap\n";
static char OK_replicate[] = "3000 OK replicate\n";
static char BADcmd[] = "3991 Bad %s command: %s\n";
static char OKBandwidth[] = "2000 OK Bandwidth\n";
static char OKpassive[] = "2000 OK passive client\n";
static char OKpluginoptions[] = "2000 OK plugin options\n";
static char OKsecureerase[] = "2000 OK SDSecureEraseCmd %s \n";

#define MAX_SETDEVICE_NAME_LENGTH 128  // including the trailing zero
static char setdevice_autoselect[] = "setdevice device=%127s autoselect=%d";

/* Forward referenced functions */
// static bool ActionOnPurgeCmd(JobControlRecord *jcr);
static bool BootstrapCmd(JobControlRecord* jcr);
static bool CancelCmd(JobControlRecord* cjcr);
static bool ChangerCmd(JobControlRecord* jcr);
static bool die_cmd(JobControlRecord* jcr);
static bool LabelCmd(JobControlRecord* jcr);
static bool ListenCmd(JobControlRecord* jcr);
static bool MountCmd(JobControlRecord* jcr);
static bool PassiveCmd(JobControlRecord* jcr);
static bool PluginoptionsCmd(JobControlRecord* jcr);
static bool ReadlabelCmd(JobControlRecord* jcr);
static bool ResolveCmd(JobControlRecord* jcr);
static bool RelabelCmd(JobControlRecord* jcr);
static bool ReleaseCmd(JobControlRecord* jcr);
static bool ReplicateCmd(JobControlRecord* jcr);
static bool RunCmd(JobControlRecord* jcr);
static bool SecureerasereqCmd(JobControlRecord* jcr);
static bool SetbandwidthCmd(JobControlRecord* jcr);
static bool SetdebugCmd(JobControlRecord* jcr);
static bool UnmountCmd(JobControlRecord* jcr);
static bool SetdeviceCmd(JobControlRecord* jcr);

static DeviceControlRecord* FindDevice(JobControlRecord* jcr,
                                       PoolMem& dev_name,
                                       drive_number_t drive,
                                       BlockSizeBoundaries* blocksizes);
static void ReadVolumeLabel(JobControlRecord* jcr,
                            DeviceControlRecord* dcr,
                            Device* dev,
                            slot_number_t slot);
static void LabelVolumeIfOk(DeviceControlRecord* dcr,
                            char* oldname,
                            char* newname,
                            char* poolname,
                            slot_number_t Slot,
                            bool relabel);
static int TryAutoloadDevice(JobControlRecord* jcr,
                             DeviceControlRecord* dcr,
                             slot_number_t slot,
                             const char* VolName);
static void SendDirBusyMessage(BareosSocket* dir, Device* dev);

struct s_sd_dir_cmds {
  const char* cmd;
  bool (*func)(JobControlRecord* jcr);
  bool monitoraccess; /* set if monitors can access this cmd */
};

/**
 * The following are the recognized commands from the Director.
 *
 * Keywords are sorted first longest match when the keywords start with the same
 * string.
 */
static struct s_sd_dir_cmds cmds[] = {
    // { "action_on_purge",  ActionOnPurgeCmd, false },
    {"autochanger", ChangerCmd, false},
    {"bootstrap", BootstrapCmd, false},
    {"cancel", CancelCmd, false},
    {".die", die_cmd, false},
    {"finish", FinishCmd, false}, /**< End of backup */
    {"JobId=", job_cmd, false},   /**< Start Job */
    {"label", LabelCmd, false},   /**< Label a tape */
    {"listen", ListenCmd, false}, /**< Listen for an incoming Storage Job */
    {"mount", MountCmd, false},
    {"nextrun", nextRunCmd,
     false}, /**< Prepare for next backup/restore part of same Job */
    {"passive", PassiveCmd, false},
    {"pluginoptions", PluginoptionsCmd, false},
    {"readlabel", ReadlabelCmd, false},
    {"relabel", RelabelCmd, false}, /**< Relabel a tape */
    {"release", ReleaseCmd, false},
    {"resolve", ResolveCmd, false},
    {"replicate", ReplicateCmd, false}, /**< Replicate data to an external SD */
    {"run", RunCmd, false},             /**< Start of Job */
    {"getSecureEraseCmd", SecureerasereqCmd, false},
    {"setbandwidth=", SetbandwidthCmd, false},
    {"setdebug=", SetdebugCmd, false},  /**< Set debug level */
    {"setdevice", SetdeviceCmd, false}, /**< Set device parameter */
    {"stats", StatsCmd, false},
    {"status", StatusCmd, true},
    {".status", DotstatusCmd, true},
    {"unmount", UnmountCmd, false},
    {"use storage=", use_cmd, false},
    {NULL, NULL, false} /**< list terminator */
};

static inline bool AreMaxConcurrentJobsExceeded()
{
  JobControlRecord* jcr;
  unsigned int cnt = 0;

  foreach_jcr (jcr) {
    cnt++;
  }
  endeach_jcr(jcr);

  return (cnt >= me->MaxConcurrentJobs) ? true : false;
}

/**
 * Connection request from an director.
 *
 * Basic tasks done here:
 *  - Create a JobControlRecord record
 *  - Authenticate the Director
 *  - We wait for a command
 *  - We execute the command
 *  - We continue or exit depending on the return status
 */
void* HandleDirectorConnection(BareosSocket* dir)
{
  JobControlRecord* jcr;
  int i, errstat;
  int bnet_stat = 0;
  bool found, quit;

  if (AreMaxConcurrentJobsExceeded()) {
    Emsg0(
        M_ERROR, 0,
        _("Number of Jobs exhausted, please increase MaximumConcurrentJobs\n"));
    dir->signal(BNET_TERMINATE);
    return NULL;
  }

  // This is a connection from the Director, so setup a JobControlRecord
  jcr = NewStoredJcr();
  NewPlugins(jcr);      /* instantiate plugins */
  jcr->dir_bsock = dir; /* save Director bsock */
  jcr->dir_bsock->SetJcr(jcr);

  // Initialize Start Job condition variable
  errstat = pthread_cond_init(&jcr->sd_impl->job_start_wait, NULL);
  if (errstat != 0) {
    BErrNo be;
    Jmsg1(jcr, M_FATAL, 0,
          _("Unable to init job start cond variable: ERR=%s\n"),
          be.bstrerror(errstat));
    goto bail_out;
  }

  // Initialize End Job condition variable
  errstat = pthread_cond_init(&jcr->sd_impl->job_end_wait, NULL);
  if (errstat != 0) {
    BErrNo be;
    Jmsg1(jcr, M_FATAL, 0, _("Unable to init job end cond variable: ERR=%s\n"),
          be.bstrerror(errstat));
    goto bail_out;
  }

  Dmsg0(1000, "stored in start_job\n");

  SetJcrInThreadSpecificData(jcr);

  // Authenticate the Director
  if (!AuthenticateDirector(jcr)) {
    Jmsg(jcr, M_FATAL, 0, _("Unable to authenticate Director\n"));
    goto bail_out;
  }

  Dmsg0(90, "Message channel init completed.\n");

  quit = false;
  while (!quit) {
    // Read command
    if ((bnet_stat = dir->recv()) <= 0) { break; /* connection terminated */ }

    Dmsg1(199, "<dird: %s", dir->msg);

    // Ensure that device initialization is complete
    while (!init_done) { Bmicrosleep(1, 0); }

    found = false;
    for (i = 0; cmds[i].cmd; i++) {
      if (bstrncmp(cmds[i].cmd, dir->msg, strlen(cmds[i].cmd))) {
        if ((!cmds[i].monitoraccess) && (jcr->sd_impl->director->monitor)) {
          Dmsg1(100, "Command \"%s\" is invalid.\n", cmds[i].cmd);
          dir->fsend(invalid_cmd);
          dir->signal(BNET_EOD);
          break;
        }
        Dmsg1(200, "Do command: %s\n", cmds[i].cmd);
        if (!cmds[i].func(jcr)) { /* do command */
          quit = true;            /* error, get out */
          Dmsg1(190, "Command %s requests quit\n", cmds[i].cmd);
        }
        found = true; /* indicate command found */
        break;
      }
    }
    if (!found) { /* command not found */
      PoolMem err_msg;
      Mmsg(err_msg, "%s %s\n", derrmsg, dir->msg);
      dir->fsend(err_msg.c_str());
      break;
    }
  }

bail_out:
  GeneratePluginEvent(jcr, bSdEventJobEnd);
  DequeueMessages(jcr); /* send any queued messages */
  dir->signal(BNET_TERMINATE);
  FreePlugins(jcr); /* release instantiated plugins */
  FreeJcr(jcr);

  return NULL;
}

/**
 * Force SD to die, and hopefully dump itself.  Turned on only in development
 * version.
 */
static bool die_cmd(JobControlRecord*)
{
#ifdef DEVELOPER
  JobControlRecord* djcr = NULL;
  int a;
  BareosSocket* dir = jcr->dir_bsock;
  pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

  if (strstr(dir->msg, "deadlock")) {
    Pmsg0(000, "I have been requested to deadlock ...\n");
    lock_mutex(m);
    lock_mutex(m);
  }

  Pmsg1(000, "I have been requested to die ... (%s)\n", dir->msg);
  a = djcr->JobId; /* ref NULL pointer */
  djcr->JobId = a;
#endif
  return false;
}


/**
 * Handles the secureerase request
 * replies the configured secure erase command
 * or "*None*"
 */
static bool SecureerasereqCmd(JobControlRecord* jcr)
{
  BareosSocket* dir = jcr->dir_bsock;

  Dmsg1(220, "Secure Erase Cmd Request: %s\n",
        (me->secure_erase_cmdline ? me->secure_erase_cmdline : "*None*"));

  return dir->fsend(
      OKsecureerase,
      (me->secure_erase_cmdline ? me->secure_erase_cmdline : "*None*"));
}

// Set bandwidth limit as requested by the Director
static bool SetbandwidthCmd(JobControlRecord* jcr)
{
  BareosSocket* dir = jcr->dir_bsock;
  int64_t bw = 0;
  JobControlRecord* cjcr;
  char Job[MAX_NAME_LENGTH];

  *Job = 0;
  if (sscanf(dir->msg, setbandwidth, &bw, Job) != 2 || bw < 0) {
    PmStrcpy(jcr->errmsg, dir->msg);
    dir->fsend(_("2991 Bad setbandwidth command: %s\n"), jcr->errmsg);
    return false;
  }

  if (*Job) {
    if (!(cjcr = get_jcr_by_full_name(Job))) {
      dir->fsend(_("2901 Job %s not found.\n"), Job);
    } else {
      cjcr->max_bandwidth = bw;
      if (cjcr->store_bsock) {
        cjcr->store_bsock->SetBwlimit(bw);
        if (me->allow_bw_bursting) { cjcr->store_bsock->SetBwlimitBursting(); }
      }
      FreeJcr(cjcr);
    }
  } else {                          /* No job requested, apply globally */
    me->max_bandwidth_per_job = bw; /* Overwrite directive */
  }

  return dir->fsend(OKBandwidth);
}

// Set debug level as requested by the Director
static bool SetdebugCmd(JobControlRecord* jcr)
{
  BareosSocket* dir = jcr->dir_bsock;
  int32_t level, trace_flag, timestamp_flag;
  int scan;

  Dmsg1(10, "SetdebugCmd: %s\n", dir->msg);
  scan = sscanf(dir->msg, setdebugv1cmd, &level, &trace_flag, &timestamp_flag);
  if (scan != 3) {
    scan = sscanf(dir->msg, setdebugv0cmd, &level, &trace_flag);
  }
  if ((scan != 3 && scan != 2) || level < 0) {
    dir->fsend(BADcmd, "setdebug", dir->msg);
    return false;
  }

  PoolMem tracefilename(PM_FNAME);
  Mmsg(tracefilename, "%s/%s.trace", TRACEFILEDIRECTORY, my_name);

  debug_level = level;
  SetTrace(trace_flag);
  if (scan == 3) {
    SetTimestamp(timestamp_flag);
    Dmsg4(50, "level=%d trace=%d timestamp=%d tracefilename=%s\n", level,
          GetTrace(), GetTimestamp(), tracefilename.c_str());
    return dir->fsend(OKsetdebugv1, level, GetTrace(), GetTimestamp(),
                      tracefilename.c_str());
  } else {
    Dmsg3(50, "level=%d trace=%d\n", level, GetTrace(), tracefilename.c_str());
    return dir->fsend(OKsetdebugv0, level, tracefilename.c_str());
  }
}

static DeviceResource* GetDeviceResource(const std::string& name)
{
  return static_cast<DeviceResource*>(
      my_config->GetResWithName(R_DEVICE, name.c_str()));
}

static bool SetdeviceCmd(JobControlRecord* jcr)
{
  BareosSocket* dir = jcr->dir_bsock;

  Dmsg1(10, "SetdeviceCmd: %s\n", dir->msg);

  std::vector<char> device_name(MAX_SETDEVICE_NAME_LENGTH);
  int autoselect_value = 0;
  int scan = sscanf(dir->msg, setdevice_autoselect, device_name.data(),
                    &autoselect_value);
  if (scan != 2) {
    dir->fsend(BADcmd, "setdevice", dir->msg);
    return false;
  }

  auto res = GetDeviceResource(device_name.data());
  if (res == nullptr) {
    std::string err{"Device not found: "};
    err += device_name.data();
    dir->fsend(BADcmd, "setdevice", err.c_str());
    return false;
  }

  res->autoselect = autoselect_value == 0 ? false : true;
  if (res->dev) { res->dev->autoselect = res->autoselect; }

  return dir->fsend(OKsetdevice, device_name.data(), autoselect_value);
}

/**
 * Cancel a Job
 *   Be careful, we switch to using the job's JobControlRecord! So, using
 *   BSOCKs on that jcr can have two threads in the same code.
 */
static bool CancelCmd(JobControlRecord* cjcr)
{
  BareosSocket* dir = cjcr->dir_bsock;
  int oldStatus;
  char Job[MAX_NAME_LENGTH];
  JobId_t JobId;
  JobControlRecord* jcr;
  int status;
  const char* reason;

  if (sscanf(dir->msg, cancelcmd, Job) == 1) {
    status = JS_Canceled;
    reason = "canceled";
  } else {
    dir->fsend(_("3903 Error scanning cancel command.\n"));
    goto bail_out;
  }

  // See if the Jobname is a number only then its a JobId.
  if (Is_a_number(Job)) {
    JobId = str_to_int64(Job);
    if (!(jcr = get_jcr_by_id(JobId))) {
      dir->fsend(_("3904 Job %s not found.\n"), Job);
      goto bail_out;
    }
  } else {
    if (!(jcr = get_jcr_by_full_name(Job))) {
      dir->fsend(_("3904 Job %s not found.\n"), Job);
      goto bail_out;
    }
  }

  oldStatus = jcr->getJobStatus();
  jcr->setJobStatusWithPriorityCheck(status);

  Dmsg2(800, "Cancel JobId=%d %p\n", jcr->JobId, jcr);
  if (!jcr->authenticated
      && (oldStatus == JS_WaitFD || oldStatus == JS_WaitSD)) {
    pthread_cond_signal(
        &jcr->sd_impl->job_start_wait); /* wake waiting thread */
  }

  if (jcr->file_bsock) {
    jcr->file_bsock->SetTerminated();
    jcr->file_bsock->SetTimedOut();
    Dmsg2(800, "Term bsock jid=%d %p\n", jcr->JobId, jcr);
  } else {
    if (oldStatus != JS_WaitSD) {
      // Still waiting for FD to connect, release it
      pthread_cond_signal(&jcr->sd_impl->job_start_wait); /* wake waiting job */
      Dmsg2(800, "Signal FD connect jid=%d %p\n", jcr->JobId, jcr);
    }
  }

  // If thread waiting on mount, wake him
  if (jcr->sd_impl->dcr && jcr->sd_impl->dcr->dev
      && jcr->sd_impl->dcr->dev->waiting_for_mount()) {
    pthread_cond_broadcast(&jcr->sd_impl->dcr->dev->wait_next_vol);
    Dmsg1(100, "JobId=%u broadcast wait_device_release\n",
          (uint32_t)jcr->JobId);
    ReleaseDeviceCond();
  }

  if (jcr->sd_impl->read_dcr && jcr->sd_impl->read_dcr->dev
      && jcr->sd_impl->read_dcr->dev->waiting_for_mount()) {
    pthread_cond_broadcast(&jcr->sd_impl->read_dcr->dev->wait_next_vol);
    Dmsg1(100, "JobId=%u broadcast wait_device_release\n",
          (uint32_t)jcr->JobId);
    ReleaseDeviceCond();
  }

  /*
   * See if the Job has a certain protocol.
   * When canceling a NDMP job make sure we call the end_of_ndmp_* functions.
   */
  switch (jcr->getJobProtocol()) {
    case PT_NDMP_BAREOS:
      switch (jcr->getJobType()) {
        case JT_BACKUP:
          EndOfNdmpBackup(jcr);
          break;
        case JT_RESTORE:
          EndOfNdmpRestore(jcr);
          break;
        default:
          break;
      }
  }

  pthread_cond_signal(&jcr->sd_impl->job_end_wait); /* wake waiting job */
  jcr->MyThreadSendSignal(TIMEOUT_SIGNAL);

  dir->fsend(_("3000 JobId=%ld Job=\"%s\" marked to be %s.\n"), jcr->JobId,
             jcr->Job, reason);
  FreeJcr(jcr);

bail_out:
  dir->signal(BNET_EOD);
  return true;
}

// Resolve a hostname
static bool ResolveCmd(JobControlRecord* jcr)
{
  BareosSocket* dir = jcr->dir_bsock;
  dlist<IPADDR>* addr_list;
  const char* errstr;
  char addresses[2048];
  char hostname[2048];

  sscanf(dir->msg, resolvecmd, &hostname);

  if ((addr_list = BnetHost2IpAddrs(hostname, 0, &errstr)) == NULL) {
    dir->fsend(_("%s: Failed to resolve %s\n"), my_name, hostname);
    goto bail_out;
  }

  dir->fsend(
      _("%s resolves %s to %s\n"), my_name, hostname,
      BuildAddressesString(addr_list, addresses, sizeof(addresses), false));
  FreeAddresses(addr_list);

bail_out:
  dir->signal(BNET_EOD);
  return true;
}

static drive_number_t IntToDriveNumber(short int drive_input)
{
  return (drive_input == -1) ? kInvalidDriveNumber
                             : static_cast<drive_number_t>(drive_input);
}

static bool DoLabel(JobControlRecord* jcr, bool relabel)
{
  int len;
  POOLMEM *newname, *oldname, *poolname, *mediatype;
  PoolMem dev_name;
  BareosSocket* dir = jcr->dir_bsock;
  DeviceControlRecord* dcr;
  Device* dev;
  BlockSizeBoundaries blocksizes;
  bool ok = false;
  slot_number_t slot;

  /*
   * Determine the length of the temporary buffers.
   * If the total length of the incoming message is less
   * then MAX_NAME_LENGTH we can use that as the upper limit.
   * If the incomming message is bigger then MAX_NAME_LENGTH
   * limit the temporary buffer to MAX_NAME_LENGTH bytes as
   * we use a sscanf %127s for reading the temorary buffer.
   */
  len = dir->message_length + 1;
  if (len > MAX_NAME_LENGTH) { len = MAX_NAME_LENGTH; }

  newname = GetMemory(len);
  oldname = GetMemory(len);
  poolname = GetMemory(len);
  mediatype = GetMemory(len);

  short int drive_input = -1;

  if (relabel) {
    if (sscanf(dir->msg, relabelcmd, dev_name.c_str(), oldname, newname,
               poolname, mediatype, &slot, &drive_input,
               &blocksizes.min_block_size, &blocksizes.max_block_size)
        == 9) {
      ok = true;
    }
  } else {
    *oldname = 0;
    if (sscanf(dir->msg, labelcmd, dev_name.c_str(), newname, poolname,
               mediatype, &slot, &drive_input, &blocksizes.min_block_size,
               &blocksizes.max_block_size)
        == 8) {
      ok = true;
    }
  }

  if (ok) {
    UnbashSpaces(newname);
    UnbashSpaces(oldname);
    UnbashSpaces(poolname);
    UnbashSpaces(mediatype);

    drive_number_t drive = IntToDriveNumber(drive_input);

    dcr = FindDevice(jcr, dev_name, drive, &blocksizes);
    if (dcr) {
      dev = dcr->dev;


      dev->Lock(); /* Use P to avoid indefinite block */
      dcr->VolMinBlocksize = blocksizes.min_block_size;
      dcr->VolMaxBlocksize = blocksizes.max_block_size;
      dev->SetBlocksizes(dcr); /* apply blocksizes from dcr to dev  */

      if (!dev->IsOpen() && !dev->IsBusy()) {
        Dmsg1(400, "Can %slabel. Device is not open\n", relabel ? "re" : "");
        LabelVolumeIfOk(dcr, oldname, newname, poolname, slot, relabel);
        dev->close(dcr);
        /* Under certain "safe" conditions, we can steal the lock */
      } else if (dev->CanStealLock()) {
        Dmsg0(400, "Can relabel. CanStealLock\n");
        LabelVolumeIfOk(dcr, oldname, newname, poolname, slot, relabel);
      } else if (dev->IsBusy() || dev->IsBlocked()) {
        SendDirBusyMessage(dir, dev);
      } else { /* device not being used */
        Dmsg0(400, "Can relabel. device not used\n");
        LabelVolumeIfOk(dcr, oldname, newname, poolname, slot, relabel);
      }
      dev->Unlock();
      FreeDeviceControlRecord(dcr);
    } else {
      dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"),
                 dev_name.c_str());
    }
  } else {
    /* NB dir->msg gets clobbered in BnetFsend, so save command */
    PmStrcpy(jcr->errmsg, dir->msg);
    dir->fsend(_("3903 Error scanning label command: %s\n"), jcr->errmsg);
  }
  FreeMemory(oldname);
  FreeMemory(newname);
  FreeMemory(poolname);
  FreeMemory(mediatype);
  dir->signal(BNET_EOD);
  return true;
}

// Label a Volume
static bool LabelCmd(JobControlRecord* jcr) { return DoLabel(jcr, false); }

static bool RelabelCmd(JobControlRecord* jcr) { return DoLabel(jcr, true); }

/**
 * Read the tape label and determine if we can safely
 * label the tape (not a Bareos volume), then label it.
 *
 *  Enter with the mutex set
 */
static void LabelVolumeIfOk(DeviceControlRecord* dcr,
                            char* oldname,
                            char* newname,
                            char* poolname,
                            slot_number_t slot,
                            bool relabel)
{
  BareosSocket* dir = dcr->jcr->dir_bsock;
  bsteal_lock_t hold;
  Device* dev = dcr->dev;
  int label_status;
  DeviceMode mode;
  const char* volname = relabel ? oldname : newname;
  char ed1[50];

  StealDeviceLock(dev, &hold, BST_WRITING_LABEL);
  Dmsg1(100, "Stole device %s lock, writing label.\n", dev->print_name());

  Dmsg0(90, "TryAutoloadDevice - looking for volume_info\n");
  switch (TryAutoloadDevice(dcr->jcr, dcr, slot, volname)) {
    case -1:
      goto cleanup;
    case -2:
      goto bail_out;
    case 0:
    default:
      break;
  }

  // Ensure that the device is open -- AutoloadDevice() closes it
  if (dev->IsTape()) {
    mode = DeviceMode::OPEN_READ_WRITE;
  } else {
    mode = DeviceMode::CREATE_READ_WRITE;
  }

  // Set old volume name for open if relabeling
  dcr->setVolCatName(volname);

  if (!dev->open(dcr, mode)) {
    dir->fsend(_("3910 Unable to open device \"%s\": ERR=%s\n"),
               dev->print_name(), dev->bstrerror());
    goto cleanup;
  }

  // See what we have for a Volume
  label_status = ReadDevVolumeLabel(dcr);

  // Set new volume name
  dcr->setVolCatName(newname);
  switch (label_status) {
    case VOL_NAME_ERROR:
    case VOL_VERSION_ERROR:
    case VOL_LABEL_ERROR:
    case VOL_OK:
      if (!relabel) {
        dir->fsend(_("3920 Cannot label Volume because it is already labeled: "
                     "\"%s\"\n"),
                   dev->VolHdr.VolumeName);
        goto cleanup;
      }

      // Relabel request. If oldname matches, continue
      if (!bstrcmp(oldname, dev->VolHdr.VolumeName)) {
        dir->fsend(_("3921 Wrong volume mounted.\n"));
        goto cleanup;
      }

      if (dev->label_type != B_BAREOS_LABEL) {
        dir->fsend(_("3922 Cannot relabel an ANSI/IBM labeled Volume.\n"));
        goto cleanup;
      }
      [[fallthrough]];
    case VOL_IO_ERROR:
    case VOL_NO_LABEL:
      if (!WriteNewVolumeLabelToDev(dcr, newname, poolname, relabel)) {
        dir->fsend(_("3912 Failed to label Volume: ERR=%s\n"),
                   dev->bstrerror());
        goto cleanup;
      }
      bstrncpy(dcr->VolumeName, newname, sizeof(dcr->VolumeName));

      // The following 3000 OK label. string is scanned in ua_label.c
      dir->fsend("3000 OK label. VolBytes=%s Volume=\"%s\" Device=%s\n",
                 edit_uint64(dev->VolCatInfo.VolCatBytes, ed1), newname,
                 dev->print_name());
      break;
    case VOL_NO_MEDIA:
      dir->fsend(_("3914 Failed to label Volume (no media): ERR=%s\n"),
                 dev->bstrerror());
      break;
    default:
      dir->fsend(_("3913 Cannot label Volume. "
                   "Unknown status %d from ReadVolumeLabel()\n"),
                 label_status);
      break;
  }

cleanup:
  if (dev->IsOpen() && !dev->HasCap(CAP_ALWAYSOPEN)) { dev->close(dcr); }
  if (!dev->IsOpen()) { dev->ClearVolhdr(); }
  VolumeUnused(dcr); /* no longer using volume */

bail_out:
  GiveBackDeviceLock(dev, &hold);

  return;
}

/**
 * Read the tape label
 *
 *  Enter with the mutex set
 */
static bool ReadLabel(DeviceControlRecord* dcr)
{
  int ok;
  JobControlRecord* jcr = dcr->jcr;
  BareosSocket* dir = jcr->dir_bsock;
  bsteal_lock_t hold;
  Device* dev = dcr->dev;

  StealDeviceLock(dev, &hold, BST_DOING_ACQUIRE);

  dcr->VolumeName[0] = 0;
  dev->ClearLabeled(); /* force read of label */
  switch (ReadDevVolumeLabel(dcr)) {
    case VOL_OK:
      dir->fsend(_("3001 Mounted Volume: %s\n"), dev->VolHdr.VolumeName);
      ok = true;
      break;
    default:
      dir->fsend(
          _("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
          dev->print_name(), jcr->errmsg);
      ok = false;
      break;
  }
  VolumeUnused(dcr);
  GiveBackDeviceLock(dev, &hold);
  return ok;
}

// Searches for device by name, and if found, creates a dcr and returns it.
static DeviceControlRecord* FindDevice(JobControlRecord* jcr,
                                       PoolMem& devname,
                                       drive_number_t drive,
                                       BlockSizeBoundaries* blocksizes)
{
  DeviceResource* device_resource = nullptr;
  AutochangerResource* changer;
  bool found = false;
  DeviceControlRecord* dcr = NULL;

  UnbashSpaces(devname);
  foreach_res (device_resource, R_DEVICE) {
    // Find resource, and make sure we were able to open it
    if (bstrcmp(device_resource->resource_name_, devname.c_str())) {
      if (!device_resource->dev) {
        device_resource->dev = FactoryCreateDevice(jcr, device_resource);
      }
      if (!device_resource->dev) {
        Jmsg(jcr, M_WARNING, 0,
             _("\n"
               "     Device \"%s\" requested by DIR could not be opened or "
               "does not exist.\n"),
             devname.c_str());
        continue;
      }
      Dmsg1(20, "Found device %s\n", device_resource->resource_name_);
      found = true;
      break;
    }
  }

  if (!found) {
    foreach_res (changer, R_AUTOCHANGER) {
      // Find resource, and make sure we were able to open it
      if (bstrcmp(devname.c_str(), changer->resource_name_)) {
        // Try each device in this AutoChanger
        foreach_alist (device_resource, changer->device_resources) {
          Dmsg1(100, "Try changer device %s\n",
                device_resource->resource_name_);
          if (!device_resource->dev) {
            device_resource->dev = FactoryCreateDevice(jcr, device_resource);
          }
          if (!device_resource->dev) {
            Dmsg1(100, "Device %s could not be opened. Skipped\n",
                  devname.c_str());
            Jmsg(jcr, M_WARNING, 0,
                 _("\n"
                   "     Device \"%s\" in changer \"%s\" requested by DIR "
                   "could not be opened or does not exist.\n"),
                 device_resource->resource_name_, devname.c_str());
            continue;
          }
          if ((drive == kInvalidDriveNumber && device_resource->dev->autoselect)
              || drive == device_resource->dev->drive) {
            Dmsg1(20, "Found changer device %s\n",
                  device_resource->resource_name_);
            found = true;
            break;
          }
          Dmsg3(100, "Device %s drive wrong: want=%hd got=%hd skipping\n",
                devname.c_str(), drive, device_resource->dev->drive);

          if (changer->device_resources->current()
              == changer->device_resources->size()) {
            Jmsg(jcr, M_ERROR, 0,
                 _("Drive number \"%d\" for device \"%s\" not found.\n"), drive,
                 devname.c_str());
          }
        }
        break; /* we found it but could not open a device */
      }
    }
  }

  if (found) {
    Dmsg1(100, "Found device %s\n", device_resource->resource_name_);
    dcr = new StorageDaemonDeviceControlRecord;
    SetupNewDcrDevice(jcr, dcr, device_resource->dev, blocksizes);
    dcr->SetWillWrite();
    dcr->device_resource = device_resource;
  }
  return dcr;
}

// Mount command from Director
static bool MountCmd(JobControlRecord* jcr)
{
  PoolMem devname;
  BareosSocket* dir = jcr->dir_bsock;
  Device* dev;
  DeviceControlRecord* dcr;
  slot_number_t slot = 0;

  short int drive_input = -1;
  bool ok = sscanf(dir->msg, mountslotcmd, devname.c_str(), &drive_input, &slot)
            == 3;

  if (!ok) {
    ok = sscanf(dir->msg, mountcmd, devname.c_str(), &drive_input) == 2;
  }

  Dmsg3(100, "ok=%d drive=%hd slot=%hd\n", ok, drive_input, slot);
  if (ok) {
    drive_number_t drive = IntToDriveNumber(drive_input);
    dcr = FindDevice(jcr, devname, drive, NULL);
    if (dcr) {
      dev = dcr->dev;
      dev->Lock(); /* Use P to avoid indefinite block */
      Dmsg2(100, "mount cmd blocked=%d MustUnload=%d\n", dev->blocked(),
            dev->MustUnload());
      switch (dev->blocked()) { /* device blocked? */
        case BST_WAITING_FOR_SYSOP:
          /* Someone is waiting, wake him */
          Dmsg0(100, "Waiting for mount. Attempting to wake thread\n");
          dev->SetBlocked(BST_MOUNT);
          dir->fsend("3001 OK mount requested. %sDevice=%s\n",
                     (slot > 0) ? _("Specified slot ignored. ") : "",
                     dev->print_name());
          pthread_cond_broadcast(&dev->wait_next_vol);
          Dmsg1(100, "JobId=%u broadcast wait_device_release\n",
                (uint32_t)dcr->jcr->JobId);
          ReleaseDeviceCond();
          break;

        /* In both of these two cases, we (the user) unmounted the Volume */
        case BST_UNMOUNTED_WAITING_FOR_SYSOP:
        case BST_UNMOUNTED:
          Dmsg2(100, "Unmounted changer=%d slot=%hd\n",
                dev->AttachedToAutochanger(), slot);
          if (dev->AttachedToAutochanger() && slot > 0) {
            TryAutoloadDevice(jcr, dcr, slot, "");
          }
          /* We freed the device, so reopen it and wake any waiting threads */
          if (!dev->open(dcr, DeviceMode::OPEN_READ_ONLY)) {
            dir->fsend(_("3901 Unable to open device %s: ERR=%s\n"),
                       dev->print_name(), dev->bstrerror());
            if (dev->blocked() == BST_UNMOUNTED) {
              /* We blocked the device, so unblock it */
              Dmsg0(100, "Unmounted. Unblocking device\n");
              UnblockDevice(dev);
            }
            break;
          }
          ReadDevVolumeLabel(dcr);
          if (dev->blocked() == BST_UNMOUNTED) {
            /* We blocked the device, so unblock it */
            Dmsg0(100, "Unmounted. Unblocking device\n");
            ReadLabel(dcr); /* this should not be necessary */
            UnblockDevice(dev);
          } else {
            Dmsg0(100,
                  "Unmounted waiting for mount. Attempting to wake thread\n");
            dev->SetBlocked(BST_MOUNT);
          }
          if (dev->IsLabeled()) {
            dir->fsend(_("3001 Device %s is mounted with Volume \"%s\"\n"),
                       dev->print_name(), dev->VolHdr.VolumeName);
          } else {
            dir->fsend(
                _("3905 Device %s open but no Bareos volume is mounted.\n"
                  "If this is not a blank tape, try unmounting and remounting "
                  "the Volume.\n"),
                dev->print_name());
          }
          pthread_cond_broadcast(&dev->wait_next_vol);
          Dmsg1(100, "JobId=%u broadcast wait_device_release\n",
                (uint32_t)dcr->jcr->JobId);
          ReleaseDeviceCond();
          break;

        case BST_DOING_ACQUIRE:
          dir->fsend(_("3001 Device %s is doing acquire.\n"),
                     dev->print_name());
          break;

        case BST_WRITING_LABEL:
          dir->fsend(_("3903 Device %s is being labeled.\n"),
                     dev->print_name());
          break;

        case BST_NOT_BLOCKED:
          Dmsg2(100, "Not blocked changer=%d slot=%hd\n",
                dev->AttachedToAutochanger(), slot);
          if (dev->AttachedToAutochanger() && slot > 0) {
            TryAutoloadDevice(jcr, dcr, slot, "");
          }
          if (dev->IsOpen()) {
            if (dev->IsLabeled()) {
              dir->fsend(_("3001 Device %s is mounted with Volume \"%s\"\n"),
                         dev->print_name(), dev->VolHdr.VolumeName);
            } else {
              dir->fsend(
                  _("3905 Device %s open but no Bareos volume is mounted.\n"
                    "If this is not a blank tape, try unmounting and "
                    "remounting the Volume.\n"),
                  dev->print_name());
            }
          } else if (dev->IsTape()) {
            if (!dev->open(dcr, DeviceMode::OPEN_READ_ONLY)) {
              dir->fsend(_("3901 Unable to open device %s: ERR=%s\n"),
                         dev->print_name(), dev->bstrerror());
              break;
            }
            ReadLabel(dcr);
            if (dev->IsLabeled()) {
              dir->fsend(
                  _("3001 Device %s is already mounted with Volume \"%s\"\n"),
                  dev->print_name(), dev->VolHdr.VolumeName);
            } else {
              dir->fsend(
                  _("3905 Device %s open but no Bareos volume is mounted.\n"
                    "If this is not a blank tape, try unmounting and "
                    "remounting the Volume.\n"),
                  dev->print_name());
            }
            if (dev->IsOpen() && !dev->HasCap(CAP_ALWAYSOPEN)) {
              dev->close(dcr);
            }
          } else if (dev->IsUnmountable()) {
            if (dev->mount(dcr, 1)) {
              dir->fsend(_("3002 Device %s is mounted.\n"), dev->print_name());
            } else {
              dir->fsend(_("3907 %s"), dev->bstrerror());
            }
          } else { /* must be file */
            dir->fsend(_("3906 File device %s is always mounted.\n"),
                       dev->print_name());
            pthread_cond_broadcast(&dev->wait_next_vol);
            Dmsg1(100, "JobId=%u broadcast wait_device_release\n",
                  (uint32_t)dcr->jcr->JobId);
            ReleaseDeviceCond();
          }
          break;

        case BST_RELEASING:
          dir->fsend(_("3930 Device %s is being released.\n"),
                     dev->print_name());
          break;

        default:
          dir->fsend(_("3905 Unknown wait state %d\n"), dev->blocked());
          break;
      }
      dev->Unlock();
      FreeDeviceControlRecord(dcr);
    } else {
      dir->fsend(_("3999 Device %s not found or could not be opened.\n"),
                 devname.c_str());
    }
  } else {
    PmStrcpy(jcr->errmsg, dir->msg);
    dir->fsend(_("3909 Error scanning mount command: %s\n"), jcr->errmsg);
  }
  dir->signal(BNET_EOD);
  return true;
}

// unmount command from Director
static bool UnmountCmd(JobControlRecord* jcr)
{
  PoolMem devname;
  BareosSocket* dir = jcr->dir_bsock;
  Device* dev;
  DeviceControlRecord* dcr;

  short int drive_input = -1;
  if (sscanf(dir->msg, unmountcmd, devname.c_str(), &drive_input) == 2) {
    drive_number_t drive = IntToDriveNumber(drive_input);
    dcr = FindDevice(jcr, devname, drive, NULL);
    if (dcr) {
      dev = dcr->dev;
      dev->Lock(); /* Use P to avoid indefinite block */
      if (!dev->IsOpen()) {
        if (!dev->IsBusy()) { UnloadAutochanger(dcr, kInvalidSlotNumber); }
        if (dev->IsUnmountable()) {
          if (dev->unmount(dcr, 0)) {
            dir->fsend(_("3002 Device \"%s\" unmounted.\n"), dev->print_name());
          } else {
            dir->fsend(_("3907 %s"), dev->bstrerror());
          }
        } else {
          Dmsg0(90, "Device already unmounted\n");
          dir->fsend(_("3901 Device \"%s\" is already unmounted.\n"),
                     dev->print_name());
        }
      } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
        Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
              dev->blocked());
        if (!UnloadAutochanger(dcr, kInvalidSlotNumber)) {
          /* ***FIXME**** what is this ????  */
          dev->close(dcr);
          FreeVolume(dev);
        }
        if (dev->IsUnmountable() && !dev->unmount(dcr, 0)) {
          dir->fsend(_("3907 %s"), dev->bstrerror());
        } else {
          dev->SetBlocked(BST_UNMOUNTED_WAITING_FOR_SYSOP);
          dir->fsend(_("3001 Device \"%s\" unmounted.\n"), dev->print_name());
        }

      } else if (dev->blocked() == BST_DOING_ACQUIRE) {
        dir->fsend(_("3902 Device \"%s\" is busy in acquire.\n"),
                   dev->print_name());

      } else if (dev->blocked() == BST_WRITING_LABEL) {
        dir->fsend(_("3903 Device \"%s\" is being labeled.\n"),
                   dev->print_name());

      } else if (dev->IsBusy()) {
        SendDirBusyMessage(dir, dev);
      } else { /* device not being used */
        Dmsg0(90, "Device not in use, unmounting\n");
        /* On FreeBSD, I am having ASSERT() failures in BlockDevice()
         * and I can only imagine that the thread id that we are
         * leaving in no_wait_id is being re-used. So here,
         * we simply do it by hand.  Gross, but a solution.
         */
        /*  BlockDevice(dev, BST_UNMOUNTED); replace with 2 lines below */
        dev->SetBlocked(BST_UNMOUNTED);
        ClearThreadId(dev->no_wait_id);
        if (!UnloadAutochanger(dcr, kInvalidSlotNumber)) {
          dev->close(dcr);
          FreeVolume(dev);
        }
        if (dev->IsUnmountable() && !dev->unmount(dcr, 0)) {
          dir->fsend(_("3907 %s"), dev->bstrerror());
        } else {
          dir->fsend(_("3002 Device \"%s\" unmounted.\n"), dev->print_name());
        }
      }
      dev->Unlock();
      FreeDeviceControlRecord(dcr);
    } else {
      dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"),
                 devname.c_str());
    }
  } else {
    /* NB dir->msg gets clobbered in BnetFsend, so save command */
    PmStrcpy(jcr->errmsg, dir->msg);
    dir->fsend(_("3907 Error scanning unmount command: %s\n"), jcr->errmsg);
  }
  dir->signal(BNET_EOD);
  return true;
}

/**
 * Release command from Director. This rewinds the device and if
 *   configured does a offline and ensures that Bareos will
 *   re-read the label of the tape before continuing. This gives
 *   the operator the chance to change the tape anytime before the
 *   next job starts.
 */
static bool ReleaseCmd(JobControlRecord* jcr)
{
  PoolMem devname;
  BareosSocket* dir = jcr->dir_bsock;
  Device* dev;
  DeviceControlRecord* dcr;
  short int drive_input = -1;

  if (sscanf(dir->msg, releasecmd, devname.c_str(), &drive_input) == 2) {
    drive_number_t drive = IntToDriveNumber(drive_input);
    dcr = FindDevice(jcr, devname, drive, NULL);
    if (dcr) {
      dev = dcr->dev;
      dev->Lock(); /* Use P to avoid indefinite block */
      if (!dev->IsOpen()) {
        if (!dev->IsBusy()) { UnloadAutochanger(dcr, kInvalidSlotNumber); }
        Dmsg0(90, "Device already released\n");
        dir->fsend(_("3921 Device \"%s\" already released.\n"),
                   dev->print_name());

      } else if (dev->blocked() == BST_WAITING_FOR_SYSOP) {
        Dmsg2(90, "%d waiter dev_block=%d.\n", dev->num_waiting,
              dev->blocked());
        UnloadAutochanger(dcr, kInvalidSlotNumber);
        dir->fsend(_("3922 Device \"%s\" waiting for sysop.\n"),
                   dev->print_name());

      } else if (dev->blocked() == BST_UNMOUNTED_WAITING_FOR_SYSOP) {
        Dmsg2(90, "%d waiter dev_block=%d. doing unmount\n", dev->num_waiting,
              dev->blocked());
        dir->fsend(_("3922 Device \"%s\" waiting for mount.\n"),
                   dev->print_name());

      } else if (dev->blocked() == BST_DOING_ACQUIRE) {
        dir->fsend(_("3923 Device \"%s\" is busy in acquire.\n"),
                   dev->print_name());

      } else if (dev->blocked() == BST_WRITING_LABEL) {
        dir->fsend(_("3914 Device \"%s\" is being labeled.\n"),
                   dev->print_name());

      } else if (dev->IsBusy()) {
        SendDirBusyMessage(dir, dev);
      } else { /* device not being used */
        Dmsg0(90, "Device not in use, releasing\n");
        dcr->ReleaseVolume();
        dir->fsend(_("3022 Device \"%s\" released.\n"), dev->print_name());
      }
      dev->Unlock();
      FreeDeviceControlRecord(dcr);
    } else {
      dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"),
                 devname.c_str());
    }
  } else {
    /* NB dir->msg gets clobbered in BnetFsend, so save command */
    PmStrcpy(jcr->errmsg, dir->msg);
    dir->fsend(_("3927 Error scanning release command: %s\n"), jcr->errmsg);
  }
  dir->signal(BNET_EOD);
  return true;
}

static pthread_mutex_t bsr_mutex = PTHREAD_MUTEX_INITIALIZER;
static uint32_t bsr_uniq = 0;

static inline bool GetBootstrapFile(JobControlRecord* jcr, BareosSocket* sock)
{
  POOLMEM* fname = GetPoolMemory(PM_FNAME);
  FILE* bs;
  bool ok = false;

  if (jcr->RestoreBootstrap) {
    SecureErase(jcr, jcr->RestoreBootstrap);
    FreePoolMemory(jcr->RestoreBootstrap);
  }
  lock_mutex(bsr_mutex);
  bsr_uniq++;
  Mmsg(fname, "%s/%s.%s.%d.bootstrap", me->working_directory,
       me->resource_name_, jcr->Job, bsr_uniq);
  unlock_mutex(bsr_mutex);
  Dmsg1(400, "bootstrap=%s\n", fname);
  jcr->RestoreBootstrap = fname;
  bs = fopen(fname, "a+b"); /* create file */
  if (!bs) {
    BErrNo be;
    Jmsg(jcr, M_FATAL, 0, _("Could not create bootstrap file %s: ERR=%s\n"),
         jcr->RestoreBootstrap, be.bstrerror());
    goto bail_out;
  }
  Dmsg0(10, "=== Bootstrap file ===\n");
  while (sock->recv() >= 0) {
    Dmsg1(10, "%s", sock->msg);
    fputs(sock->msg, bs);
  }
  fclose(bs);
  Dmsg0(10, "=== end bootstrap file ===\n");
  jcr->sd_impl->read_session.bsr
      = libbareos::parse_bsr(jcr, jcr->RestoreBootstrap);
  if (!jcr->sd_impl->read_session.bsr) {
    Jmsg(jcr, M_FATAL, 0, _("Error parsing bootstrap file.\n"));
    goto bail_out;
  }
  if (debug_level >= 10) {
    libbareos::DumpBsr(jcr->sd_impl->read_session.bsr, true);
  }
  /* If we got a bootstrap, we are reading, so create read volume list */
  CreateRestoreVolumeList(jcr);
  ok = true;

bail_out:
  SecureErase(jcr, jcr->RestoreBootstrap);
  FreePoolMemory(jcr->RestoreBootstrap);
  jcr->RestoreBootstrap = NULL;
  if (!ok) {
    sock->fsend(ERROR_bootstrap);
    return false;
  }
  return sock->fsend(OK_bootstrap);
}

static bool BootstrapCmd(JobControlRecord* jcr)
{
  return GetBootstrapFile(jcr, jcr->dir_bsock);
}

// Autochanger command from Director
static bool ChangerCmd(JobControlRecord* jcr)
{
  slot_number_t src_slot, dst_slot;
  PoolMem devname;
  BareosSocket* dir = jcr->dir_bsock;
  Device* dev;
  DeviceControlRecord* dcr;
  const char* cmd = NULL;
  bool ok = false;
  bool is_transfer = false;
  /*
   * A safe_cmd may call autochanger script but does not load/unload
   *    slots so it can be done at the same time that the drive is open.
   */
  bool safe_cmd = false;

  if (sscanf(dir->msg, "autochanger listall %127s", devname.c_str()) == 1) {
    cmd = "listall";
    safe_cmd = ok = true;
  } else if (sscanf(dir->msg, "autochanger list %127s", devname.c_str()) == 1) {
    cmd = "list";
    safe_cmd = ok = true;
  } else if (sscanf(dir->msg, "autochanger slots %127s", devname.c_str())
             == 1) {
    cmd = "slots";
    safe_cmd = ok = true;
  } else if (sscanf(dir->msg, "autochanger drives %127s", devname.c_str())
             == 1) {
    cmd = "drives";
    safe_cmd = ok = true;
  } else if (sscanf(dir->msg, "autochanger transfer %127s %hd %hd",
                    devname.c_str(), &src_slot, &dst_slot)
             == 3) {
    cmd = "transfer";
    safe_cmd = ok = true;
    is_transfer = true;
  }
  if (ok) {
    dcr = FindDevice(jcr, devname, kInvalidDriveNumber, NULL);
    if (dcr) {
      dev = dcr->dev;
      dev->Lock(); /* Use P to avoid indefinite block */
      if (!dev->device_resource->changer_res) {
        dir->fsend(_("3998 Device \"%s\" is not an autochanger.\n"),
                   dev->print_name());
        /* Under certain "safe" conditions, we can steal the lock */
      } else if (safe_cmd || !dev->IsOpen() || dev->CanStealLock()) {
        if (is_transfer) {
          AutochangerTransferCmd(dcr, dir, src_slot, dst_slot);
        } else {
          AutochangerCmd(dcr, dir, cmd);
        }
      } else if (dev->IsBusy() || dev->IsBlocked()) {
        SendDirBusyMessage(dir, dev);
      } else { /* device not being used */
        if (is_transfer) {
          AutochangerTransferCmd(dcr, dir, src_slot, dst_slot);
        } else {
          AutochangerCmd(dcr, dir, cmd);
        }
      }
      dev->Unlock();
      FreeDeviceControlRecord(dcr);
    } else {
      dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"),
                 devname.c_str());
    }
  } else { /* error on scanf */
    PmStrcpy(jcr->errmsg, dir->msg);
    dir->fsend(
        _("3908 Error scanning autochanger drives/list/slots command: %s\n"),
        jcr->errmsg);
  }
  dir->signal(BNET_EOD);
  return true;
}

// Read and return the Volume label
static bool ReadlabelCmd(JobControlRecord* jcr)
{
  PoolMem devname;
  BareosSocket* dir = jcr->dir_bsock;
  Device* dev;
  DeviceControlRecord* dcr;
  slot_number_t slot;
  short int drive_input = -1;

  if (sscanf(dir->msg, readlabelcmd, devname.c_str(), &slot, &drive_input)
      == 3) {
    drive_number_t drive = IntToDriveNumber(drive_input);
    dcr = FindDevice(jcr, devname, drive, NULL);
    if (dcr) {
      dev = dcr->dev;
      dev->Lock(); /* Use P to avoid indefinite block */
      if (!dev->IsOpen()) {
        ReadVolumeLabel(jcr, dcr, dev, slot);
        dev->close(dcr);
        /* Under certain "safe" conditions, we can steal the lock */
      } else if (dev->CanStealLock()) {
        ReadVolumeLabel(jcr, dcr, dev, slot);
      } else if (dev->IsBusy() || dev->IsBlocked()) {
        SendDirBusyMessage(dir, dev);
      } else { /* device not being used */
        ReadVolumeLabel(jcr, dcr, dev, slot);
      }
      dev->Unlock();
      FreeDeviceControlRecord(dcr);
    } else {
      dir->fsend(_("3999 Device \"%s\" not found or could not be opened.\n"),
                 devname.c_str());
    }
  } else {
    PmStrcpy(jcr->errmsg, dir->msg);
    dir->fsend(_("3909 Error scanning readlabel command: %s\n"), jcr->errmsg);
  }
  dir->signal(BNET_EOD);
  return true;
}

/**
 * Read the tape label
 *
 *  Enter with the mutex set
 */
static void ReadVolumeLabel(JobControlRecord* jcr,
                            DeviceControlRecord* dcr,
                            Device* dev,
                            slot_number_t Slot)
{
  BareosSocket* dir = jcr->dir_bsock;
  bsteal_lock_t hold;

  dcr->SetDev(dev);
  StealDeviceLock(dev, &hold, BST_WRITING_LABEL);

  switch (TryAutoloadDevice(dcr->jcr, dcr, Slot, "")) {
    case -1:
    case -2:
      goto bail_out;
    case 0:
    default:
      break;
  }

  dev->ClearLabeled(); /* force read of label */
  switch (ReadDevVolumeLabel(dcr)) {
    case VOL_OK:
      /* DO NOT add quotes around the Volume name. It is scanned in the DIR */
      dir->fsend(_("3001 Volume=%s Slot=%hd\n"), dev->VolHdr.VolumeName, Slot);
      Dmsg1(100, "Volume: %s\n", dev->VolHdr.VolumeName);
      break;
    default:
      dir->fsend(
          _("3902 Cannot mount Volume on Storage Device \"%s\" because:\n%s"),
          dev->print_name(), jcr->errmsg);
      break;
  }

bail_out:
  GiveBackDeviceLock(dev, &hold);

  return;
}

/**
 * Try autoloading a device.
 *
 * Returns: 1 on success
 *          0 on failure (no changer available)
 *         -1 on error on autochanger
 *         -2 on error locking the autochanger
 */
static int TryAutoloadDevice(JobControlRecord* jcr,
                             DeviceControlRecord* dcr,
                             slot_number_t Slot,
                             const char* VolName)
{
  BareosSocket* dir = jcr->dir_bsock;

  bstrncpy(dcr->VolumeName, VolName, sizeof(dcr->VolumeName));
  dcr->VolCatInfo.Slot = Slot;
  dcr->VolCatInfo.InChanger = Slot > 0;

  return AutoloadDevice(dcr, 0, dir);
}

static void SendDirBusyMessage(BareosSocket* dir, Device* dev)
{
  if (dev->IsBlocked()) {
    switch (dev->blocked()) {
      case BST_UNMOUNTED:
        dir->fsend(_("3931 Device \"%s\" is BLOCKED. user unmounted.\n"),
                   dev->print_name());
        break;
      case BST_UNMOUNTED_WAITING_FOR_SYSOP:
        dir->fsend(_("3932 Device \"%s\" is BLOCKED. user unmounted during "
                     "wait for media/mount.\n"),
                   dev->print_name());
        break;
      case BST_WAITING_FOR_SYSOP:
        dir->fsend(_("3933 Device \"%s\" is BLOCKED waiting for media.\n"),
                   dev->print_name());
        break;
      case BST_DOING_ACQUIRE:
        dir->fsend(_("3934 Device \"%s\" is being initialized.\n"),
                   dev->print_name());
        break;
      case BST_WRITING_LABEL:
        dir->fsend(_("3935 Device \"%s\" is blocked labeling a Volume.\n"),
                   dev->print_name());
        break;
      default:
        dir->fsend(_("3935 Device \"%s\" is blocked for unknown reason.\n"),
                   dev->print_name());
        break;
    }
  } else if (dev->CanRead()) {
    dir->fsend(_("3936 Device \"%s\" is busy reading.\n"), dev->print_name());
  } else {
    dir->fsend(_("3937 Device \"%s\" is busy with writers=%d reserved=%d.\n"),
               dev->print_name(), dev->num_writers, dev->NumReserved());
  }
}

static void SetStorageAuthKeyAndTlsPolicy(JobControlRecord* jcr,
                                          char* key,
                                          TlsPolicy policy)
{
  if (!*key) { return; }

  if (jcr->sd_auth_key) { free(jcr->sd_auth_key); }

  jcr->sd_auth_key = strdup(key);
  Dmsg0(5, "set sd auth key\n");

  jcr->sd_tls_policy = policy;
  Dmsg1(5, "set sd ssl_policy to %d\n", policy);
}

// Listen for incoming replication session from other SD.
static bool ListenCmd(JobControlRecord* jcr) { return DoListenRun(jcr); }

enum class ReplicateCmdState
{
  kInit,
  kConnected,
  kTlsEstablished,
  kAuthenticated,
  kError
};

class ReplicateCmdConnectState {
  JobControlRecord* jcr_;
  ReplicateCmdState state_;

 public:
  ReplicateCmdConnectState(JobControlRecord* jcr)
      : jcr_(jcr), state_(ReplicateCmdState::kInit)
  {
  }

  ~ReplicateCmdConnectState()
  {
    if (state_ == ReplicateCmdState::kInit
        || state_ == ReplicateCmdState::kError) {
      if (!jcr_) { return; }
      if (jcr_->dir_bsock) {
        jcr_->dir_bsock->fsend(BADcmd, "replicate", jcr_->dir_bsock->msg);
      }
      jcr_->store_bsock = nullptr;
    }
  }
  void operator()(ReplicateCmdState state) { state_ = state; }
};

static bool ReplicateCmd(JobControlRecord* jcr)
{
  int stored_port;      /* storage daemon port */
  TlsPolicy tls_policy; /* enable ssl to sd */
  char JobName[MAX_NAME_LENGTH];
  char stored_addr[MAX_NAME_LENGTH];
  uint32_t JobId = 0;
  PoolMem sd_auth_key(PM_MESSAGE);
  BareosSocket* dir = jcr->dir_bsock;
  std::unique_ptr<BareosSocket> storage_daemon_socket
      = std::make_unique<BareosSocketTCP>();

  Dmsg1(100, "ReplicateCmd: %s", dir->msg);
  sd_auth_key.check_size(dir->message_length);

  if (sscanf(dir->msg, replicatecmd, &JobId, JobName, stored_addr, &stored_port,
             &tls_policy, sd_auth_key.c_str())
      != 6) {
    dir->fsend(BADcmd, "replicate", dir->msg);
    return false;
  }

  SetStorageAuthKeyAndTlsPolicy(jcr, sd_auth_key.c_str(), tls_policy);

  Dmsg3(110, "Open storage: %s:%d ssl=%d\n", stored_addr, stored_port,
        tls_policy);

  storage_daemon_socket->SetSourceAddress(me->SDsrc_addr);

  if (!jcr->max_bandwidth) {
    if (jcr->sd_impl->director->max_bandwidth_per_job) {
      jcr->max_bandwidth = jcr->sd_impl->director->max_bandwidth_per_job;
    } else if (me->max_bandwidth_per_job) {
      jcr->max_bandwidth = me->max_bandwidth_per_job;
    }
  }

  storage_daemon_socket->SetBwlimit(jcr->max_bandwidth);
  if (me->allow_bw_bursting) { storage_daemon_socket->SetBwlimitBursting(); }

  ReplicateCmdConnectState connect_state(jcr);

  if (!storage_daemon_socket->connect(
          jcr, 10, (int)me->SDConnectTimeout, me->heartbeat_interval,
          _("Storage daemon"), stored_addr, NULL, stored_port, 1)) {
    Jmsg(jcr, M_FATAL, 0, _("Failed to connect to Storage daemon: %s:%d\n"),
         stored_addr, stored_port);
    Dmsg2(100, "Failed to connect to Storage daemon: %s:%d\n", stored_addr,
          stored_port);
    connect_state(ReplicateCmdState::kError);
    return false;
  }
  Dmsg0(110, "Connection OK to SD.\n");
  connect_state(ReplicateCmdState::kConnected);

  if (tls_policy == TlsPolicy::kBnetTlsAuto) {
    std::string qualified_resource_name;
    if (!my_config->GetQualifiedResourceNameTypeConverter()->ResourceToString(
            JobName, R_JOB, qualified_resource_name)) {
      connect_state(ReplicateCmdState::kError);
      return false;
    } else if (!storage_daemon_socket->DoTlsHandshake(
                   TlsPolicy::kBnetTlsAuto, me, false,
                   qualified_resource_name.c_str(), jcr->sd_auth_key, jcr)) {
      Dmsg0(110, "TLS direct handshake failed\n");
      connect_state(ReplicateCmdState::kError);
      return false;
    } else {
      connect_state(ReplicateCmdState::kTlsEstablished);
    }
  }

  jcr->store_bsock = storage_daemon_socket.get();

  storage_daemon_socket->InitBnetDump(
      my_config->CreateOwnQualifiedNameForNetworkDump());
  storage_daemon_socket->fsend("Hello Start Storage Job %s\n", JobName);

  if (!AuthenticateWithStoragedaemon(jcr)) {
    Jmsg(jcr, M_FATAL, 0, _("Failed to authenticate Storage daemon.\n"));
    connect_state(ReplicateCmdState::kError);
    return false;
  } else {
    connect_state(ReplicateCmdState::kAuthenticated);
    Dmsg0(110, "Authenticated with SD.\n");

    jcr->sd_impl->remote_replicate = true;

    storage_daemon_socket.release(); /* jcr->store_bsock */
    return dir->fsend(OK_replicate);
  }
}

static bool RunCmd(JobControlRecord* jcr)
{
  Dmsg1(200, "Run_cmd: %s\n", jcr->dir_bsock->msg);

  // If we do not need the FD, we are doing a migrate, copy, or virtual
  // backup.
  if (jcr->NoClientUsed()) {
    return DoMacRun(jcr);
  } else {
    return DoJobRun(jcr);
  }
}

static bool PassiveCmd(JobControlRecord* jcr)
{
  int filed_port;       /* file daemon port */
  TlsPolicy tls_policy; /* enable ssl to fd */
  char filed_addr[MAX_NAME_LENGTH];
  BareosSocket* dir = jcr->dir_bsock;
  BareosSocket* fd; /* file daemon bsock */

  Dmsg1(100, "PassiveClientCmd: %s", dir->msg);
  if (sscanf(dir->msg, passiveclientcmd, filed_addr, &filed_port, &tls_policy)
      != 3) {
    PmStrcpy(jcr->errmsg, dir->msg);
    Jmsg(jcr, M_FATAL, 0, _("Bad passiveclientcmd command: %s"), jcr->errmsg);
    goto bail_out;
  }

  Dmsg3(110, "PassiveClientCmd: %s:%d ssl=%d\n", filed_addr, filed_port,
        tls_policy);

  jcr->passive_client = true;

  fd = new BareosSocketTCP;
  fd->SetSourceAddress(me->SDsrc_addr);

  // Open command communications with passive filedaemon
  if (!fd->connect(jcr, 10, (int)me->FDConnectTimeout, me->heartbeat_interval,
                   _("File Daemon"), filed_addr, NULL, filed_port, 1)) {
    delete fd;
    fd = NULL;
  }

  if (fd == NULL) {
    Jmsg(jcr, M_FATAL, 0, _("Failed to connect to File daemon: %s:%d\n"),
         filed_addr, filed_port);
    Dmsg2(100, "Failed to connect to File daemon: %s:%d\n", filed_addr,
          filed_port);
    goto bail_out;
  }
  Dmsg0(110, "Connection OK to FD.\n");

  if (tls_policy == TlsPolicy::kBnetTlsAuto) {
    std::string qualified_resource_name;
    if (!my_config->GetQualifiedResourceNameTypeConverter()->ResourceToString(
            jcr->Job, R_JOB, qualified_resource_name)) {
      goto bail_out;
    }

    if (!fd->DoTlsHandshake(TlsPolicy::kBnetTlsAuto, me, false,
                            qualified_resource_name.c_str(), jcr->sd_auth_key,
                            jcr)) {
      goto bail_out;
    }
  }

  jcr->file_bsock = fd;
  fd->InitBnetDump(my_config->CreateOwnQualifiedNameForNetworkDump());
  fd->fsend("Hello Storage calling Start Job %s\n", jcr->Job);
  if (!AuthenticateWithFiledaemon(jcr)) {
    Jmsg(jcr, M_FATAL, 0, _("Failed to authenticate File daemon.\n"));
    delete fd;
    jcr->file_bsock = NULL;
    goto bail_out;
  } else {
    utime_t now;

    Dmsg0(110, "Authenticated with FD.\n");

    // Update the initial Job Statistics.
    now = (utime_t)time(NULL);
    UpdateJobStatistics(jcr, now);
  }

  // Send OK to Director
  return dir->fsend(OKpassive);

bail_out:
  dir->fsend(BADcmd, "passive client");
  return false;
}

static bool PluginoptionsCmd(JobControlRecord* jcr)
{
  BareosSocket* dir = jcr->dir_bsock;
  char plugin_options[2048];

  Dmsg1(100, "PluginOptionsCmd: %s", dir->msg);
  if (sscanf(dir->msg, pluginoptionscmd, plugin_options) != 1) {
    PmStrcpy(jcr->errmsg, dir->msg);
    Jmsg(jcr, M_FATAL, 0, _("Bad pluginoptionscmd command: %s"), jcr->errmsg);
    goto bail_out;
  }

  UnbashSpaces(plugin_options);
  if (!jcr->sd_impl->plugin_options) {
    jcr->sd_impl->plugin_options = new alist<const char*>(10, owned_by_alist);
  }
  jcr->sd_impl->plugin_options->append(strdup(plugin_options));

  // Send OK to Director
  return dir->fsend(OKpluginoptions);

bail_out:
  dir->fsend(BADcmd, "plugin options");
  return false;
}

} /* namespace storagedaemon */