]> Pileus Git - ~andy/fetchmail/blob - imap.c
Also expunge on re-poll when expunge period is zero.
[~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     /* 
778      * Assumption: expunges are cheap, so we want to do them
779      * after every message unless user said otherwise.
780      */
781     if (NUM_SPECIFIED(ctl->expunge))
782         expunge_period = NUM_VALUE_OUT(ctl->expunge);
783     else
784         expunge_period = 1;
785
786     if (preauth)
787         return(PS_SUCCESS);
788
789 #if OPIE
790     if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
791     {
792         if (outlevel >= O_DEBUG)
793             report(stdout, _("OTP authentication is supported\n"));
794         if (do_otp(sock, ctl) == PS_SUCCESS)
795             return(PS_SUCCESS);
796     };
797 #endif /* OPIE */
798
799 #ifdef GSSAPI
800     if (strstr(capabilities, "AUTH=GSSAPI"))
801     {
802         if (ctl->server.protocol == P_IMAP_GSS)
803         {
804             if (outlevel >= O_DEBUG)
805                 report(stdout, _("GSS authentication is supported\n"));
806             return do_gssauth(sock, ctl->server.truename, ctl->remotename);
807         }
808     }
809     else if (ctl->server.protocol == P_IMAP_GSS)
810     {
811         report(stderr, 
812                _("Required GSS capability not supported by server\n"));
813         return(PS_AUTHFAIL);
814     }
815 #endif /* GSSAPI */
816
817 #ifdef KERBEROS_V4
818     if (strstr(capabilities, "AUTH=KERBEROS_V4"))
819     {
820         if (outlevel >= O_DEBUG)
821             report(stdout, _("KERBEROS_V4 authentication is supported\n"));
822
823         if (ctl->server.protocol == P_IMAP_K4)
824         {
825             if ((ok = do_rfc1731(sock, ctl->server.truename)))
826             {
827                 if (outlevel >= O_MONITOR)
828                     report(stdout, "IMAP> *\n");
829                 SockWrite(sock, "*\r\n", 3);
830             }
831             
832             return(ok);
833         }
834         /* else fall through to ordinary AUTH=LOGIN case */
835     }
836     else if (ctl->server.protocol == P_IMAP_K4)
837     {
838         report(stderr, 
839                _("Required KERBEROS_V4 capability not supported by server\n"));
840         return(PS_AUTHFAIL);
841     }
842 #endif /* KERBEROS_V4 */
843
844     if (strstr (capabilities, "AUTH=CRAM-MD5"))
845     {
846         if (outlevel >= O_DEBUG)
847             report (stdout, _("CRAM-MD5 authentication is supported\n"));
848         if ((ok = do_cram_md5 (sock, ctl)))
849         {
850             if (outlevel >= O_MONITOR)
851                 report (stdout, "IMAP> *\n");
852             SockWrite (sock, "*\r\n", 3);
853         }
854         return ok;
855     }
856
857 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
858     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
859     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
860       report(stderr, 
861              _("Required LOGIN capability not supported by server\n"));
862       return PS_AUTHFAIL;
863     };
864 #endif /* __UNUSED__ */
865
866     imap_canonicalize(password, ctl->password);
867     ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
868     if (ok)
869         return(ok);
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 -- unless the
908          * expunge period is one and we've been nuking each message 
909          * just after deletion.
910          */
911         ok = 0;
912         if (deletions && expunge_period != 1)
913             internal_expunge(sock);
914         count = -1;
915         if (ok || gen_transact(sock, "NOOP"))
916         {
917             report(stderr, _("re-poll failed\n"));
918             return(ok);
919         }
920         else if (count == -1)   /* no EXISTS response to NOOP */
921         {
922             count = recent = 0;
923             unseen = -1;
924         }
925     }
926     else
927     {
928         if (!check_only)
929             ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
930         else
931             ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
932         if (ok != 0)
933         {
934             report(stderr, _("mailbox selection failed\n"));
935             return(ok);
936         }
937     }
938
939     *countp = count;
940
941     /*
942      * Note: because IMAP has an is_old method, this number is used
943      * only for the "X messages (Y unseen)" notification.  Accordingly
944      * it doesn't matter much that it can be wrong (e.g. if we see an
945      * UNSEEN response but not all messages above the first UNSEEN one
946      * are likewise).
947      */
948     if (unseen >= 0)            /* optional, but better if we see it */
949         *newp = count - unseen + 1;
950     else if (recent >= 0)       /* mandatory */
951         *newp = recent;
952     else
953         *newp = -1;             /* should never happen, RECENT is mandatory */ 
954
955     expunged = 0;
956
957     return(PS_SUCCESS);
958 }
959
960 static int imap_getsizes(int sock, int count, int *sizes)
961 /* capture the sizes of all messages */
962 {
963     char buf [MSGBUFSIZE+1];
964
965     /*
966      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
967      * won't accept 1:1 as valid set syntax.  Some implementors
968      * should be taken out and shot for excessive anality.
969      */
970     if (count == 1)
971         gen_send(sock, "FETCH 1 RFC822.SIZE", count);
972     else
973         gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
974     for (;;)
975     {
976         int num, size, ok;
977
978         if ((ok = gen_recv(sock, buf, sizeof(buf))))
979             return(ok);
980         if (strstr(buf, "OK"))
981             break;
982         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
983             sizes[num - 1] = size;
984     }
985
986     return(PS_SUCCESS);
987 }
988
989 static int imap_is_old(int sock, struct query *ctl, int number)
990 /* is the given message old? */
991 {
992     int ok;
993
994     /* expunges change the fetch numbers */
995     number -= expunged;
996
997     if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
998         return(PS_ERROR);
999
1000     return(seen);
1001 }
1002
1003 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1004 /* request headers of nth message */
1005 {
1006     char buf [MSGBUFSIZE+1];
1007     int num;
1008
1009     /* expunges change the fetch numbers */
1010     number -= expunged;
1011
1012     /*
1013      * This is blessed by RFC 1176, RFC1730, RFC2060.
1014      * According to the RFCs, it should *not* set the \Seen flag.
1015      */
1016     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1017
1018     /* looking for FETCH response */
1019     do {
1020         int     ok;
1021
1022         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1023             return(ok);
1024     } while
1025         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
1026
1027     if (num != number)
1028         return(PS_ERROR);
1029     else
1030         return(PS_SUCCESS);
1031 }
1032
1033 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1034 /* request body of nth message */
1035 {
1036     char buf [MSGBUFSIZE+1], *cp;
1037     int num;
1038
1039     /* expunges change the fetch numbers */
1040     number -= expunged;
1041
1042     /*
1043      * If we're using IMAP4, we can fetch the message without setting its
1044      * seen flag.  This is good!  It means that if the protocol exchange
1045      * craps out during the message, it will still be marked `unseen' on
1046      * the server.
1047      *
1048      * However...*don't* do this if we're using keep to suppress deletion!
1049      * In that case, marking the seen flag is the only way to prevent the
1050      * message from being re-fetched on subsequent runs.
1051      */
1052     switch (imap_version)
1053     {
1054     case IMAP4rev1:     /* RFC 2060 */
1055         if (!ctl->keep)
1056             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1057         else
1058             gen_send(sock, "FETCH %d BODY[TEXT]", number);
1059         break;
1060
1061     case IMAP4:         /* RFC 1730 */
1062         if (!ctl->keep)
1063             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1064         else
1065             gen_send(sock, "FETCH %d RFC822.TEXT", number);
1066         break;
1067
1068     default:            /* RFC 1176 */
1069         gen_send(sock, "FETCH %d RFC822.TEXT", number);
1070         break;
1071     }
1072
1073     /* looking for FETCH response */
1074     do {
1075         int     ok;
1076
1077         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1078             return(ok);
1079     } while
1080         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1081
1082     if (num != number)
1083         return(PS_ERROR);
1084
1085     /* try to extract a length */
1086     if ((cp = strchr(buf, '{')))
1087         *lenp = atoi(cp + 1);
1088     else
1089         *lenp = 0;
1090
1091     return(PS_SUCCESS);
1092 }
1093
1094 static int imap_trail(int sock, struct query *ctl, int number)
1095 /* discard tail of FETCH response after reading message text */
1096 {
1097     /* expunges change the fetch numbers */
1098     /* number -= expunged; */
1099
1100     for (;;)
1101     {
1102         char buf[MSGBUFSIZE+1];
1103         int ok;
1104
1105         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1106             return(ok);
1107
1108         /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1109         if (strstr(buf, "OK"))
1110             break;
1111     }
1112
1113     return(PS_SUCCESS);
1114 }
1115
1116 static int imap_delete(int sock, struct query *ctl, int number)
1117 /* set delete flag for given message */
1118 {
1119     int ok;
1120
1121     /* expunges change the fetch numbers */
1122     number -= expunged;
1123
1124     /*
1125      * Use SILENT if possible as a minor throughput optimization.
1126      * Note: this has been dropped from IMAP4rev1.
1127      *
1128      * We set Seen because there are some IMAP servers (notably HP
1129      * OpenMail) that do message-receipt DSNs, but only when the seen
1130      * bit is set.  This is the appropriate time -- we get here right
1131      * after the local SMTP response that says delivery was
1132      * successful.
1133      */
1134     if ((ok = gen_transact(sock,
1135                         imap_version == IMAP4 
1136                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1137                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1138                         number)))
1139         return(ok);
1140     else
1141         deletions++;
1142
1143     /*
1144      * We do an expunge after expunge_period messages, rather than
1145      * just before quit, so that a line hit during a long session
1146      * won't result in lots of messages being fetched again during
1147      * the next session.
1148      */
1149     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1150         internal_expunge(sock);
1151
1152     return(PS_SUCCESS);
1153 }
1154
1155 static int imap_logout(int sock, struct query *ctl)
1156 /* send logout command */
1157 {
1158     /* if expunges after deletion have been suppressed, ship one now */
1159     if (NUM_SPECIFIED(expunge_period) && NUM_ZERO(expunge_period) && deletions)
1160         internal_expunge(sock);
1161
1162     return(gen_transact(sock, "LOGOUT"));
1163 }
1164
1165 const static struct method imap =
1166 {
1167     "IMAP",             /* Internet Message Access Protocol */
1168 #if INET6
1169     "imap",
1170 #else /* INET6 */
1171     143,                /* standard IMAP2bis/IMAP4 port */
1172 #endif /* INET6 */
1173     TRUE,               /* this is a tagged protocol */
1174     FALSE,              /* no message delimiter */
1175     imap_ok,            /* parse command response */
1176     imap_canonicalize,  /* deal with embedded slashes and spaces */
1177     imap_getauth,       /* get authorization */
1178     imap_getrange,      /* query range of messages */
1179     imap_getsizes,      /* get sizes of messages (used for --limit option */
1180     imap_is_old,        /* no UID check */
1181     imap_fetch_headers, /* request given message headers */
1182     imap_fetch_body,    /* request given message body */
1183     imap_trail,         /* eat message trailer */
1184     imap_delete,        /* delete the message */
1185     imap_logout,        /* expunge and exit */
1186     TRUE,               /* yes, we can re-poll */
1187 };
1188
1189 int doIMAP(struct query *ctl)
1190 /* retrieve messages using IMAP Version 2bis or Version 4 */
1191 {
1192     return(do_protocol(ctl, &imap));
1193 }
1194
1195 /* imap.c ends here */