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