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