]> Pileus Git - ~andy/fetchmail/blob - driver.c
Large protocol independence patch.
[~andy/fetchmail] / driver.c
1 /*
2  * driver.c -- generic driver for mail fetch method protocols
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  <setjmp.h>
11 #include  <errno.h>
12 #include  <string.h>
13 #ifdef HAVE_MEMORY_H
14 #include  <memory.h>
15 #endif /* HAVE_MEMORY_H */
16 #if defined(STDC_HEADERS)
17 #include  <stdlib.h>
18 #include  <limits.h>
19 #endif
20 #if defined(HAVE_UNISTD_H)
21 #include <unistd.h>
22 #endif
23 #if defined(HAVE_SYS_ITIMER_H)
24 #include <sys/itimer.h>
25 #endif
26 #include  <signal.h>
27 #ifdef HAVE_SYS_WAIT_H
28 #include <sys/wait.h>
29 #endif
30
31 #ifdef HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
33 #endif
34 #ifdef HAVE_NET_SOCKET_H
35 #include <net/socket.h>
36 #endif
37 #include <netdb.h>
38 #ifdef HAVE_PKG_hesiod
39 #include <hesiod.h>
40 #endif
41
42 #include <langinfo.h>
43
44 #include "kerberos.h"
45 #ifdef KERBEROS_V4
46 #include <netinet/in.h>
47 #endif /* KERBEROS_V4 */
48
49 #include "i18n.h"
50 #include "socket.h"
51
52 #include "fetchmail.h"
53 #include "getaddrinfo.h"
54 #include "tunable.h"
55
56 /* throw types for runtime errors */
57 #define THROW_TIMEOUT   1               /* server timed out */
58 #define THROW_SIGPIPE   2               /* SIGPIPE on stream socket */
59
60 /* magic values for the message length array */
61 #define MSGLEN_UNKNOWN  0               /* length unknown (0 is impossible) */
62 #define MSGLEN_INVALID  -1              /* length passed back is invalid */
63 #define MSGLEN_TOOLARGE -2              /* message is too large */
64 #define MSGLEN_OLD      -3              /* message is old */
65
66 int pass;               /* how many times have we re-polled? */
67 int stage;              /* where are we? */
68 int phase;              /* where are we, for error-logging purposes? */
69 int batchcount;         /* count of messages sent in current batch */
70 flag peek_capable;      /* can we peek for better error recovery? */
71 int mailserver_socket_temp = -1;        /* socket to free if connect timeout */ 
72
73 static volatile int timeoutcount = 0;   /* count consecutive timeouts */
74 static volatile int idletimeout = 0;    /* timeout occured in idle stage? */
75
76 static jmp_buf  restart;
77
78 int isidletimeout(void)
79 /* last timeout occured in idle stage? */
80 {
81     return idletimeout;
82 }
83
84 void resetidletimeout(void)
85 {
86     idletimeout = 0;
87 }
88
89 void set_timeout(int timeleft)
90 /* reset the nonresponse-timeout */
91 {
92 #if !defined(__EMX__) && !defined(__BEOS__)
93     struct itimerval ntimeout;
94
95     if (timeleft == 0)
96         timeoutcount = 0;
97
98     ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
99     ntimeout.it_value.tv_sec  = timeleft;
100     ntimeout.it_value.tv_usec = 0;
101     setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
102 #endif
103 }
104
105 static RETSIGTYPE timeout_handler (int signal)
106 /* handle SIGALRM signal indicating a server timeout */
107 {
108     if(stage != STAGE_IDLE) {
109         timeoutcount++;
110         longjmp(restart, THROW_TIMEOUT);
111     } else
112         idletimeout = 1;
113 }
114
115 static RETSIGTYPE sigpipe_handler (int signal)
116 /* handle SIGPIPE signal indicating a broken stream socket */
117 {
118     longjmp(restart, THROW_SIGPIPE);
119 }
120
121 #define CLEANUP_TIMEOUT 60 /* maximum timeout during cleanup */
122
123 static int cleanupSockClose (int fd)
124 /* close sockets in maximum CLEANUP_TIMEOUT seconds during cleanup */
125 {
126     int scerror;
127     SIGHANDLERTYPE alrmsave;
128     alrmsave = set_signal_handler(SIGALRM, null_signal_handler);
129     set_timeout(CLEANUP_TIMEOUT);
130     scerror = SockClose(fd);
131     set_timeout(0);
132     set_signal_handler(SIGALRM, alrmsave);
133     return (scerror);
134 }
135
136 #ifdef KERBEROS_V4
137 static int kerberos_auth(socket, canonical, principal) 
138 /* authenticate to the server host using Kerberos V4 */
139 int socket;             /* socket to server host */
140 char *canonical;        /* server name */
141 char *principal;
142 {
143     char * host_primary;
144     KTEXT ticket;
145     MSG_DAT msg_data;
146     CREDENTIALS cred;
147     Key_schedule schedule;
148     int rem;
149     char * prin_copy = (char *) NULL;
150     char * prin = (char *) NULL;
151     char * inst = (char *) NULL;
152     char * realm = (char *) NULL;
153
154     if (principal != (char *)NULL && *principal)
155     {
156         char *cp;
157         prin = prin_copy = xstrdup(principal);
158         for (cp = prin_copy; *cp && *cp != '.'; ++cp)
159             ;
160         if (*cp)
161         {
162             *cp++ = '\0';
163             inst = cp;
164             while (*cp && *cp != '@')
165                 ++cp;
166             if (*cp)
167             {
168                 *cp++ = '\0';
169                 realm = cp;
170             }
171         }
172     }
173   
174     ticket = xmalloc(sizeof (KTEXT_ST));
175     rem = (krb_sendauth (0L, socket, ticket,
176                          prin ? prin : "pop",
177                          inst ? inst : canonical,
178                          realm ? realm : ((char *) (krb_realmofhost (canonical))),
179                          ((unsigned long) 0),
180                          (&msg_data),
181                          (&cred),
182                          (schedule),
183                          ((struct sockaddr_in *) 0),
184                          ((struct sockaddr_in *) 0),
185                          "KPOPV0.1"));
186     free(ticket);
187     if (prin_copy)
188     {
189         free(prin_copy);
190     }
191     if (rem != KSUCCESS)
192     {
193         report(stderr, GT_("kerberos error %s\n"), (krb_get_err_text (rem)));
194         return (PS_AUTHFAIL);
195     }
196     return (0);
197 }
198 #endif /* KERBEROS_V4 */
199
200 #ifdef KERBEROS_V5
201 static int kerberos5_auth(socket, canonical)
202 /* authenticate to the server host using Kerberos V5 */
203 int socket;             /* socket to server host */
204 const char *canonical;  /* server name */
205 {
206     krb5_error_code retval;
207     krb5_context context;
208     krb5_ccache ccdef;
209     krb5_principal client = NULL, server = NULL;
210     krb5_error *err_ret = NULL;
211
212     krb5_auth_context auth_context = NULL;
213
214     krb5_init_context(&context);
215     krb5_auth_con_init(context, &auth_context);
216
217     if (retval = krb5_cc_default(context, &ccdef)) {
218         report(stderr, "krb5_cc_default: %s\n", error_message(retval));
219         return(PS_ERROR);
220     }
221
222     if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
223         report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval));
224         return(PS_ERROR);
225     }
226
227     if (retval = krb5_sname_to_principal(context, canonical, "pop",
228            KRB5_NT_UNKNOWN,
229            &server)) {
230         report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval));
231         return(PS_ERROR);
232     }
233
234     retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
235          "KPOPV1.0", client, server,
236          AP_OPTS_MUTUAL_REQUIRED,
237          NULL,  /* no data to checksum */
238          0,   /* no creds, use ccache instead */
239          ccdef,
240          &err_ret, 0,
241
242          NULL); /* don't need reply */
243
244     krb5_free_principal(context, server);
245     krb5_free_principal(context, client);
246     krb5_auth_con_free(context, auth_context);
247
248     if (retval) {
249 #ifdef HEIMDAL
250       if (err_ret && err_ret->e_text) {
251           report(stderr, GT_("krb5_sendauth: %s [server says '%*s'] \n"),
252                  error_message(retval),
253                  err_ret->e_text);
254 #else
255       if (err_ret && err_ret->text.length) {
256           report(stderr, GT_("krb5_sendauth: %s [server says '%*s'] \n"),
257                  error_message(retval),
258                  err_ret->text.length,
259                  err_ret->text.data);
260 #endif
261           krb5_free_error(context, err_ret);
262       } else
263           report(stderr, "krb5_sendauth: %s\n", error_message(retval));
264       return(PS_ERROR);
265     }
266
267     return 0;
268 }
269 #endif /* KERBEROS_V5 */
270
271 static void clean_skipped_list(struct idlist **skipped_list)
272 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
273 {
274     struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
275     prev = current = head = *skipped_list;
276
277     if (!head)
278         return;
279     do
280     {
281         /* if item has no reference, remove it */
282         if (current && current->val.status.mark == 0)
283         {
284             if (current == head) /* remove first item (head) */
285             {
286                 head = current->next;
287                 if (current->id) free(current->id);
288                 free(current);
289                 prev = current = head;
290             }
291             else /* remove middle/last item */
292             {
293                 tmp = current->next;
294                 prev->next = tmp;
295                 if (current->id) free(current->id);
296                 free(current);
297                 current = tmp;
298             }
299         }
300         else /* skip this item */
301         {
302             prev = current;
303             current = current->next;
304         }
305     } while(current);
306
307     *skipped_list = head;
308 }
309
310 static void send_size_warnings(struct query *ctl)
311 /* send warning mail with skipped msg; reset msg count when user notified */
312 {
313     int size, nbr;
314     int msg_to_send = FALSE;
315     struct idlist *head=NULL, *current=NULL;
316     int max_warning_poll_count;
317
318     head = ctl->skipped;
319     if (!head)
320         return;
321
322     /* don't start a notification message unless we need to */
323     for (current = head; current; current = current->next)
324         if (current->val.status.num == 0 && current->val.status.mark)
325             msg_to_send = TRUE;
326     if (!msg_to_send)
327         return;
328
329     /*
330      * There's no good way to recover if we can't send notification mail, 
331      * but it's not a disaster, either, since the skipped mail will not
332      * be deleted.
333      */
334     if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
335         return;
336     stuff_warning(iana_charset, ctl,
337            GT_("Subject: Fetchmail oversized-messages warning"));
338     stuff_warning(NULL, ctl, "%s", "");
339     stuff_warning(NULL, ctl,
340             GT_("The following oversized messages remain on the mail server %s:"),
341             ctl->server.pollname);
342
343     stuff_warning(NULL, ctl, "%s", "");
344
345     if (run.poll_interval == 0)
346         max_warning_poll_count = 0;
347     else
348         max_warning_poll_count = ctl->warnings/run.poll_interval;
349
350     /* parse list of skipped msg, adding items to the mail */
351     for (current = head; current; current = current->next)
352     {
353         if (current->val.status.num == 0 && current->val.status.mark)
354         {
355             nbr = current->val.status.mark;
356             size = atoi(current->id);
357             stuff_warning(NULL, ctl,
358                     GT_("  %d msg %d octets long skipped by fetchmail."),
359                     nbr, size);
360         }
361         current->val.status.num++;
362         current->val.status.mark = 0;
363
364         if (current->val.status.num >= max_warning_poll_count)
365             current->val.status.num = 0;
366     }
367
368     stuff_warning(NULL, ctl, "%s", "");
369
370     close_warning_by_mail(ctl, (struct msgblk *)NULL);
371 }
372
373 static void mark_oversized(struct query *ctl, int num, int size)
374 /* mark a message oversized */
375 {
376     struct idlist *current=NULL, *tmp=NULL;
377     char sizestr[32];
378     int cnt;
379
380     /* convert size to string */
381     snprintf(sizestr, sizeof(sizestr), "%d", size);
382
383     /* build a list of skipped messages
384      * val.id = size of msg (string cnvt)
385      * val.status.num = warning_poll_count
386      * val.status.mask = nbr of msg this size
387      */
388
389     current = ctl->skipped;
390
391     /* initialise warning_poll_count to the
392      * current value so that all new msg will
393      * be included in the next mail
394      */
395     cnt = current ? current->val.status.num : 0;
396
397     /* if entry exists, increment the count */
398     if (current && str_in_list(&current, sizestr, FALSE))
399     {
400         for ( ; current; current = current->next)
401         {
402             if (strcmp(current->id, sizestr) == 0)
403             {
404                 current->val.status.mark++;
405                 break;
406             }
407         }
408     }
409     /* otherwise, create a new entry */
410     /* initialise with current poll count */
411     else
412     {
413         tmp = save_str(&ctl->skipped, sizestr, 1);
414         tmp->val.status.num = cnt;
415     }
416 }
417
418 static int fetch_messages(int mailserver_socket, struct query *ctl, 
419                           int count, int **msgsizes, int maxfetch,
420                           int *fetches, int *dispatches, int *deletions)
421 /* fetch messages in lockstep mode */
422 {
423     flag force_retrieval;
424     int num, firstnum = 1, lastnum = 0, err, len;
425     int fetchsizelimit = ctl->fetchsizelimit;
426     int msgsize;
427
428     if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit))
429     {
430         /* for POP3, we can get the size of one mail only! Unfortunately, this
431          * protocol specific test cannot be done elsewhere as the protocol
432          * could be "auto". */
433         switch (ctl->server.protocol)
434         {
435             case P_POP3: case P_APOP: case P_RPOP:
436             fetchsizelimit = 1;
437         }
438
439         /* Time to allocate memory to store the sizes */
440         xfree(*msgsizes);
441         *msgsizes = xmalloc(sizeof(int) * fetchsizelimit);
442     }
443
444     /*
445      * What forces this code is that in POP2 and
446      * IMAP2bis you can't fetch a message without
447      * having it marked `seen'.  In POP3 and IMAP4, on the
448      * other hand, you can (peek_capable is set by 
449      * each driver module to convey this; it's not a
450      * method constant because of the difference between
451      * IMAP2bis and IMAP4, and because POP3 doesn't  peek
452      * if fetchall is on).
453      *
454      * The result of being unable to peek is that if there's
455      * any kind of transient error (DNS lookup failure, or
456      * sendmail refusing delivery due to process-table limits)
457      * the message will be marked "seen" on the server without
458      * having been delivered.  This is not a big problem if
459      * fetchmail is running in foreground, because the user
460      * will see a "skipped" message when it next runs and get
461      * clued in.
462      *
463      * But in daemon mode this leads to the message
464      * being silently ignored forever.  This is not
465      * acceptable.
466      *
467      * We compensate for this by checking the error
468      * count from the previous pass and forcing all
469      * messages to be considered new if it's nonzero.
470      */
471     force_retrieval = !peek_capable && (ctl->errcount > 0);
472
473     for (num = 1; num <= count; num++)
474     {
475         flag suppress_delete = FALSE;
476         flag suppress_forward = FALSE;
477         flag suppress_readbody = FALSE;
478         flag retained = FALSE;
479         int msgcode = MSGLEN_UNKNOWN;
480
481         /* check if the message is old
482          * Note: the size of the message may not be known here */
483         if (ctl->fetchall || force_retrieval)
484             ;
485         else if (ctl->server.base_protocol->is_old && (ctl->server.base_protocol->is_old)(mailserver_socket,ctl,num))
486             msgcode = MSGLEN_OLD;
487         if (msgcode == MSGLEN_OLD)
488         {
489                 /* To avoid flooding the syslog when using --keep,
490                  * report "Skipped message" only when:
491                  *  1) --verbose is on, or
492                  *  2) fetchmail does not use syslog
493                  */
494             if (   (outlevel >= O_VERBOSE) ||
495                    (outlevel > O_SILENT && !run.use_syslog)
496                )
497             {
498                 report_build(stdout, 
499                              GT_("skipping message %s@%s:%d"),
500                              ctl->remotename, ctl->server.truename, num);
501             }
502
503             goto flagthemail;
504         }
505
506         if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit) &&
507             lastnum < num)
508         {
509             /* Instead of getting the sizes of all mails at the start, we get
510              * the sizes in blocks of fetchsizelimit. This leads to better
511              * performance when there are too many mails (say, 10000) in
512              * the mailbox and either we are not getting all the mails at
513              * one go (--fetchlimit 100) or there is a frequent socket
514              * error while just getting the sizes of all mails! */
515
516             int i;
517             int oldstage = stage;
518             firstnum = num;
519             lastnum = num + fetchsizelimit - 1;
520             if (lastnum > count)
521                 lastnum = count;
522             for (i = 0; i < fetchsizelimit; i++)
523                 (*msgsizes)[i] = 0;
524
525             stage = STAGE_GETSIZES;
526             err = (ctl->server.base_protocol->getpartialsizes)(mailserver_socket, num, lastnum, *msgsizes);
527             if (err != 0) {
528                 return err;
529             }
530             stage = oldstage;
531         }
532
533         msgsize = *msgsizes ? (*msgsizes)[num-firstnum] : 0;
534
535         /* check if the message is oversized */
536         if (NUM_NONZERO(ctl->limit) && (msgsize > ctl->limit))
537             msgcode = MSGLEN_TOOLARGE;
538 /*      else if (msgsize == 512)
539             msgcode = MSGLEN_OLD;  (hmh) sample code to skip message */
540
541         if (msgcode < 0)
542         {
543             if ((msgcode == MSGLEN_TOOLARGE) && !check_only)
544             {
545                 mark_oversized(ctl, num, msgsize);
546                 /* we do not want to delete oversized messages in daemon
547                  * mode, but allow deletions in single-pass mode. */
548                 if (run.poll_interval)
549                     suppress_delete = TRUE;
550             }
551             if (outlevel > O_SILENT)
552             {
553                 /* old messages are already handled above */
554                 report_build(stdout, 
555                              GT_("skipping message %s@%s:%d (%d octets)"),
556                              ctl->remotename, ctl->server.truename, num,
557                              msgsize);
558                 switch (msgcode)
559                 {
560                 case MSGLEN_INVALID:
561                     /*
562                      * Invalid lengths are produced by Post Office/NT's
563                      * annoying habit of randomly prepending bogus
564                      * LIST items of length -1.  Patrick Audley
565                      * <paudley@pobox.com> tells us: LIST shows a
566                      * size of -1, RETR and TOP return "-ERR
567                      * System error - couldn't open message", and
568                      * DELE succeeds but doesn't actually delete
569                      * the message.
570                      */
571                     report_build(stdout, GT_(" (length -1)"));
572                     break;
573                 case MSGLEN_TOOLARGE:
574                     report_build(stdout, GT_(" (oversized)"));
575                     break;
576                 }
577             }
578         }
579         else
580         {
581             flag wholesize = !ctl->server.base_protocol->fetch_body;
582             flag separatefetchbody = (ctl->server.base_protocol->fetch_body) ? TRUE : FALSE;
583
584             /* request a message */
585             err = (ctl->server.base_protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
586             if (err == PS_TRANSIENT)    /* server is probably Exchange */
587             {
588                 report(stdout,
589                              GT_("couldn't fetch headers, message %s@%s:%d (%d octets)\n"),
590                              ctl->remotename, ctl->server.truename, num,
591                              msgsize);
592                 continue;
593             }
594             else if (err != 0)
595                 return(err);
596
597             /* -1 means we didn't see a size in the response */
598             if (len == -1)
599             {
600                 len = msgsize;
601                 wholesize = TRUE;
602             }
603
604             if (outlevel > O_SILENT)
605             {
606                 report_build(stdout, GT_("reading message %s@%s:%d of %d"),
607                              ctl->remotename, ctl->server.truename,
608                              num, count);
609
610                 if (len > 0)
611                     report_build(stdout, wholesize ? GT_(" (%d octets)")
612                                  : GT_(" (%d header octets)"), len);
613                 if (outlevel >= O_VERBOSE)
614                     report_complete(stdout, "\n");
615                 else
616                     report_complete(stdout, " ");
617             }
618
619             /* 
620              * Read the message headers and ship them to the
621              * output sink.  
622              */
623             err = readheaders(mailserver_socket, len, msgsize,
624                              ctl, num,
625                              /* pass the suppress_readbody flag only if the underlying
626                               * protocol does not fetch the body separately */
627                              separatefetchbody ? 0 : &suppress_readbody);
628             if (err == PS_RETAINED)
629                 suppress_forward = suppress_delete = retained = TRUE;
630             else if (err == PS_TRANSIENT)
631                 suppress_delete = suppress_forward = TRUE;
632             else if (err == PS_REFUSED)
633                 suppress_forward = TRUE;
634             else if (err == PS_TRUNCATED)
635                 suppress_readbody = TRUE;
636             else if (err)
637                 return(err);
638
639             /* tell server we got it OK and resynchronize */
640             if (separatefetchbody && ctl->server.base_protocol->trail)
641             {
642                 if (outlevel >= O_VERBOSE && !isafile(1))
643                 {
644                     fputc('\n', stdout);
645                     fflush(stdout);
646                 }
647
648                 if ((err = (ctl->server.base_protocol->trail)(mailserver_socket, ctl, num)))
649                     return(err);
650             }
651
652             /* do not read the body which is not being forwarded only if
653              * the underlying protocol allows the body to be fetched
654              * separately */
655             if (separatefetchbody && suppress_forward)
656                 suppress_readbody = TRUE;
657
658             /* 
659              * If we're using IMAP4 or something else that
660              * can fetch headers separately from bodies,
661              * it's time to request the body now.  This
662              * fetch may be skipped if we got an anti-spam
663              * or other PS_REFUSED error response during
664              * readheaders.
665              */
666             if (!suppress_readbody)
667             {
668                 if (separatefetchbody)
669                 {
670                     len = -1;
671                     if ((err=(ctl->server.base_protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
672                         return(err);
673                     /*
674                      * Work around a bug in Novell's
675                      * broken GroupWise IMAP server;
676                      * its body FETCH response is missing
677                      * the required length for the data
678                      * string.  This violates RFC2060.
679                      */
680                     if (len == -1)
681                         len = msgsize - msgblk.msglen;
682                     if (outlevel > O_SILENT && !wholesize)
683                         report_complete(stdout,
684                                         GT_(" (%d body octets) "), len);
685                 }
686
687                 /* process the body now */
688                 err = readbody(mailserver_socket,
689                               ctl,
690                               !suppress_forward,
691                               len);
692                 if (err == PS_TRANSIENT)
693                     suppress_delete = suppress_forward = TRUE;
694                 else if (err)
695                     return(err);
696
697                 /* tell server we got it OK and resynchronize */
698                 if (ctl->server.base_protocol->trail)
699                 {
700                     if (outlevel >= O_VERBOSE && !isafile(1))
701                     {
702                         fputc('\n', stdout);
703                         fflush(stdout);
704                     }
705
706                     err = (ctl->server.base_protocol->trail)(mailserver_socket, ctl, num);
707                     if (err != 0)
708                         return(err);
709                 }
710             }
711
712             /* count # messages forwarded on this pass */
713             if (!suppress_forward)
714                 (*dispatches)++;
715
716             /*
717              * Check to see if the numbers matched?
718              *
719              * Yes, some servers foo this up horribly.
720              * All IMAP servers seem to get it right, and
721              * so does Eudora QPOP at least in 2.xx
722              * versions.
723              *
724              * Microsoft Exchange gets it completely
725              * wrong, reporting compressed rather than
726              * actual sizes (so the actual length of
727              * message is longer than the reported size).
728              * Another fine example of Microsoft brain death!
729              *
730              * Some older POP servers, like the old UCB
731              * POP server and the pre-QPOP QUALCOMM
732              * versions, report a longer size in the LIST
733              * response than actually gets shipped up.
734              * It's unclear what is going on here, as the
735              * QUALCOMM server (at least) seems to be
736              * reporting the on-disk size correctly.
737              */
738             if (msgblk.msglen != msgsize)
739             {
740                 if (outlevel >= O_DEBUG)
741                     report(stdout,
742                            GT_("message %s@%s:%d was not the expected length (%d actual != %d expected)\n"),
743                            ctl->remotename, ctl->server.truename, num,
744                            msgblk.msglen, msgsize);
745             }
746
747             /* end-of-message processing starts here */
748             if (!close_sink(ctl, &msgblk, !suppress_forward))
749             {
750                 ctl->errcount++;
751                 suppress_delete = TRUE;
752             }
753             if (!retained)
754                 (*fetches)++;
755         }
756
757 flagthemail:
758         /*
759          * At this point in flow of control, either
760          * we've bombed on a protocol error or had
761          * delivery refused by the SMTP server
762          * (unlikely -- I've never seen it) or we've
763          * seen `accepted for delivery' and the
764          * message is shipped.  It's safe to mark the
765          * message seen and delete it on the server
766          * now.
767          */
768
769         /* maybe we delete this message now? */
770         if (retained)
771         {
772             if (outlevel > O_SILENT) 
773                 report(stdout, GT_(" retained\n"));
774         }
775         else if (ctl->server.base_protocol->delete
776                  && !suppress_delete
777                  && ((msgcode >= 0 && !ctl->keep)
778                      || ((msgcode == MSGLEN_OLD || msgcode == MSGLEN_TOOLARGE) && ctl->flush)))
779         {
780             (*deletions)++;
781             if (outlevel > O_SILENT) 
782                 report_complete(stdout, GT_(" flushed\n"));
783             err = (ctl->server.base_protocol->delete)(mailserver_socket, ctl, num);
784             if (err != 0)
785                 return(err);
786         }
787         else
788         {
789             if (   (outlevel >= O_VERBOSE) ||
790                         /* To avoid flooding the syslog when using --keep,
791                          * report "Skipped message" only when:
792                          *  1) --verbose is on, or
793                          *  2) fetchmail does not use syslog, or
794                          *  3) the message was skipped for some other
795                          *     reason than just being old.
796                          */
797                    (outlevel > O_SILENT && (!run.use_syslog || msgcode != MSGLEN_OLD))
798                )
799             report_complete(stdout, GT_(" not flushed\n"));
800
801             /* maybe we mark this message as seen now? */
802             if (ctl->server.base_protocol->mark_seen
803                 && !suppress_delete
804                 && (msgcode >= 0 && ctl->keep))
805             {
806                 err = (ctl->server.base_protocol->mark_seen)(mailserver_socket, ctl, num);
807                 if (err != 0)
808                     return(err);
809             }
810         }
811
812         /* perhaps this as many as we're ready to handle */
813         if (maxfetch && maxfetch <= *fetches && num < count)
814         {
815             report(stdout,
816                    ngettext("fetchlimit %d reached; %d message left on server %s account %s\n",
817                             "fetchlimit %d reached; %d messages left on server %s account %s\n", count - *fetches),
818                    maxfetch, count - *fetches, ctl->server.truename, ctl->remotename);
819             return(PS_MAXFETCH);
820         }
821     } /* for (num = 1; num <= count; num++) */
822
823     return(PS_SUCCESS);
824 }
825
826 /* retrieve messages from server using given protocol method table */
827 static int do_session(
828         /* parsed options with merged-in defaults */
829         struct query *ctl,
830         /* protocol method table */
831         const struct method *proto,
832         /* maximum number of messages to fetch */
833         const int maxfetch)
834 {
835     static int *msgsizes;
836     volatile int err, mailserver_socket = -1;   /* pacifies -Wall */
837     int deletions = 0, js;
838     const char *msg;
839     SIGHANDLERTYPE pipesave;
840     SIGHANDLERTYPE alrmsave;
841
842     ctl->server.base_protocol = proto;
843
844     msgsizes = NULL;
845     pass = 0;
846     err = 0;
847     init_transact(proto);
848
849     /* set up the server-nonresponse timeout */
850     alrmsave = set_signal_handler(SIGALRM, timeout_handler);
851     mytimeout = ctl->server.timeout;
852
853     /* set up the broken-pipe timeout */
854     pipesave = set_signal_handler(SIGPIPE, sigpipe_handler);
855
856     if ((js = setjmp(restart)))
857     {
858         /* exception caught */
859 #ifdef HAVE_SIGPROCMASK
860         /*
861          * Don't rely on setjmp() to restore the blocked-signal mask.
862          * It does this under BSD but is required not to under POSIX.
863          *
864          * If your Unix doesn't have sigprocmask, better hope it has
865          * BSD-like behavior.  Otherwise you may see fetchmail get
866          * permanently wedged after a second timeout on a bad read,
867          * because alarm signals were blocked after the first.
868          */
869         sigset_t        allsigs;
870
871         sigfillset(&allsigs);
872         sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
873 #endif /* HAVE_SIGPROCMASK */
874         
875         if (js == THROW_SIGPIPE)
876         {
877             set_signal_handler(SIGPIPE, SIG_IGN);
878             report(stdout,
879                    GT_("SIGPIPE thrown from an MDA or a stream socket error\n"));
880             wait(0);
881         }
882         else if (js == THROW_TIMEOUT)
883         {
884             if (phase == OPEN_WAIT)
885                 report(stdout,
886                        GT_("timeout after %d seconds waiting to connect to server %s.\n"),
887                        ctl->server.timeout, ctl->server.pollname);
888             else if (phase == SERVER_WAIT)
889                 report(stdout,
890                        GT_("timeout after %d seconds waiting for server %s.\n"),
891                        ctl->server.timeout, ctl->server.pollname);
892             else if (phase == FORWARDING_WAIT)
893                 report(stdout,
894                        GT_("timeout after %d seconds waiting for %s.\n"),
895                        ctl->server.timeout,
896                        ctl->mda ? "MDA" : "SMTP");
897             else if (phase == LISTENER_WAIT)
898                 report(stdout,
899                        GT_("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
900             else
901                 report(stdout, 
902                        GT_("timeout after %d seconds.\n"), ctl->server.timeout);
903
904             /*
905              * If we've exceeded our threshold for consecutive timeouts, 
906              * try to notify the user, then mark the connection wedged.
907              * Don't do this if the connection can idle, though; idle
908              * timeouts just mean the frequency of mail is low.
909              */
910             if (timeoutcount > MAX_TIMEOUTS 
911                 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
912             {
913                 stuff_warning(iana_charset, ctl,
914                               GT_("Subject: fetchmail sees repeated timeouts"));
915                 stuff_warning(NULL, ctl, "%s", "");
916                 stuff_warning(NULL, ctl,
917                               GT_("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\n"), 
918                               MAX_TIMEOUTS,
919                               ctl->remotename, ctl->server.truename);
920                 stuff_warning(NULL, ctl, 
921     GT_("This could mean that your mailserver is stuck, or that your SMTP\n" \
922     "server is wedged, or that your mailbox file on the server has been\n" \
923     "corrupted by a server error.  You can run `fetchmail -v -v' to\n" \
924     "diagnose the problem.\n\n" \
925     "Fetchmail won't poll this mailbox again until you restart it.\n"));
926                 close_warning_by_mail(ctl, (struct msgblk *)NULL);
927                 ctl->wedged = TRUE;
928             }
929         }
930
931         err = PS_SOCKET;
932         goto cleanUp;
933     }
934     else
935     {
936         /* setjmp returned zero -> normal operation */
937         char buf[MSGBUFSIZE+1], *realhost;
938         int count, new, bytes;
939         int fetches, dispatches, oldphase;
940         struct idlist *idp;
941
942         /* execute pre-initialization command, if any */
943         if (ctl->preconnect && (err = system(ctl->preconnect)))
944         {
945             report(stderr, 
946                    GT_("pre-connection command failed with status %d\n"), err);
947             err = PS_SYNTAX;
948             goto closeUp;
949         }
950
951         /* open a socket to the mail server */
952         oldphase = phase;
953         phase = OPEN_WAIT;
954         set_timeout(mytimeout);
955
956 #ifdef HAVE_PKG_hesiod
957         /* If either the pollname or vianame are "hesiod" we want to
958            lookup the user's hesiod pobox host */
959         if (!strcasecmp(ctl->server.queryname, "hesiod")) {
960             struct hes_postoffice *hes_p;
961             hes_p = hes_getmailhost(ctl->remotename);
962             if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
963                  free(ctl->server.queryname);
964                  ctl->server.queryname = xstrdup(hes_p->po_host);
965                  if (ctl->server.via)
966                      free(ctl->server.via);
967                  ctl->server.via = xstrdup(hes_p->po_host);
968             } else {
969                  report(stderr,
970                         GT_("couldn't find HESIOD pobox for %s\n"),
971                         ctl->remotename);
972             }
973         }
974 #endif /* HESIOD */
975
976         /*
977          * Canonicalize the server truename for later use.  This also
978          * functions as a probe for whether the mailserver is accessible.
979          * We try it on each poll cycle until we get a result.  This way,
980          * fetchmail won't fail if started up when the network is inaccessible.
981          */
982         if (ctl->server.dns && !ctl->server.trueaddr)
983         {
984             if (ctl->server.lead_server)
985             {
986                 char    *leadname = ctl->server.lead_server->truename;
987
988                 /* prevent core dump from ill-formed or duplicate entry */
989                 if (!leadname)
990                 {
991                     report(stderr, GT_("Lead server has no name.\n"));
992                     err = PS_DNS;
993                     set_timeout(0);
994                     phase = oldphase;
995                     goto closeUp;
996                 }
997
998                 xfree(ctl->server.truename);
999                 ctl->server.truename = xstrdup(leadname);
1000             }
1001             else
1002             {
1003                 struct addrinfo hints, *res;
1004                 int error;
1005
1006                 memset(&hints, 0, sizeof(hints));
1007                 hints.ai_socktype = SOCK_STREAM;
1008                 hints.ai_family = AF_UNSPEC;
1009                 hints.ai_flags = AI_CANONNAME;
1010
1011                 error = getaddrinfo(ctl->server.queryname, NULL, &hints, &res);
1012                 if (error)
1013                 {
1014                     report(stderr,
1015                            GT_("couldn't find canonical DNS name of %s (%s)\n"),
1016                            ctl->server.pollname, ctl->server.queryname);
1017                     err = PS_DNS;
1018                     set_timeout(0);
1019                     phase = oldphase;
1020                     goto closeUp;
1021                 }
1022                 else
1023                 {
1024                     xfree(ctl->server.truename);
1025                     ctl->server.truename = xstrdup(res->ai_canonname);
1026                     ctl->server.trueaddr = xmalloc(res->ai_addrlen);
1027                     ctl->server.trueaddr_len = res->ai_addrlen;
1028                     memcpy(ctl->server.trueaddr, res->ai_addr, res->ai_addrlen);
1029                     freeaddrinfo(res);
1030                 }
1031             }
1032         }
1033
1034         realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1035
1036         /* allow time for the port to be set up if we have a plugin */
1037         if (ctl->server.plugin)
1038             (void)sleep(1);
1039         if ((mailserver_socket = SockOpen(realhost, 
1040                              ctl->server.service ? ctl->server.service : ( ctl->use_ssl ? ctl->server.base_protocol->sslservice : ctl->server.base_protocol->service ),
1041                              ctl->server.plugin)) == -1)
1042         {
1043             char        errbuf[BUFSIZ];
1044             int err_no = errno;
1045             /*
1046              * Avoid generating a bogus error every poll cycle when we're
1047              * in daemon mode but the connection to the outside world
1048              * is down.
1049              */
1050             if (!((err_no == EHOSTUNREACH || err_no == ENETUNREACH) 
1051                   && run.poll_interval))
1052             {
1053                 report_build(stderr, GT_("%s connection to %s failed"), 
1054                              ctl->server.base_protocol->name, ctl->server.pollname);
1055                     strlcpy(errbuf, strerror(err_no), sizeof(errbuf));
1056                 report_complete(stderr, ": %s\n", errbuf);
1057
1058 #ifdef __UNUSED
1059                 /* 
1060                  * Don't use this.  It was an attempt to address Debian bug
1061                  * #47143 (Notify user by mail when pop server nonexistent).
1062                  * Trouble is, that doesn't work; you trip over the case 
1063                  * where your SLIP or PPP link is down...
1064                  */
1065                 /* warn the system administrator */
1066                 if (open_warning_by_mail(ctl, (struct msgblk *)NULL) == 0)
1067                 {
1068                     stuff_warning(iana_charset, ctl,
1069                          GT_("Subject: Fetchmail unreachable-server warning."));
1070                     stuff_warning(NULL, ctl, "");
1071                     stuff_warning(NULL, ctl, GT_("Fetchmail could not reach the mail server %s:"),
1072                                   ctl->server.pollname);
1073                     stuff_warning(NULL, ctl, errbuf, ctl->server.pollname);
1074                     close_warning_by_mail(ctl, (struct msgblk *)NULL);
1075                 }
1076 #endif
1077             }
1078             err = PS_SOCKET;
1079             set_timeout(0);
1080             phase = oldphase;
1081             goto closeUp;
1082         }
1083
1084 #ifdef SSL_ENABLE
1085         /* Save the socket opened. Useful if Fetchmail hangs on SSLOpen 
1086          * because the socket can be closed.
1087          */
1088         mailserver_socket_temp = mailserver_socket;
1089         set_timeout(mytimeout);
1090
1091         /* perform initial SSL handshake on open connection */
1092         /* Note:  We pass the realhost name over for certificate
1093                 verification.  We may want to make this configurable */
1094         if (ctl->use_ssl && SSLOpen(mailserver_socket,ctl->sslcert,ctl->sslkey,ctl->sslproto,ctl->sslcertck,
1095             ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1) 
1096         {
1097             report(stderr, GT_("SSL connection failed.\n"));
1098             err = PS_AUTHFAIL;
1099             goto cleanUp;
1100         }
1101         
1102         /* Fetchmail didn't hang on SSLOpen, 
1103          * then no need to set mailserver_socket_temp 
1104          */
1105         mailserver_socket_temp = -1;
1106 #endif
1107         
1108         /* A timeout is still defined before SSLOpen, 
1109          * then Fetchmail hanging on SSLOpen is handled.
1110          */
1111         set_timeout(0);
1112         phase = oldphase;
1113 #ifdef KERBEROS_V4
1114         if (ctl->server.authenticate == A_KERBEROS_V4 && (strcasecmp(proto->name,"IMAP") != 0))
1115         {
1116             set_timeout(mytimeout);
1117             err = kerberos_auth(mailserver_socket, ctl->server.truename,
1118                                ctl->server.principal);
1119             set_timeout(0);
1120             if (err != 0)
1121                 goto cleanUp;
1122         }
1123 #endif /* KERBEROS_V4 */
1124
1125 #ifdef KERBEROS_V5
1126         if (ctl->server.authenticate == A_KERBEROS_V5)
1127         {
1128             set_timeout(mytimeout);
1129             err = kerberos5_auth(mailserver_socket, ctl->server.truename);
1130             set_timeout(0);
1131             if (err != 0)
1132                 goto cleanUp;
1133         }
1134 #endif /* KERBEROS_V5 */
1135
1136         /* accept greeting message from mail server */
1137         err = (ctl->server.base_protocol->parse_response)(mailserver_socket, buf);
1138         if (err != 0)
1139             goto cleanUp;
1140
1141         /* try to get authorized to fetch mail */
1142         stage = STAGE_GETAUTH;
1143         if (ctl->server.base_protocol->getauth)
1144         {
1145             err = (ctl->server.base_protocol->getauth)(mailserver_socket, ctl, buf);
1146
1147             if (err != 0)
1148             {
1149                 if (err == PS_LOCKBUSY)
1150                     report(stderr, GT_("Lock-busy error on %s@%s\n"),
1151                           ctl->remotename,
1152                           ctl->server.truename);
1153                 else if (err == PS_SERVBUSY)
1154                     report(stderr, GT_("Server busy error on %s@%s\n"),
1155                           ctl->remotename,
1156                           ctl->server.truename);
1157                 else if (err == PS_AUTHFAIL)
1158                 {
1159                     report(stderr, GT_("Authorization failure on %s@%s%s\n"), 
1160                            ctl->remotename,
1161                            ctl->server.truename,
1162                            (ctl->wehaveauthed ? GT_(" (previously authorized)") : "")
1163                         );
1164
1165                     /*
1166                      * If we're running in background, try to mail the
1167                      * calling user a heads-up about the authentication 
1168                      * failure once it looks like this isn't a fluke 
1169                      * due to the server being temporarily inaccessible.
1170                      * When we get third succesive failure, we notify the user
1171                      * but only if we haven't already managed to get
1172                      * authorization.  After that, once we get authorization
1173                      * we let the user know service is restored.
1174                      */
1175                     if (run.poll_interval
1176                         && !ctl->wehavesentauthnote
1177                         && ((ctl->wehaveauthed && ++ctl->authfailcount >= 10)
1178                             || (!ctl->wehaveauthed && ++ctl->authfailcount >= 3))
1179                         && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1180                     {
1181                         ctl->wehavesentauthnote = 1;
1182                         stuff_warning(iana_charset, ctl,
1183                                       GT_("Subject: fetchmail authentication failed on %s@%s"),
1184                             ctl->remotename, ctl->server.truename);
1185                         stuff_warning(NULL, ctl, "%s", "");
1186                         stuff_warning(NULL, ctl,
1187                                       GT_("Fetchmail could not get mail from %s@%s.\n"), 
1188                                       ctl->remotename,
1189                                       ctl->server.truename);
1190                         if (ctl->wehaveauthed)
1191                             stuff_warning(NULL, ctl, GT_("\
1192 The attempt to get authorization failed.\n\
1193 Since we have already succeeded in getting authorization for this\n\
1194 connection, this is probably another failure mode (such as busy server)\n\
1195 that fetchmail cannot distinguish because the server didn't send a useful\n\
1196 error message.\n\
1197 \n\
1198 However, if you HAVE changed your account details since starting the\n\
1199 fetchmail daemon, you need to stop the daemon, change your configuration\n\
1200 of fetchmail, and then restart the daemon.\n\
1201 \n\
1202 The fetchmail daemon will continue running and attempt to connect\n\
1203 at each cycle.  No future notifications will be sent until service\n\
1204 is restored."));
1205                         else
1206                             stuff_warning(NULL, ctl, GT_("\
1207 The attempt to get authorization failed.\n\
1208 This probably means your password is invalid, but some servers have\n\
1209 other failure modes that fetchmail cannot distinguish from this\n\
1210 because they don't send useful error messages on login failure.\n\
1211 \n\
1212 The fetchmail daemon will continue running and attempt to connect\n\
1213 at each cycle.  No future notifications will be sent until service\n\
1214 is restored."));
1215                         close_warning_by_mail(ctl, (struct msgblk *)NULL);
1216                     }
1217                 }
1218                 else if (err == PS_REPOLL)
1219                 {
1220                   if (outlevel >= O_VERBOSE)
1221                     report(stderr, GT_("Repoll immediately on %s@%s\n"),
1222                            ctl->remotename,
1223                            ctl->server.truename);
1224                 }
1225                 else
1226                     report(stderr, GT_("Unknown login or authentication error on %s@%s\n"),
1227                            ctl->remotename,
1228                            ctl->server.truename);
1229                     
1230                 goto cleanUp;
1231             }
1232             else
1233             {
1234                 /*
1235                  * This connection has given us authorization at least once.
1236                  *
1237                  * There are dodgy server (clubinternet.fr for example) that
1238                  * give spurious authorization failures on patently good
1239                  * account/password details, then 5 minutes later let you in!
1240                  *
1241                  * This is meant to build in some tolerance of such nasty bits
1242                  * of work.
1243                  */
1244                 ctl->wehaveauthed = 1;
1245                 /*if (ctl->authfailcount >= 3)*/
1246                 if (ctl->wehavesentauthnote)
1247                 {
1248                     ctl->wehavesentauthnote = 0;
1249                     report(stderr,
1250                            GT_("Authorization OK on %s@%s\n"),
1251                            ctl->remotename,
1252                            ctl->server.truename);
1253                     if (!open_warning_by_mail(ctl, (struct msgblk *)NULL))
1254                     {
1255                         stuff_warning(iana_charset, ctl,
1256                               GT_("Subject: fetchmail authentication OK on %s@%s"), 
1257                                       ctl->remotename, ctl->server.truename);
1258                         stuff_warning(NULL, ctl, "%s", "");
1259                         stuff_warning(NULL, ctl,
1260                               GT_("Fetchmail was able to log into %s@%s.\n"), 
1261                                       ctl->remotename,
1262                                       ctl->server.truename);
1263                         stuff_warning(NULL, ctl, 
1264                                       GT_("Service has been restored.\n"));
1265                         close_warning_by_mail(ctl, (struct msgblk *)NULL);
1266                     
1267                     }
1268                 }
1269                 /*
1270                  * Reporting only after the first three
1271                  * consecutive failures, or ten consecutive
1272                  * failures after we have managed to get
1273                  * authorization.
1274                  */
1275                 ctl->authfailcount = 0;
1276             }
1277         }
1278
1279         ctl->errcount = fetches = 0;
1280
1281         /* now iterate over each folder selected */
1282         for (idp = ctl->mailboxes; idp; idp = idp->next)
1283         {
1284             pass = 0;
1285             do {
1286                 dispatches = 0;
1287                 ++pass;
1288
1289                 /* reset timeout, in case we did an IDLE */
1290                 mytimeout = ctl->server.timeout;
1291
1292                 if (outlevel >= O_DEBUG)
1293                 {
1294                     if (idp->id)
1295                         report(stdout, GT_("selecting or re-polling folder %s\n"), idp->id);
1296                     else
1297                         report(stdout, GT_("selecting or re-polling default folder\n"));
1298                 }
1299
1300                 /* compute # of messages and number of new messages waiting */
1301                 stage = STAGE_GETRANGE;
1302                 err = (ctl->server.base_protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &new, &bytes);
1303                 if (err != 0)
1304                     goto cleanUp;
1305
1306                 /* show user how many messages we downloaded */
1307                 if (idp->id)
1308                     (void) snprintf(buf, sizeof(buf),
1309                                    GT_("%s at %s (folder %s)"),
1310                                    ctl->remotename, ctl->server.pollname, idp->id);
1311                 else
1312                     (void) snprintf(buf, sizeof(buf), GT_("%s at %s"),
1313                                    ctl->remotename, ctl->server.pollname);
1314                 if (outlevel > O_SILENT)
1315                 {
1316                     if (count == -1)            /* only used for ETRN */
1317                         report(stdout, GT_("Polling %s\n"), ctl->server.truename);
1318                     else if (count != 0)
1319                     {
1320                         if (new != -1 && (count - new) > 0)
1321                             report_build(stdout, ngettext("%d message (%d %s) for %s", "%d messages (%d %s) for %s", (unsigned long)count),
1322                                   count,
1323                                   count-new, 
1324                                   ngettext("seen", "seen", (unsigned long)count-new),
1325                                   buf);
1326                         else
1327                             report_build(stdout, ngettext("%d message for %s",
1328                                                           "%d messages for %s",
1329                                                           count), 
1330                                   count, buf);
1331                         if (bytes == -1)
1332                             report_complete(stdout, ".\n");
1333                         else
1334                             report_complete(stdout, GT_(" (%d octets).\n"), bytes);
1335                     }
1336                     else
1337                     {
1338                         /* these are pointless in normal daemon mode */
1339                         if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1340                             report(stdout, GT_("No mail for %s\n"), buf); 
1341                     }
1342                 }
1343
1344                 /* very important, this is where we leave the do loop */ 
1345                 if (count == 0)
1346                     break;
1347
1348                 if (check_only)
1349                 {
1350                     if (new == -1 || ctl->fetchall)
1351                         new = count;
1352                     fetches = new;      /* set error status correctly */
1353                     /*
1354                      * There used to be a `goto noerror' here, but this
1355                      * prevented checking of multiple folders.  This
1356                      * comment is a reminder in case I introduced some
1357                      * subtle bug by removing it...
1358                      */
1359                 }
1360                 else if (count > 0)
1361                 {    
1362                     int         i;
1363
1364                     /*
1365                      * Don't trust the message count passed by the server.
1366                      * Without this check, it might be possible to do a
1367                      * DNS-spoofing attack that would pass back a ridiculous 
1368                      * count, and allocate a malloc area that would overlap
1369                      * a portion of the stack.
1370                      */
1371                     if (count > INT_MAX/sizeof(int))
1372                     {
1373                         report(stderr, GT_("bogus message count!"));
1374                         return(PS_PROTOCOL);
1375                     }
1376
1377                     /* 
1378                      * We need the size of each message before it's
1379                      * loaded in order to pass it to the ESMTP SIZE
1380                      * option.  If the protocol has a getsizes method,
1381                      * we presume this means it doesn't get reliable
1382                      * sizes from message fetch responses.
1383                      *
1384                      * If the protocol supports getting sizes of subset of
1385                      * messages, we skip this step now.
1386                      */
1387                     if (proto->getsizes &&
1388                         !(proto->getpartialsizes && NUM_NONZERO(ctl->fetchsizelimit)))
1389                     {
1390                         msgsizes = xmalloc(sizeof(int) * count);
1391                         for (i = 0; i < count; i++)
1392                             msgsizes[i] = 0;
1393
1394                         stage = STAGE_GETSIZES;
1395                         err = (proto->getsizes)(mailserver_socket, count, msgsizes);
1396                         if (err != 0)
1397                             goto cleanUp;
1398
1399                         if (bytes == -1)
1400                         {
1401                             bytes = 0;
1402                             for (i = 0; i < count; i++)
1403                                 bytes += msgsizes[i];
1404                         }
1405                     }
1406
1407                     /* read, forward, and delete messages */
1408                     stage = STAGE_FETCH;
1409
1410                     /* fetch in lockstep mode */
1411                     err = fetch_messages(mailserver_socket, ctl, 
1412                                          count, &msgsizes,
1413                                          maxfetch,
1414                                          &fetches, &dispatches, &deletions);
1415                     if (err)
1416                         goto cleanUp;
1417
1418                     if (!check_only && ctl->skipped
1419                         && run.poll_interval > 0 && !nodetach)
1420                     {
1421                         clean_skipped_list(&ctl->skipped);
1422                         send_size_warnings(ctl);
1423                     }
1424                 }
1425             } while
1426                   /*
1427                    * Only re-poll if we either had some actual forwards and 
1428                    * either allowed deletions and had no errors.
1429                    * Otherwise it is far too easy to get into infinite loops.
1430                    */
1431                   (dispatches && ctl->server.base_protocol->retry && !ctl->keep && !ctl->errcount);
1432         }
1433
1434     /* no_error: */
1435         /* ordinary termination with no errors -- officially log out */
1436         err = (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1437         /*
1438          * Hmmmm...arguably this would be incorrect if we had fetches but
1439          * no dispatches (due to oversized messages, etc.)
1440          */
1441         if (err == 0)
1442             err = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
1443         cleanupSockClose(mailserver_socket);
1444         goto closeUp;
1445
1446     cleanUp:
1447         /* we only get here on error */
1448         if (err != 0 && err != PS_SOCKET && err != PS_REPOLL)
1449         {
1450             stage = STAGE_LOGOUT;
1451             (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1452         }
1453
1454         /* try to clean up all streams */
1455         release_sink(ctl);
1456         smtp_close(ctl, 0);
1457         if (mailserver_socket != -1) {
1458             cleanupSockClose(mailserver_socket);
1459             mailserver_socket = -1;
1460         }
1461         /* If there was a connect timeout, the socket should be closed.
1462          * mailserver_socket_temp contains the socket to close.
1463          */
1464         if (mailserver_socket_temp != -1) {
1465             cleanupSockClose(mailserver_socket_temp);
1466             mailserver_socket_temp = -1;
1467         }
1468     }
1469
1470     /* no report on PS_MAXFETCH or PS_UNDEFINED or PS_AUTHFAIL */
1471     msg = NULL;
1472     switch (err)
1473     {
1474     case PS_SOCKET:
1475         msg = GT_("socket");
1476         break;
1477     case PS_SYNTAX:
1478         msg = GT_("missing or bad RFC822 header");
1479         break;
1480     case PS_IOERR:
1481         msg = GT_("MDA");
1482         break;
1483     case PS_ERROR:
1484         msg = GT_("client/server synchronization");
1485         break;
1486     case PS_PROTOCOL:
1487         msg = GT_("client/server protocol");
1488         break;
1489     case PS_LOCKBUSY:
1490         msg = GT_("lock busy on server");
1491         break;
1492     case PS_SMTP:
1493         msg = GT_("SMTP transaction");
1494         break;
1495     case PS_DNS:
1496         msg = GT_("DNS lookup");
1497         break;
1498     case PS_UNDEFINED:
1499         report(stderr, GT_("undefined error\n"));
1500         break;
1501     }
1502     if (msg) {
1503         const char *stem;
1504
1505         if (phase == FORWARDING_WAIT || phase == LISTENER_WAIT)
1506             stem = GT_("%s error while delivering to SMTP host %s\n");
1507         else
1508             stem = GT_("%s error while fetching from %s\n");
1509         report(stderr, stem, msg, ctl->server.pollname);
1510     }
1511
1512 closeUp:
1513     xfree(msgsizes);
1514
1515     /* execute wrapup command, if any */
1516     if (ctl->postconnect && (err = system(ctl->postconnect)))
1517     {
1518         report(stderr, GT_("post-connection command failed with status %d\n"), err);
1519         if (err == PS_SUCCESS)
1520             err = PS_SYNTAX;
1521     }
1522
1523     set_timeout(0); /* cancel any pending alarm */
1524     set_signal_handler(SIGALRM, alrmsave);
1525     set_signal_handler(SIGPIPE, pipesave);
1526     return(err);
1527 }
1528
1529 int do_protocol(ctl, proto)
1530 /* retrieve messages from server using given protocol method table */
1531 struct query *ctl;              /* parsed options with merged-in defaults */
1532 const struct method *proto;     /* protocol method table */
1533 {
1534     int err;
1535
1536 #ifndef KERBEROS_V4
1537     if (ctl->server.authenticate == A_KERBEROS_V4)
1538     {
1539         report(stderr, GT_("Kerberos V4 support not linked.\n"));
1540         return(PS_ERROR);
1541     }
1542 #endif /* KERBEROS_V4 */
1543
1544 #ifndef KERBEROS_V5
1545     if (ctl->server.authenticate == A_KERBEROS_V5)
1546     {
1547         report(stderr, GT_("Kerberos V5 support not linked.\n"));
1548         return(PS_ERROR);
1549     }
1550 #endif /* KERBEROS_V5 */
1551
1552     /* lacking methods, there are some options that may fail */
1553     if (!proto->is_old)
1554     {
1555         /* check for unsupported options */
1556         if (ctl->flush) {
1557             report(stderr,
1558                     GT_("Option --flush is not supported with %s\n"),
1559                     proto->name);
1560             return(PS_SYNTAX);
1561         }
1562         else if (ctl->fetchall) {
1563             report(stderr,
1564                     GT_("Option --all is not supported with %s\n"),
1565                     proto->name);
1566             return(PS_SYNTAX);
1567         }
1568     }
1569     if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1570     {
1571         report(stderr,
1572                 GT_("Option --limit is not supported with %s\n"),
1573                 proto->name);
1574         return(PS_SYNTAX);
1575     }
1576
1577     /*
1578      * If no expunge limit or we do expunges within the driver,
1579      * then just do one session, passing in any fetchlimit.
1580      */
1581     if ((ctl->keep && !ctl->flush) ||
1582         proto->retry || !NUM_SPECIFIED(ctl->expunge))
1583         return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
1584     /*
1585      * There's an expunge limit, and it isn't handled in the driver itself.
1586      * OK; do multiple sessions, each fetching a limited # of messages.
1587      * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
1588      * (if it was nonzero).
1589      */
1590     else
1591     {
1592         int totalcount = 0; 
1593         int lockouts   = 0;
1594         int expunge    = NUM_VALUE_OUT(ctl->expunge);
1595         int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
1596
1597         do {
1598             if (fetchlimit > 0 && (expunge == 0 || expunge > fetchlimit - totalcount))
1599                 expunge = fetchlimit - totalcount;
1600             err = do_session(ctl, proto, expunge);
1601             totalcount += expunge;
1602             if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
1603                 break;
1604             if (err != PS_LOCKBUSY)
1605                 lockouts = 0;
1606             else if (lockouts >= MAX_LOCKOUTS)
1607                 break;
1608             else /* err == PS_LOCKBUSY */
1609             {
1610                 /*
1611                  * Allow time for the server lock to release.  if we
1612                  * don't do this, we'll often hit a locked-mailbox
1613                  * condition and fail.
1614                  */
1615                 lockouts++;
1616                 sleep(3);
1617             }
1618         } while
1619             (err == PS_MAXFETCH || err == PS_LOCKBUSY);
1620
1621         return(err);
1622     }
1623 }
1624
1625
1626 /* driver.c ends here */