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