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>
44 #ifndef strstr /* glibc-2.1 declares this as a macro */
45 extern char *strstr(); /* needed on sysV68 R3V7.1. */
48 /* imap_version values */
49 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
50 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
51 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
53 static int count, seen, recent, unseen, deletions, imap_version;
54 static int expunged, expunge_period;
55 static char capabilities[MSGBUFSIZE+1];
57 int imap_ok(int sock, char *argbuf)
58 /* parse command response */
60 char buf [MSGBUFSIZE+1];
67 if ((ok = gen_recv(sock, buf, sizeof(buf))))
70 /* all tokens in responses are caseblind */
71 for (cp = buf; *cp; cp++)
75 /* interpret untagged status responses */
76 if (strstr(buf, "* CAPABILITY"))
77 strncpy(capabilities, buf + 12, sizeof(capabilities));
78 if (strstr(buf, "EXISTS"))
80 if (strstr(buf, "RECENT"))
82 if (strstr(buf, "UNSEEN"))
87 * Handle both "* 42 UNSEEN" (if tha ever happens) and
88 * "* OK [UNSEEN 42] 42". Note that what this gets us is
89 * a minimum index, not a count.
92 for (cp = buf; *cp && !isdigit(*cp); cp++)
96 if (strstr(buf, "FLAGS"))
97 seen = (strstr(buf, "SEEN") != (char *)NULL);
99 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
112 for (cp = buf; !isspace(*cp); cp++)
117 if (strncmp(cp, "OK", 2) == 0)
123 else if (strncmp(cp, "BAD", 3) == 0)
125 else if (strncmp(cp, "NO", 2) == 0)
133 static int do_otp(int sock, struct query *ctl)
137 char challenge[OPIE_CHALLENGE_MAX+1];
138 char response[OPIE_RESPONSE_MAX+1];
140 gen_send(sock, "AUTHENTICATE X-OTP");
142 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
145 if ((i = from64tobits(challenge, buffer)) < 0) {
146 report(stderr, _("Could not decode initial BASE64 challenge\n"));
151 to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
153 if (outlevel >= O_MONITOR)
154 report(stdout, "IMAP> %s\n", buffer);
155 SockWrite(sock, buffer, strlen(buffer));
156 SockWrite(sock, "\r\n", 2);
158 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
161 if ((i = from64tobits(challenge, buffer)) < 0) {
162 report(stderr, _("Could not decode OTP challenge\n"));
166 rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
167 if ((rval == -2) && !run.poll_interval) {
168 char secret[OPIE_SECRET_MAX+1];
169 fprintf(stderr, _("Secret pass phrase: "));
170 if (opiereadpass(secret, sizeof(secret), 0))
171 rval = opiegenerator(challenge, secret, response);
172 memset(secret, 0, sizeof(secret));
178 to64frombits(buffer, response, strlen(response));
180 if (outlevel >= O_MONITOR)
181 report(stdout, "IMAP> %s\n", buffer);
182 SockWrite(sock, buffer, strlen(buffer));
183 SockWrite(sock, "\r\n", 2);
185 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
188 if (strstr(buffer, "OK"))
198 #elif SIZEOF_SHORT == 4
200 #elif SIZEOF_LONG == 4
203 #error Cannot deduce a 32-bit-type
206 static int do_rfc1731(int sock, char *truename)
207 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
210 char buf1[4096], buf2[4096];
214 } challenge1, challenge2;
215 char srvinst[INST_SZ];
217 char srvrealm[REALM_SZ];
218 KTEXT_ST authenticator;
219 CREDENTIALS credentials;
220 char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
221 char tktinst[INST_SZ];
222 char tktrealm[REALM_SZ];
224 des_key_schedule schedule;
226 gen_send(sock, "AUTHENTICATE KERBEROS_V4");
228 /* The data encoded in the first ready response contains a random
229 * 32-bit number in network byte order. The client should respond
230 * with a Kerberos ticket and an authenticator for the principal
231 * "imap.hostname@realm", where "hostname" is the first component
232 * of the host name of the server with all letters in lower case
233 * and where "realm" is the Kerberos realm of the server. The
234 * encrypted checksum field included within the Kerberos
235 * authenticator should contain the server provided 32-bit number
236 * in network byte order.
239 if (result = gen_recv(sock, buf1, sizeof buf1)) {
243 /* this patch by Dan Root <dar@thekeep.org> solves an endianess problem. */
247 *(int *)tmp = ntohl(*(int *) challenge1.cstr);
248 memcpy(challenge1.cstr, tmp, sizeof(tmp));
251 len = from64tobits(challenge1.cstr, buf1);
253 report(stderr, _("could not decode initial BASE64 challenge\n"));
257 /* Client responds with a Kerberos ticket and an authenticator for
258 * the principal "imap.hostname@realm" where "hostname" is the
259 * first component of the host name of the server with all letters
260 * in lower case and where "realm" is the Kerberos realm of the
261 * server. The encrypted checksum field included within the
262 * Kerberos authenticator should contain the server-provided
263 * 32-bit number in network byte order.
266 strncpy(srvinst, truename, (sizeof srvinst)-1);
267 srvinst[(sizeof srvinst)-1] = '\0';
268 for (p = srvinst; *p; p++) {
274 strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
275 srvrealm[(sizeof srvrealm)-1] = '\0';
276 if (p = strchr(srvinst, '.')) {
280 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
282 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
286 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
288 report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
292 memcpy(session, credentials.session, sizeof session);
293 memset(&credentials, 0, sizeof credentials);
294 des_key_sched(session, schedule);
296 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
298 report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
302 if (strcmp(tktuser, user) != 0) {
304 _("principal %s in ticket does not match -u %s\n"), tktuser,
311 _("non-null instance (%s) might cause strange behavior\n"),
313 strcat(tktuser, ".");
314 strcat(tktuser, tktinst);
317 if (strcmp(tktrealm, srvrealm) != 0) {
318 strcat(tktuser, "@");
319 strcat(tktuser, tktrealm);
322 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
325 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
329 to64frombits(buf1, authenticator.dat, authenticator.length);
330 if (outlevel >= O_MONITOR) {
331 report(stdout, "IMAP> %s\n", buf1);
333 SockWrite(sock, buf1, strlen(buf1));
334 SockWrite(sock, "\r\n", 2);
336 /* Upon decrypting and verifying the ticket and authenticator, the
337 * server should verify that the contained checksum field equals
338 * the original server provided random 32-bit number. Should the
339 * verification be successful, the server must add one to the
340 * checksum and construct 8 octets of data, with the first four
341 * octets containing the incremented checksum in network byte
342 * order, the fifth octet containing a bit-mask specifying the
343 * protection mechanisms supported by the server, and the sixth
344 * through eighth octets containing, in network byte order, the
345 * maximum cipher-text buffer size the server is able to receive.
346 * The server must encrypt the 8 octets of data in the session key
347 * and issue that encrypted data in a second ready response. The
348 * client should consider the server authenticated if the first
349 * four octets the un-encrypted data is equal to one plus the
350 * checksum it previously sent.
353 if (result = gen_recv(sock, buf1, sizeof buf1))
356 /* The client must construct data with the first four octets
357 * containing the original server-issued checksum in network byte
358 * order, the fifth octet containing the bit-mask specifying the
359 * selected protection mechanism, the sixth through eighth octets
360 * containing in network byte order the maximum cipher-text buffer
361 * size the client is able to receive, and the following octets
362 * containing a user name string. The client must then append
363 * from one to eight octets so that the length of the data is a
364 * multiple of eight octets. The client must then PCBC encrypt the
365 * data with the session key and respond to the second ready
366 * response with the encrypted data. The server decrypts the data
367 * and verifies the contained checksum. The username field
368 * identifies the user for whom subsequent IMAP operations are to
369 * be performed; the server must verify that the principal
370 * identified in the Kerberos ticket is authorized to connect as
371 * that user. After these verifications, the authentication
372 * process is complete.
375 len = from64tobits(buf2, buf1);
377 report(stderr, _("could not decode BASE64 ready response\n"));
381 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
382 memcpy(challenge2.cstr, buf2, 4);
383 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
384 report(stderr, _("challenge mismatch\n"));
388 memset(authenticator.dat, 0, sizeof authenticator.dat);
390 result = htonl(challenge1.cint);
391 memcpy(authenticator.dat, &result, sizeof result);
393 /* The protection mechanisms and their corresponding bit-masks are as
396 * 1 No protection mechanism
397 * 2 Integrity (krb_mk_safe) protection
398 * 4 Privacy (krb_mk_priv) protection
400 authenticator.dat[4] = 1;
402 len = strlen(tktuser);
403 strncpy(authenticator.dat+8, tktuser, len);
404 authenticator.length = len + 8 + 1;
405 while (authenticator.length & 7) {
406 authenticator.length++;
408 des_pcbc_encrypt((des_cblock *)authenticator.dat,
409 (des_cblock *)authenticator.dat, authenticator.length, schedule,
412 to64frombits(buf1, authenticator.dat, authenticator.length);
413 if (outlevel >= O_MONITOR) {
414 report(stdout, "IMAP> %s\n", buf1);
416 SockWrite(sock, buf1, strlen(buf1));
417 SockWrite(sock, "\r\n", 2);
419 if (result = gen_recv(sock, buf1, sizeof buf1))
422 if (strstr(buf1, "OK")) {
429 #endif /* KERBEROS_V4 */
432 #define GSSAUTH_P_NONE 1
433 #define GSSAUTH_P_INTEGRITY 2
434 #define GSSAUTH_P_PRIVACY 4
436 static int do_gssauth(int sock, char *hostname, char *username)
438 gss_buffer_desc request_buf, send_token;
439 gss_buffer_t sec_token;
440 gss_name_t target_name;
441 gss_ctx_id_t context;
445 OM_uint32 maj_stat, min_stat;
446 char buf1[8192], buf2[8192], server_conf_flags;
447 unsigned long buf_size;
450 /* first things first: get an imap ticket for host */
451 sprintf(buf1, "imap@%s", hostname);
452 request_buf.value = buf1;
453 request_buf.length = strlen(buf1) + 1;
454 maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name,
456 if (maj_stat != GSS_S_COMPLETE) {
457 report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
460 else if (outlevel >= O_DEBUG) {
461 maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
463 report(stderr, _("Using service name [%s]\n"),request_buf.value);
464 maj_stat = gss_release_buffer(&min_stat, &request_buf);
467 gen_send(sock, "AUTHENTICATE GSSAPI");
469 /* upon receipt of the GSSAPI authentication request, server returns
470 * null data ready response. */
471 if (result = gen_recv(sock, buf1, sizeof buf1)) {
475 /* now start the security context initialisation loop... */
476 sec_token = GSS_C_NO_BUFFER;
477 context = GSS_C_NO_CONTEXT;
478 if (outlevel >= O_VERBOSE)
479 report(stdout, _("Sending credentials\n"));
481 maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL,
482 &context, target_name, NULL, 0, 0, NULL, sec_token, NULL,
483 &send_token, &cflags, NULL);
484 if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
485 report(stderr, _("Error exchanging credentials\n"));
486 gss_release_name(&min_stat, &target_name);
487 /* wake up server and await NO response */
488 SockWrite(sock, "\r\n", 2);
489 if (result = gen_recv(sock, buf1, sizeof buf1))
493 to64frombits(buf1, send_token.value, send_token.length);
494 gss_release_buffer(&min_stat, &send_token);
495 SockWrite(sock, buf1, strlen(buf1));
496 SockWrite(sock, "\r\n", 2);
497 if (outlevel >= O_MONITOR)
498 report(stdout, "IMAP> %s\n", buf1);
499 if (maj_stat == GSS_S_CONTINUE_NEEDED) {
500 if (result = gen_recv(sock, buf1, sizeof buf1)) {
501 gss_release_name(&min_stat, &target_name);
504 request_buf.length = from64tobits(buf2, buf1 + 2);
505 request_buf.value = buf2;
506 sec_token = &request_buf;
508 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
509 gss_release_name(&min_stat, &target_name);
511 /* get security flags and buffer size */
512 if (result = gen_recv(sock, buf1, sizeof buf1)) {
515 request_buf.length = from64tobits(buf2, buf1 + 2);
516 request_buf.value = buf2;
518 maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
520 if (maj_stat != GSS_S_COMPLETE) {
521 report(stderr, _("Couldn't unwrap security level data\n"));
522 gss_release_buffer(&min_stat, &send_token);
525 if (outlevel >= O_DEBUG)
526 report(stdout, _("Credential exchange complete\n"));
527 /* first octet is security levels supported. We want none, for now */
528 server_conf_flags = ((char *)send_token.value)[0];
529 if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
530 report(stderr, _("Server requires integrity and/or privacy\n"));
531 gss_release_buffer(&min_stat, &send_token);
534 ((char *)send_token.value)[0] = 0;
535 buf_size = ntohl(*((long *)send_token.value));
536 /* we don't care about buffer size if we don't wrap data */
537 gss_release_buffer(&min_stat, &send_token);
538 if (outlevel >= O_DEBUG) {
539 report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
540 server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
541 server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
542 server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
543 report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
546 /* now respond in kind (hack!!!) */
547 buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
548 memcpy(buf1, &buf_size, 4);
549 buf1[0] = GSSAUTH_P_NONE;
550 strcpy(buf1+4, username); /* server decides if princ is user */
551 request_buf.length = 4 + strlen(username) + 1;
552 request_buf.value = buf1;
553 maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
554 &cflags, &send_token);
555 if (maj_stat != GSS_S_COMPLETE) {
556 report(stderr, _("Error creating security level request\n"));
559 to64frombits(buf1, send_token.value, send_token.length);
560 if (outlevel >= O_DEBUG) {
561 report(stdout, _("Requesting authorisation as %s\n"), username);
562 report(stdout, "IMAP> %s\n",buf1);
564 SockWrite(sock, buf1, strlen(buf1));
565 SockWrite(sock, "\r\n", 2);
567 /* we should be done. Get status and finish up */
568 if (result = gen_recv(sock, buf1, sizeof buf1))
570 if (strstr(buf1, "OK")) {
571 /* flush security context */
572 if (outlevel >= O_DEBUG)
573 report(stdout, _("Releasing GSS credentials\n"));
574 maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
575 if (maj_stat != GSS_S_COMPLETE) {
576 report(stderr, _("Error releasing credentials\n"));
579 /* send_token may contain a notification to the server to flush
580 * credentials. RFC 1731 doesn't specify what to do, and since this
581 * support is only for authentication, we'll assume the server
582 * knows enough to flush its own credentials */
583 gss_release_buffer(&min_stat, &send_token);
591 int imap_canonicalize(char *result, char *passwd)
592 /* encode an IMAP password as per RFC1730's quoting conventions */
597 for (i = 0; i < strlen(passwd); i++)
599 if ((passwd[i] == '\\') || (passwd[i] == '"'))
601 result[j++] = passwd[i];
608 int imap_getauth(int sock, struct query *ctl, char *greeting)
609 /* apply for connection authorization */
612 char password[PASSWORDLEN*2];
614 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
615 capabilities[0] = '\0';
616 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
618 /* UW-IMAP server 10.173 notifies in all caps */
619 if (strstr(capabilities, "IMAP4REV1"))
621 imap_version = IMAP4rev1;
622 if (outlevel >= O_DEBUG)
623 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
627 imap_version = IMAP4;
628 if (outlevel >= O_DEBUG)
629 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
632 else if (ok == PS_ERROR)
634 imap_version = IMAP2;
635 if (outlevel >= O_DEBUG)
636 report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
641 peek_capable = (imap_version >= IMAP4);
644 if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
646 if (outlevel >= O_DEBUG)
647 report(stdout, _("OTP authentication is supported\n"));
648 if (do_otp(sock, ctl) == PS_SUCCESS)
654 if (strstr(capabilities, "AUTH=GSSAPI"))
656 if (ctl->server.protocol == P_IMAP_GSS)
658 if (outlevel >= O_DEBUG)
659 report(stdout, _("GSS authentication is supported\n"));
660 return do_gssauth(sock, ctl->server.truename, ctl->remotename);
663 else if (ctl->server.protocol == P_IMAP_GSS)
666 _("Required GSS capability not supported by server\n"));
672 if (strstr(capabilities, "AUTH=KERBEROS_V4"))
674 if (outlevel >= O_DEBUG)
675 report(stdout, _("KERBEROS_V4 authentication is supported\n"));
677 if (ctl->server.protocol == P_IMAP_K4)
679 if ((ok = do_rfc1731(sock, ctl->server.truename)))
681 if (outlevel >= O_MONITOR)
682 report(stdout, "IMAP> *\n");
683 SockWrite(sock, "*\r\n", 3);
688 /* else fall through to ordinary AUTH=LOGIN case */
690 else if (ctl->server.protocol == P_IMAP_K4)
693 _("Required KERBEROS_V4 capability not supported by server\n"));
696 #endif /* KERBEROS_V4 */
698 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
699 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
700 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
702 _("Required LOGIN capability not supported by server\n"));
705 #endif /* __UNUSED__ */
707 imap_canonicalize(password, ctl->password);
708 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
713 * Assumption: expunges are cheap, so we want to do them
714 * after every message unless user said otherwise.
716 if (NUM_SPECIFIED(ctl->expunge))
717 expunge_period = NUM_VALUE_OUT(ctl->expunge);
724 static int internal_expunge(int sock)
725 /* ship an expunge, resetting associated counters */
729 if ((ok = gen_transact(sock, "EXPUNGE")))
732 expunged += deletions;
735 #ifdef IMAP_UID /* not used */
737 #endif /* IMAP_UID */
742 static int imap_getrange(int sock,
745 int *countp, int *newp, int *bytes)
746 /* get range of messages to be fetched */
750 /* find out how many messages are waiting */
751 *bytes = recent = unseen = -1;
756 * We have to have an expunge here, otherwise the re-poll will
757 * infinite-loop picking up un-expunged messages.
760 if (deletions && expunge_period > 1)
761 internal_expunge(sock);
763 if (ok || gen_transact(sock, "NOOP"))
765 report(stderr, _("re-poll failed\n"));
768 else if (count == -1) /* no EXISTS response to NOOP */
777 ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
779 ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
782 report(stderr, _("mailbox selection failed\n"));
790 * Note: because IMAP has an is_old method, this number is used
791 * only for the "X messages (Y unseen)" notification. Accordingly
792 * it doesn't matter much that it can be wrong (e.g. if we see an
793 * UNSEEN response but not all messages above the first UNSEEN one
796 if (unseen >= 0) /* optional, but better if we see it */
797 *newp = count - unseen + 1;
798 else if (recent >= 0) /* mandatory */
801 *newp = -1; /* should never happen, RECENT is mandatory */
808 static int imap_getsizes(int sock, int count, int *sizes)
809 /* capture the sizes of all messages */
811 char buf [MSGBUFSIZE+1];
814 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
815 * won't accept 1:1 as valid set syntax. Some implementors
816 * should be taken out and shot for excessive anality.
819 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
821 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
826 if ((ok = gen_recv(sock, buf, sizeof(buf))))
828 if (strstr(buf, "OK"))
830 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
831 sizes[num - 1] = size;
837 static int imap_is_old(int sock, struct query *ctl, int number)
838 /* is the given message old? */
842 /* expunges change the fetch numbers */
845 if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
851 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
852 /* request headers of nth message */
854 char buf [MSGBUFSIZE+1];
857 /* expunges change the fetch numbers */
861 * This is blessed by RFC 1176, RFC1730, RFC2060.
862 * According to the RFCs, it should *not* set the \Seen flag.
864 gen_send(sock, "FETCH %d RFC822.HEADER", number);
866 /* looking for FETCH response */
870 if ((ok = gen_recv(sock, buf, sizeof(buf))))
873 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
881 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
882 /* request body of nth message */
884 char buf [MSGBUFSIZE+1], *cp;
887 /* expunges change the fetch numbers */
891 * If we're using IMAP4, we can fetch the message without setting its
892 * seen flag. This is good! It means that if the protocol exchange
893 * craps out during the message, it will still be marked `unseen' on
896 * However...*don't* do this if we're using keep to suppress deletion!
897 * In that case, marking the seen flag is the only way to prevent the
898 * message from being re-fetched on subsequent runs.
900 switch (imap_version)
902 case IMAP4rev1: /* RFC 2060 */
904 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
906 gen_send(sock, "FETCH %d BODY[TEXT]", number);
909 case IMAP4: /* RFC 1730 */
911 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
913 gen_send(sock, "FETCH %d RFC822.TEXT", number);
916 default: /* RFC 1176 */
917 gen_send(sock, "FETCH %d RFC822.TEXT", number);
921 /* looking for FETCH response */
925 if ((ok = gen_recv(sock, buf, sizeof(buf))))
928 (sscanf(buf+2, "%d FETCH", &num) != 1);
933 /* try to extract a length */
934 if ((cp = strchr(buf, '{')))
935 *lenp = atoi(cp + 1);
942 static int imap_trail(int sock, struct query *ctl, int number)
943 /* discard tail of FETCH response after reading message text */
945 /* expunges change the fetch numbers */
946 /* number -= expunged; */
950 char buf[MSGBUFSIZE+1];
953 if ((ok = gen_recv(sock, buf, sizeof(buf))))
956 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
957 if (strstr(buf, "OK"))
964 static int imap_delete(int sock, struct query *ctl, int number)
965 /* set delete flag for given message */
969 /* expunges change the fetch numbers */
973 * Use SILENT if possible as a minor throughput optimization.
974 * Note: this has been dropped from IMAP4rev1.
976 * We set Seen because there are some IMAP servers (notably HP
977 * OpenMail) that do message-receipt DSNs, but only when the seen
978 * bit is set. This is the appropriate time -- we get here right
979 * after the local SMTP response that says delivery was
982 if ((ok = gen_transact(sock,
983 imap_version == IMAP4
984 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
985 : "STORE %d +FLAGS (\\Seen \\Deleted)",
992 * We do an expunge after expunge_period messages, rather than
993 * just before quit, so that a line hit during a long session
994 * won't result in lots of messages being fetched again during
997 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
998 internal_expunge(sock);
1003 static int imap_logout(int sock, struct query *ctl)
1004 /* send logout command */
1006 /* if expunges after deletion have been suppressed, ship one now */
1007 if (NUM_SPECIFIED(expunge_period) && NUM_ZERO(expunge_period) && deletions)
1008 internal_expunge(sock);
1010 return(gen_transact(sock, "LOGOUT"));
1013 const static struct method imap =
1015 "IMAP", /* Internet Message Access Protocol */
1019 143, /* standard IMAP2bis/IMAP4 port */
1021 TRUE, /* this is a tagged protocol */
1022 FALSE, /* no message delimiter */
1023 imap_ok, /* parse command response */
1024 imap_canonicalize, /* deal with embedded slashes and spaces */
1025 imap_getauth, /* get authorization */
1026 imap_getrange, /* query range of messages */
1027 imap_getsizes, /* get sizes of messages (used for --limit option */
1028 imap_is_old, /* no UID check */
1029 imap_fetch_headers, /* request given message headers */
1030 imap_fetch_body, /* request given message body */
1031 imap_trail, /* eat message trailer */
1032 imap_delete, /* delete the message */
1033 imap_logout, /* expunge and exit */
1034 TRUE, /* yes, we can re-poll */
1037 int doIMAP(struct query *ctl)
1038 /* retrieve messages using IMAP Version 2bis or Version 4 */
1040 return(do_protocol(ctl, &imap));
1043 /* imap.c ends here */