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