/* * driver.c -- generic driver for mail fetch method protocols * * Copyright 1997 by Eric S. Raymond * For license terms, see the file COPYING in this directory. */ #include "config.h" #include #include #include #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #if defined(STDC_HEADERS) #include #include #endif #if defined(HAVE_UNISTD_H) #include #endif #if defined(HAVE_SYS_ITIMER_H) #include #endif #include #include #ifdef HAVE_SYS_WAIT_H #include #endif #ifdef HAVE_NET_SOCKET_H #include #endif #ifdef HESIOD #include #endif #if defined(HAVE_RES_SEARCH) || defined(HAVE_GETHOSTBYNAME) #include #include "mx.h" #endif /* defined(HAVE_RES_SEARCH) || defined(HAVE_GETHOSTBYNAME) */ #include "kerberos.h" #ifdef KERBEROS_V4 #include #endif /* KERBEROS_V4 */ #include "i18n.h" #include "socket.h" #include "fetchmail.h" #include "tunable.h" /* throw types for runtime errors */ #define THROW_TIMEOUT 1 /* server timed out */ #define THROW_SIGPIPE 2 /* SIGPIPE on stream socket */ /* magic values for the message length array */ #define MSGLEN_UNKNOWN 0 /* length unknown (0 is impossible) */ #define MSGLEN_INVALID -1 /* length passed back is invalid */ #define MSGLEN_TOOLARGE -2 /* message is too large */ #define MSGLEN_OLD -3 /* message is old */ int pass; /* how many times have we re-polled? */ int stage; /* where are we? */ int phase; /* where are we, for error-logging purposes? */ int batchcount; /* count of messages sent in current batch */ flag peek_capable; /* can we peek for better error recovery? */ int mailserver_socket_temp = -1; /* socket to free if connect timeout */ static volatile int timeoutcount = 0; /* count consecutive timeouts */ static volatile int idletimeout = 0; /* timeout occured in idle stage? */ static jmp_buf restart; int isidletimeout(void) /* last timeout occured in idle stage? */ { return idletimeout; } void resetidletimeout(void) { idletimeout = 0; } void set_timeout(int timeleft) /* reset the nonresponse-timeout */ { #if !defined(__EMX__) && !defined(__BEOS__) struct itimerval ntimeout; if (timeleft == 0) timeoutcount = 0; ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0; ntimeout.it_value.tv_sec = timeleft; ntimeout.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL); #endif } static RETSIGTYPE timeout_handler (int signal) /* handle SIGALRM signal indicating a server timeout */ { if(stage != STAGE_IDLE) { timeoutcount++; longjmp(restart, THROW_TIMEOUT); } else idletimeout = 1; } static RETSIGTYPE sigpipe_handler (int signal) /* handle SIGPIPE signal indicating a broken stream socket */ { longjmp(restart, THROW_SIGPIPE); } #define CLEANUP_TIMEOUT 60 /* maximum timeout during cleanup */ static int cleanupSockClose (int fd) /* close sockets in maximum CLEANUP_TIMEOUT seconds during cleanup */ { int scerror; SIGHANDLERTYPE alrmsave; alrmsave = set_signal_handler(SIGALRM, null_signal_handler); set_timeout(CLEANUP_TIMEOUT); scerror = SockClose(fd); set_timeout(0); set_signal_handler(SIGALRM, alrmsave); return (scerror); } #ifdef KERBEROS_V4 static int kerberos_auth(socket, canonical, principal) /* authenticate to the server host using Kerberos V4 */ int socket; /* socket to server host */ char *canonical; /* server name */ char *principal; { char * host_primary; KTEXT ticket; MSG_DAT msg_data; CREDENTIALS cred; Key_schedule schedule; int rem; char * prin_copy = (char *) NULL; char * prin = (char *) NULL; char * inst = (char *) NULL; char * realm = (char *) NULL; if (principal != (char *)NULL && *principal) { char *cp; prin = prin_copy = xstrdup(principal); for (cp = prin_copy; *cp && *cp != '.'; ++cp) ; if (*cp) { *cp++ = '\0'; inst = cp; while (*cp && *cp != '@') ++cp; if (*cp) { *cp++ = '\0'; realm = cp; } } } xalloca(ticket, KTEXT, sizeof (KTEXT_ST)); rem = (krb_sendauth (0L, socket, ticket, prin ? prin : "pop", inst ? inst : canonical, realm ? realm : ((char *) (krb_realmofhost (canonical))), ((unsigned long) 0), (&msg_data), (&cred), (schedule), ((struct sockaddr_in *) 0), ((struct sockaddr_in *) 0), "KPOPV0.1")); if (prin_copy) { free(prin_copy); } if (rem != KSUCCESS) { report(stderr, GT_("kerberos error %s\n"), (krb_get_err_text (rem))); return (PS_AUTHFAIL); } return (0); } #endif /* KERBEROS_V4 */ #ifdef KERBEROS_V5 static int kerberos5_auth(socket, canonical) /* authenticate to the server host using Kerberos V5 */ int socket; /* socket to server host */ const char *canonical; /* server name */ { krb5_error_code retval; krb5_context context; krb5_ccache ccdef; krb5_principal client = NULL, server = NULL; krb5_error *err_ret = NULL; krb5_auth_context auth_context = NULL; krb5_init_context(&context); krb5_init_ets(context); krb5_auth_con_init(context, &auth_context); if (retval = krb5_cc_default(context, &ccdef)) { report(stderr, "krb5_cc_default: %s\n", error_message(retval)); return(PS_ERROR); } if (retval = krb5_cc_get_principal(context, ccdef, &client)) { report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval)); return(PS_ERROR); } if (retval = krb5_sname_to_principal(context, canonical, "pop", KRB5_NT_UNKNOWN, &server)) { report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval)); return(PS_ERROR); } retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket, "KPOPV1.0", client, server, AP_OPTS_MUTUAL_REQUIRED, NULL, /* no data to checksum */ 0, /* no creds, use ccache instead */ ccdef, &err_ret, 0, NULL); /* don't need reply */ krb5_free_principal(context, server); krb5_free_principal(context, client); krb5_auth_con_free(context, auth_context); if (retval) { #ifdef HEIMDAL if (err_ret && err_ret->e_text) { report(stderr, GT_("krb5_sendauth: %s [server says '%*s'] \n"), error_message(retval), err_ret->e_text); #else if (err_ret && err_ret->text.length) { report(stderr, GT_("krb5_sendauth: %s [server says '%*s'] \n"), error_message(retval), err_ret->text.length, err_ret->text.data); #endif krb5_free_error(context, err_ret); } else report(stderr, "krb5_sendauth: %s\n", error_message(retval)); return(PS_ERROR); } return 0; } #endif /* KERBEROS_V5 */ static void clean_skipped_list(struct idlist **skipped_list) /* struct "idlist" contains no "prev" ptr; we must remove unused items first */ { struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL; prev = current = head = *skipped_list; if (!head) return; do { /* if item has no reference, remove it */ if (current && current->val.status.mark == 0) { if (current == head) /* remove first item (head) */ { head = current->next; if (current->id) free(current->id); free(current); prev = current = head; } else /* remove middle/last item */ { tmp = current->next; prev->next = tmp; if (current->id) free(current->id); free(current); current = tmp; } } else /* skip this item */ { prev = current; current = current->next; } } while(current); *skipped_list = head; } static void send_size_warnings(struct query *ctl) /* send warning mail with skipped msg; reset msg count when user notified */ { int size, nbr; int msg_to_send = FALSE; struct idlist *head=NULL, *current=NULL; int max_warning_poll_count; head = ctl->skipped; if (!head) return; /* don't start a notification message unless we need to */ for (current = head; current; current = current->next) if (current->val.status.num == 0 && current->val.status.mark) msg_to_send = TRUE; if (!msg_to_send) return; /* * There's no good way to recover if we can't send notification mail, * but it's not a disaster, either, since the skipped mail will not * be deleted. */ if (open_warning_by_mail(ctl, (struct msgblk *)NULL)) return; stuff_warning(ctl, GT_("Subject: Fetchmail oversized-messages warning.\n" "\n" "The following
/* getopt_long and getopt_long_only entry points for GNU getopt.
   Copyright (C) 1987, 88, 89, 90, 91, 92, 1993, 1994
	Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "getopt.h"

#if !defined (__STDC__) || !__STDC__
/* This is a separate conditional since some stdc systems
   reject `defined (const)'.  */
#ifndef const
#define const
#endif
#endif

#include <stdio.h>

/* Comment out all this code if we are using the GNU C Library, and are not
   actually compiling the library itself.  This code is part of the GNU C
   Library, but also included in many other GNU distributions.  Compiling
   and linking in this code is a waste when using the GNU C library
   (especially if it is a shared library).  Rather than having every GNU
   program understand `configure --with-gnu-libc' and omit the object files,
   it is simpler to just do this in the source for each such file.  */

#if defined (_LIBC) || !defined (__GNU_LIBRARY__)


/* This needs to come after some library #include
   to get __GNU_LIBRARY__ defined.  */
#ifdef __GNU_LIBRARY__
#include <stdlib.h>
#else
char *getenv ();
#endif

#ifndef	NULL
#define NULL 0
#endif

int
getopt_long (argc, argv, options, long_options, opt_index)
     int argc;
     char *const *argv;
     const char *options;
     const struct option *long_options;
     int *opt_index;
{
  return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
}

/* Like getopt_long, but '-' as well as '--' can indicate a long option.
   If an option that starts with '-' (not '--') doesn't match a long option,
   but does match a short option, it is parsed as a short option
   instead.  */

int
getopt_long_only (argc, argv, options, long_options, opt_index)
     int argc;
     char *const *argv;
     const char *options;
     const struct option *long_options;
     int *opt_index;
{
  return _getopt_internal (argc, argv, options, long_options, opt_index, 1);
}


#endif	/* _LIBC or not __GNU_LIBRARY__.  */

#ifdef TEST

#include <stdio.h>

int
main (argc, argv)
     int argc;
     char **argv;
{
  int c;
  int digit_optind = 0;

  while (1)
    {
      int this_option_optind = optind ? optind : 1;
      int option_index = 0;
      static struct option long_options[] =
      {
	{"add", 1, 0, 0},
	{"append", 0, 0, 0},
	{"delete", 1, 0, 0},
	{"verbose", 0, 0, 0},
	{"create", 0, 0, 0},
	{"file", 1, 0, 0},
	{0, 0, 0, 0}
      };

      c = getopt_long (argc, argv, "abc:d:0123456789",
		       long_options, &option_index);
      if (c == EOF)
	break;

      switch (c)
	{
	case 0:
	  printf ("option %s", long_options[option_index].name);
	  if (optarg)
	    printf (" with arg %s", optarg);
	  printf ("\n");
	  break;

	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	  if (digit_optind != 0 && digit_optind != this_option_optind)
	    printf ("digits occur in two different argv-elements.\n");
	  digit_optind = this_option_optind;
	  printf ("option %c\n", c);
	  break;

	case 'a':
	  printf ("option a\n");
	  break;

	case 'b':
	  printf ("option b\n");
	  break;

	case 'c':
	  printf ("option c with value `%s'\n", optarg);
	  break;

	case 'd':
	  printf ("option d with value `%s'\n", optarg);
	  break;

	case '?':
	  break;

	default:
	  printf ("?? getopt returned character code 0%o ??\n", c);
	}
    }

  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
	printf ("%s ", argv[optind++]);
      printf ("\n");
    }

  exit (0);
}

#endif /* TEST */
ns will be sent until service\n\ is restored.")); else stuff_warning(ctl, GT_("\ The attempt to get authorization failed.\n\ This probably means your password is invalid, but some servers have\n\ other failure modes that fetchmail cannot distinguish from this\n\ because they don't send useful error messages on login failure.\n\ \n\ The fetchmail daemon will continue running and attempt to connect\n\ at each cycle. No future notifications will be sent until service\n\ is restored.")); close_warning_by_mail(ctl, (struct msgblk *)NULL); } } else if (err == PS_REPOLL) { if (outlevel >= O_VERBOSE) report(stderr, GT_("Repoll immediately on %s@%s\n"), ctl->remotename, ctl->server.truename); } else report(stderr, GT_("Unknown login or authentication error on %s@%s\n"), ctl->remotename, ctl->server.truename); goto cleanUp; } else { /* * This connection has given us authorization at least once. * * There are dodgy server (clubinternet.fr for example) that * give spurious authorization failures on patently good * account/password details, then 5 minutes later let you in! * * This is meant to build in some tolerance of such nasty bits * of work. */ ctl->wehaveauthed = 1; /*if (ctl->authfailcount >= 3)*/ if (ctl->wehavesentauthnote) { ctl->wehavesentauthnote = 0; report(stderr, GT_("Authorization OK on %s@%s\n"), ctl->remotename, ctl->server.truename); if (!open_warning_by_mail(ctl, (struct msgblk *)NULL)) { stuff_warning(ctl, GT_("Subject: fetchmail authentication OK on %s@%s\n"), ctl->remotename, ctl->server.truename); stuff_warning(ctl, GT_("Fetchmail was able to log into %s@%s.\n"), ctl->remotename, ctl->server.truename); stuff_warning(ctl, GT_("Service has been restored.\n")); close_warning_by_mail(ctl, (struct msgblk *)NULL); } } /* * Reporting only after the first three * consecutive failures, or ten consecutive * failures after we have managed to get * authorization. */ ctl->authfailcount = 0; } } ctl->errcount = fetches = 0; /* now iterate over each folder selected */ for (idp = ctl->mailboxes; idp; idp = idp->next) { pass = 0; do { dispatches = 0; ++pass; /* reset timeout, in case we did an IDLE */ mytimeout = ctl->server.timeout; if (outlevel >= O_DEBUG) { if (idp->id) report(stdout, GT_("selecting or re-polling folder %s\n"), idp->id); else report(stdout, GT_("selecting or re-polling default folder\n")); } /* compute # of messages and number of new messages waiting */ stage = STAGE_GETRANGE; err = (ctl->server.base_protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &new, &bytes); if (err != 0) goto cleanUp; /* show user how many messages we downloaded */ if (idp->id) #ifdef HAVE_SNPRINTF (void) snprintf(buf, sizeof(buf), #else (void) sprintf(buf, #endif /* HAVE_SNPRINTF */ GT_("%s at %s (folder %s)"), ctl->remotename, ctl->server.pollname, idp->id); else #ifdef HAVE_SNPRINTF (void) snprintf(buf, sizeof(buf), #else (void) sprintf(buf, #endif /* HAVE_SNPRINTF */ GT_("%s at %s"), ctl->remotename, ctl->server.pollname); if (outlevel > O_SILENT) { if (count == -1) /* only used for ETRN */ report(stdout, GT_("Polling %s\n"), ctl->server.truename); else if (count != 0) { if (new != -1 && (count - new) > 0) report_build(stdout, GT_("%d %s (%d %s) for %s"), count, count > 1 ? GT_("messages") : GT_("message"), count-new, GT_("seen"), buf); else report_build(stdout, GT_("%d %s for %s"), count, count > 1 ? GT_("messages") : GT_("message"), buf); if (bytes == -1) report_complete(stdout, ".\n"); else report_complete(stdout, GT_(" (%d octets).\n"), bytes); } else { /* these are pointless in normal daemon mode */ if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE)) report(stdout, GT_("No mail for %s\n"), buf); } } /* very important, this is where we leave the do loop */ if (count == 0) break; if (check_only) { if (new == -1 || ctl->fetchall) new = count; fetches = new; /* set error status correctly */ /* * There used to be a `goto noerror' here, but this * prevented checking of multiple folders. This * comment is a reminder in case I introduced some * subtle bug by removing it... */ } else if (count > 0) { int i; /* * Don't trust the message count passed by the server. * Without this check, it might be possible to do a * DNS-spoofing attack that would pass back a ridiculous * count, and allocate a malloc area that would overlap * a portion of the stack. */ if (count > INT_MAX/sizeof(int)) { report(stderr, GT_("bogus message count!")); return(PS_PROTOCOL); } /* * We need the size of each message before it's * loaded in order to pass it to the ESMTP SIZE * option. If the protocol has a getsizes method, * we presume this means it doesn't get reliable * sizes from message fetch responses. * * If the protocol supports getting sizes of subset of * messages, we skip this step now. */ if (proto->getsizes && !(proto->getpartialsizes && NUM_NONZERO(ctl->fetchsizelimit))) { xalloca(msgsizes, int *, sizeof(int) * count); for (i = 0; i < count; i++) msgsizes[i] = 0; stage = STAGE_GETSIZES; err = (proto->getsizes)(mailserver_socket, count, msgsizes); if (err != 0) goto cleanUp; if (bytes == -1) { bytes = 0; for (i = 0; i < count; i++) bytes += msgsizes[i]; } } /* read, forward, and delete messages */ stage = STAGE_FETCH; /* fetch in lockstep mode */ err = fetch_messages(mailserver_socket, ctl, count, msgsizes, maxfetch, &fetches, &dispatches, &deletions); if (err) goto cleanUp; if (!check_only && ctl->skipped && run.poll_interval > 0 && !nodetach) { clean_skipped_list(&ctl->skipped); send_size_warnings(ctl); } } } while /* * Only re-poll if we either had some actual forwards and * either allowed deletions and had no errors. * Otherwise it is far too easy to get into infinite loops. */ (dispatches && ctl->server.base_protocol->retry && !ctl->keep && !ctl->errcount); } /* no_error: */ /* ordinary termination with no errors -- officially log out */ err = (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl); /* * Hmmmm...arguably this would be incorrect if we had fetches but * no dispatches (due to oversized messages, etc.) */ if (err == 0) err = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL; cleanupSockClose(mailserver_socket); goto closeUp; cleanUp: /* we only get here on error */ if (err != 0 && err != PS_SOCKET && err != PS_REPOLL) { stage = STAGE_LOGOUT; (ctl->server.base_protocol->logout_cmd)(mailserver_socket, ctl); } /* try to clean up all streams */ release_sink(ctl); smtp_close(ctl, 0); if (mailserver_socket != -1) { cleanupSockClose(mailserver_socket); mailserver_socket = -1; } /* If there was a connect timeout, the socket should be closed. * mailserver_socket_temp contains the socket to close. */ if (mailserver_socket_temp != -1) { cleanupSockClose(mailserver_socket_temp); mailserver_socket_temp = -1; } } msg = (const char *)NULL; /* sacrifice to -Wall */ switch (err) { case PS_SOCKET: msg = GT_("socket"); break; case PS_SYNTAX: msg = GT_("missing or bad RFC822 header"); break; case PS_IOERR: msg = GT_("MDA"); break; case PS_ERROR: msg = GT_("client/server synchronization"); break; case PS_PROTOCOL: msg = GT_("client/server protocol"); break; case PS_LOCKBUSY: msg = GT_("lock busy on server"); break; case PS_SMTP: msg = GT_("SMTP transaction"); break; case PS_DNS: msg = GT_("DNS lookup"); break; case PS_UNDEFINED: report(stderr, GT_("undefined error\n")); break; } /* no report on PS_MAXFETCH or PS_UNDEFINED or PS_AUTHFAIL */ if (err==PS_SOCKET || err==PS_SYNTAX || err==PS_IOERR || err==PS_ERROR || err==PS_PROTOCOL || err==PS_LOCKBUSY || err==PS_SMTP || err==PS_DNS) { char *stem; if (phase == FORWARDING_WAIT || phase == LISTENER_WAIT) stem = GT_("%s error while delivering to SMTP host %s\n"); else stem = GT_("%s error while fetching from %s\n"); report(stderr, stem, msg, ctl->server.pollname); } closeUp: /* execute wrapup command, if any */ if (ctl->postconnect && (err = system(ctl->postconnect))) { report(stderr, GT_("post-connection command failed with status %d\n"), err); if (err == PS_SUCCESS) err = PS_SYNTAX; } set_timeout(0); /* cancel any pending alarm */ set_signal_handler(SIGALRM, alrmsave); set_signal_handler(SIGPIPE, pipesave); return(err); } int do_protocol(ctl, proto) /* retrieve messages from server using given protocol method table */ struct query *ctl; /* parsed options with merged-in defaults */ const struct method *proto; /* protocol method table */ { int err; #ifndef KERBEROS_V4 if (ctl->server.authenticate == A_KERBEROS_V4) { report(stderr, GT_("Kerberos V4 support not linked.\n")); return(PS_ERROR); } #endif /* KERBEROS_V4 */ #ifndef KERBEROS_V5 if (ctl->server.authenticate == A_KERBEROS_V5) { report(stderr, GT_("Kerberos V5 support not linked.\n")); return(PS_ERROR); } #endif /* KERBEROS_V5 */ /* lacking methods, there are some options that may fail */ if (!proto->is_old) { /* check for unsupported options */ if (ctl->flush) { report(stderr, GT_("Option --flush is not supported with %s\n"), proto->name); return(PS_SYNTAX); } else if (ctl->fetchall) { report(stderr, GT_("Option --all is not supported with %s\n"), proto->name); return(PS_SYNTAX); } } if (!proto->getsizes && NUM_SPECIFIED(ctl->limit)) { report(stderr, GT_("Option --limit is not supported with %s\n"), proto->name); return(PS_SYNTAX); } /* * If no expunge limit or we do expunges within the driver, * then just do one session, passing in any fetchlimit. */ if ((ctl->keep && !ctl->flush) || proto->retry || !NUM_SPECIFIED(ctl->expunge)) return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit))); /* * There's an expunge limit, and it isn't handled in the driver itself. * OK; do multiple sessions, each fetching a limited # of messages. * Stop if the total count of retrieved messages exceeds ctl->fetchlimit * (if it was nonzero). */ else { int totalcount = 0; int lockouts = 0; int expunge = NUM_VALUE_OUT(ctl->expunge); int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit); do { if (fetchlimit > 0 && (expunge == 0 || expunge > fetchlimit - totalcount)) expunge = fetchlimit - totalcount; err = do_session(ctl, proto, expunge); totalcount += expunge; if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit) break; if (err != PS_LOCKBUSY) lockouts = 0; else if (lockouts >= MAX_LOCKOUTS) break; else /* err == PS_LOCKBUSY */ { /* * Allow time for the server lock to release. if we * don't do this, we'll often hit a locked-mailbox * condition and fail. */ lockouts++; sleep(3); } } while (err == PS_MAXFETCH || err == PS_LOCKBUSY); return(err); } } /* driver.c ends here */