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