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 */
58 #define THROW_SIGPIPE 2 /* SIGPIPE on stream socket */
60 /* magic values for the message length array */
61 #define MSGLEN_UNKNOWN 0 /* length unknown (0 is impossible) */
62 #define MSGLEN_INVALID -1 /* length passed back is invalid */
63 #define MSGLEN_TOOLARGE -2 /* message is too large */
64 #define MSGLEN_OLD -3 /* message is old */
66 int pass; /* how many times have we re-polled? */
67 int stage; /* where are we? */
68 int phase; /* where are we, for error-logging purposes? */
69 int batchcount; /* count of messages sent in current batch */
70 flag peek_capable; /* can we peek for better error recovery? */
71 int mailserver_socket_temp = -1; /* socket to free if connect timeout */
73 static volatile int timeoutcount = 0; /* count consecutive timeouts */
74 static volatile int idletimeout = 0; /* timeout occured in idle stage? */
76 static jmp_buf restart;
78 int is_idletimeout(void)
79 /* last timeout occured in idle stage? */
84 void resetidletimeout(void)
89 void set_timeout(int timeleft)
90 /* reset the nonresponse-timeout */
92 #if !defined(__EMX__) && !defined(__BEOS__)
93 struct itimerval ntimeout;
98 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
99 ntimeout.it_value.tv_sec = timeleft;
100 ntimeout.it_value.tv_usec = 0;
101 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
105 static RETSIGTYPE timeout_handler (int signal)
106 /* handle SIGALRM signal indicating a server timeout */
109 if(stage != STAGE_IDLE) {
111 longjmp(restart, THROW_TIMEOUT);
116 static RETSIGTYPE sigpipe_handler (int signal)
117 /* handle SIGPIPE signal indicating a broken stream socket */
120 longjmp(restart, THROW_SIGPIPE);
123 #define CLEANUP_TIMEOUT 60 /* maximum timeout during cleanup */
125 static int cleanupSockClose (int fd)
126 /* close sockets in maximum CLEANUP_TIMEOUT seconds during cleanup */
129 SIGHANDLERTYPE alrmsave;
130 alrmsave = set_signal_handler(SIGALRM, null_signal_handler);
131 set_timeout(CLEANUP_TIMEOUT);
132 scerror = SockClose(fd);
134 set_signal_handler(SIGALRM, alrmsave);
139 static int kerberos_auth(socket, canonical, principal)
140 /* authenticate to the server host using Kerberos V4 */
141 int socket; /* socket to server host */
142 char *canonical; /* server name */
148 Key_schedule schedule;
150 char * prin_copy = (char *) NULL;
151 char * prin = (char *) NULL;
152 char * inst = (char *) NULL;
153 char * realm = (char *) NULL;
155 if (principal != (char *)NULL && *principal)
158 prin = prin_copy = xstrdup(principal);
159 for (cp = prin_copy; *cp && *cp != '.'; ++cp)
165 while (*cp && *cp != '@')
175 ticket = xmalloc(sizeof (KTEXT_ST));
176 rem = (krb_sendauth (0L, socket, ticket,
178 inst ? inst : canonical,
179 realm ? realm : ((char *) (krb_realmofhost (canonical))),
184 ((struct sockaddr_in *) 0),
185 ((struct sockaddr_in *) 0),
194 report(stderr, GT_("kerberos error %s\n"), (krb_get_err_text (rem)));
195 return (PS_AUTHFAIL);
199 #endif /* KERBEROS_V4 */
202 static int kerberos5_auth(socket, canonical)
203 /* authenticate to the server host using Kerberos V5 */
204 int socket; /* socket to server host */
205 const char *canonical; /* server name */
207 krb5_error_code retval;
208 krb5_context context;
210 krb5_principal client = NULL, server = NULL;
211 krb5_error *err_ret = NULL;
213 krb5_auth_context auth_context = NULL;
215 krb5_init_context(&context);
216 krb5_auth_con_init(context, &auth_context);
218 if ((retval = krb5_cc_default(context, &ccdef))) {
219 report(stderr, "krb5_cc_default: %s\n", error_message(retval));
223 if ((retval = krb5_cc_get_principal(context, ccdef, &client))) {
224 report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval));
228 if ((retval = krb5_sname_to_principal(context, canonical, "pop",
231 report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval));
235 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
236 "KPOPV1.0", client, server,
237 AP_OPTS_MUTUAL_REQUIRED,
238 NULL, /* no data to checksum */
239 0, /* no creds, use ccache instead */
243 NULL); /* don't need reply */
245 krb5_free_principal(context, server);
246 krb5_free_principal(context, client);
247 krb5_auth_con_free(context, auth_context);
251 if (err_ret && err_ret->e_text) {
252 report(stderr, GT_("krb5_sendauth: %s [server says '%*s'] \n"),
253 error_message(retval),
256 if (err_ret && err_ret->text.length) {
257 report(stderr, GT_("krb5_sendauth: %s [server says '%*s'] \n"),
258 error_message(retval),
259 err_ret->text.length,
262 krb5_free_error(context, err_ret);
264 report(stderr, "krb5_sendauth: %s\n", error_message(retval));
270 #endif /* KERBEROS_V5 */
272 static void clean_skipped_list(struct idlist **skipped_list)
273 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
275 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
276 prev = current = head = *skipped_list;
282 /* if item has no reference, remove it */
283 if (current && current->val.status.mark == 0)
285 if (current == head) /* remove first item (head) */
287 head = current->next;
288 if (current->id) free(current->id);
290 prev = current = head;
292 else /* remove middle/last item */
296 if (current->id) free(current->id);
301 else /* skip this item */
304 current = current->next;
308 *skipped_list = head;
311 static void send_size_warnings(struct query *ctl)
312 /* send warning mail with skipped msg; reset msg count when user notified */
315 int msg_to_send = FALSE;
316 struct idlist *head=NULL, *current=NULL;
317 int max_warning_poll_count;
323 /* don't start a notification message unless we need to */
324 for (current = head; current; current = current->next)
325 if (current->val.status.num == 0 && current->val.status.mark)
331 * There's no good way to recover if we can't send notification mail,
332 * but it's not a disaster, either, since the skipped mail will not
335 if (open_warning_by_mail(ctl))
337 stuff_warning(iana_charset, ctl,
338 GT_("Subject: Fetchmail oversized-messages warning"));
339 stuff_warning(NULL, ctl, "%s", "");
341 stuff_warning(NULL, ctl,
342 GT_("The following oversized messages were deleted on server %s account %s:"),
343 ctl->server.pollname, ctl->remotename);
345 stuff_warning(NULL, ctl,
346 GT_("The following oversized messages remain on server %s account %s:"),
347 ctl->server.pollname, ctl->remotename);
349 stuff_warning(NULL, ctl, "%s", "");
351 if (run.poll_interval == 0)
352 max_warning_poll_count = 0;
354 max_warning_poll_count = ctl->warnings/run.poll_interval;
356 /* parse list of skipped msg, adding items to the mail */
357 for (current = head; current; current = current->next)
359 if (current->val.status.num == 0 && current->val.status.mark)
361 nbr = current->val.status.mark;
362 size = atoi(current->id);
364 stuff_warning(NULL, ctl,
365 GT_(" %d msg %d octets long deleted by fetchmail."),
368 stuff_warning(NULL, ctl,
369 GT_(" %d msg %d octets long skipped by fetchmail."),
372 current->val.status.num++;
373 current->val.status.mark = 0;
375 if (current->val.status.num >= max_warning_poll_count)
376 current->val.status.num = 0;
379 stuff_warning(NULL, ctl, "%s", "");
381 close_warning_by_mail(ctl, (struct msgblk *)NULL);
384 static void mark_oversized(struct query *ctl, int size)
385 /* mark a message oversized */
387 struct idlist *current=NULL, *tmp=NULL;
391 /* convert size to string */
392 snprintf(sizestr, sizeof(sizestr), "%d", size);
394 /* build a list of skipped messages
395 * val.id = size of msg (string cnvt)
396 * val.status.num = warning_poll_count
397 * val.status.mask = nbr of msg this size
400 current = ctl->skipped;
402 /* initialise warning_poll_count to the
403 * current value so that all new msg will
404 * be included in the next mail
406 cnt = current ? current->val.status.num : 0;
408 /* if entry exists, increment the count */
409 if (current && (tmp = str_in_list(¤t, sizestr, FALSE)))
411 tmp->val.status.mark++;
413 /* otherwise, create a new entry */
414 /* initialise with current poll count */
417 tmp = save_str(&ctl->skipped, sizestr, 1);
418 tmp->val.status.num = cnt;
422 static int fetch_messages(int mailserver_socket, struct query *ctl,
423 int count, int **msgsizes, int maxfetch,
424 int *fetches, int *dispatches, int *deletions)
425 /* fetch messages in lockstep mode */
427 flag force_retrieval;
428 int num, firstnum = 1, lastnum = 0, err, len;
429 int fetchsizelimit = ctl->fetchsizelimit;
431 int initialfetches = *fetches;
433 if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit))
435 /* for POP3, we can get the size of one mail only! Unfortunately, this
436 * protocol specific test cannot be done elsewhere as the protocol
437 * could be "auto". */
438 switch (ctl->server.protocol)
440 case P_POP3: case P_APOP: case P_RPOP:
444 /* Time to allocate memory to store the sizes */
446 *msgsizes = (int *)xmalloc(sizeof(int) * fetchsizelimit);
450 * What forces this code is that in POP2 and
451 * IMAP2bis you can't fetch a message without
452 * having it marked `seen'. In POP3 and IMAP4, on the
453 * other hand, you can (peek_capable is set by
454 * each driver module to convey this; it's not a
455 * method constant because of the difference between
456 * IMAP2bis and IMAP4, and because POP3 doesn't peek
457 * if fetchall is on).
459 * The result of being unable to peek is that if there's
460 * any kind of transient error (DNS lookup failure, or
461 * sendmail refusing delivery due to process-table limits)
462 * the message will be marked "seen" on the server without
463 * having been delivered. This is not a big problem if
464 * fetchmail is running in foreground, because the user
465 * will see a "skipped" message when it next runs and get
468 * But in daemon mode this leads to the message
469 * being silently ignored forever. This is not
472 * We compensate for this by checking the error
473 * count from the previous pass and forcing all
474 * messages to be considered new if it's nonzero.
476 force_retrieval = !peek_capable && (ctl->errcount > 0);
478 for (num = 1; num <= count; num++)
480 flag suppress_delete = FALSE;
481 flag suppress_forward = FALSE;
482 flag suppress_readbody = FALSE;
483 flag retained = FALSE;
484 int msgcode = MSGLEN_UNKNOWN;
486 /* check if the message is old
487 * Note: the size of the message may not be known here */
488 if (ctl->fetchall || force_retrieval)
490 else if (ctl->server.base_protocol->is_old && (ctl->server.base_protocol->is_old)(mailserver_socket,ctl,num))
491 msgcode = MSGLEN_OLD;
492 if (msgcode == MSGLEN_OLD)
494 /* To avoid flooding the syslog when using --keep,
495 * report "Skipped message" only when:
496 * 1) --verbose is on, or
497 * 2) fetchmail does not use syslog
499 if ( (outlevel >= O_VERBOSE) ||
500 (outlevel > O_SILENT && !run.use_syslog)
504 GT_("skipping message %s@%s:%d"),
505 ctl->remotename, ctl->server.truename, num);
511 if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit) &&
514 /* Instead of getting the sizes of all mails at the start, we get
515 * the sizes in blocks of fetchsizelimit. This leads to better
516 * performance when there are too many mails (say, 10000) in
517 * the mailbox and either we are not getting all the mails at
518 * one go (--fetchlimit 100) or there is a frequent socket
519 * error while just getting the sizes of all mails! */
522 int oldstage = stage;
524 lastnum = num + fetchsizelimit - 1;
527 for (i = 0; i < fetchsizelimit; i++)
530 stage = STAGE_GETSIZES;
531 err = (ctl->server.base_protocol->getpartialsizes)(mailserver_socket, num, lastnum, *msgsizes);
538 msgsize = *msgsizes ? (*msgsizes)[num-firstnum] : 0;
540 /* check if the message is oversized */
541 if (NUM_NONZERO(ctl->limit) && (msgsize > ctl->limit))
542 msgcode = MSGLEN_TOOLARGE;
543 /* else if (msgsize == 512)
544 msgcode = MSGLEN_OLD; (hmh) sample code to skip message */
548 if (msgcode == MSGLEN_TOOLARGE)
550 mark_oversized(ctl, msgsize);
551 if (!ctl->limitflush)
552 suppress_delete = TRUE;
554 if (outlevel > O_SILENT)
556 /* old messages are already handled above */
558 GT_("skipping message %s@%s:%d (%d octets)"),
559 ctl->remotename, ctl->server.truename, num,
565 * Invalid lengths are produced by Post Office/NT's
566 * annoying habit of randomly prepending bogus
567 * LIST items of length -1. Patrick Audley
568 * <paudley@pobox.com> tells us: LIST shows a
569 * size of -1, RETR and TOP return "-ERR
570 * System error - couldn't open message", and
571 * DELE succeeds but doesn't actually delete
574 report_build(stdout, GT_(" (length -1)"));
576 case MSGLEN_TOOLARGE:
577 report_build(stdout, GT_(" (oversized)"));
584 flag wholesize = !ctl->server.base_protocol->fetch_body;
585 flag separatefetchbody = (ctl->server.base_protocol->fetch_body) ? TRUE : FALSE;
587 /* request a message */
588 err = (ctl->server.base_protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
589 if (err == PS_TRANSIENT) /* server is probably Exchange */
592 GT_("couldn't fetch headers, message %s@%s:%d (%d octets)\n"),
593 ctl->remotename, ctl->server.truename, num,
600 /* -1 means we didn't see a size in the response */
607 if (outlevel > O_SILENT)
609 report_build(stdout, GT_("reading message %s@%s:%d of %d"),
610 ctl->remotename, ctl->server.truename,
614 report_build(stdout, wholesize ? GT_(" (%d octets)")
615 : GT_(" (%d header octets)"), len);
616 if (outlevel >= O_VERBOSE)
617 report_complete(stdout, "\n");
621 * Read the message headers and ship them to the
624 err = readheaders(mailserver_socket, len, msgsize,
626 /* pass the suppress_readbody flag only if the underlying
627 * protocol does not fetch the body separately */
628 separatefetchbody ? 0 : &suppress_readbody);
629 if (err == PS_RETAINED)
630 suppress_forward = suppress_delete = retained = TRUE;
631 else if (err == PS_TRANSIENT)
632 suppress_delete = suppress_forward = TRUE;
633 else if (err == PS_REFUSED)
634 suppress_forward = TRUE;
635 else if (err == PS_TRUNCATED)
636 suppress_readbody = TRUE;
640 /* tell server we got it OK and resynchronize */
641 if (separatefetchbody && ctl->server.base_protocol->trail)
643 if (outlevel >= O_VERBOSE && !is_a_file(1) && !run.use_syslog)
649 if ((err = (ctl->server.base_protocol->trail)(mailserver_socket, ctl, tag)))
653 /* do not read the body which is not being forwarded only if
654 * the underlying protocol allows the body to be fetched
656 if (separatefetchbody && suppress_forward)
657 suppress_readbody = TRUE;
660 * If we're using IMAP4 or something else that
661 * can fetch headers separately from bodies,
662 * it's time to request the body now. This
663 * fetch may be skipped if we got an anti-spam
664 * or other PS_REFUSED error response during
667 if (!suppress_readbody)
669 if (separatefetchbody)
672 if ((err=(ctl->server.base_protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
675 * Work around a bug in Novell's
676 * broken GroupWise IMAP server;
677 * its body FETCH response is missing
678 * the required length for the data
679 * string. This violates RFC2060.
682 len = msgsize - msgblk.msglen;
683 if (outlevel > O_SILENT && !wholesize)
685 GT_(" (%d body octets)"), len);
688 /* process the body now */
689 err = readbody(mailserver_socket,
693 if (err == PS_TRANSIENT)
694 suppress_delete = suppress_forward = TRUE;
698 /* tell server we got it OK and resynchronize */
699 if (ctl->server.base_protocol->trail)
701 if (outlevel >= O_VERBOSE && !is_a_file(1) && !run.use_syslog)
707 err = (ctl->server.base_protocol->trail)(mailserver_socket, ctl, tag);
713 /* count # messages forwarded on this pass */
714 if (!suppress_forward)
718 * Check to see if the numbers matched?
720 * Yes, some servers foo this up horribly.
721 * All IMAP servers seem to get it right, and
722 * so does Eudora QPOP at least in 2.xx
725 * Microsoft Exchange gets it completely
726 * wrong, reporting compressed rather than
727 * actual sizes (so the actual length of
728 * message is longer than the reported size).
729 * Another fine example of Microsoft brain death!
731 * Some older POP servers, like the old UCB
732 * POP server and the pre-QPOP QUALCOMM
733 * versions, report a longer size in the LIST
734 * response than actually gets shipped up.
735 * It's unclear what is going on here, as the
736 * QUALCOMM server (at least) seems to be
737 * reporting the on-disk size correctly.
739 * qmail-pop3d also goofs up message sizes and does not
740 * count the line end characters properly.
742 if (msgblk.msglen != msgsize)
744 if (outlevel >= O_DEBUG)
746 GT_("message %s@%s:%d was not the expected length (%d actual != %d expected)\n"),
747 ctl->remotename, ctl->server.truename, num,
748 msgblk.msglen, msgsize);
751 /* end-of-message processing starts here */
752 if (!close_sink(ctl, &msgblk, !suppress_forward))
755 suppress_delete = TRUE;
763 * At this point in flow of control, either
764 * we've bombed on a protocol error or had
765 * delivery refused by the SMTP server
766 * (unlikely -- I've never seen it) or we've
767 * seen `accepted for delivery' and the
768 * message is shipped. It's safe to mark the
769 * message seen and delete it on the server
773 /* maybe we delete this message now? */
776 if (outlevel > O_SILENT)
777 report_complete(stdout, GT_(" retained\n"));
779 else if (ctl->server.base_protocol->delete_msg
781 && ((msgcode >= 0 && !ctl->keep)
782 || (msgcode == MSGLEN_OLD && ctl->flush)
783 || (msgcode == MSGLEN_TOOLARGE && ctl->limitflush)))
786 if (outlevel > O_SILENT)
787 report_complete(stdout, GT_(" flushed\n"));
788 err = (ctl->server.base_protocol->delete_msg)(mailserver_socket, ctl, num);
794 if ( (outlevel >= O_VERBOSE) ||
795 /* To avoid flooding the syslog when using --keep,
796 * report "Skipped message" only when:
797 * 1) --verbose is on, or
798 * 2) fetchmail does not use syslog, or
799 * 3) the message was skipped for some other
800 * reason than just being old.
802 (outlevel > O_SILENT && (!run.use_syslog || msgcode != MSGLEN_OLD))
804 report_complete(stdout, GT_(" not flushed\n"));
806 /* maybe we mark this message as seen now? */
807 if (ctl->server.base_protocol->mark_seen
809 && (msgcode >= 0 && ctl->keep))
811 err = (ctl->server.base_protocol->mark_seen)(mailserver_socket, ctl, num);
817 /* perhaps this as many as we're ready to handle */
818 if (maxfetch && maxfetch <= *fetches && num < count)
820 int remcount = count - (*fetches - initialfetches);
822 ngettext("fetchlimit %d reached; %d message left on server %s account %s\n",
823 "fetchlimit %d reached; %d messages left on server %s account %s\n", remcount),
824 maxfetch, remcount, ctl->server.truename, ctl->remotename);
827 } /* for (num = 1; num <= count; num++) */
832 /* retrieve messages from server using given protocol method table */
833 static int do_session(
834 /* parsed options with merged-in defaults */
836 /* protocol method table */
837 const struct method *proto,
838 /* maximum number of messages to fetch */
841 static int *msgsizes;
842 volatile int err, mailserver_socket = -1; /* pacifies -Wall */
844 int deletions = 0, js;
846 SIGHANDLERTYPE pipesave;
847 SIGHANDLERTYPE alrmsave;
849 ctl->server.base_protocol = proto;
854 init_transact(proto);
856 /* set up the server-nonresponse timeout */
857 alrmsave = set_signal_handler(SIGALRM, timeout_handler);
858 mytimeout = ctl->server.timeout;
860 /* set up the broken-pipe timeout */
861 pipesave = set_signal_handler(SIGPIPE, sigpipe_handler);
863 if ((js = setjmp(restart)))
865 /* exception caught */
866 #ifdef HAVE_SIGPROCMASK
868 * Don't rely on setjmp() to restore the blocked-signal mask.
869 * It does this under BSD but is required not to under POSIX.
871 * If your Unix doesn't have sigprocmask, better hope it has
872 * BSD-like behavior. Otherwise you may see fetchmail get
873 * permanently wedged after a second timeout on a bad read,
874 * because alarm signals were blocked after the first.
878 sigfillset(&allsigs);
879 sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
880 #endif /* HAVE_SIGPROCMASK */
882 if (js == THROW_SIGPIPE)
884 set_signal_handler(SIGPIPE, SIG_IGN);
886 GT_("SIGPIPE thrown from an MDA or a stream socket error\n"));
889 else if (js == THROW_TIMEOUT)
891 if (phase == OPEN_WAIT)
893 GT_("timeout after %d seconds waiting to connect to server %s.\n"),
894 ctl->server.timeout, ctl->server.pollname);
895 else if (phase == SERVER_WAIT)
897 GT_("timeout after %d seconds waiting for server %s.\n"),
898 ctl->server.timeout, ctl->server.pollname);
899 else if (phase == FORWARDING_WAIT)
901 GT_("timeout after %d seconds waiting for %s.\n"),
903 ctl->mda ? "MDA" : "SMTP");
904 else if (phase == LISTENER_WAIT)
906 GT_("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
909 GT_("timeout after %d seconds.\n"), ctl->server.timeout);
912 * If we've exceeded our threshold for consecutive timeouts,
913 * try to notify the user, then mark the connection wedged.
914 * Don't do this if the connection can idle, though; idle
915 * timeouts just mean the frequency of mail is low.
917 if (timeoutcount > MAX_TIMEOUTS
918 && !open_warning_by_mail(ctl))
920 stuff_warning(iana_charset, ctl,
921 GT_("Subject: fetchmail sees repeated timeouts"));
922 stuff_warning(NULL, ctl, "%s", "");
923 stuff_warning(NULL, ctl,
924 GT_("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\n"),
926 ctl->remotename, ctl->server.truename);
927 stuff_warning(NULL, ctl,
928 GT_("This could mean that your mailserver is stuck, or that your SMTP\n" \
929 "server is wedged, or that your mailbox file on the server has been\n" \
930 "corrupted by a server error. You can run `fetchmail -v -v' to\n" \
931 "diagnose the problem.\n\n" \
932 "Fetchmail won't poll this mailbox again until you restart it.\n"));
933 close_warning_by_mail(ctl, (struct msgblk *)NULL);
943 /* setjmp returned zero -> normal operation */
944 char buf[MSGBUFSIZE+1], *realhost;
945 int count, newm, bytes;
946 int fetches, dispatches, oldphase;
949 /* execute pre-initialization command, if any */
950 if (ctl->preconnect && (err = system(ctl->preconnect)))
953 GT_("pre-connection command failed with status %d\n"), err);
958 /* open a socket to the mail server */
961 set_timeout(mytimeout);
963 #ifdef HAVE_PKG_hesiod
964 /* If either the pollname or vianame are "hesiod" we want to
965 lookup the user's hesiod pobox host */
966 if (!strcasecmp(ctl->server.queryname, "hesiod")) {
967 struct hes_postoffice *hes_p;
968 hes_p = hes_getmailhost(ctl->remotename);
969 if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
970 free(ctl->server.queryname);
971 ctl->server.queryname = xstrdup(hes_p->po_host);
973 free(ctl->server.via);
974 ctl->server.via = xstrdup(hes_p->po_host);
977 GT_("couldn't find HESIOD pobox for %s\n"),
984 * Canonicalize the server truename for later use. This also
985 * functions as a probe for whether the mailserver is accessible.
986 * We try it on each poll cycle until we get a result. This way,
987 * fetchmail won't fail if started up when the network is inaccessible.
989 if (ctl->server.dns && !ctl->server.trueaddr)
991 if (ctl->server.lead_server)
993 char *leadname = ctl->server.lead_server->truename;
995 /* prevent core dump from ill-formed or duplicate entry */
998 report(stderr, GT_("Lead server has no name.\n"));
1005 xfree(ctl->server.truename);
1006 ctl->server.truename = xstrdup(leadname);
1010 struct addrinfo hints, *res;
1013 memset(&hints, 0, sizeof(hints));
1014 hints.ai_socktype = SOCK_STREAM;
1015 hints.ai_family = AF_UNSPEC;
1016 hints.ai_flags = AI_CANONNAME;
1018 error = getaddrinfo(ctl->server.queryname, NULL, &hints, &res);
1022 GT_("couldn't find canonical DNS name of %s (%s)\n"),
1023 ctl->server.pollname, ctl->server.queryname);
1031 xfree(ctl->server.truename);
1032 /* Older FreeBSD versions return NULL in ai_canonname
1033 * if they cannot canonicalize, rather than copying
1034 * the queryname here, as IEEE Std 1003.1-2001
1035 * requires. Work around NULL. */
1036 if (res->ai_canonname != NULL) {
1037 ctl->server.truename = xstrdup(res->ai_canonname);
1039 ctl->server.truename = xstrdup(ctl->server.queryname);
1041 ctl->server.trueaddr = (struct sockaddr *)xmalloc(res->ai_addrlen);
1042 ctl->server.trueaddr_len = res->ai_addrlen;
1043 memcpy(ctl->server.trueaddr, res->ai_addr, res->ai_addrlen);
1049 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1051 /* allow time for the port to be set up if we have a plugin */
1052 if (ctl->server.plugin)
1054 if ((mailserver_socket = SockOpen(realhost,
1055 ctl->server.service ? ctl->server.service : ( ctl->use_ssl ? ctl->server.base_protocol->sslservice : ctl->server.base_protocol->service ),
1056 ctl->server.plugin)) == -1)
1058 char errbuf[BUFSIZ];
1061 * Avoid generating a bogus error every poll cycle when we're
1062 * in daemon mode but the connection to the outside world
1065 if (!((err_no == EHOSTUNREACH || err_no == ENETUNREACH)
1066 && run.poll_interval))
1068 report_build(stderr, GT_("%s connection to %s failed"),
1069 ctl->server.base_protocol->name, ctl->server.pollname);
1070 strlcpy(errbuf, strerror(err_no), sizeof(errbuf));
1071 report_complete(stderr, ": %s\n", errbuf);
1075 * Don't use this. It was an attempt to address Debian bug
1076 * #47143 (Notify user by mail when pop server nonexistent).
1077 * Trouble is, that doesn't work; you trip over the case
1078 * where your SLIP or PPP link is down...
1080 /* warn the system administrator */
1081 if (open_warning_by_mail(ctl) == 0)
1083 stuff_warning(iana_charset, ctl,
1084 GT_("Subject: Fetchmail unreachable-server warning."));
1085 stuff_warning(NULL, ctl, "");
1086 stuff_warning(NULL, ctl, GT_("Fetchmail could not reach the mail server %s:"),
1087 ctl->server.pollname);
1088 stuff_warning(NULL, ctl, errbuf, ctl->server.pollname);
1089 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1100 /* Save the socket opened. Useful if Fetchmail hangs on SSLOpen
1101 * because the socket can be closed.
1103 mailserver_socket_temp = mailserver_socket;
1104 set_timeout(mytimeout);
1106 /* perform initial SSL handshake on open connection */
1107 /* Note: We pass the realhost name over for certificate
1108 verification. We may want to make this configurable */
1109 if (ctl->use_ssl && SSLOpen(mailserver_socket,ctl->sslcert,ctl->sslkey,ctl->sslproto,ctl->sslcertck,
1110 ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
1112 report(stderr, GT_("SSL connection failed.\n"));
1117 /* Fetchmail didn't hang on SSLOpen,
1118 * then no need to set mailserver_socket_temp
1120 mailserver_socket_temp = -1;
1123 /* A timeout is still defined before SSLOpen,
1124 * then Fetchmail hanging on SSLOpen is handled.
1129 if (ctl->server.authenticate == A_KERBEROS_V4 && (strcasecmp(proto->name,"IMAP") != 0))
1131 set_timeout(mytimeout);
1132 err = kerberos_auth(mailserver_socket, ctl->server.truename,
1133 ctl->server.principal);
1138 #endif /* KERBEROS_V4 */
1141 if (ctl->server.authenticate == A_KERBEROS_V5)
1143 set_timeout(mytimeout);
1144 err = kerberos5_auth(mailserver_socket, ctl->server.truename);
1149 #endif /* KERBEROS_V5 */
1151 /* accept greeting message from mail server */
1152 err = (ctl->server.base_protocol->parse_response)(mailserver_socket, buf);
1156 /* try to get authorized to fetch mail */
1157 stage = STAGE_GETAUTH;
1158 if (ctl->server.base_protocol->getauth)
1160 err = (ctl->server.base_protocol->getauth)(mailserver_socket, ctl, buf);
1164 if (err == PS_LOCKBUSY)
1165 report(stderr, GT_("Lock-busy error on %s@%s\n"),
1167 ctl->server.truename);
1168 else if (err == PS_SERVBUSY)
1169 report(stderr, GT_("Server busy error on %s@%s\n"),
1171 ctl->server.truename);
1172 else if (err == PS_AUTHFAIL)
1174 report(stderr, GT_("Authorization failure on %s@%s%s\n"),
1176 ctl->server.truename,
1177 (ctl->wehaveauthed ? GT_(" (previously authorized)") : "")
1181 * If we're running in background, try to mail the
1182 * calling user a heads-up about the authentication
1183 * failure once it looks like this isn't a fluke
1184 * due to the server being temporarily inaccessible.
1185 * When we get third succesive failure, we notify the user
1186 * but only if we haven't already managed to get
1187 * authorization. After that, once we get authorization
1188 * we let the user know service is restored.
1190 if (run.poll_interval
1191 && !ctl->wehavesentauthnote
1192 && ((ctl->wehaveauthed && ++ctl->authfailcount >= 10)
1193 || (!ctl->wehaveauthed && ++ctl->authfailcount >= 3))
1194 && !open_warning_by_mail(ctl))
1196 ctl->wehavesentauthnote = 1;
1197 stuff_warning(iana_charset, ctl,
1198 GT_("Subject: fetchmail authentication failed on %s@%s"),
1199 ctl->remotename, ctl->server.truename);
1200 stuff_warning(NULL, ctl, "%s", "");
1201 stuff_warning(NULL, ctl,
1202 GT_("Fetchmail could not get mail from %s@%s.\n"),
1204 ctl->server.truename);
1205 if (ctl->wehaveauthed) {
1206 stuff_warning(NULL, ctl, GT_("\
1207 The attempt to get authorization failed.\n\
1208 Since we have already succeeded in getting authorization for this\n\
1209 connection, this is probably another failure mode (such as busy server)\n\
1210 that fetchmail cannot distinguish because the server didn't send a useful\n\
1212 stuff_warning(NULL, ctl, GT_("\
1214 However, if you HAVE changed your account details since starting the\n\
1215 fetchmail daemon, you need to stop the daemon, change your configuration\n\
1216 of fetchmail, and then restart the daemon.\n\
1218 The fetchmail daemon will continue running and attempt to connect\n\
1219 at each cycle. No future notifications will be sent until service\n\
1222 stuff_warning(NULL, ctl, GT_("\
1223 The attempt to get authorization failed.\n\
1224 This probably means your password is invalid, but some servers have\n\
1225 other failure modes that fetchmail cannot distinguish from this\n\
1226 because they don't send useful error messages on login failure.\n\
1228 The fetchmail daemon will continue running and attempt to connect\n\
1229 at each cycle. No future notifications will be sent until service\n\
1232 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1235 else if (err == PS_REPOLL)
1237 if (outlevel >= O_VERBOSE)
1238 report(stderr, GT_("Repoll immediately on %s@%s\n"),
1240 ctl->server.truename);
1243 report(stderr, GT_("Unknown login or authentication error on %s@%s\n"),
1245 ctl->server.truename);
1252 * This connection has given us authorization at least once.
1254 * There are dodgy server (clubinternet.fr for example) that
1255 * give spurious authorization failures on patently good
1256 * account/password details, then 5 minutes later let you in!
1258 * This is meant to build in some tolerance of such nasty bits
1261 ctl->wehaveauthed = 1;
1262 /*if (ctl->authfailcount >= 3)*/
1263 if (ctl->wehavesentauthnote)
1265 ctl->wehavesentauthnote = 0;
1267 GT_("Authorization OK on %s@%s\n"),
1269 ctl->server.truename);
1270 if (!open_warning_by_mail(ctl))
1272 stuff_warning(iana_charset, ctl,
1273 GT_("Subject: fetchmail authentication OK on %s@%s"),
1274 ctl->remotename, ctl->server.truename);
1275 stuff_warning(NULL, ctl, "%s", "");
1276 stuff_warning(NULL, ctl,
1277 GT_("Fetchmail was able to log into %s@%s.\n"),
1279 ctl->server.truename);
1280 stuff_warning(NULL, ctl,
1281 GT_("Service has been restored.\n"));
1282 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1287 * Reporting only after the first three
1288 * consecutive failures, or ten consecutive
1289 * failures after we have managed to get
1292 ctl->authfailcount = 0;
1296 ctl->errcount = fetches = 0;
1298 /* now iterate over each folder selected */
1299 for (idp = ctl->mailboxes; idp; idp = idp->next)
1301 ctl->folder = idp->id;
1307 /* reset timeout, in case we did an IDLE */
1308 mytimeout = ctl->server.timeout;
1310 if (outlevel >= O_DEBUG)
1313 report(stdout, GT_("selecting or re-polling folder %s\n"), idp->id);
1315 report(stdout, GT_("selecting or re-polling default folder\n"));
1318 /* compute # of messages and number of new messages waiting */
1319 stage = STAGE_GETRANGE;
1320 err = (ctl->server.base_protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &newm, &bytes);
1324 /* show user how many messages we downloaded */
1326 (void) snprintf(buf, sizeof(buf),
1327 GT_("%s at %s (folder %s)"),
1328 ctl->remotename, ctl->server.pollname, idp->id);
1330 (void) snprintf(buf, sizeof(buf), GT_("%s at %s"),
1331 ctl->remotename, ctl->server.pollname);
1332 if (outlevel > O_SILENT)
1334 if (count == -1) /* only used for ETRN */
1335 report(stdout, GT_("Polling %s\n"), ctl->server.truename);
1336 else if (count != 0)
1338 if (newm != -1 && (count - newm) > 0)
1339 report_build(stdout, ngettext("%d message (%d %s) for %s", "%d messages (%d %s) for %s", (unsigned long)count),
1342 ngettext("seen", "seen", (unsigned long)count-newm),
1345 report_build(stdout, ngettext("%d message for %s",
1346 "%d messages for %s",
1350 report_complete(stdout, ".\n");
1352 report_complete(stdout, GT_(" (%d octets).\n"), bytes);
1356 /* these are pointless in normal daemon mode */
1357 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1358 report(stdout, GT_("No mail for %s\n"), buf);
1362 /* very important, this is where we leave the do loop */
1368 if (newm == -1 || ctl->fetchall)
1370 fetches = newm; /* set error status correctly */
1372 * There used to be a `goto noerror' here, but this
1373 * prevented checking of multiple folders. This
1374 * comment is a reminder in case I introduced some
1375 * subtle bug by removing it...
1383 * Don't trust the message count passed by the server.
1384 * Without this check, it might be possible to do a
1385 * DNS-spoofing attack that would pass back a ridiculous
1386 * count, and allocate a malloc area that would overlap
1387 * a portion of the stack.
1389 if ((unsigned)count > INT_MAX/sizeof(int))
1391 report(stderr, GT_("bogus message count!"));
1397 * We need the size of each message before it's
1398 * loaded in order to pass it to the ESMTP SIZE
1399 * option. If the protocol has a getsizes method,
1400 * we presume this means it doesn't get reliable
1401 * sizes from message fetch responses.
1403 * If the protocol supports getting sizes of subset of
1404 * messages, we skip this step now.
1406 if (proto->getsizes &&
1407 !(proto->getpartialsizes && NUM_NONZERO(ctl->fetchsizelimit)))
1410 msgsizes = (int *)xmalloc(sizeof(int) * count);
1411 for (i = 0; i < count; i++)
1414 stage = STAGE_GETSIZES;
1415 err = (proto->getsizes)(mailserver_socket, count, msgsizes);
1422 for (i = 0; i < count; i++)
1423 bytes += msgsizes[i];
1427 /* read, forward, and delete messages */
1428 stage = STAGE_FETCH;
1430 /* fetch in lockstep mode */
1431 err = fetch_messages(mailserver_socket, ctl,
1434 &fetches, &dispatches, &deletions);
1435 if (err != PS_SUCCESS && err != PS_MAXFETCH)
1438 if (!check_only && ctl->skipped
1439 && run.poll_interval > 0 && !nodetach)
1441 clean_skipped_list(&ctl->skipped);
1442 send_size_warnings(ctl);
1446 /* end-of-mailbox processing before we repoll or switch to another one */
1447 if (ctl->server.base_protocol->end_mailbox_poll)
1449 err = (ctl->server.base_protocol->end_mailbox_poll)(mailserver_socket, ctl);
1453 /* Return now if we have reached the fetchlimit */
1454 if (maxfetch && maxfetch <= fetches)
1458 * Only repoll if we either had some actual forwards
1459 * or are idling for new mails and had no errors.
1460 * Otherwise it is far too easy to get into infinite loops.
1462 (ctl->server.base_protocol->retry && (dispatches || ctl->idle) && !ctl->errcount);
1465 /* XXX: From this point onwards, preserve err unless a new error has occurred */
1468 /* PS_SUCCESS, PS_MAXFETCH: ordinary termination with no errors -- officially log out */
1469 stage = STAGE_LOGOUT;
1470 tmperr = (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1471 if (tmperr != PS_SUCCESS)
1474 * Hmmmm...arguably this would be incorrect if we had fetches but
1475 * no dispatches (due to oversized messages, etc.)
1477 else if (err == PS_SUCCESS && fetches == 0)
1480 * Close all SMTP delivery sockets. For optimum performance
1481 * we'd like to hold them open til end of run, but (1) this
1482 * loses if our poll interval is longer than the MTA's
1483 * inactivity timeout, and (2) some MTAs (like smail) don't
1484 * deliver after each message, but rather queue up mail and
1485 * wait to actually deliver it until the input socket is
1488 * don't send QUIT for ODMR case because we're acting as a
1489 * proxy between the SMTP server and client.
1491 smtp_close(ctl, ctl->server.protocol != P_ODMR);
1492 cleanupSockClose(mailserver_socket);
1496 /* we only get here on error */
1497 if (err != 0 && err != PS_SOCKET && err != PS_REPOLL)
1499 stage = STAGE_LOGOUT;
1500 (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1503 /* try to clean up all streams */
1506 * Sending SMTP QUIT on signal is theoretically nice, but led
1507 * to a subtle bug. If fetchmail was terminated by signal
1508 * while it was shipping message text, it would hang forever
1509 * waiting for a command acknowledge. In theory we could
1510 * enable the QUIT only outside of the message send. In
1511 * practice, we don't care. All mailservers hang up on a
1512 * dropped TCP/IP connection anyway.
1515 if (mailserver_socket != -1) {
1516 cleanupSockClose(mailserver_socket);
1517 mailserver_socket = -1;
1519 /* If there was a connect timeout, the socket should be closed.
1520 * mailserver_socket_temp contains the socket to close.
1522 if (mailserver_socket_temp != -1) {
1523 cleanupSockClose(mailserver_socket_temp);
1524 mailserver_socket_temp = -1;
1528 /* no report on PS_AUTHFAIL */
1533 msg = GT_("socket");
1536 msg = GT_("missing or bad RFC822 header");
1542 msg = GT_("client/server synchronization");
1545 msg = GT_("client/server protocol");
1548 msg = GT_("lock busy on server");
1551 msg = GT_("SMTP transaction");
1554 msg = GT_("DNS lookup");
1557 msg = GT_("undefined");
1561 if (phase == FORWARDING_WAIT || phase == LISTENER_WAIT
1563 report(stderr, GT_("%s error while fetching from %s@%s and delivering to SMTP host %s\n"),
1564 msg, ctl->remotename, ctl->server.pollname,
1565 ctl->smtphost ? ctl->smtphost : GT_("unknown"));
1567 report(stderr, GT_("%s error while fetching from %s@%s\n"),
1568 msg, ctl->remotename, ctl->server.pollname);
1575 /* execute wrapup command, if any */
1576 if (ctl->postconnect && (tmperr = system(ctl->postconnect)))
1578 report(stderr, GT_("post-connection command failed with status %d\n"), tmperr);
1579 if (err == PS_SUCCESS)
1583 set_timeout(0); /* cancel any pending alarm */
1584 set_signal_handler(SIGALRM, alrmsave);
1585 set_signal_handler(SIGPIPE, pipesave);
1589 /** retrieve messages from server using given protocol method table */
1590 int do_protocol(struct query *ctl /** parsed options with merged-in defaults */,
1591 const struct method *proto /** protocol method table */)
1596 if (ctl->server.authenticate == A_KERBEROS_V4)
1598 report(stderr, GT_("Kerberos V4 support not linked.\n"));
1601 #endif /* KERBEROS_V4 */
1604 if (ctl->server.authenticate == A_KERBEROS_V5)
1606 report(stderr, GT_("Kerberos V5 support not linked.\n"));
1609 #endif /* KERBEROS_V5 */
1611 /* lacking methods, there are some options that may fail */
1614 /* check for unsupported options */
1617 GT_("Option --flush is not supported with %s\n"),
1621 else if (ctl->fetchall) {
1623 GT_("Option --all is not supported with %s\n"),
1628 if (!(proto->getsizes || proto->getpartialsizes)
1629 && NUM_SPECIFIED(ctl->limit))
1632 GT_("Option --limit is not supported with %s\n"),
1638 * If no expunge limit or we do expunges within the driver,
1639 * then just do one session, passing in any fetchlimit.
1641 if ((ctl->keep && !ctl->flush) ||
1642 proto->retry || !NUM_SPECIFIED(ctl->expunge))
1643 return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
1645 * There's an expunge limit, and it isn't handled in the driver itself.
1646 * OK; do multiple sessions, each fetching a limited # of messages.
1647 * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
1648 * (if it was nonzero).
1654 int expunge = NUM_VALUE_OUT(ctl->expunge);
1655 int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
1658 if (fetchlimit > 0 && (expunge == 0 || expunge > fetchlimit - totalcount))
1659 expunge = fetchlimit - totalcount;
1660 err = do_session(ctl, proto, expunge);
1661 totalcount += expunge;
1662 if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
1664 if (err != PS_LOCKBUSY)
1666 else if (lockouts >= MAX_LOCKOUTS)
1668 else /* err == PS_LOCKBUSY */
1671 * Allow time for the server lock to release. if we
1672 * don't do this, we'll often hit a locked-mailbox
1673 * condition and fail.
1679 (err == PS_MAXFETCH || err == PS_LOCKBUSY);
1686 /* driver.c ends here */