]> Pileus Git - ~andy/fetchmail/blob - imap.c
Bug fixes and internationalization improvements.
[~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 #ifdef HAVE_GSSAPI_H
37 #include <gssapi.h>
38 #endif
39 #ifdef HAVE_GSSAPI_GSSAPI_H
40 #include <gssapi/gssapi.h>
41 #endif
42 #ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H
43 #include <gssapi/gssapi_generic.h>
44 #endif
45 #ifndef HAVE_GSS_C_NT_HOSTBASED_SERVICE
46 #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
47 #endif
48 #endif
49
50 #include "md5.h"
51
52 #if OPIE_ENABLE
53 #include <opie.h>
54 #endif /* OPIE_ENABLE */
55
56 #ifndef strstr          /* glibc-2.1 declares this as a macro */
57 extern char *strstr();  /* needed on sysV68 R3V7.1. */
58 #endif /* strstr */
59
60 /* imap_version values */
61 #define IMAP2           -1      /* IMAP2 or IMAP2BIS, RFC1176 */
62 #define IMAP4           0       /* IMAP4 rev 0, RFC1730 */
63 #define IMAP4rev1       1       /* IMAP4 rev 1, RFC2060 */
64
65 static int count, unseen, deletions, imap_version, preauth; 
66 static int expunged, expunge_period, saved_timeout;
67 static flag do_idle;
68 static char capabilities[MSGBUFSIZE+1];
69 static unsigned int *unseen_messages;
70
71 int imap_ok(int sock, char *argbuf)
72 /* parse command response */
73 {
74     char buf[MSGBUFSIZE+1];
75
76     do {
77         int     ok;
78         char    *cp;
79
80         if ((ok = gen_recv(sock, buf, sizeof(buf))))
81             return(ok);
82
83         /* all tokens in responses are caseblind */
84         for (cp = buf; *cp; cp++)
85             if (islower(*cp))
86                 *cp = toupper(*cp);
87
88         /* interpret untagged status responses */
89         if (strstr(buf, "* CAPABILITY"))
90             strncpy(capabilities, buf + 12, sizeof(capabilities));
91         else if (strstr(buf, "EXISTS"))
92         {
93             count = atoi(buf+2);
94             /*
95              * Nasty kluge to handle RFC2177 IDLE.  If we know we're idling
96              * we can't wait for the tag matching the IDLE; we have to tell the
97              * server the IDLE is finished by shipping back a DONE when we
98              * see an EXISTS.  Only after that will a tagged response be
99              * shipped.  The idling flag also gets cleared on a timeout.
100              */
101             if (stage == STAGE_IDLE)
102             {
103                 /* we do our own write and report here to disable tagging */
104                 SockWrite(sock, "DONE\r\n", 6);
105                 if (outlevel >= O_MONITOR)
106                     report(stdout, "IMAP> DONE\n");
107
108                 mytimeout = saved_timeout;
109                 stage = STAGE_FETCH;
110             }
111         }
112         else if (strstr(buf, "PREAUTH"))
113             preauth = TRUE;
114     } while
115         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
116
117     if (tag[0] == '\0')
118     {
119         if (argbuf)
120             strcpy(argbuf, buf);
121         return(PS_SUCCESS); 
122     }
123     else
124     {
125         char    *cp;
126
127         /* skip the tag */
128         for (cp = buf; !isspace(*cp); cp++)
129             continue;
130         while (isspace(*cp))
131             cp++;
132
133         if (strncmp(cp, "OK", 2) == 0)
134         {
135             if (argbuf)
136                 strcpy(argbuf, cp);
137             return(PS_SUCCESS);
138         }
139         else if (strncmp(cp, "BAD", 3) == 0)
140             return(PS_ERROR);
141         else if (strncmp(cp, "NO", 2) == 0)
142         {
143             if (stage == STAGE_GETAUTH) 
144                 return(PS_AUTHFAIL);    /* RFC2060, 6.2.2 */
145             else
146                 return(PS_ERROR);
147         }
148         else
149             return(PS_PROTOCOL);
150     }
151 }
152
153 #if OPIE_ENABLE
154 static int do_otp(int sock, struct query *ctl)
155 {
156     int i, rval;
157     char buffer[128];
158     char challenge[OPIE_CHALLENGE_MAX+1];
159     char response[OPIE_RESPONSE_MAX+1];
160
161     gen_send(sock, "AUTHENTICATE X-OTP");
162
163     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
164         return rval;
165
166     if ((i = from64tobits(challenge, buffer)) < 0) {
167         report(stderr, _("Could not decode initial BASE64 challenge\n"));
168         return PS_AUTHFAIL;
169     };
170
171
172     to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
173
174     if (outlevel >= O_MONITOR)
175         report(stdout, "IMAP> %s\n", buffer);
176
177     /* best not to count on the challenge code handling multiple writes */
178     strcat(buffer, "\r\n");
179     SockWrite(sock, buffer, strlen(buffer));
180
181     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
182         return rval;
183
184     if ((i = from64tobits(challenge, buffer)) < 0) {
185         report(stderr, _("Could not decode OTP challenge\n"));
186         return PS_AUTHFAIL;
187     };
188
189     rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
190     if ((rval == -2) && !run.poll_interval) {
191         char secret[OPIE_SECRET_MAX+1];
192         fprintf(stderr, _("Secret pass phrase: "));
193         if (opiereadpass(secret, sizeof(secret), 0))
194             rval = opiegenerator(challenge, secret, response);
195         memset(secret, 0, sizeof(secret));
196     };
197
198     if (rval)
199         return(PS_AUTHFAIL);
200
201     to64frombits(buffer, response, strlen(response));
202
203     if (outlevel >= O_MONITOR)
204         report(stdout, "IMAP> %s\n", buffer);
205     strcat(buffer, "\r\n");
206     SockWrite(sock, buffer, strlen(buffer));
207
208     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
209         return rval;
210
211     if (strstr(buffer, "OK"))
212         return PS_SUCCESS;
213     else
214         return PS_AUTHFAIL;
215 };
216 #endif /* OPIE_ENABLE */
217
218 #ifdef KERBEROS_V4
219 #if SIZEOF_INT == 4
220 typedef int     int32;
221 #elif SIZEOF_SHORT == 4
222 typedef short   int32;
223 #elif SIZEOF_LONG == 4
224 typedef long    int32;
225 #else
226 #error Cannot deduce a 32-bit-type
227 #endif
228
229 static int do_rfc1731(int sock, char *truename)
230 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
231 {
232     int result = 0, len;
233     char buf1[4096], buf2[4096];
234     union {
235       int32 cint;
236       char cstr[4];
237     } challenge1, challenge2;
238     char srvinst[INST_SZ];
239     char *p;
240     char srvrealm[REALM_SZ];
241     KTEXT_ST authenticator;
242     CREDENTIALS credentials;
243     char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
244     char tktinst[INST_SZ];
245     char tktrealm[REALM_SZ];
246     des_cblock session;
247     des_key_schedule schedule;
248
249     gen_send(sock, "AUTHENTICATE KERBEROS_V4");
250
251     /* The data encoded in the first ready response contains a random
252      * 32-bit number in network byte order.  The client should respond
253      * with a Kerberos ticket and an authenticator for the principal
254      * "imap.hostname@realm", where "hostname" is the first component
255      * of the host name of the server with all letters in lower case
256      * and where "realm" is the Kerberos realm of the server.  The
257      * encrypted checksum field included within the Kerberos
258      * authenticator should contain the server provided 32-bit number
259      * in network byte order.
260      */
261
262     if (result = gen_recv(sock, buf1, sizeof buf1)) {
263         return result;
264     }
265
266     len = from64tobits(challenge1.cstr, buf1);
267     if (len < 0) {
268         report(stderr, _("could not decode initial BASE64 challenge\n"));
269         return PS_AUTHFAIL;
270     }
271
272     /* this patch by Dan Root <dar@thekeep.org> solves an endianess
273      * problem. */
274     {
275         char tmp[4];
276
277         *(int *)tmp = ntohl(*(int *) challenge1.cstr);
278         memcpy(challenge1.cstr, tmp, sizeof(tmp));
279     }
280
281     /* Client responds with a Kerberos ticket and an authenticator for
282      * the principal "imap.hostname@realm" where "hostname" is the
283      * first component of the host name of the server with all letters
284      * in lower case and where "realm" is the Kerberos realm of the
285      * server.  The encrypted checksum field included within the
286      * Kerberos authenticator should contain the server-provided
287      * 32-bit number in network byte order.
288      */
289
290     strncpy(srvinst, truename, (sizeof srvinst)-1);
291     srvinst[(sizeof srvinst)-1] = '\0';
292     for (p = srvinst; *p; p++) {
293       if (isupper(*p)) {
294         *p = tolower(*p);
295       }
296     }
297
298     strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
299     srvrealm[(sizeof srvrealm)-1] = '\0';
300     if (p = strchr(srvinst, '.')) {
301       *p = '\0';
302     }
303
304     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
305     if (result) {
306         report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
307         return PS_AUTHFAIL;
308     }
309
310     result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
311     if (result) {
312         report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
313         return PS_AUTHFAIL;
314     }
315
316     memcpy(session, credentials.session, sizeof session);
317     memset(&credentials, 0, sizeof credentials);
318     des_key_sched(session, schedule);
319
320     result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
321     if (result) {
322         report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
323         return PS_AUTHFAIL;
324     }
325
326 #ifdef __UNUSED__
327     /*
328      * Andrew H. Chatham <andrew.chatham@duke.edu> alleges that this check
329      * is not necessary and has consistently been messing him up.
330      */
331     if (strcmp(tktuser, user) != 0) {
332         report(stderr, 
333                _("principal %s in ticket does not match -u %s\n"), tktuser,
334                 user);
335         return PS_AUTHFAIL;
336     }
337 #endif /* __UNUSED__ */
338
339     if (tktinst[0]) {
340         report(stderr, 
341                _("non-null instance (%s) might cause strange behavior\n"),
342                 tktinst);
343         strcat(tktuser, ".");
344         strcat(tktuser, tktinst);
345     }
346
347     if (strcmp(tktrealm, srvrealm) != 0) {
348         strcat(tktuser, "@");
349         strcat(tktuser, tktrealm);
350     }
351
352     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
353             challenge1.cint);
354     if (result) {
355         report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
356         return PS_AUTHFAIL;
357     }
358
359     to64frombits(buf1, authenticator.dat, authenticator.length);
360     if (outlevel >= O_MONITOR) {
361         report(stdout, "IMAP> %s\n", buf1);
362     }
363     strcat(buf1, "\r\n");
364     SockWrite(sock, buf1, strlen(buf1));
365
366     /* Upon decrypting and verifying the ticket and authenticator, the
367      * server should verify that the contained checksum field equals
368      * the original server provided random 32-bit number.  Should the
369      * verification be successful, the server must add one to the
370      * checksum and construct 8 octets of data, with the first four
371      * octets containing the incremented checksum in network byte
372      * order, the fifth octet containing a bit-mask specifying the
373      * protection mechanisms supported by the server, and the sixth
374      * through eighth octets containing, in network byte order, the
375      * maximum cipher-text buffer size the server is able to receive.
376      * The server must encrypt the 8 octets of data in the session key
377      * and issue that encrypted data in a second ready response.  The
378      * client should consider the server authenticated if the first
379      * four octets the un-encrypted data is equal to one plus the
380      * checksum it previously sent.
381      */
382     
383     if (result = gen_recv(sock, buf1, sizeof buf1))
384         return result;
385
386     /* The client must construct data with the first four octets
387      * containing the original server-issued checksum in network byte
388      * order, the fifth octet containing the bit-mask specifying the
389      * selected protection mechanism, the sixth through eighth octets
390      * containing in network byte order the maximum cipher-text buffer
391      * size the client is able to receive, and the following octets
392      * containing a user name string.  The client must then append
393      * from one to eight octets so that the length of the data is a
394      * multiple of eight octets. The client must then PCBC encrypt the
395      * data with the session key and respond to the second ready
396      * response with the encrypted data.  The server decrypts the data
397      * and verifies the contained checksum.  The username field
398      * identifies the user for whom subsequent IMAP operations are to
399      * be performed; the server must verify that the principal
400      * identified in the Kerberos ticket is authorized to connect as
401      * that user.  After these verifications, the authentication
402      * process is complete.
403      */
404
405     len = from64tobits(buf2, buf1);
406     if (len < 0) {
407         report(stderr, _("could not decode BASE64 ready response\n"));
408         return PS_AUTHFAIL;
409     }
410
411     des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
412     memcpy(challenge2.cstr, buf2, 4);
413     if (ntohl(challenge2.cint) != challenge1.cint + 1) {
414         report(stderr, _("challenge mismatch\n"));
415         return PS_AUTHFAIL;
416     }       
417
418     memset(authenticator.dat, 0, sizeof authenticator.dat);
419
420     result = htonl(challenge1.cint);
421     memcpy(authenticator.dat, &result, sizeof result);
422
423     /* The protection mechanisms and their corresponding bit-masks are as
424      * follows:
425      *
426      * 1 No protection mechanism
427      * 2 Integrity (krb_mk_safe) protection
428      * 4 Privacy (krb_mk_priv) protection
429      */
430     authenticator.dat[4] = 1;
431
432     len = strlen(tktuser);
433     strncpy(authenticator.dat+8, tktuser, len);
434     authenticator.length = len + 8 + 1;
435     while (authenticator.length & 7) {
436         authenticator.length++;
437     }
438     des_pcbc_encrypt((des_cblock *)authenticator.dat,
439             (des_cblock *)authenticator.dat, authenticator.length, schedule,
440             &session, 1);
441
442     to64frombits(buf1, authenticator.dat, authenticator.length);
443     if (outlevel >= O_MONITOR) {
444         report(stdout, "IMAP> %s\n", buf1);
445     }
446
447     strcat(buf1, "\r\n");
448     SockWrite(sock, buf1, strlen(buf1));
449
450     if (result = gen_recv(sock, buf1, sizeof buf1))
451         return result;
452
453     if (strstr(buf1, "OK")) {
454         return PS_SUCCESS;
455     }
456     else {
457         return PS_AUTHFAIL;
458     }
459 }
460 #endif /* KERBEROS_V4 */
461
462 #ifdef GSSAPI
463 #define GSSAUTH_P_NONE      1
464 #define GSSAUTH_P_INTEGRITY 2
465 #define GSSAUTH_P_PRIVACY   4
466
467 static int do_gssauth(int sock, char *hostname, char *username)
468 {
469     gss_buffer_desc request_buf, send_token;
470     gss_buffer_t sec_token;
471     gss_name_t target_name;
472     gss_ctx_id_t context;
473     gss_OID mech_name;
474     gss_qop_t quality;
475     int cflags;
476     OM_uint32 maj_stat, min_stat;
477     char buf1[8192], buf2[8192], server_conf_flags;
478     unsigned long buf_size;
479     int result;
480
481     /* first things first: get an imap ticket for host */
482     sprintf(buf1, "imap@%s", hostname);
483     request_buf.value = buf1;
484     request_buf.length = strlen(buf1) + 1;
485     maj_stat = gss_import_name(&min_stat, &request_buf, GSS_C_NT_HOSTBASED_SERVICE,
486         &target_name);
487     if (maj_stat != GSS_S_COMPLETE) {
488         report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
489         return PS_AUTHFAIL;
490     }
491     else if (outlevel >= O_DEBUG) {
492         maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
493             &mech_name);
494         report(stderr, _("Using service name [%s]\n"),request_buf.value);
495         maj_stat = gss_release_buffer(&min_stat, &request_buf);
496     }
497
498     gen_send(sock, "AUTHENTICATE GSSAPI");
499
500     /* upon receipt of the GSSAPI authentication request, server returns
501      * null data ready response. */
502     if (result = gen_recv(sock, buf1, sizeof buf1)) {
503         return result;
504     }
505
506     /* now start the security context initialisation loop... */
507     sec_token = GSS_C_NO_BUFFER;
508     context = GSS_C_NO_CONTEXT;
509     if (outlevel >= O_VERBOSE)
510         report(stdout, _("Sending credentials\n"));
511     do {
512         send_token.length = 0;
513         send_token.value = NULL;
514         maj_stat = gss_init_sec_context(&min_stat, 
515                                         GSS_C_NO_CREDENTIAL,
516                                         &context, 
517                                         target_name, 
518                                         GSS_C_NO_OID, 
519                                         GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG, 
520                                         0, 
521                                         GSS_C_NO_CHANNEL_BINDINGS, 
522                                         sec_token, 
523                                         NULL, 
524                                         &send_token, 
525                                         NULL, 
526                                         NULL);
527         if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
528             report(stderr, _("Error exchanging credentials\n"));
529             gss_release_name(&min_stat, &target_name);
530             /* wake up server and await NO response */
531             SockWrite(sock, "\r\n", 2);
532             if (result = gen_recv(sock, buf1, sizeof buf1))
533                 return result;
534             return PS_AUTHFAIL;
535         }
536         to64frombits(buf1, send_token.value, send_token.length);
537         gss_release_buffer(&min_stat, &send_token);
538         strcat(buf1, "\r\n");
539         SockWrite(sock, buf1, strlen(buf1));
540         if (outlevel >= O_MONITOR)
541             report(stdout, "IMAP> %s\n", buf1);
542         if (maj_stat == GSS_S_CONTINUE_NEEDED) {
543             if (result = gen_recv(sock, buf1, sizeof buf1)) {
544                 gss_release_name(&min_stat, &target_name);
545                 return result;
546             }
547             request_buf.length = from64tobits(buf2, buf1 + 2);
548             request_buf.value = buf2;
549             sec_token = &request_buf;
550         }
551     } while (maj_stat == GSS_S_CONTINUE_NEEDED);
552     gss_release_name(&min_stat, &target_name);
553
554     /* get security flags and buffer size */
555     if (result = gen_recv(sock, buf1, sizeof buf1)) {
556         return result;
557     }
558     request_buf.length = from64tobits(buf2, buf1 + 2);
559     request_buf.value = buf2;
560
561     maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
562         &cflags, &quality);
563     if (maj_stat != GSS_S_COMPLETE) {
564         report(stderr, _("Couldn't unwrap security level data\n"));
565         gss_release_buffer(&min_stat, &send_token);
566         return PS_AUTHFAIL;
567     }
568     if (outlevel >= O_DEBUG)
569         report(stdout, _("Credential exchange complete\n"));
570     /* first octet is security levels supported. We want none, for now */
571     server_conf_flags = ((char *)send_token.value)[0];
572     if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
573         report(stderr, _("Server requires integrity and/or privacy\n"));
574         gss_release_buffer(&min_stat, &send_token);
575         return PS_AUTHFAIL;
576     }
577     ((char *)send_token.value)[0] = 0;
578     buf_size = ntohl(*((long *)send_token.value));
579     /* we don't care about buffer size if we don't wrap data */
580     gss_release_buffer(&min_stat, &send_token);
581     if (outlevel >= O_DEBUG) {
582         report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
583             server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
584             server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
585             server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
586         report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
587     }
588
589     /* now respond in kind (hack!!!) */
590     buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
591     memcpy(buf1, &buf_size, 4);
592     buf1[0] = GSSAUTH_P_NONE;
593     strcpy(buf1+4, username); /* server decides if princ is user */
594     request_buf.length = 4 + strlen(username) + 1;
595     request_buf.value = buf1;
596     maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
597         &cflags, &send_token);
598     if (maj_stat != GSS_S_COMPLETE) {
599         report(stderr, _("Error creating security level request\n"));
600         return PS_AUTHFAIL;
601     }
602     to64frombits(buf1, send_token.value, send_token.length);
603     if (outlevel >= O_DEBUG) {
604         report(stdout, _("Requesting authorization as %s\n"), username);
605         report(stdout, "IMAP> %s\n",buf1);
606     }
607     strcat(buf1, "\r\n");
608     SockWrite(sock, buf1, strlen(buf1));
609
610     /* we should be done. Get status and finish up */
611     if (result = gen_recv(sock, buf1, sizeof buf1))
612         return result;
613     if (strstr(buf1, "OK")) {
614         /* flush security context */
615         if (outlevel >= O_DEBUG)
616             report(stdout, _("Releasing GSS credentials\n"));
617         maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
618         if (maj_stat != GSS_S_COMPLETE) {
619             report(stderr, _("Error releasing credentials\n"));
620             return PS_AUTHFAIL;
621         }
622         /* send_token may contain a notification to the server to flush
623          * credentials. RFC 1731 doesn't specify what to do, and since this
624          * support is only for authentication, we'll assume the server
625          * knows enough to flush its own credentials */
626         gss_release_buffer(&min_stat, &send_token);
627         return PS_SUCCESS;
628     }
629
630     return PS_AUTHFAIL;
631 }       
632 #endif /* GSSAPI */
633
634 static void hmac_md5 (unsigned char *password,  size_t pass_len,
635                       unsigned char *challenge, size_t chal_len,
636                       unsigned char *response,  size_t resp_len)
637 {
638     int i;
639     unsigned char ipad[64];
640     unsigned char opad[64];
641     unsigned char hash_passwd[16];
642
643     MD5_CTX ctx;
644     
645     if (resp_len != 16)
646         return;
647
648     if (pass_len > sizeof (ipad))
649     {
650         MD5Init (&ctx);
651         MD5Update (&ctx, password, pass_len);
652         MD5Final (hash_passwd, &ctx);
653         password = hash_passwd; pass_len = sizeof (hash_passwd);
654     }
655
656     memset (ipad, 0, sizeof (ipad));
657     memset (opad, 0, sizeof (opad));
658     memcpy (ipad, password, pass_len);
659     memcpy (opad, password, pass_len);
660
661     for (i=0; i<64; i++) {
662         ipad[i] ^= 0x36;
663         opad[i] ^= 0x5c;
664     }
665
666     MD5Init (&ctx);
667     MD5Update (&ctx, ipad, sizeof (ipad));
668     MD5Update (&ctx, challenge, chal_len);
669     MD5Final (response, &ctx);
670
671     MD5Init (&ctx);
672     MD5Update (&ctx, opad, sizeof (opad));
673     MD5Update (&ctx, response, resp_len);
674     MD5Final (response, &ctx);
675 }
676
677 #if NTLM_ENABLE
678 #include "ntlm.h"
679
680 static tSmbNtlmAuthRequest   request;              
681 static tSmbNtlmAuthChallenge challenge;
682 static tSmbNtlmAuthResponse  response;
683
684 /*
685  * NTLM support by Grant Edwards.
686  *
687  * Handle MS-Exchange NTLM authentication method.  This is the same
688  * as the NTLM auth used by Samba for SMB related services. We just
689  * encode the packets in base64 instead of sending them out via a
690  * network interface.
691  * 
692  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
693  */
694
695 static int do_imap_ntlm(int sock, struct query *ctl)
696 {
697     char msgbuf[2048];
698     int result,len;
699   
700     gen_send(sock, "AUTHENTICATE NTLM");
701
702     if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
703         return result;
704   
705     if (msgbuf[0] != '+')
706         return PS_AUTHFAIL;
707   
708     buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
709
710     if (outlevel >= O_DEBUG)
711         dumpSmbNtlmAuthRequest(stdout, &request);
712
713     memset(msgbuf,0,sizeof msgbuf);
714     to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
715   
716     if (outlevel >= O_MONITOR)
717         report(stdout, "IMAP> %s\n", msgbuf);
718   
719     strcat(msgbuf,"\r\n");
720     SockWrite (sock, msgbuf, strlen (msgbuf));
721
722     if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
723         return result;
724   
725     len = from64tobits ((unsigned char*)&challenge, msgbuf);
726     
727     if (outlevel >= O_DEBUG)
728         dumpSmbNtlmAuthChallenge(stdout, &challenge);
729     
730     buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
731   
732     if (outlevel >= O_DEBUG)
733         dumpSmbNtlmAuthResponse(stdout, &response);
734   
735     memset(msgbuf,0,sizeof msgbuf);
736     to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
737
738     if (outlevel >= O_MONITOR)
739         report(stdout, "IMAP> %s\n", msgbuf);
740       
741     strcat(msgbuf,"\r\n");
742
743     SockWrite (sock, msgbuf, strlen (msgbuf));
744   
745     if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
746         return result;
747   
748     if (strstr (msgbuf, "OK"))
749         return PS_SUCCESS;
750     else
751         return PS_AUTHFAIL;
752 }
753 #endif /* NTLM */
754
755 static int do_cram_md5 (int sock, struct query *ctl)
756 /* authenticate as per RFC2195 */
757 {
758     int result;
759     int len;
760     unsigned char buf1[1024];
761     unsigned char msg_id[768];
762     unsigned char response[16];
763     unsigned char reply[1024];
764
765     gen_send (sock, "AUTHENTICATE CRAM-MD5");
766
767     /* From RFC2195:
768      * The data encoded in the first ready response contains an
769      * presumptively arbitrary string of random digits, a timestamp, and the
770      * fully-qualified primary host name of the server.  The syntax of the
771      * unencoded form must correspond to that of an RFC 822 'msg-id'
772      * [RFC822] as described in [POP3].
773      */
774
775     if ((result = gen_recv (sock, buf1, sizeof (buf1)))) {
776         return result;
777     }
778
779     len = from64tobits (msg_id, buf1);
780     if (len < 0) {
781         report (stderr, _("could not decode BASE64 challenge\n"));
782         return PS_AUTHFAIL;
783     } else if (len < sizeof (msg_id)) {
784         msg_id[len] = 0;
785     } else {
786         msg_id[sizeof (msg_id)-1] = 0;
787     }
788     if (outlevel >= O_DEBUG) {
789         report (stdout, _("decoded as %s\n"), msg_id);
790     }
791
792     /* The client makes note of the data and then responds with a string
793      * consisting of the user name, a space, and a 'digest'.  The latter is
794      * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where
795      * the key is a shared secret and the digested text is the timestamp
796      * (including angle-brackets).
797      */
798
799     hmac_md5 (ctl->password, strlen (ctl->password),
800               msg_id, strlen (msg_id),
801               response, sizeof (response));
802
803 #ifdef HAVE_SNPRINTF
804     snprintf (reply, sizeof (reply),
805 #else
806     sprintf(reply,
807 #endif
808               "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", 
809               ctl->remotename,
810               response[0], response[1], response[2], response[3],
811               response[4], response[5], response[6], response[7],
812               response[8], response[9], response[10], response[11],
813               response[12], response[13], response[14], response[15]);
814
815     if (outlevel >= O_DEBUG) {
816         report (stdout, _("replying with %s\n"), reply);
817     }
818
819     to64frombits (buf1, reply, strlen (reply));
820     if (outlevel >= O_MONITOR) {
821         report (stdout, "IMAP> %s\n", buf1);
822     }
823
824     /* PMDF5.2 IMAP has a bug that requires this to be a single write */
825     strcat (buf1, "\r\n");
826     SockWrite (sock, buf1, strlen (buf1));
827
828     if ((result = gen_recv (sock, buf1, sizeof (buf1))))
829         return result;
830
831     if (strstr (buf1, "OK")) {
832         return PS_SUCCESS;
833     } else {
834         return PS_AUTHFAIL;
835     }
836 }
837
838 int imap_canonicalize(char *result, char *raw, int maxlen)
839 /* encode an IMAP password as per RFC1730's quoting conventions */
840 {
841     int i, j;
842
843     j = 0;
844     for (i = 0; i < strlen(raw) && i < maxlen; i++)
845     {
846         if ((raw[i] == '\\') || (raw[i] == '"'))
847             result[j++] = '\\';
848         result[j++] = raw[i];
849     }
850     result[j] = '\0';
851
852     return(i);
853 }
854
855 int imap_getauth(int sock, struct query *ctl, char *greeting)
856 /* apply for connection authorization */
857 {
858     int ok = 0;
859
860     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
861     capabilities[0] = '\0';
862     if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
863     {
864         /* UW-IMAP server 10.173 notifies in all caps */
865         if (strstr(capabilities, "IMAP4REV1"))
866         {
867             imap_version = IMAP4rev1;
868             if (outlevel >= O_DEBUG)
869                 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
870         }
871         else
872         {
873             imap_version = IMAP4;
874             if (outlevel >= O_DEBUG)
875                 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
876         }
877     }
878     else if (ok == PS_ERROR)
879     {
880         imap_version = IMAP2;
881         if (outlevel >= O_DEBUG)
882             report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
883     }
884     else
885         return(ok);
886
887     peek_capable = (imap_version >= IMAP4);
888
889     /* 
890      * Assumption: expunges are cheap, so we want to do them
891      * after every message unless user said otherwise.
892      */
893     if (NUM_SPECIFIED(ctl->expunge))
894         expunge_period = NUM_VALUE_OUT(ctl->expunge);
895     else
896         expunge_period = 1;
897
898     /* 
899      * If either (a) we saw a PREAUTH token in the greeting, or
900      * (b) the user specified ssh preauthentication, then we're done.
901      */
902     if (preauth || ctl->server.preauthenticate == A_SSH)
903     {
904         preauth = FALSE;  /* reset for the next session */
905         return(PS_SUCCESS);
906     }
907
908     /* 
909      * Handle idling.  We depend on coming through here on startup
910      * and after each timeout (including timeouts during idles).
911      */
912     if (strstr(capabilities, "IDLE") && ctl->idle)
913     {
914         do_idle = TRUE;
915         if (outlevel >= O_VERBOSE)
916             report(stdout, _("will idle after poll\n"));
917     }
918
919 #if OPIE_ENABLE
920     if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
921     {
922         if (outlevel >= O_DEBUG)
923             report(stdout, _("OTP authentication is supported\n"));
924         if (do_otp(sock, ctl) == PS_SUCCESS)
925             return(PS_SUCCESS);
926     };
927 #endif /* OPIE_ENABLE */
928
929 #ifdef GSSAPI
930     if (strstr(capabilities, "AUTH=GSSAPI"))
931     {
932         if (ctl->server.protocol == P_IMAP_GSS)
933         {
934             if (outlevel >= O_DEBUG)
935                 report(stdout, _("GSS authentication is supported\n"));
936             return do_gssauth(sock, ctl->server.truename, ctl->remotename);
937         }
938     }
939     else if (ctl->server.protocol == P_IMAP_GSS)
940     {
941         report(stderr, 
942                _("Required GSS capability not supported by server\n"));
943         return(PS_AUTHFAIL);
944     }
945 #endif /* GSSAPI */
946
947 #ifdef KERBEROS_V4
948     if (strstr(capabilities, "AUTH=KERBEROS_V4"))
949     {
950         if (outlevel >= O_DEBUG)
951             report(stdout, _("KERBEROS_V4 authentication is supported\n"));
952
953         if (ctl->server.protocol == P_IMAP_K4)
954         {
955             if ((ok = do_rfc1731(sock, ctl->server.truename)))
956             {
957                 if (outlevel >= O_MONITOR)
958                     report(stdout, "IMAP> *\n");
959                 SockWrite(sock, "*\r\n", 3);
960             }
961             
962             return(ok);
963         }
964         /* else fall through to ordinary AUTH=LOGIN case */
965     }
966     else if (ctl->server.protocol == P_IMAP_K4)
967     {
968         report(stderr, 
969                _("Required KERBEROS_V4 capability not supported by server\n"));
970         return(PS_AUTHFAIL);
971     }
972 #endif /* KERBEROS_V4 */
973
974     if (strstr(capabilities, "AUTH=CRAM-MD5"))
975     {
976         if (outlevel >= O_DEBUG)
977             report (stdout, _("CRAM-MD5 authentication is supported\n"));
978         if (ctl->server.protocol != P_IMAP_LOGIN)
979         {
980             if ((ok = do_cram_md5 (sock, ctl)))
981             {
982                 if (outlevel >= O_MONITOR)
983                     report (stdout, "IMAP> *\n");
984                 SockWrite (sock, "*\r\n", 3);
985             }
986             return ok;
987         }
988     }
989     else if (ctl->server.protocol == P_IMAP_CRAM_MD5)
990     {
991         report(stderr,
992                _("Required CRAM-MD5 capability not supported by server\n"));
993         return(PS_AUTHFAIL);
994     }
995
996 #ifdef NTLM_ENABLE
997     if (strstr (capabilities, "AUTH=NTLM"))
998     {
999         if (outlevel >= O_DEBUG)
1000             report (stdout, _("NTLM authentication is supported\n"));
1001         return do_imap_ntlm (sock, ctl);
1002     }
1003 #endif /* NTLM_ENABLE */
1004
1005 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
1006     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
1007     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
1008       report(stderr, 
1009              _("Required LOGIN capability not supported by server\n"));
1010       return PS_AUTHFAIL;
1011     };
1012 #endif /* __UNUSED__ */
1013
1014     {
1015         /* these sizes guarantee no buffer overflow */
1016         char    remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
1017
1018         imap_canonicalize(remotename, ctl->remotename, NAMELEN);
1019         imap_canonicalize(password, ctl->password, PASSWORDLEN);
1020         ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
1021     }
1022
1023     if (ok)
1024         return(ok);
1025     
1026     return(PS_SUCCESS);
1027 }
1028
1029 static int internal_expunge(int sock)
1030 /* ship an expunge, resetting associated counters */
1031 {
1032     int ok;
1033
1034     if ((ok = gen_transact(sock, "EXPUNGE")))
1035         return(ok);
1036
1037     expunged += deletions;
1038     deletions = 0;
1039
1040 #ifdef IMAP_UID /* not used */
1041     expunge_uids(ctl);
1042 #endif /* IMAP_UID */
1043
1044     return(PS_SUCCESS);
1045 }
1046
1047 static int imap_idle(int sock)
1048 /* start an RFC2177 IDLE */
1049 {
1050     stage = STAGE_IDLE;
1051     saved_timeout = mytimeout;
1052     mytimeout = 0;
1053
1054     return (gen_transact(sock, "IDLE"));
1055 }
1056
1057 static int imap_getrange(int sock, 
1058                          struct query *ctl, 
1059                          const char *folder, 
1060                          int *countp, int *newp, int *bytes)
1061 /* get range of messages to be fetched */
1062 {
1063     int ok;
1064     char buf[MSGBUFSIZE+1], *cp;
1065
1066     /* find out how many messages are waiting */
1067     *bytes = -1;
1068
1069     if (pass > 1)
1070     {
1071         /* 
1072          * We have to have an expunge here, otherwise the re-poll will
1073          * infinite-loop picking up un-expunged messages -- unless the
1074          * expunge period is one and we've been nuking each message 
1075          * just after deletion.
1076          */
1077         ok = 0;
1078         if (deletions && expunge_period != 1)
1079             ok = internal_expunge(sock);
1080         count = -1;
1081         if (do_idle)
1082             ok = imap_idle(sock);
1083         if (ok || gen_transact(sock, "NOOP"))
1084         {
1085             report(stderr, _("re-poll failed\n"));
1086             return(ok);
1087         }
1088         else if (count == -1)   /* no EXISTS response to NOOP/IDLE */
1089         {
1090             count = 0;
1091         }
1092         if (outlevel >= O_DEBUG)
1093             report(stdout, _("%d messages waiting after re-poll\n"), count);
1094     }
1095     else
1096     {
1097         ok = gen_transact(sock, 
1098                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
1099                           folder ? folder : "INBOX");
1100         if (ok != 0)
1101         {
1102             report(stderr, _("mailbox selection failed\n"));
1103             return(ok);
1104         }
1105         else if (outlevel >= O_DEBUG)
1106             report(stdout, _("%d messages waiting after first poll\n"), count);
1107
1108         /* no messages?  then we may need to idle until we get some */
1109         if (count == 0 && do_idle)
1110             imap_idle(sock);
1111     }
1112
1113     *countp = count;
1114
1115     /* OK, now get a count of unseen messages and their indices */
1116     if (!ctl->fetchall && count > 0)
1117     {
1118         if (unseen_messages)
1119             free(unseen_messages);
1120         unseen_messages = xmalloc(count * sizeof(unsigned int));
1121         memset(unseen_messages, 0, count * sizeof(unsigned int));
1122         unseen = 0;
1123
1124         gen_send(sock, "SEARCH UNSEEN");
1125         do {
1126             ok = gen_recv(sock, buf, sizeof(buf));
1127             if (ok != 0)
1128             {
1129                 report(stderr, _("search for unseen messages failed\n"));
1130                 return(PS_PROTOCOL);
1131             }
1132             else if ((cp = strstr(buf, "* SEARCH")))
1133             {
1134                 char    *ep;
1135
1136                 cp += 8;        /* skip "* SEARCH" */
1137
1138                 while (*cp && unseen < count)
1139                 {
1140                     /* skip whitespace */
1141                     while (*cp && isspace(*cp))
1142                         cp++;
1143                     if (*cp) 
1144                     {
1145                         /*
1146                          * Message numbers are between 1 and 2^32 inclusive,
1147                          * so unsigned int is large enough.
1148                          */
1149                         unseen_messages[unseen]=(unsigned int)strtol(cp,&ep,10);
1150
1151                         if (outlevel >= O_DEBUG)
1152                             report(stdout, 
1153                                    _("%u is unseen\n"), 
1154                                    unseen_messages[unseen]);
1155                 
1156                         unseen++;
1157                         cp = ep;
1158                     }
1159                 }
1160             }
1161         } while
1162             (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
1163     }
1164
1165     *newp = unseen;
1166     expunged = 0;
1167
1168     return(PS_SUCCESS);
1169 }
1170
1171 static int imap_getsizes(int sock, int count, int *sizes)
1172 /* capture the sizes of all messages */
1173 {
1174     char buf [MSGBUFSIZE+1];
1175
1176     /*
1177      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1178      * won't accept 1:1 as valid set syntax.  Some implementors
1179      * should be taken out and shot for excessive anality.
1180      *
1181      * Microsoft Exchange (brain-dead piece of crap that it is) 
1182      * sometimes gets its knickers in a knot about bodiless messages.
1183      * You may see responses like this:
1184      *
1185      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1186      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1187      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1188      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1189      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1190      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1191      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1192      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1193      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1194      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
1195      *
1196      * This means message 1 has only headers.  For kicks and grins
1197      * you can telnet in and look:
1198      *  A003 FETCH 1 FULL
1199      *  A003 NO The requested item could not be found.
1200      *  A004 fetch 1 rfc822.header
1201      *  A004 NO The requested item could not be found.
1202      *  A006 FETCH 1 BODY
1203      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1204      *  A006 OK FETCH completed.
1205      *
1206      * To get around this, we terminate the read loop on a NO and count
1207      * on the fact that the sizes array has been preinitialized with a
1208      * known-bad size value.
1209      */
1210     if (count == 1)
1211         gen_send(sock, "FETCH 1 RFC822.SIZE", count);
1212     else
1213         gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
1214     for (;;)
1215     {
1216         int num, size, ok;
1217
1218         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1219             return(ok);
1220         else if (strstr(buf, "OK") || strstr(buf, "NO"))
1221             break;
1222         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
1223             sizes[num - 1] = size;
1224     }
1225
1226     return(PS_SUCCESS);
1227 }
1228
1229 static int imap_is_old(int sock, struct query *ctl, int number)
1230 /* is the given message old? */
1231 {
1232     flag seen = TRUE;
1233     int i;
1234
1235     /* 
1236      * Expunges change the fetch numbers, but unseen_messages contains
1237      * indices from before any expungees were done.  So neither the
1238      * argument nor the values in message_sequence need to be decremented.
1239      */
1240
1241     seen = TRUE;
1242     for (i = 0; i < unseen; i++)
1243         if (unseen_messages[i] == number)
1244         {
1245             seen = FALSE;
1246             break;
1247         }
1248
1249     return(seen);
1250 }
1251
1252 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1253 /* request headers of nth message */
1254 {
1255     char buf [MSGBUFSIZE+1];
1256     int num;
1257
1258     /* expunges change the fetch numbers */
1259     number -= expunged;
1260
1261     /*
1262      * This is blessed by RFC1176, RFC1730, RFC2060.
1263      * According to the RFCs, it should *not* set the \Seen flag.
1264      */
1265     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1266
1267     /* looking for FETCH response */
1268     do {
1269         int     ok;
1270
1271         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1272             return(ok);
1273     } while
1274         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
1275
1276     if (num != number)
1277         return(PS_ERROR);
1278     else
1279         return(PS_SUCCESS);
1280 }
1281
1282 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1283 /* request body of nth message */
1284 {
1285     char buf [MSGBUFSIZE+1], *cp;
1286     int num;
1287
1288     /* expunges change the fetch numbers */
1289     number -= expunged;
1290
1291     /*
1292      * If we're using IMAP4, we can fetch the message without setting its
1293      * seen flag.  This is good!  It means that if the protocol exchange
1294      * craps out during the message, it will still be marked `unseen' on
1295      * the server.
1296      *
1297      * However...*don't* do this if we're using keep to suppress deletion!
1298      * In that case, marking the seen flag is the only way to prevent the
1299      * message from being re-fetched on subsequent runs (and according
1300      * to RFC2060 p.43 this fetch should set Seen as a side effect).
1301      *
1302      * According to RFC2060, and Mark Crispin the IMAP maintainer,
1303      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
1304      * equivalent".  However, we know of at least one server that
1305      * treats them differently in the presence of MIME attachments;
1306      * the latter form downloads the attachment, the former does not.
1307      * The server is InterChange, and the fool who implemented this
1308      * misfeature ought to be strung up by his thumbs.  
1309      *
1310      * When I tried working around this by disabling use of the 4rev1 form,
1311      * I found that doing this breaks operation with M$ Exchange.
1312      * Annoyingly enough, Exchange's refusal to cope is technically legal
1313      * under RFC2062.  Trust Microsoft, the Great Enemy of interoperability
1314      * standards, to find a way to make standards compliance irritating....
1315      */
1316     switch (imap_version)
1317     {
1318     case IMAP4rev1:     /* RFC 2060 */
1319         if (!ctl->keep)
1320             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1321         else
1322             gen_send(sock, "FETCH %d BODY[TEXT]", number);
1323         break;
1324
1325     case IMAP4:         /* RFC 1730 */
1326         if (!ctl->keep)
1327             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1328         else
1329             gen_send(sock, "FETCH %d RFC822.TEXT", number);
1330         break;
1331
1332     default:            /* RFC 1176 */
1333         gen_send(sock, "FETCH %d RFC822.TEXT", number);
1334         break;
1335     }
1336
1337     /* looking for FETCH response */
1338     do {
1339         int     ok;
1340
1341         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1342             return(ok);
1343     } while
1344         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1345
1346     if (num != number)
1347         return(PS_ERROR);
1348
1349     /*
1350      * Try to extract a length from the FETCH response.  RFC2060 requires
1351      * it to be present, but at least one IMAP server (Novell GroupWise)
1352      * botches this.
1353      */
1354     if ((cp = strchr(buf, '{')))
1355         *lenp = atoi(cp + 1);
1356     else
1357         *lenp = -1;     /* missing length part in FETCH reponse */
1358
1359     return(PS_SUCCESS);
1360 }
1361
1362 static int imap_trail(int sock, struct query *ctl, int number)
1363 /* discard tail of FETCH response after reading message text */
1364 {
1365     /* expunges change the fetch numbers */
1366     /* number -= expunged; */
1367
1368     for (;;)
1369     {
1370         char buf[MSGBUFSIZE+1];
1371         int ok;
1372
1373         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1374             return(ok);
1375
1376         /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1377         if (strstr(buf, "OK"))
1378             break;
1379
1380 #ifdef __UNUSED__
1381         /*
1382          * Any IMAP server that fails to set Seen on a BODY[TEXT]
1383          * fetch violates RFC2060 p.43 (top).  This becomes an issue
1384          * when keep is on, because seen messages aren't deleted and
1385          * get refetched on each poll.  As a workaround, if keep is on
1386          * we can set the Seen flag explicitly.
1387          *
1388          * This code isn't used yet because we don't know of any IMAP
1389          * servers broken in this way.
1390          */
1391         if (ctl->keep)
1392             if ((ok = gen_transact(sock,
1393                         imap_version == IMAP4 
1394                                 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1395                                 : "STORE %d +FLAGS (\\Seen)", 
1396                         number)))
1397                 return(ok);
1398 #endif /* __UNUSED__ */
1399     }
1400
1401     return(PS_SUCCESS);
1402 }
1403
1404 static int imap_delete(int sock, struct query *ctl, int number)
1405 /* set delete flag for given message */
1406 {
1407     int ok;
1408
1409     /* expunges change the fetch numbers */
1410     number -= expunged;
1411
1412     /*
1413      * Use SILENT if possible as a minor throughput optimization.
1414      * Note: this has been dropped from IMAP4rev1.
1415      *
1416      * We set Seen because there are some IMAP servers (notably HP
1417      * OpenMail) that do message-receipt DSNs, but only when the seen
1418      * bit is set.  This is the appropriate time -- we get here right
1419      * after the local SMTP response that says delivery was
1420      * successful.
1421      */
1422     if ((ok = gen_transact(sock,
1423                         imap_version == IMAP4 
1424                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1425                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1426                         number)))
1427         return(ok);
1428     else
1429         deletions++;
1430
1431     /*
1432      * We do an expunge after expunge_period messages, rather than
1433      * just before quit, so that a line hit during a long session
1434      * won't result in lots of messages being fetched again during
1435      * the next session.
1436      */
1437     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1438         internal_expunge(sock);
1439
1440     return(PS_SUCCESS);
1441 }
1442
1443 static int imap_logout(int sock, struct query *ctl)
1444 /* send logout command */
1445 {
1446     /* if any un-expunged deletions remain, ship an expunge now */
1447     if (deletions)
1448         internal_expunge(sock);
1449
1450 #ifdef USE_SEARCH
1451     /* Memory clean-up */
1452     if (unseen_messages)
1453         free(unseen_messages);
1454 #endif /* USE_SEARCH */
1455
1456     return(gen_transact(sock, "LOGOUT"));
1457 }
1458
1459 const static struct method imap =
1460 {
1461     "IMAP",             /* Internet Message Access Protocol */
1462 #if INET6_ENABLE
1463     "imap",
1464     "imaps",
1465 #else /* INET6_ENABLE */
1466     143,                /* standard IMAP2bis/IMAP4 port */
1467     993,                /* ssl IMAP2bis/IMAP4 port */
1468 #endif /* INET6_ENABLE */
1469     TRUE,               /* this is a tagged protocol */
1470     FALSE,              /* no message delimiter */
1471     imap_ok,            /* parse command response */
1472     imap_canonicalize,  /* deal with embedded slashes and spaces */
1473     imap_getauth,       /* get authorization */
1474     imap_getrange,      /* query range of messages */
1475     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1476     imap_is_old,        /* no UID check */
1477     imap_fetch_headers, /* request given message headers */
1478     imap_fetch_body,    /* request given message body */
1479     imap_trail,         /* eat message trailer */
1480     imap_delete,        /* delete the message */
1481     imap_logout,        /* expunge and exit */
1482     TRUE,               /* yes, we can re-poll */
1483 };
1484
1485 int doIMAP(struct query *ctl)
1486 /* retrieve messages using IMAP Version 2bis or Version 4 */
1487 {
1488     return(do_protocol(ctl, &imap));
1489 }
1490
1491 /* imap.c ends here */