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