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