aboutsummaryrefslogtreecommitdiffstats
path: root/fetchmail.h
blob: c0f72f69af097407ef190737ebfeabe583601078 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/*
 * For license terms, see the file COPYING in this directory.
 */

/* We need this for HAVE_STDARG_H, etc */
#include "config.h"

/* constants designating the various supported protocols */
#define		P_AUTO		1
#define		P_POP2		2
#define		P_POP3		3
#define		P_APOP		4
#define		P_RPOP		5
#define		P_IMAP		6
#define		P_IMAP_K4	7
#define		P_IMAP_GSS	8
#define		P_IMAP_CRAM_MD5	9
#define		P_IMAP_LOGIN	10
#define		P_ETRN		11
#define		P_ODMR		12

#if INET6_ENABLE
#define		SMTP_PORT	"smtp"
#define		KPOP_PORT	"kpop"
#else /* INET6_ENABLE */
#define		SMTP_PORT	25
#define		KPOP_PORT	1109
#endif /* INET6_ENABLE */

#ifdef SSL_ENABLE
#define		SIMAP_PORT	993
#define		SPOP3_PORT	995
#endif

/* preauthentication types */
#define		A_PASSWORD	0	/* password or inline authentication */
#define		A_KERBEROS_V4	1	/* preauthenticate w/ Kerberos V4 */
#define		A_KERBEROS_V5	2	/* preauthenticate w/ Kerberos V5 */
#define		A_SSH		3	/* preauthentication at session level */

/*
 * Definitions for buffer sizes.  We get little help on setting maxima
 * from IMAP RFCs up to 2060, so these are mostly from POP3.
 */
#define		HOSTLEN		635	/* max hostname length (RFC1123) */
#define		POPBUFSIZE	512	/* max length of response (RFC1939) */
#define		IDLEN		128	/* max length of UID (RFC1939) */

/* per RFC1939 this should be 40, but Microsoft Exchange ignores that limit */
#define		USERNAMELEN	128	/* max POP3 arg length */

/* clear a netBSD kernel parameter out of the way */ 
#undef		MSGBUFSIZE

/*
 * The RFC822 limit on message line size is just 998.  But
 * make this *way* oversized; idiot DOS-world mailers that
 * don't line-wrap properly often ship entire paragraphs as
 * lines.
 */
#define		MSGBUFSIZE	8192

#define		NAMELEN		64	/* max username length */
#define		PASSWORDLEN	64	/* max password length */
#define		DIGESTLEN	33	/* length of MD5 digest */

/* exit code values */
#define		PS_SUCCESS	0	/* successful receipt of messages */
#define		PS_NOMAIL       1	/* no mail available */
#define		PS_SOCKET	2	/* socket I/O woes */
#define		PS_AUTHFAIL	3	/* user authorization failed */
#define		PS_PROTOCOL	4	/* protocol violation */
#define		PS_SYNTAX	5	/* command-line syntax error */
#define		PS_IOERR	6	/* bad permissions on rc file */
#define		PS_ERROR	7	/* protocol error */
#define		PS_EXCLUDE	8	/* client-side exclusion error */
#define		PS_LOCKBUSY	9	/* server responded lock busy */
#define		PS_SMTP         10      /* SMTP error */
#define		PS_DNS		11	/* fatal DNS error */
#define		PS_BSMTP	12	/* output batch could not be opened */
#define		PS_MAXFETCH	13	/* poll ended by fetch limit */
/* leave space for more codes */
#define		PS_UNDEFINED	23	/* something I hadn't thought of */
#define		PS_TRANSIENT	24	/* transient failure (internal use) */
#define		PS_REFUSED	25	/* mail refused (internal use) */
#define		PS_RETAINED	26	/* message retained (internal use) */
#define		PS_TRUNCATED	27	/* headers incomplete (internal use) */

/* output noise level */
#define         O_SILENT	0	/* mute, max squelch, etc. */
#define		O_NORMAL	1	/* user-friendly */
#define		O_VERBOSE	2	/* chatty */
#define		O_DEBUG		3	/* prolix */
#define		O_MONITOR	O_VERBOSE

#define		SIZETICKER	1024	/* print 1 dot per this many bytes */

/*
 * We #ifdef this and use flag rather than bool
 * to avoid a type clash with curses.h
 */
#ifndef TRUE
#define FALSE	0
#define TRUE	1
#endif /* TRUE */
typedef	char	flag;

/* we need to use zero as a flag-uninitialized value */
#define FLAG_TRUE	2
#define FLAG_FALSE	1

struct runctl
{
    char	*logfile;
    char	*idfile;
    int		poll_interval;
    char	*postmaster;
    flag	bouncemail;
    flag	spambounce;
    char	*properties;
    flag	use_syslog;
    flag	invisible;
    flag	showdots;
};

struct idlist
{
    unsigned char *id;
    union
    {
	struct
	{
	    short	num;
	    flag	mark;		/* UID-index information */
#define UID_UNSEEN	0		/* hasn't been seen */
#define UID_SEEN	1		/* seen, but not deleted */
#define UID_DELETED	2		/* this message has been deleted */
#define UID_EXPUNGED	3		/* this message has been expunged */ 
        }
	status;
	unsigned char *id2;
    } val;
    struct idlist *next;
};

struct query;

struct method		/* describe methods for protocol state machine */
{
    const char *name;		/* protocol name */
#if INET6_ENABLE
    const char *service;
    const char *sslservice;
#else /* INET6_ENABLE */
    int	port;			/* service port */
    int	sslport;		/* service port for ssl */
#endif /* INET6_ENABLE */
    flag tagged;		/* if true, generate & expect command tags */
    flag delimited;		/* if true, accept "." message delimiter */
    int (*parse_response)(int, char *);
				/* response_parsing function */
    int (*password_canonify)(char *, char *, int);
				/* canonicalize password */
    int (*getauth)(int, struct query *, char *);
				/* authorization fetcher */
    int (*getrange)(int, struct query *, const char *, int *, int *, int *);
				/* get message range to fetch */
    int (*getsizes)(int, int, int *);
				/* get sizes of messages */
    int (*is_old)(int, struct query *, int);
				/* check for old message */
    int (*fetch_headers)(int, struct query *, int, int *);
				/* fetch FROM headera given message */
    int (*fetch_body)(int, struct query *, int, int *);
				/* fetch a given message */
    int (*trail)(int, struct query *, int);
				/* eat trailer of a message */
    int (*delete)(int, struct query *, int);
				/* delete method */
    int (*logout_cmd)(int, struct query *);
				/* logout command */
    flag retry;			/* can getrange poll for new messages? */
};

struct hostdata		/* shared among all user connections to given server */
{
    /* rc file data */
    char *pollname;			/* poll label of host */
    char *via;				/* "true" server name if non-NULL */
    struct idlist *akalist;		/* server name first, then akas */
    struct idlist *localdomains;	/* list of pass-through domains */
    int protocol;			/* protocol type */
#if INET6_ENABLE
    char *service;			/* IPv6 service name */
    void *netsec;			/* IPv6 security request */
#else /* INET6_ENABLE */
    int port;				/* TCP/IP service port number */
#endif /* INET6_ENABLE */
    int interval;			/* # cycles to skip between polls */
    int preauthenticate;		/* preauthentication mode to try */
    int timeout;			/* inactivity timout in seconds */
    char *envelope;			/* envelope address list header */
    int envskip;			/* skip to numbered envelope header */
    char *qvirtual;			/* prefix removed from local user id */
    flag skip;				/* suppress poll in implicit mode? */
    flag dns;				/* do DNS lookup on multidrop? */
    flag uidl;				/* use RFC1725 UIDLs? */
#ifdef SDPS_ENABLE
    flag sdps;				/* use Demon Internet SDPS *ENV */
#endif /* SDPS_ENABLE */
    flag checkalias;                  	/* resolve aliases by comparing IPs? */
    char *principal;			/* Kerberos principal for mail service */


#if defined(linux) || defined(__FreeBSD__)
    char *interface;
    char *monitor;
    int  monitor_io;
    struct interface_pair_s *interface_pair;
#endif /* linux */

    char *plugin,*plugout;

    /* computed for internal use */
    const struct method *base_protocol;	/* relevant protocol method table */
    int poll_count;			/* count of polls so far */
    char *queryname;			/* name to attempt DNS lookup on */
    char *truename;			/* "true name" of server host */
    char *trueaddr;                     /* IP address of truename, as char */
    struct hostdata *lead_server;	/* ptr to lead query for this server */
    int esmtp_options;
};

struct query
{
    /* mailserver connection controls */
    struct hostdata server;

    /* per-user data */
    struct idlist *localnames;	/* including calling user's name */
    int wildcard;		/* should unmatched names be passed through */
    char *remotename;		/* remote login name to use */
    char *password;		/* remote password to use */
    struct idlist *mailboxes;	/* list of mailboxes to check */

    /* per-forwarding-target data */
    struct idlist *smtphunt;	/* list of SMTP hosts to try forwarding to */
    char *smtpaddress;		/* address to force in RCPT TO */ 
    char *smtpname;             /* full RCPT TO name, including domain */
    struct idlist *antispam;	/* list of listener's antispam response */
    char *mda;			/* local MDA to pass mail to */
    char *bsmtp;		/* BSMTP output file */
    char listener;		/* what's the listener's wire protocol? */
#define SMTP_MODE	'S'
#define LMTP_MODE	'L'
    char *preconnect;		/* pre-connection command to execute */
    char *postconnect;		/* post-connection command to execute */

    /* per-user control flags */
    flag keep;			/* if TRUE, leave messages undeleted */
    flag fetchall;		/* if TRUE, fetch all (not just unseen) */
    flag flush;			/* if TRUE, delete messages already seen */
    flag rewrite;		/* if TRUE, canonicalize recipient addresses */
    flag stripcr;		/* if TRUE, strip CRs in text */
    flag forcecr;		/* if TRUE, force CRs before LFs in text */
    flag pass8bits;		/* if TRUE, ignore Content-Transfer-Encoding */
    flag dropstatus;		/* if TRUE, drop Status lines in mail */
    flag dropdelivered;         /* if TRUE, drop Delivered-To lines in mail */
    flag mimedecode;		/* if TRUE, decode MIME-armored messages */
    flag idle;			/* if TRUE, idle after each poll */
    int	limit;			/* limit size of retrieved messages */
    int warnings;		/* size warning interval */
    int	fetchlimit;		/* max # msgs to get in single poll */
    int	batchlimit;		/* max # msgs to pass in single SMTP session */
    int	expunge;		/* max # msgs to pass between expunges */
    flag use_ssl;		/* use SSL encrypted session */
    char *sslkey;		/* optional SSL private key file */
    char *sslcert;		/* optional SSL certificate file */
    char *properties;		/* passthrough properties for extensions */

    /* internal use -- per-poll state */
    flag active;		/* should we actually poll this server? */
    const char *destaddr;	/* destination host for this query */
    int errcount;		/* count transient errors in last pass */
    int authfailcount;		/* count of authorization failures */
    int wedged;			/* wedged by auth failures or timeouts? */
    char *smtphost;		/* actual SMTP host we connected to */
    int smtp_socket;		/* socket descriptor for SMTP connection */
    unsigned int uid;		/* UID of user to deliver to */
    struct idlist *skipped;	/* messages skipped on the mail server */
    struct idlist *oldsaved, *newsaved;
    char *lastid;		/* last Message-ID seen on this connection */

    /* internal use -- per-message state */
    int mimemsg;		/* bitmask indicating MIME body-type */
    char digest [DIGESTLEN];	/* md5 digest buffer */

    /* internal use -- housekeeping */
    struct query *next;		/* next query control block in chain */
};

struct msgblk			/* message header parsed for open_sink() */
{
    char   		*headers;	/* raw message headers */
    struct idlist	*recipients;	/* addressees */
    char		return_path[HOSTLEN + USERNAMELEN + 4]; 
    int			reallen;
};


/*
 * Numeric option handling.  Numeric option value of zero actually means
 * it's unspecified.  Value less than zero is zero.  The reason for this
 * screwy encoding is so we can zero out an option block in order to set the
 * numeric flags in it to unspecified.
 */
#define NUM_VALUE_IN(n)		(((n) == 0) ? -1 : (n))
#define NUM_VALUE_OUT(n)	(((n) < 0) ? 0 : (n))
#define NUM_NONZERO(n)		((n) > 0)
#define NUM_ZERO(n)		((n) < 0)
#define NUM_SPECIFIED(n)	((n) != 0)

#define MULTIDROP(ctl)	(ctl->wildcard || \
				((ctl)->localnames && (ctl)->localnames->next))

/*
 * Note: tags are generated with an a%04d format from a 1-origin
 * integer sequence number.  Length 4 permits transaction numbers
 * up to 9999, so we force rollover with % 10000.  There's no special
 * reason for this format other than to look like the exmples in the
 * IMAP RFCs.
 */
#define TAGLEN	6		/* 'a' + 4 digits + NUL */
extern char tag[TAGLEN];
#define TAGMOD	10000

/* list of hosts assembled from run control file and command line */
extern struct query cmd_opts, *querylist;

/* what's returned by envquery */
extern void envquery(int, char **);

/* controls the detail level of status/progress messages written to stderr */
extern int outlevel;    	/* see the O_.* constants above */
extern int yydebug;		/* enable parse debugging */

/* these get computed */
extern int batchcount;		/* count of messages sent in current batch */
extern flag peek_capable;	/* can we read msgs without setting seen? */

/* miscellaneous global controls */
extern struct runctl run;	/* global controls for this run */
extern flag nodetach;		/* if TRUE, don't detach daemon process */
extern flag quitmode;		/* if --quit was set */
extern flag check_only;		/* if --check was set */
extern char *rcfile;		/* path name of rc file */
extern int linelimit;		/* limit # lines retrieved per site */
extern flag versioninfo;	/* emit only version info */
extern char *user;		/* name of invoking user */
extern char *home;		/* home directory of invoking user */
extern char *fmhome;		/* fetchmail home directory */
extern int pass;		/* number of re-polling pass */
extern flag configdump;		/* dump control blocks as Python dictionary */
extern const char *fetchmailhost;
				/* either "localhost" or an FQDN */
extern suppress_tags;		/* suppress tags in tagged protocols? */
#ifdef SDPS_ENABLE
extern char *sdps_envfrom;
extern char *sdps_envto;
#endif /* SDPS_ENABLE */

/* prototypes for globally callable functions */

/* error.c: Error reporting */
#if defined(HAVE_STDARG_H)
void report_init(int foreground);
void report (FILE *fp, const char *format, ...);
void report_build (FILE *fp, const char *format, ...);
void report_complete (FILE *fp, const char *format, ...);
void report_at_line (FILE *fp, int, const char *, unsigned int, const char *, ...);
#else
void report ();
void report_build ();
void report_complete ();
void report_at_line ();
#endif

/* driver.c: transaction support */
void set_timeout(int);
#if defined(HAVE_STDARG_H)
void gen_send (int sock, const char *, ... );
int gen_recv(int sock, char *buf, int size);
int gen_transact (int sock, const char *, ... );
#else
void gen_send ();
int gen_recv();
int gen_transact ();
#endif

/* use these to track what was happening when the nonresponse timer fired */
#define GENERAL_WAIT	0	/* unknown wait type */
#define OPEN_WAIT	1	/* waiting from mailserver open */
#define SERVER_WAIT	2	/* waiting for mailserver response */
#define LISTENER_WAIT	3	/* waiting for listener initialization */
#define FORWARDING_WAIT	4	/* waiting for listener response */
extern int phase;

/* response hooks can use this to identify the query stage */
#define STAGE_GETAUTH	0
#define STAGE_GETRANGE	1
#define STAGE_GETSIZES	2
#define STAGE_FETCH	3
#define STAGE_IDLE	4
#define STAGE_LOGOUT	5
extern int stage;

extern int mytimeout;

/* mark values for name lists */
#define XMIT_ACCEPT	1	/* accepted; matches local domain or name */
#define XMIT_REJECT	2	/* rejected; no match */
#define XMIT_RCPTBAD	3	/* SMTP listener rejected the name */ 

/* idle.c */
int interruptible_idle(int interval);

/* sink.c: forwarding */
int stuffline(struct query *, char *);
int open_sink(struct query*, struct msgblk *, int*, int*);
void release_sink(struct query *);
int close_sink(struct query *, struct msgblk *, flag);
int open_warning_by_mail(struct query *, struct msgblk *);
#if defined(HAVE_STDARG_H)
void stuff_warning(struct query *, const char *, ... );
#else
void stuff_warning();
#endif
void close_warning_by_mail(struct query *, struct msgblk *);

/* rfc822.c: RFC822 header parsing */
unsigned char *reply_hack(unsigned char *, const unsigned char *);
unsigned char *nxtaddr(const unsigned char *);

/* uid.c: UID support */
void initialize_saved_lists(struct query *, const char *);
struct idlist *save_str(struct idlist **, const char *, flag);
void free_str_list(struct idlist **);
struct idlist *copy_str_list(struct idlist *idl);
void save_str_pair(struct idlist **, const char *, const char *);
void free_str_pair_list(struct idlist **);
int delete_str(struct idlist **, int);
int str_in_list(struct idlist **, const char *, const flag);
int str_nr_in_list(struct idlist **, const char *);
int str_nr_last_in_list(struct idlist **, const char *);
void str_set_mark( struct idlist **, const char *, const flag);
int count_list( struct idlist **idl );
char *str_from_nr_list( struct idlist **idl, int number );
char *str_find(struct idlist **, int);
char *idpair_find(struct idlist **, const char *);
void append_str_list(struct idlist **, struct idlist **);
void expunge_uids(struct query *);
void uid_swap_lists(struct query *);
void write_saved_lists(struct query *, const char *);

/* rcfile_y.y */
int prc_parse_file(const char *, const flag);
int prc_filecheck(const char *, const flag);

/* base64.c */
void to64frombits(unsigned char *, const unsigned char *, int);
int from64tobits(char *, const char *);

/* unmime.c */
/* Bit-mask returned by MimeBodyType */
#define MSG_IS_7BIT       0x01
#define MSG_IS_8BIT       0x02
#define MSG_NEEDS_DECODE  0x80
extern void UnMimeHeader(unsigned char *buf);
extern int  MimeBodyType(unsigned char *hdrs, int WantDecode);
extern int  UnMimeBodyline(unsigned char **buf, flag delimited, flag issoftline);

/* interface.c */
void interface_init(void);
void interface_parse(char *, struct hostdata *);
void interface_note_activity(struct hostdata *);
int interface_approve(struct hostdata *, flag domonitor);

/* xmalloc.c */
#if defined(HAVE_VOIDPOINTER)
#define XMALLOCTYPE void
#else
#define XMALLOCTYPE char
#endif
XMALLOCTYPE *xmalloc(int);
XMALLOCTYPE *xrealloc(XMALLOCTYPE *, int);
char *xstrdup(const char *);
#if defined(HAVE_ALLOCA_H)
#include <alloca.h>
#else
#ifdef _AIX
 #pragma alloca
#endif
#endif
#define	xalloca(ptr, t, n)	if (!(ptr = (t) alloca(n)))\
       {report(stderr, _("alloca failed")); exit(PS_UNDEFINED);}
#if FALSE
/*
 * This is a hack to help xgettext which cannot find strings in
 * macro definitions like the one for xalloca above.
 */
static char *dummy = gettext_noop("alloca failed");
#endif

/* protocol driver and methods */
int do_protocol(struct query *, const struct method *);
int doPOP2 (struct query *); 
int doPOP3 (struct query *);
int doIMAP (struct query *);
int doETRN (struct query *);

/* miscellanea */
struct query *hostalloc(struct query *); 
int parsecmdline (int, char **, struct runctl *, struct query *);
char *MD5Digest (unsigned char *);
int POP3_auth_rpa(unsigned char *, unsigned char *, int socket);
void deal_with_sigchld(void);
int daemonize(const char *, void (*)(int));
char *fm_getpassword(char *);
void escapes(const char *, char *);
char *visbuf(const char *);
const char *showproto(int);
void dump_config(struct runctl *runp, struct query *querylist);
int is_host_alias(const char *, struct query *);
char *host_fqdn(void);
char *rfc822timestamp(void);
flag isafile(int);
int do_cram_md5 (int sock, char *command, struct query *ctl);

void yyerror(const char *);
int yylex(void);

#ifdef __EMX__
void itimerthread(void*);
/* Have to include these first to avoid errors from redefining getcwd
   and chdir.  They're re-include protected in EMX, so it's okay, I
   guess.  */
#include <stdlib.h>
#include <unistd.h>
/* Redefine getcwd and chdir to get drive-letter support so we can
   find all of our lock files and stuff. */
#define getcwd _getcwd2
#define chdir _chdir2
#endif /* _EMX_ */

# if HAVE_STRERROR
#  ifndef strerror		/* On some systems, strerror is a macro */
char *strerror ();
#  endif
# endif /* HAVE_STRERROR */

#define STRING_DISABLED	(char *)-1
#define STRING_DUMMY	""

#ifdef NeXT
#ifndef S_IXGRP
#define S_IXGRP 0000010
#endif
#endif

#ifdef FETCHMAIL_DEBUG
#define exit(e) do { \
       FILE *out; \
       out = fopen("/tmp/fetchmail.log", "a"); \
       fprintf(out, \
               "Exiting fetchmail from file %s, line %d with status %d\n", \
               __FILE__, __LINE__, e); \
       fclose(out); \
       _exit(e); \
       } while(0)
#endif /* FETCHMAIL_DEBUG */

/* fetchmail.h ends here */
erver.via, ctl->remotename); if (p && p->password) ctl->password = xstrdup(p->password); } } } } /* perhaps we just want to check options? */ if (versioninfo) { int havercfile = access(rcfile, 0); printf(GT_("Taking options from command line%s%s\n"), havercfile ? "" : GT_(" and "), havercfile ? "" : rcfile); if (querylist == NULL) fprintf(stderr, GT_("No mailservers set up -- perhaps %s is missing?\n"), rcfile); else dump_params(&run, querylist, implicitmode); exit(0); } /* dump options as a Python dictionary, for configurator use */ if (configdump) { dump_config(&run, querylist); exit(0); } /* check for another fetchmail running concurrently */ pid = lock_state(); bkgd = (pid < 0); pid = bkgd ? -pid : pid; /* if no mail servers listed and nothing in background, we're done */ if (!(quitmode && argc == 2) && pid == 0 && querylist == NULL) { (void)fputs(GT_("fetchmail: no mailservers have been specified.\n"),stderr); exit(PS_SYNTAX); } /* perhaps user asked us to kill the other fetchmail */ if (quitmode) { if (pid == 0) { fprintf(stderr,GT_("fetchmail: no other fetchmail is running\n")); if (argc == 2) exit(PS_EXCLUDE); } else if (getpid() == pid) { /* this test enables re-execing on a changed rcfile */ if (argc == 2) { fprintf(stderr,GT_("fetchmail: no other fetchmail is running\n")); exit(PS_EXCLUDE); } } else if (kill(pid, SIGTERM) < 0) { fprintf(stderr,GT_("fetchmail: error killing %s fetchmail at %d; bailing out.\n"), bkgd ? GT_("background") : GT_("foreground"), pid); exit(PS_EXCLUDE); } else { fprintf(stderr,GT_("fetchmail: %s fetchmail at %d killed.\n"), bkgd ? GT_("background") : GT_("foreground"), pid); fm_lock_release(); if (argc == 2) exit(0); else pid = 0; } } /* another fetchmail is running -- wake it up or die */ if (pid != 0) { if (check_only) { fprintf(stderr, GT_("fetchmail: can't check mail while another fetchmail to same host is running.\n")); return(PS_EXCLUDE); } else if (!implicitmode) { fprintf(stderr, GT_("fetchmail: can't poll specified hosts with another fetchmail running at %d.\n"), pid); return(PS_EXCLUDE); } else if (!bkgd) { fprintf(stderr, GT_("fetchmail: another foreground fetchmail is running at %d.\n"), pid); return(PS_EXCLUDE); } else if (getpid() == pid) /* this test enables re-execing on a changed rcfile */ lock_assert(); else if (argc > 1) { fprintf(stderr, GT_("fetchmail: can't accept options while a background fetchmail is running.\n")); return(PS_EXCLUDE); } else if (kill(pid, SIGUSR1) == 0) { fprintf(stderr, GT_("fetchmail: background fetchmail at %d awakened.\n"), pid); return(0); } else { /* * Should never happen -- possible only if a background fetchmail * croaks after the first kill probe above but before the * SIGUSR1/SIGHUP transmission. */ fprintf(stderr, GT_("fetchmail: elder sibling at %d died mysteriously.\n"), pid); return(PS_UNDEFINED); } } /* pick up interactively any passwords we need but don't have */ for (ctl = querylist; ctl; ctl = ctl->next) { if (ctl->active && !(implicitmode && ctl->server.skip) && !NO_PASSWORD(ctl) && !ctl->password) { if (!isatty(0)) { fprintf(stderr, GT_("fetchmail: can't find a password for %s@%s.\n"), ctl->remotename, ctl->server.pollname); return(PS_AUTHFAIL); } else { const char* password_prompt = GT_("Enter password for %s@%s: "); size_t pplen = strlen(password_prompt) + strlen(ctl->remotename) + strlen(ctl->server.pollname) + 1; tmpbuf = xmalloc(pplen); snprintf(tmpbuf, pplen, password_prompt, ctl->remotename, ctl->server.pollname); ctl->password = xstrdup((char *)fm_getpassword(tmpbuf)); free(tmpbuf); } } } /* * Time to initiate the SOCKS library (this is not mandatory: it just * registers the correct application name for logging purpose. If you * have some problem, comment out these lines). */ #ifdef HAVE_SOCKS SOCKSinit("fetchmail"); #endif /* HAVE_SOCKS */ /* avoid zombies from plugins */ deal_with_sigchld(); /* * Maybe time to go to demon mode... */ if (run.poll_interval) { if (!nodetach) daemonize(run.logfile, terminate_run); report(stdout, GT_("starting fetchmail %s daemon \n"), VERSION); /* * We'll set up a handler for these when we're sleeping, * but ignore them otherwise so as not to interrupt a poll. */ set_signal_handler(SIGUSR1, SIG_IGN); if (run.poll_interval && getuid() == ROOT_UID) set_signal_handler(SIGHUP, SIG_IGN); } else { if (run.logfile && !nodetach && access(run.logfile, F_OK) == 0) { if (!freopen(run.logfile, "a", stdout)) report(stderr, GT_("could not open %s to append logs to \n"), run.logfile); if (!freopen(run.logfile, "a", stderr)) report(stdout, GT_("could not open %s to append logs to \n"), run.logfile); } } interface_init(); /* beyond here we don't want more than one fetchmail running per user */ umask(0077); set_signal_handler(SIGABRT, terminate_run); set_signal_handler(SIGINT, terminate_run); set_signal_handler(SIGTERM, terminate_run); set_signal_handler(SIGALRM, terminate_run); set_signal_handler(SIGPIPE, terminate_run); set_signal_handler(SIGQUIT, terminate_run); /* here's the exclusion lock */ lock_or_die(); /* * Query all hosts. If there's only one, the error return will * reflect the status of that transaction. */ do { /* * Check to see if the rcfile has been touched. If so, * re-exec so the file will be reread. Doing it this way * avoids all the complications of trying to deallocate the * in-core control structures -- and the potential memory * leaks... */ struct stat rcstat; if (stat(rcfile, &rcstat) == -1) { if (errno != ENOENT) report(stderr, GT_("couldn't time-check %s (error %d)\n"), rcfile, errno); } else if (rcstat.st_mtime > parsetime) { report(stdout, GT_("restarting fetchmail (%s changed)\n"), rcfile); #ifdef HAVE_GETCWD /* restore the startup directory */ if (!currentwd[0] || chdir (currentwd) == -1) report(stderr, GT_("attempt to re-exec may fail as directory has not been restored\n")); #endif /* * Matthias Andree: Isn't this prone to introduction of * "false" programs by interfering with PATH? Those * path-searching execs might not be the best ideas for * this reason. * * Rob Funk: But is there any way for someone to modify * the PATH variable of a running fetchmail? I don't know * of a way. * * Dave's change makes fetchmail restart itself in exactly * the way it was started from the shell (or shell script) * in the first place. If you're concerned about PATH * contamination, call fetchmail initially with a full * path, and use Dave's patch. * * Not using a -p variant of exec means that the restart * will break if both (a) the user depended on PATH to * call fetchmail in the first place, and (b) the system * doesn't save the whole path in argv[0] if the whole * path wasn't used in the initial call. (If I recall * correctly, Linux saves it but many other Unices don't.) */ execvp(argv[0], argv); report(stderr, GT_("attempt to re-exec fetchmail failed\n")); } #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS) /* * This was an efficiency hack that backfired. The theory * was that using TCP/IP for DNS queries would get us better * reliability and shave off some per-UDP-packet costs. * Unfortunately it interacted badly with diald, which effectively * filters out DNS queries over TCP/IP for reasons having to do * with some obscure Linux kernel problem involving bootstrapping of * dynamically-addressed links. I don't understand this mess * and don't want to, so it's "See ya!" to this hack. */ sethostent(TRUE); /* use TCP/IP for mailserver queries */ #endif /* HAVE_RES_SEARCH */ activecount = 0; batchcount = 0; for (ctl = querylist; ctl; ctl = ctl->next) if (ctl->active) { activecount++; if (!(implicitmode && ctl->server.skip)) { if (ctl->wedged) { report(stderr, GT_("poll of %s skipped (failed authentication or too many timeouts)\n"), ctl->server.pollname); continue; } /* check skip interval first so that it counts all polls */ if (run.poll_interval && ctl->server.interval) { if (ctl->server.poll_count++ % ctl->server.interval) { if (outlevel >= O_VERBOSE) report(stdout, GT_("interval not reached, not querying %s\n"), ctl->server.pollname); continue; } } #ifdef CAN_MONITOR /* * Don't do monitoring if we were woken by a signal. * Note that interface_approve() does its own error logging. */ if (!interface_approve(&ctl->server, !lastsig)) continue; #endif /* CAN_MONITOR */ dofastuidl = 0; /* this is reset in the driver if required */ querystatus = query_host(ctl); if (NUM_NONZERO(ctl->fastuidl)) ctl->fastuidlcount = (ctl->fastuidlcount + 1) % ctl->fastuidl; #ifdef POP3_ENABLE /* leave the UIDL state alone if there have been any errors */ if (!check_only && ((querystatus==PS_SUCCESS) || (querystatus==PS_NOMAIL) || (querystatus==PS_MAXFETCH))) uid_swap_lists(ctl); else uid_discard_new_list(ctl); uid_reset_num(ctl); #endif /* POP3_ENABLE */ if (querystatus == PS_SUCCESS) successes++; else if (!check_only && ((querystatus!=PS_NOMAIL) || (outlevel==O_DEBUG))) switch(querystatus) { case PS_SUCCESS: report(stdout,GT_("Query status=0 (SUCCESS)\n"));break; case PS_NOMAIL: report(stdout,GT_("Query status=1 (NOMAIL)\n")); break; case PS_SOCKET: report(stdout,GT_("Query status=2 (SOCKET)\n")); break; case PS_AUTHFAIL: report(stdout,GT_("Query status=3 (AUTHFAIL)\n"));break; case PS_PROTOCOL: report(stdout,GT_("Query status=4 (PROTOCOL)\n"));break; case PS_SYNTAX: report(stdout,GT_("Query status=5 (SYNTAX)\n")); break; case PS_IOERR: report(stdout,GT_("Query status=6 (IOERR)\n")); break; case PS_ERROR: report(stdout,GT_("Query status=7 (ERROR)\n")); break; case PS_EXCLUDE: report(stdout,GT_("Query status=8 (EXCLUDE)\n")); break; case PS_LOCKBUSY: report(stdout,GT_("Query status=9 (LOCKBUSY)\n"));break; case PS_SMTP: report(stdout,GT_("Query status=10 (SMTP)\n")); break; case PS_DNS: report(stdout,GT_("Query status=11 (DNS)\n")); break; case PS_BSMTP: report(stdout,GT_("Query status=12 (BSMTP)\n")); break; case PS_MAXFETCH: report(stdout,GT_("Query status=13 (MAXFETCH)\n"));break; default: report(stdout,GT_("Query status=%d\n"),querystatus); break; } #ifdef CAN_MONITOR if (ctl->server.monitor) { /* * Allow some time for the link to quiesce. One * second is usually sufficient, three is safe. * Note: this delay is important - don't remove! */ sleep(3); interface_note_activity(&ctl->server); } #endif /* CAN_MONITOR */ } } #if defined(HAVE_RES_SEARCH) && defined(USE_TCPIP_FOR_DNS) endhostent(); /* release TCP/IP connection to nameserver */ #endif /* HAVE_RES_SEARCH */ /* close connections cleanly */ terminate_poll(0); /* * OK, we've polled. Now sleep. */ if (run.poll_interval) { /* * Because passwords can expire, it may happen that *all* * hosts are now out of the loop due to authfail * conditions. If this happens daemon-mode fetchmail * should softly and silently vanish away, rather than * spinning uselessly. */ int unwedged = 0; for (ctl = querylist; ctl; ctl = ctl->next) if (ctl->active && !(implicitmode && ctl->server.skip)) if (!ctl->wedged) unwedged++; if (!unwedged) { report(stderr, GT_("All connections are wedged. Exiting.\n")); /* FIXME: someday, send notification mail */ exit(PS_AUTHFAIL); } if (outlevel > O_SILENT) report(stdout, GT_("sleeping at %s\n"), timestamp()); /* * With this simple hack, we make it possible for a foreground * fetchmail to wake up one in daemon mode. What we want is the * side effect of interrupting any sleep that may be going on, * forcing fetchmail to re-poll its hosts. The second line is * for people who think all system daemons wake up on SIGHUP. */ set_signal_handler(SIGUSR1, donothing); if (getuid() != ROOT_UID) set_signal_handler(SIGHUP, donothing); /* * OK, now pause until it's time for the next poll cycle. * A nonzero return indicates we received a wakeup signal; * unwedge all servers in case the problem has been * manually repaired. */ if ((lastsig = interruptible_idle(run.poll_interval))) { if (outlevel > O_SILENT) #ifdef SYS_SIGLIST_DECLARED report(stdout, GT_("awakened by %s\n"), sys_siglist[lastsig]); #else report(stdout, GT_("awakened by signal %d\n"), lastsig); #endif for (ctl = querylist; ctl; ctl = ctl->next) ctl->wedged = FALSE; } if (outlevel > O_SILENT) report(stdout, GT_("awakened at %s\n"), timestamp()); } } while (run.poll_interval); if (outlevel >= O_VERBOSE) report(stdout, GT_("normal termination, status %d\n"), successes ? PS_SUCCESS : querystatus); terminate_run(0); if (successes) exit(PS_SUCCESS); else if (querystatus) exit(querystatus); else /* in case we interrupted before a successful fetch */ exit(PS_NOMAIL); } static void list_merge(struct idlist **dstl, struct idlist **srcl, int force) { /* * If force is off, modify dstl fields only when they're empty (treat srcl * as defaults). If force is on, modify each dstl field whenever scrcl * is nonempty (treat srcl as an override). */ if (force ? !!*srcl : !*dstl) { struct idlist *cpl = copy_str_list(*srcl); append_str_list(dstl, &cpl); } } static void optmerge(struct query *h2, struct query *h1, int force) /* merge two options records */ { list_merge(&h2->server.localdomains, &h1->server.localdomains, force); list_merge(&h2->localnames, &h1->localnames, force); list_merge(&h2->mailboxes, &h1->mailboxes, force); list_merge(&h2->smtphunt, &h1->smtphunt, force); list_merge(&h2->domainlist, &h1->domainlist, force); list_merge(&h2->antispam, &h1->antispam, force); #define FLAG_MERGE(fld) if (force ? !!h1->fld : !h2->fld) h2->fld = h1->fld FLAG_MERGE(server.via); FLAG_MERGE(server.protocol); FLAG_MERGE(server.service); FLAG_MERGE(server.interval); FLAG_MERGE(server.authenticate); FLAG_MERGE(server.timeout); FLAG_MERGE(server.envelope); FLAG_MERGE(server.envskip); FLAG_MERGE(server.qvirtual); FLAG_MERGE(server.skip); FLAG_MERGE(server.dns); FLAG_MERGE(server.checkalias); FLAG_MERGE(server.uidl); FLAG_MERGE(server.principal); #ifdef CAN_MONITOR FLAG_MERGE(server.interface); FLAG_MERGE(server.interface_pair); FLAG_MERGE(server.monitor); #endif FLAG_MERGE(server.plugin); FLAG_MERGE(server.plugout); FLAG_MERGE(server.tracepolls); FLAG_MERGE(wildcard); FLAG_MERGE(remotename); FLAG_MERGE(password); FLAG_MERGE(mda); FLAG_MERGE(bsmtp); FLAG_MERGE(listener); FLAG_MERGE(smtpaddress); FLAG_MERGE(smtpname); FLAG_MERGE(preconnect); FLAG_MERGE(postconnect); FLAG_MERGE(keep); FLAG_MERGE(flush); FLAG_MERGE(limitflush); FLAG_MERGE(fetchall); FLAG_MERGE(rewrite); FLAG_MERGE(forcecr); FLAG_MERGE(stripcr); FLAG_MERGE(pass8bits); FLAG_MERGE(dropstatus); FLAG_MERGE(dropdelivered); FLAG_MERGE(mimedecode); FLAG_MERGE(idle); FLAG_MERGE(limit); FLAG_MERGE(warnings); FLAG_MERGE(fetchlimit); FLAG_MERGE(fetchsizelimit); FLAG_MERGE(fastuidl); FLAG_MERGE(batchlimit); #ifdef SSL_ENABLE FLAG_MERGE(use_ssl); FLAG_MERGE(sslkey); FLAG_MERGE(sslcert); FLAG_MERGE(sslproto); FLAG_MERGE(sslcertck); FLAG_MERGE(sslcertpath); FLAG_MERGE(sslfingerprint); #endif FLAG_MERGE(expunge); FLAG_MERGE(properties); #undef FLAG_MERGE } static int load_params(int argc, char **argv, int optind) { int implicitmode, st; struct passwd *pw; struct query def_opts, *ctl; struct stat rcstat; char *p; run.bouncemail = TRUE; run.spambounce = FALSE; /* don't bounce back to innocent bystanders */ memset(&def_opts, '\0', sizeof(struct query)); def_opts.smtp_socket = -1; def_opts.smtpaddress = (char *)0; def_opts.smtpname = (char *)0; def_opts.server.protocol = P_AUTO; def_opts.server.timeout = CLIENT_TIMEOUT; def_opts.server.esmtp_name = user; def_opts.warnings = WARNING_INTERVAL; def_opts.remotename = user; def_opts.listener = SMTP_MODE; def_opts.fetchsizelimit = 100; def_opts.fastuidl = 10; /* get the location of rcfile */ rcfiledir[0] = 0; p = strrchr (rcfile, '/'); if (p && (p - rcfile) < sizeof (rcfiledir)) { *p = 0; /* replace '/' by '0' */ strlcpy (rcfiledir, rcfile, sizeof(rcfiledir)); *p = '/'; /* restore '/' */ if (!rcfiledir[0]) /* "/.fetchmailrc" case */ strcpy (rcfiledir, "/"); } /* note the parse time, so we can pick up on modifications */ parsetime = 0; /* foil compiler warnings */ if (stat(rcfile, &rcstat) != -1) parsetime = rcstat.st_mtime; else if (errno != ENOENT) report(stderr, GT_("couldn't time-check the run-control file\n")); /* this builds the host list */ if ((st = prc_parse_file(rcfile, !versioninfo)) != 0) /* * FIXME: someday, send notification mail here if backgrounded. * Right now, that can happen if the user changes the rcfile * while the fetchmail is running in background. Do similarly * for the other exit() calls in this function. */ exit(st); if ((implicitmode = (optind >= argc))) { for (ctl = querylist; ctl; ctl = ctl->next) ctl->active = !ctl->server.skip; } else for (; optind < argc; optind++) { flag predeclared = FALSE; /* * If hostname corresponds to a host known from the rc file, * simply declare it active. Otherwise synthesize a host * record from command line and defaults */ for (ctl = querylist; ctl; ctl = ctl->next) if (!strcmp(ctl->server.pollname, argv[optind]) || str_in_list(&ctl->server.akalist, argv[optind], TRUE)) { /* Is this correct? */ if (predeclared && outlevel == O_VERBOSE) fprintf(stderr,GT_("Warning: multiple mentions of host %s in config file\n"),argv[optind]); ctl->active = TRUE; predeclared = TRUE; } if (!predeclared) { /* * Allocate and link record without copying in * command-line args; we'll do that with the optmerge * call later on. */ ctl = hostalloc((struct query *)NULL); ctl->server.via = ctl->server.pollname = xstrdup(argv[optind]); ctl->active = TRUE; ctl->server.lead_server = (struct hostdata *)NULL; } } /* * If there's a defaults record, merge it and lose it. */ if (querylist && strcmp(querylist->server.pollname, "defaults") == 0) { for (ctl = querylist->next; ctl; ctl = ctl->next) optmerge(ctl, querylist, FALSE); querylist = querylist->next; } /* don't allow a defaults record after the first */ for (ctl = querylist; ctl; ctl = ctl->next) if (ctl != querylist && strcmp(ctl->server.pollname, "defaults") == 0) exit(PS_SYNTAX); /* use localhost if we never fetch the FQDN of this host */ fetchmailhost = "localhost"; /* here's where we override globals */ if (cmd_run.logfile) run.logfile = cmd_run.logfile; if (cmd_run.idfile) run.idfile = cmd_run.idfile; /* do this before the keep/fetchall test below, otherwise -d0 may fail */ if (cmd_run.poll_interval >= 0) run.poll_interval = cmd_run.poll_interval; if (cmd_run.invisible) run.invisible = cmd_run.invisible; if (cmd_run.showdots) run.showdots = cmd_run.showdots; if (cmd_run.use_syslog) run.use_syslog = (cmd_run.use_syslog == FLAG_TRUE); if (cmd_run.postmaster) run.postmaster = cmd_run.postmaster; if (cmd_run.bouncemail) run.bouncemail = cmd_run.bouncemail; /* check and daemon options are not compatible */ if (check_only && run.poll_interval) run.poll_interval = 0; /* * DNS support is required for some protocols. We used to * do this unconditionally, but it made fetchmail excessively * vulnerable to misconfigured DNS setups. * * If we're using ETRN or ODMR, the smtp hunt list is the * list of systems we're polling on behalf of; these have * to be fully-qualified domain names. The default for * this list should be the FQDN of localhost. * * If we're using Kerberos for authentication, we need * the FQDN in order to generate capability keys. */ for (ctl = querylist; ctl; ctl = ctl->next) if (ctl->active && (ctl->server.protocol==P_ETRN || ctl->server.protocol==P_ODMR || ctl->server.authenticate == A_KERBEROS_V4 || ctl->server.authenticate == A_KERBEROS_V5)) { fetchmailhost = host_fqdn(); break; } /* this code enables flags to be turned off */ #define DEFAULT(flag, dflt) if (flag == FLAG_TRUE)\ flag = TRUE;\ else if (flag == FLAG_FALSE)\ flag = FALSE;\ else\ flag = (dflt) /* one global gets treated specially */ DEFAULT(run.showdots, run.poll_interval==0 || nodetach); /* merge in wired defaults, do sanity checks and prepare internal fields */ for (ctl = querylist; ctl; ctl = ctl->next) { ctl->wedged = FALSE; /* merge in defaults */ optmerge(ctl, &def_opts, FALSE); /* force command-line options */ optmerge(ctl, &cmd_opts, TRUE); /* * queryname has to be set up for inactive servers too. * Otherwise the UIDL code core-dumps on startup. */ if (ctl->server.via) ctl->server.queryname = xstrdup(ctl->server.via); else ctl->server.queryname = xstrdup(ctl->server.pollname); /* * We no longer do DNS lookups at startup. * This is a kluge. It enables users to edit their * configurations when DNS isn't available. */ ctl->server.truename = xstrdup(ctl->server.queryname); if (configdump || ctl->active ) { DEFAULT(ctl->keep, FALSE); DEFAULT(ctl->fetchall, FALSE); DEFAULT(ctl->flush, FALSE); DEFAULT(ctl->limitflush, FALSE); DEFAULT(ctl->rewrite, TRUE); DEFAULT(ctl->stripcr, (ctl->mda != (char *)NULL)); DEFAULT(ctl->forcecr, FALSE); DEFAULT(ctl->pass8bits, FALSE); DEFAULT(ctl->dropstatus, FALSE); DEFAULT(ctl->dropdelivered, FALSE); DEFAULT(ctl->mimedecode, FALSE); DEFAULT(ctl->idle, FALSE); DEFAULT(ctl->server.dns, TRUE); DEFAULT(ctl->server.uidl, FALSE); DEFAULT(ctl->use_ssl, FALSE); DEFAULT(ctl->sslcertck, FALSE); DEFAULT(ctl->server.checkalias, FALSE); #ifndef SSL_ENABLE /* * XXX FIXME: do we need this check or can we rely on the .y * parser handling this? */ if (ctl->use_ssl) { report(stderr, GT_("SSL support is not compiled in.\n")); exit(PS_SYNTAX); } #endif /* SSL_ENABLE */ #undef DEFAULT /* * Make sure we have a nonempty host list to forward to. */ if (!ctl->smtphunt) save_str(&ctl->smtphunt, fetchmailhost, FALSE); /* * Make sure we have a nonempty list of domains to fetch from. */ if ((ctl->server.protocol==P_ETRN || ctl->server.protocol==P_ODMR) && !ctl->domainlist) save_str(&ctl->domainlist, fetchmailhost, FALSE); /* if `user' doesn't name a real local user, try to run as root */ if ((pw = getpwnam(user)) == (struct passwd *)NULL) ctl->uid = 0; else ctl->uid = pw->pw_uid; /* for local delivery via MDA */ if (!ctl->localnames) /* for local delivery via SMTP */ save_str_pair(&ctl->localnames, user, NULL); #ifndef HAVE_RES_SEARCH /* can't handle multidrop mailboxes unless we can do DNS lookups */ if (MULTIDROP(ctl) && ctl->server.dns) { ctl->server.dns = FALSE; report(stderr, GT_("fetchmail: warning: no DNS available to check multidrop fetches from %s\n"), ctl->server.pollname); } #endif /* !HAVE_RES_SEARCH */ /* * can't handle multidrop mailboxes without "envelope" * option, this causes truckloads full of support complaints * "all mail forwarded to postmaster" */ if (MULTIDROP(ctl) && !ctl->server.envelope) { report(stderr, GT_("warning: multidrop for %s requires envelope option!\n"), ctl->server.pollname); report(stderr, GT_("warning: Do not ask for support if all mail goes to postmaster!\n")); } /* if no folders were specified, set up the null one as default */ if (!ctl->mailboxes) save_str(&ctl->mailboxes, (char *)NULL, 0); /* maybe user overrode timeout on command line? */ if (ctl->server.timeout == -1) ctl->server.timeout = CLIENT_TIMEOUT; /* sanity checks */ if (ctl->server.service) { int port = servport(ctl->server.service); if (port < 0) { (void) fprintf(stderr, GT_("fetchmail: %s configuration invalid, specify positive port number for service or port\n"), ctl->server.pollname); exit(PS_SYNTAX); } if (ctl->server.protocol == P_RPOP && port >= 1024) { (void) fprintf(stderr, GT_("fetchmail: %s configuration invalid, RPOP requires a privileged port\n"), ctl->server.pollname); exit(PS_SYNTAX); } } if (ctl->listener == LMTP_MODE) { struct idlist *idp; for (idp = ctl->smtphunt; idp; idp = idp->next) { char *cp; if (!(cp = strrchr(idp->id, '/')) || ++cp, (0 == strcmp(cp, SMTP_PORT)) || servport(cp) == SMTP_PORT_NUM) { (void) fprintf(stderr, GT_("%s configuration invalid, LMTP can't use default SMTP port\n"), ctl->server.pollname); exit(PS_SYNTAX); } } } /* * "I beg to you, have mercy on the we[a]k minds like myself." * wrote Pehr Anderson. Your petition is granted. */ if (ctl->fetchall && ctl->keep && run.poll_interval && !nodetach) { (void) fprintf(stderr, GT_("Both fetchall and keep on in daemon mode is a mistake!\n")); exit(PS_SYNTAX); } } } #ifdef POP3_ENABLE /* initialize UID handling */ if (!versioninfo && (st = prc_filecheck(run.idfile, !versioninfo)) != 0) exit(st); else initialize_saved_lists(querylist, run.idfile); #endif /* POP3_ENABLE */ /* * If the user didn't set a last-resort user to get misaddressed * multidrop mail, set an appropriate default here. */ if (!run.postmaster) { if (getuid() != ROOT_UID) /* ordinary user */ run.postmaster = user; else /* root */ run.postmaster = "postmaster"; } return(implicitmode); } static RETSIGTYPE terminate_poll(int sig) /* to be executed at the end of a poll cycle */ { /* * Close all SMTP delivery sockets. For optimum performance * we'd like to hold them open til end of run, but (1) this * loses if our poll interval is longer than the MTA's inactivity * timeout, and (2) some MTAs (like smail) don't deliver after * each message, but rather queue up mail and wait to actually * deliver it until the input socket is closed. * * Sending SMTP QUIT on signal is theoretically nice, but led to a * subtle bug. If fetchmail was terminated by signal while it was * shipping message text, it would hang forever waiting for a * command acknowledge. In theory we could enable the QUIT * only outside of the message send. In practice, we don't * care. All mailservers hang up on a dropped TCP/IP connection * anyway. */ if (sig != 0) report(stdout, GT_("terminated with signal %d\n"), sig); else { struct query *ctl; /* terminate all SMTP connections cleanly */ for (ctl = querylist; ctl; ctl = ctl->next) if (ctl->smtp_socket != -1) { /* don't send QUIT for ODMR case because we're acting as a proxy between the SMTP server and client. */ smtp_close(ctl, ctl->server.protocol != P_ODMR); } } #ifdef POP3_ENABLE /* * Update UID information at end of each poll, rather than at end * of run, because that way we don't lose all UIDL information since * the beginning of time if fetchmail crashes. */ if (!check_only) write_saved_lists(querylist, run.idfile); #endif /* POP3_ENABLE */ } static RETSIGTYPE terminate_run(int sig) /* to be executed on normal or signal-induced termination */ { struct query *ctl; terminate_poll(sig); /* * Craig Metz, the RFC1938 one-time-password guy, points out: * "Remember that most kernels don't zero pages before handing them to the * next process and many kernels share pages between user and kernel space. * You'd be very surprised what you can find from a short program to do a * malloc() and then dump the contents of the pages you got. By zeroing * the secrets at end of run (earlier if you can), you make sure the next * guy can't get the password/pass phrase." * * Right you are, Craig! */ for (ctl = querylist; ctl; ctl = ctl->next) if (ctl->password) memset(ctl->password, '\0', strlen(ctl->password)); #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT) fm_lock_release(); #endif if (activecount == 0) exit(PS_NOMAIL); else exit(successes ? PS_SUCCESS : querystatus); } /* * Sequence of protocols to try when autoprobing, most capable to least. */ static const int autoprobe[] = { #ifdef IMAP_ENABLE P_IMAP, #endif /* IMAP_ENABLE */ #ifdef POP3_ENABLE P_POP3, #endif /* POP3_ENABLE */ #ifdef POP2_ENABLE P_POP2 #endif /* POP2_ENABLE */ }; static int query_host(struct query *ctl) /* perform fetch transaction with single host */ { int i, st = 0; /* * If we're syslogging the progress messages are automatically timestamped. * Force timestamping if we're going to a logfile. */ if (outlevel >= O_VERBOSE) { report(stdout, GT_("%s querying %s (protocol %s) at %s: poll started\n"), VERSION, ctl->server.pollname, showproto(ctl->server.protocol), timestamp()); } switch (ctl->server.protocol) { case P_AUTO: for (i = 0; i < sizeof(autoprobe)/sizeof(autoprobe[0]); i++) { ctl->server.protocol = autoprobe[i]; do { st = query_host(ctl); } while (st == PS_REPOLL); if (st == PS_SUCCESS || st == PS_NOMAIL || st == PS_AUTHFAIL || st == PS_LOCKBUSY || st == PS_SMTP || st == PS_MAXFETCH || st == PS_DNS) break; } ctl->server.protocol = P_AUTO; break; case P_POP2: #ifdef POP2_ENABLE st = doPOP2(ctl); #else report(stderr, GT_("POP2 support is not configured.\n")); st = PS_PROTOCOL; #endif /* POP2_ENABLE */ break; case P_POP3: case P_APOP: case P_RPOP: #ifdef POP3_ENABLE do { st = doPOP3(ctl); } while (st == PS_REPOLL); #else report(stderr, GT_("POP3 support is not configured.\n")); st = PS_PROTOCOL; #endif /* POP3_ENABLE */ break; case P_IMAP: #ifdef IMAP_ENABLE do { st = doIMAP(ctl); } while (st == PS_REPOLL); #else report(stderr, GT_("IMAP support is not configured.\n")); st = PS_PROTOCOL; #endif /* IMAP_ENABLE */ break; case P_ETRN: #ifndef ETRN_ENABLE report(stderr, GT_("ETRN support is not configured.\n")); st = PS_PROTOCOL; #else st = doETRN(ctl); break; #endif /* ETRN_ENABLE */ case P_ODMR: #ifndef ODMR_ENABLE report(stderr, GT_("ODMR support is not configured.\n")); st = PS_PROTOCOL; #else st = doODMR(ctl); #endif /* ODMR_ENABLE */ break; default: report(stderr, GT_("unsupported protocol selected.\n")); st = PS_PROTOCOL; } /* * If we're syslogging the progress messages are automatically timestamped. * Force timestamping if we're going to a logfile. */ if (outlevel >= O_VERBOSE) { report(stdout, GT_("%s querying %s (protocol %s) at %s: poll completed\n"), VERSION, ctl->server.pollname, showproto(ctl->server.protocol), timestamp()); } return(st); } static void dump_params (struct runctl *runp, struct query *querylist, flag implicit) /* display query parameters in English */ { struct query *ctl; if (runp->poll_interval) printf(GT_("Poll interval is %d seconds\n"), runp->poll_interval); if (runp->logfile) printf(GT_("Logfile is %s\n"), runp->logfile); if (strcmp(runp->idfile, IDFILE_NAME)) printf(GT_("Idfile is %s\n"), runp->idfile); #if defined(HAVE_SYSLOG) if (runp->use_syslog) printf(GT_("Progress messages will be logged via syslog\n")); #endif if (runp->invisible) printf(GT_("Fetchmail will masquerade and will not generate Received\n")); if (runp->showdots) printf(GT_("Fetchmail will show progress dots even in logfiles.\n")); if (runp->postmaster) printf(GT_("Fetchmail will forward misaddressed multidrop messages to %s.\n"), runp->postmaster); if (!runp->bouncemail) printf(GT_("Fetchmail will direct error mail to the postmaster.\n")); else if (outlevel >= O_VERBOSE) printf(GT_("Fetchmail will direct error mail to the sender.\n")); for (ctl = querylist; ctl; ctl = ctl->next) { if (!ctl->active || (implicit && ctl->server.skip)) continue; printf(GT_("Options for retrieving from %s@%s:\n"), ctl->remotename, visbuf(ctl->server.pollname)); if (ctl->server.via && MAILBOX_PROTOCOL(ctl)) printf(GT_(" Mail will be retrieved via %s\n"), ctl->server.via); if (ctl->server.interval) printf(ngettext(" Poll of this server will occur every %d interval.\n", " Poll of this server will occur every %d intervals.\n", ctl->server.interval), ctl->server.interval); if (ctl->server.truename) printf(GT_(" True name of server is %s.\n"), ctl->server.truename); if (ctl->server.skip || outlevel >= O_VERBOSE) printf(ctl->server.skip ? GT_(" This host will not be queried when no host is specified.\n") : GT_(" This host will be queried when no host is specified.\n")); if (!NO_PASSWORD(ctl)) { if (!ctl->password) printf(GT_(" Password will be prompted for.\n")); else if (outlevel >= O_VERBOSE) { if (ctl->server.protocol == P_APOP) printf(GT_(" APOP secret = \"%s\".\n"), visbuf(ctl->password)); else if (ctl->server.protocol == P_RPOP) printf(GT_(" RPOP id = \"%s\".\n"), visbuf(ctl->password)); else printf(GT_(" Password = \"%s\".\n"), visbuf(ctl->password)); } } if (ctl->server.protocol == P_POP3 && ctl->server.service && !strcmp(ctl->server.service, KPOP_PORT) && (ctl->server.authenticate == A_KERBEROS_V4 || ctl->server.authenticate == A_KERBEROS_V5)) printf(GT_(" Protocol is KPOP with Kerberos %s authentication"), ctl->server.authenticate == A_KERBEROS_V5 ? "V" : "IV"); else printf(GT_(" Protocol is %s"), showproto(ctl->server.protocol)); if (ctl->server.service) printf(GT_(" (using service %s)"), ctl->server.service); else if (outlevel >= O_VERBOSE) printf(GT_(" (using default port)")); if (ctl->server.uidl && MAILBOX_PROTOCOL(ctl)) printf(GT_(" (forcing UIDL use)")); putchar('.'); putchar('\n'); switch (ctl->server.authenticate) { case A_ANY: printf(GT_(" All available authentication methods will be tried.\n")); break; case A_PASSWORD: printf(GT_(" Password authentication will be forced.\n")); break; case A_MSN: printf(GT_(" MSN authentication will be forced.\n")); break; case A_NTLM: printf(GT_(" NTLM authentication will be forced.\n")); break; case A_OTP: printf(GT_(" OTP authentication will be forced.\n")); break; case A_CRAM_MD5: printf(GT_(" CRAM-Md5 authentication will be forced.\n")); break; case A_GSSAPI: printf(GT_(" GSSAPI authentication will be forced.\n")); break; case A_KERBEROS_V4: printf(GT_(" Kerberos V4 authentication will be forced.\n")); break; case A_KERBEROS_V5: printf(GT_(" Kerberos V5 authentication will be forced.\n")); break; case A_SSH: printf(GT_(" End-to-end encryption assumed.\n")); break; } if (ctl->server.principal != (char *) NULL) printf(GT_(" Mail service principal is: %s\n"), ctl->server.principal); #ifdef SSL_ENABLE if (ctl->use_ssl) printf(GT_(" SSL encrypted sessions enabled.\n")); if (ctl->sslproto) printf(GT_(" SSL protocol: %s.\n"), ctl->sslproto); if (ctl->sslcertck) { printf(GT_(" SSL server certificate checking enabled.\n")); if (ctl->sslcertpath != NULL) printf(GT_(" SSL trusted certificate directory: %s\n"), ctl->sslcertpath); } if (ctl->sslfingerprint != NULL) printf(GT_(" SSL key fingerprint (checked against the server key): %s\n"), ctl->sslfingerprint); #endif if (ctl->server.timeout > 0) printf(GT_(" Server nonresponse timeout is %d seconds"), ctl->server.timeout); if (ctl->server.timeout == CLIENT_TIMEOUT) printf(GT_(" (default).\n")); else printf(".\n"); if (MAILBOX_PROTOCOL(ctl)) { if (!ctl->mailboxes->id) printf(GT_(" Default mailbox selected.\n")); else { struct idlist *idp; printf(GT_(" Selected mailboxes are:")); for (idp = ctl->mailboxes; idp; idp = idp->next) printf(" %s", (char *)idp->id); printf("\n"); } printf(ctl->fetchall ? GT_(" All messages will be retrieved (--all on).\n") : GT_(" Only new messages will be retrieved (--all off).\n")); printf(ctl->keep ? GT_(" Fetched messages will be kept on the server (--keep on).\n") : GT_(" Fetched messages will not be kept on the server (--keep off).\n")); printf(ctl->flush ? GT_(" Old messages will be flushed before message retrieval (--flush on).\n") : GT_(" Old messages will not be flushed before message retrieval (--flush off).\n")); printf(ctl->limitflush ? GT_(" Oversized messages will be flushed before message retrieval (--limitflush on).\n") : GT_(" Oversized messages will not be flushed before message retrieval (--limitflush off).\n")); printf(ctl->rewrite ? GT_(" Rewrite of server-local addresses is enabled (--norewrite off).\n") : GT_(" Rewrite of server-local addresses is disabled (--norewrite on).\n")); printf(ctl->stripcr ? GT_(" Carriage-return stripping is enabled (stripcr on).\n") : GT_(" Carriage-return stripping is disabled (stripcr off).\n")); printf(ctl->forcecr ? GT_(" Carriage-return forcing is enabled (forcecr on).\n") : GT_(" Carriage-return forcing is disabled (forcecr off).\n")); printf(ctl->pass8bits ? GT_(" Interpretation of Content-Transfer-Encoding is disabled (pass8bits on).\n") : GT_(" Interpretation of Content-Transfer-Encoding is enabled (pass8bits off).\n")); printf(ctl->mimedecode ? GT_(" MIME decoding is enabled (mimedecode on).\n") : GT_(" MIME decoding is disabled (mimedecode off).\n")); printf(ctl->idle ? GT_(" Idle after poll is enabled (idle on).\n") : GT_(" Idle after poll is disabled (idle off).\n")); printf(ctl->dropstatus ? GT_(" Nonempty Status lines will be discarded (dropstatus on)\n") : GT_(" Nonempty Status lines will be kept (dropstatus off)\n")); printf(ctl->dropdelivered ? GT_(" Delivered-To lines will be discarded (dropdelivered on)\n") : GT_(" Delivered-To lines will be kept (dropdelivered off)\n")); if (NUM_NONZERO(ctl->limit)) { if (NUM_NONZERO(ctl->limit)) printf(GT_(" Message size limit is %d octets (--limit %d).\n"), ctl->limit, ctl->limit); else if (outlevel >= O_VERBOSE) printf(GT_(" No message size limit (--limit 0).\n")); if (run.poll_interval > 0) printf(GT_(" Message size warning interval is %d seconds (--warnings %d).\n"), ctl->warnings, ctl->warnings); else if (outlevel >= O_VERBOSE) printf(GT_(" Size warnings on every poll (--warnings 0).\n")); } if (NUM_NONZERO(ctl->fetchlimit)) printf(GT_(" Received-message limit is %d (--fetchlimit %d).\n"), ctl->fetchlimit, ctl->fetchlimit); else if (outlevel >= O_VERBOSE) printf(GT_(" No received-message limit (--fetchlimit 0).\n")); if (NUM_NONZERO(ctl->fetchsizelimit)) printf(GT_(" Fetch message size limit is %d (--fetchsizelimit %d).\n"), ctl->fetchsizelimit, ctl->fetchsizelimit); else if (outlevel >= O_VERBOSE) printf(GT_(" No fetch message size limit (--fetchsizelimit 0).\n")); if (NUM_NONZERO(ctl->fastuidl) && MAILBOX_PROTOCOL(ctl)) { if (ctl->fastuidl == 1) printf(GT_(" Do binary search of UIDs during each poll (--fastuidl 1).\n")); else printf(GT_(" Do binary search of UIDs during %d out of %d polls (--fastuidl %d).\n"), ctl->fastuidl - 1, ctl->fastuidl, ctl->fastuidl); } else if (outlevel >= O_VERBOSE) printf(GT_(" Do linear search of UIDs during each poll (--fastuidl 0).\n")); if (NUM_NONZERO(ctl->batchlimit)) printf(GT_(" SMTP message batch limit is %d.\n"), ctl->batchlimit); else if (outlevel >= O_VERBOSE) printf(GT_(" No SMTP message batch limit (--batchlimit 0).\n")); if (MAILBOX_PROTOCOL(ctl)) { if (NUM_NONZERO(ctl->expunge)) printf(GT_(" Deletion interval between expunges forced to %d (--expunge %d).\n"), ctl->expunge, ctl->expunge); else if (outlevel >= O_VERBOSE) printf(GT_(" No forced expunges (--expunge 0).\n")); } } else /* ODMR or ETRN */ { struct idlist *idp; printf(GT_(" Domains for which mail will be fetched are:")); for (idp = ctl->domainlist; idp; idp = idp->next) { printf(" %s", (char *)idp->id); if (!idp->val.status.mark) printf(GT_(" (default)")); } printf("\n"); } if (ctl->bsmtp) printf(GT_(" Messages will be appended to %s as BSMTP\n"), visbuf(ctl->bsmtp)); else if (ctl->mda && MAILBOX_PROTOCOL(ctl)) printf(GT_(" Messages will be delivered with \"%s\".\n"), visbuf(ctl->mda)); else { struct idlist *idp; if (ctl->smtphunt) { printf(GT_(" Messages will be %cMTP-forwarded to:"), ctl->listener); for (idp = ctl->smtphunt; idp; idp = idp->next) { printf(" %s", (char *)idp->id); if (!idp->val.status.mark) printf(GT_(" (default)")); } printf("\n"); } if (ctl->smtpaddress) printf(GT_(" Host part of MAIL FROM line will be %s\n"), ctl->smtpaddress); if (ctl->smtpname) printf(GT_(" Address to be put in RCPT TO lines shipped to SMTP will be %s\n"), ctl->smtpname); } if (MAILBOX_PROTOCOL(ctl)) { if (ctl->antispam != (struct idlist *)NULL) { struct idlist *idp; printf(GT_(" Recognized listener spam block responses are:")); for (idp = ctl->antispam; idp; idp = idp->next) printf(" %d", idp->val.status.num); printf("\n"); } else if (outlevel >= O_VERBOSE) printf(GT_(" Spam-blocking disabled\n")); } if (ctl->preconnect) printf(GT_(" Server connection will be brought up with \"%s\".\n"), visbuf(ctl->preconnect)); else if (outlevel >= O_VERBOSE) printf(GT_(" No pre-connection command.\n")); if (ctl->postconnect) printf(GT_(" Server connection will be taken down with \"%s\".\n"), visbuf(ctl->postconnect)); else if (outlevel >= O_VERBOSE) printf(GT_(" No post-connection command.\n")); if (MAILBOX_PROTOCOL(ctl)) { if (!ctl->localnames) printf(GT_(" No localnames declared for this host.\n")); else { struct idlist *idp; int count = 0; for (idp = ctl->localnames; idp; idp = idp->next) ++count; if (count > 1 || ctl->wildcard) printf(GT_(" Multi-drop mode: ")); else printf(GT_(" Single-drop mode: ")); printf(ngettext("%d local name recognized.\n", "%d local names recognized.\n", count), count); if (outlevel >= O_VERBOSE) { for (idp = ctl->localnames; idp; idp = idp->next) if (idp->val.id2) printf("\t%s -> %s\n", (char *)idp->id, (char *)idp->val.id2); else printf("\t%s\n", (char *)idp->id); if (ctl->wildcard) fputs("\t*\n", stdout); } if (count > 1 || ctl->wildcard) { printf(ctl->server.dns ? GT_(" DNS lookup for multidrop addresses is enabled.\n") : GT_(" DNS lookup for multidrop addresses is disabled.\n")); if (ctl->server.dns) { if (ctl->server.checkalias) printf(GT_(" Server aliases will be compared with multidrop addresses by IP address.\n")); else printf(GT_(" Server aliases will be compared with multidrop addresses by name.\n")); } if (ctl->server.envelope == STRING_DISABLED) printf(GT_(" Envelope-address routing is disabled\n")); else { printf(GT_(" Envelope header is assumed to be: %s\n"), ctl->server.envelope ? ctl->server.envelope : "Received"); if (ctl->server.envskip || outlevel >= O_VERBOSE) printf(GT_(" Number of envelope headers to be skipped over: %d\n"), ctl->server.envskip); if (ctl->server.qvirtual) printf(GT_(" Prefix %s will be removed from user id\n"), ctl->server.qvirtual); else if (outlevel >= O_VERBOSE) printf(GT_(" No prefix stripping\n")); } if (ctl->server.akalist) { struct idlist *idp; printf(GT_(" Predeclared mailserver aliases:")); for (idp = ctl->server.akalist; idp; idp = idp->next) printf(" %s", (char *)idp->id); putchar('\n'); } if (ctl->server.localdomains) { struct idlist *idp; printf(GT_(" Local domains:")); for (idp = ctl->server.localdomains; idp; idp = idp->next) printf(" %s", (char *)idp->id); putchar('\n'); } } } } #ifdef CAN_MONITOR if (ctl->server.interface) printf(GT_(" Connection must be through interface %s.\n"), ctl->server.interface); else if (outlevel >= O_VERBOSE) printf(GT_(" No interface requirement specified.\n")); if (ctl->server.monitor) printf(GT_(" Polling loop will monitor %s.\n"), ctl->server.monitor); else if (outlevel >= O_VERBOSE) printf(GT_(" No monitor interface specified.\n")); #endif if (ctl->server.plugin) printf(GT_(" Server connections will be made via plugin %s (--plugin %s).\n"), ctl->server.plugin, ctl->server.plugin); else if (outlevel >= O_VERBOSE) printf(GT_(" No plugin command specified.\n")); if (ctl->server.plugout) printf(GT_(" Listener connections will be made via plugout %s (--plugout %s).\n"), ctl->server.plugout, ctl->server.plugout); else if (outlevel >= O_VERBOSE) printf(GT_(" No plugout command specified.\n")); if (ctl->server.protocol > P_POP2 && MAILBOX_PROTOCOL(ctl)) { if (!ctl->oldsaved) printf(GT_(" No UIDs saved from this host.\n")); else { struct idlist *idp; int count = 0; for (idp = ctl->oldsaved; idp; idp = idp->next) ++count; printf(GT_(" %d UIDs saved.\n"), count); if (outlevel >= O_VERBOSE) for (idp = ctl->oldsaved; idp; idp = idp->next) printf("\t%s\n", (char *)idp->id); } } if (ctl->server.tracepolls) printf(GT_(" Poll trace information will be added to the Received header.\n")); else if (outlevel >= O_VERBOSE) printf(GT_(" No poll trace information will be added to the Received header.\n.\n")); if (ctl->properties) printf(GT_(" Pass-through properties \"%s\".\n"), visbuf(ctl->properties)); } } /* fetchmail.c ends here */