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"
20 #include <kerberosIV/des.h>
21 #include <kerberosIV/krb.h>
23 #if defined (__bsdi__)
25 #define krb_get_err_text(e) (krb_err_txt[e])
27 #if defined(__NetBSD__) || (__FreeBSD__) || defined(__linux__)
28 #define krb_get_err_text(e) (krb_err_txt[e])
32 #endif /* KERBEROS_V4 */
39 #ifdef HAVE_GSSAPI_GSSAPI_H
40 #include <gssapi/gssapi.h>
42 #ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H
43 #include <gssapi/gssapi_generic.h>
45 #ifndef HAVE_GSS_C_NT_HOSTBASED_SERVICE
46 #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
54 #endif /* OPIE_ENABLE */
56 #ifndef strstr /* glibc-2.1 declares this as a macro */
57 extern char *strstr(); /* needed on sysV68 R3V7.1. */
60 /* imap_version values */
61 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
62 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
63 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
65 static int count, unseen, deletions, imap_version, preauth;
66 static int expunged, expunge_period, saved_timeout;
68 static char capabilities[MSGBUFSIZE+1];
69 static unsigned int *unseen_messages;
71 int imap_ok(int sock, char *argbuf)
72 /* parse command response */
74 char buf[MSGBUFSIZE+1];
80 if ((ok = gen_recv(sock, buf, sizeof(buf))))
83 /* all tokens in responses are caseblind */
84 for (cp = buf; *cp; cp++)
88 /* interpret untagged status responses */
89 if (strstr(buf, "* CAPABILITY"))
90 strncpy(capabilities, buf + 12, sizeof(capabilities));
91 else if (strstr(buf, "EXISTS"))
95 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
96 * we can't wait for the tag matching the IDLE; we have to tell the
97 * server the IDLE is finished by shipping back a DONE when we
98 * see an EXISTS. Only after that will a tagged response be
99 * shipped. The idling flag also gets cleared on a timeout.
101 if (stage == STAGE_IDLE)
103 /* we do our own write and report here to disable tagging */
104 SockWrite(sock, "DONE\r\n", 6);
105 if (outlevel >= O_MONITOR)
106 report(stdout, "IMAP> DONE\n");
108 mytimeout = saved_timeout;
112 else if (strstr(buf, "PREAUTH"))
115 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
128 for (cp = buf; !isspace(*cp); cp++)
133 if (strncmp(cp, "OK", 2) == 0)
139 else if (strncmp(cp, "BAD", 3) == 0)
141 else if (strncmp(cp, "NO", 2) == 0)
143 if (stage == STAGE_GETAUTH)
144 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
154 static int do_otp(int sock, struct query *ctl)
158 char challenge[OPIE_CHALLENGE_MAX+1];
159 char response[OPIE_RESPONSE_MAX+1];
161 gen_send(sock, "AUTHENTICATE X-OTP");
163 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
166 if ((i = from64tobits(challenge, buffer)) < 0) {
167 report(stderr, _("Could not decode initial BASE64 challenge\n"));
172 to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
174 if (outlevel >= O_MONITOR)
175 report(stdout, "IMAP> %s\n", buffer);
177 /* best not to count on the challenge code handling multiple writes */
178 strcat(buffer, "\r\n");
179 SockWrite(sock, buffer, strlen(buffer));
181 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
184 if ((i = from64tobits(challenge, buffer)) < 0) {
185 report(stderr, _("Could not decode OTP challenge\n"));
189 rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
190 if ((rval == -2) && !run.poll_interval) {
191 char secret[OPIE_SECRET_MAX+1];
192 fprintf(stderr, _("Secret pass phrase: "));
193 if (opiereadpass(secret, sizeof(secret), 0))
194 rval = opiegenerator(challenge, secret, response);
195 memset(secret, 0, sizeof(secret));
201 to64frombits(buffer, response, strlen(response));
203 if (outlevel >= O_MONITOR)
204 report(stdout, "IMAP> %s\n", buffer);
205 strcat(buffer, "\r\n");
206 SockWrite(sock, buffer, strlen(buffer));
208 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
211 if (strstr(buffer, "OK"))
216 #endif /* OPIE_ENABLE */
221 #elif SIZEOF_SHORT == 4
223 #elif SIZEOF_LONG == 4
226 #error Cannot deduce a 32-bit-type
229 static int do_rfc1731(int sock, char *truename)
230 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
233 char buf1[4096], buf2[4096];
237 } challenge1, challenge2;
238 char srvinst[INST_SZ];
240 char srvrealm[REALM_SZ];
241 KTEXT_ST authenticator;
242 CREDENTIALS credentials;
243 char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
244 char tktinst[INST_SZ];
245 char tktrealm[REALM_SZ];
247 des_key_schedule schedule;
249 gen_send(sock, "AUTHENTICATE KERBEROS_V4");
251 /* The data encoded in the first ready response contains a random
252 * 32-bit number in network byte order. The client should respond
253 * with a Kerberos ticket and an authenticator for the principal
254 * "imap.hostname@realm", where "hostname" is the first component
255 * of the host name of the server with all letters in lower case
256 * and where "realm" is the Kerberos realm of the server. The
257 * encrypted checksum field included within the Kerberos
258 * authenticator should contain the server provided 32-bit number
259 * in network byte order.
262 if (result = gen_recv(sock, buf1, sizeof buf1)) {
266 len = from64tobits(challenge1.cstr, buf1);
268 report(stderr, _("could not decode initial BASE64 challenge\n"));
272 /* this patch by Dan Root <dar@thekeep.org> solves an endianess
277 *(int *)tmp = ntohl(*(int *) challenge1.cstr);
278 memcpy(challenge1.cstr, tmp, sizeof(tmp));
281 /* Client responds with a Kerberos ticket and an authenticator for
282 * the principal "imap.hostname@realm" where "hostname" is the
283 * first component of the host name of the server with all letters
284 * in lower case and where "realm" is the Kerberos realm of the
285 * server. The encrypted checksum field included within the
286 * Kerberos authenticator should contain the server-provided
287 * 32-bit number in network byte order.
290 strncpy(srvinst, truename, (sizeof srvinst)-1);
291 srvinst[(sizeof srvinst)-1] = '\0';
292 for (p = srvinst; *p; p++) {
298 strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
299 srvrealm[(sizeof srvrealm)-1] = '\0';
300 if (p = strchr(srvinst, '.')) {
304 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
306 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
310 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
312 report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
316 memcpy(session, credentials.session, sizeof session);
317 memset(&credentials, 0, sizeof credentials);
318 des_key_sched(&session, schedule);
320 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
322 report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
326 if (strcmp(tktuser, user) != 0) {
328 _("principal %s in ticket does not match -u %s\n"), tktuser,
335 _("non-null instance (%s) might cause strange behavior\n"),
337 strcat(tktuser, ".");
338 strcat(tktuser, tktinst);
341 if (strcmp(tktrealm, srvrealm) != 0) {
342 strcat(tktuser, "@");
343 strcat(tktuser, tktrealm);
346 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
349 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
353 to64frombits(buf1, authenticator.dat, authenticator.length);
354 if (outlevel >= O_MONITOR) {
355 report(stdout, "IMAP> %s\n", buf1);
357 strcat(buf1, "\r\n");
358 SockWrite(sock, buf1, strlen(buf1));
360 /* Upon decrypting and verifying the ticket and authenticator, the
361 * server should verify that the contained checksum field equals
362 * the original server provided random 32-bit number. Should the
363 * verification be successful, the server must add one to the
364 * checksum and construct 8 octets of data, with the first four
365 * octets containing the incremented checksum in network byte
366 * order, the fifth octet containing a bit-mask specifying the
367 * protection mechanisms supported by the server, and the sixth
368 * through eighth octets containing, in network byte order, the
369 * maximum cipher-text buffer size the server is able to receive.
370 * The server must encrypt the 8 octets of data in the session key
371 * and issue that encrypted data in a second ready response. The
372 * client should consider the server authenticated if the first
373 * four octets the un-encrypted data is equal to one plus the
374 * checksum it previously sent.
377 if (result = gen_recv(sock, buf1, sizeof buf1))
380 /* The client must construct data with the first four octets
381 * containing the original server-issued checksum in network byte
382 * order, the fifth octet containing the bit-mask specifying the
383 * selected protection mechanism, the sixth through eighth octets
384 * containing in network byte order the maximum cipher-text buffer
385 * size the client is able to receive, and the following octets
386 * containing a user name string. The client must then append
387 * from one to eight octets so that the length of the data is a
388 * multiple of eight octets. The client must then PCBC encrypt the
389 * data with the session key and respond to the second ready
390 * response with the encrypted data. The server decrypts the data
391 * and verifies the contained checksum. The username field
392 * identifies the user for whom subsequent IMAP operations are to
393 * be performed; the server must verify that the principal
394 * identified in the Kerberos ticket is authorized to connect as
395 * that user. After these verifications, the authentication
396 * process is complete.
399 len = from64tobits(buf2, buf1);
401 report(stderr, _("could not decode BASE64 ready response\n"));
405 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
406 memcpy(challenge2.cstr, buf2, 4);
407 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
408 report(stderr, _("challenge mismatch\n"));
412 memset(authenticator.dat, 0, sizeof authenticator.dat);
414 result = htonl(challenge1.cint);
415 memcpy(authenticator.dat, &result, sizeof result);
417 /* The protection mechanisms and their corresponding bit-masks are as
420 * 1 No protection mechanism
421 * 2 Integrity (krb_mk_safe) protection
422 * 4 Privacy (krb_mk_priv) protection
424 authenticator.dat[4] = 1;
426 len = strlen(tktuser);
427 strncpy(authenticator.dat+8, tktuser, len);
428 authenticator.length = len + 8 + 1;
429 while (authenticator.length & 7) {
430 authenticator.length++;
432 des_pcbc_encrypt((des_cblock *)authenticator.dat,
433 (des_cblock *)authenticator.dat, authenticator.length, schedule,
436 to64frombits(buf1, authenticator.dat, authenticator.length);
437 if (outlevel >= O_MONITOR) {
438 report(stdout, "IMAP> %s\n", buf1);
441 strcat(buf1, "\r\n");
442 SockWrite(sock, buf1, strlen(buf1));
444 if (result = gen_recv(sock, buf1, sizeof buf1))
447 if (strstr(buf1, "OK")) {
454 #endif /* KERBEROS_V4 */
457 #define GSSAUTH_P_NONE 1
458 #define GSSAUTH_P_INTEGRITY 2
459 #define GSSAUTH_P_PRIVACY 4
461 static int do_gssauth(int sock, char *hostname, char *username)
463 gss_buffer_desc request_buf, send_token;
464 gss_buffer_t sec_token;
465 gss_name_t target_name;
466 gss_ctx_id_t context;
470 OM_uint32 maj_stat, min_stat;
471 char buf1[8192], buf2[8192], server_conf_flags;
472 unsigned long buf_size;
475 /* first things first: get an imap ticket for host */
476 sprintf(buf1, "imap@%s", hostname);
477 request_buf.value = buf1;
478 request_buf.length = strlen(buf1) + 1;
479 maj_stat = gss_import_name(&min_stat, &request_buf, GSS_C_NT_HOSTBASED_SERVICE,
481 if (maj_stat != GSS_S_COMPLETE) {
482 report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
485 else if (outlevel >= O_DEBUG) {
486 maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
488 report(stderr, _("Using service name [%s]\n"),request_buf.value);
489 maj_stat = gss_release_buffer(&min_stat, &request_buf);
492 gen_send(sock, "AUTHENTICATE GSSAPI");
494 /* upon receipt of the GSSAPI authentication request, server returns
495 * null data ready response. */
496 if (result = gen_recv(sock, buf1, sizeof buf1)) {
500 /* now start the security context initialisation loop... */
501 sec_token = GSS_C_NO_BUFFER;
502 context = GSS_C_NO_CONTEXT;
503 if (outlevel >= O_VERBOSE)
504 report(stdout, _("Sending credentials\n"));
506 send_token.length = 0;
507 send_token.value = NULL;
508 maj_stat = gss_init_sec_context(&min_stat,
513 GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG,
515 GSS_C_NO_CHANNEL_BINDINGS,
521 if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
522 report(stderr, _("Error exchanging credentials\n"));
523 gss_release_name(&min_stat, &target_name);
524 /* wake up server and await NO response */
525 SockWrite(sock, "\r\n", 2);
526 if (result = gen_recv(sock, buf1, sizeof buf1))
530 to64frombits(buf1, send_token.value, send_token.length);
531 gss_release_buffer(&min_stat, &send_token);
532 strcat(buf1, "\r\n");
533 SockWrite(sock, buf1, strlen(buf1));
534 if (outlevel >= O_MONITOR)
535 report(stdout, "IMAP> %s\n", buf1);
536 if (maj_stat == GSS_S_CONTINUE_NEEDED) {
537 if (result = gen_recv(sock, buf1, sizeof buf1)) {
538 gss_release_name(&min_stat, &target_name);
541 request_buf.length = from64tobits(buf2, buf1 + 2);
542 request_buf.value = buf2;
543 sec_token = &request_buf;
545 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
546 gss_release_name(&min_stat, &target_name);
548 /* get security flags and buffer size */
549 if (result = gen_recv(sock, buf1, sizeof buf1)) {
552 request_buf.length = from64tobits(buf2, buf1 + 2);
553 request_buf.value = buf2;
555 maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
557 if (maj_stat != GSS_S_COMPLETE) {
558 report(stderr, _("Couldn't unwrap security level data\n"));
559 gss_release_buffer(&min_stat, &send_token);
562 if (outlevel >= O_DEBUG)
563 report(stdout, _("Credential exchange complete\n"));
564 /* first octet is security levels supported. We want none, for now */
565 server_conf_flags = ((char *)send_token.value)[0];
566 if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
567 report(stderr, _("Server requires integrity and/or privacy\n"));
568 gss_release_buffer(&min_stat, &send_token);
571 ((char *)send_token.value)[0] = 0;
572 buf_size = ntohl(*((long *)send_token.value));
573 /* we don't care about buffer size if we don't wrap data */
574 gss_release_buffer(&min_stat, &send_token);
575 if (outlevel >= O_DEBUG) {
576 report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
577 server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
578 server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
579 server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
580 report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
583 /* now respond in kind (hack!!!) */
584 buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
585 memcpy(buf1, &buf_size, 4);
586 buf1[0] = GSSAUTH_P_NONE;
587 strcpy(buf1+4, username); /* server decides if princ is user */
588 request_buf.length = 4 + strlen(username) + 1;
589 request_buf.value = buf1;
590 maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
591 &cflags, &send_token);
592 if (maj_stat != GSS_S_COMPLETE) {
593 report(stderr, _("Error creating security level request\n"));
596 to64frombits(buf1, send_token.value, send_token.length);
597 if (outlevel >= O_DEBUG) {
598 report(stdout, _("Requesting authorization as %s\n"), username);
599 report(stdout, "IMAP> %s\n",buf1);
601 strcat(buf1, "\r\n");
602 SockWrite(sock, buf1, strlen(buf1));
604 /* we should be done. Get status and finish up */
605 if (result = gen_recv(sock, buf1, sizeof buf1))
607 if (strstr(buf1, "OK")) {
608 /* flush security context */
609 if (outlevel >= O_DEBUG)
610 report(stdout, _("Releasing GSS credentials\n"));
611 maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
612 if (maj_stat != GSS_S_COMPLETE) {
613 report(stderr, _("Error releasing credentials\n"));
616 /* send_token may contain a notification to the server to flush
617 * credentials. RFC 1731 doesn't specify what to do, and since this
618 * support is only for authentication, we'll assume the server
619 * knows enough to flush its own credentials */
620 gss_release_buffer(&min_stat, &send_token);
628 static void hmac_md5 (unsigned char *password, size_t pass_len,
629 unsigned char *challenge, size_t chal_len,
630 unsigned char *response, size_t resp_len)
633 unsigned char ipad[64];
634 unsigned char opad[64];
635 unsigned char hash_passwd[16];
642 if (pass_len > sizeof (ipad))
645 MD5Update (&ctx, password, pass_len);
646 MD5Final (hash_passwd, &ctx);
647 password = hash_passwd; pass_len = sizeof (hash_passwd);
650 memset (ipad, 0, sizeof (ipad));
651 memset (opad, 0, sizeof (opad));
652 memcpy (ipad, password, pass_len);
653 memcpy (opad, password, pass_len);
655 for (i=0; i<64; i++) {
661 MD5Update (&ctx, ipad, sizeof (ipad));
662 MD5Update (&ctx, challenge, chal_len);
663 MD5Final (response, &ctx);
666 MD5Update (&ctx, opad, sizeof (opad));
667 MD5Update (&ctx, response, resp_len);
668 MD5Final (response, &ctx);
674 static tSmbNtlmAuthRequest request;
675 static tSmbNtlmAuthChallenge challenge;
676 static tSmbNtlmAuthResponse response;
679 * NTLM support by Grant Edwards.
681 * Handle MS-Exchange NTLM authentication method. This is the same
682 * as the NTLM auth used by Samba for SMB related services. We just
683 * encode the packets in base64 instead of sending them out via a
686 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
689 static int do_imap_ntlm(int sock, struct query *ctl)
694 gen_send(sock, "AUTHENTICATE NTLM");
696 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
699 if (msgbuf[0] != '+')
702 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
704 if (outlevel >= O_DEBUG)
705 dumpSmbNtlmAuthRequest(stdout, &request);
707 memset(msgbuf,0,sizeof msgbuf);
708 to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
710 if (outlevel >= O_MONITOR)
711 report(stdout, "IMAP> %s\n", msgbuf);
713 strcat(msgbuf,"\r\n");
714 SockWrite (sock, msgbuf, strlen (msgbuf));
716 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
719 len = from64tobits ((unsigned char*)&challenge, msgbuf);
721 if (outlevel >= O_DEBUG)
722 dumpSmbNtlmAuthChallenge(stdout, &challenge);
724 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
726 if (outlevel >= O_DEBUG)
727 dumpSmbNtlmAuthResponse(stdout, &response);
729 memset(msgbuf,0,sizeof msgbuf);
730 to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
732 if (outlevel >= O_MONITOR)
733 report(stdout, "IMAP> %s\n", msgbuf);
735 strcat(msgbuf,"\r\n");
737 SockWrite (sock, msgbuf, strlen (msgbuf));
739 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
742 if (strstr (msgbuf, "OK"))
749 static int do_cram_md5 (int sock, struct query *ctl)
750 /* authenticate as per RFC2195 */
754 unsigned char buf1[1024];
755 unsigned char msg_id[768];
756 unsigned char response[16];
757 unsigned char reply[1024];
759 gen_send (sock, "AUTHENTICATE CRAM-MD5");
762 * The data encoded in the first ready response contains an
763 * presumptively arbitrary string of random digits, a timestamp, and the
764 * fully-qualified primary host name of the server. The syntax of the
765 * unencoded form must correspond to that of an RFC 822 'msg-id'
766 * [RFC822] as described in [POP3].
769 if ((result = gen_recv (sock, buf1, sizeof (buf1)))) {
773 len = from64tobits (msg_id, buf1);
775 report (stderr, _("could not decode BASE64 challenge\n"));
777 } else if (len < sizeof (msg_id)) {
780 msg_id[sizeof (msg_id)-1] = 0;
782 if (outlevel >= O_DEBUG) {
783 report (stdout, "decoded as %s\n", msg_id);
786 /* The client makes note of the data and then responds with a string
787 * consisting of the user name, a space, and a 'digest'. The latter is
788 * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where
789 * the key is a shared secret and the digested text is the timestamp
790 * (including angle-brackets).
793 hmac_md5 (ctl->password, strlen (ctl->password),
794 msg_id, strlen (msg_id),
795 response, sizeof (response));
798 snprintf (reply, sizeof (reply),
802 "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
804 response[0], response[1], response[2], response[3],
805 response[4], response[5], response[6], response[7],
806 response[8], response[9], response[10], response[11],
807 response[12], response[13], response[14], response[15]);
809 if (outlevel >= O_DEBUG) {
810 report (stdout, "replying with %s\n", reply);
813 to64frombits (buf1, reply, strlen (reply));
814 if (outlevel >= O_MONITOR) {
815 report (stdout, "IMAP> %s\n", buf1);
818 /* PMDF5.2 IMAP has a bug that requires this to be a single write */
819 strcat (buf1, "\r\n");
820 SockWrite (sock, buf1, strlen (buf1));
822 if ((result = gen_recv (sock, buf1, sizeof (buf1))))
825 if (strstr (buf1, "OK")) {
832 int imap_canonicalize(char *result, char *raw, int maxlen)
833 /* encode an IMAP password as per RFC1730's quoting conventions */
838 for (i = 0; i < strlen(raw) && i < maxlen; i++)
840 if ((raw[i] == '\\') || (raw[i] == '"'))
842 result[j++] = raw[i];
849 int imap_getauth(int sock, struct query *ctl, char *greeting)
850 /* apply for connection authorization */
854 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
855 capabilities[0] = '\0';
856 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
858 /* UW-IMAP server 10.173 notifies in all caps */
859 if (strstr(capabilities, "IMAP4REV1"))
861 imap_version = IMAP4rev1;
862 if (outlevel >= O_DEBUG)
863 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
867 imap_version = IMAP4;
868 if (outlevel >= O_DEBUG)
869 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
872 else if (ok == PS_ERROR)
874 imap_version = IMAP2;
875 if (outlevel >= O_DEBUG)
876 report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
881 peek_capable = (imap_version >= IMAP4);
884 * Assumption: expunges are cheap, so we want to do them
885 * after every message unless user said otherwise.
887 if (NUM_SPECIFIED(ctl->expunge))
888 expunge_period = NUM_VALUE_OUT(ctl->expunge);
893 * If either (a) we saw a PREAUTH token in the greeting, or
894 * (b) the user specified ssh preauthentication, then we're done.
896 if (preauth || ctl->server.preauthenticate == A_SSH)
898 preauth = FALSE; /* reset for the next session */
903 * Handle idling. We depend on coming through here on startup
904 * and after each timeout (including timeouts during idles).
906 if (strstr(capabilities, "IDLE") && ctl->idle)
909 if (outlevel >= O_VERBOSE)
910 report(stdout, "will idle after poll\n");
914 if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
916 if (outlevel >= O_DEBUG)
917 report(stdout, _("OTP authentication is supported\n"));
918 if (do_otp(sock, ctl) == PS_SUCCESS)
921 #endif /* OPIE_ENABLE */
924 if (strstr(capabilities, "AUTH=GSSAPI"))
926 if (ctl->server.protocol == P_IMAP_GSS)
928 if (outlevel >= O_DEBUG)
929 report(stdout, _("GSS authentication is supported\n"));
930 return do_gssauth(sock, ctl->server.truename, ctl->remotename);
933 else if (ctl->server.protocol == P_IMAP_GSS)
936 _("Required GSS capability not supported by server\n"));
942 if (strstr(capabilities, "AUTH=KERBEROS_V4"))
944 if (outlevel >= O_DEBUG)
945 report(stdout, _("KERBEROS_V4 authentication is supported\n"));
947 if (ctl->server.protocol == P_IMAP_K4)
949 if ((ok = do_rfc1731(sock, ctl->server.truename)))
951 if (outlevel >= O_MONITOR)
952 report(stdout, "IMAP> *\n");
953 SockWrite(sock, "*\r\n", 3);
958 /* else fall through to ordinary AUTH=LOGIN case */
960 else if (ctl->server.protocol == P_IMAP_K4)
963 _("Required KERBEROS_V4 capability not supported by server\n"));
966 #endif /* KERBEROS_V4 */
968 if (strstr(capabilities, "AUTH=CRAM-MD5"))
970 if (outlevel >= O_DEBUG)
971 report (stdout, _("CRAM-MD5 authentication is supported\n"));
972 if (ctl->server.protocol != P_IMAP_LOGIN)
974 if ((ok = do_cram_md5 (sock, ctl)))
976 if (outlevel >= O_MONITOR)
977 report (stdout, "IMAP> *\n");
978 SockWrite (sock, "*\r\n", 3);
983 else if (ctl->server.protocol == P_IMAP_CRAM_MD5)
986 _("Required CRAM-MD5 capability not supported by server\n"));
991 if (strstr (capabilities, "AUTH=NTLM"))
993 if (outlevel >= O_DEBUG)
994 report (stdout, _("NTLM authentication is supported\n"));
995 return do_imap_ntlm (sock, ctl);
997 #endif /* NTLM_ENABLE */
999 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
1000 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
1001 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
1003 _("Required LOGIN capability not supported by server\n"));
1006 #endif /* __UNUSED__ */
1009 /* these sizes guarantee no buffer overflow */
1010 char remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
1012 imap_canonicalize(remotename, ctl->remotename, NAMELEN);
1013 imap_canonicalize(password, ctl->password, PASSWORDLEN);
1014 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
1023 static int internal_expunge(int sock)
1024 /* ship an expunge, resetting associated counters */
1028 if ((ok = gen_transact(sock, "EXPUNGE")))
1031 expunged += deletions;
1032 unseen -= deletions;
1035 #ifdef IMAP_UID /* not used */
1037 #endif /* IMAP_UID */
1042 static int imap_getrange(int sock,
1045 int *countp, int *newp, int *bytes)
1046 /* get range of messages to be fetched */
1049 char buf[MSGBUFSIZE+1], *cp;
1051 /* find out how many messages are waiting */
1057 * We have to have an expunge here, otherwise the re-poll will
1058 * infinite-loop picking up un-expunged messages -- unless the
1059 * expunge period is one and we've been nuking each message
1060 * just after deletion.
1063 if (deletions && expunge_period != 1)
1064 ok = internal_expunge(sock);
1069 saved_timeout = mytimeout;
1072 if (ok || gen_transact(sock, do_idle ? "IDLE" : "NOOP"))
1074 report(stderr, _("re-poll failed\n"));
1077 else if (count == -1) /* no EXISTS response to NOOP/IDLE */
1084 ok = gen_transact(sock,
1085 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
1086 folder ? folder : "INBOX");
1089 report(stderr, _("mailbox selection failed\n"));
1096 /* OK, now get a count of unseen messages and their indices */
1098 if (unseen_messages)
1099 free(unseen_messages);
1100 unseen_messages = xmalloc(count * sizeof(unsigned int));
1101 memset(unseen_messages, 0, count * sizeof(unsigned int));
1104 gen_send(sock, "SEARCH UNSEEN");
1106 ok = gen_recv(sock, buf, sizeof(buf));
1109 report(stderr, _("search for unseen messages failed\n"));
1110 return(PS_PROTOCOL);
1112 else if ((cp = strstr(buf, "* SEARCH")))
1116 cp += 8; /* skip "* SEARCH" */
1118 while (*cp && unseen < count)
1120 /* skip whitespace */
1121 while (*cp && isspace(*cp))
1126 * Message numbers are between 1 and 2^32 inclusive,
1127 * so unsigned int is large enough.
1129 unseen_messages[unseen]=(unsigned int)strtol(cp,&ep,10);
1131 if (outlevel >= O_DEBUG)
1133 _("%u is unseen\n"),
1134 unseen_messages[unseen]);
1142 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
1150 static int imap_getsizes(int sock, int count, int *sizes)
1151 /* capture the sizes of all messages */
1153 char buf [MSGBUFSIZE+1];
1156 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1157 * won't accept 1:1 as valid set syntax. Some implementors
1158 * should be taken out and shot for excessive anality.
1160 * Microsoft Exchange (brain-dead piece of crap that it is)
1161 * sometimes gets its knickers in a knot about bodiless messages.
1162 * You may see responses like this:
1164 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1165 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1166 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1167 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1168 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1169 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1170 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1171 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1172 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1173 * fetchmail: IMAP< A0004 NO The requested item could not be found.
1175 * This means message 1 has only headers. For kicks and grins
1176 * you can telnet in and look:
1178 * A003 NO The requested item could not be found.
1179 * A004 fetch 1 rfc822.header
1180 * A004 NO The requested item could not be found.
1182 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1183 * A006 OK FETCH completed.
1185 * To get around this, we terminate the read loop on a NO and count
1186 * on the fact that the sizes array has been preinitialized with a
1187 * known-bad size value.
1190 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
1192 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
1197 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1199 else if (strstr(buf, "OK") || strstr(buf, "NO"))
1201 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
1202 sizes[num - 1] = size;
1208 static int imap_is_old(int sock, struct query *ctl, int number)
1209 /* is the given message old? */
1215 * Expunges change the fetch numbers, but unseen_messages contains
1216 * indices from before any expungees were done. So neither the
1217 * argument nor the values in message_sequence need to be decremented.
1221 for (i = 0; i < unseen; i++)
1222 if (unseen_messages[i] == number)
1231 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1232 /* request headers of nth message */
1234 char buf [MSGBUFSIZE+1];
1237 /* expunges change the fetch numbers */
1241 * This is blessed by RFC1176, RFC1730, RFC2060.
1242 * According to the RFCs, it should *not* set the \Seen flag.
1244 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1246 /* looking for FETCH response */
1250 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1253 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
1261 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1262 /* request body of nth message */
1264 char buf [MSGBUFSIZE+1], *cp;
1267 /* expunges change the fetch numbers */
1271 * If we're using IMAP4, we can fetch the message without setting its
1272 * seen flag. This is good! It means that if the protocol exchange
1273 * craps out during the message, it will still be marked `unseen' on
1276 * However...*don't* do this if we're using keep to suppress deletion!
1277 * In that case, marking the seen flag is the only way to prevent the
1278 * message from being re-fetched on subsequent runs (and according
1279 * to RFC2060 p.43 this fetch should set Seen as a side effect).
1281 * According to RFC2060, and Mark Crispin the IMAP maintainer,
1282 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
1283 * equivalent". However, we know of at least one server that
1284 * treats them differently in the presence of MIME attachments;
1285 * the latter form downloads the attachment, the former does not.
1286 * The server is InterChange, and the fool who implemented this
1287 * misfeature ought to be strung up by his thumbs.
1289 * When I tried working around this by disable use of the 4rev1 form,
1290 * I found that doing this breaks operation with M$ Exchange.
1291 * Annoyingly enough, Exchange's refusal to cope is technically legal
1292 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
1293 * standards, to find a way to make standards compliance irritating....
1295 switch (imap_version)
1297 case IMAP4rev1: /* RFC 2060 */
1299 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1301 gen_send(sock, "FETCH %d BODY[TEXT]", number);
1304 case IMAP4: /* RFC 1730 */
1306 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1308 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1311 default: /* RFC 1176 */
1312 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1316 /* looking for FETCH response */
1320 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1323 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1329 * Try to extract a length from the FETCH response. RFC2060 requires
1330 * it to be present, but at least one IMAP server (Novell GroupWise)
1333 if ((cp = strchr(buf, '{')))
1334 *lenp = atoi(cp + 1);
1336 *lenp = -1; /* missing length part in FETCH reponse */
1341 static int imap_trail(int sock, struct query *ctl, int number)
1342 /* discard tail of FETCH response after reading message text */
1344 /* expunges change the fetch numbers */
1345 /* number -= expunged; */
1349 char buf[MSGBUFSIZE+1];
1352 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1355 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1356 if (strstr(buf, "OK"))
1361 * Any IMAP server that fails to set Seen on a BODY[TEXT]
1362 * fetch violates RFC2060 p.43 (top). This becomes an issue
1363 * when keep is on, because seen messages aren't deleted and
1364 * get refetched on each poll. As a workaround, if keep is on
1365 * we can set the Seen flag explicitly.
1367 * This code isn't used yet because we don't know of any IMAP
1368 * servers broken in this way.
1371 if ((ok = gen_transact(sock,
1372 imap_version == IMAP4
1373 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1374 : "STORE %d +FLAGS (\\Seen)",
1377 #endif /* __UNUSED__ */
1383 static int imap_delete(int sock, struct query *ctl, int number)
1384 /* set delete flag for given message */
1388 /* expunges change the fetch numbers */
1392 * Use SILENT if possible as a minor throughput optimization.
1393 * Note: this has been dropped from IMAP4rev1.
1395 * We set Seen because there are some IMAP servers (notably HP
1396 * OpenMail) that do message-receipt DSNs, but only when the seen
1397 * bit is set. This is the appropriate time -- we get here right
1398 * after the local SMTP response that says delivery was
1401 if ((ok = gen_transact(sock,
1402 imap_version == IMAP4
1403 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1404 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1411 * We do an expunge after expunge_period messages, rather than
1412 * just before quit, so that a line hit during a long session
1413 * won't result in lots of messages being fetched again during
1416 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1417 internal_expunge(sock);
1422 static int imap_logout(int sock, struct query *ctl)
1423 /* send logout command */
1425 /* if any un-expunged deletions remain, ship an expunge now */
1427 internal_expunge(sock);
1430 /* Memory clean-up */
1431 if (unseen_messages)
1432 free(unseen_messages);
1433 #endif /* USE_SEARCH */
1435 return(gen_transact(sock, "LOGOUT"));
1438 const static struct method imap =
1440 "IMAP", /* Internet Message Access Protocol */
1444 #else /* INET6_ENABLE */
1445 143, /* standard IMAP2bis/IMAP4 port */
1446 993, /* ssl IMAP2bis/IMAP4 port */
1447 #endif /* INET6_ENABLE */
1448 TRUE, /* this is a tagged protocol */
1449 FALSE, /* no message delimiter */
1450 imap_ok, /* parse command response */
1451 imap_canonicalize, /* deal with embedded slashes and spaces */
1452 imap_getauth, /* get authorization */
1453 imap_getrange, /* query range of messages */
1454 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
1455 imap_is_old, /* no UID check */
1456 imap_fetch_headers, /* request given message headers */
1457 imap_fetch_body, /* request given message body */
1458 imap_trail, /* eat message trailer */
1459 imap_delete, /* delete the message */
1460 imap_logout, /* expunge and exit */
1461 TRUE, /* yes, we can re-poll */
1464 int doIMAP(struct query *ctl)
1465 /* retrieve messages using IMAP Version 2bis or Version 4 */
1467 return(do_protocol(ctl, &imap));
1470 /* imap.c ends here */