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"
21 #include <kerberosIV/des.h>
22 #include <kerberosIV/krb.h>
24 #if defined (__bsdi__)
26 #define krb_get_err_text(e) (krb_err_txt[e])
28 #if defined(__NetBSD__) || (__FreeBSD__) || defined(__linux__)
29 #define krb_get_err_text(e) (krb_err_txt[e])
33 #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 error(0, -1, _("Could not decode initial BASE64 challenge"));
150 to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
152 if (outlevel >= O_MONITOR)
153 error(0, 0, "IMAP> %s", 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 error(0, -1, _("Could not decode OTP challenge"));
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 error(0, 0, "IMAP> %s", 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 len = from64tobits(challenge1.cstr, buf1);
244 error(0, -1, _("could not decode initial BASE64 challenge"));
248 /* Client responds with a Kerberos ticket and an authenticator for
249 * the principal "imap.hostname@realm" where "hostname" is the
250 * first component of the host name of the server with all letters
251 * in lower case and where "realm" is the Kerberos realm of the
252 * server. The encrypted checksum field included within the
253 * Kerberos authenticator should contain the server-provided
254 * 32-bit number in network byte order.
257 strncpy(srvinst, truename, (sizeof srvinst)-1);
258 srvinst[(sizeof srvinst)-1] = '\0';
259 for (p = srvinst; *p; p++) {
265 strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
266 srvrealm[(sizeof srvrealm)-1] = '\0';
267 if (p = strchr(srvinst, '.')) {
271 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
273 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
277 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
279 error(0, -1, "krb_get_cred: %s", krb_get_err_text(result));
283 memcpy(session, credentials.session, sizeof session);
284 memset(&credentials, 0, sizeof credentials);
285 des_key_sched(session, schedule);
287 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
289 error(0, -1, "krb_get_tf_fullname: %s", krb_get_err_text(result));
293 if (strcmp(tktuser, user) != 0) {
294 error(0, -1, _("principal %s in ticket does not match -u %s"), tktuser,
300 error(0, 0, _("non-null instance (%s) might cause strange behavior"),
302 strcat(tktuser, ".");
303 strcat(tktuser, tktinst);
306 if (strcmp(tktrealm, srvrealm) != 0) {
307 strcat(tktuser, "@");
308 strcat(tktuser, tktrealm);
311 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
314 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
318 to64frombits(buf1, authenticator.dat, authenticator.length);
319 if (outlevel >= O_MONITOR) {
320 error(0, 0, "IMAP> %s", buf1);
322 SockWrite(sock, buf1, strlen(buf1));
323 SockWrite(sock, "\r\n", 2);
325 /* Upon decrypting and verifying the ticket and authenticator, the
326 * server should verify that the contained checksum field equals
327 * the original server provided random 32-bit number. Should the
328 * verification be successful, the server must add one to the
329 * checksum and construct 8 octets of data, with the first four
330 * octets containing the incremented checksum in network byte
331 * order, the fifth octet containing a bit-mask specifying the
332 * protection mechanisms supported by the server, and the sixth
333 * through eighth octets containing, in network byte order, the
334 * maximum cipher-text buffer size the server is able to receive.
335 * The server must encrypt the 8 octets of data in the session key
336 * and issue that encrypted data in a second ready response. The
337 * client should consider the server authenticated if the first
338 * four octets the un-encrypted data is equal to one plus the
339 * checksum it previously sent.
342 if (result = gen_recv(sock, buf1, sizeof buf1))
345 /* The client must construct data with the first four octets
346 * containing the original server-issued checksum in network byte
347 * order, the fifth octet containing the bit-mask specifying the
348 * selected protection mechanism, the sixth through eighth octets
349 * containing in network byte order the maximum cipher-text buffer
350 * size the client is able to receive, and the following octets
351 * containing a user name string. The client must then append
352 * from one to eight octets so that the length of the data is a
353 * multiple of eight octets. The client must then PCBC encrypt the
354 * data with the session key and respond to the second ready
355 * response with the encrypted data. The server decrypts the data
356 * and verifies the contained checksum. The username field
357 * identifies the user for whom subsequent IMAP operations are to
358 * be performed; the server must verify that the principal
359 * identified in the Kerberos ticket is authorized to connect as
360 * that user. After these verifications, the authentication
361 * process is complete.
364 len = from64tobits(buf2, buf1);
366 error(0, -1, _("could not decode BASE64 ready response"));
370 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
371 memcpy(challenge2.cstr, buf2, 4);
372 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
373 error(0, -1, _("challenge mismatch"));
377 memset(authenticator.dat, 0, sizeof authenticator.dat);
379 result = htonl(challenge1.cint);
380 memcpy(authenticator.dat, &result, sizeof result);
382 /* The protection mechanisms and their corresponding bit-masks are as
385 * 1 No protection mechanism
386 * 2 Integrity (krb_mk_safe) protection
387 * 4 Privacy (krb_mk_priv) protection
389 authenticator.dat[4] = 1;
391 len = strlen(tktuser);
392 strncpy(authenticator.dat+8, tktuser, len);
393 authenticator.length = len + 8 + 1;
394 while (authenticator.length & 7) {
395 authenticator.length++;
397 des_pcbc_encrypt((des_cblock *)authenticator.dat,
398 (des_cblock *)authenticator.dat, authenticator.length, schedule,
401 to64frombits(buf1, authenticator.dat, authenticator.length);
402 if (outlevel >= O_MONITOR) {
403 error(0, 0, "IMAP> %s", buf1);
405 SockWrite(sock, buf1, strlen(buf1));
406 SockWrite(sock, "\r\n", 2);
408 if (result = gen_recv(sock, buf1, sizeof buf1))
411 if (strstr(buf1, "OK")) {
418 #endif /* KERBEROS_V4 */
421 #define GSSAUTH_P_NONE 1
422 #define GSSAUTH_P_INTEGRITY 2
423 #define GSSAUTH_P_PRIVACY 4
425 static int do_gssauth(int sock, char *hostname, char *username)
427 gss_buffer_desc request_buf, send_token;
428 gss_buffer_t sec_token;
429 gss_name_t target_name;
430 gss_ctx_id_t context;
434 OM_uint32 maj_stat, min_stat;
435 char buf1[8192], buf2[8192], server_conf_flags;
436 unsigned long buf_size;
439 /* first things first: get an imap ticket for host */
440 sprintf(buf1, "imap@%s", hostname);
441 request_buf.value = buf1;
442 request_buf.length = strlen(buf1) + 1;
443 maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name,
445 if (maj_stat != GSS_S_COMPLETE) {
446 error(0, -1, _("Couldn't get service name for [%s]"), buf1);
449 else if (outlevel >= O_DEBUG) {
450 maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
452 error(0, 0, _("Using service name [%s]"),request_buf.value);
453 maj_stat = gss_release_buffer(&min_stat, &request_buf);
456 gen_send(sock, "AUTHENTICATE GSSAPI");
458 /* upon receipt of the GSSAPI authentication request, server returns
459 * null data ready response. */
460 if (result = gen_recv(sock, buf1, sizeof buf1)) {
464 /* now start the security context initialisation loop... */
465 sec_token = GSS_C_NO_BUFFER;
466 context = GSS_C_NO_CONTEXT;
467 if (outlevel >= O_VERBOSE)
468 error(0,0,_("Sending credentials"));
470 maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL,
471 &context, target_name, NULL, 0, 0, NULL, sec_token, NULL,
472 &send_token, &cflags, NULL);
473 if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
474 error(0, -1,_("Error exchanging credentials"));
475 gss_release_name(&min_stat, &target_name);
476 /* wake up server and await NO response */
477 SockWrite(sock, "\r\n", 2);
478 if (result = gen_recv(sock, buf1, sizeof buf1))
482 to64frombits(buf1, send_token.value, send_token.length);
483 gss_release_buffer(&min_stat, &send_token);
484 SockWrite(sock, buf1, strlen(buf1));
485 SockWrite(sock, "\r\n", 2);
486 if (outlevel >= O_MONITOR)
487 error(0,0,"IMAP> %s", buf1);
488 if (maj_stat == GSS_S_CONTINUE_NEEDED) {
489 if (result = gen_recv(sock, buf1, sizeof buf1)) {
490 gss_release_name(&min_stat, &target_name);
493 request_buf.length = from64tobits(buf2, buf1 + 2);
494 request_buf.value = buf2;
495 sec_token = &request_buf;
497 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
498 gss_release_name(&min_stat, &target_name);
500 /* get security flags and buffer size */
501 if (result = gen_recv(sock, buf1, sizeof buf1)) {
504 request_buf.length = from64tobits(buf2, buf1 + 2);
505 request_buf.value = buf2;
507 maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
509 if (maj_stat != GSS_S_COMPLETE) {
510 error(0,-1,_("Couldn't unwrap security level data"));
511 gss_release_buffer(&min_stat, &send_token);
514 if (outlevel >= O_DEBUG)
515 error(0,0,_("Credential exchange complete"));
516 /* first octet is security levels supported. We want none, for now */
517 server_conf_flags = ((char *)send_token.value)[0];
518 if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
519 error(0,-1,_("Server requires integrity and/or privacy"));
520 gss_release_buffer(&min_stat, &send_token);
523 ((char *)send_token.value)[0] = 0;
524 buf_size = ntohl(*((long *)send_token.value));
525 /* we don't care about buffer size if we don't wrap data */
526 gss_release_buffer(&min_stat, &send_token);
527 if (outlevel >= O_DEBUG) {
528 error(0,0,_("Unwrapped security level flags: %s%s%s"),
529 server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
530 server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
531 server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
532 error(0,0,_("Maximum GSS token size is %ld"),buf_size);
535 /* now respond in kind (hack!!!) */
536 buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
537 memcpy(buf1, &buf_size, 4);
538 buf1[0] = GSSAUTH_P_NONE;
539 strcpy(buf1+4, username); /* server decides if princ is user */
540 request_buf.length = 4 + strlen(username) + 1;
541 request_buf.value = buf1;
542 maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
543 &cflags, &send_token);
544 if (maj_stat != GSS_S_COMPLETE) {
545 error(0,-1,_("Error creating security level request"));
548 to64frombits(buf1, send_token.value, send_token.length);
549 if (outlevel >= O_DEBUG) {
550 error(0,0,_("Requesting authorisation as %s"), username);
551 error(0,0,"IMAP> %s",buf1);
553 SockWrite(sock, buf1, strlen(buf1));
554 SockWrite(sock, "\r\n", 2);
556 /* we should be done. Get status and finish up */
557 if (result = gen_recv(sock, buf1, sizeof buf1))
559 if (strstr(buf1, "OK")) {
560 /* flush security context */
561 if (outlevel >= O_DEBUG)
562 error(0, 0, _("Releasing GSS credentials"));
563 maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
564 if (maj_stat != GSS_S_COMPLETE) {
565 error(0, -1, _("Error releasing credentials"));
568 /* send_token may contain a notification to the server to flush
569 * credentials. RFC 1731 doesn't specify what to do, and since this
570 * support is only for authentication, we'll assume the server
571 * knows enough to flush its own credentials */
572 gss_release_buffer(&min_stat, &send_token);
580 int imap_canonicalize(char *result, char *passwd)
581 /* encode an IMAP password as per RFC1730's quoting conventions */
586 for (i = 0; i < strlen(passwd); i++)
588 if ((passwd[i] == '\\') || (passwd[i] == '"'))
590 result[j++] = passwd[i];
597 int imap_getauth(int sock, struct query *ctl, char *greeting)
598 /* apply for connection authorization */
601 char password[PASSWORDLEN*2];
603 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
604 capabilities[0] = '\0';
605 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
607 /* UW-IMAP server 10.173 notifies in all caps */
608 if (strstr(capabilities, "IMAP4REV1"))
610 imap_version = IMAP4rev1;
611 if (outlevel >= O_DEBUG)
612 error(0, 0, _("Protocol identified as IMAP4 rev 1"));
616 imap_version = IMAP4;
617 if (outlevel >= O_DEBUG)
618 error(0, 0, _("Protocol identified as IMAP4 rev 0"));
621 else if (ok == PS_ERROR)
623 imap_version = IMAP2;
624 if (outlevel >= O_DEBUG)
625 error(0, 0, _("Protocol identified as IMAP2 or IMAP2BIS"));
630 peek_capable = (imap_version >= IMAP4);
633 if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
635 if (outlevel >= O_DEBUG)
636 error(0, 0, _("OTP authentication is supported"));
637 if (do_otp(sock, ctl) == PS_SUCCESS)
643 if (strstr(capabilities, "AUTH=GSSAPI"))
645 if (ctl->server.protocol == P_IMAP_GSS)
647 if (outlevel >= O_DEBUG)
648 error(0, 0, _("GSS authentication is supported"));
649 return do_gssauth(sock, ctl->server.truename, ctl->remotename);
652 else if (ctl->server.protocol == P_IMAP_GSS)
654 error(0,-1, _("Required GSS capability not supported by server"));
660 if (strstr(capabilities, "AUTH=KERBEROS_V4"))
662 if (outlevel >= O_DEBUG)
663 error(0, 0, _("KERBEROS_V4 authentication is supported"));
665 if (ctl->server.protocol == P_IMAP_K4)
667 if ((ok = do_rfc1731(sock, ctl->server.truename)))
669 if (outlevel >= O_MONITOR)
670 error(0, 0, "IMAP> *");
671 SockWrite(sock, "*\r\n", 3);
676 /* else fall through to ordinary AUTH=LOGIN case */
678 else if (ctl->server.protocol == P_IMAP_K4)
680 error(0,-1, _("Required KERBEROS_V4 capability not supported by server"));
683 #endif /* KERBEROS_V4 */
685 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
686 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
687 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
688 error(0,-1, _("Required LOGIN capability not supported by server"));
691 #endif /* __UNUSED__ */
693 imap_canonicalize(password, ctl->password);
694 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
701 static int internal_expunge(int sock)
702 /* ship an expunge, resetting associated counters */
706 if ((ok = gen_transact(sock, "EXPUNGE")))
709 expunged += deletions;
712 #ifdef IMAP_UID /* not used */
714 #endif /* IMAP_UID */
719 static int imap_getrange(int sock,
722 int *countp, int *newp, int *bytes)
723 /* get range of messages to be fetched */
727 /* find out how many messages are waiting */
728 *bytes = recent = unseen = -1;
733 * We have to have an expunge here, otherwise the re-poll will
734 * infinite-loop picking up un-expunged message.
737 if (deletions && ctl->expunge > 1)
738 internal_expunge(sock);
740 if (ok || gen_transact(sock, "NOOP"))
742 error(0, 0, _("re-poll failed"));
745 else if (count == -1) /* no EXISTS response to NOOP */
754 ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
756 ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
759 error(0, 0, _("mailbox selection failed"));
767 * Note: because IMAP has an is_old method, this number is used
768 * only for the "X messages (Y unseen)" notification. Accordingly
769 * it doesn't matter much that it can be wrong (e.g. if we see an
770 * UNSEEN response but not all messages above the first UNSEEN one
773 if (unseen >= 0) /* optional, but better if we see it */
774 *newp = count - unseen + 1;
775 else if (recent >= 0) /* mandatory */
778 *newp = -1; /* should never happen, RECENT is mandatory */
785 static int imap_getsizes(int sock, int count, int *sizes)
786 /* capture the sizes of all messages */
788 char buf [MSGBUFSIZE+1];
791 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
792 * won't accept 1:1 as valid set syntax. Some implementors
793 * should be taken out and shot for excessive anality.
796 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
798 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
803 if ((ok = gen_recv(sock, buf, sizeof(buf))))
805 if (strstr(buf, "OK"))
807 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
808 sizes[num - 1] = size;
814 static int imap_is_old(int sock, struct query *ctl, int number)
815 /* is the given message old? */
819 /* expunges change the fetch numbers */
822 if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
828 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
829 /* request headers of nth message */
831 char buf [MSGBUFSIZE+1];
834 /* expunges change the fetch numbers */
838 * This is blessed by RFC 1176, RFC1730, RFC2060.
839 * According to the RFCs, it should *not* set the \Seen flag.
841 gen_send(sock, "FETCH %d RFC822.HEADER", number);
843 /* looking for FETCH response */
847 if ((ok = gen_recv(sock, buf, sizeof(buf))))
850 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
858 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
859 /* request body of nth message */
861 char buf [MSGBUFSIZE+1], *cp;
864 /* expunges change the fetch numbers */
868 * If we're using IMAP4, we can fetch the message without setting its
869 * seen flag. This is good! It means that if the protocol exchange
870 * craps out during the message, it will still be marked `unseen' on
873 * However...*don't* do this if we're using keep to suppress deletion!
874 * In that case, marking the seen flag is the only way to prevent the
875 * message from being re-fetched on subsequent runs.
877 switch (imap_version)
879 case IMAP4rev1: /* RFC 2060 */
881 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
883 gen_send(sock, "FETCH %d BODY[TEXT]", number);
886 case IMAP4: /* RFC 1730 */
888 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
890 gen_send(sock, "FETCH %d RFC822.TEXT", number);
893 default: /* RFC 1176 */
894 gen_send(sock, "FETCH %d RFC822.TEXT", number);
898 /* looking for FETCH response */
902 if ((ok = gen_recv(sock, buf, sizeof(buf))))
905 (sscanf(buf+2, "%d FETCH", &num) != 1);
910 /* try to extract a length */
911 if ((cp = strchr(buf, '{')))
912 *lenp = atoi(cp + 1);
919 static int imap_trail(int sock, struct query *ctl, int number)
920 /* discard tail of FETCH response after reading message text */
922 /* expunges change the fetch numbers */
923 /* number -= expunged; */
927 char buf[MSGBUFSIZE+1];
930 if ((ok = gen_recv(sock, buf, sizeof(buf))))
933 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
934 if (strstr(buf, "OK"))
941 static int imap_delete(int sock, struct query *ctl, int number)
942 /* set delete flag for given message */
946 /* expunges change the fetch numbers */
950 * Use SILENT if possible as a minor throughput optimization.
951 * Note: this has been dropped from IMAP4rev1.
953 if ((ok = gen_transact(sock,
954 imap_version == IMAP4
955 ? "STORE %d +FLAGS.SILENT (\\Deleted)"
956 : "STORE %d +FLAGS (\\Deleted)",
963 * We do an expunge after ctl->expunge messages, rather than
964 * just before quit, so that a line hit during a long session
965 * won't result in lots of messages being fetched again during
968 if (NUM_NONZERO(ctl->expunge) && (deletions % ctl->expunge) == 0)
969 internal_expunge(sock);
974 static int imap_logout(int sock, struct query *ctl)
975 /* send logout command */
977 /* if expunges after deletion have been suppressed, ship one now */
978 if (NUM_SPECIFIED(ctl->expunge) && NUM_ZERO(ctl->expunge) && deletions)
979 internal_expunge(sock);
981 return(gen_transact(sock, "LOGOUT"));
984 const static struct method imap =
986 "IMAP", /* Internet Message Access Protocol */
990 143, /* standard IMAP2bis/IMAP4 port */
992 TRUE, /* this is a tagged protocol */
993 FALSE, /* no message delimiter */
994 imap_ok, /* parse command response */
995 imap_canonicalize, /* deal with embedded slashes and spaces */
996 imap_getauth, /* get authorization */
997 imap_getrange, /* query range of messages */
998 imap_getsizes, /* get sizes of messages (used for --limit option */
999 imap_is_old, /* no UID check */
1000 imap_fetch_headers, /* request given message headers */
1001 imap_fetch_body, /* request given message body */
1002 imap_trail, /* eat message trailer */
1003 imap_delete, /* delete the message */
1004 imap_logout, /* expunge and exit */
1005 TRUE, /* yes, we can re-poll */
1008 int doIMAP(struct query *ctl)
1009 /* retrieve messages using IMAP Version 2bis or Version 4 */
1011 return(do_protocol(ctl, &imap));
1014 /* imap.c ends here */