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.
13 #if defined(STDC_HEADERS)
18 #include "fetchmail.h"
23 /* imap_version values */
24 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
25 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
26 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
28 /* global variables: please reinitialize them explicitly for proper
29 * working in daemon mode */
31 /* TODO: session variables to be initialized before server greeting */
32 static int preauth = FALSE;
34 /* session variables initialized in capa_probe() or imap_getauth() */
35 static char capabilities[MSGBUFSIZE+1];
36 static int imap_version = IMAP4;
37 static flag do_idle = FALSE, has_idle = FALSE;
38 static int expunge_period = 1;
40 /* mailbox variables initialized in imap_getrange() */
41 static int count = 0, oldcount = 0, recentcount = 0, unseen = 0, deletions = 0;
42 static unsigned int startcount = 1;
43 static int expunged = 0;
44 static unsigned int *unseen_messages;
46 /* for "IMAP> EXPUNGE" */
47 static int actual_deletions = 0;
49 /* for "IMAP> IDLE" */
50 static int saved_timeout = 0, idle_timeout = 0;
51 static time_t idle_start_time = 0;
53 static int imap_untagged_response(int sock, const char *buf)
54 /* interpret untagged status responses */
56 /* For each individual check, use a BLANK before the word to avoid
57 * confusion with the \Recent flag or similar */
58 if (stage == STAGE_GETAUTH
59 && !strncmp(buf, "* CAPABILITY", 12))
61 strlcpy(capabilities, buf + 12, sizeof(capabilities));
63 else if (stage == STAGE_GETAUTH
64 && !strncmp(buf, "* PREAUTH", 9))
68 else if (stage != STAGE_LOGOUT
69 && !strncmp(buf, "* BYE", 5))
71 /* log the unexpected bye from server as we expect the
72 * connection to be cut-off after this */
73 if (outlevel > O_SILENT)
74 report(stderr, GT_("Received BYE response from IMAP server: %s"), buf + 5);
76 else if (strstr(buf, " EXISTS"))
78 char *t; unsigned long u;
80 u = strtoul(buf+2, &t, 10);
82 * Don't trust the message count passed by the server.
83 * Without this check, it might be possible to do a
84 * DNS-spoofing attack that would pass back a ridiculous
85 * count, and allocate a malloc area that would overlap
86 * a portion of the stack.
88 if (errno /* strtoul failed */
89 || t == buf+2 /* no valid data */
90 || u > (unsigned long)(INT_MAX/sizeof(int)) /* too large */)
92 report(stderr, GT_("bogus message count in \"%s\"!"), buf);
95 count = u; /* safe as long as count <= INT_MAX - checked above */
97 if ((recentcount = count - oldcount) < 0)
101 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
102 * we can't wait for the tag matching the IDLE; we have to tell the
103 * server the IDLE is finished by shipping back a DONE when we
104 * see an EXISTS. Only after that will a tagged response be
105 * shipped. The idling flag also gets cleared on a timeout.
107 if (stage == STAGE_IDLE)
109 /* If IDLE isn't supported, we were only sending NOOPs anyway. */
112 /* we do our own write and report here to disable tagging */
113 SockWrite(sock, "DONE\r\n", 6);
114 if (outlevel >= O_MONITOR)
115 report(stdout, "IMAP> DONE\n");
118 mytimeout = saved_timeout;
119 stage = STAGE_GETRANGE;
122 /* we now compute recentcount as a difference between
123 * new and old EXISTS, hence disable RECENT check */
125 else if (strstr(buf, " RECENT"))
127 /* fixme: use strto[u]l and error checking */
128 recentcount = atoi(buf+2);
131 else if (strstr(buf, " EXPUNGE"))
133 unsigned long u; char *t;
134 /* the response "* 10 EXPUNGE" means that the currently
135 * tenth (i.e. only one) message has been deleted */
137 u = strtoul(buf+2, &t, 10);
138 if (errno /* conversion error */ || t == buf+2 /* no number found */) {
139 report(stderr, GT_("bogus EXPUNGE count in \"%s\"!"), buf);
148 /* We do expect an EXISTS response immediately
149 * after this, so this updation of recentcount is
150 * just a precaution! */
151 if ((recentcount = count - oldcount) < 0)
157 * The server may decide to make the mailbox read-only,
158 * which causes fetchmail to go into a endless loop
159 * fetching the same message over and over again.
161 * However, for check_only, we use EXAMINE which will
162 * mark the mailbox read-only as per the RFC.
164 * This checks for the condition and aborts if
165 * the mailbox is read-only.
167 * See RFC 2060 section 6.3.1 (SELECT).
168 * See RFC 2060 section 6.3.2 (EXAMINE).
170 else if (stage == STAGE_GETRANGE
171 && !check_only && strstr(buf, "[READ-ONLY]"))
182 static int imap_response(int sock, char *argbuf)
183 /* parse command response */
185 char buf[MSGBUFSIZE+1];
191 if ((ok = gen_recv(sock, buf, sizeof(buf))))
194 /* all tokens in responses are caseblind */
195 for (cp = buf; *cp; cp++)
196 if (islower((unsigned char)*cp))
197 *cp = toupper((unsigned char)*cp);
199 /* untagged responses start with "* " */
200 if (buf[0] == '*' && buf[1] == ' ') {
201 ok = imap_untagged_response(sock, buf);
202 if (ok == PS_UNTAGGED)
204 if (argbuf && stage != STAGE_IDLE && tag[0] != '\0')
206 /* if there is an unmatched response, pass it back to
207 * the calling function for further analysis. The
208 * calling function should call imap_response() again
209 * to read the remaining response */
214 else if (ok != PS_SUCCESS)
218 if (stage == STAGE_IDLE)
220 /* reduce the timeout: servers may not reset their timeout
221 * when they send some information asynchronously */
222 mytimeout = idle_timeout - (time((time_t *) NULL) - idle_start_time);
224 return(PS_IDLETIMEOUT);
227 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
240 for (cp = buf; !isspace((unsigned char)*cp); cp++)
242 while (isspace((unsigned char)*cp))
245 if (strncasecmp(cp, "OK", 2) == 0)
251 else if (strncasecmp(cp, "BAD", 3) == 0)
253 else if (strncasecmp(cp, "NO", 2) == 0)
255 if (stage == STAGE_GETAUTH)
256 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
257 else if (stage == STAGE_GETSIZES)
258 return(PS_SUCCESS); /* see comments in imap_getpartialsizes() */
267 static int imap_ok(int sock, char *argbuf)
268 /* parse command response */
272 while ((ok = imap_response(sock, argbuf)) == PS_UNTAGGED)
273 ; /* wait for the tagged response */
281 * NTLM support by Grant Edwards.
283 * Handle MS-Exchange NTLM authentication method. This is the same
284 * as the NTLM auth used by Samba for SMB related services. We just
285 * encode the packets in base64 instead of sending them out via a
288 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
291 static int do_imap_ntlm(int sock, struct query *ctl)
295 gen_send(sock, "AUTHENTICATE NTLM");
297 if ((result = ntlm_helper(sock, ctl, "IMAP")))
300 result = imap_ok (sock, NULL);
301 if (result == PS_SUCCESS)
308 static void imap_canonicalize(char *result, char *raw, size_t maxlen)
309 /* encode an IMAP password as per RFC1730's quoting conventions */
314 for (i = 0; i < strlen(raw) && i < maxlen; i++)
316 if ((raw[i] == '\\') || (raw[i] == '"'))
318 result[j++] = raw[i];
323 static void capa_probe(int sock, struct query *ctl)
324 /* set capability variables from a CAPA probe */
328 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
329 capabilities[0] = '\0';
330 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
334 /* capability checks are supposed to be caseblind */
335 for (cp = capabilities; *cp; cp++)
336 *cp = toupper((unsigned char)*cp);
338 /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
339 should expect a response in mixed-case */
340 if (strstr(capabilities, "IMAP4REV1"))
342 imap_version = IMAP4rev1;
343 if (outlevel >= O_DEBUG)
344 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
348 imap_version = IMAP4;
349 if (outlevel >= O_DEBUG)
350 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
353 else if (ok == PS_ERROR)
355 imap_version = IMAP2;
356 if (outlevel >= O_DEBUG)
357 report(stdout, GT_("Protocol identified as IMAP2 or IMAP2BIS\n"));
361 * Handle idling. We depend on coming through here on startup
362 * and after each timeout (including timeouts during idles).
367 if (strstr(capabilities, "IDLE"))
371 if (outlevel >= O_VERBOSE)
372 report(stdout, GT_("will idle after poll\n"));
375 peek_capable = (imap_version >= IMAP4);
378 static int do_authcert (int sock, const char *command, const char *name)
379 /* do authentication "external" (authentication provided by client cert) */
385 size_t len = strlen(name);
386 if ((len / 3) + ((len % 3) ? 4 : 0) < sizeof(buf))
387 to64frombits (buf, name, strlen(name));
389 return PS_AUTHFAIL; /* buffer too small. */
393 return gen_transact(sock, "%s EXTERNAL %s",command,buf);
396 static int imap_getauth(int sock, struct query *ctl, char *greeting)
397 /* apply for connection authorization */
406 * Assumption: expunges are cheap, so we want to do them
407 * after every message unless user said otherwise.
409 if (NUM_SPECIFIED(ctl->expunge))
410 expunge_period = NUM_VALUE_OUT(ctl->expunge);
414 capa_probe(sock, ctl);
417 * If either (a) we saw a PREAUTH token in the greeting, or
418 * (b) the user specified ssh preauthentication, then we're done.
420 if (preauth || ctl->server.authenticate == A_SSH)
422 preauth = FALSE; /* reset for the next session */
427 if (maybe_tls(ctl)) {
430 commonname = ctl->server.pollname;
432 commonname = ctl->server.via;
433 if (ctl->sslcommonname)
434 commonname = ctl->sslcommonname;
436 if (strstr(capabilities, "STARTTLS"))
438 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
439 * protocol that will work with STARTTLS. Don't need to worry
440 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
442 if (gen_transact(sock, "STARTTLS") == PS_SUCCESS
443 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
444 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
445 ctl->server.pollname, &ctl->remotename) != -1)
448 * RFC 2595 says this:
450 * "Once TLS has been started, the client MUST discard cached
451 * information about server capabilities and SHOULD re-issue the
452 * CAPABILITY command. This is necessary to protect against
453 * man-in-the-middle attacks which alter the capabilities list prior
454 * to STARTTLS. The server MAY advertise different capabilities
457 * Now that we're confident in our TLS connection we can
458 * guarantee a secure capability re-probe.
461 capa_probe(sock, ctl);
462 if (outlevel >= O_VERBOSE)
464 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
471 /* Config required TLS but we couldn't guarantee it, so we must
473 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
476 if (outlevel >= O_VERBOSE) {
477 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue\n"), commonname);
479 /* We don't know whether the connection is in a working state, so
480 * test by issuing a NOOP. */
481 if (gen_transact(sock, "NOOP") != PS_SUCCESS) {
482 /* Not usable. Empty sslproto to force an unencrypted
483 * connection on the next attempt, and repoll. */
484 ctl->sslproto = xstrdup("");
487 /* Usable. Proceed with authenticating insecurely. */
491 #endif /* SSL_ENABLE */
494 * Time to authenticate the user.
495 * Try the protocol variants that don't require passwords first.
499 /* Yahoo hack - we'll just try ID if it was offered by the server,
500 * and IGNORE errors. */
502 char *tmp = strstr(capabilities, " ID");
503 if (tmp && !isalnum((unsigned char)tmp[3]) && strstr(ctl->server.via ? ctl->server.via : ctl->server.pollname, "yahoo.com")) {
504 (void)gen_transact(sock, "ID (\"guid\" \"1\")");
508 if ((ctl->server.authenticate == A_ANY
509 || ctl->server.authenticate == A_EXTERNAL)
510 && strstr(capabilities, "AUTH=EXTERNAL"))
512 ok = do_authcert(sock, "AUTHENTICATE", ctl->remotename);
515 /* SASL cancellation of authentication */
517 if (ctl->server.authenticate != A_ANY)
525 if (((ctl->server.authenticate == A_ANY && check_gss_creds("imap", ctl->server.truename) == PS_SUCCESS)
526 || ctl->server.authenticate == A_GSSAPI)
527 && strstr(capabilities, "AUTH=GSSAPI"))
529 if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
530 ctl->server.truename, ctl->remotename)))
532 if (ctl->server.authenticate != A_ANY)
541 if ((ctl->server.authenticate == A_ANY
542 || ctl->server.authenticate == A_KERBEROS_V4
543 || ctl->server.authenticate == A_KERBEROS_V5)
544 && strstr(capabilities, "AUTH=KERBEROS_V4"))
546 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
548 /* SASL cancellation of authentication */
550 if(ctl->server.authenticate != A_ANY)
556 #endif /* KERBEROS_V4 */
559 * No such luck. OK, now try the variants that mask your password
560 * in a challenge-response.
563 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
564 || ctl->server.authenticate == A_CRAM_MD5)
566 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
568 if(ctl->server.authenticate != A_ANY)
576 if ((ctl->server.authenticate == A_ANY
577 || ctl->server.authenticate == A_OTP)
578 && strstr(capabilities, "AUTH=X-OTP")) {
579 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
581 /* SASL cancellation of authentication */
583 if(ctl->server.authenticate != A_ANY)
590 if (ctl->server.authenticate == A_OTP)
593 GT_("Required OTP capability not compiled into fetchmail\n"));
595 #endif /* OPIE_ENABLE */
598 if ((ctl->server.authenticate == A_ANY
599 || ctl->server.authenticate == A_NTLM)
600 && strstr (capabilities, "AUTH=NTLM")) {
601 if ((ok = do_imap_ntlm(sock, ctl)))
603 if(ctl->server.authenticate != A_ANY)
610 if (ctl->server.authenticate == A_NTLM)
613 GT_("Required NTLM capability not compiled into fetchmail\n"));
615 #endif /* NTLM_ENABLE */
617 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
618 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
619 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
622 GT_("Required LOGIN capability not supported by server\n"));
624 #endif /* __UNUSED__ */
627 * We're stuck with sending the password en clair.
628 * The reason for this odd-looking logic is that some
629 * servers return LOGINDISABLED even though login
630 * actually works. So arrange things in such a way that
631 * setting auth passwd makes it ignore this capability.
633 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
634 || ctl->server.authenticate == A_PASSWORD)
636 /* these sizes guarantee no buffer overflow */
637 char *remotename, *password;
639 rnl = 2 * strlen(ctl->remotename) + 1;
640 pwl = 2 * strlen(ctl->password) + 1;
641 remotename = (char *)xmalloc(rnl);
642 password = (char *)xmalloc(pwl);
644 imap_canonicalize(remotename, ctl->remotename, rnl);
645 imap_canonicalize(password, ctl->password, pwl);
647 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
648 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
649 memset(shroud, 0x55, sizeof(shroud));
651 memset(password, 0x55, strlen(password));
656 if(ctl->server.authenticate != A_ANY)
666 static int internal_expunge(int sock)
667 /* ship an expunge, resetting associated counters */
671 actual_deletions = 0;
673 if ((ok = gen_transact(sock, "EXPUNGE")))
676 /* if there is a mismatch between the number of mails which should
677 * have been expunged and the number of mails actually expunged,
678 * another email client may be deleting mails. Quit here,
679 * otherwise fetchmail gets out-of-sync with the imap server,
680 * reports the wrong size to the SMTP server on MAIL FROM: and
681 * triggers a "message ... was not the expected length" error on
682 * every subsequent mail */
683 if (deletions > 0 && deletions != actual_deletions)
686 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
687 actual_deletions, deletions);
692 expunged += deletions;
695 #ifdef IMAP_UID /* not used */
697 #endif /* IMAP_UID */
702 static int imap_idle(int sock)
703 /* start an RFC2177 IDLE, or fake one if unsupported */
707 saved_timeout = mytimeout;
710 /* special timeout to terminate the IDLE and re-issue it
711 * at least every 28 minutes:
712 * (the server may have an inactivity timeout) */
713 mytimeout = idle_timeout = 1680; /* 28 min */
714 time(&idle_start_time);
716 /* enter IDLE mode */
717 ok = gen_transact(sock, "IDLE");
719 if (ok == PS_IDLETIMEOUT) {
720 /* send "DONE" continuation */
721 SockWrite(sock, "DONE\r\n", 6);
722 if (outlevel >= O_MONITOR)
723 report(stdout, "IMAP> DONE\n");
724 /* reset stage and timeout here: we are not idling any more */
725 mytimeout = saved_timeout;
726 stage = STAGE_GETRANGE;
727 /* get OK IDLE message */
728 ok = imap_ok(sock, NULL);
730 } else { /* no idle support, fake it */
731 /* Note: stage and timeout have not been changed here as NOOP
733 ok = gen_transact(sock, "NOOP");
735 /* no error, but no new mail either */
736 if (ok == PS_SUCCESS && recentcount == 0)
738 /* There are some servers who do send new mail
739 * notification out of the blue. This is in compliance
740 * with RFC 2060 section 5.3. Wait for that with a low
742 mytimeout = idle_timeout = 28;
743 time(&idle_start_time);
745 /* We are waiting for notification; no tag needed */
747 /* wait (briefly) for an unsolicited status update */
748 ok = imap_ok(sock, NULL);
749 if (ok == PS_IDLETIMEOUT) {
750 /* no notification came; ok */
756 /* restore normal timeout value */
758 mytimeout = saved_timeout;
759 stage = STAGE_GETRANGE;
764 /* maximum number of numbers we can process in "SEARCH" response */
765 # define IMAP_SEARCH_MAX 1000
767 static int imap_search(int sock, struct query *ctl, int count)
768 /* search for unseen messages */
771 char buf[MSGBUFSIZE+1], *cp;
773 /* Don't count deleted messages. Enabled only for IMAP4 servers or
774 * higher and only when keeping mails. This flag will have an
775 * effect only when user has marked some unread mails for deletion
776 * using another e-mail client. */
777 flag skipdeleted = (imap_version >= IMAP4) && ctl->keep;
778 const char *undeleted;
780 /* Skip range search if there are less than or equal to
781 * IMAP_SEARCH_MAX mails. */
782 flag skiprangesearch = (count <= IMAP_SEARCH_MAX);
784 /* startcount is higher than count so that if there are no
785 * unseen messages, imap_getsizes() will not need to do
787 startcount = count + 1;
789 for (first = 1, last = IMAP_SEARCH_MAX; first <= count; first += IMAP_SEARCH_MAX, last += IMAP_SEARCH_MAX)
795 undeleted = (skipdeleted ? " UNDELETED" : "");
797 gen_send(sock, "SEARCH UNSEEN%s", undeleted);
798 else if (last == first)
799 gen_send(sock, "SEARCH %d UNSEEN%s", last, undeleted);
801 gen_send(sock, "SEARCH %d:%d UNSEEN%s", first, last, undeleted);
802 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
804 if ((cp = strstr(buf, "* SEARCH")))
808 cp += 8; /* skip "* SEARCH" */
809 while (*cp && unseen < count)
811 /* skip whitespace */
812 while (*cp && isspace((unsigned char)*cp))
819 um = strtoul(cp,&ep,10);
820 if (errno == 0 && ep > cp
821 && um <= INT_MAX && um <= (unsigned)count)
823 unseen_messages[unseen++] = um;
824 if (outlevel >= O_DEBUG)
825 report(stdout, GT_("%lu is unseen\n"), um);
834 /* if there is a protocol error on the first loop, try a
835 * different search command */
836 if (ok == PS_ERROR && first == 1)
840 /* retry with "SEARCH 1:1000 UNSEEN" */
844 if (!skiprangesearch)
846 /* retry with "SEARCH UNSEEN" */
847 skiprangesearch = TRUE;
850 /* try with "FETCH 1:n FLAGS" */
853 if (ok != PS_SUCCESS)
855 /* loop back only when searching in range */
863 gen_send(sock, "FETCH %d FLAGS", count);
865 gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
866 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
871 /* expected response format:
872 * IMAP< * 1 FETCH (FLAGS (\Seen))
873 * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
874 * IMAP< * 3 FETCH (FLAGS ())
875 * IMAP< * 4 FETCH (FLAGS (\Recent))
876 * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
879 && sscanf(buf, "* %u %n", &num, &consumed) == 1
880 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
881 && isspace((unsigned char)buf[consumed+5])
882 && num >= 1 && num <= (unsigned)count
883 && strstr(buf, "FLAGS ")
884 && !strstr(buf, "\\SEEN")
885 && !strstr(buf, "\\DELETED"))
887 unseen_messages[unseen++] = num;
888 if (outlevel >= O_DEBUG)
889 report(stdout, GT_("%u is unseen\n"), num);
890 if (startcount > num)
897 static int imap_getrange(int sock,
900 int *countp, int *newp, int *bytes)
901 /* get range of messages to be fetched */
905 /* find out how many messages are waiting */
910 /* deleted mails have already been expunged by
911 * end_mailbox_poll().
913 * recentcount is already set here by the last imap command which
914 * returned EXISTS on detecting new mail. if recentcount is 0, wait
917 * this is a while loop because imap_idle() might return on other
918 * mailbox changes also */
919 while (recentcount == 0 && do_idle) {
921 ok = imap_idle(sock);
924 report(stderr, GT_("re-poll failed\n"));
928 /* if recentcount is 0, return no mail */
929 if (recentcount == 0)
931 if (outlevel >= O_DEBUG)
932 report(stdout, ngettext("%d message waiting after re-poll\n",
933 "%d messages waiting after re-poll\n",
938 oldcount = count = 0;
939 ok = gen_transact(sock,
940 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
941 folder ? folder : "INBOX");
942 /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
943 * which we can safely use in fetchall keep only */
944 if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
949 report(stderr, GT_("mailbox selection failed\n"));
952 else if (outlevel >= O_DEBUG)
953 report(stdout, ngettext("%d message waiting after first poll\n",
954 "%d messages waiting after first poll\n",
958 * We should have an expunge here to
959 * a) avoid fetching deleted mails during 'fetchall'
960 * b) getting a wrong count of mails during 'no fetchall'
962 if (!check_only && !ctl->keep && count > 0)
964 ok = internal_expunge(sock);
967 report(stderr, GT_("expunge failed\n"));
970 if (outlevel >= O_DEBUG)
971 report(stdout, ngettext("%d message waiting after expunge\n",
972 "%d messages waiting after expunge\n",
976 if (count == 0 && do_idle)
978 /* no messages? then we may need to idle until we get some */
980 ok = imap_idle(sock);
983 report(stderr, GT_("re-poll failed\n"));
987 if (outlevel >= O_DEBUG)
988 report(stdout, ngettext("%d message waiting after re-poll\n",
989 "%d messages waiting after re-poll\n",
994 *countp = oldcount = count;
998 /* OK, now get a count of unseen messages and their indices */
999 if (!ctl->fetchall && count > 0)
1001 if (unseen_messages)
1002 free(unseen_messages);
1003 unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
1004 memset(unseen_messages, 0, count * sizeof(unsigned int));
1007 ok = imap_search(sock, ctl, count);
1010 report(stderr, GT_("search for unseen messages failed\n"));
1014 if (outlevel >= O_DEBUG && unseen > 0)
1015 report(stdout, GT_("%u is first unseen\n"), startcount);
1026 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
1027 /* capture the sizes of messages #first-#last */
1029 char buf [MSGBUFSIZE+1];
1033 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1034 * won't accept 1:1 as valid set syntax. Some implementors
1035 * should be taken out and shot for excessive anality.
1037 * Microsoft Exchange (brain-dead piece of crap that it is)
1038 * sometimes gets its knickers in a knot about bodiless messages.
1039 * You may see responses like this:
1041 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1042 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1043 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1044 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1045 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1046 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1047 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1048 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1049 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1050 * fetchmail: IMAP< A0004 NO The requested item could not be found.
1052 * This means message 1 has only headers. For kicks and grins
1053 * you can telnet in and look:
1055 * A003 NO The requested item could not be found.
1056 * A004 fetch 1 rfc822.header
1057 * A004 NO The requested item could not be found.
1059 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1060 * A006 OK FETCH completed.
1062 * To get around this, we treat the final NO as success and count
1063 * on the fact that the sizes array has been preinitialized with a
1064 * known-bad size value.
1067 /* expunges change the fetch numbers */
1072 gen_send(sock, "FETCH %d RFC822.SIZE", last);
1073 else if (last > first)
1074 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1075 else /* no unseen messages! */
1077 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1084 /* expected response formats:
1085 * IMAP> A0005 FETCH 1 RFC822.SIZE
1086 * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1087 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1089 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1090 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1091 && isspace((unsigned char)buf[consumed + 5])
1092 && (ptr = strstr(buf, "RFC822.SIZE "))
1093 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1095 if (num >= first && num <= last)
1096 sizes[num - first] = size;
1099 GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1105 static int imap_getsizes(int sock, int count, int *sizes)
1106 /* capture the sizes of all messages */
1108 return imap_getpartialsizes(sock, 1, count, sizes);
1111 static int imap_is_old(int sock, struct query *ctl, int number)
1112 /* is the given message old? */
1120 * Expunges change the fetch numbers, but unseen_messages contains
1121 * indices from before any expungees were done. So neither the
1122 * argument nor the values in message_sequence need to be decremented.
1126 for (i = 0; i < unseen; i++)
1127 if (unseen_messages[i] == (unsigned)number)
1137 static char *skip_token(char *ptr)
1139 while(isspace((unsigned char)*ptr)) ptr++;
1140 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1141 while(isspace((unsigned char)*ptr)) ptr++;
1146 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1147 /* request headers of nth message */
1149 char buf [MSGBUFSIZE+1];
1155 /* expunges change the fetch numbers */
1159 * This is blessed by RFC1176, RFC1730, RFC2060.
1160 * According to the RFCs, it should *not* set the \Seen flag.
1162 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1164 /* looking for FETCH response */
1165 if ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1168 /* expected response formats:
1169 * IMAP> A0006 FETCH 1 RFC822.HEADER
1170 * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1171 * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1172 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1174 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1175 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1176 && isspace((unsigned char)buf[5+consumed])
1178 && (ptr = strstr(buf, "RFC822.HEADER"))
1179 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1180 && ptr[consumed-1] == '}')
1185 /* wait for a tagged response */
1188 /* try to recover for some responses */
1189 if (!strncmp(buf, "* NO", 4) ||
1190 !strncmp(buf, "* BAD", 5))
1192 return(PS_TRANSIENT);
1195 /* a response which does not match any of the above */
1196 if (outlevel > O_SILENT)
1197 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1200 else if (ok == PS_SUCCESS)
1202 /* an unexpected tagged response */
1203 if (outlevel > O_SILENT)
1204 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1210 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1211 /* request body of nth message */
1213 char buf [MSGBUFSIZE+1], *cp;
1217 /* expunges change the fetch numbers */
1221 * If we're using IMAP4, we can fetch the message without setting its
1222 * seen flag. This is good! It means that if the protocol exchange
1223 * craps out during the message, it will still be marked `unseen' on
1226 * According to RFC2060, and Mark Crispin the IMAP maintainer,
1227 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
1228 * equivalent". However, we know of at least one server that
1229 * treats them differently in the presence of MIME attachments;
1230 * the latter form downloads the attachment, the former does not.
1231 * The server is InterChange, and the fool who implemented this
1232 * misfeature ought to be strung up by his thumbs.
1234 * When I tried working around this by disabling use of the 4rev1 form,
1235 * I found that doing this breaks operation with M$ Exchange.
1236 * Annoyingly enough, Exchange's refusal to cope is technically legal
1237 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
1238 * standards, to find a way to make standards compliance irritating....
1240 switch (imap_version)
1242 case IMAP4rev1: /* RFC 2060 */
1243 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1246 case IMAP4: /* RFC 1730 */
1247 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1250 default: /* RFC 1176 */
1251 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1255 /* looking for FETCH response */
1259 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1262 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1267 /* Understand "NIL" as length => no body present
1268 * (MS Exchange, BerliOS Bug #11980) */
1269 if (strstr(buf+10, "NIL)")) {
1275 * Try to extract a length from the FETCH response. RFC2060 requires
1276 * it to be present, but at least one IMAP server (Novell GroupWise)
1277 * botches this. The overflow check is needed because of a broken
1278 * server called dbmail that returns huge garbage lengths.
1280 if ((cp = strchr(buf, '{'))) {
1284 l = strtol(cp, &t, 10);
1285 if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1286 || l < 0 || l > INT_MAX /* range check */) {
1292 *lenp = -1; /* missing length part in FETCH reponse */
1298 static int imap_trail(int sock, struct query *ctl, const char *tag)
1299 /* discard tail of FETCH response after reading message text */
1301 /* expunges change the fetch numbers */
1302 /* number -= expunged; */
1307 return imap_ok(sock, NULL);
1310 static int imap_delete(int sock, struct query *ctl, int number)
1311 /* set delete flag for given message */
1316 /* expunges change the fetch numbers */
1320 * Use SILENT if possible as a minor throughput optimization.
1321 * Note: this has been dropped from IMAP4rev1.
1323 * We set Seen because there are some IMAP servers (notably HP
1324 * OpenMail) that do message-receipt DSNs, but only when the seen
1325 * bit is set. This is the appropriate time -- we get here right
1326 * after the local SMTP response that says delivery was
1329 if ((ok = gen_transact(sock,
1330 imap_version == IMAP4
1331 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1332 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1339 * We do an expunge after expunge_period messages, rather than
1340 * just before quit, so that a line hit during a long session
1341 * won't result in lots of messages being fetched again during
1344 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1346 if ((ok = internal_expunge(sock)))
1353 static int imap_mark_seen(int sock, struct query *ctl, int number)
1354 /* mark the given message as seen */
1358 /* expunges change the message numbers */
1361 return(gen_transact(sock,
1362 imap_version == IMAP4
1363 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1364 : "STORE %d +FLAGS (\\Seen)",
1368 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1369 /* cleanup mailbox before we idle or switch to another one */
1373 internal_expunge(sock);
1377 static int imap_logout(int sock, struct query *ctl)
1378 /* send logout command */
1381 /* if any un-expunged deletions remain, ship an expunge now */
1383 internal_expunge(sock);
1386 /* Memory clean-up */
1387 if (unseen_messages)
1388 free(unseen_messages);
1389 #endif /* USE_SEARCH */
1391 return(gen_transact(sock, "LOGOUT"));
1394 static const struct method imap =
1396 "IMAP", /* Internet Message Access Protocol */
1397 "imap", /* service (plain and TLS) */
1398 "imaps", /* service (SSL) */
1399 TRUE, /* this is a tagged protocol */
1400 FALSE, /* no message delimiter */
1401 imap_ok, /* parse command response */
1402 imap_getauth, /* get authorization */
1403 imap_getrange, /* query range of messages */
1404 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1405 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1406 imap_is_old, /* no UID check */
1407 imap_fetch_headers, /* request given message headers */
1408 imap_fetch_body, /* request given message body */
1409 imap_trail, /* eat message trailer */
1410 imap_delete, /* delete the message */
1411 imap_mark_seen, /* how to mark a message as seen */
1412 imap_end_mailbox_poll, /* end-of-mailbox processing */
1413 imap_logout, /* expunge and exit */
1414 TRUE, /* yes, we can re-poll */
1417 int doIMAP(struct query *ctl)
1418 /* retrieve messages using IMAP Version 2bis or Version 4 */
1420 return(do_protocol(ctl, &imap));
1423 /* imap.c ends here */