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