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