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 unsigned int startcount = 1;
36 static int expunged, expunge_period, saved_timeout = 0;
37 static int imap_version, preauth;
38 static flag do_idle, has_idle;
39 static char capabilities[MSGBUFSIZE+1];
40 static unsigned int *unseen_messages;
42 static int imap_ok(int sock, char *argbuf)
43 /* parse command response */
45 char buf[MSGBUFSIZE+1];
51 if ((ok = gen_recv(sock, buf, sizeof(buf))))
54 /* all tokens in responses are caseblind */
55 for (cp = buf; *cp; cp++)
56 if (islower((unsigned char)*cp))
57 *cp = toupper((unsigned char)*cp);
59 /* interpret untagged status responses */
60 if (strstr(buf, "* CAPABILITY"))
62 strncpy(capabilities, buf + 12, sizeof(capabilities));
63 capabilities[sizeof(capabilities)-1] = '\0';
65 else if (strstr(buf, "EXISTS"))
69 * Don't trust the message count passed by the server.
70 * Without this check, it might be possible to do a
71 * DNS-spoofing attack that would pass back a ridiculous
72 * count, and allocate a malloc area that would overlap
73 * a portion of the stack.
75 if (count > INT_MAX/sizeof(int))
77 report(stderr, "bogus message count!");
82 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
83 * we can't wait for the tag matching the IDLE; we have to tell the
84 * server the IDLE is finished by shipping back a DONE when we
85 * see an EXISTS. Only after that will a tagged response be
86 * shipped. The idling flag also gets cleared on a timeout.
88 if (stage == STAGE_IDLE)
90 /* If IDLE isn't supported, we were only sending NOOPs anyway. */
93 /* we do our own write and report here to disable tagging */
94 SockWrite(sock, "DONE\r\n", 6);
95 if (outlevel >= O_MONITOR)
96 report(stdout, "IMAP> DONE\n");
99 mytimeout = saved_timeout;
103 /* a space is required to avoid confusion with the \Recent flag */
104 else if (strstr(buf, " RECENT"))
106 recentcount = atoi(buf+2);
108 else if (strstr(buf, "PREAUTH"))
111 * The server may decide to make the mailbox read-only,
112 * which causes fetchmail to go into a endless loop
113 * fetching the same message over and over again.
115 * However, for check_only, we use EXAMINE which will
116 * mark the mailbox read-only as per the RFC.
118 * This checks for the condition and aborts if
119 * the mailbox is read-only.
121 * See RFC 2060 section 6.3.1 (SELECT).
122 * See RFC 2060 section 6.3.2 (EXAMINE).
124 else if (!check_only && strstr(buf, "[READ-ONLY]"))
127 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
140 for (cp = buf; !isspace((unsigned char)*cp); cp++)
142 while (isspace((unsigned char)*cp))
145 if (strncasecmp(cp, "OK", 2) == 0)
151 else if (strncasecmp(cp, "BAD", 3) == 0)
153 else if (strncasecmp(cp, "NO", 2) == 0)
155 if (stage == STAGE_GETAUTH)
156 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
168 static tSmbNtlmAuthRequest request;
169 static tSmbNtlmAuthChallenge challenge;
170 static tSmbNtlmAuthResponse response;
173 * NTLM support by Grant Edwards.
175 * Handle MS-Exchange NTLM authentication method. This is the same
176 * as the NTLM auth used by Samba for SMB related services. We just
177 * encode the packets in base64 instead of sending them out via a
180 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
183 static int do_imap_ntlm(int sock, struct query *ctl)
188 gen_send(sock, "AUTHENTICATE NTLM");
190 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
193 if (msgbuf[0] != '+')
196 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
198 if (outlevel >= O_DEBUG)
199 dumpSmbNtlmAuthRequest(stdout, &request);
201 memset(msgbuf,0,sizeof msgbuf);
202 to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
204 if (outlevel >= O_MONITOR)
205 report(stdout, "IMAP> %s\n", msgbuf);
207 strcat(msgbuf,"\r\n");
208 SockWrite (sock, msgbuf, strlen (msgbuf));
210 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
213 len = from64tobits ((char*)&challenge, msgbuf, sizeof(challenge));
215 if (outlevel >= O_DEBUG)
216 dumpSmbNtlmAuthChallenge(stdout, &challenge);
218 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
220 if (outlevel >= O_DEBUG)
221 dumpSmbNtlmAuthResponse(stdout, &response);
223 memset(msgbuf,0,sizeof msgbuf);
224 to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
226 if (outlevel >= O_MONITOR)
227 report(stdout, "IMAP> %s\n", msgbuf);
229 strcat(msgbuf,"\r\n");
230 SockWrite (sock, msgbuf, strlen (msgbuf));
232 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
235 if (strstr (msgbuf, "OK"))
242 static int imap_canonicalize(char *result, char *raw, int maxlen)
243 /* encode an IMAP password as per RFC1730's quoting conventions */
248 for (i = 0; i < strlen(raw) && i < maxlen; i++)
250 if ((raw[i] == '\\') || (raw[i] == '"'))
252 result[j++] = raw[i];
259 static void capa_probe(int sock, struct query *ctl)
260 /* set capability variables from a CAPA probe */
264 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
265 capabilities[0] = '\0';
266 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
270 /* capability checks are supposed to be caseblind */
271 for (cp = capabilities; *cp; cp++)
274 /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
275 should expect a response in mixed-case */
276 if (strstr(capabilities, "IMAP4REV1"))
278 imap_version = IMAP4rev1;
279 if (outlevel >= O_DEBUG)
280 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
284 imap_version = IMAP4;
285 if (outlevel >= O_DEBUG)
286 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
289 else if (ok == PS_ERROR)
291 imap_version = IMAP2;
292 if (outlevel >= O_DEBUG)
293 report(stdout, GT_("Protocol identified as IMAP2 or IMAP2BIS\n"));
297 * Handle idling. We depend on coming through here on startup
298 * and after each timeout (including timeouts during idles).
303 if (strstr(capabilities, "IDLE"))
307 if (outlevel >= O_VERBOSE)
308 report(stdout, GT_("will idle after poll\n"));
311 peek_capable = (imap_version >= IMAP4);
314 static int imap_getauth(int sock, struct query *ctl, char *greeting)
315 /* apply for connection authorization */
319 flag did_stls = FALSE;
320 #endif /* SSL_ENABLE */
323 * Assumption: expunges are cheap, so we want to do them
324 * after every message unless user said otherwise.
326 if (NUM_SPECIFIED(ctl->expunge))
327 expunge_period = NUM_VALUE_OUT(ctl->expunge);
331 capa_probe(sock, ctl);
334 * If either (a) we saw a PREAUTH token in the greeting, or
335 * (b) the user specified ssh preauthentication, then we're done.
337 if (preauth || ctl->server.authenticate == A_SSH)
339 preauth = FALSE; /* reset for the next session */
344 if ((!ctl->sslproto || !strcmp(ctl->sslproto,"tls1"))
346 && strstr(capabilities, "STARTTLS"))
350 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
351 ok = gen_transact(sock, "STARTTLS");
353 /* We use "tls1" instead of ctl->sslproto, as we want STARTTLS,
354 * not other SSL protocols
356 if (ok == PS_SUCCESS &&
357 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
359 if (!ctl->sslproto && !ctl->wehaveauthed)
361 ctl->sslproto = xstrdup("");
362 /* repoll immediately */
366 GT_("SSL connection failed.\n"));
372 * RFC 2595 says this:
374 * "Once TLS has been started, the client MUST discard cached
375 * information about server capabilities and SHOULD re-issue the
376 * CAPABILITY command. This is necessary to protect against
377 * man-in-the-middle attacks which alter the capabilities list prior
378 * to STARTTLS. The server MAY advertise different capabilities
381 capa_probe(sock, ctl);
383 #endif /* SSL_ENABLE */
386 * Time to authenticate the user.
387 * Try the protocol variants that don't require passwords first.
392 if ((ctl->server.authenticate == A_ANY
393 || ctl->server.authenticate == A_GSSAPI)
394 && strstr(capabilities, "AUTH=GSSAPI"))
395 if(ok = do_gssauth(sock, "AUTHENTICATE", "imap", ctl->server.truename, ctl->remotename))
397 /* SASL cancellation of authentication */
399 if(ctl->server.authenticate != A_ANY)
407 if ((ctl->server.authenticate == A_ANY
408 || ctl->server.authenticate == A_KERBEROS_V4
409 || ctl->server.authenticate == A_KERBEROS_V5)
410 && strstr(capabilities, "AUTH=KERBEROS_V4"))
412 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
414 /* SASL cancellation of authentication */
416 if(ctl->server.authenticate != A_ANY)
422 #endif /* KERBEROS_V4 */
425 * No such luck. OK, now try the variants that mask your password
426 * in a challenge-response.
429 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
430 || ctl->server.authenticate == A_CRAM_MD5)
432 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
434 /* SASL cancellation of authentication */
436 if(ctl->server.authenticate != A_ANY)
444 if ((ctl->server.authenticate == A_ANY
445 || ctl->server.authenticate == A_OTP)
446 && strstr(capabilities, "AUTH=X-OTP")) {
447 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
449 /* SASL cancellation of authentication */
451 if(ctl->server.authenticate != A_ANY)
458 if (ctl->server.authenticate == A_OTP)
461 GT_("Required OTP capability not compiled into fetchmail\n"));
463 #endif /* OPIE_ENABLE */
466 if ((ctl->server.authenticate == A_ANY
467 || ctl->server.authenticate == A_NTLM)
468 && strstr (capabilities, "AUTH=NTLM")) {
469 if ((ok = do_imap_ntlm(sock, ctl)))
471 /* SASL cancellation of authentication */
473 if(ctl->server.authenticate != A_ANY)
480 if (ctl->server.authenticate == A_NTLM)
483 GT_("Required NTLM capability not compiled into fetchmail\n"));
485 #endif /* NTLM_ENABLE */
487 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
488 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
489 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
492 GT_("Required LOGIN capability not supported by server\n"));
494 #endif /* __UNUSED__ */
497 * We're stuck with sending the password en clair.
498 * The reason for this odd-looking logic is that some
499 * servers return LOGINDISABLED even though login
500 * actually works. So arrange things in such a way that
501 * setting auth passwd makes it ignore this capability.
503 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
504 || ctl->server.authenticate == A_PASSWORD)
506 /* these sizes guarantee no buffer overflow */
507 char remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
509 imap_canonicalize(remotename, ctl->remotename, NAMELEN);
510 imap_canonicalize(password, ctl->password, PASSWORDLEN);
513 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
515 strcpy(shroud, "\"");
516 strcat(shroud, password);
517 strcat(shroud, "\"");
519 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
522 /* this is for servers which claim to support TLS, but actually
524 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
526 ctl->sslproto = xstrdup("");
527 /* repoll immediately */
533 /* SASL cancellation of authentication */
535 if(ctl->server.authenticate != A_ANY)
545 static int internal_expunge(int sock)
546 /* ship an expunge, resetting associated counters */
550 if ((ok = gen_transact(sock, "EXPUNGE")))
553 expunged += deletions;
556 #ifdef IMAP_UID /* not used */
558 #endif /* IMAP_UID */
563 static int imap_idle(int sock)
564 /* start an RFC2177 IDLE, or fake one if unsupported */
569 saved_timeout = mytimeout;
572 /* special timeout to terminate the IDLE and re-issue it
573 * at least every 28 minutes:
574 * (the server may have an inactivity timeout) */
575 mytimeout = 1680; /* 28 min */
576 /* enter IDLE mode */
577 ok = gen_transact(sock, "IDLE");
579 if (ok == PS_IDLETIMEOUT) {
580 /* send "DONE" continuation */
581 SockWrite(sock, "DONE\r\n", 6);
582 if (outlevel >= O_MONITOR)
583 report(stdout, "IMAP> DONE\n");
585 /* not idle timeout */
587 } else { /* no idle support, fake it */
588 /* when faking an idle, we can't assume the server will
589 * send us the new messages out of the blue (RFC2060);
590 * this timeout is potentially the delay before we notice
591 * new mail (can be small since NOOP checking is cheap) */
593 ok = gen_transact(sock, "NOOP");
594 /* if there's an error (not likely) or we just found mail (stage
595 * has changed, timeout has also been restored), we're done */
596 if (ok != 0 || stage != STAGE_IDLE)
599 /* wait (briefly) for an unsolicited status update */
600 ok = imap_ok(sock, NULL);
601 /* again, this is new mail or an error */
602 if (ok != PS_IDLETIMEOUT)
606 /* restore normal timeout value */
607 mytimeout = saved_timeout;
610 /* get OK IDLE message */
612 return imap_ok(sock, NULL);
617 static int imap_getrange(int sock,
620 int *countp, int *newp, int *bytes)
621 /* get range of messages to be fetched */
624 char buf[MSGBUFSIZE+1], *cp;
626 /* find out how many messages are waiting */
632 * We have to have an expunge here, otherwise the re-poll will
633 * infinite-loop picking up un-expunged messages -- unless the
634 * expunge period is one and we've been nuking each message
635 * just after deletion.
639 ok = internal_expunge(sock);
642 report(stderr, GT_("expunge failed\n"));
648 * recentcount is already set here by the last imap command which
649 * returned RECENT on detecting new mail. if recentcount is 0, wait
653 /* some servers do not report RECENT after an EXPUNGE. this check
654 * forces an incorrect recentcount to be ignored. */
655 if (recentcount > count)
657 /* this is a while loop because imap_idle() might return on other
658 * mailbox changes also */
659 while (recentcount == 0 && do_idle) {
661 ok = imap_idle(sock);
664 report(stderr, GT_("re-poll failed\n"));
668 /* if recentcount is 0, return no mail */
669 if (recentcount == 0)
671 if (outlevel >= O_DEBUG)
672 report(stdout, GT_("%d messages waiting after re-poll\n"), count);
677 ok = gen_transact(sock,
678 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
679 folder ? folder : "INBOX");
682 report(stderr, GT_("mailbox selection failed\n"));
685 else if (outlevel >= O_DEBUG)
686 report(stdout, GT_("%d messages waiting after first poll\n"), count);
688 /* no messages? then we may need to idle until we get some */
689 while (count == 0 && do_idle) {
690 ok = imap_idle(sock);
693 report(stderr, GT_("re-poll failed\n"));
699 * We should have an expunge here to
700 * a) avoid fetching deleted mails during 'fetchall'
701 * b) getting a wrong count of mails during 'no fetchall'
703 if (!check_only && !ctl->keep && count > 0)
705 ok = internal_expunge(sock);
708 report(stderr, GT_("expunge failed\n"));
711 if (outlevel >= O_DEBUG)
712 report(stdout, GT_("%d messages waiting after expunge\n"), count);
720 /* OK, now get a count of unseen messages and their indices */
721 if (!ctl->fetchall && count > 0)
724 free(unseen_messages);
725 unseen_messages = xmalloc(count * sizeof(unsigned int));
726 memset(unseen_messages, 0, count * sizeof(unsigned int));
729 /* don't count deleted messages, in case user enabled keep last time */
730 gen_send(sock, "SEARCH UNSEEN NOT DELETED");
732 ok = gen_recv(sock, buf, sizeof(buf));
735 report(stderr, GT_("search for unseen messages failed\n"));
738 else if ((cp = strstr(buf, "* SEARCH")))
742 cp += 8; /* skip "* SEARCH" */
743 /* startcount is higher than count so that if there are no
744 * unseen messages, imap_getsizes() will not need to do
746 startcount = count + 1;
748 while (*cp && unseen < count)
750 /* skip whitespace */
751 while (*cp && isspace((unsigned char)*cp))
757 * Message numbers are between 1 and 2^32 inclusive,
758 * so unsigned int is large enough.
760 um=(unsigned int)strtol(cp,&ep,10);
763 unseen_messages[unseen++] = um;
764 if (outlevel >= O_DEBUG)
765 report(stdout, GT_("%u is unseen\n"), um);
774 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
776 if (outlevel >= O_DEBUG && unseen > 0)
777 report(stdout, GT_("%u is first unseen\n"), startcount);
789 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
790 /* capture the sizes of messages #first-#last */
792 char buf [MSGBUFSIZE+1];
795 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
796 * won't accept 1:1 as valid set syntax. Some implementors
797 * should be taken out and shot for excessive anality.
799 * Microsoft Exchange (brain-dead piece of crap that it is)
800 * sometimes gets its knickers in a knot about bodiless messages.
801 * You may see responses like this:
803 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
804 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
805 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
806 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
807 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
808 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
809 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
810 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
811 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
812 * fetchmail: IMAP< A0004 NO The requested item could not be found.
814 * This means message 1 has only headers. For kicks and grins
815 * you can telnet in and look:
817 * A003 NO The requested item could not be found.
818 * A004 fetch 1 rfc822.header
819 * A004 NO The requested item could not be found.
821 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
822 * A006 OK FETCH completed.
824 * To get around this, we terminate the read loop on a NO and count
825 * on the fact that the sizes array has been preinitialized with a
826 * known-bad size value.
829 /* expunges change the fetch numbers */
834 gen_send(sock, "FETCH %d RFC822.SIZE", last);
835 else if (last > first)
836 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
837 else /* no unseen messages! */
841 unsigned int num, size;
845 if ((ok = gen_recv(sock, buf, sizeof(buf))))
847 /* we want response matching to be case-insensitive */
848 for (cp = buf; *cp; cp++)
850 /* an untagged NO means that a message was not readable */
851 if (strstr(buf, "* NO"))
853 else if (strstr(buf, "OK") || strstr(buf, "NO"))
855 else if (sscanf(buf, "* %u FETCH (RFC822.SIZE %u)", &num, &size) == 2)
857 if (num >= first && num <= last)
858 sizes[num - first] = size;
860 report(stderr, "Warning: ignoring bogus data for message sizes returned by the server.\n");
867 static int imap_getsizes(int sock, int count, int *sizes)
868 /* capture the sizes of all messages */
870 return imap_getpartialsizes(sock, 1, count, sizes);
873 static int imap_is_old(int sock, struct query *ctl, int number)
874 /* is the given message old? */
880 * Expunges change the fetch numbers, but unseen_messages contains
881 * indices from before any expungees were done. So neither the
882 * argument nor the values in message_sequence need to be decremented.
886 for (i = 0; i < unseen; i++)
887 if (unseen_messages[i] == number)
896 static char *skip_token(char *ptr)
898 while(isspace((unsigned char)*ptr)) ptr++;
899 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
900 while(isspace((unsigned char)*ptr)) ptr++;
904 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
905 /* request headers of nth message */
907 char buf [MSGBUFSIZE+1];
910 /* expunges change the fetch numbers */
914 * This is blessed by RFC1176, RFC1730, RFC2060.
915 * According to the RFCs, it should *not* set the \Seen flag.
917 gen_send(sock, "FETCH %d RFC822.HEADER", number);
919 /* looking for FETCH response */
925 if ((ok = gen_recv(sock, buf, sizeof(buf))))
927 ptr = skip_token(buf); /* either "* " or "AXXXX " */
928 if (sscanf(ptr, "%d FETCH (%*s {%d}", &num, lenp) == 2)
930 /* try to recover from chronically fucked-up M$ Exchange servers */
931 else if (!strncmp(ptr, "NO", 2))
933 /* wait for a tagged response */
934 if (strstr (buf, "* NO"))
936 return(PS_TRANSIENT);
938 else if (!strncmp(ptr, "BAD", 3))
940 /* wait for a tagged response */
941 if (strstr (buf, "* BAD"))
943 return(PS_TRANSIENT);
953 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
954 /* request body of nth message */
956 char buf [MSGBUFSIZE+1], *cp;
959 /* expunges change the fetch numbers */
963 * If we're using IMAP4, we can fetch the message without setting its
964 * seen flag. This is good! It means that if the protocol exchange
965 * craps out during the message, it will still be marked `unseen' on
968 * According to RFC2060, and Mark Crispin the IMAP maintainer,
969 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
970 * equivalent". However, we know of at least one server that
971 * treats them differently in the presence of MIME attachments;
972 * the latter form downloads the attachment, the former does not.
973 * The server is InterChange, and the fool who implemented this
974 * misfeature ought to be strung up by his thumbs.
976 * When I tried working around this by disabling use of the 4rev1 form,
977 * I found that doing this breaks operation with M$ Exchange.
978 * Annoyingly enough, Exchange's refusal to cope is technically legal
979 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
980 * standards, to find a way to make standards compliance irritating....
982 switch (imap_version)
984 case IMAP4rev1: /* RFC 2060 */
985 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
988 case IMAP4: /* RFC 1730 */
989 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
992 default: /* RFC 1176 */
993 gen_send(sock, "FETCH %d RFC822.TEXT", number);
997 /* looking for FETCH response */
1001 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1004 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1010 * Try to extract a length from the FETCH response. RFC2060 requires
1011 * it to be present, but at least one IMAP server (Novell GroupWise)
1012 * botches this. The overflow check is needed because of a broken
1013 * server called dbmail that returns huge garbage lengths.
1015 if ((cp = strchr(buf, '{'))) {
1017 *lenp = (int)strtol(cp + 1, (char **)NULL, 10);
1018 if (errno == ERANGE && (*lenp == LONG_MAX || *lenp == LONG_MIN))
1019 *lenp = -1; /* length is too big/small for us to handle */
1022 *lenp = -1; /* missing length part in FETCH reponse */
1027 static int imap_trail(int sock, struct query *ctl, int number)
1028 /* discard tail of FETCH response after reading message text */
1030 /* expunges change the fetch numbers */
1031 /* number -= expunged; */
1035 char buf[MSGBUFSIZE+1];
1038 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1041 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1042 if (strstr(buf, "OK"))
1049 static int imap_delete(int sock, struct query *ctl, int number)
1050 /* set delete flag for given message */
1054 /* expunges change the fetch numbers */
1058 * Use SILENT if possible as a minor throughput optimization.
1059 * Note: this has been dropped from IMAP4rev1.
1061 * We set Seen because there are some IMAP servers (notably HP
1062 * OpenMail) that do message-receipt DSNs, but only when the seen
1063 * bit is set. This is the appropriate time -- we get here right
1064 * after the local SMTP response that says delivery was
1067 if ((ok = gen_transact(sock,
1068 imap_version == IMAP4
1069 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1070 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1077 * We do an expunge after expunge_period messages, rather than
1078 * just before quit, so that a line hit during a long session
1079 * won't result in lots of messages being fetched again during
1082 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1083 internal_expunge(sock);
1088 static int imap_mark_seen(int sock, struct query *ctl, int number)
1089 /* mark the given message as seen */
1091 return(gen_transact(sock,
1092 imap_version == IMAP4
1093 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1094 : "STORE %d +FLAGS (\\Seen)",
1098 static int imap_logout(int sock, struct query *ctl)
1099 /* send logout command */
1101 /* if any un-expunged deletions remain, ship an expunge now */
1103 internal_expunge(sock);
1106 /* Memory clean-up */
1107 if (unseen_messages)
1108 free(unseen_messages);
1109 #endif /* USE_SEARCH */
1111 return(gen_transact(sock, "LOGOUT"));
1114 static const struct method imap =
1116 "IMAP", /* Internet Message Access Protocol */
1120 #else /* INET6_ENABLE */
1121 143, /* standard IMAP2bis/IMAP4 port */
1122 993, /* ssl IMAP2bis/IMAP4 port */
1123 #endif /* INET6_ENABLE */
1124 TRUE, /* this is a tagged protocol */
1125 FALSE, /* no message delimiter */
1126 imap_ok, /* parse command response */
1127 imap_getauth, /* get authorization */
1128 imap_getrange, /* query range of messages */
1129 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1130 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1131 imap_is_old, /* no UID check */
1132 imap_fetch_headers, /* request given message headers */
1133 imap_fetch_body, /* request given message body */
1134 imap_trail, /* eat message trailer */
1135 imap_delete, /* delete the message */
1136 imap_mark_seen, /* how to mark a message as seen */
1137 imap_logout, /* expunge and exit */
1138 TRUE, /* yes, we can re-poll */
1141 int doIMAP(struct query *ctl)
1142 /* retrieve messages using IMAP Version 2bis or Version 4 */
1144 return(do_protocol(ctl, &imap));
1147 /* imap.c ends here */