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