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