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