]> Pileus Git - ~andy/fetchmail/blob - pop3.c
8fd07d11008fc0ee17079f0b56fcfbd836bd5bd6
[~andy/fetchmail] / pop3.c
1 /*
2  * pop3.c -- POP3 protocol methods
3  *
4  * Copyright 1998 by Eric S. Raymond.
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include  "config.h"
9 #ifdef POP3_ENABLE
10 #include  <stdio.h>
11 #include  <string.h>
12 #include  <ctype.h>
13 #if defined(HAVE_UNISTD_H)
14 #include <unistd.h>
15 #endif
16 #if defined(STDC_HEADERS)
17 #include  <stdlib.h>
18 #endif
19  
20 #include  "fetchmail.h"
21 #include  "socket.h"
22 #include  "i18n.h"
23
24 #if OPIE_ENABLE
25 #include <opie.h>
26 #endif /* OPIE_ENABLE */
27
28 #ifndef strstr          /* glibc-2.1 declares this as a macro */
29 extern char *strstr();  /* needed on sysV68 R3V7.1. */
30 #endif /* strstr */
31
32 static int last;
33 #ifdef SDPS_ENABLE
34 char *sdps_envfrom;
35 char *sdps_envto;
36 #endif /* SDPS_ENABLE */
37
38 #if OPIE_ENABLE
39 static char lastok[POPBUFSIZE+1];
40 #endif /* OPIE_ENABLE */
41
42 #define DOTLINE(s)      (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
43
44 static int pop3_ok (int sock, char *argbuf)
45 /* parse command response */
46 {
47     int ok;
48     char buf [POPBUFSIZE+1];
49     char *bufp;
50
51     if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
52     {   bufp = buf;
53         if (*bufp == '+' || *bufp == '-')
54             bufp++;
55         else
56             return(PS_PROTOCOL);
57
58         while (isalpha(*bufp))
59             bufp++;
60
61         if (*bufp)
62           *(bufp++) = '\0';
63
64         if (strcmp(buf,"+OK") == 0)
65         {
66 #if OPIE_ENABLE
67             strcpy(lastok, bufp);
68 #endif /* OPIE_ENABLE */
69             ok = 0;
70         }
71         else if (strncmp(buf,"-ERR", 4) == 0)
72         {
73             if (stage == STAGE_FETCH)
74                 ok = PS_TRANSIENT;
75             else if (stage > STAGE_GETAUTH)
76                 ok = PS_PROTOCOL;
77             /*
78              * We're checking for "lock busy", "unable to lock", 
79              * "already locked", "wait a few minutes" etc. here. 
80              * This indicates that we have to wait for the server to
81              * unwedge itself before we can poll again.
82              *
83              * PS_LOCKBUSY check empirically verified with two recent
84              * versions of the Berkeley popper; QPOP (version 2.2)  and
85              * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
86              * These are caught by the case-indifferent "lock" check.
87              * The "wait" catches "mail storage services unavailable,
88              * wait a few minutes and try again" on the InterMail server.
89              *
90              * If these aren't picked up on correctly, fetchmail will 
91              * think there is an authentication failure and wedge the
92              * connection in order to prevent futile polls.
93              *
94              * Gad, what a kluge.
95              */
96             else if (strstr(bufp,"lock")
97                      || strstr(bufp,"Lock")
98                      || strstr(bufp,"LOCK")
99                      || strstr(bufp,"wait")
100                      /* these are blessed by RFC 2449 */
101                      || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
102                 ok = PS_LOCKBUSY;
103             else if ((strstr(bufp,"Service")
104                      || strstr(bufp,"service"))
105                          && (strstr(bufp,"unavailable")))
106                 ok = PS_SERVBUSY;
107             else
108                 ok = PS_AUTHFAIL;
109             /*
110              * We always want to pass the user lock-busy messages, because
111              * they're red flags.  Other stuff (like AUTH failures on non-
112              * RFC1734 servers) only if we're debugging.
113              */
114             if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
115               report(stderr, "%s\n", bufp);
116         }
117         else
118             ok = PS_PROTOCOL;
119
120         if (argbuf != NULL)
121             strcpy(argbuf,bufp);
122     }
123
124     return(ok);
125 }
126
127 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
128 /* apply for connection authorization */
129 {
130     int ok;
131     char *start,*end;
132     char *msg;
133 #if OPIE_ENABLE
134     char *challenge;
135 #endif /* OPIE_ENABLE */
136 #if defined(GSSAPI)
137     flag has_gssapi = FALSE;
138 #endif /* defined(GSSAPI) */
139 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
140     flag has_kerberos = FALSE;
141 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
142     flag has_cram = FALSE;
143 #ifdef OPIE_ENABLE
144     flag has_otp = FALSE;
145 #endif /* OPIE_ENABLE */
146 #ifdef SSL_ENABLE
147     flag has_ssl = FALSE;
148 #endif /* SSL_ENABLE */
149
150 #ifdef SDPS_ENABLE
151     /*
152      * This needs to catch both demon.co.uk and demon.net.
153      * If we see either, and we're in multidrop mode, try to use
154      * the SDPS *ENV extension.
155      */
156     if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
157         ctl->server.sdps = TRUE;
158 #endif /* SDPS_ENABLE */
159
160     switch (ctl->server.protocol) {
161     case P_POP3:
162 #ifdef RPA_ENABLE
163         /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
164         if (strstr(ctl->remotename, "@compuserve.com"))
165         {
166             /* AUTH command should return a list of available mechanisms */
167             if (gen_transact(sock, "AUTH") == 0)
168             {
169                 char buffer[10];
170                 flag has_rpa = FALSE;
171
172                 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
173                 {
174                     if (DOTLINE(buffer))
175                         break;
176                     if (strncasecmp(buffer, "rpa", 3) == 0)
177                         has_rpa = TRUE;
178                 }
179                 if (has_rpa && !POP3_auth_rpa(ctl->remotename, 
180                                               ctl->password, sock))
181                     return(PS_SUCCESS);
182             }
183
184             return(PS_AUTHFAIL);
185         }
186 #endif /* RPA_ENABLE */
187
188         /*
189          * CAPA command may return a list including available
190          * authentication mechanisms.  if it doesn't, no harm done, we
191          * just fall back to a plain login.  Note that this code 
192          * latches the server's authentication type, so that in daemon mode
193          * the CAPA check only needs to be done once at start of run.
194          *
195          * If CAPA fails, then force the authentication method to PASSORD
196          * and repoll immediately.
197          *
198          * These authentication methods are blessed by RFC1734,
199          * describing the POP3 AUTHentication command.
200          */
201         if (ctl->server.authenticate == A_ANY)
202         {
203             ok = gen_transact(sock, "CAPA");
204             if (ok == PS_SUCCESS)
205             {
206                 char buffer[64];
207
208                 /* determine what authentication methods we have available */
209                 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
210                 {
211                     if (DOTLINE(buffer))
212                         break;
213 #ifdef SSL_ENABLE
214                     if (strstr(buffer, "STLS"))
215                         has_ssl = TRUE;
216 #endif /* SSL_ENABLE */
217 #if defined(GSSAPI)
218                     if (strstr(buffer, "GSSAPI"))
219                         has_gssapi = TRUE;
220 #endif /* defined(GSSAPI) */
221 #if defined(KERBEROS_V4)
222                     if (strstr(buffer, "KERBEROS_V4"))
223                         has_kerberos = TRUE;
224 #endif /* defined(KERBEROS_V4)  */
225 #ifdef OPIE_ENABLE
226                     if (strstr(buffer, "X-OTP"))
227                         has_otp = TRUE;
228 #endif /* OPIE_ENABLE */
229                     if (strstr(buffer, "CRAM-MD5"))
230                         has_cram = TRUE;
231                 }
232             }
233             /* we are in STAGE_GETAUTH! */
234             else if (ok == PS_AUTHFAIL ||
235                 /* Some servers directly close the socket. However, if we
236                  * have already authenticated before, then a previous CAPA
237                  * must have succeeded. In that case, treat this as a
238                  * genuine socket error and do not change the auth method.
239                  */
240                 (ok == PS_SOCKET && !ctl->wehaveauthed))
241             {
242                 ctl->server.authenticate = A_PASSWORD;
243                 /* repoll immediately */
244                 ok = PS_REPOLL;
245                 break;
246             }
247         }
248
249 #ifdef SSL_ENABLE
250         if (has_ssl
251             && !ctl->use_ssl
252             && (ctl->server.authenticate == A_ANY))
253         {
254             char *realhost;
255
256             realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;           gen_transact(sock, "STLS");
257             if (SSLOpen(sock,ctl->sslcert,ctl->sslkey,ctl->sslproto,ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
258             {
259                 report(stderr,
260                        GT_("SSL connection failed.\n"));
261                 return(PS_AUTHFAIL);
262             }
263         }
264 #endif /* SSL_ENABLE */
265
266         /*
267          * OK, we have an authentication type now.
268          */
269 #if defined(KERBEROS_V4)
270         /* 
271          * Servers doing KPOP have to go through a dummy login sequence
272          * rather than doing SASL.
273          */
274         if (has_kerberos &&
275 #if INET6_ENABLE
276             ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
277 #else /* INET6_ENABLE */
278             ctl->server.port != KPOP_PORT
279 #endif /* INET6_ENABLE */
280             && (ctl->server.authenticate == A_KERBEROS_V4
281              || ctl->server.authenticate == A_KERBEROS_V5
282              || ctl->server.authenticate == A_ANY))
283         {
284             ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
285             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
286                 break;
287         }
288 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
289
290 #if defined(GSSAPI)
291         if (has_gssapi &&
292             (ctl->server.authenticate == A_GSSAPI ||
293              ctl->server.authenticate == A_ANY))
294         {
295             ok = do_gssauth(sock,"AUTH",ctl->server.truename,ctl->remotename);
296             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
297                 break;
298         }
299 #endif /* defined(GSSAPI) */
300
301 #ifdef OPIE_ENABLE
302         if (has_otp &&
303             (ctl->server.authenticate == A_OTP ||
304              ctl->server.authenticate == A_ANY))
305         {
306             ok = do_otp(sock, "AUTH", ctl);
307             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
308                 break;
309         }
310 #endif /* OPIE_ENABLE */
311
312         if (has_cram &&
313             (ctl->server.authenticate == A_CRAM_MD5 ||
314              ctl->server.authenticate == A_ANY))
315         {
316             ok = do_cram_md5(sock, "AUTH", ctl, NULL);
317             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
318                 break;
319         }
320
321         /* ordinary validation, no one-time password or RPA */ 
322         gen_transact(sock, "USER %s", ctl->remotename);
323
324 #if OPIE_ENABLE
325         /* see RFC1938: A One-Time Password System */
326         if (challenge = strstr(lastok, "otp-")) {
327           char response[OPIE_RESPONSE_MAX+1];
328           int i;
329
330           i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
331           if ((i == -2) && !run.poll_interval) {
332             char secret[OPIE_SECRET_MAX+1];
333             fprintf(stderr, GT_("Secret pass phrase: "));
334             if (opiereadpass(secret, sizeof(secret), 0))
335               i = opiegenerator(challenge,  secret, response);
336             memset(secret, 0, sizeof(secret));
337           };
338
339           if (i) {
340             ok = PS_ERROR;
341             break;
342           };
343
344           ok = gen_transact(sock, "PASS %s", response);
345           break;
346         }
347 #endif /* OPIE_ENABLE */
348
349         strcpy(shroud, ctl->password);
350         ok = gen_transact(sock, "PASS %s", ctl->password);
351         shroud[0] = '\0';
352         break;
353
354     case P_APOP:
355         /* build MD5 digest from greeting timestamp + password */
356         /* find start of timestamp */
357         for (start = greeting;  *start != 0 && *start != '<';  start++)
358             continue;
359         if (*start == 0) {
360             report(stderr,
361                    GT_("Required APOP timestamp not found in greeting\n"));
362             return(PS_AUTHFAIL);
363         }
364
365         /* find end of timestamp */
366         for (end = start;  *end != 0  && *end != '>';  end++)
367             continue;
368         if (*end == 0 || end == start + 1) {
369             report(stderr, 
370                    GT_("Timestamp syntax error in greeting\n"));
371             return(PS_AUTHFAIL);
372         }
373         else
374             *++end = '\0';
375
376         /* copy timestamp and password into digestion buffer */
377         xalloca(msg, char *, (end-start+1) + strlen(ctl->password) + 1);
378         strcpy(msg,start);
379         strcat(msg,ctl->password);
380
381         strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
382
383         ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
384         break;
385
386     case P_RPOP:
387         if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
388             ok = gen_transact(sock, "RPOP %s", ctl->password);
389         break;
390
391     default:
392         report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
393         ok = PS_ERROR;
394     }
395
396     if (ok != 0)
397     {
398         /* maybe we detected a lock-busy condition? */
399         if (ok == PS_LOCKBUSY)
400             report(stderr, GT_("lock busy!  Is another session active?\n")); 
401
402         return(ok);
403     }
404
405     /*
406      * Empirical experience shows some server/OS combinations
407      * may need a brief pause even after any lockfiles on the
408      * server are released, to give the server time to finish
409      * copying back very large mailfolders from the temp-file...
410      * this is only ever an issue with extremely large mailboxes.
411      */
412     sleep(3); /* to be _really_ safe, probably need sleep(5)! */
413
414     /* we're peek-capable if use of TOP is enabled */
415     peek_capable = !(ctl->fetchall || ctl->keep);
416
417     /* we're approved */
418     return(PS_SUCCESS);
419 }
420
421 static int pop3_gettopid( int sock, int num , char *id)
422 {
423     int ok;
424     int got_it;
425     char buf [POPBUFSIZE+1];
426     sprintf( buf, "TOP %d 1", num );
427     if ((ok = gen_transact(sock, buf )) != 0)
428        return ok; 
429     got_it = 0;
430     while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0) 
431     {
432         if (DOTLINE(buf))
433             break;
434         if ( ! got_it && ! strncasecmp("Message-Id:", buf, 11 )) {
435             got_it = 1;
436             /* prevent stack overflows */
437             buf[IDLEN+12] = 0;
438             sscanf( buf+12, "%s", id);
439         }
440     }
441     return 0;
442 }
443
444 static int pop3_slowuidl( int sock,  struct query *ctl, int *countp, int *newp)
445 {
446     /* This approach tries to get the message headers from the
447      * remote hosts and compares the message-id to the already known
448      * ones:
449      *  + if the first message containes a new id, all messages on
450      *    the server will be new
451      *  + if the first is known, try to estimate the last known message
452      *    on the server and check. If this works you know the total number
453      *    of messages to get.
454      *  + Otherwise run a binary search to determine the last known message
455      */
456     int ok, nolinear = 0;
457     int first_nr, list_len, try_id, try_nr, add_id;
458     int num;
459     char id [IDLEN+1];
460     
461     if( (ok = pop3_gettopid( sock, 1, id )) != 0 )
462         return ok;
463     
464     if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
465         /* the first message is unknown -> all messages are new */
466         *newp = *countp;        
467         return 0;
468     }
469
470     /* check where we expect the latest known message */
471     list_len = count_list( &ctl->oldsaved );
472     try_id = list_len  - first_nr; /* -1 + 1 */
473     if( try_id > 1 ) {
474         if( try_id <= *countp ) {
475             if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
476                 return ok;
477     
478             try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
479         } else {
480             try_id = *countp+1;
481             try_nr = -1;
482         }
483         if( try_nr != list_len -1 ) {
484             /* some messages inbetween have been deleted... */
485             if( try_nr == -1 ) {
486                 nolinear = 1;
487
488                 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
489                     ;
490                 for( ; add_id; add_id >>= 1 ) {
491                     if( try_nr == -1 ) {
492                         if( try_id - add_id <= 1 ) {
493                             continue;
494                         }
495                         try_id -= add_id;
496                     } else 
497                         try_id += add_id;
498                     
499                     if( (ok = pop3_gettopid( sock, try_id, id )) != 0 )
500                         return ok;
501                     try_nr = str_nr_in_list(&ctl->oldsaved, id);
502                 }
503                 if( try_nr == -1 ) {
504                     try_id--;
505                 }
506             } else {
507                 report(stderr, 
508                        GT_("Messages inserted into list on server. Cannot handle this.\n"));
509                 return -1;
510             }
511         } 
512     }
513     /* the first try_id messages are known -> copy them to the newsaved list */
514     for( num = first_nr; num < list_len; num++ )
515     {
516         struct idlist   *new = save_str(&ctl->newsaved, 
517                                 str_from_nr_list(&ctl->oldsaved, num),
518                                 UID_UNSEEN);
519         new->val.status.num = num - first_nr + 1;
520     }
521
522     if( nolinear ) {
523         free_str_list(&ctl->oldsaved);
524         ctl->oldsaved = 0;
525         last = try_id;
526     }
527
528     *newp = *countp - try_id;
529     return 0;
530 }
531
532 static int pop3_getrange(int sock, 
533                          struct query *ctl,
534                          const char *folder,
535                          int *countp, int *newp, int *bytes)
536 /* get range of messages to be fetched */
537 {
538     int ok;
539     char buf [POPBUFSIZE+1];
540
541     /* Ensure that the new list is properly empty */
542     ctl->newsaved = (struct idlist *)NULL;
543
544 #ifdef MBOX
545     /* Alain Knaff suggests this, but it's not RFC standard */
546     if (folder)
547         if ((ok = gen_transact(sock, "MBOX %s", folder)))
548             return ok;
549 #endif /* MBOX */
550
551     /* get the total message count */
552     gen_send(sock, "STAT");
553     ok = pop3_ok(sock, buf);
554     if (ok == 0)
555         sscanf(buf,"%d %d", countp, bytes);
556     else
557         return(ok);
558
559     /*
560      * Newer, RFC-1725-conformant POP servers may not have the LAST command.
561      * We work as hard as possible to hide this ugliness, but it makes 
562      * counting new messages intrinsically quadratic in the worst case.
563      */
564     last = 0;
565     *newp = -1;
566     if (*countp > 0 && !ctl->fetchall)
567     {
568         char id [IDLEN+1];
569
570         if (!ctl->server.uidl) {
571             gen_send(sock, "LAST");
572             ok = pop3_ok(sock, buf);
573         } else
574             ok = 1;
575         if (ok == 0)
576         {
577             if (sscanf(buf, "%d", &last) == 0)
578             {
579                 report(stderr, GT_("protocol error\n"));
580                 return(PS_ERROR);
581             }
582             *newp = (*countp - last);
583         }
584         else
585         {
586             /* grab the mailbox's UID list */
587             if ((ok = gen_transact(sock, "UIDL")) != 0)
588             {
589                 /* don't worry, yet! do it the slow way */
590                 if((ok = pop3_slowuidl( sock, ctl, countp, newp))!=0)
591                 {
592                     report(stderr, GT_("protocol error while fetching UIDLs\n"));
593                     return(PS_ERROR);
594                 }
595             }
596             else
597             {
598                 int     num;
599
600                 *newp = 0;
601                 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
602                 {
603                     if (DOTLINE(buf))
604                         break;
605                     else if (sscanf(buf, "%d %s", &num, id) == 2)
606                     {
607                         struct idlist   *new;
608
609                         new = save_str(&ctl->newsaved, id, UID_UNSEEN);
610                         new->val.status.num = num;
611
612                         if (str_in_list(&ctl->oldsaved, id, FALSE)) {
613                             new->val.status.mark = UID_SEEN;
614                             str_set_mark(&ctl->oldsaved, id, UID_SEEN);
615                         }
616                         else
617                             (*newp)++;
618                     }
619                 }
620             }
621         }
622     }
623
624     return(PS_SUCCESS);
625 }
626
627 static int pop3_getsizes(int sock, int count, int *sizes)
628 /* capture the sizes of all messages */
629 {
630     int ok;
631
632     if ((ok = gen_transact(sock, "LIST")) != 0)
633         return(ok);
634     else
635     {
636         char buf [POPBUFSIZE+1];
637
638         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
639         {
640             unsigned int num, size;
641
642             if (DOTLINE(buf))
643                 break;
644             else if (sscanf(buf, "%u %u", &num, &size) == 2) {
645                 if (num > 0 && num <= count)
646                     sizes[num - 1] = size;
647                 else
648                     /* warn about possible attempt to induce buffer overrun */
649                     report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
650             }
651         }
652
653         return(ok);
654     }
655 }
656
657 static int pop3_is_old(int sock, struct query *ctl, int num)
658 /* is the given message old? */
659 {
660     if (!ctl->oldsaved)
661         return (num <= last);
662     else
663         return (str_in_list(&ctl->oldsaved,
664                             str_find(&ctl->newsaved, num), FALSE));
665 }
666
667 #ifdef UNUSED
668 /*
669  * We could use this to fetch headers only as we do for IMAP.  The trouble 
670  * is that there's no way to fetch the body only.  So the following RETR 
671  * would have to re-fetch the header.  Enough messages have longer headers
672  * than bodies to make this a net loss.
673  */
674 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
675 /* request headers of nth message */
676 {
677     int ok;
678     char buf[POPBUFSIZE+1];
679
680     gen_send(sock, "TOP %d 0", number);
681     if ((ok = pop3_ok(sock, buf)) != 0)
682         return(ok);
683
684     *lenp = -1;         /* we got sizes from the LIST response */
685
686     return(PS_SUCCESS);
687 }
688 #endif /* UNUSED */
689
690 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
691 /* request nth message */
692 {
693     int ok;
694     char buf[POPBUFSIZE+1];
695
696 #ifdef SDPS_ENABLE
697     /*
698      * See http://www.demon.net/services/mail/sdps-tech.html
699      * for a description of what we're parsing here.
700      */
701     if (ctl->server.sdps)
702     {
703         int     linecount = 0;
704
705         sdps_envfrom = (char *)NULL;
706         sdps_envto = (char *)NULL;
707         gen_send(sock, "*ENV %d", number);
708         do {
709             if (gen_recv(sock, buf, sizeof(buf)))
710             {
711                 break;
712             }
713             linecount++;
714             switch (linecount) {
715             case 4:
716                 /* No need to wrap envelope from address */
717                 sdps_envfrom = xmalloc(strlen(buf)+1);
718                 strcpy(sdps_envfrom,buf);
719                 break;
720             case 5:
721                 /* Wrap address with To: <> so nxtaddr() likes it */
722                 sdps_envto = xmalloc(strlen(buf)+7);
723                 sprintf(sdps_envto,"To: <%s>",buf);
724                 break;
725             }
726         } while
727             (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
728     }
729 #endif /* SDPS_ENABLE */
730
731     /*
732      * Though the POP RFCs don't document this fact, on almost every
733      * POP3 server I know of messages are marked "seen" only at the
734      * time the OK response to a RETR is issued.
735      *
736      * This means we can use TOP to fetch the message without setting its
737      * seen flag.  This is good!  It means that if the protocol exchange
738      * craps out during the message, it will still be marked `unseen' on
739      * the server.  (Exception: in early 1999 SpryNet's POP3 servers were
740      * reported to mark messages seen on a TOP fetch.)
741      *
742      * However...*don't* do this if we're using keep to suppress deletion!
743      * In that case, marking the seen flag is the only way to prevent the
744      * message from being re-fetched on subsequent runs.
745      *
746      * Also use RETR if fetchall is on.  This gives us a workaround
747      * for servers like usa.net's that bungle TOP.  It's pretty
748      * harmless because fetchall guarantees that any message dropped
749      * by an interrupted RETR will be picked up on the next poll of the
750      * site.
751      *
752      * We take advantage here of the fact that, according to all the
753      * POP RFCs, "if the number of lines requested by the POP3 client
754      * is greater than than the number of lines in the body, then the
755      * POP3 server sends the entire message.").
756      *
757      * The line count passed (99999999) is the maximum value CompuServe will
758      * accept; it's much lower than the natural value 2147483646 (the maximum
759      * twos-complement signed 32-bit integer minus 1) */
760     if (ctl->keep || ctl->fetchall)
761         gen_send(sock, "RETR %d", number);
762     else
763         gen_send(sock, "TOP %d 99999999", number);
764     if ((ok = pop3_ok(sock, buf)) != 0)
765         return(ok);
766
767     *lenp = -1;         /* we got sizes from the LIST response */
768
769     return(PS_SUCCESS);
770 }
771
772 static int pop3_delete(int sock, struct query *ctl, int number)
773 /* delete a given message */
774 {
775     /* actually, mark for deletion -- doesn't happen until QUIT time */
776     return(gen_transact(sock, "DELE %d", number));
777 }
778
779 static int pop3_logout(int sock, struct query *ctl)
780 /* send logout command */
781 {
782     int ok;
783
784 #ifdef __UNUSED__
785     /*
786      * We used to do this in case the server marks messages deleted when seen.
787      * (Yes, this has been reported, in the MercuryP/NLM server.
788      * It's even legal under RFC 1939 (section 8) as a site policy.)
789      * It interacted badly with UIDL, though.  Thomas Zajic wrote:
790      * "Running 'fetchmail -F -v' and checking the logs, I found out
791      * that fetchmail did in fact flush my mailbox properly, but sent
792      * a RSET just before sending QUIT to log off.  This caused the
793      * POP3 server to undo/forget about the previous DELEs, resetting
794      * my mailbox to its original (ie.  unflushed) state. The
795      * ~/.fetchids file did get flushed though, so the next time
796      * fetchmail was run it saw all the old messages as new ones ..."
797      */
798      if (ctl->keep)
799         gen_transact(sock, "RSET");
800 #endif /* __UNUSED__ */
801
802     ok = gen_transact(sock, "QUIT");
803     if (!ok)
804         expunge_uids(ctl);
805
806     if (ctl->lastid)
807     {
808         free(ctl->lastid);
809         ctl->lastid = NULL;
810     }
811
812     return(ok);
813 }
814
815 const static struct method pop3 =
816 {
817     "POP3",             /* Post Office Protocol v3 */
818 #if INET6_ENABLE
819     "pop3",             /* standard POP3 port */
820     "pop3s",            /* ssl POP3 port */
821 #else /* INET6_ENABLE */
822     110,                /* standard POP3 port */
823     995,                /* ssl POP3 port */
824 #endif /* INET6_ENABLE */
825     FALSE,              /* this is not a tagged protocol */
826     TRUE,               /* this uses a message delimiter */
827     pop3_ok,            /* parse command response */
828     pop3_getauth,       /* get authorization */
829     pop3_getrange,      /* query range of messages */
830     pop3_getsizes,      /* we can get a list of sizes */
831     pop3_is_old,        /* how do we tell a message is old? */
832     pop3_fetch,         /* request given message */
833     NULL,               /* no way to fetch body alone */
834     NULL,               /* no message trailer */
835     pop3_delete,        /* how to delete a message */
836     pop3_logout,        /* log out, we're done */
837     FALSE,              /* no, we can't re-poll */
838 };
839
840 int doPOP3 (struct query *ctl)
841 /* retrieve messages using POP3 */
842 {
843 #ifndef MBOX
844     if (ctl->mailboxes->id) {
845         fprintf(stderr,GT_("Option --remote is not supported with POP3\n"));
846         return(PS_SYNTAX);
847     }
848 #endif /* MBOX */
849     peek_capable = !ctl->fetchall;
850     return(do_protocol(ctl, &pop3));
851 }
852 #endif /* POP3_ENABLE */
853
854 /* pop3.c ends here */