2 * imap.c -- IMAP2bis/IMAP4 protocol methods
4 * Copyright 1997 by Eric S. Raymond
5 * For license terms, see the file COPYING in this directory.
16 #include "fetchmail.h"
21 /* imap_version values */
22 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
23 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
24 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
26 /* global variables: please reinitialize them explicitly for proper
27 * working in daemon mode */
29 /* TODO: session variables to be initialized before server greeting */
30 static int preauth = FALSE;
32 /* session variables initialized in capa_probe() or imap_getauth() */
33 static char capabilities[MSGBUFSIZE+1];
34 static int imap_version = IMAP4;
35 static flag do_idle = FALSE, has_idle = FALSE;
36 static int expunge_period = 1;
38 /* mailbox variables initialized in imap_getrange() */
39 static int count = 0, oldcount = 0, recentcount = 0, unseen = 0, deletions = 0;
40 static unsigned int startcount = 1;
41 static int expunged = 0;
42 static unsigned int *unseen_messages;
44 /* for "IMAP> EXPUNGE" */
45 static int actual_deletions = 0;
47 /* for "IMAP> IDLE" */
48 static int saved_timeout = 0, idle_timeout = 0;
49 static time_t idle_start_time = 0;
51 static int imap_untagged_response(int sock, const char *buf)
52 /* interpret untagged status responses */
54 /* For each individual check, use a BLANK before the word to avoid
55 * confusion with the \Recent flag or similar */
56 if (stage == STAGE_GETAUTH
57 && !strncmp(buf, "* CAPABILITY", 12))
59 strlcpy(capabilities, buf + 12, sizeof(capabilities));
61 else if (stage == STAGE_GETAUTH
62 && !strncmp(buf, "* PREAUTH", 9))
66 else if (stage != STAGE_LOGOUT
67 && !strncmp(buf, "* BYE", 5))
69 /* log the unexpected bye from server as we expect the
70 * connection to be cut-off after this */
71 if (outlevel > O_SILENT)
72 report(stderr, GT_("Received BYE response from IMAP server: %s"), buf + 5);
74 else if (strstr(buf, " EXISTS"))
76 char *t; unsigned long u;
78 u = strtoul(buf+2, &t, 10);
80 * Don't trust the message count passed by the server.
81 * Without this check, it might be possible to do a
82 * DNS-spoofing attack that would pass back a ridiculous
83 * count, and allocate a malloc area that would overlap
84 * a portion of the stack.
86 if (errno /* strtoul failed */
87 || t == buf+2 /* no valid data */
88 || u > (unsigned long)(INT_MAX/sizeof(int)) /* too large */)
90 report(stderr, GT_("bogus message count in \"%s\"!"), buf);
93 count = u; /* safe as long as count <= INT_MAX - checked above */
95 if ((recentcount = count - oldcount) < 0)
99 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
100 * we can't wait for the tag matching the IDLE; we have to tell the
101 * server the IDLE is finished by shipping back a DONE when we
102 * see an EXISTS. Only after that will a tagged response be
103 * shipped. The idling flag also gets cleared on a timeout.
105 if (stage == STAGE_IDLE)
107 /* If IDLE isn't supported, we were only sending NOOPs anyway. */
110 /* we do our own write and report here to disable tagging */
111 SockWrite(sock, "DONE\r\n", 6);
112 if (outlevel >= O_MONITOR)
113 report(stdout, "IMAP> DONE\n");
116 mytimeout = saved_timeout;
117 stage = STAGE_GETRANGE;
120 /* we now compute recentcount as a difference between
121 * new and old EXISTS, hence disable RECENT check */
123 else if (strstr(buf, " RECENT"))
125 /* fixme: use strto[u]l and error checking */
126 recentcount = atoi(buf+2);
129 else if (strstr(buf, " EXPUNGE"))
131 unsigned long u; char *t;
132 /* the response "* 10 EXPUNGE" means that the currently
133 * tenth (i.e. only one) message has been deleted */
135 u = strtoul(buf+2, &t, 10);
136 if (errno /* conversion error */ || t == buf+2 /* no number found */) {
137 report(stderr, GT_("bogus EXPUNGE count in \"%s\"!"), buf);
146 /* We do expect an EXISTS response immediately
147 * after this, so this updation of recentcount is
148 * just a precaution! */
149 if ((recentcount = count - oldcount) < 0)
155 * The server may decide to make the mailbox read-only,
156 * which causes fetchmail to go into a endless loop
157 * fetching the same message over and over again.
159 * However, for check_only, we use EXAMINE which will
160 * mark the mailbox read-only as per the RFC.
162 * This checks for the condition and aborts if
163 * the mailbox is read-only.
165 * See RFC 2060 section 6.3.1 (SELECT).
166 * See RFC 2060 section 6.3.2 (EXAMINE).
168 else if (stage == STAGE_GETRANGE
169 && !check_only && strstr(buf, "[READ-ONLY]"))
180 static int imap_response(int sock, char *argbuf)
181 /* parse command response */
183 char buf[MSGBUFSIZE+1];
189 if ((ok = gen_recv(sock, buf, sizeof(buf))))
192 /* all tokens in responses are caseblind */
193 for (cp = buf; *cp; cp++)
194 if (islower((unsigned char)*cp))
195 *cp = toupper((unsigned char)*cp);
197 /* untagged responses start with "* " */
198 if (buf[0] == '*' && buf[1] == ' ') {
199 ok = imap_untagged_response(sock, buf);
200 if (ok == PS_UNTAGGED)
202 if (argbuf && stage != STAGE_IDLE && tag[0] != '\0')
204 /* if there is an unmatched response, pass it back to
205 * the calling function for further analysis. The
206 * calling function should call imap_response() again
207 * to read the remaining response */
212 else if (ok != PS_SUCCESS)
216 if (stage == STAGE_IDLE)
218 /* reduce the timeout: servers may not reset their timeout
219 * when they send some information asynchronously */
220 mytimeout = idle_timeout - (time((time_t *) NULL) - idle_start_time);
222 return(PS_IDLETIMEOUT);
225 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
238 for (cp = buf; !isspace((unsigned char)*cp); cp++)
240 while (isspace((unsigned char)*cp))
243 if (strncasecmp(cp, "OK", 2) == 0)
249 else if (strncasecmp(cp, "BAD", 3) == 0)
251 else if (strncasecmp(cp, "NO", 2) == 0)
253 if (stage == STAGE_GETAUTH)
254 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
255 else if (stage == STAGE_GETSIZES)
256 return(PS_SUCCESS); /* see comments in imap_getpartialsizes() */
265 static int imap_ok(int sock, char *argbuf)
266 /* parse command response */
270 while ((ok = imap_response(sock, argbuf)) == PS_UNTAGGED)
271 ; /* wait for the tagged response */
279 * NTLM support by Grant Edwards.
281 * Handle MS-Exchange NTLM authentication method. This is the same
282 * as the NTLM auth used by Samba for SMB related services. We just
283 * encode the packets in base64 instead of sending them out via a
286 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
289 static int do_imap_ntlm(int sock, struct query *ctl)
293 gen_send(sock, "AUTHENTICATE NTLM");
295 if ((result = ntlm_helper(sock, ctl, "IMAP")))
298 result = imap_ok (sock, NULL);
299 if (result == PS_SUCCESS)
306 static void imap_canonicalize(char *result, char *raw, size_t maxlen)
307 /* encode an IMAP password as per RFC1730's quoting conventions */
312 for (i = 0; i < strlen(raw) && i < maxlen; i++)
314 if ((raw[i] == '\\') || (raw[i] == '"'))
316 result[j++] = raw[i];
321 static void capa_probe(int sock, struct query *ctl)
322 /* set capability variables from a CAPA probe */
326 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
327 capabilities[0] = '\0';
328 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
332 /* capability checks are supposed to be caseblind */
333 for (cp = capabilities; *cp; cp++)
334 *cp = toupper((unsigned char)*cp);
336 /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
337 should expect a response in mixed-case */
338 if (strstr(capabilities, "IMAP4REV1"))
340 imap_version = IMAP4rev1;
341 if (outlevel >= O_DEBUG)
342 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
346 imap_version = IMAP4;
347 if (outlevel >= O_DEBUG)
348 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
351 else if (ok == PS_ERROR)
353 imap_version = IMAP2;
354 if (outlevel >= O_DEBUG)
355 report(stdout, GT_("Protocol identified as IMAP2 or IMAP2BIS\n"));
359 * Handle idling. We depend on coming through here on startup
360 * and after each timeout (including timeouts during idles).
365 if (strstr(capabilities, "IDLE"))
369 if (outlevel >= O_VERBOSE)
370 report(stdout, GT_("will idle after poll\n"));
373 peek_capable = (imap_version >= IMAP4);
376 static int do_authcert (int sock, const char *command, const char *name)
377 /* do authentication "external" (authentication provided by client cert) */
383 size_t len = strlen(name);
384 if ((len / 3) + ((len % 3) ? 4 : 0) < sizeof(buf))
385 to64frombits (buf, name, strlen(name));
387 return PS_AUTHFAIL; /* buffer too small. */
391 return gen_transact(sock, "%s EXTERNAL %s",command,buf);
394 static int imap_getauth(int sock, struct query *ctl, char *greeting)
395 /* apply for connection authorization */
401 * Assumption: expunges are cheap, so we want to do them
402 * after every message unless user said otherwise.
404 if (NUM_SPECIFIED(ctl->expunge))
405 expunge_period = NUM_VALUE_OUT(ctl->expunge);
409 capa_probe(sock, ctl);
412 * If either (a) we saw a PREAUTH token in the greeting, or
413 * (b) the user specified ssh preauthentication, then we're done.
415 if (preauth || ctl->server.authenticate == A_SSH)
417 preauth = FALSE; /* reset for the next session */
422 if (maybe_tls(ctl)) {
425 commonname = ctl->server.pollname;
427 commonname = ctl->server.via;
428 if (ctl->sslcommonname)
429 commonname = ctl->sslcommonname;
431 if (strstr(capabilities, "STARTTLS")
432 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
434 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
435 * protocol that will work with STARTTLS. Don't need to worry
436 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
438 if (gen_transact(sock, "STARTTLS") == PS_SUCCESS
439 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
440 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
441 ctl->server.pollname, &ctl->remotename) != -1)
444 * RFC 2595 says this:
446 * "Once TLS has been started, the client MUST discard cached
447 * information about server capabilities and SHOULD re-issue the
448 * CAPABILITY command. This is necessary to protect against
449 * man-in-the-middle attacks which alter the capabilities list prior
450 * to STARTTLS. The server MAY advertise different capabilities
453 * Now that we're confident in our TLS connection we can
454 * guarantee a secure capability re-probe.
456 capa_probe(sock, ctl);
457 if (outlevel >= O_VERBOSE)
459 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
461 } else if (must_tls(ctl)) {
462 /* Config required TLS but we couldn't guarantee it, so we must
464 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
467 if (outlevel >= O_VERBOSE) {
468 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue\n"), commonname);
470 /* We don't know whether the connection is in a working state, so
471 * test by issuing a NOOP. */
472 if (gen_transact(sock, "NOOP") != PS_SUCCESS) {
473 /* Not usable. Empty sslproto to force an unencrypted
474 * connection on the next attempt, and repoll. */
475 ctl->sslproto = xstrdup("");
478 /* Usable. Proceed with authenticating insecurely. */
482 #endif /* SSL_ENABLE */
485 * Time to authenticate the user.
486 * Try the protocol variants that don't require passwords first.
490 /* Yahoo hack - we'll just try ID if it was offered by the server,
491 * and IGNORE errors. */
493 char *tmp = strstr(capabilities, " ID");
494 if (tmp && !isalnum((unsigned char)tmp[3]) && strstr(ctl->server.via ? ctl->server.via : ctl->server.pollname, "yahoo.com")) {
495 (void)gen_transact(sock, "ID (\"guid\" \"1\")");
499 if ((ctl->server.authenticate == A_ANY
500 || ctl->server.authenticate == A_EXTERNAL)
501 && strstr(capabilities, "AUTH=EXTERNAL"))
503 ok = do_authcert(sock, "AUTHENTICATE", ctl->remotename);
506 /* SASL cancellation of authentication */
508 if (ctl->server.authenticate != A_ANY)
516 if (((ctl->server.authenticate == A_ANY && check_gss_creds("imap", ctl->server.truename) == PS_SUCCESS)
517 || ctl->server.authenticate == A_GSSAPI)
518 && strstr(capabilities, "AUTH=GSSAPI"))
520 if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
521 ctl->server.truename, ctl->remotename)))
523 if (ctl->server.authenticate != A_ANY)
532 if ((ctl->server.authenticate == A_ANY
533 || ctl->server.authenticate == A_KERBEROS_V4
534 || ctl->server.authenticate == A_KERBEROS_V5)
535 && strstr(capabilities, "AUTH=KERBEROS_V4"))
537 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
539 /* SASL cancellation of authentication */
541 if(ctl->server.authenticate != A_ANY)
547 #endif /* KERBEROS_V4 */
550 * No such luck. OK, now try the variants that mask your password
551 * in a challenge-response.
554 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
555 || ctl->server.authenticate == A_CRAM_MD5)
557 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
559 if(ctl->server.authenticate != A_ANY)
567 if ((ctl->server.authenticate == A_ANY
568 || ctl->server.authenticate == A_OTP)
569 && strstr(capabilities, "AUTH=X-OTP")) {
570 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
572 /* SASL cancellation of authentication */
574 if(ctl->server.authenticate != A_ANY)
581 if (ctl->server.authenticate == A_OTP)
584 GT_("Required OTP capability not compiled into fetchmail\n"));
586 #endif /* OPIE_ENABLE */
589 if ((ctl->server.authenticate == A_ANY
590 || ctl->server.authenticate == A_NTLM)
591 && strstr (capabilities, "AUTH=NTLM")) {
592 if ((ok = do_imap_ntlm(sock, ctl)))
594 if(ctl->server.authenticate != A_ANY)
601 if (ctl->server.authenticate == A_NTLM)
604 GT_("Required NTLM capability not compiled into fetchmail\n"));
606 #endif /* NTLM_ENABLE */
608 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
609 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
610 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
613 GT_("Required LOGIN capability not supported by server\n"));
615 #endif /* __UNUSED__ */
618 * We're stuck with sending the password en clair.
619 * The reason for this odd-looking logic is that some
620 * servers return LOGINDISABLED even though login
621 * actually works. So arrange things in such a way that
622 * setting auth passwd makes it ignore this capability.
624 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
625 || ctl->server.authenticate == A_PASSWORD)
627 /* these sizes guarantee no buffer overflow */
628 char *remotename, *password;
630 rnl = 2 * strlen(ctl->remotename) + 1;
631 pwl = 2 * strlen(ctl->password) + 1;
632 remotename = (char *)xmalloc(rnl);
633 password = (char *)xmalloc(pwl);
635 imap_canonicalize(remotename, ctl->remotename, rnl);
636 imap_canonicalize(password, ctl->password, pwl);
638 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
639 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
640 memset(shroud, 0x55, sizeof(shroud));
642 memset(password, 0x55, strlen(password));
647 if(ctl->server.authenticate != A_ANY)
657 static int internal_expunge(int sock)
658 /* ship an expunge, resetting associated counters */
662 actual_deletions = 0;
664 if ((ok = gen_transact(sock, "EXPUNGE")))
667 /* if there is a mismatch between the number of mails which should
668 * have been expunged and the number of mails actually expunged,
669 * another email client may be deleting mails. Quit here,
670 * otherwise fetchmail gets out-of-sync with the imap server,
671 * reports the wrong size to the SMTP server on MAIL FROM: and
672 * triggers a "message ... was not the expected length" error on
673 * every subsequent mail */
674 if (deletions > 0 && deletions != actual_deletions)
677 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
678 actual_deletions, deletions);
683 expunged += deletions;
686 #ifdef IMAP_UID /* not used */
688 #endif /* IMAP_UID */
693 static int imap_idle(int sock)
694 /* start an RFC2177 IDLE, or fake one if unsupported */
698 saved_timeout = mytimeout;
701 /* special timeout to terminate the IDLE and re-issue it
702 * at least every 28 minutes:
703 * (the server may have an inactivity timeout) */
704 mytimeout = idle_timeout = 1680; /* 28 min */
705 time(&idle_start_time);
707 /* enter IDLE mode */
708 ok = gen_transact(sock, "IDLE");
710 if (ok == PS_IDLETIMEOUT) {
711 /* send "DONE" continuation */
712 SockWrite(sock, "DONE\r\n", 6);
713 if (outlevel >= O_MONITOR)
714 report(stdout, "IMAP> DONE\n");
715 /* reset stage and timeout here: we are not idling any more */
716 mytimeout = saved_timeout;
717 stage = STAGE_GETRANGE;
718 /* get OK IDLE message */
719 ok = imap_ok(sock, NULL);
721 } else { /* no idle support, fake it */
722 /* Note: stage and timeout have not been changed here as NOOP
724 ok = gen_transact(sock, "NOOP");
726 /* no error, but no new mail either */
727 if (ok == PS_SUCCESS && recentcount == 0)
729 /* There are some servers who do send new mail
730 * notification out of the blue. This is in compliance
731 * with RFC 2060 section 5.3. Wait for that with a low
733 mytimeout = idle_timeout = 28;
734 time(&idle_start_time);
736 /* We are waiting for notification; no tag needed */
738 /* wait (briefly) for an unsolicited status update */
739 ok = imap_ok(sock, NULL);
740 if (ok == PS_IDLETIMEOUT) {
741 /* no notification came; ok */
747 /* restore normal timeout value */
749 mytimeout = saved_timeout;
750 stage = STAGE_GETRANGE;
755 /* maximum number of numbers we can process in "SEARCH" response */
756 # define IMAP_SEARCH_MAX 1000
758 static int imap_search(int sock, struct query *ctl, int count)
759 /* search for unseen messages */
762 char buf[MSGBUFSIZE+1], *cp;
764 /* Don't count deleted messages. Enabled only for IMAP4 servers or
765 * higher and only when keeping mails. This flag will have an
766 * effect only when user has marked some unread mails for deletion
767 * using another e-mail client. */
768 flag skipdeleted = (imap_version >= IMAP4) && ctl->keep;
769 const char *undeleted;
771 /* Skip range search if there are less than or equal to
772 * IMAP_SEARCH_MAX mails. */
773 flag skiprangesearch = (count <= IMAP_SEARCH_MAX);
775 /* startcount is higher than count so that if there are no
776 * unseen messages, imap_getsizes() will not need to do
778 startcount = count + 1;
780 for (first = 1, last = IMAP_SEARCH_MAX; first <= count; first += IMAP_SEARCH_MAX, last += IMAP_SEARCH_MAX)
786 undeleted = (skipdeleted ? " UNDELETED" : "");
788 gen_send(sock, "SEARCH UNSEEN%s", undeleted);
789 else if (last == first)
790 gen_send(sock, "SEARCH %d UNSEEN%s", last, undeleted);
792 gen_send(sock, "SEARCH %d:%d UNSEEN%s", first, last, undeleted);
793 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
795 if ((cp = strstr(buf, "* SEARCH")))
799 cp += 8; /* skip "* SEARCH" */
800 while (*cp && unseen < count)
802 /* skip whitespace */
803 while (*cp && isspace((unsigned char)*cp))
810 um = strtoul(cp,&ep,10);
811 if (errno == 0 && ep > cp
812 && um <= INT_MAX && um <= (unsigned)count)
814 unseen_messages[unseen++] = um;
815 if (outlevel >= O_DEBUG)
816 report(stdout, GT_("%lu is unseen\n"), um);
825 /* if there is a protocol error on the first loop, try a
826 * different search command */
827 if (ok == PS_ERROR && first == 1)
831 /* retry with "SEARCH 1:1000 UNSEEN" */
835 if (!skiprangesearch)
837 /* retry with "SEARCH UNSEEN" */
838 skiprangesearch = TRUE;
841 /* try with "FETCH 1:n FLAGS" */
844 if (ok != PS_SUCCESS)
846 /* loop back only when searching in range */
854 gen_send(sock, "FETCH %d FLAGS", count);
856 gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
857 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
862 /* expected response format:
863 * IMAP< * 1 FETCH (FLAGS (\Seen))
864 * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
865 * IMAP< * 3 FETCH (FLAGS ())
866 * IMAP< * 4 FETCH (FLAGS (\Recent))
867 * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
870 && sscanf(buf, "* %u %n", &num, &consumed) == 1
871 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
872 && isspace((unsigned char)buf[consumed+5])
873 && num >= 1 && num <= (unsigned)count
874 && strstr(buf, "FLAGS ")
875 && !strstr(buf, "\\SEEN")
876 && !strstr(buf, "\\DELETED"))
878 unseen_messages[unseen++] = num;
879 if (outlevel >= O_DEBUG)
880 report(stdout, GT_("%u is unseen\n"), num);
881 if (startcount > num)
888 static int imap_getrange(int sock,
891 int *countp, int *newp, int *bytes)
892 /* get range of messages to be fetched */
896 /* find out how many messages are waiting */
901 /* deleted mails have already been expunged by
902 * end_mailbox_poll().
904 * recentcount is already set here by the last imap command which
905 * returned EXISTS on detecting new mail. if recentcount is 0, wait
908 * this is a while loop because imap_idle() might return on other
909 * mailbox changes also */
910 while (recentcount == 0 && do_idle) {
912 ok = imap_idle(sock);
915 report(stderr, GT_("re-poll failed\n"));
919 /* if recentcount is 0, return no mail */
920 if (recentcount == 0)
922 if (outlevel >= O_DEBUG)
923 report(stdout, ngettext("%d message waiting after re-poll\n",
924 "%d messages waiting after re-poll\n",
929 oldcount = count = 0;
930 ok = gen_transact(sock,
931 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
932 folder ? folder : "INBOX");
933 /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
934 * which we can safely use in fetchall keep only */
935 if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
940 report(stderr, GT_("mailbox selection failed\n"));
943 else if (outlevel >= O_DEBUG)
944 report(stdout, ngettext("%d message waiting after first poll\n",
945 "%d messages waiting after first poll\n",
949 * We should have an expunge here to
950 * a) avoid fetching deleted mails during 'fetchall'
951 * b) getting a wrong count of mails during 'no fetchall'
953 if (!check_only && !ctl->keep && count > 0)
955 ok = internal_expunge(sock);
958 report(stderr, GT_("expunge failed\n"));
961 if (outlevel >= O_DEBUG)
962 report(stdout, ngettext("%d message waiting after expunge\n",
963 "%d messages waiting after expunge\n",
967 if (count == 0 && do_idle)
969 /* no messages? then we may need to idle until we get some */
971 ok = imap_idle(sock);
974 report(stderr, GT_("re-poll failed\n"));
978 if (outlevel >= O_DEBUG)
979 report(stdout, ngettext("%d message waiting after re-poll\n",
980 "%d messages waiting after re-poll\n",
985 *countp = oldcount = count;
989 /* OK, now get a count of unseen messages and their indices */
990 if (!ctl->fetchall && count > 0)
993 free(unseen_messages);
994 unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
995 memset(unseen_messages, 0, count * sizeof(unsigned int));
998 ok = imap_search(sock, ctl, count);
1001 report(stderr, GT_("search for unseen messages failed\n"));
1005 if (outlevel >= O_DEBUG && unseen > 0)
1006 report(stdout, GT_("%u is first unseen\n"), startcount);
1017 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
1018 /* capture the sizes of messages #first-#last */
1020 char buf [MSGBUFSIZE+1];
1024 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1025 * won't accept 1:1 as valid set syntax. Some implementors
1026 * should be taken out and shot for excessive anality.
1028 * Microsoft Exchange (brain-dead piece of crap that it is)
1029 * sometimes gets its knickers in a knot about bodiless messages.
1030 * You may see responses like this:
1032 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1033 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1034 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1035 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1036 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1037 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1038 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1039 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1040 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1041 * fetchmail: IMAP< A0004 NO The requested item could not be found.
1043 * This means message 1 has only headers. For kicks and grins
1044 * you can telnet in and look:
1046 * A003 NO The requested item could not be found.
1047 * A004 fetch 1 rfc822.header
1048 * A004 NO The requested item could not be found.
1050 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1051 * A006 OK FETCH completed.
1053 * To get around this, we treat the final NO as success and count
1054 * on the fact that the sizes array has been preinitialized with a
1055 * known-bad size value.
1058 /* expunges change the fetch numbers */
1063 gen_send(sock, "FETCH %d RFC822.SIZE", last);
1064 else if (last > first)
1065 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1066 else /* no unseen messages! */
1068 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1075 /* expected response formats:
1076 * IMAP> A0005 FETCH 1 RFC822.SIZE
1077 * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1078 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1080 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1081 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1082 && isspace((unsigned char)buf[consumed + 5])
1083 && (ptr = strstr(buf, "RFC822.SIZE "))
1084 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1086 if (num >= first && num <= last)
1087 sizes[num - first] = size;
1090 GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1096 static int imap_getsizes(int sock, int count, int *sizes)
1097 /* capture the sizes of all messages */
1099 return imap_getpartialsizes(sock, 1, count, sizes);
1102 static int imap_is_old(int sock, struct query *ctl, int number)
1103 /* is the given message old? */
1111 * Expunges change the fetch numbers, but unseen_messages contains
1112 * indices from before any expungees were done. So neither the
1113 * argument nor the values in message_sequence need to be decremented.
1117 for (i = 0; i < unseen; i++)
1118 if (unseen_messages[i] == (unsigned)number)
1128 static char *skip_token(char *ptr)
1130 while(isspace((unsigned char)*ptr)) ptr++;
1131 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1132 while(isspace((unsigned char)*ptr)) ptr++;
1137 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1138 /* request headers of nth message */
1140 char buf [MSGBUFSIZE+1];
1146 /* expunges change the fetch numbers */
1150 * This is blessed by RFC1176, RFC1730, RFC2060.
1151 * According to the RFCs, it should *not* set the \Seen flag.
1153 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1155 /* looking for FETCH response */
1156 if ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1159 /* expected response formats:
1160 * IMAP> A0006 FETCH 1 RFC822.HEADER
1161 * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1162 * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1163 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1165 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1166 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1167 && isspace((unsigned char)buf[5+consumed])
1169 && (ptr = strstr(buf, "RFC822.HEADER"))
1170 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1171 && ptr[consumed-1] == '}')
1176 /* wait for a tagged response */
1179 /* try to recover for some responses */
1180 if (!strncmp(buf, "* NO", 4) ||
1181 !strncmp(buf, "* BAD", 5))
1183 return(PS_TRANSIENT);
1186 /* a response which does not match any of the above */
1187 if (outlevel > O_SILENT)
1188 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1191 else if (ok == PS_SUCCESS)
1193 /* an unexpected tagged response */
1194 if (outlevel > O_SILENT)
1195 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1201 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1202 /* request body of nth message */
1204 char buf [MSGBUFSIZE+1], *cp;
1208 /* expunges change the fetch numbers */
1212 * If we're using IMAP4, we can fetch the message without setting its
1213 * seen flag. This is good! It means that if the protocol exchange
1214 * craps out during the message, it will still be marked `unseen' on
1217 * According to RFC2060, and Mark Crispin the IMAP maintainer,
1218 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
1219 * equivalent". However, we know of at least one server that
1220 * treats them differently in the presence of MIME attachments;
1221 * the latter form downloads the attachment, the former does not.
1222 * The server is InterChange, and the fool who implemented this
1223 * misfeature ought to be strung up by his thumbs.
1225 * When I tried working around this by disabling use of the 4rev1 form,
1226 * I found that doing this breaks operation with M$ Exchange.
1227 * Annoyingly enough, Exchange's refusal to cope is technically legal
1228 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
1229 * standards, to find a way to make standards compliance irritating....
1231 switch (imap_version)
1233 case IMAP4rev1: /* RFC 2060 */
1234 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1237 case IMAP4: /* RFC 1730 */
1238 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1241 default: /* RFC 1176 */
1242 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1246 /* looking for FETCH response */
1250 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1253 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1258 /* Understand "NIL" as length => no body present
1259 * (MS Exchange, BerliOS Bug #11980) */
1260 if (strstr(buf+10, "NIL)")) {
1265 /* Understand the empty string. Seen on Yahoo. */
1266 /* XXX FIXME: we should be able to handle strings here. */
1267 if (strstr(buf+10, "\"\")")) {
1273 * Try to extract a length from the FETCH response. RFC2060 requires
1274 * it to be present, but at least one IMAP server (Novell GroupWise)
1275 * botches this. The overflow check is needed because of a broken
1276 * server called dbmail that returns huge garbage lengths.
1278 if ((cp = strchr(buf, '{'))) {
1282 l = strtol(cp, &t, 10);
1283 if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1284 || l < 0 || l > INT_MAX /* range check */) {
1290 *lenp = -1; /* missing length part in FETCH reponse */
1296 static int imap_trail(int sock, struct query *ctl, const char *tag)
1297 /* discard tail of FETCH response after reading message text */
1299 /* expunges change the fetch numbers */
1300 /* number -= expunged; */
1305 return imap_ok(sock, NULL);
1308 static int imap_delete(int sock, struct query *ctl, int number)
1309 /* set delete flag for given message */
1314 /* expunges change the fetch numbers */
1318 * Use SILENT if possible as a minor throughput optimization.
1319 * Note: this has been dropped from IMAP4rev1.
1321 * We set Seen because there are some IMAP servers (notably HP
1322 * OpenMail) that do message-receipt DSNs, but only when the seen
1323 * bit is set. This is the appropriate time -- we get here right
1324 * after the local SMTP response that says delivery was
1327 if ((ok = gen_transact(sock,
1328 imap_version == IMAP4
1329 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1330 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1337 * We do an expunge after expunge_period messages, rather than
1338 * just before quit, so that a line hit during a long session
1339 * won't result in lots of messages being fetched again during
1342 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1344 if ((ok = internal_expunge(sock)))
1351 static int imap_mark_seen(int sock, struct query *ctl, int number)
1352 /* mark the given message as seen */
1356 /* expunges change the message numbers */
1359 return(gen_transact(sock,
1360 imap_version == IMAP4
1361 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1362 : "STORE %d +FLAGS (\\Seen)",
1366 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1367 /* cleanup mailbox before we idle or switch to another one */
1371 internal_expunge(sock);
1375 static int imap_logout(int sock, struct query *ctl)
1376 /* send logout command */
1379 /* if any un-expunged deletions remain, ship an expunge now */
1381 internal_expunge(sock);
1384 /* Memory clean-up */
1385 if (unseen_messages)
1386 free(unseen_messages);
1387 #endif /* USE_SEARCH */
1389 return(gen_transact(sock, "LOGOUT"));
1392 static const struct method imap =
1394 "IMAP", /* Internet Message Access Protocol */
1395 "imap", /* service (plain and TLS) */
1396 "imaps", /* service (SSL) */
1397 TRUE, /* this is a tagged protocol */
1398 FALSE, /* no message delimiter */
1399 imap_ok, /* parse command response */
1400 imap_getauth, /* get authorization */
1401 imap_getrange, /* query range of messages */
1402 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1403 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1404 imap_is_old, /* no UID check */
1405 imap_fetch_headers, /* request given message headers */
1406 imap_fetch_body, /* request given message body */
1407 imap_trail, /* eat message trailer */
1408 imap_delete, /* delete the message */
1409 imap_mark_seen, /* how to mark a message as seen */
1410 imap_end_mailbox_poll, /* end-of-mailbox processing */
1411 imap_logout, /* expunge and exit */
1412 TRUE, /* yes, we can re-poll */
1415 int doIMAP(struct query *ctl)
1416 /* retrieve messages using IMAP Version 2bis or Version 4 */
1418 return(do_protocol(ctl, &imap));
1421 /* imap.c ends here */