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, struct RecvSplit *rs)
183 /* parse command response */
185 char buf[MSGBUFSIZE+1];
192 ok = gen_recv_split(sock, buf, sizeof(buf), rs);
194 ok = gen_recv(sock, buf, sizeof(buf));
195 if (ok != PS_SUCCESS)
198 /* all tokens in responses are caseblind */
199 for (cp = buf; *cp; cp++)
200 if (islower((unsigned char)*cp))
201 *cp = toupper((unsigned char)*cp);
203 /* untagged responses start with "* " */
204 if (buf[0] == '*' && buf[1] == ' ') {
205 ok = imap_untagged_response(sock, buf);
206 if (ok == PS_UNTAGGED)
208 if (argbuf && stage != STAGE_IDLE && tag[0] != '\0')
210 /* if there is an unmatched response, pass it back to
211 * the calling function for further analysis. The
212 * calling function should call imap_response() again
213 * to read the remaining response */
218 else if (ok != PS_SUCCESS)
222 if (stage == STAGE_IDLE)
224 /* reduce the timeout: servers may not reset their timeout
225 * when they send some information asynchronously */
226 mytimeout = idle_timeout - (time((time_t *) NULL) - idle_start_time);
228 return(PS_IDLETIMEOUT);
231 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
244 for (cp = buf; !isspace((unsigned char)*cp); cp++)
246 while (isspace((unsigned char)*cp))
249 if (strncasecmp(cp, "OK", 2) == 0)
255 else if (strncasecmp(cp, "BAD", 3) == 0)
257 else if (strncasecmp(cp, "NO", 2) == 0)
259 if (stage == STAGE_GETAUTH)
260 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
261 else if (stage == STAGE_GETSIZES)
262 return(PS_SUCCESS); /* see comments in imap_getpartialsizes() */
271 static int imap_ok(int sock, char *argbuf)
272 /* parse command response */
276 while ((ok = imap_response(sock, argbuf, NULL)) == PS_UNTAGGED)
277 ; /* wait for the tagged response */
285 * NTLM support by Grant Edwards.
287 * Handle MS-Exchange NTLM authentication method. This is the same
288 * as the NTLM auth used by Samba for SMB related services. We just
289 * encode the packets in base64 instead of sending them out via a
292 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
295 static int do_imap_ntlm(int sock, struct query *ctl)
299 gen_send(sock, "AUTHENTICATE NTLM");
301 if ((result = ntlm_helper(sock, ctl, "IMAP")))
304 result = imap_ok (sock, NULL);
305 if (result == PS_SUCCESS)
312 static void imap_canonicalize(char *result, char *raw, size_t maxlen)
313 /* encode an IMAP password as per RFC1730's quoting conventions */
318 for (i = 0; i < strlen(raw) && i < maxlen; i++)
320 if ((raw[i] == '\\') || (raw[i] == '"'))
322 result[j++] = raw[i];
327 static int capa_probe(int sock, struct query *ctl)
328 /* set capability variables from a CAPA probe */
332 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
333 capabilities[0] = '\0';
334 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
338 /* capability checks are supposed to be caseblind */
339 for (cp = capabilities; *cp; cp++)
340 *cp = toupper((unsigned char)*cp);
342 /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
343 should expect a response in mixed-case */
344 if (strstr(capabilities, "IMAP4REV1"))
346 imap_version = IMAP4rev1;
347 if (outlevel >= O_DEBUG)
348 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
352 imap_version = IMAP4;
353 if (outlevel >= O_DEBUG)
354 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
357 else if (ok == PS_ERROR)
359 imap_version = IMAP2;
360 if (outlevel >= O_DEBUG)
361 report(stdout, GT_("Protocol identified as IMAP2 or IMAP2BIS\n"));
367 * Handle idling. We depend on coming through here on startup
368 * and after each timeout (including timeouts during idles).
373 if (strstr(capabilities, "IDLE"))
377 if (outlevel >= O_VERBOSE)
378 report(stdout, GT_("will idle after poll\n"));
381 peek_capable = (imap_version >= IMAP4);
386 static int do_authcert (int sock, const char *command, const char *name)
387 /* do authentication "external" (authentication provided by client cert) */
393 size_t len = strlen(name);
394 if ((len / 3) + ((len % 3) ? 4 : 0) < sizeof(buf))
395 to64frombits (buf, name, strlen(name));
397 return PS_AUTHFAIL; /* buffer too small. */
401 return gen_transact(sock, "%s EXTERNAL %s",command,buf);
404 static int imap_getauth(int sock, struct query *ctl, char *greeting)
405 /* apply for connection authorization */
411 * Assumption: expunges are cheap, so we want to do them
412 * after every message unless user said otherwise.
414 if (NUM_SPECIFIED(ctl->expunge))
415 expunge_period = NUM_VALUE_OUT(ctl->expunge);
419 if ((ok = capa_probe(sock, ctl)))
423 * If either (a) we saw a PREAUTH token in the greeting, or
424 * (b) the user specified ssh preauthentication, then we're done.
426 if (preauth || ctl->server.authenticate == A_SSH)
428 preauth = FALSE; /* reset for the next session */
433 if (maybe_tls(ctl)) {
436 commonname = ctl->server.pollname;
438 commonname = ctl->server.via;
439 if (ctl->sslcommonname)
440 commonname = ctl->sslcommonname;
442 if (strstr(capabilities, "STARTTLS")
443 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
445 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
446 * protocol that will work with STARTTLS. Don't need to worry
447 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
449 if (gen_transact(sock, "STARTTLS") == PS_SUCCESS
450 && (set_timeout(mytimeout), SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
451 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
452 ctl->server.pollname, &ctl->remotename)) != -1)
455 * RFC 2595 says this:
457 * "Once TLS has been started, the client MUST discard cached
458 * information about server capabilities and SHOULD re-issue the
459 * CAPABILITY command. This is necessary to protect against
460 * man-in-the-middle attacks which alter the capabilities list prior
461 * to STARTTLS. The server MAY advertise different capabilities
464 * Now that we're confident in our TLS connection we can
465 * guarantee a secure capability re-probe.
467 if ((ok = capa_probe(sock, ctl)))
469 if (outlevel >= O_VERBOSE)
471 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
473 } else if (must_tls(ctl)) {
474 /* Config required TLS but we couldn't guarantee it, so we must
477 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
481 if (outlevel >= O_VERBOSE) {
482 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue\n"), commonname);
484 /* We don't know whether the connection is in a working state, so
485 * test by issuing a NOOP. */
486 if (gen_transact(sock, "NOOP") != PS_SUCCESS) {
487 /* Not usable. Empty sslproto to force an unencrypted
488 * connection on the next attempt, and repoll. */
489 ctl->sslproto = xstrdup("");
492 /* Usable. Proceed with authenticating insecurely. */
496 #endif /* SSL_ENABLE */
499 * Time to authenticate the user.
500 * Try the protocol variants that don't require passwords first.
504 /* Yahoo hack - we'll just try ID if it was offered by the server,
505 * and IGNORE errors. */
507 char *tmp = strstr(capabilities, " ID");
508 if (tmp && !isalnum((unsigned char)tmp[3]) && strstr(ctl->server.via ? ctl->server.via : ctl->server.pollname, "yahoo.com")) {
509 (void)gen_transact(sock, "ID (\"guid\" \"1\")");
513 if ((ctl->server.authenticate == A_ANY
514 || ctl->server.authenticate == A_EXTERNAL)
515 && strstr(capabilities, "AUTH=EXTERNAL"))
517 ok = do_authcert(sock, "AUTHENTICATE", ctl->remotename);
520 /* SASL cancellation of authentication */
522 if (ctl->server.authenticate != A_ANY)
530 if (((ctl->server.authenticate == A_ANY && check_gss_creds("imap", ctl->server.truename) == PS_SUCCESS)
531 || ctl->server.authenticate == A_GSSAPI)
532 && strstr(capabilities, "AUTH=GSSAPI"))
534 if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
535 ctl->server.truename, ctl->remotename)))
537 if (ctl->server.authenticate != A_ANY)
546 if ((ctl->server.authenticate == A_ANY
547 || ctl->server.authenticate == A_KERBEROS_V4
548 || ctl->server.authenticate == A_KERBEROS_V5)
549 && strstr(capabilities, "AUTH=KERBEROS_V4"))
551 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
553 /* SASL cancellation of authentication */
555 if(ctl->server.authenticate != A_ANY)
561 #endif /* KERBEROS_V4 */
564 * No such luck. OK, now try the variants that mask your password
565 * in a challenge-response.
568 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
569 || ctl->server.authenticate == A_CRAM_MD5)
571 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
573 if(ctl->server.authenticate != A_ANY)
581 if ((ctl->server.authenticate == A_ANY
582 || ctl->server.authenticate == A_OTP)
583 && strstr(capabilities, "AUTH=X-OTP")) {
584 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
586 /* SASL cancellation of authentication */
588 if(ctl->server.authenticate != A_ANY)
595 if (ctl->server.authenticate == A_OTP)
598 GT_("Required OTP capability not compiled into fetchmail\n"));
600 #endif /* OPIE_ENABLE */
603 if ((ctl->server.authenticate == A_ANY
604 || ctl->server.authenticate == A_NTLM)
605 && strstr (capabilities, "AUTH=NTLM")) {
606 if ((ok = do_imap_ntlm(sock, ctl)))
608 if(ctl->server.authenticate != A_ANY)
615 if (ctl->server.authenticate == A_NTLM)
618 GT_("Required NTLM capability not compiled into fetchmail\n"));
620 #endif /* NTLM_ENABLE */
622 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
623 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
624 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
627 GT_("Required LOGIN capability not supported by server\n"));
629 #endif /* __UNUSED__ */
632 * We're stuck with sending the password en clair.
633 * The reason for this odd-looking logic is that some
634 * servers return LOGINDISABLED even though login
635 * actually works. So arrange things in such a way that
636 * setting auth passwd makes it ignore this capability.
638 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
639 || ctl->server.authenticate == A_PASSWORD)
641 /* these sizes guarantee no buffer overflow */
642 char *remotename, *password;
644 rnl = 2 * strlen(ctl->remotename) + 1;
645 pwl = 2 * strlen(ctl->password) + 1;
646 remotename = (char *)xmalloc(rnl);
647 password = (char *)xmalloc(pwl);
649 imap_canonicalize(remotename, ctl->remotename, rnl);
650 imap_canonicalize(password, ctl->password, pwl);
652 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
653 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
654 memset(shroud, 0x55, sizeof(shroud));
656 memset(password, 0x55, strlen(password));
661 if(ctl->server.authenticate != A_ANY)
671 static int internal_expunge(int sock)
672 /* ship an expunge, resetting associated counters */
676 actual_deletions = 0;
678 if ((ok = gen_transact(sock, "EXPUNGE")))
681 /* if there is a mismatch between the number of mails which should
682 * have been expunged and the number of mails actually expunged,
683 * another email client may be deleting mails. Quit here,
684 * otherwise fetchmail gets out-of-sync with the imap server,
685 * reports the wrong size to the SMTP server on MAIL FROM: and
686 * triggers a "message ... was not the expected length" error on
687 * every subsequent mail */
688 if (deletions > 0 && deletions != actual_deletions)
691 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
692 actual_deletions, deletions);
697 expunged += deletions;
700 #ifdef IMAP_UID /* not used */
702 #endif /* IMAP_UID */
707 static int imap_idle(int sock)
708 /* start an RFC2177 IDLE, or fake one if unsupported */
712 saved_timeout = mytimeout;
715 /* special timeout to terminate the IDLE and re-issue it
716 * at least every 28 minutes:
717 * (the server may have an inactivity timeout) */
718 mytimeout = idle_timeout = 1680; /* 28 min */
719 time(&idle_start_time);
721 /* enter IDLE mode */
722 ok = gen_transact(sock, "IDLE");
724 if (ok == PS_IDLETIMEOUT) {
725 /* send "DONE" continuation */
726 SockWrite(sock, "DONE\r\n", 6);
727 if (outlevel >= O_MONITOR)
728 report(stdout, "IMAP> DONE\n");
729 /* reset stage and timeout here: we are not idling any more */
730 mytimeout = saved_timeout;
731 stage = STAGE_GETRANGE;
732 /* get OK IDLE message */
733 ok = imap_ok(sock, NULL);
735 } else { /* no idle support, fake it */
736 /* Note: stage and timeout have not been changed here as NOOP
738 ok = gen_transact(sock, "NOOP");
740 /* no error, but no new mail either */
741 if (ok == PS_SUCCESS && recentcount == 0)
743 /* There are some servers who do send new mail
744 * notification out of the blue. This is in compliance
745 * with RFC 2060 section 5.3. Wait for that with a low
747 mytimeout = idle_timeout = 28;
748 time(&idle_start_time);
750 /* We are waiting for notification; no tag needed */
752 /* wait (briefly) for an unsolicited status update */
753 ok = imap_ok(sock, NULL);
754 if (ok == PS_IDLETIMEOUT) {
755 /* no notification came; ok */
761 /* restore normal timeout value */
763 mytimeout = saved_timeout;
764 stage = STAGE_GETRANGE;
769 static int imap_search(int sock, struct query *ctl, int count)
770 /* search for unseen messages */
773 char buf[MSGBUFSIZE+1], *cp;
775 /* Don't count deleted messages. Enabled only for IMAP4 servers or
776 * higher and only when keeping mails. This flag will have an
777 * effect only when user has marked some unread mails for deletion
778 * using another e-mail client. */
779 flag skipdeleted = (imap_version >= IMAP4) && ctl->keep;
780 const char *undeleted;
782 /* structure to keep the end portion of the incomplete response */
785 /* startcount is higher than count so that if there are no
786 * unseen messages, imap_getsizes() will not need to do
788 startcount = count + 1;
792 undeleted = (skipdeleted ? " UNDELETED" : "");
793 gen_send(sock, "SEARCH UNSEEN%s", undeleted);
794 gen_recv_split_init("* SEARCH", &rs);
795 while ((ok = imap_response(sock, buf, &rs)) == PS_UNTAGGED)
797 if ((cp = strstr(buf, "* SEARCH")))
801 cp += 8; /* skip "* SEARCH" */
802 while (*cp && unseen < count)
804 /* skip whitespace */
805 while (*cp && isspace((unsigned char)*cp))
812 um = strtoul(cp,&ep,10);
813 if (errno == 0 && ep > cp
814 && um <= INT_MAX && um <= (unsigned)count)
816 unseen_messages[unseen++] = um;
817 if (outlevel >= O_DEBUG)
818 report(stdout, GT_("%lu is unseen\n"), um);
827 if (ok != PS_ERROR) /* success or non-protocol error */
830 /* there is a protocol error. try a different search command. */
833 /* retry with "SEARCH UNSEEN" */
837 /* try with "FETCH 1:n FLAGS" */
842 gen_send(sock, "FETCH %d FLAGS", count);
844 gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
845 while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
850 /* expected response format:
851 * IMAP< * 1 FETCH (FLAGS (\Seen))
852 * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
853 * IMAP< * 3 FETCH (FLAGS ())
854 * IMAP< * 4 FETCH (FLAGS (\Recent))
855 * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
858 && sscanf(buf, "* %u %n", &num, &consumed) == 1
859 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
860 && isspace((unsigned char)buf[consumed+5])
861 && num >= 1 && num <= (unsigned)count
862 && strstr(buf, "FLAGS ")
863 && !strstr(buf, "\\SEEN")
864 && !strstr(buf, "\\DELETED"))
866 unseen_messages[unseen++] = num;
867 if (outlevel >= O_DEBUG)
868 report(stdout, GT_("%u is unseen\n"), num);
869 if (startcount > num)
876 static int imap_getrange(int sock,
879 int *countp, int *newp, int *bytes)
880 /* get range of messages to be fetched */
884 /* find out how many messages are waiting */
889 /* deleted mails have already been expunged by
890 * end_mailbox_poll().
892 * recentcount is already set here by the last imap command which
893 * returned EXISTS on detecting new mail. if recentcount is 0, wait
896 * this is a while loop because imap_idle() might return on other
897 * mailbox changes also */
898 while (recentcount == 0 && do_idle) {
900 ok = imap_idle(sock);
903 report(stderr, GT_("re-poll failed\n"));
907 /* if recentcount is 0, return no mail */
908 if (recentcount == 0)
910 if (outlevel >= O_DEBUG)
911 report(stdout, ngettext("%d message waiting after re-poll\n",
912 "%d messages waiting after re-poll\n",
917 oldcount = count = 0;
918 ok = gen_transact(sock,
919 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
920 folder ? folder : "INBOX");
921 /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
922 * which we can safely use in fetchall keep only */
923 if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
928 report(stderr, GT_("mailbox selection failed\n"));
931 else if (outlevel >= O_DEBUG)
932 report(stdout, ngettext("%d message waiting after first poll\n",
933 "%d messages waiting after first poll\n",
937 * We should have an expunge here to
938 * a) avoid fetching deleted mails during 'fetchall'
939 * b) getting a wrong count of mails during 'no fetchall'
941 if (!check_only && !ctl->keep && count > 0)
943 ok = internal_expunge(sock);
946 report(stderr, GT_("expunge failed\n"));
949 if (outlevel >= O_DEBUG)
950 report(stdout, ngettext("%d message waiting after expunge\n",
951 "%d messages waiting after expunge\n",
955 if (count == 0 && do_idle)
957 /* no messages? then we may need to idle until we get some */
959 ok = imap_idle(sock);
962 report(stderr, GT_("re-poll failed\n"));
966 if (outlevel >= O_DEBUG)
967 report(stdout, ngettext("%d message waiting after re-poll\n",
968 "%d messages waiting after re-poll\n",
973 *countp = oldcount = count;
977 /* OK, now get a count of unseen messages and their indices */
978 if (!ctl->fetchall && count > 0)
981 free(unseen_messages);
982 unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
983 memset(unseen_messages, 0, count * sizeof(unsigned int));
986 ok = imap_search(sock, ctl, count);
989 report(stderr, GT_("search for unseen messages failed\n"));
993 if (outlevel >= O_DEBUG && unseen > 0)
994 report(stdout, GT_("%u is first unseen\n"), startcount);
1005 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
1006 /* capture the sizes of messages #first-#last */
1008 char buf [MSGBUFSIZE+1];
1012 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1013 * won't accept 1:1 as valid set syntax. Some implementors
1014 * should be taken out and shot for excessive anality.
1016 * Microsoft Exchange (brain-dead piece of crap that it is)
1017 * sometimes gets its knickers in a knot about bodiless messages.
1018 * You may see responses like this:
1020 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1021 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1022 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1023 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1024 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1025 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1026 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1027 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1028 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1029 * fetchmail: IMAP< A0004 NO The requested item could not be found.
1031 * This means message 1 has only headers. For kicks and grins
1032 * you can telnet in and look:
1034 * A003 NO The requested item could not be found.
1035 * A004 fetch 1 rfc822.header
1036 * A004 NO The requested item could not be found.
1038 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1039 * A006 OK FETCH completed.
1041 * To get around this, we treat the final NO as success and count
1042 * on the fact that the sizes array has been preinitialized with a
1043 * known-bad size value.
1046 /* expunges change the fetch numbers */
1051 gen_send(sock, "FETCH %d RFC822.SIZE", last);
1052 else if (last > first)
1053 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1054 else /* no unseen messages! */
1056 while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
1063 /* expected response formats:
1064 * IMAP> A0005 FETCH 1 RFC822.SIZE
1065 * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1066 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1068 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1069 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1070 && isspace((unsigned char)buf[consumed + 5])
1071 && (ptr = strstr(buf, "RFC822.SIZE "))
1072 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1074 if (num >= first && num <= last)
1075 sizes[num - first] = size;
1078 GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1084 static int imap_getsizes(int sock, int count, int *sizes)
1085 /* capture the sizes of all messages */
1087 return imap_getpartialsizes(sock, 1, count, sizes);
1090 static int imap_is_old(int sock, struct query *ctl, int number)
1091 /* is the given message old? */
1099 * Expunges change the fetch numbers, but unseen_messages contains
1100 * indices from before any expungees were done. So neither the
1101 * argument nor the values in message_sequence need to be decremented.
1105 for (i = 0; i < unseen; i++)
1106 if (unseen_messages[i] == (unsigned)number)
1116 static char *skip_token(char *ptr)
1118 while(isspace((unsigned char)*ptr)) ptr++;
1119 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1120 while(isspace((unsigned char)*ptr)) ptr++;
1125 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1126 /* request headers of nth message */
1128 char buf [MSGBUFSIZE+1];
1134 /* expunges change the fetch numbers */
1138 * This is blessed by RFC1176, RFC1730, RFC2060.
1139 * According to the RFCs, it should *not* set the \Seen flag.
1141 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1143 /* looking for FETCH response */
1144 if ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
1147 /* expected response formats:
1148 * IMAP> A0006 FETCH 1 RFC822.HEADER
1149 * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1150 * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1151 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1153 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1154 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1155 && isspace((unsigned char)buf[5+consumed])
1157 && (ptr = strstr(buf, "RFC822.HEADER"))
1158 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1159 && ptr[consumed-1] == '}')
1164 /* wait for a tagged response */
1167 /* try to recover for some responses */
1168 if (!strncmp(buf, "* NO", 4) ||
1169 !strncmp(buf, "* BAD", 5) ||
1170 strstr(buf, "FETCH ()"))
1172 return(PS_TRANSIENT);
1175 /* a response which does not match any of the above */
1176 if (outlevel > O_SILENT)
1177 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1180 else if (ok == PS_SUCCESS)
1182 /* an unexpected tagged response */
1183 if (outlevel > O_SILENT)
1184 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1185 return(PS_TRANSIENT);
1190 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1191 /* request body of nth message */
1193 char buf [MSGBUFSIZE+1], *cp;
1197 /* expunges change the fetch numbers */
1201 * If we're using IMAP4, we can fetch the message without setting its
1202 * seen flag. This is good! It means that if the protocol exchange
1203 * craps out during the message, it will still be marked `unseen' on
1206 * According to RFC2060, and Mark Crispin the IMAP maintainer,
1207 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
1208 * equivalent". However, we know of at least one server that
1209 * treats them differently in the presence of MIME attachments;
1210 * the latter form downloads the attachment, the former does not.
1211 * The server is InterChange, and the fool who implemented this
1212 * misfeature ought to be strung up by his thumbs.
1214 * When I tried working around this by disabling use of the 4rev1 form,
1215 * I found that doing this breaks operation with M$ Exchange.
1216 * Annoyingly enough, Exchange's refusal to cope is technically legal
1217 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
1218 * standards, to find a way to make standards compliance irritating....
1220 switch (imap_version)
1222 case IMAP4rev1: /* RFC 2060 */
1223 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1226 case IMAP4: /* RFC 1730 */
1227 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1230 default: /* RFC 1176 */
1231 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1235 /* looking for FETCH response */
1239 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1242 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1247 /* Understand "NIL" as length => no body present
1248 * (MS Exchange, BerliOS Bug #11980) */
1249 if (strstr(buf+10, "NIL)")) {
1254 /* Understand the empty string. Seen on Yahoo. */
1255 /* XXX FIXME: we should be able to handle strings here. */
1256 if (strstr(buf+10, "\"\")")) {
1262 * Try to extract a length from the FETCH response. RFC2060 requires
1263 * it to be present, but at least one IMAP server (Novell GroupWise)
1264 * botches this. The overflow check is needed because of a broken
1265 * server called dbmail that returns huge garbage lengths.
1267 if ((cp = strchr(buf, '{'))) {
1271 l = strtol(cp, &t, 10);
1272 if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1273 || l < 0 || l > INT_MAX /* range check */) {
1279 *lenp = -1; /* missing length part in FETCH reponse */
1285 static int imap_trail(int sock, struct query *ctl, const char *tag)
1286 /* discard tail of FETCH response after reading message text */
1288 /* expunges change the fetch numbers */
1289 /* number -= expunged; */
1294 return imap_ok(sock, NULL);
1297 static int imap_delete(int sock, struct query *ctl, int number)
1298 /* set delete flag for given message */
1301 /* Select which flags to set on message deletion: */
1302 const char delflags_seen[] = "\\Seen \\Deleted";
1303 static const char *delflags;
1304 /* Which environment variable to look for: */
1306 /* DEFAULT since many fetchmail versions <= 6.3.X */
1307 delflags = delflags_seen;
1310 /* expunges change the fetch numbers */
1314 * Use SILENT if possible as a minor throughput optimization.
1315 * Note: this has been dropped from IMAP4rev1.
1317 * We set \Seen because there are some IMAP servers (notably HP
1318 * OpenMail and MS Exchange) do message-receipt DSNs,
1319 * but only when the seen bit gets set.
1320 * This is the appropriate time -- we get here right
1321 * after the local SMTP response that says delivery was
1324 if ((ok = gen_transact(sock,
1325 imap_version == IMAP4
1326 ? "STORE %d +FLAGS.SILENT (%s)"
1327 : "STORE %d +FLAGS (%s)",
1334 * We do an expunge after expunge_period messages, rather than
1335 * just before quit, so that a line hit during a long session
1336 * won't result in lots of messages being fetched again during
1339 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1341 if ((ok = internal_expunge(sock)))
1348 static int imap_mark_seen(int sock, struct query *ctl, int number)
1349 /* mark the given message as seen */
1353 /* expunges change the message numbers */
1356 return(gen_transact(sock,
1357 imap_version == IMAP4
1358 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1359 : "STORE %d +FLAGS (\\Seen)",
1363 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1364 /* cleanup mailbox before we idle or switch to another one */
1368 internal_expunge(sock);
1372 static int imap_logout(int sock, struct query *ctl)
1373 /* send logout command */
1376 /* if any un-expunged deletions remain, ship an expunge now */
1378 internal_expunge(sock);
1381 /* Memory clean-up */
1382 if (unseen_messages)
1383 free(unseen_messages);
1384 #endif /* USE_SEARCH */
1386 return(gen_transact(sock, "LOGOUT"));
1389 static const struct method imap =
1391 "IMAP", /* Internet Message Access Protocol */
1392 "imap", /* service (plain and TLS) */
1393 "imaps", /* service (SSL) */
1394 TRUE, /* this is a tagged protocol */
1395 FALSE, /* no message delimiter */
1396 imap_ok, /* parse command response */
1397 imap_getauth, /* get authorization */
1398 imap_getrange, /* query range of messages */
1399 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1400 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1401 imap_is_old, /* no UID check */
1402 imap_fetch_headers, /* request given message headers */
1403 imap_fetch_body, /* request given message body */
1404 imap_trail, /* eat message trailer */
1405 imap_delete, /* delete the message */
1406 imap_mark_seen, /* how to mark a message as seen */
1407 imap_end_mailbox_poll, /* end-of-mailbox processing */
1408 imap_logout, /* expunge and exit */
1409 TRUE, /* yes, we can re-poll */
1412 int doIMAP(struct query *ctl)
1413 /* retrieve messages using IMAP Version 2bis or Version 4 */
1415 return(do_protocol(ctl, &imap));
1418 /* imap.c ends here */