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