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