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