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.
20 #include <sys/socket.h>
22 #ifdef HAVE_PKG_hesiod
39 #include "fetchmail.h"
40 #include "getaddrinfo.h"
45 /* throw types for runtime errors */
46 #define THROW_TIMEOUT 1 /* server timed out */
48 /* magic values for the message length array */
49 #define MSGLEN_UNKNOWN 0 /* length unknown (0 is impossible) */
50 #define MSGLEN_INVALID -1 /* length passed back is invalid */
51 #define MSGLEN_TOOLARGE -2 /* message is too large */
52 #define MSGLEN_OLD -3 /* message is old */
54 int pass; /* how many times have we re-polled? */
55 int stage; /* where are we? */
56 int phase; /* where are we, for error-logging purposes? */
57 int batchcount; /* count of messages sent in current batch */
58 flag peek_capable; /* can we peek for better error recovery? */
59 int mailserver_socket_temp = -1; /* socket to free if connect timeout */
61 struct addrinfo *ai0, *ai1; /* clean these up after signal */
63 static volatile int timeoutcount = 0; /* count consecutive timeouts */
64 static volatile int idletimeout = 0; /* timeout occured in idle stage? */
66 static sigjmp_buf restart;
68 int is_idletimeout(void)
69 /* last timeout occured in idle stage? */
74 void resetidletimeout(void)
79 void set_timeout(int timeleft)
80 /* reset the nonresponse-timeout */
82 struct itimerval ntimeout;
87 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
88 ntimeout.it_value.tv_sec = timeleft;
89 ntimeout.it_value.tv_usec = 0;
90 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
93 static void timeout_handler (int signal)
94 /* handle SIGALRM signal indicating a server timeout */
97 if(stage != STAGE_IDLE) {
99 /* XXX FIXME: this siglongjmp must die - it's not safe to be
100 * called from a function handler and breaks, for instance,
102 siglongjmp(restart, THROW_TIMEOUT);
107 #define CLEANUP_TIMEOUT 60 /* maximum timeout during cleanup */
109 static int cleanupSockClose (int fd)
110 /* close sockets in maximum CLEANUP_TIMEOUT seconds during cleanup */
113 SIGHANDLERTYPE alrmsave;
114 alrmsave = set_signal_handler(SIGALRM, null_signal_handler);
115 set_timeout(CLEANUP_TIMEOUT);
116 scerror = SockClose(fd);
118 set_signal_handler(SIGALRM, alrmsave);
123 /** authenticate to the server host using Kerberos V5 */
124 static int kerberos5_auth(int socket /** socket to server host */, const char *canonical /** server name */)
126 krb5_error_code retval;
127 krb5_context context;
129 krb5_principal client = NULL, server = NULL;
130 krb5_error *err_ret = NULL;
132 krb5_auth_context auth_context = NULL;
134 krb5_init_context(&context);
135 krb5_auth_con_init(context, &auth_context);
137 if ((retval = krb5_cc_default(context, &ccdef))) {
138 report(stderr, "krb5_cc_default: %s\n", error_message(retval));
142 if ((retval = krb5_cc_get_principal(context, ccdef, &client))) {
143 report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval));
147 if ((retval = krb5_sname_to_principal(context, canonical, "pop",
150 report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval));
154 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
155 "KPOPV1.0", client, server,
156 AP_OPTS_MUTUAL_REQUIRED,
157 NULL, /* no data to checksum */
158 0, /* no creds, use ccache instead */
162 NULL); /* don't need reply */
164 krb5_free_principal(context, server);
165 krb5_free_principal(context, client);
166 krb5_auth_con_free(context, auth_context);
170 if (err_ret && err_ret->e_text) {
171 char *t = err_ret->e_text;
172 char *tt = sdump(t, strlen(t));
173 report(stderr, GT_("krb5_sendauth: %s [server says '%s']\n"),
174 error_message(retval), tt);
177 if (err_ret && err_ret->text.length) {
178 char *tt = sdump(err_ret->text.data, err_ret->text.length);
179 report(stderr, GT_("krb5_sendauth: %s [server says '%s']\n"),
180 error_message(retval), tt);
183 krb5_free_error(context, err_ret);
185 report(stderr, "krb5_sendauth: %s\n", error_message(retval));
191 #endif /* KERBEROS_V5 */
193 static void clean_skipped_list(struct idlist **skipped_list)
194 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
196 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
197 prev = current = head = *skipped_list;
203 /* if item has no reference, remove it */
204 if (current && current->val.status.mark == 0)
206 if (current == head) /* remove first item (head) */
208 head = current->next;
209 if (current->id) free(current->id);
211 prev = current = head;
213 else /* remove middle/last item */
217 if (current->id) free(current->id);
222 else /* skip this item */
225 current = current->next;
229 *skipped_list = head;
232 static void send_size_warnings(struct query *ctl)
233 /* send warning mail with skipped msg; reset msg count when user notified */
236 int msg_to_send = FALSE;
237 struct idlist *head=NULL, *current=NULL;
238 int max_warning_poll_count;
244 /* don't start a notification message unless we need to */
245 for (current = head; current; current = current->next)
246 if (current->val.status.num == 0 && current->val.status.mark)
252 * There's no good way to recover if we can't send notification mail,
253 * but it's not a disaster, either, since the skipped mail will not
256 if (open_warning_by_mail(ctl))
258 stuff_warning(iana_charset, ctl,
259 GT_("Subject: Fetchmail oversized-messages warning"));
260 stuff_warning(NULL, ctl, "%s", "");
262 stuff_warning(NULL, ctl,
263 GT_("The following oversized messages were deleted on server %s account %s:"),
264 ctl->server.pollname, ctl->remotename);
266 stuff_warning(NULL, ctl,
267 GT_("The following oversized messages remain on server %s account %s:"),
268 ctl->server.pollname, ctl->remotename);
270 stuff_warning(NULL, ctl, "%s", "");
272 if (run.poll_interval == 0)
273 max_warning_poll_count = 0;
275 max_warning_poll_count = ctl->warnings/run.poll_interval;
277 /* parse list of skipped msg, adding items to the mail */
278 for (current = head; current; current = current->next)
280 if (current->val.status.num == 0 && current->val.status.mark)
282 nbr = current->val.status.mark;
283 size = atoi(current->id);
285 stuff_warning(NULL, ctl,
286 ngettext(" %d message %d octets long deleted by fetchmail.",
287 " %d messages %d octets long deleted by fetchmail.", nbr),
290 stuff_warning(NULL, ctl,
291 ngettext(" %d message %d octets long skipped by fetchmail.",
292 " %d messages %d octets long skipped by fetchmail.", nbr),
295 current->val.status.num++;
296 current->val.status.mark = 0;
298 if (current->val.status.num >= max_warning_poll_count)
299 current->val.status.num = 0;
302 stuff_warning(NULL, ctl, "%s", "");
304 close_warning_by_mail(ctl, (struct msgblk *)NULL);
307 static void mark_oversized(struct query *ctl, int size)
308 /* mark a message oversized */
310 struct idlist *current=NULL, *tmp=NULL;
314 /* convert size to string */
315 snprintf(sizestr, sizeof(sizestr), "%d", size);
317 /* build a list of skipped messages
318 * val.id = size of msg (string cnvt)
319 * val.status.num = warning_poll_count
320 * val.status.mask = nbr of msg this size
323 current = ctl->skipped;
325 /* initialise warning_poll_count to the
326 * current value so that all new msg will
327 * be included in the next mail
329 cnt = current ? current->val.status.num : 0;
331 /* if entry exists, increment the count */
332 if (current && (tmp = str_in_list(¤t, sizestr, FALSE)))
334 tmp->val.status.mark++;
336 /* otherwise, create a new entry */
337 /* initialise with current poll count */
340 tmp = save_str(&ctl->skipped, sizestr, 1);
341 tmp->val.status.num = cnt;
345 static int eat_trailer(int sock, struct query *ctl)
347 /* we only need this LF if we're printing ticker dots
348 * AND we are dumping protocol traces. */
349 if (outlevel >= O_VERBOSE && want_progress()) fputc('\n', stdout);
350 return (ctl->server.base_protocol->trail)(sock, ctl, tag);
353 static int fetch_messages(int mailserver_socket, struct query *ctl,
354 int count, int **msgsizes, int maxfetch,
355 int *fetches, int *dispatches, int *deletions)
356 /* fetch messages in lockstep mode */
358 flag force_retrieval;
359 int num, firstnum = 1, lastnum = 0, err, len;
360 int fetchsizelimit = ctl->fetchsizelimit;
362 int initialfetches = *fetches;
364 if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit))
366 /* for POP3, we can get the size of one mail only! Unfortunately, this
367 * protocol specific test cannot be done elsewhere as the protocol
368 * could be "auto". */
369 switch (ctl->server.protocol)
371 case P_POP3: case P_APOP:
375 /* Time to allocate memory to store the sizes */
377 *msgsizes = (int *)xmalloc(sizeof(int) * fetchsizelimit);
381 * What forces this code is that in
382 * IMAP2bis you can't fetch a message without
383 * having it marked `seen'. In POP3 and IMAP4, on the
384 * other hand, you can (peek_capable is set by
385 * each driver module to convey this; it's not a
386 * method constant because of the difference between
387 * IMAP2bis and IMAP4, and because POP3 doesn't peek
388 * if fetchall is on).
390 * The result of being unable to peek is that if there's
391 * any kind of transient error (DNS lookup failure, or
392 * sendmail refusing delivery due to process-table limits)
393 * the message will be marked "seen" on the server without
394 * having been delivered. This is not a big problem if
395 * fetchmail is running in foreground, because the user
396 * will see a "skipped" message when it next runs and get
399 * But in daemon mode this leads to the message
400 * being silently ignored forever. This is not
403 * We compensate for this by checking the error
404 * count from the previous pass and forcing all
405 * messages to be considered new if it's nonzero.
407 force_retrieval = !peek_capable && (ctl->errcount > 0);
409 for (num = 1; num <= count; num++)
411 flag suppress_delete = FALSE;
412 flag suppress_forward = FALSE;
413 flag suppress_readbody = FALSE;
414 flag retained = FALSE;
415 int msgcode = MSGLEN_UNKNOWN;
417 /* check if the message is old
418 * Note: the size of the message may not be known here */
419 if (ctl->fetchall || force_retrieval) {
422 if (ctl->server.base_protocol->is_old && (ctl->server.base_protocol->is_old)(mailserver_socket,ctl,num)) {
423 msgcode = MSGLEN_OLD;
426 if (msgcode == MSGLEN_OLD)
428 /* To avoid flooding the syslog when using --keep,
429 * report "Skipped message" only when:
430 * 1) --verbose is on, or
431 * 2) fetchmail does not use syslog
433 if ( (outlevel >= O_VERBOSE) ||
434 (outlevel > O_SILENT && !run.use_syslog)
438 GT_("skipping message %s@%s:%d"),
439 ctl->remotename, ctl->server.truename, num);
445 if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit) &&
448 /* Instead of getting the sizes of all mails at the start, we get
449 * the sizes in blocks of fetchsizelimit. This leads to better
450 * performance when there are too many mails (say, 10000) in
451 * the mailbox and either we are not getting all the mails at
452 * one go (--fetchlimit 100) or there is a frequent socket
453 * error while just getting the sizes of all mails! */
456 int oldstage = stage;
458 lastnum = num + fetchsizelimit - 1;
461 for (i = 0; i < fetchsizelimit; i++)
464 stage = STAGE_GETSIZES;
465 err = (ctl->server.base_protocol->getpartialsizes)(mailserver_socket, num, lastnum, *msgsizes);
472 msgsize = *msgsizes ? (*msgsizes)[num-firstnum] : 0;
474 /* check if the message is oversized */
475 if (NUM_NONZERO(ctl->limit) && (msgsize > ctl->limit))
476 msgcode = MSGLEN_TOOLARGE;
477 /* else if (msgsize == 512)
478 msgcode = MSGLEN_OLD; (hmh) sample code to skip message */
482 if (msgcode == MSGLEN_TOOLARGE)
484 mark_oversized(ctl, msgsize);
485 if (!ctl->limitflush)
486 suppress_delete = TRUE;
488 if (outlevel > O_SILENT)
490 /* old messages are already handled above */
492 GT_("skipping message %s@%s:%d (%d octets)"),
493 ctl->remotename, ctl->server.truename, num,
499 * Invalid lengths are produced by Post Office/NT's
500 * annoying habit of randomly prepending bogus
501 * LIST items of length -1. Patrick Audley
502 * <paudley@pobox.com> tells us: LIST shows a
503 * size of -1, RETR and TOP return "-ERR
504 * System error - couldn't open message", and
505 * DELE succeeds but doesn't actually delete
508 report_build(stdout, GT_(" (length -1)"));
510 case MSGLEN_TOOLARGE:
511 report_build(stdout, GT_(" (oversized)"));
518 /* XXX FIXME: make this one variable, wholesize and
519 separatefetchbody query the same variable just with
521 flag wholesize = !ctl->server.base_protocol->fetch_body;
522 flag separatefetchbody = (ctl->server.base_protocol->fetch_body) ? TRUE : FALSE;
524 /* request a message */
525 err = (ctl->server.base_protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
526 if (err == PS_TRANSIENT) /* server is probably Exchange */
529 GT_("couldn't fetch headers, message %s@%s:%d (%d octets)\n"),
530 ctl->remotename, ctl->server.truename, num,
537 /* -1 means we didn't see a size in the response */
544 if (outlevel > O_SILENT)
546 report_build(stdout, GT_("reading message %s@%s:%d of %d"),
547 ctl->remotename, ctl->server.truename,
551 report_build(stdout, wholesize ? GT_(" (%d octets)")
552 : GT_(" (%d header octets)"), len);
553 if (want_progress()) {
554 /* flush and add a blank to append ticker dots */
555 report_flush(stdout);
561 * Read the message headers and ship them to the
564 err = readheaders(mailserver_socket, len, msgsize,
566 /* pass the suppress_readbody flag only if the underlying
567 * protocol does not fetch the body separately */
568 separatefetchbody ? 0 : &suppress_readbody);
570 if (err == PS_RETAINED)
571 suppress_forward = suppress_delete = retained = TRUE;
572 else if (err == PS_TRANSIENT)
573 suppress_delete = suppress_forward = TRUE;
574 else if (err == PS_REFUSED)
575 suppress_forward = TRUE;
579 /* tell server we got it OK and resynchronize */
580 if (separatefetchbody && ctl->server.base_protocol->trail)
582 err = eat_trailer(mailserver_socket, ctl);
583 if (err) return(err);
586 /* do not read the body which is not being forwarded only if
587 * the underlying protocol allows the body to be fetched
589 if (separatefetchbody && suppress_forward)
590 suppress_readbody = TRUE;
593 * If we're using IMAP4 or something else that
594 * can fetch headers separately from bodies,
595 * it's time to request the body now. This
596 * fetch may be skipped if we got an anti-spam
597 * or other PS_REFUSED error response during
600 if (!suppress_readbody)
602 if (separatefetchbody)
605 if ((err=(ctl->server.base_protocol->fetch_body)(mailserver_socket,ctl,num,&len))) {
606 if (err == PS_ERROR && ctl->server.retrieveerror) {
608 * Mark a message with a protocol error as seen.
609 * This can be used to see which messages we've attempted
610 * to download, but failed.
612 if (ctl->server.retrieveerror == RE_MARKSEEN) {
613 if ((ctl->server.base_protocol->mark_seen)(mailserver_socket,ctl,num)) {
618 if (ctl->server.retrieveerror != RE_ABORT) {
620 * Do not abort download session. Continue with the next message.
622 * Prevents a malformed message from blocking all other messages
623 * behind it in the mailbox from being downloaded.
625 * Reconnect to SMTP to force this incomplete message to be dropped.
626 * Required because we've already begun the DATA portion of the
627 * interaction with the SMTP server (commands are ignored/
628 * considered part of the message data).
630 abort_message_sink(ctl);
632 // Ensure we don't delete the failed message from the server.
633 suppress_delete = TRUE;
635 // Bookkeeping required before next message can be downloaded.
644 * Work around a bug in Novell's
645 * broken GroupWise IMAP server;
646 * its body FETCH response is missing
647 * the required length for the data
648 * string. This violates RFC2060.
651 len = msgsize - msgblk.msglen;
653 if (outlevel > O_SILENT)
655 GT_(" (%d body octets)"), len);
656 if (want_progress()) {
657 report_flush(stdout);
663 /* process the body now */
664 err = readbody(mailserver_socket,
669 if (err == PS_TRANSIENT)
670 suppress_delete = suppress_forward = TRUE;
674 /* tell server we got it OK and resynchronize */
675 if (ctl->server.base_protocol->trail) {
676 err = eat_trailer(mailserver_socket, ctl);
677 if (err) return(err);
681 /* count # messages forwarded on this pass */
682 if (!suppress_forward)
686 * Check to see if the numbers matched?
688 * Yes, some servers foo this up horribly.
689 * All IMAP servers seem to get it right, and
690 * so does Eudora QPOP at least in 2.xx
693 * Microsoft Exchange gets it completely
694 * wrong, reporting compressed rather than
695 * actual sizes (so the actual length of
696 * message is longer than the reported size).
697 * Another fine example of Microsoft brain death!
699 * Some older POP servers, like the old UCB
700 * POP server and the pre-QPOP QUALCOMM
701 * versions, report a longer size in the LIST
702 * response than actually gets shipped up.
703 * It's unclear what is going on here, as the
704 * QUALCOMM server (at least) seems to be
705 * reporting the on-disk size correctly.
707 * qmail-pop3d also goofs up message sizes and does not
708 * count the line end characters properly.
710 if (msgblk.msglen != msgsize)
712 if (outlevel >= O_DEBUG)
714 GT_("message %s@%s:%d was not the expected length (%d actual != %d expected)\n"),
715 ctl->remotename, ctl->server.truename, num,
716 msgblk.msglen, msgsize);
719 /* end-of-message processing starts here */
720 if (!close_sink(ctl, &msgblk, !suppress_forward))
723 suppress_delete = TRUE;
731 * At this point in flow of control,
732 * either we've bombed on a protocol error
733 * or had delivery refused by the SMTP server
734 * or we've seen `accepted for delivery' and the message is shipped.
735 * It's safe to mark the message seen and delete it on the server now.
738 /* in softbounce mode, suppress deletion and marking as seen */
739 if (suppress_forward)
740 suppress_delete = suppress_delete || run.softbounce;
742 /* maybe we delete this message now? */
745 if (outlevel > O_SILENT)
746 report_complete(stdout, GT_(" retained\n"));
748 else if (ctl->server.base_protocol->delete_msg
750 && ((msgcode >= 0 && !ctl->keep)
751 || (msgcode == MSGLEN_OLD && ctl->flush)
752 || (msgcode == MSGLEN_TOOLARGE && ctl->limitflush)))
755 if (outlevel > O_SILENT)
756 report_complete(stdout, GT_(" flushed\n"));
757 err = (ctl->server.base_protocol->delete_msg)(mailserver_socket, ctl, num);
763 if ( (outlevel >= O_VERBOSE) ||
764 /* To avoid flooding the syslog when using --keep,
765 * report "Skipped message" only when:
766 * 1) --verbose is on, or
767 * 2) fetchmail does not use syslog, or
768 * 3) the message was skipped for some other
769 * reason than just being old.
771 (outlevel > O_SILENT && (!run.use_syslog || msgcode != MSGLEN_OLD))
773 report_complete(stdout, GT_(" not flushed\n"));
775 /* maybe we mark this message as seen now? */
776 if (ctl->server.base_protocol->mark_seen
778 && (msgcode >= 0 && ctl->keep))
780 err = (ctl->server.base_protocol->mark_seen)(mailserver_socket, ctl, num);
786 /* perhaps this as many as we're ready to handle */
787 if (maxfetch && maxfetch <= *fetches && num < count)
789 int remcount = count - (*fetches - initialfetches);
791 ngettext("fetchlimit %d reached; %d message left on server %s account %s\n",
792 "fetchlimit %d reached; %d messages left on server %s account %s\n", remcount),
793 maxfetch, remcount, ctl->server.truename, ctl->remotename);
796 } /* for (num = 1; num <= count; num++) */
801 /* retrieve messages from server using given protocol method table */
802 static int do_session(
803 /* parsed options with merged-in defaults */
805 /* protocol method table */
806 const struct method *proto,
807 /* maximum number of messages to fetch */
810 static int *msgsizes;
811 volatile int err, mailserver_socket = -1; /* pacifies -Wall */
813 int deletions = 0, js;
815 SIGHANDLERTYPE alrmsave;
817 ctl->server.base_protocol = proto;
822 init_transact(proto);
824 /* set up the server-nonresponse timeout */
825 alrmsave = set_signal_handler(SIGALRM, timeout_handler);
826 mytimeout = ctl->server.timeout;
828 if ((js = sigsetjmp(restart,1)))
830 /* exception caught */
833 sigfillset(&allsigs);
834 sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
837 fm_freeaddrinfo(ai0); ai0 = NULL;
841 fm_freeaddrinfo(ai1); ai1 = NULL;
844 if (js == THROW_TIMEOUT)
846 if (phase == OPEN_WAIT)
848 GT_("timeout after %d seconds waiting to connect to server %s.\n"),
849 ctl->server.timeout, ctl->server.pollname);
850 else if (phase == SERVER_WAIT)
852 GT_("timeout after %d seconds waiting for server %s.\n"),
853 ctl->server.timeout, ctl->server.pollname);
854 else if (phase == FORWARDING_WAIT)
856 GT_("timeout after %d seconds waiting for %s.\n"),
858 ctl->mda ? "MDA" : "SMTP");
859 else if (phase == LISTENER_WAIT)
861 GT_("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
864 GT_("timeout after %d seconds.\n"), ctl->server.timeout);
867 * If we've exceeded our threshold for consecutive timeouts,
868 * try to notify the user, then mark the connection wedged.
869 * Don't do this if the connection can idle, though; idle
870 * timeouts just mean the frequency of mail is low.
872 if (timeoutcount > MAX_TIMEOUTS
873 && !open_warning_by_mail(ctl))
875 stuff_warning(iana_charset, ctl,
876 GT_("Subject: fetchmail sees repeated timeouts"));
877 stuff_warning(NULL, ctl, "%s", "");
878 stuff_warning(NULL, ctl,
879 GT_("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\n"),
881 ctl->remotename, ctl->server.truename);
882 stuff_warning(NULL, ctl,
883 GT_("This could mean that your mailserver is stuck, or that your SMTP\n" \
884 "server is wedged, or that your mailbox file on the server has been\n" \
885 "corrupted by a server error. You can run `fetchmail -v -v' to\n" \
886 "diagnose the problem.\n\n" \
887 "Fetchmail won't poll this mailbox again until you restart it.\n"));
888 close_warning_by_mail(ctl, (struct msgblk *)NULL);
898 /* sigsetjmp returned zero -> normal operation */
899 char buf[MSGBUFSIZE+1], *realhost;
900 int count, newm, bytes;
901 int fetches, dispatches, oldphase;
904 /* execute pre-initialization command, if any */
905 if (ctl->preconnect && (err = system(ctl->preconnect)))
907 if (WIFSIGNALED(err))
909 GT_("pre-connection command terminated with signal %d\n"), WTERMSIG(err));
912 GT_("pre-connection command failed with status %d\n"), WEXITSTATUS(err));
917 /* open a socket to the mail server */
920 set_timeout(mytimeout);
922 #ifdef HAVE_PKG_hesiod
923 /* If either the pollname or vianame are "hesiod" we want to
924 lookup the user's hesiod pobox host */
925 if (!strcasecmp(ctl->server.queryname, "hesiod")) {
926 struct hes_postoffice *hes_p;
927 hes_p = hes_getmailhost(ctl->remotename);
928 if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
929 free(ctl->server.queryname);
930 ctl->server.queryname = xstrdup(hes_p->po_host);
932 free(ctl->server.via);
933 ctl->server.via = xstrdup(hes_p->po_host);
936 GT_("couldn't find HESIOD pobox for %s\n"),
943 * Canonicalize the server truename for later use. This also
944 * functions as a probe for whether the mailserver is accessible.
945 * We try it on each poll cycle until we get a result. This way,
946 * fetchmail won't fail if started up when the network is inaccessible.
948 if (ctl->server.dns && !ctl->server.trueaddr)
950 if (ctl->server.lead_server)
952 char *leadname = ctl->server.lead_server->truename;
954 /* prevent core dump from ill-formed or duplicate entry */
957 report(stderr, GT_("Lead server has no name.\n"));
964 xfree(ctl->server.truename);
965 ctl->server.truename = xstrdup(leadname);
969 struct addrinfo hints, *res;
972 memset(&hints, 0, sizeof(hints));
973 hints.ai_socktype = SOCK_STREAM;
974 hints.ai_family = AF_UNSPEC;
975 hints.ai_flags = AI_CANONNAME;
977 hints.ai_flags |= AI_ADDRCONFIG;
980 error = fm_getaddrinfo(ctl->server.queryname, NULL, &hints, &res);
984 GT_("couldn't find canonical DNS name of %s (%s): %s\n"),
985 ctl->server.pollname, ctl->server.queryname,
986 gai_strerror(error));
994 xfree(ctl->server.truename);
995 /* Older FreeBSD versions return NULL in ai_canonname
996 * if they cannot canonicalize, rather than copying
997 * the queryname here, as IEEE Std 1003.1-2001
998 * requires. Work around NULL. */
999 if (res->ai_canonname != NULL) {
1000 ctl->server.truename = xstrdup(res->ai_canonname);
1002 ctl->server.truename = xstrdup(ctl->server.queryname);
1004 ctl->server.trueaddr = (struct sockaddr *)xmalloc(res->ai_addrlen);
1005 ctl->server.trueaddr_len = res->ai_addrlen;
1006 memcpy(ctl->server.trueaddr, res->ai_addr, res->ai_addrlen);
1007 fm_freeaddrinfo(res);
1012 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1014 /* allow time for the port to be set up if we have a plugin */
1015 if (ctl->server.plugin)
1017 if ((mailserver_socket = SockOpen(realhost,
1018 ctl->server.service ? ctl->server.service : ( ctl->use_ssl ? ctl->server.base_protocol->sslservice : ctl->server.base_protocol->service ),
1019 ctl->server.plugin, &ai0)) == -1)
1021 char errbuf[BUFSIZ];
1024 * Avoid generating a bogus error every poll cycle when we're
1025 * in daemon mode but the connection to the outside world
1028 if (!((err_no == EHOSTUNREACH || err_no == ENETUNREACH)
1029 && run.poll_interval))
1031 report_build(stderr, GT_("%s connection to %s failed"),
1032 ctl->server.base_protocol->name, ctl->server.pollname);
1033 strlcpy(errbuf, strerror(err_no), sizeof(errbuf));
1034 report_complete(stderr, ": %s\n", errbuf);
1043 /* Save the socket opened. Useful if Fetchmail hangs on SSLOpen
1044 * because the socket can be closed.
1046 mailserver_socket_temp = mailserver_socket;
1047 set_timeout(mytimeout);
1049 /* perform initial SSL handshake on open connection */
1051 SSLOpen(mailserver_socket, ctl->sslcert, ctl->sslkey,
1052 ctl->sslproto, ctl->sslcertck,
1053 ctl->sslcertfile, ctl->sslcertpath,
1054 ctl->sslfingerprint, ctl->sslcommonname ?
1055 ctl->sslcommonname : realhost, ctl->server.pollname,
1056 &ctl->remotename) == -1)
1058 report(stderr, GT_("SSL connection failed.\n"));
1063 /* Fetchmail didn't hang on SSLOpen,
1064 * then no need to set mailserver_socket_temp
1066 mailserver_socket_temp = -1;
1069 /* A timeout is still defined before SSLOpen,
1070 * then Fetchmail hanging on SSLOpen is handled.
1076 if (ctl->server.authenticate == A_KERBEROS_V5)
1078 set_timeout(mytimeout);
1079 err = kerberos5_auth(mailserver_socket, ctl->server.truename);
1084 #endif /* KERBEROS_V5 */
1086 /* accept greeting message from mail server */
1087 err = (ctl->server.base_protocol->parse_response)(mailserver_socket, buf);
1091 /* try to get authorized to fetch mail */
1092 stage = STAGE_GETAUTH;
1093 if (ctl->server.base_protocol->getauth)
1095 set_timeout(mytimeout);
1096 err = (ctl->server.base_protocol->getauth)(mailserver_socket, ctl, buf);
1101 if (err == PS_LOCKBUSY)
1102 report(stderr, GT_("Lock-busy error on %s@%s\n"),
1104 ctl->server.truename);
1105 else if (err == PS_SERVBUSY)
1106 report(stderr, GT_("Server busy error on %s@%s\n"),
1108 ctl->server.truename);
1109 else if (err == PS_AUTHFAIL)
1111 report(stderr, GT_("Authorization failure on %s@%s%s\n"),
1113 ctl->server.truename,
1114 (ctl->wehaveauthed ? GT_(" (previously authorized)") : "")
1116 if (ctl->server.authenticate == A_ANY && !ctl->wehaveauthed) {
1117 report(stderr, GT_("For help, see http://www.fetchmail.info/fetchmail-FAQ.html#R15\n"));
1121 * If we're running in background, try to mail the
1122 * calling user a heads-up about the authentication
1123 * failure once it looks like this isn't a fluke
1124 * due to the server being temporarily inaccessible.
1125 * When we get third succesive failure, we notify the user
1126 * but only if we haven't already managed to get
1127 * authorization. After that, once we get authorization
1128 * we let the user know service is restored.
1130 if (run.poll_interval
1131 && !ctl->wehavesentauthnote
1132 && ((ctl->wehaveauthed && ++ctl->authfailcount >= 10)
1133 || (!ctl->wehaveauthed && ++ctl->authfailcount >= 3))
1134 && !open_warning_by_mail(ctl))
1136 ctl->wehavesentauthnote = 1;
1137 stuff_warning(iana_charset, ctl,
1138 GT_("Subject: fetchmail authentication failed on %s@%s"),
1139 ctl->remotename, ctl->server.truename);
1140 stuff_warning(NULL, ctl, "%s", "");
1141 stuff_warning(NULL, ctl,
1142 GT_("Fetchmail could not get mail from %s@%s.\n"),
1144 ctl->server.truename);
1145 if (ctl->wehaveauthed) {
1146 stuff_warning(NULL, ctl, GT_("\
1147 The attempt to get authorization failed.\n\
1148 Since we have already succeeded in getting authorization for this\n\
1149 connection, this is probably another failure mode (such as busy server)\n\
1150 that fetchmail cannot distinguish because the server didn't send a useful\n\
1152 stuff_warning(NULL, ctl, GT_("\
1154 However, if you HAVE changed your account details since starting the\n\
1155 fetchmail daemon, you need to stop the daemon, change your configuration\n\
1156 of fetchmail, and then restart the daemon.\n\
1158 The fetchmail daemon will continue running and attempt to connect\n\
1159 at each cycle. No future notifications will be sent until service\n\
1162 stuff_warning(NULL, ctl, GT_("\
1163 The attempt to get authorization failed.\n\
1164 This probably means your password is invalid, but some servers have\n\
1165 other failure modes that fetchmail cannot distinguish from this\n\
1166 because they don't send useful error messages on login failure.\n\
1168 The fetchmail daemon will continue running and attempt to connect\n\
1169 at each cycle. No future notifications will be sent until service\n\
1172 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1175 else if (err == PS_REPOLL)
1177 if (outlevel >= O_VERBOSE)
1178 report(stderr, GT_("Repoll immediately on %s@%s\n"),
1180 ctl->server.truename);
1183 report(stderr, GT_("Unknown login or authentication error on %s@%s\n"),
1185 ctl->server.truename);
1192 * This connection has given us authorization at least once.
1194 * There are dodgy server (clubinternet.fr for example) that
1195 * give spurious authorization failures on patently good
1196 * account/password details, then 5 minutes later let you in!
1198 * This is meant to build in some tolerance of such nasty bits
1201 ctl->wehaveauthed = 1;
1202 /*if (ctl->authfailcount >= 3)*/
1203 if (ctl->wehavesentauthnote)
1205 ctl->wehavesentauthnote = 0;
1207 GT_("Authorization OK on %s@%s\n"),
1209 ctl->server.truename);
1210 if (!open_warning_by_mail(ctl))
1212 stuff_warning(iana_charset, ctl,
1213 GT_("Subject: fetchmail authentication OK on %s@%s"),
1214 ctl->remotename, ctl->server.truename);
1215 stuff_warning(NULL, ctl, "%s", "");
1216 stuff_warning(NULL, ctl,
1217 GT_("Fetchmail was able to log into %s@%s.\n"),
1219 ctl->server.truename);
1220 stuff_warning(NULL, ctl,
1221 GT_("Service has been restored.\n"));
1222 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1227 * Reporting only after the first three
1228 * consecutive failures, or ten consecutive
1229 * failures after we have managed to get
1232 ctl->authfailcount = 0;
1236 ctl->errcount = fetches = 0;
1238 /* now iterate over each folder selected */
1239 for (idp = ctl->mailboxes; idp; idp = idp->next)
1241 ctl->folder = idp->id;
1247 /* reset timeout, in case we did an IDLE */
1248 mytimeout = ctl->server.timeout;
1250 if (outlevel >= O_DEBUG)
1253 report(stdout, GT_("selecting or re-polling folder %s\n"), idp->id);
1255 report(stdout, GT_("selecting or re-polling default folder\n"));
1258 /* compute # of messages and number of new messages waiting */
1259 stage = STAGE_GETRANGE;
1260 err = (ctl->server.base_protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &newm, &bytes);
1264 /* show user how many messages we downloaded */
1266 (void) snprintf(buf, sizeof(buf),
1267 GT_("%s at %s (folder %s)"),
1268 ctl->remotename, ctl->server.pollname, idp->id);
1270 (void) snprintf(buf, sizeof(buf), GT_("%s at %s"),
1271 ctl->remotename, ctl->server.pollname);
1272 if (outlevel > O_SILENT)
1274 if (count == -1) /* only used for ETRN */
1275 report(stdout, GT_("Polling %s\n"), ctl->server.truename);
1276 else if (count != 0)
1278 if (newm != -1 && (count - newm) > 0)
1279 report_build(stdout, ngettext("%d message (%d %s) for %s", "%d messages (%d %s) for %s", (unsigned long)count),
1282 ngettext("seen", "seen", (unsigned long)count-newm),
1285 report_build(stdout, ngettext("%d message for %s",
1286 "%d messages for %s",
1290 report_complete(stdout, ".\n");
1292 report_complete(stdout, GT_(" (%d octets).\n"), bytes);
1296 /* these are pointless in normal daemon mode */
1297 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1298 report(stdout, GT_("No mail for %s\n"), buf);
1302 /* very important, this is where we leave the do loop */
1308 if (newm == -1 || ctl->fetchall)
1310 fetches = newm; /* set error status correctly */
1312 * There used to be a `goto noerror' here, but this
1313 * prevented checking of multiple folders. This
1314 * comment is a reminder in case I introduced some
1315 * subtle bug by removing it...
1323 * Don't trust the message count passed by the server.
1324 * Without this check, it might be possible to do a
1325 * DNS-spoofing attack that would pass back a ridiculous
1326 * count, and allocate a malloc area that would overlap
1327 * a portion of the stack.
1329 if ((unsigned)count > INT_MAX/sizeof(int))
1331 report(stderr, GT_("bogus message count!"));
1337 * We need the size of each message before it's
1338 * loaded in order to pass it to the ESMTP SIZE
1339 * option. If the protocol has a getsizes method,
1340 * we presume this means it doesn't get reliable
1341 * sizes from message fetch responses.
1343 * If the protocol supports getting sizes of subset of
1344 * messages, we skip this step now.
1346 if (proto->getsizes &&
1347 !(proto->getpartialsizes && NUM_NONZERO(ctl->fetchsizelimit)))
1350 msgsizes = (int *)xmalloc(sizeof(int) * count);
1351 for (i = 0; i < count; i++)
1354 stage = STAGE_GETSIZES;
1355 err = (proto->getsizes)(mailserver_socket, count, msgsizes);
1362 for (i = 0; i < count; i++)
1363 bytes += msgsizes[i];
1367 /* read, forward, and delete messages */
1368 stage = STAGE_FETCH;
1370 /* fetch in lockstep mode */
1371 err = fetch_messages(mailserver_socket, ctl,
1374 &fetches, &dispatches, &deletions);
1375 if (err != PS_SUCCESS && err != PS_MAXFETCH)
1378 if (!check_only && ctl->skipped
1379 && run.poll_interval > 0 && !nodetach)
1381 clean_skipped_list(&ctl->skipped);
1382 send_size_warnings(ctl);
1386 /* end-of-mailbox processing before we repoll or switch to another one */
1387 if (ctl->server.base_protocol->end_mailbox_poll)
1389 tmperr = (ctl->server.base_protocol->end_mailbox_poll)(mailserver_socket, ctl);
1395 /* Return now if we have reached the fetchlimit */
1396 if (maxfetch && maxfetch <= fetches)
1400 * Only repoll if we either had some actual forwards
1401 * or are idling for new mails and had no errors.
1402 * Otherwise it is far too easy to get into infinite loops.
1404 (ctl->server.base_protocol->retry && (dispatches || ctl->idle) && !ctl->errcount);
1407 /* XXX: From this point onwards, preserve err unless a new error has occurred */
1410 /* PS_SUCCESS, PS_MAXFETCH: ordinary termination with no errors -- officially log out */
1411 stage = STAGE_LOGOUT;
1412 tmperr = (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1413 if (tmperr != PS_SUCCESS)
1416 * Hmmmm...arguably this would be incorrect if we had fetches but
1417 * no dispatches (due to oversized messages, etc.)
1419 else if (err == PS_SUCCESS && fetches == 0)
1422 * Close all SMTP delivery sockets. For optimum performance
1423 * we'd like to hold them open til end of run, but (1) this
1424 * loses if our poll interval is longer than the MTA's
1425 * inactivity timeout, and (2) some MTAs (like smail) don't
1426 * deliver after each message, but rather queue up mail and
1427 * wait to actually deliver it until the input socket is
1430 * don't send QUIT for ODMR case because we're acting as a
1431 * proxy between the SMTP server and client.
1433 smtp_close(ctl, ctl->server.protocol != P_ODMR);
1434 cleanupSockClose(mailserver_socket);
1438 /* we only get here on error */
1439 if (err != 0 && err != PS_SOCKET && err != PS_REPOLL)
1441 stage = STAGE_LOGOUT;
1442 (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1445 /* try to clean up all streams */
1448 * Sending SMTP QUIT on signal is theoretically nice, but led
1449 * to a subtle bug. If fetchmail was terminated by signal
1450 * while it was shipping message text, it would hang forever
1451 * waiting for a command acknowledge. In theory we could
1452 * enable the QUIT only outside of the message send. In
1453 * practice, we don't care. All mailservers hang up on a
1454 * dropped TCP/IP connection anyway.
1457 if (mailserver_socket != -1) {
1458 cleanupSockClose(mailserver_socket);
1460 /* If there was a connect timeout, the socket should be closed.
1461 * mailserver_socket_temp contains the socket to close.
1463 if (mailserver_socket_temp != -1) {
1464 cleanupSockClose(mailserver_socket_temp);
1465 mailserver_socket_temp = -1;
1469 /* no report on PS_AUTHFAIL */
1474 msg = GT_("socket");
1477 msg = GT_("missing or bad RFC822 header");
1483 msg = GT_("client/server synchronization");
1486 msg = GT_("client/server protocol");
1489 msg = GT_("lock busy on server");
1492 msg = GT_("SMTP transaction");
1495 msg = GT_("DNS lookup");
1498 msg = GT_("undefined");
1502 if (phase == FORWARDING_WAIT || phase == LISTENER_WAIT
1504 report(stderr, GT_("%s error while fetching from %s@%s and delivering to SMTP host %s\n"),
1505 msg, ctl->remotename, ctl->server.pollname,
1506 ctl->smtphost ? ctl->smtphost : GT_("unknown"));
1508 report(stderr, GT_("%s error while fetching from %s@%s\n"),
1509 msg, ctl->remotename, ctl->server.pollname);
1516 /* execute wrapup command, if any */
1517 if (ctl->postconnect && (tmperr = system(ctl->postconnect)))
1519 if (WIFSIGNALED(tmperr))
1520 report(stderr, GT_("post-connection command terminated with signal %d\n"), WTERMSIG(tmperr));
1522 report(stderr, GT_("post-connection command failed with status %d\n"), WEXITSTATUS(tmperr));
1523 if (err == PS_SUCCESS)
1527 set_timeout(0); /* cancel any pending alarm */
1528 set_signal_handler(SIGALRM, alrmsave);
1532 /** retrieve messages from server using given protocol method table */
1533 int do_protocol(struct query *ctl /** parsed options with merged-in defaults */,
1534 const struct method *proto /** protocol method table */)
1539 if (ctl->server.authenticate == A_KERBEROS_V5)
1541 report(stderr, GT_("Kerberos V5 support not linked.\n"));
1544 #endif /* KERBEROS_V5 */
1546 /* lacking methods, there are some options that may fail */
1549 /* check for unsupported options */
1552 GT_("Option --flush is not supported with %s\n"),
1556 else if (ctl->fetchall) {
1558 GT_("Option --all is not supported with %s\n"),
1563 if (!(proto->getsizes || proto->getpartialsizes)
1564 && NUM_SPECIFIED(ctl->limit))
1567 GT_("Option --limit is not supported with %s\n"),
1573 * If no expunge limit or we do expunges within the driver,
1574 * then just do one session, passing in any fetchlimit.
1576 if ((ctl->keep && !ctl->flush) ||
1577 proto->retry || !NUM_SPECIFIED(ctl->expunge))
1578 return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
1580 * There's an expunge limit, and it isn't handled in the driver itself.
1581 * OK; do multiple sessions, each fetching a limited # of messages.
1582 * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
1583 * (if it was nonzero).
1589 int expunge = NUM_VALUE_OUT(ctl->expunge);
1590 int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
1593 if (fetchlimit > 0 && (expunge == 0 || expunge > fetchlimit - totalcount))
1594 expunge = fetchlimit - totalcount;
1595 err = do_session(ctl, proto, expunge);
1596 totalcount += expunge;
1597 if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
1599 if (err != PS_LOCKBUSY)
1601 else if (lockouts >= MAX_LOCKOUTS)
1603 else /* err == PS_LOCKBUSY */
1606 * Allow time for the server lock to release. if we
1607 * don't do this, we'll often hit a locked-mailbox
1608 * condition and fail.
1614 (err == PS_MAXFETCH || err == PS_LOCKBUSY);
1621 /* driver.c ends here */