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)
15 #include "fetchmail.h"
22 #ifdef HAVE_GSSAPI_GSSAPI_H
23 #include <gssapi/gssapi.h>
25 #ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H
26 #include <gssapi/gssapi_generic.h>
28 #ifndef HAVE_GSS_C_NT_HOSTBASED_SERVICE
29 #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
37 #endif /* OPIE_ENABLE */
39 #ifndef strstr /* glibc-2.1 declares this as a macro */
40 extern char *strstr(); /* needed on sysV68 R3V7.1. */
43 /* imap_version values */
44 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
45 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
46 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
48 static int count, unseen, deletions, imap_version, preauth;
49 static int expunged, expunge_period, saved_timeout;
51 static char capabilities[MSGBUFSIZE+1];
52 static unsigned int *unseen_messages;
54 int imap_ok(int sock, char *argbuf)
55 /* parse command response */
57 char buf[MSGBUFSIZE+1];
63 if ((ok = gen_recv(sock, buf, sizeof(buf))))
66 /* all tokens in responses are caseblind */
67 for (cp = buf; *cp; cp++)
71 /* interpret untagged status responses */
72 if (strstr(buf, "* CAPABILITY"))
73 strncpy(capabilities, buf + 12, sizeof(capabilities));
74 else if (strstr(buf, "EXISTS"))
78 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
79 * we can't wait for the tag matching the IDLE; we have to tell the
80 * server the IDLE is finished by shipping back a DONE when we
81 * see an EXISTS. Only after that will a tagged response be
82 * shipped. The idling flag also gets cleared on a timeout.
84 if (stage == STAGE_IDLE)
86 /* we do our own write and report here to disable tagging */
87 SockWrite(sock, "DONE\r\n", 6);
88 if (outlevel >= O_MONITOR)
89 report(stdout, "IMAP> DONE\n");
91 mytimeout = saved_timeout;
95 else if (strstr(buf, "PREAUTH"))
98 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
111 for (cp = buf; !isspace(*cp); cp++)
116 if (strncmp(cp, "OK", 2) == 0)
122 else if (strncmp(cp, "BAD", 3) == 0)
124 else if (strncmp(cp, "NO", 2) == 0)
126 if (stage == STAGE_GETAUTH)
127 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
137 static int do_otp(int sock, struct query *ctl)
141 char challenge[OPIE_CHALLENGE_MAX+1];
142 char response[OPIE_RESPONSE_MAX+1];
144 gen_send(sock, "AUTHENTICATE X-OTP");
146 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
149 if ((i = from64tobits(challenge, buffer)) < 0) {
150 report(stderr, _("Could not decode initial BASE64 challenge\n"));
155 to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
157 if (outlevel >= O_MONITOR)
158 report(stdout, "IMAP> %s\n", buffer);
160 /* best not to count on the challenge code handling multiple writes */
161 strcat(buffer, "\r\n");
162 SockWrite(sock, buffer, strlen(buffer));
164 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
167 if ((i = from64tobits(challenge, buffer)) < 0) {
168 report(stderr, _("Could not decode OTP challenge\n"));
172 rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
173 if ((rval == -2) && !run.poll_interval) {
174 char secret[OPIE_SECRET_MAX+1];
175 fprintf(stderr, _("Secret pass phrase: "));
176 if (opiereadpass(secret, sizeof(secret), 0))
177 rval = opiegenerator(challenge, secret, response);
178 memset(secret, 0, sizeof(secret));
184 to64frombits(buffer, response, strlen(response));
186 if (outlevel >= O_MONITOR)
187 report(stdout, "IMAP> %s\n", buffer);
188 strcat(buffer, "\r\n");
189 SockWrite(sock, buffer, strlen(buffer));
191 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
194 if (strstr(buffer, "OK"))
199 #endif /* OPIE_ENABLE */
202 #define GSSAUTH_P_NONE 1
203 #define GSSAUTH_P_INTEGRITY 2
204 #define GSSAUTH_P_PRIVACY 4
206 static int do_gssauth(int sock, char *hostname, char *username)
208 gss_buffer_desc request_buf, send_token;
209 gss_buffer_t sec_token;
210 gss_name_t target_name;
211 gss_ctx_id_t context;
215 OM_uint32 maj_stat, min_stat;
216 char buf1[8192], buf2[8192], server_conf_flags;
217 unsigned long buf_size;
220 /* first things first: get an imap ticket for host */
221 sprintf(buf1, "imap@%s", hostname);
222 request_buf.value = buf1;
223 request_buf.length = strlen(buf1) + 1;
224 maj_stat = gss_import_name(&min_stat, &request_buf, GSS_C_NT_HOSTBASED_SERVICE,
226 if (maj_stat != GSS_S_COMPLETE) {
227 report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
230 else if (outlevel >= O_DEBUG) {
231 maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
233 report(stderr, _("Using service name [%s]\n"),request_buf.value);
234 maj_stat = gss_release_buffer(&min_stat, &request_buf);
237 gen_send(sock, "AUTHENTICATE GSSAPI");
239 /* upon receipt of the GSSAPI authentication request, server returns
240 * null data ready response. */
241 if (result = gen_recv(sock, buf1, sizeof buf1)) {
245 /* now start the security context initialisation loop... */
246 sec_token = GSS_C_NO_BUFFER;
247 context = GSS_C_NO_CONTEXT;
248 if (outlevel >= O_VERBOSE)
249 report(stdout, _("Sending credentials\n"));
251 send_token.length = 0;
252 send_token.value = NULL;
253 maj_stat = gss_init_sec_context(&min_stat,
258 GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG,
260 GSS_C_NO_CHANNEL_BINDINGS,
266 if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
267 report(stderr, _("Error exchanging credentials\n"));
268 gss_release_name(&min_stat, &target_name);
269 /* wake up server and await NO response */
270 SockWrite(sock, "\r\n", 2);
271 if (result = gen_recv(sock, buf1, sizeof buf1))
275 to64frombits(buf1, send_token.value, send_token.length);
276 gss_release_buffer(&min_stat, &send_token);
277 strcat(buf1, "\r\n");
278 SockWrite(sock, buf1, strlen(buf1));
279 if (outlevel >= O_MONITOR)
280 report(stdout, "IMAP> %s\n", buf1);
281 if (maj_stat == GSS_S_CONTINUE_NEEDED) {
282 if (result = gen_recv(sock, buf1, sizeof buf1)) {
283 gss_release_name(&min_stat, &target_name);
286 request_buf.length = from64tobits(buf2, buf1 + 2);
287 request_buf.value = buf2;
288 sec_token = &request_buf;
290 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
291 gss_release_name(&min_stat, &target_name);
293 /* get security flags and buffer size */
294 if (result = gen_recv(sock, buf1, sizeof buf1)) {
297 request_buf.length = from64tobits(buf2, buf1 + 2);
298 request_buf.value = buf2;
300 maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
302 if (maj_stat != GSS_S_COMPLETE) {
303 report(stderr, _("Couldn't unwrap security level data\n"));
304 gss_release_buffer(&min_stat, &send_token);
307 if (outlevel >= O_DEBUG)
308 report(stdout, _("Credential exchange complete\n"));
309 /* first octet is security levels supported. We want none, for now */
310 server_conf_flags = ((char *)send_token.value)[0];
311 if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
312 report(stderr, _("Server requires integrity and/or privacy\n"));
313 gss_release_buffer(&min_stat, &send_token);
316 ((char *)send_token.value)[0] = 0;
317 buf_size = ntohl(*((long *)send_token.value));
318 /* we don't care about buffer size if we don't wrap data */
319 gss_release_buffer(&min_stat, &send_token);
320 if (outlevel >= O_DEBUG) {
321 report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
322 server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
323 server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
324 server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
325 report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
328 /* now respond in kind (hack!!!) */
329 buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
330 memcpy(buf1, &buf_size, 4);
331 buf1[0] = GSSAUTH_P_NONE;
332 strcpy(buf1+4, username); /* server decides if princ is user */
333 request_buf.length = 4 + strlen(username) + 1;
334 request_buf.value = buf1;
335 maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
336 &cflags, &send_token);
337 if (maj_stat != GSS_S_COMPLETE) {
338 report(stderr, _("Error creating security level request\n"));
341 to64frombits(buf1, send_token.value, send_token.length);
342 if (outlevel >= O_DEBUG) {
343 report(stdout, _("Requesting authorization as %s\n"), username);
344 report(stdout, "IMAP> %s\n",buf1);
346 strcat(buf1, "\r\n");
347 SockWrite(sock, buf1, strlen(buf1));
349 /* we should be done. Get status and finish up */
351 if (result = gen_recv(sock, buf1, sizeof buf1))
353 } while(strncmp(buf1, tag, strlen(tag)) != 0);
354 if (strstr(buf1, "OK")) {
355 /* flush security context */
356 if (outlevel >= O_DEBUG)
357 report(stdout, _("Releasing GSS credentials\n"));
358 maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
359 if (maj_stat != GSS_S_COMPLETE) {
360 report(stderr, _("Error releasing credentials\n"));
363 /* send_token may contain a notification to the server to flush
364 * credentials. RFC 1731 doesn't specify what to do, and since this
365 * support is only for authentication, we'll assume the server
366 * knows enough to flush its own credentials */
367 gss_release_buffer(&min_stat, &send_token);
378 static tSmbNtlmAuthRequest request;
379 static tSmbNtlmAuthChallenge challenge;
380 static tSmbNtlmAuthResponse response;
383 * NTLM support by Grant Edwards.
385 * Handle MS-Exchange NTLM authentication method. This is the same
386 * as the NTLM auth used by Samba for SMB related services. We just
387 * encode the packets in base64 instead of sending them out via a
390 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
393 static int do_imap_ntlm(int sock, struct query *ctl)
398 gen_send(sock, "AUTHENTICATE NTLM");
400 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
403 if (msgbuf[0] != '+')
406 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
408 if (outlevel >= O_DEBUG)
409 dumpSmbNtlmAuthRequest(stdout, &request);
411 memset(msgbuf,0,sizeof msgbuf);
412 to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
414 if (outlevel >= O_MONITOR)
415 report(stdout, "IMAP> %s\n", msgbuf);
417 strcat(msgbuf,"\r\n");
418 SockWrite (sock, msgbuf, strlen (msgbuf));
420 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
423 len = from64tobits ((unsigned char*)&challenge, msgbuf);
425 if (outlevel >= O_DEBUG)
426 dumpSmbNtlmAuthChallenge(stdout, &challenge);
428 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
430 if (outlevel >= O_DEBUG)
431 dumpSmbNtlmAuthResponse(stdout, &response);
433 memset(msgbuf,0,sizeof msgbuf);
434 to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
436 if (outlevel >= O_MONITOR)
437 report(stdout, "IMAP> %s\n", msgbuf);
439 strcat(msgbuf,"\r\n");
441 SockWrite (sock, msgbuf, strlen (msgbuf));
443 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
446 if (strstr (msgbuf, "OK"))
453 int imap_canonicalize(char *result, char *raw, int maxlen)
454 /* encode an IMAP password as per RFC1730's quoting conventions */
459 for (i = 0; i < strlen(raw) && i < maxlen; i++)
461 if ((raw[i] == '\\') || (raw[i] == '"'))
463 result[j++] = raw[i];
470 int imap_getauth(int sock, struct query *ctl, char *greeting)
471 /* apply for connection authorization */
475 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
476 capabilities[0] = '\0';
477 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
479 /* UW-IMAP server 10.173 notifies in all caps */
480 if (strstr(capabilities, "IMAP4REV1"))
482 imap_version = IMAP4rev1;
483 if (outlevel >= O_DEBUG)
484 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
488 imap_version = IMAP4;
489 if (outlevel >= O_DEBUG)
490 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
493 else if (ok == PS_ERROR)
495 imap_version = IMAP2;
496 if (outlevel >= O_DEBUG)
497 report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
502 peek_capable = (imap_version >= IMAP4);
505 * Assumption: expunges are cheap, so we want to do them
506 * after every message unless user said otherwise.
508 if (NUM_SPECIFIED(ctl->expunge))
509 expunge_period = NUM_VALUE_OUT(ctl->expunge);
514 * Handle idling. We depend on coming through here on startup
515 * and after each timeout (including timeouts during idles).
517 if (strstr(capabilities, "IDLE") && ctl->idle)
520 if (outlevel >= O_VERBOSE)
521 report(stdout, _("will idle after poll\n"));
525 * If either (a) we saw a PREAUTH token in the greeting, or
526 * (b) the user specified ssh preauthentication, then we're done.
528 if (preauth || ctl->server.preauthenticate == A_SSH)
530 preauth = FALSE; /* reset for the next session */
535 if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
537 if (outlevel >= O_DEBUG)
538 report(stdout, _("OTP authentication is supported\n"));
539 if (do_otp(sock, ctl) == PS_SUCCESS)
542 #endif /* OPIE_ENABLE */
545 if (strstr(capabilities, "AUTH=GSSAPI"))
547 if (ctl->server.protocol == P_IMAP_GSS)
549 if (outlevel >= O_DEBUG)
550 report(stdout, _("GSS authentication is supported\n"));
551 return do_gssauth(sock, ctl->server.truename, ctl->remotename);
554 else if (ctl->server.protocol == P_IMAP_GSS)
557 _("Required GSS capability not supported by server\n"));
563 if (strstr(capabilities, "AUTH=KERBEROS_V4"))
565 if (outlevel >= O_DEBUG)
566 report(stdout, _("KERBEROS_V4 authentication is supported\n"));
568 if (ctl->server.protocol == P_IMAP_K4)
570 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
571 /* SASL cancellation of authentication */
576 /* else fall through to ordinary AUTH=LOGIN case */
578 else if (ctl->server.protocol == P_IMAP_K4)
581 _("Required KERBEROS_V4 capability not supported by server\n"));
584 #endif /* KERBEROS_V4 */
586 if (strstr(capabilities, "AUTH=CRAM-MD5"))
588 if (outlevel >= O_DEBUG)
589 report (stdout, _("CRAM-MD5 authentication is supported\n"));
590 if (ctl->server.protocol != P_IMAP_LOGIN)
592 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl)))
593 /* SASL cancellation of authentication */
599 else if (ctl->server.protocol == P_IMAP_CRAM_MD5)
602 _("Required CRAM-MD5 capability not supported by server\n"));
607 if (strstr (capabilities, "AUTH=NTLM"))
609 if (outlevel >= O_DEBUG)
610 report (stdout, _("NTLM authentication is supported\n"));
611 return do_imap_ntlm (sock, ctl);
613 #endif /* NTLM_ENABLE */
615 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
616 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
617 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
619 _("Required LOGIN capability not supported by server\n"));
622 #endif /* __UNUSED__ */
625 /* these sizes guarantee no buffer overflow */
626 char remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
628 imap_canonicalize(remotename, ctl->remotename, NAMELEN);
629 imap_canonicalize(password, ctl->password, PASSWORDLEN);
630 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
639 static int internal_expunge(int sock)
640 /* ship an expunge, resetting associated counters */
644 if ((ok = gen_transact(sock, "EXPUNGE")))
647 expunged += deletions;
650 #ifdef IMAP_UID /* not used */
652 #endif /* IMAP_UID */
657 static int imap_idle(int sock)
658 /* start an RFC2177 IDLE */
661 saved_timeout = mytimeout;
664 return (gen_transact(sock, "IDLE"));
667 static int imap_getrange(int sock,
670 int *countp, int *newp, int *bytes)
671 /* get range of messages to be fetched */
674 char buf[MSGBUFSIZE+1], *cp;
676 /* find out how many messages are waiting */
682 * We have to have an expunge here, otherwise the re-poll will
683 * infinite-loop picking up un-expunged messages -- unless the
684 * expunge period is one and we've been nuking each message
685 * just after deletion.
688 if (deletions && expunge_period != 1)
689 ok = internal_expunge(sock);
692 ok = imap_idle(sock);
693 if (ok || gen_transact(sock, "NOOP"))
695 report(stderr, _("re-poll failed\n"));
698 else if (count == -1) /* no EXISTS response to NOOP/IDLE */
702 if (outlevel >= O_DEBUG)
703 report(stdout, _("%d messages waiting after re-poll\n"), count);
707 ok = gen_transact(sock,
708 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
709 folder ? folder : "INBOX");
712 report(stderr, _("mailbox selection failed\n"));
715 else if (outlevel >= O_DEBUG)
716 report(stdout, _("%d messages waiting after first poll\n"), count);
718 /* no messages? then we may need to idle until we get some */
719 if (count == 0 && do_idle)
725 /* OK, now get a count of unseen messages and their indices */
726 if (!ctl->fetchall && count > 0)
729 free(unseen_messages);
730 unseen_messages = xmalloc(count * sizeof(unsigned int));
731 memset(unseen_messages, 0, count * sizeof(unsigned int));
734 gen_send(sock, "SEARCH UNSEEN");
736 ok = gen_recv(sock, buf, sizeof(buf));
739 report(stderr, _("search for unseen messages failed\n"));
742 else if ((cp = strstr(buf, "* SEARCH")))
746 cp += 8; /* skip "* SEARCH" */
748 while (*cp && unseen < count)
750 /* skip whitespace */
751 while (*cp && isspace(*cp))
756 * Message numbers are between 1 and 2^32 inclusive,
757 * so unsigned int is large enough.
759 unseen_messages[unseen]=(unsigned int)strtol(cp,&ep,10);
761 if (outlevel >= O_DEBUG)
764 unseen_messages[unseen]);
772 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
781 static int imap_getsizes(int sock, int count, int *sizes)
782 /* capture the sizes of all messages */
784 char buf [MSGBUFSIZE+1];
787 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
788 * won't accept 1:1 as valid set syntax. Some implementors
789 * should be taken out and shot for excessive anality.
791 * Microsoft Exchange (brain-dead piece of crap that it is)
792 * sometimes gets its knickers in a knot about bodiless messages.
793 * You may see responses like this:
795 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
796 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
797 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
798 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
799 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
800 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
801 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
802 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
803 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
804 * fetchmail: IMAP< A0004 NO The requested item could not be found.
806 * This means message 1 has only headers. For kicks and grins
807 * you can telnet in and look:
809 * A003 NO The requested item could not be found.
810 * A004 fetch 1 rfc822.header
811 * A004 NO The requested item could not be found.
813 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
814 * A006 OK FETCH completed.
816 * To get around this, we terminate the read loop on a NO and count
817 * on the fact that the sizes array has been preinitialized with a
818 * known-bad size value.
821 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
823 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
828 if ((ok = gen_recv(sock, buf, sizeof(buf))))
830 else if (strstr(buf, "OK") || strstr(buf, "NO"))
832 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
833 sizes[num - 1] = size;
839 static int imap_is_old(int sock, struct query *ctl, int number)
840 /* is the given message old? */
846 * Expunges change the fetch numbers, but unseen_messages contains
847 * indices from before any expungees were done. So neither the
848 * argument nor the values in message_sequence need to be decremented.
852 for (i = 0; i < unseen; i++)
853 if (unseen_messages[i] == number)
862 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
863 /* request headers of nth message */
865 char buf [MSGBUFSIZE+1];
868 /* expunges change the fetch numbers */
872 * This is blessed by RFC1176, RFC1730, RFC2060.
873 * According to the RFCs, it should *not* set the \Seen flag.
875 gen_send(sock, "FETCH %d RFC822.HEADER", number);
877 /* looking for FETCH response */
881 if ((ok = gen_recv(sock, buf, sizeof(buf))))
884 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
892 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
893 /* request body of nth message */
895 char buf [MSGBUFSIZE+1], *cp;
898 /* expunges change the fetch numbers */
902 * If we're using IMAP4, we can fetch the message without setting its
903 * seen flag. This is good! It means that if the protocol exchange
904 * craps out during the message, it will still be marked `unseen' on
907 * However...*don't* do this if we're using keep to suppress deletion!
908 * In that case, marking the seen flag is the only way to prevent the
909 * message from being re-fetched on subsequent runs (and according
910 * to RFC2060 p.43 this fetch should set Seen as a side effect).
912 * According to RFC2060, and Mark Crispin the IMAP maintainer,
913 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
914 * equivalent". However, we know of at least one server that
915 * treats them differently in the presence of MIME attachments;
916 * the latter form downloads the attachment, the former does not.
917 * The server is InterChange, and the fool who implemented this
918 * misfeature ought to be strung up by his thumbs.
920 * When I tried working around this by disabling use of the 4rev1 form,
921 * I found that doing this breaks operation with M$ Exchange.
922 * Annoyingly enough, Exchange's refusal to cope is technically legal
923 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
924 * standards, to find a way to make standards compliance irritating....
926 switch (imap_version)
928 case IMAP4rev1: /* RFC 2060 */
930 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
932 gen_send(sock, "FETCH %d BODY[TEXT]", number);
935 case IMAP4: /* RFC 1730 */
937 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
939 gen_send(sock, "FETCH %d RFC822.TEXT", number);
942 default: /* RFC 1176 */
943 gen_send(sock, "FETCH %d RFC822.TEXT", number);
947 /* looking for FETCH response */
951 if ((ok = gen_recv(sock, buf, sizeof(buf))))
954 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
960 * Try to extract a length from the FETCH response. RFC2060 requires
961 * it to be present, but at least one IMAP server (Novell GroupWise)
964 if ((cp = strchr(buf, '{')))
965 *lenp = atoi(cp + 1);
967 *lenp = -1; /* missing length part in FETCH reponse */
972 static int imap_trail(int sock, struct query *ctl, int number)
973 /* discard tail of FETCH response after reading message text */
975 /* expunges change the fetch numbers */
976 /* number -= expunged; */
980 char buf[MSGBUFSIZE+1];
983 if ((ok = gen_recv(sock, buf, sizeof(buf))))
986 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
987 if (strstr(buf, "OK"))
992 * Any IMAP server that fails to set Seen on a BODY[TEXT]
993 * fetch violates RFC2060 p.43 (top). This becomes an issue
994 * when keep is on, because seen messages aren't deleted and
995 * get refetched on each poll. As a workaround, if keep is on
996 * we can set the Seen flag explicitly.
998 * This code isn't used yet because we don't know of any IMAP
999 * servers broken in this way.
1002 if ((ok = gen_transact(sock,
1003 imap_version == IMAP4
1004 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1005 : "STORE %d +FLAGS (\\Seen)",
1008 #endif /* __UNUSED__ */
1014 static int imap_delete(int sock, struct query *ctl, int number)
1015 /* set delete flag for given message */
1019 /* expunges change the fetch numbers */
1023 * Use SILENT if possible as a minor throughput optimization.
1024 * Note: this has been dropped from IMAP4rev1.
1026 * We set Seen because there are some IMAP servers (notably HP
1027 * OpenMail) that do message-receipt DSNs, but only when the seen
1028 * bit is set. This is the appropriate time -- we get here right
1029 * after the local SMTP response that says delivery was
1032 if ((ok = gen_transact(sock,
1033 imap_version == IMAP4
1034 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1035 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1042 * We do an expunge after expunge_period messages, rather than
1043 * just before quit, so that a line hit during a long session
1044 * won't result in lots of messages being fetched again during
1047 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1048 internal_expunge(sock);
1053 static int imap_logout(int sock, struct query *ctl)
1054 /* send logout command */
1056 /* if any un-expunged deletions remain, ship an expunge now */
1058 internal_expunge(sock);
1061 /* Memory clean-up */
1062 if (unseen_messages)
1063 free(unseen_messages);
1064 #endif /* USE_SEARCH */
1066 return(gen_transact(sock, "LOGOUT"));
1069 const static struct method imap =
1071 "IMAP", /* Internet Message Access Protocol */
1075 #else /* INET6_ENABLE */
1076 143, /* standard IMAP2bis/IMAP4 port */
1077 993, /* ssl IMAP2bis/IMAP4 port */
1078 #endif /* INET6_ENABLE */
1079 TRUE, /* this is a tagged protocol */
1080 FALSE, /* no message delimiter */
1081 imap_ok, /* parse command response */
1082 imap_canonicalize, /* deal with embedded slashes and spaces */
1083 imap_getauth, /* get authorization */
1084 imap_getrange, /* query range of messages */
1085 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1086 imap_is_old, /* no UID check */
1087 imap_fetch_headers, /* request given message headers */
1088 imap_fetch_body, /* request given message body */
1089 imap_trail, /* eat message trailer */
1090 imap_delete, /* delete the message */
1091 imap_logout, /* expunge and exit */
1092 TRUE, /* yes, we can re-poll */
1095 int doIMAP(struct query *ctl)
1096 /* retrieve messages using IMAP Version 2bis or Version 4 */
1098 return(do_protocol(ctl, &imap));
1101 /* imap.c ends here */