File: nnrpd.c

package info (click to toggle)
inn2 2.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 13,228 kB
  • sloc: ansic: 96,526; sh: 15,562; perl: 13,281; makefile: 3,700; yacc: 842; python: 309; lex: 262
file content (1617 lines) | stat: -rw-r--r-- 48,073 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
/*  $Id: nnrpd.c 10320 2018-12-29 13:46:28Z iulius $
**
**  NNTP server for readers (NNRP) for InterNetNews.
**
**  This server doesn't do any real load-limiting, except for what has
**  proven empirically necessary (i.e. look at GRPscandir).
*/

#include "config.h"
#include "portable/alloca.h"
#include "clibrary.h"
#include "portable/setproctitle.h"
#include "portable/socket.h"
#include <netdb.h>
#include <signal.h>
#if defined(INN_BSDI_HOST)
# include <netinet/tcp.h>
#endif

#if HAVE_GETSPNAM
# include <shadow.h>
#endif
#include <sys/wait.h>

#include "inn/innconf.h"
#include "inn/libinn.h"
#include "inn/messages.h"
#include "inn/network.h"
#include "inn/network-innbind.h"
#include "inn/newsuser.h"
#include "inn/ov.h"
#include "inn/version.h"
#define MAINLINE
#include "nnrpd.h"

#include "tls.h"

#if defined(HAVE_OPENSSL)
extern SSL *tls_conn;
#endif

#if defined(HAVE_OPENSSL) || defined(HAVE_SASL)
bool encryption_layer_on = false;
#endif 

static void Usage(void) __attribute__ ((__noreturn__));

/*
**  If we have getloadavg, include the appropriate header file.  Otherwise,
**  just assume that we always have a load of 0.
*/
#if HAVE_GETLOADAVG
# if HAVE_SYS_LOADAVG_H
#  include <sys/loadavg.h>
# endif
#else
static int
getloadavg(double loadavg[], int nelem)
{
    int i;

    for (i = 0; i < nelem && i < 3; i++)
        loadavg[i] = 0;
    return i;
}
#endif


#define MAXPATTERNDEFINE	10

#define CMDany		-1


typedef struct _CMDENT {
    const char *        Name;
    void                (*Function)(int, char **);
    bool                Needauth;
    int                 Minac;
    int                 Maxac;
    bool                Stripspaces;
    const char *        Help;
} CMDENT;


char	*ACTIVE = NULL;
char	*ACTIVETIMES = NULL;
char	*HISTORY = NULL;
char	*NEWSGROUPS = NULL;
char	*NNRPACCESS = NULL;

static char 	*LocalLogFileName = NULL;
static char 	*LocalLogDirName;

struct history *History;
static double	STATstart;
static double	STATfinish;
static char	*PushedBack;
static sig_atomic_t	ChangeTrace;
bool	DaemonMode = false;
bool	ForeGroundMode = false;
static const char 	*HostErrorStr;
bool GetHostByAddr = true;      /* Formerly DO_NNRP_GETHOSTBYADDR. */
const char *NNRPinstance = "";

/* Default values for the syntaxchecks parameter in inn.conf. */
bool laxmid = false;

#ifdef DO_PERL
bool   PerlLoaded = false;
#endif

#ifdef DO_PYTHON
bool PY_use_dynamic = false;
#endif

static char	CMDfetchhelp[] = "[message-ID|number]";


/*
**  { command base name, function to call, need authentication,
**    min args, max args, strip spaces, help string }
*/
static CMDENT	CMDtable[] = {
    {	"ARTICLE",	CMDfetch,	true,	1,	2,      true,
	CMDfetchhelp },
    /* Parse AUTHINFO in a special way so as to keep white spaces
     * in usernames and passwords. */
    {   "AUTHINFO",     CMDauthinfo,    false,  3,      CMDany, false,
        "USER name|PASS password"
#ifdef HAVE_SASL
        "|SASL mechanism [initial-response]"
#endif
        "|GENERIC program [argument ...]" },
    {	"BODY",		CMDfetch,	true,	1,	2,      true,
	CMDfetchhelp },
    {   "CAPABILITIES", CMDcapabilities,false,  1,      2,      true,
        "[keyword]" },
#if defined(HAVE_ZLIB)
    {   "COMPRESS",     CMDcompress,    false,  2,      2,      true,
        "DEFLATE" },
#endif
    {	"DATE",		CMDdate,	false,	1,	1,      true,
	NULL },
    {	"GROUP",	CMDgroup,	true,	2,	2,      true,
	"newsgroup" },
    {   "HDR",          CMDpat  ,       true,   2,      3,      true,
        "header [message-ID|range]" },
    {	"HEAD",		CMDfetch,	true,	1,	2,      true,
	CMDfetchhelp },
    {	"HELP",		CMDhelp,	false,	1,	1,      true,
	NULL },
    {	"IHAVE",	CMDpost,	true,	2,	2,      true,
	"message-ID" },
    {	"LAST",		CMDnextlast,	true,	1,	1,      true,
	NULL },
    {	"LIST",		CMDlist,	true,	1,	3,      true,
        "[ACTIVE [wildmat]|ACTIVE.TIMES [wildmat]|COUNTS [wildmat]|DISTRIB.PATS"
        "|DISTRIBUTIONS|HEADERS [MSGID|RANGE]|MODERATORS|MOTD|NEWSGROUPS [wildmat]"
        "|OVERVIEW.FMT|SUBSCRIPTIONS [wildmat]]" },
    {	"LISTGROUP",	CMDgroup,	true,	1,	3,      true,
	"[newsgroup [range]]" },
    {	"MODE",		CMDmode,	false,	2,	2,      true,
	"READER" },
    {	"NEWGROUPS",	CMDnewgroups,	true,	3,	4,      true,
	"[yy]yymmdd hhmmss [GMT]" },
    {	"NEWNEWS",	CMDnewnews,	true,	4,	5,      true,
	"wildmat [yy]yymmdd hhmmss [GMT]" },
    {	"NEXT",		CMDnextlast,	true,	1,	1,      true,
	NULL },
    {   "OVER",         CMDover,        true,   1,      2,      true,
        "[range]" },
    {	"POST",		CMDpost,	true,	1,	1,      true,
	NULL },
    {   "QUIT",         CMDquit,        false,  1,      1,      true,
        NULL },
    /* SLAVE (which was ill-defined in RFC 977) was removed from the NNTP
     * protocol in RFC 3977. */
    {	"SLAVE",	CMD_unimp,	false,	1,	1,      true,
	NULL },
#ifdef HAVE_OPENSSL
    {   "STARTTLS",     CMDstarttls,    false,  1,      1,      true,
        NULL },
#endif
    {	"STAT",		CMDfetch,	true,	1,	2,      true,
	CMDfetchhelp },
    {	"XGTITLE",	CMDxgtitle,	true,	1,	2,      true,
	"[wildmat]" },
    {	"XHDR",		CMDpat,		true,	2,	3,      true,
	"header [message-ID|range]" },
    {	"XOVER",	CMDover,	true,	1,	2,      true,
	"[range]" },
    {	"XPAT",		CMDpat,		true,	4,	CMDany,      true,
	"header message-ID|range pattern [pattern ...]" },
    {	NULL,           CMD_unimp,      false,  0,      0,      true,
        NULL }
};


static const char *const timer_name[] = {
    "idle",
    "newnews",
    "readart",
    "checkart",
    "nntpread",
    "nntpwrite",
};


/*
**  Log a summary status message and exit.
*/
void
ExitWithStats(int x, bool readconf)
{
    double		usertime;
    double		systime;

    line_free(&NNTPline);
    fflush(stdout);
    STATfinish = TMRnow_double();
    if (GetResourceUsage(&usertime, &systime) < 0) {
	usertime = 0;
	systime = 0;
    }

    GRPreport();
    if (ARTcount)
        syslog(L_NOTICE, "%s exit articles %ld groups %ld", 
    	    Client.host, ARTcount, GRPcount);
    if (POSTreceived || POSTrejected)
	syslog(L_NOTICE, "%s posts received %ld rejected %ld",
	   Client.host, POSTreceived, POSTrejected);
    syslog(L_NOTICE, "%s times user %.3f system %.3f idle %.3f elapsed %.3f",
	Client.host, usertime, systime, IDLEtime, STATfinish - STATstart);
    /* Tracking code - Make entries in the logfile(s) to show that we have
     * finished with this session. */
    if (!readconf && PERMaccessconf && PERMaccessconf->readertrack) {
	syslog(L_NOTICE, "%s Tracking Disabled (%s)", Client.host, Username);
	if (LLOGenable) {
		fprintf(locallog, "%s Tracking Disabled (%s)\n", Client.host, Username);
		fclose(locallog);
		syslog(L_NOTICE,"%s Local Logging ends (%s) %s", Client.host, Username, LocalLogFileName);
	}
    }
    if (ARTget)
        syslog(L_NOTICE, "%s artstats get %ld time %ld size %ld", Client.host,
            ARTget, ARTgettime, ARTgetsize);
    if (!readconf && PERMaccessconf && PERMaccessconf->nnrpdoverstats && OVERcount)
        syslog(L_NOTICE, "%s overstats count %ld hit %ld miss %ld time %ld size %ld dbz %ld seek %ld get %ld artcheck %ld", Client.host,
            OVERcount, OVERhit, OVERmiss, OVERtime, OVERsize, OVERdbz, OVERseek, OVERget, OVERartcheck);

#ifdef HAVE_OPENSSL
     if (tls_conn) {
        SSL_shutdown(tls_conn);
        SSL_free(tls_conn);
        tls_conn = NULL;
     } 
#endif

#ifdef HAVE_SASL
    if (sasl_conn) {
	sasl_dispose(&sasl_conn);
	sasl_conn = NULL;
	sasl_ssf = 0;
	sasl_maxout = NNTP_MAXLEN_COMMAND;
    }
    sasl_done();
#endif /* HAVE_SASL */

#if defined(HAVE_ZLIB)
    if (compression_layer_on) {
        inflateEnd(zstream_in);
        free(zstream_in);
        free(zbuf_in);
        deflateEnd(zstream_out);
        free(zstream_out);
        free(zbuf_out);
    }
#endif /* HAVE_ZLIB */

     if (DaemonMode) {
     	shutdown(STDIN_FILENO, 2);
     	shutdown(STDOUT_FILENO, 2);
     	shutdown(STDERR_FILENO, 2);
 	close(STDIN_FILENO);
 	close(STDOUT_FILENO);
 	close(STDERR_FILENO);
     }
    
    OVclose();
    SMshutdown();

#ifdef DO_PYTHON
    PY_close_python();
#endif /* DO_PYTHON */

    if (History)
	HISclose(History);

    if (innconf->timer != 0) {
        TMRsummary(Client.host, timer_name);
        TMRfree();
    }

    if (LocalLogFileName != NULL)
	free(LocalLogFileName);
    closelog();
    exit(x);
}


/*
**  The HELP command.
*/
void
CMDhelp(int ac UNUSED, char *av[] UNUSED)
{
    CMDENT	*cp;
    char	*p, *q;
    static const char *newsmaster = NEWSMASTER;

    Reply("%d Legal commands\r\n", NNTP_INFO_HELP);
    for (cp = CMDtable; cp->Name; cp++) {
        if (cp->Function == CMD_unimp)
            continue;
	if (cp->Help == NULL)
	    Printf("  %s\r\n", cp->Name);
	else
	    Printf("  %s %s\r\n", cp->Name, cp->Help);
    }
    if (PERMaccessconf && (VirtualPathlen > 0)) {
	if (PERMaccessconf->newsmaster) {
	    if (strchr(PERMaccessconf->newsmaster, '@') == NULL) {
		Printf("Report problems to <%s@%s>.\r\n",
		    PERMaccessconf->newsmaster, PERMaccessconf->domain);
	    } else {
		Printf("Report problems to <%s>.\r\n",
		    PERMaccessconf->newsmaster);
	    }
	} else {
	    /* Sigh, pickup from newsmaster anyway. */
	    if ((p = strchr(newsmaster, '@')) == NULL)
		Printf("Report problems to <%s@%s>.\r\n",
		    newsmaster, PERMaccessconf->domain);
	    else {
                q = xstrndup(newsmaster, p - newsmaster);
		Printf("Report problems to <%s@%s>.\r\n",
		    q, PERMaccessconf->domain);
		free(q);
	    }
	}
    } else {
	if (strchr(newsmaster, '@') == NULL)
	    Printf("Report problems to <%s@%s>.\r\n",
		newsmaster, innconf->fromhost);
	else
	    Printf("Report problems to <%s>.\r\n",
		newsmaster);
    }
    Printf(".\r\n");
}


/*
**  The CAPABILITIES command.
**
**  nnrpd does not advertise the MODE-READER capability; only innd may
**  advertise it.
*/
void
CMDcapabilities(int ac, char *av[])
{
    if (ac == 2 && !IsValidKeyword(av[1])) {
        Reply("%d Syntax error in keyword\r\n", NNTP_ERR_SYNTAX);
        return;
    }

    Reply("%d Capability list:\r\n", NNTP_INFO_CAPABILITIES);

    Printf("VERSION 2\r\n");

    Printf("IMPLEMENTATION %s\r\n", INN_VERSION_STRING);

#ifdef HAVE_SASL
    const char *mechlist = NULL;

    /* Check for available SASL mechanisms.
     * Start the string with a space for the strstr() calls afterwards. */
    sasl_listmech(sasl_conn, NULL, " ", " ", "", &mechlist, NULL, NULL);
#endif

    /* The client is not already authenticated. */
    if ((!PERMauthorized || PERMneedauth || PERMcanauthenticate)) {
        Printf("AUTHINFO");

        /* No arguments if the server does not permit any authentication
         * commands in its current state (either a compression layer other
         * than the one negotiated along with TLS is active, or the user
         * has no way to authenticate successfully). */
        if (
#if defined(HAVE_ZLIB)
            (!compression_layer_on || tls_compression_on) &&
#endif /* HAVE_ZLIB */
            PERMcanauthenticate) {
#ifdef HAVE_OPENSSL
            if (PERMcanauthenticatewithoutSSL || encryption_layer_on) {
#endif
                /* AUTHINFO USER is advertised only if a TLS layer is active,
                 * if compiled with TLS support. */
                Printf(" USER");
#ifdef HAVE_OPENSSL
            } else {
# ifdef HAVE_SASL
                /* Remove unsecure PLAIN, LOGIN and EXTERNAL SASL mechanisms,
                 * if compiled with TLS support and a TLS layer is not active. */
                if (mechlist != NULL) {
                    char *p;

                    if ((p = strstr(mechlist, " PLAIN")) != NULL
                        && (p[6] == '\0' || p[6] == ' ')) {
                        memmove(p, p+6, strlen(p)-5);
                    }
                    if ((p = strstr(mechlist, " LOGIN")) != NULL
                        && (p[6] == '\0' || p[6] == ' ')) {
                        memmove(p, p+6, strlen(p)-5);
                    }
                    if ((p = strstr(mechlist, " EXTERNAL")) != NULL
                        && (p[9] == '\0' || p[9] == ' ')) {
                        memmove(p, p+9, strlen(p)-8);
                    }
                }
# endif /* HAVE_SASL */
            }
#endif /* HAVE_OPENSSL */
#ifdef HAVE_SASL
            /* Check whether at least one SASL mechanism is available. */
            if (mechlist != NULL && strlen(mechlist) > 2) {
                Printf(" SASL");
            }
#endif
        }
        Printf("\r\n");
    }

#if defined(HAVE_ZLIB)
    /* A compression layer is not active. */
    if (!compression_layer_on) {
        Printf("COMPRESS DEFLATE\r\n");
    }
#endif /* HAVE_ZLIB */

    if (PERMcanread) {
        Printf("HDR\r\n");
    }
    
    if (PERMaccessconf->allowihave && PERMcanpost) {
        Printf("IHAVE\r\n");
    }

    Printf("LIST ACTIVE ACTIVE.TIMES COUNTS DISTRIB.PATS DISTRIBUTIONS"
           " HEADERS MODERATORS MOTD NEWSGROUPS OVERVIEW.FMT SUBSCRIPTIONS\r\n");
    
    if (PERMaccessconf->allownewnews && PERMcanread) {
        Printf("NEWNEWS\r\n");
    }

    if (PERMcanread) {
        Printf("OVER\r\n");
    }

    if (PERMcanpost) {
        Printf("POST\r\n");
    }

    Printf("READER\r\n");

#if defined(HAVE_SASL)
    /* Check whether at least one SASL mechanism is available.
     * The SASL capability has to be advertised, even after authentication,
     * so that the client can detect a possible active down-negotiation
     * attack. */
    if (mechlist != NULL && strlen(mechlist) > 2) {
        Printf("SASL%s\r\n", mechlist);
    }
#endif /* HAVE_SASL */

#if defined(HAVE_OPENSSL)
    /* A TLS layer is not active, a compression layer is not active,
     * and the client is not already authenticated. */
    if (!encryption_layer_on
# if defined(HAVE_ZLIB)
        && !compression_layer_on
# endif /* HAVE_ZLIB */
        && (!PERMauthorized || PERMneedauth || PERMcanauthenticate)) {
        Printf("STARTTLS\r\n");
    }
#endif /* HAVE_OPENSSL */

    if (PERMcanread) {
        Printf("XPAT\r\n");
    }

    Printf(".\r\n");
}


/*
**  Catch-all for unimplemented functions.
*/
void
CMD_unimp(int ac UNUSED, char *av[])
{
    Reply("%d \"%s\" not implemented; try \"HELP\"\r\n",
        NNTP_ERR_COMMAND, av[0]);
}


/*
**  The QUIT command.
*/
void
CMDquit(int ac UNUSED, char *av[] UNUSED)
{
    Reply("%d Bye!\r\n", NNTP_OK_QUIT);
    ExitWithStats(0, false);
}


/*
**  Convert an address to a hostname.  Don't trust the reverse lookup
**  since anyone can fake reverse DNS entries.
*/
static bool
Address2Name(struct sockaddr *sa, socklen_t len, char *hostname, size_t size)
{
    static const char MISMATCH[] = "reverse lookup validation failed";
    struct addrinfo hints, *ai, *host;
    char *p;
    int ret;
    bool valid = false;

    /* Get the official hostname, store it away. */
    ret = getnameinfo(sa, len, hostname, size, NULL, 0, NI_NAMEREQD);
    if (ret != 0) {
	HostErrorStr = gai_strerror(ret);
	return false;
    }

    /* Get addresses for this host. */
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    ret = getaddrinfo(hostname, NULL, &hints, &ai);
    if (ret != 0) {
	HostErrorStr = gai_strerror(ret);
	return false;
    }

    /* Make sure one of those addresses is the address we got. */
    for (host = ai; host != NULL; host = host->ai_next)
        if (network_sockaddr_equal(sa, host->ai_addr)) {
            valid = true;
            break;
        }
    freeaddrinfo(ai);

    /* Lowercase the returned name since wildmats are case-sensitive. */
    if (valid) {
        for (p = hostname; *p != '\0'; p++)
            if (isupper((unsigned char) *p))
                *p = tolower((unsigned char) *p);
        return true;
    } else {
	HostErrorStr = MISMATCH;
	return false;
    }
}


/*
**  Determine hostname and IP of the client, amongst other information.
*/
static void
GetClientInfo(unsigned short port)
{
    static const char *default_host_error = "unknown error";
    struct sockaddr_storage ssc, sss;
    struct sockaddr *sac = (struct sockaddr *) &ssc;
    struct sockaddr *sas = (struct sockaddr *) &sss;
    socklen_t length;
    size_t size;

    memset(&Client, 0, sizeof(Client));
    strlcpy(Client.host, "?", sizeof(Client.host));

    /* Get the peer's name. */
    length = sizeof(ssc);
    if (getpeername(STDIN_FILENO, sac, &length) < 0) {
        if (!isatty(STDIN_FILENO)) {
	    sysnotice("? can't getpeername");
	    Reply("%d Can't get your name.  Goodbye!\r\n", NNTP_ERR_ACCESS);
	    ExitWithStats(1, true);
	}
        strlcpy(Client.host, "localhost", sizeof(Client.host));
    } else {
	/* Figure out client's IP address/hostname. */
	HostErrorStr = default_host_error;
        if (!network_sockaddr_sprint(Client.ip, sizeof(Client.ip), sac)) {
            notice("? can't get client numeric address: %s", HostErrorStr);
            Reply("%d Can't get your numeric address.  Goodbye!\r\n",
                   NNTP_ERR_ACCESS);
	    ExitWithStats(1, true);
	}
	if (GetHostByAddr) {
            HostErrorStr = default_host_error;
            if (!Address2Name(sac, length, Client.host, sizeof(Client.host))) {
                notice("? reverse lookup for %s failed: %s -- using IP"
                       " address for access", Client.ip, HostErrorStr);
	        strlcpy(Client.host, Client.ip, sizeof(Client.host));
	    }
	} else {
            strlcpy(Client.host, Client.ip, sizeof(Client.host));
        }

	/* Figure out server's IP address/hostname. */
        length = sizeof(sss);
	if (getsockname(STDIN_FILENO, sas, &length) < 0) {
	    sysnotice("%s can't getsockname", Client.host);
	    Reply("%d Can't figure out where you connected to.  Goodbye!\r\n",
                   NNTP_ERR_ACCESS);
	    ExitWithStats(1, true);
	}
	HostErrorStr = default_host_error;
        size = sizeof(Client.serverip);
        if (!network_sockaddr_sprint(Client.serverip, size, sas)) {
            notice("? can't get server numeric address: %s", HostErrorStr);
            Reply("%d Can't get my own numeric address.  Goodbye!\r\n",
                   NNTP_ERR_ACCESS);
	    ExitWithStats(1, true);
	}
	if (GetHostByAddr) {
	    HostErrorStr = default_host_error;
            size = sizeof(Client.serverhost);
            if (!Address2Name(sas, length, Client.serverhost, size)) {
                notice("? reverse lookup for %s failed: %s -- using IP"
                       " address for access", Client.serverip, HostErrorStr);
	        strlcpy(Client.serverhost, Client.serverip,
                        sizeof(Client.serverhost));
	    }
	} else {
            strlcpy(Client.serverhost, Client.serverip,
                    sizeof(Client.serverhost));
        }

	/* Get port numbers. */
        Client.port = network_sockaddr_port(sac);
        Client.serverport = network_sockaddr_port(sas);
    }

#if defined(INN_BSDI_HOST)
    /* Setting TCP_NODELAY to nnrpd fixes a problem of slow downloading
     * of overviews and slow answers on some architectures (like BSD/OS
     * where TCP delayed acknowledgements are enabled). */
    int nodelay = 1;
    setsockopt(STDIN_FILENO, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay));
#endif

    notice("%s (%s) connect - port %u", Client.host, Client.ip, port);
}


/*
**  Write a buffer, via compression layer and/or SASL security layer
**  and/or TLS if necessary.
*/
void
write_buffer(const char *buff, ssize_t len)
{
    const char *p;
    ssize_t n;

    TMRstart(TMR_NNTPWRITE);
    p = buff;

#if defined(HAVE_ZLIB)
    if (compression_layer_on) {
        int r;

        zstream_out->next_in = (unsigned char *) p;
        zstream_out->avail_in = len;
        zstream_out->next_out = zbuf_out;
        zstream_out->avail_out = zbuf_out_size;

        do {
            /* Grow the output buffer if needed. */
            if (zstream_out->avail_out == 0) {
                size_t newsize = zbuf_out_size * 2;
                zbuf_out = xrealloc(zbuf_out, newsize);
                zstream_out->next_out = zbuf_out + zbuf_out_size;
                zstream_out->avail_out = zbuf_out_size;
                zbuf_out_size = newsize;
            }

            r = deflate(zstream_out,
                        zstream_flush_needed ? Z_PARTIAL_FLUSH : Z_NO_FLUSH);

            if (!(r == Z_OK || r == Z_BUF_ERROR || r == Z_STREAM_END)) {
                sysnotice("deflate() failed: %d; %s", r,
                          zstream_out->msg != NULL ? zstream_out->msg :
                          "no detail");
                return;
            }
        } while (r == Z_OK && zstream_out->avail_out == 0);

        p = (char *) zbuf_out;
        len = zbuf_out_size - zstream_out->avail_out;
        zstream_flush_needed = false;
    }
#endif /* HAVE_ZLIB */

    while (len > 0) {
	const char *out;
	unsigned outlen;

#if defined(HAVE_SASL)
        if (sasl_conn != NULL && sasl_ssf > 0) {
            int r;

            /* Can only encode as much as the client can handle at one time. */
            n = (len > sasl_maxout) ? sasl_maxout : len;
            if ((r = sasl_encode(sasl_conn, p, n, &out, &outlen)) != SASL_OK) {
                const char *ed = sasl_errdetail(sasl_conn);

                sysnotice("sasl_encode() failed: %s; %s",
                          sasl_errstring(r, NULL, NULL),
                          ed != NULL ? ed : "no detail");
                return;
            }
        } else
#endif /* HAVE_SASL */
	{
	    /* Output the entire unencoded string. */
	    n = len;
	    out = p;
	    outlen = len;
	}

	len -= n;
	p += n;

#ifdef HAVE_OPENSSL
	if (tls_conn) {
            int r;

Again:
	    r = SSL_write(tls_conn, out, outlen);
	    switch (SSL_get_error(tls_conn, r)) {
	    case SSL_ERROR_NONE:
	    case SSL_ERROR_SYSCALL:
		break;
	    case SSL_ERROR_WANT_WRITE:
		goto Again;
		break;
	    case SSL_ERROR_SSL:
		SSL_shutdown(tls_conn);
		tls_conn = NULL;
		errno = ECONNRESET;
		break;
	    case SSL_ERROR_ZERO_RETURN:
		break;
	    }
	} else
#endif /* HAVE_OPENSSL */
	    do {
		n = write(STDIN_FILENO, out, outlen);
	    } while (n == -1 && errno == EINTR);
    }

    TMRstop(TMR_NNTPWRITE);
}


/*
**  Send formatted output, possibly with debugging output.
*/
static void __attribute__((__format__(printf, 1, 0)))
VPrintf(const char *fmt, va_list args, int dotrace)
{
    char buff[2048], *p;
    ssize_t len;

    len = vsnprintf(buff, sizeof(buff), fmt, args);
    if (len < 0)
        len = 0;
    else if ((size_t)len >= sizeof(buff))
        len = sizeof(buff) - 1;
    write_buffer(buff, len);

    if (dotrace && Tracing) {
	int oerrno = errno;

        /* Copy output, but strip trailing CR-LF.  Note we're assuming here
         * that no output line can ever be longer than 2045 characters. */
        p = buff + strlen(buff) - 1;
        while (p >= buff && (*p == '\n' || *p == '\r'))
            *p-- = '\0';
        syslog(L_TRACE, "%s > %s", Client.host, buff);

        errno = oerrno;
    }
}


/*
**  Send a reply, possibly with debugging output.
**  Reply() is used for answers which can possibly be traced (response codes).
**  Printf() is used in other cases.
*/
void
Reply(const char *fmt, ...)
{
    va_list args;

#if defined(HAVE_ZLIB)
    /* For single-line responses, immediately flush the output stream. */
    zstream_flush_needed = true;
#endif /* HAVE_ZLIB */

    va_start(args, fmt);
    VPrintf(fmt, args, 1);
    va_end(args);
}

void
Printf(const char *fmt, ...)
{
    va_list args;

#if defined(HAVE_ZLIB)
    /* Last line of a multi-line data block response.
     * Time to flush the compressed output stream.
     * Check that only when the compression layer is active. */
    if (compression_layer_on &&
        strlen(fmt) == 3 && strcasecmp(fmt, ".\r\n") == 0) {
        zstream_flush_needed = true;
    }
#endif /* HAVE_ZLIB */

    va_start(args, fmt);
    VPrintf(fmt, args, 0);
    va_end(args);
}


#ifdef HAVE_SIGACTION
#define NO_SIGACTION_UNUSED UNUSED
#else
#define NO_SIGACTION_UNUSED
#endif


/*
**  Got a signal; toggle tracing.
*/
static void
ToggleTrace(int s NO_SIGACTION_UNUSED)
{
    ChangeTrace = true;
#ifndef HAVE_SIGACTION
    xsignal(s, ToggleTrace);
#endif
}

/*
**  Got a SIGPIPE; exit cleanly.
*/
static void
CatchPipe(int s UNUSED)
{
    ExitWithStats(0, false);
}


/*
**  Got a signal; wait for children.
*/
static void
WaitChild(int s NO_SIGACTION_UNUSED)
{
    int pid;

    for (;;) {
       pid = waitpid(-1, NULL, WNOHANG);
       if (pid <= 0)
       	    break;
    }
#ifndef HAVE_SIGACTION
    xsignal(s, WaitChild);
#endif
}


static void
SetupDaemon(void)
{
    bool                val;

    val = true;
    if (SMsetup(SM_PREOPEN, (void *)&val) && !SMinit()) {
	syslog(L_NOTICE, "can't initialize storage method, %s", SMerrorstr);
	Reply("%d NNTP server unavailable.  Try later!\r\n", NNTP_FAIL_TERMINATING);
	ExitWithStats(1, true);
    }
    OVextra = overview_extra_fields(false);
    if (OVextra == NULL) {
	/* overview_extra_fields() should already have logged something
	 * useful. */
	Reply("%d NNTP server unavailable.  Try later!\r\n", NNTP_FAIL_TERMINATING);
	ExitWithStats(1, true);
    }
    overhdr_xref = overview_index("Xref", OVextra);
    if (!OVopen(OV_READ)) {
	/* This shouldn't really happen. */
	syslog(L_NOTICE, "can't open overview %m");
	Reply("%d NNTP server unavailable.  Try later!\r\n", NNTP_FAIL_TERMINATING);
	ExitWithStats(1, true);
    }
    if (!OVctl(OVCACHEKEEP, &val)) {
	syslog(L_NOTICE, "can't enable overview cache %m");
	Reply("%d NNTP server unavailable.  Try later!\r\n", NNTP_FAIL_TERMINATING);
	ExitWithStats(1, true);
    }
}


/*
**  Print a usage message and exit.
*/
static void
Usage(void)
{
    fprintf(stderr, "Usage error.\n");
    exit(1);
}


int
main(int argc, char *argv[])
{
    const char *name;
    CMDENT		*cp;
    char		buff[NNTP_MAXLEN_COMMAND];
    char		**av;
    int			ac;
    READTYPE		r;
    int                 i;
    unsigned int        j;
    char                **v;
    char		*Reject;
    int			timeout;
    unsigned int	vid=0;
    int 		count=123456789;
    struct		timeval tv;
    unsigned short	ListenPort = NNTP_PORT;
    char                *ListenAddr = NULL;
    char                *ListenAddr6 = NULL;
    int			*lfds;
    fd_set              lfdset, lfdsetread;
    unsigned int        lfdcount;
    int                 lfdreadcount;
    bool                lfdokay;
    int                 lfdmax = 0;
    int                 fd = -1;
    pid_t		pid = -1;
    FILE                *pidfile;
    int			clienttimeout;
    char		*ConfFile = NULL;
    char                *path;
    bool                validcommandtoolong;

    int respawn = 0;

    setproctitle_init(argc, argv);

    /* Parse arguments.  Must xstrdup() optarg if used because setproctitle
     * may clobber it! */
    Reject = NULL;
    LLOGenable = false;
    GRPcur = NULL;
    MaxBytesPerSecond = 0;
    strlcpy(Username, "unknown", sizeof(Username));

    /* Set up the pathname, first thing, and teach our error handlers about
     * the name of the program. */
    name = argv[0];
    if (name == NULL || *name == '\0')
	name = "nnrpd";
    else {
	const char *p;

        /* We take the last "/" in the path. */
	p = strrchr(name, '/');
	if (p != NULL)
	    name = p + 1;
    }
    message_program_name = xstrdup(name);
    openlog(message_program_name, L_OPENLOG_FLAGS | LOG_PID, LOG_INN_PROG);
    message_handlers_die(1, message_log_syslog_crit);
    message_handlers_warn(1, message_log_syslog_warning);
    message_handlers_notice(1, message_log_syslog_notice);

    /* Initialize the character class tables for message-IDs. */
    InitializeMessageIDcclass();

    if (!innconf_read(NULL))
        exit(1);

#ifdef HAVE_SASL
    if (sasl_server_init(sasl_callbacks, "INN") != SASL_OK) {
	syslog(L_FATAL, "sasl_server_init() failed");
	exit(1);
    }
#endif /* HAVE_SASL */

#ifdef HAVE_OPENSSL
    while ((i = getopt(argc, argv, "4:6:b:c:Dfi:I:nop:P:r:s:St")) != EOF)
#else
    while ((i = getopt(argc, argv, "4:6:b:c:Dfi:I:nop:P:r:s:t")) != EOF)
#endif /* HAVE_OPENSSL */
	switch (i) {
	default:
	    Usage();
	    /* NOTREACHED */
        case '4':                       /* Bind to a certain IPv4 address. */
        case 'b':
            if (ListenAddr != NULL)
                die("-b and -4 are the same and both may not be given");
            ListenAddr = xstrdup(optarg);
            break;
        case '6':                       /* Bind to a certain IPv6 address. */
            ListenAddr6 = xstrdup(optarg);
            break;
	case 'c':                       /* Use alternate readers.conf. */
	    ConfFile = concatpath(innconf->pathetc, optarg);
	    break;
 	case 'D':			/* Standalone daemon mode. */
 	    DaemonMode = true;
 	    break;
        case 'P':                       /* Prespawn count in daemon mode. */
	    respawn = atoi(optarg);
	    break;
 	case 'f':			/* Don't fork on daemon mode. */
 	    ForeGroundMode = true;
 	    break;
	case 'i':			/* Initial command. */
	    PushedBack = xstrdup(optarg);
	    break;
	case 'I':			/* Instance. */
	    NNRPinstance = xstrdup(optarg);
	    break;
	case 'n':			/* No DNS lookups. */
	    GetHostByAddr = false;
	    break;
	case 'o':
	    Offlinepost = true;		/* Offline posting only. */
	    break;
 	case 'p':			/* TCP port for daemon mode. */
 	    ListenPort = atoi(optarg);
 	    break;
	case 'r':			/* Reject connection message. */
	    Reject = xstrdup(optarg);
	    break;
	case 's':			/* Unused title string. */
	    break;
	case 't':			/* Tracing. */
	    Tracing = true;
	    break;
#ifdef HAVE_OPENSSL
	case 'S':			/* Force the negotiation of an encryption layer. */
	    initialSSL = true;
	    break;
#endif /* HAVE_OPENSSL */
	}
    argc -= optind;
    if (argc)
	Usage();

    /* Make other processes happier if someone is reading.  This allows other
     * processes like overchan to keep up when there are lots of readers.
     * Note that this is cumulative with nicekids. */
    if (innconf->nicennrpd != 0)
	nice(innconf->nicennrpd);

    HISTORY = concatpath(innconf->pathdb, INN_PATH_HISTORY);
    ACTIVE = concatpath(innconf->pathdb, INN_PATH_ACTIVE);
    ACTIVETIMES = concatpath(innconf->pathdb, INN_PATH_ACTIVETIMES);
    NEWSGROUPS = concatpath(innconf->pathdb, INN_PATH_NEWSGROUPS);
    if(ConfFile)
        NNRPACCESS = ConfFile;
    else
        NNRPACCESS = concatpath(innconf->pathetc,INN_PATH_NNRPACCESS);

    /* Initialize the checks to perform or not on article syntax. */
    if ((innconf->syntaxchecks != NULL) && (innconf->syntaxchecks->count > 0)) {
        for (j = 0; j < innconf->syntaxchecks->count; j++) {
            if (innconf->syntaxchecks->strings[j] != NULL) {
                if (strcmp(innconf->syntaxchecks->strings[j], "laxmid") == 0) {
                    laxmid = true;
                } else if (strcmp(innconf->syntaxchecks->strings[j], 
                                  "no-laxmid") == 0) {
                    laxmid = false;
                } else {
                    syslog(L_NOTICE, "Unknown \"%s\" value in syntaxchecks "
                           "parameter in inn.conf",
                           innconf->syntaxchecks->strings[j]);
                }
            }
        }
    }

    if (DaemonMode) {
        /* Allocate an lfds array to hold the file descriptors
         * for IPv4 and/or IPv6 connections. */
        if (ListenAddr == NULL && ListenAddr6 == NULL) {
            network_innbind_all(SOCK_STREAM, ListenPort, &lfds, &lfdcount);
        } else {
            if (ListenAddr != NULL && ListenAddr6 != NULL)
                lfdcount = 2;
            else
                lfdcount = 1;
            lfds = xmalloc(lfdcount * sizeof(int));
            i = 0;
            if (ListenAddr6 != NULL) {
                lfds[i++] = network_innbind_ipv6(SOCK_STREAM, ListenAddr6,
                                                 ListenPort);
            }
            if (ListenAddr != NULL) {
                lfds[i] = network_innbind_ipv4(SOCK_STREAM, ListenAddr,
                                               ListenPort);
            }
        }

        /* Bail if we couldn't listen on any sockets. */
        lfdokay = false;
        for (j = 0; j < lfdcount; j++) {
            if (lfds[j] < 0)
                continue;
            lfdokay = true;
        }
        if (!lfdokay)
            die("can't bind to any addresses");

        /* If started as root, switch to news uid.  Unlike other parts of INN, we
         * don't die if we can't become the news user.  As long as we're not
         * running as root, everything's fine; it's okay to write the things we
         * write as a member of the news group. */
        if (getuid() == 0) {
            ensure_news_user_grp(true, true);
        }

	/* Detach. */
	if (!ForeGroundMode) {
	    daemonize("/");
	}

	if (ListenPort == NNTP_PORT)
	    strlcpy(buff, "nnrpd.pid", sizeof(buff));
	else
	    snprintf(buff, sizeof(buff), "nnrpd-%d.pid", ListenPort);
        path = concatpath(innconf->pathrun, buff);
        pidfile = fopen(path, "w");
        free(path);
	if (pidfile == NULL) {
	    syslog(L_ERROR, "cannot write %s %m", buff);
            exit(1);
	}
	fprintf(pidfile,"%lu\n", (unsigned long) getpid());
	fclose(pidfile);

	/* Set signal handle to care for dead children. */
	if (!respawn)
	    xsignal(SIGCHLD, WaitChild);

	/* Arrange to toggle tracing. */
	xsignal(SIGHUP, ToggleTrace);
 
	setproctitle("accepting connections");
 	
        /* Initialize the listener file descriptors set. */
        FD_ZERO(&lfdset);

        for (j = 0; j < lfdcount; j++) {
            if (listen(lfds[j], 128) < 0) {
                if (j != 0 && errno == EADDRINUSE)
                    continue;
                syslog(L_ERROR, "can't listen to socket");
            } else {
                /* Remember the largest descriptor number
                 * that is to be tested by select(). */
                FD_SET(lfds[j], &lfdset);
                if (lfdmax < lfds[j])
                    lfdmax = lfds[j];
            }
        }

	if (respawn) {
	    /* Pre-forked mode. */
	    for (;;) {
		if (respawn > 0) {
		    --respawn;
		    pid = fork();
		    if (pid == 0) {
			do {
                            fd = -1;

                            /* Copy the master set because lfdsetread
                             * will be modified. */
                            lfdsetread = lfdset;
                            lfdreadcount = select(lfdmax + 1, &lfdsetread,
                                                  NULL, NULL, NULL);

                            if (lfdreadcount > 0) {
                                for (j = 0; j < lfdcount; j++) {
                                    if (FD_ISSET(lfds[j], &lfdsetread)) {
                                        fd = accept(lfds[j], NULL, NULL);
                                        /* Only handle the first match.  Future
                                         * calls to select() will handle possible
                                         * other matches. */
                                        if (fd >= 0)
                                            break;
                                    }
                                }
                            }
			} while (fd < 0);
			break;
		    }
		}
		for (;;) {
		    if (respawn == 0)
			pid = wait(NULL);
		    else
			pid = waitpid(-1, NULL, WNOHANG);
		    if (pid <= 0)
			break;
		    ++respawn;
		}
	    }
	} else {
	    /* Fork on demand. */
	    do {
                fd = -1;
                
                /* Copy the master set because lfdsetread will be modified. */
                lfdsetread = lfdset;
                lfdreadcount = select(lfdmax + 1, &lfdsetread, NULL, NULL, NULL);

                if (lfdreadcount > 0) {
                    for (j = 0; j < lfdcount; j++) {
                        if (FD_ISSET(lfds[j], &lfdsetread)) {
                            fd = accept(lfds[j], NULL, NULL);
                            /* Only handle the first match.  Future calls
                             * to select() will handle possible other matches. */
                            if (fd >= 0)
                                break;
                        }
                    }
                }
		if (fd < 0)
		    continue;

		for (j = 0; j <= innconf->maxforks && (pid = fork()) < 0; j++) {
		    if (j == innconf->maxforks) {
			syslog(L_FATAL, "can't fork (dropping connection): %m");
			continue;
		    }
		    syslog(L_NOTICE, "can't fork (waiting): %m");
		    sleep(1);
		}
		if (ChangeTrace) {
		    Tracing = Tracing ? false : true;
		    syslog(L_TRACE, "trace %sabled", Tracing ? "en" : "dis");
		    ChangeTrace = false;
		}
		if (pid != 0)
		    close(fd);
	    } while (pid != 0);
	}

	/* Child process starts here. */
	setproctitle("connected");
        for (j = 0; j < lfdcount; j++) {
            close(lfds[j]);
        }
	dup2(fd, 0);
	close(fd);
	dup2(0, 1);
	dup2(0, 2);
        if (innconf->timer != 0)
            TMRinit(TMR_MAX);
        STATstart = TMRnow_double();
	SetupDaemon();

	/* If we are a daemon, innd didn't make us nice, so be nice kids. */
	if (innconf->nicekids) {
	    if (nice(innconf->nicekids) < 0)
		syslog(L_ERROR, "Could not nice child to %ld: %m", innconf->nicekids);
	}

	/* Only automatically reap children in the listening process. */
	xsignal(SIGCHLD, SIG_DFL);
 
    } else {
        if (innconf->timer != 0)
            TMRinit(TMR_MAX);
        STATstart = TMRnow_double();
	SetupDaemon();
	/* Arrange to toggle tracing. */
	xsignal(SIGHUP, ToggleTrace);
    } /* DaemonMode */

#ifdef HAVE_OPENSSL
    if (initialSSL) {
        tls_init();
        if (tls_start_servertls(0, 1) == -1) {
            GetClientInfo(ListenPort);
            notice("%s failure to negotiate TLS session", Client.host);
            Reply("%d Encrypted TLS connection failed\r\n",
                  NNTP_FAIL_TERMINATING);
            ExitWithStats(1, false);
        }
        encryption_layer_on = true;

# if defined(HAVE_ZLIB) && OPENSSL_VERSION_NUMBER >= 0x00090800fL
        /* Check whether a compression layer has just been added.
         * SSL_get_current_compression() is defined in OpenSSL versions >= 0.9.8
         * final release. */
        tls_compression_on = (SSL_get_current_compression(tls_conn) != NULL);
        compression_layer_on = tls_compression_on;
# endif /* HAVE_ZLIB && OPENSSL >= v0.9.8 */
    }
#endif /* HAVE_OPENSSL */

    /* If requested, check the load average. */
    if (innconf->nnrpdloadlimit != 0) {
        double load[1];

        if (getloadavg(load, 1) < 0)
            warn("cannot obtain system load");
        else {
            if ((unsigned long)(load[0] + 0.5) > innconf->nnrpdloadlimit) {
                GetClientInfo(ListenPort);
                notice("%s load %.2f > %lu", Client.host,
                       load[0], innconf->nnrpdloadlimit);
                Reply("%d load at %.2f, try later\r\n", NNTP_FAIL_TERMINATING,
                      load[0]);
                ExitWithStats(1, true);
            }
        }
    }

    /* Catch SIGPIPE so that we can exit out of long write loops. */
    xsignal(SIGPIPE, CatchPipe);

    /* Get permissions and see if we can talk to this client. */
    GetClientInfo(ListenPort);
    PERMgetinitialaccess(NNRPACCESS);
    PERMgetaccess(true);
    PERMgetpermissions();

    if (!PERMcanread && !PERMcanpost && !PERMneedauth) {
	syslog(L_NOTICE, "%s no_permission", Client.host);
	Reply("%d You have no permission to talk.  Goodbye!\r\n",
	       NNTP_ERR_ACCESS);
	ExitWithStats(1, false);
    }

    /* Proceed with initialization. */
    setproctitle("%s connect", Client.host);

    /* Were we told to reject connections? */
    if (Reject) {
	syslog(L_NOTICE, "%s rejected %s", Client.host, Reject);
	Reply("%d %s\r\n", NNTP_FAIL_TERMINATING,
              is_valid_utf8(Reject) ? Reject : "Connection rejected");
	ExitWithStats(0, false);
    }

    if (PERMaccessconf) {
	if (PERMaccessconf->readertrack)
	    PERMaccessconf->readertrack =
                TrackClient(Client.host, Username, sizeof(Username));
    } else {
	if (innconf->readertrack)
	    innconf->readertrack =
                TrackClient(Client.host, Username, sizeof(Username));
    }

    if ((PERMaccessconf && PERMaccessconf->readertrack)
        || (!PERMaccessconf && innconf->readertrack)) {
	int len;
	syslog(L_NOTICE, "%s Tracking Enabled (%s)", Client.host, Username);
	pid=getpid();
	gettimeofday(&tv,NULL);
	count += pid;
	vid = tv.tv_sec ^ tv.tv_usec ^ pid ^ count;
	len = strlen("innconf->pathlog") + strlen("/tracklogs/log-") + BUFSIZ;
	LocalLogFileName = xmalloc(len);
	sprintf(LocalLogFileName, "%s/tracklogs/log-%u", innconf->pathlog, vid);
	if ((locallog = fopen(LocalLogFileName, "w")) == NULL) {
            LocalLogDirName = concatpath(innconf->pathlog, "tracklogs");
	    MakeDirectory(LocalLogDirName, false);
	    free(LocalLogDirName);
	}
	if (locallog == NULL && (locallog = fopen(LocalLogFileName, "w")) == NULL) {
	    syslog(L_ERROR, "%s Local Logging failed (%s) %s: %m", Client.host, Username, LocalLogFileName);
	} else {
	    syslog(L_NOTICE, "%s Local Logging begins (%s) %s",Client.host, Username, LocalLogFileName);
	    fprintf(locallog, "%s Tracking Enabled (%s)\n", Client.host, Username);
	    fflush(locallog);
	    LLOGenable = true;
	}
    }

#ifdef HAVE_SASL
    SASLnewserver();
#endif /* HAVE_SASL */

    if (PERMaccessconf) {
        Reply("%d %s InterNetNews NNRP server %s ready (%s)\r\n",
	   (PERMcanpost || (PERMcanauthenticate && PERMcanpostgreeting)) ?
               NNTP_OK_BANNER_POST : NNTP_OK_BANNER_NOPOST,
           PERMaccessconf->pathhost, INN_VERSION_STRING,
	   (!PERMneedauth && PERMcanpost) ? "posting ok" : "no posting");
	clienttimeout = PERMaccessconf->clienttimeout;
    } else {
        Reply("%d %s InterNetNews NNRP server %s ready (%s)\r\n",
	   (PERMcanpost || (PERMcanauthenticate && PERMcanpostgreeting)) ?
               NNTP_OK_BANNER_POST : NNTP_OK_BANNER_NOPOST,
           innconf->pathhost, INN_VERSION_STRING,
	   (!PERMneedauth && PERMcanpost) ? "posting ok" : "no posting");
	clienttimeout = innconf->clienttimeout;
    }

    line_init(&NNTPline);

    /* Main dispatch loop. */
    for (timeout = innconf->initialtimeout, av = NULL, ac = 0; ;
			timeout = clienttimeout) {
        alloca_free();
	TMRstart(TMR_NNTPWRITE);
	fflush(stdout);
	TMRstop(TMR_NNTPWRITE);
	if (ChangeTrace) {
	    Tracing = Tracing ? false : true;
	    syslog(L_TRACE, "trace %sabled", Tracing ? "en" : "dis");
	    ChangeTrace = false;
	}
	if (PushedBack) {
	    if (PushedBack[0] == '\0')
		continue;
	    if (Tracing)
		syslog(L_TRACE, "%s < %s", Client.host, PushedBack);
	    ac = nArgify(PushedBack, &av, 1);
	    r = RTok;
	}
	else {
	    size_t len;
            size_t lenstripped = 0;
	    const char *p;
            char *q;

	    r = line_read(&NNTPline, timeout, &p, &len, &lenstripped);
	    switch (r) {
	    default:
		syslog(L_ERROR, "%s internal %d in main", Client.host, r);
		/* FALLTHROUGH */
	    case RTtimeout:
		if (timeout < clienttimeout)
		    syslog(L_NOTICE, "%s timeout short", Client.host);
		else
		    syslog(L_NOTICE, "%s timeout", Client.host);
		ExitWithStats(1, false);
		break;
	    case RTok:
                /* len does not count CRLF. */
		if (len + lenstripped <= sizeof(buff)) {
		    /* line_read guarantees null termination. */
		    memcpy(buff, p, len + 1);
		    /* Do some input processing, check for blank line. */
                    if (buff[0] != '\0')
                        ac = nArgify(buff, &av, 1);
		    if (Tracing) {
                        /* Do not log passwords if AUTHINFO PASS,
                         * AUTHINFO SASL PLAIN or AUTHINFO SASL EXTERNAL
                         * are used.  (Only one space between SASL and
                         * PLAIN/EXTERNAL should be put; otherwise, the
                         * whole command will be logged).
                         * AUTHINFO SASL LOGIN does not use an initial response;
                         * therefore, there is nothing to hide here. */
                        if (ac > 1 && strcasecmp(av[0], "AUTHINFO") == 0) {
                            if (strncasecmp(av[1], "PASS", 4) == 0)
                                syslog(L_TRACE, "%s < AUTHINFO PASS ********",
                                       Client.host);
                            else if (strncasecmp(av[1], "SASL PLAIN", 10) == 0)
                                syslog(L_TRACE, "%s < AUTHINFO SASL PLAIN ********",
                                       Client.host);
                            else if (strncasecmp(av[1], "SASL EXTERNAL", 13) == 0)
                                syslog(L_TRACE, "%s < AUTHINFO SASL EXTERNAL ********",
                                       Client.host);
                            else
                                syslog(L_TRACE, "%s < %s", Client.host, buff);
                        } else {
                            syslog(L_TRACE, "%s < %s", Client.host, buff);
                        }
                    }
		    if (buff[0] == '\0')
			continue;
		    break;
		}
		/* FALLTHROUGH */		
	    case RTlong:
                /* The line is too long but we have to make sure that
                 * no recognized command has been sent. */
                q = (char *)p;
                ac = nArgify(q, &av, 1);
                validcommandtoolong = false;
                for (cp = CMDtable; cp->Name; cp++) {
                    if ((cp->Function != CMD_unimp) &&
                        (ac > 0 && strcasecmp(cp->Name, av[0]) == 0)) {
                        validcommandtoolong = true;
                        break;
                    }
                }
                Reply("%d Line too long\r\n",
                      validcommandtoolong ? NNTP_ERR_SYNTAX : NNTP_ERR_COMMAND);
		continue;
	    case RTeof:
		/* Handled below. */
		break;
	    }
	}
	/* Client gone? */
	if (r == RTeof)
	    break;
	if (ac == 0)
	    continue;

	/* Find command. */
	for (cp = CMDtable; cp->Name; cp++)
	    if (strcasecmp(cp->Name, av[0]) == 0)
		break;

        /* If no command has been recognized. */
	if (cp->Name == NULL) {
	    if ((int)strlen(buff) > 40)
		syslog(L_NOTICE, "%s unrecognized %.40s...", Client.host, buff);
	    else
		syslog(L_NOTICE, "%s unrecognized %s", Client.host, buff);
	    if (strcasecmp(av[0], "XYZZY") == 0) {
                /* Acknowledge the magic word from the Colossal Cave Adventure computer game. */
                Reply("%d Nothing happens\r\n", NNTP_ERR_COMMAND);
            } else {
                Reply("%d What?\r\n", NNTP_ERR_COMMAND);
            }
	    continue;
	}

        /* Go on parsing the command. */
        ac--;
        ac += reArgify(av[ac], &av[ac],
                       cp->Stripspaces ? -1 : cp->Minac - ac - 1,
                       cp->Stripspaces);

        /* Check whether all arguments do not exceed their allowed size. */
        if (ac > 1) {
            validcommandtoolong = false;
            for (v = av; *v; v++)
                if (strlen(*v) > NNTP_MAXLEN_ARG) {
                    validcommandtoolong = true;
                    Reply("%d Argument too long\r\n", NNTP_ERR_SYNTAX);
                    break;
                }
            if (validcommandtoolong)
                continue;
        }

	/* Check usage. */
	if ((cp->Minac != CMDany && ac < cp->Minac)
	 || (cp->Maxac != CMDany && ac > cp->Maxac)) {
	    Reply("%d Syntax is:  %s %s\r\n",
		NNTP_ERR_SYNTAX, cp->Name, cp->Help ? cp->Help : "(no argument allowed)");
	    continue;
	}

	/* Check permissions and dispatch. */
	if (cp->Needauth && PERMneedauth) {
	    Reply("%d Authentication required for command\r\n",
		NNTP_FAIL_AUTH_NEEDED);
	    continue;
	}
	setproctitle("%s %s", Client.host, av[0]);

        (*cp->Function)(ac, av);

        if (PushedBack)
	    break;
	if (PERMaccessconf)
	    clienttimeout = PERMaccessconf->clienttimeout;
	else
	    clienttimeout = innconf->clienttimeout;
    }

    ExitWithStats(0, false);

    /* NOTREACHED */
    return 1;
}