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 */
403 * Assumption: expunges are cheap, so we want to do them
404 * after every message unless user said otherwise.
406 if (NUM_SPECIFIED(ctl->expunge))
407 expunge_period = NUM_VALUE_OUT(ctl->expunge);
411 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 && 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 capa_probe(sock, ctl);
459 if (outlevel >= O_VERBOSE)
461 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
463 } else if (must_tls(ctl)) {
464 /* Config required TLS but we couldn't guarantee it, so we must
466 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
469 if (outlevel >= O_VERBOSE) {
470 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue\n"), commonname);
472 /* We don't know whether the connection is in a working state, so
473 * test by issuing a NOOP. */
474 if (gen_transact(sock, "NOOP") != PS_SUCCESS) {
475 /* Not usable. Empty sslproto to force an unencrypted
476 * connection on the next attempt, and repoll. */
477 ctl->sslproto = xstrdup("");
480 /* Usable. Proceed with authenticating insecurely. */
484 #endif /* SSL_ENABLE */
487 * Time to authenticate the user.
488 * Try the protocol variants that don't require passwords first.
492 /* Yahoo hack - we'll just try ID if it was offered by the server,
493 * and IGNORE errors. */
495 char *tmp = strstr(capabilities, " ID");
496 if (tmp && !isalnum((unsigned char)tmp[3]) && strstr(ctl->server.via ? ctl->server.via : ctl->server.pollname, "yahoo.com")) {
497 (void)gen_transact(sock, "ID (\"guid\" \"1\")");
501 if ((ctl->server.authenticate == A_ANY
502 || ctl->server.authenticate == A_EXTERNAL)
503 && strstr(capabilities, "AUTH=EXTERNAL"))
505 ok = do_authcert(sock, "AUTHENTICATE", ctl->remotename);
508 /* SASL cancellation of authentication */
510 if (ctl->server.authenticate != A_ANY)
518 if (((ctl->server.authenticate == A_ANY && check_gss_creds("imap", ctl->server.truename) == PS_SUCCESS)
519 || ctl->server.authenticate == A_GSSAPI)
520 && strstr(capabilities, "AUTH=GSSAPI"))
522 if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
523 ctl->server.truename, ctl->remotename)))
525 if (ctl->server.authenticate != A_ANY)
534 if ((ctl->server.authenticate == A_ANY
535 || ctl->server.authenticate == A_KERBEROS_V4
536 || ctl->server.authenticate == A_KERBEROS_V5)
537 && strstr(capabilities, "AUTH=KERBEROS_V4"))
539 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
541 /* SASL cancellation of authentication */
543 if(ctl->server.authenticate != A_ANY)
549 #endif /* KERBEROS_V4 */
552 * No such luck. OK, now try the variants that mask your password
553 * in a challenge-response.
556 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
557 || ctl->server.authenticate == A_CRAM_MD5)
559 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
561 if(ctl->server.authenticate != A_ANY)
569 if ((ctl->server.authenticate == A_ANY
570 || ctl->server.authenticate == A_OTP)
571 && strstr(capabilities, "AUTH=X-OTP")) {
572 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
574 /* SASL cancellation of authentication */
576 if(ctl->server.authenticate != A_ANY)
583 if (ctl->server.authenticate == A_OTP)
586 GT_("Required OTP capability not compiled into fetchmail\n"));
588 #endif /* OPIE_ENABLE */
591 if ((ctl->server.authenticate == A_ANY
592 || ctl->server.authenticate == A_NTLM)
593 && strstr (capabilities, "AUTH=NTLM")) {
594 if ((ok = do_imap_ntlm(sock, ctl)))
596 if(ctl->server.authenticate != A_ANY)
603 if (ctl->server.authenticate == A_NTLM)
606 GT_("Required NTLM capability not compiled into fetchmail\n"));
608 #endif /* NTLM_ENABLE */
610 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
611 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
612 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
615 GT_("Required LOGIN capability not supported by server\n"));
617 #endif /* __UNUSED__ */
620 * We're stuck with sending the password en clair.
621 * The reason for this odd-looking logic is that some
622 * servers return LOGINDISABLED even though login
623 * actually works. So arrange things in such a way that
624 * setting auth passwd makes it ignore this capability.
626 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
627 || ctl->server.authenticate == A_PASSWORD)
629 /* these sizes guarantee no buffer overflow */
630 char *remotename, *password;
632 rnl = 2 * strlen(ctl->remotename) + 1;
633 pwl = 2 * strlen(ctl->password) + 1;
634 remotename = (char *)xmalloc(rnl);
635 password = (char *)xmalloc(pwl);
637 imap_canonicalize(remotename, ctl->remotename, rnl);
638 imap_canonicalize(password, ctl->password, pwl);
640 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
641 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
642 memset(shroud, 0x55, sizeof(shroud));
644 memset(password, 0x55, strlen(password));
649 if(ctl->server.authenticate != A_ANY)
659 static int internal_expunge(int sock)
660 /* ship an expunge, resetting associated counters */
664 actual_deletions = 0;
666 if ((ok = gen_transact(sock, "EXPUNGE")))
669 /* if there is a mismatch between the number of mails which should
670 * have been expunged and the number of mails actually expunged,
671 * another email client may be deleting mails. Quit here,
672 * otherwise fetchmail gets out-of-sync with the imap server,
673 * reports the wrong size to the SMTP server on MAIL FROM: and
674 * triggers a "message ... was not the expected length" error on
675 * every subsequent mail */
676 if (deletions > 0 && deletions != actual_deletions)
679 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
680 actual_deletions, deletions);
685 expunged += deletions;
688 #ifdef IMAP_UID /* not used */
690 #endif /* IMAP_UID */
695 static int imap_idle(int sock)
696 /* start an RFC2177 IDLE, or fake one if unsupported */
700 saved_timeout = mytimeout;
703 /* special timeout to terminate the IDLE and re-issue it
704 * at least every 28 minutes:
705 * (the server may have an inactivity timeout) */
706 mytimeout = idle_timeout = 1680; /* 28 min */
707 time(&idle_start_time);
709 /* enter IDLE mode */
710 ok = gen_transact(sock, "IDLE");
712 if (ok == PS_IDLETIMEOUT) {
713 /* send "DONE" continuation */
714 SockWrite(sock, "DONE\r\n", 6);
715 if (outlevel >= O_MONITOR)
716 report(stdout, "IMAP> DONE\n");
717 /* reset stage and timeout here: we are not idling any more */
718 mytimeout = saved_timeout;
719 stage = STAGE_GETRANGE;
720 /* get OK IDLE message */
721 ok = imap_ok(sock, NULL);
723 } else { /* no idle support, fake it */
724 /* Note: stage and timeout have not been changed here as NOOP
726 ok = gen_transact(sock, "NOOP");
728 /* no error, but no new mail either */
729 if (ok == PS_SUCCESS && recentcount == 0)
731 /* There are some servers who do send new mail
732 * notification out of the blue. This is in compliance
733 * with RFC 2060 section 5.3. Wait for that with a low
735 mytimeout = idle_timeout = 28;
736 time(&idle_start_time);
738 /* We are waiting for notification; no tag needed */
740 /* wait (briefly) for an unsolicited status update */
741 ok = imap_ok(sock, NULL);
742 if (ok == PS_IDLETIMEOUT) {
743 /* no notification came; ok */
749 /* restore normal timeout value */
751 mytimeout = saved_timeout;
752 stage = STAGE_GETRANGE;
757 /* maximum number of numbers we can process in "SEARCH" response */
758 # define IMAP_SEARCH_MAX 1000
760 static int imap_search(int sock, struct query *ctl, int count)
761 /* search for unseen messages */
764 char buf[MSGBUFSIZE+1], *cp;
766 /* Don't count deleted messages. Enabled only for IMAP4 servers or
767 * higher and only when keeping mails. This flag will have an
768 * effect only when user has marked some unread mails for deletion
769 * using another e-mail client. */
770 flag skipdeleted = (imap_version >= IMAP4) && ctl->keep;
771 const char *undeleted;
773 /* Skip range search if there are less than or equal to
774 * IMAP_SEARCH_MAX mails. */
775 flag skiprangesearch = (count <= IMAP_SEARCH_MAX);
777 /* startcount is higher than count so that if there are no
778 * unseen messages, imap_getsizes() will not need to do
780 startcount = count + 1;
782 for (first = 1, last = IMAP_SEARCH_MAX; first <= count; first += IMAP_SEARCH_MAX, last += IMAP_SEARCH_MAX)
788 undeleted = (skipdeleted ? " UNDELETED" : "");
790 gen_send(sock, "SEARCH UNSEEN%s", undeleted);
791 else if (last == first)
792 gen_send(sock, "SEARCH %d UNSEEN%s", last, undeleted);
794 gen_send(sock, "SEARCH %d:%d UNSEEN%s", first, last, undeleted);
795 while ((ok = imap_response(sock, buf)) == 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 there is a protocol error on the first loop, try a
828 * different search command */
829 if (ok == PS_ERROR && first == 1)
833 /* retry with "SEARCH 1:1000 UNSEEN" */
837 if (!skiprangesearch)
839 /* retry with "SEARCH UNSEEN" */
840 skiprangesearch = TRUE;
843 /* try with "FETCH 1:n FLAGS" */
846 if (ok != PS_SUCCESS)
848 /* loop back only when searching in range */
856 gen_send(sock, "FETCH %d FLAGS", count);
858 gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
859 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
864 /* expected response format:
865 * IMAP< * 1 FETCH (FLAGS (\Seen))
866 * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
867 * IMAP< * 3 FETCH (FLAGS ())
868 * IMAP< * 4 FETCH (FLAGS (\Recent))
869 * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
872 && sscanf(buf, "* %u %n", &num, &consumed) == 1
873 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
874 && isspace((unsigned char)buf[consumed+5])
875 && num >= 1 && num <= (unsigned)count
876 && strstr(buf, "FLAGS ")
877 && !strstr(buf, "\\SEEN")
878 && !strstr(buf, "\\DELETED"))
880 unseen_messages[unseen++] = num;
881 if (outlevel >= O_DEBUG)
882 report(stdout, GT_("%u is unseen\n"), num);
883 if (startcount > num)
890 static int imap_getrange(int sock,
893 int *countp, int *newp, int *bytes)
894 /* get range of messages to be fetched */
898 /* find out how many messages are waiting */
903 /* deleted mails have already been expunged by
904 * end_mailbox_poll().
906 * recentcount is already set here by the last imap command which
907 * returned EXISTS on detecting new mail. if recentcount is 0, wait
910 * this is a while loop because imap_idle() might return on other
911 * mailbox changes also */
912 while (recentcount == 0 && do_idle) {
914 ok = imap_idle(sock);
917 report(stderr, GT_("re-poll failed\n"));
921 /* if recentcount is 0, return no mail */
922 if (recentcount == 0)
924 if (outlevel >= O_DEBUG)
925 report(stdout, ngettext("%d message waiting after re-poll\n",
926 "%d messages waiting after re-poll\n",
931 oldcount = count = 0;
932 ok = gen_transact(sock,
933 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
934 folder ? folder : "INBOX");
935 /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
936 * which we can safely use in fetchall keep only */
937 if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
942 report(stderr, GT_("mailbox selection failed\n"));
945 else if (outlevel >= O_DEBUG)
946 report(stdout, ngettext("%d message waiting after first poll\n",
947 "%d messages waiting after first poll\n",
951 * We should have an expunge here to
952 * a) avoid fetching deleted mails during 'fetchall'
953 * b) getting a wrong count of mails during 'no fetchall'
955 if (!check_only && !ctl->keep && count > 0)
957 ok = internal_expunge(sock);
960 report(stderr, GT_("expunge failed\n"));
963 if (outlevel >= O_DEBUG)
964 report(stdout, ngettext("%d message waiting after expunge\n",
965 "%d messages waiting after expunge\n",
969 if (count == 0 && do_idle)
971 /* no messages? then we may need to idle until we get some */
973 ok = imap_idle(sock);
976 report(stderr, GT_("re-poll failed\n"));
980 if (outlevel >= O_DEBUG)
981 report(stdout, ngettext("%d message waiting after re-poll\n",
982 "%d messages waiting after re-poll\n",
987 *countp = oldcount = count;
991 /* OK, now get a count of unseen messages and their indices */
992 if (!ctl->fetchall && count > 0)
995 free(unseen_messages);
996 unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
997 memset(unseen_messages, 0, count * sizeof(unsigned int));
1000 ok = imap_search(sock, ctl, count);
1003 report(stderr, GT_("search for unseen messages failed\n"));
1007 if (outlevel >= O_DEBUG && unseen > 0)
1008 report(stdout, GT_("%u is first unseen\n"), startcount);
1019 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
1020 /* capture the sizes of messages #first-#last */
1022 char buf [MSGBUFSIZE+1];
1026 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1027 * won't accept 1:1 as valid set syntax. Some implementors
1028 * should be taken out and shot for excessive anality.
1030 * Microsoft Exchange (brain-dead piece of crap that it is)
1031 * sometimes gets its knickers in a knot about bodiless messages.
1032 * You may see responses like this:
1034 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1035 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1036 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1037 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1038 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1039 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1040 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1041 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1042 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1043 * fetchmail: IMAP< A0004 NO The requested item could not be found.
1045 * This means message 1 has only headers. For kicks and grins
1046 * you can telnet in and look:
1048 * A003 NO The requested item could not be found.
1049 * A004 fetch 1 rfc822.header
1050 * A004 NO The requested item could not be found.
1052 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1053 * A006 OK FETCH completed.
1055 * To get around this, we treat the final NO as success and count
1056 * on the fact that the sizes array has been preinitialized with a
1057 * known-bad size value.
1060 /* expunges change the fetch numbers */
1065 gen_send(sock, "FETCH %d RFC822.SIZE", last);
1066 else if (last > first)
1067 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1068 else /* no unseen messages! */
1070 while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1077 /* expected response formats:
1078 * IMAP> A0005 FETCH 1 RFC822.SIZE
1079 * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1080 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1082 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1083 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1084 && isspace((unsigned char)buf[consumed + 5])
1085 && (ptr = strstr(buf, "RFC822.SIZE "))
1086 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1088 if (num >= first && num <= last)
1089 sizes[num - first] = size;
1092 GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1098 static int imap_getsizes(int sock, int count, int *sizes)
1099 /* capture the sizes of all messages */
1101 return imap_getpartialsizes(sock, 1, count, sizes);
1104 static int imap_is_old(int sock, struct query *ctl, int number)
1105 /* is the given message old? */
1113 * Expunges change the fetch numbers, but unseen_messages contains
1114 * indices from before any expungees were done. So neither the
1115 * argument nor the values in message_sequence need to be decremented.
1119 for (i = 0; i < unseen; i++)
1120 if (unseen_messages[i] == (unsigned)number)
1130 static char *skip_token(char *ptr)
1132 while(isspace((unsigned char)*ptr)) ptr++;
1133 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1134 while(isspace((unsigned char)*ptr)) ptr++;
1139 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1140 /* request headers of nth message */
1142 char buf [MSGBUFSIZE+1];
1148 /* expunges change the fetch numbers */
1152 * This is blessed by RFC1176, RFC1730, RFC2060.
1153 * According to the RFCs, it should *not* set the \Seen flag.
1155 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1157 /* looking for FETCH response */
1158 if ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1161 /* expected response formats:
1162 * IMAP> A0006 FETCH 1 RFC822.HEADER
1163 * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1164 * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1165 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1167 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1168 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1169 && isspace((unsigned char)buf[5+consumed])
1171 && (ptr = strstr(buf, "RFC822.HEADER"))
1172 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1173 && ptr[consumed-1] == '}')
1178 /* wait for a tagged response */
1181 /* try to recover for some responses */
1182 if (!strncmp(buf, "* NO", 4) ||
1183 !strncmp(buf, "* BAD", 5))
1185 return(PS_TRANSIENT);
1188 /* a response which does not match any of the above */
1189 if (outlevel > O_SILENT)
1190 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1193 else if (ok == PS_SUCCESS)
1195 /* an unexpected tagged response */
1196 if (outlevel > O_SILENT)
1197 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1203 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1204 /* request body of nth message */
1206 char buf [MSGBUFSIZE+1], *cp;
1210 /* expunges change the fetch numbers */
1214 * If we're using IMAP4, we can fetch the message without setting its
1215 * seen flag. This is good! It means that if the protocol exchange
1216 * craps out during the message, it will still be marked `unseen' on
1219 * According to RFC2060, and Mark Crispin the IMAP maintainer,
1220 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
1221 * equivalent". However, we know of at least one server that
1222 * treats them differently in the presence of MIME attachments;
1223 * the latter form downloads the attachment, the former does not.
1224 * The server is InterChange, and the fool who implemented this
1225 * misfeature ought to be strung up by his thumbs.
1227 * When I tried working around this by disabling use of the 4rev1 form,
1228 * I found that doing this breaks operation with M$ Exchange.
1229 * Annoyingly enough, Exchange's refusal to cope is technically legal
1230 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
1231 * standards, to find a way to make standards compliance irritating....
1233 switch (imap_version)
1235 case IMAP4rev1: /* RFC 2060 */
1236 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1239 case IMAP4: /* RFC 1730 */
1240 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1243 default: /* RFC 1176 */
1244 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1248 /* looking for FETCH response */
1252 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1255 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1260 /* Understand "NIL" as length => no body present
1261 * (MS Exchange, BerliOS Bug #11980) */
1262 if (strstr(buf+10, "NIL)")) {
1267 /* Understand the empty string. Seen on Yahoo. */
1268 /* XXX FIXME: we should be able to handle strings here. */
1269 if (strstr(buf+10, "\"\")")) {
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 */