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