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