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