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