File: NNTPServer.m

package info (click to toggle)
lusernet.app 0.4.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 828 kB
  • sloc: objc: 8,495; makefile: 22
file content (2108 lines) | stat: -rw-r--r-- 43,444 bytes parent folder | download
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
/*
copyright 2001-2002 Alexander Malmberg <alexander@malmberg.org>
          2015 Riccardo Mottola
*/

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <netdb.h>
#include <fcntl.h>
#include <sys/socket.h>

#include <Foundation/NSException.h>
#include <Foundation/NSRunLoop.h>
#include <Foundation/NSAutoreleasePool.h>
#include <Foundation/NSString.h>

#include <Foundation/NSBundle.h>

#include "NNTPServer.h"

/* TODO: owner specifies modes? */
#include <AppKit/NSApplication.h>


//#define DEBUG_SCHEDULER

#ifdef DEBUG_SCHEDULER
@interface NNTPServer (debug_scheduler)
-(void) _updateDebugScheduler;
@end
#endif


/* TODO: better error handling? */


static NSTimeInterval Now(void)
{
	return [NSDate timeIntervalSinceReferenceDate];
}


//#define DEBUG_SOCKET


/* based on a sample of 29314 messages from a few different (non-binary)
groups */
#define ESTIMATED_MSG_SIZE 2183


/* TODO: for temporary xover stat collection */
//#define XOVER_STATS
#ifdef XOVER_STATS
static int stat_num_headers,stat_num_expected_headers,stat_header_bytes;
#endif


#define MAX_CONNECTIONS 2

typedef struct
{
	int time_limit; /* open if work is above work_limit, close after */
	int work_limit; /* work<work_limit time_limit seconds */
} work_limit_t;

static work_limit_t work_limits[MAX_CONNECTIONS+1]=
{ /* TODO: test and tweak, manage priorities and almost completed tasks? */
#if 0
	{ 120,     0},
	{   5,    10},
	{   5,    20},
	{   5,    30},
#else
#if 0
	{  10,      0},
	{   5,  80000}, /* open second connection soon so single large downloads */
	{   5, 200000}, /* don't prevent higher priority stuff from running */
	{   5,1000000},
#else
	{ 120,      0},
	{  60,  80000}, /* open second connection soon so single large downloads */
//	{  30, 160000}, /* don't prevent higher priority stuff from running */
//	{  15,1000000},
#endif
#endif
};


typedef enum
{
WHAT_NONE,
WHAT_DATE,
WHAT_GROUP_INFO,
WHAT_HEADER_RANGE,
WHAT_HEADER_ID,
WHAT_ARTICLE_RANGE,
WHAT_ARTICLE_ID,
WHAT_GROUP_LIST,
WHAT_POST_ARTICLE,
} what_t;

typedef struct
{
	signed short priority;
	what_t what;
	unsigned int qid;
	union
	{
		int group;
		struct
		{
			int group;
			unsigned int l,h;
		} range;
		struct
		{
			char *id;
			int bytes;
		} msg;
		struct
		{
			unsigned char *data;
			int length;
		} post;
	} d;
} queue_entry_t;


typedef struct nntp_queue_s
{
	queue_entry_t *qe;
	int qe_num,qe_size;
	int total_work;
	unsigned int qid;
} queue_t;


static queue_t *queue_new(void)
{
	queue_t *q=malloc(sizeof(queue_t));
	if (!q) return NULL;
	memset(q,0,sizeof(queue_t));
	q->qe_size=8;
	q->qid=1;
	q->qe=malloc(sizeof(queue_entry_t)*q->qe_size);
	if (!q->qe) return NULL;
	q->qe[0].priority=10000;
	return q;
}

static void queue_free(queue_t *q)
{
	free(q->qe);
	free(q);
}

/* return an estimated number of bytes returned */
static int queue_work(queue_entry_t *qe)
{
	switch (qe->what)
	{
	case WHAT_NONE: return 0;

	case WHAT_DATE: return 10;
	case WHAT_GROUP_INFO: return 10;

	case WHAT_HEADER_ID:
		return 500;
	case WHAT_HEADER_RANGE:
		/* testing suggets 380 bytes/message */
		return (qe->d.range.h-qe->d.range.l+1)*380;

	case WHAT_ARTICLE_ID:
		return qe->d.msg.bytes;
	case WHAT_ARTICLE_RANGE:
		return (qe->d.range.h-qe->d.range.l+1)*ESTIMATED_MSG_SIZE;

	case WHAT_GROUP_LIST:
		return 10000; /* will probably be a lot more, but could be a lot less */

	case WHAT_POST_ARTICLE:
		return qe->d.post.length;
	}
	fprintf(stderr,"unhandled q->what %i in queue_work()\n",qe->what);
	abort();
	return 1; /* shouldn't happen */
}

static unsigned int queue_add(queue_t *q,signed short priority,queue_entry_t *qadd)
{
	queue_entry_t *qe;
	int i;
	if (q->qe_num==q->qe_size-1)
	{
		queue_entry_t *e;
		int nsize;
		if (q->qe_size>1024)
			nsize=q->qe_size+1024;
		else
			nsize=q->qe_size*2;
		e=realloc(q->qe,nsize*sizeof(queue_entry_t));
		if (!e)
		{ /* TODO: very difficult to handle gracefully, but should never happen */
			fprintf(stderr,"queue_add: out of memory, dropping\n");
			abort();
//			return NULL;
		}
		q->qe=e;
		q->qe_size=nsize;
	}
	q->qe_num++;
	for (i=q->qe_num;q->qe[i/2].priority<priority;i/=2)
		q->qe[i]=q->qe[i/2];
	qe=&q->qe[i];
	*qe=*qadd;
	qe->priority=priority;
	qe->qid=q->qid++;
	q->total_work+=queue_work(qe);
	return qe->qid;
}

#define QE_LESS(q1,q2) ( ((q2)->priority>(q1)->priority) || ( ((q1)->priority==(q2)->priority) && ((q2)->qid<(q1)->qid) ) )

static void queue_remove(queue_t *q,queue_entry_t *qe)
{
	queue_entry_t *ins;
	int pri;
	int i,j;

	pri=qe->priority;
	i=qe-q->qe;
	if (i<1 || i>q->qe_num) return;

	q->total_work-=queue_work(qe);

	ins=&q->qe[q->qe_num];
	q->qe_num--;

	qe=ins;
	if (qe->priority==pri)
	{
		q->qe[i]=*qe;
		return;
	}

	if (qe->priority<pri)
	{
		for (;i*2<=q->qe_num;i=j)
		{
			j=i*2;
			if (j+1<=q->qe_num && QE_LESS(&q->qe[j],&q->qe[j+1])) j++;
			if (QE_LESS(qe,&q->qe[j]))
				q->qe[i]=q->qe[j];
			else
				break;
		}
		q->qe[i]=*qe;
	}
	else
	{
		for (;q->qe[i/2].priority<qe->priority;i/=2)
			q->qe[i]=q->qe[i/2];
		q->qe[i]=*qe;
	}
}


static queue_entry_t *queue_get(queue_t *q)
{
	if (!q->qe_num) return NULL;
	return &q->qe[1];
}

static void queue_delete_max(queue_t *q)
{
	int i,j;
	queue_entry_t *qe;

	q->total_work-=queue_work(&q->qe[1]);
	qe=&q->qe[q->qe_num--];

	for (i=1;i*2<=q->qe_num;i=j)
	{
		j=i*2;
		if (j+1<=q->qe_num && QE_LESS(&q->qe[j],&q->qe[j+1])) j++;
		if (QE_LESS(qe,&q->qe[j]))
			q->qe[i]=q->qe[j];
		else
			break;
	}
	q->qe[i]=*qe;
}

#undef QE_LESS

static void queue_entry_clear(queue_entry_t *q)
{
	if (q->what==WHAT_HEADER_ID || q->what==WHAT_ARTICLE_ID )
		if (q->d.msg.id)
		{
			free(q->d.msg.id);
			q->d.msg.id=NULL;
		}

	if (q->what==WHAT_POST_ARTICLE)
		if (q->d.post.data)
		{
			free(q->d.post.data);
			q->d.post.data=NULL;
		}

	q->what=WHAT_NONE;
}


typedef enum
{
S_NONE,
S_IDLE,

S_CONNECT1,   /* connected, waiting for hello message */
              /* send 'mode reader' */
S_CONNECT2,   /* waiting for 'mode reader' response */

S_QUIT,       /* waiting for 205 response */

S_DATE,       /* waiting for DATE response */

S_GROUP,      /* waiting for GROUP response for group info */

S_SWITCH_GROUP, /* waiting for GROUP response while switching groups */
                /* for some other command */

S_HEADER_RANGE1,
S_HEADER_RANGE2,

S_HEADER_ID1,
S_HEADER_ID2,

S_ARTICLE_RANGE1,
S_ARTICLE_RANGE2,

S_ARTICLE_ID1,
S_ARTICLE_ID2,

S_GROUP_LIST1,
S_GROUP_LIST2,

S_POST_ARTICLE1,
S_POST_ARTICLE2,

} state_t;

typedef struct nntp_connection_s
{
	int valid;

	int sock;

	char *write_pending;
	int write_pending_ofs;
	int write_len;

	/*
	 0=no response yet
	 1=have status
	 2=have status, waiting for data
	 3=have status and data
	*/
	int resp;
	int resp_code;            /* numeric code in status */
	char *resp_msg;           /* status message (if any) */
	unsigned char *resp_buf;  /* read buffer */
	int resp_buf_len;         /* length of buffer */
	int resp_data_len;        /* data has been processed up to this point */
	int resp_data_nline;

	int resp_data_len_last;   /* used to keep user updated on long responses */

	state_t state;
	char should_close,reg_write;

	queue_entry_t cur;
	int cur_group;

#ifdef DEBUG_SOCKET
	FILE *debug_write;
#endif
} con_t;


static char **group_names;
static int num_group_names;


@interface NNTPServer (private) <RunLoopEvents>
-(void) updateQueue;
-setup;

-(int) nc_connect: (con_t *)c;
-(void) nc_update: (con_t *)c;
-(void) nc_setState: (con_t *)c : (state_t)nstate;
-(void) nc_close: (con_t *)c;
-(void) nc_free: (con_t *)c;

-(void) nc_parseResponse: (con_t *)c;
-(void) nc_updateRead: (con_t *)c;
-(void) nc_updateWrite: (con_t *)c;

-(void) nc_writeCommand: (con_t *)c : (const char *)cmd, ...;
-(void) nc_writeData: (con_t *)c : (unsigned char *)data : (int)length;

-(void) nc_responseClear: (con_t *)c;
-(void) nc_responseWantData: (con_t *)c;

-(void) nc_updateState: (con_t *)c;
-(void) nc_handleWhat: (con_t *)c;

-(void) nc_fail: (con_t *)c;

-(void) nc_timeout;
@end


@implementation NNTPServer (private)

-setup
{
	should_connect=0;
	runloop=[[NSRunLoop currentRunLoop] retain];
	runmodes=[[NSArray alloc] initWithObjects:
		NSDefaultRunLoopMode,
		NSModalPanelRunLoopMode,
		NSEventTrackingRunLoopMode,
		nil];

	queue=queue_new();
	if (!queue)
		[NSException raise: @"NNTPServer_Error" format: @"out of memory"];

	num_cons=MAX_CONNECTIONS;
	cons=malloc(sizeof(con_t)*num_cons);
	if (!cons)
		[NSException raise: @"NNTPServer_Error" format: @"out of memory"];
	memset(cons,0,sizeof(con_t)*num_cons);

	lca_delta=-1.0;
	last_connect_attempt=Now();
//	last_activity=Now();

	return self;
}


-(int) fixAddr
{
	if (!have_addr)
	{
		struct hostent *h;
		unsigned char *a;

		h=gethostbyname(host);
		if (!h)
		{
			DESTROY(last_error);
			last_error=[[NSString stringWithFormat: _(@"lookup of %s failed: %s"),host,strerror(errno)] retain];
			return 0;
		}
		addr.sin_addr=*(struct in_addr *)h->h_addr;
		a=(unsigned char *)h->h_addr;
		[rec nntp_message:
			[NSString
				stringWithFormat: _(@"Resolved '%s' to %i.%i.%i.%i"),
					host,a[0],a[1],a[2],a[3]]];
		have_addr=1;
	}
	if (port==-1)
	{
		struct servent *s;
		struct protoent *p;
		s=getservbyname("nntp","tcp");
		if (!s)
		{
			[rec nntp_message:
				[NSString stringWithFormat: _(@"warning: can't find service 'nntp', assuming port 119")]];
			port=119;
			p=getprotobyname("tcp");
		}
		else
		{
			port=ntohs(s->s_port);
			p=getprotobyname(s->s_proto);
		}
		if (!p)
		{
			[rec nntp_message:
				[NSString stringWithFormat: _(@"warning: can't find protocol, assuming 0")]];
			protocol=0;
		}
		else
			protocol=p->p_proto;
	}
	if (protocol==-1)
	{
		struct protoent *p;
		p=getprotobyname("tcp");
		if (!p)
		{
			[rec nntp_message:
				[NSString stringWithFormat: _(@"warning: can't find protocol, assuming 0")]];
			protocol=0;
		}
		else
			protocol=p->p_proto;
	}
	return 1;
}


-(int) nc_connect: (con_t *)c
{
	if (![self fixAddr])
		return 0;

	addr.sin_family=AF_INET;
	addr.sin_port=htons(port);

#ifdef DEBUG_SOCKET
	{
		char buf[128];
		sprintf(buf,"ncon%i.txt",c-cons);
		c->debug_write=fopen(buf,"at");
	}
#endif

	{
		unsigned char *a=(unsigned char *)&addr.sin_addr;
		[rec nntp_message:
			[NSString stringWithFormat: _(@"Connecting to %i.%i.%i.%i:%i..."),
				a[0],a[1],a[2],a[3],port]];
#ifdef DEBUG_SOCKET
		fprintf(c->debug_write,"-=- Connecting to %i.%i.%i.%i:%i\n",a[0],a[1],a[2],a[3],port);fflush(c->debug_write);
#endif
	}

	c->sock=socket(PF_INET,SOCK_STREAM,protocol);
	if (c->sock<0)
	{
		DESTROY(last_error);
		last_error=[[NSString
			stringWithFormat: _(@"can't create socket: %s"),strerror(errno)]
			retain];
		return 0;
	}

	if (connect(c->sock,(struct sockaddr *)&addr,sizeof(addr))<0)
	{
		DESTROY(last_error);
		last_error=[[NSString
			stringWithFormat: _(@"Can't open connection: %s"),strerror(errno)]
			retain];
		close(c->sock);
		c->sock=-1;
		return 0;
	}

	{
		int flags;
		flags=fcntl(c->sock,F_GETFL);
		flags|=O_NONBLOCK;
		if (fcntl(c->sock,F_SETFL,flags))
		{
			DESTROY(last_error);
			last_error=[[NSString
				stringWithFormat: _(@"fcntl failed to set non-blocking mode: %s"),strerror(errno)]
				retain];
			close(c->sock);
			c->sock=-1;
			return 0;
		}
	}

	c->valid=1;

	{
		int i,count=[runmodes count];
		for (i=0;i<count;i++)
		{
		  [runloop addEvent: (void *)(intptr_t)c->sock type: ET_RDESC watcher: self
				forMode: [runmodes objectAtIndex: i]];
		  [runloop addEvent: (void *)(intptr_t)c->sock type: ET_EDESC watcher: self
				forMode: [runmodes objectAtIndex: i]];
		}
	}

	[self nc_setState: c : S_CONNECT1];

	return 1;
}


-(void) nc_update: (con_t *)c
{
	int i,count;
	if (c->state==S_NONE) return;
	count=[runmodes count];
	if (c->reg_write && !c->write_pending && c->sock>=0)
	{
		for (i=0;i<count;i++)
		  [runloop removeEvent: (void *)(intptr_t)c->sock type: ET_WDESC
				forMode: [runmodes objectAtIndex: i] all: YES];
		c->reg_write=0;
	}
	else
	if (!c->reg_write && c->write_pending && c->sock>=0)
	{
		for (i=0;i<count;i++)
		  [runloop addEvent: (void *)(intptr_t)c->sock type: ET_WDESC watcher: self
				forMode: [runmodes objectAtIndex: i]];
		c->reg_write=1;
	}
}

-(void) nc_setState: (con_t *)c : (state_t)nstate
{
	if (c->state==nstate) return;
	if (c->state==S_CONNECT1 || c->state==S_CONNECT2)
		num_starting--;
	if (c->state==S_IDLE)
		num_idle--;

	if (c->state==S_NONE)
		num_active++;

	if (nstate==S_CONNECT1 || nstate==S_CONNECT2)
		num_starting++;
	if (nstate==S_IDLE)
		num_idle++;
	if (nstate==S_NONE)
		num_active--;

	c->state=nstate;
}

-(void) nc_close: (con_t *)c
{
	if (c->state==S_NONE) return;
	c->should_close=1;
	if (set_timeout==1)
	{
		set_timeout=0;
		[NSObject
			cancelPreviousPerformRequestsWithTarget: self
			selector: @selector(nc_timeout)
			object: [NSObject class]];
	}
}

-(void) nc_free: (con_t *)c
{
#ifdef DEBUG_SOCKET
	if (c->debug_write)
	{
		fclose(c->debug_write);
		c->debug_write=NULL;
	}
#endif

	if (set_timeout==1)
	{
		set_timeout=0;
		[NSObject
			cancelPreviousPerformRequestsWithTarget: self
			selector: @selector(nc_timeout)
			object: [NSObject class]];
	}

	queue_entry_clear(&c->cur);
	{
		int i,count=[runmodes count];
		for (i=0;i<count;i++)
		{
		  [runloop removeEvent: (void *)(intptr_t)c->sock type: ET_RDESC
				forMode: [runmodes objectAtIndex: i] all: YES];
		  [runloop removeEvent: (void *)(intptr_t)c->sock type: ET_WDESC
				forMode: [runmodes objectAtIndex: i] all: YES];
		  [runloop removeEvent: (void *)(intptr_t)c->sock type: ET_EDESC
				forMode: [runmodes objectAtIndex: i] all: YES];
		}
	}
	if (c->write_pending)
	{
		free(c->write_pending);
		c->write_pending=NULL;
	}
	if (c->resp_msg)
	{
		free(c->resp_msg);
		c->resp_msg=NULL;
	}
	if (c->resp_buf)
	{
		free(c->resp_buf);
		c->resp_buf=NULL;
		c->resp_buf_len=0;
	}
	if (c->sock>=0 && c->valid)
	{
		close(c->sock);
	}
	[self nc_setState: c : S_NONE];
	memset(c,0,sizeof(con_t));
	c->sock=-1;
}


-(void) nc_parseResponse: (con_t *)cn
{
	if (!cn->resp_buf_len) return;
	if (cn->resp==0)
	{ /* look for status line */
		unsigned char *b,*c,*e;
		e=cn->resp_buf+cn->resp_buf_len;
		for (c=cn->resp_buf;c<e-1;c++)
			if (c[0]=='\r' && c[1]=='\n')
				break;

		if (c==e-1) return;

		b=cn->resp_buf+3;
		if (*b==' ') b++;
		if (c>b)
		{
			cn->resp_msg=malloc(c-b+1);
			if (!cn->resp_msg)
				[NSException raise: @"NNTPServer_Error" format: @"out of memory"];
			memcpy(cn->resp_msg,b,c-b);
			cn->resp_msg[c-b]=0;
		}
		cn->resp_code=atoi((const char *)(cn->resp_buf));
		c+=2;
		if (c==e)
			cn->resp_buf_len=0;
		else
		{
			cn->resp_buf_len-=(c-cn->resp_buf);
			memmove(cn->resp_buf,c,cn->resp_buf_len);
		}
		/* status lines are probably short, so don't bother reallocating the
		buffer (we'd just end up allocating just as much on the next status
		line) */
		cn->resp=1;
	}
	else
	if (cn->resp==2)
	{ /* look for data ended by ".\r\n" alone on a line */
		unsigned char *c,*d,*e;
		c=d=cn->resp_buf+cn->resp_data_len;
		e=cn->resp_buf+cn->resp_buf_len;
		for (;c<e;c++)
		{
			if (cn->resp_data_nline && *c=='.')
			{
				if (c>e-3) break;
				if (c[1]=='\r' && c[2]=='\n')
				{ /* we have all the data */
					cn->resp=3;
					break;
				}
				cn->resp_data_nline=0;
				continue; /* skip the first period */
			}
			cn->resp_data_nline=0;
			if (cn->resp_data_len>0 && *c=='\n' && d[-1]=='\r')
			{
				d[-1]='\n';
				cn->resp_data_nline=1;
				continue;
			}
			*d++=*c;
			cn->resp_data_len++;
		}
		if (c==e)
		{ /* we ran out of data before finding the end
		  resp_buf: | resp_data_len |
		  */
			cn->resp_buf_len=cn->resp_data_len;
		}
		else
		if (cn->resp==3)
		{ /* we found the end, remove the end marker and fix the c/d gap
		  resp_buf: | resp_data_len stuff(resp_buf_len-resp_data_len) |
		  */
			c+=3;
			if (c!=e)
				memmove(d,c,e-c);
			cn->resp_buf_len-=c-d;

			cn->resp_data_len_last=0;
		}
		else
		{ /* we've found a period but can't tell if it's end of data yet (yuck)
		  resp_buf: | resp_data_len stuff(resp_buf_len-resp_data_len)
		  */
			memmove(d,c,e-c);
			cn->resp_buf_len-=c-d;
		}
	}
	if (cn->state==S_HEADER_RANGE2)
	{
		if (cn->resp_data_len>48*1024)
		{
			unsigned char **list;
			int num;
			unsigned char *b,*d,*e;

			num=0;
			/* TODO: this will be excessively large almost all the time */
			list=malloc(sizeof(unsigned char *)*(cn->cur.d.range.h-cn->cur.d.range.l+1));
			d=b=cn->resp_buf;
			/* always leave at least one byte so there will be a final
			non-partial call to nntp_headerRange:... */
			e=b+cn->resp_data_len-1;
			for (;b<e;b++)
			{
				if (*b=='\n')
				{
					list[num++]=d;
					d=b+1;
					*b=0;
				}
			}

			/* list[] is now finished, d points to the first character not
			put in the list */

#ifdef XOVER_STATS
			stat_num_headers+=num;
			stat_header_bytes+=d - cn->resp_buf;
#endif

			[rec nntp_headerRange:
			       cn->cur.d.range.group :
			       cn->cur.d.range.l : cn->cur.d.range.h : num : (char **)list
			     partial: YES
			     qid: (unsigned int)cn->cur.qid];

			free(list);

			num=d-cn->resp_buf;
			memmove(cn->resp_buf,d,cn->resp_buf_len-num);
			cn->resp_buf_len-=num;
			cn->resp_data_len-=num;
		}
	}
	else
	{
		int i,j;
		i=cn->resp_data_len/(20*1024);
		j=cn->resp_data_len_last/(20*1024);
		if (i>j)
		{
			[rec nntp_progress: cn->resp_data_len : cn->cur.qid];
			cn->resp_data_len_last=cn->resp_data_len;
		}
	}
}

-(void) nc_responseClear: (con_t *)c
{
	if (c->resp==0 || c->resp==2)
		[NSException raise: @"NNTPServer_Error" format: @"responseClear called when resp=%i",c->resp];
	if (c->resp==3)
	{
		unsigned char *b;
		c->resp_buf_len-=c->resp_data_len;
		/* data might have been large, so shrink the buffer again */
		if (c->resp_buf_len)
		{
			memmove(c->resp_buf,c->resp_buf+c->resp_data_len,c->resp_buf_len);
			b=realloc(c->resp_buf,c->resp_buf_len);
			if (b) c->resp_buf=b;
		}
		else
		{
			free(c->resp_buf);
			c->resp_buf=NULL;
		}
		c->resp_data_len=0;
	}
	c->resp=0;
	if (c->resp_msg)
		free(c->resp_msg);
	c->resp_msg=NULL;
	[self nc_parseResponse: c];
}

-(void) nc_responseWantData: (con_t *)c
{
	if (c->resp!=1)
		[NSException raise: @"NNTPServer_Error" format: @"responseWantData called when resp=%i",c->resp];
	c->resp=2;
	c->resp_data_len=0;
	c->resp_data_nline=0;
	[self nc_parseResponse: c];
}


-(void) nc_updateRead: (con_t *)c
{
	unsigned char buf[512];
	int len,ilen;
	unsigned char *b;
	/* if the socket has already been closed we're just parsing data we've already recieved */
	ilen=0;
	if (c->sock!=-1)
	{
		while ((len=read(c->sock,buf,sizeof(buf)))>0)
		{
			b=realloc(c->resp_buf,c->resp_buf_len+len);
			if (!b)
			{
				c->valid=0; /* TODO */
				[NSException raise: @"NNTPServer_Error" format: @"out of memory"];
			}
			c->resp_buf=b;
			b+=c->resp_buf_len;
			memcpy(b,buf,len);
			c->resp_buf_len+=len;
			ilen+=len;

#ifdef DEBUG_SOCKET
			{
				unsigned char b2[513];
				memcpy(b2,buf,512);
				b2[len]=0;
				fprintf(c->debug_write,"%s",b2);fflush(c->debug_write);
			}
#endif

		}

		if (len<0 && errno!=EAGAIN)
		{
			fprintf(stderr,"error reading from socket %i: %m\n",c->sock);
			c->valid=0;
			return;
		}
		if (len==0)
		{
			int i,count=[runmodes count];
			close(c->sock);
			for (i=0;i<count;i++)
			{
			  [runloop removeEvent: (void *)(intptr_t)c->sock type: ET_RDESC
					forMode: [runmodes objectAtIndex: i] all: YES];
			  [runloop removeEvent: (void *)(intptr_t)c->sock type: ET_EDESC
					forMode: [runmodes objectAtIndex: i] all: YES];
			  [runloop removeEvent: (void *)(intptr_t)c->sock type: ET_WDESC
					forMode: [runmodes objectAtIndex: i] all: YES];
			}
			c->sock=-1;
		}
		if (ilen!=0)
			[self nc_parseResponse: c];
	}
}

-(void) nc_updateWrite: (con_t *)cn
{
	const char *c;
	int len,wlen;
	if (!cn->write_pending) return;
	if (cn->sock==-1)
	{ /* TODO */
		free(cn->write_pending);
		cn->write_pending=NULL;
		cn->write_len=0;
		return;
	}
	c=cn->write_pending+cn->write_pending_ofs;
	len=cn->write_len-cn->write_pending_ofs;
	wlen=write(cn->sock,c,len);
	if (wlen<0)
	{
		if (errno==EAGAIN) return;
		fprintf(stderr,"error writing to socket %i: %m\n",cn->sock);
		cn->valid=0;
		return;
	}
	cn->write_pending_ofs+=wlen;
	if (wlen==len)
	{
		free(cn->write_pending);
		cn->write_pending=NULL;
		cn->write_len=0;
	}
}


-(void) nc_writeCommand: (con_t *)c : (const char *)cmd, ...
{
extern int vasprintf(char **c,const char *format,va_list args); /* TODO? */
	va_list va;
	char *d;
	if (c->write_pending)
	{
		abort(); /* TODO? */
	}
	if (!cmd) return;
	c->write_pending=NULL;

	va_start(va,cmd);
	vasprintf(&d,cmd,va);
	va_end(va);

	if (!d)
		[NSException raise: @"NNTPServer_Error" format: @"out of memory"];

	c->write_len=strlen(d)+2;

	d=realloc(d,c->write_len+1);
	if (!d)
		[NSException raise: @"NNTPServer_Error" format: @"out of memory"];

	c->write_pending=d;

	strcat(c->write_pending,"\r\n");
	c->write_pending_ofs=0;

#ifdef DEBUG_SOCKET
	fprintf(c->debug_write,"=C: %s",c->write_pending);fflush(c->debug_write);
#endif

	[self nc_updateWrite: c];
}

-(void) nc_writeData: (con_t *)c : (unsigned char *)data : (int)length
{
	if (c->write_pending)
	{
		abort(); /* TODO? */
	}
	c->write_pending=NULL;

	c->write_len=length;
	c->write_pending=(char *)data;
	c->write_pending_ofs=0;

#ifdef DEBUG_SOCKET
	fprintf(c->debug_write,"=C DATA||\n");
	fwrite(c->write_pending,1,c->write_len,c->debug_write);
	fprintf(c->debug_write,"||\n");fflush(c->debug_write);
#endif

	[self nc_updateWrite: c];
}


-(void) receivedEvent: (void *)data type: (RunLoopEventType) type extra: (void *)extra forMode: (NSString *)mode
{
	CREATE_AUTORELEASE_POOL(arp);
	con_t *c;
	int i,j;
//	printf("--- got event %i type %i extra %p\n",(int)data,type,extra);
	j=(intptr_t)data;
	for (i=0,c=cons;i<num_cons;i++,c++)
		if (c->sock==j)
			break;
	if (i==num_cons)
	{
		fprintf(stderr,"[NNTPServer receivedEvent] can't find connection for socket\n");
		DESTROY(arp);
		return;
	}
	if (type==ET_EDESC)
	{ /* probably eof */
		[self nc_updateRead: c];
		[self nc_updateState: c];
	}
	else
	if (type==ET_WDESC)
	{
		[self nc_updateWrite: c];
	}
	else
	if (type==ET_RDESC)
	{
		[self nc_updateRead: c];
		[self nc_updateState: c];
	}

	[self updateQueue];
	[self nc_update: c];

//	printf("--- done received\n");
#ifdef DEBUG_AUTORELEASE_COUNT
	fprintf(stderr,"receivedEvent arp contains %i objects\n",[arp autoreleaseCount]);
#endif
	DESTROY(arp);
}

-(NSDate *) timedOutEvent: (void *)data type: (RunLoopEventType) type forMode: (NSString *)mode
{ /* shouldn't happen */
	fprintf(stderr,"got timedOutEvent\n");
	return nil;
}


-(void) nc_fail: (con_t *)c
{
	[rec nntp_fail:
		[NSString stringWithFormat: @"Unexpected reply: %i %s",c->resp_code,c->resp_msg]
		qid: c->cur.qid];
}


-(int) nc_switchGroup: (con_t *)c : (int)group
{
	if (group==c->cur_group)
		return 0;
	[self nc_setState: c : S_SWITCH_GROUP];
	[self nc_writeCommand: c : "GROUP %s",group_names[group]];
	return 1;
}


-(void) nc_updateState: (con_t *)c
{
	int code;
	queue_entry_t *q;
	while (c->resp==1 || c->resp==3)
	{
		code=c->resp_code;
		q=&c->cur;

		switch (c->state)
		{
		case S_NONE:
			[rec nntp_message: @"Warning: got response in state S_NONE"];
			[self nc_responseClear: c];
			break;
		case S_IDLE:
			fprintf(stderr,"TODO handle S_IDLE  %i '%s'\n",code,c->resp_msg);
			[self nc_close: c];
			break;

		case S_QUIT:
			[rec nntp_message:
				[NSString stringWithFormat:
					_(@"Closing connection: %i %s"),
					code,c->resp_msg]];
			[self nc_free: c];
			break;

		case S_CONNECT1:
			[rec nntp_message:
				[NSString stringWithFormat: _(@"New connection (%i total): %i %s"),num_active,code,c->resp_msg]];
			[self nc_responseClear: c];
			[self nc_writeCommand: c : "MODE READER"];
			[self nc_setState: c : S_CONNECT2];
			break;
		case S_CONNECT2:
			if (/*code!=500 && */code!=200 && code!=201)
			{
				if (num_active==1)
				{
					should_connect=0; /* TODO: think hard about how this should be handled */
					[rec nntp_fail_connect:
						[NSString stringWithFormat: _(@"Unexpected response when connecting: %i %s"),code,c->resp_msg]];
				}
				else
				{
					[rec nntp_message:
						[NSString stringWithFormat: _(@"Unexpected response when connecting: %i %s"),code,c->resp_msg]];
				}
				[self nc_close: c];
				break;
			}
			[self nc_responseClear: c];
			[self nc_setState: c : S_IDLE];
			lca_delta=-1.0;
			break;

		case S_DATE:
			if (code==111)
				[rec nntp_serverDate: c->resp_msg qid: q->qid];
			else
				[self nc_fail: c];

			[self nc_responseClear: c];
			[self nc_setState: c : S_IDLE];
			queue_entry_clear(q);
			break;

		case S_GROUP:
			if (code==211)
			{ /* 211 n f l s group selected */
				int num,first,last;
				c->cur_group=q->d.group;
				if (sscanf(c->resp_msg,"%i %i %i",&num,&first,&last)==3)
					[rec nntp_groupInfo: q->d.group : num : first : last qid: q->qid];
				else
					[self nc_fail: c];
			}
			else
			if (code==411)
			{ /* 411 no such news group */
				[rec nntp_groupInfo: q->d.group : -1 : -1 : -1 qid: q->qid];
			}
			else
				[self nc_fail: c];

			[self nc_responseClear: c];
			[self nc_setState: c : S_IDLE];
			queue_entry_clear(q);
			break;

		case S_SWITCH_GROUP:
			if (code==211)
			{
				c->cur_group=q->d.group;
				[self nc_responseClear: c];
				[self nc_handleWhat: c];
			}
			else
			{
				[self nc_fail: c];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			break;

		case S_HEADER_RANGE1:
			if (code==224)
			{
				[self nc_responseWantData: c];
				[self nc_setState: c : S_HEADER_RANGE2];
			}
			else
			{
				[self nc_fail: c];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			break;
		case S_HEADER_RANGE2:
		{
			unsigned char **list;
			int num;
			unsigned char *b,*d,*e;

			num=0;
			list=malloc(sizeof(char *)*(q->d.range.h-q->d.range.l+1));
			d=b=c->resp_buf;
			e=b+c->resp_data_len;
			for (;b<e;b++)
			{
				if (*b=='\n')
				{
					list[num++]=d;
					d=b+1;
					*b=0;
				}
			}

#ifdef XOVER_STATS
			stat_num_headers+=num;
			stat_num_expected_headers+=q->d.range.h-q->d.range.l+1;
			stat_header_bytes+=c->resp_data_len;
#endif

			if (num)
			{
				[rec nntp_headerRange:
					q->d.range.group :
				       q->d.range.l : q->d.range.h : num : (char **)list
					partial: NO
				     qid: (unsigned int)q->qid];
			}

			free(list);

			[self nc_responseClear: c];
			[self nc_setState: c : S_IDLE];
			queue_entry_clear(q);
			break;
		}

		case S_HEADER_ID1:
			if (code==221)
			{
				[self nc_responseWantData: c];
				[self nc_setState: c : S_HEADER_ID2];
			}
			else
			{
				[self nc_fail: c];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			break;
		case S_HEADER_ID2:
			[rec nntp_headerId: q->d.msg.id data: c->resp_buf : c->resp_data_len qid: q->qid];
			[self nc_responseClear: c];
			[self nc_setState: c : S_IDLE];
			queue_entry_clear(q);
			break;

		case S_ARTICLE_RANGE1:
			if (code==220)
			{
				[self nc_responseWantData: c];
				[self nc_setState: c : S_ARTICLE_RANGE2];
			}
			else
			if (code==423)
			{
				[rec nntp_articleRange: q->d.range.group : q->d.range.l data: NULL:-1 qid: q->qid];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			else
			{
				[self nc_fail: c];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			break;
		case S_ARTICLE_RANGE2:
			[rec nntp_articleRange: q->d.range.group : q->d.range.l data: c->resp_buf : c->resp_data_len qid: q->qid];
			[self nc_responseClear: c];
			[self nc_setState: c : S_IDLE];
			queue_entry_clear(q);
			break;

		case S_ARTICLE_ID1:
			if (code==220)
			{
				[self nc_responseWantData: c];
				[self nc_setState: c : S_ARTICLE_ID2];
			}
			else
			if (code==430)
			{
				[rec nntp_articleId: q->d.msg.id data: NULL:-1 qid: q->qid];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			else
			{
				[self nc_fail: c];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			break;
		case S_ARTICLE_ID2:
			[rec nntp_articleId: q->d.msg.id data: c->resp_buf : c->resp_data_len qid: q->qid];
			[self nc_responseClear: c];
			[self nc_setState: c : S_IDLE];
			queue_entry_clear(q);
			break;

		case S_GROUP_LIST1:
			if (code==215)
			{
				[self nc_responseWantData: c];
				[self nc_setState: c : S_GROUP_LIST2];
			}
			else
			{
				[self nc_fail: c];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			break;
		case S_GROUP_LIST2:
			[rec nntp_groupList: c->resp_buf : c->resp_data_len qid: q->qid];
			[self nc_responseClear: c];
			[self nc_setState: c : S_IDLE];
			queue_entry_clear(q);
			break;

		case S_POST_ARTICLE1:
//			fprintf(stderr,"POST_ARTICLE1: %3i %s\n",code,c->resp_msg);
			if (code!=340)
			{
				[rec nntp_postArticle: NO qid: q->qid];
				[self nc_fail: c];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			else
			{
				[self nc_responseClear: c];
				[self nc_writeData: c : q->d.post.data : q->d.post.length];
				q->d.post.data=NULL;
				q->d.post.length=0;
				[self nc_setState: c : S_POST_ARTICLE2];
			}
			break;
		case S_POST_ARTICLE2:
//			fprintf(stderr,"POST_ARTICLE2: %3i %s\n",code,c->resp_msg);
			if (code==240)
			{
				[rec nntp_postArticle: YES qid: q->qid];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			else
			{
				[rec nntp_postArticle: NO qid: q->qid]; /* TODO: really do this here? */
				[self nc_fail: c];
				[self nc_responseClear: c];
				[self nc_setState: c : S_IDLE];
				queue_entry_clear(q);
			}
			break;

		default:
			fprintf(stderr,"unknown state %i\n",c->state);
			abort();
			break;
		}
	}
}

-(void) nc_handleWhat: (con_t *)c
{
	queue_entry_t *q=&c->cur;
	switch (q->what)
	{
	case WHAT_DATE:
		[self nc_setState: c : S_DATE];
		[self nc_writeCommand: c : "DATE"];
		break;

	case WHAT_GROUP_INFO:
		[self nc_setState: c : S_GROUP];
		[self nc_writeCommand: c : "GROUP %s", group_names[q->d.group]];
		break;

	case WHAT_HEADER_RANGE:
		if ([self nc_switchGroup: c : q->d.range.group])
			break;
		[self nc_setState: c : S_HEADER_RANGE1];
		[self nc_writeCommand: c : "XOVER %i-%i",q->d.range.l,q->d.range.h];
		break;

	case WHAT_HEADER_ID:
		[self nc_setState: c : S_HEADER_ID1];
		[self nc_writeCommand: c : "HEAD %s",q->d.msg.id];
		break;

	case WHAT_ARTICLE_RANGE:
		if ([self nc_switchGroup: c : q->d.range.group])
			break;
		[self nc_setState: c : S_ARTICLE_RANGE1];
		[self nc_writeCommand: c : "ARTICLE %i",q->d.range.l];
		break;

	case WHAT_ARTICLE_ID:
		[self nc_setState: c : S_ARTICLE_ID1];
		[self nc_writeCommand: c : "ARTICLE %s",q->d.msg.id];
		break;

	case WHAT_GROUP_LIST:
		[self nc_setState: c : S_GROUP_LIST1];
		[self nc_writeCommand: c : "LIST"];
		break;

	case WHAT_POST_ARTICLE:
		[self nc_setState: c : S_POST_ARTICLE1];
		[self nc_writeCommand: c : "POST"];
		break;

	default:
		fprintf(stderr,"unhandled q->what %i\n",q->what);
		break;
	}
}


-(void) nc_timeout
{
	int i;
	con_t *c;
//	printf("timing out, closing one at %30.15g\n",Now());
	for (i=0,c=cons;i<num_cons;i++,c++)
		if (c->state==S_IDLE)
			break;
	if (i==num_cons)
	{
		for (i=0,c=cons;i<num_cons;i++,c++)
			if (c->state!=S_NONE)
				break;
	}
	set_timeout=0;
	if (i!=num_cons)
		[self nc_close: c];
	[self updateQueue];
}


-(void) updateQueue
{
	queue_entry_t *q;
	int i;
	int num_closing;
	int cur_work;
	int active;
	con_t *c;

//	fprintf(stderr," --- update: %i/%i/%i ---\n",num_idle,num_active,num_cons);

	for (c=cons,i=0;i<num_cons;i++,c++)
	{
		if (c->state!=S_IDLE)
			continue;
		if (c->should_close)
		{
			[self nc_writeCommand: c : "QUIT"];
			[self nc_setState: c : S_QUIT];
			[self nc_update: c];
			continue;
		}
		q=queue_get(queue);
		if (!q) continue;
/*		printf("%i in queue\n",queue->qe_num);
		printf("got pri %i what %i on %i/%i (p %i %i %i)\n",
			q->priority,q->what,i,c->sock,
			q->d.range.group,q->d.range.l,q->d.range.h);*/
		c->cur=*q;
		if (q->what==WHAT_ARTICLE_RANGE)
		{
			c->cur.d.range.h=c->cur.d.range.l;
			q->d.range.l++;
			queue->total_work-=ESTIMATED_MSG_SIZE; /* TODO: yuck */
			if (q->d.range.l>q->d.range.h)
				queue_delete_max(queue);
		}
		else
		{
			queue_delete_max(queue);
		}
		[self nc_handleWhat: c];
		[self nc_update: c];
	}

	num_closing=0;
	cur_work=0;
	for (i=0,c=cons;i<num_cons;i++,c++)
	{
		if (c->state!=S_NONE && (c->should_close || c->state==S_QUIT))
			num_closing++;
		if (c->state!=S_NONE && c->state!=S_IDLE && c->state!=S_QUIT)
			cur_work+=queue_work(&c->cur);
	}

	cur_work+=queue->total_work;

	if (num_active-num_closing>0)
		active=cur_work>work_limits[num_active-1-num_closing].work_limit;
	else
		active=!!cur_work;

/*	fprintf(stderr,"work=%i %i  active=%i  num_closing=%i\n",queue->total_work,cur_work,active,num_closing);

	fprintf(stderr,"%i %i %i %i\n",active,should_connect,
		Now()>lca_delta+last_connect_attempt,queue->total_work>work_limits[num_active].work_limit);

	fprintf(stderr,"update queue: approx. %i bytes left\n",queue->total_work);*/

	if (
		active && should_connect &&
		num_active<num_cons && !num_starting &&
		Now()>lca_delta+last_connect_attempt &&
		cur_work>work_limits[num_active].work_limit &&
		queue->qe_num>num_active
	   )
	{
		for (i=0,c=cons;i<num_cons;i++,c++)
			if (c->state==S_NONE)
				break;
//		printf("opening new\n");
		last_connect_attempt=Now();
		if ([self nc_connect: c])
		{
			lca_delta=15.0;
		}
		else
		{
			if (!num_active)
			{
				should_connect=0;
				[rec nntp_fail_connect: last_error];
			}
			else
			{
				if (!lca_delta)
					lca_delta=15.0;
				else
				if (lca_delta>90.0)
					lca_delta=90.0;
				else
					lca_delta+=15.0;
			}
		}
	}

	if (!active && (num_active-num_closing) && set_timeout==0)
	{
//		last_activity=Now();
		[self
			performSelector: @selector(nc_timeout)
			withObject: [NSObject class]
			afterDelay: work_limits[num_active-1-num_closing].time_limit];
		set_timeout=1;
	}
	else
	if (active && set_timeout==1)
	{
		set_timeout=0;
		[NSObject
			cancelPreviousPerformRequestsWithTarget: self
			selector: @selector(nc_timeout)
			object: [NSObject class]];
	}

//	printf("done update\n");

#ifdef DEBUG_SCHEDULER
	[self _updateDebugScheduler];
#endif
}

@end


@implementation NNTPServer


+(int) getGroupNum: (const char *)group;
{
	int i;
	char *c,**l;
	if (!group_names)
	{
		group_names=malloc(sizeof(char *));
		if (!group_names) return -1;
		num_group_names=1;
		group_names[0]=NULL;
	}
	for (i=1;i<num_group_names;i++)
		if (!strcasecmp(group,group_names[i]))
			return i;
	c=strdup(group);
	if (!c) return -1; /* TODO? */
	l=realloc(group_names,sizeof(char *)*(num_group_names+1));
	if (!l) return -1;
	group_names=l;
	group_names[i=num_group_names++]=c;
	return i;
}


+(const char *) getGroupName: (int)group
{
	if (group<1 || group>=num_group_names)
		return NULL;
	return group_names[group];
}


-init
{
	return [self initWithHost: "localhost"];
}

-initWithHost: (const char *)ahost
{
	return [self initWithHost: ahost port: -1];
}

-initWithHost: (const char *)ahost  port: (int)aport
{
	self=[super init];
	if (!self) return nil;
	host=strdup(ahost);
	if (!host)
		[NSException raise: @"NNTPServer_Error" format: @"out of memory"];
	port=aport;
	protocol=-1;
	have_addr=0;

	return [self setup];
}


-initWithAddr: (struct sockaddr_in *)aaddr  port: (int)aport  host: (const char *)ahost
{
	self=[super init];
	if (!self) return nil;

	if (host)
		host=strdup(ahost);
	else
		host=strdup("<unknown>");
	if (!host)
		[NSException raise: @"NNTPServer_Error" format: @"out of memory"];
	port=aport;
	protocol=-1;
	have_addr=1;
	addr=*aaddr;

	return [self setup];
}


-(void) dealloc
{
#ifdef XOVER_STATS
	printf("got %i/%i headers, %i bytes, %g bytes/msg\n",
		stat_num_headers,stat_num_expected_headers,stat_header_bytes,
		stat_header_bytes/(double)stat_num_headers);
#endif
	[self killAllConnections];
	DESTROY(runloop);
	DESTROY(runmodes);
	DESTROY(last_error);
	free(host);
	free(cons);
	queue_free(queue);
	[super dealloc];
}


-(void) closeAllConnections
{
	int i;
	con_t *c;
	for (c=cons,i=0;i<num_cons;i++,c++)
		[self nc_close: c];
	[self updateQueue];
}


-(void) killAllConnections
{
	int i;
	con_t *c;
	for (c=cons,i=0;i<num_cons;i++,c++)
		[self nc_free: c];
}


-(void) setReceiver: (id<NNTPServer_Receiver,NSObject>)arec;
{
	rec=arec;
}

-(void) enableConnect: (int)c
{
	should_connect=c;
	if (c) lca_delta=-1.0;
	[self updateQueue];
}

-(void) enableTimeout: (int)t
{
	if (t)
	{
		set_timeout=0;
	}
	else
	{
		if (set_timeout==1)
		{
			[NSObject
				cancelPreviousPerformRequestsWithTarget: self
				selector: @selector(nc_timeout)
				object: [NSObject class]];
		}
		set_timeout=-1;
	}
}


-(unsigned int) queueAdd: (queue_entry_t *)q : (int)priority
{
	unsigned int qid;
	qid=queue_add(queue,priority,q);
	[self updateQueue];
	return qid;
}

-(BOOL) cancelQid: (unsigned int)qid  kill: (BOOL)kill
{
	int i;
	queue_entry_t *qe;

	for (qe=queue->qe+1,i=0;i<queue->qe_num;i++,qe++)
	{
		if (qe->qid==qid)
		{
			queue_remove(queue,qe);
			[self updateQueue];
			return YES;
		}
	}
	if (kill)
	{
		fprintf(stderr,"[NNTPServer -cancelQid: kill: YES] not implemented!\n");
	}
	return NO;
}


-(unsigned int) getServerDate
{
	queue_entry_t q;
	q.what=WHAT_DATE;
	return [self queueAdd: &q : 0];
}

-(unsigned int) getGroupInfo: (int)group
{
	queue_entry_t q;
	q.what=WHAT_GROUP_INFO;
	q.d.group=group;
	return [self queueAdd: &q : 0];
}

-(unsigned int) getHeaderRange: (int)low : (int)high  group: (int)group  priority: (int)pri
{
	queue_entry_t q;
	q.what=WHAT_HEADER_RANGE;
	q.d.range.group=group;
	q.d.range.l=low;
	q.d.range.h=high;
	return [self queueAdd: &q : pri];
}

-(unsigned int) getHeaderById: (const char *)msg_id  priority: (int)pri
{
	queue_entry_t q;
	q.what=WHAT_HEADER_ID;
	q.d.msg.id=strdup(msg_id); /* TODO: handle error */
	return [self queueAdd: &q : pri];
}

-(unsigned int) getArticleRange: (int)low : (int)high  group: (int)group  priority: (int)pri
{
	queue_entry_t q;
	q.what=WHAT_ARTICLE_RANGE;
	q.d.range.group=group;
	q.d.range.l=low;
	q.d.range.h=high;
	return [self queueAdd: &q : pri];
}

-(unsigned int) getArticleById: (const char *)msg_id  priority: (int)pri
{
	queue_entry_t q;
	q.what=WHAT_ARTICLE_ID;
	q.d.msg.id=strdup(msg_id); /* TODO: handle error */
	q.d.msg.bytes=1000;
	return [self queueAdd: &q : pri];
}

-(unsigned int) getArticleById: (const char *)msg_id  size: (int)bytes  priority: (int)pri
{
	queue_entry_t q;
	q.what=WHAT_ARTICLE_ID;
	q.d.msg.id=strdup(msg_id); /* TODO: handle error */
	q.d.msg.bytes=bytes;
	return [self queueAdd: &q : pri];
}

-(unsigned int) getGroupList: (int)priority
{
	queue_entry_t q;
	q.what=WHAT_GROUP_LIST;
	return [self queueAdd: &q : priority];
}


-(unsigned int) postArticle: (unsigned char *)data  length: (int)length  priority: (int)priority
{
	queue_entry_t q;
	unsigned char *b,*c,*dst;
	int i,j;

	q.what=WHAT_POST_ARTICLE;

	for (b=data,i=length,j=0;i;b++,i--)
		if (b[0]=='\n')
		{
			j++;
			if (i>0 && b[1]=='.') j++;
		}
	j+=length;
	j+=5;

	dst=malloc(j);
	if (!dst) abort(); /* TODO: handle error */
	for (b=data,c=dst,i=length;i;i--)
	{
		if (b[0]=='\n')
			*c++='\r';
		*c++=*b++;
		if (i>1 && b[-1]=='\n' && b[0]=='.')
			*c++='.';
	}
	*c++='\r';
	*c++='\n';
	*c++='.';
	*c++='\r';
	*c++='\n';

	q.d.post.data=dst;
	q.d.post.length=j;

	return [self queueAdd: &q : priority];
}


-(NSString *)qidDescription: (unsigned int)qid
{
	int i;
	queue_entry_t *q=NULL;

	for (i=0;i<num_cons;i++)
		if (cons[i].cur.qid==qid)
		{
			q=&cons[i].cur;
			break;
		}

	if (!q)
	{
		for (q=queue->qe+1,i=0;i<queue->qe_num;i++,q++)
			if (q->qid==qid)
				break;
		if (i==queue->qe_num)
			q=NULL;
	}

	if (!q)
		return [NSString stringWithFormat: @"qid %i",qid];

	switch (q->what)
	{
	default: return [NSString stringWithFormat: @"qid %i %i",qid,q->what];

	case WHAT_NONE: return @"NONE";
	case WHAT_DATE: return @"DATE";
	case WHAT_GROUP_INFO:
		return [NSString stringWithFormat: @"GROUP_INFO %s",group_names[q->d.group]];

	case WHAT_HEADER_RANGE:
		return [NSString stringWithFormat:
			@"HEADER_RANGE %s %i-%i",
			group_names[q->d.range.group],q->d.range.l,q->d.range.h];
	case WHAT_HEADER_ID:
		return [NSString stringWithFormat: @"HEADER_ID %s",q->d.msg.id];

	case WHAT_ARTICLE_RANGE:
		return [NSString stringWithFormat:
			@"ARTICLE_RANGE %s %i-%i",
			group_names[q->d.range.group],q->d.range.l,q->d.range.h];
	case WHAT_ARTICLE_ID:
		return [NSString stringWithFormat: @"ARTICLE_ID %s",q->d.msg.id];

	case WHAT_GROUP_LIST:
		return @"GROUP_LIST";

	case WHAT_POST_ARTICLE:
		return @"POST_ARTICLE";
	}
}


@end


#ifdef DEBUG_SCHEDULER

#include <AppKit/NSWindow.h>
#include <AppKit/NSTextView.h>
#include <AppKit/NSFont.h>
#include <AppKit/NSTextContainer.h>

static NSTextView *ds_tv;
static NNTPServer *ds_server;
static FILE *f;
static NSString *last_string;

@implementation NNTPServer (debug_scheduler)
-(void) _updateDebugScheduler
{
	NSMutableString *s;
	int i;
	con_t *c;
	queue_entry_t *qe;
	if (!ds_tv)
	{
		NSWindow *win;
		if (!queue->qe_num && !num_active) return;
		win=[[NSWindow alloc] initWithContentRect: NSMakeRect(10,64,500,500)
			styleMask: NSClosableWindowMask|NSTitledWindowMask|NSResizableWindowMask|NSMiniaturizableWindowMask
			backing: NSBackingStoreRetained
			defer: YES];

		ds_tv=[[NSTextView alloc] init];
		[ds_tv setFont: [NSFont userFixedPitchFontOfSize: 0]];
		[ds_tv setEditable: NO];
		[[ds_tv textContainer] setWidthTracksTextView: YES];
		[[ds_tv textContainer] setHeightTracksTextView: NO];
		[[ds_tv textContainer] setContainerSize: NSMakeSize(1e6,1e6)];
		[win setContentView: ds_tv];
		RELEASE(ds_tv);
		ds_server=self;
		[win setTitle: @"NNTPServer debug"];
		[win orderFront: self];
		printf("created window: %p\n",win);

		f=fopen("debug_sched.txt","at");
	}
	if (ds_server!=self) return;
	s=[[NSMutableString alloc] init];
	[s appendString: [NSString stringWithFormat: @"num=%i idle=%i active=%i starting=%i\n\n",
		num_cons,num_idle,num_active,num_starting]];
	for (i=0,c=cons;i<num_cons;i++,c++)
	{
static const char * const state_name[]={
"S_NONE",
"S_IDLE",
"S_CONNECT1",
"S_CONNECT2",
"S_QUIT",
"S_DATE",
"S_GROUP",
"S_SWITCH_GROUP",
"S_HEADER_RANGE1",
"S_HEADER_RANGE2",
"S_HEADER_ID1",
"S_HEADER_ID2",
"S_ARTICLE_RANGE1",
"S_ARTICLE_RANGE2",
"S_ARTICLE_ID1",
"S_ARTICLE_ID2",
"S_GROUP_LIST1",
"S_GROUP_LIST2",
"S_POST_ARTICLE1",
"S_POST_ARTICLE2"};

		[s appendString: [NSString stringWithFormat:
			@"c%i: %i %i: wr %i %i: resp=%i %i %s\n"
			@"  buf=%i data=%i\n"
			@"  state=%i %s\n"
			@"  group=%i close=%i reg=%i\n"
			@"  cur=%3i %@\n\n",
			i,c->valid,c->sock,
			c->write_len,c->write_pending_ofs,
			c->resp,c->resp_code,c->resp_msg,
			c->resp_buf_len,c->resp_data_len,
			c->state,state_name[c->state],
			c->cur_group,c->should_close,c->reg_write,
			c->cur.priority,[self qidDescription: c->cur.qid]]];
	}
	for (i=1,qe=queue->qe+1;i<=queue->qe_num;i++,qe++)
	{
		[s appendString: [NSString stringWithFormat:
			@"%3i: %3i %@\n",qe->qid,qe->priority,[self qidDescription: qe->qid]]];
	}
	[ds_tv setString: s];

	if ([s isEqual: last_string])
	{
		DESTROY(s);
	}
	else
	{
		fputs("----\n",f);
		fputs([s cString],f);
		fflush(f);
		DESTROY(last_string);
		last_string=s;
	}
}
@end
#endif