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