]> Pileus Git - ~andy/fetchmail/blob - imap.c
Support imapd PREAUTH response.
[~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 #ifdef KERBEROS_V5
20 #include <kerberosIV/des.h>
21 #include <kerberosIV/krb.h>
22 #else
23 #if defined (__bsdi__)
24 #include <des.h>
25 #define krb_get_err_text(e) (krb_err_txt[e])
26 #endif
27 #if defined(__NetBSD__) || (__FreeBSD__) || defined(__linux__)
28 #define krb_get_err_text(e) (krb_err_txt[e])
29 #endif
30 #include <krb.h>
31 #endif
32 #endif /* KERBEROS_V4 */
33 #include  "i18n.h"
34
35 #ifdef GSSAPI
36 #include <gssapi/gssapi.h>
37 #include <gssapi/gssapi_generic.h>
38 #endif
39
40 #include "md5.h"
41
42 #if OPIE
43 #include <opie.h>
44 #endif /* OPIE */
45
46 #ifndef strstr          /* glibc-2.1 declares this as a macro */
47 extern char *strstr();  /* needed on sysV68 R3V7.1. */
48 #endif /* strstr */
49
50 /* imap_version values */
51 #define IMAP2           -1      /* IMAP2 or IMAP2BIS, RFC1176 */
52 #define IMAP4           0       /* IMAP4 rev 0, RFC1730 */
53 #define IMAP4rev1       1       /* IMAP4 rev 1, RFC2060 */
54
55 static int count, seen, recent, unseen, deletions, imap_version, preauth; 
56 static int expunged, expunge_period;
57 static char capabilities[MSGBUFSIZE+1];
58
59 int imap_ok(int sock, char *argbuf)
60 /* parse command response */
61 {
62     char buf [MSGBUFSIZE+1];
63
64     seen = 0;
65     do {
66         int     ok;
67         char    *cp;
68
69         if ((ok = gen_recv(sock, buf, sizeof(buf))))
70             return(ok);
71
72         /* all tokens in responses are caseblind */
73         for (cp = buf; *cp; cp++)
74             if (islower(*cp))
75                 *cp = toupper(*cp);
76
77         /* interpret untagged status responses */
78         if (strstr(buf, "* CAPABILITY"))
79             strncpy(capabilities, buf + 12, sizeof(capabilities));
80         if (strstr(buf, "EXISTS"))
81             count = atoi(buf+2);
82         if (strstr(buf, "RECENT"))
83             recent = atoi(buf+2);
84         if (strstr(buf, "UNSEEN"))
85         {
86             char        *cp;
87
88             /*
89              * Handle both "* 42 UNSEEN" (if tha ever happens) and 
90              * "* OK [UNSEEN 42] 42". Note that what this gets us is
91              * a minimum index, not a count.
92              */
93             unseen = 0;
94             for (cp = buf; *cp && !isdigit(*cp); cp++)
95                 continue;
96             unseen = atoi(cp);
97         }
98         if (strstr(buf, "FLAGS"))
99             seen = (strstr(buf, "SEEN") != (char *)NULL);
100     } while
101         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
102
103     if (tag[0] == '\0')
104     {
105         if (argbuf)
106             strcpy(argbuf, buf);
107         return(PS_SUCCESS); 
108     }
109     else
110     {
111         char    *cp;
112
113         /* skip the tag */
114         for (cp = buf; !isspace(*cp); cp++)
115             continue;
116         while (isspace(*cp))
117             cp++;
118
119         if (strncmp(cp, "PREAUTH", 2) == 0)
120         {
121             if (argbuf)
122                 strcpy(argbuf, cp);
123             preauth = TRUE;
124             return(PS_SUCCESS);
125         }
126         else if (strncmp(cp, "OK", 2) == 0)
127         {
128             if (argbuf)
129                 strcpy(argbuf, cp);
130             return(PS_SUCCESS);
131         }
132         else if (strncmp(cp, "BAD", 3) == 0)
133             return(PS_ERROR);
134         else if (strncmp(cp, "NO", 2) == 0)
135             return(PS_ERROR);
136         else
137             return(PS_PROTOCOL);
138     }
139 }
140
141 #if OPIE
142 static int do_otp(int sock, struct query *ctl)
143 {
144     int i, rval;
145     char buffer[128];
146     char challenge[OPIE_CHALLENGE_MAX+1];
147     char response[OPIE_RESPONSE_MAX+1];
148
149     gen_send(sock, "AUTHENTICATE X-OTP");
150
151     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
152         return rval;
153
154     if ((i = from64tobits(challenge, buffer)) < 0) {
155         report(stderr, _("Could not decode initial BASE64 challenge\n"));
156         return PS_AUTHFAIL;
157     };
158
159
160     to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
161
162     if (outlevel >= O_MONITOR)
163         report(stdout, "IMAP> %s\n", buffer);
164     SockWrite(sock, buffer, strlen(buffer));
165     SockWrite(sock, "\r\n", 2);
166
167     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
168         return rval;
169
170     if ((i = from64tobits(challenge, buffer)) < 0) {
171         report(stderr, _("Could not decode OTP challenge\n"));
172         return PS_AUTHFAIL;
173     };
174
175     rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
176     if ((rval == -2) && !run.poll_interval) {
177         char secret[OPIE_SECRET_MAX+1];
178         fprintf(stderr, _("Secret pass phrase: "));
179         if (opiereadpass(secret, sizeof(secret), 0))
180             rval = opiegenerator(challenge, secret, response);
181         memset(secret, 0, sizeof(secret));
182     };
183
184     if (rval)
185         return PS_AUTHFAIL;
186
187     to64frombits(buffer, response, strlen(response));
188
189     if (outlevel >= O_MONITOR)
190         report(stdout, "IMAP> %s\n", buffer);
191     SockWrite(sock, buffer, strlen(buffer));
192     SockWrite(sock, "\r\n", 2);
193
194     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
195         return rval;
196
197     if (strstr(buffer, "OK"))
198         return PS_SUCCESS;
199     else
200         return PS_AUTHFAIL;
201 };
202 #endif /* OPIE */
203
204 #ifdef KERBEROS_V4
205 #if SIZEOF_INT == 4
206 typedef int     int32;
207 #elif SIZEOF_SHORT == 4
208 typedef short   int32;
209 #elif SIZEOF_LONG == 4
210 typedef long    int32;
211 #else
212 #error Cannot deduce a 32-bit-type
213 #endif
214
215 static int do_rfc1731(int sock, char *truename)
216 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
217 {
218     int result = 0, len;
219     char buf1[4096], buf2[4096];
220     union {
221       int32 cint;
222       char cstr[4];
223     } challenge1, challenge2;
224     char srvinst[INST_SZ];
225     char *p;
226     char srvrealm[REALM_SZ];
227     KTEXT_ST authenticator;
228     CREDENTIALS credentials;
229     char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
230     char tktinst[INST_SZ];
231     char tktrealm[REALM_SZ];
232     des_cblock session;
233     des_key_schedule schedule;
234
235     gen_send(sock, "AUTHENTICATE KERBEROS_V4");
236
237     /* The data encoded in the first ready response contains a random
238      * 32-bit number in network byte order.  The client should respond
239      * with a Kerberos ticket and an authenticator for the principal
240      * "imap.hostname@realm", where "hostname" is the first component
241      * of the host name of the server with all letters in lower case
242      * and where "realm" is the Kerberos realm of the server.  The
243      * encrypted checksum field included within the Kerberos
244      * authenticator should contain the server provided 32-bit number
245      * in network byte order.
246      */
247
248     if (result = gen_recv(sock, buf1, sizeof buf1)) {
249         return result;
250     }
251
252     /* this patch by Dan Root <dar@thekeep.org> solves an endianess problem. */
253     {
254         char tmp[4];
255
256         *(int *)tmp = ntohl(*(int *) challenge1.cstr);
257         memcpy(challenge1.cstr, tmp, sizeof(tmp));
258     }
259
260     len = from64tobits(challenge1.cstr, buf1);
261     if (len < 0) {
262         report(stderr, _("could not decode initial BASE64 challenge\n"));
263         return PS_AUTHFAIL;
264     }
265
266     /* Client responds with a Kerberos ticket and an authenticator for
267      * the principal "imap.hostname@realm" where "hostname" is the
268      * first component of the host name of the server with all letters
269      * in lower case and where "realm" is the Kerberos realm of the
270      * server.  The encrypted checksum field included within the
271      * Kerberos authenticator should contain the server-provided
272      * 32-bit number in network byte order.
273      */
274
275     strncpy(srvinst, truename, (sizeof srvinst)-1);
276     srvinst[(sizeof srvinst)-1] = '\0';
277     for (p = srvinst; *p; p++) {
278       if (isupper(*p)) {
279         *p = tolower(*p);
280       }
281     }
282
283     strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
284     srvrealm[(sizeof srvrealm)-1] = '\0';
285     if (p = strchr(srvinst, '.')) {
286       *p = '\0';
287     }
288
289     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
290     if (result) {
291         report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
292         return PS_AUTHFAIL;
293     }
294
295     result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
296     if (result) {
297         report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
298         return PS_AUTHFAIL;
299     }
300
301     memcpy(session, credentials.session, sizeof session);
302     memset(&credentials, 0, sizeof credentials);
303     des_key_sched(&session, schedule);
304
305     result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
306     if (result) {
307         report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
308         return PS_AUTHFAIL;
309     }
310
311     if (strcmp(tktuser, user) != 0) {
312         report(stderr, 
313                _("principal %s in ticket does not match -u %s\n"), tktuser,
314                 user);
315         return PS_AUTHFAIL;
316     }
317
318     if (tktinst[0]) {
319         report(stderr, 
320                _("non-null instance (%s) might cause strange behavior\n"),
321                 tktinst);
322         strcat(tktuser, ".");
323         strcat(tktuser, tktinst);
324     }
325
326     if (strcmp(tktrealm, srvrealm) != 0) {
327         strcat(tktuser, "@");
328         strcat(tktuser, tktrealm);
329     }
330
331     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
332             challenge1.cint);
333     if (result) {
334         report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
335         return PS_AUTHFAIL;
336     }
337
338     to64frombits(buf1, authenticator.dat, authenticator.length);
339     if (outlevel >= O_MONITOR) {
340         report(stdout, "IMAP> %s\n", buf1);
341     }
342     SockWrite(sock, buf1, strlen(buf1));
343     SockWrite(sock, "\r\n", 2);
344
345     /* Upon decrypting and verifying the ticket and authenticator, the
346      * server should verify that the contained checksum field equals
347      * the original server provided random 32-bit number.  Should the
348      * verification be successful, the server must add one to the
349      * checksum and construct 8 octets of data, with the first four
350      * octets containing the incremented checksum in network byte
351      * order, the fifth octet containing a bit-mask specifying the
352      * protection mechanisms supported by the server, and the sixth
353      * through eighth octets containing, in network byte order, the
354      * maximum cipher-text buffer size the server is able to receive.
355      * The server must encrypt the 8 octets of data in the session key
356      * and issue that encrypted data in a second ready response.  The
357      * client should consider the server authenticated if the first
358      * four octets the un-encrypted data is equal to one plus the
359      * checksum it previously sent.
360      */
361     
362     if (result = gen_recv(sock, buf1, sizeof buf1))
363         return result;
364
365     /* The client must construct data with the first four octets
366      * containing the original server-issued checksum in network byte
367      * order, the fifth octet containing the bit-mask specifying the
368      * selected protection mechanism, the sixth through eighth octets
369      * containing in network byte order the maximum cipher-text buffer
370      * size the client is able to receive, and the following octets
371      * containing a user name string.  The client must then append
372      * from one to eight octets so that the length of the data is a
373      * multiple of eight octets. The client must then PCBC encrypt the
374      * data with the session key and respond to the second ready
375      * response with the encrypted data.  The server decrypts the data
376      * and verifies the contained checksum.  The username field
377      * identifies the user for whom subsequent IMAP operations are to
378      * be performed; the server must verify that the principal
379      * identified in the Kerberos ticket is authorized to connect as
380      * that user.  After these verifications, the authentication
381      * process is complete.
382      */
383
384     len = from64tobits(buf2, buf1);
385     if (len < 0) {
386         report(stderr, _("could not decode BASE64 ready response\n"));
387         return PS_AUTHFAIL;
388     }
389
390     des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
391     memcpy(challenge2.cstr, buf2, 4);
392     if (ntohl(challenge2.cint) != challenge1.cint + 1) {
393         report(stderr, _("challenge mismatch\n"));
394         return PS_AUTHFAIL;
395     }       
396
397     memset(authenticator.dat, 0, sizeof authenticator.dat);
398
399     result = htonl(challenge1.cint);
400     memcpy(authenticator.dat, &result, sizeof result);
401
402     /* The protection mechanisms and their corresponding bit-masks are as
403      * follows:
404      *
405      * 1 No protection mechanism
406      * 2 Integrity (krb_mk_safe) protection
407      * 4 Privacy (krb_mk_priv) protection
408      */
409     authenticator.dat[4] = 1;
410
411     len = strlen(tktuser);
412     strncpy(authenticator.dat+8, tktuser, len);
413     authenticator.length = len + 8 + 1;
414     while (authenticator.length & 7) {
415         authenticator.length++;
416     }
417     des_pcbc_encrypt((des_cblock *)authenticator.dat,
418             (des_cblock *)authenticator.dat, authenticator.length, schedule,
419             &session, 1);
420
421     to64frombits(buf1, authenticator.dat, authenticator.length);
422     if (outlevel >= O_MONITOR) {
423         report(stdout, "IMAP> %s\n", buf1);
424     }
425     SockWrite(sock, buf1, strlen(buf1));
426     SockWrite(sock, "\r\n", 2);
427
428     if (result = gen_recv(sock, buf1, sizeof buf1))
429         return result;
430
431     if (strstr(buf1, "OK")) {
432         return PS_SUCCESS;
433     }
434     else {
435         return PS_AUTHFAIL;
436     }
437 }
438 #endif /* KERBEROS_V4 */
439
440 #ifdef GSSAPI
441 #define GSSAUTH_P_NONE      1
442 #define GSSAUTH_P_INTEGRITY 2
443 #define GSSAUTH_P_PRIVACY   4
444
445 static int do_gssauth(int sock, char *hostname, char *username)
446 {
447     gss_buffer_desc request_buf, send_token;
448     gss_buffer_t sec_token;
449     gss_name_t target_name;
450     gss_ctx_id_t context;
451     gss_OID mech_name;
452     gss_qop_t quality;
453     int cflags;
454     OM_uint32 maj_stat, min_stat;
455     char buf1[8192], buf2[8192], server_conf_flags;
456     unsigned long buf_size;
457     int result;
458
459     /* first things first: get an imap ticket for host */
460     sprintf(buf1, "imap@%s", hostname);
461     request_buf.value = buf1;
462     request_buf.length = strlen(buf1) + 1;
463     maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name,
464         &target_name);
465     if (maj_stat != GSS_S_COMPLETE) {
466         report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
467         return PS_AUTHFAIL;
468     }
469     else if (outlevel >= O_DEBUG) {
470         maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
471             &mech_name);
472         report(stderr, _("Using service name [%s]\n"),request_buf.value);
473         maj_stat = gss_release_buffer(&min_stat, &request_buf);
474     }
475
476     gen_send(sock, "AUTHENTICATE GSSAPI");
477
478     /* upon receipt of the GSSAPI authentication request, server returns
479      * null data ready response. */
480     if (result = gen_recv(sock, buf1, sizeof buf1)) {
481         return result;
482     }
483
484     /* now start the security context initialisation loop... */
485     sec_token = GSS_C_NO_BUFFER;
486     context = GSS_C_NO_CONTEXT;
487     if (outlevel >= O_VERBOSE)
488         report(stdout, _("Sending credentials\n"));
489     do {
490         maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL, 
491             &context, target_name, NULL, 0, 0, NULL, sec_token, NULL,
492             &send_token, &cflags, NULL);
493         if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
494             report(stderr, _("Error exchanging credentials\n"));
495             gss_release_name(&min_stat, &target_name);
496             /* wake up server and await NO response */
497             SockWrite(sock, "\r\n", 2);
498             if (result = gen_recv(sock, buf1, sizeof buf1))
499                 return result;
500             return PS_AUTHFAIL;
501         }
502         to64frombits(buf1, send_token.value, send_token.length);
503         gss_release_buffer(&min_stat, &send_token);
504         SockWrite(sock, buf1, strlen(buf1));
505         SockWrite(sock, "\r\n", 2);
506         if (outlevel >= O_MONITOR)
507             report(stdout, "IMAP> %s\n", buf1);
508         if (maj_stat == GSS_S_CONTINUE_NEEDED) {
509             if (result = gen_recv(sock, buf1, sizeof buf1)) {
510                 gss_release_name(&min_stat, &target_name);
511                 return result;
512             }
513             request_buf.length = from64tobits(buf2, buf1 + 2);
514             request_buf.value = buf2;
515             sec_token = &request_buf;
516         }
517     } while (maj_stat == GSS_S_CONTINUE_NEEDED);
518     gss_release_name(&min_stat, &target_name);
519
520     /* get security flags and buffer size */
521     if (result = gen_recv(sock, buf1, sizeof buf1)) {
522         return result;
523     }
524     request_buf.length = from64tobits(buf2, buf1 + 2);
525     request_buf.value = buf2;
526
527     maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
528         &cflags, &quality);
529     if (maj_stat != GSS_S_COMPLETE) {
530         report(stderr, _("Couldn't unwrap security level data\n"));
531         gss_release_buffer(&min_stat, &send_token);
532         return PS_AUTHFAIL;
533     }
534     if (outlevel >= O_DEBUG)
535         report(stdout, _("Credential exchange complete\n"));
536     /* first octet is security levels supported. We want none, for now */
537     server_conf_flags = ((char *)send_token.value)[0];
538     if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
539         report(stderr, _("Server requires integrity and/or privacy\n"));
540         gss_release_buffer(&min_stat, &send_token);
541         return PS_AUTHFAIL;
542     }
543     ((char *)send_token.value)[0] = 0;
544     buf_size = ntohl(*((long *)send_token.value));
545     /* we don't care about buffer size if we don't wrap data */
546     gss_release_buffer(&min_stat, &send_token);
547     if (outlevel >= O_DEBUG) {
548         report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
549             server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
550             server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
551             server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
552         report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
553     }
554
555     /* now respond in kind (hack!!!) */
556     buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
557     memcpy(buf1, &buf_size, 4);
558     buf1[0] = GSSAUTH_P_NONE;
559     strcpy(buf1+4, username); /* server decides if princ is user */
560     request_buf.length = 4 + strlen(username) + 1;
561     request_buf.value = buf1;
562     maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
563         &cflags, &send_token);
564     if (maj_stat != GSS_S_COMPLETE) {
565         report(stderr, _("Error creating security level request\n"));
566         return PS_AUTHFAIL;
567     }
568     to64frombits(buf1, send_token.value, send_token.length);
569     if (outlevel >= O_DEBUG) {
570         report(stdout, _("Requesting authorisation as %s\n"), username);
571         report(stdout, "IMAP> %s\n",buf1);
572     }
573     SockWrite(sock, buf1, strlen(buf1));
574     SockWrite(sock, "\r\n", 2);
575
576     /* we should be done. Get status and finish up */
577     if (result = gen_recv(sock, buf1, sizeof buf1))
578         return result;
579     if (strstr(buf1, "OK")) {
580         /* flush security context */
581         if (outlevel >= O_DEBUG)
582             report(stdout, _("Releasing GSS credentials\n"));
583         maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
584         if (maj_stat != GSS_S_COMPLETE) {
585             report(stderr, _("Error releasing credentials\n"));
586             return PS_AUTHFAIL;
587         }
588         /* send_token may contain a notification to the server to flush
589          * credentials. RFC 1731 doesn't specify what to do, and since this
590          * support is only for authentication, we'll assume the server
591          * knows enough to flush its own credentials */
592         gss_release_buffer(&min_stat, &send_token);
593         return PS_SUCCESS;
594     }
595
596     return PS_AUTHFAIL;
597 }       
598 #endif /* GSSAPI */
599
600 static void hmac_md5 (unsigned char *password,  size_t pass_len,
601                       unsigned char *challenge, size_t chal_len,
602                       unsigned char *response,  size_t resp_len)
603 {
604     int i;
605     unsigned char ipad[64];
606     unsigned char opad[64];
607     unsigned char hash_passwd[16];
608
609     MD5_CTX ctx;
610     
611     if (resp_len != 16)
612         return;
613
614     if (pass_len > sizeof (ipad))
615     {
616         MD5Init (&ctx);
617         MD5Update (&ctx, password, pass_len);
618         MD5Final (hash_passwd, &ctx);
619         password = hash_passwd; pass_len = sizeof (hash_passwd);
620     }
621
622     memset (ipad, 0, sizeof (ipad));
623     memset (opad, 0, sizeof (opad));
624     memcpy (ipad, password, pass_len);
625     memcpy (opad, password, pass_len);
626
627     for (i=0; i<64; i++) {
628         ipad[i] ^= 0x36;
629         opad[i] ^= 0x5c;
630     }
631
632     MD5Init (&ctx);
633     MD5Update (&ctx, ipad, sizeof (ipad));
634     MD5Update (&ctx, challenge, chal_len);
635     MD5Final (response, &ctx);
636
637     MD5Init (&ctx);
638     MD5Update (&ctx, opad, sizeof (opad));
639     MD5Update (&ctx, response, resp_len);
640     MD5Final (response, &ctx);
641 }
642
643
644 static int do_cram_md5 (int sock, struct query *ctl)
645 /* authenticate as per RFC2195 */
646 {
647     int result;
648     int len;
649     unsigned char buf1[1024];
650     unsigned char msg_id[768];
651     unsigned char response[16];
652     unsigned char reply[1024];
653
654     gen_send (sock, "AUTHENTICATE CRAM-MD5");
655
656     /* From RFC2195:
657      * The data encoded in the first ready response contains an
658      * presumptively arbitrary string of random digits, a timestamp, and the
659      * fully-qualified primary host name of the server.  The syntax of the
660      * unencoded form must correspond to that of an RFC 822 'msg-id'
661      * [RFC822] as described in [POP3].
662      */
663
664     if (result = gen_recv (sock, buf1, sizeof (buf1))) {
665         return result;
666     }
667
668     len = from64tobits (msg_id, buf1);
669     if (len < 0) {
670         report (stderr, _("could not decode BASE64 challenge\n"));
671         return PS_AUTHFAIL;
672     } else if (len < sizeof (msg_id)) {
673         msg_id[len] = 0;
674     } else {
675         msg_id[sizeof (msg_id)-1] = 0;
676     }
677     if (outlevel >= O_DEBUG) {
678         report (stdout, "decoded as %s\n", msg_id);
679     }
680
681     /* The client makes note of the data and then responds with a string
682      * consisting of the user name, a space, and a 'digest'.  The latter is
683      * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where
684      * the key is a shared secret and the digested text is the timestamp
685      * (including angle-brackets).
686      */
687
688     hmac_md5 (ctl->password, strlen (ctl->password),
689               msg_id, strlen (msg_id),
690               response, sizeof (response));
691
692 #ifdef HAVE_SNPRINTF
693     snprintf (reply, sizeof (reply),
694 #else
695     sprintf(reply,
696 #endif
697               "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", 
698               ctl->remotename,
699               response[0], response[1], response[2], response[3],
700               response[4], response[5], response[6], response[7],
701               response[8], response[9], response[10], response[11],
702               response[12], response[13], response[14], response[15]);
703
704     if (outlevel >= O_DEBUG) {
705         report (stdout, "replying with %s\n", reply);
706     }
707
708     to64frombits (buf1, reply, strlen (reply));
709     if (outlevel >= O_MONITOR) {
710         report (stdout, "IMAP> %s\n", buf1);
711     }
712     SockWrite (sock, buf1, strlen (buf1));
713     SockWrite (sock, "\r\n", 2);
714
715     if (result = gen_recv (sock, buf1, sizeof (buf1)))
716         return result;
717
718     if (strstr (buf1, "OK")) {
719         return PS_SUCCESS;
720     } else {
721         return PS_AUTHFAIL;
722     }
723 }
724
725 int imap_canonicalize(char *result, char *passwd)
726 /* encode an IMAP password as per RFC1730's quoting conventions */
727 {
728     int i, j;
729
730     j = 0;
731     for (i = 0; i < strlen(passwd); i++)
732     {
733         if ((passwd[i] == '\\') || (passwd[i] == '"'))
734             result[j++] = '\\';
735         result[j++] = passwd[i];
736     }
737     result[j] = '\0';
738
739     return(i);
740 }
741
742 int imap_getauth(int sock, struct query *ctl, char *greeting)
743 /* apply for connection authorization */
744 {
745     int ok = 0;
746     char        password[PASSWORDLEN*2];
747
748     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
749     capabilities[0] = '\0';
750     if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
751     {
752         /* UW-IMAP server 10.173 notifies in all caps */
753         if (strstr(capabilities, "IMAP4REV1"))
754         {
755             imap_version = IMAP4rev1;
756             if (outlevel >= O_DEBUG)
757                 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
758         }
759         else
760         {
761             imap_version = IMAP4;
762             if (outlevel >= O_DEBUG)
763                 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
764         }
765     }
766     else if (ok == PS_ERROR)
767     {
768         imap_version = IMAP2;
769         if (outlevel >= O_DEBUG)
770             report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
771     }
772     else
773         return(ok);
774
775     peek_capable = (imap_version >= IMAP4);
776
777     if (preauth)
778         return(PS_SUCCESS);
779
780 #if OPIE
781     if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
782     {
783         if (outlevel >= O_DEBUG)
784             report(stdout, _("OTP authentication is supported\n"));
785         if (do_otp(sock, ctl) == PS_SUCCESS)
786             return(PS_SUCCESS);
787     };
788 #endif /* OPIE */
789
790 #ifdef GSSAPI
791     if (strstr(capabilities, "AUTH=GSSAPI"))
792     {
793         if (ctl->server.protocol == P_IMAP_GSS)
794         {
795             if (outlevel >= O_DEBUG)
796                 report(stdout, _("GSS authentication is supported\n"));
797             return do_gssauth(sock, ctl->server.truename, ctl->remotename);
798         }
799     }
800     else if (ctl->server.protocol == P_IMAP_GSS)
801     {
802         report(stderr, 
803                _("Required GSS capability not supported by server\n"));
804         return(PS_AUTHFAIL);
805     }
806 #endif /* GSSAPI */
807
808 #ifdef KERBEROS_V4
809     if (strstr(capabilities, "AUTH=KERBEROS_V4"))
810     {
811         if (outlevel >= O_DEBUG)
812             report(stdout, _("KERBEROS_V4 authentication is supported\n"));
813
814         if (ctl->server.protocol == P_IMAP_K4)
815         {
816             if ((ok = do_rfc1731(sock, ctl->server.truename)))
817             {
818                 if (outlevel >= O_MONITOR)
819                     report(stdout, "IMAP> *\n");
820                 SockWrite(sock, "*\r\n", 3);
821             }
822             
823             return(ok);
824         }
825         /* else fall through to ordinary AUTH=LOGIN case */
826     }
827     else if (ctl->server.protocol == P_IMAP_K4)
828     {
829         report(stderr, 
830                _("Required KERBEROS_V4 capability not supported by server\n"));
831         return(PS_AUTHFAIL);
832     }
833 #endif /* KERBEROS_V4 */
834
835     if (strstr (capabilities, "AUTH=CRAM-MD5"))
836     {
837         if (outlevel >= O_DEBUG)
838             report (stdout, _("CRAM-MD5 authentication is supported\n"));
839         if ((ok = do_cram_md5 (sock, ctl)))
840         {
841             if (outlevel >= O_MONITOR)
842                 report (stdout, "IMAP> *\n");
843             SockWrite (sock, "*\r\n", 3);
844         }
845         return ok;
846     }
847
848 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
849     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
850     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
851       report(stderr, 
852              _("Required LOGIN capability not supported by server\n"));
853       return PS_AUTHFAIL;
854     };
855 #endif /* __UNUSED__ */
856
857     imap_canonicalize(password, ctl->password);
858     ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
859     if (ok)
860         return(ok);
861     
862     /* 
863      * Assumption: expunges are cheap, so we want to do them
864      * after every message unless user said otherwise.
865      */
866     if (NUM_SPECIFIED(ctl->expunge))
867         expunge_period = NUM_VALUE_OUT(ctl->expunge);
868     else
869         expunge_period = 1;
870
871     return(PS_SUCCESS);
872 }
873
874 static int internal_expunge(int sock)
875 /* ship an expunge, resetting associated counters */
876 {
877     int ok;
878
879     if ((ok = gen_transact(sock, "EXPUNGE")))
880         return(ok);
881
882     expunged += deletions;
883     deletions = 0;
884
885 #ifdef IMAP_UID /* not used */
886     expunge_uids(ctl);
887 #endif /* IMAP_UID */
888
889     return(PS_SUCCESS);
890 }
891
892 static int imap_getrange(int sock, 
893                          struct query *ctl, 
894                          const char *folder, 
895                          int *countp, int *newp, int *bytes)
896 /* get range of messages to be fetched */
897 {
898     int ok;
899
900     /* find out how many messages are waiting */
901     *bytes = recent = unseen = -1;
902
903     if (pass > 1)
904     {
905         /* 
906          * We have to have an expunge here, otherwise the re-poll will
907          * infinite-loop picking up un-expunged messages.
908          */
909         ok = 0;
910         if (deletions && expunge_period > 1)
911             internal_expunge(sock);
912         count = -1;
913         if (ok || gen_transact(sock, "NOOP"))
914         {
915             report(stderr, _("re-poll failed\n"));
916             return(ok);
917         }
918         else if (count == -1)   /* no EXISTS response to NOOP */
919         {
920             count = recent = 0;
921             unseen = -1;
922         }
923     }
924     else
925     {
926         if (!check_only)
927             ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
928         else
929             ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
930         if (ok != 0)
931         {
932             report(stderr, _("mailbox selection failed\n"));
933             return(ok);
934         }
935     }
936
937     *countp = count;
938
939     /*
940      * Note: because IMAP has an is_old method, this number is used
941      * only for the "X messages (Y unseen)" notification.  Accordingly
942      * it doesn't matter much that it can be wrong (e.g. if we see an
943      * UNSEEN response but not all messages above the first UNSEEN one
944      * are likewise).
945      */
946     if (unseen >= 0)            /* optional, but better if we see it */
947         *newp = count - unseen + 1;
948     else if (recent >= 0)       /* mandatory */
949         *newp = recent;
950     else
951         *newp = -1;             /* should never happen, RECENT is mandatory */ 
952
953     expunged = 0;
954
955     return(PS_SUCCESS);
956 }
957
958 static int imap_getsizes(int sock, int count, int *sizes)
959 /* capture the sizes of all messages */
960 {
961     char buf [MSGBUFSIZE+1];
962
963     /*
964      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
965      * won't accept 1:1 as valid set syntax.  Some implementors
966      * should be taken out and shot for excessive anality.
967      */
968     if (count == 1)
969         gen_send(sock, "FETCH 1 RFC822.SIZE", count);
970     else
971         gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
972     for (;;)
973     {
974         int num, size, ok;
975
976         if ((ok = gen_recv(sock, buf, sizeof(buf))))
977             return(ok);
978         if (strstr(buf, "OK"))
979             break;
980         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
981             sizes[num - 1] = size;
982     }
983
984     return(PS_SUCCESS);
985 }
986
987 static int imap_is_old(int sock, struct query *ctl, int number)
988 /* is the given message old? */
989 {
990     int ok;
991
992     /* expunges change the fetch numbers */
993     number -= expunged;
994
995     if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
996         return(PS_ERROR);
997
998     return(seen);
999 }
1000
1001 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1002 /* request headers of nth message */
1003 {
1004     char buf [MSGBUFSIZE+1];
1005     int num;
1006
1007     /* expunges change the fetch numbers */
1008     number -= expunged;
1009
1010     /*
1011      * This is blessed by RFC 1176, RFC1730, RFC2060.
1012      * According to the RFCs, it should *not* set the \Seen flag.
1013      */
1014     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1015
1016     /* looking for FETCH response */
1017     do {
1018         int     ok;
1019
1020         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1021             return(ok);
1022     } while
1023         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
1024
1025     if (num != number)
1026         return(PS_ERROR);
1027     else
1028         return(PS_SUCCESS);
1029 }
1030
1031 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1032 /* request body of nth message */
1033 {
1034     char buf [MSGBUFSIZE+1], *cp;
1035     int num;
1036
1037     /* expunges change the fetch numbers */
1038     number -= expunged;
1039
1040     /*
1041      * If we're using IMAP4, we can fetch the message without setting its
1042      * seen flag.  This is good!  It means that if the protocol exchange
1043      * craps out during the message, it will still be marked `unseen' on
1044      * the server.
1045      *
1046      * However...*don't* do this if we're using keep to suppress deletion!
1047      * In that case, marking the seen flag is the only way to prevent the
1048      * message from being re-fetched on subsequent runs.
1049      */
1050     switch (imap_version)
1051     {
1052     case IMAP4rev1:     /* RFC 2060 */
1053         if (!ctl->keep)
1054             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1055         else
1056             gen_send(sock, "FETCH %d BODY[TEXT]", number);
1057         break;
1058
1059     case IMAP4:         /* RFC 1730 */
1060         if (!ctl->keep)
1061             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1062         else
1063             gen_send(sock, "FETCH %d RFC822.TEXT", number);
1064         break;
1065
1066     default:            /* RFC 1176 */
1067         gen_send(sock, "FETCH %d RFC822.TEXT", number);
1068         break;
1069     }
1070
1071     /* looking for FETCH response */
1072     do {
1073         int     ok;
1074
1075         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1076             return(ok);
1077     } while
1078         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1079
1080     if (num != number)
1081         return(PS_ERROR);
1082
1083     /* try to extract a length */
1084     if ((cp = strchr(buf, '{')))
1085         *lenp = atoi(cp + 1);
1086     else
1087         *lenp = 0;
1088
1089     return(PS_SUCCESS);
1090 }
1091
1092 static int imap_trail(int sock, struct query *ctl, int number)
1093 /* discard tail of FETCH response after reading message text */
1094 {
1095     /* expunges change the fetch numbers */
1096     /* number -= expunged; */
1097
1098     for (;;)
1099     {
1100         char buf[MSGBUFSIZE+1];
1101         int ok;
1102
1103         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1104             return(ok);
1105
1106         /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1107         if (strstr(buf, "OK"))
1108             break;
1109     }
1110
1111     return(PS_SUCCESS);
1112 }
1113
1114 static int imap_delete(int sock, struct query *ctl, int number)
1115 /* set delete flag for given message */
1116 {
1117     int ok;
1118
1119     /* expunges change the fetch numbers */
1120     number -= expunged;
1121
1122     /*
1123      * Use SILENT if possible as a minor throughput optimization.
1124      * Note: this has been dropped from IMAP4rev1.
1125      *
1126      * We set Seen because there are some IMAP servers (notably HP
1127      * OpenMail) that do message-receipt DSNs, but only when the seen
1128      * bit is set.  This is the appropriate time -- we get here right
1129      * after the local SMTP response that says delivery was
1130      * successful.
1131      */
1132     if ((ok = gen_transact(sock,
1133                         imap_version == IMAP4 
1134                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1135                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1136                         number)))
1137         return(ok);
1138     else
1139         deletions++;
1140
1141     /*
1142      * We do an expunge after expunge_period messages, rather than
1143      * just before quit, so that a line hit during a long session
1144      * won't result in lots of messages being fetched again during
1145      * the next session.
1146      */
1147     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1148         internal_expunge(sock);
1149
1150     return(PS_SUCCESS);
1151 }
1152
1153 static int imap_logout(int sock, struct query *ctl)
1154 /* send logout command */
1155 {
1156     /* if expunges after deletion have been suppressed, ship one now */
1157     if (NUM_SPECIFIED(expunge_period) && NUM_ZERO(expunge_period) && deletions)
1158         internal_expunge(sock);
1159
1160     return(gen_transact(sock, "LOGOUT"));
1161 }
1162
1163 const static struct method imap =
1164 {
1165     "IMAP",             /* Internet Message Access Protocol */
1166 #if INET6
1167     "imap",
1168 #else /* INET6 */
1169     143,                /* standard IMAP2bis/IMAP4 port */
1170 #endif /* INET6 */
1171     TRUE,               /* this is a tagged protocol */
1172     FALSE,              /* no message delimiter */
1173     imap_ok,            /* parse command response */
1174     imap_canonicalize,  /* deal with embedded slashes and spaces */
1175     imap_getauth,       /* get authorization */
1176     imap_getrange,      /* query range of messages */
1177     imap_getsizes,      /* get sizes of messages (used for --limit option */
1178     imap_is_old,        /* no UID check */
1179     imap_fetch_headers, /* request given message headers */
1180     imap_fetch_body,    /* request given message body */
1181     imap_trail,         /* eat message trailer */
1182     imap_delete,        /* delete the message */
1183     imap_logout,        /* expunge and exit */
1184     TRUE,               /* yes, we can re-poll */
1185 };
1186
1187 int doIMAP(struct query *ctl)
1188 /* retrieve messages using IMAP Version 2bis or Version 4 */
1189 {
1190     return(do_protocol(ctl, &imap));
1191 }
1192
1193 /* imap.c ends here */