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