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 static int count = 0, recentcount = 0, unseen = 0, deletions = 0;
28 static int recentcount_ok = 0;
29 static unsigned int startcount = 1;
30 static int expunged, expunge_period, saved_timeout = 0;
31 static int imap_version, preauth;
32 static flag do_idle, has_idle;
33 static char capabilities[MSGBUFSIZE+1];
34 static unsigned int *unseen_messages;
36 static int imap_ok(int sock, char *argbuf)
37 /* parse command response */
39 char buf[MSGBUFSIZE+1];
45 if ((ok = gen_recv(sock, buf, sizeof(buf))))
48 /* all tokens in responses are caseblind */
49 for (cp = buf; *cp; cp++)
50 if (islower((unsigned char)*cp))
51 *cp = toupper((unsigned char)*cp);
53 /* interpret untagged status responses */
54 if (strstr(buf, "* CAPABILITY"))
56 strncpy(capabilities, buf + 12, sizeof(capabilities));
57 capabilities[sizeof(capabilities)-1] = '\0';
59 else if (strstr(buf, "EXISTS"))
63 * Don't trust the message count passed by the server.
64 * Without this check, it might be possible to do a
65 * DNS-spoofing attack that would pass back a ridiculous
66 * count, and allocate a malloc area that would overlap
67 * a portion of the stack.
69 if (count > INT_MAX/sizeof(int))
71 report(stderr, "bogus message count!");
76 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
77 * we can't wait for the tag matching the IDLE; we have to tell the
78 * server the IDLE is finished by shipping back a DONE when we
79 * see an EXISTS. Only after that will a tagged response be
80 * shipped. The idling flag also gets cleared on a timeout.
82 if (stage == STAGE_IDLE)
84 /* If IDLE isn't supported, we were only sending NOOPs anyway. */
87 /* we do our own write and report here to disable tagging */
88 SockWrite(sock, "DONE\r\n", 6);
89 if (outlevel >= O_MONITOR)
90 report(stdout, "IMAP> DONE\n");
93 mytimeout = saved_timeout;
97 /* a space is required to avoid confusion with the \Recent flag */
98 else if (strstr(buf, " RECENT"))
101 recentcount = atoi(buf+2);
103 else if (strstr(buf, "EXPUNGE") && !strstr(buf, "OK"))
105 count -= atoi(buf+2);
109 else if (strstr(buf, "PREAUTH"))
112 * The server may decide to make the mailbox read-only,
113 * which causes fetchmail to go into a endless loop
114 * fetching the same message over and over again.
116 * However, for check_only, we use EXAMINE which will
117 * mark the mailbox read-only as per the RFC.
119 * This checks for the condition and aborts if
120 * the mailbox is read-only.
122 * See RFC 2060 section 6.3.1 (SELECT).
123 * See RFC 2060 section 6.3.2 (EXAMINE).
125 else if (!check_only && strstr(buf, "[READ-ONLY]"))
128 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
141 for (cp = buf; !isspace((unsigned char)*cp); cp++)
143 while (isspace((unsigned char)*cp))
146 if (strncasecmp(cp, "OK", 2) == 0)
152 else if (strncasecmp(cp, "BAD", 3) == 0)
154 else if (strncasecmp(cp, "NO", 2) == 0)
156 if (stage == STAGE_GETAUTH)
157 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
169 static tSmbNtlmAuthRequest request;
170 static tSmbNtlmAuthChallenge challenge;
171 static tSmbNtlmAuthResponse response;
174 * NTLM support by Grant Edwards.
176 * Handle MS-Exchange NTLM authentication method. This is the same
177 * as the NTLM auth used by Samba for SMB related services. We just
178 * encode the packets in base64 instead of sending them out via a
181 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
184 static int do_imap_ntlm(int sock, struct query *ctl)
189 gen_send(sock, "AUTHENTICATE NTLM");
191 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
194 if (msgbuf[0] != '+')
197 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
199 if (outlevel >= O_DEBUG)
200 dumpSmbNtlmAuthRequest(stdout, &request);
202 memset(msgbuf,0,sizeof msgbuf);
203 to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
205 if (outlevel >= O_MONITOR)
206 report(stdout, "IMAP> %s\n", msgbuf);
208 strcat(msgbuf,"\r\n");
209 SockWrite (sock, msgbuf, strlen (msgbuf));
211 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
214 len = from64tobits ((char*)&challenge, msgbuf, sizeof(challenge));
216 if (outlevel >= O_DEBUG)
217 dumpSmbNtlmAuthChallenge(stdout, &challenge);
219 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
221 if (outlevel >= O_DEBUG)
222 dumpSmbNtlmAuthResponse(stdout, &response);
224 memset(msgbuf,0,sizeof msgbuf);
225 to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
227 if (outlevel >= O_MONITOR)
228 report(stdout, "IMAP> %s\n", msgbuf);
230 strcat(msgbuf,"\r\n");
231 SockWrite (sock, msgbuf, strlen (msgbuf));
233 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
236 if (strstr (msgbuf, "OK"))
243 static int imap_canonicalize(char *result, char *raw, int maxlen)
244 /* encode an IMAP password as per RFC1730's quoting conventions */
249 for (i = 0; i < strlen(raw) && i < maxlen; i++)
251 if ((raw[i] == '\\') || (raw[i] == '"'))
253 result[j++] = raw[i];
260 static void capa_probe(int sock, struct query *ctl)
261 /* set capability variables from a CAPA probe */
265 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
266 capabilities[0] = '\0';
267 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
271 /* capability checks are supposed to be caseblind */
272 for (cp = capabilities; *cp; cp++)
275 /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
276 should expect a response in mixed-case */
277 if (strstr(capabilities, "IMAP4REV1"))
279 imap_version = IMAP4rev1;
280 if (outlevel >= O_DEBUG)
281 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
285 imap_version = IMAP4;
286 if (outlevel >= O_DEBUG)
287 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
290 else if (ok == PS_ERROR)
292 imap_version = IMAP2;
293 if (outlevel >= O_DEBUG)
294 report(stdout, GT_("Protocol identified as IMAP2 or IMAP2BIS\n"));
298 * Handle idling. We depend on coming through here on startup
299 * and after each timeout (including timeouts during idles).
304 if (strstr(capabilities, "IDLE"))
308 if (outlevel >= O_VERBOSE)
309 report(stdout, GT_("will idle after poll\n"));
312 peek_capable = (imap_version >= IMAP4);
315 static int imap_getauth(int sock, struct query *ctl, char *greeting)
316 /* apply for connection authorization */
320 flag did_stls = FALSE;
321 #endif /* SSL_ENABLE */
324 * Assumption: expunges are cheap, so we want to do them
325 * after every message unless user said otherwise.
327 if (NUM_SPECIFIED(ctl->expunge))
328 expunge_period = NUM_VALUE_OUT(ctl->expunge);
332 capa_probe(sock, ctl);
335 * If either (a) we saw a PREAUTH token in the greeting, or
336 * (b) the user specified ssh preauthentication, then we're done.
338 if (preauth || ctl->server.authenticate == A_SSH)
340 preauth = FALSE; /* reset for the next session */
345 if ((!ctl->sslproto || !strcmp(ctl->sslproto,"tls1"))
347 && strstr(capabilities, "STARTTLS"))
351 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
352 ok = gen_transact(sock, "STARTTLS");
354 /* We use "tls1" instead of ctl->sslproto, as we want STARTTLS,
355 * not other SSL protocols
357 if (ok == PS_SUCCESS &&
358 SSLOpen(sock,ctl->sslcert,ctl->sslkey,"tls1",ctl->sslcertck, ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
360 if (!ctl->sslproto && !ctl->wehaveauthed)
362 ctl->sslproto = xstrdup("");
363 /* repoll immediately */
367 GT_("SSL connection failed.\n"));
373 * RFC 2595 says this:
375 * "Once TLS has been started, the client MUST discard cached
376 * information about server capabilities and SHOULD re-issue the
377 * CAPABILITY command. This is necessary to protect against
378 * man-in-the-middle attacks which alter the capabilities list prior
379 * to STARTTLS. The server MAY advertise different capabilities
382 capa_probe(sock, ctl);
384 #endif /* SSL_ENABLE */
387 * Time to authenticate the user.
388 * Try the protocol variants that don't require passwords first.
393 if ((ctl->server.authenticate == A_ANY
394 || ctl->server.authenticate == A_GSSAPI)
395 && strstr(capabilities, "AUTH=GSSAPI"))
396 if(ok = do_gssauth(sock, "AUTHENTICATE", "imap", ctl->server.truename, ctl->remotename))
398 /* SASL cancellation of authentication */
400 if(ctl->server.authenticate != A_ANY)
408 if ((ctl->server.authenticate == A_ANY
409 || ctl->server.authenticate == A_KERBEROS_V4
410 || ctl->server.authenticate == A_KERBEROS_V5)
411 && strstr(capabilities, "AUTH=KERBEROS_V4"))
413 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
415 /* SASL cancellation of authentication */
417 if(ctl->server.authenticate != A_ANY)
423 #endif /* KERBEROS_V4 */
426 * No such luck. OK, now try the variants that mask your password
427 * in a challenge-response.
430 if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
431 || ctl->server.authenticate == A_CRAM_MD5)
433 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
435 /* SASL cancellation of authentication */
437 if(ctl->server.authenticate != A_ANY)
445 if ((ctl->server.authenticate == A_ANY
446 || ctl->server.authenticate == A_OTP)
447 && strstr(capabilities, "AUTH=X-OTP")) {
448 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
450 /* SASL cancellation of authentication */
452 if(ctl->server.authenticate != A_ANY)
459 if (ctl->server.authenticate == A_OTP)
462 GT_("Required OTP capability not compiled into fetchmail\n"));
464 #endif /* OPIE_ENABLE */
467 if ((ctl->server.authenticate == A_ANY
468 || ctl->server.authenticate == A_NTLM)
469 && strstr (capabilities, "AUTH=NTLM")) {
470 if ((ok = do_imap_ntlm(sock, ctl)))
472 /* SASL cancellation of authentication */
474 if(ctl->server.authenticate != A_ANY)
481 if (ctl->server.authenticate == A_NTLM)
484 GT_("Required NTLM capability not compiled into fetchmail\n"));
486 #endif /* NTLM_ENABLE */
488 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
489 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
490 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
493 GT_("Required LOGIN capability not supported by server\n"));
495 #endif /* __UNUSED__ */
498 * We're stuck with sending the password en clair.
499 * The reason for this odd-looking logic is that some
500 * servers return LOGINDISABLED even though login
501 * actually works. So arrange things in such a way that
502 * setting auth passwd makes it ignore this capability.
504 if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
505 || ctl->server.authenticate == A_PASSWORD)
507 /* these sizes guarantee no buffer overflow */
508 char remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
510 imap_canonicalize(remotename, ctl->remotename, NAMELEN);
511 imap_canonicalize(password, ctl->password, PASSWORDLEN);
513 snprintf(shroud, sizeof (shroud), "\"%s\"", password);
514 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
517 /* this is for servers which claim to support TLS, but actually
519 if (did_stls && ok == PS_SOCKET && !ctl->sslproto && !ctl->wehaveauthed)
521 ctl->sslproto = xstrdup("");
522 /* repoll immediately */
528 /* SASL cancellation of authentication */
530 if(ctl->server.authenticate != A_ANY)
540 static int internal_expunge(int sock)
541 /* ship an expunge, resetting associated counters */
547 if ((ok = gen_transact(sock, "EXPUNGE")))
550 /* some servers do not report RECENT after an EXPUNGE. in this case,
551 * the previous value of recentcount is just ignored. */
555 expunged += deletions;
558 #ifdef IMAP_UID /* not used */
560 #endif /* IMAP_UID */
565 static int imap_idle(int sock)
566 /* start an RFC2177 IDLE, or fake one if unsupported */
571 saved_timeout = mytimeout;
574 /* special timeout to terminate the IDLE and re-issue it
575 * at least every 28 minutes:
576 * (the server may have an inactivity timeout) */
577 mytimeout = 1680; /* 28 min */
578 /* enter IDLE mode */
579 ok = gen_transact(sock, "IDLE");
581 if (ok == PS_IDLETIMEOUT) {
582 /* send "DONE" continuation */
583 SockWrite(sock, "DONE\r\n", 6);
584 if (outlevel >= O_MONITOR)
585 report(stdout, "IMAP> DONE\n");
587 /* not idle timeout */
589 } else { /* no idle support, fake it */
590 /* when faking an idle, we can't assume the server will
591 * send us the new messages out of the blue (RFC2060);
592 * this timeout is potentially the delay before we notice
593 * new mail (can be small since NOOP checking is cheap) */
595 ok = gen_transact(sock, "NOOP");
596 /* if there's an error (not likely) or we just found mail (stage
597 * has changed, timeout has also been restored), we're done */
598 if (ok != 0 || stage != STAGE_IDLE)
601 /* wait (briefly) for an unsolicited status update */
602 ok = imap_ok(sock, NULL);
603 /* again, this is new mail or an error */
604 if (ok != PS_IDLETIMEOUT)
608 /* restore normal timeout value */
609 mytimeout = saved_timeout;
612 /* get OK IDLE message */
614 return imap_ok(sock, NULL);
619 static int imap_getrange(int sock,
622 int *countp, int *newp, int *bytes)
623 /* get range of messages to be fetched */
626 char buf[MSGBUFSIZE+1], *cp;
628 /* find out how many messages are waiting */
634 * We have to have an expunge here, otherwise the re-poll will
635 * infinite-loop picking up un-expunged messages -- unless the
636 * expunge period is one and we've been nuking each message
637 * just after deletion.
641 ok = internal_expunge(sock);
644 report(stderr, GT_("expunge failed\n"));
650 * recentcount is already set here by the last imap command which
651 * returned RECENT on detecting new mail. if recentcount is 0, wait
655 /* this is a while loop because imap_idle() might return on other
656 * mailbox changes also */
657 while (recentcount == 0 && do_idle) {
659 ok = imap_idle(sock);
662 report(stderr, GT_("re-poll failed\n"));
666 /* if recentcount is 0, return no mail */
667 if (recentcount == 0)
669 if (outlevel >= O_DEBUG)
670 report(stdout, GT_("%d messages waiting after re-poll\n"), count);
675 ok = gen_transact(sock,
676 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
677 folder ? folder : "INBOX");
680 report(stderr, GT_("mailbox selection failed\n"));
683 else if (outlevel >= O_DEBUG)
684 report(stdout, GT_("%d messages waiting after first poll\n"), count);
686 /* no messages? then we may need to idle until we get some */
687 while (count == 0 && do_idle) {
688 ok = imap_idle(sock);
691 report(stderr, GT_("re-poll failed\n"));
697 * We should have an expunge here to
698 * a) avoid fetching deleted mails during 'fetchall'
699 * b) getting a wrong count of mails during 'no fetchall'
701 if (!check_only && !ctl->keep && count > 0)
703 ok = internal_expunge(sock);
706 report(stderr, GT_("expunge failed\n"));
709 if (outlevel >= O_DEBUG)
710 report(stdout, GT_("%d messages waiting after expunge\n"), count);
718 /* OK, now get a count of unseen messages and their indices */
719 if (!ctl->fetchall && count > 0)
722 free(unseen_messages);
723 unseen_messages = xmalloc(count * sizeof(unsigned int));
724 memset(unseen_messages, 0, count * sizeof(unsigned int));
727 /* don't count deleted messages, in case user enabled keep last time */
728 gen_send(sock, "SEARCH UNSEEN NOT DELETED");
730 ok = gen_recv(sock, buf, sizeof(buf));
733 report(stderr, GT_("search for unseen messages failed\n"));
736 else if ((cp = strstr(buf, "* SEARCH")))
740 cp += 8; /* skip "* SEARCH" */
741 /* startcount is higher than count so that if there are no
742 * unseen messages, imap_getsizes() will not need to do
744 startcount = count + 1;
746 while (*cp && unseen < count)
748 /* skip whitespace */
749 while (*cp && isspace((unsigned char)*cp))
755 * Message numbers are between 1 and 2^32 inclusive,
756 * so unsigned int is large enough.
758 um=(unsigned int)strtol(cp,&ep,10);
761 unseen_messages[unseen++] = um;
762 if (outlevel >= O_DEBUG)
763 report(stdout, GT_("%u is unseen\n"), um);
772 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
774 if (outlevel >= O_DEBUG && unseen > 0)
775 report(stdout, GT_("%u is first unseen\n"), startcount);
787 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
788 /* capture the sizes of messages #first-#last */
790 char buf [MSGBUFSIZE+1];
793 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
794 * won't accept 1:1 as valid set syntax. Some implementors
795 * should be taken out and shot for excessive anality.
797 * Microsoft Exchange (brain-dead piece of crap that it is)
798 * sometimes gets its knickers in a knot about bodiless messages.
799 * You may see responses like this:
801 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
802 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
803 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
804 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
805 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
806 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
807 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
808 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
809 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
810 * fetchmail: IMAP< A0004 NO The requested item could not be found.
812 * This means message 1 has only headers. For kicks and grins
813 * you can telnet in and look:
815 * A003 NO The requested item could not be found.
816 * A004 fetch 1 rfc822.header
817 * A004 NO The requested item could not be found.
819 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
820 * A006 OK FETCH completed.
822 * To get around this, we terminate the read loop on a NO and count
823 * on the fact that the sizes array has been preinitialized with a
824 * known-bad size value.
827 /* expunges change the fetch numbers */
832 gen_send(sock, "FETCH %d RFC822.SIZE", last);
833 else if (last > first)
834 gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
835 else /* no unseen messages! */
839 unsigned int num, size;
843 if ((ok = gen_recv(sock, buf, sizeof(buf))))
845 /* we want response matching to be case-insensitive */
846 for (cp = buf; *cp; cp++)
848 /* an untagged NO means that a message was not readable */
849 if (strstr(buf, "* NO"))
851 else if (strstr(buf, "OK") || strstr(buf, "NO"))
853 else if (sscanf(buf, "* %u FETCH (RFC822.SIZE %u)", &num, &size) == 2)
855 if (num >= first && num <= last)
856 sizes[num - first] = size;
858 report(stderr, "Warning: ignoring bogus data for message sizes returned by the server.\n");
865 static int imap_getsizes(int sock, int count, int *sizes)
866 /* capture the sizes of all messages */
868 return imap_getpartialsizes(sock, 1, count, sizes);
871 static int imap_is_old(int sock, struct query *ctl, int number)
872 /* is the given message old? */
878 * Expunges change the fetch numbers, but unseen_messages contains
879 * indices from before any expungees were done. So neither the
880 * argument nor the values in message_sequence need to be decremented.
884 for (i = 0; i < unseen; i++)
885 if (unseen_messages[i] == number)
894 static char *skip_token(char *ptr)
896 while(isspace((unsigned char)*ptr)) ptr++;
897 while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
898 while(isspace((unsigned char)*ptr)) ptr++;
902 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
903 /* request headers of nth message */
905 char buf [MSGBUFSIZE+1];
908 /* expunges change the fetch numbers */
912 * This is blessed by RFC1176, RFC1730, RFC2060.
913 * According to the RFCs, it should *not* set the \Seen flag.
915 gen_send(sock, "FETCH %d RFC822.HEADER", number);
917 /* looking for FETCH response */
923 if ((ok = gen_recv(sock, buf, sizeof(buf))))
925 ptr = skip_token(buf); /* either "* " or "AXXXX " */
926 if (sscanf(ptr, "%d FETCH (%*s {%d}", &num, lenp) == 2)
928 /* try to recover from chronically fucked-up M$ Exchange servers */
929 else if (!strncmp(ptr, "NO", 2))
931 /* wait for a tagged response */
932 if (strstr (buf, "* NO"))
934 return(PS_TRANSIENT);
936 else if (!strncmp(ptr, "BAD", 3))
938 /* wait for a tagged response */
939 if (strstr (buf, "* BAD"))
941 return(PS_TRANSIENT);
951 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
952 /* request body of nth message */
954 char buf [MSGBUFSIZE+1], *cp;
957 /* expunges change the fetch numbers */
961 * If we're using IMAP4, we can fetch the message without setting its
962 * seen flag. This is good! It means that if the protocol exchange
963 * craps out during the message, it will still be marked `unseen' on
966 * According to RFC2060, and Mark Crispin the IMAP maintainer,
967 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
968 * equivalent". However, we know of at least one server that
969 * treats them differently in the presence of MIME attachments;
970 * the latter form downloads the attachment, the former does not.
971 * The server is InterChange, and the fool who implemented this
972 * misfeature ought to be strung up by his thumbs.
974 * When I tried working around this by disabling use of the 4rev1 form,
975 * I found that doing this breaks operation with M$ Exchange.
976 * Annoyingly enough, Exchange's refusal to cope is technically legal
977 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
978 * standards, to find a way to make standards compliance irritating....
980 switch (imap_version)
982 case IMAP4rev1: /* RFC 2060 */
983 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
986 case IMAP4: /* RFC 1730 */
987 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
990 default: /* RFC 1176 */
991 gen_send(sock, "FETCH %d RFC822.TEXT", number);
995 /* looking for FETCH response */
999 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1002 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1008 * Try to extract a length from the FETCH response. RFC2060 requires
1009 * it to be present, but at least one IMAP server (Novell GroupWise)
1010 * botches this. The overflow check is needed because of a broken
1011 * server called dbmail that returns huge garbage lengths.
1013 if ((cp = strchr(buf, '{'))) {
1015 *lenp = (int)strtol(cp + 1, (char **)NULL, 10);
1016 if (errno == ERANGE && (*lenp == LONG_MAX || *lenp == LONG_MIN))
1017 *lenp = -1; /* length is too big/small for us to handle */
1020 *lenp = -1; /* missing length part in FETCH reponse */
1025 static int imap_trail(int sock, struct query *ctl, int number)
1026 /* discard tail of FETCH response after reading message text */
1028 /* expunges change the fetch numbers */
1029 /* number -= expunged; */
1033 char buf[MSGBUFSIZE+1];
1036 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1039 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1040 if (strstr(buf, "OK"))
1047 static int imap_delete(int sock, struct query *ctl, int number)
1048 /* set delete flag for given message */
1052 /* expunges change the fetch numbers */
1056 * Use SILENT if possible as a minor throughput optimization.
1057 * Note: this has been dropped from IMAP4rev1.
1059 * We set Seen because there are some IMAP servers (notably HP
1060 * OpenMail) that do message-receipt DSNs, but only when the seen
1061 * bit is set. This is the appropriate time -- we get here right
1062 * after the local SMTP response that says delivery was
1065 if ((ok = gen_transact(sock,
1066 imap_version == IMAP4
1067 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1068 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1075 * We do an expunge after expunge_period messages, rather than
1076 * just before quit, so that a line hit during a long session
1077 * won't result in lots of messages being fetched again during
1080 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1081 internal_expunge(sock);
1086 static int imap_mark_seen(int sock, struct query *ctl, int number)
1087 /* mark the given message as seen */
1089 return(gen_transact(sock,
1090 imap_version == IMAP4
1091 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1092 : "STORE %d +FLAGS (\\Seen)",
1096 static int imap_logout(int sock, struct query *ctl)
1097 /* send logout command */
1099 /* if any un-expunged deletions remain, ship an expunge now */
1101 internal_expunge(sock);
1104 /* Memory clean-up */
1105 if (unseen_messages)
1106 free(unseen_messages);
1107 #endif /* USE_SEARCH */
1109 return(gen_transact(sock, "LOGOUT"));
1112 static const struct method imap =
1114 "IMAP", /* Internet Message Access Protocol */
1118 #else /* INET6_ENABLE */
1119 143, /* standard IMAP2bis/IMAP4 port */
1120 993, /* ssl IMAP2bis/IMAP4 port */
1121 #endif /* INET6_ENABLE */
1122 TRUE, /* this is a tagged protocol */
1123 FALSE, /* no message delimiter */
1124 imap_ok, /* parse command response */
1125 imap_getauth, /* get authorization */
1126 imap_getrange, /* query range of messages */
1127 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1128 imap_getpartialsizes, /* get sizes of subset of messages (used for ESMTP SIZE option) */
1129 imap_is_old, /* no UID check */
1130 imap_fetch_headers, /* request given message headers */
1131 imap_fetch_body, /* request given message body */
1132 imap_trail, /* eat message trailer */
1133 imap_delete, /* delete the message */
1134 imap_mark_seen, /* how to mark a message as seen */
1135 imap_logout, /* expunge and exit */
1136 TRUE, /* yes, we can re-poll */
1139 int doIMAP(struct query *ctl)
1140 /* retrieve messages using IMAP Version 2bis or Version 4 */
1142 return(do_protocol(ctl, &imap));
1145 /* imap.c ends here */