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