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"
23 #endif /* OPIE_ENABLE */
25 #ifndef strstr /* glibc-2.1 declares this as a macro */
26 extern char *strstr(const char *, const char *); /* needed on sysV68 R3V7.1. */
29 /* imap_version values */
30 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
31 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
32 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
34 static int count = 0, recentcount = 0, unseen = 0, deletions = 0;
35 static int recentcount_ok = 0;
36 static unsigned int startcount = 1;
37 static int expunged, expunge_period, saved_timeout = 0;
38 static int imap_version, preauth;
39 static flag do_idle, has_idle;
40 static char capabilities[MSGBUFSIZE+1];
41 static unsigned int *unseen_messages;
43 static int imap_ok(int sock, char *argbuf)
44 /* parse command response */
46 char buf[MSGBUFSIZE+1];
52 if ((ok = gen_recv(sock, buf, sizeof(buf))))
55 /* all tokens in responses are caseblind */
56 for (cp = buf; *cp; cp++)
57 if (islower((unsigned char)*cp))
58 *cp = toupper((unsigned char)*cp);
60 /* interpret untagged status responses */
61 if (strstr(buf, "* CAPABILITY"))
63 strncpy(capabilities, buf + 12, sizeof(capabilities));
64 capabilities[sizeof(capabilities)-1] = '\0';
66 else if (strstr(buf, "EXISTS"))
70 * Don't trust the message count passed by the server.
71 * Without this check, it might be possible to do a
72 * DNS-spoofing attack that would pass back a ridiculous
73 * count, and allocate a malloc area that would overlap
74 * a portion of the stack.
76 if (count > INT_MAX/sizeof(int))
78 report(stderr, "bogus message count!");
83 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
84 * we can't wait for the tag matching the IDLE; we have to tell the
85 * server the IDLE is finished by shipping back a DONE when we
86 * see an EXISTS. Only after that will a tagged response be
87 * shipped. The idling flag also gets cleared on a timeout.
89 if (stage == STAGE_IDLE)
91 /* If IDLE isn't supported, we were only sending NOOPs anyway. */
94 /* we do our own write and report here to disable tagging */
95 SockWrite(sock, "DONE\r\n", 6);
96 if (outlevel >= O_MONITOR)
97 report(stdout, "IMAP> DONE\n");
100 mytimeout = saved_timeout;
104 /* a space is required to avoid confusion with the \Recent flag */
105 else if (strstr(buf, " RECENT"))
108 recentcount = atoi(buf+2);
110 else if (strstr(buf, "EXPUNGE") && !strstr(buf, "OK"))
112 count -= atoi(buf+2);
116 else if (strstr(buf, "PREAUTH"))
119 * The server may decide to make the mailbox read-only,
120 * which causes fetchmail to go into a endless loop
121 * fetching the same message over and over again.
123 * However, for check_only, we use EXAMINE which will
124 * mark the mailbox read-only as per the RFC.
126 * This checks for the condition and aborts if
127 * the mailbox is read-only.
129 * See RFC 2060 section 6.3.1 (SELECT).
130 * See RFC 2060 section 6.3.2 (EXAMINE).
132 else if (!check_only && strstr(buf, "[READ-ONLY]"))
135 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
148 for (cp = buf; !isspace((unsigned char)*cp); cp++)
150 while (isspace((unsigned char)*cp))
153 if (strncasecmp(cp, "OK", 2) == 0)
159 else if (strncasecmp(cp, "BAD", 3) == 0)
161 else if (strncasecmp(cp, "NO", 2) == 0)
163 if (stage == STAGE_GETAUTH)
164 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
176 static tSmbNtlmAuthRequest request;
177 static tSmbNtlmAuthChallenge challenge;
178 static tSmbNtlmAuthResponse response;
181 * NTLM support by Grant Edwards.
183 * Handle MS-Exchange NTLM authentication method. This is the same
184 * as the NTLM auth used by Samba for SMB related services. We just
185 * encode the packets in base64 instead of sending them out via a
188 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
191 static int do_imap_ntlm(int sock, struct query *ctl)
196 gen_send(sock, "AUTHENTICATE NTLM");
198 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
201 if (msgbuf[0] != '+')
204 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
206 if (outlevel >= O_DEBUG)
207 dumpSmbNtlmAuthRequest(stdout, &request);
209 memset(msgbuf,0,sizeof msgbuf);
210 to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
212 if (outlevel >= O_MONITOR)
213 report(stdout, "IMAP> %s\n", msgbuf);
215 strcat(msgbuf,"\r\n");
216 SockWrite (sock, msgbuf, strlen (msgbuf));
218 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
221 len = from64tobits ((char*)&challenge, msgbuf, sizeof(challenge));
223 if (outlevel >= O_DEBUG)
224 dumpSmbNtlmAuthChallenge(stdout, &challenge);
226 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
228 if (outlevel >= O_DEBUG)
229 dumpSmbNtlmAuthResponse(stdout, &response);
231 memset(msgbuf,0,sizeof msgbuf);
232 to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
234 if (outlevel >= O_MONITOR)
235 report(stdout, "IMAP> %s\n", msgbuf);
237 strcat(msgbuf,"\r\n");
238 SockWrite (sock, msgbuf, strlen (msgbuf));
240 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
243 if (strstr (msgbuf, "OK"))
250 static int imap_canonicalize(char *result, char *raw, int maxlen)
251 /* encode an IMAP password as per RFC1730's quoting conventions */
256 for (i = 0; i < strlen(raw) && i < maxlen; i++)
258 if ((raw[i] == '\\') || (raw[i] == '"'))
260 result[j++] = raw[i];
267 static void capa_probe(int sock, struct query *ctl)
268 /* set capability variables from a CAPA probe */
272 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
273 capabilities[0] = '\0';
274 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
278 /* capability checks are supposed to be caseblind */
279 for (cp = capabilities; *cp; cp++)
282 /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
283 should expect a response in mixed-case */
284 if (strstr(capabilities, "IMAP4REV1"))
286 imap_version = IMAP4rev1;
287 if (outlevel >= O_DEBUG)
288 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
292 imap_version = IMAP4;
293 if (outlevel >= O_DEBUG)
294 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
297 else if (ok == PS_ERROR)
299 imap_version = IMAP2;
300 if (outlevel >= O_DEBUG)
301 report(stdout, GT_("Protocol identified as IMAP2 or IMAP2BIS\n"));
305 * Handle idling. We depend on coming through here on startup
306 * and after each timeout (including timeouts during idles).
311 if (strstr(capabilities, "IDLE"))
315 if (outlevel >= O_VERBOSE)
316 report(stdout, GT_("will idle after poll\n"));
319 peek_capable = (imap_version >= IMAP4);
322 static int imap_getauth(int sock, struct query *ctl, char *greeting)
323 /* apply for connection authorization */
327 flag did_stls = FALSE;
328 #endif /* SSL_ENABLE */
331 * Assumption: expunges are cheap, so we want to do them
332 * after every message unless user said otherwise.
334 if (NUM_SPECIFIED(ctl->expunge))
335 expunge_period = NUM_VALUE_OUT(ctl->expunge);
339 capa_probe(sock, ctl);
342 * If either (a) we saw a PREAUTH token in the greeting, or
343 * (b) the user specified ssh preauthentication, then we're done.
345 if (preauth || ctl->server.authenticate == A_SSH)
347 preauth = FALSE; /* reset for the next session */
352 if ((!ctl->sslproto || !strcmp(ctl->sslproto,"tls1"))
354 && strstr(capabilities, "STARTTLS"))
358 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
359 ok = gen_transact(sock, "STARTTLS");
361 /* We use "tls1" instead of ctl->sslproto, as we want STARTTLS,
362 * not other SSL protocols
364 if (ok == PS_SUCCESS &&
365 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
367 if (!ctl->sslproto && !ctl->wehaveauthed)
369 ctl->sslproto = xstrdup("");
370 /* repoll immediately */
374 GT_("SSL connection failed.\n"));
380 * RFC 2595 says this:
382 * "Once TLS has been started, the client MUST discard cached
383 * information about server capabilities and SHOULD re-issue the
384 * CAPABILITY command. This is necessary to protect against
385 * man-in-the-middle attacks which alter the capabilities list prior
386 * to STARTTLS. The server MAY advertise different capabilities
389 capa_probe(sock, ctl);
391 #endif /* SSL_ENABLE */
394 * Time to authenticate the user.
395 * Try the protocol variants that don't require passwords first.
400 if ((ctl->server.authenticate == A_ANY
401 || ctl->server.authenticate == A_GSSAPI)
402 && strstr(capabilities, "AUTH=GSSAPI"))
403 if(ok = do_gssauth(sock, "AUTHENTICATE", "imap", ctl->server.truename, ctl->remotename))
405 /* SASL cancellation of authentication */
407 if(ctl->server.authenticate != A_ANY)
415 if ((ctl->server.authenticate == A_ANY
416 || ctl->server.authenticate == A_KERBEROS_V4
417 || ctl->server.authenticate == A_KERBEROS_V5)
418 && strstr(capabilities, "AUTH=KERBEROS_V4"))
420 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
422 /* SASL cancellation of authentication */
424 if(ctl->server.authenticate != A_ANY)
430 #endif /* KERBEROS_V4 */
433 * No such luck. OK, now try the variants that mask your password
434 * in a challenge-response.
437 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
438 || ctl->server.authenticate == A_CRAM_MD5)
440 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
442 /* SASL cancellation of authentication */
444 if(ctl->server.authenticate != A_ANY)
452 if ((ctl->server.authenticate == A_ANY
453 || ctl->server.authenticate == A_OTP)
454 && strstr(capabilities, "AUTH=X-OTP")) {
455 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
457 /* SASL cancellation of authentication */
459 if(ctl->server.authenticate != A_ANY)
466 if (ctl->server.authenticate == A_OTP)
469 GT_("Required OTP capability not compiled into fetchmail\n"));
471 #endif /* OPIE_ENABLE */
474 if ((ctl->server.authenticate == A_ANY
475 || ctl->server.authenticate == A_NTLM)
476 && strstr (capabilities, "AUTH=NTLM")) {
477 if ((ok = do_imap_ntlm(sock, ctl)))
479 /* SASL cancellation of authentication */
481 if(ctl->server.authenticate != A_ANY)
488 if (ctl->server.authenticate == A_NTLM)
491 GT_("Required NTLM capability not compiled into fetchmail\n"));
493 #endif /* NTLM_ENABLE */
495 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
496 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
497 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
500 GT_("Required LOGIN capability not supported by server\n"));
502 #endif /* __UNUSED__ */
505 * We're stuck with sending the password en clair.
506 * The reason for this odd-looking logic is that some
507 * servers return LOGINDISABLED even though login
508 * actually works. So arrange things in such a way that
509 * setting auth passwd makes it ignore this capability.
511 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
512 || ctl->server.authenticate == A_PASSWORD)
514 /* these sizes guarantee no buffer overflow */
515 char remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
517 imap_canonicalize(remotename, ctl->remotename, NAMELEN);
518 imap_canonicalize(password, ctl->password, PASSWORDLEN);
521 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
523 strcpy(shroud, "\"");
524 strcat(shroud, password);
525 strcat(shroud, "\"");
527 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
530 /* this is for servers which claim to support TLS, but actually
532 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
534 ctl->sslproto = xstrdup("");
535 /* repoll immediately */
541 /* SASL cancellation of authentication */
543 if(ctl->server.authenticate != A_ANY)
553 static int internal_expunge(int sock)
554 /* ship an expunge, resetting associated counters */
560 if ((ok = gen_transact(sock, "EXPUNGE")))
563 /* some servers do not report RECENT after an EXPUNGE. in this case,
564 * the previous value of recentcount is just ignored. */
568 expunged += deletions;
571 #ifdef IMAP_UID /* not used */
573 #endif /* IMAP_UID */
578 static int imap_idle(int sock)
579 /* start an RFC2177 IDLE, or fake one if unsupported */
584 saved_timeout = mytimeout;
587 /* special timeout to terminate the IDLE and re-issue it
588 * at least every 28 minutes:
589 * (the server may have an inactivity timeout) */
590 mytimeout = 1680; /* 28 min */
591 /* enter IDLE mode */
592 ok = gen_transact(sock, "IDLE");
594 if (ok == PS_IDLETIMEOUT) {
595 /* send "DONE" continuation */
596 SockWrite(sock, "DONE\r\n", 6);
597 if (outlevel >= O_MONITOR)
598 report(stdout, "IMAP> DONE\n");
600 /* not idle timeout */
602 } else { /* no idle support, fake it */
603 /* when faking an idle, we can't assume the server will
604 * send us the new messages out of the blue (RFC2060);
605 * this timeout is potentially the delay before we notice
606 * new mail (can be small since NOOP checking is cheap) */
608 ok = gen_transact(sock, "NOOP");
609 /* if there's an error (not likely) or we just found mail (stage
610 * has changed, timeout has also been restored), we're done */
611 if (ok != 0 || stage != STAGE_IDLE)
614 /* wait (briefly) for an unsolicited status update */
615 ok = imap_ok(sock, NULL);
616 /* again, this is new mail or an error */
617 if (ok != PS_IDLETIMEOUT)
621 /* restore normal timeout value */
622 mytimeout = saved_timeout;
625 /* get OK IDLE message */
627 return imap_ok(sock, NULL);
632 static int imap_getrange(int sock,
635 int *countp, int *newp, int *bytes)
636 /* get range of messages to be fetched */
639 char buf[MSGBUFSIZE+1], *cp;
641 /* find out how many messages are waiting */
647 * We have to have an expunge here, otherwise the re-poll will
648 * infinite-loop picking up un-expunged messages -- unless the
649 * expunge period is one and we've been nuking each message
650 * just after deletion.
654 ok = internal_expunge(sock);
657 report(stderr, GT_("expunge failed\n"));
663 * recentcount is already set here by the last imap command which
664 * returned RECENT on detecting new mail. if recentcount is 0, wait
668 /* this is a while loop because imap_idle() might return on other
669 * mailbox changes also */
670 while (recentcount == 0 && do_idle) {
672 ok = imap_idle(sock);
675 report(stderr, GT_("re-poll failed\n"));
679 /* if recentcount is 0, return no mail */
680 if (recentcount == 0)
682 if (outlevel >= O_DEBUG)
683 report(stdout, GT_("%d messages waiting after re-poll\n"), count);
688 ok = gen_transact(sock,
689 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
690 folder ? folder : "INBOX");
693 report(stderr, GT_("mailbox selection failed\n"));
696 else if (outlevel >= O_DEBUG)
697 report(stdout, GT_("%d messages waiting after first poll\n"), count);
699 /* no messages? then we may need to idle until we get some */
700 while (count == 0 && do_idle) {
701 ok = imap_idle(sock);
704 report(stderr, GT_("re-poll failed\n"));
710 * We should have an expunge here to
711 * a) avoid fetching deleted mails during 'fetchall'
712 * b) getting a wrong count of mails during 'no fetchall'
714 if (!check_only && !ctl->keep && count > 0)
716 ok = internal_expunge(sock);
719 report(stderr, GT_("expunge failed\n"));
722 if (outlevel >= O_DEBUG)
723 report(stdout, GT_("%d messages waiting after expunge\n"), count);
731 /* OK, now get a count of unseen messages and their indices */
732 if (!ctl->fetchall && count > 0)
735 free(unseen_messages);
736 unseen_messages = xmalloc(count * sizeof(unsigned int));
737 memset(unseen_messages, 0, count * sizeof(unsigned int));
740 /* don't count deleted messages, in case user enabled keep last time */
741 gen_send(sock, "SEARCH UNSEEN NOT DELETED");
743 ok = gen_recv(sock, buf, sizeof(buf));
746 report(stderr, GT_("search for unseen messages failed\n"));
749 else if ((cp = strstr(buf, "* SEARCH")))
753 cp += 8; /* skip "* SEARCH" */
754 /* startcount is higher than count so that if there are no
755 * unseen messages, imap_getsizes() will not need to do
757 startcount = count + 1;
759 while (*cp && unseen < count)
761 /* skip whitespace */
762 while (*cp && isspace((unsigned char)*cp))
768 * Message numbers are between 1 and 2^32 inclusive,
769 * so unsigned int is large enough.
771 um=(unsigned int)strtol(cp,&ep,10);
774 unseen_messages[unseen++] = um;
775 if (outlevel >= O_DEBUG)
776 report(stdout, GT_("%u is unseen\n"), um);
785 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
787 if (outlevel >= O_DEBUG && unseen > 0)
788 report(stdout, GT_("%u is first unseen\n"), startcount);
800 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
801 /* capture the sizes of messages #first-#last */
803 char buf [MSGBUFSIZE+1];
806 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
807 * won't accept 1:1 as valid set syntax. Some implementors
808 * should be taken out and shot for excessive anality.
810 * Microsoft Exchange (brain-dead piece of crap that it is)
811 * sometimes gets its knickers in a knot about bodiless messages.
812 * You may see responses like this:
814 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
815 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
816 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
817 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
818 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
819 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
820 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
821 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
822 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
823 * fetchmail: IMAP< A0004 NO The requested item could not be found.
825 * This means message 1 has only headers. For kicks and grins
826 * you can telnet in and look:
828 * A003 NO The requested item could not be found.
829 * A004 fetch 1 rfc822.header
830 * A004 NO The requested item could not be found.
832 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
833 * A006 OK FETCH completed.
835 * To get around this, we terminate the read loop on a NO and count
836 * on the fact that the sizes array has been preinitialized with a
837 * known-bad size value.
840 /* expunges change the fetch numbers */
845 gen_send(sock, "FETCH %d RFC822.SIZE", last);
846 else if (last > first)
847 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
848 else /* no unseen messages! */
852 unsigned int num, size;
856 if ((ok = gen_recv(sock, buf, sizeof(buf))))
858 /* we want response matching to be case-insensitive */
859 for (cp = buf; *cp; cp++)
861 /* an untagged NO means that a message was not readable */
862 if (strstr(buf, "* NO"))
864 else if (strstr(buf, "OK") || strstr(buf, "NO"))
866 else if (sscanf(buf, "* %u FETCH (RFC822.SIZE %u)", &num, &size) == 2)
868 if (num >= first && num <= last)
869 sizes[num - first] = size;
871 report(stderr, "Warning: ignoring bogus data for message sizes returned by the server.\n");
878 static int imap_getsizes(int sock, int count, int *sizes)
879 /* capture the sizes of all messages */
881 return imap_getpartialsizes(sock, 1, count, sizes);
884 static int imap_is_old(int sock, struct query *ctl, int number)
885 /* is the given message old? */
891 * Expunges change the fetch numbers, but unseen_messages contains
892 * indices from before any expungees were done. So neither the
893 * argument nor the values in message_sequence need to be decremented.
897 for (i = 0; i < unseen; i++)
898 if (unseen_messages[i] == number)
907 static char *skip_token(char *ptr)
909 while(isspace((unsigned char)*ptr)) ptr++;
910 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
911 while(isspace((unsigned char)*ptr)) ptr++;
915 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
916 /* request headers of nth message */
918 char buf [MSGBUFSIZE+1];
921 /* expunges change the fetch numbers */
925 * This is blessed by RFC1176, RFC1730, RFC2060.
926 * According to the RFCs, it should *not* set the \Seen flag.
928 gen_send(sock, "FETCH %d RFC822.HEADER", number);
930 /* looking for FETCH response */
936 if ((ok = gen_recv(sock, buf, sizeof(buf))))
938 ptr = skip_token(buf); /* either "* " or "AXXXX " */
939 if (sscanf(ptr, "%d FETCH (%*s {%d}", &num, lenp) == 2)
941 /* try to recover from chronically fucked-up M$ Exchange servers */
942 else if (!strncmp(ptr, "NO", 2))
944 /* wait for a tagged response */
945 if (strstr (buf, "* NO"))
947 return(PS_TRANSIENT);
949 else if (!strncmp(ptr, "BAD", 3))
951 /* wait for a tagged response */
952 if (strstr (buf, "* BAD"))
954 return(PS_TRANSIENT);
964 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
965 /* request body of nth message */
967 char buf [MSGBUFSIZE+1], *cp;
970 /* expunges change the fetch numbers */
974 * If we're using IMAP4, we can fetch the message without setting its
975 * seen flag. This is good! It means that if the protocol exchange
976 * craps out during the message, it will still be marked `unseen' on
979 * According to RFC2060, and Mark Crispin the IMAP maintainer,
980 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
981 * equivalent". However, we know of at least one server that
982 * treats them differently in the presence of MIME attachments;
983 * the latter form downloads the attachment, the former does not.
984 * The server is InterChange, and the fool who implemented this
985 * misfeature ought to be strung up by his thumbs.
987 * When I tried working around this by disabling use of the 4rev1 form,
988 * I found that doing this breaks operation with M$ Exchange.
989 * Annoyingly enough, Exchange's refusal to cope is technically legal
990 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
991 * standards, to find a way to make standards compliance irritating....
993 switch (imap_version)
995 case IMAP4rev1: /* RFC 2060 */
996 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
999 case IMAP4: /* RFC 1730 */
1000 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1003 default: /* RFC 1176 */
1004 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1008 /* looking for FETCH response */
1012 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1015 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1021 * Try to extract a length from the FETCH response. RFC2060 requires
1022 * it to be present, but at least one IMAP server (Novell GroupWise)
1023 * botches this. The overflow check is needed because of a broken
1024 * server called dbmail that returns huge garbage lengths.
1026 if ((cp = strchr(buf, '{'))) {
1028 *lenp = (int)strtol(cp + 1, (char **)NULL, 10);
1029 if (errno == ERANGE && (*lenp == LONG_MAX || *lenp == LONG_MIN))
1030 *lenp = -1; /* length is too big/small for us to handle */
1033 *lenp = -1; /* missing length part in FETCH reponse */
1038 static int imap_trail(int sock, struct query *ctl, int number)
1039 /* discard tail of FETCH response after reading message text */
1041 /* expunges change the fetch numbers */
1042 /* number -= expunged; */
1046 char buf[MSGBUFSIZE+1];
1049 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1052 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1053 if (strstr(buf, "OK"))
1060 static int imap_delete(int sock, struct query *ctl, int number)
1061 /* set delete flag for given message */
1065 /* expunges change the fetch numbers */
1069 * Use SILENT if possible as a minor throughput optimization.
1070 * Note: this has been dropped from IMAP4rev1.
1072 * We set Seen because there are some IMAP servers (notably HP
1073 * OpenMail) that do message-receipt DSNs, but only when the seen
1074 * bit is set. This is the appropriate time -- we get here right
1075 * after the local SMTP response that says delivery was
1078 if ((ok = gen_transact(sock,
1079 imap_version == IMAP4
1080 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1081 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1088 * We do an expunge after expunge_period messages, rather than
1089 * just before quit, so that a line hit during a long session
1090 * won't result in lots of messages being fetched again during
1093 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1094 internal_expunge(sock);
1099 static int imap_mark_seen(int sock, struct query *ctl, int number)
1100 /* mark the given message as seen */
1102 return(gen_transact(sock,
1103 imap_version == IMAP4
1104 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1105 : "STORE %d +FLAGS (\\Seen)",
1109 static int imap_logout(int sock, struct query *ctl)
1110 /* send logout command */
1112 /* if any un-expunged deletions remain, ship an expunge now */
1114 internal_expunge(sock);
1117 /* Memory clean-up */
1118 if (unseen_messages)
1119 free(unseen_messages);
1120 #endif /* USE_SEARCH */
1122 return(gen_transact(sock, "LOGOUT"));
1125 static const struct method imap =
1127 "IMAP", /* Internet Message Access Protocol */
1131 #else /* INET6_ENABLE */
1132 143, /* standard IMAP2bis/IMAP4 port */
1133 993, /* ssl IMAP2bis/IMAP4 port */
1134 #endif /* INET6_ENABLE */
1135 TRUE, /* this is a tagged protocol */
1136 FALSE, /* no message delimiter */
1137 imap_ok, /* parse command response */
1138 imap_getauth, /* get authorization */
1139 imap_getrange, /* query range of messages */
1140 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1141 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1142 imap_is_old, /* no UID check */
1143 imap_fetch_headers, /* request given message headers */
1144 imap_fetch_body, /* request given message body */
1145 imap_trail, /* eat message trailer */
1146 imap_delete, /* delete the message */
1147 imap_mark_seen, /* how to mark a message as seen */
1148 imap_logout, /* expunge and exit */
1149 TRUE, /* yes, we can re-poll */
1152 int doIMAP(struct query *ctl)
1153 /* retrieve messages using IMAP Version 2bis or Version 4 */
1155 return(do_protocol(ctl, &imap));
1158 /* imap.c ends here */