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 * No such luck. OK, now try the variants that mask your password
533 * in a challenge-response.
536 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
537 || ctl->server.authenticate == A_CRAM_MD5)
539 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
541 if(ctl->server.authenticate != A_ANY)
549 if ((ctl->server.authenticate == A_ANY
550 || ctl->server.authenticate == A_OTP)
551 && strstr(capabilities, "AUTH=X-OTP")) {
552 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
554 /* SASL cancellation of authentication */
556 if(ctl->server.authenticate != A_ANY)
563 if (ctl->server.authenticate == A_OTP)
566 GT_("Required OTP capability not compiled into fetchmail\n"));
568 #endif /* OPIE_ENABLE */
571 if ((ctl->server.authenticate == A_ANY
572 || ctl->server.authenticate == A_NTLM)
573 && strstr (capabilities, "AUTH=NTLM")) {
574 if ((ok = do_imap_ntlm(sock, ctl)))
576 if(ctl->server.authenticate != A_ANY)
583 if (ctl->server.authenticate == A_NTLM)
586 GT_("Required NTLM capability not compiled into fetchmail\n"));
588 #endif /* NTLM_ENABLE */
591 * We're stuck with sending the password en clair.
592 * The reason for this odd-looking logic is that some
593 * servers return LOGINDISABLED even though login
594 * actually works. So arrange things in such a way that
595 * setting auth passwd makes it ignore this capability.
597 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
598 || ctl->server.authenticate == A_PASSWORD)
600 /* these sizes guarantee no buffer overflow */
601 char *remotename, *password;
603 rnl = 2 * strlen(ctl->remotename) + 1;
604 pwl = 2 * strlen(ctl->password) + 1;
605 remotename = (char *)xmalloc(rnl);
606 password = (char *)xmalloc(pwl);
608 imap_canonicalize(remotename, ctl->remotename, rnl);
609 imap_canonicalize(password, ctl->password, pwl);
611 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
612 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
613 memset(shroud, 0x55, sizeof(shroud));
615 memset(password, 0x55, strlen(password));
620 if(ctl->server.authenticate != A_ANY)
630 static int internal_expunge(int sock)
631 /* ship an expunge, resetting associated counters */
635 actual_deletions = 0;
637 if ((ok = gen_transact(sock, "EXPUNGE")))
640 /* if there is a mismatch between the number of mails which should
641 * have been expunged and the number of mails actually expunged,
642 * another email client may be deleting mails. Quit here,
643 * otherwise fetchmail gets out-of-sync with the imap server,
644 * reports the wrong size to the SMTP server on MAIL FROM: and
645 * triggers a "message ... was not the expected length" error on
646 * every subsequent mail */
647 if (deletions > 0 && deletions != actual_deletions)
650 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
651 actual_deletions, deletions);
656 expunged += deletions;
659 #ifdef IMAP_UID /* not used */
661 #endif /* IMAP_UID */
666 static int imap_idle(int sock)
667 /* start an RFC2177 IDLE, or fake one if unsupported */
671 saved_timeout = mytimeout;
674 /* special timeout to terminate the IDLE and re-issue it
675 * at least every 28 minutes:
676 * (the server may have an inactivity timeout) */
677 mytimeout = idle_timeout = 1680; /* 28 min */
678 time(&idle_start_time);
680 /* enter IDLE mode */
681 ok = gen_transact(sock, "IDLE");
683 if (ok == PS_IDLETIMEOUT) {
684 /* send "DONE" continuation */
685 SockWrite(sock, "DONE\r\n", 6);
686 if (outlevel >= O_MONITOR)
687 report(stdout, "IMAP> DONE\n");
688 /* reset stage and timeout here: we are not idling any more */
689 mytimeout = saved_timeout;
690 stage = STAGE_GETRANGE;
691 /* get OK IDLE message */
692 ok = imap_ok(sock, NULL);
694 } else { /* no idle support, fake it */
695 /* Note: stage and timeout have not been changed here as NOOP
697 ok = gen_transact(sock, "NOOP");
699 /* no error, but no new mail either */
700 if (ok == PS_SUCCESS && recentcount == 0)
702 /* There are some servers who do send new mail
703 * notification out of the blue. This is in compliance
704 * with RFC 2060 section 5.3. Wait for that with a low
706 mytimeout = idle_timeout = 28;
707 time(&idle_start_time);
709 /* We are waiting for notification; no tag needed */
711 /* wait (briefly) for an unsolicited status update */
712 ok = imap_ok(sock, NULL);
713 if (ok == PS_IDLETIMEOUT) {
714 /* no notification came; ok */
720 /* restore normal timeout value */
722 mytimeout = saved_timeout;
723 stage = STAGE_GETRANGE;
728 /* maximum number of numbers we can process in "SEARCH" response */
729 # define IMAP_SEARCH_MAX 1000
731 static int imap_search(int sock, struct query *ctl, int count)
732 /* search for unseen messages */
735 char buf[MSGBUFSIZE+1], *cp;
737 /* Don't count deleted messages. Enabled only for IMAP4 servers or
738 * higher and only when keeping mails. This flag will have an
739 * effect only when user has marked some unread mails for deletion
740 * using another e-mail client. */
741 flag skipdeleted = (imap_version >= IMAP4) && ctl->keep;
742 const char *undeleted;
744 /* Skip range search if there are less than or equal to
745 * IMAP_SEARCH_MAX mails. */
746 flag skiprangesearch = (count <= IMAP_SEARCH_MAX);
748 /* startcount is higher than count so that if there are no
749 * unseen messages, imap_getsizes() will not need to do
751 startcount = count + 1;
753 for (first = 1, last = IMAP_SEARCH_MAX; first <= count; first += IMAP_SEARCH_MAX, last += IMAP_SEARCH_MAX)
759 undeleted = (skipdeleted ? " UNDELETED" : "");
761 gen_send(sock, "SEARCH UNSEEN%s", undeleted);
762 else if (last == first)
763 gen_send(sock, "SEARCH %d UNSEEN%s", last, undeleted);
765 gen_send(sock, "SEARCH %d:%d UNSEEN%s", first, last, undeleted);
766 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
768 if ((cp = strstr(buf, "* SEARCH")))
772 cp += 8; /* skip "* SEARCH" */
773 while (*cp && unseen < count)
775 /* skip whitespace */
776 while (*cp && isspace((unsigned char)*cp))
783 um = strtoul(cp,&ep,10);
784 if (errno == 0 && ep > cp
785 && um <= INT_MAX && um <= (unsigned)count)
787 unseen_messages[unseen++] = um;
788 if (outlevel >= O_DEBUG)
789 report(stdout, GT_("%lu is unseen\n"), um);
798 /* if there is a protocol error on the first loop, try a
799 * different search command */
800 if (ok == PS_ERROR && first == 1)
804 /* retry with "SEARCH 1:1000 UNSEEN" */
808 if (!skiprangesearch)
810 /* retry with "SEARCH UNSEEN" */
811 skiprangesearch = TRUE;
814 /* try with "FETCH 1:n FLAGS" */
817 if (ok != PS_SUCCESS)
819 /* loop back only when searching in range */
827 gen_send(sock, "FETCH %d FLAGS", count);
829 gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
830 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
835 /* expected response format:
836 * IMAP< * 1 FETCH (FLAGS (\Seen))
837 * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
838 * IMAP< * 3 FETCH (FLAGS ())
839 * IMAP< * 4 FETCH (FLAGS (\Recent))
840 * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
843 && sscanf(buf, "* %u %n", &num, &consumed) == 1
844 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
845 && isspace((unsigned char)buf[consumed+5])
846 && num >= 1 && num <= (unsigned)count
847 && strstr(buf, "FLAGS ")
848 && !strstr(buf, "\\SEEN")
849 && !strstr(buf, "\\DELETED"))
851 unseen_messages[unseen++] = num;
852 if (outlevel >= O_DEBUG)
853 report(stdout, GT_("%u is unseen\n"), num);
854 if (startcount > num)
861 static int imap_getrange(int sock,
864 int *countp, int *newp, int *bytes)
865 /* get range of messages to be fetched */
869 /* find out how many messages are waiting */
874 /* deleted mails have already been expunged by
875 * end_mailbox_poll().
877 * recentcount is already set here by the last imap command which
878 * returned EXISTS on detecting new mail. if recentcount is 0, wait
881 * this is a while loop because imap_idle() might return on other
882 * mailbox changes also */
883 while (recentcount == 0 && do_idle) {
885 ok = imap_idle(sock);
888 report(stderr, GT_("re-poll failed\n"));
892 /* if recentcount is 0, return no mail */
893 if (recentcount == 0)
895 if (outlevel >= O_DEBUG)
896 report(stdout, ngettext("%d message waiting after re-poll\n",
897 "%d messages waiting after re-poll\n",
902 oldcount = count = 0;
903 ok = gen_transact(sock,
904 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
905 folder ? folder : "INBOX");
906 /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
907 * which we can safely use in fetchall keep only */
908 if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
913 report(stderr, GT_("mailbox selection failed\n"));
916 else if (outlevel >= O_DEBUG)
917 report(stdout, ngettext("%d message waiting after first poll\n",
918 "%d messages waiting after first poll\n",
922 * We should have an expunge here to
923 * a) avoid fetching deleted mails during 'fetchall'
924 * b) getting a wrong count of mails during 'no fetchall'
926 if (!check_only && !ctl->keep && count > 0)
928 ok = internal_expunge(sock);
931 report(stderr, GT_("expunge failed\n"));
934 if (outlevel >= O_DEBUG)
935 report(stdout, ngettext("%d message waiting after expunge\n",
936 "%d messages waiting after expunge\n",
940 if (count == 0 && do_idle)
942 /* no messages? then we may need to idle until we get some */
944 ok = imap_idle(sock);
947 report(stderr, GT_("re-poll failed\n"));
951 if (outlevel >= O_DEBUG)
952 report(stdout, ngettext("%d message waiting after re-poll\n",
953 "%d messages waiting after re-poll\n",
958 *countp = oldcount = count;
962 /* OK, now get a count of unseen messages and their indices */
963 if (!ctl->fetchall && count > 0)
966 free(unseen_messages);
967 unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
968 memset(unseen_messages, 0, count * sizeof(unsigned int));
971 ok = imap_search(sock, ctl, count);
974 report(stderr, GT_("search for unseen messages failed\n"));
978 if (outlevel >= O_DEBUG && unseen > 0)
979 report(stdout, GT_("%u is first unseen\n"), startcount);
990 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
991 /* capture the sizes of messages #first-#last */
993 char buf [MSGBUFSIZE+1];
997 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
998 * won't accept 1:1 as valid set syntax. Some implementors
999 * should be taken out and shot for excessive anality.
1001 * Microsoft Exchange (brain-dead piece of crap that it is)
1002 * sometimes gets its knickers in a knot about bodiless messages.
1003 * You may see responses like this:
1005 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1006 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1007 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1008 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1009 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1010 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1011 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1012 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1013 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1014 * fetchmail: IMAP< A0004 NO The requested item could not be found.
1016 * This means message 1 has only headers. For kicks and grins
1017 * you can telnet in and look:
1019 * A003 NO The requested item could not be found.
1020 * A004 fetch 1 rfc822.header
1021 * A004 NO The requested item could not be found.
1023 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1024 * A006 OK FETCH completed.
1026 * To get around this, we treat the final NO as success and count
1027 * on the fact that the sizes array has been preinitialized with a
1028 * known-bad size value.
1031 /* expunges change the fetch numbers */
1036 gen_send(sock, "FETCH %d RFC822.SIZE", last);
1037 else if (last > first)
1038 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1039 else /* no unseen messages! */
1041 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1048 /* expected response formats:
1049 * IMAP> A0005 FETCH 1 RFC822.SIZE
1050 * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1051 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1053 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1054 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1055 && isspace((unsigned char)buf[consumed + 5])
1056 && (ptr = strstr(buf, "RFC822.SIZE "))
1057 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1059 if (num >= first && num <= last)
1060 sizes[num - first] = size;
1063 GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1069 static int imap_getsizes(int sock, int count, int *sizes)
1070 /* capture the sizes of all messages */
1072 return imap_getpartialsizes(sock, 1, count, sizes);
1075 static int imap_is_old(int sock, struct query *ctl, int number)
1076 /* is the given message old? */
1084 * Expunges change the fetch numbers, but unseen_messages contains
1085 * indices from before any expungees were done. So neither the
1086 * argument nor the values in message_sequence need to be decremented.
1090 for (i = 0; i < unseen; i++)
1091 if (unseen_messages[i] == (unsigned)number)
1101 static char *skip_token(char *ptr)
1103 while(isspace((unsigned char)*ptr)) ptr++;
1104 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1105 while(isspace((unsigned char)*ptr)) ptr++;
1110 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1111 /* request headers of nth message */
1113 char buf [MSGBUFSIZE+1];
1119 /* expunges change the fetch numbers */
1123 * This is blessed by RFC1176, RFC1730, RFC2060.
1124 * According to the RFCs, it should *not* set the \Seen flag.
1126 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1128 /* looking for FETCH response */
1129 if ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1132 /* expected response formats:
1133 * IMAP> A0006 FETCH 1 RFC822.HEADER
1134 * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1135 * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1136 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1138 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1139 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1140 && isspace((unsigned char)buf[5+consumed])
1142 && (ptr = strstr(buf, "RFC822.HEADER"))
1143 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1144 && ptr[consumed-1] == '}')
1149 /* wait for a tagged response */
1152 /* try to recover for some responses */
1153 if (!strncmp(buf, "* NO", 4) ||
1154 !strncmp(buf, "* BAD", 5))
1156 return(PS_TRANSIENT);
1159 /* a response which does not match any of the above */
1160 if (outlevel > O_SILENT)
1161 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1164 else if (ok == PS_SUCCESS)
1166 /* an unexpected tagged response */
1167 if (outlevel > O_SILENT)
1168 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1174 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1175 /* request body of nth message */
1177 char buf [MSGBUFSIZE+1], *cp;
1181 /* expunges change the fetch numbers */
1185 * If we're using IMAP4, we can fetch the message without setting its
1186 * seen flag. This is good! It means that if the protocol exchange
1187 * craps out during the message, it will still be marked `unseen' on
1190 * According to RFC2060, and Mark Crispin the IMAP maintainer,
1191 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
1192 * equivalent". However, we know of at least one server that
1193 * treats them differently in the presence of MIME attachments;
1194 * the latter form downloads the attachment, the former does not.
1195 * The server is InterChange, and the fool who implemented this
1196 * misfeature ought to be strung up by his thumbs.
1198 * When I tried working around this by disabling use of the 4rev1 form,
1199 * I found that doing this breaks operation with M$ Exchange.
1200 * Annoyingly enough, Exchange's refusal to cope is technically legal
1201 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
1202 * standards, to find a way to make standards compliance irritating....
1204 switch (imap_version)
1206 case IMAP4rev1: /* RFC 2060 */
1207 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1210 case IMAP4: /* RFC 1730 */
1211 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1214 default: /* RFC 1176 */
1215 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1219 /* looking for FETCH response */
1223 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1226 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1231 /* Understand "NIL" as length => no body present
1232 * (MS Exchange, BerliOS Bug #11980) */
1233 if (strstr(buf+10, "NIL)")) {
1238 /* Understand the empty string. Seen on Yahoo. */
1239 /* XXX FIXME: we should be able to handle strings here. */
1240 if (strstr(buf+10, "\"\")")) {
1246 * Try to extract a length from the FETCH response. RFC2060 requires
1247 * it to be present, but at least one IMAP server (Novell GroupWise)
1248 * botches this. The overflow check is needed because of a broken
1249 * server called dbmail that returns huge garbage lengths.
1251 if ((cp = strchr(buf, '{'))) {
1255 l = strtol(cp, &t, 10);
1256 if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1257 || l < 0 || l > INT_MAX /* range check */) {
1263 *lenp = -1; /* missing length part in FETCH reponse */
1269 static int imap_trail(int sock, struct query *ctl, const char *tag)
1270 /* discard tail of FETCH response after reading message text */
1272 /* expunges change the fetch numbers */
1273 /* number -= expunged; */
1278 return imap_ok(sock, NULL);
1281 static int imap_delete(int sock, struct query *ctl, int number)
1282 /* set delete flag for given message */
1287 /* expunges change the fetch numbers */
1291 * Use SILENT if possible as a minor throughput optimization.
1292 * Note: this has been dropped from IMAP4rev1.
1294 * We set Seen because there are some IMAP servers (notably HP
1295 * OpenMail) that do message-receipt DSNs, but only when the seen
1296 * bit is set. This is the appropriate time -- we get here right
1297 * after the local SMTP response that says delivery was
1300 if ((ok = gen_transact(sock,
1301 imap_version == IMAP4
1302 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1303 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1310 * We do an expunge after expunge_period messages, rather than
1311 * just before quit, so that a line hit during a long session
1312 * won't result in lots of messages being fetched again during
1315 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1317 if ((ok = internal_expunge(sock)))
1324 static int imap_mark_seen(int sock, struct query *ctl, int number)
1325 /* mark the given message as seen */
1329 /* expunges change the message numbers */
1332 return(gen_transact(sock,
1333 imap_version == IMAP4
1334 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1335 : "STORE %d +FLAGS (\\Seen)",
1339 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1340 /* cleanup mailbox before we idle or switch to another one */
1344 internal_expunge(sock);
1348 static int imap_logout(int sock, struct query *ctl)
1349 /* send logout command */
1352 /* if any un-expunged deletions remain, ship an expunge now */
1354 internal_expunge(sock);
1357 /* Memory clean-up */
1358 if (unseen_messages)
1359 free(unseen_messages);
1360 #endif /* USE_SEARCH */
1362 return(gen_transact(sock, "LOGOUT"));
1365 static const struct method imap =
1367 "IMAP", /* Internet Message Access Protocol */
1368 "imap", /* service (plain and TLS) */
1369 "imaps", /* service (SSL) */
1370 TRUE, /* this is a tagged protocol */
1371 FALSE, /* no message delimiter */
1372 imap_ok, /* parse command response */
1373 imap_getauth, /* get authorization */
1374 imap_getrange, /* query range of messages */
1375 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1376 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1377 imap_is_old, /* no UID check */
1378 imap_fetch_headers, /* request given message headers */
1379 imap_fetch_body, /* request given message body */
1380 imap_trail, /* eat message trailer */
1381 imap_delete, /* delete the message */
1382 imap_mark_seen, /* how to mark a message as seen */
1383 imap_end_mailbox_poll, /* end-of-mailbox processing */
1384 imap_logout, /* expunge and exit */
1385 TRUE, /* yes, we can re-poll */
1388 int doIMAP(struct query *ctl)
1389 /* retrieve messages using IMAP Version 2bis or Version 4 */
1391 return(do_protocol(ctl, &imap));
1394 /* imap.c ends here */