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 GT_(" %d msg %d octets long deleted by fetchmail."),
365 stuff_warning(NULL, ctl,
366 GT_(" %d msg %d octets long skipped by fetchmail."),
369 current->val.status.num++;
370 current->val.status.mark = 0;
372 if (current->val.status.num >= max_warning_poll_count)
373 current->val.status.num = 0;
376 stuff_warning(NULL, ctl, "%s", "");
378 close_warning_by_mail(ctl, (struct msgblk *)NULL);
381 static void mark_oversized(struct query *ctl, int size)
382 /* mark a message oversized */
384 struct idlist *current=NULL, *tmp=NULL;
388 /* convert size to string */
389 snprintf(sizestr, sizeof(sizestr), "%d", size);
391 /* build a list of skipped messages
392 * val.id = size of msg (string cnvt)
393 * val.status.num = warning_poll_count
394 * val.status.mask = nbr of msg this size
397 current = ctl->skipped;
399 /* initialise warning_poll_count to the
400 * current value so that all new msg will
401 * be included in the next mail
403 cnt = current ? current->val.status.num : 0;
405 /* if entry exists, increment the count */
406 if (current && (tmp = str_in_list(¤t, sizestr, FALSE)))
408 tmp->val.status.mark++;
410 /* otherwise, create a new entry */
411 /* initialise with current poll count */
414 tmp = save_str(&ctl->skipped, sizestr, 1);
415 tmp->val.status.num = cnt;
419 static int fetch_messages(int mailserver_socket, struct query *ctl,
420 int count, int **msgsizes, int maxfetch,
421 int *fetches, int *dispatches, int *deletions)
422 /* fetch messages in lockstep mode */
424 flag force_retrieval;
425 int num, firstnum = 1, lastnum = 0, err, len;
426 int fetchsizelimit = ctl->fetchsizelimit;
428 int initialfetches = *fetches;
430 if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit))
432 /* for POP3, we can get the size of one mail only! Unfortunately, this
433 * protocol specific test cannot be done elsewhere as the protocol
434 * could be "auto". */
435 switch (ctl->server.protocol)
437 case P_POP3: case P_APOP: case P_RPOP:
441 /* Time to allocate memory to store the sizes */
443 *msgsizes = (int *)xmalloc(sizeof(int) * fetchsizelimit);
447 * What forces this code is that in POP2 and
448 * IMAP2bis you can't fetch a message without
449 * having it marked `seen'. In POP3 and IMAP4, on the
450 * other hand, you can (peek_capable is set by
451 * each driver module to convey this; it's not a
452 * method constant because of the difference between
453 * IMAP2bis and IMAP4, and because POP3 doesn't peek
454 * if fetchall is on).
456 * The result of being unable to peek is that if there's
457 * any kind of transient error (DNS lookup failure, or
458 * sendmail refusing delivery due to process-table limits)
459 * the message will be marked "seen" on the server without
460 * having been delivered. This is not a big problem if
461 * fetchmail is running in foreground, because the user
462 * will see a "skipped" message when it next runs and get
465 * But in daemon mode this leads to the message
466 * being silently ignored forever. This is not
469 * We compensate for this by checking the error
470 * count from the previous pass and forcing all
471 * messages to be considered new if it's nonzero.
473 force_retrieval = !peek_capable && (ctl->errcount > 0);
475 for (num = 1; num <= count; num++)
477 flag suppress_delete = FALSE;
478 flag suppress_forward = FALSE;
479 flag suppress_readbody = FALSE;
480 flag retained = FALSE;
481 int msgcode = MSGLEN_UNKNOWN;
483 /* check if the message is old
484 * Note: the size of the message may not be known here */
485 if (ctl->fetchall || force_retrieval)
487 else if (ctl->server.base_protocol->is_old && (ctl->server.base_protocol->is_old)(mailserver_socket,ctl,num))
488 msgcode = MSGLEN_OLD;
489 if (msgcode == MSGLEN_OLD)
491 /* To avoid flooding the syslog when using --keep,
492 * report "Skipped message" only when:
493 * 1) --verbose is on, or
494 * 2) fetchmail does not use syslog
496 if ( (outlevel >= O_VERBOSE) ||
497 (outlevel > O_SILENT && !run.use_syslog)
501 GT_("skipping message %s@%s:%d"),
502 ctl->remotename, ctl->server.truename, num);
508 if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit) &&
511 /* Instead of getting the sizes of all mails at the start, we get
512 * the sizes in blocks of fetchsizelimit. This leads to better
513 * performance when there are too many mails (say, 10000) in
514 * the mailbox and either we are not getting all the mails at
515 * one go (--fetchlimit 100) or there is a frequent socket
516 * error while just getting the sizes of all mails! */
519 int oldstage = stage;
521 lastnum = num + fetchsizelimit - 1;
524 for (i = 0; i < fetchsizelimit; i++)
527 stage = STAGE_GETSIZES;
528 err = (ctl->server.base_protocol->getpartialsizes)(mailserver_socket, num, lastnum, *msgsizes);
535 msgsize = *msgsizes ? (*msgsizes)[num-firstnum] : 0;
537 /* check if the message is oversized */
538 if (NUM_NONZERO(ctl->limit) && (msgsize > ctl->limit))
539 msgcode = MSGLEN_TOOLARGE;
540 /* else if (msgsize == 512)
541 msgcode = MSGLEN_OLD; (hmh) sample code to skip message */
545 if (msgcode == MSGLEN_TOOLARGE)
547 mark_oversized(ctl, msgsize);
548 if (!ctl->limitflush)
549 suppress_delete = TRUE;
551 if (outlevel > O_SILENT)
553 /* old messages are already handled above */
555 GT_("skipping message %s@%s:%d (%d octets)"),
556 ctl->remotename, ctl->server.truename, num,
562 * Invalid lengths are produced by Post Office/NT's
563 * annoying habit of randomly prepending bogus
564 * LIST items of length -1. Patrick Audley
565 * <paudley@pobox.com> tells us: LIST shows a
566 * size of -1, RETR and TOP return "-ERR
567 * System error - couldn't open message", and
568 * DELE succeeds but doesn't actually delete
571 report_build(stdout, GT_(" (length -1)"));
573 case MSGLEN_TOOLARGE:
574 report_build(stdout, GT_(" (oversized)"));
581 flag wholesize = !ctl->server.base_protocol->fetch_body;
582 flag separatefetchbody = (ctl->server.base_protocol->fetch_body) ? TRUE : FALSE;
584 /* request a message */
585 err = (ctl->server.base_protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
586 if (err == PS_TRANSIENT) /* server is probably Exchange */
589 GT_("couldn't fetch headers, message %s@%s:%d (%d octets)\n"),
590 ctl->remotename, ctl->server.truename, num,
597 /* -1 means we didn't see a size in the response */
604 if (outlevel > O_SILENT)
606 report_build(stdout, GT_("reading message %s@%s:%d of %d"),
607 ctl->remotename, ctl->server.truename,
611 report_build(stdout, wholesize ? GT_(" (%d octets)")
612 : GT_(" (%d header octets)"), len);
613 if (outlevel >= O_VERBOSE)
614 report_complete(stdout, "\n");
618 * Read the message headers and ship them to the
621 err = readheaders(mailserver_socket, len, msgsize,
623 /* pass the suppress_readbody flag only if the underlying
624 * protocol does not fetch the body separately */
625 separatefetchbody ? 0 : &suppress_readbody);
626 if (err == PS_RETAINED)
627 suppress_forward = suppress_delete = retained = TRUE;
628 else if (err == PS_TRANSIENT)
629 suppress_delete = suppress_forward = TRUE;
630 else if (err == PS_REFUSED)
631 suppress_forward = TRUE;
632 else if (err == PS_TRUNCATED)
633 suppress_readbody = TRUE;
637 /* tell server we got it OK and resynchronize */
638 if (separatefetchbody && ctl->server.base_protocol->trail)
640 if (outlevel >= O_VERBOSE && !is_a_file(1) && !run.use_syslog)
646 if ((err = (ctl->server.base_protocol->trail)(mailserver_socket, ctl, tag)))
650 /* do not read the body which is not being forwarded only if
651 * the underlying protocol allows the body to be fetched
653 if (separatefetchbody && suppress_forward)
654 suppress_readbody = TRUE;
657 * If we're using IMAP4 or something else that
658 * can fetch headers separately from bodies,
659 * it's time to request the body now. This
660 * fetch may be skipped if we got an anti-spam
661 * or other PS_REFUSED error response during
664 if (!suppress_readbody)
666 if (separatefetchbody)
669 if ((err=(ctl->server.base_protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
672 * Work around a bug in Novell's
673 * broken GroupWise IMAP server;
674 * its body FETCH response is missing
675 * the required length for the data
676 * string. This violates RFC2060.
679 len = msgsize - msgblk.msglen;
680 if (outlevel > O_SILENT && !wholesize)
682 GT_(" (%d body octets)"), len);
685 /* process the body now */
686 err = readbody(mailserver_socket,
690 if (err == PS_TRANSIENT)
691 suppress_delete = suppress_forward = TRUE;
695 /* tell server we got it OK and resynchronize */
696 if (ctl->server.base_protocol->trail)
698 if (outlevel >= O_VERBOSE && !is_a_file(1) && !run.use_syslog)
704 err = (ctl->server.base_protocol->trail)(mailserver_socket, ctl, tag);
710 /* count # messages forwarded on this pass */
711 if (!suppress_forward)
715 * Check to see if the numbers matched?
717 * Yes, some servers foo this up horribly.
718 * All IMAP servers seem to get it right, and
719 * so does Eudora QPOP at least in 2.xx
722 * Microsoft Exchange gets it completely
723 * wrong, reporting compressed rather than
724 * actual sizes (so the actual length of
725 * message is longer than the reported size).
726 * Another fine example of Microsoft brain death!
728 * Some older POP servers, like the old UCB
729 * POP server and the pre-QPOP QUALCOMM
730 * versions, report a longer size in the LIST
731 * response than actually gets shipped up.
732 * It's unclear what is going on here, as the
733 * QUALCOMM server (at least) seems to be
734 * reporting the on-disk size correctly.
736 * qmail-pop3d also goofs up message sizes and does not
737 * count the line end characters properly.
739 if (msgblk.msglen != msgsize)
741 if (outlevel >= O_DEBUG)
743 GT_("message %s@%s:%d was not the expected length (%d actual != %d expected)\n"),
744 ctl->remotename, ctl->server.truename, num,
745 msgblk.msglen, msgsize);
748 /* end-of-message processing starts here */
749 if (!close_sink(ctl, &msgblk, !suppress_forward))
752 suppress_delete = TRUE;
760 * At this point in flow of control, either
761 * we've bombed on a protocol error or had
762 * delivery refused by the SMTP server
763 * (unlikely -- I've never seen it) or we've
764 * seen `accepted for delivery' and the
765 * message is shipped. It's safe to mark the
766 * message seen and delete it on the server
770 /* maybe we delete this message now? */
773 if (outlevel > O_SILENT)
774 report_complete(stdout, GT_(" retained\n"));
776 else if (ctl->server.base_protocol->delete_msg
778 && ((msgcode >= 0 && !ctl->keep)
779 || (msgcode == MSGLEN_OLD && ctl->flush)
780 || (msgcode == MSGLEN_TOOLARGE && ctl->limitflush)))
783 if (outlevel > O_SILENT)
784 report_complete(stdout, GT_(" flushed\n"));
785 err = (ctl->server.base_protocol->delete_msg)(mailserver_socket, ctl, num);
791 if ( (outlevel >= O_VERBOSE) ||
792 /* To avoid flooding the syslog when using --keep,
793 * report "Skipped message" only when:
794 * 1) --verbose is on, or
795 * 2) fetchmail does not use syslog, or
796 * 3) the message was skipped for some other
797 * reason than just being old.
799 (outlevel > O_SILENT && (!run.use_syslog || msgcode != MSGLEN_OLD))
801 report_complete(stdout, GT_(" not flushed\n"));
803 /* maybe we mark this message as seen now? */
804 if (ctl->server.base_protocol->mark_seen
806 && (msgcode >= 0 && ctl->keep))
808 err = (ctl->server.base_protocol->mark_seen)(mailserver_socket, ctl, num);
814 /* perhaps this as many as we're ready to handle */
815 if (maxfetch && maxfetch <= *fetches && num < count)
817 int remcount = count - (*fetches - initialfetches);
819 ngettext("fetchlimit %d reached; %d message left on server %s account %s\n",
820 "fetchlimit %d reached; %d messages left on server %s account %s\n", remcount),
821 maxfetch, remcount, ctl->server.truename, ctl->remotename);
824 } /* for (num = 1; num <= count; num++) */
829 /* retrieve messages from server using given protocol method table */
830 static int do_session(
831 /* parsed options with merged-in defaults */
833 /* protocol method table */
834 const struct method *proto,
835 /* maximum number of messages to fetch */
838 static int *msgsizes;
839 volatile int err, mailserver_socket = -1; /* pacifies -Wall */
841 int deletions = 0, js;
843 SIGHANDLERTYPE alrmsave;
845 ctl->server.base_protocol = proto;
850 init_transact(proto);
852 /* set up the server-nonresponse timeout */
853 alrmsave = set_signal_handler(SIGALRM, timeout_handler);
854 mytimeout = ctl->server.timeout;
856 if ((js = sigsetjmp(restart,1)))
858 /* exception caught */
861 sigfillset(&allsigs);
862 sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
865 freeaddrinfo(ai0); ai0 = NULL;
869 freeaddrinfo(ai1); ai1 = NULL;
872 if (js == THROW_TIMEOUT)
874 if (phase == OPEN_WAIT)
876 GT_("timeout after %d seconds waiting to connect to server %s.\n"),
877 ctl->server.timeout, ctl->server.pollname);
878 else if (phase == SERVER_WAIT)
880 GT_("timeout after %d seconds waiting for server %s.\n"),
881 ctl->server.timeout, ctl->server.pollname);
882 else if (phase == FORWARDING_WAIT)
884 GT_("timeout after %d seconds waiting for %s.\n"),
886 ctl->mda ? "MDA" : "SMTP");
887 else if (phase == LISTENER_WAIT)
889 GT_("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
892 GT_("timeout after %d seconds.\n"), ctl->server.timeout);
895 * If we've exceeded our threshold for consecutive timeouts,
896 * try to notify the user, then mark the connection wedged.
897 * Don't do this if the connection can idle, though; idle
898 * timeouts just mean the frequency of mail is low.
900 if (timeoutcount > MAX_TIMEOUTS
901 && !open_warning_by_mail(ctl))
903 stuff_warning(iana_charset, ctl,
904 GT_("Subject: fetchmail sees repeated timeouts"));
905 stuff_warning(NULL, ctl, "%s", "");
906 stuff_warning(NULL, ctl,
907 GT_("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\n"),
909 ctl->remotename, ctl->server.truename);
910 stuff_warning(NULL, ctl,
911 GT_("This could mean that your mailserver is stuck, or that your SMTP\n" \
912 "server is wedged, or that your mailbox file on the server has been\n" \
913 "corrupted by a server error. You can run `fetchmail -v -v' to\n" \
914 "diagnose the problem.\n\n" \
915 "Fetchmail won't poll this mailbox again until you restart it.\n"));
916 close_warning_by_mail(ctl, (struct msgblk *)NULL);
926 /* sigsetjmp returned zero -> normal operation */
927 char buf[MSGBUFSIZE+1], *realhost;
928 int count, newm, bytes;
929 int fetches, dispatches, oldphase;
932 /* execute pre-initialization command, if any */
933 if (ctl->preconnect && (err = system(ctl->preconnect)))
936 GT_("pre-connection command failed with status %d\n"), err);
941 /* open a socket to the mail server */
944 set_timeout(mytimeout);
946 #ifdef HAVE_PKG_hesiod
947 /* If either the pollname or vianame are "hesiod" we want to
948 lookup the user's hesiod pobox host */
949 if (!strcasecmp(ctl->server.queryname, "hesiod")) {
950 struct hes_postoffice *hes_p;
951 hes_p = hes_getmailhost(ctl->remotename);
952 if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
953 free(ctl->server.queryname);
954 ctl->server.queryname = xstrdup(hes_p->po_host);
956 free(ctl->server.via);
957 ctl->server.via = xstrdup(hes_p->po_host);
960 GT_("couldn't find HESIOD pobox for %s\n"),
967 * Canonicalize the server truename for later use. This also
968 * functions as a probe for whether the mailserver is accessible.
969 * We try it on each poll cycle until we get a result. This way,
970 * fetchmail won't fail if started up when the network is inaccessible.
972 if (ctl->server.dns && !ctl->server.trueaddr)
974 if (ctl->server.lead_server)
976 char *leadname = ctl->server.lead_server->truename;
978 /* prevent core dump from ill-formed or duplicate entry */
981 report(stderr, GT_("Lead server has no name.\n"));
988 xfree(ctl->server.truename);
989 ctl->server.truename = xstrdup(leadname);
993 struct addrinfo hints, *res;
996 memset(&hints, 0, sizeof(hints));
997 hints.ai_socktype = SOCK_STREAM;
998 hints.ai_family = AF_UNSPEC;
999 hints.ai_flags = AI_CANONNAME;
1001 error = getaddrinfo(ctl->server.queryname, NULL, &hints, &res);
1005 GT_("couldn't find canonical DNS name of %s (%s)\n"),
1006 ctl->server.pollname, ctl->server.queryname);
1014 xfree(ctl->server.truename);
1015 /* Older FreeBSD versions return NULL in ai_canonname
1016 * if they cannot canonicalize, rather than copying
1017 * the queryname here, as IEEE Std 1003.1-2001
1018 * requires. Work around NULL. */
1019 if (res->ai_canonname != NULL) {
1020 ctl->server.truename = xstrdup(res->ai_canonname);
1022 ctl->server.truename = xstrdup(ctl->server.queryname);
1024 ctl->server.trueaddr = (struct sockaddr *)xmalloc(res->ai_addrlen);
1025 ctl->server.trueaddr_len = res->ai_addrlen;
1026 memcpy(ctl->server.trueaddr, res->ai_addr, res->ai_addrlen);
1032 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1034 /* allow time for the port to be set up if we have a plugin */
1035 if (ctl->server.plugin)
1037 if ((mailserver_socket = SockOpen(realhost,
1038 ctl->server.service ? ctl->server.service : ( ctl->use_ssl ? ctl->server.base_protocol->sslservice : ctl->server.base_protocol->service ),
1039 ctl->server.plugin, &ai0)) == -1)
1041 char errbuf[BUFSIZ];
1044 * Avoid generating a bogus error every poll cycle when we're
1045 * in daemon mode but the connection to the outside world
1048 if (!((err_no == EHOSTUNREACH || err_no == ENETUNREACH)
1049 && run.poll_interval))
1051 report_build(stderr, GT_("%s connection to %s failed"),
1052 ctl->server.base_protocol->name, ctl->server.pollname);
1053 strlcpy(errbuf, strerror(err_no), sizeof(errbuf));
1054 report_complete(stderr, ": %s\n", errbuf);
1058 * Don't use this. It was an attempt to address Debian bug
1059 * #47143 (Notify user by mail when pop server nonexistent).
1060 * Trouble is, that doesn't work; you trip over the case
1061 * where your SLIP or PPP link is down...
1063 /* warn the system administrator */
1064 if (open_warning_by_mail(ctl) == 0)
1066 stuff_warning(iana_charset, ctl,
1067 GT_("Subject: Fetchmail unreachable-server warning."));
1068 stuff_warning(NULL, ctl, "");
1069 stuff_warning(NULL, ctl, GT_("Fetchmail could not reach the mail server %s:"),
1070 ctl->server.pollname);
1071 stuff_warning(NULL, ctl, errbuf, ctl->server.pollname);
1072 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1083 /* Save the socket opened. Useful if Fetchmail hangs on SSLOpen
1084 * because the socket can be closed.
1086 mailserver_socket_temp = mailserver_socket;
1087 set_timeout(mytimeout);
1089 /* perform initial SSL handshake on open connection */
1090 /* Note: We pass the realhost name over for certificate
1091 verification. We may want to make this configurable */
1092 if (ctl->use_ssl && SSLOpen(mailserver_socket,ctl->sslcert,ctl->sslkey,ctl->sslproto,ctl->sslcertck,
1093 ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
1095 report(stderr, GT_("SSL connection failed.\n"));
1100 /* Fetchmail didn't hang on SSLOpen,
1101 * then no need to set mailserver_socket_temp
1103 mailserver_socket_temp = -1;
1106 /* A timeout is still defined before SSLOpen,
1107 * then Fetchmail hanging on SSLOpen is handled.
1112 if (ctl->server.authenticate == A_KERBEROS_V4 && (strcasecmp(proto->name,"IMAP") != 0))
1114 set_timeout(mytimeout);
1115 err = kerberos_auth(mailserver_socket, ctl->server.truename,
1116 ctl->server.principal);
1121 #endif /* KERBEROS_V4 */
1124 if (ctl->server.authenticate == A_KERBEROS_V5)
1126 set_timeout(mytimeout);
1127 err = kerberos5_auth(mailserver_socket, ctl->server.truename);
1132 #endif /* KERBEROS_V5 */
1134 /* accept greeting message from mail server */
1135 err = (ctl->server.base_protocol->parse_response)(mailserver_socket, buf);
1139 /* try to get authorized to fetch mail */
1140 stage = STAGE_GETAUTH;
1141 if (ctl->server.base_protocol->getauth)
1143 err = (ctl->server.base_protocol->getauth)(mailserver_socket, ctl, buf);
1147 if (err == PS_LOCKBUSY)
1148 report(stderr, GT_("Lock-busy error on %s@%s\n"),
1150 ctl->server.truename);
1151 else if (err == PS_SERVBUSY)
1152 report(stderr, GT_("Server busy error on %s@%s\n"),
1154 ctl->server.truename);
1155 else if (err == PS_AUTHFAIL)
1157 report(stderr, GT_("Authorization failure on %s@%s%s\n"),
1159 ctl->server.truename,
1160 (ctl->wehaveauthed ? GT_(" (previously authorized)") : "")
1164 * If we're running in background, try to mail the
1165 * calling user a heads-up about the authentication
1166 * failure once it looks like this isn't a fluke
1167 * due to the server being temporarily inaccessible.
1168 * When we get third succesive failure, we notify the user
1169 * but only if we haven't already managed to get
1170 * authorization. After that, once we get authorization
1171 * we let the user know service is restored.
1173 if (run.poll_interval
1174 && !ctl->wehavesentauthnote
1175 && ((ctl->wehaveauthed && ++ctl->authfailcount >= 10)
1176 || (!ctl->wehaveauthed && ++ctl->authfailcount >= 3))
1177 && !open_warning_by_mail(ctl))
1179 ctl->wehavesentauthnote = 1;
1180 stuff_warning(iana_charset, ctl,
1181 GT_("Subject: fetchmail authentication failed on %s@%s"),
1182 ctl->remotename, ctl->server.truename);
1183 stuff_warning(NULL, ctl, "%s", "");
1184 stuff_warning(NULL, ctl,
1185 GT_("Fetchmail could not get mail from %s@%s.\n"),
1187 ctl->server.truename);
1188 if (ctl->wehaveauthed) {
1189 stuff_warning(NULL, ctl, GT_("\
1190 The attempt to get authorization failed.\n\
1191 Since we have already succeeded in getting authorization for this\n\
1192 connection, this is probably another failure mode (such as busy server)\n\
1193 that fetchmail cannot distinguish because the server didn't send a useful\n\
1195 stuff_warning(NULL, ctl, GT_("\
1197 However, if you HAVE changed your account details since starting the\n\
1198 fetchmail daemon, you need to stop the daemon, change your configuration\n\
1199 of fetchmail, and then restart the daemon.\n\
1201 The fetchmail daemon will continue running and attempt to connect\n\
1202 at each cycle. No future notifications will be sent until service\n\
1205 stuff_warning(NULL, ctl, GT_("\
1206 The attempt to get authorization failed.\n\
1207 This probably means your password is invalid, but some servers have\n\
1208 other failure modes that fetchmail cannot distinguish from this\n\
1209 because they don't send useful error messages on login failure.\n\
1211 The fetchmail daemon will continue running and attempt to connect\n\
1212 at each cycle. No future notifications will be sent until service\n\
1215 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1218 else if (err == PS_REPOLL)
1220 if (outlevel >= O_VERBOSE)
1221 report(stderr, GT_("Repoll immediately on %s@%s\n"),
1223 ctl->server.truename);
1226 report(stderr, GT_("Unknown login or authentication error on %s@%s\n"),
1228 ctl->server.truename);
1235 * This connection has given us authorization at least once.
1237 * There are dodgy server (clubinternet.fr for example) that
1238 * give spurious authorization failures on patently good
1239 * account/password details, then 5 minutes later let you in!
1241 * This is meant to build in some tolerance of such nasty bits
1244 ctl->wehaveauthed = 1;
1245 /*if (ctl->authfailcount >= 3)*/
1246 if (ctl->wehavesentauthnote)
1248 ctl->wehavesentauthnote = 0;
1250 GT_("Authorization OK on %s@%s\n"),
1252 ctl->server.truename);
1253 if (!open_warning_by_mail(ctl))
1255 stuff_warning(iana_charset, ctl,
1256 GT_("Subject: fetchmail authentication OK on %s@%s"),
1257 ctl->remotename, ctl->server.truename);
1258 stuff_warning(NULL, ctl, "%s", "");
1259 stuff_warning(NULL, ctl,
1260 GT_("Fetchmail was able to log into %s@%s.\n"),
1262 ctl->server.truename);
1263 stuff_warning(NULL, ctl,
1264 GT_("Service has been restored.\n"));
1265 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1270 * Reporting only after the first three
1271 * consecutive failures, or ten consecutive
1272 * failures after we have managed to get
1275 ctl->authfailcount = 0;
1279 ctl->errcount = fetches = 0;
1281 /* now iterate over each folder selected */
1282 for (idp = ctl->mailboxes; idp; idp = idp->next)
1284 ctl->folder = idp->id;
1290 /* reset timeout, in case we did an IDLE */
1291 mytimeout = ctl->server.timeout;
1293 if (outlevel >= O_DEBUG)
1296 report(stdout, GT_("selecting or re-polling folder %s\n"), idp->id);
1298 report(stdout, GT_("selecting or re-polling default folder\n"));
1301 /* compute # of messages and number of new messages waiting */
1302 stage = STAGE_GETRANGE;
1303 err = (ctl->server.base_protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &newm, &bytes);
1307 /* show user how many messages we downloaded */
1309 (void) snprintf(buf, sizeof(buf),
1310 GT_("%s at %s (folder %s)"),
1311 ctl->remotename, ctl->server.pollname, idp->id);
1313 (void) snprintf(buf, sizeof(buf), GT_("%s at %s"),
1314 ctl->remotename, ctl->server.pollname);
1315 if (outlevel > O_SILENT)
1317 if (count == -1) /* only used for ETRN */
1318 report(stdout, GT_("Polling %s\n"), ctl->server.truename);
1319 else if (count != 0)
1321 if (newm != -1 && (count - newm) > 0)
1322 report_build(stdout, ngettext("%d message (%d %s) for %s", "%d messages (%d %s) for %s", (unsigned long)count),
1325 ngettext("seen", "seen", (unsigned long)count-newm),
1328 report_build(stdout, ngettext("%d message for %s",
1329 "%d messages for %s",
1333 report_complete(stdout, ".\n");
1335 report_complete(stdout, GT_(" (%d octets).\n"), bytes);
1339 /* these are pointless in normal daemon mode */
1340 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1341 report(stdout, GT_("No mail for %s\n"), buf);
1345 /* very important, this is where we leave the do loop */
1351 if (newm == -1 || ctl->fetchall)
1353 fetches = newm; /* set error status correctly */
1355 * There used to be a `goto noerror' here, but this
1356 * prevented checking of multiple folders. This
1357 * comment is a reminder in case I introduced some
1358 * subtle bug by removing it...
1366 * Don't trust the message count passed by the server.
1367 * Without this check, it might be possible to do a
1368 * DNS-spoofing attack that would pass back a ridiculous
1369 * count, and allocate a malloc area that would overlap
1370 * a portion of the stack.
1372 if ((unsigned)count > INT_MAX/sizeof(int))
1374 report(stderr, GT_("bogus message count!"));
1380 * We need the size of each message before it's
1381 * loaded in order to pass it to the ESMTP SIZE
1382 * option. If the protocol has a getsizes method,
1383 * we presume this means it doesn't get reliable
1384 * sizes from message fetch responses.
1386 * If the protocol supports getting sizes of subset of
1387 * messages, we skip this step now.
1389 if (proto->getsizes &&
1390 !(proto->getpartialsizes && NUM_NONZERO(ctl->fetchsizelimit)))
1393 msgsizes = (int *)xmalloc(sizeof(int) * count);
1394 for (i = 0; i < count; i++)
1397 stage = STAGE_GETSIZES;
1398 err = (proto->getsizes)(mailserver_socket, count, msgsizes);
1405 for (i = 0; i < count; i++)
1406 bytes += msgsizes[i];
1410 /* read, forward, and delete messages */
1411 stage = STAGE_FETCH;
1413 /* fetch in lockstep mode */
1414 err = fetch_messages(mailserver_socket, ctl,
1417 &fetches, &dispatches, &deletions);
1418 if (err != PS_SUCCESS && err != PS_MAXFETCH)
1421 if (!check_only && ctl->skipped
1422 && run.poll_interval > 0 && !nodetach)
1424 clean_skipped_list(&ctl->skipped);
1425 send_size_warnings(ctl);
1429 /* end-of-mailbox processing before we repoll or switch to another one */
1430 if (ctl->server.base_protocol->end_mailbox_poll)
1432 err = (ctl->server.base_protocol->end_mailbox_poll)(mailserver_socket, ctl);
1436 /* Return now if we have reached the fetchlimit */
1437 if (maxfetch && maxfetch <= fetches)
1441 * Only repoll if we either had some actual forwards
1442 * or are idling for new mails and had no errors.
1443 * Otherwise it is far too easy to get into infinite loops.
1445 (ctl->server.base_protocol->retry && (dispatches || ctl->idle) && !ctl->errcount);
1448 /* XXX: From this point onwards, preserve err unless a new error has occurred */
1451 /* PS_SUCCESS, PS_MAXFETCH: ordinary termination with no errors -- officially log out */
1452 stage = STAGE_LOGOUT;
1453 tmperr = (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1454 if (tmperr != PS_SUCCESS)
1457 * Hmmmm...arguably this would be incorrect if we had fetches but
1458 * no dispatches (due to oversized messages, etc.)
1460 else if (err == PS_SUCCESS && fetches == 0)
1463 * Close all SMTP delivery sockets. For optimum performance
1464 * we'd like to hold them open til end of run, but (1) this
1465 * loses if our poll interval is longer than the MTA's
1466 * inactivity timeout, and (2) some MTAs (like smail) don't
1467 * deliver after each message, but rather queue up mail and
1468 * wait to actually deliver it until the input socket is
1471 * don't send QUIT for ODMR case because we're acting as a
1472 * proxy between the SMTP server and client.
1474 smtp_close(ctl, ctl->server.protocol != P_ODMR);
1475 cleanupSockClose(mailserver_socket);
1479 /* we only get here on error */
1480 if (err != 0 && err != PS_SOCKET && err != PS_REPOLL)
1482 stage = STAGE_LOGOUT;
1483 (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1486 /* try to clean up all streams */
1489 * Sending SMTP QUIT on signal is theoretically nice, but led
1490 * to a subtle bug. If fetchmail was terminated by signal
1491 * while it was shipping message text, it would hang forever
1492 * waiting for a command acknowledge. In theory we could
1493 * enable the QUIT only outside of the message send. In
1494 * practice, we don't care. All mailservers hang up on a
1495 * dropped TCP/IP connection anyway.
1498 if (mailserver_socket != -1) {
1499 cleanupSockClose(mailserver_socket);
1500 mailserver_socket = -1;
1502 /* If there was a connect timeout, the socket should be closed.
1503 * mailserver_socket_temp contains the socket to close.
1505 if (mailserver_socket_temp != -1) {
1506 cleanupSockClose(mailserver_socket_temp);
1507 mailserver_socket_temp = -1;
1511 /* no report on PS_AUTHFAIL */
1516 msg = GT_("socket");
1519 msg = GT_("missing or bad RFC822 header");
1525 msg = GT_("client/server synchronization");
1528 msg = GT_("client/server protocol");
1531 msg = GT_("lock busy on server");
1534 msg = GT_("SMTP transaction");
1537 msg = GT_("DNS lookup");
1540 msg = GT_("undefined");
1544 if (phase == FORWARDING_WAIT || phase == LISTENER_WAIT
1546 report(stderr, GT_("%s error while fetching from %s@%s and delivering to SMTP host %s\n"),
1547 msg, ctl->remotename, ctl->server.pollname,
1548 ctl->smtphost ? ctl->smtphost : GT_("unknown"));
1550 report(stderr, GT_("%s error while fetching from %s@%s\n"),
1551 msg, ctl->remotename, ctl->server.pollname);
1558 /* execute wrapup command, if any */
1559 if (ctl->postconnect && (tmperr = system(ctl->postconnect)))
1561 report(stderr, GT_("post-connection command failed with status %d\n"), tmperr);
1562 if (err == PS_SUCCESS)
1566 set_timeout(0); /* cancel any pending alarm */
1567 set_signal_handler(SIGALRM, alrmsave);
1571 /** retrieve messages from server using given protocol method table */
1572 int do_protocol(struct query *ctl /** parsed options with merged-in defaults */,
1573 const struct method *proto /** protocol method table */)
1578 if (ctl->server.authenticate == A_KERBEROS_V4)
1580 report(stderr, GT_("Kerberos V4 support not linked.\n"));
1583 #endif /* KERBEROS_V4 */
1586 if (ctl->server.authenticate == A_KERBEROS_V5)
1588 report(stderr, GT_("Kerberos V5 support not linked.\n"));
1591 #endif /* KERBEROS_V5 */
1593 /* lacking methods, there are some options that may fail */
1596 /* check for unsupported options */
1599 GT_("Option --flush is not supported with %s\n"),
1603 else if (ctl->fetchall) {
1605 GT_("Option --all is not supported with %s\n"),
1610 if (!(proto->getsizes || proto->getpartialsizes)
1611 && NUM_SPECIFIED(ctl->limit))
1614 GT_("Option --limit is not supported with %s\n"),
1620 * If no expunge limit or we do expunges within the driver,
1621 * then just do one session, passing in any fetchlimit.
1623 if ((ctl->keep && !ctl->flush) ||
1624 proto->retry || !NUM_SPECIFIED(ctl->expunge))
1625 return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
1627 * There's an expunge limit, and it isn't handled in the driver itself.
1628 * OK; do multiple sessions, each fetching a limited # of messages.
1629 * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
1630 * (if it was nonzero).
1636 int expunge = NUM_VALUE_OUT(ctl->expunge);
1637 int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
1640 if (fetchlimit > 0 && (expunge == 0 || expunge > fetchlimit - totalcount))
1641 expunge = fetchlimit - totalcount;
1642 err = do_session(ctl, proto, expunge);
1643 totalcount += expunge;
1644 if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
1646 if (err != PS_LOCKBUSY)
1648 else if (lockouts >= MAX_LOCKOUTS)
1650 else /* err == PS_LOCKBUSY */
1653 * Allow time for the server lock to release. if we
1654 * don't do this, we'll often hit a locked-mailbox
1655 * condition and fail.
1661 (err == PS_MAXFETCH || err == PS_LOCKBUSY);
1668 /* driver.c ends here */