2 * driver.c -- generic driver for mail fetch method protocols
4 * Copyright 1997 by Eric S. Raymond
5 * For license terms, see the file COPYING in this directory.
15 #endif /* HAVE_MEMORY_H */
16 #if defined(STDC_HEADERS)
20 #if defined(HAVE_UNISTD_H)
23 #if defined(HAVE_SYS_ITIMER_H)
24 #include <sys/itimer.h>
27 #ifdef HAVE_SYS_WAIT_H
31 #ifdef HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
34 #ifdef HAVE_NET_SOCKET_H
35 #include <net/socket.h>
38 #ifdef HAVE_PKG_hesiod
46 #include <netinet/in.h>
47 #endif /* KERBEROS_V4 */
52 #include "fetchmail.h"
53 #include "getaddrinfo.h"
56 /* throw types for runtime errors */
57 #define THROW_TIMEOUT 1 /* server timed out */
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 */
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 */
72 struct addrinfo *ai0, *ai1; /* clean these up after signal */
74 static volatile int timeoutcount = 0; /* count consecutive timeouts */
75 static volatile int idletimeout = 0; /* timeout occured in idle stage? */
77 static sigjmp_buf restart;
79 int is_idletimeout(void)
80 /* last timeout occured in idle stage? */
85 void resetidletimeout(void)
90 void set_timeout(int timeleft)
91 /* reset the nonresponse-timeout */
93 #if !defined(__EMX__) && !defined(__BEOS__)
94 struct itimerval ntimeout;
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);
106 static RETSIGTYPE timeout_handler (int signal)
107 /* handle SIGALRM signal indicating a server timeout */
110 if(stage != STAGE_IDLE) {
112 /* XXX FIXME: this siglongjmp must die - it's not safe to be
113 * called from a function handler and breaks, for instance,
115 siglongjmp(restart, THROW_TIMEOUT);
120 #define CLEANUP_TIMEOUT 60 /* maximum timeout during cleanup */
122 static int cleanupSockClose (int fd)
123 /* close sockets in maximum CLEANUP_TIMEOUT seconds during cleanup */
126 SIGHANDLERTYPE alrmsave;
127 alrmsave = set_signal_handler(SIGALRM, null_signal_handler);
128 set_timeout(CLEANUP_TIMEOUT);
129 scerror = SockClose(fd);
131 set_signal_handler(SIGALRM, alrmsave);
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 */
145 Key_schedule schedule;
147 char * prin_copy = (char *) NULL;
148 char * prin = (char *) NULL;
149 char * inst = (char *) NULL;
150 char * realm = (char *) NULL;
152 if (principal != (char *)NULL && *principal)
155 prin = prin_copy = xstrdup(principal);
156 for (cp = prin_copy; *cp && *cp != '.'; ++cp)
162 while (*cp && *cp != '@')
172 ticket = xmalloc(sizeof (KTEXT_ST));
173 rem = (krb_sendauth (0L, socket, ticket,
175 inst ? inst : canonical,
176 realm ? realm : ((char *) (krb_realmofhost (canonical))),
181 ((struct sockaddr_in *) 0),
182 ((struct sockaddr_in *) 0),
191 report(stderr, GT_("kerberos error %s\n"), (krb_get_err_text (rem)));
192 return (PS_AUTHFAIL);
196 #endif /* KERBEROS_V4 */
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 */
204 krb5_error_code retval;
205 krb5_context context;
207 krb5_principal client = NULL, server = NULL;
208 krb5_error *err_ret = NULL;
210 krb5_auth_context auth_context = NULL;
212 krb5_init_context(&context);
213 krb5_auth_con_init(context, &auth_context);
215 if ((retval = krb5_cc_default(context, &ccdef))) {
216 report(stderr, "krb5_cc_default: %s\n", error_message(retval));
220 if ((retval = krb5_cc_get_principal(context, ccdef, &client))) {
221 report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval));
225 if ((retval = krb5_sname_to_principal(context, canonical, "pop",
228 report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval));
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 */
240 NULL); /* don't need reply */
242 krb5_free_principal(context, server);
243 krb5_free_principal(context, client);
244 krb5_auth_con_free(context, auth_context);
248 if (err_ret && err_ret->e_text) {
249 report(stderr, GT_("krb5_sendauth: %s [server says '%*s'] \n"),
250 error_message(retval),
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,
259 krb5_free_error(context, err_ret);
261 report(stderr, "krb5_sendauth: %s\n", error_message(retval));
267 #endif /* KERBEROS_V5 */
269 static void clean_skipped_list(struct idlist **skipped_list)
270 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
272 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
273 prev = current = head = *skipped_list;
279 /* if item has no reference, remove it */
280 if (current && current->val.status.mark == 0)
282 if (current == head) /* remove first item (head) */
284 head = current->next;
285 if (current->id) free(current->id);
287 prev = current = head;
289 else /* remove middle/last item */
293 if (current->id) free(current->id);
298 else /* skip this item */
301 current = current->next;
305 *skipped_list = head;
308 static void send_size_warnings(struct query *ctl)
309 /* send warning mail with skipped msg; reset msg count when user notified */
312 int msg_to_send = FALSE;
313 struct idlist *head=NULL, *current=NULL;
314 int max_warning_poll_count;
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)
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
332 if (open_warning_by_mail(ctl))
334 stuff_warning(iana_charset, ctl,
335 GT_("Subject: Fetchmail oversized-messages warning"));
336 stuff_warning(NULL, ctl, "%s", "");
338 stuff_warning(NULL, ctl,
339 GT_("The following oversized messages were deleted on server %s account %s:"),
340 ctl->server.pollname, ctl->remotename);
342 stuff_warning(NULL, ctl,
343 GT_("The following oversized messages remain on server %s account %s:"),
344 ctl->server.pollname, ctl->remotename);
346 stuff_warning(NULL, ctl, "%s", "");
348 if (run.poll_interval == 0)
349 max_warning_poll_count = 0;
351 max_warning_poll_count = ctl->warnings/run.poll_interval;
353 /* parse list of skipped msg, adding items to the mail */
354 for (current = head; current; current = current->next)
356 if (current->val.status.num == 0 && current->val.status.mark)
358 nbr = current->val.status.mark;
359 size = atoi(current->id);
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),
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),
371 current->val.status.num++;
372 current->val.status.mark = 0;
374 if (current->val.status.num >= max_warning_poll_count)
375 current->val.status.num = 0;
378 stuff_warning(NULL, ctl, "%s", "");
380 close_warning_by_mail(ctl, (struct msgblk *)NULL);
383 static void mark_oversized(struct query *ctl, int size)
384 /* mark a message oversized */
386 struct idlist *current=NULL, *tmp=NULL;
390 /* convert size to string */
391 snprintf(sizestr, sizeof(sizestr), "%d", size);
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
399 current = ctl->skipped;
401 /* initialise warning_poll_count to the
402 * current value so that all new msg will
403 * be included in the next mail
405 cnt = current ? current->val.status.num : 0;
407 /* if entry exists, increment the count */
408 if (current && (tmp = str_in_list(¤t, sizestr, FALSE)))
410 tmp->val.status.mark++;
412 /* otherwise, create a new entry */
413 /* initialise with current poll count */
416 tmp = save_str(&ctl->skipped, sizestr, 1);
417 tmp->val.status.num = cnt;
421 static int eat_trailer(int sock, struct query *ctl)
423 /* we only need this LF if we're printing ticker dots
424 * AND we are dumping protocol traces. */
425 if (outlevel >= O_VERBOSE && want_progress()) fputc('\n', stdout);
426 return (ctl->server.base_protocol->trail)(sock, ctl, tag);
429 static int fetch_messages(int mailserver_socket, struct query *ctl,
430 int count, int **msgsizes, int maxfetch,
431 int *fetches, int *dispatches, int *deletions)
432 /* fetch messages in lockstep mode */
434 flag force_retrieval;
435 int num, firstnum = 1, lastnum = 0, err, len;
436 int fetchsizelimit = ctl->fetchsizelimit;
438 int initialfetches = *fetches;
440 if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit))
442 /* for POP3, we can get the size of one mail only! Unfortunately, this
443 * protocol specific test cannot be done elsewhere as the protocol
444 * could be "auto". */
445 switch (ctl->server.protocol)
447 case P_POP3: case P_APOP: case P_RPOP:
451 /* Time to allocate memory to store the sizes */
453 *msgsizes = (int *)xmalloc(sizeof(int) * fetchsizelimit);
457 * What forces this code is that in POP2 and
458 * IMAP2bis you can't fetch a message without
459 * having it marked `seen'. In POP3 and IMAP4, on the
460 * other hand, you can (peek_capable is set by
461 * each driver module to convey this; it's not a
462 * method constant because of the difference between
463 * IMAP2bis and IMAP4, and because POP3 doesn't peek
464 * if fetchall is on).
466 * The result of being unable to peek is that if there's
467 * any kind of transient error (DNS lookup failure, or
468 * sendmail refusing delivery due to process-table limits)
469 * the message will be marked "seen" on the server without
470 * having been delivered. This is not a big problem if
471 * fetchmail is running in foreground, because the user
472 * will see a "skipped" message when it next runs and get
475 * But in daemon mode this leads to the message
476 * being silently ignored forever. This is not
479 * We compensate for this by checking the error
480 * count from the previous pass and forcing all
481 * messages to be considered new if it's nonzero.
483 force_retrieval = !peek_capable && (ctl->errcount > 0);
485 for (num = 1; num <= count; num++)
487 flag suppress_delete = FALSE;
488 flag suppress_forward = FALSE;
489 flag suppress_readbody = FALSE;
490 flag retained = FALSE;
491 int msgcode = MSGLEN_UNKNOWN;
493 /* check if the message is old
494 * Note: the size of the message may not be known here */
495 if (ctl->fetchall || force_retrieval)
497 else if (ctl->server.base_protocol->is_old && (ctl->server.base_protocol->is_old)(mailserver_socket,ctl,num))
498 msgcode = MSGLEN_OLD;
499 if (msgcode == MSGLEN_OLD)
501 /* To avoid flooding the syslog when using --keep,
502 * report "Skipped message" only when:
503 * 1) --verbose is on, or
504 * 2) fetchmail does not use syslog
506 if ( (outlevel >= O_VERBOSE) ||
507 (outlevel > O_SILENT && !run.use_syslog)
511 GT_("skipping message %s@%s:%d"),
512 ctl->remotename, ctl->server.truename, num);
518 if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit) &&
521 /* Instead of getting the sizes of all mails at the start, we get
522 * the sizes in blocks of fetchsizelimit. This leads to better
523 * performance when there are too many mails (say, 10000) in
524 * the mailbox and either we are not getting all the mails at
525 * one go (--fetchlimit 100) or there is a frequent socket
526 * error while just getting the sizes of all mails! */
529 int oldstage = stage;
531 lastnum = num + fetchsizelimit - 1;
534 for (i = 0; i < fetchsizelimit; i++)
537 stage = STAGE_GETSIZES;
538 err = (ctl->server.base_protocol->getpartialsizes)(mailserver_socket, num, lastnum, *msgsizes);
545 msgsize = *msgsizes ? (*msgsizes)[num-firstnum] : 0;
547 /* check if the message is oversized */
548 if (NUM_NONZERO(ctl->limit) && (msgsize > ctl->limit))
549 msgcode = MSGLEN_TOOLARGE;
550 /* else if (msgsize == 512)
551 msgcode = MSGLEN_OLD; (hmh) sample code to skip message */
555 if (msgcode == MSGLEN_TOOLARGE)
557 mark_oversized(ctl, msgsize);
558 if (!ctl->limitflush)
559 suppress_delete = TRUE;
561 if (outlevel > O_SILENT)
563 /* old messages are already handled above */
565 GT_("skipping message %s@%s:%d (%d octets)"),
566 ctl->remotename, ctl->server.truename, num,
572 * Invalid lengths are produced by Post Office/NT's
573 * annoying habit of randomly prepending bogus
574 * LIST items of length -1. Patrick Audley
575 * <paudley@pobox.com> tells us: LIST shows a
576 * size of -1, RETR and TOP return "-ERR
577 * System error - couldn't open message", and
578 * DELE succeeds but doesn't actually delete
581 report_build(stdout, GT_(" (length -1)"));
583 case MSGLEN_TOOLARGE:
584 report_build(stdout, GT_(" (oversized)"));
591 /* XXX FIXME: make this one variable, wholesize and
592 separatefetchbody query the same variable just with
594 flag wholesize = !ctl->server.base_protocol->fetch_body;
595 flag separatefetchbody = (ctl->server.base_protocol->fetch_body) ? TRUE : FALSE;
597 /* request a message */
598 err = (ctl->server.base_protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
599 if (err == PS_TRANSIENT) /* server is probably Exchange */
602 GT_("couldn't fetch headers, message %s@%s:%d (%d octets)\n"),
603 ctl->remotename, ctl->server.truename, num,
610 /* -1 means we didn't see a size in the response */
617 if (outlevel > O_SILENT)
619 report_build(stdout, GT_("reading message %s@%s:%d of %d"),
620 ctl->remotename, ctl->server.truename,
624 report_build(stdout, wholesize ? GT_(" (%d octets)")
625 : GT_(" (%d header octets)"), len);
626 if (want_progress()) {
627 /* flush and add a blank to append ticker dots */
628 report_flush(stdout);
634 * Read the message headers and ship them to the
637 err = readheaders(mailserver_socket, len, msgsize,
639 /* pass the suppress_readbody flag only if the underlying
640 * protocol does not fetch the body separately */
641 separatefetchbody ? 0 : &suppress_readbody);
643 if (err == PS_RETAINED)
644 suppress_forward = suppress_delete = retained = TRUE;
645 else if (err == PS_TRANSIENT)
646 suppress_delete = suppress_forward = TRUE;
647 else if (err == PS_REFUSED)
648 suppress_forward = TRUE;
652 /* tell server we got it OK and resynchronize */
653 if (separatefetchbody && ctl->server.base_protocol->trail)
655 err = eat_trailer(mailserver_socket, ctl);
656 if (err) return(err);
659 /* do not read the body which is not being forwarded only if
660 * the underlying protocol allows the body to be fetched
662 if (separatefetchbody && suppress_forward)
663 suppress_readbody = TRUE;
666 * If we're using IMAP4 or something else that
667 * can fetch headers separately from bodies,
668 * it's time to request the body now. This
669 * fetch may be skipped if we got an anti-spam
670 * or other PS_REFUSED error response during
673 if (!suppress_readbody)
675 if (separatefetchbody)
678 if ((err=(ctl->server.base_protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
681 * Work around a bug in Novell's
682 * broken GroupWise IMAP server;
683 * its body FETCH response is missing
684 * the required length for the data
685 * string. This violates RFC2060.
688 len = msgsize - msgblk.msglen;
690 if (outlevel > O_SILENT)
692 GT_(" (%d body octets)"), len);
693 if (want_progress()) {
694 report_flush(stdout);
700 /* process the body now */
701 err = readbody(mailserver_socket,
706 if (err == PS_TRANSIENT)
707 suppress_delete = suppress_forward = TRUE;
711 /* tell server we got it OK and resynchronize */
712 if (ctl->server.base_protocol->trail) {
713 err = eat_trailer(mailserver_socket, ctl);
714 if (err) return(err);
718 /* count # messages forwarded on this pass */
719 if (!suppress_forward)
723 * Check to see if the numbers matched?
725 * Yes, some servers foo this up horribly.
726 * All IMAP servers seem to get it right, and
727 * so does Eudora QPOP at least in 2.xx
730 * Microsoft Exchange gets it completely
731 * wrong, reporting compressed rather than
732 * actual sizes (so the actual length of
733 * message is longer than the reported size).
734 * Another fine example of Microsoft brain death!
736 * Some older POP servers, like the old UCB
737 * POP server and the pre-QPOP QUALCOMM
738 * versions, report a longer size in the LIST
739 * response than actually gets shipped up.
740 * It's unclear what is going on here, as the
741 * QUALCOMM server (at least) seems to be
742 * reporting the on-disk size correctly.
744 * qmail-pop3d also goofs up message sizes and does not
745 * count the line end characters properly.
747 if (msgblk.msglen != msgsize)
749 if (outlevel >= O_DEBUG)
751 GT_("message %s@%s:%d was not the expected length (%d actual != %d expected)\n"),
752 ctl->remotename, ctl->server.truename, num,
753 msgblk.msglen, msgsize);
756 /* end-of-message processing starts here */
757 if (!close_sink(ctl, &msgblk, !suppress_forward))
760 suppress_delete = TRUE;
768 * At this point in flow of control,
769 * either we've bombed on a protocol error
770 * or had delivery refused by the SMTP server
771 * or we've seen `accepted for delivery' and the message is shipped.
772 * It's safe to mark the message seen and delete it on the server now.
775 /* in softbounce mode, suppress deletion and marking as seen */
776 if (suppress_forward)
777 suppress_delete = suppress_delete || run.softbounce;
779 /* maybe we delete this message now? */
782 if (outlevel > O_SILENT)
783 report_complete(stdout, GT_(" retained\n"));
785 else if (ctl->server.base_protocol->delete_msg
787 && ((msgcode >= 0 && !ctl->keep)
788 || (msgcode == MSGLEN_OLD && ctl->flush)
789 || (msgcode == MSGLEN_TOOLARGE && ctl->limitflush)))
792 if (outlevel > O_SILENT)
793 report_complete(stdout, GT_(" flushed\n"));
794 err = (ctl->server.base_protocol->delete_msg)(mailserver_socket, ctl, num);
800 if ( (outlevel >= O_VERBOSE) ||
801 /* To avoid flooding the syslog when using --keep,
802 * report "Skipped message" only when:
803 * 1) --verbose is on, or
804 * 2) fetchmail does not use syslog, or
805 * 3) the message was skipped for some other
806 * reason than just being old.
808 (outlevel > O_SILENT && (!run.use_syslog || msgcode != MSGLEN_OLD))
810 report_complete(stdout, GT_(" not flushed\n"));
812 /* maybe we mark this message as seen now? */
813 if (ctl->server.base_protocol->mark_seen
815 && (msgcode >= 0 && ctl->keep))
817 err = (ctl->server.base_protocol->mark_seen)(mailserver_socket, ctl, num);
823 /* perhaps this as many as we're ready to handle */
824 if (maxfetch && maxfetch <= *fetches && num < count)
826 int remcount = count - (*fetches - initialfetches);
828 ngettext("fetchlimit %d reached; %d message left on server %s account %s\n",
829 "fetchlimit %d reached; %d messages left on server %s account %s\n", remcount),
830 maxfetch, remcount, ctl->server.truename, ctl->remotename);
833 } /* for (num = 1; num <= count; num++) */
838 /* retrieve messages from server using given protocol method table */
839 static int do_session(
840 /* parsed options with merged-in defaults */
842 /* protocol method table */
843 const struct method *proto,
844 /* maximum number of messages to fetch */
847 static int *msgsizes;
848 volatile int err, mailserver_socket = -1; /* pacifies -Wall */
850 int deletions = 0, js;
852 SIGHANDLERTYPE alrmsave;
854 ctl->server.base_protocol = proto;
859 init_transact(proto);
861 /* set up the server-nonresponse timeout */
862 alrmsave = set_signal_handler(SIGALRM, timeout_handler);
863 mytimeout = ctl->server.timeout;
865 if ((js = sigsetjmp(restart,1)))
867 /* exception caught */
870 sigfillset(&allsigs);
871 sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
874 fm_freeaddrinfo(ai0); ai0 = NULL;
878 fm_freeaddrinfo(ai1); ai1 = NULL;
881 if (js == THROW_TIMEOUT)
883 if (phase == OPEN_WAIT)
885 GT_("timeout after %d seconds waiting to connect to server %s.\n"),
886 ctl->server.timeout, ctl->server.pollname);
887 else if (phase == SERVER_WAIT)
889 GT_("timeout after %d seconds waiting for server %s.\n"),
890 ctl->server.timeout, ctl->server.pollname);
891 else if (phase == FORWARDING_WAIT)
893 GT_("timeout after %d seconds waiting for %s.\n"),
895 ctl->mda ? "MDA" : "SMTP");
896 else if (phase == LISTENER_WAIT)
898 GT_("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
901 GT_("timeout after %d seconds.\n"), ctl->server.timeout);
904 * If we've exceeded our threshold for consecutive timeouts,
905 * try to notify the user, then mark the connection wedged.
906 * Don't do this if the connection can idle, though; idle
907 * timeouts just mean the frequency of mail is low.
909 if (timeoutcount > MAX_TIMEOUTS
910 && !open_warning_by_mail(ctl))
912 stuff_warning(iana_charset, ctl,
913 GT_("Subject: fetchmail sees repeated timeouts"));
914 stuff_warning(NULL, ctl, "%s", "");
915 stuff_warning(NULL, ctl,
916 GT_("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\n"),
918 ctl->remotename, ctl->server.truename);
919 stuff_warning(NULL, ctl,
920 GT_("This could mean that your mailserver is stuck, or that your SMTP\n" \
921 "server is wedged, or that your mailbox file on the server has been\n" \
922 "corrupted by a server error. You can run `fetchmail -v -v' to\n" \
923 "diagnose the problem.\n\n" \
924 "Fetchmail won't poll this mailbox again until you restart it.\n"));
925 close_warning_by_mail(ctl, (struct msgblk *)NULL);
935 /* sigsetjmp returned zero -> normal operation */
936 char buf[MSGBUFSIZE+1], *realhost;
937 int count, newm, bytes;
938 int fetches, dispatches, oldphase;
941 /* execute pre-initialization command, if any */
942 if (ctl->preconnect && (err = system(ctl->preconnect)))
944 if (WIFSIGNALED(err))
946 GT_("pre-connection command terminated with signal %d\n"), WTERMSIG(err));
949 GT_("pre-connection command failed with status %d\n"), WEXITSTATUS(err));
954 /* open a socket to the mail server */
957 set_timeout(mytimeout);
959 #ifdef HAVE_PKG_hesiod
960 /* If either the pollname or vianame are "hesiod" we want to
961 lookup the user's hesiod pobox host */
962 if (!strcasecmp(ctl->server.queryname, "hesiod")) {
963 struct hes_postoffice *hes_p;
964 hes_p = hes_getmailhost(ctl->remotename);
965 if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
966 free(ctl->server.queryname);
967 ctl->server.queryname = xstrdup(hes_p->po_host);
969 free(ctl->server.via);
970 ctl->server.via = xstrdup(hes_p->po_host);
973 GT_("couldn't find HESIOD pobox for %s\n"),
980 * Canonicalize the server truename for later use. This also
981 * functions as a probe for whether the mailserver is accessible.
982 * We try it on each poll cycle until we get a result. This way,
983 * fetchmail won't fail if started up when the network is inaccessible.
985 if (ctl->server.dns && !ctl->server.trueaddr)
987 if (ctl->server.lead_server)
989 char *leadname = ctl->server.lead_server->truename;
991 /* prevent core dump from ill-formed or duplicate entry */
994 report(stderr, GT_("Lead server has no name.\n"));
1001 xfree(ctl->server.truename);
1002 ctl->server.truename = xstrdup(leadname);
1006 struct addrinfo hints, *res;
1009 memset(&hints, 0, sizeof(hints));
1010 hints.ai_socktype = SOCK_STREAM;
1011 hints.ai_family = AF_UNSPEC;
1012 hints.ai_flags = AI_CANONNAME;
1014 error = fm_getaddrinfo(ctl->server.queryname, NULL, &hints, &res);
1018 GT_("couldn't find canonical DNS name of %s (%s): %s\n"),
1019 ctl->server.pollname, ctl->server.queryname,
1020 gai_strerror(error));
1028 xfree(ctl->server.truename);
1029 /* Older FreeBSD versions return NULL in ai_canonname
1030 * if they cannot canonicalize, rather than copying
1031 * the queryname here, as IEEE Std 1003.1-2001
1032 * requires. Work around NULL. */
1033 if (res->ai_canonname != NULL) {
1034 ctl->server.truename = xstrdup(res->ai_canonname);
1036 ctl->server.truename = xstrdup(ctl->server.queryname);
1038 ctl->server.trueaddr = (struct sockaddr *)xmalloc(res->ai_addrlen);
1039 ctl->server.trueaddr_len = res->ai_addrlen;
1040 memcpy(ctl->server.trueaddr, res->ai_addr, res->ai_addrlen);
1041 fm_freeaddrinfo(res);
1046 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1048 /* allow time for the port to be set up if we have a plugin */
1049 if (ctl->server.plugin)
1051 if ((mailserver_socket = SockOpen(realhost,
1052 ctl->server.service ? ctl->server.service : ( ctl->use_ssl ? ctl->server.base_protocol->sslservice : ctl->server.base_protocol->service ),
1053 ctl->server.plugin, &ai0)) == -1)
1055 char errbuf[BUFSIZ];
1058 * Avoid generating a bogus error every poll cycle when we're
1059 * in daemon mode but the connection to the outside world
1062 if (!((err_no == EHOSTUNREACH || err_no == ENETUNREACH)
1063 && run.poll_interval))
1065 report_build(stderr, GT_("%s connection to %s failed"),
1066 ctl->server.base_protocol->name, ctl->server.pollname);
1067 strlcpy(errbuf, strerror(err_no), sizeof(errbuf));
1068 report_complete(stderr, ": %s\n", errbuf);
1072 * Don't use this. It was an attempt to address Debian bug
1073 * #47143 (Notify user by mail when pop server nonexistent).
1074 * Trouble is, that doesn't work; you trip over the case
1075 * where your SLIP or PPP link is down...
1077 /* warn the system administrator */
1078 if (open_warning_by_mail(ctl) == 0)
1080 stuff_warning(iana_charset, ctl,
1081 GT_("Subject: Fetchmail unreachable-server warning."));
1082 stuff_warning(NULL, ctl, "");
1083 stuff_warning(NULL, ctl, GT_("Fetchmail could not reach the mail server %s:"),
1084 ctl->server.pollname);
1085 stuff_warning(NULL, ctl, errbuf, ctl->server.pollname);
1086 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1097 /* Save the socket opened. Useful if Fetchmail hangs on SSLOpen
1098 * because the socket can be closed.
1100 mailserver_socket_temp = mailserver_socket;
1101 set_timeout(mytimeout);
1103 /* perform initial SSL handshake on open connection */
1105 SSLOpen(mailserver_socket, ctl->sslcert, ctl->sslkey,
1106 ctl->sslproto, ctl->sslcertck, ctl->sslcertpath,
1107 ctl->sslfingerprint, ctl->sslcommonname ?
1108 ctl->sslcommonname : realhost, ctl->server.pollname,
1109 &ctl->remotename) == -1)
1111 report(stderr, GT_("SSL connection failed.\n"));
1116 /* Fetchmail didn't hang on SSLOpen,
1117 * then no need to set mailserver_socket_temp
1119 mailserver_socket_temp = -1;
1122 /* A timeout is still defined before SSLOpen,
1123 * then Fetchmail hanging on SSLOpen is handled.
1128 if (ctl->server.authenticate == A_KERBEROS_V4 && (strcasecmp(proto->name,"IMAP") != 0))
1130 set_timeout(mytimeout);
1131 err = kerberos_auth(mailserver_socket, ctl->server.truename,
1132 ctl->server.principal);
1137 #endif /* KERBEROS_V4 */
1140 if (ctl->server.authenticate == A_KERBEROS_V5)
1142 set_timeout(mytimeout);
1143 err = kerberos5_auth(mailserver_socket, ctl->server.truename);
1148 #endif /* KERBEROS_V5 */
1150 /* accept greeting message from mail server */
1151 err = (ctl->server.base_protocol->parse_response)(mailserver_socket, buf);
1155 /* try to get authorized to fetch mail */
1156 stage = STAGE_GETAUTH;
1157 if (ctl->server.base_protocol->getauth)
1159 err = (ctl->server.base_protocol->getauth)(mailserver_socket, ctl, buf);
1163 if (err == PS_LOCKBUSY)
1164 report(stderr, GT_("Lock-busy error on %s@%s\n"),
1166 ctl->server.truename);
1167 else if (err == PS_SERVBUSY)
1168 report(stderr, GT_("Server busy error on %s@%s\n"),
1170 ctl->server.truename);
1171 else if (err == PS_AUTHFAIL)
1173 report(stderr, GT_("Authorization failure on %s@%s%s\n"),
1175 ctl->server.truename,
1176 (ctl->wehaveauthed ? GT_(" (previously authorized)") : "")
1180 * If we're running in background, try to mail the
1181 * calling user a heads-up about the authentication
1182 * failure once it looks like this isn't a fluke
1183 * due to the server being temporarily inaccessible.
1184 * When we get third succesive failure, we notify the user
1185 * but only if we haven't already managed to get
1186 * authorization. After that, once we get authorization
1187 * we let the user know service is restored.
1189 if (run.poll_interval
1190 && !ctl->wehavesentauthnote
1191 && ((ctl->wehaveauthed && ++ctl->authfailcount >= 10)
1192 || (!ctl->wehaveauthed && ++ctl->authfailcount >= 3))
1193 && !open_warning_by_mail(ctl))
1195 ctl->wehavesentauthnote = 1;
1196 stuff_warning(iana_charset, ctl,
1197 GT_("Subject: fetchmail authentication failed on %s@%s"),
1198 ctl->remotename, ctl->server.truename);
1199 stuff_warning(NULL, ctl, "%s", "");
1200 stuff_warning(NULL, ctl,
1201 GT_("Fetchmail could not get mail from %s@%s.\n"),
1203 ctl->server.truename);
1204 if (ctl->wehaveauthed) {
1205 stuff_warning(NULL, ctl, GT_("\
1206 The attempt to get authorization failed.\n\
1207 Since we have already succeeded in getting authorization for this\n\
1208 connection, this is probably another failure mode (such as busy server)\n\
1209 that fetchmail cannot distinguish because the server didn't send a useful\n\
1211 stuff_warning(NULL, ctl, GT_("\
1213 However, if you HAVE changed your account details since starting the\n\
1214 fetchmail daemon, you need to stop the daemon, change your configuration\n\
1215 of fetchmail, and then restart the daemon.\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\
1221 stuff_warning(NULL, ctl, GT_("\
1222 The attempt to get authorization failed.\n\
1223 This probably means your password is invalid, but some servers have\n\
1224 other failure modes that fetchmail cannot distinguish from this\n\
1225 because they don't send useful error messages on login failure.\n\
1227 The fetchmail daemon will continue running and attempt to connect\n\
1228 at each cycle. No future notifications will be sent until service\n\
1231 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1234 else if (err == PS_REPOLL)
1236 if (outlevel >= O_VERBOSE)
1237 report(stderr, GT_("Repoll immediately on %s@%s\n"),
1239 ctl->server.truename);
1242 report(stderr, GT_("Unknown login or authentication error on %s@%s\n"),
1244 ctl->server.truename);
1251 * This connection has given us authorization at least once.
1253 * There are dodgy server (clubinternet.fr for example) that
1254 * give spurious authorization failures on patently good
1255 * account/password details, then 5 minutes later let you in!
1257 * This is meant to build in some tolerance of such nasty bits
1260 ctl->wehaveauthed = 1;
1261 /*if (ctl->authfailcount >= 3)*/
1262 if (ctl->wehavesentauthnote)
1264 ctl->wehavesentauthnote = 0;
1266 GT_("Authorization OK on %s@%s\n"),
1268 ctl->server.truename);
1269 if (!open_warning_by_mail(ctl))
1271 stuff_warning(iana_charset, ctl,
1272 GT_("Subject: fetchmail authentication OK on %s@%s"),
1273 ctl->remotename, ctl->server.truename);
1274 stuff_warning(NULL, ctl, "%s", "");
1275 stuff_warning(NULL, ctl,
1276 GT_("Fetchmail was able to log into %s@%s.\n"),
1278 ctl->server.truename);
1279 stuff_warning(NULL, ctl,
1280 GT_("Service has been restored.\n"));
1281 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1286 * Reporting only after the first three
1287 * consecutive failures, or ten consecutive
1288 * failures after we have managed to get
1291 ctl->authfailcount = 0;
1295 ctl->errcount = fetches = 0;
1297 /* now iterate over each folder selected */
1298 for (idp = ctl->mailboxes; idp; idp = idp->next)
1300 ctl->folder = idp->id;
1306 /* reset timeout, in case we did an IDLE */
1307 mytimeout = ctl->server.timeout;
1309 if (outlevel >= O_DEBUG)
1312 report(stdout, GT_("selecting or re-polling folder %s\n"), idp->id);
1314 report(stdout, GT_("selecting or re-polling default folder\n"));
1317 /* compute # of messages and number of new messages waiting */
1318 stage = STAGE_GETRANGE;
1319 err = (ctl->server.base_protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &newm, &bytes);
1323 /* show user how many messages we downloaded */
1325 (void) snprintf(buf, sizeof(buf),
1326 GT_("%s at %s (folder %s)"),
1327 ctl->remotename, ctl->server.pollname, idp->id);
1329 (void) snprintf(buf, sizeof(buf), GT_("%s at %s"),
1330 ctl->remotename, ctl->server.pollname);
1331 if (outlevel > O_SILENT)
1333 if (count == -1) /* only used for ETRN */
1334 report(stdout, GT_("Polling %s\n"), ctl->server.truename);
1335 else if (count != 0)
1337 if (newm != -1 && (count - newm) > 0)
1338 report_build(stdout, ngettext("%d message (%d %s) for %s", "%d messages (%d %s) for %s", (unsigned long)count),
1341 ngettext("seen", "seen", (unsigned long)count-newm),
1344 report_build(stdout, ngettext("%d message for %s",
1345 "%d messages for %s",
1349 report_complete(stdout, ".\n");
1351 report_complete(stdout, GT_(" (%d octets).\n"), bytes);
1355 /* these are pointless in normal daemon mode */
1356 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1357 report(stdout, GT_("No mail for %s\n"), buf);
1361 /* very important, this is where we leave the do loop */
1367 if (newm == -1 || ctl->fetchall)
1369 fetches = newm; /* set error status correctly */
1371 * There used to be a `goto noerror' here, but this
1372 * prevented checking of multiple folders. This
1373 * comment is a reminder in case I introduced some
1374 * subtle bug by removing it...
1382 * Don't trust the message count passed by the server.
1383 * Without this check, it might be possible to do a
1384 * DNS-spoofing attack that would pass back a ridiculous
1385 * count, and allocate a malloc area that would overlap
1386 * a portion of the stack.
1388 if ((unsigned)count > INT_MAX/sizeof(int))
1390 report(stderr, GT_("bogus message count!"));
1396 * We need the size of each message before it's
1397 * loaded in order to pass it to the ESMTP SIZE
1398 * option. If the protocol has a getsizes method,
1399 * we presume this means it doesn't get reliable
1400 * sizes from message fetch responses.
1402 * If the protocol supports getting sizes of subset of
1403 * messages, we skip this step now.
1405 if (proto->getsizes &&
1406 !(proto->getpartialsizes && NUM_NONZERO(ctl->fetchsizelimit)))
1409 msgsizes = (int *)xmalloc(sizeof(int) * count);
1410 for (i = 0; i < count; i++)
1413 stage = STAGE_GETSIZES;
1414 err = (proto->getsizes)(mailserver_socket, count, msgsizes);
1421 for (i = 0; i < count; i++)
1422 bytes += msgsizes[i];
1426 /* read, forward, and delete messages */
1427 stage = STAGE_FETCH;
1429 /* fetch in lockstep mode */
1430 err = fetch_messages(mailserver_socket, ctl,
1433 &fetches, &dispatches, &deletions);
1434 if (err != PS_SUCCESS && err != PS_MAXFETCH)
1437 if (!check_only && ctl->skipped
1438 && run.poll_interval > 0 && !nodetach)
1440 clean_skipped_list(&ctl->skipped);
1441 send_size_warnings(ctl);
1445 /* end-of-mailbox processing before we repoll or switch to another one */
1446 if (ctl->server.base_protocol->end_mailbox_poll)
1448 tmperr = (ctl->server.base_protocol->end_mailbox_poll)(mailserver_socket, ctl);
1454 /* Return now if we have reached the fetchlimit */
1455 if (maxfetch && maxfetch <= fetches)
1459 * Only repoll if we either had some actual forwards
1460 * or are idling for new mails and had no errors.
1461 * Otherwise it is far too easy to get into infinite loops.
1463 (ctl->server.base_protocol->retry && (dispatches || ctl->idle) && !ctl->errcount);
1466 /* XXX: From this point onwards, preserve err unless a new error has occurred */
1469 /* PS_SUCCESS, PS_MAXFETCH: ordinary termination with no errors -- officially log out */
1470 stage = STAGE_LOGOUT;
1471 tmperr = (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1472 if (tmperr != PS_SUCCESS)
1475 * Hmmmm...arguably this would be incorrect if we had fetches but
1476 * no dispatches (due to oversized messages, etc.)
1478 else if (err == PS_SUCCESS && fetches == 0)
1481 * Close all SMTP delivery sockets. For optimum performance
1482 * we'd like to hold them open til end of run, but (1) this
1483 * loses if our poll interval is longer than the MTA's
1484 * inactivity timeout, and (2) some MTAs (like smail) don't
1485 * deliver after each message, but rather queue up mail and
1486 * wait to actually deliver it until the input socket is
1489 * don't send QUIT for ODMR case because we're acting as a
1490 * proxy between the SMTP server and client.
1492 smtp_close(ctl, ctl->server.protocol != P_ODMR);
1493 cleanupSockClose(mailserver_socket);
1497 /* we only get here on error */
1498 if (err != 0 && err != PS_SOCKET && err != PS_REPOLL)
1500 stage = STAGE_LOGOUT;
1501 (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1504 /* try to clean up all streams */
1507 * Sending SMTP QUIT on signal is theoretically nice, but led
1508 * to a subtle bug. If fetchmail was terminated by signal
1509 * while it was shipping message text, it would hang forever
1510 * waiting for a command acknowledge. In theory we could
1511 * enable the QUIT only outside of the message send. In
1512 * practice, we don't care. All mailservers hang up on a
1513 * dropped TCP/IP connection anyway.
1516 if (mailserver_socket != -1) {
1517 cleanupSockClose(mailserver_socket);
1518 mailserver_socket = -1;
1520 /* If there was a connect timeout, the socket should be closed.
1521 * mailserver_socket_temp contains the socket to close.
1523 if (mailserver_socket_temp != -1) {
1524 cleanupSockClose(mailserver_socket_temp);
1525 mailserver_socket_temp = -1;
1529 /* no report on PS_AUTHFAIL */
1534 msg = GT_("socket");
1537 msg = GT_("missing or bad RFC822 header");
1543 msg = GT_("client/server synchronization");
1546 msg = GT_("client/server protocol");
1549 msg = GT_("lock busy on server");
1552 msg = GT_("SMTP transaction");
1555 msg = GT_("DNS lookup");
1558 msg = GT_("undefined");
1562 if (phase == FORWARDING_WAIT || phase == LISTENER_WAIT
1564 report(stderr, GT_("%s error while fetching from %s@%s and delivering to SMTP host %s\n"),
1565 msg, ctl->remotename, ctl->server.pollname,
1566 ctl->smtphost ? ctl->smtphost : GT_("unknown"));
1568 report(stderr, GT_("%s error while fetching from %s@%s\n"),
1569 msg, ctl->remotename, ctl->server.pollname);
1576 /* execute wrapup command, if any */
1577 if (ctl->postconnect && (tmperr = system(ctl->postconnect)))
1579 if (WIFSIGNALED(tmperr))
1580 report(stderr, GT_("post-connection command terminated with signal %d\n"), WTERMSIG(tmperr));
1582 report(stderr, GT_("post-connection command failed with status %d\n"), WEXITSTATUS(tmperr));
1583 if (err == PS_SUCCESS)
1587 set_timeout(0); /* cancel any pending alarm */
1588 set_signal_handler(SIGALRM, alrmsave);
1592 /** retrieve messages from server using given protocol method table */
1593 int do_protocol(struct query *ctl /** parsed options with merged-in defaults */,
1594 const struct method *proto /** protocol method table */)
1599 if (ctl->server.authenticate == A_KERBEROS_V4)
1601 report(stderr, GT_("Kerberos V4 support not linked.\n"));
1604 #endif /* KERBEROS_V4 */
1607 if (ctl->server.authenticate == A_KERBEROS_V5)
1609 report(stderr, GT_("Kerberos V5 support not linked.\n"));
1612 #endif /* KERBEROS_V5 */
1614 /* lacking methods, there are some options that may fail */
1617 /* check for unsupported options */
1620 GT_("Option --flush is not supported with %s\n"),
1624 else if (ctl->fetchall) {
1626 GT_("Option --all is not supported with %s\n"),
1631 if (!(proto->getsizes || proto->getpartialsizes)
1632 && NUM_SPECIFIED(ctl->limit))
1635 GT_("Option --limit is not supported with %s\n"),
1641 * If no expunge limit or we do expunges within the driver,
1642 * then just do one session, passing in any fetchlimit.
1644 if ((ctl->keep && !ctl->flush) ||
1645 proto->retry || !NUM_SPECIFIED(ctl->expunge))
1646 return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
1648 * There's an expunge limit, and it isn't handled in the driver itself.
1649 * OK; do multiple sessions, each fetching a limited # of messages.
1650 * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
1651 * (if it was nonzero).
1657 int expunge = NUM_VALUE_OUT(ctl->expunge);
1658 int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
1661 if (fetchlimit > 0 && (expunge == 0 || expunge > fetchlimit - totalcount))
1662 expunge = fetchlimit - totalcount;
1663 err = do_session(ctl, proto, expunge);
1664 totalcount += expunge;
1665 if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
1667 if (err != PS_LOCKBUSY)
1669 else if (lockouts >= MAX_LOCKOUTS)
1671 else /* err == PS_LOCKBUSY */
1674 * Allow time for the server lock to release. if we
1675 * don't do this, we'll often hit a locked-mailbox
1676 * condition and fail.
1682 (err == PS_MAXFETCH || err == PS_LOCKBUSY);
1689 /* driver.c ends here */