]> Pileus Git - ~andy/fetchmail/blob - imap.c
36bdaf068c14bfa784f4c28969c7145499975ebc
[~andy/fetchmail] / imap.c
1 /*
2  * imap.c -- IMAP2bis/IMAP4 protocol methods
3  *
4  * Copyright 1996 by Eric S. Raymond
5  * All rights reserved.
6  * For license terms, see the file COPYING in this directory.
7  */
8
9 #include  <config.h>
10 #include  <stdio.h>
11 #include  <string.h>
12 #include  <ctype.h>
13 #if defined(STDC_HEADERS)
14 #include  <stdlib.h>
15 #endif
16 #include  "fetchmail.h"
17 #include  "socket.h"
18
19 #ifdef KERBEROS_V4
20 #include <krb.h>
21 #include "base64.h"
22 #endif /* KERBEROS_V4 */
23
24 extern char *strstr();  /* needed on sysV68 R3V7.1. */
25
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 */
30
31 static int count, seen, recent, unseen, deletecount, imap_version;
32
33 int imap_ok (int sock,  char *argbuf)
34 /* parse command response */
35 {
36     char buf [POPBUFSIZE+1];
37
38     seen = 0;
39     do {
40         int     ok;
41
42         if ((ok = gen_recv(sock, buf, sizeof(buf))))
43             return(ok);
44
45         /* interpret untagged status responses */
46         if (strstr(buf, "EXISTS"))
47             count = atoi(buf+2);
48         if (strstr(buf, "RECENT"))
49             recent = atoi(buf+2);
50         if (strstr(buf, "UNSEEN"))
51             unseen = atoi(buf+2);
52         if (strstr(buf, "FLAGS"))
53             seen = (strstr(buf, "Seen") != (char *)NULL);
54     } while
55         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
56
57     if (tag[0] == '\0')
58     {
59         strcpy(argbuf, buf);
60         return(PS_SUCCESS); 
61     }
62     else
63     {
64         char    *cp;
65
66         /* skip the tag */
67         for (cp = buf; !isspace(*cp); cp++)
68             continue;
69         while (isspace(*cp))
70             cp++;
71
72         if (strncmp(cp, "OK", 2) == 0)
73         {
74             strcpy(argbuf, cp);
75             return(PS_SUCCESS);
76         }
77         else if (strncmp(cp, "BAD", 2) == 0)
78             return(PS_ERROR);
79         else
80             return(PS_PROTOCOL);
81     }
82 }
83
84 #ifdef KERBEROS_V4
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!
89  *
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
94  * scheme used here.
95  */
96 {
97     int result = 0, len;
98     char buf1[4096], buf2[4096];
99     union {
100       int cint;
101       char cstr[4];
102     } challenge1, challenge2;
103     char srvinst[INST_SZ];
104     char *p;
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];
111     des_cblock session;
112     des_key_schedule schedule;
113
114     gen_send(sock, "AUTHENTICATE KERBEROS_V4");
115
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.
125      */
126
127     if (result = gen_recv(sock, buf1, sizeof buf1)) {
128         return result;
129     }
130
131     len = from64(challenge1.cstr, buf1);
132     if (len < 0) {
133         error(0, -1, "could not decode initial BASE64 challenge");
134         return PS_AUTHFAIL;
135     }
136
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.
144      */
145
146     strncpy(srvinst, ctl->server.names->id, (sizeof srvinst)-1);
147     srvinst[(sizeof srvinst)-1] = '\0';
148     for (p = srvinst; *p; p++) {
149       if (isupper(*p)) {
150         *p = tolower(*p);
151       }
152     }
153
154     strncpy(srvrealm, krb_realmofhost(srvinst), (sizeof srvrealm)-1);
155     srvrealm[(sizeof srvrealm)-1] = '\0';
156     if (p = strchr(srvinst, '.')) {
157       *p = '\0';
158     }
159
160     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
161     if (result) {
162         error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
163         return PS_AUTHFAIL;
164     }
165
166     result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
167     if (result) {
168         error(0, -1, "krb_get_cred: %s", krb_get_err_text(result));
169         return PS_AUTHFAIL;
170     }
171
172     memcpy(session, credentials.session, sizeof session);
173     memset(&credentials, 0, sizeof credentials);
174     des_key_sched(session, schedule);
175
176     result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
177     if (result) {
178         error(0, -1, "krb_get_tf_fullname: %s", krb_get_err_text(result));
179         return PS_AUTHFAIL;
180     }
181
182     if (strcmp(tktuser, user) != 0) {
183         error(0, -1, "principal %s in ticket does not match -u %s", tktuser,
184                 user);
185         return PS_AUTHFAIL;
186     }
187
188     if (tktinst[0]) {
189         error(0, 0, "non-null instance (%s) might cause strange behavior",
190                 tktinst);
191         strcat(tktuser, ".");
192         strcat(tktuser, tktinst);
193     }
194
195     if (strcmp(tktrealm, srvrealm) != 0) {
196         strcat(tktuser, "@");
197         strcat(tktuser, tktrealm);
198     }
199
200     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
201             challenge1.cint);
202     if (result) {
203         error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
204         return PS_AUTHFAIL;
205     }
206
207     to64(buf1, authenticator.dat, authenticator.length);
208     if (outlevel == O_VERBOSE) {
209         error(0, 0, "IMAP> %s", buf1);
210     }
211     SockWrite(sock, buf1, strlen(buf1));
212     SockWrite(sock, "\r\n", 2);
213
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.
229      */
230     
231     if (result = gen_recv(sock, buf1, sizeof buf1))
232         return result;
233
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.
251      */
252
253     len = from64(buf2, buf1);
254     if (len < 0) {
255         error(0, -1, "could not decode BASE64 ready response");
256         return PS_AUTHFAIL;
257     }
258
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");
263         return PS_AUTHFAIL;
264     }       
265
266     memset(authenticator.dat, 0, sizeof authenticator.dat);
267
268     result = htonl(challenge1.cint);
269     memcpy(authenticator.dat, &result, sizeof result);
270
271     /* The protection mechanisms and their corresponding bit-masks are as
272      * follows:
273      *
274      * 1 No protection mechanism
275      * 2 Integrity (krb_mk_safe) protection
276      * 4 Privacy (krb_mk_priv) protection
277      */
278     authenticator.dat[4] = 1;
279
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++;
285     }
286     des_pcbc_encrypt((des_cblock *)authenticator.dat,
287             (des_cblock *)authenticator.dat, authenticator.length, schedule,
288             &session, 1);
289
290     to64(buf1, authenticator.dat, authenticator.length);
291     if (outlevel == O_VERBOSE) {
292         error(0, 0, "IMAP> %s", buf1);
293     }
294     SockWrite(sock, buf1, strlen(buf1));
295     SockWrite(sock, "\r\n", 2);
296
297     if (result = gen_recv(sock, buf1, sizeof buf1))
298         return result;
299
300     if (strstr(buf1, "OK")) {
301         return PS_SUCCESS;
302     }
303     else {
304         return PS_AUTHFAIL;
305     }
306 }
307 #endif /* KERBEROS_V4 */
308
309 int imap_getauth(int sock, struct query *ctl, char *buf)
310 /* apply for connection authorization */
311 {
312     char rbuf [POPBUFSIZE+1];
313     int ok = 0;
314 #ifdef KERBEROS_V4
315     int kerbok = 0;
316
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);
322
323      if (ok)
324          return(ok);
325
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))))
329          return(ok);
330      if (strstr(rbuf, "BAD"))
331      {
332          imap_version = IMAP2;
333          if (outlevel == O_VERBOSE)
334              error(0, 0, "Protocol identified as IMAP2 or IMAP2BIS");
335      }
336      else if (strstr(rbuf, "IMAP4rev1"))
337      {
338          imap_version = IMAP4rev1;
339          if (outlevel == O_VERBOSE)
340              error(0, 0, "Protocol identified as IMAP4 rev 1");
341      }
342      else
343      {
344          imap_version = IMAP4;
345          if (outlevel == O_VERBOSE)
346              error(0, 0, "Protocol identified as IMAP4 rev 0");
347      }
348
349      peek_capable = (imap_version >= IMAP4);
350
351 #ifdef KERBEROS_V4
352      if (strstr(rbuf, "AUTH=KERBEROS_V4"))
353      {
354          kerbok++;
355          if (outlevel == O_VERBOSE)
356                 error(0, 0, "KERBEROS_V4 authentication is supported");
357      }
358
359      /* eat OK response */
360      if ((ok = gen_recv(sock, rbuf, sizeof(rbuf))))
361          return(ok);
362
363      if (!strstr(rbuf, "OK"))
364          return(PS_AUTHFAIL);
365  
366      if ((imap_version >= IMAP4) && (ctl->server.protocol == P_IMAP_K4))
367      {
368          if (!kerbok)
369          {
370              error(0, -1, "Required KERBEROS_V4 capability not supported by server");
371              return(PS_AUTHFAIL);
372          }
373
374          if ((ok = do_rfc1731(sock, ctl, buf)))
375          {
376              if (outlevel == O_VERBOSE)
377                  error(0, 0, "IMAP> *");
378              SockWrite(sock, "*\r\n", 3);
379              return(ok);
380          }
381      }
382 #endif /* KERBEROS_V4 */
383
384      return(PS_SUCCESS);
385 }
386
387 static int imap_getrange(int sock, 
388                          struct query *ctl, 
389                          const char *folder, 
390                          int *countp, int *newp)
391 /* get range of messages to be fetched */
392 {
393     int ok;
394
395     /* find out how many messages are waiting */
396     recent = unseen = 0;
397     ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
398     if (ok != 0)
399     {
400         error(0, 0, "mailbox selection failed");
401         return(ok);
402     }
403
404     *countp = count;
405
406     if (unseen)         /* optional response, but better if we see it */
407         *newp = unseen;
408     else if (recent)    /* mandatory */
409         *newp = recent;
410     else
411         *newp = -1;     /* should never happen, RECENT is mandatory */ 
412
413     deletecount = 0;
414
415     return(PS_SUCCESS);
416 }
417
418 static int imap_getsizes(int sock, int count, int *sizes)
419 /* capture the sizes of all messages */
420 {
421     char buf [POPBUFSIZE+1];
422
423     gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
424     while (SockRead(sock, buf, sizeof(buf)))
425     {
426         int num, size, ok;
427
428         if ((ok = gen_recv(sock, buf, sizeof(buf))))
429             return(ok);
430         if (strstr(buf, "OK"))
431             break;
432         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
433             sizes[num - 1] = size;
434         else
435             sizes[num - 1] = -1;
436     }
437
438     return(PS_SUCCESS);
439 }
440
441 static int imap_is_old(int sock, struct query *ctl, int number)
442 /* is the given message old? */
443 {
444     int ok;
445
446     /* expunges change the fetch numbers */
447     number -= deletecount;
448
449     if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
450         return(PS_ERROR);
451
452     return(seen);
453 }
454
455 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
456 /* request headers of nth message */
457 {
458     char buf [POPBUFSIZE+1];
459     int num;
460
461     /* expunges change the fetch numbers */
462     number -= deletecount;
463
464     /*
465      * This is blessed by RFC 1176, RFC1730, RFC2060.
466      * According to the RFCs, it should *not* set the \Seen flag.
467      */
468     gen_send(sock, "FETCH %d RFC822.HEADER", number);
469
470     /* looking for FETCH response */
471     do {
472         int     ok;
473
474         if ((ok = gen_recv(sock, buf, sizeof(buf))))
475             return(ok);
476     } while
477         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
478
479     if (num != number)
480         return(PS_ERROR);
481     else
482         return(PS_SUCCESS);
483 }
484
485 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
486 /* request body of nth message */
487 {
488     char buf [POPBUFSIZE+1];
489     int num;
490
491     /* expunges change the fetch numbers */
492     number -= deletecount;
493
494     /*
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
498      * the server.
499      *
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.
503      */
504     switch (imap_version)
505     {
506     case IMAP4rev1:     /* RFC 2060 */
507         if (!ctl->keep)
508             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
509         else
510             gen_send(sock, "FETCH %d BODY[TEXT]", number);
511         break;
512
513     case IMAP4:         /* RFC 1730 */
514         if (!ctl->keep)
515             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
516         else
517             gen_send(sock, "FETCH %d RFC822.TEXT", number);
518         break;
519
520     default:            /* RFC 1176 */
521         gen_send(sock, "FETCH %d RFC822.TEXT", number);
522         break;
523     }
524
525     /* looking for FETCH response */
526     do {
527         int     ok;
528
529         if ((ok = gen_recv(sock, buf, sizeof(buf))))
530             return(ok);
531     } while
532         /* third token can be "RFC822" or "BODY[]" */
533         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
534
535     if (num != number)
536         return(PS_ERROR);
537     else
538         return(PS_SUCCESS);
539 }
540
541 static int imap_trail(int sock, struct query *ctl, int number)
542 /* discard tail of FETCH response after reading message text */
543 {
544     char buf [POPBUFSIZE+1];
545
546     /* expunges change the fetch numbers */
547     /* number -= deletecount; */
548
549     return(gen_recv(sock, buf, sizeof(buf)));
550 }
551
552 static int imap_delete(int sock, struct query *ctl, int number)
553 /* set delete flag for given message */
554 {
555     int ok;
556
557     /* expunges change the fetch numbers */
558     number -= deletecount;
559
560     /*
561      * Use SILENT if possible as a minor throughput optimization.
562      * Note: this has been dropped from IMAP4rev1.
563      */
564     if ((ok = gen_transact(sock,
565                         imap_version == IMAP4 
566                                 ? "STORE %d +FLAGS.SILENT (\\Deleted)"
567                                 : "STORE %d +FLAGS (\\Deleted)", 
568                         number)))
569         return(ok);
570
571     /*
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.
575      */
576     if ((ok = gen_transact(sock, "EXPUNGE")))
577         return(ok);
578
579     deletecount++;
580
581     return(PS_SUCCESS);
582 }
583
584 const static struct method imap =
585 {
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 */
600 };
601
602 int doIMAP(struct query *ctl)
603 /* retrieve messages using IMAP Version 2bis or Version 4 */
604 {
605     return(do_protocol(ctl, &imap));
606 }
607
608 /* imap.c ends here */