]> Pileus Git - ~andy/fetchmail/blob - imap.c
5e76801cf02b5acb39efe60c43e39d6d835d430c
[~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 void 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
355     /* 
356      * Handle idling.  We depend on coming through here on startup
357      * and after each timeout (including timeouts during idles).
358      */
359     do_idle = ctl->idle;
360     if (ctl->idle)
361     {
362         if (strstr(capabilities, "IDLE"))
363             has_idle = TRUE;
364         else
365             has_idle = FALSE;
366         if (outlevel >= O_VERBOSE)
367             report(stdout, GT_("will idle after poll\n"));
368     }
369
370     peek_capable = TRUE;
371 }
372
373 static int do_authcert (int sock, const char *command, const char *name)
374 /* do authentication "external" (authentication provided by client cert) */
375 {
376     char buf[256];
377
378     if (name && name[0])
379     {
380         size_t len = strlen(name);
381         if ((len / 3) + ((len % 3) ? 4 : 0)  < sizeof(buf))
382             to64frombits (buf, name, strlen(name));
383         else
384             return PS_AUTHFAIL; /* buffer too small. */
385     }
386     else
387         buf[0]=0;
388     return gen_transact(sock, "%s EXTERNAL %s",command,buf);
389 }
390
391 static int imap_getauth(int sock, struct query *ctl, char *greeting)
392 /* apply for connection authorization */
393 {
394     int ok = 0;
395     (void)greeting;
396
397     /*
398      * Assumption: expunges are cheap, so we want to do them
399      * after every message unless user said otherwise.
400      */
401     if (NUM_SPECIFIED(ctl->expunge))
402         expunge_period = NUM_VALUE_OUT(ctl->expunge);
403     else
404         expunge_period = 1;
405
406     capa_probe(sock, ctl);
407
408     /* 
409      * If either (a) we saw a PREAUTH token in the greeting, or
410      * (b) the user specified ssh preauthentication, then we're done.
411      */
412     if (preauth || ctl->server.authenticate == A_SSH)
413     {
414         preauth = FALSE;  /* reset for the next session */
415         return(PS_SUCCESS);
416     }
417
418 #ifdef SSL_ENABLE
419     if (maybe_tls(ctl)) {
420         char *commonname;
421
422         commonname = ctl->server.pollname;
423         if (ctl->server.via)
424             commonname = ctl->server.via;
425         if (ctl->sslcommonname)
426             commonname = ctl->sslcommonname;
427
428         if (strstr(capabilities, "STARTTLS")
429                 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
430         {
431             /* Use "tls1" rather than ctl->sslproto because tls1 is the only
432              * protocol that will work with STARTTLS.  Don't need to worry
433              * whether TLS is mandatory or opportunistic unless SSLOpen() fails
434              * (see below). */
435             if (gen_transact(sock, "STARTTLS") == PS_SUCCESS
436                     && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
437                         ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
438                         ctl->server.pollname, &ctl->remotename) != -1)
439             {
440                 /*
441                  * RFC 2595 says this:
442                  *
443                  * "Once TLS has been started, the client MUST discard cached
444                  * information about server capabilities and SHOULD re-issue the
445                  * CAPABILITY command.  This is necessary to protect against
446                  * man-in-the-middle attacks which alter the capabilities list prior
447                  * to STARTTLS.  The server MAY advertise different capabilities
448                  * after STARTTLS."
449                  *
450                  * Now that we're confident in our TLS connection we can
451                  * guarantee a secure capability re-probe.
452                  */
453                 capa_probe(sock, ctl);
454                 if (outlevel >= O_VERBOSE)
455                 {
456                     report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
457                 }
458             } else if (must_tls(ctl)) {
459                 /* Config required TLS but we couldn't guarantee it, so we must
460                  * stop. */
461                 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
462                 return PS_SOCKET;
463             } else {
464                 if (outlevel >= O_VERBOSE) {
465                     report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue\n"), commonname);
466                 }
467                 /* We don't know whether the connection is in a working state, so
468                  * test by issuing a NOOP. */
469                 if (gen_transact(sock, "NOOP") != PS_SUCCESS) {
470                     /* Not usable.  Empty sslproto to force an unencrypted
471                      * connection on the next attempt, and repoll. */
472                     ctl->sslproto = xstrdup("");
473                     return PS_REPOLL;
474                 }
475                 /* Usable.  Proceed with authenticating insecurely. */
476             }
477         }
478     }
479 #endif /* SSL_ENABLE */
480
481     /*
482      * Time to authenticate the user.
483      * Try the protocol variants that don't require passwords first.
484      */
485     ok = PS_AUTHFAIL;
486
487     /* Yahoo hack - we'll just try ID if it was offered by the server,
488      * and IGNORE errors. */
489     {
490         char *tmp = strstr(capabilities, " ID");
491         if (tmp && !isalnum((unsigned char)tmp[3]) && strstr(ctl->server.via ? ctl->server.via : ctl->server.pollname, "yahoo.com")) {
492                 (void)gen_transact(sock, "ID (\"guid\" \"1\")");
493         }
494     }
495
496     if ((ctl->server.authenticate == A_ANY 
497          || ctl->server.authenticate == A_EXTERNAL)
498         && strstr(capabilities, "AUTH=EXTERNAL"))
499     {
500         ok = do_authcert(sock, "AUTHENTICATE", ctl->remotename);
501         if (ok)
502         {
503             /* SASL cancellation of authentication */
504             gen_send(sock, "*");
505             if (ctl->server.authenticate != A_ANY)
506                 return ok;
507         } else {
508             return ok;
509         }
510     }
511
512 #ifdef GSSAPI
513     if (((ctl->server.authenticate == A_ANY && check_gss_creds("imap", ctl->server.truename) == PS_SUCCESS)
514          || ctl->server.authenticate == A_GSSAPI)
515         && strstr(capabilities, "AUTH=GSSAPI"))
516     {
517         if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
518                         ctl->server.truename, ctl->remotename)))
519         {
520             if (ctl->server.authenticate != A_ANY)
521                 return ok;
522         } else  {
523             return ok;
524         }
525     }
526 #endif /* GSSAPI */
527
528     /*
529      * No such luck.  OK, now try the variants that mask your password
530      * in a challenge-response.
531      */
532
533     if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
534         || ctl->server.authenticate == A_CRAM_MD5)
535     {
536         if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
537         {
538             if(ctl->server.authenticate != A_ANY)
539                 return ok;
540         }
541         else
542             return ok;
543     }
544
545 #ifdef OPIE_ENABLE
546     if ((ctl->server.authenticate == A_ANY 
547          || ctl->server.authenticate == A_OTP)
548         && strstr(capabilities, "AUTH=X-OTP")) {
549         if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
550         {
551             /* SASL cancellation of authentication */
552             gen_send(sock, "*");
553             if(ctl->server.authenticate != A_ANY)
554                 return ok;
555         } else {
556             return ok;
557         }
558     }
559 #else
560     if (ctl->server.authenticate == A_OTP)
561     {
562         report(stderr, 
563            GT_("Required OTP capability not compiled into fetchmail\n"));
564     }
565 #endif /* OPIE_ENABLE */
566
567 #ifdef NTLM_ENABLE
568     if ((ctl->server.authenticate == A_ANY 
569          || ctl->server.authenticate == A_NTLM) 
570         && strstr (capabilities, "AUTH=NTLM")) {
571         if ((ok = do_imap_ntlm(sock, ctl)))
572         {
573             if(ctl->server.authenticate != A_ANY)
574                 return ok;
575         }
576         else
577             return(ok);
578     }
579 #else
580     if (ctl->server.authenticate == A_NTLM)
581     {
582         report(stderr, 
583            GT_("Required NTLM capability not compiled into fetchmail\n"));
584     }
585 #endif /* NTLM_ENABLE */
586
587     /* 
588      * We're stuck with sending the password en clair.
589      * The reason for this odd-looking logic is that some
590      * servers return LOGINDISABLED even though login 
591      * actually works.  So arrange things in such a way that
592      * setting auth passwd makes it ignore this capability.
593      */
594     if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
595         || ctl->server.authenticate == A_PASSWORD)
596     {
597         /* these sizes guarantee no buffer overflow */
598         char *remotename, *password;
599         size_t rnl, pwl;
600         rnl = 2 * strlen(ctl->remotename) + 1;
601         pwl = 2 * strlen(ctl->password) + 1;
602         remotename = (char *)xmalloc(rnl);
603         password = (char *)xmalloc(pwl);
604
605         imap_canonicalize(remotename, ctl->remotename, rnl);
606         imap_canonicalize(password, ctl->password, pwl);
607
608         snprintf(shroud, sizeof (shroud), "\"%s\"", password);
609         ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
610         memset(shroud, 0x55, sizeof(shroud));
611         shroud[0] = '\0';
612         memset(password, 0x55, strlen(password));
613         free(password);
614         free(remotename);
615         if (ok)
616         {
617             if(ctl->server.authenticate != A_ANY)
618                 return ok;
619         }
620         else
621             return(ok);
622     }
623
624     return(ok);
625 }
626
627 static int internal_expunge(int sock)
628 /* ship an expunge, resetting associated counters */
629 {
630     int ok;
631
632     actual_deletions = 0;
633
634     if ((ok = gen_transact(sock, "EXPUNGE")))
635         return(ok);
636
637     /* if there is a mismatch between the number of mails which should
638      * have been expunged and the number of mails actually expunged,
639      * another email client may be deleting mails. Quit here,
640      * otherwise fetchmail gets out-of-sync with the imap server,
641      * reports the wrong size to the SMTP server on MAIL FROM: and
642      * triggers a "message ... was not the expected length" error on
643      * every subsequent mail */
644     if (deletions > 0 && deletions != actual_deletions)
645     {
646         report(stderr,
647                 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
648                 actual_deletions, deletions);
649         deletions = 0;
650         return(PS_ERROR);
651     }
652
653     expunged += deletions;
654     deletions = 0;
655
656 #ifdef IMAP_UID /* not used */
657     expunge_uids(ctl);
658 #endif /* IMAP_UID */
659
660     return(PS_SUCCESS);
661 }
662
663 static int imap_idle(int sock)
664 /* start an RFC2177 IDLE, or fake one if unsupported */
665 {
666     int ok;
667
668     saved_timeout = mytimeout;
669
670     if (has_idle) {
671         /* special timeout to terminate the IDLE and re-issue it
672          * at least every 28 minutes:
673          * (the server may have an inactivity timeout) */
674         mytimeout = idle_timeout = 1680; /* 28 min */
675         time(&idle_start_time);
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_GETRANGE;
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 = idle_timeout = 28;
704             time(&idle_start_time);
705             stage = STAGE_IDLE;
706             /* We are waiting for notification; no tag needed */
707             tag[0] = '\0';
708             /* wait (briefly) for an unsolicited status update */
709             ok = imap_ok(sock, NULL);
710             if (ok == PS_IDLETIMEOUT) {
711                 /* no notification came; ok */
712                 ok = PS_SUCCESS;
713             }
714         }
715     }
716
717     /* restore normal timeout value */
718     mytimeout = saved_timeout;
719     stage = STAGE_GETRANGE;
720
721     return(ok);
722 }
723
724 static int imap_search(int sock, struct query *ctl, int count)
725 /* search for unseen messages */
726 {
727     int ok;
728     char buf[MSGBUFSIZE+1], *cp;
729
730     /* Don't count deleted messages. Enabled only for IMAP4 servers or
731      * higher and only when keeping mails. This flag will have an
732      * effect only when user has marked some unread mails for deletion
733      * using another e-mail client. */
734     flag skipdeleted = ctl->keep;
735     const char *undeleted;
736
737     /* structure to keep the end portion of the incomplete response */
738     struct RecvSplit rs;
739
740     /* startcount is higher than count so that if there are no
741      * unseen messages, imap_getsizes() will not need to do
742      * anything! */
743     startcount = count + 1;
744
745     for (;;)
746     {
747         undeleted = (skipdeleted ? " UNDELETED" : "");
748         gen_send(sock, "SEARCH UNSEEN%s", undeleted);
749         gen_recv_split_init("* SEARCH", &rs);
750         while ((ok = imap_response(sock, buf, &rs)) == PS_UNTAGGED)
751         {
752             if ((cp = strstr(buf, "* SEARCH")))
753             {
754                 char    *ep;
755
756                 cp += 8;        /* skip "* SEARCH" */
757                 while (*cp && unseen < count)
758                 {
759                     /* skip whitespace */
760                     while (*cp && isspace((unsigned char)*cp))
761                         cp++;
762                     if (*cp) 
763                     {
764                         unsigned long um;
765
766                         errno = 0;
767                         um = strtoul(cp,&ep,10);
768                         if (errno == 0 && ep > cp
769                                 && um <= INT_MAX && um <= (unsigned)count)
770                         {
771                             unseen_messages[unseen++] = um;
772                             if (outlevel >= O_DEBUG)
773                                 report(stdout, GT_("%lu is unseen\n"), um);
774                             if (startcount > um)
775                                 startcount = um;
776                         }
777                         cp = ep;
778                     }
779                 }
780             }
781         }
782         if (ok != PS_ERROR) /* success or non-protocol error */
783             return(ok);
784
785         /* there is a protocol error. try a different search command. */
786         if (skipdeleted)
787         {
788             /* retry with "SEARCH UNSEEN" */
789             skipdeleted = FALSE;
790             continue;
791         }
792         /* try with "FETCH 1:n FLAGS" */
793         break;
794     }
795
796     if (count == 1)
797         gen_send(sock, "FETCH %d FLAGS", count);
798     else
799         gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
800     while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
801     {
802         unsigned int num;
803         int consumed;
804
805         /* expected response format:
806          * IMAP< * 1 FETCH (FLAGS (\Seen))
807          * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
808          * IMAP< * 3 FETCH (FLAGS ())
809          * IMAP< * 4 FETCH (FLAGS (\Recent))
810          * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
811          */
812         if (unseen < count
813                 && sscanf(buf, "* %u %n", &num, &consumed) == 1
814                 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
815                 && isspace((unsigned char)buf[consumed+5])
816                 && num >= 1 && num <= (unsigned)count
817                 && strstr(buf, "FLAGS ")
818                 && !strstr(buf, "\\SEEN")
819                 && !strstr(buf, "\\DELETED"))
820         {
821             unseen_messages[unseen++] = num;
822             if (outlevel >= O_DEBUG)
823                 report(stdout, GT_("%u is unseen\n"), num);
824             if (startcount > num)
825                 startcount = num;
826         }
827     }
828     return(ok);
829 }
830
831 static int imap_getrange(int sock, 
832                          struct query *ctl, 
833                          const char *folder, 
834                          int *countp, int *newp, int *bytes)
835 /* get range of messages to be fetched */
836 {
837     int ok;
838
839     /* find out how many messages are waiting */
840     *bytes = -1;
841
842     if (pass > 1)
843     {
844         /* deleted mails have already been expunged by
845          * end_mailbox_poll().
846          *
847          * recentcount is already set here by the last imap command which
848          * returned EXISTS on detecting new mail. if recentcount is 0, wait
849          * for new mail.
850          *
851          * this is a while loop because imap_idle() might return on other
852          * mailbox changes also */
853         while (recentcount == 0 && do_idle) {
854             smtp_close(ctl, 1);
855             ok = imap_idle(sock);
856             if (ok)
857             {
858                 report(stderr, GT_("re-poll failed\n"));
859                 return(ok);
860             }
861         }
862         /* if recentcount is 0, return no mail */
863         if (recentcount == 0)
864                 count = 0;
865         if (outlevel >= O_DEBUG)
866             report(stdout, ngettext("%d message waiting after re-poll\n",
867                                     "%d messages waiting after re-poll\n",
868                                     count), count);
869     }
870     else
871     {
872         oldcount = count = 0;
873         ok = gen_transact(sock, 
874                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
875                           folder ? folder : "INBOX");
876         /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
877          * which we can safely use in fetchall keep only */
878         if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
879             ok = 0;
880
881         if (ok != 0)
882         {
883             report(stderr, GT_("mailbox selection failed\n"));
884             return(ok);
885         }
886         else if (outlevel >= O_DEBUG)
887             report(stdout, ngettext("%d message waiting after first poll\n",
888                                     "%d messages waiting after first poll\n",
889                                     count), count);
890
891         /*
892          * We should have an expunge here to
893          * a) avoid fetching deleted mails during 'fetchall'
894          * b) getting a wrong count of mails during 'no fetchall'
895          */
896         if (!check_only && !ctl->keep && count > 0)
897         {
898             ok = internal_expunge(sock);
899             if (ok)
900             {
901                 report(stderr, GT_("expunge failed\n"));
902                 return(ok);
903             }
904             if (outlevel >= O_DEBUG)
905                 report(stdout, ngettext("%d message waiting after expunge\n",
906                                         "%d messages waiting after expunge\n",
907                                         count), count);
908         }
909
910         if (count == 0 && do_idle)
911         {
912             /* no messages?  then we may need to idle until we get some */
913             while (count == 0) {
914                 ok = imap_idle(sock);
915                 if (ok)
916                 {
917                     report(stderr, GT_("re-poll failed\n"));
918                     return(ok);
919                 }
920             }
921             if (outlevel >= O_DEBUG)
922                 report(stdout, ngettext("%d message waiting after re-poll\n",
923                                         "%d messages waiting after re-poll\n",
924                                         count), count);
925         }
926     }
927
928     *countp = oldcount = count;
929     recentcount = 0;
930     startcount = 1;
931
932     /* OK, now get a count of unseen messages and their indices */
933     if (!ctl->fetchall && count > 0)
934     {
935         if (unseen_messages)
936             free(unseen_messages);
937         unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
938         memset(unseen_messages, 0, count * sizeof(unsigned int));
939         unseen = 0;
940
941         ok = imap_search(sock, ctl, count);
942         if (ok != 0)
943         {
944             report(stderr, GT_("search for unseen messages failed\n"));
945             return(ok);
946         }
947
948         if (outlevel >= O_DEBUG && unseen > 0)
949             report(stdout, GT_("%u is first unseen\n"), startcount);
950     } else
951         unseen = -1;
952
953     *newp = unseen;
954     expunged = 0;
955     deletions = 0;
956
957     return(PS_SUCCESS);
958 }
959
960 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
961 /* capture the sizes of messages #first-#last */
962 {
963     char buf [MSGBUFSIZE+1];
964     int ok;
965
966     /*
967      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
968      * won't accept 1:1 as valid set syntax.  Some implementors
969      * should be taken out and shot for excessive anality.
970      *
971      * Microsoft Exchange (brain-dead piece of crap that it is) 
972      * sometimes gets its knickers in a knot about bodiless messages.
973      * You may see responses like this:
974      *
975      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
976      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
977      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
978      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
979      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
980      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
981      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
982      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
983      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
984      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
985      *
986      * This means message 1 has only headers.  For kicks and grins
987      * you can telnet in and look:
988      *  A003 FETCH 1 FULL
989      *  A003 NO The requested item could not be found.
990      *  A004 fetch 1 rfc822.header
991      *  A004 NO The requested item could not be found.
992      *  A006 FETCH 1 BODY
993      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
994      *  A006 OK FETCH completed.
995      *
996      * To get around this, we treat the final NO as success and count
997      * on the fact that the sizes array has been preinitialized with a
998      * known-bad size value.
999      */
1000
1001     /* expunges change the fetch numbers */
1002     first -= expunged;
1003     last -= expunged;
1004
1005     if (last == first)
1006         gen_send(sock, "FETCH %d RFC822.SIZE", last);
1007     else if (last > first)
1008         gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1009     else /* no unseen messages! */
1010         return(PS_SUCCESS);
1011     while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
1012     {
1013         unsigned int size;
1014         int num;
1015         int consumed;
1016         char *ptr;
1017
1018         /* expected response formats:
1019          * IMAP> A0005 FETCH 1 RFC822.SIZE
1020          * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1021          * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1022          */
1023         if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1024             && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1025             && isspace((unsigned char)buf[consumed + 5])
1026                 && (ptr = strstr(buf, "RFC822.SIZE "))
1027                 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1028         {
1029             if (num >= first && num <= last)
1030                 sizes[num - first] = size;
1031             else
1032                 report(stderr,
1033                         GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1034         }
1035     }
1036     return(ok);
1037 }
1038
1039 static int imap_getsizes(int sock, int count, int *sizes)
1040 /* capture the sizes of all messages */
1041 {
1042     return imap_getpartialsizes(sock, 1, count, sizes);
1043 }
1044
1045 static int imap_is_old(int sock, struct query *ctl, int number)
1046 /* is the given message old? */
1047 {
1048     flag seen = TRUE;
1049     int i;
1050
1051     (void)sock;
1052     (void)ctl;
1053     /* 
1054      * Expunges change the fetch numbers, but unseen_messages contains
1055      * indices from before any expungees were done.  So neither the
1056      * argument nor the values in message_sequence need to be decremented.
1057      */
1058
1059     seen = TRUE;
1060     for (i = 0; i < unseen; i++)
1061         if (unseen_messages[i] == (unsigned)number)
1062         {
1063             seen = FALSE;
1064             break;
1065         }
1066
1067     return(seen);
1068 }
1069
1070 #if 0
1071 static char *skip_token(char *ptr)
1072 {
1073     while(isspace((unsigned char)*ptr)) ptr++;
1074     while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1075     while(isspace((unsigned char)*ptr)) ptr++;
1076     return(ptr);
1077 }
1078 #endif
1079
1080 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1081 /* request headers of nth message */
1082 {
1083     char buf [MSGBUFSIZE+1];
1084     int num;
1085     int ok;
1086     char *ptr;
1087
1088     (void)ctl;
1089     /* expunges change the fetch numbers */
1090     number -= expunged;
1091
1092     /*
1093      * This is blessed by RFC1176, RFC1730, RFC2060.
1094      * According to the RFCs, it should *not* set the \Seen flag.
1095      */
1096     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1097
1098     /* looking for FETCH response */
1099     if ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
1100     {
1101                 int consumed;
1102         /* expected response formats:
1103          * IMAP> A0006 FETCH 1 RFC822.HEADER
1104          * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1105          * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1106          * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1107          */
1108         if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1109             && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1110             && isspace((unsigned char)buf[5+consumed])
1111                 && num == number
1112                 && (ptr = strstr(buf, "RFC822.HEADER"))
1113                 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1114                 && ptr[consumed-1] == '}')
1115         {
1116             return(PS_SUCCESS);
1117         }
1118
1119         /* wait for a tagged response */
1120         imap_ok (sock, 0);
1121
1122         /* try to recover for some responses */
1123         if (!strncmp(buf, "* NO", 4) ||
1124                 !strncmp(buf, "* BAD", 5))
1125         {
1126             return(PS_TRANSIENT);
1127         }
1128
1129         /* a response which does not match any of the above */
1130         if (outlevel > O_SILENT)
1131             report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1132         return(PS_ERROR);
1133     }
1134     else if (ok == PS_SUCCESS)
1135     {
1136         /* an unexpected tagged response */
1137         if (outlevel > O_SILENT)
1138             report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1139         return(PS_ERROR);
1140     }
1141     return(ok);
1142 }
1143
1144 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1145 /* request body of nth message */
1146 {
1147     char buf [MSGBUFSIZE+1], *cp;
1148     int num;
1149
1150     (void)ctl;
1151     /* expunges change the fetch numbers */
1152     number -= expunged;
1153
1154     /*
1155      * If we're using IMAP4, we can fetch the message without setting its
1156      * seen flag.  This is good!  It means that if the protocol exchange
1157      * craps out during the message, it will still be marked `unseen' on
1158      * the server.
1159      *
1160      * According to RFC2060, and Mark Crispin the IMAP maintainer,
1161      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
1162      * equivalent".  However, we know of at least one server that
1163      * treats them differently in the presence of MIME attachments;
1164      * the latter form downloads the attachment, the former does not.
1165      * The server is InterChange.
1166      *
1167      * When I tried working around this by disabling use of the 4rev1 form,
1168      * I found that doing this breaks operation with M$ Exchange.
1169      * Annoyingly enough, Exchange's refusal to cope is technically legal
1170      * under RFC2062.
1171      */
1172     switch (imap_version)
1173     {
1174     case IMAP4rev1:     /* RFC 2060 */
1175     default:
1176         gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1177         break;
1178
1179     case IMAP4:         /* RFC 1730 */
1180         gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1181         break;
1182     }
1183
1184     /* looking for FETCH response */
1185     do {
1186         int     ok;
1187
1188         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1189             return(ok);
1190     } while
1191         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1192
1193     if (num != number)
1194         return(PS_ERROR);
1195
1196     /* Understand "NIL" as length => no body present
1197      * (MS Exchange, BerliOS Bug #11980) */
1198     if (strstr(buf+10, "NIL)")) {
1199             *lenp = 0;
1200             return PS_SUCCESS;
1201     }
1202
1203     /* Understand the empty string. Seen on Yahoo. */
1204     /* XXX FIXME: we should be able to handle strings here. */
1205     if (strstr(buf+10, "\"\")")) {
1206             *lenp = 0;
1207             return PS_SUCCESS;
1208     }
1209
1210     /*
1211      * Try to extract a length from the FETCH response.  RFC2060 requires
1212      * it to be present, but at least one IMAP server (Novell GroupWise)
1213      * botches this.  The overflow check is needed because of a broken
1214      * server called dbmail that returns huge garbage lengths.
1215      */
1216     if ((cp = strchr(buf, '{'))) {
1217         long l; char *t;
1218         errno = 0;
1219         ++ cp;
1220         l = strtol(cp, &t, 10);
1221         if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1222                     || l < 0 || l > INT_MAX /* range check */) {
1223             *lenp = -1;
1224         } else {
1225             *lenp = l;
1226         }
1227     } else {
1228         *lenp = -1;     /* missing length part in FETCH reponse */
1229     }
1230
1231     return PS_SUCCESS;
1232 }
1233
1234 static int imap_trail(int sock, struct query *ctl, const char *tag)
1235 /* discard tail of FETCH response after reading message text */
1236 {
1237     /* expunges change the fetch numbers */
1238     /* number -= expunged; */
1239
1240     (void)ctl;
1241     (void)tag;
1242
1243     return imap_ok(sock, NULL);
1244 }
1245
1246 static int imap_delete(int sock, struct query *ctl, int number)
1247 /* set delete flag for given message */
1248 {
1249     int ok;
1250     /* Select which flags to set on message deletion: */
1251     const char delflags_seen[] = "\\Seen \\Deleted";
1252     const char delflags_unseen[] = "\\Deleted";
1253     static const char *delflags;
1254     /* Which environment variable to look for: */
1255     const char dis_env[] = "FETCHMAIL_IMAP_DELETED_REMAINS_UNSEEN";
1256
1257     if (!delflags) {
1258         char *tmp;
1259         if ((tmp = getenv(dis_env)) != NULL && *tmp) {
1260             delflags = delflags_unseen;
1261         } else {
1262             /* DEFAULT since many fetchmail versions <= 6.3.X */
1263             delflags = delflags_seen;
1264         }
1265     }
1266
1267     (void)ctl;
1268     /* expunges change the fetch numbers */
1269     number -= expunged;
1270
1271     /*
1272      * We set Seen because there are some IMAP servers (notably HP
1273      * OpenMail) that do message-receipt DSNs, but only when the seen
1274      * bit is set.  This is the appropriate time -- we get here right
1275      * after the local SMTP response that says delivery was
1276      * successful.
1277      */
1278     if ((ok = gen_transact(sock, "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)", number)))
1279         return(ok);
1280     else
1281         deletions++;
1282
1283     /*
1284      * We do an expunge after expunge_period messages, rather than
1285      * just before quit, so that a line hit during a long session
1286      * won't result in lots of messages being fetched again during
1287      * the next session.
1288      */
1289     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1290     {
1291         if ((ok = internal_expunge(sock)))
1292             return(ok);
1293     }
1294
1295     return(PS_SUCCESS);
1296 }
1297
1298 static int imap_mark_seen(int sock, struct query *ctl, int number)
1299 /* mark the given message as seen */
1300 {
1301     (void)ctl;
1302
1303     /* expunges change the message numbers */
1304     number -= expunged;
1305
1306     return(gen_transact(sock,"STORE %d +FLAGS.SILENT (\\Seen)", number));
1307 }
1308
1309 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1310 /* cleanup mailbox before we idle or switch to another one */
1311 {
1312     (void)ctl;
1313     if (deletions)
1314         internal_expunge(sock);
1315     return(PS_SUCCESS);
1316 }
1317
1318 static int imap_logout(int sock, struct query *ctl)
1319 /* send logout command */
1320 {
1321     (void)ctl;
1322     /* if any un-expunged deletions remain, ship an expunge now */
1323     if (deletions)
1324         internal_expunge(sock);
1325
1326 #ifdef USE_SEARCH
1327     /* Memory clean-up */
1328     if (unseen_messages)
1329         free(unseen_messages);
1330 #endif /* USE_SEARCH */
1331
1332     return(gen_transact(sock, "LOGOUT"));
1333 }
1334
1335 static const struct method imap =
1336 {
1337     "IMAP",             /* Internet Message Access Protocol */
1338     "imap",             /* service (plain and TLS) */
1339     "imaps",            /* service (SSL) */
1340     TRUE,               /* this is a tagged protocol */
1341     FALSE,              /* no message delimiter */
1342     imap_ok,            /* parse command response */
1343     imap_getauth,       /* get authorization */
1344     imap_getrange,      /* query range of messages */
1345     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1346     imap_getpartialsizes,       /* get sizes of subset of messages (used for ESMTP SIZE option) */
1347     imap_is_old,        /* no UID check */
1348     imap_fetch_headers, /* request given message headers */
1349     imap_fetch_body,    /* request given message body */
1350     imap_trail,         /* eat message trailer */
1351     imap_delete,        /* delete the message */
1352     imap_mark_seen,     /* how to mark a message as seen */
1353     imap_end_mailbox_poll,      /* end-of-mailbox processing */
1354     imap_logout,        /* expunge and exit */
1355     TRUE,               /* yes, we can re-poll */
1356 };
1357
1358 int doIMAP(struct query *ctl)
1359 /* retrieve messages using IMAP Version 2bis or Version 4 */
1360 {
1361     return(do_protocol(ctl, &imap));
1362 }
1363
1364 /* imap.c ends here */