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