2 * imap.c -- IMAP2bis/IMAP4 protocol methods
4 * Copyright 1996 by Eric S. Raymond
6 * For license terms, see the file COPYING in this directory.
13 #if defined(STDC_HEADERS)
16 #include "fetchmail.h"
22 #endif /* KERBEROS_V4 */
24 extern char *strstr(); /* needed on sysV68 R3V7.1. */
26 /* imap_version values */
27 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
28 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
29 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
31 static int count, seen, recent, unseen, deletecount, imap_version;
33 int imap_ok (int sock, char *argbuf)
34 /* parse command response */
36 char buf [POPBUFSIZE+1];
42 if ((ok = gen_recv(sock, buf, sizeof(buf))))
45 /* interpret untagged status responses */
46 if (strstr(buf, "EXISTS"))
48 if (strstr(buf, "RECENT"))
50 if (strstr(buf, "UNSEEN"))
52 if (strstr(buf, "FLAGS"))
53 seen = (strstr(buf, "Seen") != (char *)NULL);
55 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
67 for (cp = buf; !isspace(*cp); cp++)
72 if (strncmp(cp, "OK", 2) == 0)
77 else if (strncmp(cp, "BAD", 2) == 0)
85 static int do_rfc1731(int sock, struct query *ctl, char *buf)
86 /* authenticate as per RFC1731
87 * note 32-bit integer requirement here...
88 * sizeof int must be 4!
90 * Note: Base64 conversion routines come from Cyrus IMAPd and have
91 * possibly too-restrictive redistribution requirements. See base64.c
92 * for details. Base64 is defined in RFC2045 section 6.8, "Base64
93 * Content-Transfer-Encoding", but lines must not be broken in the
98 char buf1[4096], buf2[4096];
102 } challenge1, challenge2;
103 char srvinst[INST_SZ];
105 char srvrealm[REALM_SZ];
106 KTEXT_ST authenticator;
107 CREDENTIALS credentials;
108 char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
109 char tktinst[INST_SZ];
110 char tktrealm[REALM_SZ];
112 des_key_schedule schedule;
114 gen_send(sock, "AUTHENTICATE KERBEROS_V4");
116 /* The data encoded in the first ready response contains a random
117 * 32-bit number in network byte order. The client should respond
118 * with a Kerberos ticket and an authenticator for the principal
119 * "imap.hostname@realm", where "hostname" is the first component
120 * of the host name of the server with all letters in lower case
121 * and where "realm" is the Kerberos realm of the server. The
122 * encrypted checksum field included within the Kerberos
123 * authenticator should contain the server provided 32-bit number
124 * in network byte order.
127 if (result = gen_recv(sock, buf1, sizeof buf1)) {
131 len = from64(challenge1.cstr, buf1);
133 error(0, -1, "could not decode initial BASE64 challenge");
137 /* Client responds with a Kerberos ticket and an authenticator for
138 * the principal "imap.hostname@realm" where "hostname" is the
139 * first component of the host name of the server with all letters
140 * in lower case and where "realm" is the Kerberos realm of the
141 * server. The encrypted checksum field included within the
142 * Kerberos authenticator should contain the server-provided
143 * 32-bit number in network byte order.
146 strncpy(srvinst, ctl->server.names->id, (sizeof srvinst)-1);
147 srvinst[(sizeof srvinst)-1] = '\0';
148 for (p = srvinst; *p; p++) {
154 strncpy(srvrealm, krb_realmofhost(srvinst), (sizeof srvrealm)-1);
155 srvrealm[(sizeof srvrealm)-1] = '\0';
156 if (p = strchr(srvinst, '.')) {
160 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
162 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
166 result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
168 error(0, -1, "krb_get_cred: %s", krb_get_err_text(result));
172 memcpy(session, credentials.session, sizeof session);
173 memset(&credentials, 0, sizeof credentials);
174 des_key_sched(session, schedule);
176 result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
178 error(0, -1, "krb_get_tf_fullname: %s", krb_get_err_text(result));
182 if (strcmp(tktuser, user) != 0) {
183 error(0, -1, "principal %s in ticket does not match -u %s", tktuser,
189 error(0, 0, "non-null instance (%s) might cause strange behavior",
191 strcat(tktuser, ".");
192 strcat(tktuser, tktinst);
195 if (strcmp(tktrealm, srvrealm) != 0) {
196 strcat(tktuser, "@");
197 strcat(tktuser, tktrealm);
200 result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
203 error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
207 to64(buf1, authenticator.dat, authenticator.length);
208 if (outlevel == O_VERBOSE) {
209 error(0, 0, "IMAP> %s", buf1);
211 SockWrite(sock, buf1, strlen(buf1));
212 SockWrite(sock, "\r\n", 2);
214 /* Upon decrypting and verifying the ticket and authenticator, the
215 * server should verify that the contained checksum field equals
216 * the original server provided random 32-bit number. Should the
217 * verification be successful, the server must add one to the
218 * checksum and construct 8 octets of data, with the first four
219 * octets containing the incremented checksum in network byte
220 * order, the fifth octet containing a bit-mask specifying the
221 * protection mechanisms supported by the server, and the sixth
222 * through eighth octets containing, in network byte order, the
223 * maximum cipher-text buffer size the server is able to receive.
224 * The server must encrypt the 8 octets of data in the session key
225 * and issue that encrypted data in a second ready response. The
226 * client should consider the server authenticated if the first
227 * four octets the un-encrypted data is equal to one plus the
228 * checksum it previously sent.
231 if (result = gen_recv(sock, buf1, sizeof buf1))
234 /* The client must construct data with the first four octets
235 * containing the original server-issued checksum in network byte
236 * order, the fifth octet containing the bit-mask specifying the
237 * selected protection mechanism, the sixth through eighth octets
238 * containing in network byte order the maximum cipher-text buffer
239 * size the client is able to receive, and the following octets
240 * containing a user name string. The client must then append
241 * from one to eight octets so that the length of the data is a
242 * multiple of eight octets. The client must then PCBC encrypt the
243 * data with the session key and respond to the second ready
244 * response with the encrypted data. The server decrypts the data
245 * and verifies the contained checksum. The username field
246 * identifies the user for whom subsequent IMAP operations are to
247 * be performed; the server must verify that the principal
248 * identified in the Kerberos ticket is authorized to connect as
249 * that user. After these verifications, the authentication
250 * process is complete.
253 len = from64(buf2, buf1);
255 error(0, -1, "could not decode BASE64 ready response");
259 des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
260 memcpy(challenge2.cstr, buf2, 4);
261 if (ntohl(challenge2.cint) != challenge1.cint + 1) {
262 error(0, -1, "challenge mismatch");
266 memset(authenticator.dat, 0, sizeof authenticator.dat);
268 result = htonl(challenge1.cint);
269 memcpy(authenticator.dat, &result, sizeof result);
271 /* The protection mechanisms and their corresponding bit-masks are as
274 * 1 No protection mechanism
275 * 2 Integrity (krb_mk_safe) protection
276 * 4 Privacy (krb_mk_priv) protection
278 authenticator.dat[4] = 1;
280 len = strlen(tktuser);
281 strncpy(authenticator.dat+8, tktuser, len);
282 authenticator.length = len + 8 + 1;
283 while (authenticator.length & 7) {
284 authenticator.length++;
286 des_pcbc_encrypt((des_cblock *)authenticator.dat,
287 (des_cblock *)authenticator.dat, authenticator.length, schedule,
290 to64(buf1, authenticator.dat, authenticator.length);
291 if (outlevel == O_VERBOSE) {
292 error(0, 0, "IMAP> %s", buf1);
294 SockWrite(sock, buf1, strlen(buf1));
295 SockWrite(sock, "\r\n", 2);
297 if (result = gen_recv(sock, buf1, sizeof buf1))
300 if (strstr(buf1, "OK")) {
307 #endif /* KERBEROS_V4 */
309 int imap_getauth(int sock, struct query *ctl, char *buf)
310 /* apply for connection authorization */
312 char rbuf [POPBUFSIZE+1];
317 if (ctl->server.protocol != P_IMAP_K4)
318 #endif /* KERBEROS_V4 */
319 /* try to get authorized */
320 ok = gen_transact(sock,
321 "LOGIN %s \"%s\"", ctl->remotename, ctl->password);
326 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
327 gen_send(sock, "CAPABILITY");
328 if ((ok = gen_recv(sock, rbuf, sizeof(rbuf))))
330 if (strstr(rbuf, "BAD"))
332 imap_version = IMAP2;
333 if (outlevel == O_VERBOSE)
334 error(0, 0, "Protocol identified as IMAP2 or IMAP2BIS");
336 else if (strstr(rbuf, "IMAP4rev1"))
338 imap_version = IMAP4rev1;
339 if (outlevel == O_VERBOSE)
340 error(0, 0, "Protocol identified as IMAP4 rev 1");
344 imap_version = IMAP4;
345 if (outlevel == O_VERBOSE)
346 error(0, 0, "Protocol identified as IMAP4 rev 0");
349 peek_capable = (imap_version >= IMAP4);
352 if (strstr(rbuf, "AUTH=KERBEROS_V4"))
355 if (outlevel == O_VERBOSE)
356 error(0, 0, "KERBEROS_V4 authentication is supported");
359 /* eat OK response */
360 if ((ok = gen_recv(sock, rbuf, sizeof(rbuf))))
363 if (!strstr(rbuf, "OK"))
366 if ((imap_version >= IMAP4) && (ctl->server.protocol == P_IMAP_K4))
370 error(0, -1, "Required KERBEROS_V4 capability not supported by server");
374 if ((ok = do_rfc1731(sock, ctl, buf)))
376 if (outlevel == O_VERBOSE)
377 error(0, 0, "IMAP> *");
378 SockWrite(sock, "*\r\n", 3);
382 #endif /* KERBEROS_V4 */
387 static int imap_getrange(int sock,
390 int *countp, int *newp)
391 /* get range of messages to be fetched */
395 /* find out how many messages are waiting */
397 ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
400 error(0, 0, "mailbox selection failed");
406 if (unseen) /* optional response, but better if we see it */
408 else if (recent) /* mandatory */
411 *newp = -1; /* should never happen, RECENT is mandatory */
418 static int imap_getsizes(int sock, int count, int *sizes)
419 /* capture the sizes of all messages */
421 char buf [POPBUFSIZE+1];
423 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
424 while (SockRead(sock, buf, sizeof(buf)))
428 if ((ok = gen_recv(sock, buf, sizeof(buf))))
430 if (strstr(buf, "OK"))
432 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
433 sizes[num - 1] = size;
441 static int imap_is_old(int sock, struct query *ctl, int number)
442 /* is the given message old? */
446 /* expunges change the fetch numbers */
447 number -= deletecount;
449 if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
455 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
456 /* request headers of nth message */
458 char buf [POPBUFSIZE+1];
461 /* expunges change the fetch numbers */
462 number -= deletecount;
465 * This is blessed by RFC 1176, RFC1730, RFC2060.
466 * According to the RFCs, it should *not* set the \Seen flag.
468 gen_send(sock, "FETCH %d RFC822.HEADER", number);
470 /* looking for FETCH response */
474 if ((ok = gen_recv(sock, buf, sizeof(buf))))
477 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
485 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
486 /* request body of nth message */
488 char buf [POPBUFSIZE+1];
491 /* expunges change the fetch numbers */
492 number -= deletecount;
495 * If we're using IMAP4, we can fetch the message without setting its
496 * seen flag. This is good! It means that if the protocol exchange
497 * craps out during the message, it will still be marked `unseen' on
500 * However...*don't* do this if we're using keep to suppress deletion!
501 * In that case, marking the seen flag is the only way to prevent the
502 * message from being re-fetched on subsequent runs.
504 switch (imap_version)
506 case IMAP4rev1: /* RFC 2060 */
508 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
510 gen_send(sock, "FETCH %d BODY[TEXT]", number);
513 case IMAP4: /* RFC 1730 */
515 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
517 gen_send(sock, "FETCH %d RFC822.TEXT", number);
520 default: /* RFC 1176 */
521 gen_send(sock, "FETCH %d RFC822.TEXT", number);
525 /* looking for FETCH response */
529 if ((ok = gen_recv(sock, buf, sizeof(buf))))
532 /* third token can be "RFC822" or "BODY[]" */
533 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
541 static int imap_trail(int sock, struct query *ctl, int number)
542 /* discard tail of FETCH response after reading message text */
544 char buf [POPBUFSIZE+1];
546 /* expunges change the fetch numbers */
547 /* number -= deletecount; */
549 return(gen_recv(sock, buf, sizeof(buf)));
552 static int imap_delete(int sock, struct query *ctl, int number)
553 /* set delete flag for given message */
557 /* expunges change the fetch numbers */
558 number -= deletecount;
561 * Use SILENT if possible as a minor throughput optimization.
562 * Note: this has been dropped from IMAP4rev1.
564 if ((ok = gen_transact(sock,
565 imap_version == IMAP4
566 ? "STORE %d +FLAGS.SILENT (\\Deleted)"
567 : "STORE %d +FLAGS (\\Deleted)",
572 * We do an expunge after each message, rather than just before quit,
573 * so that a line hit during a long session won't result in lots of
574 * messages being fetched again during the next session.
576 if ((ok = gen_transact(sock, "EXPUNGE")))
584 const static struct method imap =
586 "IMAP", /* Internet Message Access Protocol */
587 143, /* standard IMAP2bis/IMAP4 port */
588 1, /* this is a tagged protocol */
589 0, /* no message delimiter */
590 imap_ok, /* parse command response */
591 imap_getauth, /* get authorization */
592 imap_getrange, /* query range of messages */
593 imap_getsizes, /* grab message sizes */
594 imap_is_old, /* no UID check */
595 imap_fetch_headers, /* request given message headers */
596 imap_fetch_body, /* request given message body */
597 imap_trail, /* eat message trailer */
598 imap_delete, /* delete the message */
599 "LOGOUT", /* the IMAP exit command */
602 int doIMAP(struct query *ctl)
603 /* retrieve messages using IMAP Version 2bis or Version 4 */
605 return(do_protocol(ctl, &imap));
608 /* imap.c ends here */