]> Pileus Git - ~andy/fetchmail/blob - imap.c
Attempt merging from 6.3.24.
[~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     set_timeout(0);
727     mytimeout = saved_timeout;
728     stage = STAGE_GETRANGE;
729
730     return(ok);
731 }
732
733 static int imap_search(int sock, struct query *ctl, int count)
734 /* search for unseen messages */
735 {
736     int ok;
737     char buf[MSGBUFSIZE+1], *cp;
738
739     /* Don't count deleted messages. Enabled only for IMAP4 servers or
740      * higher and only when keeping mails. This flag will have an
741      * effect only when user has marked some unread mails for deletion
742      * using another e-mail client. */
743     flag skipdeleted = ctl->keep;
744     const char *undeleted;
745
746     /* structure to keep the end portion of the incomplete response */
747     struct RecvSplit rs;
748
749     /* startcount is higher than count so that if there are no
750      * unseen messages, imap_getsizes() will not need to do
751      * anything! */
752     startcount = count + 1;
753
754     for (;;)
755     {
756         undeleted = (skipdeleted ? " UNDELETED" : "");
757         gen_send(sock, "SEARCH UNSEEN%s", undeleted);
758         gen_recv_split_init("* SEARCH", &rs);
759         while ((ok = imap_response(sock, buf, &rs)) == PS_UNTAGGED)
760         {
761             if ((cp = strstr(buf, "* SEARCH")))
762             {
763                 char    *ep;
764
765                 cp += 8;        /* skip "* SEARCH" */
766                 while (*cp && unseen < count)
767                 {
768                     /* skip whitespace */
769                     while (*cp && isspace((unsigned char)*cp))
770                         cp++;
771                     if (*cp) 
772                     {
773                         unsigned long um;
774
775                         errno = 0;
776                         um = strtoul(cp,&ep,10);
777                         if (errno == 0 && ep > cp
778                                 && um <= INT_MAX && um <= (unsigned)count)
779                         {
780                             unseen_messages[unseen++] = um;
781                             if (outlevel >= O_DEBUG)
782                                 report(stdout, GT_("%lu is unseen\n"), um);
783                             if (startcount > um)
784                                 startcount = um;
785                         }
786                         cp = ep;
787                     }
788                 }
789             }
790         }
791         if (ok != PS_ERROR) /* success or non-protocol error */
792             return(ok);
793
794         /* there is a protocol error. try a different search command. */
795         if (skipdeleted)
796         {
797             /* retry with "SEARCH UNSEEN" */
798             skipdeleted = FALSE;
799             continue;
800         }
801         /* try with "FETCH 1:n FLAGS" */
802         break;
803     }
804
805     if (count == 1)
806         gen_send(sock, "FETCH %d FLAGS", count);
807     else
808         gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
809     while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
810     {
811         unsigned int num;
812         int consumed;
813
814         /* expected response format:
815          * IMAP< * 1 FETCH (FLAGS (\Seen))
816          * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
817          * IMAP< * 3 FETCH (FLAGS ())
818          * IMAP< * 4 FETCH (FLAGS (\Recent))
819          * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
820          */
821         if (unseen < count
822                 && sscanf(buf, "* %u %n", &num, &consumed) == 1
823                 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
824                 && isspace((unsigned char)buf[consumed+5])
825                 && num >= 1 && num <= (unsigned)count
826                 && strstr(buf, "FLAGS ")
827                 && !strstr(buf, "\\SEEN")
828                 && !strstr(buf, "\\DELETED"))
829         {
830             unseen_messages[unseen++] = num;
831             if (outlevel >= O_DEBUG)
832                 report(stdout, GT_("%u is unseen\n"), num);
833             if (startcount > num)
834                 startcount = num;
835         }
836     }
837     return(ok);
838 }
839
840 static int imap_getrange(int sock, 
841                          struct query *ctl, 
842                          const char *folder, 
843                          int *countp, int *newp, int *bytes)
844 /* get range of messages to be fetched */
845 {
846     int ok;
847
848     /* find out how many messages are waiting */
849     *bytes = -1;
850
851     if (pass > 1)
852     {
853         /* deleted mails have already been expunged by
854          * end_mailbox_poll().
855          *
856          * recentcount is already set here by the last imap command which
857          * returned EXISTS on detecting new mail. if recentcount is 0, wait
858          * for new mail.
859          *
860          * this is a while loop because imap_idle() might return on other
861          * mailbox changes also */
862         while (recentcount == 0 && do_idle) {
863             smtp_close(ctl, 1);
864             ok = imap_idle(sock);
865             if (ok)
866             {
867                 report(stderr, GT_("re-poll failed\n"));
868                 return(ok);
869             }
870         }
871         /* if recentcount is 0, return no mail */
872         if (recentcount == 0)
873                 count = 0;
874         if (outlevel >= O_DEBUG)
875             report(stdout, ngettext("%d message waiting after re-poll\n",
876                                     "%d messages waiting after re-poll\n",
877                                     count), count);
878     }
879     else
880     {
881         oldcount = count = 0;
882         ok = gen_transact(sock, 
883                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
884                           folder ? folder : "INBOX");
885         /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
886          * which we can safely use in fetchall keep only */
887         if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
888             ok = 0;
889
890         if (ok != 0)
891         {
892             report(stderr, GT_("mailbox selection failed\n"));
893             return(ok);
894         }
895         else if (outlevel >= O_DEBUG)
896             report(stdout, ngettext("%d message waiting after first poll\n",
897                                     "%d messages waiting after first poll\n",
898                                     count), count);
899
900         /*
901          * We should have an expunge here to
902          * a) avoid fetching deleted mails during 'fetchall'
903          * b) getting a wrong count of mails during 'no fetchall'
904          */
905         if (!check_only && !ctl->keep && count > 0)
906         {
907             ok = internal_expunge(sock);
908             if (ok)
909             {
910                 report(stderr, GT_("expunge failed\n"));
911                 return(ok);
912             }
913             if (outlevel >= O_DEBUG)
914                 report(stdout, ngettext("%d message waiting after expunge\n",
915                                         "%d messages waiting after expunge\n",
916                                         count), count);
917         }
918
919         if (count == 0 && do_idle)
920         {
921             /* no messages?  then we may need to idle until we get some */
922             while (count == 0) {
923                 ok = imap_idle(sock);
924                 if (ok)
925                 {
926                     report(stderr, GT_("re-poll failed\n"));
927                     return(ok);
928                 }
929             }
930             if (outlevel >= O_DEBUG)
931                 report(stdout, ngettext("%d message waiting after re-poll\n",
932                                         "%d messages waiting after re-poll\n",
933                                         count), count);
934         }
935     }
936
937     *countp = oldcount = count;
938     recentcount = 0;
939     startcount = 1;
940
941     /* OK, now get a count of unseen messages and their indices */
942     if (!ctl->fetchall && count > 0)
943     {
944         if (unseen_messages)
945             free(unseen_messages);
946         unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
947         memset(unseen_messages, 0, count * sizeof(unsigned int));
948         unseen = 0;
949
950         ok = imap_search(sock, ctl, count);
951         if (ok != 0)
952         {
953             report(stderr, GT_("search for unseen messages failed\n"));
954             return(ok);
955         }
956
957         if (outlevel >= O_DEBUG && unseen > 0)
958             report(stdout, GT_("%u is first unseen\n"), startcount);
959     } else
960         unseen = -1;
961
962     *newp = unseen;
963     expunged = 0;
964     deletions = 0;
965
966     return(PS_SUCCESS);
967 }
968
969 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
970 /* capture the sizes of messages #first-#last */
971 {
972     char buf [MSGBUFSIZE+1];
973     int ok;
974
975     /*
976      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
977      * won't accept 1:1 as valid set syntax.  Some implementors
978      * should be taken out and shot for excessive anality.
979      *
980      * Microsoft Exchange (brain-dead piece of crap that it is) 
981      * sometimes gets its knickers in a knot about bodiless messages.
982      * You may see responses like this:
983      *
984      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
985      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
986      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
987      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
988      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
989      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
990      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
991      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
992      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
993      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
994      *
995      * This means message 1 has only headers.  For kicks and grins
996      * you can telnet in and look:
997      *  A003 FETCH 1 FULL
998      *  A003 NO The requested item could not be found.
999      *  A004 fetch 1 rfc822.header
1000      *  A004 NO The requested item could not be found.
1001      *  A006 FETCH 1 BODY
1002      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1003      *  A006 OK FETCH completed.
1004      *
1005      * To get around this, we treat the final NO as success and count
1006      * on the fact that the sizes array has been preinitialized with a
1007      * known-bad size value.
1008      */
1009
1010     /* expunges change the fetch numbers */
1011     first -= expunged;
1012     last -= expunged;
1013
1014     if (last == first)
1015         gen_send(sock, "FETCH %d RFC822.SIZE", last);
1016     else if (last > first)
1017         gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1018     else /* no unseen messages! */
1019         return(PS_SUCCESS);
1020     while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
1021     {
1022         unsigned int size;
1023         int num;
1024         int consumed;
1025         char *ptr;
1026
1027         /* expected response formats:
1028          * IMAP> A0005 FETCH 1 RFC822.SIZE
1029          * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1030          * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1031          */
1032         if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1033             && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1034             && isspace((unsigned char)buf[consumed + 5])
1035                 && (ptr = strstr(buf, "RFC822.SIZE "))
1036                 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1037         {
1038             if (num >= first && num <= last)
1039                 sizes[num - first] = size;
1040             else
1041                 report(stderr,
1042                         GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1043         }
1044     }
1045     return(ok);
1046 }
1047
1048 static int imap_getsizes(int sock, int count, int *sizes)
1049 /* capture the sizes of all messages */
1050 {
1051     return imap_getpartialsizes(sock, 1, count, sizes);
1052 }
1053
1054 static int imap_is_old(int sock, struct query *ctl, int number)
1055 /* is the given message old? */
1056 {
1057     flag seen = TRUE;
1058     int i;
1059
1060     (void)sock;
1061     (void)ctl;
1062     /* 
1063      * Expunges change the fetch numbers, but unseen_messages contains
1064      * indices from before any expungees were done.  So neither the
1065      * argument nor the values in message_sequence need to be decremented.
1066      */
1067
1068     seen = TRUE;
1069     for (i = 0; i < unseen; i++)
1070         if (unseen_messages[i] == (unsigned)number)
1071         {
1072             seen = FALSE;
1073             break;
1074         }
1075
1076     return(seen);
1077 }
1078
1079 #if 0
1080 static char *skip_token(char *ptr)
1081 {
1082     while(isspace((unsigned char)*ptr)) ptr++;
1083     while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1084     while(isspace((unsigned char)*ptr)) ptr++;
1085     return(ptr);
1086 }
1087 #endif
1088
1089 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1090 /* request headers of nth message */
1091 {
1092     char buf [MSGBUFSIZE+1];
1093     int num;
1094     int ok;
1095     char *ptr;
1096
1097     (void)ctl;
1098     /* expunges change the fetch numbers */
1099     number -= expunged;
1100
1101     /*
1102      * This is blessed by RFC1176, RFC1730, RFC2060.
1103      * According to the RFCs, it should *not* set the \Seen flag.
1104      */
1105     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1106
1107     /* looking for FETCH response */
1108     if ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
1109     {
1110                 int consumed;
1111         /* expected response formats:
1112          * IMAP> A0006 FETCH 1 RFC822.HEADER
1113          * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1114          * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1115          * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1116          */
1117         if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1118             && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1119             && isspace((unsigned char)buf[5+consumed])
1120                 && num == number
1121                 && (ptr = strstr(buf, "RFC822.HEADER"))
1122                 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1123                 && ptr[consumed-1] == '}')
1124         {
1125             return(PS_SUCCESS);
1126         }
1127
1128         /* wait for a tagged response */
1129         imap_ok (sock, 0);
1130
1131         /* try to recover for some responses */
1132         if (!strncmp(buf, "* NO", 4) ||
1133                 !strncmp(buf, "* BAD", 5) ||
1134                 strstr(buf, "FETCH ()"))
1135         {
1136             return(PS_TRANSIENT);
1137         }
1138
1139         /* a response which does not match any of the above */
1140         if (outlevel > O_SILENT)
1141             report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1142         return(PS_ERROR);
1143     }
1144     else if (ok == PS_SUCCESS)
1145     {
1146         /* an unexpected tagged response */
1147         if (outlevel > O_SILENT)
1148             report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1149         return(PS_TRANSIENT);
1150     }
1151     return(ok);
1152 }
1153
1154 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1155 /* request body of nth message */
1156 {
1157     char buf [MSGBUFSIZE+1], *cp;
1158     int num;
1159
1160     (void)ctl;
1161     /* expunges change the fetch numbers */
1162     number -= expunged;
1163
1164     /*
1165      * If we're using IMAP4, we can fetch the message without setting its
1166      * seen flag.  This is good!  It means that if the protocol exchange
1167      * craps out during the message, it will still be marked `unseen' on
1168      * the server.
1169      *
1170      * According to RFC2060, and Mark Crispin the IMAP maintainer,
1171      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
1172      * equivalent".  However, we know of at least one server that
1173      * treats them differently in the presence of MIME attachments;
1174      * the latter form downloads the attachment, the former does not.
1175      * The server is InterChange.
1176      *
1177      * When I tried working around this by disabling use of the 4rev1 form,
1178      * I found that doing this breaks operation with M$ Exchange.
1179      * Annoyingly enough, Exchange's refusal to cope is technically legal
1180      * under RFC2062.
1181      */
1182     switch (imap_version)
1183     {
1184     case IMAP4rev1:     /* RFC 2060 */
1185     default:
1186         gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1187         break;
1188
1189     case IMAP4:         /* RFC 1730 */
1190         gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1191         break;
1192     }
1193
1194     /* looking for FETCH response */
1195     do {
1196         int     ok;
1197
1198         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1199             return(ok);
1200     } while
1201         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1202
1203     if (num != number)
1204         return(PS_ERROR);
1205
1206     /* Understand "NIL" as length => no body present
1207      * (MS Exchange, BerliOS Bug #11980) */
1208     if (strstr(buf+10, "NIL)")) {
1209             *lenp = 0;
1210             return PS_SUCCESS;
1211     }
1212
1213     /* Understand the empty string. Seen on Yahoo. */
1214     /* XXX FIXME: we should be able to handle strings here. */
1215     if (strstr(buf+10, "\"\")")) {
1216             *lenp = 0;
1217             return PS_SUCCESS;
1218     }
1219
1220     /*
1221      * Try to extract a length from the FETCH response.  RFC2060 requires
1222      * it to be present, but at least one IMAP server (Novell GroupWise)
1223      * botches this.  The overflow check is needed because of a broken
1224      * server called dbmail that returns huge garbage lengths.
1225      */
1226     if ((cp = strchr(buf, '{'))) {
1227         long l; char *t;
1228         errno = 0;
1229         ++ cp;
1230         l = strtol(cp, &t, 10);
1231         if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1232                     || l < 0 || l > INT_MAX /* range check */) {
1233             *lenp = -1;
1234         } else {
1235             *lenp = l;
1236         }
1237     } else {
1238         *lenp = -1;     /* missing length part in FETCH reponse */
1239     }
1240
1241     return PS_SUCCESS;
1242 }
1243
1244 static int imap_trail(int sock, struct query *ctl, const char *tag)
1245 /* discard tail of FETCH response after reading message text */
1246 {
1247     /* expunges change the fetch numbers */
1248     /* number -= expunged; */
1249
1250     (void)ctl;
1251     (void)tag;
1252
1253     return imap_ok(sock, NULL);
1254 }
1255
1256 static int imap_delete(int sock, struct query *ctl, int number)
1257 /* set delete flag for given message */
1258 {
1259     int ok;
1260     /* Select which flags to set on message deletion: */
1261     const char delflags_seen[] = "\\Seen \\Deleted";
1262     static const char *delflags;
1263     /* Which environment variable to look for: */
1264
1265     /* DEFAULT since many fetchmail versions <= 6.3.X */
1266     delflags = delflags_seen;
1267
1268     (void)ctl;
1269     /* expunges change the fetch numbers */
1270     number -= expunged;
1271
1272     /*
1273      * We set Seen because there are some IMAP servers (notably HP
1274      * OpenMail) that do message-receipt DSNs, but only when the seen
1275      * bit is set.  This is the appropriate time -- we get here right
1276      * after the local SMTP response that says delivery was
1277      * successful.
1278      */
1279     if ((ok = gen_transact(sock, "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)", number)))
1280         return(ok);
1281     else
1282         deletions++;
1283
1284     /*
1285      * We do an expunge after expunge_period messages, rather than
1286      * just before quit, so that a line hit during a long session
1287      * won't result in lots of messages being fetched again during
1288      * the next session.
1289      */
1290     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1291     {
1292         if ((ok = internal_expunge(sock)))
1293             return(ok);
1294     }
1295
1296     return(PS_SUCCESS);
1297 }
1298
1299 static int imap_mark_seen(int sock, struct query *ctl, int number)
1300 /* mark the given message as seen */
1301 {
1302     (void)ctl;
1303
1304     /* expunges change the message numbers */
1305     number -= expunged;
1306
1307     return(gen_transact(sock,"STORE %d +FLAGS.SILENT (\\Seen)", number));
1308 }
1309
1310 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1311 /* cleanup mailbox before we idle or switch to another one */
1312 {
1313     (void)ctl;
1314     if (deletions)
1315         internal_expunge(sock);
1316     return(PS_SUCCESS);
1317 }
1318
1319 static int imap_logout(int sock, struct query *ctl)
1320 /* send logout command */
1321 {
1322     (void)ctl;
1323     /* if any un-expunged deletions remain, ship an expunge now */
1324     if (deletions)
1325         internal_expunge(sock);
1326
1327 #ifdef USE_SEARCH
1328     /* Memory clean-up */
1329     if (unseen_messages)
1330         free(unseen_messages);
1331 #endif /* USE_SEARCH */
1332
1333     return(gen_transact(sock, "LOGOUT"));
1334 }
1335
1336 static const struct method imap =
1337 {
1338     "IMAP",             /* Internet Message Access Protocol */
1339     "imap",             /* service (plain and TLS) */
1340     "imaps",            /* service (SSL) */
1341     TRUE,               /* this is a tagged protocol */
1342     FALSE,              /* no message delimiter */
1343     imap_ok,            /* parse command response */
1344     imap_getauth,       /* get authorization */
1345     imap_getrange,      /* query range of messages */
1346     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1347     imap_getpartialsizes,       /* get sizes of subset of messages (used for ESMTP SIZE option) */
1348     imap_is_old,        /* no UID check */
1349     imap_fetch_headers, /* request given message headers */
1350     imap_fetch_body,    /* request given message body */
1351     imap_trail,         /* eat message trailer */
1352     imap_delete,        /* delete the message */
1353     imap_mark_seen,     /* how to mark a message as seen */
1354     imap_end_mailbox_poll,      /* end-of-mailbox processing */
1355     imap_logout,        /* expunge and exit */
1356     TRUE,               /* yes, we can re-poll */
1357 };
1358
1359 int doIMAP(struct query *ctl)
1360 /* retrieve messages using IMAP Version 2bis or Version 4 */
1361 {
1362     return(do_protocol(ctl, &imap));
1363 }
1364
1365 /* imap.c ends here */