]> Pileus Git - ~andy/fetchmail/blob - imap.c
Re-enable OPIE build.
[~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(__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_opts.poll_interval == -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         gss_release_buffer(&min_stat, &send_token);
565         return PS_SUCCESS;
566     }
567
568     return PS_AUTHFAIL;
569 }       
570 #endif /* GSSAPI */
571
572 int imap_canonicalize(char *result, char *passwd)
573 /* encode an IMAP password as per RFC1730's quoting conventions */
574 {
575     int i, j;
576
577     j = 0;
578     for (i = 0; i < strlen(passwd); i++)
579     {
580         if ((passwd[i] == '\\') || (passwd[i] == '"'))
581             result[j++] = '\\';
582         result[j++] = passwd[i];
583     }
584     result[j] = '\0';
585
586     return(i);
587 }
588
589 int imap_getauth(int sock, struct query *ctl, char *greeting)
590 /* apply for connection authorization */
591 {
592     int ok = 0;
593     char        password[PASSWORDLEN*2];
594
595     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
596     capabilities[0] = '\0';
597     if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
598     {
599         /* UW-IMAP server 10.173 notifies in all caps */
600         if (strstr(capabilities, "IMAP4REV1"))
601         {
602             imap_version = IMAP4rev1;
603             if (outlevel == O_VERBOSE)
604                 error(0, 0, "Protocol identified as IMAP4 rev 1");
605         }
606         else
607         {
608             imap_version = IMAP4;
609             if (outlevel == O_VERBOSE)
610             error(0, 0, "Protocol identified as IMAP4 rev 0");
611         }
612     }
613     else if (ok == PS_ERROR)
614     {
615         imap_version = IMAP2;
616         if (outlevel == O_VERBOSE)
617             error(0, 0, "Protocol identified as IMAP2 or IMAP2BIS");
618     }
619     else
620         return(ok);
621
622     peek_capable = (imap_version >= IMAP4);
623
624 #if OPIE
625     if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP")) {
626       if (outlevel == O_VERBOSE)
627         error(0, 0, "OTP authentication is supported");
628       if (do_otp(sock, ctl) == PS_SUCCESS)
629         return PS_SUCCESS;
630     };
631 #endif /* OPIE */
632
633 #ifdef GSSAPI
634     if (strstr(capabilities, "AUTH=GSSAPI"))
635     {
636         if (ctl->server.protocol == P_IMAP_GSS)
637         {
638             if (outlevel == O_VERBOSE)
639                 error(0, 0, "GSS authentication is supported");
640             return do_gssauth(sock, ctl->server.truename, ctl->remotename);
641         }
642     }
643     else if (ctl->server.protocol == P_IMAP_GSS)
644     {
645         error(0,-1, "Required GSS capability not supported by server");
646         return(PS_AUTHFAIL);
647     }
648 #endif /* GSSAPI */
649
650 #ifdef KERBEROS_V4
651     if (strstr(capabilities, "AUTH=KERBEROS_V4"))
652     {
653         if (outlevel == O_VERBOSE)
654             error(0, 0, "KERBEROS_V4 authentication is supported");
655
656         if (ctl->server.protocol == P_IMAP_K4)
657         {
658             if ((ok = do_rfc1731(sock, ctl->server.truename)))
659             {
660                 if (outlevel == O_VERBOSE)
661                     error(0, 0, "IMAP> *");
662                 SockWrite(sock, "*\r\n", 3);
663             }
664             
665             return(ok);
666         }
667         /* else fall through to ourdinary AUTH=LOGIN case */
668     }
669     else if (ctl->server.protocol == P_IMAP_K4)
670     {
671         error(0,-1, "Required KERBEROS_V4 capability not supported by server");
672         return(PS_AUTHFAIL);
673     }
674 #endif /* KERBEROS_V4 */
675
676 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
677     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
678     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
679       error(0,-1, "Required LOGIN capability not supported by server");
680       return PS_AUTHFAIL;
681     };
682 #endif /* __UNUSED__ */
683
684     imap_canonicalize(password, ctl->password);
685     ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", ctl->remotename, password);
686     if (ok)
687         return(ok);
688     
689     return(PS_SUCCESS);
690 }
691
692 static int internal_expunge(int sock)
693 /* ship an expunge, resetting associated counters */
694 {
695     int ok;
696
697     if ((ok = gen_transact(sock, "EXPUNGE")))
698         return(ok);
699
700     expunged += deletions;
701     deletions = 0;
702
703 #ifdef IMAP_UID /* not used */
704     expunge_uids(ctl);
705 #endif /* IMAP_UID */
706
707     return(PS_SUCCESS);
708 }
709
710 static int imap_getrange(int sock, 
711                          struct query *ctl, 
712                          const char *folder, 
713                          int *countp, int *newp, int *bytes)
714 /* get range of messages to be fetched */
715 {
716     int ok;
717
718     /* find out how many messages are waiting */
719     *bytes = recent = unseen = -1;
720
721     if (pass > 1)
722     {
723         /* 
724          * We have to have an expunge here, otherwise the re-poll will
725          * infinite-loop picking up un-expunged message.
726          */
727         ok = 0;
728         if (deletions && ctl->expunge > 1)
729             internal_expunge(sock);
730         count = -1;
731         if (ok || gen_transact(sock, "NOOP"))
732         {
733             error(0, 0, "re-poll failed");
734             return(ok);
735         }
736         else if (count == -1)   /* no EXISTS response to NOOP */
737         {
738             count = recent = 0;
739             unseen = -1;
740         }
741     }
742     else
743     {
744         if (!check_only)
745             ok = gen_transact(sock, "SELECT %s", folder ? folder : "INBOX");
746         else
747             ok = gen_transact(sock, "EXAMINE %s", folder ? folder : "INBOX");
748         if (ok != 0)
749         {
750             error(0, 0, "mailbox selection failed");
751             return(ok);
752         }
753     }
754
755     *countp = count;
756
757     /*
758      * Note: because IMAP has an is_old method, this number is used
759      * only for the "X messages (Y unseen)" notification.  Accordingly
760      * it doesn't matter much that it can be wrong (e.g. if we see an
761      * UNSEEN response but not all messages above the first UNSEEN one
762      * are likewise).
763      */
764     if (unseen >= 0)            /* optional, but better if we see it */
765         *newp = count - unseen + 1;
766     else if (recent >= 0)       /* mandatory */
767         *newp = recent;
768     else
769         *newp = -1;             /* should never happen, RECENT is mandatory */ 
770
771     expunged = 0;
772
773     return(PS_SUCCESS);
774 }
775
776 static int imap_getsizes(int sock, int count, int *sizes)
777 /* capture the sizes of all messages */
778 {
779     char buf [MSGBUFSIZE+1];
780
781     /*
782      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
783      * won't accept 1:1 as valid set syntax.  Some implementors
784      * should be taken out and shot for excessive anality.
785      */
786     if (count == 1)
787         gen_send(sock, "FETCH 1 RFC822.SIZE", count);
788     else
789         gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
790     for (;;)
791     {
792         int num, size, ok;
793
794         if ((ok = gen_recv(sock, buf, sizeof(buf))))
795             return(ok);
796         if (strstr(buf, "OK"))
797             break;
798         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
799             sizes[num - 1] = size;
800     }
801
802     return(PS_SUCCESS);
803 }
804
805 static int imap_is_old(int sock, struct query *ctl, int number)
806 /* is the given message old? */
807 {
808     int ok;
809
810     /* expunges change the fetch numbers */
811     number -= expunged;
812
813     if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
814         return(PS_ERROR);
815
816     return(seen);
817 }
818
819 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
820 /* request headers of nth message */
821 {
822     char buf [MSGBUFSIZE+1];
823     int num;
824
825     /* expunges change the fetch numbers */
826     number -= expunged;
827
828     /*
829      * This is blessed by RFC 1176, RFC1730, RFC2060.
830      * According to the RFCs, it should *not* set the \Seen flag.
831      */
832     gen_send(sock, "FETCH %d RFC822.HEADER", number);
833
834     /* looking for FETCH response */
835     do {
836         int     ok;
837
838         if ((ok = gen_recv(sock, buf, sizeof(buf))))
839             return(ok);
840     } while
841         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
842
843     if (num != number)
844         return(PS_ERROR);
845     else
846         return(PS_SUCCESS);
847 }
848
849 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
850 /* request body of nth message */
851 {
852     char buf [MSGBUFSIZE+1], *cp;
853     int num;
854
855     /* expunges change the fetch numbers */
856     number -= expunged;
857
858     /*
859      * If we're using IMAP4, we can fetch the message without setting its
860      * seen flag.  This is good!  It means that if the protocol exchange
861      * craps out during the message, it will still be marked `unseen' on
862      * the server.
863      *
864      * However...*don't* do this if we're using keep to suppress deletion!
865      * In that case, marking the seen flag is the only way to prevent the
866      * message from being re-fetched on subsequent runs.
867      */
868     switch (imap_version)
869     {
870     case IMAP4rev1:     /* RFC 2060 */
871         if (!ctl->keep)
872             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
873         else
874             gen_send(sock, "FETCH %d BODY[TEXT]", number);
875         break;
876
877     case IMAP4:         /* RFC 1730 */
878         if (!ctl->keep)
879             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
880         else
881             gen_send(sock, "FETCH %d RFC822.TEXT", number);
882         break;
883
884     default:            /* RFC 1176 */
885         gen_send(sock, "FETCH %d RFC822.TEXT", number);
886         break;
887     }
888
889     /* looking for FETCH response */
890     do {
891         int     ok;
892
893         if ((ok = gen_recv(sock, buf, sizeof(buf))))
894             return(ok);
895     } while
896         (sscanf(buf+2, "%d FETCH", &num) != 1);
897
898     if (num != number)
899         return(PS_ERROR);
900
901     /* try to extract a length */
902     if ((cp = strchr(buf, '{')))
903         *lenp = atoi(cp + 1);
904     else
905         *lenp = 0;
906
907     return(PS_SUCCESS);
908 }
909
910 static int imap_trail(int sock, struct query *ctl, int number)
911 /* discard tail of FETCH response after reading message text */
912 {
913     /* expunges change the fetch numbers */
914     /* number -= expunged; */
915
916     for (;;)
917     {
918         char buf[MSGBUFSIZE+1];
919         int ok;
920
921         if ((ok = gen_recv(sock, buf, sizeof(buf))))
922             return(ok);
923
924         /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
925         if (strstr(buf, "OK"))
926             break;
927     }
928
929     return(PS_SUCCESS);
930 }
931
932 static int imap_delete(int sock, struct query *ctl, int number)
933 /* set delete flag for given message */
934 {
935     int ok;
936
937     /* expunges change the fetch numbers */
938     number -= expunged;
939
940     /*
941      * Use SILENT if possible as a minor throughput optimization.
942      * Note: this has been dropped from IMAP4rev1.
943      */
944     if ((ok = gen_transact(sock,
945                         imap_version == IMAP4 
946                                 ? "STORE %d +FLAGS.SILENT (\\Deleted)"
947                                 : "STORE %d +FLAGS (\\Deleted)", 
948                         number)))
949         return(ok);
950     else
951         deletions++;
952
953     /*
954      * We do an expunge after ctl->expunge messages, rather than
955      * just before quit, so that a line hit during a long session
956      * won't result in lots of messages being fetched again during
957      * the next session.
958      */
959     if (NUM_NONZERO(ctl->expunge) && (deletions % ctl->expunge) == 0)
960         internal_expunge(sock);
961
962     return(PS_SUCCESS);
963 }
964
965 static int imap_logout(int sock, struct query *ctl)
966 /* send logout command */
967 {
968     /* if expunges after deletion have been suppressed, ship one now */
969     if (NUM_SPECIFIED(ctl->expunge) && NUM_ZERO(ctl->expunge) && deletions)
970         internal_expunge(sock);
971
972     return(gen_transact(sock, "LOGOUT"));
973 }
974
975 const static struct method imap =
976 {
977     "IMAP",             /* Internet Message Access Protocol */
978 #if INET6
979     "imap",
980 #else /* INET6 */
981     143,                /* standard IMAP2bis/IMAP4 port */
982 #endif /* INET6 */
983     TRUE,               /* this is a tagged protocol */
984     FALSE,              /* no message delimiter */
985     imap_ok,            /* parse command response */
986     imap_canonicalize,  /* deal with embedded slashes and spaces */
987     imap_getauth,       /* get authorization */
988     imap_getrange,      /* query range of messages */
989     imap_getsizes,      /* get sizes of messages (used for --limit option */
990     imap_is_old,        /* no UID check */
991     imap_fetch_headers, /* request given message headers */
992     imap_fetch_body,    /* request given message body */
993     imap_trail,         /* eat message trailer */
994     imap_delete,        /* delete the message */
995     imap_logout,        /* expunge and exit */
996     TRUE,               /* yes, we can re-poll */
997 };
998
999 int doIMAP(struct query *ctl)
1000 /* retrieve messages using IMAP Version 2bis or Version 4 */
1001 {
1002     return(do_protocol(ctl, &imap));
1003 }
1004
1005 /* imap.c ends here */