2 * imap.c -- IMAP2bis/IMAP4 protocol methods
4 * Copyright 1997 by Eric S. Raymond
5 * For license terms, see the file COPYING in this directory.
16 #include "fetchmail.h"
21 /* imap_version values */
22 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
23 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
25 /* global variables: please reinitialize them explicitly for proper
26 * working in daemon mode */
28 /* TODO: session variables to be initialized before server greeting */
29 static int preauth = FALSE;
31 /* session variables initialized in capa_probe() or imap_getauth() */
32 static char capabilities[MSGBUFSIZE+1];
33 static int imap_version = IMAP4;
34 static flag do_idle = FALSE, has_idle = FALSE;
35 static int expunge_period = 1;
37 /* mailbox variables initialized in imap_getrange() */
38 static int count = 0, oldcount = 0, recentcount = 0, unseen = 0, deletions = 0;
39 static unsigned int startcount = 1;
40 static int expunged = 0;
41 static unsigned int *unseen_messages;
43 /* for "IMAP> EXPUNGE" */
44 static int actual_deletions = 0;
46 /* for "IMAP> IDLE" */
47 static int saved_timeout = 0, idle_timeout = 0;
48 static time_t idle_start_time = 0;
50 static int imap_untagged_response(int sock, const char *buf)
51 /* interpret untagged status responses */
53 /* For each individual check, use a BLANK before the word to avoid
54 * confusion with the \Recent flag or similar */
55 if (stage == STAGE_GETAUTH
56 && !strncmp(buf, "* CAPABILITY", 12))
58 strlcpy(capabilities, buf + 12, sizeof(capabilities));
60 else if (stage == STAGE_GETAUTH
61 && !strncmp(buf, "* PREAUTH", 9))
65 else if (stage != STAGE_LOGOUT
66 && !strncmp(buf, "* BYE", 5))
68 /* log the unexpected bye from server as we expect the
69 * connection to be cut-off after this */
70 if (outlevel > O_SILENT)
71 report(stderr, GT_("Received BYE response from IMAP server: %s"), buf + 5);
73 else if (strstr(buf, " EXISTS"))
75 char *t; unsigned long u;
77 u = strtoul(buf+2, &t, 10);
79 * Don't trust the message count passed by the server.
80 * Without this check, it might be possible to do a
81 * DNS-spoofing attack that would pass back a ridiculous
82 * count, and allocate a malloc area that would overlap
83 * a portion of the stack.
85 if (errno /* strtoul failed */
86 || t == buf+2 /* no valid data */
87 || u > (unsigned long)(INT_MAX/sizeof(int)) /* too large */)
89 report(stderr, GT_("bogus message count in \"%s\"!"), buf);
92 count = u; /* safe as long as count <= INT_MAX - checked above */
94 if ((recentcount = count - oldcount) < 0)
98 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
99 * we can't wait for the tag matching the IDLE; we have to tell the
100 * server the IDLE is finished by shipping back a DONE when we
101 * see an EXISTS. Only after that will a tagged response be
102 * shipped. The idling flag also gets cleared on a timeout.
104 if (stage == STAGE_IDLE)
106 /* If IDLE isn't supported, we were only sending NOOPs anyway. */
109 /* we do our own write and report here to disable tagging */
110 SockWrite(sock, "DONE\r\n", 6);
111 if (outlevel >= O_MONITOR)
112 report(stdout, "IMAP> DONE\n");
115 mytimeout = saved_timeout;
116 stage = STAGE_GETRANGE;
119 /* we now compute recentcount as a difference between
120 * new and old EXISTS, hence disable RECENT check */
122 else if (strstr(buf, " RECENT"))
124 /* fixme: use strto[u]l and error checking */
125 recentcount = atoi(buf+2);
128 else if (strstr(buf, " EXPUNGE"))
130 unsigned long u; char *t;
131 /* the response "* 10 EXPUNGE" means that the currently
132 * tenth (i.e. only one) message has been deleted */
134 u = strtoul(buf+2, &t, 10);
135 if (errno /* conversion error */ || t == buf+2 /* no number found */) {
136 report(stderr, GT_("bogus EXPUNGE count in \"%s\"!"), buf);
145 /* We do expect an EXISTS response immediately
146 * after this, so this updation of recentcount is
147 * just a precaution! */
148 if ((recentcount = count - oldcount) < 0)
154 * The server may decide to make the mailbox read-only,
155 * which causes fetchmail to go into a endless loop
156 * fetching the same message over and over again.
158 * However, for check_only, we use EXAMINE which will
159 * mark the mailbox read-only as per the RFC.
161 * This checks for the condition and aborts if
162 * the mailbox is read-only.
164 * See RFC 2060 section 6.3.1 (SELECT).
165 * See RFC 2060 section 6.3.2 (EXAMINE).
167 else if (stage == STAGE_GETRANGE
168 && !check_only && strstr(buf, "[READ-ONLY]"))
179 static int imap_response(int sock, char *argbuf, struct RecvSplit *rs)
180 /* parse command response */
182 char buf[MSGBUFSIZE+1];
189 ok = gen_recv_split(sock, buf, sizeof(buf), rs);
191 ok = gen_recv(sock, buf, sizeof(buf));
192 if (ok != PS_SUCCESS)
195 /* all tokens in responses are caseblind */
196 for (cp = buf; *cp; cp++)
197 if (islower((unsigned char)*cp))
198 *cp = toupper((unsigned char)*cp);
200 /* untagged responses start with "* " */
201 if (buf[0] == '*' && buf[1] == ' ') {
202 ok = imap_untagged_response(sock, buf);
203 if (ok == PS_UNTAGGED)
205 if (argbuf && stage != STAGE_IDLE && tag[0] != '\0')
207 /* if there is an unmatched response, pass it back to
208 * the calling function for further analysis. The
209 * calling function should call imap_response() again
210 * to read the remaining response */
215 else if (ok != PS_SUCCESS)
219 if (stage == STAGE_IDLE)
221 /* reduce the timeout: servers may not reset their timeout
222 * when they send some information asynchronously */
223 mytimeout = idle_timeout - (time((time_t *) NULL) - idle_start_time);
225 return(PS_IDLETIMEOUT);
228 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
241 for (cp = buf; !isspace((unsigned char)*cp); cp++)
243 while (isspace((unsigned char)*cp))
246 if (strncasecmp(cp, "OK", 2) == 0)
252 else if (strncasecmp(cp, "BAD", 3) == 0)
254 else if (strncasecmp(cp, "NO", 2) == 0)
256 if (stage == STAGE_GETAUTH)
257 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
258 else if (stage == STAGE_GETSIZES)
259 return(PS_SUCCESS); /* see comments in imap_getpartialsizes() */
268 static int imap_ok(int sock, char *argbuf)
269 /* parse command response */
273 while ((ok = imap_response(sock, argbuf, NULL)) == PS_UNTAGGED)
274 ; /* wait for the tagged response */
282 * NTLM support by Grant Edwards.
284 * Handle MS-Exchange NTLM authentication method. This is the same
285 * as the NTLM auth used by Samba for SMB related services. We just
286 * encode the packets in base64 instead of sending them out via a
289 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
292 static int do_imap_ntlm(int sock, struct query *ctl)
296 gen_send(sock, "AUTHENTICATE NTLM");
298 if ((result = ntlm_helper(sock, ctl, "IMAP")))
301 result = imap_ok (sock, NULL);
302 if (result == PS_SUCCESS)
309 static void imap_canonicalize(char *result, char *raw, size_t maxlen)
310 /* encode an IMAP password as per RFC1730's quoting conventions */
315 for (i = 0; i < strlen(raw) && i < maxlen; i++)
317 if ((raw[i] == '\\') || (raw[i] == '"'))
319 result[j++] = raw[i];
324 static void capa_probe(int sock, struct query *ctl)
325 /* set capability variables from a CAPA probe */
329 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
330 capabilities[0] = '\0';
331 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
335 /* capability checks are supposed to be caseblind */
336 for (cp = capabilities; *cp; cp++)
337 *cp = toupper((unsigned char)*cp);
339 /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
340 should expect a response in mixed-case */
341 if (strstr(capabilities, "IMAP4REV1"))
343 imap_version = IMAP4rev1;
344 if (outlevel >= O_DEBUG)
345 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
349 imap_version = IMAP4;
350 if (outlevel >= O_DEBUG)
351 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
356 * Handle idling. We depend on coming through here on startup
357 * and after each timeout (including timeouts during idles).
362 if (strstr(capabilities, "IDLE"))
366 if (outlevel >= O_VERBOSE)
367 report(stdout, GT_("will idle after poll\n"));
373 static int do_authcert (int sock, const char *command, const char *name)
374 /* do authentication "external" (authentication provided by client cert) */
380 size_t len = strlen(name);
381 if ((len / 3) + ((len % 3) ? 4 : 0) < sizeof(buf))
382 to64frombits (buf, name, strlen(name));
384 return PS_AUTHFAIL; /* buffer too small. */
388 return gen_transact(sock, "%s EXTERNAL %s",command,buf);
391 static int imap_getauth(int sock, struct query *ctl, char *greeting)
392 /* apply for connection authorization */
398 * Assumption: expunges are cheap, so we want to do them
399 * after every message unless user said otherwise.
401 if (NUM_SPECIFIED(ctl->expunge))
402 expunge_period = NUM_VALUE_OUT(ctl->expunge);
406 capa_probe(sock, ctl);
409 * If either (a) we saw a PREAUTH token in the greeting, or
410 * (b) the user specified ssh preauthentication, then we're done.
412 if (preauth || ctl->server.authenticate == A_SSH)
414 preauth = FALSE; /* reset for the next session */
419 if (maybe_tls(ctl)) {
422 commonname = ctl->server.pollname;
424 commonname = ctl->server.via;
425 if (ctl->sslcommonname)
426 commonname = ctl->sslcommonname;
428 if (strstr(capabilities, "STARTTLS")
429 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
431 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
432 * protocol that will work with STARTTLS. Don't need to worry
433 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
435 if (gen_transact(sock, "STARTTLS") == PS_SUCCESS
436 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
437 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
438 ctl->server.pollname, &ctl->remotename) != -1)
441 * RFC 2595 says this:
443 * "Once TLS has been started, the client MUST discard cached
444 * information about server capabilities and SHOULD re-issue the
445 * CAPABILITY command. This is necessary to protect against
446 * man-in-the-middle attacks which alter the capabilities list prior
447 * to STARTTLS. The server MAY advertise different capabilities
450 * Now that we're confident in our TLS connection we can
451 * guarantee a secure capability re-probe.
453 capa_probe(sock, ctl);
454 if (outlevel >= O_VERBOSE)
456 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
458 } else if (must_tls(ctl)) {
459 /* Config required TLS but we couldn't guarantee it, so we must
461 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
464 if (outlevel >= O_VERBOSE) {
465 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue\n"), commonname);
467 /* We don't know whether the connection is in a working state, so
468 * test by issuing a NOOP. */
469 if (gen_transact(sock, "NOOP") != PS_SUCCESS) {
470 /* Not usable. Empty sslproto to force an unencrypted
471 * connection on the next attempt, and repoll. */
472 ctl->sslproto = xstrdup("");
475 /* Usable. Proceed with authenticating insecurely. */
479 #endif /* SSL_ENABLE */
482 * Time to authenticate the user.
483 * Try the protocol variants that don't require passwords first.
487 /* Yahoo hack - we'll just try ID if it was offered by the server,
488 * and IGNORE errors. */
490 char *tmp = strstr(capabilities, " ID");
491 if (tmp && !isalnum((unsigned char)tmp[3]) && strstr(ctl->server.via ? ctl->server.via : ctl->server.pollname, "yahoo.com")) {
492 (void)gen_transact(sock, "ID (\"guid\" \"1\")");
496 if ((ctl->server.authenticate == A_ANY
497 || ctl->server.authenticate == A_EXTERNAL)
498 && strstr(capabilities, "AUTH=EXTERNAL"))
500 ok = do_authcert(sock, "AUTHENTICATE", ctl->remotename);
503 /* SASL cancellation of authentication */
505 if (ctl->server.authenticate != A_ANY)
513 if (((ctl->server.authenticate == A_ANY && check_gss_creds("imap", ctl->server.truename) == PS_SUCCESS)
514 || ctl->server.authenticate == A_GSSAPI)
515 && strstr(capabilities, "AUTH=GSSAPI"))
517 if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
518 ctl->server.truename, ctl->remotename)))
520 if (ctl->server.authenticate != A_ANY)
529 * No such luck. OK, now try the variants that mask your password
530 * in a challenge-response.
533 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
534 || ctl->server.authenticate == A_CRAM_MD5)
536 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
538 if(ctl->server.authenticate != A_ANY)
546 if ((ctl->server.authenticate == A_ANY
547 || ctl->server.authenticate == A_OTP)
548 && strstr(capabilities, "AUTH=X-OTP")) {
549 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
551 /* SASL cancellation of authentication */
553 if(ctl->server.authenticate != A_ANY)
560 if (ctl->server.authenticate == A_OTP)
563 GT_("Required OTP capability not compiled into fetchmail\n"));
565 #endif /* OPIE_ENABLE */
568 if ((ctl->server.authenticate == A_ANY
569 || ctl->server.authenticate == A_NTLM)
570 && strstr (capabilities, "AUTH=NTLM")) {
571 if ((ok = do_imap_ntlm(sock, ctl)))
573 if(ctl->server.authenticate != A_ANY)
580 if (ctl->server.authenticate == A_NTLM)
583 GT_("Required NTLM capability not compiled into fetchmail\n"));
585 #endif /* NTLM_ENABLE */
588 * We're stuck with sending the password en clair.
589 * The reason for this odd-looking logic is that some
590 * servers return LOGINDISABLED even though login
591 * actually works. So arrange things in such a way that
592 * setting auth passwd makes it ignore this capability.
594 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
595 || ctl->server.authenticate == A_PASSWORD)
597 /* these sizes guarantee no buffer overflow */
598 char *remotename, *password;
600 rnl = 2 * strlen(ctl->remotename) + 1;
601 pwl = 2 * strlen(ctl->password) + 1;
602 remotename = (char *)xmalloc(rnl);
603 password = (char *)xmalloc(pwl);
605 imap_canonicalize(remotename, ctl->remotename, rnl);
606 imap_canonicalize(password, ctl->password, pwl);
608 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
609 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
610 memset(shroud, 0x55, sizeof(shroud));
612 memset(password, 0x55, strlen(password));
617 if(ctl->server.authenticate != A_ANY)
627 static int internal_expunge(int sock)
628 /* ship an expunge, resetting associated counters */
632 actual_deletions = 0;
634 if ((ok = gen_transact(sock, "EXPUNGE")))
637 /* if there is a mismatch between the number of mails which should
638 * have been expunged and the number of mails actually expunged,
639 * another email client may be deleting mails. Quit here,
640 * otherwise fetchmail gets out-of-sync with the imap server,
641 * reports the wrong size to the SMTP server on MAIL FROM: and
642 * triggers a "message ... was not the expected length" error on
643 * every subsequent mail */
644 if (deletions > 0 && deletions != actual_deletions)
647 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
648 actual_deletions, deletions);
653 expunged += deletions;
656 #ifdef IMAP_UID /* not used */
658 #endif /* IMAP_UID */
663 static int imap_idle(int sock)
664 /* start an RFC2177 IDLE, or fake one if unsupported */
668 saved_timeout = mytimeout;
671 /* special timeout to terminate the IDLE and re-issue it
672 * at least every 28 minutes:
673 * (the server may have an inactivity timeout) */
674 mytimeout = idle_timeout = 1680; /* 28 min */
675 time(&idle_start_time);
677 /* enter IDLE mode */
678 ok = gen_transact(sock, "IDLE");
680 if (ok == PS_IDLETIMEOUT) {
681 /* send "DONE" continuation */
682 SockWrite(sock, "DONE\r\n", 6);
683 if (outlevel >= O_MONITOR)
684 report(stdout, "IMAP> DONE\n");
685 /* reset stage and timeout here: we are not idling any more */
686 mytimeout = saved_timeout;
687 stage = STAGE_GETRANGE;
688 /* get OK IDLE message */
689 ok = imap_ok(sock, NULL);
691 } else { /* no idle support, fake it */
692 /* Note: stage and timeout have not been changed here as NOOP
694 ok = gen_transact(sock, "NOOP");
696 /* no error, but no new mail either */
697 if (ok == PS_SUCCESS && recentcount == 0)
699 /* There are some servers who do send new mail
700 * notification out of the blue. This is in compliance
701 * with RFC 2060 section 5.3. Wait for that with a low
703 mytimeout = idle_timeout = 28;
704 time(&idle_start_time);
706 /* We are waiting for notification; no tag needed */
708 /* wait (briefly) for an unsolicited status update */
709 ok = imap_ok(sock, NULL);
710 if (ok == PS_IDLETIMEOUT) {
711 /* no notification came; ok */
717 /* restore normal timeout value */
718 mytimeout = saved_timeout;
719 stage = STAGE_GETRANGE;
724 static int imap_search(int sock, struct query *ctl, int count)
725 /* search for unseen messages */
728 char buf[MSGBUFSIZE+1], *cp;
730 /* Don't count deleted messages. Enabled only for IMAP4 servers or
731 * higher and only when keeping mails. This flag will have an
732 * effect only when user has marked some unread mails for deletion
733 * using another e-mail client. */
734 flag skipdeleted = ctl->keep;
735 const char *undeleted;
737 /* structure to keep the end portion of the incomplete response */
740 /* startcount is higher than count so that if there are no
741 * unseen messages, imap_getsizes() will not need to do
743 startcount = count + 1;
747 undeleted = (skipdeleted ? " UNDELETED" : "");
748 gen_send(sock, "SEARCH UNSEEN%s", undeleted);
749 gen_recv_split_init("* SEARCH", &rs);
750 while ((ok = imap_response(sock, buf, &rs)) == PS_UNTAGGED)
752 if ((cp = strstr(buf, "* SEARCH")))
756 cp += 8; /* skip "* SEARCH" */
757 while (*cp && unseen < count)
759 /* skip whitespace */
760 while (*cp && isspace((unsigned char)*cp))
767 um = strtoul(cp,&ep,10);
768 if (errno == 0 && ep > cp
769 && um <= INT_MAX && um <= (unsigned)count)
771 unseen_messages[unseen++] = um;
772 if (outlevel >= O_DEBUG)
773 report(stdout, GT_("%lu is unseen\n"), um);
782 if (ok != PS_ERROR) /* success or non-protocol error */
785 /* there is a protocol error. try a different search command. */
788 /* retry with "SEARCH UNSEEN" */
792 /* try with "FETCH 1:n FLAGS" */
797 gen_send(sock, "FETCH %d FLAGS", count);
799 gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
800 while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
805 /* expected response format:
806 * IMAP< * 1 FETCH (FLAGS (\Seen))
807 * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
808 * IMAP< * 3 FETCH (FLAGS ())
809 * IMAP< * 4 FETCH (FLAGS (\Recent))
810 * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
813 && sscanf(buf, "* %u %n", &num, &consumed) == 1
814 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
815 && isspace((unsigned char)buf[consumed+5])
816 && num >= 1 && num <= (unsigned)count
817 && strstr(buf, "FLAGS ")
818 && !strstr(buf, "\\SEEN")
819 && !strstr(buf, "\\DELETED"))
821 unseen_messages[unseen++] = num;
822 if (outlevel >= O_DEBUG)
823 report(stdout, GT_("%u is unseen\n"), num);
824 if (startcount > num)
831 static int imap_getrange(int sock,
834 int *countp, int *newp, int *bytes)
835 /* get range of messages to be fetched */
839 /* find out how many messages are waiting */
844 /* deleted mails have already been expunged by
845 * end_mailbox_poll().
847 * recentcount is already set here by the last imap command which
848 * returned EXISTS on detecting new mail. if recentcount is 0, wait
851 * this is a while loop because imap_idle() might return on other
852 * mailbox changes also */
853 while (recentcount == 0 && do_idle) {
855 ok = imap_idle(sock);
858 report(stderr, GT_("re-poll failed\n"));
862 /* if recentcount is 0, return no mail */
863 if (recentcount == 0)
865 if (outlevel >= O_DEBUG)
866 report(stdout, ngettext("%d message waiting after re-poll\n",
867 "%d messages waiting after re-poll\n",
872 oldcount = count = 0;
873 ok = gen_transact(sock,
874 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
875 folder ? folder : "INBOX");
876 /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
877 * which we can safely use in fetchall keep only */
878 if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
883 report(stderr, GT_("mailbox selection failed\n"));
886 else if (outlevel >= O_DEBUG)
887 report(stdout, ngettext("%d message waiting after first poll\n",
888 "%d messages waiting after first poll\n",
892 * We should have an expunge here to
893 * a) avoid fetching deleted mails during 'fetchall'
894 * b) getting a wrong count of mails during 'no fetchall'
896 if (!check_only && !ctl->keep && count > 0)
898 ok = internal_expunge(sock);
901 report(stderr, GT_("expunge failed\n"));
904 if (outlevel >= O_DEBUG)
905 report(stdout, ngettext("%d message waiting after expunge\n",
906 "%d messages waiting after expunge\n",
910 if (count == 0 && do_idle)
912 /* no messages? then we may need to idle until we get some */
914 ok = imap_idle(sock);
917 report(stderr, GT_("re-poll failed\n"));
921 if (outlevel >= O_DEBUG)
922 report(stdout, ngettext("%d message waiting after re-poll\n",
923 "%d messages waiting after re-poll\n",
928 *countp = oldcount = count;
932 /* OK, now get a count of unseen messages and their indices */
933 if (!ctl->fetchall && count > 0)
936 free(unseen_messages);
937 unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
938 memset(unseen_messages, 0, count * sizeof(unsigned int));
941 ok = imap_search(sock, ctl, count);
944 report(stderr, GT_("search for unseen messages failed\n"));
948 if (outlevel >= O_DEBUG && unseen > 0)
949 report(stdout, GT_("%u is first unseen\n"), startcount);
960 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
961 /* capture the sizes of messages #first-#last */
963 char buf [MSGBUFSIZE+1];
967 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
968 * won't accept 1:1 as valid set syntax. Some implementors
969 * should be taken out and shot for excessive anality.
971 * Microsoft Exchange (brain-dead piece of crap that it is)
972 * sometimes gets its knickers in a knot about bodiless messages.
973 * You may see responses like this:
975 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
976 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
977 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
978 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
979 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
980 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
981 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
982 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
983 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
984 * fetchmail: IMAP< A0004 NO The requested item could not be found.
986 * This means message 1 has only headers. For kicks and grins
987 * you can telnet in and look:
989 * A003 NO The requested item could not be found.
990 * A004 fetch 1 rfc822.header
991 * A004 NO The requested item could not be found.
993 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
994 * A006 OK FETCH completed.
996 * To get around this, we treat the final NO as success and count
997 * on the fact that the sizes array has been preinitialized with a
998 * known-bad size value.
1001 /* expunges change the fetch numbers */
1006 gen_send(sock, "FETCH %d RFC822.SIZE", last);
1007 else if (last > first)
1008 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1009 else /* no unseen messages! */
1011 while ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
1018 /* expected response formats:
1019 * IMAP> A0005 FETCH 1 RFC822.SIZE
1020 * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1021 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1023 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1024 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1025 && isspace((unsigned char)buf[consumed + 5])
1026 && (ptr = strstr(buf, "RFC822.SIZE "))
1027 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1029 if (num >= first && num <= last)
1030 sizes[num - first] = size;
1033 GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1039 static int imap_getsizes(int sock, int count, int *sizes)
1040 /* capture the sizes of all messages */
1042 return imap_getpartialsizes(sock, 1, count, sizes);
1045 static int imap_is_old(int sock, struct query *ctl, int number)
1046 /* is the given message old? */
1054 * Expunges change the fetch numbers, but unseen_messages contains
1055 * indices from before any expungees were done. So neither the
1056 * argument nor the values in message_sequence need to be decremented.
1060 for (i = 0; i < unseen; i++)
1061 if (unseen_messages[i] == (unsigned)number)
1071 static char *skip_token(char *ptr)
1073 while(isspace((unsigned char)*ptr)) ptr++;
1074 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1075 while(isspace((unsigned char)*ptr)) ptr++;
1080 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1081 /* request headers of nth message */
1083 char buf [MSGBUFSIZE+1];
1089 /* expunges change the fetch numbers */
1093 * This is blessed by RFC1176, RFC1730, RFC2060.
1094 * According to the RFCs, it should *not* set the \Seen flag.
1096 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1098 /* looking for FETCH response */
1099 if ((ok = imap_response(sock, buf, NULL)) == PS_UNTAGGED)
1102 /* expected response formats:
1103 * IMAP> A0006 FETCH 1 RFC822.HEADER
1104 * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1105 * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1106 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1108 if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1109 && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1110 && isspace((unsigned char)buf[5+consumed])
1112 && (ptr = strstr(buf, "RFC822.HEADER"))
1113 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1114 && ptr[consumed-1] == '}')
1119 /* wait for a tagged response */
1122 /* try to recover for some responses */
1123 if (!strncmp(buf, "* NO", 4) ||
1124 !strncmp(buf, "* BAD", 5))
1126 return(PS_TRANSIENT);
1129 /* a response which does not match any of the above */
1130 if (outlevel > O_SILENT)
1131 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1134 else if (ok == PS_SUCCESS)
1136 /* an unexpected tagged response */
1137 if (outlevel > O_SILENT)
1138 report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1144 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1145 /* request body of nth message */
1147 char buf [MSGBUFSIZE+1], *cp;
1151 /* expunges change the fetch numbers */
1155 * If we're using IMAP4, we can fetch the message without setting its
1156 * seen flag. This is good! It means that if the protocol exchange
1157 * craps out during the message, it will still be marked `unseen' on
1160 * According to RFC2060, and Mark Crispin the IMAP maintainer,
1161 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
1162 * equivalent". However, we know of at least one server that
1163 * treats them differently in the presence of MIME attachments;
1164 * the latter form downloads the attachment, the former does not.
1165 * The server is InterChange.
1167 * When I tried working around this by disabling use of the 4rev1 form,
1168 * I found that doing this breaks operation with M$ Exchange.
1169 * Annoyingly enough, Exchange's refusal to cope is technically legal
1172 switch (imap_version)
1174 case IMAP4rev1: /* RFC 2060 */
1176 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1179 case IMAP4: /* RFC 1730 */
1180 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1184 /* looking for FETCH response */
1188 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1191 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1196 /* Understand "NIL" as length => no body present
1197 * (MS Exchange, BerliOS Bug #11980) */
1198 if (strstr(buf+10, "NIL)")) {
1203 /* Understand the empty string. Seen on Yahoo. */
1204 /* XXX FIXME: we should be able to handle strings here. */
1205 if (strstr(buf+10, "\"\")")) {
1211 * Try to extract a length from the FETCH response. RFC2060 requires
1212 * it to be present, but at least one IMAP server (Novell GroupWise)
1213 * botches this. The overflow check is needed because of a broken
1214 * server called dbmail that returns huge garbage lengths.
1216 if ((cp = strchr(buf, '{'))) {
1220 l = strtol(cp, &t, 10);
1221 if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1222 || l < 0 || l > INT_MAX /* range check */) {
1228 *lenp = -1; /* missing length part in FETCH reponse */
1234 static int imap_trail(int sock, struct query *ctl, const char *tag)
1235 /* discard tail of FETCH response after reading message text */
1237 /* expunges change the fetch numbers */
1238 /* number -= expunged; */
1243 return imap_ok(sock, NULL);
1246 static int imap_delete(int sock, struct query *ctl, int number)
1247 /* set delete flag for given message */
1250 /* Select which flags to set on message deletion: */
1251 const char delflags_seen[] = "\\Seen \\Deleted";
1252 const char delflags_unseen[] = "\\Deleted";
1253 static const char *delflags;
1254 /* Which environment variable to look for: */
1255 const char dis_env[] = "FETCHMAIL_IMAP_DELETED_REMAINS_UNSEEN";
1259 if ((tmp = getenv(dis_env)) != NULL && *tmp) {
1260 delflags = delflags_unseen;
1262 /* DEFAULT since many fetchmail versions <= 6.3.X */
1263 delflags = delflags_seen;
1268 /* expunges change the fetch numbers */
1272 * We set Seen because there are some IMAP servers (notably HP
1273 * OpenMail) that do message-receipt DSNs, but only when the seen
1274 * bit is set. This is the appropriate time -- we get here right
1275 * after the local SMTP response that says delivery was
1278 if ((ok = gen_transact(sock, "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)", number)))
1284 * We do an expunge after expunge_period messages, rather than
1285 * just before quit, so that a line hit during a long session
1286 * won't result in lots of messages being fetched again during
1289 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1291 if ((ok = internal_expunge(sock)))
1298 static int imap_mark_seen(int sock, struct query *ctl, int number)
1299 /* mark the given message as seen */
1303 /* expunges change the message numbers */
1306 return(gen_transact(sock,"STORE %d +FLAGS.SILENT (\\Seen)", number));
1309 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1310 /* cleanup mailbox before we idle or switch to another one */
1314 internal_expunge(sock);
1318 static int imap_logout(int sock, struct query *ctl)
1319 /* send logout command */
1322 /* if any un-expunged deletions remain, ship an expunge now */
1324 internal_expunge(sock);
1327 /* Memory clean-up */
1328 if (unseen_messages)
1329 free(unseen_messages);
1330 #endif /* USE_SEARCH */
1332 return(gen_transact(sock, "LOGOUT"));
1335 static const struct method imap =
1337 "IMAP", /* Internet Message Access Protocol */
1338 "imap", /* service (plain and TLS) */
1339 "imaps", /* service (SSL) */
1340 TRUE, /* this is a tagged protocol */
1341 FALSE, /* no message delimiter */
1342 imap_ok, /* parse command response */
1343 imap_getauth, /* get authorization */
1344 imap_getrange, /* query range of messages */
1345 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1346 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1347 imap_is_old, /* no UID check */
1348 imap_fetch_headers, /* request given message headers */
1349 imap_fetch_body, /* request given message body */
1350 imap_trail, /* eat message trailer */
1351 imap_delete, /* delete the message */
1352 imap_mark_seen, /* how to mark a message as seen */
1353 imap_end_mailbox_poll, /* end-of-mailbox processing */
1354 imap_logout, /* expunge and exit */
1355 TRUE, /* yes, we can re-poll */
1358 int doIMAP(struct query *ctl)
1359 /* retrieve messages using IMAP Version 2bis or Version 4 */
1361 return(do_protocol(ctl, &imap));
1364 /* imap.c ends here */