]> Pileus Git - ~andy/fetchmail/blob - fetchmail.c
Philippe de Muyter's port patches.
[~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
7 #include "config.h"
8
9 #include <stdio.h>
10 #include <ctype.h>
11 #if defined(STDC_HEADERS)
12 #include <stdlib.h>
13 #endif
14 #if defined(HAVE_UNISTD_H)
15 #include <unistd.h>
16 #endif
17 #if defined(HAVE_ALLOCA_H)
18 #include <alloca.h>
19 #else
20 #ifdef _AIX
21  #pragma alloca
22 #endif
23 #endif
24 #include <string.h>
25 #include <signal.h>
26 #if defined(HAVE_SYSLOG)
27 #include <syslog.h>
28 #endif
29 #include <pwd.h>
30 #include <errno.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #ifdef HAVE_SYS_WAIT_H
35 #include <sys/wait.h>
36 #endif
37
38 #ifdef HAVE_GETHOSTBYNAME
39 #include <netdb.h>
40 #endif /* HAVE_GETHOSTBYNAME */
41
42 #include "fetchmail.h"
43 #include "tunable.h"
44 #include "smtp.h"
45 #include "getopt.h"
46 #include "netrc.h"
47
48 #ifndef ENETUNREACH
49 #define ENETUNREACH   128       /* Interactive doesn't know this */
50 #endif /* ENETUNREACH */
51
52 /* prototypes for internal functions */
53 static int load_params(int, char **, int);
54 static void dump_params (struct query *);
55 static int query_host(struct query *);
56
57 /* controls the detail level of status/progress messages written to stderr */
58 int outlevel;           /* see the O_.* constants above */
59
60 /* daemon mode control */
61 flag nodetach;          /* if TRUE, don't detach daemon process */
62 flag quitmode;          /* if --quit was set */
63 flag check_only;        /* if --probe was set */
64 char *cmd_logfile;      /* if --logfile was set */
65 int cmd_daemon;         /* if --daemon was set */
66
67 /* miscellaneous global controls */
68 char *idfile;           /* UID list file */
69 flag versioninfo;       /* emit only version info */
70 char *user;             /* the name of the invoking user */
71 char *home;
72 char *fetchmailhost;    /* the name of the host running fetchmail */
73 char *program_name;     /* the name to prefix error messages with */
74
75 static char *lockfile;          /* name of lockfile */
76 static int querystatus;         /* status of query */
77 static int successes;           /* count number of successful polls */
78 static int lastsig;             /* last signal received */
79
80 static void termhook();         /* forward declaration of exit hook */
81
82 RETSIGTYPE donothing(sig) int sig; {signal(sig, donothing); lastsig = sig;}
83
84 #ifdef HAVE_ON_EXIT
85 static void unlockit(int n, void *p)
86 #else
87 static void unlockit(void)
88 #endif
89 /* must-do actions for exit (but we can't count on being able to do malloc) */
90 {
91     unlink(lockfile);
92 }
93
94 int main (int argc, char **argv)
95 {
96     int st, bkgd = FALSE;
97     int parsestatus, implicitmode = FALSE;
98     struct query *ctl;
99     FILE        *lockfp;
100     netrc_entry *netrc_list;
101     char *netrc_file, tmpbuf[BUFSIZ];
102     pid_t pid;
103
104     envquery(argc, argv);
105
106 #define IDFILE_NAME     ".fetchids"
107     idfile = (char *) xmalloc(strlen(home)+strlen(IDFILE_NAME)+2);
108     strcpy(idfile, home);
109     strcat(idfile, "/");
110     strcat(idfile, IDFILE_NAME);
111   
112     outlevel = O_NORMAL;
113
114     if ((parsestatus = parsecmdline(argc,argv,&cmd_opts)) < 0)
115         exit(PS_SYNTAX);
116
117     /* this hint to stdio should help messages come out in the right order */
118     setvbuf(stdout, NULL, _IOLBF, POPBUFSIZE);
119
120     if (versioninfo)
121     {
122         printf("This is fetchmail release %s", RELEASE_ID);
123 #ifdef POP2_ENABLE
124         printf("+POP2");
125 #endif /* POP2_ENABLE */
126 #ifndef POP3_ENABLE
127         printf("-POP3");
128 #endif /* POP3_ENABLE */
129 #ifndef IMAP_ENABLE
130         printf("-IMAP");
131 #endif /* IMAP_ENABLE */
132 #ifdef RPA_ENABLE
133         printf("+RPA");
134 #endif /* RPA_ENABLE */
135 #ifndef ETRN_ENABLE
136         printf("-ETRN");
137 #endif /* ETRN_ENABLE */
138         putchar('\n');
139
140         /* this is an attempt to help remote debugging */
141         system("uname -a");
142     }
143
144     /* avoid parsing the config file if all we're doing is killing a daemon */ 
145     if (!(quitmode && argc == 2))
146         implicitmode = load_params(argc, argv, optind);
147
148     /* set up to do lock protocol */
149     if (!getuid())
150         sprintf(tmpbuf, "%s/fetchmail.pid", PID_DIR);
151     else {
152         strcpy(tmpbuf, home);
153         strcat(tmpbuf, "/.fetchmail.pid");
154     }
155
156     /* perhaps we just want to check options? */
157     if (versioninfo) {
158         printf("Taking options from command line");
159         if (access(rcfile, 0))
160             printf("\n");
161         else
162             printf(" and %s\n", rcfile);
163         if (poll_interval)
164             printf("Poll interval is %d seconds\n", poll_interval);
165         if (outlevel == O_VERBOSE)
166             printf("Lockfile at %s\n", tmpbuf);
167         if (logfile)
168             printf("Logfile is %s\n", logfile);
169 #if defined(HAVE_SYSLOG)
170         if (errors_to_syslog)
171             printf("Progress messages will be logged via syslog\n");
172 #endif
173         if (use_invisible)
174             printf("Fetchmail will masquerade and will not generate Received\n");
175         for (ctl = querylist; ctl; ctl = ctl->next) {
176             if (ctl->active && !(implicitmode && ctl->server.skip))
177                 dump_params(ctl);
178         }
179         if (querylist == NULL)
180             (void) fprintf(stderr,
181                 "No mailservers set up -- perhaps %s is missing?\n", rcfile);
182         exit(0);
183     }
184
185     /* check for another fetchmail running concurrently */
186     pid = -1;
187     if ((lockfile = (char *) malloc(strlen(tmpbuf) + 1)) == NULL)
188     {
189         fprintf(stderr,"fetchmail: cannot allocate memory for lock name.\n");
190         exit(PS_EXCLUDE);
191     }
192     else
193         (void) strcpy(lockfile, tmpbuf);
194     if ((lockfp = fopen(lockfile, "r")) != NULL )
195     {
196         bkgd = (fscanf(lockfp,"%d %d", &pid, &st) == 2);
197
198         if (kill(pid, 0) == -1) {
199             fprintf(stderr,"fetchmail: removing stale lockfile\n");
200             pid = -1;
201             bkgd = FALSE;
202             unlink(lockfile);
203         }
204         fclose(lockfp);
205     }
206
207     /* if no mail servers listed and nothing in background, we're done */
208     if (!(quitmode && argc == 2) && pid == -1 && querylist == NULL) {
209         (void)fputs("fetchmail: no mailservers have been specified.\n",stderr);
210         exit(PS_SYNTAX);
211     }
212
213     /* perhaps user asked us to kill the other fetchmail */
214     if (quitmode)
215     {
216         if (pid == -1) 
217         {
218             fprintf(stderr,"fetchmail: no other fetchmail is running\n");
219             if (argc == 2)
220                 exit(PS_EXCLUDE);
221         }
222         else if (kill(pid, SIGTERM) < 0)
223         {
224             fprintf(stderr,"fetchmail: error killing %s fetchmail at %d; bailing out.\n",
225                     bkgd ? "background" : "foreground", pid);
226             exit(PS_EXCLUDE);
227         }
228         else
229         {
230             fprintf(stderr,"fetchmail: %s fetchmail at %d killed.\n",
231                     bkgd ? "background" : "foreground", pid);
232             unlink(lockfile);
233             if (argc == 2)
234                 exit(0);
235             else
236                 pid = -1; 
237         }
238     }
239
240     /* another fetchmail is running -- wake it up or die */
241     if (pid != -1)
242     {
243         if (check_only)
244         {
245             fprintf(stderr,
246                  "fetchmail: can't check mail while another fetchmail to same host is running.\n");
247             return(PS_EXCLUDE);
248         }
249         else if (!implicitmode)
250         {
251             fprintf(stderr,
252                  "fetchmail: can't poll specified hosts with another fetchmail running at %d.\n",
253                  pid);
254                 return(PS_EXCLUDE);
255         }
256         else if (!bkgd)
257         {
258             fprintf(stderr,
259                  "fetchmail: another foreground fetchmail is running at %d.\n",
260                  pid);
261                 return(PS_EXCLUDE);
262         }
263         else if (argc > 1)
264         {
265             fprintf(stderr,
266                     "fetchmail: can't accept options while a background fetchmail is running.\n");
267             return(PS_EXCLUDE);
268         }
269         else if (kill(pid, SIGUSR1) == 0)
270         {
271             fprintf(stderr,
272                     "fetchmail: background fetchmail at %d awakened.\n",
273                     pid);
274             return(0);
275         }
276         else
277         {
278             /*
279              * Should never happen -- possible only if a background fetchmail
280              * croaks after the first kill probe above but before the
281              * SIGUSR1/SIGHUP transmission.
282              */
283             fprintf(stderr,
284                     "fetchmail: elder sibling at %d died mysteriously.\n",
285                     pid);
286             return(PS_UNDEFINED);
287         }
288     }
289
290     /* parse the ~/.netrc file (if present) for future password lookups. */
291     netrc_file = (char *) xmalloc (strlen (home) + 8);
292     strcpy (netrc_file, home);
293     strcat (netrc_file, "/.netrc");
294     netrc_list = parse_netrc(netrc_file);
295
296     /* pick up interactively any passwords we need but don't have */ 
297     for (ctl = querylist; ctl; ctl = ctl->next)
298         if (ctl->active && !(implicitmode && ctl->server.skip)&&!ctl->password)
299         {
300             if (ctl->server.preauthenticate == A_KERBEROS_V4 || ctl->server.protocol == P_IMAP_K4 || ctl->server.protocol == P_IMAP_GSS)
301                 /* Server won't care what the password is, but there
302                    must be some non-null string here.  */
303                 ctl->password = ctl->remotename;
304             else
305             {
306                 /* look up the host and account in the .netrc file. */
307                 netrc_entry *p = search_netrc(netrc_list,ctl->server.pollname);
308                 while (p && strcmp(p->account, ctl->remotename))
309                     p = search_netrc(p->next, ctl->remotename);
310
311                 /* if we find a matching entry with a password, use it */
312                 if (p && p->password)
313                     ctl->password = xstrdup(p->password);
314             }
315
316             if (ctl->server.protocol != P_ETRN && ctl->server.protocol != P_IMAP_K4 && ctl->server.protocol != P_IMAP_GSS && !ctl->password)
317             {
318                 (void) sprintf(tmpbuf, "Enter password for %s@%s: ",
319                                ctl->remotename, ctl->server.pollname);
320                 ctl->password = xstrdup((char *)getpassword(tmpbuf));
321             }
322         }
323
324     /*
325      * Maybe time to go to demon mode...
326      */
327 #if defined(HAVE_SYSLOG)
328     if (errors_to_syslog)
329     {
330         openlog(program_name, LOG_PID, LOG_MAIL);
331         error_init(-1);
332     }
333     else
334 #endif
335         error_init(poll_interval == 0 && !logfile);
336
337     if (poll_interval)
338     {
339         if (!nodetach)
340             daemonize(logfile, termhook);
341         error( 0, 0, "starting fetchmail %s daemon ", RELEASE_ID);
342
343         /*
344          * We'll set up a handler for these when we're sleeping,
345          * but ignore them otherwise so as not to interrupt a poll.
346          */
347         signal(SIGUSR1, SIG_IGN);
348         if (poll_interval && !getuid())
349             signal(SIGHUP, SIG_IGN);
350     }
351
352     /* beyond here we don't want more than one fetchmail running per user */
353     umask(0077);
354     signal(SIGABRT, termhook);
355     signal(SIGINT, termhook);
356     signal(SIGTERM, termhook);
357     signal(SIGALRM, termhook);
358     signal(SIGPIPE, termhook);
359     signal(SIGQUIT, termhook);
360
361     /* here's the exclusion lock */
362     if ((lockfp = fopen(lockfile,"w")) != NULL) {
363         fprintf(lockfp,"%d",getpid());
364         if (poll_interval)
365             fprintf(lockfp," %d", poll_interval);
366         fclose(lockfp);
367
368 #ifdef HAVE_ATEXIT
369         atexit(unlockit);
370 #endif
371 #ifdef HAVE_ON_EXIT
372         on_exit(unlockit, (char *)NULL);
373 #endif
374     }
375
376     /*
377      * Query all hosts. If there's only one, the error return will
378      * reflect the status of that transaction.
379      */
380     do {
381 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
382         /*
383          * This was an efficiency hack that backfired.  The theory
384          * was that using TCP/IP for DNS queries would get us better
385          * reliability and shave off some per-UDP-packet costs.
386          * Unfortunately it interacted badly with diald, which effectively 
387          * filters out DNS queries over TCP/IP for reasons having to do
388          * with some obscure kernel problem involving bootstrapping of
389          * dynamically-addressed links.  I don't understand this mess
390          * and don't want to, so it's "See ya!" to this hack.
391          */
392         sethostent(TRUE);       /* use TCP/IP for mailserver queries */
393 #endif /* HAVE_RES_SEARCH */
394
395         batchcount = 0;
396         for (ctl = querylist; ctl; ctl = ctl->next)
397         {
398             if (ctl->active && !(implicitmode && ctl->server.skip))
399             {
400                 /* check skip interval first so that it counts all polls */
401                 if (poll_interval && ctl->server.interval) 
402                 {
403                     if (ctl->server.poll_count++ % ctl->server.interval) 
404                     {
405                         if (outlevel == O_VERBOSE)
406                             fprintf(stderr,
407                                     "fetchmail: interval not reached, not querying %s\n",
408                                     ctl->server.pollname);
409                         continue;
410                     }
411                 }
412
413 #ifdef linux
414                 /* interface_approve() does its own error logging */
415                 if (!interface_approve(&ctl->server))
416                     continue;
417 #endif /* linux */
418
419 #ifdef HAVE_GETHOSTBYNAME
420                 /*
421                  * This functions partly as a probe to make sure our
422                  * nameserver is still up.  The multidrop case
423                  * (especially) needs it.
424                  */
425                 if (ctl->server.preauthenticate==A_KERBEROS_V4 || MULTIDROP(ctl))
426                 {
427                     struct hostent      *namerec;
428
429                     /* compute the canonical name of the host */
430                     errno = 0;
431                     namerec = gethostbyname(ctl->server.queryname);
432                     if (namerec == (struct hostent *)NULL)
433                     {
434                         error(0, errno,
435                                 "skipping %s poll, ",
436                                 ctl->server.pollname);
437                         if (errno)
438                         {
439                             if (errno == ENETUNREACH)
440                                 break;  /* go to sleep */
441                         }
442 #ifdef HAVE_HERROR              /* NEXTSTEP doesn't */
443                         else
444                             herror("DNS error");
445 #endif /* HAVE_HERROR */
446                         continue;
447                     }
448                     else
449                     {
450                         free(ctl->server.truename);
451                         ctl->server.truename=xstrdup((char *)namerec->h_name);
452                     }
453                 }
454 #endif /* HAVE_GETHOSTBYNAME */
455
456                 querystatus = query_host(ctl);
457
458                 if (querystatus == PS_SUCCESS) {
459                     successes++;
460 #ifdef POP3_ENABLE
461                     if (!check_only)
462                       update_str_lists(ctl);
463 #endif  /* POP3_ENABLE */
464                 }
465 #ifdef  linux
466                 if (ctl->server.monitor)
467                     {
468                         /* Allow some time for the link to quiesce.  One
469                          * second is usually sufficient, three is safe.
470                          * Note:  this delay is important - don't remove!
471                          */
472                         sleep(3);
473                         interface_note_activity(&ctl->server);
474                     }
475 #endif
476             }
477         }
478
479 #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS)
480         endhostent();           /* release TCP/IP connection to nameserver */
481 #endif /* HAVE_RES_SEARCH */
482
483         /*
484          * Close all SMTP delivery sockets.  For optimum performance
485          * we'd like to hold them open til end of run, but (1) this
486          * loses if our poll interval is longer than the MTA's inactivity
487          * timeout, and (2) some MTAs (like smail) don't deliver after
488          * each message, but rather queue up mail and wait to actually
489          * deliver it until the input socket is closed. 
490          */
491         for (ctl = querylist; ctl; ctl = ctl->next)
492             if (ctl->smtp_socket != -1)
493             {
494                 SMTP_quit(ctl->smtp_socket);
495                 close(ctl->smtp_socket);
496                 ctl->smtp_socket = -1;
497             }
498
499         /*
500          * OK, we've polled.  Now sleep.
501          */
502         if (poll_interval)
503         {
504             if (outlevel == O_VERBOSE)
505             {
506                 time_t  now;
507
508                 time(&now);
509                 fprintf(stderr, "fetchmail: sleeping at %s", ctime(&now));
510             }
511
512             /*
513              * With this simple hack, we make it possible for a foreground 
514              * fetchmail to wake up one in daemon mode.  What we want is the
515              * side effect of interrupting any sleep that may be going on,
516              * forcing fetchmail to re-poll its hosts.  The second line is
517              * for people who think all system daemons wake up on SIGHUP.
518              */
519             signal(SIGUSR1, donothing);
520             if (!getuid())
521                 signal(SIGHUP, donothing);
522
523             /*
524              * We can't use sleep(3) here because we need an alarm(3)
525              * equivalent in order to implement server nonresponse timeout.
526              * We'll just assume setitimer(2) is available since fetchmail
527              * has to have a BSDoid socket layer to work at all.
528              */
529             {
530                 struct itimerval ntimeout;
531
532                 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
533                 ntimeout.it_value.tv_sec  = poll_interval;
534                 ntimeout.it_value.tv_usec = 0;
535
536                 setitimer(ITIMER_REAL,&ntimeout,NULL);
537                 signal(SIGALRM, donothing);
538                 pause();
539                 signal(SIGALRM, SIG_IGN);
540                 if (lastsig == SIGUSR1
541                         || ((poll_interval && !getuid()) && lastsig == SIGHUP))
542                 {
543 #ifdef SYS_SIGLIST_DECLARED
544                     error(0, 0, "awakened by %s", sys_siglist[lastsig]);
545 #else
546                     error(0, 0, "awakened by signal %d", lastsig);
547 #endif
548                 }
549             }
550
551             /* now lock out interrupts again */
552             signal(SIGUSR1, SIG_IGN);
553             if (!getuid())
554                 signal(SIGHUP, SIG_IGN);
555
556             if (outlevel == O_VERBOSE)
557             {
558                 time_t  now;
559
560                 time(&now);
561                 fprintf(stderr, "fetchmail: awakened at %s", ctime(&now));
562             }
563         }
564     } while
565         (poll_interval);
566
567     if (outlevel == O_VERBOSE)
568         fprintf(stderr,"fetchmail: normal termination, status %d\n",
569                 successes ? PS_SUCCESS : querystatus);
570
571     termhook(0);
572     exit(successes ? PS_SUCCESS : querystatus);
573 }
574
575 static int load_params(int argc, char **argv, int optind)
576 {
577     int implicitmode, st;
578     struct passwd *pw;
579     struct query def_opts, *ctl;
580
581     memset(&def_opts, '\0', sizeof(struct query));
582     def_opts.smtp_socket = -1;
583     def_opts.smtpaddress = (char *)0;
584
585     def_opts.server.protocol = P_AUTO;
586     def_opts.server.timeout = CLIENT_TIMEOUT;
587     def_opts.remotename = user;
588     def_opts.expunge = 1;
589
590     /* this builds the host list */
591     if (prc_parse_file(rcfile, !versioninfo) != 0)
592         exit(PS_SYNTAX);
593
594     if ((implicitmode = (optind >= argc)))
595     {
596         for (ctl = querylist; ctl; ctl = ctl->next)
597             ctl->active = TRUE;
598     }
599     else
600         for (; optind < argc; optind++) 
601         {
602             /*
603              * If hostname corresponds to a host known from the rc file,
604              * simply declare it active.  Otherwise synthesize a host
605              * record from command line and defaults
606              */
607             for (ctl = querylist; ctl; ctl = ctl->next)
608                 if (!strcmp(ctl->server.pollname, argv[optind])
609                         || str_in_list(&ctl->server.akalist, argv[optind]))
610                     goto foundit;
611
612             ctl = hostalloc(&cmd_opts);
613             ctl->server.pollname = xstrdup(argv[optind]);
614
615         foundit:
616             ctl->active = TRUE;
617         }
618
619     /* if there's a defaults record, merge it and lose it */ 
620     if (querylist && strcmp(querylist->server.pollname, "defaults") == 0)
621     {
622         for (ctl = querylist->next; ctl; ctl = ctl->next)
623             optmerge(ctl, querylist);
624         querylist = querylist->next;
625     }
626
627     /* don't allow a defaults record after the first */
628     for (ctl = querylist; ctl; ctl = ctl->next)
629         if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0)
630             exit(PS_SYNTAX);
631
632     /* merge in wired defaults, do sanity checks and prepare internal fields */
633     for (ctl = querylist; ctl; ctl = ctl->next)
634     {
635         if (ctl->active && !(implicitmode && ctl->server.skip))
636         {
637             /* merge in defaults */
638             optmerge(ctl, &def_opts);
639
640             /* make sure we have a nonempty host list to forward to */
641             if (!ctl->smtphunt)
642                 save_str(&ctl->smtphunt, FALSE, fetchmailhost);
643
644             /* keep lusers from shooting themselves in the foot :-) */
645             if (poll_interval && ctl->limit)
646             {
647                 fprintf(stderr,"fetchmail: you'd never see large messages!\n");
648                 exit(PS_SYNTAX);
649             }
650
651             /* if `user' doesn't name a real local user, try to run as root */
652             if ((pw = getpwnam(user)) == (struct passwd *)NULL)
653                 ctl->uid = 0;
654             else
655                 ctl->uid = pw->pw_uid;  /* for local delivery via MDA */
656             if (!ctl->localnames)       /* for local delivery via SMTP */
657                 save_str_pair(&ctl->localnames, user, NULL);
658
659             /* this code enables flags to be turned off */
660 #define DEFAULT(flag, dflt)     if (flag == FLAG_TRUE)\
661                                         flag = TRUE;\
662                                 else if (flag == FLAG_FALSE)\
663                                         flag = FALSE;\
664                                 else\
665                                         flag = (dflt)
666             DEFAULT(ctl->keep, FALSE);
667             DEFAULT(ctl->fetchall, FALSE);
668             DEFAULT(ctl->flush, FALSE);
669             DEFAULT(ctl->rewrite, TRUE);
670             DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL)); 
671             DEFAULT(ctl->forcecr, FALSE);
672             DEFAULT(ctl->pass8bits, FALSE);
673             DEFAULT(ctl->dropstatus, FALSE);
674             DEFAULT(ctl->server.dns, TRUE);
675             DEFAULT(ctl->server.uidl, FALSE);
676 #undef DEFAULT
677
678 #if !defined(HAVE_GETHOSTBYNAME) || !defined(HAVE_RES_SEARCH)
679             /* can't handle multidrop mailboxes unless we can do DNS lookups */
680             if (ctl->localnames && ctl->localnames->next && ctl->server.dns)
681             {
682                 ctl->server.dns = FALSE;
683                 fprintf(stderr, "fetchmail: warning: no DNS available to check multidrop fetches from %s\n", ctl->server.pollname);
684             }
685 #endif /* !HAVE_GETHOSTBYNAME || !HAVE_RES_SEARCH */
686
687             /*
688              *
689              * Compute the true name of the mailserver host.  
690              * There are two clashing cases here:
691              *
692              * (1) The poll name is a label, possibly on one of several
693              *     poll configurations for the same host.  In this case 
694              *     the `via' option will be present and give the true name.
695              *
696              * (2) The poll name is the true one, the via name is 
697              *     localhost.   This is going to be typical for ssh-using
698              *     configurations.
699              *
700              * We're going to assume the via name is true unless it's
701              * localhost.
702              *
703              * Each poll cycle, if we've got DNS, we'll try to canonicalize
704              * the name.  This will function as a probe to ensure the
705              * host's nameserver is up.
706              */
707             if (ctl->server.via && strcmp(ctl->server.via, "localhost"))
708                 ctl->server.queryname = xstrdup(ctl->server.via);
709             else
710                 ctl->server.queryname = xstrdup(ctl->server.pollname);
711             ctl->server.truename = xstrdup(ctl->server.queryname);
712
713             /* if no folders were specified, set up the null one as default */
714             if (!ctl->mailboxes)
715                 save_str(&ctl->mailboxes, -1, (char *)NULL);
716
717             /* maybe user overrode timeout on command line? */
718             if (ctl->server.timeout == -1)      
719                 ctl->server.timeout = CLIENT_TIMEOUT;
720
721             /* sanity checks */
722             if (ctl->server.port < 0)
723             {
724                 (void) fprintf(stderr,
725                                "%s configuration invalid, port number cannot be negative",
726                                ctl->server.pollname);
727                 exit(PS_SYNTAX);
728             }
729             if (ctl->server.protocol == P_RPOP && ctl->server.port >= 1024)
730             {
731                 (void) fprintf(stderr,
732                                "%s configuration invalid, RPOP requires a privileged port",
733                                ctl->server.pollname);
734                 exit(PS_SYNTAX);
735             }
736         }
737     }
738
739     /* initialize UID handling */
740     if (!versioninfo && (st = prc_filecheck(idfile)) != 0)
741         exit(st);
742 #ifdef POP3_ENABLE
743     else
744         initialize_saved_lists(querylist, idfile);
745 #endif /* POP3_ENABLE */
746
747     /* if cmd_logfile was explicitly set, use it to override logfile */
748     if (cmd_logfile)
749         logfile = cmd_logfile;
750
751     /* likewise for poll_interval */
752     if (cmd_daemon >= 0)
753         poll_interval = cmd_daemon;
754
755     /* check and daemon options are not compatible */
756     if (check_only && poll_interval)
757         poll_interval = 0;
758
759     return(implicitmode);
760 }
761
762 void termhook(int sig)
763 /* to be executed on normal or signal-induced termination */
764 {
765     struct query        *ctl;
766
767     /*
768      * Sending SMTP QUIT on signal is theoretically nice, but led to a 
769      * subtle bug.  If fetchmail was terminated by signal while it was 
770      * shipping message text, it would hang forever waiting for a
771      * command acknowledge.  In theory we could enable the QUIT
772      * only outside of the message send.  In practice, we don't
773      * care.  All mailservers hang up on a dropped TCP/IP connection
774      * anyway.
775      */
776
777     if (sig != 0)
778         error(0, 0, "terminated with signal %d", sig);
779     else
780         /* terminate all SMTP connections cleanly */
781         for (ctl = querylist; ctl; ctl = ctl->next)
782             if (ctl->smtp_socket != -1)
783                 SMTP_quit(ctl->smtp_socket);
784
785 #ifdef POP3_ENABLE
786     if (!check_only)
787         write_saved_lists(querylist, idfile);
788 #endif /* POP3_ENABLE */
789
790     /* 
791      * Craig Metz, the RFC1938 one-time-password guy, points out:
792      * "Remember that most kernels don't zero pages before handing them to the
793      * next process and many kernels share pages between user and kernel space.
794      * You'd be very surprised what you can find from a short program to do a
795      * malloc() and then dump the contents of the pages you got. By zeroing
796      * the secrets at end of run (earlier if you can), you make sure the next
797      * guy can't get the password/pass phrase."
798      *
799      * Right you are, Craig!
800      */
801     for (ctl = querylist; ctl; ctl = ctl->next)
802         if (ctl->password)
803           memset(ctl->password, '\0', strlen(ctl->password));
804
805 #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
806     unlockit();
807 #endif
808
809     exit(successes ? PS_SUCCESS : querystatus);
810 }
811
812 /*
813  * Sequence of protocols to try when autoprobing, most capable to least.
814  */
815 static const int autoprobe[] = 
816 {
817 #ifdef IMAP_ENABLE
818     P_IMAP,
819 #endif /* IMAP_ENABLE */
820 #ifdef POP3_ENABLE
821     P_POP3,
822 #endif /* POP3_ENABLE */
823 #ifdef POP2_ENABLE
824     P_POP2
825 #endif /* POP2_ENABLE */
826 };
827
828 static int query_host(struct query *ctl)
829 /* perform fetch transaction with single host */
830 {
831     int i, st;
832
833     if (outlevel == O_VERBOSE)
834     {
835         time_t now;
836
837         time(&now);
838         fprintf(stderr, "fetchmail: %s querying %s (protocol %s) at %s",
839             RELEASE_ID,
840             ctl->server.pollname, showproto(ctl->server.protocol), ctime(&now));
841     }
842     switch (ctl->server.protocol) {
843     case P_AUTO:
844         for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++)
845         {
846             ctl->server.protocol = autoprobe[i];
847             if ((st = query_host(ctl)) == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP)
848                 break;
849         }
850         ctl->server.protocol = P_AUTO;
851         return(st);
852         break;
853     case P_POP2:
854 #ifdef POP2_ENABLE
855         return(doPOP2(ctl));
856 #else
857         fprintf(stderr, "POP2 support is not configured.\n");
858         return(PS_PROTOCOL);
859 #endif /* POP2_ENABLE */
860         break;
861     case P_POP3:
862     case P_APOP:
863     case P_RPOP:
864 #ifdef POP3_ENABLE
865         return(doPOP3(ctl));
866 #else
867         fprintf(stderr, "POP3 support is not configured.\n");
868         return(PS_PROTOCOL);
869 #endif /* POP3_ENABLE */
870         break;
871     case P_IMAP:
872     case P_IMAP_K4:
873     case P_IMAP_GSS:
874 #ifdef IMAP_ENABLE
875         return(doIMAP(ctl));
876 #else
877         fprintf(stderr, "IMAP support is not configured.\n");
878         return(PS_PROTOCOL);
879 #endif /* IMAP_ENABLE */
880         break;
881     case P_ETRN:
882 #ifndef ETRN_ENABLE
883         fprintf(stderr, "ETRN support is not configured.\n");
884         return(PS_PROTOCOL);
885 #else
886 #ifdef HAVE_GETHOSTBYNAME
887         return(doETRN(ctl));
888 #else
889         fprintf(stderr, "Cannot support ETRN without gethostbyname(2).\n");
890         return(PS_PROTOCOL);
891 #endif /* HAVE_GETHOSTBYNAME */
892 #endif /* ETRN_ENABLE */
893     default:
894         error(0, 0, "unsupported protocol selected.");
895         return(PS_PROTOCOL);
896     }
897 }
898
899 void dump_params (struct query *ctl)
900 /* display query parameters in English */
901 {
902     printf("Options for retrieving from %s@%s:\n",
903            ctl->remotename, visbuf(ctl->server.pollname));
904
905     if (ctl->server.via)
906         printf("  Mail will be retrieved via %s\n", ctl->server.via);
907
908     if (ctl->server.interval)
909         printf("  Poll of this server will occur every %d intervals.\n",
910                ctl->server.interval);
911     if (ctl->server.truename)
912         printf("  True name of server is %s.\n", ctl->server.truename);
913     if (ctl->server.skip || outlevel == O_VERBOSE)
914         printf("  This host will%s be queried when no host is specified.\n",
915                ctl->server.skip ? " not" : "");
916     if (!ctl->password)
917         printf("  Password will be prompted for.\n");
918     else if (outlevel == O_VERBOSE)
919         if (ctl->server.protocol == P_APOP)
920             printf("  APOP secret = '%s'.\n", visbuf(ctl->password));
921         else if (ctl->server.protocol == P_RPOP)
922             printf("  RPOP id = '%s'.\n", visbuf(ctl->password));
923         else
924             printf("  Password = '%s'.\n", visbuf(ctl->password));
925     if (ctl->server.protocol == P_POP3 
926                 && ctl->server.port == KPOP_PORT
927                 && ctl->server.preauthenticate == A_KERBEROS_V4)
928         printf("  Protocol is KPOP");
929     else
930         printf("  Protocol is %s", showproto(ctl->server.protocol));
931     if (ctl->server.port)
932         printf(" (using port %d)", ctl->server.port);
933     else if (outlevel == O_VERBOSE)
934         printf(" (using default port)");
935     if (ctl->server.uidl)
936         printf(" (forcing UIDL use)");
937     putchar('.');
938     putchar('\n');
939     if (ctl->server.preauthenticate == A_KERBEROS_V4)
940             printf("  Kerberos V4 preauthentication enabled.\n");
941     if (ctl->server.timeout > 0)
942         printf("  Server nonresponse timeout is %d seconds", ctl->server.timeout);
943     if (ctl->server.timeout ==  CLIENT_TIMEOUT)
944         printf(" (default).\n");
945     else
946         printf(".\n");
947
948     if (!ctl->mailboxes->id)
949         printf("  Default mailbox selected.\n");
950     else
951     {
952         struct idlist *idp;
953
954         printf("  Selected mailboxes are:");
955         for (idp = ctl->mailboxes; idp; idp = idp->next)
956             printf(" %s", idp->id);
957         printf("\n");
958     }
959     printf("  %s messages will be retrieved (--all %s).\n",
960            ctl->fetchall ? "All" : "Only new",
961            ctl->fetchall ? "on" : "off");
962     printf("  Fetched messages will%s be kept on the server (--keep %s).\n",
963            ctl->keep ? "" : " not",
964            ctl->keep ? "on" : "off");
965     printf("  Old messages will%s be flushed before message retrieval (--flush %s).\n",
966            ctl->flush ? "" : " not",
967            ctl->flush ? "on" : "off");
968     printf("  Rewrite of server-local addresses is %sabled (--norewrite %s).\n",
969            ctl->rewrite ? "en" : "dis",
970            ctl->rewrite ? "off" : "on");
971     printf("  Carriage-return stripping is %sabled (stripcr %s).\n",
972            ctl->stripcr ? "en" : "dis",
973            ctl->stripcr ? "on" : "off");
974     printf("  Carriage-return forcing is %sabled (forcecr %s).\n",
975            ctl->forcecr ? "en" : "dis",
976            ctl->forcecr ? "on" : "off");
977     printf("  Interpretation of Content-Transfer-Encoding is %sabled (pass8bits %s).\n",
978            ctl->pass8bits ? "dis" : "en",
979            ctl->pass8bits ? "on" : "off");
980     printf("  Nonempty Status lines will be %s (dropstatus %s)\n",
981            ctl->dropstatus ? "discarded" : "kept",
982            ctl->dropstatus ? "on" : "off");
983     if (NUM_NONZERO(ctl->limit))
984         printf("  Message size limit is %d bytes (--limit %d).\n", 
985                ctl->limit, ctl->limit);
986     else if (outlevel == O_VERBOSE)
987         printf("  No message size limit (--limit 0).\n");
988     if (NUM_NONZERO(ctl->fetchlimit))
989         printf("  Received-message limit is %d (--fetchlimit %d).\n",
990                ctl->fetchlimit, ctl->fetchlimit);
991     else if (outlevel == O_VERBOSE)
992         printf("  No received-message limit (--fetchlimit 0).\n");
993     if (NUM_NONZERO(ctl->batchlimit))
994         printf("  SMTP message batch limit is %d.\n", ctl->batchlimit);
995     else if (outlevel == O_VERBOSE)
996         printf("  No SMTP message batch limit (--batchlimit 0).\n");
997     if (ctl->server.protocol == P_IMAP)
998         if (NUM_NONZERO(ctl->expunge))
999             printf("  Deletion interval between expunges is %d (--expunge %d).\n", ctl->expunge, ctl->expunge);
1000         else if (outlevel == O_VERBOSE)
1001             printf("  No expunges (--expunge 0).\n");
1002     if (ctl->mda)
1003         printf("  Messages will be delivered with '%s.'\n", visbuf(ctl->mda));
1004     else
1005     {
1006         struct idlist *idp;
1007
1008         printf("  Messages will be SMTP-forwarded to:");
1009         for (idp = ctl->smtphunt; idp; idp = idp->next)
1010             if (ctl->server.protocol != P_ETRN || idp->val.num)
1011             {
1012                 printf(" %s", idp->id);
1013                 if (!idp->val.num)
1014                     printf(" (default)");
1015             }
1016         printf("\n");
1017         if (ctl->smtpaddress)
1018             printf("  Host part of MAIL FROM line will be %s\n",
1019                    ctl->smtpaddress);
1020     }
1021     if (ctl->preconnect)
1022         printf("  Server connection will be brought up with '%s.'\n",
1023                visbuf(ctl->preconnect));
1024     else if (outlevel == O_VERBOSE)
1025         printf("  No pre-connection command.\n");
1026     if (ctl->postconnect)
1027         printf("  Server connection will be taken down with '%s.'\n",
1028                visbuf(ctl->postconnect));
1029     else if (outlevel == O_VERBOSE)
1030         printf("  No post-connection command.\n");
1031     if (!ctl->localnames)
1032         printf("  No localnames declared for this host.\n");
1033     else
1034     {
1035         struct idlist *idp;
1036         int count = 0;
1037
1038         for (idp = ctl->localnames; idp; idp = idp->next)
1039             ++count;
1040
1041         if (count > 1 || ctl->wildcard)
1042             printf("  Multi-drop mode: ");
1043         else
1044             printf("  Single-drop mode: ");
1045
1046         printf("%d local name(s) recognized.\n", count);
1047         if (outlevel == O_VERBOSE)
1048         {
1049             for (idp = ctl->localnames; idp; idp = idp->next)
1050                 if (idp->val.id2)
1051                     printf("\t%s -> %s\n", idp->id, idp->val.id2);
1052                 else
1053                     printf("\t%s\n", idp->id);
1054             if (ctl->wildcard)
1055                 fputs("*\n", stdout);
1056         }
1057
1058         if (count > 1 || ctl->wildcard)
1059         {
1060             printf("  DNS lookup for multidrop addresses is %sabled.\n",
1061                    ctl->server.dns ? "en" : "dis");
1062
1063             if (ctl->server.envelope == STRING_DISABLED)
1064                 printf("  Envelope-address routing is disabled\n");
1065             else
1066             {
1067                 printf("  Envelope header is assumed to be: %s\n",
1068                        ctl->server.envelope ? ctl->server.envelope:"Received");
1069                 if (ctl->server.envskip > 1 || outlevel >= O_VERBOSE)
1070                     printf("  Number of envelope header to be parsed: %d\n",
1071                            ctl->server.envskip);
1072                 if (ctl->server.qvirtual)
1073                     printf("  Prefix %s will be removed from user id\n",
1074                            ctl->server.qvirtual);
1075                 else if (outlevel >= O_VERBOSE) 
1076                     printf("  No prefix stripping\n");
1077             }
1078
1079             if (ctl->server.akalist)
1080             {
1081                 struct idlist *idp;
1082
1083                 printf("  Predeclared mailserver aliases:");
1084                 for (idp = ctl->server.akalist; idp; idp = idp->next)
1085                     printf(" %s", idp->id);
1086                 putchar('\n');
1087             }
1088             if (ctl->server.localdomains)
1089             {
1090                 struct idlist *idp;
1091
1092                 printf("  Local domains:");
1093                 for (idp = ctl->server.localdomains; idp; idp = idp->next)
1094                     printf(" %s", idp->id);
1095                 putchar('\n');
1096             }
1097         }
1098     }
1099 #ifdef  linux
1100     if (ctl->server.interface)
1101         printf("  Connection must be through interface %s.\n", ctl->server.interface);
1102     else if (outlevel == O_VERBOSE)
1103         printf("  No interface requirement specified.\n");
1104     if (ctl->server.monitor)
1105         printf("  Polling loop will monitor %s.\n", ctl->server.monitor);
1106     else if (outlevel == O_VERBOSE)
1107         printf("  No monitor interface specified.\n");
1108 #endif
1109
1110     if (ctl->server.protocol > P_POP2)
1111         if (!ctl->oldsaved)
1112             printf("  No UIDs saved from this host.\n");
1113         else
1114         {
1115             struct idlist *idp;
1116             int count = 0;
1117
1118             for (idp = ctl->oldsaved; idp; idp = idp->next)
1119                 ++count;
1120
1121             printf("  %d UIDs saved.\n", count);
1122             if (outlevel == O_VERBOSE)
1123                 for (idp = ctl->oldsaved; idp; idp = idp->next)
1124                     fprintf(stderr, "\t%s\n", idp->id);
1125         }
1126 }
1127
1128 /* fetchmail.c ends here */