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