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 */
36 #include <gssapi/gssapi.h>
37 #include <gssapi/gssapi_generic.h>
46 #ifndef strstr /* glibc-2.1 declares this as a macro */
47 extern char *strstr(); /* needed on sysV68 R3V7.1. */
50 /* imap_version values */
51 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
52 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
53 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
55 static int count, seen, recent, unseen, deletions, imap_version;
56 static int expunged, expunge_period;
57 static char capabilities[MSGBUFSIZE+1];
59 int imap_ok(int sock, char *argbuf)
60 /* parse command response */
62 char buf [MSGBUFSIZE+1];
69 if ((ok = gen_recv(sock, buf, sizeof(buf))))
72 /* all tokens in responses are caseblind */
73 for (cp = buf; *cp; cp++)
77 /* interpret untagged status responses */
78 if (strstr(buf, "* CAPABILITY"))
79 strncpy(capabilities, buf + 12, sizeof(capabilities));
80 if (strstr(buf, "EXISTS"))
82 if (strstr(buf, "RECENT"))
84 if (strstr(buf, "UNSEEN"))
89 * Handle both "* 42 UNSEEN" (if tha ever happens) and
90 * "* OK [UNSEEN 42] 42". Note that what this gets us is
91 * a minimum index, not a count.
94 for (cp = buf; *cp && !isdigit(*cp); cp++)
98 if (strstr(buf, "FLAGS"))
99 seen = (strstr(buf, "SEEN") != (char *)NULL);
101 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
114 for (cp = buf; !isspace(*cp); cp++)
119 if (strncmp(cp, "OK", 2) == 0)
125 else if (strncmp(cp, "BAD", 3) == 0)
127 else if (strncmp(cp, "NO", 2) == 0)
135 static int do_otp(int sock, struct query *ctl)
139 char challenge[OPIE_CHALLENGE_MAX+1];
140 char response[OPIE_RESPONSE_MAX+1];
142 gen_send(sock, "AUTHENTICATE X-OTP");
144 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
147 if ((i = from64tobits(challenge, buffer)) < 0) {
148 report(stderr, _("Could not decode initial BASE64 challenge\n"));
153 to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
155 if (outlevel >= O_MONITOR)
156 report(stdout, "IMAP> %s\n", buffer);
157 SockWrite(sock, buffer, strlen(buffer));
158 SockWrite(sock, "\r\n", 2);
160 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
163 if ((i = from64tobits(challenge, buffer)) < 0) {
164 report(stderr, _("Could not decode OTP challenge\n"));
168 rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
169 if ((rval == -2) && !run.poll_interval) {
170 char secret[OPIE_SECRET_MAX+1];
171 fprintf(stderr, _("Secret pass phrase: "));
172 if (opiereadpass(secret, sizeof(secret), 0))
173 rval = opiegenerator(challenge, secret, response);
174 memset(secret, 0, sizeof(secret));
180 to64frombits(buffer, response, strlen(response));
182 if (outlevel >= O_MONITOR)
183 report(stdout, "IMAP> %s\n", buffer);
184 SockWrite(sock, buffer, strlen(buffer));
185 SockWrite(sock, "\r\n", 2);
187 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
190 if (strstr(buffer, "OK"))
200 #elif SIZEOF_SHORT == 4
202 #elif SIZEOF_LONG == 4
205 #error Cannot deduce a 32-bit-type
208 static int do_rfc1731(int sock, char *truename)
209 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
212 char buf1[4096], buf2[4096];
216 } challenge1, challenge2;
217 char srvinst[INST_SZ];
219 char srvrealm[REALM_SZ];
220 KTEXT_ST authenticator;
221 CREDENTIALS credentials;
222 char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
223 char tktinst[INST_SZ];
224 char tktrealm[REALM_SZ];
226 des_key_schedule schedule;
228 gen_send(sock, "AUTHENTICATE KERBEROS_V4");
230 /* The data encoded in the first ready response contains a random
231 * 32-bit number in network byte order. The client should respond
232 * with a Kerberos ticket and an authenticator for the principal
233 * "imap.hostname@realm", where "hostname" is the first component
234 * of the host name of the server with all letters in lower case
235 * and where "realm" is the Kerberos realm of the server. The
236 * encrypted checksum field included within the Kerberos
237 * authenticator should contain the server provided 32-bit number
238 * in network byte order.
241 if (result = gen_recv(sock, buf1, sizeof buf1)) {
245 /* this patch by Dan Root <dar@thekeep.org> solves an endianess problem. */
249 *(int *)tmp = ntohl(*(int *) challenge1.cstr);
250 memcpy(challenge1.cstr, tmp, sizeof(tmp));
253 len = from64tobits(challenge1.cstr, buf1);
255 report(stderr, _("could not decode initial BASE64 challenge\n"));
259 /* Client responds with a Kerberos ticket and an authenticator for
260 * the principal "imap.hostname@realm" where "hostname" is the
261 * first component of the host name of the server with all letters
262 * in lower case and where "realm" is the Kerberos realm of the
263 * server. The encrypted checksum field included within the
264 * Kerberos authenticator should contain the server-provided
265 * 32-bit number in network byte order.
268 strncpy(srvinst, truename, (sizeof srvinst)-1);
269 srvinst[(sizeof srvinst)-1] = '\0';
270 for (p = srvinst; *p; p++) {
276 strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
277 srvrealm[(sizeof srvrealm)-1] = '\0';
278 if (p = strchr(srvinst, '.')) {
282 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
284 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
288 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
290 report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
294 memcpy(session, credentials.session, sizeof session);
295 memset(&credentials, 0, sizeof credentials);
296 des_key_sched(session, schedule);
298 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
300 report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
304 if (strcmp(tktuser, user) != 0) {
306 _("principal %s in ticket does not match -u %s\n"), tktuser,
313 _("non-null instance (%s) might cause strange behavior\n"),
315 strcat(tktuser, ".");
316 strcat(tktuser, tktinst);
319 if (strcmp(tktrealm, srvrealm) != 0) {
320 strcat(tktuser, "@");
321 strcat(tktuser, tktrealm);
324 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
327 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
331 to64frombits(buf1, authenticator.dat, authenticator.length);
332 if (outlevel >= O_MONITOR) {
333 report(stdout, "IMAP> %s\n", buf1);
335 SockWrite(sock, buf1, strlen(buf1));
336 SockWrite(sock, "\r\n", 2);
338 /* Upon decrypting and verifying the ticket and authenticator, the
339 * server should verify that the contained checksum field equals
340 * the original server provided random 32-bit number. Should the
341 * verification be successful, the server must add one to the
342 * checksum and construct 8 octets of data, with the first four
343 * octets containing the incremented checksum in network byte
344 * order, the fifth octet containing a bit-mask specifying the
345 * protection mechanisms supported by the server, and the sixth
346 * through eighth octets containing, in network byte order, the
347 * maximum cipher-text buffer size the server is able to receive.
348 * The server must encrypt the 8 octets of data in the session key
349 * and issue that encrypted data in a second ready response. The
350 * client should consider the server authenticated if the first
351 * four octets the un-encrypted data is equal to one plus the
352 * checksum it previously sent.
355 if (result = gen_recv(sock, buf1, sizeof buf1))
358 /* The client must construct data with the first four octets
359 * containing the original server-issued checksum in network byte
360 * order, the fifth octet containing the bit-mask specifying the
361 * selected protection mechanism, the sixth through eighth octets
362 * containing in network byte order the maximum cipher-text buffer
363 * size the client is able to receive, and the following octets
364 * containing a user name string. The client must then append
365 * from one to eight octets so that the length of the data is a
366 * multiple of eight octets. The client must then PCBC encrypt the
367 * data with the session key and respond to the second ready
368 * response with the encrypted data. The server decrypts the data
369 * and verifies the contained checksum. The username field
370 * identifies the user for whom subsequent IMAP operations are to
371 * be performed; the server must verify that the principal
372 * identified in the Kerberos ticket is authorized to connect as
373 * that user. After these verifications, the authentication
374 * process is complete.
377 len = from64tobits(buf2, buf1);
379 report(stderr, _("could not decode BASE64 ready response\n"));
383 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
384 memcpy(challenge2.cstr, buf2, 4);
385 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
386 report(stderr, _("challenge mismatch\n"));
390 memset(authenticator.dat, 0, sizeof authenticator.dat);
392 result = htonl(challenge1.cint);
393 memcpy(authenticator.dat, &result, sizeof result);
395 /* The protection mechanisms and their corresponding bit-masks are as
398 * 1 No protection mechanism
399 * 2 Integrity (krb_mk_safe) protection
400 * 4 Privacy (krb_mk_priv) protection
402 authenticator.dat[4] = 1;
404 len = strlen(tktuser);
405 strncpy(authenticator.dat+8, tktuser, len);
406 authenticator.length = len + 8 + 1;
407 while (authenticator.length & 7) {
408 authenticator.length++;
410 des_pcbc_encrypt((des_cblock *)authenticator.dat,
411 (des_cblock *)authenticator.dat, authenticator.length, schedule,
414 to64frombits(buf1, authenticator.dat, authenticator.length);
415 if (outlevel >= O_MONITOR) {
416 report(stdout, "IMAP> %s\n", buf1);
418 SockWrite(sock, buf1, strlen(buf1));
419 SockWrite(sock, "\r\n", 2);
421 if (result = gen_recv(sock, buf1, sizeof buf1))
424 if (strstr(buf1, "OK")) {
431 #endif /* KERBEROS_V4 */
434 #define GSSAUTH_P_NONE 1
435 #define GSSAUTH_P_INTEGRITY 2
436 #define GSSAUTH_P_PRIVACY 4
438 static int do_gssauth(int sock, char *hostname, char *username)
440 gss_buffer_desc request_buf, send_token;
441 gss_buffer_t sec_token;
442 gss_name_t target_name;
443 gss_ctx_id_t context;
447 OM_uint32 maj_stat, min_stat;
448 char buf1[8192], buf2[8192], server_conf_flags;
449 unsigned long buf_size;
452 /* first things first: get an imap ticket for host */
453 sprintf(buf1, "imap@%s", hostname);
454 request_buf.value = buf1;
455 request_buf.length = strlen(buf1) + 1;
456 maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name,
458 if (maj_stat != GSS_S_COMPLETE) {
459 report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
462 else if (outlevel >= O_DEBUG) {
463 maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
465 report(stderr, _("Using service name [%s]\n"),request_buf.value);
466 maj_stat = gss_release_buffer(&min_stat, &request_buf);
469 gen_send(sock, "AUTHENTICATE GSSAPI");
471 /* upon receipt of the GSSAPI authentication request, server returns
472 * null data ready response. */
473 if (result = gen_recv(sock, buf1, sizeof buf1)) {
477 /* now start the security context initialisation loop... */
478 sec_token = GSS_C_NO_BUFFER;
479 context = GSS_C_NO_CONTEXT;
480 if (outlevel >= O_VERBOSE)
481 report(stdout, _("Sending credentials\n"));
483 maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL,
484 &context, target_name, NULL, 0, 0, NULL, sec_token, NULL,
485 &send_token, &cflags, NULL);
486 if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
487 report(stderr, _("Error exchanging credentials\n"));
488 gss_release_name(&min_stat, &target_name);
489 /* wake up server and await NO response */
490 SockWrite(sock, "\r\n", 2);
491 if (result = gen_recv(sock, buf1, sizeof buf1))
495 to64frombits(buf1, send_token.value, send_token.length);
496 gss_release_buffer(&min_stat, &send_token);
497 SockWrite(sock, buf1, strlen(buf1));
498 SockWrite(sock, "\r\n", 2);
499 if (outlevel >= O_MONITOR)
500 report(stdout, "IMAP> %s\n", buf1);
501 if (maj_stat == GSS_S_CONTINUE_NEEDED) {
502 if (result = gen_recv(sock, buf1, sizeof buf1)) {
503 gss_release_name(&min_stat, &target_name);
506 request_buf.length = from64tobits(buf2, buf1 + 2);
507 request_buf.value = buf2;
508 sec_token = &request_buf;
510 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
511 gss_release_name(&min_stat, &target_name);
513 /* get security flags and buffer size */
514 if (result = gen_recv(sock, buf1, sizeof buf1)) {
517 request_buf.length = from64tobits(buf2, buf1 + 2);
518 request_buf.value = buf2;
520 maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
522 if (maj_stat != GSS_S_COMPLETE) {
523 report(stderr, _("Couldn't unwrap security level data\n"));
524 gss_release_buffer(&min_stat, &send_token);
527 if (outlevel >= O_DEBUG)
528 report(stdout, _("Credential exchange complete\n"));
529 /* first octet is security levels supported. We want none, for now */
530 server_conf_flags = ((char *)send_token.value)[0];
531 if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
532 report(stderr, _("Server requires integrity and/or privacy\n"));
533 gss_release_buffer(&min_stat, &send_token);
536 ((char *)send_token.value)[0] = 0;
537 buf_size = ntohl(*((long *)send_token.value));
538 /* we don't care about buffer size if we don't wrap data */
539 gss_release_buffer(&min_stat, &send_token);
540 if (outlevel >= O_DEBUG) {
541 report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
542 server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
543 server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
544 server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
545 report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
548 /* now respond in kind (hack!!!) */
549 buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
550 memcpy(buf1, &buf_size, 4);
551 buf1[0] = GSSAUTH_P_NONE;
552 strcpy(buf1+4, username); /* server decides if princ is user */
553 request_buf.length = 4 + strlen(username) + 1;
554 request_buf.value = buf1;
555 maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
556 &cflags, &send_token);
557 if (maj_stat != GSS_S_COMPLETE) {
558 report(stderr, _("Error creating security level request\n"));
561 to64frombits(buf1, send_token.value, send_token.length);
562 if (outlevel >= O_DEBUG) {
563 report(stdout, _("Requesting authorisation as %s\n"), username);
564 report(stdout, "IMAP> %s\n",buf1);
566 SockWrite(sock, buf1, strlen(buf1));
567 SockWrite(sock, "\r\n", 2);
569 /* we should be done. Get status and finish up */
570 if (result = gen_recv(sock, buf1, sizeof buf1))
572 if (strstr(buf1, "OK")) {
573 /* flush security context */
574 if (outlevel >= O_DEBUG)
575 report(stdout, _("Releasing GSS credentials\n"));
576 maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
577 if (maj_stat != GSS_S_COMPLETE) {
578 report(stderr, _("Error releasing credentials\n"));
581 /* send_token may contain a notification to the server to flush
582 * credentials. RFC 1731 doesn't specify what to do, and since this
583 * support is only for authentication, we'll assume the server
584 * knows enough to flush its own credentials */
585 gss_release_buffer(&min_stat, &send_token);
593 static void hmac_md5 (unsigned char *password, size_t pass_len,
594 unsigned char *challenge, size_t chal_len,
595 unsigned char *response, size_t resp_len)
598 unsigned char ipad[64];
599 unsigned char opad[64];
600 unsigned char hash_passwd[16];
607 if (pass_len > sizeof (ipad))
610 MD5Update (&ctx, password, pass_len);
611 MD5Final (hash_passwd, &ctx);
612 password = hash_passwd; pass_len = sizeof (hash_passwd);
615 memset (ipad, 0, sizeof (ipad));
616 memset (opad, 0, sizeof (opad));
617 memcpy (ipad, password, pass_len);
618 memcpy (opad, password, pass_len);
620 for (i=0; i<64; i++) {
626 MD5Update (&ctx, ipad, sizeof (ipad));
627 MD5Update (&ctx, challenge, chal_len);
628 MD5Final (response, &ctx);
631 MD5Update (&ctx, opad, sizeof (opad));
632 MD5Update (&ctx, response, resp_len);
633 MD5Final (response, &ctx);
637 static int do_cram_md5 (int sock, struct query *ctl)
638 /* authenticate as per RFC2195 */
642 unsigned char buf1[1024];
643 unsigned char msg_id[768];
644 unsigned char response[16];
645 unsigned char reply[1024];
647 gen_send (sock, "AUTHENTICATE CRAM-MD5");
650 * The data encoded in the first ready response contains an
651 * presumptively arbitrary string of random digits, a timestamp, and the
652 * fully-qualified primary host name of the server. The syntax of the
653 * unencoded form must correspond to that of an RFC 822 'msg-id'
654 * [RFC822] as described in [POP3].
657 if (result = gen_recv (sock, buf1, sizeof (buf1))) {
661 len = from64tobits (msg_id, buf1);
663 report (stderr, _("could not decode BASE64 challenge\n"));
665 } else if (len < sizeof (msg_id)) {
668 msg_id[sizeof (msg_id)-1] = 0;
670 if (outlevel >= O_DEBUG) {
671 report (stdout, "decoded as %s\n", msg_id);
674 /* The client makes note of the data and then responds with a string
675 * consisting of the user name, a space, and a 'digest'. The latter is
676 * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where
677 * the key is a shared secret and the digested text is the timestamp
678 * (including angle-brackets).
681 hmac_md5 (ctl->password, strlen (ctl->password),
682 msg_id, strlen (msg_id),
683 response, sizeof (response));
685 snprintf (reply, sizeof (reply),
686 "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
688 response[0], response[1], response[2], response[3],
689 response[4], response[5], response[6], response[7],
690 response[8], response[9], response[10], response[11],
691 response[12], response[13], response[14], response[15]);
693 if (outlevel >= O_DEBUG) {
694 report (stdout, "replying with %s\n", reply);
697 to64frombits (buf1, reply, strlen (reply));
698 if (outlevel >= O_MONITOR) {
699 report (stdout, "IMAP> %s\n", buf1);
701 SockWrite (sock, buf1, strlen (buf1));
702 SockWrite (sock, "\r\n", 2);
704 if (result = gen_recv (sock, buf1, sizeof (buf1)))
707 if (strstr (buf1, "OK")) {
714 int imap_canonicalize(char *result, char *passwd)
715 /* encode an IMAP password as per RFC1730's quoting conventions */
720 for (i = 0; i < strlen(passwd); i++)
722 if ((passwd[i] == '\\') || (passwd[i] == '"'))
724 result[j++] = passwd[i];
731 int imap_getauth(int sock, struct query *ctl, char *greeting)
732 /* apply for connection authorization */
735 char password[PASSWORDLEN*2];
737 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
738 capabilities[0] = '\0';
739 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
741 /* UW-IMAP server 10.173 notifies in all caps */
742 if (strstr(capabilities, "IMAP4REV1"))
744 imap_version = IMAP4rev1;
745 if (outlevel >= O_DEBUG)
746 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
750 imap_version = IMAP4;
751 if (outlevel >= O_DEBUG)
752 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
755 else if (ok == PS_ERROR)
757 imap_version = IMAP2;
758 if (outlevel >= O_DEBUG)
759 report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
764 peek_capable = (imap_version >= IMAP4);
767 if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
769 if (outlevel >= O_DEBUG)
770 report(stdout, _("OTP authentication is supported\n"));
771 if (do_otp(sock, ctl) == PS_SUCCESS)
777 if (strstr(capabilities, "AUTH=GSSAPI"))
779 if (ctl->server.protocol == P_IMAP_GSS)
781 if (outlevel >= O_DEBUG)
782 report(stdout, _("GSS authentication is supported\n"));
783 return do_gssauth(sock, ctl->server.truename, ctl->remotename);
786 else if (ctl->server.protocol == P_IMAP_GSS)
789 _("Required GSS capability not supported by server\n"));
795 if (strstr(capabilities, "AUTH=KERBEROS_V4"))
797 if (outlevel >= O_DEBUG)
798 report(stdout, _("KERBEROS_V4 authentication is supported\n"));
800 if (ctl->server.protocol == P_IMAP_K4)
802 if ((ok = do_rfc1731(sock, ctl->server.truename)))
804 if (outlevel >= O_MONITOR)
805 report(stdout, "IMAP> *\n");
806 SockWrite(sock, "*\r\n", 3);
811 /* else fall through to ordinary AUTH=LOGIN case */
813 else if (ctl->server.protocol == P_IMAP_K4)
816 _("Required KERBEROS_V4 capability not supported by server\n"));
819 #endif /* KERBEROS_V4 */
821 if (strstr (capabilities, "AUTH=CRAM-MD5"))
823 if (outlevel >= O_DEBUG)
824 report (stdout, _("CRAM-MD5 authentication is supported\n"));
825 if ((ok = do_cram_md5 (sock, ctl)))
827 if (outlevel >= O_MONITOR)
828 report (stdout, "IMAP> *\n");
829 SockWrite (sock, "*\r\n", 3);
834 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
835 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
836 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
838 _("Required LOGIN capability not supported by server\n"));
841 #endif /* __UNUSED__ */
843 imap_canonicalize(password, ctl->password);
844 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
849 * Assumption: expunges are cheap, so we want to do them
850 * after every message unless user said otherwise.
852 if (NUM_SPECIFIED(ctl->expunge))
853 expunge_period = NUM_VALUE_OUT(ctl->expunge);
860 static int internal_expunge(int sock)
861 /* ship an expunge, resetting associated counters */
865 if ((ok = gen_transact(sock, "EXPUNGE")))
868 expunged += deletions;
871 #ifdef IMAP_UID /* not used */
873 #endif /* IMAP_UID */
878 static int imap_getrange(int sock,
881 int *countp, int *newp, int *bytes)
882 /* get range of messages to be fetched */
886 /* find out how many messages are waiting */
887 *bytes = recent = unseen = -1;
892 * We have to have an expunge here, otherwise the re-poll will
893 * infinite-loop picking up un-expunged messages.
896 if (deletions && expunge_period > 1)
897 internal_expunge(sock);
899 if (ok || gen_transact(sock, "NOOP"))
901 report(stderr, _("re-poll failed\n"));
904 else if (count == -1) /* no EXISTS response to NOOP */
913 ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
915 ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
918 report(stderr, _("mailbox selection failed\n"));
926 * Note: because IMAP has an is_old method, this number is used
927 * only for the "X messages (Y unseen)" notification. Accordingly
928 * it doesn't matter much that it can be wrong (e.g. if we see an
929 * UNSEEN response but not all messages above the first UNSEEN one
932 if (unseen >= 0) /* optional, but better if we see it */
933 *newp = count - unseen + 1;
934 else if (recent >= 0) /* mandatory */
937 *newp = -1; /* should never happen, RECENT is mandatory */
944 static int imap_getsizes(int sock, int count, int *sizes)
945 /* capture the sizes of all messages */
947 char buf [MSGBUFSIZE+1];
950 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
951 * won't accept 1:1 as valid set syntax. Some implementors
952 * should be taken out and shot for excessive anality.
955 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
957 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
962 if ((ok = gen_recv(sock, buf, sizeof(buf))))
964 if (strstr(buf, "OK"))
966 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
967 sizes[num - 1] = size;
973 static int imap_is_old(int sock, struct query *ctl, int number)
974 /* is the given message old? */
978 /* expunges change the fetch numbers */
981 if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
987 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
988 /* request headers of nth message */
990 char buf [MSGBUFSIZE+1];
993 /* expunges change the fetch numbers */
997 * This is blessed by RFC 1176, RFC1730, RFC2060.
998 * According to the RFCs, it should *not* set the \Seen flag.
1000 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1002 /* looking for FETCH response */
1006 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1009 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
1017 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1018 /* request body of nth message */
1020 char buf [MSGBUFSIZE+1], *cp;
1023 /* expunges change the fetch numbers */
1027 * If we're using IMAP4, we can fetch the message without setting its
1028 * seen flag. This is good! It means that if the protocol exchange
1029 * craps out during the message, it will still be marked `unseen' on
1032 * However...*don't* do this if we're using keep to suppress deletion!
1033 * In that case, marking the seen flag is the only way to prevent the
1034 * message from being re-fetched on subsequent runs.
1036 switch (imap_version)
1038 case IMAP4rev1: /* RFC 2060 */
1040 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1042 gen_send(sock, "FETCH %d BODY[TEXT]", number);
1045 case IMAP4: /* RFC 1730 */
1047 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1049 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1052 default: /* RFC 1176 */
1053 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1057 /* looking for FETCH response */
1061 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1064 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1069 /* try to extract a length */
1070 if ((cp = strchr(buf, '{')))
1071 *lenp = atoi(cp + 1);
1078 static int imap_trail(int sock, struct query *ctl, int number)
1079 /* discard tail of FETCH response after reading message text */
1081 /* expunges change the fetch numbers */
1082 /* number -= expunged; */
1086 char buf[MSGBUFSIZE+1];
1089 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1092 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1093 if (strstr(buf, "OK"))
1100 static int imap_delete(int sock, struct query *ctl, int number)
1101 /* set delete flag for given message */
1105 /* expunges change the fetch numbers */
1109 * Use SILENT if possible as a minor throughput optimization.
1110 * Note: this has been dropped from IMAP4rev1.
1112 * We set Seen because there are some IMAP servers (notably HP
1113 * OpenMail) that do message-receipt DSNs, but only when the seen
1114 * bit is set. This is the appropriate time -- we get here right
1115 * after the local SMTP response that says delivery was
1118 if ((ok = gen_transact(sock,
1119 imap_version == IMAP4
1120 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1121 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1128 * We do an expunge after expunge_period messages, rather than
1129 * just before quit, so that a line hit during a long session
1130 * won't result in lots of messages being fetched again during
1133 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1134 internal_expunge(sock);
1139 static int imap_logout(int sock, struct query *ctl)
1140 /* send logout command */
1142 /* if expunges after deletion have been suppressed, ship one now */
1143 if (NUM_SPECIFIED(expunge_period) && NUM_ZERO(expunge_period) && deletions)
1144 internal_expunge(sock);
1146 return(gen_transact(sock, "LOGOUT"));
1149 const static struct method imap =
1151 "IMAP", /* Internet Message Access Protocol */
1155 143, /* standard IMAP2bis/IMAP4 port */
1157 TRUE, /* this is a tagged protocol */
1158 FALSE, /* no message delimiter */
1159 imap_ok, /* parse command response */
1160 imap_canonicalize, /* deal with embedded slashes and spaces */
1161 imap_getauth, /* get authorization */
1162 imap_getrange, /* query range of messages */
1163 imap_getsizes, /* get sizes of messages (used for --limit option */
1164 imap_is_old, /* no UID check */
1165 imap_fetch_headers, /* request given message headers */
1166 imap_fetch_body, /* request given message body */
1167 imap_trail, /* eat message trailer */
1168 imap_delete, /* delete the message */
1169 imap_logout, /* expunge and exit */
1170 TRUE, /* yes, we can re-poll */
1173 int doIMAP(struct query *ctl)
1174 /* retrieve messages using IMAP Version 2bis or Version 4 */
1176 return(do_protocol(ctl, &imap));
1179 /* imap.c ends here */