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, preauth;
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, "PREAUTH", 2) == 0)
126 else if (strncmp(cp, "OK", 2) == 0)
132 else if (strncmp(cp, "BAD", 3) == 0)
134 else if (strncmp(cp, "NO", 2) == 0)
142 static int do_otp(int sock, struct query *ctl)
146 char challenge[OPIE_CHALLENGE_MAX+1];
147 char response[OPIE_RESPONSE_MAX+1];
149 gen_send(sock, "AUTHENTICATE X-OTP");
151 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
154 if ((i = from64tobits(challenge, buffer)) < 0) {
155 report(stderr, _("Could not decode initial BASE64 challenge\n"));
160 to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
162 if (outlevel >= O_MONITOR)
163 report(stdout, "IMAP> %s\n", buffer);
164 SockWrite(sock, buffer, strlen(buffer));
165 SockWrite(sock, "\r\n", 2);
167 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
170 if ((i = from64tobits(challenge, buffer)) < 0) {
171 report(stderr, _("Could not decode OTP challenge\n"));
175 rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
176 if ((rval == -2) && !run.poll_interval) {
177 char secret[OPIE_SECRET_MAX+1];
178 fprintf(stderr, _("Secret pass phrase: "));
179 if (opiereadpass(secret, sizeof(secret), 0))
180 rval = opiegenerator(challenge, secret, response);
181 memset(secret, 0, sizeof(secret));
187 to64frombits(buffer, response, strlen(response));
189 if (outlevel >= O_MONITOR)
190 report(stdout, "IMAP> %s\n", buffer);
191 SockWrite(sock, buffer, strlen(buffer));
192 SockWrite(sock, "\r\n", 2);
194 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
197 if (strstr(buffer, "OK"))
207 #elif SIZEOF_SHORT == 4
209 #elif SIZEOF_LONG == 4
212 #error Cannot deduce a 32-bit-type
215 static int do_rfc1731(int sock, char *truename)
216 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
219 char buf1[4096], buf2[4096];
223 } challenge1, challenge2;
224 char srvinst[INST_SZ];
226 char srvrealm[REALM_SZ];
227 KTEXT_ST authenticator;
228 CREDENTIALS credentials;
229 char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
230 char tktinst[INST_SZ];
231 char tktrealm[REALM_SZ];
233 des_key_schedule schedule;
235 gen_send(sock, "AUTHENTICATE KERBEROS_V4");
237 /* The data encoded in the first ready response contains a random
238 * 32-bit number in network byte order. The client should respond
239 * with a Kerberos ticket and an authenticator for the principal
240 * "imap.hostname@realm", where "hostname" is the first component
241 * of the host name of the server with all letters in lower case
242 * and where "realm" is the Kerberos realm of the server. The
243 * encrypted checksum field included within the Kerberos
244 * authenticator should contain the server provided 32-bit number
245 * in network byte order.
248 if (result = gen_recv(sock, buf1, sizeof buf1)) {
252 /* this patch by Dan Root <dar@thekeep.org> solves an endianess problem. */
256 *(int *)tmp = ntohl(*(int *) challenge1.cstr);
257 memcpy(challenge1.cstr, tmp, sizeof(tmp));
260 len = from64tobits(challenge1.cstr, buf1);
262 report(stderr, _("could not decode initial BASE64 challenge\n"));
266 /* Client responds with a Kerberos ticket and an authenticator for
267 * the principal "imap.hostname@realm" where "hostname" is the
268 * first component of the host name of the server with all letters
269 * in lower case and where "realm" is the Kerberos realm of the
270 * server. The encrypted checksum field included within the
271 * Kerberos authenticator should contain the server-provided
272 * 32-bit number in network byte order.
275 strncpy(srvinst, truename, (sizeof srvinst)-1);
276 srvinst[(sizeof srvinst)-1] = '\0';
277 for (p = srvinst; *p; p++) {
283 strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
284 srvrealm[(sizeof srvrealm)-1] = '\0';
285 if (p = strchr(srvinst, '.')) {
289 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
291 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
295 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
297 report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
301 memcpy(session, credentials.session, sizeof session);
302 memset(&credentials, 0, sizeof credentials);
303 des_key_sched(&session, schedule);
305 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
307 report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
311 if (strcmp(tktuser, user) != 0) {
313 _("principal %s in ticket does not match -u %s\n"), tktuser,
320 _("non-null instance (%s) might cause strange behavior\n"),
322 strcat(tktuser, ".");
323 strcat(tktuser, tktinst);
326 if (strcmp(tktrealm, srvrealm) != 0) {
327 strcat(tktuser, "@");
328 strcat(tktuser, tktrealm);
331 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
334 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
338 to64frombits(buf1, authenticator.dat, authenticator.length);
339 if (outlevel >= O_MONITOR) {
340 report(stdout, "IMAP> %s\n", buf1);
342 SockWrite(sock, buf1, strlen(buf1));
343 SockWrite(sock, "\r\n", 2);
345 /* Upon decrypting and verifying the ticket and authenticator, the
346 * server should verify that the contained checksum field equals
347 * the original server provided random 32-bit number. Should the
348 * verification be successful, the server must add one to the
349 * checksum and construct 8 octets of data, with the first four
350 * octets containing the incremented checksum in network byte
351 * order, the fifth octet containing a bit-mask specifying the
352 * protection mechanisms supported by the server, and the sixth
353 * through eighth octets containing, in network byte order, the
354 * maximum cipher-text buffer size the server is able to receive.
355 * The server must encrypt the 8 octets of data in the session key
356 * and issue that encrypted data in a second ready response. The
357 * client should consider the server authenticated if the first
358 * four octets the un-encrypted data is equal to one plus the
359 * checksum it previously sent.
362 if (result = gen_recv(sock, buf1, sizeof buf1))
365 /* The client must construct data with the first four octets
366 * containing the original server-issued checksum in network byte
367 * order, the fifth octet containing the bit-mask specifying the
368 * selected protection mechanism, the sixth through eighth octets
369 * containing in network byte order the maximum cipher-text buffer
370 * size the client is able to receive, and the following octets
371 * containing a user name string. The client must then append
372 * from one to eight octets so that the length of the data is a
373 * multiple of eight octets. The client must then PCBC encrypt the
374 * data with the session key and respond to the second ready
375 * response with the encrypted data. The server decrypts the data
376 * and verifies the contained checksum. The username field
377 * identifies the user for whom subsequent IMAP operations are to
378 * be performed; the server must verify that the principal
379 * identified in the Kerberos ticket is authorized to connect as
380 * that user. After these verifications, the authentication
381 * process is complete.
384 len = from64tobits(buf2, buf1);
386 report(stderr, _("could not decode BASE64 ready response\n"));
390 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
391 memcpy(challenge2.cstr, buf2, 4);
392 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
393 report(stderr, _("challenge mismatch\n"));
397 memset(authenticator.dat, 0, sizeof authenticator.dat);
399 result = htonl(challenge1.cint);
400 memcpy(authenticator.dat, &result, sizeof result);
402 /* The protection mechanisms and their corresponding bit-masks are as
405 * 1 No protection mechanism
406 * 2 Integrity (krb_mk_safe) protection
407 * 4 Privacy (krb_mk_priv) protection
409 authenticator.dat[4] = 1;
411 len = strlen(tktuser);
412 strncpy(authenticator.dat+8, tktuser, len);
413 authenticator.length = len + 8 + 1;
414 while (authenticator.length & 7) {
415 authenticator.length++;
417 des_pcbc_encrypt((des_cblock *)authenticator.dat,
418 (des_cblock *)authenticator.dat, authenticator.length, schedule,
421 to64frombits(buf1, authenticator.dat, authenticator.length);
422 if (outlevel >= O_MONITOR) {
423 report(stdout, "IMAP> %s\n", buf1);
425 SockWrite(sock, buf1, strlen(buf1));
426 SockWrite(sock, "\r\n", 2);
428 if (result = gen_recv(sock, buf1, sizeof buf1))
431 if (strstr(buf1, "OK")) {
438 #endif /* KERBEROS_V4 */
441 #define GSSAUTH_P_NONE 1
442 #define GSSAUTH_P_INTEGRITY 2
443 #define GSSAUTH_P_PRIVACY 4
445 static int do_gssauth(int sock, char *hostname, char *username)
447 gss_buffer_desc request_buf, send_token;
448 gss_buffer_t sec_token;
449 gss_name_t target_name;
450 gss_ctx_id_t context;
454 OM_uint32 maj_stat, min_stat;
455 char buf1[8192], buf2[8192], server_conf_flags;
456 unsigned long buf_size;
459 /* first things first: get an imap ticket for host */
460 sprintf(buf1, "imap@%s", hostname);
461 request_buf.value = buf1;
462 request_buf.length = strlen(buf1) + 1;
463 maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name,
465 if (maj_stat != GSS_S_COMPLETE) {
466 report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
469 else if (outlevel >= O_DEBUG) {
470 maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
472 report(stderr, _("Using service name [%s]\n"),request_buf.value);
473 maj_stat = gss_release_buffer(&min_stat, &request_buf);
476 gen_send(sock, "AUTHENTICATE GSSAPI");
478 /* upon receipt of the GSSAPI authentication request, server returns
479 * null data ready response. */
480 if (result = gen_recv(sock, buf1, sizeof buf1)) {
484 /* now start the security context initialisation loop... */
485 sec_token = GSS_C_NO_BUFFER;
486 context = GSS_C_NO_CONTEXT;
487 if (outlevel >= O_VERBOSE)
488 report(stdout, _("Sending credentials\n"));
490 maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL,
491 &context, target_name, NULL, 0, 0, NULL, sec_token, NULL,
492 &send_token, &cflags, NULL);
493 if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
494 report(stderr, _("Error exchanging credentials\n"));
495 gss_release_name(&min_stat, &target_name);
496 /* wake up server and await NO response */
497 SockWrite(sock, "\r\n", 2);
498 if (result = gen_recv(sock, buf1, sizeof buf1))
502 to64frombits(buf1, send_token.value, send_token.length);
503 gss_release_buffer(&min_stat, &send_token);
504 SockWrite(sock, buf1, strlen(buf1));
505 SockWrite(sock, "\r\n", 2);
506 if (outlevel >= O_MONITOR)
507 report(stdout, "IMAP> %s\n", buf1);
508 if (maj_stat == GSS_S_CONTINUE_NEEDED) {
509 if (result = gen_recv(sock, buf1, sizeof buf1)) {
510 gss_release_name(&min_stat, &target_name);
513 request_buf.length = from64tobits(buf2, buf1 + 2);
514 request_buf.value = buf2;
515 sec_token = &request_buf;
517 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
518 gss_release_name(&min_stat, &target_name);
520 /* get security flags and buffer size */
521 if (result = gen_recv(sock, buf1, sizeof buf1)) {
524 request_buf.length = from64tobits(buf2, buf1 + 2);
525 request_buf.value = buf2;
527 maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
529 if (maj_stat != GSS_S_COMPLETE) {
530 report(stderr, _("Couldn't unwrap security level data\n"));
531 gss_release_buffer(&min_stat, &send_token);
534 if (outlevel >= O_DEBUG)
535 report(stdout, _("Credential exchange complete\n"));
536 /* first octet is security levels supported. We want none, for now */
537 server_conf_flags = ((char *)send_token.value)[0];
538 if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
539 report(stderr, _("Server requires integrity and/or privacy\n"));
540 gss_release_buffer(&min_stat, &send_token);
543 ((char *)send_token.value)[0] = 0;
544 buf_size = ntohl(*((long *)send_token.value));
545 /* we don't care about buffer size if we don't wrap data */
546 gss_release_buffer(&min_stat, &send_token);
547 if (outlevel >= O_DEBUG) {
548 report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
549 server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
550 server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
551 server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
552 report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
555 /* now respond in kind (hack!!!) */
556 buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
557 memcpy(buf1, &buf_size, 4);
558 buf1[0] = GSSAUTH_P_NONE;
559 strcpy(buf1+4, username); /* server decides if princ is user */
560 request_buf.length = 4 + strlen(username) + 1;
561 request_buf.value = buf1;
562 maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
563 &cflags, &send_token);
564 if (maj_stat != GSS_S_COMPLETE) {
565 report(stderr, _("Error creating security level request\n"));
568 to64frombits(buf1, send_token.value, send_token.length);
569 if (outlevel >= O_DEBUG) {
570 report(stdout, _("Requesting authorisation as %s\n"), username);
571 report(stdout, "IMAP> %s\n",buf1);
573 SockWrite(sock, buf1, strlen(buf1));
574 SockWrite(sock, "\r\n", 2);
576 /* we should be done. Get status and finish up */
577 if (result = gen_recv(sock, buf1, sizeof buf1))
579 if (strstr(buf1, "OK")) {
580 /* flush security context */
581 if (outlevel >= O_DEBUG)
582 report(stdout, _("Releasing GSS credentials\n"));
583 maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
584 if (maj_stat != GSS_S_COMPLETE) {
585 report(stderr, _("Error releasing credentials\n"));
588 /* send_token may contain a notification to the server to flush
589 * credentials. RFC 1731 doesn't specify what to do, and since this
590 * support is only for authentication, we'll assume the server
591 * knows enough to flush its own credentials */
592 gss_release_buffer(&min_stat, &send_token);
600 static void hmac_md5 (unsigned char *password, size_t pass_len,
601 unsigned char *challenge, size_t chal_len,
602 unsigned char *response, size_t resp_len)
605 unsigned char ipad[64];
606 unsigned char opad[64];
607 unsigned char hash_passwd[16];
614 if (pass_len > sizeof (ipad))
617 MD5Update (&ctx, password, pass_len);
618 MD5Final (hash_passwd, &ctx);
619 password = hash_passwd; pass_len = sizeof (hash_passwd);
622 memset (ipad, 0, sizeof (ipad));
623 memset (opad, 0, sizeof (opad));
624 memcpy (ipad, password, pass_len);
625 memcpy (opad, password, pass_len);
627 for (i=0; i<64; i++) {
633 MD5Update (&ctx, ipad, sizeof (ipad));
634 MD5Update (&ctx, challenge, chal_len);
635 MD5Final (response, &ctx);
638 MD5Update (&ctx, opad, sizeof (opad));
639 MD5Update (&ctx, response, resp_len);
640 MD5Final (response, &ctx);
644 static int do_cram_md5 (int sock, struct query *ctl)
645 /* authenticate as per RFC2195 */
649 unsigned char buf1[1024];
650 unsigned char msg_id[768];
651 unsigned char response[16];
652 unsigned char reply[1024];
654 gen_send (sock, "AUTHENTICATE CRAM-MD5");
657 * The data encoded in the first ready response contains an
658 * presumptively arbitrary string of random digits, a timestamp, and the
659 * fully-qualified primary host name of the server. The syntax of the
660 * unencoded form must correspond to that of an RFC 822 'msg-id'
661 * [RFC822] as described in [POP3].
664 if (result = gen_recv (sock, buf1, sizeof (buf1))) {
668 len = from64tobits (msg_id, buf1);
670 report (stderr, _("could not decode BASE64 challenge\n"));
672 } else if (len < sizeof (msg_id)) {
675 msg_id[sizeof (msg_id)-1] = 0;
677 if (outlevel >= O_DEBUG) {
678 report (stdout, "decoded as %s\n", msg_id);
681 /* The client makes note of the data and then responds with a string
682 * consisting of the user name, a space, and a 'digest'. The latter is
683 * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where
684 * the key is a shared secret and the digested text is the timestamp
685 * (including angle-brackets).
688 hmac_md5 (ctl->password, strlen (ctl->password),
689 msg_id, strlen (msg_id),
690 response, sizeof (response));
693 snprintf (reply, sizeof (reply),
697 "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
699 response[0], response[1], response[2], response[3],
700 response[4], response[5], response[6], response[7],
701 response[8], response[9], response[10], response[11],
702 response[12], response[13], response[14], response[15]);
704 if (outlevel >= O_DEBUG) {
705 report (stdout, "replying with %s\n", reply);
708 to64frombits (buf1, reply, strlen (reply));
709 if (outlevel >= O_MONITOR) {
710 report (stdout, "IMAP> %s\n", buf1);
712 SockWrite (sock, buf1, strlen (buf1));
713 SockWrite (sock, "\r\n", 2);
715 if (result = gen_recv (sock, buf1, sizeof (buf1)))
718 if (strstr (buf1, "OK")) {
725 int imap_canonicalize(char *result, char *passwd)
726 /* encode an IMAP password as per RFC1730's quoting conventions */
731 for (i = 0; i < strlen(passwd); i++)
733 if ((passwd[i] == '\\') || (passwd[i] == '"'))
735 result[j++] = passwd[i];
742 int imap_getauth(int sock, struct query *ctl, char *greeting)
743 /* apply for connection authorization */
746 char password[PASSWORDLEN*2];
748 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
749 capabilities[0] = '\0';
750 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
752 /* UW-IMAP server 10.173 notifies in all caps */
753 if (strstr(capabilities, "IMAP4REV1"))
755 imap_version = IMAP4rev1;
756 if (outlevel >= O_DEBUG)
757 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
761 imap_version = IMAP4;
762 if (outlevel >= O_DEBUG)
763 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
766 else if (ok == PS_ERROR)
768 imap_version = IMAP2;
769 if (outlevel >= O_DEBUG)
770 report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
775 peek_capable = (imap_version >= IMAP4);
778 * Assumption: expunges are cheap, so we want to do them
779 * after every message unless user said otherwise.
781 if (NUM_SPECIFIED(ctl->expunge))
782 expunge_period = NUM_VALUE_OUT(ctl->expunge);
790 if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
792 if (outlevel >= O_DEBUG)
793 report(stdout, _("OTP authentication is supported\n"));
794 if (do_otp(sock, ctl) == PS_SUCCESS)
800 if (strstr(capabilities, "AUTH=GSSAPI"))
802 if (ctl->server.protocol == P_IMAP_GSS)
804 if (outlevel >= O_DEBUG)
805 report(stdout, _("GSS authentication is supported\n"));
806 return do_gssauth(sock, ctl->server.truename, ctl->remotename);
809 else if (ctl->server.protocol == P_IMAP_GSS)
812 _("Required GSS capability not supported by server\n"));
818 if (strstr(capabilities, "AUTH=KERBEROS_V4"))
820 if (outlevel >= O_DEBUG)
821 report(stdout, _("KERBEROS_V4 authentication is supported\n"));
823 if (ctl->server.protocol == P_IMAP_K4)
825 if ((ok = do_rfc1731(sock, ctl->server.truename)))
827 if (outlevel >= O_MONITOR)
828 report(stdout, "IMAP> *\n");
829 SockWrite(sock, "*\r\n", 3);
834 /* else fall through to ordinary AUTH=LOGIN case */
836 else if (ctl->server.protocol == P_IMAP_K4)
839 _("Required KERBEROS_V4 capability not supported by server\n"));
842 #endif /* KERBEROS_V4 */
844 if (strstr (capabilities, "AUTH=CRAM-MD5"))
846 if (outlevel >= O_DEBUG)
847 report (stdout, _("CRAM-MD5 authentication is supported\n"));
848 if ((ok = do_cram_md5 (sock, ctl)))
850 if (outlevel >= O_MONITOR)
851 report (stdout, "IMAP> *\n");
852 SockWrite (sock, "*\r\n", 3);
857 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
858 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
859 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
861 _("Required LOGIN capability not supported by server\n"));
864 #endif /* __UNUSED__ */
866 imap_canonicalize(password, ctl->password);
867 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
874 static int internal_expunge(int sock)
875 /* ship an expunge, resetting associated counters */
879 if ((ok = gen_transact(sock, "EXPUNGE")))
882 expunged += deletions;
885 #ifdef IMAP_UID /* not used */
887 #endif /* IMAP_UID */
892 static int imap_getrange(int sock,
895 int *countp, int *newp, int *bytes)
896 /* get range of messages to be fetched */
900 /* find out how many messages are waiting */
901 *bytes = recent = unseen = -1;
906 * We have to have an expunge here, otherwise the re-poll will
907 * infinite-loop picking up un-expunged messages -- unless the
908 * expunge period is one and we've been nuking each message
909 * just after deletion.
912 if (deletions && expunge_period != 1)
913 internal_expunge(sock);
915 if (ok || gen_transact(sock, "NOOP"))
917 report(stderr, _("re-poll failed\n"));
920 else if (count == -1) /* no EXISTS response to NOOP */
929 ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
931 ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
934 report(stderr, _("mailbox selection failed\n"));
942 * Note: because IMAP has an is_old method, this number is used
943 * only for the "X messages (Y unseen)" notification. Accordingly
944 * it doesn't matter much that it can be wrong (e.g. if we see an
945 * UNSEEN response but not all messages above the first UNSEEN one
948 if (unseen >= 0) /* optional, but better if we see it */
949 *newp = count - unseen + 1;
950 else if (recent >= 0) /* mandatory */
953 *newp = -1; /* should never happen, RECENT is mandatory */
960 static int imap_getsizes(int sock, int count, int *sizes)
961 /* capture the sizes of all messages */
963 char buf [MSGBUFSIZE+1];
966 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
967 * won't accept 1:1 as valid set syntax. Some implementors
968 * should be taken out and shot for excessive anality.
971 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
973 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
978 if ((ok = gen_recv(sock, buf, sizeof(buf))))
980 if (strstr(buf, "OK"))
982 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
983 sizes[num - 1] = size;
989 static int imap_is_old(int sock, struct query *ctl, int number)
990 /* is the given message old? */
994 /* expunges change the fetch numbers */
997 if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
1003 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1004 /* request headers of nth message */
1006 char buf [MSGBUFSIZE+1];
1009 /* expunges change the fetch numbers */
1013 * This is blessed by RFC 1176, RFC1730, RFC2060.
1014 * According to the RFCs, it should *not* set the \Seen flag.
1016 gen_send(sock, "FETCH %d RFC822.HEADER", number);
1018 /* looking for FETCH response */
1022 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1025 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
1033 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1034 /* request body of nth message */
1036 char buf [MSGBUFSIZE+1], *cp;
1039 /* expunges change the fetch numbers */
1043 * If we're using IMAP4, we can fetch the message without setting its
1044 * seen flag. This is good! It means that if the protocol exchange
1045 * craps out during the message, it will still be marked `unseen' on
1048 * However...*don't* do this if we're using keep to suppress deletion!
1049 * In that case, marking the seen flag is the only way to prevent the
1050 * message from being re-fetched on subsequent runs.
1052 switch (imap_version)
1054 case IMAP4rev1: /* RFC 2060 */
1056 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1058 gen_send(sock, "FETCH %d BODY[TEXT]", number);
1061 case IMAP4: /* RFC 1730 */
1063 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1065 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1068 default: /* RFC 1176 */
1069 gen_send(sock, "FETCH %d RFC822.TEXT", number);
1073 /* looking for FETCH response */
1077 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1080 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1085 /* try to extract a length */
1086 if ((cp = strchr(buf, '{')))
1087 *lenp = atoi(cp + 1);
1094 static int imap_trail(int sock, struct query *ctl, int number)
1095 /* discard tail of FETCH response after reading message text */
1097 /* expunges change the fetch numbers */
1098 /* number -= expunged; */
1102 char buf[MSGBUFSIZE+1];
1105 if ((ok = gen_recv(sock, buf, sizeof(buf))))
1108 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1109 if (strstr(buf, "OK"))
1116 static int imap_delete(int sock, struct query *ctl, int number)
1117 /* set delete flag for given message */
1121 /* expunges change the fetch numbers */
1125 * Use SILENT if possible as a minor throughput optimization.
1126 * Note: this has been dropped from IMAP4rev1.
1128 * We set Seen because there are some IMAP servers (notably HP
1129 * OpenMail) that do message-receipt DSNs, but only when the seen
1130 * bit is set. This is the appropriate time -- we get here right
1131 * after the local SMTP response that says delivery was
1134 if ((ok = gen_transact(sock,
1135 imap_version == IMAP4
1136 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1137 : "STORE %d +FLAGS (\\Seen \\Deleted)",
1144 * We do an expunge after expunge_period messages, rather than
1145 * just before quit, so that a line hit during a long session
1146 * won't result in lots of messages being fetched again during
1149 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1150 internal_expunge(sock);
1155 static int imap_logout(int sock, struct query *ctl)
1156 /* send logout command */
1158 /* if expunges after deletion have been suppressed, ship one now */
1159 if (NUM_SPECIFIED(expunge_period) && NUM_ZERO(expunge_period) && deletions)
1160 internal_expunge(sock);
1162 return(gen_transact(sock, "LOGOUT"));
1165 const static struct method imap =
1167 "IMAP", /* Internet Message Access Protocol */
1171 143, /* standard IMAP2bis/IMAP4 port */
1173 TRUE, /* this is a tagged protocol */
1174 FALSE, /* no message delimiter */
1175 imap_ok, /* parse command response */
1176 imap_canonicalize, /* deal with embedded slashes and spaces */
1177 imap_getauth, /* get authorization */
1178 imap_getrange, /* query range of messages */
1179 imap_getsizes, /* get sizes of messages (used for --limit option */
1180 imap_is_old, /* no UID check */
1181 imap_fetch_headers, /* request given message headers */
1182 imap_fetch_body, /* request given message body */
1183 imap_trail, /* eat message trailer */
1184 imap_delete, /* delete the message */
1185 imap_logout, /* expunge and exit */
1186 TRUE, /* yes, we can re-poll */
1189 int doIMAP(struct query *ctl)
1190 /* retrieve messages using IMAP Version 2bis or Version 4 */
1192 return(do_protocol(ctl, &imap));
1195 /* imap.c ends here */