]> Pileus Git - ~andy/fetchmail/blob - imap.c
First round ofmlong-delayed bug fixes.
[~andy/fetchmail] / imap.c
1 /*
2  * imap.c -- IMAP2bis/IMAP4 protocol methods
3  *
4  * Copyright 1997 by Eric S. Raymond
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include  "config.h"
9 #include  <stdio.h>
10 #include  <string.h>
11 #include  <ctype.h>
12 #if defined(STDC_HEADERS)
13 #include  <stdlib.h>
14 #include  <limits.h>
15 #endif
16 #include  "fetchmail.h"
17 #include  "socket.h"
18
19 #include  "i18n.h"
20
21 #if OPIE_ENABLE
22 #endif /* OPIE_ENABLE */
23
24 #ifndef strstr          /* glibc-2.1 declares this as a macro */
25 extern char *strstr();  /* needed on sysV68 R3V7.1. */
26 #endif /* strstr */
27
28 /* imap_version values */
29 #define IMAP2           -1      /* IMAP2 or IMAP2BIS, RFC1176 */
30 #define IMAP4           0       /* IMAP4 rev 0, RFC1730 */
31 #define IMAP4rev1       1       /* IMAP4 rev 1, RFC2060 */
32
33 static int count = 0, recentcount = 0, unseen = 0, deletions = 0;
34 static unsigned int startcount = 1;
35 static int expunged, expunge_period, saved_timeout = 0;
36 static int imap_version, preauth;
37 static flag do_idle;
38 static char capabilities[MSGBUFSIZE+1];
39 static unsigned int *unseen_messages;
40
41 static int imap_ok(int sock, char *argbuf)
42 /* parse command response */
43 {
44     char buf[MSGBUFSIZE+1];
45
46     do {
47         int     ok;
48         char    *cp;
49
50         if ((ok = gen_recv(sock, buf, sizeof(buf))))
51             return(ok);
52
53         /* all tokens in responses are caseblind */
54         for (cp = buf; *cp; cp++)
55             if (islower(*cp))
56                 *cp = toupper(*cp);
57
58         /* interpret untagged status responses */
59         if (strstr(buf, "* CAPABILITY"))
60         {
61             strncpy(capabilities, buf + 12, sizeof(capabilities));
62             capabilities[sizeof(capabilities)-1] = '\0';
63         }
64         else if (strstr(buf, "EXISTS"))
65         {
66             count = atoi(buf+2);
67             /*
68              * Don't trust the message count passed by the server.
69              * Without this check, it might be possible to do a
70              * DNS-spoofing attack that would pass back a ridiculous 
71              * count, and allocate a malloc area that would overlap
72              * a portion of the stack.
73              */
74             if (count > INT_MAX/sizeof(int))
75             {
76                 report(stderr, "bogus message count!");
77                 return(PS_PROTOCOL);
78             }
79
80             /*
81              * Nasty kluge to handle RFC2177 IDLE.  If we know we're idling
82              * we can't wait for the tag matching the IDLE; we have to tell the
83              * server the IDLE is finished by shipping back a DONE when we
84              * see an EXISTS.  Only after that will a tagged response be
85              * shipped.  The idling flag also gets cleared on a timeout.
86              */
87             if (stage == STAGE_IDLE)
88             {
89                 /* we do our own write and report here to disable tagging */
90                 SockWrite(sock, "DONE\r\n", 6);
91                 if (outlevel >= O_MONITOR)
92                     report(stdout, "IMAP> DONE\n");
93
94                 mytimeout = saved_timeout;
95                 stage = STAGE_FETCH;
96             }
97         }
98         /* a space is required to avoid confusion with the \Recent flag */
99         else if (strstr(buf, " RECENT"))
100         {
101             recentcount = atoi(buf+2);
102         }
103         else if (strstr(buf, "PREAUTH"))
104             preauth = TRUE;
105         /*
106          * The server may decide to make the mailbox read-only, 
107          * which causes fetchmail to go into a endless loop
108          * fetching the same message over and over again. 
109          * 
110          * However, for check_only, we use EXAMINE which will
111          * mark the mailbox read-only as per the RFC.
112          * 
113          * This checks for the condition and aborts if 
114          * the mailbox is read-only. 
115          *
116          * See RFC 2060 section 6.3.1 (SELECT).
117          * See RFC 2060 section 6.3.2 (EXAMINE).
118          */ 
119         else if (!check_only && strstr(buf, "[READ-ONLY]"))
120             return(PS_LOCKBUSY);
121     } while
122         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
123
124     if (tag[0] == '\0')
125     {
126         if (argbuf)
127             strcpy(argbuf, buf);
128         return(PS_SUCCESS); 
129     }
130     else
131     {
132         char    *cp;
133
134         /* skip the tag */
135         for (cp = buf; !isspace(*cp); cp++)
136             continue;
137         while (isspace(*cp))
138             cp++;
139
140         if (strncasecmp(cp, "OK", 2) == 0)
141         {
142             if (argbuf)
143                 strcpy(argbuf, cp);
144             return(PS_SUCCESS);
145         }
146         else if (strncasecmp(cp, "BAD", 3) == 0)
147             return(PS_ERROR);
148         else if (strncasecmp(cp, "NO", 2) == 0)
149         {
150             if (stage == STAGE_GETAUTH) 
151                 return(PS_AUTHFAIL);    /* RFC2060, 6.2.2 */
152             else
153                 return(PS_ERROR);
154         }
155         else
156             return(PS_PROTOCOL);
157     }
158 }
159
160 #if NTLM_ENABLE
161 #include "ntlm.h"
162
163 static tSmbNtlmAuthRequest   request;              
164 static tSmbNtlmAuthChallenge challenge;
165 static tSmbNtlmAuthResponse  response;
166
167 /*
168  * NTLM support by Grant Edwards.
169  *
170  * Handle MS-Exchange NTLM authentication method.  This is the same
171  * as the NTLM auth used by Samba for SMB related services. We just
172  * encode the packets in base64 instead of sending them out via a
173  * network interface.
174  * 
175  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
176  */
177
178 static int do_imap_ntlm(int sock, struct query *ctl)
179 {
180     char msgbuf[2048];
181     int result,len;
182   
183     gen_send(sock, "AUTHENTICATE NTLM");
184
185     if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
186         return result;
187   
188     if (msgbuf[0] != '+')
189         return PS_AUTHFAIL;
190   
191     buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
192
193     if (outlevel >= O_DEBUG)
194         dumpSmbNtlmAuthRequest(stdout, &request);
195
196     memset(msgbuf,0,sizeof msgbuf);
197     to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
198   
199     if (outlevel >= O_MONITOR)
200         report(stdout, "IMAP> %s\n", msgbuf);
201   
202     strcat(msgbuf,"\r\n");
203     SockWrite (sock, msgbuf, strlen (msgbuf));
204
205     if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
206         return result;
207   
208     len = from64tobits ((char*)&challenge, msgbuf, sizeof(challenge));
209     
210     if (outlevel >= O_DEBUG)
211         dumpSmbNtlmAuthChallenge(stdout, &challenge);
212     
213     buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
214   
215     if (outlevel >= O_DEBUG)
216         dumpSmbNtlmAuthResponse(stdout, &response);
217   
218     memset(msgbuf,0,sizeof msgbuf);
219     to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
220
221     if (outlevel >= O_MONITOR)
222         report(stdout, "IMAP> %s\n", msgbuf);
223       
224     strcat(msgbuf,"\r\n");
225     SockWrite (sock, msgbuf, strlen (msgbuf));
226   
227     if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
228         return result;
229   
230     if (strstr (msgbuf, "OK"))
231         return PS_SUCCESS;
232     else
233         return PS_AUTHFAIL;
234 }
235 #endif /* NTLM */
236
237 static int imap_canonicalize(char *result, char *raw, int maxlen)
238 /* encode an IMAP password as per RFC1730's quoting conventions */
239 {
240     int i, j;
241
242     j = 0;
243     for (i = 0; i < strlen(raw) && i < maxlen; i++)
244     {
245         if ((raw[i] == '\\') || (raw[i] == '"'))
246             result[j++] = '\\';
247         result[j++] = raw[i];
248     }
249     result[j] = '\0';
250
251     return(i);
252 }
253
254 static void capa_probe(int sock, struct query *ctl)
255 /* set capability variables from a CAPA probe */
256 {
257     int ok;
258
259     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
260     capabilities[0] = '\0';
261     if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
262     {
263         char    *cp;
264
265         /* capability checks are supposed to be caseblind */
266         for (cp = capabilities; *cp; cp++)
267             *cp = toupper(*cp);
268
269         /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
270            should expect a response in mixed-case */
271         if (strstr(capabilities, "IMAP4REV1"))
272         {
273             imap_version = IMAP4rev1;
274             if (outlevel >= O_DEBUG)
275                 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
276         }
277         else
278         {
279             imap_version = IMAP4;
280             if (outlevel >= O_DEBUG)
281                 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
282         }
283     }
284     else if (ok == PS_ERROR)
285     {
286         imap_version = IMAP2;
287         if (outlevel >= O_DEBUG)
288             report(stdout, GT_("Protocol identified as IMAP2 or IMAP2BIS\n"));
289     }
290
291     /* 
292      * Handle idling.  We depend on coming through here on startup
293      * and after each timeout (including timeouts during idles).
294      */
295     if (strstr(capabilities, "IDLE") && ctl->idle)
296     {
297         do_idle = TRUE;
298         if (outlevel >= O_VERBOSE)
299             report(stdout, GT_("will idle after poll\n"));
300     }
301 }
302
303 static int imap_getauth(int sock, struct query *ctl, char *greeting)
304 /* apply for connection authorization */
305 {
306     int ok = 0;
307 #ifdef SSL_ENABLE
308     flag did_stls = FALSE;
309 #endif /* SSL_ENABLE */
310
311     capa_probe(sock, ctl);
312
313     /* 
314      * If either (a) we saw a PREAUTH token in the greeting, or
315      * (b) the user specified ssh preauthentication, then we're done.
316      */
317     if (preauth || ctl->server.authenticate == A_SSH)
318     {
319         preauth = FALSE;  /* reset for the next session */
320         return(PS_SUCCESS);
321     }
322     /*
323      * Time to authenticate the user.
324      * Try the protocol variants that don't require passwords first.
325      */
326     ok = PS_AUTHFAIL;
327
328 #ifdef GSSAPI
329     if ((ctl->server.authenticate == A_ANY 
330          || ctl->server.authenticate == A_GSSAPI)
331         && strstr(capabilities, "AUTH=GSSAPI"))
332         if(ok = do_gssauth(sock, "AUTHENTICATE", ctl->server.truename, ctl->remotename))
333         {
334             /* SASL cancellation of authentication */
335             gen_send(sock, "*");
336             if(ctl->server.authenticate != A_ANY)
337                 return ok;
338         }
339         else
340             return ok;
341 #endif /* GSSAPI */
342
343 #ifdef KERBEROS_V4
344     if ((ctl->server.authenticate == A_ANY 
345          || ctl->server.authenticate == A_KERBEROS_V4
346          || ctl->server.authenticate == A_KERBEROS_V5) 
347         && strstr(capabilities, "AUTH=KERBEROS_V4"))
348     {
349         if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
350         {
351             /* SASL cancellation of authentication */
352             gen_send(sock, "*");
353             if(ctl->server.authenticate != A_ANY)
354                 return ok;
355         }
356         else
357             return ok;
358     }
359 #endif /* KERBEROS_V4 */
360
361 #ifdef SSL_ENABLE
362     if ((!ctl->sslproto || !strcmp(ctl->sslproto,"tls1"))
363         && !ctl->use_ssl
364         && strstr(capabilities, "STARTTLS"))
365     {
366            char *realhost;
367
368            realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
369            ok = gen_transact(sock, "STARTTLS");
370
371            /* We use "tls1" instead of ctl->sslproto, as we want STARTTLS,
372             * not other SSL protocols
373             */
374            if (ok == PS_SUCCESS &&
375                SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
376            {
377                if (!ctl->sslproto && !ctl->wehaveauthed)
378                {
379                    ctl->sslproto = xstrdup("");
380                    /* repoll immediately */
381                    return(PS_REPOLL);
382                }
383                report(stderr,
384                       GT_("SSL connection failed.\n"));
385                return(PS_AUTHFAIL);
386            }
387            did_stls = TRUE;
388
389            /*
390             * RFC 2595 says this:
391             *
392             * "Once TLS has been started, the client MUST discard cached
393             * information about server capabilities and SHOULD re-issue the
394             * CAPABILITY command.  This is necessary to protect against
395             * man-in-the-middle attacks which alter the capabilities list prior
396             * to STARTTLS.  The server MAY advertise different capabilities
397             * after STARTTLS."
398             */
399            capa_probe(sock, ctl);
400     }
401 #endif /* SSL_ENABLE */
402
403     peek_capable = (imap_version >= IMAP4);
404
405     /* 
406      * Assumption: expunges are cheap, so we want to do them
407      * after every message unless user said otherwise.
408      */
409     if (NUM_SPECIFIED(ctl->expunge))
410         expunge_period = NUM_VALUE_OUT(ctl->expunge);
411     else
412         expunge_period = 1;
413
414     /*
415      * No such luck.  OK, now try the variants that mask your password
416      * in a challenge-response.
417      */
418
419     if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
420         || ctl->server.authenticate == A_CRAM_MD5)
421     {
422         if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
423         {
424             /* SASL cancellation of authentication */
425             gen_send(sock, "*");
426             if(ctl->server.authenticate != A_ANY)
427                 return ok;
428         }
429         else
430             return ok;
431     }
432
433 #if OPIE_ENABLE
434     if ((ctl->server.authenticate == A_ANY 
435          || ctl->server.authenticate == A_OTP)
436         && strstr(capabilities, "AUTH=X-OTP"))
437         if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
438         {
439             /* SASL cancellation of authentication */
440             gen_send(sock, "*");
441             if(ctl->server.authenticate != A_ANY)
442                 return ok;
443         }
444         else
445             return ok;
446 #else
447     if (ctl->server.authenticate == A_OTP)
448     {
449         report(stderr, 
450            GT_("Required OTP capability not compiled into fetchmail\n"));
451     }
452 #endif /* OPIE_ENABLE */
453
454 #ifdef NTLM_ENABLE
455     if ((ctl->server.authenticate == A_ANY 
456          || ctl->server.authenticate == A_NTLM) 
457         && strstr (capabilities, "AUTH=NTLM")) {
458         if ((ok = do_imap_ntlm(sock, ctl)))
459         {
460             /* SASL cancellation of authentication */
461             gen_send(sock, "*");
462             if(ctl->server.authenticate != A_ANY)
463                 return ok;
464         }
465         else
466             return(ok);
467     }
468 #else
469     if (ctl->server.authenticate == A_NTLM)
470     {
471         report(stderr, 
472            GT_("Required NTLM capability not compiled into fetchmail\n"));
473     }
474 #endif /* NTLM_ENABLE */
475
476 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
477     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
478     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
479     {
480         report(stderr, 
481                GT_("Required LOGIN capability not supported by server\n"));
482     }
483 #endif /* __UNUSED__ */
484
485     /* 
486      * We're stuck with sending the password en clair.
487      * The reason for this odd-looking logic is that some
488      * servers return LOGINDISABLED even though login 
489      * actually works.  So arrange things in such a way that
490      * setting auth passwd makes it ignore this capability.
491      */
492     if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
493         || ctl->server.authenticate == A_PASSWORD)
494     {
495         /* these sizes guarantee no buffer overflow */
496         char    remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
497
498         imap_canonicalize(remotename, ctl->remotename, NAMELEN);
499         imap_canonicalize(password, ctl->password, PASSWORDLEN);
500
501         strcpy(shroud, password);
502         ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
503         shroud[0] = '\0';
504 #ifdef SSL_ENABLE
505         /* this is for servers which claim to support TLS, but actually
506          * don't! */
507         if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
508         {
509             ctl->sslproto = xstrdup("");
510             /* repoll immediately */
511             ok = PS_REPOLL;
512         }
513 #endif
514         if (ok)
515         {
516             /* SASL cancellation of authentication */
517             gen_send(sock, "*");
518             if(ctl->server.authenticate != A_ANY)
519                 return ok;
520         }
521         else
522             return(ok);
523     }
524
525     return(ok);
526 }
527
528 static int internal_expunge(int sock)
529 /* ship an expunge, resetting associated counters */
530 {
531     int ok;
532
533     if ((ok = gen_transact(sock, "EXPUNGE")))
534         return(ok);
535
536     expunged += deletions;
537     deletions = 0;
538
539 #ifdef IMAP_UID /* not used */
540     expunge_uids(ctl);
541 #endif /* IMAP_UID */
542
543     return(PS_SUCCESS);
544 }
545
546 static int imap_idle(int sock)
547 /* start an RFC2177 IDLE */
548 {
549     int ok;
550
551     /* special timeout to terminate the IDLE and re-issue it
552      * at least every 28 minutes:
553      * (the server may have an inactivity timeout) */
554     stage = STAGE_IDLE;
555     saved_timeout = mytimeout;
556     mytimeout = 1680; /* 28 min */
557
558     /* enter IDLE mode */
559     ok = gen_transact(sock, "IDLE");
560
561     if(ok == PS_IDLETIMEOUT) {
562         /* send "DONE" continuation */
563         SockWrite(sock, "DONE\r\n", 6);
564         if (outlevel >= O_MONITOR)
565             report(stdout, "IMAP> DONE\n");
566
567         /* restore normal timeout value */
568         mytimeout = saved_timeout;
569         stage = STAGE_FETCH;
570
571         /* get OK IDLE message */
572         return imap_ok(sock, NULL);
573     } else
574         /* not idle timeout */
575         return ok;
576 }
577
578 static int imap_getrange(int sock, 
579                          struct query *ctl, 
580                          const char *folder, 
581                          int *countp, int *newp, int *bytes)
582 /* get range of messages to be fetched */
583 {
584     int ok;
585     char buf[MSGBUFSIZE+1], *cp;
586
587     /* find out how many messages are waiting */
588     *bytes = -1;
589
590     if (pass > 1)
591     {
592         /* 
593          * We have to have an expunge here, otherwise the re-poll will
594          * infinite-loop picking up un-expunged messages -- unless the
595          * expunge period is one and we've been nuking each message 
596          * just after deletion.
597          */
598         ok = 0;
599         if (deletions) {
600             ok = internal_expunge(sock);
601             if (ok)
602             {
603                 report(stderr, GT_("expunge failed\n"));
604                 return(ok);
605             }
606         }
607
608         /*
609          * recentcount is already set here by the last imap command which
610          * returned RECENT on detecting new mail. if recentcount is 0, wait
611          * for new mail.
612          */
613
614         /* some servers do not report RECENT after an EXPUNGE. this check
615          * forces an incorrect recentcount to be ignored. */
616         if (recentcount > count)
617             recentcount = 0;
618         /* this is a while loop because imap_idle() might return on other
619          * mailbox changes also */
620         while (recentcount == 0 && do_idle) {
621             smtp_close(ctl, 1);
622             ok = imap_idle(sock);
623             if (ok)
624             {
625                 report(stderr, GT_("re-poll failed\n"));
626                 return(ok);
627             }
628         }
629         /* if recentcount is 0, return no mail */
630         if (recentcount == 0)
631                 count = 0;
632         if (outlevel >= O_DEBUG)
633             report(stdout, GT_("%d messages waiting after re-poll\n"), count);
634     }
635     else
636     {
637         count = 0;
638         ok = gen_transact(sock, 
639                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
640                           folder ? folder : "INBOX");
641         if (ok != 0)
642         {
643             report(stderr, GT_("mailbox selection failed\n"));
644             return(ok);
645         }
646         else if (outlevel >= O_DEBUG)
647             report(stdout, GT_("%d messages waiting after first poll\n"), count);
648
649         /* no messages?  then we may need to idle until we get some */
650         while (count == 0 && do_idle) {
651             ok = imap_idle(sock);
652             if (ok)
653             {
654                 report(stderr, GT_("re-poll failed\n"));
655                 return(ok);
656             }
657         }
658
659         /*
660          * We should have an expunge here to
661          * a) avoid fetching deleted mails during 'fetchall'
662          * b) getting a wrong count of mails during 'no fetchall'
663          */
664         if (!check_only && !ctl->keep && count > 0)
665         {
666             ok = internal_expunge(sock);
667             if (ok)
668             {
669                 report(stderr, GT_("expunge failed\n"));
670                 return(ok);
671             }
672             if (outlevel >= O_DEBUG)
673                 report(stdout, GT_("%d messages waiting after expunge\n"), count);
674         }
675     }
676
677     *countp = count;
678     recentcount = 0;
679     startcount = 1;
680
681     /* OK, now get a count of unseen messages and their indices */
682     if (!ctl->fetchall && count > 0)
683     {
684         if (unseen_messages)
685             free(unseen_messages);
686         unseen_messages = xmalloc(count * sizeof(unsigned int));
687         memset(unseen_messages, 0, count * sizeof(unsigned int));
688         unseen = 0;
689
690         gen_send(sock, "SEARCH UNSEEN");
691         do {
692             ok = gen_recv(sock, buf, sizeof(buf));
693             if (ok != 0)
694             {
695                 report(stderr, GT_("search for unseen messages failed\n"));
696                 return(PS_PROTOCOL);
697             }
698             else if ((cp = strstr(buf, "* SEARCH")))
699             {
700                 char    *ep;
701
702                 cp += 8;        /* skip "* SEARCH" */
703                 /* startcount is higher than count so that if there are no
704                  * unseen messages, imap_getsizes() will not need to do
705                  * anything! */
706                 startcount = count + 1;
707
708                 while (*cp && unseen < count)
709                 {
710                     /* skip whitespace */
711                     while (*cp && isspace(*cp))
712                         cp++;
713                     if (*cp) 
714                     {
715                         unsigned int um;
716                         /*
717                          * Message numbers are between 1 and 2^32 inclusive,
718                          * so unsigned int is large enough.
719                          */
720                         um=(unsigned int)strtol(cp,&ep,10);
721                         if (um <= count)
722                         {
723                             unseen_messages[unseen++] = um;
724                             if (outlevel >= O_DEBUG)
725                                 report(stdout, GT_("%u is unseen\n"), um);
726                             if (startcount > um)
727                                 startcount = um;
728                         }
729                         cp = ep;
730                     }
731                 }
732             }
733         } while
734             (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
735
736         if (outlevel >= O_DEBUG && unseen > 0)
737             report(stdout, GT_("%u is first unseen\n"), startcount);
738     } else
739         unseen = -1;
740
741     *newp = unseen;
742     count = 0;
743     expunged = 0;
744     deletions = 0;
745
746     return(PS_SUCCESS);
747 }
748
749 static int imap_getsizes(int sock, int count, int *sizes)
750 /* capture the sizes of all messages */
751 {
752     char buf [MSGBUFSIZE+1];
753
754     /*
755      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
756      * won't accept 1:1 as valid set syntax.  Some implementors
757      * should be taken out and shot for excessive anality.
758      *
759      * Microsoft Exchange (brain-dead piece of crap that it is) 
760      * sometimes gets its knickers in a knot about bodiless messages.
761      * You may see responses like this:
762      *
763      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
764      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
765      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
766      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
767      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
768      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
769      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
770      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
771      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
772      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
773      *
774      * This means message 1 has only headers.  For kicks and grins
775      * you can telnet in and look:
776      *  A003 FETCH 1 FULL
777      *  A003 NO The requested item could not be found.
778      *  A004 fetch 1 rfc822.header
779      *  A004 NO The requested item could not be found.
780      *  A006 FETCH 1 BODY
781      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
782      *  A006 OK FETCH completed.
783      *
784      * To get around this, we terminate the read loop on a NO and count
785      * on the fact that the sizes array has been preinitialized with a
786      * known-bad size value.
787      */
788     /* if fetchall is specified, startcount is 1;
789      * else if there is new mail, startcount is first unseen message;
790      * else startcount is greater than count.
791      */
792     if (count == startcount)
793         gen_send(sock, "FETCH %d RFC822.SIZE", count);
794     else if (count > startcount)
795         gen_send(sock, "FETCH %d:%d RFC822.SIZE", startcount, count);
796     else /* no unseen messages! */
797         return(PS_SUCCESS);
798     for (;;)
799     {
800         unsigned int num, size;
801         int ok;
802         char *cp;
803
804         if ((ok = gen_recv(sock, buf, sizeof(buf))))
805             return(ok);
806         /* we want response matching to be case-insensitive */
807         for (cp = buf; *cp; cp++)
808             *cp = toupper(*cp);
809         /* an untagged NO means that a message was not readable */
810         if (strstr(buf, "* NO"))
811             ;
812         else if (strstr(buf, "OK") || strstr(buf, "NO"))
813             break;
814         else if (sscanf(buf, "* %u FETCH (RFC822.SIZE %u)", &num, &size) == 2) 
815         {
816             if (num > 0 && num <= count)
817                 sizes[num - 1] = size;
818             else
819                 report(stderr, "Warning: ignoring bogus data for message sizes returned by the server.\n");
820         }
821     }
822
823     return(PS_SUCCESS);
824 }
825
826 static int imap_is_old(int sock, struct query *ctl, int number)
827 /* is the given message old? */
828 {
829     flag seen = TRUE;
830     int i;
831
832     /* 
833      * Expunges change the fetch numbers, but unseen_messages contains
834      * indices from before any expungees were done.  So neither the
835      * argument nor the values in message_sequence need to be decremented.
836      */
837
838     seen = TRUE;
839     for (i = 0; i < unseen; i++)
840         if (unseen_messages[i] == number)
841         {
842             seen = FALSE;
843             break;
844         }
845
846     return(seen);
847 }
848
849 static char *skip_token(char *ptr)
850 {
851     while(isspace(*ptr)) ptr++;
852     while(!isspace(*ptr) && !iscntrl(*ptr)) ptr++;
853     while(isspace(*ptr)) ptr++;
854     return(ptr);
855 }
856
857 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
858 /* request headers of nth message */
859 {
860     char buf [MSGBUFSIZE+1];
861     int num;
862
863     /* expunges change the fetch numbers */
864     number -= expunged;
865
866     /*
867      * This is blessed by RFC1176, RFC1730, RFC2060.
868      * According to the RFCs, it should *not* set the \Seen flag.
869      */
870     gen_send(sock, "FETCH %d RFC822.HEADER", number);
871
872     /* looking for FETCH response */
873     for (;;) 
874     {
875         int     ok;
876         char    *ptr;
877
878         if ((ok = gen_recv(sock, buf, sizeof(buf))))
879             return(ok);
880         ptr = skip_token(buf);  /* either "* " or "AXXXX " */
881         if (sscanf(ptr, "%d FETCH (%*s {%d}", &num, lenp) == 2)
882             break;
883         /* try to recover from chronically fucked-up M$ Exchange servers */
884         else if (!strncmp(ptr, "NO", 2))
885         {
886             /* wait for a tagged response */
887             if (strstr (buf, "* NO"))
888                 imap_ok (sock, 0);
889             return(PS_TRANSIENT);
890         }
891         else if (!strncmp(ptr, "BAD", 3))
892         {
893             /* wait for a tagged response */
894             if (strstr (buf, "* BAD"))
895                 imap_ok (sock, 0);
896             return(PS_TRANSIENT);
897         }
898     }
899
900     if (num != number)
901         return(PS_ERROR);
902     else
903         return(PS_SUCCESS);
904 }
905
906 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
907 /* request body of nth message */
908 {
909     char buf [MSGBUFSIZE+1], *cp;
910     int num;
911
912     /* expunges change the fetch numbers */
913     number -= expunged;
914
915     /*
916      * If we're using IMAP4, we can fetch the message without setting its
917      * seen flag.  This is good!  It means that if the protocol exchange
918      * craps out during the message, it will still be marked `unseen' on
919      * the server.
920      *
921      * According to RFC2060, and Mark Crispin the IMAP maintainer,
922      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
923      * equivalent".  However, we know of at least one server that
924      * treats them differently in the presence of MIME attachments;
925      * the latter form downloads the attachment, the former does not.
926      * The server is InterChange, and the fool who implemented this
927      * misfeature ought to be strung up by his thumbs.  
928      *
929      * When I tried working around this by disabling use of the 4rev1 form,
930      * I found that doing this breaks operation with M$ Exchange.
931      * Annoyingly enough, Exchange's refusal to cope is technically legal
932      * under RFC2062.  Trust Microsoft, the Great Enemy of interoperability
933      * standards, to find a way to make standards compliance irritating....
934      */
935     switch (imap_version)
936     {
937     case IMAP4rev1:     /* RFC 2060 */
938         gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
939         break;
940
941     case IMAP4:         /* RFC 1730 */
942         gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
943         break;
944
945     default:            /* RFC 1176 */
946         gen_send(sock, "FETCH %d RFC822.TEXT", number);
947         break;
948     }
949
950     /* looking for FETCH response */
951     do {
952         int     ok;
953
954         if ((ok = gen_recv(sock, buf, sizeof(buf))))
955             return(ok);
956     } while
957         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
958
959     if (num != number)
960         return(PS_ERROR);
961
962     /*
963      * Try to extract a length from the FETCH response.  RFC2060 requires
964      * it to be present, but at least one IMAP server (Novell GroupWise)
965      * botches this.
966      */
967     if ((cp = strchr(buf, '{')))
968         *lenp = atoi(cp + 1);
969     else
970         *lenp = -1;     /* missing length part in FETCH reponse */
971
972     return(PS_SUCCESS);
973 }
974
975 static int imap_trail(int sock, struct query *ctl, int number)
976 /* discard tail of FETCH response after reading message text */
977 {
978     /* expunges change the fetch numbers */
979     /* number -= expunged; */
980
981     for (;;)
982     {
983         char buf[MSGBUFSIZE+1];
984         int ok;
985
986         if ((ok = gen_recv(sock, buf, sizeof(buf))))
987             return(ok);
988
989         /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
990         if (strstr(buf, "OK"))
991             break;
992     }
993
994     return(PS_SUCCESS);
995 }
996
997 static int imap_delete(int sock, struct query *ctl, int number)
998 /* set delete flag for given message */
999 {
1000     int ok;
1001
1002     /* expunges change the fetch numbers */
1003     number -= expunged;
1004
1005     /*
1006      * Use SILENT if possible as a minor throughput optimization.
1007      * Note: this has been dropped from IMAP4rev1.
1008      *
1009      * We set Seen because there are some IMAP servers (notably HP
1010      * OpenMail) that do message-receipt DSNs, but only when the seen
1011      * bit is set.  This is the appropriate time -- we get here right
1012      * after the local SMTP response that says delivery was
1013      * successful.
1014      */
1015     if ((ok = gen_transact(sock,
1016                         imap_version == IMAP4 
1017                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1018                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1019                         number)))
1020         return(ok);
1021     else
1022         deletions++;
1023
1024     /*
1025      * We do an expunge after expunge_period messages, rather than
1026      * just before quit, so that a line hit during a long session
1027      * won't result in lots of messages being fetched again during
1028      * the next session.
1029      */
1030     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1031         internal_expunge(sock);
1032
1033     return(PS_SUCCESS);
1034 }
1035
1036 static int imap_mark_seen(int sock, struct query *ctl, int number)
1037 /* mark the given message as seen */
1038 {
1039     return(gen_transact(sock,
1040         imap_version == IMAP4
1041         ? "STORE %d +FLAGS.SILENT (\\Seen)"
1042         : "STORE %d +FLAGS (\\Seen)",
1043         number));
1044 }
1045
1046 static int imap_logout(int sock, struct query *ctl)
1047 /* send logout command */
1048 {
1049     /* if any un-expunged deletions remain, ship an expunge now */
1050     if (deletions)
1051         internal_expunge(sock);
1052
1053 #ifdef USE_SEARCH
1054     /* Memory clean-up */
1055     if (unseen_messages)
1056         free(unseen_messages);
1057 #endif /* USE_SEARCH */
1058
1059     return(gen_transact(sock, "LOGOUT"));
1060 }
1061
1062 const static struct method imap =
1063 {
1064     "IMAP",             /* Internet Message Access Protocol */
1065 #if INET6_ENABLE
1066     "imap",
1067     "imaps",
1068 #else /* INET6_ENABLE */
1069     143,                /* standard IMAP2bis/IMAP4 port */
1070     993,                /* ssl IMAP2bis/IMAP4 port */
1071 #endif /* INET6_ENABLE */
1072     TRUE,               /* this is a tagged protocol */
1073     FALSE,              /* no message delimiter */
1074     imap_ok,            /* parse command response */
1075     imap_getauth,       /* get authorization */
1076     imap_getrange,      /* query range of messages */
1077     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1078     imap_is_old,        /* no UID check */
1079     imap_fetch_headers, /* request given message headers */
1080     imap_fetch_body,    /* request given message body */
1081     imap_trail,         /* eat message trailer */
1082     imap_delete,        /* delete the message */
1083     imap_mark_seen,     /* how to mark a message as seen */
1084     imap_logout,        /* expunge and exit */
1085     TRUE,               /* yes, we can re-poll */
1086 };
1087
1088 int doIMAP(struct query *ctl)
1089 /* retrieve messages using IMAP Version 2bis or Version 4 */
1090 {
1091     return(do_protocol(ctl, &imap));
1092 }
1093
1094 /* imap.c ends here */