File: POP3Connection.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 (748 lines) | stat: -rw-r--r-- 21,916 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
/*
 * $Id: POP3Connection.java,v 1.14 2004/08/07 14:39:46 dog Exp $
 * Copyright (C) 2003 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.pop3;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ProtocolException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

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.BASE64;
import gnu.inet.util.CRLFInputStream;
import gnu.inet.util.CRLFOutputStream;
import gnu.inet.util.EmptyX509TrustManager;
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;

/**
 * A POP3 client connection.
 * This implements the entire POP3 specification as detailed in RFC 1939,
 * with the exception of the no-arg LIST and UIDL commands (use STAT
 * followed by multiple LIST and/or UIDL instead) and TOP with a specified
 * number of content lines. It also implements the POP3 extension mechanism
 * CAPA, documented in RFC 2449, as well as the STLS command to initiate TLS
 * over POP3 documented in RFC 2595 and the AUTH command in RFC 1734.
 *
 * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
 * @version $Revision: 1.14 $ $Date: 2004/08/07 14:39:46 $
 */
public class POP3Connection
{

  /**
   * The default POP3 port.
   */
  public static final int DEFAULT_PORT = 110;

  // -- POP3 vocabulary --
  private static final String _OK = "+OK";
  private static final String _ERR = "-ERR";
  private static final String _READY = "+ ";

  protected static final String STAT = "STAT";
  protected static final String LIST = "LIST";
  protected static final String RETR = "RETR";
  protected static final String DELE = "DELE";
  protected static final String NOOP = "NOOP";
  protected static final String RSET = "RSET";
  protected static final String QUIT = "QUIT";
  protected static final String TOP = "TOP";
  protected static final String UIDL = "UIDL";
  protected static final String USER = "USER";
  protected static final String PASS = "PASS";
  protected static final String APOP = "APOP";
  protected static final String CAPA = "CAPA";
  protected static final String STLS = "STLS";
  protected static final String AUTH = "AUTH";

  protected static final int OK = 0;
  protected static final int ERR = 1;
  protected static final int READY = 2;

  /**
   * The socket used to communicate with the server.
   */
  protected Socket socket;

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

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

  /**
   * The last response received from the server.
   * The status code (+OK or -ERR) is stripped from the line.
   */
  protected String response;

  /**
   * If true, print debugging information.
   */
  protected boolean debug;

  /**
   * The APOP timestamp, if sent by the server on connection.
   * Otherwise null.
   */
  protected byte[] timestamp;

  /**
   * Creates a new connection to the server.
   * @param hostname the hostname of the server to connect to
   */
  public POP3Connection (String hostname)
    throws UnknownHostException, IOException
  {
    this (hostname, -1, 0, 0, false);
  }

  /**
   * Creates a new connection to the server.
   * @param hostname the hostname of the server to connect to
   * @param port the port to connect to (if &lt;=0, use default POP3 port)
   */
  public POP3Connection (String hostname, int port)
    throws UnknownHostException, IOException
  {
    this (hostname, port, 0, 0, false);
  }

  /**
   * Creates a new connection to the server.
   * @param hostname the hostname of the server to connect to
   * @param port the port to connect to (if &lt;=0, use default POP3 port)
   * @param connectionTimeout the connection timeout, in milliseconds
   * @param timeout the I/O timeout, in milliseconds
   * @param debug print debugging information
   */
  public POP3Connection (String hostname, int port,
                         int connectionTimeout, int timeout, boolean debug)
    throws UnknownHostException, IOException
  {
    this.debug = debug;
    if (port <= 0)
      {
        port = DEFAULT_PORT;
      }
    
    // Set up socket
    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 BufferedInputStream (in);
    in = new CRLFInputStream (in);
    this.in = new LineInputStream (in);
    OutputStream out = socket.getOutputStream ();
    out = new BufferedOutputStream (out);
    this.out = new CRLFOutputStream (out);
    
    if (getResponse() != OK)
      {
        throw new ProtocolException ("Connect failed: " + response);
      }
    // APOP timestamp
    timestamp = parseTimestamp (response);
  }

  /**
   * 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
   * @return true if authentication was successful, false otherwise
   */
  public boolean auth (String mechanism, String username, String password)
    throws IOException
  {
    try
      {
        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 (AUTH);
        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 ());
        while (true)
          {
            switch (getResponse ())
              {
              case 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 READY:
                try
                  {
                    byte[] c0 = response.getBytes ("US-ASCII");
                    byte[] c1 = BASE64.decode (c0);       // challenge
                    byte[] r0 = sasl.evaluateChallenge (c1);
                    byte[] r1 = BASE64.encode (r0);       // response
                    out.write (r1);
                    out.write (0x0d);
                    out.flush ();
                  }
                catch (SaslException e)
                  {
                    // Error in SASL challenge evaluation - cancel exchange
                    out.write (0x2a);
                    out.write (0x0d);
                    out.flush ();
                  }
              default:
                return false;
              }
          }
      }
    catch (SaslException e)
      {
        return false;             // No provider for mechanism
      }
    catch (RuntimeException e)
      {
        return false;             // No javax.security.sasl classes
      }
  }
  
  /**
   * Authenticate the specified user using the APOP MD5-based method.
   * This does not transmit the password in the clear, but doesn't provide
   * any transport-level privacy features either.
   * @param username the user to authenticate
   * @param password the user's password
   */
  public boolean apop (String username, String password)
    throws IOException
  {
    if (username == null || password == null || timestamp == null)
      {
        return false;
      }
    // APOP <username> <digest>
    try
      {
        byte[] secret = password.getBytes ("US-ASCII");
        // compute digest
        byte[] target = new byte[timestamp.length + secret.length];
        System.arraycopy (timestamp, 0, target, 0, timestamp.length);
        System.arraycopy (secret, 0, target, timestamp.length, secret.length);
        MessageDigest md5 = MessageDigest.getInstance ("MD5");
        byte[] db = md5.digest (target);
        // create hexadecimal representation
        StringBuffer digest = new StringBuffer ();
        for (int i = 0; i < db.length; i++)
          {
            int c = (int) db[i];
            if (c < 0)
              {
                c += 256;
              }
            digest.append (Integer.toHexString ((c & 0xf0) >> 4));
            digest.append (Integer.toHexString (c & 0x0f));
          }
        // send command
        String cmd = new StringBuffer (APOP)
          .append (' ')
          .append (username)
          .append (' ')
          .append (digest.toString ())
          .toString ();
        send (cmd);
        return getResponse () == OK;
      }
    catch (NoSuchAlgorithmException e)
      {
        Logger logger = Logger.getInstance ();
        logger.log ("pop3", "MD5 algorithm not found");
        return false;
      }
  }
  
  /**
   * Authenticate the user using the basic USER and PASS handshake.
   * It is recommended to use a more secure authentication method such as
   * the <code>auth</code> or <code>apop</code> method if the server
   * understands them.
   * @param username the user to authenticate
   * @param password the user's password
   */
  public boolean login (String username, String password)
    throws IOException
  {
    if (username == null || password == null)
      {
        return false;
      }
    // USER <username>
    String cmd = USER + ' ' + username;
    send (cmd);
    if (getResponse () != OK)
      {
        return false;
      }
    // PASS <password>
    cmd = PASS + ' ' + password;
    send (cmd);
    return getResponse () == OK;
  }
  
  /**
   * Attempts to start TLS on the specified connection.
   * See RFC 2595 for details
   * @return true if successful, false otherwise
   */
  public boolean stls ()
    throws IOException
  {
    return stls (new EmptyX509TrustManager ());
  }
  
  /**
   * Attempts to start TLS on the specified connection.
   * See RFC 2595 for details
   * @param tm the custom trust manager to use
   * @return true if successful, false otherwise
   */
  public boolean stls (TrustManager tm)
    throws IOException
  {
    try
      {
        // Use SSLSocketFactory to negotiate a TLS session and wrap the
        // current socket.
        SSLContext context = SSLContext.getInstance ("TLS");
        // We don't require strong validation of the server certificate
        TrustManager[] trust = new TrustManager[] { tm };
        context.init (null, trust, null);
        SSLSocketFactory factory = context.getSocketFactory ();
        
        send (STLS);
        if (getResponse () != OK)
          {
            return false;
          }
        
        String hostname = socket.getInetAddress ().getHostName ();
        int port = socket.getPort ();
        SSLSocket ss =
          (SSLSocket) factory.createSocket (socket, hostname, port, true);
        String[] protocols = { "TLSv1", "SSLv3" };
        ss.setEnabledProtocols (protocols);
        ss.setUseClientMode (true);
        ss.startHandshake ();
        
        // set up streams
        InputStream in = ss.getInputStream ();
        in = new BufferedInputStream (in);
        in = new CRLFInputStream (in);
        this.in = new LineInputStream (in);
        OutputStream out = ss.getOutputStream ();
        out = new BufferedOutputStream (out);
        this.out = new CRLFOutputStream (out);
        
        return true;
      }
    catch (GeneralSecurityException e)
      {
        return false;
      }
  }
  
  /**
   * Returns the number of messages in the maildrop.
   */
  public int stat ()
    throws IOException
  {
    send (STAT);
    if (getResponse () != OK)
      {
        throw new ProtocolException ("STAT failed: " + response);
      }
    try
      {
        return
          Integer.parseInt (response.substring (0, response.indexOf (' ')));
      }
    catch (NumberFormatException e)
      {
        throw new ProtocolException ("Not a number: " + response);
      }
    catch (ArrayIndexOutOfBoundsException e)
      {
        throw new ProtocolException ("Not a STAT response: " + response);
      }
  }
  
  /**
   * Returns the size of the specified message.
   * @param msgnum the message number
   */
  public int list (int msgnum)
    throws IOException
  {
    String cmd = LIST + ' ' + msgnum;
    send (cmd);
    if (getResponse () != OK)
      {
        throw new ProtocolException ("LIST failed: " + response);
      }
    try
      {
        return
          Integer.parseInt (response.substring (response.indexOf (' ') + 1));
      }
    catch (NumberFormatException e)
      {
        throw new ProtocolException ("Not a number: " + response);
      }
  }
  
  /**
   * Returns an input stream containing the entire message.
   * This input stream must be read in its entirety before further commands
   * can be issued on this connection.
   * @param msgnum the message number
   */
  public InputStream retr (int msgnum)
    throws IOException
  {
    String cmd = RETR + ' ' + msgnum;
    send (cmd);
    if (getResponse () != OK)
      {
        throw new ProtocolException ("RETR failed: " + response);
      }
    return new MessageInputStream (in);
  }
  
  /**
   * Marks the specified message as deleted.
   * @param msgnum the message number
   */
  public void dele (int msgnum)
    throws IOException
  {
    String cmd = DELE + ' ' + msgnum;
    send (cmd);
    if (getResponse () != OK)
      {
        throw new ProtocolException ("DELE failed: " + response);
      }
  }
  
  /**
   * Does nothing.
   * This can be used to keep the connection alive.
   */
  public void noop ()
    throws IOException
  {
    send (NOOP);
    if (getResponse () != OK)
      {
        throw new ProtocolException ("NOOP failed: " + response);
      }
  }

  /**
   * If any messages have been marked as deleted, they are unmarked.
   */
  public void rset ()
    throws IOException
  {
    send (RSET);
    if (getResponse () != OK)
      {
        throw new ProtocolException ("RSET failed: " + response);
      }
  }
  
  /**
   * Closes the connection.
   * No further commands may be issued on this connection after this method
   * has been called.
   * @return true if all deleted messages were successfully removed, false
   * otherwise
   */
  public boolean quit ()
    throws IOException
  {
    send (QUIT);
    int ret = getResponse ();
    socket.close ();
    return ret == OK;
  }

  /**
   * Returns just the headers of the specified message as an input stream.
   * The stream must be read in its entirety before further commands can be
   * issued.
   * @param msgnum the message number
   */
  public InputStream top (int msgnum)
    throws IOException
  {
    String cmd = TOP + ' ' + msgnum + ' ' + '0';
    send (cmd);
    if (getResponse () != OK)
      {
        throw new ProtocolException ("TOP failed: " + response);
      }
    return new MessageInputStream (in);
  }
  
  /**
   * Returns a unique identifier for the specified message.
   * @param msgnum the message number
   */
  public String uidl (int msgnum)
    throws IOException
  {
    String cmd = UIDL + ' ' + msgnum;
    send (cmd);
    if (getResponse () != OK)
      {
        throw new ProtocolException ("UIDL failed: " + response);
      }
    return response.substring (response.indexOf (' ') + 1);
  }

  /**
   * Returns a map of message number to UID pairs.
   * Message numbers are Integers, UIDs are Strings.
   */
  public Map uidl ()
    throws IOException
  {
    send (UIDL);
    if (getResponse () != OK)
      {
        throw new ProtocolException ("UIDL failed: " + response);
      }
    Map uids = new LinkedHashMap ();
    String line = in.readLine ();
    while (line != null && !(".".equals (line)))
      {
        int si = line.indexOf (' ');
        if (si < 1)
          {
            throw new ProtocolException ("Invalid UIDL response: " + line);
          }
        try
          {
            uids.put (new Integer (line.substring (0, si)),
                      line.substring (si + 1));
          }
        catch (NumberFormatException e)
          {
            throw new ProtocolException ("Invalid message number: " + line);
          }
      }
    return Collections.unmodifiableMap (uids);
  }

  /**
   * Returns a list of capabilities supported by the POP3 server.
   * If the server does not support POP3 extensions, returns
   * <code>null</code>.
   */
  public List capa ()
    throws IOException
  {
    send (CAPA);
    if (getResponse () == OK)
      {
        final String DOT = ".";
        List list = new ArrayList ();
        for (String line = in.readLine ();
             !DOT.equals (line);
             line = in.readLine ())
          {
            list.add (line);
          }
        return Collections.unmodifiableList (list);
      }
    return null;
  }
  
  /** 
   * Send the command to the server.
   * If <code>debug</code> is <code>true</code>,
   * the command is logged.
   */
  protected void send (String command)
    throws IOException
  {
    if (debug)
      {
        Logger logger = Logger.getInstance ();
        logger.log ("pop3", "> " + command);
      }
    out.write (command);
    out.writeln ();
    out.flush ();
  }
  
  /**
   * Parse the response from the server.
   * If <code>debug</code> is <code>true</code>,
   * the response is logged.
   */
  protected int getResponse ()
    throws IOException
  {
    response = in.readLine ();
    if (debug)
      {
        Logger logger = Logger.getInstance ();
        logger.log ("pop3", "< " + response);
      }
    if (response.indexOf (_OK) == 0)
      {
        response = response.substring (3).trim ();
        return OK;
      }
    else if (response.indexOf (_ERR) == 0)
      {
        response = response.substring (4).trim ();
        return ERR;
      }
    else if (response.indexOf (_READY) == 0)
      {
        response = response.substring (2).trim ();
        return READY;
      }
    else
      {
        throw new ProtocolException ("Unexpected response: " + response);
      }
  }
  
  /*
   * Parse the APOP timestamp from the server's banner greeting.
   */
  byte[] parseTimestamp (String greeting)
    throws IOException
  {
    int bra = greeting.indexOf ('<');
    if (bra != -1)
      {
        int ket = greeting.indexOf ('>', bra);
        if (ket != -1)
          {
            String mid = greeting.substring (bra, ket + 1);
            int at = mid.indexOf ('@');
            if (at != -1)           // This is a valid RFC822 msg-id
              {
                return mid.getBytes ("US-ASCII");
              }
          }
      }
    return null;
  }
  
}