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", 3) == 0)
118 else if (strncmp(cp, "NO", 2) == 0)
126 static int do_otp(int sock, struct query *ctl)
130 char challenge[OPIE_CHALLENGE_MAX+1];
131 char response[OPIE_RESPONSE_MAX+1];
133 gen_send(sock, "AUTHENTICATE X-OTP");
135 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
138 if ((i = from64tobits(challenge, buffer)) < 0) {
139 error(0, -1, "Could not decode initial BASE64 challenge");
144 to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
146 if (outlevel >= O_MONITOR)
147 error(0, 0, "IMAP> %s", buffer);
148 SockWrite(sock, buffer, strlen(buffer));
149 SockWrite(sock, "\r\n", 2);
151 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
154 if ((i = from64tobits(challenge, buffer)) < 0) {
155 error(0, -1, "Could not decode OTP challenge");
159 rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
160 if ((rval == -2) && !run.poll_interval) {
161 char secret[OPIE_SECRET_MAX+1];
162 fprintf(stderr, "Secret pass phrase: ");
163 if (opiereadpass(secret, sizeof(secret), 0))
164 rval = opiegenerator(challenge, secret, response);
165 memset(secret, 0, sizeof(secret));
171 to64frombits(buffer, response, strlen(response));
173 if (outlevel >= O_MONITOR)
174 error(0, 0, "IMAP> %s", buffer);
175 SockWrite(sock, buffer, strlen(buffer));
176 SockWrite(sock, "\r\n", 2);
178 if (rval = gen_recv(sock, buffer, sizeof(buffer)))
181 if (strstr(buffer, "OK"))
191 #elif SIZEOF_SHORT == 4
193 #elif SIZEOF_LONG == 4
196 #error Cannot deduce a 32-bit-type
199 static int do_rfc1731(int sock, char *truename)
200 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
203 char buf1[4096], buf2[4096];
207 } challenge1, challenge2;
208 char srvinst[INST_SZ];
210 char srvrealm[REALM_SZ];
211 KTEXT_ST authenticator;
212 CREDENTIALS credentials;
213 char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
214 char tktinst[INST_SZ];
215 char tktrealm[REALM_SZ];
217 des_key_schedule schedule;
219 gen_send(sock, "AUTHENTICATE KERBEROS_V4");
221 /* The data encoded in the first ready response contains a random
222 * 32-bit number in network byte order. The client should respond
223 * with a Kerberos ticket and an authenticator for the principal
224 * "imap.hostname@realm", where "hostname" is the first component
225 * of the host name of the server with all letters in lower case
226 * and where "realm" is the Kerberos realm of the server. The
227 * encrypted checksum field included within the Kerberos
228 * authenticator should contain the server provided 32-bit number
229 * in network byte order.
232 if (result = gen_recv(sock, buf1, sizeof buf1)) {
236 len = from64tobits(challenge1.cstr, buf1);
238 error(0, -1, "could not decode initial BASE64 challenge");
242 /* Client responds with a Kerberos ticket and an authenticator for
243 * the principal "imap.hostname@realm" where "hostname" is the
244 * first component of the host name of the server with all letters
245 * in lower case and where "realm" is the Kerberos realm of the
246 * server. The encrypted checksum field included within the
247 * Kerberos authenticator should contain the server-provided
248 * 32-bit number in network byte order.
251 strncpy(srvinst, truename, (sizeof srvinst)-1);
252 srvinst[(sizeof srvinst)-1] = '\0';
253 for (p = srvinst; *p; p++) {
259 strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
260 srvrealm[(sizeof srvrealm)-1] = '\0';
261 if (p = strchr(srvinst, '.')) {
265 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
267 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
271 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
273 error(0, -1, "krb_get_cred: %s", krb_get_err_text(result));
277 memcpy(session, credentials.session, sizeof session);
278 memset(&credentials, 0, sizeof credentials);
279 des_key_sched(session, schedule);
281 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
283 error(0, -1, "krb_get_tf_fullname: %s", krb_get_err_text(result));
287 if (strcmp(tktuser, user) != 0) {
288 error(0, -1, "principal %s in ticket does not match -u %s", tktuser,
294 error(0, 0, "non-null instance (%s) might cause strange behavior",
296 strcat(tktuser, ".");
297 strcat(tktuser, tktinst);
300 if (strcmp(tktrealm, srvrealm) != 0) {
301 strcat(tktuser, "@");
302 strcat(tktuser, tktrealm);
305 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
308 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
312 to64frombits(buf1, authenticator.dat, authenticator.length);
313 if (outlevel >= O_MONITOR) {
314 error(0, 0, "IMAP> %s", buf1);
316 SockWrite(sock, buf1, strlen(buf1));
317 SockWrite(sock, "\r\n", 2);
319 /* Upon decrypting and verifying the ticket and authenticator, the
320 * server should verify that the contained checksum field equals
321 * the original server provided random 32-bit number. Should the
322 * verification be successful, the server must add one to the
323 * checksum and construct 8 octets of data, with the first four
324 * octets containing the incremented checksum in network byte
325 * order, the fifth octet containing a bit-mask specifying the
326 * protection mechanisms supported by the server, and the sixth
327 * through eighth octets containing, in network byte order, the
328 * maximum cipher-text buffer size the server is able to receive.
329 * The server must encrypt the 8 octets of data in the session key
330 * and issue that encrypted data in a second ready response. The
331 * client should consider the server authenticated if the first
332 * four octets the un-encrypted data is equal to one plus the
333 * checksum it previously sent.
336 if (result = gen_recv(sock, buf1, sizeof buf1))
339 /* The client must construct data with the first four octets
340 * containing the original server-issued checksum in network byte
341 * order, the fifth octet containing the bit-mask specifying the
342 * selected protection mechanism, the sixth through eighth octets
343 * containing in network byte order the maximum cipher-text buffer
344 * size the client is able to receive, and the following octets
345 * containing a user name string. The client must then append
346 * from one to eight octets so that the length of the data is a
347 * multiple of eight octets. The client must then PCBC encrypt the
348 * data with the session key and respond to the second ready
349 * response with the encrypted data. The server decrypts the data
350 * and verifies the contained checksum. The username field
351 * identifies the user for whom subsequent IMAP operations are to
352 * be performed; the server must verify that the principal
353 * identified in the Kerberos ticket is authorized to connect as
354 * that user. After these verifications, the authentication
355 * process is complete.
358 len = from64tobits(buf2, buf1);
360 error(0, -1, "could not decode BASE64 ready response");
364 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
365 memcpy(challenge2.cstr, buf2, 4);
366 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
367 error(0, -1, "challenge mismatch");
371 memset(authenticator.dat, 0, sizeof authenticator.dat);
373 result = htonl(challenge1.cint);
374 memcpy(authenticator.dat, &result, sizeof result);
376 /* The protection mechanisms and their corresponding bit-masks are as
379 * 1 No protection mechanism
380 * 2 Integrity (krb_mk_safe) protection
381 * 4 Privacy (krb_mk_priv) protection
383 authenticator.dat[4] = 1;
385 len = strlen(tktuser);
386 strncpy(authenticator.dat+8, tktuser, len);
387 authenticator.length = len + 8 + 1;
388 while (authenticator.length & 7) {
389 authenticator.length++;
391 des_pcbc_encrypt((des_cblock *)authenticator.dat,
392 (des_cblock *)authenticator.dat, authenticator.length, schedule,
395 to64frombits(buf1, authenticator.dat, authenticator.length);
396 if (outlevel >= O_MONITOR) {
397 error(0, 0, "IMAP> %s", buf1);
399 SockWrite(sock, buf1, strlen(buf1));
400 SockWrite(sock, "\r\n", 2);
402 if (result = gen_recv(sock, buf1, sizeof buf1))
405 if (strstr(buf1, "OK")) {
412 #endif /* KERBEROS_V4 */
415 #define GSSAUTH_P_NONE 1
416 #define GSSAUTH_P_INTEGRITY 2
417 #define GSSAUTH_P_PRIVACY 4
419 static int do_gssauth(int sock, char *hostname, char *username)
421 gss_buffer_desc request_buf, send_token;
422 gss_buffer_t sec_token;
423 gss_name_t target_name;
424 gss_ctx_id_t context;
428 OM_uint32 maj_stat, min_stat;
429 char buf1[8192], buf2[8192], server_conf_flags;
430 unsigned long buf_size;
433 /* first things first: get an imap ticket for host */
434 sprintf(buf1, "imap@%s", hostname);
435 request_buf.value = buf1;
436 request_buf.length = strlen(buf1) + 1;
437 maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name,
439 if (maj_stat != GSS_S_COMPLETE) {
440 error(0, -1, "Couldn't get service name for [%s]", buf1);
443 else if (outlevel >= O_DEBUG) {
444 maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
446 error(0, 0, "Using service name [%s]",request_buf.value);
447 maj_stat = gss_release_buffer(&min_stat, &request_buf);
450 gen_send(sock, "AUTHENTICATE GSSAPI");
452 /* upon receipt of the GSSAPI authentication request, server returns
453 * null data ready response. */
454 if (result = gen_recv(sock, buf1, sizeof buf1)) {
458 /* now start the security context initialisation loop... */
459 sec_token = GSS_C_NO_BUFFER;
460 context = GSS_C_NO_CONTEXT;
461 if (outlevel >= O_VERBOSE)
462 error(0,0,"Sending credentials");
464 maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL,
465 &context, target_name, NULL, 0, 0, NULL, sec_token, NULL,
466 &send_token, &cflags, NULL);
467 if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
468 error(0, -1,"Error exchanging credentials");
469 gss_release_name(&min_stat, &target_name);
470 /* wake up server and await NO response */
471 SockWrite(sock, "\r\n", 2);
472 if (result = gen_recv(sock, buf1, sizeof buf1))
476 to64frombits(buf1, send_token.value, send_token.length);
477 gss_release_buffer(&min_stat, &send_token);
478 SockWrite(sock, buf1, strlen(buf1));
479 SockWrite(sock, "\r\n", 2);
480 if (outlevel >= O_MONITOR)
481 error(0,0,"IMAP> %s", buf1);
482 if (maj_stat == GSS_S_CONTINUE_NEEDED) {
483 if (result = gen_recv(sock, buf1, sizeof buf1)) {
484 gss_release_name(&min_stat, &target_name);
487 request_buf.length = from64tobits(buf2, buf1 + 2);
488 request_buf.value = buf2;
489 sec_token = &request_buf;
491 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
492 gss_release_name(&min_stat, &target_name);
494 /* get security flags and buffer size */
495 if (result = gen_recv(sock, buf1, sizeof buf1)) {
498 request_buf.length = from64tobits(buf2, buf1 + 2);
499 request_buf.value = buf2;
501 maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
503 if (maj_stat != GSS_S_COMPLETE) {
504 error(0,-1,"Couldn't unwrap security level data");
505 gss_release_buffer(&min_stat, &send_token);
508 if (outlevel >= O_DEBUG)
509 error(0,0,"Credential exchange complete");
510 /* first octet is security levels supported. We want none, for now */
511 server_conf_flags = ((char *)send_token.value)[0];
512 if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
513 error(0,-1,"Server requires integrity and/or privacy");
514 gss_release_buffer(&min_stat, &send_token);
517 ((char *)send_token.value)[0] = 0;
518 buf_size = ntohl(*((long *)send_token.value));
519 /* we don't care about buffer size if we don't wrap data */
520 gss_release_buffer(&min_stat, &send_token);
521 if (outlevel >= O_DEBUG) {
522 error(0,0,"Unwrapped security level flags: %s%s%s",
523 server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
524 server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
525 server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
526 error(0,0,"Maximum GSS token size is %ld",buf_size);
529 /* now respond in kind (hack!!!) */
530 buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
531 memcpy(buf1, &buf_size, 4);
532 buf1[0] = GSSAUTH_P_NONE;
533 strcpy(buf1+4, username); /* server decides if princ is user */
534 request_buf.length = 4 + strlen(username) + 1;
535 request_buf.value = buf1;
536 maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
537 &cflags, &send_token);
538 if (maj_stat != GSS_S_COMPLETE) {
539 error(0,-1,"Error creating security level request");
542 to64frombits(buf1, send_token.value, send_token.length);
543 if (outlevel >= O_DEBUG) {
544 error(0,0,"Requesting authorisation as %s", username);
545 error(0,0,"IMAP> %s",buf1);
547 SockWrite(sock, buf1, strlen(buf1));
548 SockWrite(sock, "\r\n", 2);
550 /* we should be done. Get status and finish up */
551 if (result = gen_recv(sock, buf1, sizeof buf1))
553 if (strstr(buf1, "OK")) {
554 /* flush security context */
555 if (outlevel >= O_DEBUG)
556 error(0, 0, "Releasing GSS credentials");
557 maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
558 if (maj_stat != GSS_S_COMPLETE) {
559 error(0, -1, "Error releasing credentials");
562 /* send_token may contain a notification to the server to flush
563 * credentials. RFC 1731 doesn't specify what to do, and since this
564 * support is only for authentication, we'll assume the server
565 * knows enough to flush its own credentials */
566 gss_release_buffer(&min_stat, &send_token);
574 int imap_canonicalize(char *result, char *passwd)
575 /* encode an IMAP password as per RFC1730's quoting conventions */
580 for (i = 0; i < strlen(passwd); i++)
582 if ((passwd[i] == '\\') || (passwd[i] == '"'))
584 result[j++] = passwd[i];
591 int imap_getauth(int sock, struct query *ctl, char *greeting)
592 /* apply for connection authorization */
595 char password[PASSWORDLEN*2];
597 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
598 capabilities[0] = '\0';
599 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
601 /* UW-IMAP server 10.173 notifies in all caps */
602 if (strstr(capabilities, "IMAP4REV1"))
604 imap_version = IMAP4rev1;
605 if (outlevel >= O_DEBUG)
606 error(0, 0, "Protocol identified as IMAP4 rev 1");
610 imap_version = IMAP4;
611 if (outlevel >= O_DEBUG)
612 error(0, 0, "Protocol identified as IMAP4 rev 0");
615 else if (ok == PS_ERROR)
617 imap_version = IMAP2;
618 if (outlevel >= O_DEBUG)
619 error(0, 0, "Protocol identified as IMAP2 or IMAP2BIS");
624 peek_capable = (imap_version >= IMAP4);
627 if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
629 if (outlevel >= O_DEBUG)
630 error(0, 0, "OTP authentication is supported");
631 if (do_otp(sock, ctl) == PS_SUCCESS)
637 if (strstr(capabilities, "AUTH=GSSAPI"))
639 if (ctl->server.protocol == P_IMAP_GSS)
641 if (outlevel >= O_DEBUG)
642 error(0, 0, "GSS authentication is supported");
643 return do_gssauth(sock, ctl->server.truename, ctl->remotename);
646 else if (ctl->server.protocol == P_IMAP_GSS)
648 error(0,-1, "Required GSS capability not supported by server");
654 if (strstr(capabilities, "AUTH=KERBEROS_V4"))
656 if (outlevel >= O_DEBUG)
657 error(0, 0, "KERBEROS_V4 authentication is supported");
659 if (ctl->server.protocol == P_IMAP_K4)
661 if ((ok = do_rfc1731(sock, ctl->server.truename)))
663 if (outlevel >= O_MONITOR)
664 error(0, 0, "IMAP> *");
665 SockWrite(sock, "*\r\n", 3);
670 /* else fall through to ordinary AUTH=LOGIN case */
672 else if (ctl->server.protocol == P_IMAP_K4)
674 error(0,-1, "Required KERBEROS_V4 capability not supported by server");
677 #endif /* KERBEROS_V4 */
679 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
680 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
681 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
682 error(0,-1, "Required LOGIN capability not supported by server");
685 #endif /* __UNUSED__ */
687 imap_canonicalize(password, ctl->password);
688 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
695 static int internal_expunge(int sock)
696 /* ship an expunge, resetting associated counters */
700 if ((ok = gen_transact(sock, "EXPUNGE")))
703 expunged += deletions;
706 #ifdef IMAP_UID /* not used */
708 #endif /* IMAP_UID */
713 static int imap_getrange(int sock,
716 int *countp, int *newp, int *bytes)
717 /* get range of messages to be fetched */
721 /* find out how many messages are waiting */
722 *bytes = recent = unseen = -1;
727 * We have to have an expunge here, otherwise the re-poll will
728 * infinite-loop picking up un-expunged message.
731 if (deletions && ctl->expunge > 1)
732 internal_expunge(sock);
734 if (ok || gen_transact(sock, "NOOP"))
736 error(0, 0, "re-poll failed");
739 else if (count == -1) /* no EXISTS response to NOOP */
748 ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
750 ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
753 error(0, 0, "mailbox selection failed");
761 * Note: because IMAP has an is_old method, this number is used
762 * only for the "X messages (Y unseen)" notification. Accordingly
763 * it doesn't matter much that it can be wrong (e.g. if we see an
764 * UNSEEN response but not all messages above the first UNSEEN one
767 if (unseen >= 0) /* optional, but better if we see it */
768 *newp = count - unseen + 1;
769 else if (recent >= 0) /* mandatory */
772 *newp = -1; /* should never happen, RECENT is mandatory */
779 static int imap_getsizes(int sock, int count, int *sizes)
780 /* capture the sizes of all messages */
782 char buf [MSGBUFSIZE+1];
785 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
786 * won't accept 1:1 as valid set syntax. Some implementors
787 * should be taken out and shot for excessive anality.
790 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
792 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
797 if ((ok = gen_recv(sock, buf, sizeof(buf))))
799 if (strstr(buf, "OK"))
801 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
802 sizes[num - 1] = size;
808 static int imap_is_old(int sock, struct query *ctl, int number)
809 /* is the given message old? */
813 /* expunges change the fetch numbers */
816 if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
822 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
823 /* request headers of nth message */
825 char buf [MSGBUFSIZE+1];
828 /* expunges change the fetch numbers */
832 * This is blessed by RFC 1176, RFC1730, RFC2060.
833 * According to the RFCs, it should *not* set the \Seen flag.
835 gen_send(sock, "FETCH %d RFC822.HEADER", number);
837 /* looking for FETCH response */
841 if ((ok = gen_recv(sock, buf, sizeof(buf))))
844 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
852 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
853 /* request body of nth message */
855 char buf [MSGBUFSIZE+1], *cp;
858 /* expunges change the fetch numbers */
862 * If we're using IMAP4, we can fetch the message without setting its
863 * seen flag. This is good! It means that if the protocol exchange
864 * craps out during the message, it will still be marked `unseen' on
867 * However...*don't* do this if we're using keep to suppress deletion!
868 * In that case, marking the seen flag is the only way to prevent the
869 * message from being re-fetched on subsequent runs.
871 switch (imap_version)
873 case IMAP4rev1: /* RFC 2060 */
875 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
877 gen_send(sock, "FETCH %d BODY[TEXT]", number);
880 case IMAP4: /* RFC 1730 */
882 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
884 gen_send(sock, "FETCH %d RFC822.TEXT", number);
887 default: /* RFC 1176 */
888 gen_send(sock, "FETCH %d RFC822.TEXT", number);
892 /* looking for FETCH response */
896 if ((ok = gen_recv(sock, buf, sizeof(buf))))
899 (sscanf(buf+2, "%d FETCH", &num) != 1);
904 /* try to extract a length */
905 if ((cp = strchr(buf, '{')))
906 *lenp = atoi(cp + 1);
913 static int imap_trail(int sock, struct query *ctl, int number)
914 /* discard tail of FETCH response after reading message text */
916 /* expunges change the fetch numbers */
917 /* number -= expunged; */
921 char buf[MSGBUFSIZE+1];
924 if ((ok = gen_recv(sock, buf, sizeof(buf))))
927 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
928 if (strstr(buf, "OK"))
935 static int imap_delete(int sock, struct query *ctl, int number)
936 /* set delete flag for given message */
940 /* expunges change the fetch numbers */
944 * Use SILENT if possible as a minor throughput optimization.
945 * Note: this has been dropped from IMAP4rev1.
947 if ((ok = gen_transact(sock,
948 imap_version == IMAP4
949 ? "STORE %d +FLAGS.SILENT (\\Deleted)"
950 : "STORE %d +FLAGS (\\Deleted)",
957 * We do an expunge after ctl->expunge messages, rather than
958 * just before quit, so that a line hit during a long session
959 * won't result in lots of messages being fetched again during
962 if (NUM_NONZERO(ctl->expunge) && (deletions % ctl->expunge) == 0)
963 internal_expunge(sock);
968 static int imap_logout(int sock, struct query *ctl)
969 /* send logout command */
971 /* if expunges after deletion have been suppressed, ship one now */
972 if (NUM_SPECIFIED(ctl->expunge) && NUM_ZERO(ctl->expunge) && deletions)
973 internal_expunge(sock);
975 return(gen_transact(sock, "LOGOUT"));
978 const static struct method imap =
980 "IMAP", /* Internet Message Access Protocol */
984 143, /* standard IMAP2bis/IMAP4 port */
986 TRUE, /* this is a tagged protocol */
987 FALSE, /* no message delimiter */
988 imap_ok, /* parse command response */
989 imap_canonicalize, /* deal with embedded slashes and spaces */
990 imap_getauth, /* get authorization */
991 imap_getrange, /* query range of messages */
992 imap_getsizes, /* get sizes of messages (used for --limit option */
993 imap_is_old, /* no UID check */
994 imap_fetch_headers, /* request given message headers */
995 imap_fetch_body, /* request given message body */
996 imap_trail, /* eat message trailer */
997 imap_delete, /* delete the message */
998 imap_logout, /* expunge and exit */
999 TRUE, /* yes, we can re-poll */
1002 int doIMAP(struct query *ctl)
1003 /* retrieve messages using IMAP Version 2bis or Version 4 */
1005 return(do_protocol(ctl, &imap));
1008 /* imap.c ends here */