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