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