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 IMAP4 0 /* IMAP4 rev 0, RFC1730 */
23 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
25 /* global variables: please reinitialize them explicitly for proper
26 * working in daemon mode */
28 /* TODO: session variables to be initialized before server greeting */
29 static int preauth = FALSE;
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;
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;
43 /* for "IMAP> EXPUNGE" */
44 static int actual_deletions = 0;
46 /* for "IMAP> IDLE" */
47 static int saved_timeout = 0, idle_timeout = 0;
48 static time_t idle_start_time = 0;
50 static int imap_untagged_response(int sock, const char *buf)
51 /* interpret untagged status responses */
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))
58 strlcpy(capabilities, buf + 12, sizeof(capabilities));
60 else if (stage == STAGE_GETAUTH
61 && !strncmp(buf, "* PREAUTH", 9))
65 else if (stage != STAGE_LOGOUT
66 && !strncmp(buf, "* BYE", 5))
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);
73 else if (strstr(buf, " EXISTS"))
75 char *t; unsigned long u;
77 u = strtoul(buf+2, &t, 10);
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.
85 if (errno /* strtoul failed */
86 || t == buf+2 /* no valid data */
87 || u > (unsigned long)(INT_MAX/sizeof(int)) /* too large */)
89 report(stderr, GT_("bogus message count in \"%s\"!"), buf);
92 count = u; /* safe as long as count <= INT_MAX - checked above */
94 if ((recentcount = count - oldcount) < 0)
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.
104 if (stage == STAGE_IDLE)
106 /* If IDLE isn't supported, we were only sending NOOPs anyway. */
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");
115 mytimeout = saved_timeout;
116 stage = STAGE_GETRANGE;
119 /* we now compute recentcount as a difference between
120 * new and old EXISTS, hence disable RECENT check */
122 else if (strstr(buf, " RECENT"))
124 /* fixme: use strto[u]l and error checking */
125 recentcount = atoi(buf+2);
128 else if (strstr(buf, " EXPUNGE"))
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 */
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);
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)
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.
158 * However, for check_only, we use EXAMINE which will
159 * mark the mailbox read-only as per the RFC.
161 * This checks for the condition and aborts if
162 * the mailbox is read-only.
164 * See RFC 2060 section 6.3.1 (SELECT).
165 * See RFC 2060 section 6.3.2 (EXAMINE).
167 else if (stage == STAGE_GETRANGE
168 && !check_only && strstr(buf, "[READ-ONLY]"))
179 static int imap_response(int sock, char *argbuf, struct RecvSplit *rs)
180 /* parse command response */
182 char buf[MSGBUFSIZE+1];
189 ok = gen_recv_split(sock, buf, sizeof(buf), rs);
191 ok = gen_recv(sock, buf, sizeof(buf));
192 if (ok != PS_SUCCESS)
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);
200 /* untagged responses start with "* " */
201 if (buf[0] == '*' && buf[1] == ' ') {
202 ok = imap_untagged_response(sock, buf);
203 if (ok == PS_UNTAGGED)
205 if (argbuf && stage != STAGE_IDLE && tag[0] != '\0')
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 */
215 else if (ok != PS_SUCCESS)
219 if (stage == STAGE_IDLE)
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);
225 return(PS_IDLETIMEOUT);
228 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
241 for (cp = buf; !isspace((unsigned char)*cp); cp++)
243 while (isspace((unsigned char)*cp))
246 if (strncasecmp(cp, "OK", 2) == 0)
252 else if (strncasecmp(cp, "BAD", 3) == 0)
254 else if (strncasecmp(cp, "NO", 2) == 0)
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() */
268 static int imap_ok(int sock, char *argbuf)
269 /* parse command response */
273 while ((ok = imap_response(sock, argbuf, NULL)) == PS_UNTAGGED)
274 ; /* wait for the tagged response */
282 * NTLM support by Grant Edwards.
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
289 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
292 static int do_imap_ntlm(int sock, struct query *ctl)
296 gen_send(sock, "AUTHENTICATE NTLM");
298 if ((result = ntlm_helper(sock, ctl, "IMAP")))
301 result = imap_ok (sock, NULL);
302 if (result == PS_SUCCESS)
309 static void imap_canonicalize(char *result, char *raw, size_t maxlen)
310 /* encode an IMAP password as per RFC1730's quoting conventions */
315 for (i = 0; i < strlen(raw) && i < maxlen; i++)
317 if ((raw[i] == '\\') || (raw[i] == '"'))
319 result[j++] = raw[i];
324 static int capa_probe(int sock, struct query *ctl)
325 /* set capability variables from a CAPA probe */
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)
335 /* capability checks are supposed to be caseblind */
336 for (cp = capabilities; *cp; cp++)
337 *cp = toupper((unsigned char)*cp);
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"))
343 imap_version = IMAP4rev1;
344 if (outlevel >= O_DEBUG)
345 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
349 imap_version = IMAP4;
350 if (outlevel >= O_DEBUG)
351 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
358 * Handle idling. We depend on coming through here on startup
359 * and after each timeout (including timeouts during idles).
364 if (strstr(capabilities, "IDLE"))
368 if (outlevel >= O_VERBOSE)
369 report(stdout, GT_("will idle after poll\n"));
377 static int do_authcert (int sock, const char *command, const char *name)
378 /* do authentication "external" (authentication provided by client cert) */
384 size_t len = strlen(name);
385 if ((len / 3) + ((len % 3) ? 4 : 0) < sizeof(buf))
386 to64frombits (buf, name, strlen(name));
388 return PS_AUTHFAIL; /* buffer too small. */
392 return gen_transact(sock, "%s EXTERNAL %s",command,buf);
395 static int imap_getauth(int sock, struct query *ctl, char *greeting)
396 /* apply for connection authorization */
402 * Assumption: expunges are cheap, so we want to do them
403 * after every message unless user said otherwise.
405 if (NUM_SPECIFIED(ctl->expunge))
406 expunge_period = NUM_VALUE_OUT(ctl->expunge);
410 if ((ok = capa_probe(sock, ctl)))
414 * If either (a) we saw a PREAUTH token in the greeting, or
415 * (b) the user specified ssh preauthentication, then we're done.
417 if (preauth || ctl->server.authenticate == A_SSH)
419 preauth = FALSE; /* reset for the next session */
424 if (maybe_tls(ctl)) {
427 commonname = ctl->server.pollname;
429 commonname = ctl->server.via;
430 if (ctl->sslcommonname)
431 commonname = ctl->sslcommonname;
433 if (strstr(capabilities, "STARTTLS")
434 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
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
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)
446 * RFC 2595 says this:
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
455 * Now that we're confident in our TLS connection we can
456 * guarantee a secure capability re-probe.
458 if ((ok = capa_probe(sock, ctl)))
460 if (outlevel >= O_VERBOSE)
462 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
464 } else if (must_tls(ctl)) {
465 /* Config required TLS but we couldn't guarantee it, so we must
468 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
472 if (outlevel >= O_VERBOSE) {
473 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue\n"), commonname);
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("");
483 /* Usable. Proceed with authenticating insecurely. */
487 #endif /* SSL_ENABLE */
490 * Time to authenticate the user.
491 * Try the protocol variants that don't require passwords first.
495 /* Yahoo hack - we'll just try ID if it was offered by the server,
496 * and IGNORE errors. */
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\")");
504 if ((ctl->server.authenticate == A_ANY
505 || ctl->server.authenticate == A_EXTERNAL)
506 && strstr(capabilities, "AUTH=EXTERNAL"))
508 ok = do_authcert(sock, "AUTHENTICATE", ctl->remotename);
511 /* SASL cancellation of authentication */
513 if (ctl->server.authenticate != A_ANY)
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"))
525 if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
526 ctl->server.truename, ctl->remotename)))
528 if (ctl->server.authenticate != A_ANY)
537 * No such luck. OK, now try the variants that mask your password
538 * in a challenge-response.
541 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
542 || ctl->server.authenticate == A_CRAM_MD5)
544 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
546 if(ctl->server.authenticate != A_ANY)
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)))
559 /* SASL cancellation of authentication */
561 if(ctl->server.authenticate != A_ANY)
568 if (ctl->server.authenticate == A_OTP)
571 GT_("Required OTP capability not compiled into fetchmail\n"));
573 #endif /* OPIE_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)))
581 if(ctl->server.authenticate != A_ANY)
588 if (ctl->server.authenticate == A_NTLM)
591 GT_("Required NTLM capability not compiled into fetchmail\n"));
593 #endif /* NTLM_ENABLE */
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.
602 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
603 || ctl->server.authenticate == A_PASSWORD)
605 /* these sizes guarantee no buffer overflow */
606 char *remotename, *password;
608 rnl = 2 * strlen(ctl->remotename) + 1;
609 pwl = 2 * strlen(ctl->password) + 1;
610 remotename = (char *)xmalloc(rnl);
611 password = (char *)xmalloc(pwl);
613 imap_canonicalize(remotename, ctl->remotename, rnl);
614 imap_canonicalize(password, ctl->password, pwl);
616 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
617 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
618 memset(shroud, 0x55, sizeof(shroud));
620 memset(password, 0x55, strlen(password));
625 if(ctl->server.authenticate != A_ANY)
635 static int internal_expunge(int sock)
636 /* ship an expunge, resetting associated counters */
640 actual_deletions = 0;
642 if ((ok = gen_transact(sock, "EXPUNGE")))
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)
655 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
656 actual_deletions, deletions);
661 expunged += deletions;
664 #ifdef IMAP_UID /* not used */
666 #endif /* IMAP_UID */
671 static int imap_idle(int sock)
672 /* start an RFC2177 IDLE, or fake one if unsupported */
676 saved_timeout = mytimeout;
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);
685 /* enter IDLE mode */
686 ok = gen_transact(sock, "IDLE");
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);
699 } else { /* no idle support, fake it */
700 /* Note: stage and timeout have not been changed here as NOOP
702 ok = gen_transact(sock, "NOOP");
704 /* no error, but no new mail either */
705 if (ok == PS_SUCCESS && recentcount == 0)
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
711 mytimeout = idle_timeout = 28;
712 time(&idle_start_time);
714 /* We are waiting for notification; no tag needed */
716 /* wait (briefly) for an unsolicited status update */
717 ok = imap_ok(sock, NULL);
718 if (ok == PS_IDLETIMEOUT) {
719 /* no notification came; ok */
725 /* restore normal timeout value */
727 mytimeout = saved_timeout;
728 stage = STAGE_GETRANGE;
733 static int imap_search(int sock, struct query *ctl, int count)
734 /* search for unseen messages */
737 char buf[MSGBUFSIZE+1], *cp;
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;
746 /* structure to keep the end portion of the incomplete response */
749 /* startcount is higher than count so that if there are no
750 * unseen messages, imap_getsizes() will not need to do
752 startcount = count + 1;
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)
761 if ((cp = strstr(buf, "* SEARCH")))
765 cp += 8; /* skip "* SEARCH" */
766 while (*cp && unseen < count)
768 /* skip whitespace */
769 while (*cp && isspace((unsigned char)*cp))
776 um = strtoul(cp,&ep,10);
777 if (errno == 0 && ep > cp
778 && um <= INT_MAX && um <= (unsigned)count)
780 unseen_messages[unseen++] = um;
781 if (outlevel >= O_DEBUG)
782 report(stdout, GT_("%lu is unseen\n"), um);
791 if (ok != PS_ERROR) /* success or non-protocol error */
794 /* there is a protocol error. try a different search command. */
797 /* retry with "SEARCH UNSEEN" */
801 /* try with "FETCH 1:n FLAGS" */
806 gen_send(sock, "FETCH %d FLAGS", count);
808 gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
809 while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
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))
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"))
830 unseen_messages[unseen++] = num;
831 if (outlevel >= O_DEBUG)
832 report(stdout, GT_("%u is unseen\n"), num);
833 if (startcount > num)
840 static int imap_getrange(int sock,
843 int *countp, int *newp, int *bytes)
844 /* get range of messages to be fetched */
848 /* find out how many messages are waiting */
853 /* deleted mails have already been expunged by
854 * end_mailbox_poll().
856 * recentcount is already set here by the last imap command which
857 * returned EXISTS on detecting new mail. if recentcount is 0, wait
860 * this is a while loop because imap_idle() might return on other
861 * mailbox changes also */
862 while (recentcount == 0 && do_idle) {
864 ok = imap_idle(sock);
867 report(stderr, GT_("re-poll failed\n"));
871 /* if recentcount is 0, return no mail */
872 if (recentcount == 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",
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)
892 report(stderr, GT_("mailbox selection failed\n"));
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",
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'
905 if (!check_only && !ctl->keep && count > 0)
907 ok = internal_expunge(sock);
910 report(stderr, GT_("expunge failed\n"));
913 if (outlevel >= O_DEBUG)
914 report(stdout, ngettext("%d message waiting after expunge\n",
915 "%d messages waiting after expunge\n",
919 if (count == 0 && do_idle)
921 /* no messages? then we may need to idle until we get some */
923 ok = imap_idle(sock);
926 report(stderr, GT_("re-poll failed\n"));
930 if (outlevel >= O_DEBUG)
931 report(stdout, ngettext("%d message waiting after re-poll\n",
932 "%d messages waiting after re-poll\n",
937 *countp = oldcount = count;
941 /* OK, now get a count of unseen messages and their indices */
942 if (!ctl->fetchall && count > 0)
945 free(unseen_messages);
946 unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
947 memset(unseen_messages, 0, count * sizeof(unsigned int));
950 ok = imap_search(sock, ctl, count);
953 report(stderr, GT_("search for unseen messages failed\n"));
957 if (outlevel >= O_DEBUG && unseen > 0)
958 report(stdout, GT_("%u is first unseen\n"), startcount);
969 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
970 /* capture the sizes of messages #first-#last */
972 char buf [MSGBUFSIZE+1];
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.
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:
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.
995 * This means message 1 has only headers. For kicks and grins
996 * you can telnet in and look:
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.
1002 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1003 * A006 OK FETCH completed.
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.
1010 /* expunges change the fetch numbers */
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! */
1020 while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
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)
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)
1038 if (num >= first && num <= last)
1039 sizes[num - first] = size;
1042 GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1048 static int imap_getsizes(int sock, int count, int *sizes)
1049 /* capture the sizes of all messages */
1051 return imap_getpartialsizes(sock, 1, count, sizes);
1054 static int imap_is_old(int sock, struct query *ctl, int number)
1055 /* is the given message old? */
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.
1069 for (i = 0; i < unseen; i++)
1070 if (unseen_messages[i] == (unsigned)number)
1080 static char *skip_token(char *ptr)
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++;
1089 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1090 /* request headers of nth message */
1092 char buf [MSGBUFSIZE+1];
1098 /* expunges change the fetch numbers */
1102 * This is blessed by RFC1176, RFC1730, RFC2060.
1103 * According to the RFCs, it should *not* set the \Seen flag.
1105 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1107 /* looking for FETCH response */
1108 if ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
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}
1117 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1118 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1119 && isspace((unsigned char)buf[5+consumed])
1121 && (ptr = strstr(buf, "RFC822.HEADER"))
1122 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1123 && ptr[consumed-1] == '}')
1128 /* wait for a tagged response */
1131 /* try to recover for some responses */
1132 if (!strncmp(buf, "* NO", 4) ||
1133 !strncmp(buf, "* BAD", 5))
1135 return(PS_TRANSIENT);
1138 /* a response which does not match any of the above */
1139 if (outlevel > O_SILENT)
1140 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1143 else if (ok == PS_SUCCESS)
1145 /* an unexpected tagged response */
1146 if (outlevel > O_SILENT)
1147 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1148 return(PS_TRANSIENT);
1153 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1154 /* request body of nth message */
1156 char buf [MSGBUFSIZE+1], *cp;
1160 /* expunges change the fetch numbers */
1164 * If we're using IMAP4, we can fetch the message without setting its
1165 * seen flag. This is good! It means that if the protocol exchange
1166 * craps out during the message, it will still be marked `unseen' on
1169 * According to RFC2060, and Mark Crispin the IMAP maintainer,
1170 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
1171 * equivalent". However, we know of at least one server that
1172 * treats them differently in the presence of MIME attachments;
1173 * the latter form downloads the attachment, the former does not.
1174 * The server is InterChange.
1176 * When I tried working around this by disabling use of the 4rev1 form,
1177 * I found that doing this breaks operation with M$ Exchange.
1178 * Annoyingly enough, Exchange's refusal to cope is technically legal
1181 switch (imap_version)
1183 case IMAP4rev1: /* RFC 2060 */
1185 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1188 case IMAP4: /* RFC 1730 */
1189 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1193 /* looking for FETCH response */
1197 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1200 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1205 /* Understand "NIL" as length => no body present
1206 * (MS Exchange, BerliOS Bug #11980) */
1207 if (strstr(buf+10, "NIL)")) {
1212 /* Understand the empty string. Seen on Yahoo. */
1213 /* XXX FIXME: we should be able to handle strings here. */
1214 if (strstr(buf+10, "\"\")")) {
1220 * Try to extract a length from the FETCH response. RFC2060 requires
1221 * it to be present, but at least one IMAP server (Novell GroupWise)
1222 * botches this. The overflow check is needed because of a broken
1223 * server called dbmail that returns huge garbage lengths.
1225 if ((cp = strchr(buf, '{'))) {
1229 l = strtol(cp, &t, 10);
1230 if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1231 || l < 0 || l > INT_MAX /* range check */) {
1237 *lenp = -1; /* missing length part in FETCH reponse */
1243 static int imap_trail(int sock, struct query *ctl, const char *tag)
1244 /* discard tail of FETCH response after reading message text */
1246 /* expunges change the fetch numbers */
1247 /* number -= expunged; */
1252 return imap_ok(sock, NULL);
1255 static int imap_delete(int sock, struct query *ctl, int number)
1256 /* set delete flag for given message */
1259 /* Select which flags to set on message deletion: */
1260 const char delflags_seen[] = "\\Seen \\Deleted";
1261 static const char *delflags;
1262 /* Which environment variable to look for: */
1264 /* DEFAULT since many fetchmail versions <= 6.3.X */
1265 delflags = delflags_seen;
1268 /* expunges change the fetch numbers */
1272 * We set Seen because there are some IMAP servers (notably HP
1273 * OpenMail) that do message-receipt DSNs, but only when the seen
1274 * bit is set. This is the appropriate time -- we get here right
1275 * after the local SMTP response that says delivery was
1278 if ((ok = gen_transact(sock, "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)", number)))
1284 * We do an expunge after expunge_period messages, rather than
1285 * just before quit, so that a line hit during a long session
1286 * won't result in lots of messages being fetched again during
1289 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1291 if ((ok = internal_expunge(sock)))
1298 static int imap_mark_seen(int sock, struct query *ctl, int number)
1299 /* mark the given message as seen */
1303 /* expunges change the message numbers */
1306 return(gen_transact(sock,"STORE %d +FLAGS.SILENT (\\Seen)", number));
1309 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1310 /* cleanup mailbox before we idle or switch to another one */
1314 internal_expunge(sock);
1318 static int imap_logout(int sock, struct query *ctl)
1319 /* send logout command */
1322 /* if any un-expunged deletions remain, ship an expunge now */
1324 internal_expunge(sock);
1327 /* Memory clean-up */
1328 if (unseen_messages)
1329 free(unseen_messages);
1330 #endif /* USE_SEARCH */
1332 return(gen_transact(sock, "LOGOUT"));
1335 static const struct method imap =
1337 "IMAP", /* Internet Message Access Protocol */
1338 "imap", /* service (plain and TLS) */
1339 "imaps", /* service (SSL) */
1340 TRUE, /* this is a tagged protocol */
1341 FALSE, /* no message delimiter */
1342 imap_ok, /* parse command response */
1343 imap_getauth, /* get authorization */
1344 imap_getrange, /* query range of messages */
1345 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1346 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1347 imap_is_old, /* no UID check */
1348 imap_fetch_headers, /* request given message headers */
1349 imap_fetch_body, /* request given message body */
1350 imap_trail, /* eat message trailer */
1351 imap_delete, /* delete the message */
1352 imap_mark_seen, /* how to mark a message as seen */
1353 imap_end_mailbox_poll, /* end-of-mailbox processing */
1354 imap_logout, /* expunge and exit */
1355 TRUE, /* yes, we can re-poll */
1358 int doIMAP(struct query *ctl)
1359 /* retrieve messages using IMAP Version 2bis or Version 4 */
1361 return(do_protocol(ctl, &imap));
1364 /* imap.c ends here */