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