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