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