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>
28 #ifdef HAVE_SYS_WAIT_H
32 #ifdef HAVE_NET_SOCKET_H
33 #include <net/socket.h>
39 #if defined(HAVE_RES_SEARCH) || defined(HAVE_GETHOSTBYNAME)
42 #endif /* defined(HAVE_RES_SEARCH) || defined(HAVE_GETHOSTBYNAME) */
46 #include <netinet/in.h>
47 #endif /* KERBEROS_V4 */
52 #include "fetchmail.h"
55 /* throw types for runtime errors */
56 #define THROW_TIMEOUT 1 /* server timed out */
57 #define THROW_SIGPIPE 2 /* SIGPIPE on stream socket */
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 static int timeoutcount; /* count consecutive timeouts */
74 static jmp_buf restart;
76 void set_timeout(int timeleft)
77 /* reset the nonresponse-timeout */
79 #if !defined(__EMX__) && !defined(__BEOS__)
80 struct itimerval ntimeout;
85 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
86 ntimeout.it_value.tv_sec = timeleft;
87 ntimeout.it_value.tv_usec = 0;
88 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
92 static void timeout_handler (int signal)
93 /* handle SIGALRM signal indicating a server timeout */
96 longjmp(restart, THROW_TIMEOUT);
99 static void sigpipe_handler (int signal)
100 /* handle SIGPIPE signal indicating a broken stream socket */
102 longjmp(restart, THROW_SIGPIPE);
105 /* ignore SIGALRM signal indicating a timeout during cleanup */
106 static void cleanup_timeout_handler (int signal) { }
108 #define CLEANUP_TIMEOUT 60 /* maximum timeout during cleanup */
110 static int cleanupSockClose (int fd)
111 /* close sockets in maximum CLEANUP_TIMEOUT seconds during cleanup */
114 void (*alrmsave)(int);
115 alrmsave = signal(SIGALRM, cleanup_timeout_handler);
116 set_timeout(CLEANUP_TIMEOUT);
117 scerror = SockClose(fd);
119 signal(SIGALRM, alrmsave);
124 static int kerberos_auth(socket, canonical, principal)
125 /* authenticate to the server host using Kerberos V4 */
126 int socket; /* socket to server host */
127 char *canonical; /* server name */
134 Key_schedule schedule;
136 char * prin_copy = (char *) NULL;
137 char * prin = (char *) NULL;
138 char * inst = (char *) NULL;
139 char * realm = (char *) NULL;
141 if (principal != (char *)NULL && *principal)
144 prin = prin_copy = xstrdup(principal);
145 for (cp = prin_copy; *cp && *cp != '.'; ++cp)
151 while (*cp && *cp != '@')
161 xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
162 rem = (krb_sendauth (0L, socket, ticket,
164 inst ? inst : canonical,
165 realm ? realm : ((char *) (krb_realmofhost (canonical))),
170 ((struct sockaddr_in *) 0),
171 ((struct sockaddr_in *) 0),
179 report(stderr, GT_("kerberos error %s\n"), (krb_get_err_text (rem)));
180 return (PS_AUTHFAIL);
184 #endif /* KERBEROS_V4 */
187 static int kerberos5_auth(socket, canonical)
188 /* authenticate to the server host using Kerberos V5 */
189 int socket; /* socket to server host */
190 const char *canonical; /* server name */
192 krb5_error_code retval;
193 krb5_context context;
195 krb5_principal client = NULL, server = NULL;
196 krb5_error *err_ret = NULL;
198 krb5_auth_context auth_context = NULL;
200 krb5_init_context(&context);
201 krb5_init_ets(context);
202 krb5_auth_con_init(context, &auth_context);
204 if (retval = krb5_cc_default(context, &ccdef)) {
205 report(stderr, "krb5_cc_default: %s\n", error_message(retval));
209 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
210 report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval));
214 if (retval = krb5_sname_to_principal(context, canonical, "pop",
217 report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval));
221 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
222 "KPOPV1.0", client, server,
223 AP_OPTS_MUTUAL_REQUIRED,
224 NULL, /* no data to checksum */
225 0, /* no creds, use ccache instead */
229 NULL); /* don't need reply */
231 krb5_free_principal(context, server);
232 krb5_free_principal(context, client);
233 krb5_auth_con_free(context, auth_context);
237 if (err_ret && err_ret->e_text) {
238 report(stderr, GT_("krb5_sendauth: %s [server says '%*s'] \n"),
239 error_message(retval),
242 if (err_ret && err_ret->text.length) {
243 report(stderr, GT_("krb5_sendauth: %s [server says '%*s'] \n"),
244 error_message(retval),
245 err_ret->text.length,
248 krb5_free_error(context, err_ret);
250 report(stderr, "krb5_sendauth: %s\n", error_message(retval));
256 #endif /* KERBEROS_V5 */
258 static void clean_skipped_list(struct idlist **skipped_list)
259 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
261 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
262 prev = current = head = *skipped_list;
268 /* if item has no reference, remove it */
269 if (current && current->val.status.mark == 0)
271 if (current == head) /* remove first item (head) */
273 head = current->next;
274 if (current->id) free(current->id);
276 prev = current = head;
278 else /* remove middle/last item */
282 if (current->id) free(current->id);
287 else /* skip this item */
290 current = current->next;
294 *skipped_list = head;
297 static void send_size_warnings(struct query *ctl)
298 /* send warning mail with skipped msg; reset msg count when user notified */
301 int msg_to_send = FALSE;
302 struct idlist *head=NULL, *current=NULL;
303 int max_warning_poll_count;
309 /* don't start a notification message unless we need to */
310 for (current = head; current; current = current->next)
311 if (current->val.status.num == 0 && current->val.status.mark)
317 * There's no good way to recover if we can't send notification mail,
318 * but it's not a disaster, either, since the skipped mail will not
321 if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
324 GT_("Subject: Fetchmail oversized-messages warning.\n"
326 "The following oversized messages remain on the mail server %s:"),
327 ctl->server.pollname);
329 if (run.poll_interval == 0)
330 max_warning_poll_count = 0;
332 max_warning_poll_count = ctl->warnings/run.poll_interval;
334 /* parse list of skipped msg, adding items to the mail */
335 for (current = head; current; current = current->next)
337 if (current->val.status.num == 0 && current->val.status.mark)
339 nbr = current->val.status.mark;
340 size = atoi(current->id);
342 GT_("\t%d msg %d octets long skipped by fetchmail.\n"),
345 current->val.status.num++;
346 current->val.status.mark = 0;
348 if (current->val.status.num >= max_warning_poll_count)
349 current->val.status.num = 0;
352 close_warning_by_mail(ctl, (struct msgblk *)NULL);
355 static void mark_oversized(struct query *ctl, int num, int size)
356 /* mark a message oversized */
358 struct idlist *current=NULL, *tmp=NULL;
362 /* convert size to string */
364 snprintf(sizestr, sizeof(sizestr),
367 #endif /* HAVE_SNPRINTF */
370 /* build a list of skipped messages
371 * val.id = size of msg (string cnvt)
372 * val.status.num = warning_poll_count
373 * val.status.mask = nbr of msg this size
376 current = ctl->skipped;
378 /* initialise warning_poll_count to the
379 * current value so that all new msg will
380 * be included in the next mail
382 cnt = current ? current->val.status.num : 0;
384 /* if entry exists, increment the count */
385 if (current && str_in_list(¤t, sizestr, FALSE))
387 for ( ; current; current = current->next)
389 if (strcmp(current->id, sizestr) == 0)
391 current->val.status.mark++;
396 /* otherwise, create a new entry */
397 /* initialise with current poll count */
400 tmp = save_str(&ctl->skipped, sizestr, 1);
401 tmp->val.status.num = cnt;
405 static int fetch_messages(int mailserver_socket, struct query *ctl,
406 int count, int *msgsizes, int *msgcodes, int maxfetch,
407 int *fetches, int *dispatches, int *deletions)
408 /* fetch messages in lockstep mode */
412 for (num = 1; num <= count; num++)
414 flag suppress_delete = FALSE;
415 flag suppress_forward = FALSE;
416 flag suppress_readbody = FALSE;
417 flag retained = FALSE;
419 if (msgcodes[num-1] < 0)
421 if ((msgcodes[num-1] == MSGLEN_TOOLARGE) && !check_only)
422 mark_oversized(ctl, num, msgsizes[num-1]);
423 if (outlevel > O_SILENT)
426 GT_("skipping message %s@%s:%d (%d octets)"),
427 ctl->remotename, ctl->server.truename, num,
429 switch (msgcodes[num-1])
433 * Invalid lengths are produced by Post Office/NT's
434 * annoying habit of randomly prepending bogus
435 * LIST items of length -1. Patrick Audley
436 * <paudley@pobox.com> tells us: LIST shows a
437 * size of -1, RETR and TOP return "-ERR
438 * System error - couldn't open message", and
439 * DELE succeeds but doesn't actually delete
442 report_build(stdout, GT_(" (length -1)"));
444 case MSGLEN_TOOLARGE:
445 report_build(stdout, GT_(" (oversized)"));
452 flag wholesize = !ctl->server.base_protocol->fetch_body;
454 /* request a message */
455 err = (ctl->server.base_protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
456 if (err == PS_TRANSIENT) /* server is probably Exchange */
459 GT_("couldn't fetch headers, message %s@%s:%d (%d octets)\n"),
460 ctl->remotename, ctl->server.truename, num,
467 /* -1 means we didn't see a size in the response */
470 len = msgsizes[num - 1];
474 if (outlevel > O_SILENT)
476 report_build(stdout, GT_("reading message %s@%s:%d of %d"),
477 ctl->remotename, ctl->server.truename,
481 report_build(stdout, GT_(" (%d %soctets)"),
482 len, wholesize ? "" : GT_("header "));
483 if (outlevel >= O_VERBOSE)
484 report_complete(stdout, "\n");
486 report_complete(stdout, " ");
490 * Read the message headers and ship them to the
493 err = readheaders(mailserver_socket, len, msgsizes[num-1],
495 if (err == PS_RETAINED)
497 suppress_forward = suppress_delete = retained = TRUE;
498 /* do not read the body only if the underlying protocol
499 * allows the body to be fetched separately */
500 if (ctl->server.base_protocol->fetch_body)
501 suppress_readbody = TRUE;
503 else if (err == PS_TRANSIENT)
505 suppress_delete = suppress_forward = TRUE;
506 if (ctl->server.base_protocol->fetch_body)
507 suppress_readbody = TRUE;
509 else if (err == PS_REFUSED)
511 suppress_forward = TRUE;
512 if (ctl->server.base_protocol->fetch_body)
513 suppress_readbody = TRUE;
517 * readheaders does not read the body when it
518 * hits a non-header. It has been recently
519 * fixed to return PS_TRUNCATED (properly) when
520 * that happens, but apparently fixing that bug
521 * opened this one here (which looks like an
522 * inproper fix from some ancient thinko)
524 else if (err == PS_TRUNCATED)
525 suppress_readbody = TRUE;
529 else if (err && err != PS_TRUNCATED)
534 * If we're using IMAP4 or something else that
535 * can fetch headers separately from bodies,
536 * it's time to request the body now. This
537 * fetch may be skipped if we got an anti-spam
538 * or other PS_REFUSED error response during
541 if (ctl->server.base_protocol->fetch_body && !suppress_readbody)
543 if (outlevel >= O_VERBOSE && !isafile(1))
549 if ((err = (ctl->server.base_protocol->trail)(mailserver_socket, ctl, num)))
552 if (!suppress_forward)
554 if ((err=(ctl->server.base_protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
557 * Work around a bug in Novell's
558 * broken GroupWise IMAP server;
559 * its body FETCH response is missing
560 * the required length for the data
561 * string. This violates RFC2060.
564 len = msgsizes[num-1] - msgblk.msglen;
565 if (outlevel > O_SILENT && !wholesize)
566 report_complete(stdout,
567 GT_(" (%d body octets) "), len);
571 /* process the body now */
574 if (suppress_readbody)
580 err = readbody(mailserver_socket,
585 if (err == PS_TRANSIENT)
586 suppress_delete = suppress_forward = TRUE;
590 /* tell server we got it OK and resynchronize */
591 if (ctl->server.base_protocol->trail)
593 if (outlevel >= O_VERBOSE && !isafile(1))
599 err = (ctl->server.base_protocol->trail)(mailserver_socket, ctl, num);
605 /* count # messages forwarded on this pass */
606 if (!suppress_forward)
610 * Check to see if the numbers matched?
612 * Yes, some servers foo this up horribly.
613 * All IMAP servers seem to get it right, and
614 * so does Eudora QPOP at least in 2.xx
617 * Microsoft Exchange gets it completely
618 * wrong, reporting compressed rather than
619 * actual sizes (so the actual length of
620 * message is longer than the reported size).
621 * Another fine example of Microsoft brain death!
623 * Some older POP servers, like the old UCB
624 * POP server and the pre-QPOP QUALCOMM
625 * versions, report a longer size in the LIST
626 * response than actually gets shipped up.
627 * It's unclear what is going on here, as the
628 * QUALCOMM server (at least) seems to be
629 * reporting the on-disk size correctly.
631 if (msgblk.msglen != msgsizes[num-1])
633 if (outlevel >= O_DEBUG)
635 GT_("message %s@%s:%d was not the expected length (%d actual != %d expected)\n"),
636 ctl->remotename, ctl->server.truename, num,
637 msgblk.msglen, msgsizes[num-1]);
640 /* end-of-message processing starts here */
641 if (!close_sink(ctl, &msgblk, !suppress_forward))
644 suppress_delete = TRUE;
651 * At this point in flow of control, either
652 * we've bombed on a protocol error or had
653 * delivery refused by the SMTP server
654 * (unlikely -- I've never seen it) or we've
655 * seen `accepted for delivery' and the
656 * message is shipped. It's safe to mark the
657 * message seen and delete it on the server
662 * Tell the UID code we've seen this.
663 * Matthias Andree: only register the UID if we could actually
664 * forward this mail. If we omit this !suppress_delete check,
665 * fetchmail will never retry mail that the local listener
666 * refused temporarily.
668 if (ctl->newsaved && !suppress_delete)
672 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
673 if ((sdp->val.status.num == num) && (msgcodes[num-1] >= 0))
675 sdp->val.status.mark = UID_SEEN;
676 save_str(&ctl->oldsaved, sdp->id,UID_SEEN);
680 /* maybe we delete this message now? */
683 if (outlevel > O_SILENT)
684 report(stdout, GT_(" retained\n"));
686 else if (ctl->server.base_protocol->delete
688 && ((msgcodes[num-1] >= 0) ? !ctl->keep : ctl->flush))
691 if (outlevel > O_SILENT)
692 report_complete(stdout, GT_(" flushed\n"));
693 err = (ctl->server.base_protocol->delete)(mailserver_socket, ctl, num);
697 delete_str(&ctl->newsaved, num);
698 #endif /* POP3_ENABLE */
700 else if (outlevel > O_SILENT)
701 report_complete(stdout, GT_(" not flushed\n"));
703 /* perhaps this as many as we're ready to handle */
704 if (maxfetch && maxfetch <= *fetches && *fetches < count)
706 report(stdout, GT_("fetchlimit %d reached; %d messages left on server %s account %s\n"),
707 maxfetch, count - *fetches, ctl->server.truename, ctl->remotename);
715 static int do_session(ctl, proto, maxfetch)
716 /* retrieve messages from server using given protocol method table */
717 struct query *ctl; /* parsed options with merged-in defaults */
718 const struct method *proto; /* protocol method table */
719 const int maxfetch; /* maximum number of messages to fetch */
723 volatile int err, mailserver_socket = -1; /* pacifies -Wall */
725 int err, mailserver_socket = -1;
726 #endif /* HAVE_VOLATILE */
728 void (*pipesave)(int);
729 void (*alrmsave)(int);
731 ctl->server.base_protocol = proto;
735 init_transact(proto);
737 /* set up the server-nonresponse timeout */
738 alrmsave = signal(SIGALRM, timeout_handler);
739 mytimeout = ctl->server.timeout;
741 /* set up the broken-pipe timeout */
742 pipesave = signal(SIGPIPE, sigpipe_handler);
744 if ((js = setjmp(restart)))
746 #ifdef HAVE_SIGPROCMASK
748 * Don't rely on setjmp() to restore the blocked-signal mask.
749 * It does this under BSD but is required not to under POSIX.
751 * If your Unix doesn't have sigprocmask, better hope it has
752 * BSD-like behavior. Otherwise you may see fetchmail get
753 * permanently wedged after a second timeout on a bad read,
754 * because alarm signals were blocked after the first.
758 sigfillset(&allsigs);
759 sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
760 #endif /* HAVE_SIGPROCMASK */
762 if (js == THROW_SIGPIPE)
764 signal(SIGPIPE, SIG_IGN);
766 GT_("SIGPIPE thrown from an MDA or a stream socket error\n"));
769 else if (js == THROW_TIMEOUT)
771 if (phase == OPEN_WAIT)
773 GT_("timeout after %d seconds waiting to connect to server %s.\n"),
774 ctl->server.timeout, ctl->server.pollname);
775 else if (phase == SERVER_WAIT)
777 GT_("timeout after %d seconds waiting for server %s.\n"),
778 ctl->server.timeout, ctl->server.pollname);
779 else if (phase == FORWARDING_WAIT)
781 GT_("timeout after %d seconds waiting for %s.\n"),
783 ctl->mda ? "MDA" : "SMTP");
784 else if (phase == LISTENER_WAIT)
786 GT_("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
789 GT_("timeout after %d seconds.\n"), ctl->server.timeout);
792 * If we've exceeded our threshold for consecutive timeouts,
793 * try to notify the user, then mark the connection wedged.
794 * Don't do this if the connection can idle, though; idle
795 * timeouts just mean the frequency of mail is low.
797 if (timeoutcount > MAX_TIMEOUTS
798 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
801 GT_("Subject: fetchmail sees repeated timeouts\n"));
803 GT_("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\n"),
806 ctl->server.truename);
808 GT_("This could mean that your mailserver is stuck, or that your SMTP\n" \
809 "server is wedged, or that your mailbox file on the server has been\n" \
810 "corrupted by a server error. You can run `fetchmail -v -v' to\n" \
811 "diagnose the problem.\n\n" \
812 "Fetchmail won't poll this mailbox again until you restart it.\n"));
813 close_warning_by_mail(ctl, (struct msgblk *)NULL);
823 char buf[MSGBUFSIZE+1], *realhost;
824 int count, new, bytes, deletions = 0;
825 int *msgsizes = (int *)NULL;
826 int *msgcodes = (int *)NULL;
828 int fetches, dispatches, oldphase;
829 #else /* INET6_ENABLE */
830 int port, fetches, dispatches, oldphase;
831 #endif /* INET6_ENABLE */
834 /* execute pre-initialization command, if any */
835 if (ctl->preconnect && (err = system(ctl->preconnect)))
838 GT_("pre-connection command failed with status %d\n"), err);
843 /* open a socket to the mail server */
846 set_timeout(mytimeout);
849 port = ctl->server.port ? ctl->server.port : ( ctl->use_ssl ? ctl->server.base_protocol->sslport : ctl->server.base_protocol->port );
851 port = ctl->server.port ? ctl->server.port : ctl->server.base_protocol->port;
853 #endif /* !INET6_ENABLE */
856 /* If either the pollname or vianame are "hesiod" we want to
857 lookup the user's hesiod pobox host */
858 if (!strcasecmp(ctl->server.queryname, "hesiod")) {
859 struct hes_postoffice *hes_p;
860 hes_p = hes_getmailhost(ctl->remotename);
861 if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
862 free(ctl->server.queryname);
863 ctl->server.queryname = xstrdup(hes_p->po_host);
865 free(ctl->server.via);
866 ctl->server.via = xstrdup(hes_p->po_host);
869 GT_("couldn't find HESIOD pobox for %s\n"),
875 #ifdef HAVE_GETHOSTBYNAME
877 * Canonicalize the server truename for later use. This also
878 * functions as a probe for whether the mailserver is accessible.
879 * We try it on each poll cycle until we get a result. This way,
880 * fetchmail won't fail if started up when the network is inaccessible.
882 if (ctl->server.dns && !ctl->server.trueaddr)
884 if (ctl->server.lead_server)
886 char *leadname = ctl->server.lead_server->truename;
888 /* prevent core dump from ill-formed or duplicate entry */
891 report(stderr, GT_("Lead server has no name.\n"));
898 ctl->server.truename = xstrdup(leadname);
902 struct hostent *namerec;
905 * Get the host's IP, so we can report it like this:
907 * Received: from hostname [10.0.0.1]
910 namerec = gethostbyname(ctl->server.queryname);
911 if (namerec == (struct hostent *)NULL)
914 GT_("couldn't find canonical DNS name of %s\n"),
915 ctl->server.pollname);
923 ctl->server.truename=xstrdup((char *)namerec->h_name);
924 ctl->server.trueaddr=xmalloc(namerec->h_length);
925 memcpy(ctl->server.trueaddr,
926 namerec->h_addr_list[0],
931 #endif /* HAVE_GETHOSTBYNAME */
933 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
935 /* allow time for the port to be set up if we have a plugin */
936 if (ctl->server.plugin)
939 if ((mailserver_socket = SockOpen(realhost,
940 ctl->server.service ? ctl->server.service : ( ctl->use_ssl ? ctl->server.base_protocol->sslservice : ctl->server.base_protocol->service ),
941 ctl->server.netsec, ctl->server.plugin)) == -1)
942 #else /* INET6_ENABLE */
943 if ((mailserver_socket = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
944 #endif /* INET6_ENABLE */
949 #ifdef HAVE_RES_SEARCH
950 if (err_no != 0 && h_errno != 0)
951 report(stderr, GT_("internal inconsistency\n"));
954 * Avoid generating a bogus error every poll cycle when we're
955 * in daemon mode but the connection to the outside world
958 if (!((err_no == EHOSTUNREACH || err_no == ENETUNREACH)
959 && run.poll_interval))
961 report_build(stderr, GT_("%s connection to %s failed"),
962 ctl->server.base_protocol->name, ctl->server.pollname);
963 #ifdef HAVE_RES_SEARCH
966 if (h_errno == HOST_NOT_FOUND)
967 strcpy(errbuf, GT_("host is unknown."));
969 else if (h_errno == NO_ADDRESS)
970 strcpy(errbuf, GT_("name is valid but has no IP address."));
972 else if (h_errno == NO_RECOVERY)
973 strcpy(errbuf, GT_("unrecoverable name server error."));
974 else if (h_errno == TRY_AGAIN)
975 strcpy(errbuf, GT_("temporary name server error."));
978 snprintf(errbuf, sizeof(errbuf),
981 #endif /* HAVE_SNPRINTF */
982 GT_("unknown DNS error %d."), h_errno);
985 #endif /* HAVE_RES_SEARCH */
986 strcpy(errbuf, strerror(err_no));
987 report_complete(stderr, ": %s\n", errbuf);
991 * Don't use this. It was an attempt to address Debian bug
992 * #47143 (Notify user by mail when pop server nonexistent).
993 * Trouble is, that doesn't work; you trip over the case
994 * where your SLIP or PPP link is down...
996 /* warn the system administrator */
997 if (open_warning_by_mail(ctl, (struct msgblk *)NULL) == 0)
1000 GT_("Subject: Fetchmail unreachable-server warning.\n"
1002 "Fetchmail could not reach the mail server %s:")
1003 ctl->server.pollname);
1004 stuff_warning(ctl, errbuf, ctl->server.pollname);
1005 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1009 #endif /* INET6_ENABLE */
1017 /* Save the socket opened. Usefull if Fetchmail hangs on SSLOpen
1018 * because the socket can be closed
1020 mailserver_socket_temp = mailserver_socket;
1021 set_timeout(mytimeout);
1023 /* perform initial SSL handshake on open connection */
1024 /* Note: We pass the realhost name over for certificate
1025 verification. We may want to make this configurable */
1026 if (ctl->use_ssl && SSLOpen(mailserver_socket,ctl->sslcert,ctl->sslkey,ctl->sslproto,ctl->sslcertck,
1027 ctl->sslcertpath,ctl->sslfingerprint,realhost,ctl->server.pollname) == -1)
1029 report(stderr, GT_("SSL connection failed.\n"));
1033 /* Fetchmail didn't hang on SSLOpen,
1034 * then no need to set mailserver_socket_temp
1036 mailserver_socket_temp = -1;
1039 /* A timeout is still defined before SSLOpen,
1040 * then Fetchmail hanging on SSLOpen is handled.
1045 if (ctl->server.authenticate == A_KERBEROS_V4 && (strcasecmp(proto->name,"IMAP") != 0))
1047 set_timeout(mytimeout);
1048 err = kerberos_auth(mailserver_socket, ctl->server.truename,
1049 ctl->server.principal);
1054 #endif /* KERBEROS_V4 */
1057 if (ctl->server.authenticate == A_KERBEROS_V5)
1059 set_timeout(mytimeout);
1060 err = kerberos5_auth(mailserver_socket, ctl->server.truename);
1065 #endif /* KERBEROS_V5 */
1067 /* accept greeting message from mail server */
1068 err = (ctl->server.base_protocol->parse_response)(mailserver_socket, buf);
1072 /* try to get authorized to fetch mail */
1073 stage = STAGE_GETAUTH;
1074 if (ctl->server.base_protocol->getauth)
1076 err = (ctl->server.base_protocol->getauth)(mailserver_socket, ctl, buf);
1080 if (err == PS_LOCKBUSY)
1081 report(stderr, GT_("Lock-busy error on %s@%s\n"),
1083 ctl->server.truename);
1084 else if (err == PS_SERVBUSY)
1085 report(stderr, GT_("Server busy error on %s@%s\n"),
1087 ctl->server.truename);
1088 else if (err == PS_AUTHFAIL)
1090 report(stderr, GT_("Authorization failure on %s@%s%s\n"),
1092 ctl->server.truename,
1093 (ctl->wehaveauthed ? GT_(" (previously authorized)") : "")
1097 * If we're running in background, try to mail the
1098 * calling user a heads-up about the authentication
1099 * failure once it looks like this isn't a fluke
1100 * due to the server being temporarily inaccessible.
1101 * When we get third succesive failure, we notify the user
1102 * but only if we haven't already managed to get
1103 * authorization. After that, once we get authorization
1104 * we let the user know service is restored.
1106 if (run.poll_interval
1107 && !ctl->wehavesentauthnote
1108 && ((ctl->wehaveauthed && ++ctl->authfailcount == 10)
1109 || ++ctl->authfailcount == 3)
1110 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1112 ctl->wehavesentauthnote = 1;
1114 GT_("Subject: fetchmail authentication failed on %s@%s\n"),
1115 ctl->remotename, ctl->server.truename);
1117 GT_("Fetchmail could not get mail from %s@%s.\n"),
1119 ctl->server.truename);
1120 if (ctl->wehaveauthed)
1121 stuff_warning(ctl, GT_("\
1122 The attempt to get authorization failed.\n\
1123 Since we have already succeeded in getting authorization for this\n\
1124 connection, this is probably another failure mode (such as busy server)\n\
1125 that fetchmail cannot distinguish because the server didn't send a useful\n\
1128 However, if you HAVE changed your account details since starting the\n\
1129 fetchmail daemon, you need to stop the daemon, change your configuration\n\
1130 of fetchmail, and then restart the daemon.\n\
1132 The fetchmail daemon will continue running and attempt to connect\n\
1133 at each cycle. No future notifications will be sent until service\n\
1136 stuff_warning(ctl, GT_("\
1137 The attempt to get authorization failed.\n\
1138 This probably means your password is invalid, but some servers have\n\
1139 other failure modes that fetchmail cannot distinguish from this\n\
1140 because they don't send useful error messages on login failure.\n\
1142 The fetchmail daemon will continue running and attempt to connect\n\
1143 at each cycle. No future notifications will be sent until service\n\
1145 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1148 else if (err == PS_REPOLL)
1150 if (outlevel >= O_VERBOSE)
1151 report(stderr, GT_("Repoll immediately on %s@%s\n"),
1153 ctl->server.truename);
1156 report(stderr, GT_("Unknown login or authentication error on %s@%s\n"),
1158 ctl->server.truename);
1165 * This connection has given us authorization at least once.
1167 * There are dodgy server (clubinternet.fr for example) that
1168 * give spurious authorization failures on patently good
1169 * account/password details, then 5 minutes later let you in!
1171 * This is meant to build in some tolerance of such nasty bits
1174 ctl->wehaveauthed = 1;
1175 /*if (ctl->authfailcount >= 3)*/
1176 if (ctl->wehavesentauthnote)
1178 ctl->wehavesentauthnote = 0;
1180 GT_("Authorization OK on %s@%s\n"),
1182 ctl->server.truename);
1183 if (!open_warning_by_mail(ctl, (struct msgblk *)NULL))
1186 GT_("Subject: fetchmail authentication OK on %s@%s\n"),
1187 ctl->remotename, ctl->server.truename);
1189 GT_("Fetchmail was able to log into %s@%s.\n"),
1191 ctl->server.truename);
1193 GT_("Service has been restored.\n"));
1194 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1199 * Reporting only after the first three
1200 * consecutive failures, or ten consecutive
1201 * failures after we have managed to get
1204 ctl->authfailcount = 0;
1208 ctl->errcount = fetches = 0;
1210 /* now iterate over each folder selected */
1211 for (idp = ctl->mailboxes; idp; idp = idp->next)
1218 /* reset timeout, in case we did an IDLE */
1219 mytimeout = ctl->server.timeout;
1221 if (outlevel >= O_DEBUG)
1224 report(stdout, GT_("selecting or re-polling folder %s\n"), idp->id);
1226 report(stdout, GT_("selecting or re-polling default folder\n"));
1229 /* compute # of messages and number of new messages waiting */
1230 stage = STAGE_GETRANGE;
1231 err = (ctl->server.base_protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &new, &bytes);
1235 /* show user how many messages we downloaded */
1237 #ifdef HAVE_SNPRINTF
1238 (void) snprintf(buf, sizeof(buf),
1241 #endif /* HAVE_SNPRINTF */
1242 GT_("%s at %s (folder %s)"),
1243 ctl->remotename, ctl->server.truename, idp->id);
1245 #ifdef HAVE_SNPRINTF
1246 (void) snprintf(buf, sizeof(buf),
1249 #endif /* HAVE_SNPRINTF */
1251 ctl->remotename, ctl->server.truename);
1252 if (outlevel > O_SILENT)
1254 if (count == -1) /* only used for ETRN */
1255 report(stdout, GT_("Polling %s\n"), ctl->server.truename);
1256 else if (count != 0)
1258 if (new != -1 && (count - new) > 0)
1259 report_build(stdout, GT_("%d %s (%d seen) for %s"),
1260 count, count > 1 ? GT_("messages") :
1264 report_build(stdout, GT_("%d %s for %s"),
1265 count, count > 1 ? GT_("messages") :
1266 GT_("message"), buf);
1268 report_complete(stdout, ".\n");
1270 report_complete(stdout, GT_(" (%d octets).\n"), bytes);
1274 /* these are pointless in normal daemon mode */
1275 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1276 report(stdout, GT_("No mail for %s\n"), buf);
1280 /* very important, this is where we leave the do loop */
1286 if (new == -1 || ctl->fetchall)
1288 fetches = new; /* set error status correctly */
1290 * There used to be a `goto noerror' here, but this
1291 * prevented checking of multiple folders. This
1292 * comment is a reminder in case I introduced some
1293 * subtle bug by removing it...
1298 flag force_retrieval;
1302 * What forces this code is that in POP2 and
1303 * IMAP2bis you can't fetch a message without
1304 * having it marked `seen'. In POP3 and IMAP4, on the
1305 * other hand, you can (peek_capable is set by
1306 * each driver module to convey this; it's not a
1307 * method constant because of the difference between
1308 * IMAP2bis and IMAP4, and because POP3 doesn't peek
1309 * if fetchall is on).
1311 * The result of being unable to peek is that if there's
1312 * any kind of transient error (DNS lookup failure, or
1313 * sendmail refusing delivery due to process-table limits)
1314 * the message will be marked "seen" on the server without
1315 * having been delivered. This is not a big problem if
1316 * fetchmail is running in foreground, because the user
1317 * will see a "skipped" message when it next runs and get
1320 * But in daemon mode this leads to the message
1321 * being silently ignored forever. This is not
1324 * We compensate for this by checking the error
1325 * count from the previous pass and forcing all
1326 * messages to be considered new if it's nonzero.
1328 force_retrieval = !peek_capable && (ctl->errcount > 0);
1331 * Don't trust the message count passed by the server.
1332 * Without this check, it might be possible to do a
1333 * DNS-spoofing attack that would pass back a ridiculous
1334 * count, and allocate a malloc area that would overlap
1335 * a portion of the stack.
1337 if (count > INT_MAX/sizeof(int))
1339 report(stderr, GT_("bogus message count!"));
1340 return(PS_PROTOCOL);
1343 /* OK, we're going to gather size info next */
1344 xalloca(msgsizes, int *, sizeof(int) * count);
1345 xalloca(msgcodes, int *, sizeof(int) * count);
1346 for (i = 0; i < count; i++) {
1348 msgcodes[i] = MSGLEN_UNKNOWN;
1352 * We need the size of each message before it's
1353 * loaded in order to pass it to the ESMTP SIZE
1354 * option. If the protocol has a getsizes method,
1355 * we presume this means it doesn't get reliable
1356 * sizes from message fetch responses.
1358 if (proto->getsizes)
1360 stage = STAGE_GETSIZES;
1361 err = (proto->getsizes)(mailserver_socket, count, msgsizes);
1368 for (i = 0; i < count; i++)
1369 bytes += msgsizes[i];
1373 /* mark some messages not to be retrieved */
1374 for (num = 1; num <= count; num++)
1376 if (NUM_NONZERO(ctl->limit) && (msgsizes[num-1] > ctl->limit))
1377 msgcodes[num-1] = MSGLEN_TOOLARGE;
1378 else if (ctl->fetchall || force_retrieval)
1380 else if (ctl->server.base_protocol->is_old && (ctl->server.base_protocol->is_old)(mailserver_socket,ctl,num))
1381 msgcodes[num-1] = MSGLEN_OLD;
1382 /* else if (msgsizes[num-1] == 512)
1383 msgcodes[num-1] = MSGLEN_OLD; (hmh) sample code to skip message */
1386 /* read, forward, and delete messages */
1387 stage = STAGE_FETCH;
1389 /* fetch in lockstep mode */
1390 err = fetch_messages(mailserver_socket, ctl,
1391 count, msgsizes, msgcodes,
1393 &fetches, &dispatches, &deletions);
1397 if (!check_only && ctl->skipped
1398 && run.poll_interval > 0 && !nodetach)
1400 clean_skipped_list(&ctl->skipped);
1401 send_size_warnings(ctl);
1406 * Only re-poll if we either had some actual forwards and
1407 * either allowed deletions and had no errors.
1408 * Otherwise it is far too easy to get into infinite loops.
1410 (dispatches && ctl->server.base_protocol->retry && !ctl->keep && !ctl->errcount);
1414 /* ordinary termination with no errors -- officially log out */
1415 err = (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1417 * Hmmmm...arguably this would be incorrect if we had fetches but
1418 * no dispatches (due to oversized messages, etc.)
1421 err = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
1422 cleanupSockClose(mailserver_socket);
1426 /* we only get here on error */
1427 if (err != 0 && err != PS_SOCKET && err != PS_REPOLL)
1429 stage = STAGE_LOGOUT;
1430 (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl);
1433 /* try to clean up all streams */
1436 if (mailserver_socket != -1) {
1437 cleanupSockClose(mailserver_socket);
1438 mailserver_socket = -1;
1440 /* If there was a connect timeout, the socket should be closed.
1441 * mailserver_socket_temp contains the socket to close.
1443 if (mailserver_socket_temp != -1) {
1444 cleanupSockClose(mailserver_socket_temp);
1445 mailserver_socket_temp = -1;
1449 msg = (const char *)NULL; /* sacrifice to -Wall */
1453 msg = GT_("socket");
1456 msg = GT_("missing or bad RFC822 header");
1462 msg = GT_("client/server synchronization");
1465 msg = GT_("client/server protocol");
1468 msg = GT_("lock busy on server");
1471 msg = GT_("SMTP transaction");
1474 msg = GT_("DNS lookup");
1477 report(stderr, GT_("undefined error\n"));
1480 /* no report on PS_MAXFETCH or PS_UNDEFINED or PS_AUTHFAIL */
1481 if (err==PS_SOCKET || err==PS_SYNTAX
1482 || err==PS_IOERR || err==PS_ERROR || err==PS_PROTOCOL
1483 || err==PS_LOCKBUSY || err==PS_SMTP || err==PS_DNS)
1487 if (phase == FORWARDING_WAIT || phase == LISTENER_WAIT)
1488 stem = GT_("%s error while delivering to SMTP host %s\n");
1490 stem = GT_("%s error while fetching from %s\n");
1491 report(stderr, stem, msg, ctl->server.pollname);
1495 /* execute wrapup command, if any */
1496 if (ctl->postconnect && (err = system(ctl->postconnect)))
1498 report(stderr, GT_("post-connection command failed with status %d\n"), err);
1499 if (err == PS_SUCCESS)
1503 signal(SIGALRM, alrmsave);
1504 signal(SIGPIPE, pipesave);
1508 int do_protocol(ctl, proto)
1509 /* retrieve messages from server using given protocol method table */
1510 struct query *ctl; /* parsed options with merged-in defaults */
1511 const struct method *proto; /* protocol method table */
1516 if (ctl->server.authenticate == A_KERBEROS_V4)
1518 report(stderr, GT_("Kerberos V4 support not linked.\n"));
1521 #endif /* KERBEROS_V4 */
1524 if (ctl->server.authenticate == A_KERBEROS_V5)
1526 report(stderr, GT_("Kerberos V5 support not linked.\n"));
1529 #endif /* KERBEROS_V5 */
1531 /* lacking methods, there are some options that may fail */
1534 /* check for unsupported options */
1537 GT_("Option --flush is not supported with %s\n"),
1541 else if (ctl->fetchall) {
1543 GT_("Option --all is not supported with %s\n"),
1548 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1551 GT_("Option --limit is not supported with %s\n"),
1557 * If no expunge limit or we do expunges within the driver,
1558 * then just do one session, passing in any fetchlimit.
1560 if (proto->retry || !NUM_SPECIFIED(ctl->expunge))
1561 return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
1563 * There's an expunge limit, and it isn't handled in the driver itself.
1564 * OK; do multiple sessions, each fetching a limited # of messages.
1565 * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
1566 * (if it was nonzero).
1572 int expunge = NUM_VALUE_OUT(ctl->expunge);
1573 int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
1576 if (fetchlimit > 0 && (expunge == 0 || expunge > fetchlimit - totalcount))
1577 expunge = fetchlimit - totalcount;
1578 err = do_session(ctl, proto, expunge);
1579 totalcount += expunge;
1580 if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
1582 if (err != PS_LOCKBUSY)
1584 else if (lockouts >= MAX_LOCKOUTS)
1586 else /* err == PS_LOCKBUSY */
1589 * Allow time for the server lock to release. if we
1590 * don't do this, we'll often hit a locked-mailbox
1591 * condition and fail.
1597 (err == PS_MAXFETCH || err == PS_LOCKBUSY);
1604 /* driver.c ends here */