File: NNTPConnection.java

package info (click to toggle)
libgnuinet-java 1.1-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,368 kB
  • ctags: 1,710
  • sloc: java: 12,475; sh: 5,408; makefile: 218; xml: 126
file content (1407 lines) | stat: -rw-r--r-- 38,349 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
/*
 * $Id: NNTPConnection.java,v 1.10 2004/08/19 21:27:07 dog Exp $
 * Copyright (C) 2002 The Free Software Foundation
 * 
 * This file is part of GNU inetlib, a library.
 * 
 * GNU inetlib is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * GNU inetlib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * As a special exception, if you link this library with other files to
 * produce an executable, this library does not by itself cause the
 * resulting executable to be covered by the GNU General Public License.
 * This exception does not however invalidate any other reasons why the
 * executable file might be covered by the GNU General Public License.
 */

package gnu.inet.nntp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.InetSocketAddress;
import java.net.ProtocolException;
import java.net.Socket;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;
import java.util.TimeZone;

import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;

import gnu.inet.util.CRLFInputStream;
import gnu.inet.util.CRLFOutputStream;
import gnu.inet.util.LineInputStream;
import gnu.inet.util.Logger;
import gnu.inet.util.MessageInputStream;
import gnu.inet.util.SaslCallbackHandler;
import gnu.inet.util.SaslInputStream;
import gnu.inet.util.SaslOutputStream;

/**
 * An NNTP client.
 * This object is used to establish and manage a connection to an NNTP
 * server.
 *
 * @author <a hef='mailto:dog@gnu.org'>Chris Burdess</a>
 * @version $Revision: 1.10 $ $Date: 2004/08/19 21:27:07 $
 */
public class NNTPConnection
  implements NNTPConstants
{

  /**
   * The default NNTP port.
   */
  public static final int DEFAULT_PORT = 119;

  /**
   * The hostname of the host we are connected to.
   */
  protected String hostname;

  /**
   * The port on the host we are connected to.
   */
  protected int port;

  /**
   * The socket used for network communication.
   */
  protected Socket socket;

  /**
   * The socket input stream.
   */
  protected LineInputStream in;

  /**
   * The socket output stream.
   */
  protected CRLFOutputStream out;

  /**
   * Whether the host permits posting of articles.
   */
  protected boolean canPost;

  /**
   * The greeting issued by the host when we connected.
   */
  protected String welcome;

  /**
   * Pending data, if any.
   */
  protected PendingData pendingData;

  /**
   * Whether to log protocol-level information to stderr.
   */
  protected boolean debug;

  private static final String DOT = ".";
  private static final String US_ASCII = "US-ASCII";

  /**
   * Creates a new connection object.
   * @param hostname the hostname or IP address of the news server
   */
  public NNTPConnection (String hostname)
    throws IOException
  {
    this (hostname, DEFAULT_PORT, 0, 0, false);
  }

  /**
   * Creates a new connection object.
   * @param hostname the hostname or IP address of the news server
   * @param port the port to connect to
   */
  public NNTPConnection (String hostname, int port)
    throws IOException
  {
    this (hostname, port, 0, 0, false);
  }

  /**
   * Creates a new connection object.
   * @param hostname the hostname or IP address of the news server
   * @param port the port to connect to
   * @param connectionTimeout the socket connection timeout
   * @param timeout the read timeout on the socket
   * @param debug whether to use debugging
   */
  public NNTPConnection (String hostname, int port,
                         int connectionTimeout, int timeout,
                         boolean debug)
    throws IOException
  {
    if (port < 0)
      {
        port = DEFAULT_PORT;
      }
    
    this.hostname = hostname;
    this.port = port;
    this.debug = debug;
    
    // Set up the socket and streams
    socket = new Socket ();
    InetSocketAddress address = new InetSocketAddress (hostname, port);
    if (connectionTimeout > 0)
      {
        socket.connect (address, connectionTimeout);
      }
    else
      {
        socket.connect (address);
      }
    if (timeout > 0)
      {
        socket.setSoTimeout (timeout);
      }
    InputStream in = socket.getInputStream ();
    in = new CRLFInputStream (in);
    this.in = new LineInputStream (in);
    OutputStream out = socket.getOutputStream ();
    out = new BufferedOutputStream (out);
    this.out = new CRLFOutputStream (out);
    
    // Read the welcome message (RFC977:2.4.3)
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case POSTING_ALLOWED:
        canPost = true;
      case NO_POSTING_ALLOWED:
        welcome = response.getMessage ();
        break;
      default:
        throw new NNTPException (response);
      }
  }
  
  /**
   * Return the welcome message sent by the server in reply to the initial
   * connection.
   * This message sometimes contains disclaimers or help information that
   * may be relevant to the user.
   */
  public String getWelcome ()
  {
    return welcome;
  }
  
  /*
   * Returns an NNTP-format date string.
   * This is only required when clients use the NEWGROUPS or NEWNEWS
   * methods, therefore rarely: we don't cache any of the variables here.
   */
  String formatDate (Date date)
  {
    DateFormat df = new SimpleDateFormat ("yyMMdd HHmmss 'GMT'");
    Calendar cal = new GregorianCalendar ();
    TimeZone gmt = TimeZone.getTimeZone ("GMT");
    cal.setTimeZone (gmt);
    df.setCalendar (cal);
    cal.setTime (date);
    return df.format (date);
  }

  /*
   * Parse the specfied NNTP date text.
   */
  Date parseDate (String text)
    throws ParseException
  {
    DateFormat df = new SimpleDateFormat ("yyMMdd HHmmss 'GMT'");
    return df.parse (text);
  }

  // RFC977:3.1 The ARTICLE, BODY, HEAD, and STAT commands

  /**
   * Send an article retrieval request to the server.
   * @param articleNumber the article number of the article to retrieve
   * @return an article response consisting of the article number and
   * message-id, and an iterator over the lines of the article header and
   * body, separated by an empty line
   */
  public ArticleResponse article (int articleNumber)
    throws IOException
  {
    return articleImpl (ARTICLE, Integer.toString(articleNumber));
  }
  
  /**
   * Send an article retrieval request to the server.
   * @param messageId the message-id of the article to retrieve
   * @return an article response consisting of the article number and
   * message-id, and an iterator over the lines of the article header and
   * body, separated by an empty line
   */
  public ArticleResponse article (String messageId)
    throws IOException
  {
    return articleImpl (ARTICLE, messageId);
  }

  /**
   * Send an article head retrieval request to the server.
   * @param articleNumber the article number of the article to head
   * @return an article response consisting of the article number and
   * message-id, and an iterator over the lines of the article header
   */
  public ArticleResponse head (int articleNumber)
    throws IOException
  {
    return articleImpl (HEAD, Integer.toString (articleNumber));
  }

  /**
   * Send an article head retrieval request to the server.
   * @param messageId the message-id of the article to head
   * @return an article response consisting of the article number and
   * message-id, and an iterator over the lines of the article header
   */
  public ArticleResponse head (String messageId)
    throws IOException
  {
    return articleImpl (HEAD, messageId);
  }

  /**
   * Send an article body retrieval request to the server.
   * @param articleNumber the article number of the article to body
   * @return an article response consisting of the article number and
   * message-id, and an iterator over the lines of the article body
   */
  public ArticleResponse body (int articleNumber)
    throws IOException
  {
    return articleImpl (BODY, Integer.toString (articleNumber));
  }

  /**
   * Send an article body retrieval request to the server.
   * @param messageId the message-id of the article to body
   * @return an article response consisting of the article number and
   * message-id, and an iterator over the lines of the article body
   */
  public ArticleResponse body (String messageId)
    throws IOException
  {
    return articleImpl (BODY, messageId);
  }

  /**
   * Send an article status request to the server.
   * @param articleNumber the article number of the article to stat
   * @return an article response consisting of the article number and
   * message-id
   */
  public ArticleResponse stat (int articleNumber)
    throws IOException
  {
    return articleImpl (STAT, Integer.toString (articleNumber));
  }

  /**
   * Send an article status request to the server.
   * @param messageId the message-id of the article to stat
   * @return an article response consisting of the article number and
   * message-id
   */
  public ArticleResponse stat (String messageId)
    throws IOException
  {
    return articleImpl (STAT, messageId);
  }

  /**
   * Performs an ARTICLE, BODY, HEAD, or STAT command.
   * @param command one of the above commands
   * @param messageId the article-number or message-id in string form
   */
  protected ArticleResponse articleImpl (String command, String messageId)
    throws IOException
  {
    if (messageId != null)
      {
        StringBuffer line = new StringBuffer (command);
        line.append (' ');
        line.append (messageId);
        send (line.toString ());
      }
    else
      {
        send (command);
      }
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case ARTICLE_FOLLOWS:
      case HEAD_FOLLOWS:
      case BODY_FOLLOWS:
        ArticleResponse aresponse = (ArticleResponse) response;
        ArticleStream astream =
          new ArticleStream (new MessageInputStream (in));
        pendingData = astream;
        aresponse.in = astream;
        return aresponse;
      case ARTICLE_RETRIEVED:
        return (ArticleResponse) response;
      default:
        // NO_GROUP_SELECTED
        // NO_ARTICLE_SELECTED
        // NO_SUCH_ARTICLE_NUMBER
        // NO_SUCH_ARTICLE
        // NO_PREVIOUS_ARTICLE
        // NO_NEXT_ARTICLE
        throw new NNTPException (response);
      }
  }
  
  // RFC977:3.2 The GROUP command

  /**
   * Send a group selection command to the server.
   * Returns a group status response.
   * @param name the name of the group to select
   */
  public GroupResponse group (String name)
    throws IOException
  {
    send (GROUP + ' ' + name);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case GROUP_SELECTED:
        return (GroupResponse) response;
      default:
        // NO_SUCH_GROUP
        throw new NNTPException (response);
      }
  }

  // RFC977:3.3 The HELP command

  /**
   * Requests a help listing.
   * @return an iterator over a collection of help lines.
   */
  public LineIterator help ()
    throws IOException
  {
    send (HELP);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case HELP_TEXT:
        LineIterator li = new LineIterator (this);
        pendingData = li;
        return li;
      default:
        throw new NNTPException (response);
      }
  }
  
  // RFC977:3.4 The IHAVE command

  /**
   * Sends an ihave command indicating that the client has an article with
   * the specified message-id.
   * @param messageId the article message-id
   * @return a PostStream if the server wants the specified article, null
   * otherwise
   */
  public PostStream ihave (String messageId)
    throws IOException
  {
    send (IHAVE + ' ' + messageId);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case SEND_TRANSFER_ARTICLE:
        return new PostStream (this, false);
      case ARTICLE_NOT_WANTED:
        return null;
      default:
        throw new NNTPException (response);
      }
  }

  // RFC(77:3.5 The LAST command

  /**
   * Sends a previous article positioning command to the server.
   * @return the article number/message-id pair associated with the new
   * article
   */
  public ArticleResponse last ()
    throws IOException
  {
    return articleImpl (LAST, null);
  }

  // RFC977:3.6 The LIST command

  /**
   * Send a group listing command to the server.
   * Returns a GroupIterator. This must be read fully before other commands
   * are issued.
   */
  public GroupIterator list ()
    throws IOException
  {
    return listImpl (LIST);
  }
  
  GroupIterator listImpl (String command)
    throws IOException
  {
    send (command);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case LIST_FOLLOWS:
        GroupIterator gi = new GroupIterator (this);
        pendingData = gi;
        return gi;
      default:
        throw new NNTPException (response);
      }
  }

  // RFC977:3.7 The NEWGROUPS command

  /**
   * Returns an iterator over the list of new groups on the server since the
   * specified date.
   * NB this method suffers from a minor millenium bug.
   * 
   * @param since the date from which to list new groups
   * @param distributions if non-null, an array of distributions to match
   */
  public LineIterator newGroups (Date since, String[]distributions)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (NEWGROUPS);
    buffer.append (' ');
    buffer.append (formatDate (since));
    if (distributions != null)
      {
        buffer.append (' ');
        for (int i = 0; i < distributions.length; i++)
          {
            if (i > 0)
              {
                buffer.append (',');
              }
            buffer.append (distributions[i]);
          }
      }
    send (buffer.toString ());
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case NEWGROUPS_LIST_FOLLOWS:
        LineIterator li = new LineIterator (this);
        pendingData = li;
        return li;
      default:
        throw new NNTPException (response);
      }
  }
  
  // RFC977:3.8 The NEWNEWS command

  /**
   * Returns an iterator over the list of message-ids posted or received to
   * the specified newsgroup(s) since the specified date.
   * NB this method suffers from a minor millenium bug.
   *
   * @param newsgroup the newsgroup wildmat
   * @param since the date from which to list new articles
   * @param distributions if non-null, a list of distributions to match
   */
  public LineIterator newNews (String newsgroup, Date since,
                               String[] distributions)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (NEWNEWS);
    buffer.append (' ');
    buffer.append (newsgroup);
    buffer.append (' ');
    buffer.append (formatDate (since));
    if (distributions != null)
      {
        buffer.append (' ');
        for (int i = 0; i < distributions.length; i++)
          {
            if (i > 0)
              {
                buffer.append (',');
              }
            buffer.append (distributions[i]);
          }
      }
    send (buffer.toString ());
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case NEWNEWS_LIST_FOLLOWS:
        LineIterator li = new LineIterator (this);
        pendingData = li;
        return li;
      default:
        throw new NNTPException (response);
      }
  }
  
  // RFC977:3.9 The NEXT command

  /**
   * Sends a next article positioning command to the server.
   * @return the article number/message-id pair associated with the new
   * article
   */
  public ArticleResponse next ()
    throws IOException
  {
    return articleImpl (NEXT, null);
  }

  // RFC977:3.10 The POST command

  /**
   * Post an article. This is a two-stage process.
   * If successful, returns an output stream to write the article to.
   * Clients should call <code>write()</code> on the stream for all the
   * bytes of the article, and finally call <code>close()</code>
   * on the stream.
   * No other method should be called in between.
   * @see #postComplete
   */
  public OutputStream post ()
    throws IOException
  {
    send (POST);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case SEND_ARTICLE:
        return new PostStream (this, false);
      default:
        // POSTING_NOT_ALLOWED
        throw new NNTPException (response);
      }
  }
  
  /**
   * Indicates that the client has finished writing all the bytes of the
   * article.
   * Called by the PostStream during <code>close()</code>.
   * @see #post
   */
  void postComplete ()
    throws IOException
  {
    send (DOT);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case ARTICLE_POSTED:
      case ARTICLE_TRANSFERRED:
        return;
      default:
        // POSTING_FAILED
        // TRANSFER_FAILED
        // ARTICLE_REJECTED
        throw new NNTPException (response);
      }
  }

  // RFC977:3.11 The QUIT command

  /**
   * Close the connection.
   * After calling this method, no further calls on this object are valid.
   */
  public void quit ()
    throws IOException
  {
    send (QUIT);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case CLOSING_CONNECTION:
        socket.close ();
        return;
      default:
        throw new NNTPException (response);
      }
  }
  
  // RFC977:3.12 The SLAVE command

  /**
   * Indicates to the server that this is a slave connection.
   */
  public void slave ()
    throws IOException
  {
    send (SLAVE);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case SLAVE_ACKNOWLEDGED:
        break;
      default:
        throw new NNTPException (response);
      }
  }
  
  // RFC2980:1.1 The CHECK command

  public boolean check (String messageId)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (CHECK);
    buffer.append (' ');
    buffer.append (messageId);
    send (buffer.toString ());
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case SEND_ARTICLE_VIA_TAKETHIS:
        return true;
      case ARTICLE_NOT_WANTED_VIA_TAKETHIS:
        return false;
      default:
        // SERVICE_DISCONTINUED
        // TRY_AGAIN_LATER
        // TRANSFER_PERMISSION_DENIED
        // COMMAND_NOT_RECOGNIZED
        throw new NNTPException (response);
      }
  }

  // RFC2980:1.2 The MODE STREAM command

  /**
   * Attempt to initialise the connection in streaming mode.
   * This is generally used to bypass the lock step nature of NNTP in order
   * to perform a series of CHECK and TAKETHIS commands.
   *
   * @return true if the server supports streaming mode
   */
  public boolean modeStream ()
    throws IOException
  {
    send (MODE_STREAM);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case STREAMING_OK:
        return true;
      default:
        // COMMAND_NOT_RECOGNIZED
        return false;
      }
  }
  
  // RFC2980:1.3 The TAKETHIS command

  /**
   * Implements the out-of-order takethis command.
   * The client uses the returned output stream to write all the bytes of the
   * article. When complete, it calls <code>close()</code> on the
   * stream.
   * @see #takethisComplete
   */
  public OutputStream takethis (String messageId)
    throws IOException
  {
    send (TAKETHIS + ' ' + messageId);
    return new PostStream (this, true);
  }

  /**
   * Completes a takethis transaction.
   * Called by PostStream.close().
   * @see #takethis
   */
  void takethisComplete ()
    throws IOException
  {
    send (DOT);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case ARTICLE_TRANSFERRED_OK:
        return;
      default:
        // SERVICE_DISCONTINUED
        // ARTICLE_TRANSFER_FAILED
        // TRANSFER_PERMISSION_DENIED
        // COMMAND_NOT_RECOGNIZED
        throw new NNTPException (response);
      }
  }
  
  // RFC2980:1.4 The XREPLIC command

  // TODO

  // RFC2980:2.1.2 The LIST ACTIVE command

  /**
   * Returns an iterator over the groups specified according to the wildmat
   * pattern. The iterator must be read fully before other commands are
   * issued.
   * @param wildmat the wildmat pattern. If null, returns all groups. If no
   * groups are matched, returns an empty iterator.
   */
  public GroupIterator listActive (String wildmat)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (LIST_ACTIVE);
    if (wildmat != null)
      {
        buffer.append (' ');
        buffer.append (wildmat);
      }
    return listImpl (buffer.toString ());
  }
  
  // RFC2980:2.1.3 The LIST ACTIVE.TIMES command

  /**
   * Returns an iterator over the active.times file.
   * Each ActiveTime object returned provides details of who created the
   * newsgroup and when.
   */
  public ActiveTimesIterator listActiveTimes ()
    throws IOException
  {
    send (LIST_ACTIVE_TIMES);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case LIST_FOLLOWS:
        return new ActiveTimesIterator (this);
      default:
        throw new NNTPException (response);
      }
  }

  // RFC2980:2.1.4 The LIST DISTRIBUTIONS command

  // TODO

  // RFC2980:2.1.5 The LIST DISTRIB.PATS command

  // TODO

  // RFC2980:2.1.6 The LIST NEWSGROUPS command

  /**
   * Returns an iterator over the group descriptions for the given groups.
   * @param wildmat if non-null, limits the groups in the iterator to the
   * specified pattern
   * @return an iterator over group name/description pairs
   * @see #xgtitle
   */
  public PairIterator listNewsgroups (String wildmat)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (LIST_NEWSGROUPS);
    if (wildmat != null)
      {
        buffer.append (' ');
        buffer.append (wildmat);
      }
    send (buffer.toString ());
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case LIST_FOLLOWS:
        PairIterator pi = new PairIterator (this);
        pendingData = pi;
        return pi;
      default:
        throw new NNTPException (response);
      }
  }

  // RFC2980:2.1.7 The LIST OVERVIEW.FMT command

  /**
   * Returns an iterator over the order in which headers are stored in the
   * overview database.
   * Each line returned by the iterator contains one header field.
   * @see #xover
   */
  public LineIterator listOverviewFmt ()
    throws IOException
  {
    send (LIST_OVERVIEW_FMT);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case LIST_FOLLOWS:
        LineIterator li = new LineIterator (this);
        pendingData = li;
        return li;
      default:
        throw new NNTPException (response);
      }
  }
  
  // RFC2980:2.1.8 The LIST SUBSCRIPTIONS command

  /**
   * Returns a list of newsgroups suitable for new users of the server.
   */
  public GroupIterator listSubscriptions ()
    throws IOException
  {
    return listImpl (LIST_SUBSCRIPTIONS);
  }

  // RFC2980:2.2 The LISTGROUP command

  /**
   * Returns a listing of all the article numbers in the specified
   * newsgroup. If the <code>group</code> parameter is null, the currently
   * selected group is assumed.
   * @param group the name of the group to list articles for
   */
  public ArticleNumberIterator listGroup (String group)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (LISTGROUP);
    if (group != null)
      {
        buffer.append (' ');
        buffer.append (group);
      }
    send (buffer.toString ());
    StatusResponse response = parseResponse (read (), true);
    switch (response.status)
      {
      case GROUP_SELECTED:
        ArticleNumberIterator ani = new ArticleNumberIterator (this);
        pendingData = ani;
        return ani;
      default:
        throw new NNTPException (response);
      }
  }

  // RFC2980:2.3 The MODE READER command

  /**
   * Indicates to the server that this is a user-agent.
   * @return true if posting is allowed, false otherwise.
   */
  public boolean modeReader ()
    throws IOException
  {
    send (MODE_READER);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case POSTING_ALLOWED:
        canPost = true;
        return canPost;
      case POSTING_NOT_ALLOWED:
        canPost = false;
        return canPost;
      default:
        throw new NNTPException (response);
      }
  }
  
  // RFC2980:2.4 The XGTITLE command

  /**
   * Returns an iterator over the list of newsgroup descriptions.
   * @param wildmat if non-null, the newsgroups to match
   */
  public PairIterator xgtitle (String wildmat)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (XGTITLE);
    if (wildmat != null)
      {
        buffer.append (' ');
        buffer.append (wildmat);
      }
    send (buffer.toString ());
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case XGTITLE_LIST_FOLLOWS:
        PairIterator pi = new PairIterator (this);
        pendingData = pi;
        return pi;
      default:
        throw new NNTPException (response);
      }
  }
  
  // RFC2980:2.6 The XHDR command

  public HeaderIterator xhdr (String header, String range)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (XHDR);
    buffer.append (' ');
    buffer.append (header);
    if (range != null)
      {
        buffer.append (' ');
        buffer.append (range);
      }
    send (buffer.toString ());
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case HEAD_FOLLOWS:
        HeaderIterator hi = new HeaderIterator (this);
        pendingData = hi;
        return hi;
      default:
        // NO_GROUP_SELECTED
        // NO_SUCH_ARTICLE
        throw new NNTPException (response);
      }
  }

  // RFC2980:2.7 The XINDEX command

  // TODO

  // RFC2980:2.8 The XOVER command

  public OverviewIterator xover (Range range)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (XOVER);
    if (range != null)
      {
        buffer.append (' ');
        buffer.append (range.toString());
      }
    send (buffer.toString ());
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case OVERVIEW_FOLLOWS:
        OverviewIterator oi = new OverviewIterator (this);
        pendingData = oi;
        return oi;
      default:
        // NO_GROUP_SELECTED
        // PERMISSION_DENIED
        throw new NNTPException (response);
      }
  }
  
  // RFC2980:2.9 The XPAT command

  // TODO

  // RFC2980:2.10 The XPATH command

  // TODO

  // RFC2980:2.11 The XROVER command

  // TODO

  // RFC2980:2.12 The XTHREAD command

  // TODO

  // RFC2980:3.1.1 Original AUTHINFO

  /**
   * Basic authentication strategy.
   * @param username the user to authenticate
   * @param password the (cleartext) password
   * @return true on success, false on failure
   */
  public boolean authinfo (String username, String password)
    throws IOException
  {
    StringBuffer buffer = new StringBuffer (AUTHINFO_USER);
    buffer.append (' ');
    buffer.append (username);
    send (buffer.toString ());
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case AUTHINFO_OK:
        return true;
      case SEND_AUTHINFOPASS:
        buffer.setLength (0);
        buffer.append (AUTHINFO_PASS);
        buffer.append (' ');
        buffer.append (password);
        send (buffer.toString ());
        response = parseResponse (read ());
        switch (response.status)
          {
          case AUTHINFO_OK:
            return true;
          case PERMISSION_DENIED:
            return false;
          default:
            throw new NNTPException (response);
          }
      default:
        // AUTHINFO_REJECTED
        throw new NNTPException (response);
      }
  }

  // RFC2980:3.1.2 AUTHINFO SIMPLE

  /**
   * Implementation of NNTP simple authentication.
   * Note that use of this authentication strategy is highly deprecated,
   * only use on servers that won't accept any other form of authentication.
   */
  public boolean authinfoSimple (String username, String password)
    throws IOException
  {
    send (AUTHINFO_SIMPLE);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case SEND_AUTHINFO_SIMPLE:
        StringBuffer buffer = new StringBuffer (username);
        buffer.append (' ');
        buffer.append (password);
        send (buffer.toString ());
        response = parseResponse (read ());
        switch (response.status)
          {
          case AUTHINFO_SIMPLE_OK:
            return true;
          case AUTHINFO_SIMPLE_DENIED:
            return false;
          default:throw new NNTPException (response);
          }
      default:
        throw new NNTPException (response);
      }
  }
  
  // RFC2980:3.1.3 AUTHINFO GENERIC

  /**
   * Authenticates the connection using the specified SASL mechanism,
   * username and password.
   * @param mechanism a SASL authentication mechanism, e.g. LOGIN, PLAIN,
   * CRAM-MD5, GSSAPI
   * @param username the authentication principal
   * @param password the authentication credentials
   */
  public boolean authinfoGeneric (String mechanism,
                                  String username, String password)
    throws IOException
  {
    String[] m = new String[] { mechanism };
    CallbackHandler ch = new SaslCallbackHandler (username, password);
    // Avoid lengthy callback procedure for GNU Crypto
    Properties p = new Properties ();
    p.put ("gnu.crypto.sasl.username", username);
    p.put ("gnu.crypto.sasl.password", password);
    SaslClient sasl =
      Sasl.createSaslClient (m, null, "smtp",
                             socket.getInetAddress ().getHostName (),
                             p, ch);
    if (sasl == null)
      {
        return false;
      }
    
    StringBuffer cmd = new StringBuffer (AUTHINFO_GENERIC);
    cmd.append (' ');
    cmd.append (mechanism);
    if (sasl.hasInitialResponse ())
      {
        cmd.append (' ');
        byte[] init = sasl.evaluateChallenge (new byte[0]);
        cmd.append (new String (init, "US-ASCII"));
      }
    send (cmd.toString ());
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case AUTHINFO_OK:
        String qop = (String) sasl.getNegotiatedProperty (Sasl.QOP);
        if ("auth-int".equalsIgnoreCase (qop)
            || "auth-conf".equalsIgnoreCase (qop))
          {
            InputStream in = socket.getInputStream ();
            in = new BufferedInputStream (in);
            in = new SaslInputStream (sasl, in);
            in = new CRLFInputStream (in);
            this.in = new LineInputStream (in);
            OutputStream out = socket.getOutputStream ();
            out = new BufferedOutputStream (out);
            out = new SaslOutputStream (sasl, out);
            this.out = new CRLFOutputStream (out);
          }
        return true;
      case PERMISSION_DENIED:
        return false;
      case COMMAND_NOT_RECOGNIZED:
      case SYNTAX_ERROR:
      case INTERNAL_ERROR:
      default:
        throw new NNTPException (response);
        // FIXME how does the server send continuations?
      }
  }
  
  // RFC2980:3.2 The DATE command

  /**
   * Returns the date on the server.
   */
  public Date date ()
    throws IOException
  {
    send (DATE);
    StatusResponse response = parseResponse (read ());
    switch (response.status)
      {
      case DATE_OK:
        String message = response.getMessage ();
        try
          {
            DateFormat df = new SimpleDateFormat ("yyyyMMddHHmmss");
            return df.parse (message);
          }
        catch (ParseException e)
          {
            throw new IOException ("Invalid date: " + message);
          }
      default:
        throw new NNTPException (response);
      }
  }

  // -- Utility functions --

  /**
   * Parse a response object from a response line sent by the server.
   */
  protected StatusResponse parseResponse (String line)
    throws ProtocolException
  {
    return parseResponse (line, false);
  }
  
  /**
   * Parse a response object from a response line sent by the server.
   * @param isListGroup whether we are invoking the LISTGROUP command
   */
  protected StatusResponse parseResponse (String line, boolean isListGroup)
    throws ProtocolException
  {
    if (line == null)
      {
        throw new ProtocolException (hostname + " closed connection");
      }
    int start = 0, end;
    short status = -1;
    String statusText = line;
    String message = null;
    end = line.indexOf (' ', start);
    if (end > start)
      {
        statusText = line.substring (start, end);
        message = line.substring (end + 1);
      }
    try
      {
        status = Short.parseShort (statusText);
      }
    catch (NumberFormatException e)
      {
        throw new ProtocolException (line);
      }
    StatusResponse response;
    switch (status)
      {
      case ARTICLE_FOLLOWS:
      case HEAD_FOLLOWS:
      case BODY_FOLLOWS:
      case ARTICLE_RETRIEVED:
      case GROUP_SELECTED:
        /* The LISTGROUP command returns a list of articles with a 211,
         * instead of the newsgroup totals returned with the GROUP command.
         * Check for this case. */
        if (status != GROUP_SELECTED || isListGroup)
          {
            try
              {
                ArticleResponse aresponse =
                  new ArticleResponse (status, message);
                // article number
                start = end + 1;
                end = line.indexOf (' ', start);
                if (end > start)
                  {
                    aresponse.articleNumber =
                      Integer.parseInt (line.substring (start, end));
                  }
                // message-id
                start = end + 1;
                end = line.indexOf (' ', start);
                if (end > start)
                  {
                    aresponse.messageId = line.substring (start, end);
                  }
                else
                  {
                    aresponse.messageId = line.substring (start);
                  }
                response = aresponse;
              }
            catch (NumberFormatException e)
              {
                // This will happen for XHDR
                response = new StatusResponse (status, message);
              }
            break;
          }
        // This is the normal case for GROUP_SELECTED
        GroupResponse gresponse = new GroupResponse (status, message);
        try
          {
            // count
            start = end + 1;
            end = line.indexOf (' ', start);
            if (end > start)
              {
                gresponse.count =
                  Integer.parseInt (line.substring (start, end));
              }
            // first
            start = end + 1;
            end = line.indexOf (' ', start);
            if (end > start)
              {
                gresponse.first =
                  Integer.parseInt (line.substring (start, end));
              }
            // last
            start = end + 1;
            end = line.indexOf (' ', start);
            if (end > start)
              {
                gresponse.last =
                  Integer.parseInt (line.substring (start, end));
              }
            // group
            start = end + 1;
            end = line.indexOf (' ', start);
            if (end > start)
              {
                gresponse.group = line.substring (start, end);
              }
            else
              {
                gresponse.group = line.substring (start);
              }
          }
        catch (NumberFormatException e)
          {
            throw new ProtocolException (line);
          }
        response = gresponse;
        break;
      default:
        response = new StatusResponse (status, message);
      }
    return response;
  }
  
  /**
   * Send a single line to the server.
   * @param line the line to send
   */
  protected void send (String line)
    throws IOException
  {
    if (pendingData != null)
      {
        // Clear pending data
        pendingData.readToEOF ();
        pendingData = null;
      }
    if (debug)
      {
        Logger logger = Logger.getInstance ();
        logger.log ("nntp", ">" + line);
      }
    byte[] data = line.getBytes (US_ASCII);
    out.write (data);
    out.writeln ();
    out.flush ();
  }
  
  /**
   * Read a single line from the server.
   * @return a line of text
   */
  protected String read ()
    throws IOException
  {
    String line = in.readLine ();
    if (debug)
      {
        Logger logger = Logger.getInstance ();
        if (line == null)
          {
            logger.log ("nntp", "<EOF");
          }
        else
          {
            logger.log ("nntp", "<" + line);
          }
      }
    return line;
  }
  
}