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"
19 #if defined (__bsdi__)
21 #define krb_get_err_text(e) (krb_err_txt[e])
23 #if defined(__NetBSD__) || (__FreeBSD__) || defined(__linux__)
24 #define krb_get_err_text(e) (krb_err_txt[e])
27 #endif /* KERBEROS_V4 */
30 #include <gssapi/gssapi.h>
31 #include <gssapi/gssapi_generic.h>
38 #ifndef strstr /* glibc-2.1 declares this as a macro */
39 extern char *strstr(); /* needed on sysV68 R3V7.1. */
42 /* imap_version values */
43 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
44 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
45 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
47 static int count, seen, recent, unseen, deletions,expunged, imap_version;
48 static char capabilities[MSGBUFSIZE+1];
50 int imap_ok(int sock, char *argbuf)
51 /* parse command response */
53 char buf [MSGBUFSIZE+1];
60 if ((ok = gen_recv(sock, buf, sizeof(buf))))
63 /* all tokens in responses are caseblind */
64 for (cp = buf; *cp; cp++)
68 /* interpret untagged status responses */
69 if (strstr(buf, "* CAPABILITY"))
70 strncpy(capabilities, buf + 12, sizeof(capabilities));
71 if (strstr(buf, "EXISTS"))
73 if (strstr(buf, "RECENT"))
75 if (strstr(buf, "UNSEEN"))
80 * Handle both "* 42 UNSEEN" (if tha ever happens) and
81 * "* OK [UNSEEN 42] 42". Note that what this gets us is
82 * a minimum index, not a count.
85 for (cp = buf; *cp && !isdigit(*cp); cp++)
89 if (strstr(buf, "FLAGS"))
90 seen = (strstr(buf, "SEEN") != (char *)NULL);
92 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
105 for (cp = buf; !isspace(*cp); cp++)
110 if (strncmp(cp, "OK", 2) == 0)
116 else if (strncmp(cp, "BAD", 2) == 0)
124 static int do_otp(int sock, struct query *ctl)
128 char challenge[OPIE_CHALLENGE_MAX+1];
129 char response[OPIE_RESPONSE_MAX+1];
131 gen_send(sock, "AUTHENTICATE X-OTP");
133 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
136 if ((i = from64tobits(challenge, buffer)) < 0) {
137 error(0, -1, "Could not decode initial BASE64 challenge");
142 to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
144 if (outlevel == O_VERBOSE)
145 error(0, 0, "IMAP> %s", buffer);
146 SockWrite(sock, buffer, strlen(buffer));
147 SockWrite(sock, "\r\n", 2);
149 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
152 if ((i = from64tobits(challenge, buffer)) < 0) {
153 error(0, -1, "Could not decode OTP challenge");
157 rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
158 if ((rval == -2) && (cmd_opts.poll_interval == -1)) {
159 char secret[OPIE_SECRET_MAX+1];
160 fprintf(stderr, "Secret pass phrase: ");
161 if (opiereadpass(secret, sizeof(secret), 0))
162 rval = opiegenerator(challenge, secret, response);
163 memset(secret, 0, sizeof(secret));
169 to64frombits(buffer, response, strlen(response));
171 if (outlevel == O_VERBOSE)
172 error(0, 0, "IMAP> %s", buffer);
173 SockWrite(sock, buffer, strlen(buffer));
174 SockWrite(sock, "\r\n", 2);
176 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
179 if (strstr(buffer, "OK"))
189 #elif SIZEOF_SHORT == 4
191 #elif SIZEOF_LONG == 4
194 #error Cannot deduce a 32-bit-type
197 static int do_rfc1731(int sock, char *truename)
198 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
201 char buf1[4096], buf2[4096];
205 } challenge1, challenge2;
206 char srvinst[INST_SZ];
208 char srvrealm[REALM_SZ];
209 KTEXT_ST authenticator;
210 CREDENTIALS credentials;
211 char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
212 char tktinst[INST_SZ];
213 char tktrealm[REALM_SZ];
215 des_key_schedule schedule;
217 gen_send(sock, "AUTHENTICATE KERBEROS_V4");
219 /* The data encoded in the first ready response contains a random
220 * 32-bit number in network byte order. The client should respond
221 * with a Kerberos ticket and an authenticator for the principal
222 * "imap.hostname@realm", where "hostname" is the first component
223 * of the host name of the server with all letters in lower case
224 * and where "realm" is the Kerberos realm of the server. The
225 * encrypted checksum field included within the Kerberos
226 * authenticator should contain the server provided 32-bit number
227 * in network byte order.
230 if (result = gen_recv(sock, buf1, sizeof buf1)) {
234 len = from64tobits(challenge1.cstr, buf1);
236 error(0, -1, "could not decode initial BASE64 challenge");
240 /* Client responds with a Kerberos ticket and an authenticator for
241 * the principal "imap.hostname@realm" where "hostname" is the
242 * first component of the host name of the server with all letters
243 * in lower case and where "realm" is the Kerberos realm of the
244 * server. The encrypted checksum field included within the
245 * Kerberos authenticator should contain the server-provided
246 * 32-bit number in network byte order.
249 strncpy(srvinst, truename, (sizeof srvinst)-1);
250 srvinst[(sizeof srvinst)-1] = '\0';
251 for (p = srvinst; *p; p++) {
257 strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
258 srvrealm[(sizeof srvrealm)-1] = '\0';
259 if (p = strchr(srvinst, '.')) {
263 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
265 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
269 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
271 error(0, -1, "krb_get_cred: %s", krb_get_err_text(result));
275 memcpy(session, credentials.session, sizeof session);
276 memset(&credentials, 0, sizeof credentials);
277 des_key_sched(session, schedule);
279 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
281 error(0, -1, "krb_get_tf_fullname: %s", krb_get_err_text(result));
285 if (strcmp(tktuser, user) != 0) {
286 error(0, -1, "principal %s in ticket does not match -u %s", tktuser,
292 error(0, 0, "non-null instance (%s) might cause strange behavior",
294 strcat(tktuser, ".");
295 strcat(tktuser, tktinst);
298 if (strcmp(tktrealm, srvrealm) != 0) {
299 strcat(tktuser, "@");
300 strcat(tktuser, tktrealm);
303 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
306 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
310 to64frombits(buf1, authenticator.dat, authenticator.length);
311 if (outlevel == O_VERBOSE) {
312 error(0, 0, "IMAP> %s", buf1);
314 SockWrite(sock, buf1, strlen(buf1));
315 SockWrite(sock, "\r\n", 2);
317 /* Upon decrypting and verifying the ticket and authenticator, the
318 * server should verify that the contained checksum field equals
319 * the original server provided random 32-bit number. Should the
320 * verification be successful, the server must add one to the
321 * checksum and construct 8 octets of data, with the first four
322 * octets containing the incremented checksum in network byte
323 * order, the fifth octet containing a bit-mask specifying the
324 * protection mechanisms supported by the server, and the sixth
325 * through eighth octets containing, in network byte order, the
326 * maximum cipher-text buffer size the server is able to receive.
327 * The server must encrypt the 8 octets of data in the session key
328 * and issue that encrypted data in a second ready response. The
329 * client should consider the server authenticated if the first
330 * four octets the un-encrypted data is equal to one plus the
331 * checksum it previously sent.
334 if (result = gen_recv(sock, buf1, sizeof buf1))
337 /* The client must construct data with the first four octets
338 * containing the original server-issued checksum in network byte
339 * order, the fifth octet containing the bit-mask specifying the
340 * selected protection mechanism, the sixth through eighth octets
341 * containing in network byte order the maximum cipher-text buffer
342 * size the client is able to receive, and the following octets
343 * containing a user name string. The client must then append
344 * from one to eight octets so that the length of the data is a
345 * multiple of eight octets. The client must then PCBC encrypt the
346 * data with the session key and respond to the second ready
347 * response with the encrypted data. The server decrypts the data
348 * and verifies the contained checksum. The username field
349 * identifies the user for whom subsequent IMAP operations are to
350 * be performed; the server must verify that the principal
351 * identified in the Kerberos ticket is authorized to connect as
352 * that user. After these verifications, the authentication
353 * process is complete.
356 len = from64tobits(buf2, buf1);
358 error(0, -1, "could not decode BASE64 ready response");
362 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
363 memcpy(challenge2.cstr, buf2, 4);
364 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
365 error(0, -1, "challenge mismatch");
369 memset(authenticator.dat, 0, sizeof authenticator.dat);
371 result = htonl(challenge1.cint);
372 memcpy(authenticator.dat, &result, sizeof result);
374 /* The protection mechanisms and their corresponding bit-masks are as
377 * 1 No protection mechanism
378 * 2 Integrity (krb_mk_safe) protection
379 * 4 Privacy (krb_mk_priv) protection
381 authenticator.dat[4] = 1;
383 len = strlen(tktuser);
384 strncpy(authenticator.dat+8, tktuser, len);
385 authenticator.length = len + 8 + 1;
386 while (authenticator.length & 7) {
387 authenticator.length++;
389 des_pcbc_encrypt((des_cblock *)authenticator.dat,
390 (des_cblock *)authenticator.dat, authenticator.length, schedule,
393 to64frombits(buf1, authenticator.dat, authenticator.length);
394 if (outlevel == O_VERBOSE) {
395 error(0, 0, "IMAP> %s", buf1);
397 SockWrite(sock, buf1, strlen(buf1));
398 SockWrite(sock, "\r\n", 2);
400 if (result = gen_recv(sock, buf1, sizeof buf1))
403 if (strstr(buf1, "OK")) {
410 #endif /* KERBEROS_V4 */
413 #define GSSAUTH_P_NONE 1
414 #define GSSAUTH_P_INTEGRITY 2
415 #define GSSAUTH_P_PRIVACY 4
417 static int do_gssauth(int sock, char *hostname, char *username)
419 gss_buffer_desc request_buf, send_token;
420 gss_buffer_t sec_token;
421 gss_name_t target_name;
422 gss_ctx_id_t context;
426 OM_uint32 maj_stat, min_stat;
427 char buf1[8192], buf2[8192], server_conf_flags;
428 unsigned long buf_size;
431 /* first things first: get an imap ticket for host */
432 sprintf(buf1, "imap@%s", hostname);
433 request_buf.value = buf1;
434 request_buf.length = strlen(buf1) + 1;
435 maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name,
437 if (maj_stat != GSS_S_COMPLETE) {
438 error(0, -1, "Couldn't get service name for [%s]", buf1);
441 else if (outlevel == O_VERBOSE) {
442 maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
444 error(0, 0, "Using service name [%s]",request_buf.value);
445 maj_stat = gss_release_buffer(&min_stat, &request_buf);
448 gen_send(sock, "AUTHENTICATE GSSAPI");
450 /* upon receipt of the GSSAPI authentication request, server returns
451 * null data ready response. */
452 if (result = gen_recv(sock, buf1, sizeof buf1)) {
456 /* now start the security context initialisation loop... */
457 sec_token = GSS_C_NO_BUFFER;
458 context = GSS_C_NO_CONTEXT;
459 if (outlevel == O_VERBOSE)
460 error(0,0,"Sending credentials");
462 maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL,
463 &context, target_name, NULL, 0, 0, NULL, sec_token, NULL,
464 &send_token, &cflags, NULL);
465 if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
466 error(0, -1,"Error exchanging credentials");
467 gss_release_name(&min_stat, &target_name);
468 /* wake up server and await NO response */
469 SockWrite(sock, "\r\n", 2);
470 if (result = gen_recv(sock, buf1, sizeof buf1))
474 to64frombits(buf1, send_token.value, send_token.length);
475 gss_release_buffer(&min_stat, &send_token);
476 SockWrite(sock, buf1, strlen(buf1));
477 SockWrite(sock, "\r\n", 2);
478 if (outlevel == O_VERBOSE)
479 error(0,0,"IMAP> %s", buf1);
480 if (maj_stat == GSS_S_CONTINUE_NEEDED) {
481 if (result = gen_recv(sock, buf1, sizeof buf1)) {
482 gss_release_name(&min_stat, &target_name);
485 request_buf.length = from64tobits(buf2, buf1 + 2);
486 request_buf.value = buf2;
487 sec_token = &request_buf;
489 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
490 gss_release_name(&min_stat, &target_name);
492 /* get security flags and buffer size */
493 if (result = gen_recv(sock, buf1, sizeof buf1)) {
496 request_buf.length = from64tobits(buf2, buf1 + 2);
497 request_buf.value = buf2;
499 maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
501 if (maj_stat != GSS_S_COMPLETE) {
502 error(0,-1,"Couldn't unwrap security level data");
503 gss_release_buffer(&min_stat, &send_token);
506 if (outlevel == O_VERBOSE)
507 error(0,0,"Credential exchange complete");
508 /* first octet is security levels supported. We want none, for now */
509 server_conf_flags = ((char *)send_token.value)[0];
510 if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
511 error(0,-1,"Server requires integrity and/or privacy");
512 gss_release_buffer(&min_stat, &send_token);
515 ((char *)send_token.value)[0] = 0;
516 buf_size = ntohl(*((long *)send_token.value));
517 /* we don't care about buffer size if we don't wrap data */
518 gss_release_buffer(&min_stat, &send_token);
519 if (outlevel == O_VERBOSE) {
520 error(0,0,"Unwrapped security level flags: %s%s%s",
521 server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
522 server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
523 server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
524 error(0,0,"Maximum GSS token size is %ld",buf_size);
527 /* now respond in kind (hack!!!) */
528 buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
529 memcpy(buf1, &buf_size, 4);
530 buf1[0] = GSSAUTH_P_NONE;
531 strcpy(buf1+4, username); /* server decides if princ is user */
532 request_buf.length = 4 + strlen(username) + 1;
533 request_buf.value = buf1;
534 maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
535 &cflags, &send_token);
536 if (maj_stat != GSS_S_COMPLETE) {
537 error(0,-1,"Error creating security level request");
540 to64frombits(buf1, send_token.value, send_token.length);
541 if (outlevel == O_VERBOSE) {
542 error(0,0,"Requesting authorisation as %s", username);
543 error(0,0,"IMAP> %s",buf1);
545 SockWrite(sock, buf1, strlen(buf1));
546 SockWrite(sock, "\r\n", 2);
548 /* we should be done. Get status and finish up */
549 if (result = gen_recv(sock, buf1, sizeof buf1))
551 if (strstr(buf1, "OK")) {
552 /* flush security context */
553 if (outlevel == O_VERBOSE)
554 error(0, 0, "Releasing GSS credentials");
555 maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
556 if (maj_stat != GSS_S_COMPLETE) {
557 error(0, -1, "Error releasing credentials");
560 /* send_token may contain a notification to the server to flush
561 * credentials. RFC 1731 doesn't specify what to do, and since this
562 * support is only for authentication, we'll assume the server
563 * knows enough to flush its own credentials */
564 gss_release_buffer(&min_stat, &send_token);
572 int imap_canonicalize(char *result, char *passwd)
573 /* encode an IMAP password as per RFC1730's quoting conventions */
578 for (i = 0; i < strlen(passwd); i++)
580 if ((passwd[i] == '\\') || (passwd[i] == '"'))
582 result[j++] = passwd[i];
589 int imap_getauth(int sock, struct query *ctl, char *greeting)
590 /* apply for connection authorization */
593 char password[PASSWORDLEN*2];
595 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
596 capabilities[0] = '\0';
597 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
599 /* UW-IMAP server 10.173 notifies in all caps */
600 if (strstr(capabilities, "IMAP4REV1"))
602 imap_version = IMAP4rev1;
603 if (outlevel == O_VERBOSE)
604 error(0, 0, "Protocol identified as IMAP4 rev 1");
608 imap_version = IMAP4;
609 if (outlevel == O_VERBOSE)
610 error(0, 0, "Protocol identified as IMAP4 rev 0");
613 else if (ok == PS_ERROR)
615 imap_version = IMAP2;
616 if (outlevel == O_VERBOSE)
617 error(0, 0, "Protocol identified as IMAP2 or IMAP2BIS");
622 peek_capable = (imap_version >= IMAP4);
625 if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP")) {
626 if (outlevel == O_VERBOSE)
627 error(0, 0, "OTP authentication is supported");
628 if (do_otp(sock, ctl) == PS_SUCCESS)
634 if (strstr(capabilities, "AUTH=GSSAPI"))
636 if (ctl->server.protocol == P_IMAP_GSS)
638 if (outlevel == O_VERBOSE)
639 error(0, 0, "GSS authentication is supported");
640 return do_gssauth(sock, ctl->server.truename, ctl->remotename);
643 else if (ctl->server.protocol == P_IMAP_GSS)
645 error(0,-1, "Required GSS capability not supported by server");
651 if (strstr(capabilities, "AUTH=KERBEROS_V4"))
653 if (outlevel == O_VERBOSE)
654 error(0, 0, "KERBEROS_V4 authentication is supported");
656 if (ctl->server.protocol == P_IMAP_K4)
658 if ((ok = do_rfc1731(sock, ctl->server.truename)))
660 if (outlevel == O_VERBOSE)
661 error(0, 0, "IMAP> *");
662 SockWrite(sock, "*\r\n", 3);
667 /* else fall through to ourdinary AUTH=LOGIN case */
669 else if (ctl->server.protocol == P_IMAP_K4)
671 error(0,-1, "Required KERBEROS_V4 capability not supported by server");
674 #endif /* KERBEROS_V4 */
676 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
677 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
678 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
679 error(0,-1, "Required LOGIN capability not supported by server");
682 #endif /* __UNUSED__ */
684 imap_canonicalize(password, ctl->password);
685 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
692 static int internal_expunge(int sock)
693 /* ship an expunge, resetting associated counters */
697 if ((ok = gen_transact(sock, "EXPUNGE")))
700 expunged += deletions;
703 #ifdef IMAP_UID /* not used */
705 #endif /* IMAP_UID */
710 static int imap_getrange(int sock,
713 int *countp, int *newp, int *bytes)
714 /* get range of messages to be fetched */
718 /* find out how many messages are waiting */
719 *bytes = recent = unseen = -1;
724 * We have to have an expunge here, otherwise the re-poll will
725 * infinite-loop picking up un-expunged message.
728 if (deletions && ctl->expunge > 1)
729 internal_expunge(sock);
731 if (ok || gen_transact(sock, "NOOP"))
733 error(0, 0, "re-poll failed");
736 else if (count == -1) /* no EXISTS response to NOOP */
745 ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
747 ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
750 error(0, 0, "mailbox selection failed");
758 * Note: because IMAP has an is_old method, this number is used
759 * only for the "X messages (Y unseen)" notification. Accordingly
760 * it doesn't matter much that it can be wrong (e.g. if we see an
761 * UNSEEN response but not all messages above the first UNSEEN one
764 if (unseen >= 0) /* optional, but better if we see it */
765 *newp = count - unseen + 1;
766 else if (recent >= 0) /* mandatory */
769 *newp = -1; /* should never happen, RECENT is mandatory */
776 static int imap_getsizes(int sock, int count, int *sizes)
777 /* capture the sizes of all messages */
779 char buf [MSGBUFSIZE+1];
782 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
783 * won't accept 1:1 as valid set syntax. Some implementors
784 * should be taken out and shot for excessive anality.
787 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
789 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
794 if ((ok = gen_recv(sock, buf, sizeof(buf))))
796 if (strstr(buf, "OK"))
798 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
799 sizes[num - 1] = size;
805 static int imap_is_old(int sock, struct query *ctl, int number)
806 /* is the given message old? */
810 /* expunges change the fetch numbers */
813 if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
819 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
820 /* request headers of nth message */
822 char buf [MSGBUFSIZE+1];
825 /* expunges change the fetch numbers */
829 * This is blessed by RFC 1176, RFC1730, RFC2060.
830 * According to the RFCs, it should *not* set the \Seen flag.
832 gen_send(sock, "FETCH %d RFC822.HEADER", number);
834 /* looking for FETCH response */
838 if ((ok = gen_recv(sock, buf, sizeof(buf))))
841 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
849 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
850 /* request body of nth message */
852 char buf [MSGBUFSIZE+1], *cp;
855 /* expunges change the fetch numbers */
859 * If we're using IMAP4, we can fetch the message without setting its
860 * seen flag. This is good! It means that if the protocol exchange
861 * craps out during the message, it will still be marked `unseen' on
864 * However...*don't* do this if we're using keep to suppress deletion!
865 * In that case, marking the seen flag is the only way to prevent the
866 * message from being re-fetched on subsequent runs.
868 switch (imap_version)
870 case IMAP4rev1: /* RFC 2060 */
872 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
874 gen_send(sock, "FETCH %d BODY[TEXT]", number);
877 case IMAP4: /* RFC 1730 */
879 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
881 gen_send(sock, "FETCH %d RFC822.TEXT", number);
884 default: /* RFC 1176 */
885 gen_send(sock, "FETCH %d RFC822.TEXT", number);
889 /* looking for FETCH response */
893 if ((ok = gen_recv(sock, buf, sizeof(buf))))
896 (sscanf(buf+2, "%d FETCH", &num) != 1);
901 /* try to extract a length */
902 if ((cp = strchr(buf, '{')))
903 *lenp = atoi(cp + 1);
910 static int imap_trail(int sock, struct query *ctl, int number)
911 /* discard tail of FETCH response after reading message text */
913 /* expunges change the fetch numbers */
914 /* number -= expunged; */
918 char buf[MSGBUFSIZE+1];
921 if ((ok = gen_recv(sock, buf, sizeof(buf))))
924 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
925 if (strstr(buf, "OK"))
932 static int imap_delete(int sock, struct query *ctl, int number)
933 /* set delete flag for given message */
937 /* expunges change the fetch numbers */
941 * Use SILENT if possible as a minor throughput optimization.
942 * Note: this has been dropped from IMAP4rev1.
944 if ((ok = gen_transact(sock,
945 imap_version == IMAP4
946 ? "STORE %d +FLAGS.SILENT (\\Deleted)"
947 : "STORE %d +FLAGS (\\Deleted)",
954 * We do an expunge after ctl->expunge messages, rather than
955 * just before quit, so that a line hit during a long session
956 * won't result in lots of messages being fetched again during
959 if (NUM_NONZERO(ctl->expunge) && (deletions % ctl->expunge) == 0)
960 internal_expunge(sock);
965 static int imap_logout(int sock, struct query *ctl)
966 /* send logout command */
968 /* if expunges after deletion have been suppressed, ship one now */
969 if (NUM_SPECIFIED(ctl->expunge) && NUM_ZERO(ctl->expunge) && deletions)
970 internal_expunge(sock);
972 return(gen_transact(sock, "LOGOUT"));
975 const static struct method imap =
977 "IMAP", /* Internet Message Access Protocol */
981 143, /* standard IMAP2bis/IMAP4 port */
983 TRUE, /* this is a tagged protocol */
984 FALSE, /* no message delimiter */
985 imap_ok, /* parse command response */
986 imap_canonicalize, /* deal with embedded slashes and spaces */
987 imap_getauth, /* get authorization */
988 imap_getrange, /* query range of messages */
989 imap_getsizes, /* get sizes of messages (used for --limit option */
990 imap_is_old, /* no UID check */
991 imap_fetch_headers, /* request given message headers */
992 imap_fetch_body, /* request given message body */
993 imap_trail, /* eat message trailer */
994 imap_delete, /* delete the message */
995 imap_logout, /* expunge and exit */
996 TRUE, /* yes, we can re-poll */
999 int doIMAP(struct query *ctl)
1000 /* retrieve messages using IMAP Version 2bis or Version 4 */
1002 return(do_protocol(ctl, &imap));
1005 /* imap.c ends here */