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