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