]> Pileus Git - ~andy/fetchmail/blob - imap.c
Try to fix the build code.
[~andy/fetchmail] / imap.c
1 /*
2  * imap.c -- IMAP2bis/IMAP4 protocol methods
3  *
4  * Copyright 1997 by Eric S. Raymond
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include  "config.h"
9 #include  <stdio.h>
10 #include  <string.h>
11 #include  <ctype.h>
12 #if defined(STDC_HEADERS)
13 #include  <stdlib.h>
14 #endif
15 #include  "fetchmail.h"
16 #include  "socket.h"
17
18 #ifdef KERBEROS_V4
19 #if defined (__bsdi__)
20 #include <des.h>
21 #define krb_get_err_text(e) (krb_err_txt[e])
22 #endif
23 #include <krb.h>
24 #endif /* KERBEROS_V4 */
25
26 extern char *strstr();  /* needed on sysV68 R3V7.1. */
27
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 */
32
33 static int count, seen, recent, unseen, deletecount, imap_version;
34
35 int imap_ok (int sock,  char *argbuf)
36 /* parse command response */
37 {
38     char buf [POPBUFSIZE+1];
39
40     seen = 0;
41     do {
42         int     ok;
43
44         if ((ok = gen_recv(sock, buf, sizeof(buf))))
45             return(ok);
46
47         /* interpret untagged status responses */
48         if (strstr(buf, "EXISTS"))
49             count = atoi(buf+2);
50         if (strstr(buf, "RECENT"))
51             recent = atoi(buf+2);
52         if (strstr(buf, "UNSEEN"))
53         {
54             char        *cp;
55
56             /*
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.
60              */
61             unseen = 0;
62             for (cp = buf; *cp && !isdigit(*cp); cp++)
63             {
64                 unseen = atoi(cp);
65                 break;
66             }
67         }
68         if (strstr(buf, "FLAGS"))
69             seen = (strstr(buf, "Seen") != (char *)NULL);
70     } while
71         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
72
73     if (tag[0] == '\0')
74     {
75         strcpy(argbuf, buf);
76         return(PS_SUCCESS); 
77     }
78     else
79     {
80         char    *cp;
81
82         /* skip the tag */
83         for (cp = buf; !isspace(*cp); cp++)
84             continue;
85         while (isspace(*cp))
86             cp++;
87
88         if (strncmp(cp, "OK", 2) == 0)
89         {
90             strcpy(argbuf, cp);
91             return(PS_SUCCESS);
92         }
93         else if (strncmp(cp, "BAD", 2) == 0)
94             return(PS_ERROR);
95         else
96             return(PS_PROTOCOL);
97     }
98 }
99
100 #ifdef KERBEROS_V4
101 #if SIZEOF_INT == 4
102 typedef int     int32;
103 #elif SIZEOF_SHORT == 4
104 typedef short   int32;
105 #elif SIZEOF_LONG == 4
106 typedef long    int32;
107 #else
108 #error Cannot deduce a 32-bit-type
109 #endif
110
111 static int do_rfc1731(int sock, struct query *ctl, char *buf)
112 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
113 {
114     int result = 0, len;
115     char buf1[4096], buf2[4096];
116     union {
117       int32 cint;
118       char cstr[4];
119     } challenge1, challenge2;
120     char srvinst[INST_SZ];
121     char *p;
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];
128     des_cblock session;
129     des_key_schedule schedule;
130
131     gen_send(sock, "AUTHENTICATE KERBEROS_V4");
132
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.
142      */
143
144     if (result = gen_recv(sock, buf1, sizeof buf1)) {
145         return result;
146     }
147
148     len = from64tobits(challenge1.cstr, buf1);
149     if (len < 0) {
150         error(0, -1, "could not decode initial BASE64 challenge");
151         return PS_AUTHFAIL;
152     }
153
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.
161      */
162
163     strncpy(srvinst, ctl->server.names->id, (sizeof srvinst)-1);
164     srvinst[(sizeof srvinst)-1] = '\0';
165     for (p = srvinst; *p; p++) {
166       if (isupper(*p)) {
167         *p = tolower(*p);
168       }
169     }
170
171     strncpy(srvrealm, krb_realmofhost(srvinst), (sizeof srvrealm)-1);
172     srvrealm[(sizeof srvrealm)-1] = '\0';
173     if (p = strchr(srvinst, '.')) {
174       *p = '\0';
175     }
176
177     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
178     if (result) {
179         error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
180         return PS_AUTHFAIL;
181     }
182
183     result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
184     if (result) {
185         error(0, -1, "krb_get_cred: %s", krb_get_err_text(result));
186         return PS_AUTHFAIL;
187     }
188
189     memcpy(session, credentials.session, sizeof session);
190     memset(&credentials, 0, sizeof credentials);
191     des_key_sched(session, schedule);
192
193     result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
194     if (result) {
195         error(0, -1, "krb_get_tf_fullname: %s", krb_get_err_text(result));
196         return PS_AUTHFAIL;
197     }
198
199     if (strcmp(tktuser, user) != 0) {
200         error(0, -1, "principal %s in ticket does not match -u %s", tktuser,
201                 user);
202         return PS_AUTHFAIL;
203     }
204
205     if (tktinst[0]) {
206         error(0, 0, "non-null instance (%s) might cause strange behavior",
207                 tktinst);
208         strcat(tktuser, ".");
209         strcat(tktuser, tktinst);
210     }
211
212     if (strcmp(tktrealm, srvrealm) != 0) {
213         strcat(tktuser, "@");
214         strcat(tktuser, tktrealm);
215     }
216
217     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
218             challenge1.cint);
219     if (result) {
220         error(0, -1, "krb_mq_req: %s", krb_get_err_text(result));
221         return PS_AUTHFAIL;
222     }
223
224     to64frombits(buf1, authenticator.dat, authenticator.length);
225     if (outlevel == O_VERBOSE) {
226         error(0, 0, "IMAP> %s", buf1);
227     }
228     SockWrite(sock, buf1, strlen(buf1));
229     SockWrite(sock, "\r\n", 2);
230
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.
246      */
247     
248     if (result = gen_recv(sock, buf1, sizeof buf1))
249         return result;
250
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.
268      */
269
270     len = from64tobits(buf2, buf1);
271     if (len < 0) {
272         error(0, -1, "could not decode BASE64 ready response");
273         return PS_AUTHFAIL;
274     }
275
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");
280         return PS_AUTHFAIL;
281     }       
282
283     memset(authenticator.dat, 0, sizeof authenticator.dat);
284
285     result = htonl(challenge1.cint);
286     memcpy(authenticator.dat, &result, sizeof result);
287
288     /* The protection mechanisms and their corresponding bit-masks are as
289      * follows:
290      *
291      * 1 No protection mechanism
292      * 2 Integrity (krb_mk_safe) protection
293      * 4 Privacy (krb_mk_priv) protection
294      */
295     authenticator.dat[4] = 1;
296
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++;
302     }
303     des_pcbc_encrypt((des_cblock *)authenticator.dat,
304             (des_cblock *)authenticator.dat, authenticator.length, schedule,
305             &session, 1);
306
307     to64frombits(buf1, authenticator.dat, authenticator.length);
308     if (outlevel == O_VERBOSE) {
309         error(0, 0, "IMAP> %s", buf1);
310     }
311     SockWrite(sock, buf1, strlen(buf1));
312     SockWrite(sock, "\r\n", 2);
313
314     if (result = gen_recv(sock, buf1, sizeof buf1))
315         return result;
316
317     if (strstr(buf1, "OK")) {
318         return PS_SUCCESS;
319     }
320     else {
321         return PS_AUTHFAIL;
322     }
323 }
324 #endif /* KERBEROS_V4 */
325
326 int imap_getauth(int sock, struct query *ctl, char *buf)
327 /* apply for connection authorization */
328 {
329     char rbuf [POPBUFSIZE+1];
330     int ok = 0;
331 #ifdef KERBEROS_V4
332     int kerbok = 0;
333
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);
339
340      if (ok)
341          return(ok);
342
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))))
346          return(ok);
347      if (strstr(rbuf, "BAD"))
348      {
349          imap_version = IMAP2;
350          if (outlevel == O_VERBOSE)
351              error(0, 0, "Protocol identified as IMAP2 or IMAP2BIS");
352      }
353      /* UW-IMAP server 10.173 notifies in all caps */
354      else if (strstr(rbuf, "IMAP4rev1") || strstr(rbuf, "IMAP4REV1"))
355      {
356          imap_version = IMAP4rev1;
357          if (outlevel == O_VERBOSE)
358              error(0, 0, "Protocol identified as IMAP4 rev 1");
359      }
360      else
361      {
362          imap_version = IMAP4;
363          if (outlevel == O_VERBOSE)
364              error(0, 0, "Protocol identified as IMAP4 rev 0");
365      }
366
367      peek_capable = (imap_version >= IMAP4);
368
369 #ifdef KERBEROS_V4
370      if (strstr(rbuf, "AUTH=KERBEROS_V4"))
371      {
372          kerbok++;
373          if (outlevel == O_VERBOSE)
374                 error(0, 0, "KERBEROS_V4 authentication is supported");
375      }
376
377      /* eat OK response */
378      if ((ok = gen_recv(sock, rbuf, sizeof(rbuf))))
379          return(ok);
380
381      if (!strstr(rbuf, "OK"))
382          return(PS_AUTHFAIL);
383  
384      if ((imap_version >= IMAP4) && (ctl->server.protocol == P_IMAP_K4))
385      {
386          if (!kerbok)
387          {
388              error(0, -1, "Required KERBEROS_V4 capability not supported by server");
389              return(PS_AUTHFAIL);
390          }
391
392          if ((ok = do_rfc1731(sock, ctl, buf)))
393          {
394              if (outlevel == O_VERBOSE)
395                  error(0, 0, "IMAP> *");
396              SockWrite(sock, "*\r\n", 3);
397              return(ok);
398          }
399      }
400 #endif /* KERBEROS_V4 */
401
402      return(PS_SUCCESS);
403 }
404
405 static int imap_getrange(int sock, 
406                          struct query *ctl, 
407                          const char *folder, 
408                          int *countp, int *newp)
409 /* get range of messages to be fetched */
410 {
411     int ok;
412
413     /* find out how many messages are waiting */
414     recent = unseen = -1;
415     ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
416     if (ok != 0)
417     {
418         error(0, 0, "mailbox selection failed");
419         return(ok);
420     }
421
422     *countp = count;
423
424     /*
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
429      * are likewise).
430      */
431     if (unseen >= 0)            /* optional, but better if we see it */
432         *newp = count - unseen + 1;
433     else if (recent >= 0)       /* mandatory */
434         *newp = recent;
435     else
436         *newp = -1;             /* should never happen, RECENT is mandatory */ 
437
438     deletecount = 0;
439
440     return(PS_SUCCESS);
441 }
442
443 static int imap_getsizes(int sock, int count, int *sizes)
444 /* capture the sizes of all messages */
445 {
446     char buf [POPBUFSIZE+1];
447
448     gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
449     while (SockRead(sock, buf, sizeof(buf)))
450     {
451         int num, size, ok;
452
453         if ((ok = gen_recv(sock, buf, sizeof(buf))))
454             return(ok);
455         if (strstr(buf, "OK"))
456             break;
457         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
458             sizes[num - 1] = size;
459         else
460             sizes[num - 1] = -1;
461     }
462
463     return(PS_SUCCESS);
464 }
465
466 static int imap_is_old(int sock, struct query *ctl, int number)
467 /* is the given message old? */
468 {
469     int ok;
470
471     /* expunges change the fetch numbers */
472     number -= deletecount;
473
474     if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
475         return(PS_ERROR);
476
477     return(seen);
478 }
479
480 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
481 /* request headers of nth message */
482 {
483     char buf [POPBUFSIZE+1];
484     int num;
485
486     /* expunges change the fetch numbers */
487     number -= deletecount;
488
489     /*
490      * This is blessed by RFC 1176, RFC1730, RFC2060.
491      * According to the RFCs, it should *not* set the \Seen flag.
492      */
493     gen_send(sock, "FETCH %d RFC822.HEADER", number);
494
495     /* looking for FETCH response */
496     do {
497         int     ok;
498
499         if ((ok = gen_recv(sock, buf, sizeof(buf))))
500             return(ok);
501     } while
502         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
503
504     if (num != number)
505         return(PS_ERROR);
506     else
507         return(PS_SUCCESS);
508 }
509
510 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
511 /* request body of nth message */
512 {
513     char buf [POPBUFSIZE+1], *cp;
514     int num;
515
516     /* expunges change the fetch numbers */
517     number -= deletecount;
518
519     /*
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
523      * the server.
524      *
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.
528      */
529     switch (imap_version)
530     {
531     case IMAP4rev1:     /* RFC 2060 */
532         if (!ctl->keep)
533             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
534         else
535             gen_send(sock, "FETCH %d BODY[TEXT]", number);
536         break;
537
538     case IMAP4:         /* RFC 1730 */
539         if (!ctl->keep)
540             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
541         else
542             gen_send(sock, "FETCH %d RFC822.TEXT", number);
543         break;
544
545     default:            /* RFC 1176 */
546         gen_send(sock, "FETCH %d RFC822.TEXT", number);
547         break;
548     }
549
550     /* looking for FETCH response */
551     do {
552         int     ok;
553
554         if ((ok = gen_recv(sock, buf, sizeof(buf))))
555             return(ok);
556     } while
557         (sscanf(buf+2, "%d FETCH", &num) != 1);
558
559     if (num != number)
560         return(PS_ERROR);
561
562     /* try to extract a length */
563     if ((cp = strchr(buf, '{')))
564         *lenp = atoi(cp + 1);
565     else
566         *lenp = 0;
567
568     return(PS_SUCCESS);
569 }
570
571 static int imap_trail(int sock, struct query *ctl, int number)
572 /* discard tail of FETCH response after reading message text */
573 {
574     /* expunges change the fetch numbers */
575     /* number -= deletecount; */
576
577     for (;;)
578     {
579         char buf[POPBUFSIZE+1];
580         int ok;
581
582         if ((ok = gen_recv(sock, buf, sizeof(buf))))
583             return(ok);
584         if (strstr(buf, "OK FETCH"))
585             break;
586     }
587
588     return(PS_SUCCESS);
589 }
590
591 static int imap_delete(int sock, struct query *ctl, int number)
592 /* set delete flag for given message */
593 {
594     int ok;
595
596     /* expunges change the fetch numbers */
597     number -= deletecount;
598
599     /*
600      * Use SILENT if possible as a minor throughput optimization.
601      * Note: this has been dropped from IMAP4rev1.
602      */
603     if ((ok = gen_transact(sock,
604                         imap_version == IMAP4 
605                                 ? "STORE %d +FLAGS.SILENT (\\Deleted)"
606                                 : "STORE %d +FLAGS (\\Deleted)", 
607                         number)))
608         return(ok);
609
610     /*
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.
614      */
615     if ((ok = gen_transact(sock, "EXPUNGE")))
616         return(ok);
617
618     deletecount++;
619
620     return(PS_SUCCESS);
621 }
622
623 const static struct method imap =
624 {
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 */
640 };
641
642 int doIMAP(struct query *ctl)
643 /* retrieve messages using IMAP Version 2bis or Version 4 */
644 {
645     return(do_protocol(ctl, &imap));
646 }
647
648 /* imap.c ends here */