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