]> Pileus Git - ~andy/fetchmail/blob - fetchmail.c
Spambounce patch.
[~andy/fetchmail] / fetchmail.c
1 /*
2  * fetchmail.c -- main driver module for fetchmail
3  *
4  * For license terms, see the file COPYING in this directory.
5  */
6 #include "config.h"
7
8 #include <stdio.h>
9 #if defined(STDC_HEADERS)
10 #include <stdlib.h>
11 #endif
12 #if defined(HAVE_UNISTD_H)
13 #include <unistd.h>
14 #endif
15 #include <fcntl.h>
16 #include <string.h>
17 #include <signal.h>
18 #if defined(HAVE_SYSLOG)
19 #include <syslog.h>
20 #endif
21 #include <pwd.h>
22 #ifdef __FreeBSD__
23 #include <grp.h>
24 #endif
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>   /* needed for Sun 4.1.2 */
29 #ifdef HAVE_SETRLIMIT
30 #include <sys/resource.h>
31 #endif /* HAVE_SETRLIMIT */
32 #include <sys/utsname.h>
33
34 #ifdef HAVE_NET_SOCKET_H
35 #include <net/socket.h>
36 #endif
37 #ifdef HAVE_GETHOSTBYNAME
38 #include <netdb.h>
39 #endif /* HAVE_GETHOSTBYNAME */
40
41 #ifdef HESIOD
42 #include <hesiod.h>
43 #endif
44
45 #include "getopt.h"
46 #include "fetchmail.h"
47 #include "socket.h"
48 #include "tunable.h"
49 #include "smtp.h"
50 #include "netrc.h"
51 #include "i18n.h"
52
53 #ifndef ENETUNREACH
54 #define ENETUNREACH   128       /* Interactive doesn't know this */
55 #endif /* ENETUNREACH */
56
57 /* prototypes for internal functions */
58 static int load_params(int, char **, int);
59 static void dump_params (struct runctl *runp, struct query *, flag implicit);
60 static int query_host(struct query *);
61
62 /* controls the detail level of status/progress messages written to stderr */
63 int outlevel;               /* see the O_.* constants above */
64
65 /* miscellaneous global controls */
66 struct runctl run;          /* global controls for this run */
67 flag nodetach;              /* if TRUE, don't detach daemon process */
68 flag quitmode;              /* if --quit was set */
69 flag check_only;            /* if --probe was set */
70 flag versioninfo;           /* emit only version info */
71 char *user;                 /* the name of the invoking user */
72 char *home;                 /* invoking user's home directory */
73 char *fmhome;               /* fetchmail's home directory */
74 char *program_name;         /* the name to prefix error messages with */
75 flag configdump;            /* dump control blocks for configurator */
76 const char *fetchmailhost;  /* either `localhost' or the host's FQDN */
77
78 #if NET_SECURITY
79 void *request = NULL;
80 int requestlen = 0;
81 #endif /* NET_SECURITY */
82
83 static char *lockfile;          /* name of lockfile */
84 static int lock_acquired;       /* have we acquired a lock */
85 static int querystatus;         /* status of query */
86 static int successes;           /* count number of successful polls */
87 static int activecount;         /* count number of active entries */
88 static struct runctl cmd_run;   /* global options set from command line */
89 static time_t parsetime;        /* time of last parse */
90
91 static void terminate_run(int);
92 static void terminate_poll(int);
93
94 #ifdef HAVE_ON_EXIT
95 static void unlockit(int n, void *p)
96 #else
97 static void unlockit(void)
98 #endif
99 /* must-do actions for exit (but we can't count on being able to do malloc) */
100 {
101     if (lockfile && lock_acquired)
102         unlink(lockfile);
103 }
104
105 #if defined(__FreeBSD__) && defined(__FreeBSD_USE_KVM)
106 /* drop SGID kmem privileage until we need it */
107 static void dropprivs(void)
108 {
109     struct group *gr;
110     gid_t        egid;
111     gid_t        rgid;
112     
113     egid = getegid();
114     rgid = getgid();
115     gr = getgrgid(egid);
116     
117     if (gr && !strcmp(gr->gr_name, "kmem"))
118     {
119         extern void interface_set_gids(gid_t egid, gid_t rgid);
120         interface_set_gids(egid, rgid);
121         setegid(rgid);
122     }
123 }
124 #endif
125
126 #if defined(HAVE_SETLOCALE) && defined(ENABLE_NLS) && defined(HAVE_STRFTIME)
127 #include <time.h>
128 #include <locale.h>
129 static char *timestamp (void)
130 {
131     time_t      now;
132     static char buf[60];
133
134     time (&now);
135     setlocale (LC_TIME, "");
136     strftime (buf, sizeof (buf), "%c", localtime(&now));
137     setlocale (LC_TIME, "C");
138     return (buf);
139 }
140 #else
141 #define timestamp rfc822timestamp
142 #endif
143
144 int main(int argc, char **argv)
145 {
146     int st, bkgd = FALSE;
147     int parsestatus, implicitmode = FALSE;
148     FILE        *lockfp;
149     struct query *ctl;
150     netrc_entry *netrc_list;
151     char *netrc_file, *tmpbuf;
152     pid_t pid;
153     int lastsig = 0;
154
155 #if defined(__FreeBSD__) && defined(__FreeBSD_USE_KVM)
156     dropprivs();
157 #endif
158
159     envquery(argc, argv);
160 #ifdef ENABLE_NLS
161     bindtextdomain(PACKAGE, LOCALEDIR);
162     textdomain(PACKAGE);
163 #endif
164
165     /*
166      * Note: because we can't initialize reporting before we  know whether
167      * syslog is supposed to be on, this message will go to stdout and
168      * be lost when running in background.
169      */
170     if (outlevel >= O_VERBOSE)
171     {
172         int i;
173
174         report(stdout, _("fetchmail: invoked with"));
175         for (i = 0; i < argc; i++)
176             report(stdout, " %s", argv[i]);
177         report(stdout, "\n");
178     }
179
180 #define IDFILE_NAME     ".fetchids"
181     run.idfile = (char *) xmalloc(strlen(fmhome)+sizeof(IDFILE_NAME)+2);
182     strcpy(run.idfile, fmhome);
183     strcat(run.idfile, "/");
184     strcat(run.idfile, IDFILE_NAME);
185   
186     outlevel = O_NORMAL;
187
188     /*
189      * We used to arrange for the lockfile to be removed on exit close
190      * to where the lock was asserted.  Now we need to do it here, because
191      * we might have re-executed in background with an existing lockfile
192      * as the result of a changed rcfile (see the code near the execvp(3)
193      * call near the beginning of the polling loop for details).  We want
194      * to be sure the lockfile gets nuked on any error exit, basically.
195      */
196 #ifdef HAVE_ATEXIT
197     atexit(unlockit);
198 #endif
199 #ifdef HAVE_ON_EXIT
200     on_exit(unlockit, (char *)NULL);
201 #endif
202
203     if ((parsestatus = parsecmdline(argc,argv, &cmd_run, &cmd_opts)) < 0)
204         exit(PS_SYNTAX);
205
206     if (versioninfo)
207     {
208         printf(_("This is fetchmail release %s"), VERSION);
209 #ifdef POP2_ENABLE
210         printf("+POP2");
211 #endif /* POP2_ENABLE */
212 #ifndef POP3_ENABLE
213         printf("-POP3");
214 #endif /* POP3_ENABLE */
215 #ifndef IMAP_ENABLE
216         printf("-IMAP");
217 #endif /* IMAP_ENABLE */
218 #ifdef GSSAPI
219         printf("+IMAP-GSS");
220 #endif /* GSSAPI */
221 #ifdef RPA_ENABLE
222         printf("+RPA");
223 #endif /* RPA_ENABLE */
224 #ifdef NTLM_ENABLE
225         printf("+NTLM");
226 #endif /* NTLM_ENABLE */
227 #ifdef SDPS_ENABLE
228         printf("+SDPS");
229 #endif /* SDPS_ENABLE */
230 #ifndef ETRN_ENABLE
231         printf("-ETRN");
232 #endif /* ETRN_ENABLE */
233 #ifdef SSL_ENABLE
234         printf("+SSL");
235 #endif
236 #if OPIE_ENABLE
237         printf("+OPIE");
238 #endif /* OPIE_ENABLE */
239 #if INET6_ENABLE
240         printf("+INET6");
241 #endif /* INET6_ENABLE */
242 #if NET_SECURITY
243         printf("+NETSEC");
244 #endif /* NET_SECURITY */
245 #ifdef HAVE_SOCKS
246         printf("+SOCKS");
247 #endif /* HAVE_SOCKS */
248 #if ENABLE_NLS
249         printf("+NLS");
250 #endif /* ENABLE_NLS */
251         putchar('\n');
252         fflush(stdout);
253
254         /* this is an attempt to help remote debugging */
255         system("uname -a");
256     }
257
258     /* avoid parsing the config file if all we're doing is killing a daemon */ 
259     if (!(quitmode && argc == 2))
260         implicitmode = load_params(argc, argv, optind);
261
262 #if defined(HAVE_SYSLOG)
263     /* logging should be set up early in case we were restarted from exec */
264     if (run.use_syslog)
265     {
266 #if defined(LOG_MAIL)
267         openlog(program_name, LOG_PID, LOG_MAIL);
268 #else
269         /* Assume BSD4.2 openlog with two arguments */
270         openlog(program_name, LOG_PID);
271 #endif
272         report_init(-1);
273     }
274     else
275 #endif
276         report_init((run.poll_interval == 0 || nodetach) && !run.logfile);
277
278     /* set up to do lock protocol */
279 #define FETCHMAIL_PIDFILE       "fetchmail.pid"
280     if (!getuid()) {
281         xalloca(tmpbuf, char *,
282                 sizeof(PID_DIR) + sizeof(FETCHMAIL_PIDFILE));
283         sprintf(tmpbuf, "%s/%s", PID_DIR, FETCHMAIL_PIDFILE);
284     } else {
285         xalloca(tmpbuf, char *, strlen(fmhome) + sizeof(FETCHMAIL_PIDFILE) + 2);
286         strcpy(tmpbuf, fmhome);
287         strcat(tmpbuf, "/");
288         if (fmhome == home)
289            strcat(tmpbuf, ".");
290         strcat(tmpbuf, FETCHMAIL_PIDFILE);
291     }
292 #undef FETCHMAIL_PIDFILE
293
294 #ifdef HAVE_SETRLIMIT
295     /*
296      * Before getting passwords, disable core dumps unless -v -d0 mode is on.
297      * Core dumps could otherwise contain passwords to be scavenged by a
298      * cracker.
299      */
300     if (outlevel < O_VERBOSE || run.poll_interval > 0)
301     {
302         struct rlimit corelimit;
303         corelimit.rlim_cur = 0;
304         corelimit.rlim_max = 0;
305         setrlimit(RLIMIT_CORE, &corelimit);
306     }
307 #endif /* HAVE_SETRLIMIT */
308
309 #define NETRC_FILE      ".netrc"
310     /* parse the ~/.netrc file (if present) for future password lookups. */
311     xalloca(netrc_file, char *, strlen(home) + sizeof(NETRC_FILE) + 2);
312     strcpy (netrc_file, home);
313     strcat (netrc_file, "/");
314     strcat (netrc_file, NETRC_FILE);
315     netrc_list = parse_netrc(netrc_file);
316 #undef NETRC_FILE
317
318     /* pick up passwords where we can */ 
319     for (ctl = querylist; ctl; ctl = ctl->next)
320     {
321         if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
322         {
323             if (ctl->server.preauthenticate == A_KERBEROS_V4 ||
324                         ctl->server.preauthenticate == A_KERBEROS_V5 ||
325                         ctl->server.preauthenticate == A_SSH ||
326 #ifdef GSSAPI
327                         ctl->server.protocol == P_IMAP_GSS ||
328 #endif /* GSSAPI */
329                         ctl->server.protocol == P_IMAP_K4)
330                 /* Server won't care what the password is, but there
331                    must be some non-null string here.  */
332                 ctl->password = ctl->remotename;
333             else
334             {
335                 netrc_entry *p;
336
337                 /* look up the pollname and account in the .netrc file. */
338                 p = search_netrc(netrc_list,
339                                  ctl->server.pollname, ctl->remotename);
340                 /* if we find a matching entry with a password, use it */
341                 if (p && p->password)
342                     ctl->password = xstrdup(p->password);
343
344                 /* otherwise try with "via" name if there is one */
345                 else if (ctl->server.via)
346                 {
347                     p = search_netrc(netrc_list, 
348                                      ctl->server.via, ctl->remotename);
349                     if (p && p->password)
350                         ctl->password = xstrdup(p->password);
351                 }
352             }
353         }
354     }
355
356     /* perhaps we just want to check options? */
357     if (versioninfo)
358     {
359         int havercfile = access(rcfile, 0);
360
361         printf(_("Taking options from command line%s%s\n"),
362                                 havercfile ? "" :  _(" and "),
363                                 havercfile ? "" : rcfile);
364
365         if (outlevel >= O_VERBOSE)
366             printf(_("Lockfile at %s\n"), tmpbuf);
367
368         if (querylist == NULL)
369             fprintf(stderr,
370                     _("No mailservers set up -- perhaps %s is missing?\n"),
371                     rcfile);
372         else
373             dump_params(&run, querylist, implicitmode);
374         exit(0);
375     }
376
377     /* dump options as a Python dictionary, for configurator use */
378     if (configdump)
379     {
380         dump_config(&run, querylist);
381         exit(0);
382     }
383
384     /* check for another fetchmail running concurrently */
385     pid = -1;
386     if ((lockfile = (char *) malloc(strlen(tmpbuf) + 1)) == NULL)
387     {
388         report(stderr,_("fetchmail: cannot allocate memory for lock name.\n"));
389         exit(PS_EXCLUDE);
390     }
391     else
392         (void) strcpy(lockfile, tmpbuf);
393     if ((lockfp = fopen(lockfile, "r")) != NULL )
394     {
395         bkgd = (fscanf(lockfp,"%d %d", &pid, &st) == 2);
396
397         if (kill(pid, 0) == -1) {
398             fprintf(stderr,_("fetchmail: removing stale lockfile\n"));
399             pid = -1;
400             bkgd = FALSE;
401             unlink(lockfile);
402         }
403         fclose(lockfp); /* not checking should be safe, file mode was "r" */
404     }
405
406     /* if no mail servers listed and nothing in background, we're done */
407     if (!(quitmode && argc == 2) && pid == -1 && querylist == NULL) {
408         (void)fputs(_("fetchmail: no mailservers have been specified.\n"),stderr);
409         exit(PS_SYNTAX);
410     }
411
412     /* perhaps user asked us to kill the other fetchmail */
413     if (quitmode)
414     {
415         if (pid == -1) 
416         {
417             fprintf(stderr,_("fetchmail: no other fetchmail is running\n"));
418             if (argc == 2)
419                 exit(PS_EXCLUDE);
420         }
421         else if (kill(pid, SIGTERM) < 0)
422         {
423             fprintf(stderr,_("fetchmail: error killing %s fetchmail at %d; bailing out.\n"),
424                     bkgd ? _("background") : _("foreground"), pid);
425             exit(PS_EXCLUDE);
426         }
427         else
428         {
429             fprintf(stderr,_("fetchmail: %s fetchmail at %d killed.\n"),
430                     bkgd ? _("background") : _("foreground"), pid);
431             unlink(lockfile);
432             if (argc == 2)
433                 exit(0);
434             else
435                 pid = -1; 
436         }
437     }
438
439     /* another fetchmail is running -- wake it up or die */
440     if (pid != -1)
441     {
442         if (check_only)
443         {
444             fprintf(stderr,
445                  _("fetchmail: can't check mail while another fetchmail to same host is running.\n"));
446             return(PS_EXCLUDE);
447         }
448         else if (!implicitmode)
449         {
450             fprintf(stderr,
451                  _("fetchmail: can't poll specified hosts with another fetchmail running at %d.\n"),
452                  pid);
453                 return(PS_EXCLUDE);
454         }
455         else if (!bkgd)
456         {
457             fprintf(stderr,
458                  _("fetchmail: another foreground fetchmail is running at %d.\n"),
459                  pid);
460                 return(PS_EXCLUDE);
461         }
462         else if (argc > 1)
463         {
464             /* this test enables re-execing on a changed rcfile */
465             if (getpid() == pid)
466                 lock_acquired = TRUE;
467             else
468             {
469                 fprintf(stderr,
470                         _("fetchmail: can't accept options while a background fetchmail is running.\n"));
471                 return(PS_EXCLUDE);
472             }
473         }
474         else if (kill(pid, SIGUSR1) == 0)
475         {
476             fprintf(stderr,
477                     _("fetchmail: background fetchmail at %d awakened.\n"),
478                     pid);
479             return(0);
480         }
481         else
482         {
483             /*
484              * Should never happen -- possible only if a background fetchmail
485              * croaks after the first kill probe above but before the
486              * SIGUSR1/SIGHUP transmission.
487              */
488             fprintf(stderr,
489                     _("fetchmail: elder sibling at %d died mysteriously.\n"),
490                     pid);
491             return(PS_UNDEFINED);
492         }
493     }
494
495     /* pick up interactively any passwords we need but don't have */ 
496     for (ctl = querylist; ctl; ctl = ctl->next)
497     {
498         if (ctl->active && !(implicitmode && ctl->server.skip)
499                 && ctl->server.protocol != P_ETRN 
500                 && ctl->server.protocol != P_IMAP_K4
501 #ifdef GSSAPI
502                 && ctl->server.protocol != P_IMAP_GSS
503 #endif /* GSSAPI */
504                 && !ctl->password)
505         {
506             if (!isatty(0))
507             {
508                 fprintf(stderr,
509                         _("fetchmail: can't find a password for %s@%s.\n"),
510                         ctl->remotename, ctl->server.pollname);
511                 return(PS_AUTHFAIL);
512             }
513             else
514             {
515                 char* password_prompt = _("Enter password for %s@%s: ");
516
517                 xalloca(tmpbuf, char *, strlen(password_prompt) +
518                         strlen(ctl->remotename) +
519                         strlen(ctl->server.pollname) + 1);
520                 (void) sprintf(tmpbuf, password_prompt,
521                                ctl->remotename, ctl->server.pollname);
522                 ctl->password = xstrdup((char *)fm_getpassword(tmpbuf));
523             }
524         }
525     }
526
527     /*
528      * Time to initiate the SOCKS library (this is not mandatory: it just
529      * registers the correct application name for logging purpose. If you
530      * have some problem, comment out these lines).
531      */
532 #ifdef HAVE_SOCKS
533     SOCKSinit("fetchmail");
534 #endif /* HAVE_SOCKS */
535
536     /*
537      * Maybe time to go to demon mode...
538      */
539     if (run.poll_interval)
540     {
541         if (!nodetach)
542             daemonize(run.logfile, terminate_run);
543         report(stdout, _("starting fetchmail %s daemon \n"), VERSION);
544
545         /*
546          * We'll set up a handler for these when we're sleeping,
547          * but ignore them otherwise so as not to interrupt a poll.
548          */
549         signal(SIGUSR1, SIG_IGN);
550         if (run.poll_interval && !getuid())
551             signal(SIGHUP, SIG_IGN);
552     }
553     else if (run.logfile && access(run.logfile, F_OK) == 0)
554     {
555         freopen(run.logfile, "a", stdout);
556         freopen(run.logfile, "a", stderr);
557     }
558
559
560 #ifdef linux
561     interface_init();
562 #endif /* linux */
563
564     /* beyond here we don't want more than one fetchmail running per user */
565     umask(0077);
566     signal(SIGABRT, terminate_run);
567     signal(SIGINT, terminate_run);
568     signal(SIGTERM, terminate_run);
569     signal(SIGALRM, terminate_run);
570     signal(SIGPIPE, terminate_run);
571     signal(SIGQUIT, terminate_run);
572
573     /* here's the exclusion lock */
574 #ifndef O_SYNC
575 #define O_SYNC  0       /* use it if we have it */
576 #endif
577     if ((st = open(lockfile, O_WRONLY|O_CREAT|O_EXCL|O_SYNC, 0666)) != -1)
578     {
579         sprintf(tmpbuf,"%d", getpid());
580         write(st, tmpbuf, strlen(tmpbuf));
581         if (run.poll_interval)
582         {
583             sprintf(tmpbuf," %d", run.poll_interval);
584             write(st, tmpbuf, strlen(tmpbuf));
585         }
586         close(st);      /* should be safe, fd was opened with O_SYNC */
587         lock_acquired = TRUE;
588     }
589     else
590     {
591         fprintf(stderr, _("fetchmail: lock creation failed.\n"));
592         return(PS_EXCLUDE);
593     }
594
595     /*
596      * Query all hosts. If there's only one, the error return will
597      * reflect the status of that transaction.
598      */
599     do {
600         /* 
601          * Check to see if the rcfile has been touched.  If so,
602          * re-exec so the file will be reread.  Doing it this way
603          * avoids all the complications of trying to deallocate the
604          * in-core control structures -- and the potential memory
605          * leaks...
606          */
607         struct stat     rcstat;
608
609         if (stat(rcfile, &rcstat) == -1)
610         {
611             if (errno != ENOENT)
612                 report(stderr, 
613                        _("couldn't time-check %s (error %d)\n"),
614                        rcfile, errno);
615         }
616         else if (rcstat.st_mtime > parsetime)
617         {
618             report(stdout, _("restarting fetchmail (%s changed)\n"), rcfile);
619             execvp("fetchmail", argv);
620             report(stderr, _("attempt to re-exec fetchmail failed\n"));
621         }
622
623 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
624         /*
625          * This was an efficiency hack that backfired.  The theory
626          * was that using TCP/IP for DNS queries would get us better
627          * reliability and shave off some per-UDP-packet costs.
628          * Unfortunately it interacted badly with diald, which effectively 
629          * filters out DNS queries over TCP/IP for reasons having to do
630          * with some obscure kernel problem involving bootstrapping of
631          * dynamically-addressed links.  I don't understand this mess
632          * and don't want to, so it's "See ya!" to this hack.
633          */
634         sethostent(TRUE);       /* use TCP/IP for mailserver queries */
635 #endif /* HAVE_RES_SEARCH */
636
637         activecount = 0;
638         batchcount = 0;
639         for (ctl = querylist; ctl; ctl = ctl->next)
640             if (ctl->active)
641             {
642                 activecount++;
643                 if (!(implicitmode && ctl->server.skip))
644                 {
645                     if (ctl->wedged)
646                     {
647                         report(stderr, 
648                                _("poll of %s skipped (failed authentication or too many timeouts)\n"),
649                                ctl->server.pollname);
650                         continue;
651                     }
652
653                     /* check skip interval first so that it counts all polls */
654                     if (run.poll_interval && ctl->server.interval) 
655                     {
656                         if (ctl->server.poll_count++ % ctl->server.interval) 
657                         {
658                             if (outlevel >= O_VERBOSE)
659                                 report(stdout,
660                                        _("interval not reached, not querying %s\n"),
661                                        ctl->server.pollname);
662                             continue;
663                         }
664                     }
665
666 #if (defined(linux) && !INET6_ENABLE) || defined(__FreeBSD__)
667                     /*
668                      * Don't do monitoring if we were woken by a signal.
669                      * Note that interface_approve() does its own error logging.
670                      */
671                     if (!interface_approve(&ctl->server, !lastsig))
672                         continue;
673 #endif /* (defined(linux) && !INET6_ENABLE) || defined(__FreeBSD__) */
674
675                     querystatus = query_host(ctl);
676
677 #ifdef POP3_ENABLE
678                     /* leave the UIDL state alone if there have been any errors */
679                     if (!check_only &&
680                                 ((querystatus==PS_SUCCESS) || (querystatus==PS_NOMAIL) || (querystatus==PS_MAXFETCH)))
681                         uid_swap_lists(ctl);
682 #endif  /* POP3_ENABLE */
683
684                     if (querystatus == PS_SUCCESS)
685                         successes++;
686                     else if (!check_only && 
687                              ((querystatus!=PS_NOMAIL) || (outlevel==O_DEBUG)))
688                         switch(querystatus)
689                         {
690                         case PS_SUCCESS:
691                             report(stdout,_("Query status=0 (SUCCESS)\n"));break;
692                         case PS_NOMAIL: 
693                             report(stdout,_("Query status=1 (NOMAIL)\n")); break;
694                         case PS_SOCKET:
695                             report(stdout,_("Query status=2 (SOCKET)\n")); break;
696                         case PS_AUTHFAIL:
697                             report(stdout,_("Query status=3 (AUTHFAIL)\n"));break;
698                         case PS_PROTOCOL:
699                             report(stdout,_("Query status=4 (PROTOCOL)\n"));break;
700                         case PS_SYNTAX:
701                             report(stdout,_("Query status=5 (SYNTAX)\n")); break;
702                         case PS_IOERR:
703                             report(stdout,_("Query status=6 (IOERR)\n"));  break;
704                         case PS_ERROR:
705                             report(stdout,_("Query status=7 (ERROR)\n"));  break;
706                         case PS_EXCLUDE:
707                             report(stdout,_("Query status=8 (EXCLUDE)\n")); break;
708                         case PS_LOCKBUSY:
709                             report(stdout,_("Query status=9 (LOCKBUSY)\n"));break;
710                         case PS_SMTP:
711                             report(stdout,_("Query status=10 (SMTP)\n")); break;
712                         case PS_DNS:
713                             report(stdout,_("Query status=11 (DNS)\n")); break;
714                         case PS_BSMTP:
715                             report(stdout,_("Query status=12 (BSMTP)\n")); break;
716                         case PS_MAXFETCH:
717                             report(stdout,_("Query status=13 (MAXFETCH)\n"));break;
718                         default:
719                             report(stdout,_("Query status=%d\n"),querystatus);
720                             break;
721                         }
722
723 #if (defined(linux) && !INET6_ENABLE) || defined (__FreeBSD__)
724                     if (ctl->server.monitor)
725                     {
726                         /*
727                          * Allow some time for the link to quiesce.  One
728                          * second is usually sufficient, three is safe.
729                          * Note:  this delay is important - don't remove!
730                          */
731                         sleep(3);
732                         interface_note_activity(&ctl->server);
733                     }
734 #endif /* (defined(linux) && !INET6_ENABLE) || defined(__FreeBSD__) */
735                 }
736             }
737
738 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
739         endhostent();           /* release TCP/IP connection to nameserver */
740 #endif /* HAVE_RES_SEARCH */
741
742         /* close connections cleanly */
743         terminate_poll(0);
744
745         /*
746          * OK, we've polled.  Now sleep.
747          */
748         if (run.poll_interval)
749         {
750             /* 
751              * Because passwords can expire, it may happen that *all*
752              * hosts are now out of the loop due to authfail
753              * conditions.  If this happens daemon-mode fetchmail
754              * should softly and silently vanish away, rather than
755              * spinning uselessly.
756              */
757             int unwedged = 0;
758
759             for (ctl = querylist; ctl; ctl = ctl->next)
760                 if (ctl->active && !(implicitmode && ctl->server.skip))
761                     if (!ctl->wedged)
762                         unwedged++;
763             if (!unwedged)
764             {
765                 report(stderr, _("All connections are wedged.  Exiting.\n"));
766                 /* FIXME: someday, send notification mail */
767                 exit(PS_AUTHFAIL);
768             }
769
770             if (outlevel >= O_VERBOSE)
771                 report(stdout, 
772                        _("fetchmail: sleeping at %s\n"), timestamp());
773
774             /*
775              * OK, now pause util it's time for the next poll cycle.
776              * A nonzero return indicates we received a wakeup signal;
777              * unwedge all servers in case the problem has been
778              * manually repaired.
779              */
780             if ((lastsig = interruptible_idle(run.poll_interval)))
781             {
782 #ifdef SYS_SIGLIST_DECLARED
783                 report(stdout, 
784                        _("awakened by %s\n"), sys_siglist[lastsig]);
785 #else
786                 report(stdout, 
787                        _("awakened by signal %d\n"), lastsig);
788 #endif
789                 for (ctl = querylist; ctl; ctl = ctl->next)
790                     ctl->wedged = FALSE;
791             }
792
793             if (outlevel >= O_VERBOSE)
794                 report(stdout, _("awakened at %s\n"), timestamp());
795         }
796     } while
797         (run.poll_interval);
798
799     if (outlevel >= O_VERBOSE)
800         report(stdout, _("normal termination, status %d\n"),
801                 successes ? PS_SUCCESS : querystatus);
802
803     terminate_run(0);
804     exit(successes ? PS_SUCCESS : querystatus);
805 }
806
807 static void list_merge(struct idlist **dstl, struct idlist **srcl, int force)
808 {
809     /*
810      * If force is off, modify dstl fields only when they're empty (treat srcl
811      * as defaults).  If force is on, modify each dstl field whenever scrcl
812      * is nonempty (treat srcl as an override).  
813      */
814     if (force ? !!*srcl : !*dstl)
815     {
816         struct idlist *cpl = copy_str_list(*srcl);
817
818         append_str_list(dstl, &cpl);
819     }
820 }
821
822 static void optmerge(struct query *h2, struct query *h1, int force)
823 /* merge two options records */
824 {
825     list_merge(&h2->server.localdomains, &h1->server.localdomains, force);
826     list_merge(&h2->localnames, &h1->localnames, force);
827     list_merge(&h2->mailboxes, &h1->mailboxes, force);
828     list_merge(&h2->smtphunt, &h1->smtphunt, force);
829     list_merge(&h2->antispam, &h1->antispam, force);
830
831 #define FLAG_MERGE(fld) if (force ? !!h1->fld : !h2->fld) h2->fld = h1->fld
832     FLAG_MERGE(server.via);
833     FLAG_MERGE(server.protocol);
834 #if INET6_ENABLE
835     FLAG_MERGE(server.service);
836     FLAG_MERGE(server.netsec);
837 #else /* INET6_ENABLE */
838     FLAG_MERGE(server.port);
839 #endif /* INET6_ENABLE */
840     FLAG_MERGE(server.interval);
841     FLAG_MERGE(server.preauthenticate);
842     FLAG_MERGE(server.timeout);
843     FLAG_MERGE(server.envelope);
844     FLAG_MERGE(server.envskip);
845     FLAG_MERGE(server.qvirtual);
846     FLAG_MERGE(server.skip);
847     FLAG_MERGE(server.dns);
848     FLAG_MERGE(server.checkalias);
849     FLAG_MERGE(server.uidl);
850     FLAG_MERGE(server.principal);
851
852 #if defined(linux) || defined(__FreeBSD__)
853     FLAG_MERGE(server.interface);
854     FLAG_MERGE(server.monitor);
855     FLAG_MERGE(server.interface_pair);
856 #endif /* linux || defined(__FreeBSD__) */
857
858     FLAG_MERGE(server.plugin);
859     FLAG_MERGE(server.plugout);
860
861     FLAG_MERGE(wildcard);
862     FLAG_MERGE(remotename);
863     FLAG_MERGE(password);
864     FLAG_MERGE(mda);
865     FLAG_MERGE(bsmtp);
866     FLAG_MERGE(listener);
867     FLAG_MERGE(smtpaddress);
868     FLAG_MERGE(smtpname);
869     FLAG_MERGE(preconnect);
870     FLAG_MERGE(postconnect);
871
872     FLAG_MERGE(keep);
873     FLAG_MERGE(flush);
874     FLAG_MERGE(fetchall);
875     FLAG_MERGE(rewrite);
876     FLAG_MERGE(forcecr);
877     FLAG_MERGE(stripcr);
878     FLAG_MERGE(pass8bits);
879     FLAG_MERGE(dropstatus);
880     FLAG_MERGE(dropdelivered);
881     FLAG_MERGE(mimedecode);
882     FLAG_MERGE(idle);
883     FLAG_MERGE(limit);
884     FLAG_MERGE(warnings);
885     FLAG_MERGE(fetchlimit);
886     FLAG_MERGE(batchlimit);
887 #ifdef  SSL_ENABLE
888     FLAG_MERGE(use_ssl);
889     FLAG_MERGE(sslkey);
890     FLAG_MERGE(sslcert);
891 #endif
892     FLAG_MERGE(expunge);
893
894     FLAG_MERGE(properties);
895 #undef FLAG_MERGE
896 }
897
898 static int load_params(int argc, char **argv, int optind)
899 {
900     int implicitmode, st;
901     struct passwd *pw;
902     struct query def_opts, *ctl;
903     struct stat rcstat;
904
905     run.bouncemail = TRUE;
906     run.spambounce = FALSE;     /* don't bounce back to innocent bystanders */
907
908     memset(&def_opts, '\0', sizeof(struct query));
909     def_opts.smtp_socket = -1;
910     def_opts.smtpaddress = (char *)0;
911     def_opts.smtpname = (char *)0;
912 #define ANTISPAM(n)     save_str(&def_opts.antispam, STRING_DUMMY, 0)->val.status.num = (n)
913     ANTISPAM(571);      /* sendmail */
914     ANTISPAM(550);      /* old exim */
915     ANTISPAM(501);      /* new exim */
916     ANTISPAM(554);      /* Postfix */
917 #undef ANTISPAM
918
919     def_opts.server.protocol = P_AUTO;
920     def_opts.server.timeout = CLIENT_TIMEOUT;
921     def_opts.warnings = WARNING_INTERVAL;
922     def_opts.remotename = user;
923     def_opts.listener = SMTP_MODE;
924
925     /* note the parse time, so we can pick up on modifications */
926     parsetime = 0;      /* foil compiler warnings */
927     if (stat(rcfile, &rcstat) != -1)
928         parsetime = rcstat.st_mtime;
929     else if (errno != ENOENT)
930         report(stderr, _("couldn't time-check the run-control file\n"));
931
932     /* this builds the host list */
933     if ((st = prc_parse_file(rcfile, !versioninfo)) != 0)
934         /*
935          * FIXME: someday, send notification mail here if backgrounded.
936          * Right now, that can happen if the user changes the rcfile
937          * while the fetchmail is running in background.  Do similarly
938          * for the other exit() calls in this function.
939          */
940         exit(st);
941
942     if ((implicitmode = (optind >= argc)))
943     {
944         for (ctl = querylist; ctl; ctl = ctl->next)
945             ctl->active = TRUE;
946     }
947     else
948         for (; optind < argc; optind++) 
949         {
950             flag        predeclared =  FALSE;
951
952             /*
953              * If hostname corresponds to a host known from the rc file,
954              * simply declare it active.  Otherwise synthesize a host
955              * record from command line and defaults
956              */
957             for (ctl = querylist; ctl; ctl = ctl->next)
958                 if (!strcmp(ctl->server.pollname, argv[optind])
959                         || str_in_list(&ctl->server.akalist, argv[optind], TRUE))
960                 {
961                     /* Is this correct? */
962                     if (predeclared && outlevel == O_VERBOSE)
963                         fprintf(stderr,_("Warning: multiple mentions of host %s in config file\n"),argv[optind]);
964                     ctl->active = TRUE;
965                     predeclared = TRUE;
966                 }
967
968             if (!predeclared)
969             {
970                 /*
971                  * Allocate and link record without copying in
972                  * command-line args; we'll do that with the optmerge
973                  * call later on.
974                  */
975                 ctl = hostalloc((struct query *)NULL);
976                 ctl->server.via =
977                     ctl->server.pollname = xstrdup(argv[optind]);
978                 ctl->active = TRUE;
979                 ctl->server.lead_server = (struct hostdata *)NULL;
980             }
981         }
982
983     /*
984      * If there's a defaults record, merge it and lose it.
985      */ 
986     if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
987     {
988         for (ctl = querylist->next; ctl; ctl = ctl->next)
989             optmerge(ctl, querylist, FALSE);
990         querylist = querylist->next;
991     }
992
993     /* don't allow a defaults record after the first */
994     for (ctl = querylist; ctl; ctl = ctl->next)
995         if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0)
996             exit(PS_SYNTAX);
997
998     /* use localhost if we never fetch the FQDN of this host */
999     fetchmailhost = "localhost";
1000
1001     /* here's where we override globals */
1002     if (cmd_run.logfile)
1003         run.logfile = cmd_run.logfile;
1004     if (cmd_run.idfile)
1005         run.idfile = cmd_run.idfile;
1006     /* do this before the keep/fetchall test below, otherwise -d0 may fail */
1007     if (cmd_run.poll_interval >= 0)
1008         run.poll_interval = cmd_run.poll_interval;
1009     if (cmd_run.invisible)
1010         run.invisible = cmd_run.invisible;
1011     if (cmd_run.showdots)
1012         run.showdots = cmd_run.showdots;
1013     if (cmd_run.use_syslog)
1014         run.use_syslog = (cmd_run.use_syslog == FLAG_TRUE);
1015     if (cmd_run.postmaster)
1016         run.postmaster = cmd_run.postmaster;
1017     if (cmd_run.bouncemail)
1018         run.bouncemail = cmd_run.bouncemail;
1019
1020     /* check and daemon options are not compatible */
1021     if (check_only && run.poll_interval)
1022         run.poll_interval = 0;
1023
1024     /* merge in wired defaults, do sanity checks and prepare internal fields */
1025     for (ctl = querylist; ctl; ctl = ctl->next)
1026     {
1027         ctl->wedged = FALSE;
1028
1029         if (configdump || ctl->active )
1030         {
1031             /* merge in defaults */
1032             optmerge(ctl, &def_opts, FALSE);
1033
1034             /* force command-line options */
1035             optmerge(ctl, &cmd_opts, TRUE);
1036
1037             /* this code enables flags to be turned off */
1038 #define DEFAULT(flag, dflt)     if (flag == FLAG_TRUE)\
1039                                         flag = TRUE;\
1040                                 else if (flag == FLAG_FALSE)\
1041                                         flag = FALSE;\
1042                                 else\
1043                                         flag = (dflt)
1044             DEFAULT(ctl->keep, FALSE);
1045             DEFAULT(ctl->fetchall, FALSE);
1046             DEFAULT(ctl->flush, FALSE);
1047             DEFAULT(ctl->rewrite, TRUE);
1048             DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL)); 
1049             DEFAULT(ctl->forcecr, FALSE);
1050             DEFAULT(ctl->pass8bits, FALSE);
1051             DEFAULT(ctl->dropstatus, FALSE);
1052             DEFAULT(ctl->dropdelivered, FALSE);
1053             DEFAULT(ctl->mimedecode, FALSE);
1054             DEFAULT(ctl->idle, FALSE);
1055             DEFAULT(ctl->server.dns, TRUE);
1056             DEFAULT(ctl->server.uidl, FALSE);
1057 #ifdef  SSL_ENABLE
1058             DEFAULT(ctl->use_ssl, FALSE);
1059 #endif
1060             DEFAULT(ctl->server.checkalias, FALSE);
1061 #undef DEFAULT
1062
1063             /*
1064              * DNS support is required for some protocols.  We used to
1065              * do this unconditionally, but it made fetchmail excessively
1066              * vulnerable to misconfigured DNS setups.
1067              *
1068              * If we're using ETRN, the smtp hunt list is the list of
1069              * systems we're polling on behalf of; these have to be 
1070              * fully-qualified domain names.  The default for this list
1071              * should be the FQDN of localhost.
1072              *
1073              * If we're using Kerberos for authentication, we need 
1074              * the FQDN in order to generate capability keys.
1075              */
1076             if (ctl->server.protocol == P_ETRN
1077                          || ctl->server.preauthenticate == A_KERBEROS_V4
1078                          || ctl->server.preauthenticate == A_KERBEROS_V5)
1079                 if (strcmp(fetchmailhost, "localhost") == 0)
1080                         fetchmailhost = host_fqdn();
1081
1082             /*
1083              * Make sure we have a nonempty host list to forward to.
1084              */
1085             if (!ctl->smtphunt)
1086                 save_str(&ctl->smtphunt, fetchmailhost, FALSE);
1087
1088             /* if `user' doesn't name a real local user, try to run as root */
1089             if ((pw = getpwnam(user)) == (struct passwd *)NULL)
1090                 ctl->uid = 0;
1091             else
1092                 ctl->uid = pw->pw_uid;  /* for local delivery via MDA */
1093             if (!ctl->localnames)       /* for local delivery via SMTP */
1094                 save_str_pair(&ctl->localnames, user, NULL);
1095
1096 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
1097             /* can't handle multidrop mailboxes unless we can do DNS lookups */
1098             if (ctl->localnames && ctl->localnames->next && ctl->server.dns)
1099             {
1100                 ctl->server.dns = FALSE;
1101                 report(stderr, _("fetchmail: warning: no DNS available to check multidrop fetches from %s\n"), ctl->server.pollname);
1102             }
1103 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
1104
1105             /*
1106              *
1107              * Compute the true name of the mailserver host.  
1108              * There are two clashing cases here:
1109              *
1110              * (1) The poll name is a label, possibly on one of several
1111              *     poll configurations for the same host.  In this case 
1112              *     the `via' option will be present and give the true name.
1113              *
1114              * (2) The poll name is the true one, the via name is 
1115              *     localhost.   This is going to be typical for ssh-using
1116              *     configurations.
1117              *
1118              * We're going to assume the via name is true unless it's
1119              * localhost.
1120              */
1121             if (ctl->server.via && strcmp(ctl->server.via, "localhost"))
1122                 ctl->server.queryname = xstrdup(ctl->server.via);
1123             else
1124                 ctl->server.queryname = xstrdup(ctl->server.pollname);
1125
1126 #ifdef HESIOD
1127         /* If either the pollname or vianame are "hesiod" we want to
1128            lookup the user's hesiod pobox host */
1129
1130         if (!strcasecmp(ctl->server.queryname, "hesiod")) {
1131             struct hes_postoffice *hes_p;
1132             hes_p = hes_getmailhost(ctl->remotename);
1133             if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
1134                  free(ctl->server.queryname);
1135                  ctl->server.queryname = xstrdup(hes_p->po_host);
1136                  if (ctl->server.via)
1137                      free(ctl->server.via);
1138                  ctl->server.via = xstrdup(hes_p->po_host);
1139             } else {
1140                  report(stderr,
1141                         _("couldn't find HESIOD pobox for %s\n"),
1142                         ctl->remotename);
1143             }
1144         }
1145 #endif /* HESIOD */
1146
1147             /*
1148              * We may have to canonicalize the server truename for later use.
1149              * Do this just once for each lead server, if necessary, in order
1150              * to minimize DNS round trips.
1151              */
1152             if (ctl->server.lead_server)
1153             {
1154                 char    *leadname = ctl->server.lead_server->truename;
1155
1156                 /* prevent core dump from ill-formed or duplicate entry */
1157                 if (!leadname)
1158                 {
1159                     report(stderr, _("Lead server has no name.\n"));
1160                     exit(PS_SYNTAX);
1161                 }
1162
1163                 ctl->server.truename = xstrdup(leadname);
1164             }
1165 #ifdef HAVE_GETHOSTBYNAME
1166             else if (!configdump)
1167             {
1168                 if (ctl->server.preauthenticate==A_KERBEROS_V4 ||
1169                       ctl->server.preauthenticate==A_KERBEROS_V5 ||
1170                     (ctl->server.dns && MULTIDROP(ctl)))
1171                 {
1172                     struct hostent      *namerec;
1173
1174                     /* compute the canonical name of the host */
1175                     errno = 0;
1176                     namerec = gethostbyname(ctl->server.queryname);
1177                     if (namerec == (struct hostent *)NULL)
1178                     {
1179                         report(stderr,
1180                                _("couldn't find canonical DNS name of %s\n"),
1181                                ctl->server.pollname);
1182                         ctl->server.truename = xstrdup(ctl->server.queryname);
1183                         ctl->server.trueaddr = NULL;
1184                     }
1185                     else
1186                         ctl->server.truename=xstrdup((char *)namerec->h_name);
1187                 }
1188 #endif /* HAVE_GETHOSTBYNAME */
1189                 else {
1190 #ifdef HAVE_GETHOSTBYNAME
1191                     struct hostent      *namerec;
1192                     
1193                     /* <fetchmail@mail.julianhaight.com>
1194                        Get the host's IP, so we can report it like this:
1195
1196                        Received: from hostname [10.0.0.1]
1197
1198                        do we actually need to gethostbyname to find the IP?
1199                        it seems like it would be faster to do this later, when
1200                        we are actually resolving the hostname for a connection,
1201                        but I ain't that smart, so I don't know where to make
1202                        the change later..
1203                     */
1204                     errno = 0;
1205                     namerec = gethostbyname(ctl->server.queryname);
1206                     if (namerec == (struct hostent *)NULL)
1207                     {
1208                         report(stderr,
1209                                _("couldn't find canonical DNS name of %s\n"),
1210                                ctl->server.pollname);
1211                         exit(PS_DNS);
1212                     }
1213                     else {
1214                         ctl->server.truename=xstrdup((char *)namerec->h_name);
1215                         ctl->server.trueaddr=xmalloc(namerec->h_length);
1216                         memcpy(ctl->server.trueaddr, 
1217                                namerec->h_addr_list[0],
1218                                namerec->h_length);
1219                     }
1220 #else
1221                     ctl->server.truename = xstrdup(ctl->server.queryname);
1222 #endif /* HAVE_GETHOSTBYNAME */
1223                 }
1224             }
1225
1226             /* if no folders were specified, set up the null one as default */
1227             if (!ctl->mailboxes)
1228                 save_str(&ctl->mailboxes, (char *)NULL, 0);
1229
1230             /* maybe user overrode timeout on command line? */
1231             if (ctl->server.timeout == -1)      
1232                 ctl->server.timeout = CLIENT_TIMEOUT;
1233
1234 #if !INET6_ENABLE
1235             /* sanity checks */
1236             if (ctl->server.port < 0)
1237             {
1238                 (void) fprintf(stderr,
1239                                _("%s configuration invalid, port number cannot be negative\n"),
1240                                ctl->server.pollname);
1241                 exit(PS_SYNTAX);
1242             }
1243             if (ctl->server.protocol == P_RPOP && ctl->server.port >= 1024)
1244             {
1245                 (void) fprintf(stderr,
1246                                _("%s configuration invalid, RPOP requires a privileged port\n"),
1247                                ctl->server.pollname);
1248                 exit(PS_SYNTAX);
1249             }
1250             if (ctl->listener == LMTP_MODE)
1251             {
1252                 struct idlist   *idp;
1253
1254                 for (idp = ctl->smtphunt; idp; idp = idp->next)
1255                 {
1256                     char        *cp;
1257
1258                     if (!(cp = strrchr(idp->id, '/')) ||
1259                                 (atoi(++cp) == SMTP_PORT))
1260                     {
1261                         (void) fprintf(stderr,
1262                                        _("%s configuration invalid, LMTP can't use default SMTP port\n"),
1263                                        ctl->server.pollname);
1264                         exit(PS_SYNTAX);
1265                     }
1266                 }
1267             }
1268 #endif /* !INET6_ENABLE */
1269
1270             /*
1271              * "I beg to you, have mercy on the week minds like myself."
1272              * wrote Pehr Anderson.  Your petition is granted.
1273              */
1274             if (ctl->fetchall && ctl->keep && run.poll_interval && !nodetach)
1275             {
1276                 (void) fprintf(stderr,
1277                                _("Both fetchall and keep on in daemon mode is a mistake!\n"));
1278                 exit(PS_SYNTAX);
1279             }
1280         }
1281     }
1282
1283 #ifdef POP3_ENABLE
1284     /* initialize UID handling */
1285     if (!versioninfo && (st = prc_filecheck(run.idfile, !versioninfo)) != 0)
1286         exit(st);
1287     else
1288         initialize_saved_lists(querylist, run.idfile);
1289 #endif /* POP3_ENABLE */
1290
1291     /*
1292      * If the user didn't set a last-resort user to get misaddressed
1293      * multidrop mail, set an appropriate default here.
1294      */
1295     if (!run.postmaster)
1296     {
1297         if (getuid())                           /* ordinary user */
1298             run.postmaster = user;
1299         else                                    /* root */
1300             run.postmaster = "postmaster";
1301     }
1302
1303     return(implicitmode);
1304 }
1305
1306 static void terminate_poll(int sig)
1307 /* to be executed at the end of a poll cycle */
1308 {
1309     /*
1310      * Close all SMTP delivery sockets.  For optimum performance
1311      * we'd like to hold them open til end of run, but (1) this
1312      * loses if our poll interval is longer than the MTA's inactivity
1313      * timeout, and (2) some MTAs (like smail) don't deliver after
1314      * each message, but rather queue up mail and wait to actually
1315      * deliver it until the input socket is closed. 
1316      *
1317      * Sending SMTP QUIT on signal is theoretically nice, but led to a 
1318      * subtle bug.  If fetchmail was terminated by signal while it was 
1319      * shipping message text, it would hang forever waiting for a
1320      * command acknowledge.  In theory we could enable the QUIT
1321      * only outside of the message send.  In practice, we don't
1322      * care.  All mailservers hang up on a dropped TCP/IP connection
1323      * anyway.
1324      */
1325
1326     if (sig != 0)
1327         report(stdout, _("terminated with signal %d\n"), sig);
1328     else
1329     {
1330         struct query *ctl;
1331
1332         /* terminate all SMTP connections cleanly */
1333         for (ctl = querylist; ctl; ctl = ctl->next)
1334             if (ctl->smtp_socket != -1)
1335             {
1336                 SMTP_quit(ctl->smtp_socket);
1337                 SockClose(ctl->smtp_socket);
1338                 ctl->smtp_socket = -1;
1339             }
1340     }
1341
1342 #ifdef POP3_ENABLE
1343     /*
1344      * Update UID information at end of each poll, rather than at end
1345      * of run, because that way we don't lose all UIDL information since
1346      * the beginning of time if fetchmail crashes.
1347      */
1348     if (!check_only)
1349         write_saved_lists(querylist, run.idfile);
1350 #endif /* POP3_ENABLE */
1351 }
1352
1353 static void terminate_run(int sig)
1354 /* to be executed on normal or signal-induced termination */
1355 {
1356     struct query        *ctl;
1357
1358     terminate_poll(sig);
1359
1360     /* 
1361      * Craig Metz, the RFC1938 one-time-password guy, points out:
1362      * "Remember that most kernels don't zero pages before handing them to the
1363      * next process and many kernels share pages between user and kernel space.
1364      * You'd be very surprised what you can find from a short program to do a
1365      * malloc() and then dump the contents of the pages you got. By zeroing
1366      * the secrets at end of run (earlier if you can), you make sure the next
1367      * guy can't get the password/pass phrase."
1368      *
1369      * Right you are, Craig!
1370      */
1371     for (ctl = querylist; ctl; ctl = ctl->next)
1372         if (ctl->password)
1373           memset(ctl->password, '\0', strlen(ctl->password));
1374
1375 #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
1376     unlockit();
1377 #endif
1378
1379     if (activecount == 0)
1380         exit(PS_NOMAIL);
1381     else
1382         exit(successes ? PS_SUCCESS : querystatus);
1383 }
1384
1385 /*
1386  * Sequence of protocols to try when autoprobing, most capable to least.
1387  */
1388 static const int autoprobe[] = 
1389 {
1390 #ifdef IMAP_ENABLE
1391     P_IMAP,
1392 #endif /* IMAP_ENABLE */
1393 #ifdef POP3_ENABLE
1394     P_POP3,
1395 #endif /* POP3_ENABLE */
1396 #ifdef POP2_ENABLE
1397     P_POP2
1398 #endif /* POP2_ENABLE */
1399 };
1400
1401 static int query_host(struct query *ctl)
1402 /* perform fetch transaction with single host */
1403 {
1404     int i, st;
1405
1406     /*
1407      * If we're syslogging the progress messages are automatically timestamped.
1408      * Force timestamping if we're going to a logfile.
1409      */
1410     if (outlevel >= O_VERBOSE || (run.logfile && outlevel > O_SILENT))
1411     {
1412         report(stdout, _("%s querying %s (protocol %s) at %s\n"),
1413                VERSION,
1414                ctl->server.pollname,
1415                showproto(ctl->server.protocol),
1416                timestamp());
1417     }
1418     switch (ctl->server.protocol) {
1419     case P_AUTO:
1420         for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
1421         {
1422             ctl->server.protocol = autoprobe[i];
1423             if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP)
1424                 break;
1425         }
1426         ctl->server.protocol = P_AUTO;
1427         return(st);
1428     case P_POP2:
1429 #ifdef POP2_ENABLE
1430         return(doPOP2(ctl));
1431 #else
1432         report(stderr, _("POP2 support is not configured.\n"));
1433         return(PS_PROTOCOL);
1434 #endif /* POP2_ENABLE */
1435         break;
1436     case P_POP3:
1437     case P_APOP:
1438     case P_RPOP:
1439 #ifdef POP3_ENABLE
1440         return(doPOP3(ctl));
1441 #else
1442         report(stderr, _("POP3 support is not configured.\n"));
1443         return(PS_PROTOCOL);
1444 #endif /* POP3_ENABLE */
1445         break;
1446     case P_IMAP:
1447     case P_IMAP_K4:
1448     case P_IMAP_CRAM_MD5:
1449     case P_IMAP_LOGIN:
1450 #ifdef GSSAPI
1451     case P_IMAP_GSS:
1452 #endif /* GSSAPI */
1453 #ifdef IMAP_ENABLE
1454         return(doIMAP(ctl));
1455 #else
1456         report(stderr, _("IMAP support is not configured.\n"));
1457         return(PS_PROTOCOL);
1458 #endif /* IMAP_ENABLE */
1459     case P_ETRN:
1460 #ifndef ETRN_ENABLE
1461         report(stderr, _("ETRN support is not configured.\n"));
1462         return(PS_PROTOCOL);
1463 #else
1464 #ifdef HAVE_GETHOSTBYNAME
1465         return(doETRN(ctl));
1466 #else
1467         report(stderr, _("Cannot support ETRN without gethostbyname(2).\n"));
1468         return(PS_PROTOCOL);
1469 #endif /* HAVE_GETHOSTBYNAME */
1470 #endif /* ETRN_ENABLE */
1471     default:
1472         report(stderr, _("unsupported protocol selected.\n"));
1473         return(PS_PROTOCOL);
1474     }
1475 }
1476
1477 static void dump_params (struct runctl *runp,
1478                          struct query *querylist, flag implicit)
1479 /* display query parameters in English */
1480 {
1481     struct query *ctl;
1482
1483     if (runp->poll_interval)
1484         printf(_("Poll interval is %d seconds\n"), runp->poll_interval);
1485     if (runp->logfile)
1486         printf(_("Logfile is %s\n"), runp->logfile);
1487     if (strcmp(runp->idfile, IDFILE_NAME))
1488         printf(_("Idfile is %s\n"), runp->idfile);
1489 #if defined(HAVE_SYSLOG)
1490     if (runp->use_syslog)
1491         printf(_("Progress messages will be logged via syslog\n"));
1492 #endif
1493     if (runp->invisible)
1494         printf(_("Fetchmail will masquerade and will not generate Received\n"));
1495     if (runp->showdots)
1496         printf(_("Fetchmail will show progress dots even in logfiles.\n"));
1497     if (runp->postmaster)
1498         printf(_("Fetchmail will forward misaddressed multidrop messages to %s.\n"),
1499                runp->postmaster);
1500
1501     if (!runp->bouncemail)
1502         printf(_("Fetchmail will direct error mail to the postmaster.\n"));
1503     else if (outlevel >= O_VERBOSE)
1504         printf(_("Fetchmail will direct error mail to the sender.\n"));
1505
1506     for (ctl = querylist; ctl; ctl = ctl->next)
1507     {
1508         if (!ctl->active || (implicit && ctl->server.skip))
1509             continue;
1510
1511         printf(_("Options for retrieving from %s@%s:\n"),
1512                ctl->remotename, visbuf(ctl->server.pollname));
1513
1514         if (ctl->server.via && (ctl->server.protocol != P_ETRN))
1515             printf(_("  Mail will be retrieved via %s\n"), ctl->server.via);
1516
1517         if (ctl->server.interval)
1518             printf(_("  Poll of this server will occur every %d intervals.\n"),
1519                    ctl->server.interval);
1520         if (ctl->server.truename)
1521             printf(_("  True name of server is %s.\n"), ctl->server.truename);
1522         if (ctl->server.skip || outlevel >= O_VERBOSE)
1523             printf(_("  This host %s be queried when no host is specified.\n"),
1524                    ctl->server.skip ? _("will not") : _("will"));
1525         /*
1526          * Don't poll for password when there is one or when using the ETRN
1527          * or IMAP-GSS protocol
1528          */
1529         /* ETRN, IMAP_GSS, and IMAP_K4 do not need a password, so skip this */
1530         if ( (ctl->server.protocol != P_ETRN)
1531 #ifdef GSSAPI
1532                                 && (ctl->server.protocol != P_IMAP_GSS)
1533 #endif /* GSSAPI */
1534                                 && (ctl->server.protocol != P_IMAP_K4) ) {
1535                 if (!ctl->password)
1536                         printf(_("  Password will be prompted for.\n"));
1537                 else if (outlevel >= O_VERBOSE)
1538                 {
1539                         if (ctl->server.protocol == P_APOP)
1540                                 printf(_("  APOP secret = \"%s\".\n"),
1541                                                         visbuf(ctl->password));
1542                         else if (ctl->server.protocol == P_RPOP)
1543                                 printf(_("  RPOP id = \"%s\".\n"),
1544                                                         visbuf(ctl->password));
1545                         else
1546                                 printf(_("  Password = \"%s\".\n"),
1547                                                         visbuf(ctl->password));
1548                 }
1549         }
1550
1551         if (ctl->server.protocol == P_POP3 
1552 #if INET6_ENABLE
1553             && ctl->server.service && !strcmp(ctl->server.service, KPOP_PORT)
1554 #else /* INET6_ENABLE */
1555             && ctl->server.port == KPOP_PORT
1556 #endif /* INET6_ENABLE */
1557             && (ctl->server.preauthenticate == A_KERBEROS_V4 ||
1558                 ctl->server.preauthenticate == A_KERBEROS_V5))
1559             printf(_("  Protocol is KPOP with Kerberos %s authentication"),
1560                    ctl->server.preauthenticate == A_KERBEROS_V5 ? "V" : "IV");
1561         else
1562             printf(_("  Protocol is %s"), showproto(ctl->server.protocol));
1563 #if INET6_ENABLE
1564         if (ctl->server.service)
1565             printf(_(" (using service %s)"), ctl->server.service);
1566         if (ctl->server.netsec)
1567             printf(_(" (using network security options %s)"), ctl->server.netsec);
1568 #else /* INET6_ENABLE */
1569         if (ctl->server.port)
1570             printf(_(" (using port %d)"), ctl->server.port);
1571 #endif /* INET6_ENABLE */
1572         else if (outlevel >= O_VERBOSE)
1573             printf(_(" (using default port)"));
1574         if (ctl->server.uidl && (ctl->server.protocol != P_ETRN))
1575             printf(_(" (forcing UIDL use)"));
1576         putchar('.');
1577         putchar('\n');
1578         if (ctl->server.preauthenticate == A_KERBEROS_V4)
1579             printf(_("  Kerberos V4 preauthentication enabled.\n"));
1580         else if (ctl->server.preauthenticate == A_KERBEROS_V5)
1581             printf(_("  Kerberos V5 preauthentication enabled.\n"));
1582         else if (ctl->server.preauthenticate == A_SSH)
1583             printf(_("  End-to-end encryption assumed.\n"));
1584         if (ctl->server.principal != (char *) NULL) {
1585             printf(_("  Mail service principal is: %s\n"), ctl->server.principal);
1586         }
1587 #ifdef  SSL_ENABLE
1588         if (ctl->use_ssl)
1589             printf("  SSL encrypted sessions enabled.\n");
1590 #endif
1591         if (ctl->server.timeout > 0)
1592             printf(_("  Server nonresponse timeout is %d seconds"), ctl->server.timeout);
1593         if (ctl->server.timeout ==  CLIENT_TIMEOUT)
1594             printf(_(" (default).\n"));
1595         else
1596             printf(".\n");
1597
1598         if (ctl->server.protocol != P_ETRN) {
1599                 if (!ctl->mailboxes->id)
1600                     printf(_("  Default mailbox selected.\n"));
1601                 else
1602                 {
1603                     struct idlist *idp;
1604
1605                     printf(_("  Selected mailboxes are:"));
1606                     for (idp = ctl->mailboxes; idp; idp = idp->next)
1607                         printf(" %s", idp->id);
1608                     printf("\n");
1609                 }
1610                 printf(_("  %s messages will be retrieved (--all %s).\n"),
1611                        ctl->fetchall ? _("All") : _("Only new"),
1612                        ctl->fetchall ? "on" : "off");
1613                 printf(_("  Fetched messages %s be kept on the server (--keep %s).\n"),
1614                        ctl->keep ? _("will") : _("will not"),
1615                        ctl->keep ? "on" : "off");
1616                 printf(_("  Old messages %s be flushed before message retrieval (--flush %s).\n"),
1617                        ctl->flush ? _("will") : _("will not"),
1618                        ctl->flush ? "on" : "off");
1619                 printf(_("  Rewrite of server-local addresses is %s (--norewrite %s).\n"),
1620                        ctl->rewrite ? _("enabled") : _("disabled"),
1621                        ctl->rewrite ? "off" : "on");
1622                 printf(_("  Carriage-return stripping is %s (stripcr %s).\n"),
1623                        ctl->stripcr ? _("enabled") : _("disabled"),
1624                        ctl->stripcr ? "on" : "off");
1625                 printf(_("  Carriage-return forcing is %s (forcecr %s).\n"),
1626                        ctl->forcecr ? _("enabled") : _("disabled"),
1627                        ctl->forcecr ? "on" : "off");
1628                 printf(_("  Interpretation of Content-Transfer-Encoding is %s (pass8bits %s).\n"),
1629                        ctl->pass8bits ? _("disabled") : _("enabled"),
1630                        ctl->pass8bits ? "on" : "off");
1631                 printf(_("  MIME decoding is %s (mimedecode %s).\n"),
1632                        ctl->mimedecode ? _("enabled") : _("disabled"),
1633                        ctl->mimedecode ? "on" : "off");
1634                 printf(_("  Idle after poll is %s (idle %s).\n"),
1635                        ctl->idle ? _("enabled") : _("disabled"),
1636                        ctl->idle ? "on" : "off");
1637                 printf(_("  Nonempty Status lines will be %s (dropstatus %s)\n"),
1638                        ctl->dropstatus ? _("discarded") : _("kept"),
1639                        ctl->dropstatus ? "on" : "off");
1640                 printf(_("  Delivered-To lines will be %s (dropdelivered %s)\n"),
1641                        ctl->dropdelivered ? _("discarded") : _("kept"),
1642                        ctl->dropdelivered ? "on" : "off");
1643                 if (NUM_NONZERO(ctl->limit))
1644                 {
1645                     if (NUM_NONZERO(ctl->limit))
1646                         printf(_("  Message size limit is %d octets (--limit %d).\n"), 
1647                                ctl->limit, ctl->limit);
1648                     else if (outlevel >= O_VERBOSE)
1649                         printf(_("  No message size limit (--limit 0).\n"));
1650                     if (run.poll_interval > 0)
1651                         printf(_("  Message size warning interval is %d seconds (--warnings %d).\n"), 
1652                                ctl->warnings, ctl->warnings);
1653                     else if (outlevel >= O_VERBOSE)
1654                         printf(_("  Size warnings on every poll (--warnings 0).\n"));
1655                 }
1656                 if (NUM_NONZERO(ctl->fetchlimit))
1657                     printf(_("  Received-message limit is %d (--fetchlimit %d).\n"),
1658                            ctl->fetchlimit, ctl->fetchlimit);
1659                 else if (outlevel >= O_VERBOSE)
1660                     printf(_("  No received-message limit (--fetchlimit 0).\n"));
1661                 if (NUM_NONZERO(ctl->batchlimit))
1662                     printf(_("  SMTP message batch limit is %d.\n"), ctl->batchlimit);
1663                 else if (outlevel >= O_VERBOSE)
1664                     printf(_("  No SMTP message batch limit (--batchlimit 0).\n"));
1665                 if (ctl->server.protocol != P_ETRN)
1666                 {
1667                     if (NUM_NONZERO(ctl->expunge))
1668                         printf(_("  Deletion interval between expunges forced to %d (--expunge %d).\n"), ctl->expunge, ctl->expunge);
1669                     else if (outlevel >= O_VERBOSE)
1670                         printf(_("  No forced expunges (--expunge 0).\n"));
1671                 }
1672         }
1673         if (ctl->bsmtp)
1674             printf(_("  Messages will be appended to %s as BSMTP\n"), visbuf(ctl->bsmtp));
1675         else if (ctl->mda && (ctl->server.protocol != P_ETRN))
1676             printf(_("  Messages will be delivered with \"%s\".\n"), visbuf(ctl->mda));
1677         else
1678         {
1679             struct idlist *idp;
1680
1681             printf(_("  Messages will be %cMTP-forwarded to:"), ctl->listener);
1682             for (idp = ctl->smtphunt; idp; idp = idp->next)
1683             {
1684                 printf(" %s", idp->id);
1685                 if (!idp->val.status.mark)
1686                     printf(_(" (default)"));
1687             }
1688             printf("\n");
1689             if (ctl->smtpaddress)
1690                 printf(_("  Host part of MAIL FROM line will be %s\n"),
1691                        ctl->smtpaddress);
1692             if (ctl->smtpname)
1693                 printf(_("  Address to be put in RCPT TO lines shipped to SMTP will be %s\n"),
1694                        ctl->smtpname);
1695         }
1696         if (ctl->server.protocol != P_ETRN)
1697         {
1698                 if (ctl->antispam != (struct idlist *)NULL)
1699                 {
1700                     struct idlist *idp;
1701
1702                     printf(_("  Recognized listener spam block responses are:"));
1703                     for (idp = ctl->antispam; idp; idp = idp->next)
1704                         printf(" %d", idp->val.status.num);
1705                     printf("\n");
1706                 }
1707                 else if (outlevel >= O_VERBOSE)
1708                     printf(_("  Spam-blocking disabled\n"));
1709         }
1710         if (ctl->preconnect)
1711             printf(_("  Server connection will be brought up with \"%s\".\n"),
1712                    visbuf(ctl->preconnect));
1713         else if (outlevel >= O_VERBOSE)
1714             printf(_("  No pre-connection command.\n"));
1715         if (ctl->postconnect)
1716             printf(_("  Server connection will be taken down with \"%s\".\n"),
1717                    visbuf(ctl->postconnect));
1718         else if (outlevel >= O_VERBOSE)
1719             printf(_("  No post-connection command.\n"));
1720         if (ctl->server.protocol != P_ETRN) {
1721                 if (!ctl->localnames)
1722                     printf(_("  No localnames declared for this host.\n"));
1723                 else
1724                 {
1725                     struct idlist *idp;
1726                     int count = 0;
1727
1728                     for (idp = ctl->localnames; idp; idp = idp->next)
1729                         ++count;
1730
1731                     if (count > 1 || ctl->wildcard)
1732                         printf(_("  Multi-drop mode: "));
1733                     else
1734                         printf(_("  Single-drop mode: "));
1735
1736                     printf(_("%d local name(s) recognized.\n"), count);
1737                     if (outlevel >= O_VERBOSE)
1738                     {
1739                         for (idp = ctl->localnames; idp; idp = idp->next)
1740                             if (idp->val.id2)
1741                                 printf("\t%s -> %s\n", idp->id, idp->val.id2);
1742                             else
1743                                 printf("\t%s\n", idp->id);
1744                         if (ctl->wildcard)
1745                             fputs("\t*\n", stdout);
1746                     }
1747
1748                     if (count > 1 || ctl->wildcard)
1749                     {
1750                         printf(_("  DNS lookup for multidrop addresses is %s.\n"),
1751                                ctl->server.dns ? _("enabled") : _("disabled"));
1752                         if (ctl->server.dns)
1753                         {
1754                             printf(_("  Server aliases will be compared with multidrop addresses by "));
1755                             if (ctl->server.checkalias)
1756                                 printf(_("IP address.\n"));
1757                             else
1758                                 printf(_("name.\n"));
1759                         }
1760                         if (ctl->server.envelope == STRING_DISABLED)
1761                             printf(_("  Envelope-address routing is disabled\n"));
1762                         else
1763                         {
1764                             printf(_("  Envelope header is assumed to be: %s\n"),
1765                                    ctl->server.envelope ? ctl->server.envelope:_("Received"));
1766                             if (ctl->server.envskip > 1 || outlevel >= O_VERBOSE)
1767                                 printf(_("  Number of envelope header to be parsed: %d\n"),
1768                                        ctl->server.envskip);
1769                             if (ctl->server.qvirtual)
1770                                 printf(_("  Prefix %s will be removed from user id\n"),
1771                                        ctl->server.qvirtual);
1772                             else if (outlevel >= O_VERBOSE) 
1773                                 printf(_("  No prefix stripping\n"));
1774                         }
1775
1776                         if (ctl->server.akalist)
1777                         {
1778                             struct idlist *idp;
1779
1780                             printf(_("  Predeclared mailserver aliases:"));
1781                             for (idp = ctl->server.akalist; idp; idp = idp->next)
1782                                 printf(" %s", idp->id);
1783                             putchar('\n');
1784                         }
1785                         if (ctl->server.localdomains)
1786                         {
1787                             struct idlist *idp;
1788
1789                             printf(_("  Local domains:"));
1790                             for (idp = ctl->server.localdomains; idp; idp = idp->next)
1791                                 printf(" %s", idp->id);
1792                             putchar('\n');
1793                         }
1794                     }
1795                 }
1796         }
1797 #if defined(linux) || defined(__FreeBSD__)
1798         if (ctl->server.interface)
1799             printf(_("  Connection must be through interface %s.\n"), ctl->server.interface);
1800         else if (outlevel >= O_VERBOSE)
1801             printf(_("  No interface requirement specified.\n"));
1802         if (ctl->server.monitor)
1803             printf(_("  Polling loop will monitor %s.\n"), ctl->server.monitor);
1804         else if (outlevel >= O_VERBOSE)
1805             printf(_("  No monitor interface specified.\n"));
1806 #endif
1807
1808         if (ctl->server.plugin)
1809             printf(_("  Server connections will be made via plugin %s (--plugin %s).\n"), ctl->server.plugin, ctl->server.plugin);
1810         else if (outlevel >= O_VERBOSE)
1811             printf(_("  No plugin command specified.\n"));
1812         if (ctl->server.plugout)
1813             printf(_("  Listener connections will be made via plugout %s (--plugout %s).\n"), ctl->server.plugout, ctl->server.plugout);
1814         else if (outlevel >= O_VERBOSE)
1815             printf(_("  No plugout command specified.\n"));
1816
1817         if (ctl->server.protocol > P_POP2 && (ctl->server.protocol != P_ETRN))
1818         {
1819             if (!ctl->oldsaved)
1820                 printf(_("  No UIDs saved from this host.\n"));
1821             else
1822             {
1823                 struct idlist *idp;
1824                 int count = 0;
1825
1826                 for (idp = ctl->oldsaved; idp; idp = idp->next)
1827                     ++count;
1828
1829                 printf(_("  %d UIDs saved.\n"), count);
1830                 if (outlevel >= O_VERBOSE)
1831                     for (idp = ctl->oldsaved; idp; idp = idp->next)
1832                         printf("\t%s\n", idp->id);
1833             }
1834         }
1835
1836         if (ctl->properties)
1837             printf(_("  Pass-through properties \"%s\".\n"),
1838                    visbuf(ctl->properties));
1839     }
1840 }
1841
1842 /* fetchmail.c ends here */