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, expunged, imap_version;
54 static char capabilities[MSGBUFSIZE+1];
56 int imap_ok(int sock, char *argbuf)
57 /* parse command response */
59 char buf [MSGBUFSIZE+1];
66 if ((ok = gen_recv(sock, buf, sizeof(buf))))
69 /* all tokens in responses are caseblind */
70 for (cp = buf; *cp; cp++)
74 /* interpret untagged status responses */
75 if (strstr(buf, "* CAPABILITY"))
76 strncpy(capabilities, buf + 12, sizeof(capabilities));
77 if (strstr(buf, "EXISTS"))
79 if (strstr(buf, "RECENT"))
81 if (strstr(buf, "UNSEEN"))
86 * Handle both "* 42 UNSEEN" (if tha ever happens) and
87 * "* OK [UNSEEN 42] 42". Note that what this gets us is
88 * a minimum index, not a count.
91 for (cp = buf; *cp && !isdigit(*cp); cp++)
95 if (strstr(buf, "FLAGS"))
96 seen = (strstr(buf, "SEEN") != (char *)NULL);
98 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
111 for (cp = buf; !isspace(*cp); cp++)
116 if (strncmp(cp, "OK", 2) == 0)
122 else if (strncmp(cp, "BAD", 3) == 0)
124 else if (strncmp(cp, "NO", 2) == 0)
132 static int do_otp(int sock, struct query *ctl)
136 char challenge[OPIE_CHALLENGE_MAX+1];
137 char response[OPIE_RESPONSE_MAX+1];
139 gen_send(sock, "AUTHENTICATE X-OTP");
141 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
144 if ((i = from64tobits(challenge, buffer)) < 0) {
145 report(stderr, _("Could not decode initial BASE64 challenge\n"));
150 to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
152 if (outlevel >= O_MONITOR)
153 report(stdout, "IMAP> %s\n", buffer);
154 SockWrite(sock, buffer, strlen(buffer));
155 SockWrite(sock, "\r\n", 2);
157 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
160 if ((i = from64tobits(challenge, buffer)) < 0) {
161 report(stderr, _("Could not decode OTP challenge\n"));
165 rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
166 if ((rval == -2) && !run.poll_interval) {
167 char secret[OPIE_SECRET_MAX+1];
168 fprintf(stderr, _("Secret pass phrase: "));
169 if (opiereadpass(secret, sizeof(secret), 0))
170 rval = opiegenerator(challenge, secret, response);
171 memset(secret, 0, sizeof(secret));
177 to64frombits(buffer, response, strlen(response));
179 if (outlevel >= O_MONITOR)
180 report(stdout, "IMAP> %s\n", buffer);
181 SockWrite(sock, buffer, strlen(buffer));
182 SockWrite(sock, "\r\n", 2);
184 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
187 if (strstr(buffer, "OK"))
197 #elif SIZEOF_SHORT == 4
199 #elif SIZEOF_LONG == 4
202 #error Cannot deduce a 32-bit-type
205 static int do_rfc1731(int sock, char *truename)
206 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
209 char buf1[4096], buf2[4096];
213 } challenge1, challenge2;
214 char srvinst[INST_SZ];
216 char srvrealm[REALM_SZ];
217 KTEXT_ST authenticator;
218 CREDENTIALS credentials;
219 char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
220 char tktinst[INST_SZ];
221 char tktrealm[REALM_SZ];
223 des_key_schedule schedule;
225 gen_send(sock, "AUTHENTICATE KERBEROS_V4");
227 /* The data encoded in the first ready response contains a random
228 * 32-bit number in network byte order. The client should respond
229 * with a Kerberos ticket and an authenticator for the principal
230 * "imap.hostname@realm", where "hostname" is the first component
231 * of the host name of the server with all letters in lower case
232 * and where "realm" is the Kerberos realm of the server. The
233 * encrypted checksum field included within the Kerberos
234 * authenticator should contain the server provided 32-bit number
235 * in network byte order.
238 if (result = gen_recv(sock, buf1, sizeof buf1)) {
242 /* this patch by Dan Root <dar@thekeep.org> solves an endianess problem. */
246 *(int *)tmp = ntohl(*(int *) challenge1.cstr);
247 memcpy(challenge1.cstr, tmp, sizeof(tmp));
250 len = from64tobits(challenge1.cstr, buf1);
252 report(stderr, _("could not decode initial BASE64 challenge\n"));
256 /* Client responds with a Kerberos ticket and an authenticator for
257 * the principal "imap.hostname@realm" where "hostname" is the
258 * first component of the host name of the server with all letters
259 * in lower case and where "realm" is the Kerberos realm of the
260 * server. The encrypted checksum field included within the
261 * Kerberos authenticator should contain the server-provided
262 * 32-bit number in network byte order.
265 strncpy(srvinst, truename, (sizeof srvinst)-1);
266 srvinst[(sizeof srvinst)-1] = '\0';
267 for (p = srvinst; *p; p++) {
273 strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
274 srvrealm[(sizeof srvrealm)-1] = '\0';
275 if (p = strchr(srvinst, '.')) {
279 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
281 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
285 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
287 report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
291 memcpy(session, credentials.session, sizeof session);
292 memset(&credentials, 0, sizeof credentials);
293 des_key_sched(session, schedule);
295 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
297 report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
301 if (strcmp(tktuser, user) != 0) {
303 _("principal %s in ticket does not match -u %s\n"), tktuser,
310 _("non-null instance (%s) might cause strange behavior\n"),
312 strcat(tktuser, ".");
313 strcat(tktuser, tktinst);
316 if (strcmp(tktrealm, srvrealm) != 0) {
317 strcat(tktuser, "@");
318 strcat(tktuser, tktrealm);
321 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
324 report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
328 to64frombits(buf1, authenticator.dat, authenticator.length);
329 if (outlevel >= O_MONITOR) {
330 report(stdout, "IMAP> %s\n", buf1);
332 SockWrite(sock, buf1, strlen(buf1));
333 SockWrite(sock, "\r\n", 2);
335 /* Upon decrypting and verifying the ticket and authenticator, the
336 * server should verify that the contained checksum field equals
337 * the original server provided random 32-bit number. Should the
338 * verification be successful, the server must add one to the
339 * checksum and construct 8 octets of data, with the first four
340 * octets containing the incremented checksum in network byte
341 * order, the fifth octet containing a bit-mask specifying the
342 * protection mechanisms supported by the server, and the sixth
343 * through eighth octets containing, in network byte order, the
344 * maximum cipher-text buffer size the server is able to receive.
345 * The server must encrypt the 8 octets of data in the session key
346 * and issue that encrypted data in a second ready response. The
347 * client should consider the server authenticated if the first
348 * four octets the un-encrypted data is equal to one plus the
349 * checksum it previously sent.
352 if (result = gen_recv(sock, buf1, sizeof buf1))
355 /* The client must construct data with the first four octets
356 * containing the original server-issued checksum in network byte
357 * order, the fifth octet containing the bit-mask specifying the
358 * selected protection mechanism, the sixth through eighth octets
359 * containing in network byte order the maximum cipher-text buffer
360 * size the client is able to receive, and the following octets
361 * containing a user name string. The client must then append
362 * from one to eight octets so that the length of the data is a
363 * multiple of eight octets. The client must then PCBC encrypt the
364 * data with the session key and respond to the second ready
365 * response with the encrypted data. The server decrypts the data
366 * and verifies the contained checksum. The username field
367 * identifies the user for whom subsequent IMAP operations are to
368 * be performed; the server must verify that the principal
369 * identified in the Kerberos ticket is authorized to connect as
370 * that user. After these verifications, the authentication
371 * process is complete.
374 len = from64tobits(buf2, buf1);
376 report(stderr, _("could not decode BASE64 ready response\n"));
380 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
381 memcpy(challenge2.cstr, buf2, 4);
382 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
383 report(stderr, _("challenge mismatch\n"));
387 memset(authenticator.dat, 0, sizeof authenticator.dat);
389 result = htonl(challenge1.cint);
390 memcpy(authenticator.dat, &result, sizeof result);
392 /* The protection mechanisms and their corresponding bit-masks are as
395 * 1 No protection mechanism
396 * 2 Integrity (krb_mk_safe) protection
397 * 4 Privacy (krb_mk_priv) protection
399 authenticator.dat[4] = 1;
401 len = strlen(tktuser);
402 strncpy(authenticator.dat+8, tktuser, len);
403 authenticator.length = len + 8 + 1;
404 while (authenticator.length & 7) {
405 authenticator.length++;
407 des_pcbc_encrypt((des_cblock *)authenticator.dat,
408 (des_cblock *)authenticator.dat, authenticator.length, schedule,
411 to64frombits(buf1, authenticator.dat, authenticator.length);
412 if (outlevel >= O_MONITOR) {
413 report(stdout, "IMAP> %s\n", buf1);
415 SockWrite(sock, buf1, strlen(buf1));
416 SockWrite(sock, "\r\n", 2);
418 if (result = gen_recv(sock, buf1, sizeof buf1))
421 if (strstr(buf1, "OK")) {
428 #endif /* KERBEROS_V4 */
431 #define GSSAUTH_P_NONE 1
432 #define GSSAUTH_P_INTEGRITY 2
433 #define GSSAUTH_P_PRIVACY 4
435 static int do_gssauth(int sock, char *hostname, char *username)
437 gss_buffer_desc request_buf, send_token;
438 gss_buffer_t sec_token;
439 gss_name_t target_name;
440 gss_ctx_id_t context;
444 OM_uint32 maj_stat, min_stat;
445 char buf1[8192], buf2[8192], server_conf_flags;
446 unsigned long buf_size;
449 /* first things first: get an imap ticket for host */
450 sprintf(buf1, "imap@%s", hostname);
451 request_buf.value = buf1;
452 request_buf.length = strlen(buf1) + 1;
453 maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name,
455 if (maj_stat != GSS_S_COMPLETE) {
456 report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
459 else if (outlevel >= O_DEBUG) {
460 maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
462 report(stderr, _("Using service name [%s]\n"),request_buf.value);
463 maj_stat = gss_release_buffer(&min_stat, &request_buf);
466 gen_send(sock, "AUTHENTICATE GSSAPI");
468 /* upon receipt of the GSSAPI authentication request, server returns
469 * null data ready response. */
470 if (result = gen_recv(sock, buf1, sizeof buf1)) {
474 /* now start the security context initialisation loop... */
475 sec_token = GSS_C_NO_BUFFER;
476 context = GSS_C_NO_CONTEXT;
477 if (outlevel >= O_VERBOSE)
478 report(stdout, _("Sending credentials\n"));
480 maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL,
481 &context, target_name, NULL, 0, 0, NULL, sec_token, NULL,
482 &send_token, &cflags, NULL);
483 if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
484 report(stderr, _("Error exchanging credentials\n"));
485 gss_release_name(&min_stat, &target_name);
486 /* wake up server and await NO response */
487 SockWrite(sock, "\r\n", 2);
488 if (result = gen_recv(sock, buf1, sizeof buf1))
492 to64frombits(buf1, send_token.value, send_token.length);
493 gss_release_buffer(&min_stat, &send_token);
494 SockWrite(sock, buf1, strlen(buf1));
495 SockWrite(sock, "\r\n", 2);
496 if (outlevel >= O_MONITOR)
497 report(stdout, "IMAP> %s\n", buf1);
498 if (maj_stat == GSS_S_CONTINUE_NEEDED) {
499 if (result = gen_recv(sock, buf1, sizeof buf1)) {
500 gss_release_name(&min_stat, &target_name);
503 request_buf.length = from64tobits(buf2, buf1 + 2);
504 request_buf.value = buf2;
505 sec_token = &request_buf;
507 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
508 gss_release_name(&min_stat, &target_name);
510 /* get security flags and buffer size */
511 if (result = gen_recv(sock, buf1, sizeof buf1)) {
514 request_buf.length = from64tobits(buf2, buf1 + 2);
515 request_buf.value = buf2;
517 maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
519 if (maj_stat != GSS_S_COMPLETE) {
520 report(stderr, _("Couldn't unwrap security level data\n"));
521 gss_release_buffer(&min_stat, &send_token);
524 if (outlevel >= O_DEBUG)
525 report(stdout, _("Credential exchange complete\n"));
526 /* first octet is security levels supported. We want none, for now */
527 server_conf_flags = ((char *)send_token.value)[0];
528 if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
529 report(stderr, _("Server requires integrity and/or privacy\n"));
530 gss_release_buffer(&min_stat, &send_token);
533 ((char *)send_token.value)[0] = 0;
534 buf_size = ntohl(*((long *)send_token.value));
535 /* we don't care about buffer size if we don't wrap data */
536 gss_release_buffer(&min_stat, &send_token);
537 if (outlevel >= O_DEBUG) {
538 report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
539 server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
540 server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
541 server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
542 report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
545 /* now respond in kind (hack!!!) */
546 buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
547 memcpy(buf1, &buf_size, 4);
548 buf1[0] = GSSAUTH_P_NONE;
549 strcpy(buf1+4, username); /* server decides if princ is user */
550 request_buf.length = 4 + strlen(username) + 1;
551 request_buf.value = buf1;
552 maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
553 &cflags, &send_token);
554 if (maj_stat != GSS_S_COMPLETE) {
555 report(stderr, _("Error creating security level request\n"));
558 to64frombits(buf1, send_token.value, send_token.length);
559 if (outlevel >= O_DEBUG) {
560 report(stdout, _("Requesting authorisation as %s\n"), username);
561 report(stdout, "IMAP> %s\n",buf1);
563 SockWrite(sock, buf1, strlen(buf1));
564 SockWrite(sock, "\r\n", 2);
566 /* we should be done. Get status and finish up */
567 if (result = gen_recv(sock, buf1, sizeof buf1))
569 if (strstr(buf1, "OK")) {
570 /* flush security context */
571 if (outlevel >= O_DEBUG)
572 report(stdout, _("Releasing GSS credentials\n"));
573 maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
574 if (maj_stat != GSS_S_COMPLETE) {
575 report(stderr, _("Error releasing credentials\n"));
578 /* send_token may contain a notification to the server to flush
579 * credentials. RFC 1731 doesn't specify what to do, and since this
580 * support is only for authentication, we'll assume the server
581 * knows enough to flush its own credentials */
582 gss_release_buffer(&min_stat, &send_token);
590 int imap_canonicalize(char *result, char *passwd)
591 /* encode an IMAP password as per RFC1730's quoting conventions */
596 for (i = 0; i < strlen(passwd); i++)
598 if ((passwd[i] == '\\') || (passwd[i] == '"'))
600 result[j++] = passwd[i];
607 int imap_getauth(int sock, struct query *ctl, char *greeting)
608 /* apply for connection authorization */
611 char password[PASSWORDLEN*2];
613 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
614 capabilities[0] = '\0';
615 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
617 /* UW-IMAP server 10.173 notifies in all caps */
618 if (strstr(capabilities, "IMAP4REV1"))
620 imap_version = IMAP4rev1;
621 if (outlevel >= O_DEBUG)
622 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
626 imap_version = IMAP4;
627 if (outlevel >= O_DEBUG)
628 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
631 else if (ok == PS_ERROR)
633 imap_version = IMAP2;
634 if (outlevel >= O_DEBUG)
635 report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
640 peek_capable = (imap_version >= IMAP4);
643 if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
645 if (outlevel >= O_DEBUG)
646 report(stdout, _("OTP authentication is supported\n"));
647 if (do_otp(sock, ctl) == PS_SUCCESS)
653 if (strstr(capabilities, "AUTH=GSSAPI"))
655 if (ctl->server.protocol == P_IMAP_GSS)
657 if (outlevel >= O_DEBUG)
658 report(stdout, _("GSS authentication is supported\n"));
659 return do_gssauth(sock, ctl->server.truename, ctl->remotename);
662 else if (ctl->server.protocol == P_IMAP_GSS)
665 _("Required GSS capability not supported by server\n"));
671 if (strstr(capabilities, "AUTH=KERBEROS_V4"))
673 if (outlevel >= O_DEBUG)
674 report(stdout, _("KERBEROS_V4 authentication is supported\n"));
676 if (ctl->server.protocol == P_IMAP_K4)
678 if ((ok = do_rfc1731(sock, ctl->server.truename)))
680 if (outlevel >= O_MONITOR)
681 report(stdout, "IMAP> *\n");
682 SockWrite(sock, "*\r\n", 3);
687 /* else fall through to ordinary AUTH=LOGIN case */
689 else if (ctl->server.protocol == P_IMAP_K4)
692 _("Required KERBEROS_V4 capability not supported by server\n"));
695 #endif /* KERBEROS_V4 */
697 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
698 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
699 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
701 _("Required LOGIN capability not supported by server\n"));
704 #endif /* __UNUSED__ */
706 imap_canonicalize(password, ctl->password);
707 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
714 static int internal_expunge(int sock)
715 /* ship an expunge, resetting associated counters */
719 if ((ok = gen_transact(sock, "EXPUNGE")))
722 expunged += deletions;
725 #ifdef IMAP_UID /* not used */
727 #endif /* IMAP_UID */
732 static int imap_getrange(int sock,
735 int *countp, int *newp, int *bytes)
736 /* get range of messages to be fetched */
740 /* find out how many messages are waiting */
741 *bytes = recent = unseen = -1;
746 * We have to have an expunge here, otherwise the re-poll will
747 * infinite-loop picking up un-expunged message.
750 if (deletions && ctl->expunge > 1)
751 internal_expunge(sock);
753 if (ok || gen_transact(sock, "NOOP"))
755 report(stderr, _("re-poll failed\n"));
758 else if (count == -1) /* no EXISTS response to NOOP */
767 ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
769 ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
772 report(stderr, _("mailbox selection failed\n"));
780 * Note: because IMAP has an is_old method, this number is used
781 * only for the "X messages (Y unseen)" notification. Accordingly
782 * it doesn't matter much that it can be wrong (e.g. if we see an
783 * UNSEEN response but not all messages above the first UNSEEN one
786 if (unseen >= 0) /* optional, but better if we see it */
787 *newp = count - unseen + 1;
788 else if (recent >= 0) /* mandatory */
791 *newp = -1; /* should never happen, RECENT is mandatory */
798 static int imap_getsizes(int sock, int count, int *sizes)
799 /* capture the sizes of all messages */
801 char buf [MSGBUFSIZE+1];
804 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
805 * won't accept 1:1 as valid set syntax. Some implementors
806 * should be taken out and shot for excessive anality.
809 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
811 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
816 if ((ok = gen_recv(sock, buf, sizeof(buf))))
818 if (strstr(buf, "OK"))
820 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
821 sizes[num - 1] = size;
827 static int imap_is_old(int sock, struct query *ctl, int number)
828 /* is the given message old? */
832 /* expunges change the fetch numbers */
835 if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
841 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
842 /* request headers of nth message */
844 char buf [MSGBUFSIZE+1];
847 /* expunges change the fetch numbers */
851 * This is blessed by RFC 1176, RFC1730, RFC2060.
852 * According to the RFCs, it should *not* set the \Seen flag.
854 gen_send(sock, "FETCH %d RFC822.HEADER", number);
856 /* looking for FETCH response */
860 if ((ok = gen_recv(sock, buf, sizeof(buf))))
863 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
871 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
872 /* request body of nth message */
874 char buf [MSGBUFSIZE+1], *cp;
877 /* expunges change the fetch numbers */
881 * If we're using IMAP4, we can fetch the message without setting its
882 * seen flag. This is good! It means that if the protocol exchange
883 * craps out during the message, it will still be marked `unseen' on
886 * However...*don't* do this if we're using keep to suppress deletion!
887 * In that case, marking the seen flag is the only way to prevent the
888 * message from being re-fetched on subsequent runs.
890 switch (imap_version)
892 case IMAP4rev1: /* RFC 2060 */
894 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
896 gen_send(sock, "FETCH %d BODY[TEXT]", number);
899 case IMAP4: /* RFC 1730 */
901 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
903 gen_send(sock, "FETCH %d RFC822.TEXT", number);
906 default: /* RFC 1176 */
907 gen_send(sock, "FETCH %d RFC822.TEXT", number);
911 /* looking for FETCH response */
915 if ((ok = gen_recv(sock, buf, sizeof(buf))))
918 (sscanf(buf+2, "%d FETCH", &num) != 1);
923 /* try to extract a length */
924 if ((cp = strchr(buf, '{')))
925 *lenp = atoi(cp + 1);
932 static int imap_trail(int sock, struct query *ctl, int number)
933 /* discard tail of FETCH response after reading message text */
935 /* expunges change the fetch numbers */
936 /* number -= expunged; */
940 char buf[MSGBUFSIZE+1];
943 if ((ok = gen_recv(sock, buf, sizeof(buf))))
946 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
947 if (strstr(buf, "OK"))
954 static int imap_delete(int sock, struct query *ctl, int number)
955 /* set delete flag for given message */
959 /* expunges change the fetch numbers */
963 * Use SILENT if possible as a minor throughput optimization.
964 * Note: this has been dropped from IMAP4rev1.
966 if ((ok = gen_transact(sock,
967 imap_version == IMAP4
968 ? "STORE %d +FLAGS.SILENT (\\Deleted)"
969 : "STORE %d +FLAGS (\\Deleted)",
976 * We do an expunge after ctl->expunge messages, rather than
977 * just before quit, so that a line hit during a long session
978 * won't result in lots of messages being fetched again during
981 if (NUM_NONZERO(ctl->expunge) && (deletions % ctl->expunge) == 0)
982 internal_expunge(sock);
987 static int imap_logout(int sock, struct query *ctl)
988 /* send logout command */
990 /* if expunges after deletion have been suppressed, ship one now */
991 if (NUM_SPECIFIED(ctl->expunge) && NUM_ZERO(ctl->expunge) && deletions)
992 internal_expunge(sock);
994 return(gen_transact(sock, "LOGOUT"));
997 const static struct method imap =
999 "IMAP", /* Internet Message Access Protocol */
1003 143, /* standard IMAP2bis/IMAP4 port */
1005 TRUE, /* this is a tagged protocol */
1006 FALSE, /* no message delimiter */
1007 imap_ok, /* parse command response */
1008 imap_canonicalize, /* deal with embedded slashes and spaces */
1009 imap_getauth, /* get authorization */
1010 imap_getrange, /* query range of messages */
1011 imap_getsizes, /* get sizes of messages (used for --limit option */
1012 imap_is_old, /* no UID check */
1013 imap_fetch_headers, /* request given message headers */
1014 imap_fetch_body, /* request given message body */
1015 imap_trail, /* eat message trailer */
1016 imap_delete, /* delete the message */
1017 imap_logout, /* expunge and exit */
1018 TRUE, /* yes, we can re-poll */
1021 int doIMAP(struct query *ctl)
1022 /* retrieve messages using IMAP Version 2bis or Version 4 */
1024 return(do_protocol(ctl, &imap));
1027 /* imap.c ends here */