File: BackupPC

package info (click to toggle)
backuppc 4.4.0-11
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,752 kB
  • sloc: perl: 37,523; sh: 607; javascript: 176; makefile: 38; ansic: 6
file content (2157 lines) | stat: -rwxr-xr-x 89,029 bytes parent folder | download | duplicates (3)
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
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
#!/usr/bin/perl
#============================================================= -*-perl-*-
#
# BackupPC: Main program for PC backups.
#
# DESCRIPTION
#
#   BackupPC reads the configuration and status information from
#   $ConfDir/conf.  It then runs and manages all the backup activity.
#
#   As specified by $Conf{WakeupSchedule}, BackupPC wakes up periodically
#   to queue backups on all the PCs.  This is a three step process:
#     1) For each host and DHCP address backup requests are queued on the
#        background command queue.
#     2) For each PC, BackupPC_dump is forked.  Several of these may
#        be run in parallel, based on the configuration.
#     3) Once each night, BackupPC_nightly is run to complete some
#        additional administrative tasks (updating reference counts,
#        cleaning etc).
#
#   BackupPC also listens for connections on a unix domain socket and
#   the tcp port $Conf{ServerPort}, which are used by various
#   sub-programs and the CGI script BackupPC_Admin for status reporting
#   and user-initiated backup or backup cancel requests.
#
# AUTHOR
#   Craig Barratt  <cbarratt@users.sourceforge.net>
#
# COPYRIGHT
#   Copyright (C) 2001-2020  Craig Barratt
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   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 General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#========================================================================
#
# Version 4.4.0, released 20 Jun 2020.
#
# See http://backuppc.sourceforge.net.
#
#========================================================================

use strict;
no utf8;

use vars qw($Hosts);
use lib "__INSTALLDIR__/lib";
use BackupPC::Lib;
use BackupPC::XS;
use Encode qw/decode_utf8/;

use File::Path;
use Data::Dumper;
use Getopt::Std;
use Socket;
use Carp;
use version;
use Digest::MD5;
use POSIX qw(setsid);

###########################################################################
# Handle command line options
###########################################################################
my %opts;
if ( !getopts("d", \%opts) || @ARGV != 0 ) {
    print(STDERR "usage: $0 [-d]\n");
    exit(1);
}

###########################################################################
# Initialize major data structures and variables
###########################################################################

#
# Get an instance of BackupPC::Lib and get some shortcuts.
#
die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );

my $TopDir = $bpc->TopDir();
my $BinDir = $bpc->BinDir();
my $LogDir = $bpc->LogDir();
my $RunDir = $bpc->RunDir();
my %Conf   = $bpc->Conf();

#
# Verify we are running as the correct user
#
if ( $Conf{BackupPCUserVerify} && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
    print(STDERR "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser}); exiting in 30s\n");
    sleep(30);
    exit(1);
}

###########################################################################
# Ensure we don't have old versions of key libraries and executables
###########################################################################
my $PackageVersion = {
    'BackupPC::XS' => '0.62',
    rsync_bpc      => '3.0.9.15',
};

if ( $BackupPC::XS::VERSION < $PackageVersion->{'BackupPC::XS'} ) {
    print(STDERR "BackupPC: old version $BackupPC::XS::VERSION of BackupPC::XS: need >= $PackageVersion->{'BackupPC::XS'}; exiting in 30s\n");
    sleep(30);
    exit(1);
}
if ( $Conf{RsyncBackupPCPath} ne "" && -x $Conf{RsyncBackupPCPath} ) {
    my $output = $bpc->cmdSystemOrEval([$Conf{RsyncBackupPCPath}, "--version"]);
    if ( $? ) {
        print(STDERR
              "BackupPC: can't run $Conf{RsyncBackupPCPath} for rsync_bpc version check; ($output) exiting in 30s\n");
        sleep(30);
        exit(1);
    }
    my $version = "unknown";
    $version = $1 if ( $output =~ /rsync_bpc\s+version\s+([\d.]+?)(\.?beta\d+)?\s+protocol/ );
    if ( $version eq "unknown" || version->parse($version) < version->parse($PackageVersion->{rsync_bpc}) ) {
        print(STDERR
              "BackupPC: rsync_bpc at $Conf{RsyncBackupPCPath} needs to be upgraded (got version $version; need >= $PackageVersion->{rsync_bpc}); exiting in 30s\n"
        );
        sleep(30);
        exit(1);
    }
}

#
# $Status maintain status information about each host.
# It is a hashref of hashes, whose first index is the host.
#
# $Info is a hashref giving general information about BackupPC status.
#
# Read old status
#
my($Status, $Info) = $bpc->{storage}->StatusDataRead();
if ( !defined($Info) && ref($Status) ne "HASH" ) {
    print STDERR "$0: status.pl read failed: $Status\n";
    $Info   = {};
    $Status = {};
}

#
# %Jobs maintains information about currently running jobs.
# It is a hash of hashes, whose first index is the host.
#
my %Jobs = ();

#
# There are three command queues:
#   - @UserQueue is a queue of user initiated backup requests.
#   - @BgQueue is a queue of automatically scheduled backup requests.
#   - @CmdQueue is a queue of administrative jobs, including tasks
#     like BackupPC_nightly
# Each queue is an array of hashes.  Each hash stores information
# about the command request.
#
my @UserQueue = ();
my @CmdQueue  = ();
my @BgQueue   = ();

#
# To quickly lookup if a given host is on a given queue, we keep
# a hash of flags for each queue type.
#
my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);

#
# BackupPC_tarCreate and BackupPC_zipCreate shouldn't run when a backup
# is active.  We maintain a per-host mutex.  A -1 value means a
# backup or delete job is running (ie: a writer).  A positive value
# is the number of readers, ie: restore, archive, BackupPC_tarCreate,
# BackupPC_zipCreate processes running.  Zero means that host is idle.
#
my(%HostMutex, %HostMutexCurrJob);

#
# One or more clients can connect to the server to get status information
# or request/cancel backups etc.  The %Clients hash maintains information
# about each of these socket connections.  The hash key is an incrementing
# number stored in $ClientConnCnt.  Each entry is a hash that contains
# various information about the client connection.
#
my %Clients       = ();
my $ClientConnCnt = 0;

#
# Read file descriptor mask used by select().  Every file descriptor
# on which we expect to read (or accept) has the corresponding bit
# set.
#
my $FDread = '';

#
# Unix seconds when we next wakeup.  A value of zero forces the scheduler
# to compute the next wakeup time.
#
my $NextWakeup = 0;

#
# Name of signal saved by catch_signal
#
my $SigName = "";

#
# Misc variables
#
my $CmdJob              = "";
my $BackupPCNightlyJobs = 0;
my $BackupPCNightlyLock = 0;
my $FirstWakeup         = 0;
my $RunNightlyWhenIdle  = 0;
my $ServerInetPort      = -1;

#
# Complete the rest of the initialization
#
Main_Initialize();

###########################################################################
# Main loop
###########################################################################
while ( 1 ) {
    #
    # Check if we can/should run BackupPC_nightly
    #
    Main_TryToRun_nightly();

    #
    # Check if we can run a new command from @CmdQueue.
    #
    Main_TryToRun_CmdQueue();

    #
    # Check if we can run a new command from @UserQueue or @BgQueue.
    #
    Main_TryToRun_Bg_or_User_Queue();

    #
    # Do a select() to wait for the next interesting thing to happen
    # (timeout, signal, someone sends a message, child dies etc).
    #
    my $fdRead = Main_Select();

    #
    # Process a signal if we received one.
    #
    if ( $SigName ) {
        Main_Process_Signal();
        $fdRead = undef;
    }

    #
    # Check if a timeout has occurred.
    #
    Main_Check_Timeout();

    #
    # Check for, and process, any messages (output) from our jobs
    #
    Main_Check_Job_Messages($fdRead);

    #
    # Check for, and process, any output from our clients.  Also checks
    # for new connections to our SERVER_UNIX and SERVER_INET sockets.
    #
    Main_Check_Client_Messages($fdRead);
}

############################################################################
# Main_Initialize()
#
# Main initialization routine.  Called once at statup.
############################################################################
sub Main_Initialize
{
    umask($Conf{UmaskMode});

    #
    # Check for another running process, verify executables are configured
    # correctly and make sure $TopDir is on a file system that supports
    # hardlinks.
    #
    if ( defined $Info->{pid} && kill(0, $Info->{pid}) && !$bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort}) ) {
        print(STDERR $bpc->timeStamp, "Another BackupPC is running (pid $Info->{pid}); quitting...\n");
        exit(1);
    }

    foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
    SendmailPath SshPath RsyncBackupPCPath) ) {
        next if ( !defined $Conf{$progName} || $Conf{$progName} eq "" || -x $Conf{$progName} );
        print(STDERR $bpc->timeStamp,
            "\$Conf{$progName} = '$Conf{$progName}' is not a valid executable program; exiting\n");
        exit(1);
    }

    #
    # Create $RunDir if it doesn't exist
    #
    if ( !-d $RunDir && !mkdir($RunDir, 0755) ) {
        print(STDERR $bpc->timeStamp, "Can't create $RunDir... exiting\n");
        exit(1);
    }

    if ( $Conf{PoolV3Enabled} && !$bpc->HardlinkTest("$TopDir/pc", "$TopDir/cpool") ) {
        print(STDERR $bpc->timeStamp,
                "PoolV3Enabled is set, and can't create a test hardlink between a"
              . " file in $TopDir/pc and $TopDir/cpool.  Either these are different"
              . " file systems, or this file system doesn't support hardlinks,"
              . " or these directories don't exist, or there is a permissions"
              . " problem, or the file system is out of inodes or full.  Use"
              . " df, df -i, and ls -ld to check each of these possibilities."
              . " Exiting...\n"
        );
        exit(1);
    }

    if ( $opts{d} ) {
        #
        # daemonize by forking; more robust method per:
        #       http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301057
        #
        my $pid;
        defined($pid = fork) or die("Can't fork: $!");
        exit if ( $pid );    # parent exits

        POSIX::setsid();
        defined($pid = fork) or die("Can't fork: $!");
        exit if $pid;        # parent exits

        chdir("/") or die("Cannot chdir to /: $!\n");
        close(STDIN);
        open(STDIN, "<", "/dev/null") or die("Cannot open /dev/null as stdin\n");

        # STDOUT and STDERR are handled in LogFileOpen() right below,
        # otherwise we would have to reopen them too.
    }

    #
    # Open the LOG file and redirect STDOUT, STDERR etc
    #
    LogFileOpen();

    #
    # Read the hosts file (force a read).
    #
    exit(1) if ( !HostsUpdate(1) );

    #
    # Clean up %ENV for taint checking
    #
    delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
    $ENV{PATH} = $Conf{MyPath};

    #
    # Initialize server sockets
    #
    ServerSocketInit();

    #
    # Catch various signals
    #
    foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
        $SIG{$sig} = \&catch_signal;
    }

    #
    # Report that we started, and update $Info.
    #
    printf(LOG "%sBackupPC %s (Perl v%vd) started, pid %d\n", $bpc->timeStamp, $bpc->{Version}, $^V, $$);
    $Info->{ConfigModTime} = $bpc->ConfigMTime();
    $Info->{pid}           = $$;
    $Info->{startTime}     = time;
    $Info->{ConfigLTime}   = time;
    $Info->{Version}       = $bpc->{Version};

    #
    # Update the status left over form the last time BackupPC ran.
    # Requeue any pending links.
    #
    foreach my $host ( sort(keys(%$Hosts)) ) {
        if ( $Status->{$host}{state} eq "Status_backup_in_progress" ) {
            #
            # should we restart it?  skip it for now.
            #
            $Status->{$host}{state} = "Status_idle";
        } else {
            $Status->{$host}{state} = "Status_idle";
        }
        $Status->{$host}{activeJob} = 0;
    }
    foreach my $host ( sort(keys(%$Status)) ) {
        next if ( defined($Hosts->{$host}) );
        delete($Status->{$host});
    }

    #
    # Write out our initial status and save our PID
    #
    StatusWrite();
    unlink("$RunDir/BackupPC.pid");
    if ( open(PID, ">", "$RunDir/BackupPC.pid") ) {
        print(PID $$);
        close(PID);
        chmod(0444, "$RunDir/BackupPC.pid");
    }

    #
    # For unknown reasons there is a very infrequent error about not
    # being able to coerce GLOBs inside the XS Data::Dumper.  I've
    # only seen this on a particular platform and perl version.
    # For now the workaround appears to be use the perl version of
    # XS Data::Dumper.
    #
    $Data::Dumper::Useqq = 1;
}

############################################################################
# Main_TryToRun_nightly()
#
# Checks to see if we can/should run BackupPC_nightly.  If so we push the
# appropriate command onto @CmdQueue.
############################################################################
sub Main_TryToRun_nightly
{
    #
    # Check if we should run BackupPC_Admin_SCGI.
    #
    SCGIStopStart();

    #
    # Check if we should run BackupPC_nightly.
    # BackupPC_nightly is run when the current job queue is empty.
    #
    if ( $RunNightlyWhenIdle == 1 ) {
        #
        # Queue multiple nightly jobs based on the configuration
        #
        $Conf{MaxBackupPCNightlyJobs} = 1
          if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
        $Info->{NightlyPhase} = $Info->{NightlyPhase} % $Conf{BackupPCNightlyPeriod}
          if ( $Info->{NightlyPhase} < 0 || $Info->{NightlyPhase} >= $Conf{BackupPCNightlyPeriod} );
        $Info->{PoolSizeNightlyPhase} ||= 0;
        #
        # Decide what subset of the 16 top-level directories 0..9a..f
        # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
        # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
        # time.  If $Conf{BackupPCNightlyPeriod} == 2 then we run
        # 0..7 one night and 89a-f the next night.  And so on.
        #
        # $Info->{NightlyPhase} counts which night, from 0 to
        # $Conf{BackupPCNightlyPeriod} - 1.
        #
        my $start = int($Info->{NightlyPhase} * 16 / $Conf{BackupPCNightlyPeriod});
        my $end   = int(($Info->{NightlyPhase} + 1) * 16 / $Conf{BackupPCNightlyPeriod});
        $end = $start + 1 if ( $end <= $start );
        $Info->{NightlyPhase}++;
        $Info->{NightlyPhase} = 0 if ( $end >= 16 );

        #
        # Check if there is a job that is still running since the last
        # time BackupPC_nightly finished.  If so, add the -r option to
        # BackupPC_nightly so it doesn't run BackupPC_refCountUpdate.
        #
        my $dontRunRefCountUpdate;
        foreach my $host ( keys(%Jobs) ) {
            next if ( $host eq $bpc->scgiJob );
            my $pid = $Jobs{$host}{pid};
            if ( $Info->{RunningPIDs}{$pid} ) {
                $dontRunRefCountUpdate = 1;
                last;
            }
        }

        if ( !$dontRunRefCountUpdate ) {
            #
            # Zero out the data we expect to get from BackupPC_nightly
            # (provided we are running BackupPC_refCountUpdate).
            #
            # Also remove Kb2 values, which aren't used in V4.
            #
            delete($Info->{poolKb2});
            delete($Info->{cpoolKb2});
            for my $p ( qw(pool cpool) ) {
                for ( my $i = $start ; $i < $end ; $i++ ) {
                    $Info->{pool}{$p}[$i]{FileCnt}       = 0;
                    $Info->{pool}{$p}[$i]{DirCnt}        = 0;
                    $Info->{pool}{$p}[$i]{Kb}            = 0;
                    $Info->{pool}{$p}[$i]{KbRm}          = 0;
                    $Info->{pool}{$p}[$i]{FileCntRm}     = 0;
                    $Info->{pool}{$p}[$i]{FileCntRep}    = 0;
                    $Info->{pool}{$p}[$i]{FileRepMax}    = 0;
                    $Info->{pool}{$p}[$i]{FileCntRename} = 0;
                    $Info->{pool}{$p}[$i]{FileLinkMax}   = 0;
                    $Info->{pool}{$p}[$i]{FileLinkTotal} = 0;
                    $Info->{pool}{$p}[$i]{Time}          = 0;
                    delete($Info->{pool}{$p}[$i]{Kb2});

                    #
                    # Normally BackupPC_refCountUpdate only reports relative changes to the
                    # pool size, which is a lot more efficient.  BackupPC_refCountUpdate
                    # computes the exact pool size only for a portion of the pool each
                    # night, based on $Conf{PoolSizeNightlyUpdatePeriod}.
                    #
                    # So decide when to clear $Info->{pool}{"${p}4"}[$i]{Kb}.
                    #
                    my $clear;
                    if ( $Conf{PoolSizeNightlyUpdatePeriod} > 0 ) {
                        $clear = ($i % $Conf{PoolSizeNightlyUpdatePeriod}) ==
                          ($Info->{PoolSizeNightlyPhase} % $Conf{PoolSizeNightlyUpdatePeriod});
                    }
                    #print(LOG $bpc->timeStamp, "updating $p size of $i (clear = $clear, phase = $Info->{PoolSizeNightlyPhase},"
                    #                         . " \$Conf{PoolSizeNightlyUpdatePeriod} = $Conf{PoolSizeNightlyUpdatePeriod})\n");

                    $Info->{pool}{"${p}4"}[$i]{Kb}            = 0 if ( $clear );
                    $Info->{pool}{"${p}4"}[$i]{FileCnt}       = 0;
                    $Info->{pool}{"${p}4"}[$i]{DirCnt}        = 0;
                    $Info->{pool}{"${p}4"}[$i]{KbRm}          = 0;
                    $Info->{pool}{"${p}4"}[$i]{FileCntRm}     = 0;
                    $Info->{pool}{"${p}4"}[$i]{FileCntRep}    = 0;
                    $Info->{pool}{"${p}4"}[$i]{FileRepMax}    = 0;
                    $Info->{pool}{"${p}4"}[$i]{FileLinkMax}   = 0;
                    $Info->{pool}{"${p}4"}[$i]{FileLinkTotal} = 0;
                    $Info->{pool}{"${p}4"}[$i]{Time}          = 0;
                    delete $Info->{pool}{"${p}4"}[$i]{FileCntRename};
                }
            }
        }
        print(LOG $bpc->timeStamp,
            sprintf(
                "Running %d BackupPC_nightly jobs from %d..%d (out of 0..15)\n",
                $Conf{MaxBackupPCNightlyJobs},
                $start, $end - 1
            )
        );

        #
        # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
        # The granularity on start and end is now 0..255.
        #
        $start *= 16;
        $end   *= 16;
        my $start0 = $start;
        for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
            #
            # The first nightly job gets the -m option (does email, log aging).
            # All jobs get the start and end options from 0..255 telling
            # them which parts of the pool to traverse.
            #
            my $cmd = ["$BinDir/BackupPC_nightly"];
            push(@$cmd, "-m") if ( $i == 0 );
            push(@$cmd, "-r") if ( $dontRunRefCountUpdate );
            push(@$cmd, "-P", $Info->{PoolSizeNightlyPhase});
            push(@$cmd, $start);
            $start = $start0 + int(($end - $start0) * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
            push(@$cmd, $start - 1);
            my $job = $bpc->adminJob($i);
            unshift(
                @CmdQueue,
                {
                    host    => $job,
                    user    => "BackupPC",
                    reqTime => time,
                    cmd     => $cmd,
                }
            );
            $CmdQueueOn{$job} = 1;
        }
        $RunNightlyWhenIdle = 2;
        $Info->{PoolSizeNightlyPhase}++;
        $Info->{PoolSizeNightlyPhase} = 0 if ( $Info->{PoolSizeNightlyPhase} >= 16 );
    }
}

############################################################################
# Main_TryToRun_CmdQueue()
#
# Decide if we can run a new command from the @CmdQueue.
# We only run one of these at a time.  The @CmdQueue is
# used to run BackupPC_nightly using a fake host name of
# $bpc->adminJob.
############################################################################
sub Main_TryToRun_CmdQueue
{
    my($req, $host);

    while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
        || @CmdQueue > 0 && $RunNightlyWhenIdle == 2 && $bpc->isAdminJob($CmdQueue[0]->{host}) ) {
        local(*FH);
        $req = pop(@CmdQueue);

        $host = $req->{host};
        if ( defined($Jobs{$host}) ) {
            print(LOG $bpc->timeStamp, "Botch on admin job for $host: already in use!! skipping cmd: $req->{cmd})\n");
            next;
        }
        $CmdQueueOn{$host} = 0;
        my $cmd = $req->{cmd};
        my $pid = open(FH, "-|");
        if ( !defined($pid) ) {
            print(LOG $bpc->timeStamp, "can't fork for $host, request by $req->{user}\n");
            close(FH);
            next;
        }
        if ( !$pid ) {
            setpgrp 0, 0;
            $ENV{BPC_REQUSER} = $req->{user};
            POSIX::nice($Conf{CmdQueueNice}) if ( $Conf{CmdQueueNice} );
            unless ( exec(@$cmd) ) {
                print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
                exit(0);
            }
        }
        $Jobs{$host}{pid} = $pid;
        $Jobs{$host}{fh}  = *FH;
        $Jobs{$host}{fn}  = fileno(FH);
        vec($FDread, $Jobs{$host}{fn}, 1) = 1;
        $Jobs{$host}{startTime}     = time;
        $Jobs{$host}{reqTime}       = $req->{reqTime};
        $cmd                        = $bpc->execCmd2ShellCmd(@$cmd);
        $Jobs{$host}{cmd}           = $cmd;
        $Jobs{$host}{user}          = $req->{user};
        $Jobs{$host}{type}          = $Status->{$host}{type};
        $Status->{$host}{state}     = "Status_admin_running";
        $Status->{$host}{activeJob} = 1;
        $Status->{$host}{endTime}   = time;
        $CmdJob                     = $host if ( $host ne $bpc->scgiJob );
        $cmd =~ s/$BinDir\///g;
        print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");

        if ( $cmd =~ /^BackupPC_nightly\s/ ) {
            $BackupPCNightlyJobs++;
            $BackupPCNightlyLock++;
        }
    }
}

############################################################################
# Main_TryToRun_Bg_or_User_Queue()
#
# Decide if we can run any new backup requests from @BgQueue
# or @UserQueue.  Several of these can be run at the same time
# based on %Conf settings.  Jobs from @UserQueue take priority,
# and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
# simultaneous jobs can run from @UserQueue.  After @UserQueue
# is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
# run from @BgQueue.
############################################################################
sub Main_TryToRun_Bg_or_User_Queue
{
    my($req,            $host);
    my(@deferUserQueue, @deferBgQueue);
    my($du,             $duInode);

    if ( !defined $Info->{DUlastValueTime} || time - $Info->{DUlastValueTime} >= 600 ) {
        #
        # Update our notion of disk usage no more than
        # once every 10 minutes
        #
        $du                       = $bpc->CheckFileSystemUsage(0);
        $Info->{DUlastValue}      = $du;
        $Info->{DUlastValueTime}  = time;
        $duInode                  = $bpc->CheckFileSystemUsage(1);
        $Info->{DUInodelastValue} = $duInode;
    } else {
        #
        # if we recently checked it then just use the old value
        #
        $du      = $Info->{DUlastValue};
        $duInode = $Info->{DUInodelastValue};
    }
    if ( $Info->{DUDailyMaxReset} ) {
        $Info->{DUDailyMaxStartTime} = time;
        $Info->{DUDailyMaxReset}     = 0;
        $Info->{DUDailyMax}          = 0;
        $Info->{DUInodeDailyMax}     = 0;
    }
    if ( !defined $Info->{DUDailyMax} || $du > $Info->{DUDailyMax} ) {
        $Info->{DUDailyMax}     = $du;
        $Info->{DUDailyMaxTime} = time;
    }
    if ( !defined $Info->{DUInodeDailyMax} || $duInode > $Info->{DUInodeDailyMax} ) {
        $Info->{DUInodeDailyMax}     = $duInode;
        $Info->{DUInodeDailyMaxTime} = time;
    }
    if ( $du > $Conf{DfMaxUsagePct} || $duInode > $Conf{DfMaxInodeUsagePct} ) {
        my @bgQueue = @BgQueue;
        my $nSkip   = 0;

        #
        # When the disk is too full, only run backups that will
        # do expires, not regular backups
        #
        @BgQueue = ();
        foreach $req ( @bgQueue ) {
            if ( $req->{dumpExpire} ) {
                unshift(@BgQueue, $req);
            } else {
                $BgQueueOn{$req->{host}} = 0;
                $nSkip++;
            }
        }
        if ( $nSkip ) {
            print(LOG $bpc->timeStamp,
                    "Disk too full (usage $du%; inode $duInode%;"
                  . " thres $Conf{DfMaxUsagePct}%/$Conf{DfMaxInodeUsagePct}%); skipped $nSkip hosts\n"
            );
            $Info->{DUDailySkipHostCnt} += $nSkip;
        }
    }

    #
    # Run background jobs anytime.  Previously they were locked out
    # when BackupPC_nightly was running or pending with this
    # condition on the while loop:
    #
    #    while ( $RunNightlyWhenIdle == 0 )
    #
    while ( 1 ) {
        local(*FH);
        my(@args, $progName, $type);
        my $nJobs = keys(%Jobs);
        #
        # CmdJob doesn't count towards MaxBackups / MaxUserBackups
        #
        if ( $CmdJob ne "" ) {
            if ( $BackupPCNightlyJobs ) {
                $nJobs -= $BackupPCNightlyJobs;
            } else {
                $nJobs--;
            }
        }
        $nJobs-- if ( defined($Jobs{$bpc->scgiJob}) );
        if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups} && @UserQueue > 0 ) {
            $req = pop(@UserQueue);
            if ( defined($Jobs{$req->{host}}) ) {
                #
                # Job is currently running for this host; save it for later
                #
                push(@deferUserQueue, $req);
                next;
            }
            if ( $HostMutex{$req->{host}} > 0 && !$req->{restore} && !$req->{archive} ) {
                #
                # Currently there are readers (eg, BackupPC_tarCreate) running, so we
                # can't run a backup or delete
                #
                push(@deferUserQueue, $req);
                next;
            }
            $UserQueueOn{$req->{host}} = 0;
        } elsif ( $nJobs < $Conf{MaxBackups}
            && (@CmdQueue + $nJobs) <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
            && @BgQueue > 0 ) {
            $req = pop(@BgQueue);
            if ( defined($Jobs{$req->{host}}) ) {
                #
                # Job is currently running for this host; save it for later
                #
                unshift(@deferBgQueue, $req);
                next;
            }
            if ( $HostMutex{$req->{host}} > 0 && !$req->{restore} && !$req->{archive} ) {
                #
                # Currently there are readers (eg, BackupPC_tarCreate) running, so we
                # can't run a backup or delete
                #
                unshift(@deferBgQueue, $req);
                next;
            }
            $BgQueueOn{$req->{host}} = 0;
        } else {
            #
            # Restore the deferred jobs
            #
            @BgQueue   = (@BgQueue,   @deferBgQueue);
            @UserQueue = (@UserQueue, @deferUserQueue);
            last;
        }
        $host = $req->{host};
        my $user = $req->{user};
        if ( $req->{restore} ) {
            $progName = "BackupPC_restore";
            $type     = "restore";
            push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
        } elsif ( $req->{delete} ) {
            $progName = "BackupPC_backupDelete";
            $type     = "delete";
            push(@args, "-L", "-h", $req->{host}, '-n', $req->{num}, $req->{opts});
        } elsif ( $req->{archive} ) {
            $progName = "BackupPC_archive";
            $type     = "archive";
            push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
        } else {
            $progName = "BackupPC_dump";
            $type     = "backup";
            push(@args, "-I") if ( $req->{backupType} eq "autoIncr" );
            push(@args, "-F") if ( $req->{backupType} eq "autoFull" );
            push(@args, "-i") if ( $req->{backupType} eq "doIncr" );
            push(@args, "-f") if ( $req->{backupType} eq "doFull" );
            push(@args, "-d") if ( $req->{backupType} eq "dhcpPoll" );
            push(@args, "-e") if ( $req->{dumpExpire} );
            push(@args, $host);
        }
        my $pid = open(FH, "-|");
        if ( !defined($pid) ) {
            print(LOG $bpc->timeStamp, "can't fork to run $progName for $host, request by $user\n");
            close(FH);
            next;
        }
        if ( !$pid ) {
            setpgrp 0, 0;
            unless ( exec("$BinDir/$progName", @args) ) {
                print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
                exit(0);
            }
        }
        $Jobs{$host}{pid}  = $pid;
        $Jobs{$host}{fh}   = *FH;
        $Jobs{$host}{fn}   = fileno(FH);
        $Jobs{$host}{dhcp} = 1 if ( $req->{backupType} eq "dhcpPoll" );
        vec($FDread, $Jobs{$host}{fn}, 1) = 1;
        $Jobs{$host}{startTime}   = time;
        $Jobs{$host}{reqTime}     = $req->{reqTime};
        $Jobs{$host}{userReq}     = $req->{userReq};
        $Jobs{$host}{cmd}         = $bpc->execCmd2ShellCmd($progName, @args);
        $Jobs{$host}{user}        = $user;
        $Jobs{$host}{type}        = $type;
        $Status->{$host}{userReq} = $req->{userReq}
          if ( defined($Hosts->{$host}) );

        if ( !$Jobs{$host}{dhcp} ) {
            $Status->{$host}{state}     = "Status_" . $type . "_starting";
            $Status->{$host}{activeJob} = 1;
            $Status->{$host}{startTime} = time;
            $Status->{$host}{endTime}   = "";
        }
    }
}

############################################################################
# Main_Select()
#
# If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
# and then do a select() to wait for the next thing to happen
# (timeout, signal, someone sends a message, child dies etc).
############################################################################
sub Main_Select
{
    if ( $NextWakeup <= 0 ) {
        #
        # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
        #
        my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
        my($currHours) = $hour + $min / 60 + $sec / 3600;
        if ( $bpc->ConfigMTime() != $Info->{ConfigModTime} ) {
            ServerReload("Re-read config file because mtime changed");
        }
        my $delta = -1;
        foreach my $t ( @{$Conf{WakeupSchedule} || [0 .. 23]} ) {
            next if ( $t < 0 || $t > 24 );
            my $tomorrow = $t + 24;
            if ( $delta < 0 || ($tomorrow - $currHours > 0 && $delta > $tomorrow - $currHours) ) {
                $delta       = $tomorrow - $currHours;
                $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
            }
            if ( $delta < 0 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
                $delta       = $t - $currHours;
                $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
            }
        }
        $NextWakeup = time + $delta * 3600;
        $Info->{nextWakeup} = $NextWakeup;
        print(LOG $bpc->timeStamp, "Next wakeup is ", $bpc->timeStamp($NextWakeup, 1), "\n");
    }
    #
    # Call select(), waiting until either a signal, a timeout,
    # any output from our jobs, or any messages from clients
    # connected via tcp.
    # select() is where we (hopefully) spend most of our time blocked...
    #
    my $timeout = $NextWakeup - time;
    $timeout = 1 if ( $timeout <= 0 );
    my $ein = $FDread;
    select(my $rout = $FDread, undef, $ein, $timeout);

    return $rout;
}

############################################################################
# Main_Process_Signal()
#
# Signal handler.
############################################################################
sub Main_Process_Signal
{
    #
    # Process signals
    #
    if ( $SigName eq "HUP" ) {
        ServerReload("Re-read config file because of a SIG_HUP");
    } elsif ( $SigName ) {
        ServerShutdown("Got signal $SigName... cleaning up", $SigName eq "TERM" ? 0 : 1);
    }
    $SigName = "";
}

############################################################################
# Main_Check_Timeout()
#
# Check if a timeout has occurred, and if so, queue all the PCs for backups.
# Also does log file aging on the first timeout after midnight.
############################################################################
sub Main_Check_Timeout
{
    #
    # Process timeouts
    #
    return if ( time < $NextWakeup || $NextWakeup <= 0 );
    $NextWakeup = 0;
    if ( $FirstWakeup ) {
        #
        # This is the first wakeup after midnight.  Do log file aging
        # and various house keeping.
        #
        $FirstWakeup = 0;
        printf(LOG "%s24hr disk usage: %d%% max, %d%% recent; inode: %d%% max, %d%% recent;  %d skipped hosts\n",
            $bpc->timeStamp,          $Info->{DUDailyMax},       $Info->{DUlastValue},
            $Info->{DUInodeDailyMax}, $Info->{DUInodelastValue}, $Info->{DUDailySkipHostCnt}
        );
        $Info->{DUDailyMaxReset}        = 1;
        $Info->{DUDailyMaxPrev}         = $Info->{DUDailyMax};
        $Info->{DUInodeDailyMaxPrev}    = $Info->{DUInodeDailyMax};
        $Info->{DUDailySkipHostCntPrev} = $Info->{DUDailySkipHostCnt};
        $Info->{DUDailySkipHostCnt}     = 0;
        my $lastLog = $Conf{MaxOldLogFiles} - 1;

        if ( -f "$LogDir/LOG.$lastLog" ) {
            print(LOG $bpc->timeStamp, "Removing $LogDir/LOG.$lastLog\n");
            unlink("$LogDir/LOG.$lastLog");
        }
        if ( -f "$LogDir/LOG.$lastLog.z" ) {
            print(LOG $bpc->timeStamp, "Removing $LogDir/LOG.$lastLog.z\n");
            unlink("$LogDir/LOG.$lastLog.z");
        }
        print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> LOG.1 -> ... -> LOG.$lastLog\n");
        close(STDERR);    # dup of LOG
        close(STDOUT);    # dup of LOG
        close(LOG);
        for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
            my $j = $i + 1;
            rename("$LogDir/LOG.$i", "$LogDir/LOG.$j")
              if ( -f "$LogDir/LOG.$i" );
            rename("$LogDir/LOG.$i.z", "$LogDir/LOG.$j.z")
              if ( -f "$LogDir/LOG.$i.z" );
        }
        #
        # Compress the log file LOG -> LOG.0.z (if enabled).
        # Otherwise, just rename LOG -> LOG.0.
        #
        BackupPC::XS::compressCopy("$LogDir/LOG", "$LogDir/LOG.0.z", "$LogDir/LOG.0", $Conf{CompressLevel}, 1);
        LogFileOpen();
        #
        # Remember to run the nightly script when the next CmdQueue
        # job is done.
        #
        if ( $RunNightlyWhenIdle == 2 || $BackupPCNightlyJobs > 0 ) {
            print(LOG $bpc->timeStamp,
                    "BackupPC_nightly is still running after 24 hours!!"
                  . "  You should adjust the config settings; Skipping this run\n"
            );
        } else {
            $RunNightlyWhenIdle = 1;
        }
    }
    #
    # Write out the current status and then queue all the PCs
    #
    HostsUpdate(0);
    StatusWrite();
    %BgQueueOn   = () if ( @BgQueue == 0 );
    %UserQueueOn = () if ( @UserQueue == 0 );
    %CmdQueueOn  = () if ( @CmdQueue == 0 );
    QueueAllPCs();
}

############################################################################
# Main_Check_Job_Messages($fdRead)
#
# Check if select() says we have bytes waiting from any of our jobs.
# Handle each of the messages when complete (newline terminated).
############################################################################
sub Main_Check_Job_Messages
{
    my($fdRead) = @_;
    foreach my $host ( keys(%Jobs) ) {
        next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
        my $mesg;
        #
        # do a last check to make sure there is something to read so
        # we are absolutely sure we won't block.
        #
        vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
        if ( !select($readMask, undef, undef, 0.0) ) {
            print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages: nothing to read from $host.  Debug dump:\n");
            my($dump) =
              Data::Dumper->new([\%Clients, \%Jobs, \$FDread, \$fdRead], [qw(*Clients  *Jobs   *FDread   *fdRead)]);
            $dump->Indent(1);
            print(LOG $dump->Dump);
            next;
        }
        my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
        $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
        #
        # Process any complete lines of output from this jobs.
        # Any output to STDOUT or STDERR from the children is processed here.
        #
        while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
            $mesg = $1;
            $Jobs{$host}{mesg} = $2;
            if ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
                $Jobs{$host}{type}      = $1;
                $Jobs{$host}{shareName} = $2;
                print(LOG $bpc->timeStamp,
                    "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
                    $Jobs{$host}{dhcpHostIP} ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
                    ", share=$Jobs{$host}{shareName})\n"
                );
                $Status->{$host}{state}     = "Status_backup_in_progress";
                $Status->{$host}{reason}    = "";
                $Status->{$host}{type}      = $1;
                $Status->{$host}{startTime} = time;
                $Status->{$host}{deadCnt}   = 0;
                $Status->{$host}{aliveCnt}++;
                $Status->{$host}{dhcpCheckCnt}--
                  if ( defined $Status->{$host}{dhcpCheckCnt} && $Status->{$host}{dhcpCheckCnt} > 0 );
            } elsif ( $mesg =~ /^xferPids *(.*)/ ) {
                $Jobs{$host}{xferPid} = $1;
            } elsif ( $mesg =~ /^__bpc_progress_state__ (.*)/ ) {
                $Jobs{$host}{xferState}   = $1;
                $Jobs{$host}{xferFileCnt} = "";
            } elsif ( $mesg =~ /^__bpc_progress_fileCnt__ (.*)/ ) {
                $Jobs{$host}{xferFileCnt} = $1;
            } elsif ( $mesg =~ /^started_restore/ ) {
                $Jobs{$host}{type} = "restore";
                print(LOG $bpc->timeStamp, "Started restore on $host (pid=$Jobs{$host}{pid})\n");
                $Status->{$host}{state}     = "Status_restore_in_progress";
                $Status->{$host}{reason}    = "";
                $Status->{$host}{type}      = "restore";
                $Status->{$host}{startTime} = time;
                $Status->{$host}{deadCnt}   = 0;
                $Status->{$host}{aliveCnt}++;
            } elsif ( $mesg =~ /^started_archive/ ) {
                $Jobs{$host}{type} = "archive";
                print(LOG $bpc->timeStamp, "Started archive on $host (pid=$Jobs{$host}{pid})\n");
                $Status->{$host}{state}     = "Status_archive_in_progress";
                $Status->{$host}{reason}    = "";
                $Status->{$host}{type}      = "archive";
                $Status->{$host}{startTime} = time;
                $Status->{$host}{deadCnt}   = 0;
                $Status->{$host}{aliveCnt}++;
            } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
                print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
                $Status->{$host}{reason} = "Reason_backup_done";
                delete($Status->{$host}{error});
                delete($Status->{$host}{errorTime});
                $Status->{$host}{endTime}            = time;
                $Status->{$host}{lastGoodBackupTime} = time;
            } elsif ( $mesg =~ /^backups disabled/ ) {
                print(LOG $bpc->timeStamp, "Ignoring old backup error on $host\n");
                $Status->{$host}{reason} = "Reason_backup_done";
                delete($Status->{$host}{error});
                delete($Status->{$host}{errorTime});
                $Status->{$host}{endTime} = time;
            } elsif ( $mesg =~ /^restore complete/ ) {
                print(LOG $bpc->timeStamp, "Finished restore on $host\n");
                $Status->{$host}{reason} = "Reason_restore_done";
                delete($Status->{$host}{error});
                delete($Status->{$host}{errorTime});
                $Status->{$host}{endTime} = time;
            } elsif ( $mesg =~ /^archive complete/ ) {
                print(LOG $bpc->timeStamp, "Finished archive on $host\n");
                $Status->{$host}{reason} = "Reason_archive_done";
                delete($Status->{$host}{error});
                delete($Status->{$host}{errorTime});
                $Status->{$host}{endTime} = time;
            } elsif ( $mesg =~ /^nothing to do/ ) {
                if (   $Status->{$host}{reason} ne "Reason_backup_failed"
                    && $Status->{$host}{reason} ne "Reason_restore_failed" ) {
                    $Status->{$host}{state}     = "Status_idle";
                    $Status->{$host}{reason}    = "Reason_nothing_to_do";
                    $Status->{$host}{startTime} = time;
                }
                $Status->{$host}{dhcpCheckCnt}--
                  if ( defined $Status->{$host}{dhcpCheckCnt} && $Status->{$host}{dhcpCheckCnt} > 0 );
            } elsif ( $mesg =~ /^no ping response/ || $mesg =~ /^ping too slow/ || $mesg =~ /^host not found/ ) {
                $Status->{$host}{state} = "Status_idle";
                if (   $Status->{$host}{userReq}
                    || $Status->{$host}{reason} ne "Reason_backup_failed"
                    || $Status->{$host}{error} =~ /^aborted by user/ ) {
                    $Status->{$host}{reason}    = "Reason_no_ping";
                    $Status->{$host}{error}     = $mesg;
                    $Status->{$host}{startTime} = time;
                }
                $Status->{$host}{deadCnt}++;
                if ( $Status->{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
                    $Status->{$host}{aliveCnt} = 0;
                }
            } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
                $Status->{$host}{state}     = "Status_idle";
                $Status->{$host}{error}     = $1;
                $Status->{$host}{errorTime} = time;
                $Status->{$host}{endTime}   = time;
                if ( $Status->{$host}{reason} eq "Reason_backup_canceled_by_user" ) {
                    print(LOG $bpc->timeStamp, "Backup canceled on $host ($1)\n");
                } else {
                    $Status->{$host}{reason} = "Reason_backup_failed";
                    print(LOG $bpc->timeStamp, "Backup failed on $host ($1)\n");
                }
            } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
                $Status->{$host}{state}     = "Status_idle";
                $Status->{$host}{error}     = $1;
                $Status->{$host}{errorTime} = time;
                $Status->{$host}{endTime}   = time;
                if ( $Status->{$host}{reason} eq "Reason_restore_canceled_by_user" ) {
                    print(LOG $bpc->timeStamp, "Restore canceled on $host ($1)\n");
                } else {
                    $Status->{$host}{reason} = "Reason_restore_failed";
                    print(LOG $bpc->timeStamp, "Restore failed on $host ($1)\n");
                }
            } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
                $Status->{$host}{state}     = "Status_idle";
                $Status->{$host}{error}     = $1;
                $Status->{$host}{errorTime} = time;
                $Status->{$host}{endTime}   = time;
                if ( $Status->{$host}{reason} eq "Reason_archive_canceled_by_user" ) {
                    print(LOG $bpc->timeStamp, "Archive canceled on $host ($1)\n");
                } else {
                    $Status->{$host}{reason} = "Reason_archive_failed";
                    print(LOG $bpc->timeStamp, "Archive failed on $host ($1)\n");
                }
            } elsif ( $mesg =~ /^log\s+(.*)/ ) {
                print(LOG $bpc->timeStamp, "$1\n");
            } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
                my $chunk = int($1 / 16);
                my @f     = split(/,/, $2);
                $Info->{pool}{$f[0]}[$chunk]{FileCnt}    += $f[1];
                $Info->{pool}{$f[0]}[$chunk]{DirCnt}     += $f[2];
                $Info->{pool}{$f[0]}[$chunk]{Kb}         += $f[3];
                $Info->{pool}{$f[0]}[$chunk]{KbRm}       += $f[4];
                $Info->{pool}{$f[0]}[$chunk]{FileCntRm}  += $f[5];
                $Info->{pool}{$f[0]}[$chunk]{FileCntRep} += $f[6];
                $Info->{pool}{$f[0]}[$chunk]{FileRepMax} = $f[7]
                  if ( $Info->{pool}{$f[0]}[$chunk]{FileRepMax} < $f[7] );
                $Info->{pool}{$f[0]}[$chunk]{FileCntRename} += $f[8];
                $Info->{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[9]
                  if ( $Info->{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[9] );
                $Info->{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[10];
                $Info->{pool}{$f[0]}[$chunk]{Time} = time;
            } elsif ( $mesg =~ /^BackupPC_stats4 (\d+) = (.*)/ ) {
                my $chunk = int($1 / 8);
                my @f     = split(/,/, $2);
                $Info->{pool}{$f[0]}[$chunk]{FileCnt}    += $f[1];
                $Info->{pool}{$f[0]}[$chunk]{DirCnt}     += $f[2];
                $Info->{pool}{$f[0]}[$chunk]{Kb}         += $f[3];
                $Info->{pool}{$f[0]}[$chunk]{KbRm}       += $f[4];
                $Info->{pool}{$f[0]}[$chunk]{FileCntRm}  += $f[5];
                $Info->{pool}{$f[0]}[$chunk]{FileCntRep} += $f[6];
                $Info->{pool}{$f[0]}[$chunk]{FileRepMax} = $f[7]
                  if ( $Info->{pool}{$f[0]}[$chunk]{FileRepMax} < $f[7] );
                $Info->{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[8]
                  if ( $Info->{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[8] );
                $Info->{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[9];
                $Info->{pool}{$f[0]}[$chunk]{Time} = time;
            } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
                $BackupPCNightlyLock--;
                if ( $BackupPCNightlyLock == 0 ) {
                    #
                    # This means the last BackupPC_nightly is done with
                    # the pool clean, so it's ok to start running regular
                    # backups again.  But starting in 3.0 regular jobs
                    # are decoupled from BackupPC_nightly.
                    #
                    $RunNightlyWhenIdle = 0;
                }
            } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
                $Jobs{$host}{processState} = $1;
            } elsif ( $mesg =~ /^link\s+(.+)/ ) {
                my($h) = $1;
                $Status->{$h}{needLink} = 1;
            } else {
                print(LOG $bpc->timeStamp, "$host: $mesg\n");
            }
        }
        #
        # shut down the client connection if we read EOF
        #
        if ( $nbytes <= 0 ) {
            close($Jobs{$host}{fh});
            vec($FDread, $Jobs{$host}{fn}, 1) = 0;
            if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
                my $cmd = $Jobs{$host}{cmd};
                $cmd =~ s/$BinDir\///g;
                print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
                $Status->{$host}{state}   = "Status_idle";
                $Status->{$host}{endTime} = time;
                if ( $cmd =~ /^BackupPC_nightly\s/ ) {
                    $BackupPCNightlyJobs--;
                    #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
                    #         . " have $BackupPCNightlyJobs running\n");
                    if ( $BackupPCNightlyJobs <= 0 ) {
                        #
                        # Last BackupPC_nightly has finished
                        #
                        $BackupPCNightlyJobs = 0;
                        $RunNightlyWhenIdle  = 0;
                        $CmdJob              = "";
                        #
                        # Update the list of currently running jobs, so
                        # we can detect if a single backup spans two
                        # consecutive BackupPC_nightly runs.
                        #
                        $Info->{RunningPIDs} = {};
                        foreach my $host ( keys(%Jobs) ) {
                            my $pid = $Jobs{$host}{pid};
                            $Info->{RunningPIDs}{$pid} = 1 if ( $pid ne "" );
                        }
                        #
                        # Combine the 16 per-directory results for the
                        # old (pool) and new pool (pool4)
                        #
                        for my $p ( qw(pool cpool pool4 cpool4) ) {
                            $Info->{"${p}FileCnt"}    = 0;
                            $Info->{"${p}DirCnt"}     = 0;
                            $Info->{"${p}Kb"}         = 0;
                            $Info->{"${p}KbRm"}       = 0;
                            $Info->{"${p}FileCntRm"}  = 0;
                            $Info->{"${p}FileCntRep"} = 0;
                            $Info->{"${p}FileRepMax"} = 0;
                            if ( $p =~ /^c?pool$/ ) {
                                $Info->{"${p}FileCntRename"} = 0;
                            } else {
                                delete $Info->{"${p}FileCntRename"};
                            }
                            $Info->{"${p}FileLinkMax"} = 0;
                            $Info->{"${p}Time"}        = 0;
                            for ( my $i = 0 ; $i < 16 ; $i++ ) {
                                $Info->{"${p}FileCnt"}    += $Info->{pool}{$p}[$i]{FileCnt};
                                $Info->{"${p}DirCnt"}     += $Info->{pool}{$p}[$i]{DirCnt};
                                $Info->{"${p}Kb"}         += $Info->{pool}{$p}[$i]{Kb};
                                $Info->{"${p}KbRm"}       += $Info->{pool}{$p}[$i]{KbRm};
                                $Info->{"${p}FileCntRm"}  += $Info->{pool}{$p}[$i]{FileCntRm};
                                $Info->{"${p}FileCntRep"} += $Info->{pool}{$p}[$i]{FileCntRep};
                                $Info->{"${p}FileRepMax"} = $Info->{pool}{$p}[$i]{FileRepMax}
                                  if ( $Info->{"${p}FileRepMax"} < $Info->{pool}{$p}[$i]{FileRepMax} );
                                $Info->{"${p}FileCntRename"} += $Info->{pool}{$p}[$i]{FileCntRename}
                                  if ( $p =~ /^c?pool$/ );
                                $Info->{"${p}FileLinkMax"} = $Info->{pool}{$p}[$i]{FileLinkMax}
                                  if ( $Info->{"${p}FileLinkMax"} < $Info->{pool}{$p}[$i]{FileLinkMax} );
                                $Info->{"${p}Time"} = $Info->{pool}{$p}[$i]{Time}
                                  if ( $Info->{"${p}Time"} < $Info->{pool}{$p}[$i]{Time} );
                            }
                            printf(LOG "%s%s nightly clean removed %d files of size %.2fGB\n",
                                $bpc->timeStamp, ucfirst($p),
                                $Info->{"${p}FileCntRm"},
                                $Info->{"${p}KbRm"} / (1000 * 1024)
                            );
                            printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
                                  . "%d max chain, %d max links), %d directories\n",
                                $bpc->timeStamp,                   ucfirst($p),
                                $Info->{"${p}Kb"} / (1000 * 1024), $Info->{"${p}FileCnt"},
                                $Info->{"${p}FileCntRep"},         $Info->{"${p}FileRepMax"},
                                $Info->{"${p}FileLinkMax"},        $Info->{"${p}DirCnt"}
                            );
                        }
                        #
                        # Queue bin/BackupPC_rrdUpdate so that the pool size graphs
                        # can be updated
                        #
                        unshift(
                            @CmdQueue,
                            {
                                host    => $bpc->adminJob(-1),
                                user    => "BackupPC",
                                reqTime => time,
                                cmd     => ["$BinDir/BackupPC_rrdUpdate"],
                            }
                        );
                        $CmdQueueOn{$bpc->adminJob(-1)} = 1;
                    }
                } else {
                    $CmdJob = "";
                }
            } elsif ( defined($Status->{$host}) ) {
                $Status->{$host}{state} = "Status_idle";
            }
            $Status->{$host}{activeJob} = 0 if ( defined($Status->{$host}) );
            delete($Status->{$host}) if ( $Jobs{$host}{dhcp} );
            delete($Jobs{$host});
        }
    }
    #
    # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
    # do a pass over $Status updating the deadCnt and aliveCnt for
    # DHCP hosts.  The reason we need to do this later is we can't
    # be sure whether a DHCP host is alive or dead until we have passed
    # over all the DHCP pool.
    #
    return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
    foreach my $host ( keys(%$Status) ) {
        next if ( !defined $Status->{$host}{dhcpCheckCnt} || $Status->{$host}{dhcpCheckCnt} <= 0 );
        $Status->{$host}{deadCnt} += $Status->{$host}{dhcpCheckCnt};
        $Status->{$host}{dhcpCheckCnt} = 0;
        if ( $Status->{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
            $Status->{$host}{aliveCnt} = 0;
        }
    }
}

############################################################################
# Main_Check_Client_Messages($fdRead)
#
# Check for, and process, any output from our clients.  Also checks
# for new connections to our SERVER_UNIX and SERVER_INET sockets.
############################################################################
sub Main_Check_Client_Messages
{
    my($fdRead) = @_;
    foreach my $client ( keys(%Clients) ) {
        next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
        my($mesg, $host);
        #
        # do a last check to make sure there is something to read so
        # we are absolutely sure we won't block.
        #
        vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
        if ( !select($readMask, undef, undef, 0.0) ) {
            print(LOG $bpc->timeStamp,
                "Botch in Main_Check_Client_Messages: nothing to read from $client.  Debug dump:\n");
            my($dump) =
              Data::Dumper->new([\%Clients, \%Jobs, \$FDread, \$fdRead], [qw(*Clients   *Jobs   *FDread   *fdRead)]);
            $dump->Indent(1);
            print(LOG $dump->Dump);
            next;
        }
        my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
        $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
        #
        # Process any complete lines received from this client.
        #
        while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
            my $reply;
            my $cmd = $1;
            $Clients{$client}{mesg} = $2;
            #
            # Authenticate the message by checking the MD5 digest
            #
            my $md5 = Digest::MD5->new;
            if (
                $cmd !~ /^(.{22}) (.*)/
                || (
                    $md5->add($Clients{$client}{seed} . $Clients{$client}{mesgCnt} . $Conf{ServerMesgSecret} . $2),
                    $md5->b64digest ne $1
                )
            ) {
                print(LOG $bpc->timeStamp,
                        "Corrupted message '$cmd' from"
                      . " client '$Clients{$client}{clientName}':"
                      . " shutting down client connection\n"
                );
                $nbytes = 0;
                last;
            }
            $Clients{$client}{mesgCnt}++;
            $cmd = decode_utf8($2);
            if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
                $host = $1;
                my $user    = $2;
                my $backoff = $3;
                $host = $bpc->uriUnesc($host);
                if ( $CmdJob ne $host && defined($Status->{$host}) && defined($Jobs{$host}) ) {
                    print(LOG $bpc->timeStamp,
                        "Stopping current $Jobs{$host}{type} of $host, request by $user (backoff=$backoff)\n");
                    kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
                    #
                    # Don't close the pipe now; wait until the child
                    # really exits later.  Otherwise close() will
                    # block until the child has exited.
                    #  old code:
                    ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
                    ##close($Jobs{$host}{fh});
                    ##delete($Jobs{$host});

                    $Status->{$host}{state} = "Status_idle";
                    if ( $Jobs{$host}{type} eq "restore" ) {
                        $Status->{$host}{reason} = "Reason_restore_canceled_by_user";
                    } elsif ( $Jobs{$host}{type} eq "archive" ) {
                        $Status->{$host}{reason} = "Reason_archive_canceled_by_user";
                    } else {
                        $Status->{$host}{reason} = "Reason_backup_canceled_by_user";
                    }
                    $Status->{$host}{activeJob} = 0;
                    $Status->{$host}{startTime} = time;
                    $reply                      = "ok: $Jobs{$host}{type} of $host canceled";
                } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
                    print(LOG $bpc->timeStamp,
                        "Stopping pending backup of $host, request by $user (backoff=$backoff)\n");
                    @BgQueue   = grep($_->{host} ne $host, @BgQueue);
                    @UserQueue = grep($_->{host} ne $host, @UserQueue);
                    $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
                    $reply = "ok: pending backup of $host canceled";
                } else {
                    print(LOG $bpc->timeStamp,
                        "Nothing to do for stop backup of $host, request by $user (backoff=$backoff)\n");
                    $reply = "ok: no backup was pending or running";
                }
                if ( defined($Status->{$host}) && $backoff ne "" ) {
                    if ( $backoff > 0 ) {
                        $Status->{$host}{backoffTime} = time + $backoff * 3600;
                    } else {
                        delete($Status->{$host}{backoffTime});
                    }
                }
            } elsif ( $cmd =~ /^backup all$/ ) {
                QueueAllPCs();
            } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
                if ( $BackupPCNightlyJobs > 0 ) {
                    print(LOG $bpc->timeStamp, "Ignoring request to run BackupPC_nightly: already running\n");
                } else {
                    $RunNightlyWhenIdle = 1;
                }
            } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
                my $hostIP = $1;
                $host = $2;
                my $user       = $3;
                my $backupType = $4;
                $host   = $bpc->uriUnesc($host);
                $hostIP = $bpc->uriUnesc($hostIP);
                if ( !defined($Hosts->{$host}) ) {
                    print(LOG $bpc->timeStamp, "User $user requested backup of unknown host $host\n");
                    $reply = "error: unknown host $host";
                } else {
                    #
                    # Handle numeric backupType for backward compatibility
                    # (technically -1 is a new feature for auto)
                    #
                    $backupType = 'auto'   if ( $backupType eq '-1' );
                    $backupType = 'doIncr' if ( $backupType eq '0' );
                    $backupType = 'doFull' if ( $backupType eq '1' );
                    if ( $backupType !~ /^doIncr|doFull|autoIncr|autoFull|auto$/i ) {
                        $reply = "error: unknown backup type $backupType";
                    } else {
                        print(LOG $bpc->timeStamp, "User $user requested backup of $host ($hostIP)\n");
                        if ( $BgQueueOn{$hostIP} ) {
                            @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
                            $BgQueueOn{$hostIP} = 0;
                        }
                        if ( $UserQueueOn{$hostIP} ) {
                            @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
                            $UserQueueOn{$hostIP} = 0;
                        }
                        my $status = QueueOnePC($host, $hostIP, $user, 'user', $backupType);
                        if ( $status == 0 ) {
                            $reply = "ok: requested backup of $host ($backupType)";
                        } elsif ( $status == 1 ) {

                            #should never see this we just dequeued it
                            $reply = "warning: $host was already queued. Ignoring this request";
                        } elsif ( $status == 2 ) {
                            print(LOG $bpc->timeStamp,
                                    "Disk too full (usage $Info->{DUlastValue}%; inode $Info->{DUInodelastValue}%)."
                                  . " Not queueing backup of $host\n"
                            );
                            $reply =
                              "error: disk too full (usage $Info->{DUlastValue}%; inode $Info->{DUInodelastValue}%)";
                            $Info->{DUDailySkipHostCnt}++;
                        } elsif ( $status == 3 ) {

                            # should never reach this because
                            # it's set to "user" above
                            $reply = "error: unknown queue name";
                        } else {
                            $reply = "error: unknown queue status $status";
                            if ( $BgQueueOn{$hostIP} || $UserQueueOn{$hostIP} ) {
                                $reply .= ".  Host is queued.";
                            } else {
                                $reply .= ".  Host is not queued.";
                            }
                        }
                    }
                }
            } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
                my $user        = $1;
                my $archivehost = $2;
                my $reqFileName = $3;
                $host = $bpc->uriUnesc($archivehost);
                if ( !defined($Status->{$host}) ) {
                    print(LOG $bpc->timeStamp, "User $user requested archive of unknown archive host $host");
                    $reply = "archive error: unknown archive host $host";
                } else {
                    print(LOG $bpc->timeStamp, "User $user requested archive on $host ($host)\n");
                    if ( defined($Jobs{$host}) ) {
                        $reply = "Archive currently running on $host, please try later";
                    } else {
                        unshift(
                            @UserQueue,
                            {
                                host        => $host,
                                user        => $user,
                                reqFileName => $reqFileName,
                                reqTime     => time,
                                dhcp        => 0,
                                archive     => 1,
                                userReq     => 1,
                            }
                        );
                        $UserQueueOn{$host} = 1;
                        $reply = "ok: requested archive on $host";
                    }
                }
            } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
                my $hostIP = $1;
                $host = $2;
                my $user        = $3;
                my $reqFileName = $4;
                $host   = $bpc->uriUnesc($host);
                $hostIP = $bpc->uriUnesc($hostIP);
                if ( !defined($Hosts->{$host}) ) {
                    print(LOG $bpc->timeStamp, "User $user requested restore to unknown host $host\n");
                    $reply = "restore error: unknown host $host";
                } else {
                    print(LOG $bpc->timeStamp, "User $user requested restore to $host ($hostIP)\n");
                    unshift(
                        @UserQueue,
                        {
                            host        => $host,
                            hostIP      => $hostIP,
                            reqFileName => $reqFileName,
                            reqTime     => time,
                            dhcp        => 0,
                            restore     => 1,
                            userReq     => 1,
                        }
                    );
                    $UserQueueOn{$host} = 1;
                    if ( defined($Jobs{$host}) ) {
                        $reply =
                            "ok: requested restore of $host, but a"
                          . " job is currently running,"
                          . " so this request will start later";
                    } else {
                        $reply = "ok: requested restore of $host";
                    }
                }
            } elsif ( $cmd =~ /^delete (\S+)\s+(\S+)\s+(\d+)\s+(.*)/ ) {
                my $user = $1;
                $host = $bpc->uriUnesc($2);
                my $num  = $3;
                my $opts = $4;
                if ( !defined($Hosts->{$host}) ) {
                    print(LOG $bpc->timeStamp, "User $user requested delete from unknown host $host\n");
                    $reply = "delete error: unknown host $host";
                } else {
                    print(LOG $bpc->timeStamp, "User $user requested delete for backup #$num from $host\n");
                    unshift(
                        @UserQueue,
                        {
                            host    => $host,
                            num     => $num,
                            reqTime => time,
                            delete  => 1,
                            opts    => $opts,
                            userReq => 1,
                        }
                    );
                    $UserQueueOn{$host} = 1;
                    if ( defined($Jobs{$host}) ) {
                        $reply =
                            "ok: requested delete from $host, but a"
                          . " job is currently running,"
                          . " so this request will start later";
                    } else {
                        $reply = "ok: requested delete from $host";
                    }
                }
            } elsif ( $cmd =~ /^status\s*(.*)/ ) {
                my($args) = $1;
                my($dump, @values, @names);
                foreach my $type ( split(/\s+/, $args) ) {
                    if ( $type =~ /^queues/ ) {
                        push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
                        push(@names, qw(*BgQueue   *UserQueue   *CmdQueue));
                    } elsif ( $type =~ /^jobs/ ) {
                        push(@values, \%Jobs);
                        push(@names,  qw(*Jobs));
                    } elsif ( $type =~ /^queueLen/ ) {
                        push(
                            @values,
                            {
                                BgQueue   => scalar(@BgQueue),
                                UserQueue => scalar(@UserQueue),
                                CmdQueue  => scalar(@CmdQueue),
                            }
                        );
                        push(@names, qw(*QueueLen));
                    } elsif ( $type =~ /^info/ ) {
                        push(@values, $Info);
                        push(@names,  qw(*Info));
                    } elsif ( $type =~ /^hosts/ ) {
                        push(@values, $Status);
                        push(@names,  qw(*Status));
                    } elsif ( $type =~ /^host\((.*)\)/ ) {
                        my $h = $bpc->uriUnesc($1);
                        if ( defined($Status->{$h}) ) {
                            push(
                                @values,
                                {
                                    %{$Status->{$h}},
                                    BgQueueOn   => $BgQueueOn{$h},
                                    UserQueueOn => $UserQueueOn{$h},
                                    CmdQueueOn  => $CmdQueueOn{$h},
                                    Job         => $Jobs{$h},
                                }
                            );
                            push(@names, qw(*StatusHost));
                        } else {
                            print(LOG $bpc->timeStamp, "Unknown host $h for status request\n");
                        }
                    } else {
                        print(LOG $bpc->timeStamp, "Unknown status request $type\n");
                    }
                }
                $dump = Data::Dumper->new(\@values, \@names);
                $dump->Indent(0);
                $reply = $dump->Dump;
            } elsif ( $cmd =~ /^log\s+(.*)/ ) {
                print(LOG $bpc->timeStamp, "$1\n");
            } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
                my($type) = $1;
                if ( $type eq 'reload' ) {
                    ServerReload("Reloading config/host files via CGI request");
                } elsif ( $type eq 'shutdown' ) {
                    $reply = "Shutting down...\n";
                    syswrite($Clients{$client}{fh}, $reply, length($reply));
                    ServerShutdown("Server shutting down...", 0);
                }
            } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
                $nbytes = 0;
                last;
            } elsif ( $cmd =~ /^hostMutex\s+(\S+)\s+(-?\d+)\s+(.*)/ ) {
                $host = $1;
                my $mutexDelta = $2;
                my $progName   = $3;
                if ( !defined($Hosts->{$host}) ) {
                    print(LOG $bpc->timeStamp, "hostMutex for unknown host $host ignored: $cmd\n");
                    $reply = "fail: hostMutex: unknown host $host";
                } elsif ( $HostMutex{$host} == 0 || ($HostMutex{$host} > 0 && $mutexDelta > 0) ) {
                    push(@{$Clients{$client}{hostMutexList}}, {host => $host, mutexDelta => $mutexDelta});
                    $HostMutex{$host} += $mutexDelta;
                    $HostMutexCurrJob{$host} = $progName;
                    $reply = "ok";
                } else {
                    print(LOG $bpc->timeStamp,
                        "Can't run $progName while $HostMutexCurrJob{$host} is running on host $host\n");
                    $reply = "fail: can't run $progName while $HostMutexCurrJob{$host} is running on host $host";
                }
            } elsif ( $cmd =~ /^hostMutexGet\s+(\S+)$/ ) {
                $host = $1;
                if ( !defined($Hosts->{$host}) ) {
                    print(LOG $bpc->timeStamp, "hostMutexGet for unknown host $host ignored: $cmd\n");
                    $reply = "fail: hostMutexGet: unknown host $host";
                } else {
                    $reply = "hostMutexGet: $host == $HostMutex{$host}";
                }
            } elsif ( $cmd =~ /^DHCP (\S+) (\S+)/ ) {
                my $host    = $1;
                my $newHost = $bpc->uriUnesc($2);
                if ( !defined($Jobs{$host}) ) {
                    print(LOG $bpc->timeStamp, "DHCP command for invalid job ignored (cmd = $cmd)\n");
                    $reply = "fail: unknown host/job $host";
                } elsif ( defined($Jobs{$newHost}) ) {
                    print(LOG $bpc->timeStamp, "Backup on $newHost is already running (DHCP command = $cmd)\n");
                    $reply = "fail: newhost $newHost already has a job running (cmd = $cmd)";
                } else {
                    $Jobs{$host}{dhcpHostIP}        = $host;
                    $Status->{$newHost}{dhcpHostIP} = $host;
                    $Jobs{$newHost}                 = $Jobs{$host};
                    $HostMutex{$newHost}            = $HostMutex{$host};
                    $HostMutexCurrJob{$newHost}     = $HostMutexCurrJob{$host};
                    delete($Jobs{$host});
                    delete($HostMutex{$host});
                    delete($HostMutexCurrJob{$host});
                    $host                       = $newHost;
                    $Status->{$host}{state}     = "Status_backup_starting";
                    $Status->{$host}{activeJob} = 1;
                    $Status->{$host}{startTime} = $Jobs{$host}{startTime};
                    $Status->{$host}{endTime}   = "";
                    $Jobs{$host}{dhcp}          = 0;
                }
            } else {
                print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
                $reply = "error: bad command $cmd";
            }
            #
            # send a reply to the client, at a minimum "ok\n".
            #
            $reply = "ok" if ( !defined $reply );
            $reply .= "\n";
            syswrite($Clients{$client}{fh}, $reply, length($reply));
        }
        #
        # Detect possible denial-of-service attack from sending a huge line
        # (ie: never terminated).  32K seems to be plenty big enough as
        # a limit.
        #
        if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
            print(LOG $bpc->timeStamp,
                    "Line too long from client"
                  . " '$Clients{$client}{clientName}':"
                  . " shutting down client connection\n"
            );
            $nbytes = 0;
        }
        #
        # Shut down the client connection if we read EOF
        #
        if ( $nbytes <= 0 ) {
            close($Clients{$client}{fh});
            vec($FDread, $Clients{$client}{fn}, 1) = 0;
            if ( defined($Clients{$client}{hostMutexList}) ) {
                foreach my $d ( @{$Clients{$client}{hostMutexList}} ) {
                    $HostMutex{$d->{host}} -= $d->{mutexDelta};
                }
            }
            delete($Clients{$client});
        }
    }
    #
    # Accept any new connections on each of our listen sockets
    #
    if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
        local(*CLIENT);
        my $paddr = accept(CLIENT, SERVER_UNIX);
        $ClientConnCnt++;
        $Clients{$ClientConnCnt}{clientName} = "unix socket";
        $Clients{$ClientConnCnt}{mesg}       = "";
        $Clients{$ClientConnCnt}{fh}         = *CLIENT;
        $Clients{$ClientConnCnt}{fn}         = fileno(CLIENT);
        vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
        #
        # Generate and send unique seed for MD5 digests to avoid
        # replay attacks.  See BackupPC::Lib::ServerMesg().
        #
        my $seed = time . ",$ClientConnCnt,$$,0\n";
        $Clients{$ClientConnCnt}{seed}    = $seed;
        $Clients{$ClientConnCnt}{mesgCnt} = 0;
        syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
    }
    if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
        local(*CLIENT);
        my $paddr = accept(CLIENT, SERVER_INET);
        my($port, $iaddr) = sockaddr_in($paddr);
        my $name = gethostbyaddr($iaddr, AF_INET);
        $ClientConnCnt++;
        $Clients{$ClientConnCnt}{mesg}       = "";
        $Clients{$ClientConnCnt}{fh}         = *CLIENT;
        $Clients{$ClientConnCnt}{fn}         = fileno(CLIENT);
        $Clients{$ClientConnCnt}{clientName} = "$name:$port";
        vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
        #
        # Generate and send unique seed for MD5 digests to avoid
        # replay attacks.  See BackupPC::Lib::ServerMesg().
        #
        my $seed = time . ",$ClientConnCnt,$$,$port\n";
        $Clients{$ClientConnCnt}{seed}    = $seed;
        $Clients{$ClientConnCnt}{mesgCnt} = 0;
        syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
    }
}

###########################################################################
# Miscellaneous subroutines
###########################################################################

#
# Write the current status to $LogDir/status.pl
#
sub StatusWrite
{
    $bpc->{storage}->StatusDataWrite($Status, $Info);
}

#
# Compare function for host sort.  Hosts with errors go first,
# sorted with the oldest errors first.  The remaining hosts
# are sorted so that those with the oldest backups go first.
#
sub HostSortCompare
{
    #
    # Hosts with errors go before hosts without errors
    #
    return -1 if ( $Status->{$a}{error} ne "" && $Status->{$b}{error} eq "" );

    #
    # Hosts with no errors go after hosts with errors
    #
    return 1 if ( $Status->{$a}{error} eq "" && $Status->{$b}{error} ne "" );

    #
    # hosts with the older last good backups sort earlier
    #
    my $r = $Status->{$a}{lastGoodBackupTime} <=> $Status->{$b}{lastGoodBackupTime};
    return $r if ( $r );

    #
    # Finally, just sort based on host name
    #
    return $a cmp $b;
}

#
# Attempt to queue a host.
# Returns 0 on success; 1 if host is already queued;
#         2 if host was skipped; 3 on invalid queue name
#
# $host       is the client's host name
# $hostIP     is usually the client's host name too, or IP address
#             if the user specified it in the manual backup command
# $user       is the user name, or BackupPC by default
# $queue      is which queue to use ("bg" by default)
# $backupType is the backup type (doIncr|doFull|autoIncr|autoFull|auto|dhcpPoll)
#
# Note: starting in 3.2.0, the PC is queued even if it has a current
# job running
#
sub QueueOnePC
{
    my($host, $hostIP, $user, $queue, $backupType) = @_;
    my $retVal = 0;
    $user       = "BackupPC" if ( $user eq '' );
    $queue      = "bg"       if ( $queue eq '' && $user eq 'BackupPC' );
    $backupType = "auto"     if ( $backupType eq '' );

    delete($Status->{$host}{backoffTime})
      if ( defined($Status->{$host}{backoffTime})
        && $Status->{$host}{backoffTime} < time );
    return 1 if ( $BgQueueOn{$host} || $UserQueueOn{$host} );
    if ( defined($Hosts->{$host}) && $Hosts->{$host}{dhcp} ) {
        $Status->{$host}{dhcpCheckCnt}++;
        if ( $RunNightlyWhenIdle ) {
            #
            # Once per night queue a check for DHCP hosts that just
            # checks for expired dumps.  We need to do this to handle
            # the case when a DHCP host has not been on the network for
            # a long time, and some of the old dumps need to be expired.
            # Normally expiry checks are done by BackupPC_dump only
            # after the DHCP hosts has been detected on the network.
            #
            unshift(
                @BgQueue,
                {
                    host       => $hostIP,
                    user       => $user,
                    reqTime    => time,
                    dhcp       => 0,
                    dumpExpire => 1
                }
            );
            $BgQueueOn{$host} = 1;
        }
    } else {
        #
        # this is a fixed ip host or DHCP ip address: queue it
        #
        if ( $Info->{DUlastValue} > $Conf{DfMaxUsagePct} || $Info->{DUInodelastValue} > $Conf{DfMaxInodeUsagePct} ) {
            #
            # Since we are out of disk space, instead of queuing
            # a regular job, queue an expire check instead.  That
            # way if the admin reduces the number of backups to
            # keep then we will actually delete them.  Otherwise
            # BackupPC_dump will never run since we have exceeded
            # the limit.
            #
            $retVal = 2;
            unshift(@BgQueue, {host => $hostIP, user => $user, reqTime => time, dumpExpire => 1});
            $BgQueueOn{$host} = 1;
        } elsif ( $queue eq 'bg' ) {
            #
            # Queue regular background backup
            #
            unshift(@BgQueue, {host => $hostIP, user => $user, reqTime => time, backupType => $backupType});
            $BgQueueOn{$host} = 1;
        } elsif ( $queue eq 'user' ) {
            #
            # Queue user backup
            #
            unshift(@UserQueue, {host => $hostIP, user => $user, reqTime => time, backupType => $backupType});
            $UserQueueOn{$host} = 1;
        } else {

            # unknown $queue type
            $retVal = 3;
        }
    }

    return $retVal;
}

#
# Queue all the hosts for backup.  This means queuing all the fixed
# ip hosts and all the dhcp address ranges.  We also additionally
# queue the dhcp hosts with a -e flag to check for expired dumps.
#
sub QueueAllPCs
{
    my $nSkip = 0;

    foreach my $host ( sort HostSortCompare keys(%$Hosts) ) {
        $nSkip++ if ( QueueOnePC($host, $host, 'BackupPC', 'bg', 'auto') == 2 );
    }
    foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
        for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
            my $ipAddr = "$dhcp->{ipAddrBase}.$i";
            $nSkip++ if ( QueueOnePC($ipAddr, $ipAddr, 'BackupPC', 'bg', 'dhcpPoll') == 2 );
        }
    }
    if ( $nSkip ) {
        print(LOG $bpc->timeStamp,
                "Disk too full (usage $Info->{DUlastValue}%; inode $Info->{DUInodelastValue}%;"
              . " thres $Conf{DfMaxUsagePct}%/$Conf{DfMaxInodeUsagePct}%);); skipped $nSkip hosts\n"
        );
        $Info->{DUDailySkipHostCnt} += $nSkip;
    }
}

#
# Read the hosts file, and update Status if any hosts have been
# added or deleted.  We also track the mtime so the only need to
# update the hosts file on changes.
#
# This function is called at startup, SIGHUP, and on each wakeup.
# It returns 1 on success and undef on failure.
#
sub HostsUpdate
{
    my($force) = @_;
    my $newHosts;
    #
    # Nothing to do if we already have the current hosts file
    #
    return 1 if ( !$force && defined($Hosts) && $Info->{HostsModTime} == $bpc->HostsMTime() );
    if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
        print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
        return;
    }
    print(LOG $bpc->timeStamp, "Reading hosts file\n");
    $Hosts = $newHosts;
    $Info->{HostsModTime} = $bpc->HostsMTime();
    #
    # Now update $Status in case any hosts have been added or deleted
    #
    foreach my $host ( sort(keys(%$Hosts)) ) {
        next if ( defined($Status->{$host}) );
        $Status->{$host}{state} = "Status_idle";
        print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
    }
    foreach my $host ( sort(keys(%$Status)) ) {
        next
          if ( $host eq $bpc->scgiJob
            || $bpc->isAdminJob($host)
            || defined($Hosts->{$host})
            || defined($Jobs{$host})
            || $BgQueueOn{$host}
            || $UserQueueOn{$host}
            || $CmdQueueOn{$host} );
        print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
        delete($Status->{$host});
    }
    return 1;
}

#
# Remember the signal name for later processing
#
sub catch_signal
{
    if ( $SigName ) {
        $SigName = shift;
        foreach my $host ( keys(%Jobs) ) {
            kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
        }
        #
        # In case we are inside the exit handler, reopen the log file
        #
        close(LOG);
        LogFileOpen();
        print(LOG "Fatal error: unhandled signal $SigName\n");
        unlink("$RunDir/BackupPC.pid");
        confess("Got new signal $SigName... quitting\n");
    } else {
        $SigName = shift;
    }
}

#
# Open the log file and point STDOUT and STDERR there too
#
sub LogFileOpen
{
    mkpath($LogDir, 0, 0777) if ( !-d $LogDir );
    open(LOG, ">>$LogDir/LOG")
      || die("Can't create LOG file $LogDir/LOG");
    close(STDOUT);
    close(STDERR);
    open(STDOUT, ">&LOG");
    open(STDERR, ">&LOG");
    select(LOG);    $| = 1;
    select(STDERR); $| = 1;
    select(STDOUT); $| = 1;
}

#
# Initialize the unix-domain and internet-domain sockets that
# we listen to for client connections (from the CGI script and
# some of the BackupPC sub-programs).
#
sub ServerSocketInit
{
    if ( !defined(fileno(SERVER_UNIX)) ) {
        #
        # one-time only: initialize unix-domain socket
        #
        if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
            print(LOG $bpc->timeStamp, "unix socket() failed: $!; exiting\n");
            exit(1);
        }
        my $sockFile = "$RunDir/BackupPC.sock";
        unlink($sockFile);
        if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
            print(LOG $bpc->timeStamp,
                "unix bind($sockFile) failed: $! (does $RunDir exist and writeable by BackupPC?); exiting\n");
            exit(1);
        }
        if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
            print(LOG $bpc->timeStamp, "unix listen($sockFile) failed: $!; exiting\n");
            exit(1);
        }
        vec($FDread, fileno(SERVER_UNIX), 1) = 1;
    }
    return if ( $ServerInetPort == $Conf{ServerPort} );
    if ( $ServerInetPort > 0 ) {
        vec($FDread, fileno(SERVER_INET), 1) = 0;
        close(SERVER_INET);
        $ServerInetPort = -1;
    }
    if ( $Conf{ServerPort} > 0 ) {
        #
        # Setup a socket to listen on $Conf{ServerPort}
        #
        my $proto = getprotobyname('tcp');
        if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
            print(LOG $bpc->timeStamp, "inet socket() failed: $!; exiting\n");
            exit(1);
        }
        if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l", 1)) ) {
            print(LOG $bpc->timeStamp, "setsockopt() failed: $!; exiting\n");
            exit(1);
        }
        if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
            print(LOG $bpc->timeStamp, "inet bind() failed: $!; exiting\n");
            exit(1);
        }
        if ( !listen(SERVER_INET, SOMAXCONN) ) {
            print(LOG $bpc->timeStamp, "inet listen() failed: $!; exiting\n");
            exit(1);
        }
        vec($FDread, fileno(SERVER_INET), 1) = 1;
        $ServerInetPort = $Conf{ServerPort};
    }
}

#
# Reload the server.  Used by Main_Process_Signal when $SigName eq "HUP"
# or when the command "server reload" is received.
#
sub ServerReload
{
    my($mesg) = @_;
    $mesg = $bpc->ConfigRead() || $mesg;
    print(LOG $bpc->timeStamp, "$mesg\n");
    $Info->{ConfigModTime} = $bpc->ConfigMTime();
    %Conf = $bpc->Conf();
    umask($Conf{UmaskMode});
    ServerSocketInit();
    HostsUpdate(0);
    SCGIStopStart();
    $NextWakeup = 0;
    $Info->{ConfigLTime} = time;
}

sub SCGIStopStart
{
    if ( $Conf{SCGIServerPort} < 0 && defined($Jobs{$bpc->scgiJob}) ) {
        #
        # SCGI was disabled - kill it
        #
        kill($bpc->sigName2num("INT"), $Jobs{$bpc->scgiJob}{pid});
    } elsif ( $Conf{SCGIServerPort} > 0 && !defined($Jobs{$bpc->scgiJob}) && !$CmdQueueOn{$bpc->scgiJob} ) {
        #
        # SCGI is enabled - start it
        #
        unshift(
            @CmdQueue,
            {
                host    => $bpc->scgiJob,
                user    => "BackupPC",
                reqTime => time,
                cmd     => ["$BinDir/BackupPC_Admin_SCGI"],
            }
        );
        $CmdQueueOn{$bpc->scgiJob} = 1;
    }
}

#
# Gracefully shutdown the server.  Used by Main_Process_Signal when
# $SigName ne "" && $SigName ne "HUP" or when the command
# "server shutdown" is received.
#
sub ServerShutdown
{
    my($mesg, $exitCode) = @_;
    print(LOG $bpc->timeStamp, "$mesg (exit code = $exitCode)\n");
    if ( keys(%Jobs) ) {
        foreach my $host ( keys(%Jobs) ) {
            kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
        }
        sleep(1);
        foreach my $host ( keys(%Jobs) ) {
            kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
        }
        %Jobs = ();
    }
    delete($Info->{pid});
    StatusWrite();
    unlink("$RunDir/BackupPC.pid");
    exit($exitCode);
}