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