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])
24 #endif /* KERBEROS_V4 */
26 extern char *strstr(); /* needed on sysV68 R3V7.1. */
28 /* imap_version values */
29 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
30 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
31 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
33 static int count, seen, recent, unseen, deletecount, imap_version;
35 int imap_ok (int sock, char *argbuf)
36 /* parse command response */
38 char buf [POPBUFSIZE+1];
44 if ((ok = gen_recv(sock, buf, sizeof(buf))))
47 /* interpret untagged status responses */
48 if (strstr(buf, "EXISTS"))
50 if (strstr(buf, "RECENT"))
52 if (strstr(buf, "UNSEEN"))
57 * Handle both "* 42 UNSEEN" (if tha ever happens) and
58 * "* OK [UNSEEN 42] 42". Note that what this gets us is
59 * a minimum index, not a count.
62 for (cp = buf; *cp && !isdigit(*cp); cp++)
68 if (strstr(buf, "FLAGS"))
69 seen = (strstr(buf, "Seen") != (char *)NULL);
71 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
83 for (cp = buf; !isspace(*cp); cp++)
88 if (strncmp(cp, "OK", 2) == 0)
93 else if (strncmp(cp, "BAD", 2) == 0)
103 #elif SIZEOF_SHORT == 4
105 #elif SIZEOF_LONG == 4
108 #error Cannot deduce a 32-bit-type
111 static int do_rfc1731(int sock, struct query *ctl, char *buf)
112 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
115 char buf1[4096], buf2[4096];
119 } challenge1, challenge2;
120 char srvinst[INST_SZ];
122 char srvrealm[REALM_SZ];
123 KTEXT_ST authenticator;
124 CREDENTIALS credentials;
125 char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
126 char tktinst[INST_SZ];
127 char tktrealm[REALM_SZ];
129 des_key_schedule schedule;
131 gen_send(sock, "AUTHENTICATE KERBEROS_V4");
133 /* The data encoded in the first ready response contains a random
134 * 32-bit number in network byte order. The client should respond
135 * with a Kerberos ticket and an authenticator for the principal
136 * "imap.hostname@realm", where "hostname" is the first component
137 * of the host name of the server with all letters in lower case
138 * and where "realm" is the Kerberos realm of the server. The
139 * encrypted checksum field included within the Kerberos
140 * authenticator should contain the server provided 32-bit number
141 * in network byte order.
144 if (result = gen_recv(sock, buf1, sizeof buf1)) {
148 len = from64tobits(challenge1.cstr, buf1);
150 error(0, -1, "could not decode initial BASE64 challenge");
154 /* Client responds with a Kerberos ticket and an authenticator for
155 * the principal "imap.hostname@realm" where "hostname" is the
156 * first component of the host name of the server with all letters
157 * in lower case and where "realm" is the Kerberos realm of the
158 * server. The encrypted checksum field included within the
159 * Kerberos authenticator should contain the server-provided
160 * 32-bit number in network byte order.
163 strncpy(srvinst, ctl->server.names->id, (sizeof srvinst)-1);
164 srvinst[(sizeof srvinst)-1] = '\0';
165 for (p = srvinst; *p; p++) {
171 strncpy(srvrealm, krb_realmofhost(srvinst), (sizeof srvrealm)-1);
172 srvrealm[(sizeof srvrealm)-1] = '\0';
173 if (p = strchr(srvinst, '.')) {
177 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
179 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
183 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
185 error(0, -1, "krb_get_cred: %s", krb_get_err_text(result));
189 memcpy(session, credentials.session, sizeof session);
190 memset(&credentials, 0, sizeof credentials);
191 des_key_sched(session, schedule);
193 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
195 error(0, -1, "krb_get_tf_fullname: %s", krb_get_err_text(result));
199 if (strcmp(tktuser, user) != 0) {
200 error(0, -1, "principal %s in ticket does not match -u %s", tktuser,
206 error(0, 0, "non-null instance (%s) might cause strange behavior",
208 strcat(tktuser, ".");
209 strcat(tktuser, tktinst);
212 if (strcmp(tktrealm, srvrealm) != 0) {
213 strcat(tktuser, "@");
214 strcat(tktuser, tktrealm);
217 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
220 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
224 to64frombits(buf1, authenticator.dat, authenticator.length);
225 if (outlevel == O_VERBOSE) {
226 error(0, 0, "IMAP> %s", buf1);
228 SockWrite(sock, buf1, strlen(buf1));
229 SockWrite(sock, "\r\n", 2);
231 /* Upon decrypting and verifying the ticket and authenticator, the
232 * server should verify that the contained checksum field equals
233 * the original server provided random 32-bit number. Should the
234 * verification be successful, the server must add one to the
235 * checksum and construct 8 octets of data, with the first four
236 * octets containing the incremented checksum in network byte
237 * order, the fifth octet containing a bit-mask specifying the
238 * protection mechanisms supported by the server, and the sixth
239 * through eighth octets containing, in network byte order, the
240 * maximum cipher-text buffer size the server is able to receive.
241 * The server must encrypt the 8 octets of data in the session key
242 * and issue that encrypted data in a second ready response. The
243 * client should consider the server authenticated if the first
244 * four octets the un-encrypted data is equal to one plus the
245 * checksum it previously sent.
248 if (result = gen_recv(sock, buf1, sizeof buf1))
251 /* The client must construct data with the first four octets
252 * containing the original server-issued checksum in network byte
253 * order, the fifth octet containing the bit-mask specifying the
254 * selected protection mechanism, the sixth through eighth octets
255 * containing in network byte order the maximum cipher-text buffer
256 * size the client is able to receive, and the following octets
257 * containing a user name string. The client must then append
258 * from one to eight octets so that the length of the data is a
259 * multiple of eight octets. The client must then PCBC encrypt the
260 * data with the session key and respond to the second ready
261 * response with the encrypted data. The server decrypts the data
262 * and verifies the contained checksum. The username field
263 * identifies the user for whom subsequent IMAP operations are to
264 * be performed; the server must verify that the principal
265 * identified in the Kerberos ticket is authorized to connect as
266 * that user. After these verifications, the authentication
267 * process is complete.
270 len = from64tobits(buf2, buf1);
272 error(0, -1, "could not decode BASE64 ready response");
276 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
277 memcpy(challenge2.cstr, buf2, 4);
278 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
279 error(0, -1, "challenge mismatch");
283 memset(authenticator.dat, 0, sizeof authenticator.dat);
285 result = htonl(challenge1.cint);
286 memcpy(authenticator.dat, &result, sizeof result);
288 /* The protection mechanisms and their corresponding bit-masks are as
291 * 1 No protection mechanism
292 * 2 Integrity (krb_mk_safe) protection
293 * 4 Privacy (krb_mk_priv) protection
295 authenticator.dat[4] = 1;
297 len = strlen(tktuser);
298 strncpy(authenticator.dat+8, tktuser, len);
299 authenticator.length = len + 8 + 1;
300 while (authenticator.length & 7) {
301 authenticator.length++;
303 des_pcbc_encrypt((des_cblock *)authenticator.dat,
304 (des_cblock *)authenticator.dat, authenticator.length, schedule,
307 to64frombits(buf1, authenticator.dat, authenticator.length);
308 if (outlevel == O_VERBOSE) {
309 error(0, 0, "IMAP> %s", buf1);
311 SockWrite(sock, buf1, strlen(buf1));
312 SockWrite(sock, "\r\n", 2);
314 if (result = gen_recv(sock, buf1, sizeof buf1))
317 if (strstr(buf1, "OK")) {
324 #endif /* KERBEROS_V4 */
326 int imap_getauth(int sock, struct query *ctl, char *buf)
327 /* apply for connection authorization */
329 char rbuf [POPBUFSIZE+1];
334 if (ctl->server.protocol != P_IMAP_K4)
335 #endif /* KERBEROS_V4 */
336 /* try to get authorized */
337 ok = gen_transact(sock,
338 "LOGIN %s \"%s\"", ctl->remotename, ctl->password);
343 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
344 gen_send(sock, "CAPABILITY");
345 if ((ok = gen_recv(sock, rbuf, sizeof(rbuf))))
347 if (strstr(rbuf, "BAD"))
349 imap_version = IMAP2;
350 if (outlevel == O_VERBOSE)
351 error(0, 0, "Protocol identified as IMAP2 or IMAP2BIS");
353 /* UW-IMAP server 10.173 notifies in all caps */
354 else if (strstr(rbuf, "IMAP4rev1") || strstr(rbuf, "IMAP4REV1"))
356 imap_version = IMAP4rev1;
357 if (outlevel == O_VERBOSE)
358 error(0, 0, "Protocol identified as IMAP4 rev 1");
362 imap_version = IMAP4;
363 if (outlevel == O_VERBOSE)
364 error(0, 0, "Protocol identified as IMAP4 rev 0");
367 peek_capable = (imap_version >= IMAP4);
370 if (strstr(rbuf, "AUTH=KERBEROS_V4"))
373 if (outlevel == O_VERBOSE)
374 error(0, 0, "KERBEROS_V4 authentication is supported");
377 /* eat OK response */
378 if ((ok = gen_recv(sock, rbuf, sizeof(rbuf))))
381 if (!strstr(rbuf, "OK"))
384 if ((imap_version >= IMAP4) && (ctl->server.protocol == P_IMAP_K4))
388 error(0, -1, "Required KERBEROS_V4 capability not supported by server");
392 if ((ok = do_rfc1731(sock, ctl, buf)))
394 if (outlevel == O_VERBOSE)
395 error(0, 0, "IMAP> *");
396 SockWrite(sock, "*\r\n", 3);
400 #endif /* KERBEROS_V4 */
405 static int imap_getrange(int sock,
408 int *countp, int *newp)
409 /* get range of messages to be fetched */
413 /* find out how many messages are waiting */
414 recent = unseen = -1;
415 ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
418 error(0, 0, "mailbox selection failed");
425 * Note: because IMAP has an is_old method, this number is used
426 * only for the "X messages (Y unseen)" notification. Accordingly
427 * it doesn't matter much that it can be wrong (e.g. if we see an
428 * UNSEEN response but not all messages above the first UNSEEN one
431 if (unseen >= 0) /* optional, but better if we see it */
432 *newp = count - unseen + 1;
433 else if (recent >= 0) /* mandatory */
436 *newp = -1; /* should never happen, RECENT is mandatory */
443 static int imap_getsizes(int sock, int count, int *sizes)
444 /* capture the sizes of all messages */
446 char buf [POPBUFSIZE+1];
448 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
449 while (SockRead(sock, buf, sizeof(buf)))
453 if ((ok = gen_recv(sock, buf, sizeof(buf))))
455 if (strstr(buf, "OK"))
457 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
458 sizes[num - 1] = size;
466 static int imap_is_old(int sock, struct query *ctl, int number)
467 /* is the given message old? */
471 /* expunges change the fetch numbers */
472 number -= deletecount;
474 if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
480 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
481 /* request headers of nth message */
483 char buf [POPBUFSIZE+1];
486 /* expunges change the fetch numbers */
487 number -= deletecount;
490 * This is blessed by RFC 1176, RFC1730, RFC2060.
491 * According to the RFCs, it should *not* set the \Seen flag.
493 gen_send(sock, "FETCH %d RFC822.HEADER", number);
495 /* looking for FETCH response */
499 if ((ok = gen_recv(sock, buf, sizeof(buf))))
502 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
510 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
511 /* request body of nth message */
513 char buf [POPBUFSIZE+1], *cp;
516 /* expunges change the fetch numbers */
517 number -= deletecount;
520 * If we're using IMAP4, we can fetch the message without setting its
521 * seen flag. This is good! It means that if the protocol exchange
522 * craps out during the message, it will still be marked `unseen' on
525 * However...*don't* do this if we're using keep to suppress deletion!
526 * In that case, marking the seen flag is the only way to prevent the
527 * message from being re-fetched on subsequent runs.
529 switch (imap_version)
531 case IMAP4rev1: /* RFC 2060 */
533 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
535 gen_send(sock, "FETCH %d BODY[TEXT]", number);
538 case IMAP4: /* RFC 1730 */
540 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
542 gen_send(sock, "FETCH %d RFC822.TEXT", number);
545 default: /* RFC 1176 */
546 gen_send(sock, "FETCH %d RFC822.TEXT", number);
550 /* looking for FETCH response */
554 if ((ok = gen_recv(sock, buf, sizeof(buf))))
557 (sscanf(buf+2, "%d FETCH", &num) != 1);
562 /* try to extract a length */
563 if ((cp = strchr(buf, '{')))
564 *lenp = atoi(cp + 1);
571 static int imap_trail(int sock, struct query *ctl, int number)
572 /* discard tail of FETCH response after reading message text */
574 /* expunges change the fetch numbers */
575 /* number -= deletecount; */
579 char buf[POPBUFSIZE+1];
582 if ((ok = gen_recv(sock, buf, sizeof(buf))))
584 if (strstr(buf, "OK FETCH"))
591 static int imap_delete(int sock, struct query *ctl, int number)
592 /* set delete flag for given message */
596 /* expunges change the fetch numbers */
597 number -= deletecount;
600 * Use SILENT if possible as a minor throughput optimization.
601 * Note: this has been dropped from IMAP4rev1.
603 if ((ok = gen_transact(sock,
604 imap_version == IMAP4
605 ? "STORE %d +FLAGS.SILENT (\\Deleted)"
606 : "STORE %d +FLAGS (\\Deleted)",
611 * We do an expunge after each message, rather than just before quit,
612 * so that a line hit during a long session won't result in lots of
613 * messages being fetched again during the next session.
615 if ((ok = gen_transact(sock, "EXPUNGE")))
623 const static struct method imap =
625 "IMAP", /* Internet Message Access Protocol */
626 143, /* standard IMAP2bis/IMAP4 port */
627 TRUE, /* this is a tagged protocol */
628 FALSE, /* no message delimiter */
629 FALSE, /* fetch response size is reliable */
630 imap_ok, /* parse command response */
631 imap_getauth, /* get authorization */
632 imap_getrange, /* query range of messages */
633 imap_getsizes, /* grab message sizes */
634 imap_is_old, /* no UID check */
635 imap_fetch_headers, /* request given message headers */
636 imap_fetch_body, /* request given message body */
637 imap_trail, /* eat message trailer */
638 imap_delete, /* delete the message */
639 "LOGOUT", /* the IMAP exit command */
642 int doIMAP(struct query *ctl)
643 /* retrieve messages using IMAP Version 2bis or Version 4 */
645 return(do_protocol(ctl, &imap));
648 /* imap.c ends here */