summaryrefslogtreecommitdiff
path: root/mailnews/news/src/nsNNTPProtocol.cpp
blob: 035dff6e6f0a6f97ff308ace955a46470f38c6a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "msgCore.h"    // precompiled header...
#include "MailNewsTypes.h"
#include "nntpCore.h"
#include "nsNetUtil.h"
#include "nsIMsgMailNewsUrl.h"
#include "nsIMsgHdr.h"
#include "nsNNTPProtocol.h"
#include "nsINNTPArticleList.h"
#include "nsIOutputStream.h"
#include "nsIMemory.h"
#include "nsIPipe.h"
#include "nsCOMPtr.h"
#include "nsMsgI18N.h"
#include "nsINNTPNewsgroupPost.h"
#include "nsMsgBaseCID.h"
#include "nsMsgNewsCID.h"

#include "nsINntpUrl.h"
#include "prmem.h"
#include "prtime.h"
#include "mozilla/Logging.h"
#include "prerror.h"
#include "nsStringGlue.h"
#include "mozilla/Attributes.h"
#include "mozilla/Services.h"
#include "mozilla/mailnews/MimeHeaderParser.h"

#include "prprf.h"

/* include event sink interfaces for news */

#include "nsIMsgSearchSession.h"
#include "nsIMsgSearchAdapter.h"
#include "nsIMsgStatusFeedback.h"

#include "nsMsgKeySet.h"

#include "nsNewsUtils.h"
#include "nsMsgUtils.h"

#include "nsIMsgIdentity.h"
#include "nsIMsgAccountManager.h"

#include "nsIPrompt.h"
#include "nsIMsgStatusFeedback.h"

#include "nsIMsgFolder.h"
#include "nsIMsgNewsFolder.h"
#include "nsIDocShell.h"

#include "nsIMsgFilterList.h"

// for the memory cache...
#include "nsICacheEntry.h"
#include "nsICacheStorage.h"
#include "nsIApplicationCache.h"
#include "nsIStreamListener.h"
#include "nsNetCID.h"

#include "nsIPrefBranch.h"
#include "nsIPrefService.h"

#include "nsIMsgWindow.h"
#include "nsIWindowWatcher.h"

#include "nsINntpService.h"
#include "nntpCore.h"
#include "nsIStreamConverterService.h"
#include "nsIStreamListenerTee.h"
#include "nsISocketTransport.h"
#include "nsIArray.h"
#include "nsArrayUtils.h"

#include "nsIInputStreamPump.h"
#include "nsIProxyInfo.h"
#include "nsContentSecurityManager.h"

#include <time.h>

#undef GetPort  // XXX Windows!
#undef SetPort  // XXX Windows!
#undef PostMessage // avoid to collision with WinUser.h

#define PREF_NEWS_CANCEL_CONFIRM  "news.cancel.confirm"
#define PREF_NEWS_CANCEL_ALERT_ON_SUCCESS "news.cancel.alert_on_success"
#define READ_NEWS_LIST_COUNT_MAX 500 /* number of groups to process at a time when reading the list from the server */
#define READ_NEWS_LIST_TIMEOUT 50  /* uSec to wait until doing more */
#define RATE_STR_BUF_LEN 32
#define UPDATE_THRESHHOLD 25600 /* only update every 25 KB */

using namespace mozilla::mailnews;
using namespace mozilla;

// NNTP extensions are supported yet
// until the extension code is ported,
// we'll skip right to the first nntp command
// after doing "mode reader"
// and "pushed" authentication (if necessary),
//#define HAVE_NNTP_EXTENSIONS

// quiet compiler warnings by defining these function prototypes
char *MSG_UnEscapeSearchUrl (const char *commandSpecificData);

/* Logging stuff */

PRLogModuleInfo* NNTP = NULL;
#define out     LogLevel::Info

#define NNTP_LOG_READ(buf) \
if (NNTP==NULL) \
    NNTP = PR_NewLogModule("NNTP"); \
MOZ_LOG(NNTP, out, ("(%p) Receiving: %s", this, buf)) ;

#define NNTP_LOG_WRITE(buf) \
if (NNTP==NULL) \
    NNTP = PR_NewLogModule("NNTP"); \
MOZ_LOG(NNTP, out, ("(%p) Sending: %s", this, buf)) ;

#define NNTP_LOG_NOTE(buf) \
if (NNTP==NULL) \
    NNTP = PR_NewLogModule("NNTP"); \
MOZ_LOG(NNTP, out, ("(%p) %s",this, buf)) ;

const char *const stateLabels[] = {
"NNTP_RESPONSE",
#ifdef BLOCK_UNTIL_AVAILABLE_CONNECTION
"NNTP_BLOCK_UNTIL_CONNECTIONS_ARE_AVAILABLE",
"NNTP_CONNECTIONS_ARE_AVAILABLE",
#endif
"NNTP_CONNECT",
"NNTP_CONNECT_WAIT",
"NNTP_LOGIN_RESPONSE",
"NNTP_SEND_MODE_READER",
"NNTP_SEND_MODE_READER_RESPONSE",
"SEND_LIST_EXTENSIONS",
"SEND_LIST_EXTENSIONS_RESPONSE",
"SEND_LIST_SEARCHES",
"SEND_LIST_SEARCHES_RESPONSE",
"NNTP_LIST_SEARCH_HEADERS",
"NNTP_LIST_SEARCH_HEADERS_RESPONSE",
"NNTP_GET_PROPERTIES",
"NNTP_GET_PROPERTIES_RESPONSE",
"SEND_LIST_SUBSCRIPTIONS",
"SEND_LIST_SUBSCRIPTIONS_RESPONSE",
"SEND_FIRST_NNTP_COMMAND",
"SEND_FIRST_NNTP_COMMAND_RESPONSE",
"SETUP_NEWS_STREAM",
"NNTP_BEGIN_AUTHORIZE",
"NNTP_AUTHORIZE_RESPONSE",
"NNTP_PASSWORD_RESPONSE",
"NNTP_READ_LIST_BEGIN",
"NNTP_READ_LIST",
"DISPLAY_NEWSGROUPS",
"NNTP_NEWGROUPS_BEGIN",
"NNTP_NEWGROUPS",
"NNTP_BEGIN_ARTICLE",
"NNTP_READ_ARTICLE",
"NNTP_XOVER_BEGIN",
"NNTP_FIGURE_NEXT_CHUNK",
"NNTP_XOVER_SEND",
"NNTP_XOVER_RESPONSE",
"NNTP_XOVER",
"NEWS_PROCESS_XOVER",
"NNTP_XHDR_SEND",
"NNTP_XHDR_RESPONSE",
"NNTP_READ_GROUP",
"NNTP_READ_GROUP_RESPONSE",
"NNTP_READ_GROUP_BODY",
"NNTP_SEND_GROUP_FOR_ARTICLE",
"NNTP_SEND_GROUP_FOR_ARTICLE_RESPONSE",
"NNTP_SEND_ARTICLE_NUMBER",
"NEWS_PROCESS_BODIES",
"NNTP_PRINT_ARTICLE_HEADERS",
"NNTP_SEND_POST_DATA",
"NNTP_SEND_POST_DATA_RESPONSE",
"NNTP_CHECK_FOR_MESSAGE",
"NEWS_START_CANCEL",
"NEWS_DO_CANCEL",
"NNTP_XPAT_SEND",
"NNTP_XPAT_RESPONSE",
"NNTP_SEARCH",
"NNTP_SEARCH_RESPONSE",
"NNTP_SEARCH_RESULTS",
"NNTP_LIST_PRETTY_NAMES",
"NNTP_LIST_PRETTY_NAMES_RESPONSE",
"NNTP_LIST_XACTIVE_RESPONSE",
"NNTP_LIST_XACTIVE",
"NNTP_LIST_GROUP",
"NNTP_LIST_GROUP_RESPONSE",
"NEWS_DONE",
"NEWS_POST_DONE",
"NEWS_ERROR",
"NNTP_ERROR",
"NEWS_FREE",
"NNTP_SUSPENDED"
};


/* end logging */

/* Forward declarations */

#define LIST_WANTED     0
#define ARTICLE_WANTED  1
#define CANCEL_WANTED   2
#define GROUP_WANTED    3
#define NEWS_POST       4
#define NEW_GROUPS      5
#define SEARCH_WANTED   6
#define IDS_WANTED      7

/* the output_buffer_size must be larger than the largest possible line
 * 2000 seems good for news
 *
 * jwz: I increased this to 4k since it must be big enough to hold the
 * entire button-bar HTML, and with the new "mailto" format, that can
 * contain arbitrarily long header fields like "references".
 *
 * fortezza: proxy auth is huge, buffer increased to 8k (sigh).
 */
#define OUTPUT_BUFFER_SIZE (4096*2)

/* the amount of time to subtract from the machine time
 * for the newgroup command sent to the nntp server
 */
#define NEWGROUPS_TIME_OFFSET 60L*60L*12L   /* 12 hours */

////////////////////////////////////////////////////////////////////////////////////////////
// TEMPORARY HARD CODED FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////////
#define NET_IS_SPACE(x) ((x)==' ' || (x)=='\t')

// turn "\xx" (with xx being hex numbers) in string into chars
char *MSG_UnEscapeSearchUrl (const char *commandSpecificData)
{
  nsAutoCString result(commandSpecificData);
  int32_t slashpos = 0;
  while (slashpos = result.FindChar('\\', slashpos),
         slashpos != kNotFound)
  {
    nsAutoCString hex;
    hex.Assign(Substring(result, slashpos + 1, 2));
    int32_t ch;
    nsresult rv;
    ch = hex.ToInteger(&rv, 16);
    result.Replace(slashpos, 3, NS_SUCCEEDED(rv) && ch != 0 ? (char) ch : 'X');
    slashpos++;
  }
  return ToNewCString(result);
}

////////////////////////////////////////////////////////////////////////////////////////////
// END OF TEMPORARY HARD CODED FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////////

NS_IMPL_ISUPPORTS_INHERITED(nsNNTPProtocol, nsMsgProtocol, nsINNTPProtocol,
  nsITimerCallback, nsICacheEntryOpenCallback, nsIMsgAsyncPromptListener)

nsNNTPProtocol::nsNNTPProtocol(nsINntpIncomingServer *aServer, nsIURI *aURL,
                               nsIMsgWindow *aMsgWindow)
: nsMsgProtocol(aURL),
  m_connectionBusy(false),
  m_nntpServer(aServer)
{
  if (!NNTP)
    NNTP = PR_NewLogModule("NNTP");

  m_ProxyServer = nullptr;
  m_responseText = nullptr;
  m_dataBuf = nullptr;

  m_key = nsMsgKey_None;

  mBytesReceived = 0;
  mBytesReceivedSinceLastStatusUpdate = 0;
  m_startTime = PR_Now();

  if (aMsgWindow) {
    m_msgWindow = aMsgWindow;
  }

  m_runningURL = nullptr;
  m_fromCache = false;
  MOZ_LOG(NNTP, LogLevel::Info,("(%p) creating",this));
  MOZ_LOG(NNTP, LogLevel::Info,("(%p) initializing, so unset m_currentGroup",this));
  m_currentGroup.Truncate();
  m_lastActiveTimeStamp = 0;
}

nsNNTPProtocol::~nsNNTPProtocol()
{
  MOZ_LOG(NNTP, LogLevel::Info,("(%p) destroying",this));
  if (m_nntpServer) {
    m_nntpServer->WriteNewsrcFile();
    m_nntpServer->RemoveConnection(this);
  }
  if (mUpdateTimer) {
    mUpdateTimer->Cancel();
    mUpdateTimer = nullptr;
  }
  Cleanup();
}

void nsNNTPProtocol::Cleanup()  //free char* member variables
{
  PR_FREEIF(m_responseText);
  PR_FREEIF(m_dataBuf);
}

NS_IMETHODIMP nsNNTPProtocol::Initialize(nsIURI *aURL, nsIMsgWindow *aMsgWindow)
{
  if (aMsgWindow) {
    m_msgWindow = aMsgWindow;
  }
  nsMsgProtocol::InitFromURI(aURL);

  nsCOMPtr<nsIMsgIncomingServer> server = do_QueryInterface(m_nntpServer);
  NS_ASSERTION(m_nntpServer, "nsNNTPProtocol need an m_nntpServer.");
  NS_ENSURE_TRUE(m_nntpServer, NS_ERROR_UNEXPECTED);

  nsresult rv = m_nntpServer->GetMaxArticles(&m_maxArticles);
  NS_ENSURE_SUCCESS(rv, rv);

  int32_t socketType;
  rv = server->GetSocketType(&socketType);
  NS_ENSURE_SUCCESS(rv, rv);

  int32_t port = 0;
  rv = m_url->GetPort(&port);
  if (NS_FAILED(rv) || (port<=0)) {
    rv = server->GetPort(&port);
    NS_ENSURE_SUCCESS(rv, rv);

    if (port<=0) {
      port = (socketType == nsMsgSocketType::SSL) ?
             nsINntpUrl::DEFAULT_NNTPS_PORT : nsINntpUrl::DEFAULT_NNTP_PORT;
    }

    rv = m_url->SetPort(port);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  NS_PRECONDITION(m_url, "invalid URL passed into NNTP Protocol");

  m_runningURL = do_QueryInterface(m_url, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  SetIsBusy(true);

  nsCString group;

  // Initialize m_newsAction before possible use in ParseURL method
  m_runningURL->GetNewsAction(&m_newsAction);

  // parse url to get the msg folder and check if the message is in the folder's
  // local cache before opening a new socket and trying to download the message
  rv = ParseURL(m_url, group, m_messageID);

  if (NS_SUCCEEDED(rv) && m_runningURL)
  {
    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(m_runningURL);
    if (mailnewsUrl)
    {
      if (aMsgWindow)
        mailnewsUrl->SetMsgWindow(aMsgWindow);

      if (m_newsAction == nsINntpUrl::ActionFetchArticle || m_newsAction == nsINntpUrl::ActionFetchPart
          || m_newsAction == nsINntpUrl::ActionSaveMessageToDisk)
      {
        // Look for the content length
        nsCOMPtr<nsIMsgMessageUrl> msgUrl(do_QueryInterface(m_runningURL));
        if (msgUrl)
        {
          nsCOMPtr<nsIMsgDBHdr> msgHdr;
          msgUrl->GetMessageHeader(getter_AddRefs(msgHdr));
          if (msgHdr)
          {
            // Note that for attachments, the messageSize is going to be the
            // size of the entire message
            uint32_t messageSize;
            msgHdr->GetMessageSize(&messageSize);
            SetContentLength(messageSize);
          }
        }

        bool msgIsInLocalCache = false;
        mailnewsUrl->GetMsgIsInLocalCache(&msgIsInLocalCache);
        if (msgIsInLocalCache || WeAreOffline())
          return NS_OK; // probably don't need to do anything else - definitely don't want
        // to open the socket.
      }
    }
  }
  else {
    return rv;
  }

  if (!m_socketIsOpen)
  {
    // When we are making a secure connection, we need to make sure that we
    // pass an interface requestor down to the socket transport so that PSM can
    // retrieve a nsIPrompt instance if needed.
    nsCOMPtr<nsIInterfaceRequestor> ir;
    if (socketType != nsMsgSocketType::plain && aMsgWindow)
    {
      nsCOMPtr<nsIDocShell> docShell;
      aMsgWindow->GetRootDocShell(getter_AddRefs(docShell));
      ir = do_QueryInterface(docShell);
    }

    // call base class to set up the transport

    int32_t port = 0;
    nsCString hostName;
    m_url->GetPort(&port);

    rv = server->GetRealHostName(hostName);
    NS_ENSURE_SUCCESS(rv, rv);

    MOZ_LOG(NNTP,  LogLevel::Info, ("(%p) opening connection to %s on port %d",
      this, hostName.get(), port));

    nsCOMPtr<nsIProxyInfo> proxyInfo;
    rv = MsgExamineForProxy(this, getter_AddRefs(proxyInfo));
    if (NS_FAILED(rv)) proxyInfo = nullptr;

    rv = OpenNetworkSocketWithInfo(hostName.get(), port,
           (socketType == nsMsgSocketType::SSL) ? "ssl" : nullptr,
           proxyInfo, ir);

    NS_ENSURE_SUCCESS(rv,rv);
    m_nextState = NNTP_LOGIN_RESPONSE;
  }
  else {
    m_nextState = SEND_FIRST_NNTP_COMMAND;
  }
  m_dataBuf = (char *) PR_Malloc(sizeof(char) * OUTPUT_BUFFER_SIZE);
  m_dataBufSize = OUTPUT_BUFFER_SIZE;

  if (!m_lineStreamBuffer)
    m_lineStreamBuffer = new nsMsgLineStreamBuffer(OUTPUT_BUFFER_SIZE, true /* create new lines */);

  m_typeWanted = 0;
  m_responseCode = 0;
  m_previousResponseCode = 0;
  m_responseText = nullptr;

  m_firstArticle = 0;
  m_lastArticle = 0;
  m_firstPossibleArticle = 0;
  m_lastPossibleArticle = 0;
  m_numArticlesLoaded = 0;
  m_numArticlesWanted = 0;

  m_key = nsMsgKey_None;

  m_articleNumber = 0;
  m_originalContentLength = 0;
  m_cancelID.Truncate();
  m_cancelFromHdr.Truncate();
  m_cancelNewsgroups.Truncate();
  m_cancelDistribution.Truncate();
  return NS_OK;
}

NS_IMETHODIMP nsNNTPProtocol::GetIsBusy(bool *aIsBusy)
{
  NS_ENSURE_ARG_POINTER(aIsBusy);
  *aIsBusy = m_connectionBusy;
  return NS_OK;
}

NS_IMETHODIMP nsNNTPProtocol::SetIsBusy(bool aIsBusy)
{
  MOZ_LOG(NNTP, LogLevel::Info,("(%p) setting busy to %d",this, aIsBusy));
  m_connectionBusy = aIsBusy;
  
  // Maybe we could load another URI.
  if (!aIsBusy && m_nntpServer)
    m_nntpServer->PrepareForNextUrl(this);

  return NS_OK;
}

NS_IMETHODIMP nsNNTPProtocol::GetIsCachedConnection(bool *aIsCachedConnection)
{
  NS_ENSURE_ARG_POINTER(aIsCachedConnection);
  *aIsCachedConnection = m_fromCache;
  return NS_OK;
}

NS_IMETHODIMP nsNNTPProtocol::SetIsCachedConnection(bool aIsCachedConnection)
{
  m_fromCache = aIsCachedConnection;
  return NS_OK;
}

/* void GetLastActiveTimeStamp (out PRTime aTimeStamp); */
NS_IMETHODIMP nsNNTPProtocol::GetLastActiveTimeStamp(PRTime *aTimeStamp)
{
  NS_ENSURE_ARG_POINTER(aTimeStamp);
  *aTimeStamp = m_lastActiveTimeStamp;
  return NS_OK;
}

NS_IMETHODIMP nsNNTPProtocol::LoadNewsUrl(nsIURI * aURL, nsISupports * aConsumer)
{
  // clear the previous channel listener and use the new one....
  // don't reuse an existing channel listener
  m_channelListener = nullptr;
  m_channelListener = do_QueryInterface(aConsumer);
  nsCOMPtr<nsINntpUrl> newsUrl (do_QueryInterface(aURL));
  newsUrl->GetNewsAction(&m_newsAction);

  SetupPartExtractorListener(m_channelListener);
  return LoadUrl(aURL, aConsumer);
}


// WARNING: the cache stream listener is intended to be accessed from the UI thread!
// it will NOT create another proxy for the stream listener that gets passed in...
class nsNntpCacheStreamListener : public nsIStreamListener
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIREQUESTOBSERVER
  NS_DECL_NSISTREAMLISTENER

  nsNntpCacheStreamListener ();

  nsresult Init(nsIStreamListener * aStreamListener, nsIChannel* channel, nsIMsgMailNewsUrl *aRunningUrl);
protected:
  virtual ~nsNntpCacheStreamListener();
    nsCOMPtr<nsIChannel> mChannelToUse;
  nsCOMPtr<nsIStreamListener> mListener;
  nsCOMPtr<nsIMsgMailNewsUrl> mRunningUrl;
};

NS_IMPL_ADDREF(nsNntpCacheStreamListener)
NS_IMPL_RELEASE(nsNntpCacheStreamListener)

NS_INTERFACE_MAP_BEGIN(nsNntpCacheStreamListener)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStreamListener)
   NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
   NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
NS_INTERFACE_MAP_END

nsNntpCacheStreamListener::nsNntpCacheStreamListener()
{
}

nsNntpCacheStreamListener::~nsNntpCacheStreamListener()
{}

nsresult nsNntpCacheStreamListener::Init(nsIStreamListener * aStreamListener, nsIChannel* channel,
                                         nsIMsgMailNewsUrl *aRunningUrl)
{
  NS_ENSURE_ARG(aStreamListener);
  NS_ENSURE_ARG(channel);

  mChannelToUse = channel;

  mListener = aStreamListener;
  mRunningUrl = aRunningUrl;
  return NS_OK;
}

NS_IMETHODIMP
nsNntpCacheStreamListener::OnStartRequest(nsIRequest *request, nsISupports * aCtxt)
{
  nsCOMPtr <nsILoadGroup> loadGroup;
  nsCOMPtr <nsIRequest> ourRequest = do_QueryInterface(mChannelToUse);

  NS_ASSERTION(mChannelToUse, "null channel in OnStartRequest");
  if (mChannelToUse)
    mChannelToUse->GetLoadGroup(getter_AddRefs(loadGroup));
  if (loadGroup)
    loadGroup->AddRequest(ourRequest, nullptr /* context isupports */);
  return (mListener) ? mListener->OnStartRequest(ourRequest, aCtxt) : NS_OK;
}

NS_IMETHODIMP
nsNntpCacheStreamListener::OnStopRequest(nsIRequest *request, nsISupports * aCtxt, nsresult aStatus)
{
  nsCOMPtr <nsIRequest> ourRequest = do_QueryInterface(mChannelToUse);
  nsresult rv = NS_OK;
  NS_ASSERTION(mListener, "this assertion is for Bug 531794 comment 7");
  if (mListener)
    mListener->OnStopRequest(ourRequest, aCtxt, aStatus);
  nsCOMPtr <nsILoadGroup> loadGroup;
  NS_ASSERTION(mChannelToUse, "null channel in OnStopRequest");
  if (mChannelToUse)
    mChannelToUse->GetLoadGroup(getter_AddRefs(loadGroup));
  if (loadGroup)
    loadGroup->RemoveRequest(ourRequest, nullptr, aStatus);

  // clear out mem cache entry so we're not holding onto it.
  if (mRunningUrl)
    mRunningUrl->SetMemCacheEntry(nullptr);

  mListener = nullptr;
  nsCOMPtr <nsINNTPProtocol> nntpProtocol = do_QueryInterface(mChannelToUse);
  if (nntpProtocol) {
    rv = nntpProtocol->SetIsBusy(false);
    NS_ENSURE_SUCCESS(rv,rv);
  }
  mChannelToUse = nullptr;
  return rv;
}

NS_IMETHODIMP
nsNntpCacheStreamListener::OnDataAvailable(nsIRequest *request, nsISupports * aCtxt, nsIInputStream * aInStream, uint64_t aSourceOffset, uint32_t aCount)
{
    NS_ENSURE_STATE(mListener);
    nsCOMPtr <nsIRequest> ourRequest = do_QueryInterface(mChannelToUse);
    return mListener->OnDataAvailable(ourRequest, aCtxt, aInStream, aSourceOffset, aCount);
}

NS_IMETHODIMP nsNNTPProtocol::GetOriginalURI(nsIURI* *aURI)
{
    // News does not seem to have the notion of an original URI (See Bug #193317)
    *aURI = m_url;
    NS_IF_ADDREF(*aURI);
    return NS_OK;
}

NS_IMETHODIMP nsNNTPProtocol::SetOriginalURI(nsIURI* aURI)
{
    // News does not seem to have the notion of an original URI (See Bug #193317)
    return NS_OK;       // ignore
}

nsresult nsNNTPProtocol::SetupPartExtractorListener(nsIStreamListener * aConsumer)
{
  bool convertData = false;
  nsresult rv = NS_OK;

  if (m_newsAction == nsINntpUrl::ActionFetchArticle)
  {
    nsCOMPtr<nsIMsgMailNewsUrl> msgUrl = do_QueryInterface(m_runningURL, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    nsAutoCString queryStr;
    rv = msgUrl->GetQuery(queryStr);
    NS_ENSURE_SUCCESS(rv,rv);

    // check if this is a filter plugin requesting the message.
    // in that case, set up a text converter
    convertData = (queryStr.Find("header=filter") != kNotFound
      || queryStr.Find("header=attach") != kNotFound);
  }
  else
  {
    convertData = (m_newsAction == nsINntpUrl::ActionFetchPart);
  }
  if (convertData)
  {
    nsCOMPtr<nsIStreamConverterService> converter = do_GetService("@mozilla.org/streamConverters;1");
    if (converter && aConsumer)
    {
      nsCOMPtr<nsIStreamListener> newConsumer;
      nsCOMPtr<nsIChannel> channel;
      QueryInterface(NS_GET_IID(nsIChannel), getter_AddRefs(channel));
      converter->AsyncConvertData("message/rfc822", "*/*",
           aConsumer, channel, getter_AddRefs(newConsumer));
      if (newConsumer)
        m_channelListener = newConsumer;
    }
  }

  return rv;
}

nsresult nsNNTPProtocol::ReadFromMemCache(nsICacheEntry *entry)
{
  NS_ENSURE_ARG(entry);

  nsCOMPtr<nsIInputStream> cacheStream;
  nsresult rv = entry->OpenInputStream(0, getter_AddRefs(cacheStream));

  if (NS_SUCCEEDED(rv))
  {
    nsCOMPtr<nsIInputStreamPump> pump;
    rv = NS_NewInputStreamPump(getter_AddRefs(pump), cacheStream);
    if (NS_FAILED(rv)) return rv;

    nsCString group;
    // do this to get m_key set, so that marking the message read will work.
    rv = ParseURL(m_url, group, m_messageID);

    RefPtr<nsNntpCacheStreamListener> cacheListener =
      new nsNntpCacheStreamListener();

    SetLoadGroup(m_loadGroup);
    m_typeWanted = ARTICLE_WANTED;

    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(m_runningURL);
    cacheListener->Init(m_channelListener, static_cast<nsIChannel *>(this), mailnewsUrl);

    mContentType = ""; // reset the content type for the upcoming read....

    rv = pump->AsyncRead(cacheListener, m_channelContext);

    if (NS_SUCCEEDED(rv)) // ONLY if we succeeded in actually starting the read should we return
    {
      // we're not calling nsMsgProtocol::AsyncRead(), which calls nsNNTPProtocol::LoadUrl, so we need to take care of some stuff it does.
      m_channelListener = nullptr;
      return rv;
    }
  }

  return rv;
}

nsresult nsNNTPProtocol::ReadFromNewsConnection()
{
  // we might end up here if we thought we had a news message offline
  // but it turned out not to be so. In which case, we need to
  // recall Initialize().
  if (!m_socketIsOpen || !m_dataBuf)
  {
    nsresult rv = Initialize(m_url, m_msgWindow);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return nsMsgProtocol::AsyncOpen(m_channelListener, m_channelContext);
}

// for messages stored in our offline cache, we have special code to handle that...
// If it's in the local cache, we return true and we can abort the download because
// this method does the rest of the work.
bool nsNNTPProtocol::ReadFromLocalCache()
{
  bool msgIsInLocalCache = false;
  nsresult rv = NS_OK;
  nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(m_runningURL);
  mailnewsUrl->GetMsgIsInLocalCache(&msgIsInLocalCache);

  if (msgIsInLocalCache)
  {
    nsCOMPtr <nsIMsgFolder> folder = do_QueryInterface(m_newsFolder);
    if (folder && NS_SUCCEEDED(rv))
    {
    // we want to create a file channel and read the msg from there.
      nsCOMPtr<nsIInputStream> fileStream;
      int64_t offset=0;
      uint32_t size=0;
      rv = folder->GetOfflineFileStream(m_key, &offset, &size, getter_AddRefs(fileStream));

      // get the file stream from the folder, somehow (through the message or
      // folder sink?) We also need to set the transfer offset to the message offset
      if (fileStream && NS_SUCCEEDED(rv))
      {
        // dougt - This may break the ablity to "cancel" a read from offline mail reading.
        // fileChannel->SetLoadGroup(m_loadGroup);

        m_typeWanted = ARTICLE_WANTED;

        RefPtr<nsNntpCacheStreamListener> cacheListener =
          new nsNntpCacheStreamListener();

        cacheListener->Init(m_channelListener, static_cast<nsIChannel *>(this), mailnewsUrl);

        // create a stream pump that will async read the specified amount of data.
        // XXX make size 64-bit int
        nsCOMPtr<nsIInputStreamPump> pump;
        rv = NS_NewInputStreamPump(getter_AddRefs(pump),
                                   fileStream, offset, (int64_t) size);
        if (NS_SUCCEEDED(rv))
          rv = pump->AsyncRead(cacheListener, m_channelContext);

        if (NS_SUCCEEDED(rv)) // ONLY if we succeeded in actually starting the read should we return
        {
          mContentType.Truncate();
          m_channelListener = nullptr;
          NNTP_LOG_NOTE("Loading message from offline storage");
          return true;
        }
      }
      else
        mailnewsUrl->SetMsgIsInLocalCache(false);
    }
  }

  return false;
}

NS_IMETHODIMP
nsNNTPProtocol::OnCacheEntryAvailable(nsICacheEntry *entry, bool aNew, nsIApplicationCache* aAppCache, nsresult status)
{
  nsresult rv = NS_OK;

  if (NS_SUCCEEDED(status))
  {
    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(m_runningURL, &rv);
    mailnewsUrl->SetMemCacheEntry(entry);

    // Insert a "stream T" into the flow so data gets written to both.
    if (aNew)
    {
      // use a stream listener Tee to force data into the cache and to our current channel listener...
      nsCOMPtr<nsIStreamListener> newListener;
      nsCOMPtr<nsIStreamListenerTee> tee = do_CreateInstance(NS_STREAMLISTENERTEE_CONTRACTID, &rv);
      NS_ENSURE_SUCCESS(rv, rv);

      nsCOMPtr<nsIOutputStream> outStream;
      rv = entry->OpenOutputStream(0, getter_AddRefs(outStream));
      NS_ENSURE_SUCCESS(rv, rv);

      rv = tee->Init(m_channelListener, outStream, nullptr);
      m_channelListener = do_QueryInterface(tee);
      NS_ENSURE_SUCCESS(rv, rv);
    }
    else
    {
      rv = ReadFromMemCache(entry);
      if (NS_SUCCEEDED(rv)) {
        entry->MarkValid();
        return NS_OK; // kick out if reading from the cache succeeded...
      }
    }
  } // if we got a valid entry back from the cache...

  // if reading from the cache failed or if we are writing into the cache, default to ReadFromNewsConnection.
  return ReadFromNewsConnection();
}

NS_IMETHODIMP
nsNNTPProtocol::OnCacheEntryCheck(nsICacheEntry* entry, nsIApplicationCache* appCache,
                                  uint32_t* aResult)
{
  *aResult = nsICacheEntryOpenCallback::ENTRY_WANTED;
  return NS_OK;
}

nsresult nsNNTPProtocol::OpenCacheEntry()
{
  nsresult rv = NS_OK;
  nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(m_runningURL, &rv);
  // get the cache session from our nntp service...
  nsCOMPtr <nsINntpService> nntpService = do_GetService(NS_NNTPSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsICacheStorage> cacheStorage;
  rv = nntpService->GetCacheStorage(getter_AddRefs(cacheStorage));
  NS_ENSURE_SUCCESS(rv, rv);

  // Open a cache entry with key = url, no extension.
  nsCOMPtr<nsIURI> uri;
  rv = mailnewsUrl->GetBaseURI(getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);

  // Truncate of the query part so we don't duplicate urls in the cache for
  // various message parts.
  nsCOMPtr<nsIURI> newUri;
  uri->Clone(getter_AddRefs(newUri));
  nsAutoCString path;
  newUri->GetPath(path);
  int32_t pos = path.FindChar('?');
  if (pos != kNotFound) {
    path.SetLength(pos);
    newUri->SetPath(path);
  }
  return cacheStorage->AsyncOpenURI(newUri, EmptyCString(), nsICacheStorage::OPEN_NORMALLY, this);
}

NS_IMETHODIMP nsNNTPProtocol::AsyncOpen(nsIStreamListener *listener, nsISupports *ctxt)
{
  nsresult rv;
  nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(m_runningURL, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  int32_t port;
  rv = mailnewsUrl->GetPort(&port);
  if (NS_FAILED(rv))
      return rv;

  rv = NS_CheckPortSafety(port, "news");
  if (NS_FAILED(rv))
      return rv;

  m_channelContext = ctxt;
  m_channelListener = listener;
  m_runningURL->GetNewsAction(&m_newsAction);

  // Before running through the connection, try to see if we can grab the data
  // from the offline storage or the memory cache. Only actions retrieving
  // messages can be cached.
  if (mailnewsUrl && (m_newsAction == nsINntpUrl::ActionFetchArticle ||
                      m_newsAction == nsINntpUrl::ActionFetchPart ||
                      m_newsAction == nsINntpUrl::ActionSaveMessageToDisk))
  {
    SetupPartExtractorListener(m_channelListener);

    // Attempt to get the message from the offline storage cache. If this
    // succeeds, we don't need to use our connection, so tell the server that we
    // are ready for the next URL.
    if (ReadFromLocalCache())
    {
      if (m_nntpServer)
        m_nntpServer->PrepareForNextUrl(this);
      return NS_OK;
    }

    // If it wasn't offline, try to get the cache from memory. If this call
    // succeeds, we probably won't need the connection, but the cache might fail
    // later on. The code there will determine if we need to fallback and will
    // handle informing the server of our readiness.
    if (NS_SUCCEEDED(OpenCacheEntry()))
      return NS_OK;
  }
  return nsMsgProtocol::AsyncOpen(listener, ctxt);
}

NS_IMETHODIMP nsNNTPProtocol::AsyncOpen2(nsIStreamListener *aListener)
{
    nsCOMPtr<nsIStreamListener> listener = aListener;
    nsresult rv = nsContentSecurityManager::doContentSecurityCheck(this, listener);
    NS_ENSURE_SUCCESS(rv, rv);
    return AsyncOpen(listener, nullptr);
}

nsresult nsNNTPProtocol::LoadUrl(nsIURI * aURL, nsISupports * aConsumer)
{
  NS_ENSURE_ARG_POINTER(aURL);

  nsCString group;
  mContentType.Truncate();
  nsresult rv = NS_OK;

  m_runningURL = do_QueryInterface(aURL, &rv);
  if (NS_FAILED(rv)) return rv;
  m_runningURL->GetNewsAction(&m_newsAction);

  SetIsBusy(true);

  rv = ParseURL(aURL, group, m_messageID);
  NS_ASSERTION(NS_SUCCEEDED(rv),"failed to parse news url");
  //if (NS_FAILED(rv)) return rv;
  // XXX group returned from ParseURL is assumed to be in UTF-8
  NS_ASSERTION(MsgIsUTF8(group), "newsgroup name is not in UTF-8");
  NS_ASSERTION(m_nntpServer, "Parsing must result in an m_nntpServer");

  MOZ_LOG(NNTP, LogLevel::Info,("(%p) m_messageID = %s", this, m_messageID.get()));
  MOZ_LOG(NNTP, LogLevel::Info,("(%p) group = %s", this, group.get()));
  MOZ_LOG(NNTP, LogLevel::Info,("(%p) m_key = %d",this,m_key));

  if (m_newsAction == nsINntpUrl::ActionFetchArticle ||
      m_newsAction == nsINntpUrl::ActionFetchPart ||
      m_newsAction == nsINntpUrl::ActionSaveMessageToDisk)
    m_typeWanted = ARTICLE_WANTED;
  else if (m_newsAction == nsINntpUrl::ActionCancelArticle)
    m_typeWanted = CANCEL_WANTED;
  else if (m_newsAction == nsINntpUrl::ActionPostArticle)
  {
    m_typeWanted = NEWS_POST;
    m_messageID = "";
  }
  else if (m_newsAction == nsINntpUrl::ActionListIds)
  {
    m_typeWanted = IDS_WANTED;
    rv = m_nntpServer->FindGroup(group, getter_AddRefs(m_newsFolder));
  }
  else if (m_newsAction == nsINntpUrl::ActionSearch)
  {
    m_typeWanted = SEARCH_WANTED;

    // Get the search data
    nsCString commandSpecificData;
    nsCOMPtr<nsIURL> url = do_QueryInterface(m_runningURL);
    rv = url->GetQuery(commandSpecificData);
    NS_ENSURE_SUCCESS(rv, rv);
    MsgUnescapeString(commandSpecificData, 0, m_searchData);

    rv = m_nntpServer->FindGroup(group, getter_AddRefs(m_newsFolder));
    if (!m_newsFolder)
      goto FAIL;
  }
  else if (m_newsAction == nsINntpUrl::ActionGetNewNews)
  {
    bool containsGroup = true;
    rv = m_nntpServer->ContainsNewsgroup(group, &containsGroup);
    if (NS_FAILED(rv))
      goto FAIL;

    if (!containsGroup)
    {
      // We have the name of a newsgroup which we're not subscribed to,
      // the next step is to ask the user whether we should subscribe to it.
      nsCOMPtr<nsIPrompt> dialog;

      if (m_msgWindow)
        m_msgWindow->GetPromptDialog(getter_AddRefs(dialog));

      if (!dialog)
      {
         nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
         wwatch->GetNewPrompter(nullptr, getter_AddRefs(dialog));
      }

      nsString statusString, confirmText;
      nsCOMPtr<nsIStringBundle> bundle;
      nsCOMPtr<nsIStringBundleService> bundleService =
        mozilla::services::GetStringBundleService();

      // to handle non-ASCII newsgroup names, we store them internally
      // as escaped. decode and unescape the newsgroup name so we'll
      // display a proper name.

      nsAutoString unescapedName;
      rv = NS_MsgDecodeUnescapeURLPath(group, unescapedName);
      NS_ENSURE_SUCCESS(rv,rv);

      bundleService->CreateBundle(NEWS_MSGS_URL, getter_AddRefs(bundle));
      const char16_t *formatStrings[1] = { unescapedName.get() };

      rv = bundle->FormatStringFromName(
        u"autoSubscribeText", formatStrings, 1,
        getter_Copies(confirmText));
      NS_ENSURE_SUCCESS(rv,rv);

      bool confirmResult = false;
      rv = dialog->Confirm(nullptr, confirmText.get(), &confirmResult);
      NS_ENSURE_SUCCESS(rv, rv);

      if (confirmResult)
      {
         rv = m_nntpServer->SubscribeToNewsgroup(group);
         containsGroup = true;
      }
      else
      {
        // XXX FIX ME
        // the way news is current written, we've already opened the socket
        // and initialized the connection.
        //
        // until that is fixed, when the user cancels an autosubscribe, we've got to close it and clean up after ourselves
        //
        // see bug http://bugzilla.mozilla.org/show_bug.cgi?id=108293
        // another problem, autosubscribe urls are ending up as cache entries
        // because the default action on nntp urls is ActionFetchArticle
        //
        // see bug http://bugzilla.mozilla.org/show_bug.cgi?id=108294
        if (m_runningURL)
          FinishMemCacheEntry(false); // cleanup mem cache entry

        return CloseConnection();
      }
    }

    // If we have a group (since before, or just subscribed), set the m_newsFolder.
    if (containsGroup)
    {
      rv = m_nntpServer->FindGroup(group, getter_AddRefs(m_newsFolder));
      if (!m_newsFolder)
        goto FAIL;
    }
    m_typeWanted = GROUP_WANTED;
  }
  else if (m_newsAction == nsINntpUrl::ActionListGroups)
    m_typeWanted = LIST_WANTED;
  else if (m_newsAction == nsINntpUrl::ActionListNewGroups)
    m_typeWanted = NEW_GROUPS;
  else if (!m_messageID.IsEmpty() || m_key != nsMsgKey_None)
    m_typeWanted = ARTICLE_WANTED;
  else
  {
    NS_NOTREACHED("Unknown news action");
    rv = NS_ERROR_FAILURE;
  }

    // if this connection comes from the cache, we need to initialize the
    // load group here, by generating the start request notification. nsMsgProtocol::OnStartRequest
    // ignores the first parameter (which is supposed to be the channel) so we'll pass in null.
    if (m_fromCache)
      nsMsgProtocol::OnStartRequest(nullptr, aURL);

      /* At this point, we're all done parsing the URL, and know exactly
      what we want to do with it.
    */

FAIL:
    if (NS_FAILED(rv))
    {
      AlertError(0, nullptr);
      return rv;
    }
    else
    {
      if (!m_socketIsOpen)
      {
        m_nextStateAfterResponse = m_nextState;
        m_nextState = NNTP_RESPONSE;
      }
      rv = nsMsgProtocol::LoadUrl(aURL, aConsumer);
    }

    // Make sure that we have the information we need to be able to run the
    // URLs
    NS_ASSERTION(m_nntpServer, "Parsing must result in an m_nntpServer");
    if (m_typeWanted == ARTICLE_WANTED)
    {
      if (m_key != nsMsgKey_None)
        NS_ASSERTION(m_newsFolder, "ARTICLE_WANTED needs m_newsFolder w/ key");
      else
        NS_ASSERTION(!m_messageID.IsEmpty(), "ARTICLE_WANTED needs m_messageID w/o key");
    }
    else if (m_typeWanted == CANCEL_WANTED)
    {
      NS_ASSERTION(!m_messageID.IsEmpty(), "CANCEL_WANTED needs m_messageID");
      NS_ASSERTION(m_newsFolder, "CANCEL_WANTED needs m_newsFolder");
      NS_ASSERTION(m_key != nsMsgKey_None, "CANCEL_WANTED needs m_key");
    }
    else if (m_typeWanted == GROUP_WANTED)
      NS_ASSERTION(m_newsFolder, "GROUP_WANTED needs m_newsFolder");
    else if (m_typeWanted == SEARCH_WANTED)
      NS_ASSERTION(!m_searchData.IsEmpty(), "SEARCH_WANTED needs m_searchData");
    else if (m_typeWanted == IDS_WANTED)
      NS_ASSERTION(m_newsFolder, "IDS_WANTED needs m_newsFolder");

    return rv;
}

void nsNNTPProtocol::FinishMemCacheEntry(bool valid)
{
  nsCOMPtr <nsICacheEntry> memCacheEntry;
  nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(m_runningURL);
  if (mailnewsurl)
    mailnewsurl->GetMemCacheEntry(getter_AddRefs(memCacheEntry));
  if (memCacheEntry)
  {
    if (valid)
      memCacheEntry->MarkValid();
    else
      memCacheEntry->AsyncDoom(nullptr);
  }
}

// stop binding is a "notification" informing us that the stream associated with aURL is going away.
NS_IMETHODIMP nsNNTPProtocol::OnStopRequest(nsIRequest *request, nsISupports * aContext, nsresult aStatus)
{
    // either remove mem cache entry, or mark it valid if url successful and
    // command succeeded
    FinishMemCacheEntry(NS_SUCCEEDED(aStatus)
      && MK_NNTP_RESPONSE_TYPE(m_responseCode) == MK_NNTP_RESPONSE_TYPE_OK);

    nsMsgProtocol::OnStopRequest(request, aContext, aStatus);

    // nsMsgProtocol::OnStopRequest() has called m_channelListener. There is
    // no need to be called again in CloseSocket(). Let's clear it here.
    if (m_channelListener) {
        m_channelListener = nullptr;
    }

  // okay, we've been told that the send is done and the connection is going away. So
  // we need to release all of our state
  return CloseSocket();
}

NS_IMETHODIMP nsNNTPProtocol::Cancel(nsresult status)  // handle stop button
{
    m_nextState = NNTP_ERROR;
    return nsMsgProtocol::Cancel(NS_BINDING_ABORTED);
}

nsresult
nsNNTPProtocol::ParseURL(nsIURI *aURL, nsCString &aGroup, nsCString &aMessageID)
{
    NS_ENSURE_ARG_POINTER(aURL);

    MOZ_LOG(NNTP, LogLevel::Info,("(%p) ParseURL",this));

    nsresult rv;
    nsCOMPtr <nsIMsgFolder> folder;
    nsCOMPtr <nsINntpService> nntpService = do_GetService(NS_NNTPSERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    nsCOMPtr<nsIMsgMessageUrl> msgUrl = do_QueryInterface(m_runningURL, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(msgUrl, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCString spec;
    rv = msgUrl->GetOriginalSpec(getter_Copies(spec));
    NS_ENSURE_SUCCESS(rv,rv);

    // if the original spec is non empty, use it to determine m_newsFolder and m_key
    if (!spec.IsEmpty()) {
        MOZ_LOG(NNTP, LogLevel::Info,("(%p) original message spec = %s",this,spec.get()));

        rv = nntpService->DecomposeNewsURI(spec.get(), getter_AddRefs(folder), &m_key);
        NS_ENSURE_SUCCESS(rv,rv);

        // since we are reading a message in this folder, we can set m_newsFolder
        m_newsFolder = do_QueryInterface(folder, &rv);
        NS_ENSURE_SUCCESS(rv,rv);

        // if we are cancelling, we aren't done.  we still need to parse out the messageID from the url
        // later, we'll use m_newsFolder and m_key to delete the message from the DB, if the cancel is successful.
        if (m_newsAction != nsINntpUrl::ActionCancelArticle) {
            return NS_OK;
        }
    }
    else {
        // clear this, we'll set it later.
        m_newsFolder = nullptr;
        m_currentGroup.Truncate();
    }

  // Load the values from the URL for parsing.
  rv = m_runningURL->GetGroup(aGroup);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = m_runningURL->GetMessageID(aMessageID);
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ASSERTION(aMessageID.IsEmpty() || aMessageID != aGroup, "something not null");

  // If we are cancelling, we've got our message id, m_key, and m_newsFolder.
  // Bail out now to prevent messing those up.
  if (m_newsAction == nsINntpUrl::ActionCancelArticle)
    return NS_OK;

  rv = m_runningURL->GetKey(&m_key);
  NS_ENSURE_SUCCESS(rv, rv);

  // Check if the key is in the local cache.
  // It's possible that we're have a server/group/key combo that doesn't exist
  // (think nntp://server/group/key), so not having the folder isn't a bad
  // thing.
  if (m_key != nsMsgKey_None)
  {
    rv = mailnewsUrl->GetFolder(getter_AddRefs(folder));
    m_newsFolder = do_QueryInterface(folder);

    if (NS_SUCCEEDED(rv) && m_newsFolder)
    {
      bool useLocalCache = false;
      rv = folder->HasMsgOffline(m_key, &useLocalCache);
      NS_ENSURE_SUCCESS(rv,rv);

      // set message is in local cache
      rv = mailnewsUrl->SetMsgIsInLocalCache(useLocalCache);
      NS_ENSURE_SUCCESS(rv,rv);
    }
  }

  return NS_OK;
}
/*
 * Writes the data contained in dataBuffer into the current output stream. It also informs
 * the transport layer that this data is now available for transmission.
 * Returns a positive number for success, 0 for failure (not all the bytes were written to the
 * stream, etc). We need to make another pass through this file to install an error system (mscott)
 */

nsresult nsNNTPProtocol::SendData(const char * dataBuffer, bool aSuppressLogging)
{
    if (!aSuppressLogging) {
        NNTP_LOG_WRITE(dataBuffer);
    }
    else {
        MOZ_LOG(NNTP, out, ("(%p) Logging suppressed for this command (it probably contained authentication information)", this));
    }

  return nsMsgProtocol::SendData(dataBuffer); // base class actually transmits the data
}

/* gets the response code from the nntp server and the
 * response line
 *
 * returns the TCP return code from the read
 */
nsresult nsNNTPProtocol::NewsResponse(nsIInputStream *inputStream, uint32_t length)
{
  uint32_t status = 0;

  NS_PRECONDITION(nullptr != inputStream, "invalid input stream");

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData);

  NNTP_LOG_READ(line);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  if(!line)
    return NS_ERROR_FAILURE;

  ClearFlag(NNTP_PAUSE_FOR_READ);  /* don't pause if we got a line */

  /* almost correct */
  if(status > 1)
  {
    mBytesReceived += status;
    mBytesReceivedSinceLastStatusUpdate += status;
  }

  m_previousResponseCode = m_responseCode;

  PR_sscanf(line, "%d", &m_responseCode);

  if (m_responseCode && PL_strlen(line) > 3)
    NS_MsgSACopy(&m_responseText, line + 4);
  else
    NS_MsgSACopy(&m_responseText, line);

  /* authentication required can come at any time
  */
  if (MK_NNTP_RESPONSE_AUTHINFO_REQUIRE == m_responseCode ||
    MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_REQUIRE == m_responseCode)
  {
    m_nextState = NNTP_BEGIN_AUTHORIZE;
  }
  else {
    m_nextState = m_nextStateAfterResponse;
  }

  PR_FREEIF(line);
  return NS_OK;
}

/* interpret the server response after the connect
 *
 * returns negative if the server responds unexpectedly
 */

nsresult nsNNTPProtocol::LoginResponse()
{
  bool postingAllowed = m_responseCode == MK_NNTP_RESPONSE_POSTING_ALLOWED;

  if(MK_NNTP_RESPONSE_TYPE(m_responseCode)!=MK_NNTP_RESPONSE_TYPE_OK)
  {
    AlertError(MK_NNTP_ERROR_MESSAGE, m_responseText);

    m_nextState = NNTP_ERROR;
    return NS_ERROR_FAILURE;
  }

  m_nntpServer->SetPostingAllowed(postingAllowed);
  m_nextState = NNTP_SEND_MODE_READER;
  return NS_OK;
}

nsresult nsNNTPProtocol::SendModeReader()
{
  nsresult rv = NS_OK;

  rv = SendData(NNTP_CMD_MODE_READER);
    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = NNTP_SEND_MODE_READER_RESPONSE;
    SetFlag(NNTP_PAUSE_FOR_READ);

    NS_ENSURE_SUCCESS(rv,rv);
    return rv;
}

nsresult nsNNTPProtocol::SendModeReaderResponse()
{
  SetFlag(NNTP_READER_PERFORMED);

  /* ignore the response code and continue
   */
  bool pushAuth = false;
  nsresult rv = NS_OK;

  NS_ASSERTION(m_nntpServer, "no server, see bug #107797");
  if (m_nntpServer) {
    rv = m_nntpServer->GetPushAuth(&pushAuth);
  }
  if (NS_SUCCEEDED(rv) && pushAuth) {
    /* if the news host is set up to require volunteered (pushed) authentication,
    * do that before we do anything else
    */
    m_nextState = NNTP_BEGIN_AUTHORIZE;
  }
  else {
#ifdef HAVE_NNTP_EXTENSIONS
    m_nextState = SEND_LIST_EXTENSIONS;
#else
    m_nextState = SEND_FIRST_NNTP_COMMAND;
#endif  /* HAVE_NNTP_EXTENSIONS */
  }

  return NS_OK;
}

nsresult nsNNTPProtocol::SendListExtensions()
{
  nsresult rv = SendData(NNTP_CMD_LIST_EXTENSIONS);

  m_nextState = NNTP_RESPONSE;
  m_nextStateAfterResponse = SEND_LIST_EXTENSIONS_RESPONSE;
  ClearFlag(NNTP_PAUSE_FOR_READ);
  return rv;
}

nsresult nsNNTPProtocol::SendListExtensionsResponse(nsIInputStream * inputStream, uint32_t length)
{
  nsresult rv = NS_OK;

  if (MK_NNTP_RESPONSE_TYPE(m_responseCode) == MK_NNTP_RESPONSE_TYPE_OK)
  {
    uint32_t status = 0;
    bool pauseForMoreData = false;
    char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

    if(pauseForMoreData)
    {
      SetFlag(NNTP_PAUSE_FOR_READ);
      return NS_OK;
    }
    if (!line)
      return rv;  /* no line yet */

        if ('.' != line[0]) {
            m_nntpServer->AddExtension(line);
        }
    else
    {
      /* tell libmsg that it's ok to ask this news host for extensions */
      m_nntpServer->SetSupportsExtensions(true);
      /* all extensions received */
      m_nextState = SEND_LIST_SEARCHES;
      ClearFlag(NNTP_PAUSE_FOR_READ);
    }
  }
  else
  {
    /* LIST EXTENSIONS not recognized
     * tell libmsg not to ask for any more extensions and move on to
     * the real NNTP command we were trying to do. */

     m_nntpServer->SetSupportsExtensions(false);
     m_nextState = SEND_FIRST_NNTP_COMMAND;
  }

  return NS_OK;
}

nsresult nsNNTPProtocol::SendListSearches()
{
    nsresult rv;
    bool searchable=false;

    rv = m_nntpServer->QueryExtension("SEARCH",&searchable);
    if (NS_SUCCEEDED(rv) && searchable)
  {
    rv = SendData(NNTP_CMD_LIST_SEARCHES);

    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = SEND_LIST_SEARCHES_RESPONSE;
    SetFlag(NNTP_PAUSE_FOR_READ);
  }
  else
  {
    /* since SEARCH isn't supported, move on to GET */
    m_nextState = NNTP_GET_PROPERTIES;
    ClearFlag(NNTP_PAUSE_FOR_READ);
  }

  return rv;
}

nsresult nsNNTPProtocol::SendListSearchesResponse(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t status = 0;
  nsresult rv = NS_OK;

  NS_PRECONDITION(inputStream, "invalid input stream");

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  NNTP_LOG_READ(line);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }
  if (!line)
    return rv;  /* no line yet */

  if ('.' != line[0])
  {
        nsAutoCString charset;
        nsAutoString lineUtf16;
        if (NS_FAILED(m_nntpServer->GetCharset(charset)) ||
            NS_FAILED(nsMsgI18NConvertToUnicode(charset.get(),
                                                nsDependentCString(line),
                                                lineUtf16, true)))
            CopyUTF8toUTF16(nsDependentCString(line), lineUtf16);

    m_nntpServer->AddSearchableGroup(lineUtf16);
  }
  else
  {
    /* all searchable groups received */
    /* LIST SRCHFIELDS is legal if the server supports the SEARCH extension, which */
    /* we already know it does */
    m_nextState = NNTP_LIST_SEARCH_HEADERS;
    ClearFlag(NNTP_PAUSE_FOR_READ);
  }

  PR_FREEIF(line);
  return rv;
}

nsresult nsNNTPProtocol::SendListSearchHeaders()
{
  nsresult rv = SendData(NNTP_CMD_LIST_SEARCH_FIELDS);

  m_nextState = NNTP_RESPONSE;
  m_nextStateAfterResponse = NNTP_LIST_SEARCH_HEADERS_RESPONSE;
  SetFlag(NNTP_PAUSE_FOR_READ);

  return rv;
}

nsresult nsNNTPProtocol::SendListSearchHeadersResponse(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t status = 0;
  nsresult rv;

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }
  if (!line)
    return rv;  /* no line yet */

  if ('.' != line[0])
        m_nntpServer->AddSearchableHeader(line);
  else
  {
    m_nextState = NNTP_GET_PROPERTIES;
    ClearFlag(NNTP_PAUSE_FOR_READ);
  }

  PR_FREEIF(line);
  return rv;
}

nsresult nsNNTPProtocol::GetProperties()
{
    nsresult rv;
    bool setget=false;

    rv = m_nntpServer->QueryExtension("SETGET",&setget);
    if (NS_SUCCEEDED(rv) && setget)
  {
    rv = SendData(NNTP_CMD_GET_PROPERTIES);
    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = NNTP_GET_PROPERTIES_RESPONSE;
    SetFlag(NNTP_PAUSE_FOR_READ);
  }
  else
  {
    /* since GET isn't supported, move on LIST SUBSCRIPTIONS */
    m_nextState = SEND_LIST_SUBSCRIPTIONS;
    ClearFlag(NNTP_PAUSE_FOR_READ);
  }
  return rv;
}

nsresult nsNNTPProtocol::GetPropertiesResponse(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t status = 0;
  nsresult rv;

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }
  if (!line)
    return rv;  /* no line yet */

  if ('.' != line[0])
  {
    char *propertyName = NS_strdup(line);
    if (propertyName)
    {
      char *space = PL_strchr(propertyName, ' ');
      if (space)
      {
        char *propertyValue = space + 1;
        *space = '\0';
                m_nntpServer->AddPropertyForGet(propertyName, propertyValue);
      }
      PR_Free(propertyName);
    }
  }
  else
  {
    /* all GET properties received, move on to LIST SUBSCRIPTIONS */
    m_nextState = SEND_LIST_SUBSCRIPTIONS;
    ClearFlag(NNTP_PAUSE_FOR_READ);
  }

  PR_FREEIF(line);
  return rv;
}

nsresult nsNNTPProtocol::SendListSubscriptions()
{
    nsresult rv = NS_OK;
/* TODO: is this needed for anything?
#if 0
    bool searchable=false;
    rv = m_nntpServer->QueryExtension("LISTSUBSCR",&listsubscr);
    if (NS_SUCCEEDED(rv) && listsubscr)
#else
  if (0)
#endif
  {
    rv = SendData(NNTP_CMD_LIST_SUBSCRIPTIONS);
    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = SEND_LIST_SUBSCRIPTIONS_RESPONSE;
    SetFlag(NNTP_PAUSE_FOR_READ);
  }
  else
*/
  {
    /* since LIST SUBSCRIPTIONS isn't supported, move on to real work */
    m_nextState = SEND_FIRST_NNTP_COMMAND;
    ClearFlag(NNTP_PAUSE_FOR_READ);
  }

  return rv;
}

nsresult nsNNTPProtocol::SendListSubscriptionsResponse(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t status = 0;
  nsresult rv;

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }
  if (!line)
    return rv;  /* no line yet */

  if ('.' != line[0])
  {
        NS_ERROR("fix me");
#if 0
    char *url = PR_smprintf ("%s//%s/%s", NEWS_SCHEME, m_hostName, line);
    if (url)
      MSG_AddSubscribedNewsgroup (cd->pane, url);
#endif
  }
  else
  {
    /* all default subscriptions received */
    m_nextState = SEND_FIRST_NNTP_COMMAND;
    ClearFlag(NNTP_PAUSE_FOR_READ);
  }

  PR_FREEIF(line);
  return rv;
}

/* figure out what the first command is and send it
 *
 * returns the status from the NETWrite */

nsresult nsNNTPProtocol::SendFirstNNTPCommand(nsIURI * url)
{
    char *command=0;

    if (m_typeWanted == ARTICLE_WANTED) {
        if (m_key != nsMsgKey_None) {
            nsresult rv;
            nsCString newsgroupName;
            if (m_newsFolder) {
                rv = m_newsFolder->GetRawName(newsgroupName);
                NS_ENSURE_SUCCESS(rv,rv);
            }
            MOZ_LOG(NNTP, LogLevel::Info,
                   ("(%p) current group = %s, desired group = %s", this,
                   m_currentGroup.get(), newsgroupName.get()));
            // if the current group is the desired group, we can just issue the ARTICLE command
            // if not, we have to do a GROUP first
            if (newsgroupName.Equals(m_currentGroup))
              m_nextState = NNTP_SEND_ARTICLE_NUMBER;
            else
              m_nextState = NNTP_SEND_GROUP_FOR_ARTICLE;

            ClearFlag(NNTP_PAUSE_FOR_READ);
            return NS_OK;
        }
    }

    if(m_typeWanted == NEWS_POST)
    {  /* posting to the news group */
        NS_MsgSACopy(&command, "POST");
    }
  else if (m_typeWanted == NEW_GROUPS)
  {
      uint32_t last_update;
      nsresult rv;

      if (!m_nntpServer)
      {
        NNTP_LOG_NOTE("m_nntpServer is null, panic!");
        return NS_ERROR_FAILURE;
      }
      rv = m_nntpServer->GetLastUpdatedTime(&last_update);
      NS_ENSURE_SUCCESS(rv, rv);

      if (!last_update)
    {
        NS_MsgSACopy(&command, "LIST");
      }
    else
      {
        char small_buf[64];
        PRExplodedTime  expandedTime;
        PRTime t_usec = (PRTime)last_update * PR_USEC_PER_SEC;
        PR_ExplodeTime(t_usec, PR_LocalTimeParameters, &expandedTime);
        PR_FormatTimeUSEnglish(small_buf, sizeof(small_buf),
                               "NEWGROUPS %y%m%d %H%M%S", &expandedTime);
        NS_MsgSACopy(&command, small_buf);
      }
  }
    else if(m_typeWanted == LIST_WANTED)
    {
      nsresult rv;

    ClearFlag(NNTP_USE_FANCY_NEWSGROUP);

        NS_ASSERTION(m_nntpServer, "no m_nntpServer");
    if (!m_nntpServer) {
          NNTP_LOG_NOTE("m_nntpServer is null, panic!");
          return NS_ERROR_FAILURE;
    }

      bool xactive=false;
      rv = m_nntpServer->QueryExtension("XACTIVE",&xactive);
      if (NS_SUCCEEDED(rv) && xactive)
      {
        NS_MsgSACopy(&command, "LIST XACTIVE");
        SetFlag(NNTP_USE_FANCY_NEWSGROUP);
      }
      else
      {
        NS_MsgSACopy(&command, "LIST");
      }
  }
  else if(m_typeWanted == GROUP_WANTED)
    {
        nsresult rv = NS_ERROR_NULL_POINTER;

        NS_ASSERTION(m_newsFolder, "m_newsFolder is null, panic!");
        if (!m_newsFolder) return NS_ERROR_FAILURE;

        nsCString group_name;
        rv = m_newsFolder->GetRawName(group_name);
        NS_ASSERTION(NS_SUCCEEDED(rv),"failed to get newsgroup name");
        NS_ENSURE_SUCCESS(rv, rv);

        m_firstArticle = 0;
        m_lastArticle = 0;

        NS_MsgSACopy(&command, "GROUP ");
        NS_MsgSACat(&command, group_name.get());
      }
  else if (m_typeWanted == SEARCH_WANTED)
  {
    nsresult rv;
    MOZ_LOG(NNTP, LogLevel::Info,("(%p) doing GROUP for XPAT", this));
    nsCString group_name;

    /* for XPAT, we have to GROUP into the group before searching */
    if (!m_newsFolder) {
        NNTP_LOG_NOTE("m_newsFolder is null, panic!");
        return NS_ERROR_FAILURE;
    }
    rv = m_newsFolder->GetRawName(group_name);
    NS_ENSURE_SUCCESS(rv, rv);

    NS_MsgSACopy(&command, "GROUP ");
    NS_MsgSACat (&command, group_name.get());

    // force a GROUP next time
    m_currentGroup.Truncate();
    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = NNTP_XPAT_SEND;
  }
  else if (m_typeWanted == IDS_WANTED)
  {
    m_nextState = NNTP_LIST_GROUP;
    return NS_OK;
  }
  else  /* article or cancel */
  {
    NS_ASSERTION(!m_messageID.IsEmpty(), "No message ID, bailing!");
    if (m_messageID.IsEmpty()) return NS_ERROR_FAILURE;

    if (m_typeWanted == CANCEL_WANTED)
      NS_MsgSACopy(&command, "HEAD ");
    else {
      NS_ASSERTION(m_typeWanted == ARTICLE_WANTED, "not cancel, and not article");
      NS_MsgSACopy(&command, "ARTICLE ");
    }

    if (m_messageID[0] != '<')
      NS_MsgSACat(&command,"<");

    NS_MsgSACat(&command, m_messageID.get());

    if (PL_strchr(command+8, '>')==0)
      NS_MsgSACat(&command,">");
  }

  NS_MsgSACat(&command, CRLF);
  nsresult rv = SendData(command);
  PR_Free(command);

  m_nextState = NNTP_RESPONSE;
  if (m_typeWanted != SEARCH_WANTED)
    m_nextStateAfterResponse = SEND_FIRST_NNTP_COMMAND_RESPONSE;
  SetFlag(NNTP_PAUSE_FOR_READ);
  return rv;
} /* sent first command */


/* interprets the server response from the first command sent
 *
 * returns negative if the server responds unexpectedly
 */

nsresult nsNNTPProtocol::SendFirstNNTPCommandResponse()
{
  int32_t major_opcode = MK_NNTP_RESPONSE_TYPE(m_responseCode);

  if((major_opcode == MK_NNTP_RESPONSE_TYPE_CONT &&
    m_typeWanted == NEWS_POST)
    || (major_opcode == MK_NNTP_RESPONSE_TYPE_OK &&
    m_typeWanted != NEWS_POST) )
  {

    m_nextState = SETUP_NEWS_STREAM;
    SetFlag(NNTP_SOME_PROTOCOL_SUCCEEDED);
    return NS_OK;
  }
  else
  {
    nsresult rv = NS_OK;

    nsString group_name;
    NS_ASSERTION(m_newsFolder, "no newsFolder");
    if (m_newsFolder)
      rv = m_newsFolder->GetUnicodeName(group_name);

    if (m_responseCode == MK_NNTP_RESPONSE_GROUP_NO_GROUP &&
      m_typeWanted == GROUP_WANTED) {
      MOZ_LOG(NNTP, LogLevel::Info,("(%p) group (%s) not found, so unset"
                                 " m_currentGroup", this,
                                 NS_ConvertUTF16toUTF8(group_name).get()));
      m_currentGroup.Truncate();

      m_nntpServer->GroupNotFound(m_msgWindow, group_name, true /* opening */);
    }

    /* if the server returned a 400 error then it is an expected
    * error.  the NEWS_ERROR state will not sever the connection
    */
    if(major_opcode == MK_NNTP_RESPONSE_TYPE_CANNOT)
      m_nextState = NEWS_ERROR;
    else
      m_nextState = NNTP_ERROR;
    // if we have no channel listener, then we're likely downloading
    // the message for offline use (or at least not displaying it)
    bool savingArticleOffline = (m_channelListener == nullptr);

    if (m_runningURL)
      FinishMemCacheEntry(false);  // cleanup mem cache entry

    if (NS_SUCCEEDED(rv) && !group_name.IsEmpty() && !savingArticleOffline) {
      nsString titleStr;
      rv = GetNewsStringByName("htmlNewsErrorTitle", getter_Copies(titleStr));
      NS_ENSURE_SUCCESS(rv,rv);

      nsString newsErrorStr;
      rv = GetNewsStringByName("htmlNewsError", getter_Copies(newsErrorStr));
      NS_ENSURE_SUCCESS(rv,rv);
      nsAutoString errorHtml;
      errorHtml.Append(newsErrorStr);

      errorHtml.AppendLiteral("<b>");
      errorHtml.Append(NS_ConvertASCIItoUTF16(m_responseText));
      errorHtml.AppendLiteral("</b><p>");

      rv = GetNewsStringByName("articleExpired", getter_Copies(newsErrorStr));
      NS_ENSURE_SUCCESS(rv,rv);
      errorHtml.Append(newsErrorStr);

      char outputBuffer[OUTPUT_BUFFER_SIZE];

      if ((m_key != nsMsgKey_None) && m_newsFolder) {
        nsCString messageID;
        rv = m_newsFolder->GetMessageIdForKey(m_key, messageID);
        if (NS_SUCCEEDED(rv)) {
          PR_snprintf(outputBuffer, OUTPUT_BUFFER_SIZE,"<P>&lt;%.512s&gt; (%lu)", messageID.get(), m_key);
          errorHtml.Append(NS_ConvertASCIItoUTF16(outputBuffer));
        }
      }

      if (m_newsFolder) {
        nsCOMPtr <nsIMsgFolder> folder = do_QueryInterface(m_newsFolder, &rv);
        if (NS_SUCCEEDED(rv) && folder) {
          nsCString folderURI;
          rv = folder->GetURI(folderURI);
          if (NS_SUCCEEDED(rv)) {
            PR_snprintf(outputBuffer,OUTPUT_BUFFER_SIZE,"<P> <A HREF=\"%s?list-ids\">", folderURI.get());
          }
        }
      }

      errorHtml.Append(NS_ConvertASCIItoUTF16(outputBuffer));

      rv = GetNewsStringByName("removeExpiredArtLinkText", getter_Copies(newsErrorStr));
      NS_ENSURE_SUCCESS(rv,rv);
      errorHtml.Append(newsErrorStr);
      errorHtml.AppendLiteral("</A> </P>");

      if (!m_msgWindow) {
        nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(m_runningURL);
        if (mailnewsurl) {
          rv = mailnewsurl->GetMsgWindow(getter_AddRefs(m_msgWindow));
          NS_ENSURE_SUCCESS(rv,rv);
        }
      }
      if (!m_msgWindow) return NS_ERROR_FAILURE;

      // note, this will cause us to close the connection.
      // this will call nsDocShell::LoadURI(), which will
      // call nsDocShell::Stop(STOP_NETWORK), which will eventually
      // call nsNNTPProtocol::Cancel(), which will close the socket.
      // we need to fix this, since the connection is still valid.
      rv = m_msgWindow->DisplayHTMLInMessagePane(titleStr, errorHtml, true);
      NS_ENSURE_SUCCESS(rv,rv);
    }
    // let's take the opportunity of removing the hdr from the db so we don't try to download
    // it again.
    else if (savingArticleOffline)
    {
      if ((m_key != nsMsgKey_None) && (m_newsFolder)) {
         rv = m_newsFolder->RemoveMessage(m_key);
      }
    }
    return NS_ERROR_FAILURE;
  }

}

nsresult nsNNTPProtocol::SendGroupForArticle()
{
  nsresult rv;

  nsCString groupname;
  rv = m_newsFolder->GetRawName(groupname);
  NS_ASSERTION(NS_SUCCEEDED(rv) && !groupname.IsEmpty(), "no group name");

  char outputBuffer[OUTPUT_BUFFER_SIZE];

  PR_snprintf(outputBuffer,
      OUTPUT_BUFFER_SIZE,
      "GROUP %.512s" CRLF,
      groupname.get());

  rv = SendData(outputBuffer);

  m_nextState = NNTP_RESPONSE;
  m_nextStateAfterResponse = NNTP_SEND_GROUP_FOR_ARTICLE_RESPONSE;
  SetFlag(NNTP_PAUSE_FOR_READ);
  return rv;
}

nsresult
nsNNTPProtocol::SetCurrentGroup()
{
  nsCString groupname;
  NS_ASSERTION(m_newsFolder, "no news folder");
  if (!m_newsFolder) {
    m_currentGroup.Truncate();
    return NS_ERROR_UNEXPECTED;
  }

  mozilla::DebugOnly<nsresult> rv = m_newsFolder->GetRawName(groupname);
  NS_ASSERTION(NS_SUCCEEDED(rv) && !groupname.IsEmpty(), "no group name");
  MOZ_LOG(NNTP, LogLevel::Info,("(%p) SetCurrentGroup to %s",this, groupname.get()));
  m_currentGroup = groupname;
  return NS_OK;
}

nsresult nsNNTPProtocol::SendGroupForArticleResponse()
{
  /* ignore the response code and continue
   */
  m_nextState = NNTP_SEND_ARTICLE_NUMBER;

  return SetCurrentGroup();
}


nsresult nsNNTPProtocol::SendArticleNumber()
{
  char outputBuffer[OUTPUT_BUFFER_SIZE];
  PR_snprintf(outputBuffer, OUTPUT_BUFFER_SIZE, "ARTICLE %lu" CRLF, m_key);

  nsresult rv = SendData(outputBuffer);

    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = SEND_FIRST_NNTP_COMMAND_RESPONSE;
    SetFlag(NNTP_PAUSE_FOR_READ);

  return rv;
}

nsresult nsNNTPProtocol::BeginArticle()
{
  if (m_typeWanted != ARTICLE_WANTED && m_typeWanted != CANCEL_WANTED)
    return NS_OK;

  /*  Set up the HTML stream
   */

#ifdef NO_ARTICLE_CACHEING
  ce->format_out = CLEAR_CACHE_BIT (ce->format_out);
#endif

  // if we have a channel listener,
  // create a pipe to pump the message into...the output will go to whoever
  // is consuming the message display
  //
  // the pipe must have an unlimited length since we are going to be filling
  // it on the main thread while reading it from the main thread.  iow, the
  // write must not block!! (see bug 190988)
  //
  if (m_channelListener) {
      nsCOMPtr<nsIPipe> pipe = do_CreateInstance("@mozilla.org/pipe;1");
      nsresult rv = pipe->Init(false, false, 4096, PR_UINT32_MAX);
      NS_ENSURE_SUCCESS(rv, rv);

      // These always succeed because the pipe is initialized above.
      MOZ_ALWAYS_SUCCEEDS(pipe->GetInputStream(getter_AddRefs(mDisplayInputStream)));
      MOZ_ALWAYS_SUCCEEDS(pipe->GetOutputStream(getter_AddRefs(mDisplayOutputStream)));
  }

  m_nextState = NNTP_READ_ARTICLE;

  return NS_OK;
}

nsresult nsNNTPProtocol::DisplayArticle(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t line_length = 0;

  bool pauseForMoreData = false;
  if (m_channelListener)
  {
    nsresult rv = NS_OK;
    char *line = m_lineStreamBuffer->ReadNextLine(inputStream, line_length, pauseForMoreData, &rv, true);
    if (pauseForMoreData)
    {
      uint64_t inlength = 0;
      mDisplayInputStream->Available(&inlength);
      if (inlength > 0) // broadcast our batched up ODA changes
        m_channelListener->OnDataAvailable(this, m_channelContext, mDisplayInputStream, 0, std::min(inlength, uint64_t(PR_UINT32_MAX)));
      SetFlag(NNTP_PAUSE_FOR_READ);
      PR_Free(line);
      return rv;
    }

    if (m_newsFolder)
      m_newsFolder->NotifyDownloadedLine(line, m_key);

    // line only contains a single dot -> message end
    if (line_length == 1 + MSG_LINEBREAK_LEN && line[0] == '.')
    {
      m_nextState = NEWS_DONE;

      ClearFlag(NNTP_PAUSE_FOR_READ);

      uint64_t inlength = 0;
      mDisplayInputStream->Available(&inlength);
      if (inlength > 0) // broadcast our batched up ODA changes
        m_channelListener->OnDataAvailable(this, m_channelContext, mDisplayInputStream, 0, std::min(inlength, uint64_t(PR_UINT32_MAX)));
      PR_Free(line);
      return rv;
    }
    else // we aren't finished with the message yet
    {
      uint32_t count = 0;

      // skip over the quoted '.'
      if (line_length > 1 && line[0] == '.' && line[1] == '.')
        mDisplayOutputStream->Write(line+1, line_length-1, &count);
      else
        mDisplayOutputStream->Write(line, line_length, &count);
    }

    PR_Free(line);
  }

  return NS_OK;
}

nsresult nsNNTPProtocol::ReadArticle(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t status = 0;
  nsresult rv;
  char *outputBuffer;

  bool pauseForMoreData = false;

  // if we have a channel listener, spool directly to it....
  // otherwise we must be doing something like save to disk or cancel
  // in which case we are doing the work.
  if (m_channelListener)
    return DisplayArticle(inputStream, length);


  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv, true);
  if (m_newsFolder && line)
  {
    const char *unescapedLine = line;
    // lines beginning with '.' are escaped by nntp server
    // or is it just '.' on a line by itself?
    if (line[0] == '.' && line[1] == '.')
      unescapedLine++;
    m_newsFolder->NotifyDownloadedLine(unescapedLine, m_key);

  }

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }
  if(status > 1)
  {
    mBytesReceived += status;
    mBytesReceivedSinceLastStatusUpdate += status;
  }

  if(!line)
    return rv;  /* no line yet or error */

  nsCOMPtr<nsISupports> ctxt = do_QueryInterface(m_runningURL);

  if (m_typeWanted == CANCEL_WANTED && m_responseCode != MK_NNTP_RESPONSE_ARTICLE_HEAD)
  {
    /* HEAD command failed. */
    PR_FREEIF(line);
    return NS_ERROR_FAILURE;
  }

  if (line[0] == '.' && line[MSG_LINEBREAK_LEN + 1] == 0)
  {
    if (m_typeWanted == CANCEL_WANTED)
      m_nextState = NEWS_START_CANCEL;
    else
      m_nextState = NEWS_DONE;

    ClearFlag(NNTP_PAUSE_FOR_READ);
  }
  else
  {
    if (line[0] == '.')
      outputBuffer = line + 1;
    else
      outputBuffer = line;

      /* Don't send content-type to mime parser if we're doing a cancel
      because it confuses mime parser into not parsing.
      */
    if (m_typeWanted != CANCEL_WANTED || strncmp(outputBuffer, "Content-Type:", 13))
    {
      // if we are attempting to cancel, we want to snarf the headers and save the aside, which is what
      // ParseHeaderForCancel() does.
      if (m_typeWanted == CANCEL_WANTED) {
        ParseHeaderForCancel(outputBuffer);
      }

    }
  }

  PR_Free(line);

  return NS_OK;
}

void nsNNTPProtocol::ParseHeaderForCancel(char *buf)
{
    static int lastHeader = 0;
    nsAutoCString header(buf);
    if (header.First() == ' ' || header.First() == '\t') {
        header.StripWhitespace();
        // Add folded line to header if needed.
        switch (lastHeader) {
        case 1:
            m_cancelFromHdr += header;
            break;
        case 2:
            m_cancelID += header;
            break;
        case 3:
            m_cancelNewsgroups += header;
            break;
        case 4:
            m_cancelDistribution += header;
            break;
        }
        // Other folded lines are of no interest.
        return;
    }

    lastHeader = 0;
    int32_t colon = header.FindChar(':');
    if (!colon)
    return;

    nsCString value(Substring(header, colon + 1));
    value.StripWhitespace();

    switch (header.First()) {
    case 'F': case 'f':
        if (header.Find("From", CaseInsensitiveCompare) == 0) {
            m_cancelFromHdr = value;
            lastHeader = 1;
        }
        break;
    case 'M': case 'm':
        if (header.Find("Message-ID", CaseInsensitiveCompare) == 0) {
            m_cancelID = value;
            lastHeader = 2;
        }
        break;
    case 'N': case 'n':
        if (header.Find("Newsgroups", CaseInsensitiveCompare) == 0) {
            m_cancelNewsgroups = value;
            lastHeader = 3;
        }
        break;
     case 'D': case 'd':
        if (header.Find("Distributions", CaseInsensitiveCompare) == 0) {
            m_cancelDistribution = value;
            lastHeader = 4;
        }
        break;
    }

  return;
}

nsresult nsNNTPProtocol::BeginAuthorization()
{
  char * command = 0;
  nsresult rv = NS_OK;

  if (!m_newsFolder && m_nntpServer) {
    nsCOMPtr<nsIMsgIncomingServer> server = do_QueryInterface(m_nntpServer);
    if (m_nntpServer) {
      nsCOMPtr<nsIMsgFolder> rootFolder;
      rv = server->GetRootFolder(getter_AddRefs(rootFolder));
      if (NS_SUCCEEDED(rv) && rootFolder) {
        m_newsFolder = do_QueryInterface(rootFolder);
      }
    }
  }

  NS_ASSERTION(m_newsFolder, "no m_newsFolder");
  if (!m_newsFolder)
    return NS_ERROR_FAILURE;

  // We want to get authentication credentials, but it is possible that the
  // master password prompt will end up being synchronous. In that case, check
  // to see if we already have the credentials stored.
  nsCString username, password;
  rv = m_newsFolder->GetGroupUsername(username);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = m_newsFolder->GetGroupPassword(password);
  NS_ENSURE_SUCCESS(rv, rv);

  // If we don't have either a username or a password, queue an asynchronous
  // prompt.
  if (username.IsEmpty() || password.IsEmpty())
  {
    nsCOMPtr<nsIMsgAsyncPrompter> asyncPrompter =
      do_GetService(NS_MSGASYNCPROMPTER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Get the key to coalesce auth prompts.
    bool singleSignon = false;
    m_nntpServer->GetSingleSignon(&singleSignon);
    
    nsCString queueKey;
    nsCOMPtr<nsIMsgIncomingServer> server = do_QueryInterface(m_nntpServer);
    server->GetKey(queueKey);
    if (!singleSignon)
    {
      nsCString groupName;
      m_newsFolder->GetRawName(groupName);
      queueKey += groupName;
    }

    // If we were called back from HandleAuthenticationFailure, we must have
    // been handling the response of an authorization state. In that case,
    // let's hurry up on the auth request
    bool didAuthFail = m_nextStateAfterResponse == NNTP_AUTHORIZE_RESPONSE ||
      m_nextStateAfterResponse == NNTP_PASSWORD_RESPONSE;
    rv = asyncPrompter->QueueAsyncAuthPrompt(queueKey, didAuthFail, this);
    NS_ENSURE_SUCCESS(rv, rv);

    m_nextState = NNTP_SUSPENDED;
    if (m_request)
      m_request->Suspend();
    return NS_OK;
  }

  NS_MsgSACopy(&command, "AUTHINFO user ");
  MOZ_LOG(NNTP,  LogLevel::Info,("(%p) use %s as the username", this, username.get()));
  NS_MsgSACat(&command, username.get());
  NS_MsgSACat(&command, CRLF);

  rv = SendData(command);

  PR_Free(command);

  m_nextState = NNTP_RESPONSE;
  m_nextStateAfterResponse = NNTP_AUTHORIZE_RESPONSE;

  SetFlag(NNTP_PAUSE_FOR_READ);

  return rv;
}

nsresult nsNNTPProtocol::AuthorizationResponse()
{
  nsresult rv = NS_OK;

  if (MK_NNTP_RESPONSE_AUTHINFO_OK == m_responseCode ||
    MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_OK == m_responseCode)
  {
    /* successful login */
#ifdef HAVE_NNTP_EXTENSIONS
    bool pushAuth;
    /* If we're here because the host demanded authentication before we
    * even sent a single command, then jump back to the beginning of everything
    */
    rv = m_nntpServer->GetPushAuth(&pushAuth);

    if (!TestFlag(NNTP_READER_PERFORMED))
      m_nextState = NNTP_SEND_MODE_READER;
      /* If we're here because the host needs pushed authentication, then we
      * should jump back to SEND_LIST_EXTENSIONS
    */
    else if (NS_SUCCEEDED(rv) && pushAuth)
      m_nextState = SEND_LIST_EXTENSIONS;
    else
      /* Normal authentication */
      m_nextState = SEND_FIRST_NNTP_COMMAND;
#else
    if (!TestFlag(NNTP_READER_PERFORMED))
      m_nextState = NNTP_SEND_MODE_READER;
    else
      m_nextState = SEND_FIRST_NNTP_COMMAND;
#endif /* HAVE_NNTP_EXTENSIONS */

    return NS_OK;
  }
  else if (MK_NNTP_RESPONSE_AUTHINFO_CONT == m_responseCode)
  {
    char * command = 0;

    // Since we had to have called BeginAuthorization to get here, we've already
    // prompted for the authorization credentials. Just grab them without a
    // further prompt.
    nsCString password;
    rv = m_newsFolder->GetGroupPassword(password);
    if (NS_FAILED(rv) || password.IsEmpty())
      return NS_ERROR_FAILURE;

    NS_MsgSACopy(&command, "AUTHINFO pass ");
    NS_MsgSACat(&command, password.get());
    NS_MsgSACat(&command, CRLF);

    rv = SendData(command, true);

    PR_FREEIF(command);

    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = NNTP_PASSWORD_RESPONSE;
    SetFlag(NNTP_PAUSE_FOR_READ);

    return rv;
  }
  else
  {
    /* login failed */
    HandleAuthenticationFailure();
    return NS_OK;
  }

  NS_ERROR("should never get here");
  return NS_ERROR_FAILURE;

}

nsresult nsNNTPProtocol::PasswordResponse()
{
  if (MK_NNTP_RESPONSE_AUTHINFO_OK == m_responseCode ||
    MK_NNTP_RESPONSE_AUTHINFO_SIMPLE_OK == m_responseCode)
  {
    /* successful login */
#ifdef HAVE_NNTP_EXTENSIONS
    bool pushAuth;
    /* If we're here because the host demanded authentication before we
    * even sent a single command, then jump back to the beginning of everything
    */
    nsresult rv = m_nntpServer->GetPushAuth(&pushAuth);

    if (!TestFlag(NNTP_READER_PERFORMED))
      m_nextState = NNTP_SEND_MODE_READER;
      /* If we're here because the host needs pushed authentication, then we
      * should jump back to SEND_LIST_EXTENSIONS
    */
    else if (NS_SUCCEEDED(rv) && pushAuth)
      m_nextState = SEND_LIST_EXTENSIONS;
    else
      /* Normal authentication */
      m_nextState = SEND_FIRST_NNTP_COMMAND;
#else
    if (!TestFlag(NNTP_READER_PERFORMED))
      m_nextState = NNTP_SEND_MODE_READER;
    else
      m_nextState = SEND_FIRST_NNTP_COMMAND;
#endif /* HAVE_NNTP_EXTENSIONS */
    return NS_OK;
  }
  else
  {
    HandleAuthenticationFailure();
    return NS_OK;
  }

  NS_ERROR("should never get here");
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP nsNNTPProtocol::OnPromptStartAsync(nsIMsgAsyncPromptCallback *aCallback)
{
  bool result = false;
  OnPromptStart(&result);
  return aCallback->OnAuthResult(result);
}

NS_IMETHODIMP nsNNTPProtocol::OnPromptStart(bool *authAvailable)
{
  NS_ENSURE_ARG_POINTER(authAvailable);
  NS_ENSURE_STATE(m_nextState == NNTP_SUSPENDED);
  
  if (!m_newsFolder)
  {
    // If we don't have a news folder, we may have been closed already.
    NNTP_LOG_NOTE("Canceling queued authentication prompt");
    *authAvailable = false;
    return NS_OK;
  }

  bool didAuthFail = m_nextState == NNTP_AUTHORIZE_RESPONSE ||
    m_nextState == NNTP_PASSWORD_RESPONSE;
  nsresult rv = m_newsFolder->GetAuthenticationCredentials(m_msgWindow,
    true, didAuthFail, authAvailable);
  NS_ENSURE_SUCCESS(rv, rv);

  // What we do depends on whether or not we have valid credentials
  return *authAvailable ? OnPromptAuthAvailable() : OnPromptCanceled();
}

NS_IMETHODIMP nsNNTPProtocol::OnPromptAuthAvailable()
{
  NS_ENSURE_STATE(m_nextState == NNTP_SUSPENDED);

  // We previously suspended the request; now resume it to read input
  if (m_request)
    m_request->Resume();

  // Now we have our password details accessible from the group, so just call
  // into the state machine to start the process going again.
  m_nextState = NNTP_BEGIN_AUTHORIZE;
  return ProcessProtocolState(nullptr, nullptr, 0, 0);
}

NS_IMETHODIMP nsNNTPProtocol::OnPromptCanceled()
{
  NS_ENSURE_STATE(m_nextState == NNTP_SUSPENDED);
 
  // We previously suspended the request; now resume it to read input
  if (m_request)
    m_request->Resume();

  // Since the prompt was canceled, we can no longer continue the connection.
  // Thus, we need to go to the NNTP_ERROR state.
  m_nextState = NNTP_ERROR;
  return ProcessProtocolState(nullptr, nullptr, 0, 0);
}

nsresult nsNNTPProtocol::DisplayNewsgroups()
{
  m_nextState = NEWS_DONE;
  ClearFlag(NNTP_PAUSE_FOR_READ);

  MOZ_LOG(NNTP, LogLevel::Info,("(%p) DisplayNewsgroups()",this));

  return NS_OK;
}

nsresult nsNNTPProtocol::BeginNewsgroups()
{
  m_nextState = NNTP_NEWGROUPS;
  mBytesReceived = 0;
    mBytesReceivedSinceLastStatusUpdate = 0;
    m_startTime = PR_Now();
  return NS_OK;
}

nsresult nsNNTPProtocol::ProcessNewsgroups(nsIInputStream * inputStream, uint32_t length)
{
  char *line, *lineToFree, *s, *s1=NULL, *s2=NULL;
  uint32_t status = 0;
  nsresult rv = NS_OK;

  bool pauseForMoreData = false;
  line = lineToFree = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  if(!line)
    return rv;  /* no line yet */

                     /* End of list?
   */
  if (line[0]=='.' && line[1]=='\0')
  {
    ClearFlag(NNTP_PAUSE_FOR_READ);
    bool xactive=false;
    rv = m_nntpServer->QueryExtension("XACTIVE",&xactive);
    if (NS_SUCCEEDED(rv) && xactive)
    {
      nsAutoCString groupName;
      rv = m_nntpServer->GetFirstGroupNeedingExtraInfo(groupName);
      if (NS_SUCCEEDED(rv)) {
        rv = m_nntpServer->FindGroup(groupName, getter_AddRefs(m_newsFolder));
        NS_ASSERTION(NS_SUCCEEDED(rv), "FindGroup failed");
        m_nextState = NNTP_LIST_XACTIVE;
        MOZ_LOG(NNTP, LogLevel::Info,("(%p) listing xactive for %s", this,
                                   groupName.get()));
        PR_Free(lineToFree);
        return NS_OK;
      }
    }
    m_nextState = NEWS_DONE;

    PR_Free(lineToFree);
    if(status > 0)
      return NS_OK;
    else
      return rv;
  }
  else if (line [0] == '.' && line [1] == '.')
    /* The NNTP server quotes all lines beginning with "." by doubling it. */
    line++;

    /* almost correct
  */
  if(status > 1)
  {
    mBytesReceived += status;
    mBytesReceivedSinceLastStatusUpdate += status;
  }

  /* format is "rec.arts.movies.past-films 7302 7119 y"
   */
  s = PL_strchr (line, ' ');
  if (s)
  {
    *s = 0;
    s1 = s+1;
    s = PL_strchr (s1, ' ');
    if (s)
    {
      *s = 0;
      s2 = s+1;
      s = PL_strchr (s2, ' ');
      if (s)
      {
        *s = 0;
      }
    }
  }

  mBytesReceived += status;
  mBytesReceivedSinceLastStatusUpdate += status;

  NS_ASSERTION(m_nntpServer, "no nntp incoming server");
  if (m_nntpServer) {
    rv = m_nntpServer->AddNewsgroupToList(line);
    NS_ASSERTION(NS_SUCCEEDED(rv),"failed to add to subscribe ds");
  }

  bool xactive=false;
  rv = m_nntpServer->QueryExtension("XACTIVE",&xactive);
  if (NS_SUCCEEDED(rv) && xactive)
  {
    nsAutoCString charset;
    nsAutoString lineUtf16;
    if (NS_SUCCEEDED(m_nntpServer->GetCharset(charset)) &&
        NS_SUCCEEDED(nsMsgI18NConvertToUnicode(charset.get(),
                                               nsDependentCString(line),
                                               lineUtf16, true)))
      m_nntpServer->SetGroupNeedsExtraInfo(NS_ConvertUTF16toUTF8(lineUtf16),
                                           true);
    else
      m_nntpServer->SetGroupNeedsExtraInfo(nsDependentCString(line), true);
  }

  PR_Free(lineToFree);
  return rv;
}

/* Ahhh, this like print's out the headers and stuff
 *
 * always returns 0
 */

nsresult nsNNTPProtocol::BeginReadNewsList()
{
  m_readNewsListCount = 0;
    mNumGroupsListed = 0;
    m_nextState = NNTP_READ_LIST;

    mBytesReceived = 0;
    mBytesReceivedSinceLastStatusUpdate = 0;
    m_startTime = PR_Now();

  return NS_OK;
}

#define RATE_CONSTANT 976.5625      /* PR_USEC_PER_SEC / 1024 bytes */

static void ComputeRate(int32_t bytes, PRTime startTime, float *rate)
{
  // rate = (bytes / USECS since start) * RATE_CONSTANT

  // compute usecs since we started.
  int32_t delta = (int32_t)(PR_Now() - startTime);

  // compute rate
  if (delta > 0) {
    *rate = (float) ((bytes * RATE_CONSTANT) / delta);
  }
  else {
    *rate = 0.0;
  }
}

/* display a list of all or part of the newsgroups list
 * from the news server
 */
nsresult nsNNTPProtocol::ReadNewsList(nsIInputStream * inputStream, uint32_t length)
{
  nsresult rv = NS_OK;
  int32_t i=0;
  uint32_t status = 1;

  bool pauseForMoreData = false;
  char *line, *lineToFree;
  line = lineToFree = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  if (pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    PR_Free(lineToFree);
    return NS_OK;
  }

  if (!line)
    return rv;  /* no line yet */

  /* End of list? */
  if (line[0]=='.' && line[1]=='\0')
  {
    bool listpnames=false;
    NS_ASSERTION(m_nntpServer, "no nntp incoming server");
    if (m_nntpServer) {
      rv = m_nntpServer->QueryExtension("LISTPNAMES",&listpnames);
    }
    if (NS_SUCCEEDED(rv) && listpnames)
      m_nextState = NNTP_LIST_PRETTY_NAMES;
    else
      m_nextState = DISPLAY_NEWSGROUPS;
    ClearFlag(NNTP_PAUSE_FOR_READ);
    PR_Free(lineToFree);
    return NS_OK;
  }
  else if (line[0] == '.')
  {
    if ((line[1] == ' ') || (line[1] == '.' && line [2] == '.' && line[3] == ' '))
    {
      // some servers send "... 0000000001 0000000002 y"
      // and some servers send ". 0000000001 0000000002 y"
      // just skip that those lines
      // see bug #69231 and #123560
      PR_Free(lineToFree);
      return rv;
    }
    // The NNTP server quotes all lines beginning with "." by doubling it, so unquote
    line++;
  }

  /* almost correct
  */
  if(status > 1)
  {
    mBytesReceived += status;
    mBytesReceivedSinceLastStatusUpdate += status;

    if ((mBytesReceivedSinceLastStatusUpdate > UPDATE_THRESHHOLD) && m_msgWindow) {
      mBytesReceivedSinceLastStatusUpdate = 0;

      nsCOMPtr <nsIMsgStatusFeedback> msgStatusFeedback;

      rv = m_msgWindow->GetStatusFeedback(getter_AddRefs(msgStatusFeedback));
      NS_ENSURE_SUCCESS(rv, rv);

      nsString statusString;

      nsCOMPtr<nsIStringBundleService> bundleService =
        mozilla::services::GetStringBundleService();
      NS_ENSURE_TRUE(bundleService, NS_ERROR_UNEXPECTED);

      nsCOMPtr<nsIStringBundle> bundle;
      rv = bundleService->CreateBundle(NEWS_MSGS_URL, getter_AddRefs(bundle));
      NS_ENSURE_SUCCESS(rv, rv);

      nsAutoString bytesStr;
      bytesStr.AppendInt(mBytesReceived / 1024);

      // compute the rate, and then convert it have one
      // decimal precision.
      float rate = 0.0;
      ComputeRate(mBytesReceived, m_startTime, &rate);
      char rate_buf[RATE_STR_BUF_LEN];
      PR_snprintf(rate_buf,RATE_STR_BUF_LEN,"%.1f", rate);

      nsAutoString numGroupsStr;
      numGroupsStr.AppendInt(mNumGroupsListed);
      NS_ConvertASCIItoUTF16 rateStr(rate_buf);

      const char16_t *formatStrings[3] = { numGroupsStr.get(), bytesStr.get(), rateStr.get()};
      rv = bundle->FormatStringFromName(u"bytesReceived",
        formatStrings, 3,
        getter_Copies(statusString));

      rv = msgStatusFeedback->ShowStatusString(statusString);
      if (NS_FAILED(rv)) {
        PR_Free(lineToFree);
        return rv;
      }
    }
  }

  /* find whitespace separator if it exits */
  for(i=0; line[i] != '\0' && !NET_IS_SPACE(line[i]); i++)
    ;  /* null body */

  line[i] = 0; /* terminate group name */

  /* store all the group names */
  NS_ASSERTION(m_nntpServer, "no nntp incoming server");
  if (m_nntpServer) {
    m_readNewsListCount++;
    mNumGroupsListed++;
    rv = m_nntpServer->AddNewsgroupToList(line);
//    NS_ASSERTION(NS_SUCCEEDED(rv),"failed to add to subscribe ds");
    // since it's not fatal, don't let this error stop the LIST command.
    rv = NS_OK;
  }
  else
    rv = NS_ERROR_FAILURE;

  if (m_readNewsListCount == READ_NEWS_LIST_COUNT_MAX) {
    m_readNewsListCount = 0;
    if (mUpdateTimer) {
      mUpdateTimer->Cancel();
      mUpdateTimer = nullptr;
    }
    mUpdateTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
    NS_ASSERTION(NS_SUCCEEDED(rv),"failed to create timer");
    if (NS_FAILED(rv)) {
      PR_Free(lineToFree);
      return rv;
    }

    mInputStream = inputStream;

    const uint32_t kUpdateTimerDelay = READ_NEWS_LIST_TIMEOUT;
    rv = mUpdateTimer->InitWithCallback(static_cast<nsITimerCallback*>(this), kUpdateTimerDelay,
      nsITimer::TYPE_ONE_SHOT);
    NS_ASSERTION(NS_SUCCEEDED(rv),"failed to init timer");
    if (NS_FAILED(rv)) {
      PR_Free(lineToFree);
      return rv;
    }

    m_nextState = NNTP_SUSPENDED;

    // suspend necko request until timeout
    // might not have a request if someone called CloseSocket()
    // see bug #195440
    if (m_request)
      m_request->Suspend();
  }

  PR_Free(lineToFree);
  return rv;
}

NS_IMETHODIMP
nsNNTPProtocol::Notify(nsITimer *timer)
{
  NS_ASSERTION(timer == mUpdateTimer.get(), "Hey, this ain't my timer!");
  mUpdateTimer = nullptr;    // release my hold
  TimerCallback();
  return NS_OK;
}

void nsNNTPProtocol::TimerCallback()
{
  MOZ_LOG(NNTP, LogLevel::Info,("nsNNTPProtocol::TimerCallback\n"));
  m_nextState = NNTP_READ_LIST;

  // process whatever is already in the buffer at least once.
  //
  // NOTE: while downloading, it would almost be enough to just
  // resume necko since it will call us again with data.  however,
  // if we are at the end of the data stream then we must call
  // ProcessProtocolState since necko will not call us again.
  //
  // NOTE: this function may Suspend necko.  Suspend is a reference
  // counted (i.e., two suspends requires two resumes before the
  // request will actually be resumed).
  //
  ProcessProtocolState(nullptr, mInputStream, 0,0);

  // resume necko request
  // might not have a request if someone called CloseSocket()
  // see bug #195440
  if (m_request)
    m_request->Resume();

  return;
}

void nsNNTPProtocol::HandleAuthenticationFailure()
{
  nsCOMPtr<nsIMsgIncomingServer> server(do_QueryInterface(m_nntpServer));
  nsCString hostname;
  server->GetRealHostName(hostname);
  int32_t choice = 1;
  MsgPromptLoginFailed(m_msgWindow, hostname, &choice);

  if (choice == 1) // Cancel
  {
    // When the user requests to cancel the connection, we can't do anything
    // anymore.
    NNTP_LOG_NOTE("Password failed, user opted to cancel connection");
    m_nextState = NNTP_ERROR;
    return;
  }

  if (choice == 2) // New password
  {
    NNTP_LOG_NOTE("Password failed, user opted to enter new password");
    NS_ASSERTION(m_newsFolder, "no newsFolder");
    m_newsFolder->ForgetAuthenticationCredentials();
  }
  else if (choice == 0) // Retry
  {
    NNTP_LOG_NOTE("Password failed, user opted to retry");
  }

  // At this point, we've either forgotten the password or opted to retry. In
  // both cases, we need to try to auth with the password again, so return to
  // the authentication state.
  m_nextState = NNTP_BEGIN_AUTHORIZE;
}

///////////////////////////////////////////////////////////////////////////////
// XOVER, XHDR, and HEAD processing code
// Used for filters
// State machine explanation located in doxygen comments for nsNNTPProtocol
///////////////////////////////////////////////////////////////////////////////

nsresult nsNNTPProtocol::BeginReadXover()
{
  int32_t count;     /* Response fields */
  nsresult rv = NS_OK;

  rv = SetCurrentGroup();
  NS_ENSURE_SUCCESS(rv, rv);

  /* Make sure we never close and automatically reopen the connection at this
  point; we'll confuse libmsg too much... */

  SetFlag(NNTP_SOME_PROTOCOL_SUCCEEDED);

  /* We have just issued a GROUP command and read the response.
  Now parse that response to help decide which articles to request
  xover data for.
   */
  PR_sscanf(m_responseText,
    "%d %d %d",
    &count,
    &m_firstPossibleArticle,
    &m_lastPossibleArticle);

  m_newsgroupList = do_CreateInstance(NS_NNTPNEWSGROUPLIST_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = m_newsgroupList->Initialize(m_runningURL, m_newsFolder);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = m_newsFolder->UpdateSummaryFromNNTPInfo(m_firstPossibleArticle, m_lastPossibleArticle, count);
  NS_ENSURE_SUCCESS(rv, rv);

  m_numArticlesLoaded = 0;

  // if the user sets max_articles to a bogus value, get them everything
  m_numArticlesWanted = m_maxArticles > 0 ? m_maxArticles : 1L << 30;

  m_nextState = NNTP_FIGURE_NEXT_CHUNK;
  ClearFlag(NNTP_PAUSE_FOR_READ);
  return NS_OK;
}

nsresult nsNNTPProtocol::FigureNextChunk()
{
    nsresult rv = NS_OK;
  int32_t status = 0;

  nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(m_runningURL);
  if (m_firstArticle > 0)
  {
      MOZ_LOG(NNTP, LogLevel::Info,("(%p) add to known articles:  %d - %d", this, m_firstArticle, m_lastArticle));

      if (NS_SUCCEEDED(rv) && m_newsgroupList) {
          rv = m_newsgroupList->AddToKnownArticles(m_firstArticle,
                                                 m_lastArticle);
      }

    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (m_numArticlesLoaded >= m_numArticlesWanted)
  {
    m_nextState = NEWS_PROCESS_XOVER;
    ClearFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

    NS_ASSERTION(m_newsgroupList, "no newsgroupList");
    if (!m_newsgroupList) return NS_ERROR_FAILURE;

    bool getOldMessages = false;
    if (m_runningURL) {
      rv = m_runningURL->GetGetOldMessages(&getOldMessages);
      NS_ENSURE_SUCCESS(rv, rv);
    }

    rv = m_newsgroupList->SetGetOldMessages(getOldMessages);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = m_newsgroupList->GetRangeOfArtsToDownload(m_msgWindow,
      m_firstPossibleArticle,
      m_lastPossibleArticle,
      m_numArticlesWanted - m_numArticlesLoaded,
      &(m_firstArticle),
      &(m_lastArticle),
      &status);

  NS_ENSURE_SUCCESS(rv, rv);

  if (m_firstArticle <= 0 || m_firstArticle > m_lastArticle)
  {
    /* Nothing more to get. */
    m_nextState = NEWS_PROCESS_XOVER;
    ClearFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  MOZ_LOG(NNTP, LogLevel::Info,("(%p) Chunk will be (%d-%d)", this, m_firstArticle, m_lastArticle));

  m_articleNumber = m_firstArticle;

    /* was MSG_InitXOVER() */
    if (m_newsgroupList) {
        rv = m_newsgroupList->InitXOVER(m_firstArticle, m_lastArticle);
  }

  NS_ENSURE_SUCCESS(rv, rv);

  ClearFlag(NNTP_PAUSE_FOR_READ);
  if (TestFlag(NNTP_NO_XOVER_SUPPORT))
    m_nextState = NNTP_READ_GROUP;
  else
    m_nextState = NNTP_XOVER_SEND;

  return NS_OK;
}

nsresult nsNNTPProtocol::XoverSend()
{
  char outputBuffer[OUTPUT_BUFFER_SIZE];

    PR_snprintf(outputBuffer,
        OUTPUT_BUFFER_SIZE,
        "XOVER %d-%d" CRLF,
        m_firstArticle,
        m_lastArticle);

    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = NNTP_XOVER_RESPONSE;
    SetFlag(NNTP_PAUSE_FOR_READ);

  return SendData(outputBuffer);
}

/* see if the xover response is going to return us data
 * if the proper code isn't returned then assume xover
 * isn't supported and use
 * normal read_group
 */

nsresult nsNNTPProtocol::ReadXoverResponse()
{
#ifdef TEST_NO_XOVER_SUPPORT
  m_responseCode = MK_NNTP_RESPONSE_CHECK_ERROR; /* pretend XOVER generated an error */
#endif

    if(m_responseCode != MK_NNTP_RESPONSE_XOVER_OK)
    {
        /* If we didn't get back "224 data follows" from the XOVER request,
       then that must mean that this server doesn't support XOVER.  Or
       maybe the server's XOVER support is busted or something.  So,
       in that case, fall back to the very slow HEAD method.

       But, while debugging here at HQ, getting into this state means
       something went very wrong, since our servers do XOVER.  Thus
       the assert.
         */
    /*NS_ASSERTION (0,"something went very wrong");*/
    m_nextState = NNTP_READ_GROUP;
    SetFlag(NNTP_NO_XOVER_SUPPORT);
    }
    else
    {
        m_nextState = NNTP_XOVER;
    }

    return NS_OK;  /* continue */
}

/* process the xover list as it comes from the server
 * and load it into the sort list.
 */

nsresult nsNNTPProtocol::ReadXover(nsIInputStream * inputStream, uint32_t length)
{
  char *line, *lineToFree;
  nsresult rv;
  uint32_t status = 1;

  bool pauseForMoreData = false;
  line = lineToFree = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  if(!line)
    return rv;  /* no line yet or TCP error */

  if(line[0] == '.' && line[1] == '\0')
  {
    m_nextState = NNTP_XHDR_SEND;
    ClearFlag(NNTP_PAUSE_FOR_READ);
    PR_Free(lineToFree);
    return NS_OK;
  }
  else if (line [0] == '.' && line [1] == '.')
    /* The NNTP server quotes all lines beginning with "." by doubling it. */
    line++;

    /* almost correct
  */
  if(status > 1)
  {
    mBytesReceived += status;
    mBytesReceivedSinceLastStatusUpdate += status;
  }

  rv = m_newsgroupList->ProcessXOVERLINE(line, &status);
  NS_ASSERTION(NS_SUCCEEDED(rv), "failed to process the XOVERLINE");

  m_numArticlesLoaded++;
  PR_Free(lineToFree);
  return rv;
}

/* Finished processing all the XOVER data.
*/

nsresult nsNNTPProtocol::ProcessXover()
{
  nsresult rv;

  /* xover_parse_state stored in MSG_Pane cd->pane */
  NS_ASSERTION(m_newsgroupList, "no newsgroupList");
  if (!m_newsgroupList) return NS_ERROR_FAILURE;

  // Some people may use the notifications in CallFilters to close the cached
  // connections, which will clear m_newsgroupList. So we keep a copy for
  // ourselves to ward off this threat.
  nsCOMPtr<nsINNTPNewsgroupList> list(m_newsgroupList);
  list->CallFilters();
  int32_t status = 0;
  rv = list->FinishXOVERLINE(0, &status);
  m_newsgroupList = nullptr;
  if (NS_SUCCEEDED(rv) && status < 0) return NS_ERROR_FAILURE;

  m_nextState = NEWS_DONE;

  return NS_OK;
}

nsresult nsNNTPProtocol::XhdrSend()
{
  nsCString header;
  m_newsgroupList->InitXHDR(header);
  if (header.IsEmpty())
  {
    m_nextState = NNTP_FIGURE_NEXT_CHUNK;
    return NS_OK;
  }
  
  char outputBuffer[OUTPUT_BUFFER_SIZE];
  PR_snprintf(outputBuffer, OUTPUT_BUFFER_SIZE, "XHDR %s %d-%d" CRLF,
              header.get(), m_firstArticle, m_lastArticle);

  m_nextState = NNTP_RESPONSE;
  m_nextStateAfterResponse = NNTP_XHDR_RESPONSE;
  SetFlag(NNTP_PAUSE_FOR_READ);

  return SendData(outputBuffer);
}

nsresult nsNNTPProtocol::XhdrResponse(nsIInputStream *inputStream)
{
  if (m_responseCode != MK_NNTP_RESPONSE_XHDR_OK)
  {
    m_nextState = NNTP_READ_GROUP;
    // The reasoning behind setting this flag and not an XHDR flag is that we
    // are going to have to use HEAD instead. At that point, using XOVER as
    // well is just wasting bandwidth.
    SetFlag(NNTP_NO_XOVER_SUPPORT);
    return NS_OK;
  }
  
  char *line, *lineToFree;
  nsresult rv;
  uint32_t status = 1;

  bool pauseForMoreData = false;
  line = lineToFree = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  if (pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  if (!line)
    return rv;  /* no line yet or TCP error */

  if (line[0] == '.' && line[1] == '\0')
  {
    m_nextState = NNTP_XHDR_SEND;
    ClearFlag(NNTP_PAUSE_FOR_READ);
    PR_Free(lineToFree);
    return NS_OK;
  }

  if (status > 1)
  {
    mBytesReceived += status;
    mBytesReceivedSinceLastStatusUpdate += status;
  }

  rv = m_newsgroupList->ProcessXHDRLine(nsDependentCString(line));
  NS_ASSERTION(NS_SUCCEEDED(rv), "failed to process the XHDRLINE");

  m_numArticlesLoaded++;
  PR_Free(lineToFree);
  return rv;
}

nsresult nsNNTPProtocol::ReadHeaders()
{
  if(m_articleNumber > m_lastArticle)
  {  /* end of groups */

    m_newsgroupList->InitHEAD(-1);
    m_nextState = NNTP_FIGURE_NEXT_CHUNK;
    ClearFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }
  else
  {
    m_newsgroupList->InitHEAD(m_articleNumber);

    char outputBuffer[OUTPUT_BUFFER_SIZE];
    PR_snprintf(outputBuffer,
      OUTPUT_BUFFER_SIZE,
      "HEAD %ld" CRLF,
      m_articleNumber++);
    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = NNTP_READ_GROUP_RESPONSE;

    SetFlag(NNTP_PAUSE_FOR_READ);
    return SendData(outputBuffer);
  }
}

/* See if the "HEAD" command was successful
*/

nsresult nsNNTPProtocol::ReadNewsgroupResponse()
{
  if (m_responseCode == MK_NNTP_RESPONSE_ARTICLE_HEAD)
  {     /* Head follows - parse it:*/
    m_nextState = NNTP_READ_GROUP_BODY;

    return NS_OK;
  }
  else
  {
    m_newsgroupList->HEADFailed(m_articleNumber);
    m_nextState = NNTP_READ_GROUP;
    return NS_OK;
  }
}

/* read the body of the "HEAD" command
*/
nsresult nsNNTPProtocol::ReadNewsgroupBody(nsIInputStream * inputStream, uint32_t length)
{
  char *line, *lineToFree;
  nsresult rv;
  uint32_t status = 1;

  bool pauseForMoreData = false;
  line = lineToFree = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  /* if TCP error of if there is not a full line yet return
  */
  if(!line)
    return rv;

  MOZ_LOG(NNTP, LogLevel::Info,("(%p) read_group_body: got line: %s|",this,line));

  /* End of body? */
  if (line[0]=='.' && line[1]=='\0')
  {
    m_nextState = NNTP_READ_GROUP;
    ClearFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }
  else if (line [0] == '.' && line [1] == '.')
    /* The NNTP server quotes all lines beginning with "." by doubling it. */
    line++;

  nsCString safe_line(line);
  rv = m_newsgroupList->ProcessHEADLine(safe_line);
  PR_Free(lineToFree);
  return rv;
}


nsresult nsNNTPProtocol::GetNewsStringByID(int32_t stringID, char16_t **aString)
{
  nsresult rv;
  nsAutoString resultString(NS_LITERAL_STRING("???"));

  if (!m_stringBundle)
  {
    nsCOMPtr<nsIStringBundleService> bundleService =
      mozilla::services::GetStringBundleService();
    NS_ENSURE_TRUE(bundleService, NS_ERROR_UNEXPECTED);

    rv = bundleService->CreateBundle(NEWS_MSGS_URL, getter_AddRefs(m_stringBundle));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (m_stringBundle) {
    char16_t *ptrv = nullptr;
    rv = m_stringBundle->GetStringFromID(stringID, &ptrv);

    if (NS_FAILED(rv)) {
      resultString.AssignLiteral("[StringID");
      resultString.AppendInt(stringID);
      resultString.AppendLiteral("?]");
      *aString = ToNewUnicode(resultString);
    }
    else {
      *aString = ptrv;
    }
  }
  else {
    rv = NS_OK;
    *aString = ToNewUnicode(resultString);
  }
  return rv;
}

nsresult nsNNTPProtocol::GetNewsStringByName(const char *aName, char16_t **aString)
{
  nsresult rv;
  nsAutoString resultString(NS_LITERAL_STRING("???"));
  if (!m_stringBundle)
  {
    nsCOMPtr<nsIStringBundleService> bundleService =
      mozilla::services::GetStringBundleService();
    NS_ENSURE_TRUE(bundleService, NS_ERROR_UNEXPECTED);

    rv = bundleService->CreateBundle(NEWS_MSGS_URL, getter_AddRefs(m_stringBundle));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (m_stringBundle)
  {
    nsAutoString unicodeName;
    CopyASCIItoUTF16(nsDependentCString(aName), unicodeName);

    char16_t *ptrv = nullptr;
    rv = m_stringBundle->GetStringFromName(unicodeName.get(), &ptrv);

    if (NS_FAILED(rv))
    {
      resultString.AssignLiteral("[StringName");
      resultString.Append(NS_ConvertASCIItoUTF16(aName));
      resultString.AppendLiteral("?]");
      *aString = ToNewUnicode(resultString);
    }
    else
    {
      *aString = ptrv;
    }
  }
  else
  {
    rv = NS_OK;
    *aString = ToNewUnicode(resultString);
  }
  return rv;
}

// sspitzer:  PostMessageInFile is derived from nsSmtpProtocol::SendMessageInFile()
nsresult nsNNTPProtocol::PostMessageInFile(nsIFile *postMessageFile)
{
    nsCOMPtr<nsIURI> url = do_QueryInterface(m_runningURL);
    if (url && postMessageFile)
        nsMsgProtocol::PostMessage(url, postMessageFile);

    SetFlag(NNTP_PAUSE_FOR_READ);

    // for now, we are always done at this point..we aren't making multiple
    // calls to post data...

    // always issue a '.' and CRLF when we are done...
    PL_strcpy(m_dataBuf, "." CRLF);
    SendData(m_dataBuf);
    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = NNTP_SEND_POST_DATA_RESPONSE;
    return NS_OK;
}

nsresult nsNNTPProtocol::PostData()
{
    /* returns 0 on done and negative on error
     * positive if it needs to continue.
     */
    NNTP_LOG_NOTE("nsNNTPProtocol::PostData()");
    nsresult rv = NS_OK;

    nsCOMPtr <nsINNTPNewsgroupPost> message;
    rv = m_runningURL->GetMessageToPost(getter_AddRefs(message));
    if (NS_SUCCEEDED(rv))
    {
        nsCOMPtr<nsIFile> filePath;
        rv = message->GetPostMessageFile(getter_AddRefs(filePath));
        if (NS_SUCCEEDED(rv))
            PostMessageInFile(filePath);
     }

    return NS_OK;
}


/* interpret the response code from the server
 * after the post is done
 */
nsresult nsNNTPProtocol::PostDataResponse()
{
  if (m_responseCode != MK_NNTP_RESPONSE_POST_OK)
  {
    AlertError(MK_NNTP_ERROR_MESSAGE,m_responseText);
    m_nextState = NEWS_ERROR;
    return NS_ERROR_FAILURE;
  }
    m_nextState = NEWS_POST_DONE;
  ClearFlag(NNTP_PAUSE_FOR_READ);
  return NS_OK;
}

nsresult nsNNTPProtocol::CheckForArticle()
{
  m_nextState = NEWS_ERROR;
  if (m_responseCode >= 220 && m_responseCode <= 223) {
    /* Yes, this article is already there, we're all done. */
    return NS_OK;
  }
  else
  {
  /* The article isn't there, so the failure we had earlier wasn't due to
     a duplicate message-id.  Return the error from that previous
     posting attempt (which is already in ce->URL_s->error_msg). */
    return NS_ERROR_FAILURE;
  }
}

nsresult nsNNTPProtocol::StartCancel()
{
  nsresult rv = SendData(NNTP_CMD_POST);

  m_nextState = NNTP_RESPONSE;
  m_nextStateAfterResponse = NEWS_DO_CANCEL;
  SetFlag(NNTP_PAUSE_FOR_READ);
  return rv;
}

void nsNNTPProtocol::CheckIfAuthor(nsIMsgIdentity *aIdentity, const nsCString &aOldFrom, nsCString &aFrom)
{
  nsAutoCString from;
  nsresult rv = aIdentity->GetEmail(from);
  if (NS_FAILED(rv))
    return;
  MOZ_LOG(NNTP, LogLevel::Info,("from = %s", from.get()));

  nsCString us;
  nsCString them;
  ExtractEmail(EncodedHeader(from), us);
  ExtractEmail(EncodedHeader(aOldFrom), them);

  MOZ_LOG(NNTP, LogLevel::Info,("us = %s, them = %s", us.get(), them.get()));

  if (us.Equals(them, nsCaseInsensitiveCStringComparator()))
    aFrom = from;
}

nsresult nsNNTPProtocol::DoCancel()
{
    int32_t status = 0;
    bool failure = false;
    nsresult rv = NS_OK;
    bool requireConfirmationForCancel = true;
    bool showAlertAfterCancel = true;

  /* #### Should we do a more real check than this?  If the POST command
     didn't respond with "MK_NNTP_RESPONSE_POST_SEND_NOW Ok", then it's not ready for us to throw a
     message at it...   But the normal posting code doesn't do this check.
     Why?
   */
  NS_ASSERTION (m_responseCode == MK_NNTP_RESPONSE_POST_SEND_NOW, "code != POST_SEND_NOW");

  nsCOMPtr<nsIStringBundleService> bundleService =
    mozilla::services::GetStringBundleService();
  NS_ENSURE_TRUE(bundleService, NS_ERROR_OUT_OF_MEMORY);

  nsCOMPtr<nsIStringBundle> brandBundle;
  bundleService->CreateBundle("chrome://branding/locale/brand.properties",
                              getter_AddRefs(brandBundle));
  NS_ENSURE_TRUE(brandBundle, NS_ERROR_FAILURE);

  nsString brandFullName;
  rv = brandBundle->GetStringFromName(u"brandFullName",
                                      getter_Copies(brandFullName));
  NS_ENSURE_SUCCESS(rv,rv);
  NS_ConvertUTF16toUTF8 appName(brandFullName);

  nsCString newsgroups(m_cancelNewsgroups);
  nsCString distribution (m_cancelDistribution);
  nsCString id (m_cancelID);
  nsCString oldFrom(m_cancelFromHdr);

  nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr<nsIPrompt> dialog;
  if (m_runningURL)
  {
    nsCOMPtr<nsIMsgMailNewsUrl> msgUrl (do_QueryInterface(m_runningURL));
    rv = GetPromptDialogFromUrl(msgUrl, getter_AddRefs(dialog));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (id.IsEmpty() || newsgroups.IsEmpty())
    return NS_ERROR_FAILURE;

  m_cancelNewsgroups.Truncate();
  m_cancelDistribution.Truncate();
  m_cancelFromHdr.Truncate();
  m_cancelID.Truncate();

  nsString alertText;
  nsString confirmText;
  int32_t confirmCancelResult = 0;

  // A little early to declare, but the goto causes problems
  nsAutoCString otherHeaders;

  /* Make sure that this loser isn't cancelling someone else's posting.
     Yes, there are occasionally good reasons to do so.  Those people
     capable of making that decision (news admins) have other tools with
     which to cancel postings (like telnet.)

     Don't do this if server tells us it will validate user. DMB 3/19/97
   */
  bool cancelchk=false;
  rv = m_nntpServer->QueryExtension("CANCELCHK",&cancelchk);
  nsCString from;
  if (NS_SUCCEEDED(rv) && !cancelchk)
  {
    NNTP_LOG_NOTE("CANCELCHK not supported");

    // get the current identity from the news session....
    nsCOMPtr<nsIMsgAccountManager> accountManager =
      do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
    if (NS_SUCCEEDED(rv) && accountManager) {
      nsCOMPtr<nsIArray> identities;
      rv = accountManager->GetAllIdentities(getter_AddRefs(identities));
      NS_ENSURE_SUCCESS(rv, rv);

      uint32_t length;
      rv = identities->GetLength(&length);
      NS_ENSURE_SUCCESS(rv, rv);

      for (uint32_t i = 0; i < length && from.IsEmpty(); ++i)
      {
        nsCOMPtr<nsIMsgIdentity> identity(do_QueryElementAt(identities, i, &rv));
        if (NS_SUCCEEDED(rv))
          CheckIfAuthor(identity, oldFrom, from);
      }
    }

    if (from.IsEmpty())
    {
      GetNewsStringByName("cancelDisallowed", getter_Copies(alertText));
      rv = dialog->Alert(nullptr, alertText.get());
      // XXX:  todo, check rv?

      /* After the cancel is disallowed, Make the status update to be the same as though the
         cancel was allowed, otherwise, the newsgroup is not able to take further requests as
         reported here */
      status = MK_NNTP_CANCEL_DISALLOWED;
      m_nextState = NNTP_RESPONSE;
      m_nextStateAfterResponse = NNTP_SEND_POST_DATA_RESPONSE;
      SetFlag(NNTP_PAUSE_FOR_READ);
      failure = true;
      goto FAIL;
    }
    else
    {
      MOZ_LOG(NNTP, LogLevel::Info,("(%p) CANCELCHK not supported, so post the cancel message as %s", this, from.get()));
    }
  }
  else
    NNTP_LOG_NOTE("CANCELCHK supported, don't do the us vs. them test");

  // QA needs to be able to disable this confirm dialog, for the automated tests.  see bug #31057
  rv = prefBranch->GetBoolPref(PREF_NEWS_CANCEL_CONFIRM, &requireConfirmationForCancel);
  if (NS_FAILED(rv) || requireConfirmationForCancel) {
    /* Last chance to cancel the cancel.*/
    GetNewsStringByName("cancelConfirm", getter_Copies(confirmText));
    bool dummyValue = false;
    rv = dialog->ConfirmEx(nullptr, confirmText.get(), nsIPrompt::STD_YES_NO_BUTTONS,
                           nullptr, nullptr, nullptr, nullptr, &dummyValue, &confirmCancelResult);
    if (NS_FAILED(rv))
    	confirmCancelResult = 1; // Default to No.
  }
  else
    confirmCancelResult = 0; // Default to Yes.
    
  if (confirmCancelResult != 0) {
      // they cancelled the cancel
      status = MK_NNTP_NOT_CANCELLED;
      failure = true;
      goto FAIL;
  }

  otherHeaders.AppendLiteral("Control: cancel ");
  otherHeaders += id;
  otherHeaders.AppendLiteral(CRLF);
  if (!distribution.IsEmpty()) {
    otherHeaders.AppendLiteral("Distribution: ");
    otherHeaders += distribution;
    otherHeaders.AppendLiteral(CRLF);
  }

  m_cancelStatus = 0;

  {
    /* NET_BlockingWrite() should go away soon? I think. */
    /* The following are what we really need to cancel a posted message */
    char *data;
    data = PR_smprintf("From: %s" CRLF
                       "Newsgroups: %s" CRLF
                       "Subject: cancel %s" CRLF
                       "References: %s" CRLF
                       "%s" /* otherHeaders, already with CRLF */
                       CRLF /* body separator */
                       "This message was cancelled from within %s." CRLF /* body */
                       "." CRLF, /* trailing message terminator "." */
                       from.get(), newsgroups.get(), id.get(), id.get(),
                       otherHeaders.get(), appName.get());

    rv = SendData(data);
    PR_Free (data);
    if (NS_FAILED(rv)) {
      nsAutoCString errorText;
      errorText.AppendInt(status);
      AlertError(MK_TCP_WRITE_ERROR, errorText.get());
      failure = true;
      goto FAIL;
    }

    SetFlag(NNTP_PAUSE_FOR_READ);
    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = NNTP_SEND_POST_DATA_RESPONSE;

    // QA needs to be able to turn this alert off, for the automate tests.  see bug #31057
    rv = prefBranch->GetBoolPref(PREF_NEWS_CANCEL_ALERT_ON_SUCCESS, &showAlertAfterCancel);
    if (NS_FAILED(rv) || showAlertAfterCancel) {
      GetNewsStringByName("messageCancelled", getter_Copies(alertText));
      rv = dialog->Alert(nullptr, alertText.get());
      // XXX:  todo, check rv?
    }

    if (!m_runningURL) return NS_ERROR_FAILURE;

    // delete the message from the db here.
    NS_ASSERTION(NS_SUCCEEDED(rv) && m_newsFolder && (m_key != nsMsgKey_None), "need more to remove this message from the db");
    if ((m_key != nsMsgKey_None) && (m_newsFolder))
       rv = m_newsFolder->RemoveMessage(m_key);

  }

FAIL:
  NS_ASSERTION(m_newsFolder,"no news folder");
  if (m_newsFolder)
    rv = ( failure ) ? m_newsFolder->CancelFailed()
                     : m_newsFolder->CancelComplete();

  return rv;
}

nsresult nsNNTPProtocol::XPATSend()
{
  nsresult rv = NS_OK;
  int32_t slash = m_searchData.FindChar('/');

  if (slash >= 0)
  {
    /* extract the XPAT encoding for one query term */
    /* char *next_search = NULL; */
    char *command = NULL;
    char *unescapedCommand = NULL;
    char *endOfTerm = NULL;
    NS_MsgSACopy (&command, m_searchData.get() + slash + 1);
    endOfTerm = PL_strchr(command, '/');
    if (endOfTerm)
      *endOfTerm = '\0';
    NS_MsgSACat(&command, CRLF);

    unescapedCommand = MSG_UnEscapeSearchUrl(command);

    /* send one term off to the server */
    rv = SendData(unescapedCommand);

    m_nextState = NNTP_RESPONSE;
    m_nextStateAfterResponse = NNTP_XPAT_RESPONSE;
    SetFlag(NNTP_PAUSE_FOR_READ);

    PR_Free(command);
    PR_Free(unescapedCommand);
  }
  else
  {
    m_nextState = NEWS_DONE;
  }
  return rv;
}

nsresult nsNNTPProtocol::XPATResponse(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t status = 1;
  nsresult rv;

  if (m_responseCode != MK_NNTP_RESPONSE_XPAT_OK)
  {
    AlertError(MK_NNTP_ERROR_MESSAGE,m_responseText);
    m_nextState = NNTP_ERROR;
    ClearFlag(NNTP_PAUSE_FOR_READ);
    return NS_ERROR_FAILURE;
  }

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  NNTP_LOG_READ(line);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  if (line)
  {
    if (line[0] != '.')
    {
      long articleNumber;
      PR_sscanf(line, "%ld", &articleNumber);
      nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(m_runningURL);
      if (mailnewsurl)
      {
        nsCOMPtr <nsIMsgSearchSession> searchSession;
        nsCOMPtr <nsIMsgSearchAdapter> searchAdapter;
        mailnewsurl->GetSearchSession(getter_AddRefs(searchSession));
        if (searchSession)
        {
          searchSession->GetRunningAdapter(getter_AddRefs(searchAdapter));
          if (searchAdapter)
            searchAdapter->AddHit((uint32_t) articleNumber);
        }
      }
    }
    else
    {
      /* set up the next term for next time around */
      int32_t slash = m_searchData.FindChar('/');

      if (slash >= 0)
        m_searchData.Cut(0, slash + 1);
      else
        m_searchData.Truncate();

      m_nextState = NNTP_XPAT_SEND;
      ClearFlag(NNTP_PAUSE_FOR_READ);
      PR_FREEIF(line);
      return NS_OK;
    }
  }
  PR_FREEIF(line);
  return NS_OK;
}

nsresult nsNNTPProtocol::ListPrettyNames()
{

  nsCString group_name;
  char outputBuffer[OUTPUT_BUFFER_SIZE];

  m_newsFolder->GetRawName(group_name);
  PR_snprintf(outputBuffer,
    OUTPUT_BUFFER_SIZE,
    "LIST PRETTYNAMES %.512s" CRLF,
    group_name.get());

  nsresult rv = SendData(outputBuffer);
  NNTP_LOG_NOTE(outputBuffer);
  m_nextState = NNTP_RESPONSE;
  m_nextStateAfterResponse = NNTP_LIST_PRETTY_NAMES_RESPONSE;

  return rv;
}

nsresult nsNNTPProtocol::ListPrettyNamesResponse(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t status = 0;

  if (m_responseCode != MK_NNTP_RESPONSE_LIST_OK)
  {
    m_nextState = DISPLAY_NEWSGROUPS;
    /*    m_nextState = NEWS_DONE; */
    ClearFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData);

  NNTP_LOG_READ(line);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  if (line)
  {
    if (line[0] != '.')
    {
#if 0 // SetPrettyName is not yet implemented. No reason to bother
      int i;
      /* find whitespace separator if it exits */
      for (i=0; line[i] != '\0' && !NET_IS_SPACE(line[i]); i++)
        ;  /* null body */

      char *prettyName;
      if(line[i] == '\0')
        prettyName = &line[i];
      else
        prettyName = &line[i+1];

      line[i] = 0; /* terminate group name */
      if (i > 0) {
        nsAutoCString charset;
        nsAutoString lineUtf16, prettyNameUtf16;
        if (NS_FAILED(m_nntpServer->GetCharset(charset) ||
            NS_FAILED(ConvertToUnicode(charset, line, lineUtf16)) ||
            NS_FAILED(ConvertToUnicode(charset, prettyName, prettyNameUtf16)))) {
          CopyUTF8toUTF16(line, lineUtf16);
          CopyUTF8toUTF16(prettyName, prettyNameUtf16);
        }
        m_nntpServer->SetPrettyNameForGroup(lineUtf16, prettyNameUtf16);

        MOZ_LOG(NNTP, LogLevel::Info,("(%p) adding pretty name %s", this,
               NS_ConvertUTF16toUTF8(prettyNameUtf16).get()));
      }
#endif
    }
    else
    {
      m_nextState = DISPLAY_NEWSGROUPS;  /* this assumes we were doing a list */
      /*      m_nextState = NEWS_DONE;   */ /* ### dmb - don't really know */
      ClearFlag(NNTP_PAUSE_FOR_READ);
      PR_FREEIF(line);
      return NS_OK;
    }
  }
  PR_FREEIF(line);
  return NS_OK;
}

nsresult nsNNTPProtocol::ListXActive()
{
  nsCString group_name;
  nsresult rv;
  rv = m_newsFolder->GetRawName(group_name);
  NS_ENSURE_SUCCESS(rv, rv);

  char outputBuffer[OUTPUT_BUFFER_SIZE];

  PR_snprintf(outputBuffer,
    OUTPUT_BUFFER_SIZE,
    "LIST XACTIVE %.512s" CRLF,
    group_name.get());

  rv = SendData(outputBuffer);

  m_nextState = NNTP_RESPONSE;
  m_nextStateAfterResponse = NNTP_LIST_XACTIVE_RESPONSE;

  return rv;
}

nsresult nsNNTPProtocol::ListXActiveResponse(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t status = 0;
  nsresult rv;

  NS_ASSERTION(m_responseCode == MK_NNTP_RESPONSE_LIST_OK, "code != LIST_OK");
  if (m_responseCode != MK_NNTP_RESPONSE_LIST_OK)
  {
    m_nextState = DISPLAY_NEWSGROUPS;
    /*    m_nextState = NEWS_DONE; */
    ClearFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData);

  NNTP_LOG_READ(line);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

   /* almost correct */
  if(status > 1)
  {
    mBytesReceived += status;
    mBytesReceivedSinceLastStatusUpdate += status;
  }

  if (line)
  {
    if (line[0] != '.')
    {
      char *s = line;
      /* format is "rec.arts.movies.past-films 7302 7119 csp"
      */
      while (*s && !NET_IS_SPACE(*s))
        s++;
      if (*s)
      {
        char flags[32];  /* ought to be big enough */
        *s = 0;
        PR_sscanf(s + 1,
          "%d %d %31s",
          &m_firstPossibleArticle,
          &m_lastPossibleArticle,
          flags);


        NS_ASSERTION(m_nntpServer, "no nntp incoming server");
        if (m_nntpServer) {
          rv = m_nntpServer->AddNewsgroupToList(line);
          NS_ASSERTION(NS_SUCCEEDED(rv),"failed to add to subscribe ds");
        }

        /* we're either going to list prettynames first, or list
        all prettynames every time, so we won't care so much
        if it gets interrupted. */
        MOZ_LOG(NNTP, LogLevel::Info,("(%p) got xactive for %s of %s", this, line, flags));
        /*  This isn't required, because the extra info is
        initialized to false for new groups. And it's
        an expensive call.
        */
        /* MSG_SetGroupNeedsExtraInfo(cd->host, line, false); */
      }
    }
    else
    {
      bool xactive=false;
      rv = m_nntpServer->QueryExtension("XACTIVE",&xactive);
      if (m_typeWanted == NEW_GROUPS &&
        NS_SUCCEEDED(rv) && xactive)
      {
        nsCOMPtr <nsIMsgNewsFolder> old_newsFolder;
        old_newsFolder = m_newsFolder;
        nsCString groupName;

        rv = m_nntpServer->GetFirstGroupNeedingExtraInfo(groupName);
        NS_ENSURE_SUCCESS(rv, rv);
        rv = m_nntpServer->FindGroup(groupName,
                                     getter_AddRefs(m_newsFolder));
        NS_ENSURE_SUCCESS(rv, rv);

        // see if we got a different group
        if (old_newsFolder && m_newsFolder &&
          (old_newsFolder.get() != m_newsFolder.get()))
          /* make sure we're not stuck on the same group */
        {
          MOZ_LOG(NNTP, LogLevel::Info,("(%p) listing xactive for %s", this, groupName.get()));
          m_nextState = NNTP_LIST_XACTIVE;
          ClearFlag(NNTP_PAUSE_FOR_READ);
          PR_FREEIF(line);
          return NS_OK;
        }
        else
        {
          m_newsFolder = nullptr;
        }
      }
      bool listpname;
      rv = m_nntpServer->QueryExtension("LISTPNAME",&listpname);
      if (NS_SUCCEEDED(rv) && listpname)
        m_nextState = NNTP_LIST_PRETTY_NAMES;
      else
        m_nextState = DISPLAY_NEWSGROUPS;  /* this assumes we were doing a list - who knows? */
      /*      m_nextState = NEWS_DONE;   */ /* ### dmb - don't really know */
      ClearFlag(NNTP_PAUSE_FOR_READ);
      PR_FREEIF(line);
      return NS_OK;
    }
  }
  PR_FREEIF(line);
  return NS_OK;
}

nsresult nsNNTPProtocol::SendListGroup()
{
  nsresult rv;
  char outputBuffer[OUTPUT_BUFFER_SIZE];

  NS_ASSERTION(m_newsFolder,"no newsFolder");
  if (!m_newsFolder) return NS_ERROR_FAILURE;
  nsCString newsgroupName;

  rv = m_newsFolder->GetRawName(newsgroupName);
  NS_ENSURE_SUCCESS(rv,rv);

  PR_snprintf(outputBuffer,
    OUTPUT_BUFFER_SIZE,
    "listgroup %.512s" CRLF,
    newsgroupName.get());

  m_articleList = do_CreateInstance(NS_NNTPARTICLELIST_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  rv = m_articleList->Initialize(m_newsFolder);
  NS_ENSURE_SUCCESS(rv,rv);

  rv = SendData(outputBuffer);

  m_nextState = NNTP_RESPONSE;
  m_nextStateAfterResponse = NNTP_LIST_GROUP_RESPONSE;
  SetFlag(NNTP_PAUSE_FOR_READ);

  return rv;
}

nsresult nsNNTPProtocol::SendListGroupResponse(nsIInputStream * inputStream, uint32_t length)
{
  uint32_t status = 0;

  NS_ASSERTION(m_responseCode == MK_NNTP_RESPONSE_GROUP_SELECTED, "code != GROUP_SELECTED");
  if (m_responseCode != MK_NNTP_RESPONSE_GROUP_SELECTED)
  {
    m_nextState = NEWS_DONE;
    ClearFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }

  if (line)
  {
    mozilla::DebugOnly<nsresult> rv;
    if (line[0] != '.')
    {
      nsMsgKey found_id = nsMsgKey_None;
      PR_sscanf(line, "%ld", &found_id);
      rv = m_articleList->AddArticleKey(found_id);
      NS_ASSERTION(NS_SUCCEEDED(rv), "add article key failed");
    }
    else
    {
      rv = m_articleList->FinishAddingArticleKeys();
      NS_ASSERTION(NS_SUCCEEDED(rv), "finish adding article key failed");
      m_articleList = nullptr;
      m_nextState = NEWS_DONE;   /* ### dmb - don't really know */
      ClearFlag(NNTP_PAUSE_FOR_READ);
      PR_FREEIF(line);
      return NS_OK;
    }
  }
  PR_FREEIF(line);
  return NS_OK;
}


nsresult nsNNTPProtocol::Search()
{
  NS_ERROR("Search not implemented");
  return NS_ERROR_NOT_IMPLEMENTED;
}

nsresult nsNNTPProtocol::SearchResponse()
{
  if (MK_NNTP_RESPONSE_TYPE(m_responseCode) == MK_NNTP_RESPONSE_TYPE_OK)
    m_nextState = NNTP_SEARCH_RESULTS;
  else
    m_nextState = NEWS_DONE;
  ClearFlag(NNTP_PAUSE_FOR_READ);
  return NS_OK;
}

nsresult nsNNTPProtocol::SearchResults(nsIInputStream *inputStream, uint32_t length)
{
  uint32_t status = 1;
  nsresult rv;

  bool pauseForMoreData = false;
  char *line = m_lineStreamBuffer->ReadNextLine(inputStream, status, pauseForMoreData, &rv);

  if(pauseForMoreData)
  {
    SetFlag(NNTP_PAUSE_FOR_READ);
    return NS_OK;
  }
  if (!line)
    return rv;  /* no line yet */

  if ('.' == line[0])
  {
    /* all overview lines received */
    m_nextState = NEWS_DONE;
    ClearFlag(NNTP_PAUSE_FOR_READ);
  }
  PR_FREEIF(line);
  return rv;
}

/* Sets state for the transfer. This used to be known as net_setup_news_stream */
nsresult nsNNTPProtocol::SetupForTransfer()
{
  if (m_typeWanted == NEWS_POST)
  {
    m_nextState = NNTP_SEND_POST_DATA;
  }
  else if(m_typeWanted == LIST_WANTED)
  {
    if (TestFlag(NNTP_USE_FANCY_NEWSGROUP))
      m_nextState = NNTP_LIST_XACTIVE_RESPONSE;
    else
      m_nextState = NNTP_READ_LIST_BEGIN;
  }
  else if(m_typeWanted == GROUP_WANTED)
    m_nextState = NNTP_XOVER_BEGIN;
  else if(m_typeWanted == NEW_GROUPS)
    m_nextState = NNTP_NEWGROUPS_BEGIN;
  else if(m_typeWanted == ARTICLE_WANTED ||
    m_typeWanted== CANCEL_WANTED)
    m_nextState = NNTP_BEGIN_ARTICLE;
  else if (m_typeWanted== SEARCH_WANTED)
    m_nextState = NNTP_XPAT_SEND;
  else
  {
    NS_ERROR("unexpected");
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// The following method is used for processing the news state machine.
// It returns a negative number (mscott: we'll change this to be an enumerated type which we'll coordinate
// with the netlib folks?) when we are done processing.
//////////////////////////////////////////////////////////////////////////////////////////////////////////
nsresult nsNNTPProtocol::ProcessProtocolState(nsIURI * url, nsIInputStream * inputStream,
                                              uint64_t sourceOffset, uint32_t length)
{
  nsresult status = NS_OK;
  nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(m_runningURL);
  if (inputStream && (!mailnewsurl || !m_nntpServer))
  {
    // In these cases, we are going to return since our data is effectively
    // invalid. However, nsInputStream would really rather that we at least read
    // some of our input data (even if not all of it). Therefore, we'll read a
    // little bit.
    char buffer[128];
    uint32_t readData = 0;
    inputStream->Read(buffer, 127, &readData);
    buffer[readData] = '\0';
    MOZ_LOG(NNTP, LogLevel::Debug, ("(%p) Ignoring data: %s", this, buffer));
  }

  if (!mailnewsurl)
    return NS_OK; // probably no data available - it's OK.

  if (!m_nntpServer)
  {
    // Parsing must result in our m_nntpServer being set, so we should never
    // have a case where m_nntpServer being false is safe. Most likely, we have
    // already closed our socket and we are merely flushing out the socket
    // receive queue. Since the user told us to stop, don't process any more
    // input.
    return inputStream ? inputStream->Close() : NS_OK;
  }

  ClearFlag(NNTP_PAUSE_FOR_READ);

  while(!TestFlag(NNTP_PAUSE_FOR_READ))
  {
    MOZ_LOG(NNTP, LogLevel::Info,("(%p) Next state: %s",this, stateLabels[m_nextState]));
    // examine our current state and call an appropriate handler for that state.....
    switch(m_nextState)
    {
    case NNTP_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = NewsResponse(inputStream, length);
      break;

      // mscott: I've removed the states involving connections on the assumption
      // that core netlib will now be managing that information.

    case NNTP_LOGIN_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = LoginResponse();
      break;

    case NNTP_SEND_MODE_READER:
      status = SendModeReader();
      break;

    case NNTP_SEND_MODE_READER_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = SendModeReaderResponse();
      break;

    case SEND_LIST_EXTENSIONS:
      status = SendListExtensions();
      break;
    case SEND_LIST_EXTENSIONS_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = SendListExtensionsResponse(inputStream, length);
      break;
    case SEND_LIST_SEARCHES:
      status = SendListSearches();
      break;
    case SEND_LIST_SEARCHES_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = SendListSearchesResponse(inputStream, length);
      break;
    case NNTP_LIST_SEARCH_HEADERS:
      status = SendListSearchHeaders();
      break;
    case NNTP_LIST_SEARCH_HEADERS_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = SendListSearchHeadersResponse(inputStream, length);
      break;
    case NNTP_GET_PROPERTIES:
      status = GetProperties();
      break;
    case NNTP_GET_PROPERTIES_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = GetPropertiesResponse(inputStream, length);
      break;
    case SEND_LIST_SUBSCRIPTIONS:
      status = SendListSubscriptions();
      break;
    case SEND_LIST_SUBSCRIPTIONS_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = SendListSubscriptionsResponse(inputStream, length);
      break;

    case SEND_FIRST_NNTP_COMMAND:
      status = SendFirstNNTPCommand(url);
      break;
    case SEND_FIRST_NNTP_COMMAND_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = SendFirstNNTPCommandResponse();
      break;

    case NNTP_SEND_GROUP_FOR_ARTICLE:
      status = SendGroupForArticle();
      break;
    case NNTP_SEND_GROUP_FOR_ARTICLE_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = SendGroupForArticleResponse();
      break;
    case NNTP_SEND_ARTICLE_NUMBER:
      status = SendArticleNumber();
      break;

    case SETUP_NEWS_STREAM:
      status = SetupForTransfer();
      break;

    case NNTP_BEGIN_AUTHORIZE:
      status = BeginAuthorization();
      break;

    case NNTP_AUTHORIZE_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = AuthorizationResponse();
      break;

    case NNTP_PASSWORD_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = PasswordResponse();
      break;

      // read list
    case NNTP_READ_LIST_BEGIN:
      status = BeginReadNewsList();
      break;
    case NNTP_READ_LIST:
      status = ReadNewsList(inputStream, length);
      break;

      // news group
    case DISPLAY_NEWSGROUPS:
      status = DisplayNewsgroups();
      break;
    case NNTP_NEWGROUPS_BEGIN:
      status = BeginNewsgroups();
      break;
    case NNTP_NEWGROUPS:
      status = ProcessNewsgroups(inputStream, length);
      break;

      // article specific
    case NNTP_BEGIN_ARTICLE:
      status = BeginArticle();
      break;

    case NNTP_READ_ARTICLE:
      status = ReadArticle(inputStream, length);
      break;

    case NNTP_XOVER_BEGIN:
      status = BeginReadXover();
      break;

    case NNTP_FIGURE_NEXT_CHUNK:
      status = FigureNextChunk();
      break;

    case NNTP_XOVER_SEND:
      status = XoverSend();
      break;

    case NNTP_XOVER:
      status = ReadXover(inputStream, length);
      break;

    case NNTP_XOVER_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = ReadXoverResponse();
      break;

    case NEWS_PROCESS_XOVER:
    case NEWS_PROCESS_BODIES:
      status = ProcessXover();
      break;

    case NNTP_XHDR_SEND:
      status = XhdrSend();
      break;

    case NNTP_XHDR_RESPONSE:
      status = XhdrResponse(inputStream);
      break;

    case NNTP_READ_GROUP:
      status = ReadHeaders();
      break;

    case NNTP_READ_GROUP_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = ReadNewsgroupResponse();
      break;

    case NNTP_READ_GROUP_BODY:
      status = ReadNewsgroupBody(inputStream, length);
      break;

    case NNTP_SEND_POST_DATA:
      status = PostData();
      break;
    case NNTP_SEND_POST_DATA_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = PostDataResponse();
      break;

    case NNTP_CHECK_FOR_MESSAGE:
      status = CheckForArticle();
      break;

      // cancel
    case NEWS_START_CANCEL:
      status = StartCancel();
      break;

    case NEWS_DO_CANCEL:
      status = DoCancel();
      break;

      // XPAT
    case NNTP_XPAT_SEND:
      status = XPATSend();
      break;
    case NNTP_XPAT_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = XPATResponse(inputStream, length);
      break;

      // search
    case NNTP_SEARCH:
      status = Search();
      break;
    case NNTP_SEARCH_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = SearchResponse();
      break;
    case NNTP_SEARCH_RESULTS:
      status = SearchResults(inputStream, length);
      break;


    case NNTP_LIST_PRETTY_NAMES:
      status = ListPrettyNames();
      break;
    case NNTP_LIST_PRETTY_NAMES_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = ListPrettyNamesResponse(inputStream, length);
      break;
    case NNTP_LIST_XACTIVE:
      status = ListXActive();
      break;
    case NNTP_LIST_XACTIVE_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = ListXActiveResponse(inputStream, length);
      break;
    case NNTP_LIST_GROUP:
      status = SendListGroup();
      break;
    case NNTP_LIST_GROUP_RESPONSE:
      if (inputStream == nullptr)
        SetFlag(NNTP_PAUSE_FOR_READ);
      else
        status = SendListGroupResponse(inputStream, length);
      break;
    case NEWS_DONE:
      m_nextState = NEWS_FREE;
      break;
    case NEWS_POST_DONE:
      NNTP_LOG_NOTE("NEWS_POST_DONE");
      mailnewsurl->SetUrlState(false, NS_OK);
      m_nextState = NEWS_FREE;
      break;
    case NEWS_ERROR:
      NNTP_LOG_NOTE("NEWS_ERROR");
      if (m_responseCode == MK_NNTP_RESPONSE_ARTICLE_NOTFOUND || m_responseCode == MK_NNTP_RESPONSE_ARTICLE_NONEXIST)
        mailnewsurl->SetUrlState(false, NS_MSG_NEWS_ARTICLE_NOT_FOUND);
      else
        mailnewsurl->SetUrlState(false, NS_ERROR_FAILURE);
      m_nextState = NEWS_FREE;
      break;
    case NNTP_ERROR:
      // XXX do we really want to remove the connection from
      // the cache on error?
      /* check if this connection came from the cache or if it was
      * a new connection.  If it was not new lets start it over
      * again.  But only if we didn't have any successful protocol
      * dialog at all.
      */
      FinishMemCacheEntry(false);  // cleanup mem cache entry
      if (m_responseCode != MK_NNTP_RESPONSE_ARTICLE_NOTFOUND && m_responseCode != MK_NNTP_RESPONSE_ARTICLE_NONEXIST)
        return CloseConnection();
      MOZ_FALLTHROUGH;
    case NEWS_FREE:
      // Remember when we last used this connection
      m_lastActiveTimeStamp = PR_Now();
      CleanupAfterRunningUrl();
      MOZ_FALLTHROUGH;
    case NNTP_SUSPENDED:
      return NS_OK;
      break;
    default:
      /* big error */
      return NS_ERROR_FAILURE;

    } // end switch

    if (NS_FAILED(status) && m_nextState != NEWS_ERROR &&
        m_nextState != NNTP_ERROR && m_nextState != NEWS_FREE)
    {
      m_nextState = NNTP_ERROR;
      ClearFlag(NNTP_PAUSE_FOR_READ);
    }

  } /* end big while */

  return NS_OK; /* keep going */
}

NS_IMETHODIMP nsNNTPProtocol::CloseConnection()
{
  MOZ_LOG(NNTP, LogLevel::Info,("(%p) ClosingConnection",this));
  SendData(NNTP_CMD_QUIT); // this will cause OnStopRequest get called, which will call CloseSocket()
  // break some cycles
  CleanupNewsgroupList();

  if (m_nntpServer) {
    m_nntpServer->RemoveConnection(this);
    m_nntpServer = nullptr;
  }
  CloseSocket();
  m_newsFolder = nullptr;

  if (m_articleList) {
    m_articleList->FinishAddingArticleKeys();
    m_articleList = nullptr;
  }

  m_key = nsMsgKey_None;
  return NS_OK;
}

nsresult nsNNTPProtocol::CleanupNewsgroupList()
{
    nsresult rv;
    if (!m_newsgroupList) return NS_OK;
  int32_t status = 0;
    rv = m_newsgroupList->FinishXOVERLINE(0,&status);
    m_newsgroupList = nullptr;
    NS_ASSERTION(NS_SUCCEEDED(rv), "FinishXOVERLINE failed");
    return rv;
}

nsresult nsNNTPProtocol::CleanupAfterRunningUrl()
{
  /* do we need to know if we're parsing xover to call finish xover?  */
  /* yes, I think we do! Why did I think we should??? */
  /* If we've gotten to NEWS_FREE and there is still XOVER
  data, there was an error or we were interrupted or
  something.  So, tell libmsg there was an abnormal
  exit so that it can free its data. */

  MOZ_LOG(NNTP, LogLevel::Info,("(%p) CleanupAfterRunningUrl()", this));

  // send StopRequest notification after we've cleaned up the protocol
  // because it can synchronously causes a new url to get run in the
  // protocol - truly evil, but we're stuck at the moment.
  if (m_channelListener)
    (void) m_channelListener->OnStopRequest(this, m_channelContext, NS_OK);

  if (m_loadGroup)
    (void) m_loadGroup->RemoveRequest(static_cast<nsIRequest *>(this), nullptr, NS_OK);
  CleanupNewsgroupList();

  // clear out mem cache entry so we're not holding onto it.
  if (m_runningURL)
  {
    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(m_runningURL);
    if (mailnewsurl)
    {
      mailnewsurl->SetUrlState(false, NS_OK);
      mailnewsurl->SetMemCacheEntry(nullptr);
    }
  }

  Cleanup();

  mDisplayInputStream = nullptr;
  mDisplayOutputStream = nullptr;
  mProgressEventSink = nullptr;
  SetOwner(nullptr);

  m_channelContext = nullptr;
  m_channelListener = nullptr;
  m_loadGroup = nullptr;
  mCallbacks = nullptr;

  // disable timeout before caching.
  nsCOMPtr<nsISocketTransport> strans = do_QueryInterface(m_transport);
  if (strans)
    strans->SetTimeout(nsISocketTransport::TIMEOUT_READ_WRITE, PR_UINT32_MAX);

  // don't mark ourselves as not busy until we are done cleaning up the connection. it should be the
  // last thing we do.
  SetIsBusy(false);

  return NS_OK;
}

nsresult nsNNTPProtocol::CloseSocket()
{
  MOZ_LOG(NNTP, LogLevel::Info,("(%p) ClosingSocket()",this));

  if (m_nntpServer) {
    m_nntpServer->RemoveConnection(this);
    m_nntpServer = nullptr;
  }

  CleanupAfterRunningUrl(); // is this needed?
  return nsMsgProtocol::CloseSocket();
}

void nsNNTPProtocol::SetProgressBarPercent(uint32_t aProgress, uint32_t aProgressMax)
{
  // XXX 64-bit
  if (mProgressEventSink)
    mProgressEventSink->OnProgress(this, m_channelContext, uint64_t(aProgress),
                                   uint64_t(aProgressMax));
}

nsresult
nsNNTPProtocol::SetProgressStatus(const char16_t *aMessage)
{
  nsresult rv = NS_OK;
  if (mProgressEventSink)
    rv = mProgressEventSink->OnStatus(this, m_channelContext, NS_OK, aMessage);
  return rv;
}

NS_IMETHODIMP nsNNTPProtocol::GetContentType(nsACString &aContentType)
{

  // if we've been set with a content type, then return it....
  // this happens when we go through libmime now as it sets our new content type
  if (!mContentType.IsEmpty())
  {
    aContentType = mContentType;
    return NS_OK;
  }

  // otherwise do what we did before...

  if (m_typeWanted == GROUP_WANTED)
    aContentType.AssignLiteral("x-application-newsgroup");
  else if (m_typeWanted == IDS_WANTED)
    aContentType.AssignLiteral("x-application-newsgroup-listids");
  else
    aContentType.AssignLiteral("message/rfc822");
  return NS_OK;
}

nsresult
nsNNTPProtocol::AlertError(int32_t errorCode, const char *text)
{
  nsresult rv = NS_OK;

  // get the prompt from the running url....
  if (m_runningURL) {
    nsCOMPtr<nsIMsgMailNewsUrl> msgUrl (do_QueryInterface(m_runningURL));
    nsCOMPtr<nsIPrompt> dialog;
    rv = GetPromptDialogFromUrl(msgUrl, getter_AddRefs(dialog));
    NS_ENSURE_SUCCESS(rv, rv);

    nsString alertText;
    rv = GetNewsStringByID(MK_NNTP_ERROR_MESSAGE, getter_Copies(alertText));
    NS_ENSURE_SUCCESS(rv,rv);
    if (text) {
      alertText.Append(' ');
      alertText.Append(NS_ConvertASCIItoUTF16(text));
    }
    rv = dialog->Alert(nullptr, alertText.get());
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return rv;
}

NS_IMETHODIMP nsNNTPProtocol::GetCurrentFolder(nsIMsgFolder **aFolder)
{
  nsresult rv = NS_ERROR_NULL_POINTER;
  NS_ENSURE_ARG_POINTER(aFolder);
  if (m_newsFolder)
    rv = m_newsFolder->QueryInterface(NS_GET_IID(nsIMsgFolder), (void **) aFolder);
  return rv;
}