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