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