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.
12 #if defined(STDC_HEADERS)
17 #include "fetchmail.h"
22 /* imap_version values */
23 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
24 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
25 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
27 /* global variables: please reinitialize them explicitly for proper
28 * working in daemon mode */
30 /* TODO: session variables to be initialized before server greeting */
31 static int preauth = FALSE;
33 /* session variables initialized in capa_probe() or imap_getauth() */
34 static char capabilities[MSGBUFSIZE+1];
35 static int imap_version = IMAP4;
36 static flag do_idle = FALSE, has_idle = FALSE;
37 static int expunge_period = 1;
39 /* mailbox variables initialized in imap_getrange() */
40 static int count = 0, oldcount = 0, recentcount = 0, unseen = 0, deletions = 0;
41 static unsigned int startcount = 1;
42 static int expunged = 0;
43 static unsigned int *unseen_messages;
45 /* for "IMAP> EXPUNGE" */
46 static int actual_deletions = 0;
48 /* for "IMAP> IDLE" */
49 static int saved_timeout = 0;
51 static int imap_ok(int sock, char *argbuf)
52 /* parse command response */
54 char buf[MSGBUFSIZE+1];
60 if ((ok = gen_recv(sock, buf, sizeof(buf))))
63 /* all tokens in responses are caseblind */
64 for (cp = buf; *cp; cp++)
65 if (islower((unsigned char)*cp))
66 *cp = toupper((unsigned char)*cp);
68 /* interpret untagged status responses
69 * First check if we really have an untagged response, starting
70 * with "*" SPACE. Then, for each individual check, use a BLANK
71 * before the word to avoid confusion with the \Recent flag or
73 if (buf[0] == '*' && buf[1] == ' ') {
74 if (strstr(buf, " CAPABILITY")) {
75 strlcpy(capabilities, buf + 12, sizeof(capabilities));
77 else if (strstr(buf, " EXISTS"))
81 * Don't trust the message count passed by the server.
82 * Without this check, it might be possible to do a
83 * DNS-spoofing attack that would pass back a ridiculous
84 * count, and allocate a malloc area that would overlap
85 * a portion of the stack.
87 if ((unsigned)count > INT_MAX/sizeof(int))
89 report(stderr, GT_("bogus message count!"));
92 if ((recentcount = count - oldcount) < 0)
96 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
97 * we can't wait for the tag matching the IDLE; we have to tell the
98 * server the IDLE is finished by shipping back a DONE when we
99 * see an EXISTS. Only after that will a tagged response be
100 * shipped. The idling flag also gets cleared on a timeout.
102 if (stage == STAGE_IDLE)
104 /* If IDLE isn't supported, we were only sending NOOPs anyway. */
107 /* we do our own write and report here to disable tagging */
108 SockWrite(sock, "DONE\r\n", 6);
109 if (outlevel >= O_MONITOR)
110 report(stdout, "IMAP> DONE\n");
113 mytimeout = saved_timeout;
117 /* we now compute recentcount as a difference between
118 * new and old EXISTS, hence disable RECENT check */
120 else if (strstr(buf, " RECENT"))
122 recentcount = atoi(buf+2);
125 else if (strstr(buf, " EXPUNGE"))
127 /* the response "* 10 EXPUNGE" means that the currently
128 * tenth (i.e. only one) message has been deleted */
135 /* We do expect an EXISTS response immediately
136 * after this, so this updation of recentcount is
137 * just a precaution! */
143 else if (strstr(buf, " PREAUTH"))
148 * The server may decide to make the mailbox read-only,
149 * which causes fetchmail to go into a endless loop
150 * fetching the same message over and over again.
152 * However, for check_only, we use EXAMINE which will
153 * mark the mailbox read-only as per the RFC.
155 * This checks for the condition and aborts if
156 * the mailbox is read-only.
158 * See RFC 2060 section 6.3.1 (SELECT).
159 * See RFC 2060 section 6.3.2 (EXAMINE).
161 else if (!check_only && strstr(buf, "[READ-ONLY]"))
167 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
180 for (cp = buf; !isspace((unsigned char)*cp); cp++)
182 while (isspace((unsigned char)*cp))
185 if (strncasecmp(cp, "OK", 2) == 0)
191 else if (strncasecmp(cp, "BAD", 3) == 0)
193 else if (strncasecmp(cp, "NO", 2) == 0)
195 if (stage == STAGE_GETAUTH)
196 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
209 * NTLM support by Grant Edwards.
211 * Handle MS-Exchange NTLM authentication method. This is the same
212 * as the NTLM auth used by Samba for SMB related services. We just
213 * encode the packets in base64 instead of sending them out via a
216 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
219 static int do_imap_ntlm(int sock, struct query *ctl)
221 tSmbNtlmAuthRequest request;
222 tSmbNtlmAuthChallenge challenge;
223 tSmbNtlmAuthResponse response;
228 gen_send(sock, "AUTHENTICATE NTLM");
230 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
233 if (msgbuf[0] != '+')
236 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
238 if (outlevel >= O_DEBUG)
239 dumpSmbNtlmAuthRequest(stdout, &request);
241 memset(msgbuf,0,sizeof msgbuf);
242 to64frombits (msgbuf, &request, SmbLength(&request));
244 if (outlevel >= O_MONITOR)
245 report(stdout, "IMAP> %s\n", msgbuf);
247 strcat(msgbuf,"\r\n");
248 SockWrite (sock, msgbuf, strlen (msgbuf));
250 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
253 len = from64tobits (&challenge, msgbuf, sizeof(challenge));
255 if (outlevel >= O_DEBUG)
256 dumpSmbNtlmAuthChallenge(stdout, &challenge);
258 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
260 if (outlevel >= O_DEBUG)
261 dumpSmbNtlmAuthResponse(stdout, &response);
263 memset(msgbuf,0,sizeof msgbuf);
264 to64frombits (msgbuf, &response, SmbLength(&response));
266 if (outlevel >= O_MONITOR)
267 report(stdout, "IMAP> %s\n", msgbuf);
269 strcat(msgbuf,"\r\n");
270 SockWrite (sock, msgbuf, strlen (msgbuf));
272 result = imap_ok (sock, NULL);
273 if (result == PS_SUCCESS)
280 static void imap_canonicalize(char *result, char *raw, size_t maxlen)
281 /* encode an IMAP password as per RFC1730's quoting conventions */
286 for (i = 0; i < strlen(raw) && i < maxlen; i++)
288 if ((raw[i] == '\\') || (raw[i] == '"'))
290 result[j++] = raw[i];
295 static void capa_probe(int sock, struct query *ctl)
296 /* set capability variables from a CAPA probe */
300 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
301 capabilities[0] = '\0';
302 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
306 /* capability checks are supposed to be caseblind */
307 for (cp = capabilities; *cp; cp++)
308 *cp = toupper((unsigned char)*cp);
310 /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
311 should expect a response in mixed-case */
312 if (strstr(capabilities, "IMAP4REV1"))
314 imap_version = IMAP4rev1;
315 if (outlevel >= O_DEBUG)
316 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
320 imap_version = IMAP4;
321 if (outlevel >= O_DEBUG)
322 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
325 else if (ok == PS_ERROR)
327 imap_version = IMAP2;
328 if (outlevel >= O_DEBUG)
329 report(stdout, GT_("Protocol identified as IMAP2 or IMAP2BIS\n"));
333 * Handle idling. We depend on coming through here on startup
334 * and after each timeout (including timeouts during idles).
339 if (strstr(capabilities, "IDLE"))
343 if (outlevel >= O_VERBOSE)
344 report(stdout, GT_("will idle after poll\n"));
347 peek_capable = (imap_version >= IMAP4);
350 static int imap_getauth(int sock, struct query *ctl, char *greeting)
351 /* apply for connection authorization */
355 flag did_stls = FALSE;
356 #endif /* SSL_ENABLE */
360 * Assumption: expunges are cheap, so we want to do them
361 * after every message unless user said otherwise.
363 if (NUM_SPECIFIED(ctl->expunge))
364 expunge_period = NUM_VALUE_OUT(ctl->expunge);
368 capa_probe(sock, ctl);
371 * If either (a) we saw a PREAUTH token in the greeting, or
372 * (b) the user specified ssh preauthentication, then we're done.
374 if (preauth || ctl->server.authenticate == A_SSH)
376 preauth = FALSE; /* reset for the next session */
381 if ((!ctl->sslproto || !strcmp(ctl->sslproto,"tls1"))
383 && strstr(capabilities, "STARTTLS"))
387 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
388 ok = gen_transact(sock, "STARTTLS");
390 /* We use "tls1" instead of ctl->sslproto, as we want STARTTLS,
391 * not other SSL protocols
393 if (ok == PS_SUCCESS &&
394 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck,
395 ctl->sslcertpath,ctl->sslfingerprint,
396 realhost,ctl->server.pollname) == -1)
398 if (!ctl->sslproto && !ctl->wehaveauthed)
400 ctl->sslproto = xstrdup("");
401 /* repoll immediately */
405 GT_("SSL connection failed.\n"));
408 if (outlevel >= O_VERBOSE && !ctl->sslproto)
409 report(stdout, GT_("%s: opportunistic upgrade to TLS.\n"), realhost);
414 * RFC 2595 says this:
416 * "Once TLS has been started, the client MUST discard cached
417 * information about server capabilities and SHOULD re-issue the
418 * CAPABILITY command. This is necessary to protect against
419 * man-in-the-middle attacks which alter the capabilities list prior
420 * to STARTTLS. The server MAY advertise different capabilities
423 capa_probe(sock, ctl);
425 #endif /* SSL_ENABLE */
428 * Time to authenticate the user.
429 * Try the protocol variants that don't require passwords first.
434 if ((ctl->server.authenticate == A_ANY
435 || ctl->server.authenticate == A_GSSAPI)
436 && strstr(capabilities, "AUTH=GSSAPI"))
438 if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
439 ctl->server.truename, ctl->remotename)))
441 /* SASL cancellation of authentication */
443 if (ctl->server.authenticate != A_ANY)
452 if ((ctl->server.authenticate == A_ANY
453 || ctl->server.authenticate == A_KERBEROS_V4
454 || ctl->server.authenticate == A_KERBEROS_V5)
455 && strstr(capabilities, "AUTH=KERBEROS_V4"))
457 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
459 /* SASL cancellation of authentication */
461 if(ctl->server.authenticate != A_ANY)
467 #endif /* KERBEROS_V4 */
470 * No such luck. OK, now try the variants that mask your password
471 * in a challenge-response.
474 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
475 || ctl->server.authenticate == A_CRAM_MD5)
477 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
479 /* SASL cancellation of authentication */
481 if(ctl->server.authenticate != A_ANY)
489 if ((ctl->server.authenticate == A_ANY
490 || ctl->server.authenticate == A_OTP)
491 && strstr(capabilities, "AUTH=X-OTP")) {
492 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
494 /* SASL cancellation of authentication */
496 if(ctl->server.authenticate != A_ANY)
503 if (ctl->server.authenticate == A_OTP)
506 GT_("Required OTP capability not compiled into fetchmail\n"));
508 #endif /* OPIE_ENABLE */
511 if ((ctl->server.authenticate == A_ANY
512 || ctl->server.authenticate == A_NTLM)
513 && strstr (capabilities, "AUTH=NTLM")) {
514 if ((ok = do_imap_ntlm(sock, ctl)))
516 /* SASL cancellation of authentication */
518 if(ctl->server.authenticate != A_ANY)
525 if (ctl->server.authenticate == A_NTLM)
528 GT_("Required NTLM capability not compiled into fetchmail\n"));
530 #endif /* NTLM_ENABLE */
532 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
533 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
534 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
537 GT_("Required LOGIN capability not supported by server\n"));
539 #endif /* __UNUSED__ */
542 * We're stuck with sending the password en clair.
543 * The reason for this odd-looking logic is that some
544 * servers return LOGINDISABLED even though login
545 * actually works. So arrange things in such a way that
546 * setting auth passwd makes it ignore this capability.
548 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
549 || ctl->server.authenticate == A_PASSWORD)
551 /* these sizes guarantee no buffer overflow */
552 char *remotename, *password;
554 rnl = 2 * strlen(ctl->remotename) + 1;
555 pwl = 2 * strlen(ctl->password) + 1;
556 remotename = xmalloc(rnl);
557 password = xmalloc(pwl);
559 imap_canonicalize(remotename, ctl->remotename, rnl);
560 imap_canonicalize(password, ctl->password, pwl);
562 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
563 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
568 /* this is for servers which claim to support TLS, but actually
570 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
572 ctl->sslproto = xstrdup("");
573 /* repoll immediately */
579 /* SASL cancellation of authentication */
581 if(ctl->server.authenticate != A_ANY)
591 static int internal_expunge(int sock)
592 /* ship an expunge, resetting associated counters */
596 actual_deletions = 0;
598 if ((ok = gen_transact(sock, "EXPUNGE")))
601 /* if there is a mismatch between the number of mails which should
602 * have been expunged and the number of mails actually expunged,
603 * another email client may be deleting mails. Quit here,
604 * otherwise fetchmail gets out-of-sync with the imap server,
605 * reports the wrong size to the SMTP server on MAIL FROM: and
606 * triggers a "message ... was not the expected length" error on
607 * every subsequent mail */
608 if (deletions > 0 && deletions != actual_deletions)
611 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
612 actual_deletions, deletions);
617 expunged += deletions;
620 #ifdef IMAP_UID /* not used */
622 #endif /* IMAP_UID */
627 static int imap_idle(int sock)
628 /* start an RFC2177 IDLE, or fake one if unsupported */
632 saved_timeout = mytimeout;
635 /* special timeout to terminate the IDLE and re-issue it
636 * at least every 28 minutes:
637 * (the server may have an inactivity timeout) */
638 mytimeout = 1680; /* 28 min */
640 /* enter IDLE mode */
641 ok = gen_transact(sock, "IDLE");
643 if (ok == PS_IDLETIMEOUT) {
644 /* send "DONE" continuation */
645 SockWrite(sock, "DONE\r\n", 6);
646 if (outlevel >= O_MONITOR)
647 report(stdout, "IMAP> DONE\n");
648 /* reset stage and timeout here: we are not idling any more */
649 mytimeout = saved_timeout;
651 /* get OK IDLE message */
652 ok = imap_ok(sock, NULL);
654 } else { /* no idle support, fake it */
655 /* Note: stage and timeout have not been changed here as NOOP
657 ok = gen_transact(sock, "NOOP");
659 /* no error, but no new mail either */
660 if (ok == PS_SUCCESS && recentcount == 0)
662 /* There are some servers who do send new mail
663 * notification out of the blue. This is in compliance
664 * with RFC 2060 section 5.3. Wait for that with a low
668 /* We are waiting for notification; no tag needed */
670 /* wait (briefly) for an unsolicited status update */
671 ok = imap_ok(sock, NULL);
672 if (ok == PS_IDLETIMEOUT) {
673 /* no notification came; ok */
679 /* restore normal timeout value */
681 mytimeout = saved_timeout;
687 static int imap_getrange(int sock,
690 int *countp, int *newp, int *bytes)
691 /* get range of messages to be fetched */
694 char buf[MSGBUFSIZE+1], *cp;
696 /* find out how many messages are waiting */
701 /* deleted mails have already been expunged by
702 * end_mailbox_poll().
704 * recentcount is already set here by the last imap command which
705 * returned EXISTS on detecting new mail. if recentcount is 0, wait
708 * this is a while loop because imap_idle() might return on other
709 * mailbox changes also */
710 while (recentcount == 0 && do_idle) {
712 ok = imap_idle(sock);
715 report(stderr, GT_("re-poll failed\n"));
719 /* if recentcount is 0, return no mail */
720 if (recentcount == 0)
722 if (outlevel >= O_DEBUG)
723 report(stdout, ngettext("%d message waiting after re-poll\n",
724 "%d messages waiting after re-poll\n",
729 oldcount = count = 0;
730 ok = gen_transact(sock,
731 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
732 folder ? folder : "INBOX");
733 /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
734 * which we can safely use in fetchall keep only */
735 if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
740 report(stderr, GT_("mailbox selection failed\n"));
743 else if (outlevel >= O_DEBUG)
744 report(stdout, ngettext("%d message waiting after first poll\n",
745 "%d messages waiting after first poll\n",
749 * We should have an expunge here to
750 * a) avoid fetching deleted mails during 'fetchall'
751 * b) getting a wrong count of mails during 'no fetchall'
753 if (!check_only && !ctl->keep && count > 0)
755 ok = internal_expunge(sock);
758 report(stderr, GT_("expunge failed\n"));
761 if (outlevel >= O_DEBUG)
762 report(stdout, ngettext("%d message waiting after expunge\n",
763 "%d messages waiting after expunge\n",
767 if (count == 0 && do_idle)
769 /* no messages? then we may need to idle until we get some */
771 ok = imap_idle(sock);
774 report(stderr, GT_("re-poll failed\n"));
778 if (outlevel >= O_DEBUG)
779 report(stdout, ngettext("%d message waiting after re-poll\n",
780 "%d messages waiting after re-poll\n",
785 *countp = oldcount = count;
789 /* OK, now get a count of unseen messages and their indices */
790 if (!ctl->fetchall && count > 0)
793 free(unseen_messages);
794 unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
795 memset(unseen_messages, 0, count * sizeof(unsigned int));
798 /* don't count deleted messages, in case user enabled keep last time */
799 gen_send(sock, "SEARCH UNSEEN NOT DELETED");
801 ok = gen_recv(sock, buf, sizeof(buf));
804 report(stderr, GT_("search for unseen messages failed\n"));
807 else if ((cp = strstr(buf, "* SEARCH")))
811 cp += 8; /* skip "* SEARCH" */
812 /* startcount is higher than count so that if there are no
813 * unseen messages, imap_getsizes() will not need to do
815 startcount = count + 1;
817 while (*cp && unseen < count)
819 /* skip whitespace */
820 while (*cp && isspace((unsigned char)*cp))
827 um = strtoul(cp,&ep,10);
828 if (errno == 0 && um <= UINT_MAX && um <= (unsigned)count)
830 unseen_messages[unseen++] = um;
831 if (outlevel >= O_DEBUG)
832 report(stdout, GT_("%lu is unseen\n"), um);
841 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
843 if (outlevel >= O_DEBUG && unseen > 0)
844 report(stdout, GT_("%u is first unseen\n"), startcount);
855 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
856 /* capture the sizes of messages #first-#last */
858 char buf [MSGBUFSIZE+1];
861 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
862 * won't accept 1:1 as valid set syntax. Some implementors
863 * should be taken out and shot for excessive anality.
865 * Microsoft Exchange (brain-dead piece of crap that it is)
866 * sometimes gets its knickers in a knot about bodiless messages.
867 * You may see responses like this:
869 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
870 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
871 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
872 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
873 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
874 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
875 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
876 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
877 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
878 * fetchmail: IMAP< A0004 NO The requested item could not be found.
880 * This means message 1 has only headers. For kicks and grins
881 * you can telnet in and look:
883 * A003 NO The requested item could not be found.
884 * A004 fetch 1 rfc822.header
885 * A004 NO The requested item could not be found.
887 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
888 * A006 OK FETCH completed.
890 * To get around this, we terminate the read loop on a NO and count
891 * on the fact that the sizes array has been preinitialized with a
892 * known-bad size value.
895 /* expunges change the fetch numbers */
900 gen_send(sock, "FETCH %d RFC822.SIZE", last);
901 else if (last > first)
902 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
903 else /* no unseen messages! */
911 if ((ok = gen_recv(sock, buf, sizeof(buf))))
913 /* we want response matching to be case-insensitive */
914 for (cp = buf; *cp; cp++)
915 *cp = toupper((unsigned char)*cp);
916 /* an untagged NO means that a message was not readable */
917 if (strstr(buf, "* NO"))
919 else if (strstr(buf, "OK") || strstr(buf, "NO"))
921 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %u)", &num, &size) == 2
922 /* some servers (like mail.internode.on.net bld-mail04) return UID information here
924 * IMAP> A0005 FETCH 1 RFC822.SIZE
925 * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
926 * IMAP< A0005 OK FETCH completed
929 || sscanf(buf, "* %d FETCH (UID %*s RFC822.SIZE %u)", &num, &size) == 2)
931 if (num >= first && num <= last)
932 sizes[num - first] = size;
935 GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
942 static int imap_getsizes(int sock, int count, int *sizes)
943 /* capture the sizes of all messages */
945 return imap_getpartialsizes(sock, 1, count, sizes);
948 static int imap_is_old(int sock, struct query *ctl, int number)
949 /* is the given message old? */
957 * Expunges change the fetch numbers, but unseen_messages contains
958 * indices from before any expungees were done. So neither the
959 * argument nor the values in message_sequence need to be decremented.
963 for (i = 0; i < unseen; i++)
964 if (unseen_messages[i] == (unsigned)number)
973 static char *skip_token(char *ptr)
975 while(isspace((unsigned char)*ptr)) ptr++;
976 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
977 while(isspace((unsigned char)*ptr)) ptr++;
981 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
982 /* request headers of nth message */
984 char buf [MSGBUFSIZE+1];
988 /* expunges change the fetch numbers */
992 * This is blessed by RFC1176, RFC1730, RFC2060.
993 * According to the RFCs, it should *not* set the \Seen flag.
995 gen_send(sock, "FETCH %d RFC822.HEADER", number);
997 /* looking for FETCH response */
1003 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1005 ptr = skip_token(buf); /* either "* " or "AXXXX " */
1006 if (sscanf(ptr, "%d FETCH (RFC822.HEADER {%d}", &num, lenp) == 2
1007 /* some servers (like mail.internode.on.net bld-mail04) return UID information here
1009 * IMAP> A0006 FETCH 1 RFC822.HEADER
1010 * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1013 * IMAP< A0006 OK FETCH completed
1016 || sscanf(ptr, "%d FETCH (UID %*s RFC822.HEADER {%d}", &num, lenp) == 2)
1018 /* try to recover from chronically fucked-up M$ Exchange servers */
1019 else if (!strncmp(ptr, "NO", 2))
1021 /* wait for a tagged response */
1022 if (strstr (buf, "* NO"))
1024 return(PS_TRANSIENT);
1026 else if (!strncmp(ptr, "BAD", 3))
1028 /* wait for a tagged response */
1029 if (strstr (buf, "* BAD"))
1031 return(PS_TRANSIENT);
1041 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1042 /* request body of nth message */
1044 char buf [MSGBUFSIZE+1], *cp;
1048 /* expunges change the fetch numbers */
1052 * If we're using IMAP4, we can fetch the message without setting its
1053 * seen flag. This is good! It means that if the protocol exchange
1054 * craps out during the message, it will still be marked `unseen' on
1057 * According to RFC2060, and Mark Crispin the IMAP maintainer,
1058 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
1059 * equivalent". However, we know of at least one server that
1060 * treats them differently in the presence of MIME attachments;
1061 * the latter form downloads the attachment, the former does not.
1062 * The server is InterChange, and the fool who implemented this
1063 * misfeature ought to be strung up by his thumbs.
1065 * When I tried working around this by disabling use of the 4rev1 form,
1066 * I found that doing this breaks operation with M$ Exchange.
1067 * Annoyingly enough, Exchange's refusal to cope is technically legal
1068 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
1069 * standards, to find a way to make standards compliance irritating....
1071 switch (imap_version)
1073 case IMAP4rev1: /* RFC 2060 */
1074 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1077 case IMAP4: /* RFC 1730 */
1078 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1081 default: /* RFC 1176 */
1082 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1086 /* looking for FETCH response */
1090 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1093 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1099 * Try to extract a length from the FETCH response. RFC2060 requires
1100 * it to be present, but at least one IMAP server (Novell GroupWise)
1101 * botches this. The overflow check is needed because of a broken
1102 * server called dbmail that returns huge garbage lengths.
1104 if ((cp = strchr(buf, '{'))) {
1106 *lenp = (int)strtol(cp + 1, (char **)NULL, 10);
1107 if (errno == ERANGE || *lenp < 0)
1108 *lenp = -1; /* length is too big/small for us to handle */
1111 *lenp = -1; /* missing length part in FETCH reponse */
1116 static int imap_trail(int sock, struct query *ctl, const char *tag)
1117 /* discard tail of FETCH response after reading message text */
1119 /* expunges change the fetch numbers */
1120 /* number -= expunged; */
1125 char buf[MSGBUFSIZE+1], *t;
1128 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1131 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1132 if (strncmp(buf, tag, strlen(tag)) == 0) {
1133 t = buf + strlen(tag);
1134 t += strspn(t, " \t");
1135 if (strncmp(t, "OK", 2) == 0)
1143 static int imap_delete(int sock, struct query *ctl, int number)
1144 /* set delete flag for given message */
1149 /* expunges change the fetch numbers */
1153 * Use SILENT if possible as a minor throughput optimization.
1154 * Note: this has been dropped from IMAP4rev1.
1156 * We set Seen because there are some IMAP servers (notably HP
1157 * OpenMail) that do message-receipt DSNs, but only when the seen
1158 * bit is set. This is the appropriate time -- we get here right
1159 * after the local SMTP response that says delivery was
1162 if ((ok = gen_transact(sock,
1163 imap_version == IMAP4
1164 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1165 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1172 * We do an expunge after expunge_period messages, rather than
1173 * just before quit, so that a line hit during a long session
1174 * won't result in lots of messages being fetched again during
1177 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1179 if ((ok = internal_expunge(sock)))
1186 static int imap_mark_seen(int sock, struct query *ctl, int number)
1187 /* mark the given message as seen */
1190 return(gen_transact(sock,
1191 imap_version == IMAP4
1192 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1193 : "STORE %d +FLAGS (\\Seen)",
1197 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1198 /* cleanup mailbox before we idle or switch to another one */
1202 internal_expunge(sock);
1206 static int imap_logout(int sock, struct query *ctl)
1207 /* send logout command */
1210 /* if any un-expunged deletions remain, ship an expunge now */
1212 internal_expunge(sock);
1215 /* Memory clean-up */
1216 if (unseen_messages)
1217 free(unseen_messages);
1218 #endif /* USE_SEARCH */
1220 return(gen_transact(sock, "LOGOUT"));
1223 static const struct method imap =
1225 "IMAP", /* Internet Message Access Protocol */
1226 "imap", /* service (plain and TLS) */
1227 "imaps", /* service (SSL) */
1228 TRUE, /* this is a tagged protocol */
1229 FALSE, /* no message delimiter */
1230 imap_ok, /* parse command response */
1231 imap_getauth, /* get authorization */
1232 imap_getrange, /* query range of messages */
1233 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1234 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1235 imap_is_old, /* no UID check */
1236 imap_fetch_headers, /* request given message headers */
1237 imap_fetch_body, /* request given message body */
1238 imap_trail, /* eat message trailer */
1239 imap_delete, /* delete the message */
1240 imap_mark_seen, /* how to mark a message as seen */
1241 imap_end_mailbox_poll, /* end-of-mailbox processing */
1242 imap_logout, /* expunge and exit */
1243 TRUE, /* yes, we can re-poll */
1246 int doIMAP(struct query *ctl)
1247 /* retrieve messages using IMAP Version 2bis or Version 4 */
1249 return(do_protocol(ctl, &imap));
1252 /* imap.c ends here */