]> Pileus Git - ~andy/fetchmail/blob - fetchmail.h
Abstract out the needs-password check.
[~andy/fetchmail] / fetchmail.h
1 /*
2  * For license terms, see the file COPYING in this directory.
3  */
4
5 /* We need this for HAVE_STDARG_H, etc */
6 #include "config.h"
7
8 /* constants designating the various supported protocols */
9 #define         P_AUTO          1
10 #define         P_POP2          2
11 #define         P_POP3          3
12 #define         P_APOP          4
13 #define         P_RPOP          5
14 #define         P_IMAP          6
15 #define         P_ETRN          7
16 #define         P_ODMR          8
17
18 #if INET6_ENABLE
19 #define         SMTP_PORT       "smtp"
20 #define         KPOP_PORT       "kpop"
21 #else /* INET6_ENABLE */
22 #define         SMTP_PORT       25
23 #define         KPOP_PORT       1109
24 #endif /* INET6_ENABLE */
25
26 #ifdef SSL_ENABLE
27 #define         SIMAP_PORT      993
28 #define         SPOP3_PORT      995
29 #endif
30
31 /* authentication types */
32 #define         A_ANY           0       /* use the first method that works */
33 #define         A_PASSWORD      1       /* password or inline authentication */
34 #define         A_KERBEROS_V4   2       /* authenticate w/ Kerberos V4 */
35 #define         A_KERBEROS_V5   3       /* authenticate w/ Kerberos V5 */
36 #define         A_GSSAPI        4       /* authenticate with GSSAPI */
37 #define         A_SSH           5       /* authentication at session level */
38
39 /* some protocols (KERBEROS, GSSAPI, SSH) don't require a password */
40 #define NO_PASSWORD(ctl)        ((ctl)->server.authenticate > A_PASSWORD || (ctl)->server.protocol >= P_ETRN)
41
42 /*
43  * Definitions for buffer sizes.  We get little help on setting maxima
44  * from IMAP RFCs up to 2060, so these are mostly from POP3.
45  */
46 #define         HOSTLEN         635     /* max hostname length (RFC1123) */
47 #define         POPBUFSIZE      512     /* max length of response (RFC1939) */
48 #define         IDLEN           128     /* max length of UID (RFC1939) */
49
50 /* per RFC1939 this should be 40, but Microsoft Exchange ignores that limit */
51 #define         USERNAMELEN     128     /* max POP3 arg length */
52
53 /* clear a netBSD kernel parameter out of the way */ 
54 #undef          MSGBUFSIZE
55
56 /*
57  * The RFC822 limit on message line size is just 998.  But
58  * make this *way* oversized; idiot DOS-world mailers that
59  * don't line-wrap properly often ship entire paragraphs as
60  * lines.
61  */
62 #define         MSGBUFSIZE      8192
63
64 #define         NAMELEN         64      /* max username length */
65 #define         PASSWORDLEN     64      /* max password length */
66 #define         DIGESTLEN       33      /* length of MD5 digest */
67
68 /* exit code values */
69 #define         PS_SUCCESS      0       /* successful receipt of messages */
70 #define         PS_NOMAIL       1       /* no mail available */
71 #define         PS_SOCKET       2       /* socket I/O woes */
72 #define         PS_AUTHFAIL     3       /* user authorization failed */
73 #define         PS_PROTOCOL     4       /* protocol violation */
74 #define         PS_SYNTAX       5       /* command-line syntax error */
75 #define         PS_IOERR        6       /* bad permissions on rc file */
76 #define         PS_ERROR        7       /* protocol error */
77 #define         PS_EXCLUDE      8       /* client-side exclusion error */
78 #define         PS_LOCKBUSY     9       /* server responded lock busy */
79 #define         PS_SMTP         10      /* SMTP error */
80 #define         PS_DNS          11      /* fatal DNS error */
81 #define         PS_BSMTP        12      /* output batch could not be opened */
82 #define         PS_MAXFETCH     13      /* poll ended by fetch limit */
83 /* leave space for more codes */
84 #define         PS_UNDEFINED    23      /* something I hadn't thought of */
85 #define         PS_TRANSIENT    24      /* transient failure (internal use) */
86 #define         PS_REFUSED      25      /* mail refused (internal use) */
87 #define         PS_RETAINED     26      /* message retained (internal use) */
88 #define         PS_TRUNCATED    27      /* headers incomplete (internal use) */
89
90 /* output noise level */
91 #define         O_SILENT        0       /* mute, max squelch, etc. */
92 #define         O_NORMAL        1       /* user-friendly */
93 #define         O_VERBOSE       2       /* chatty */
94 #define         O_DEBUG         3       /* prolix */
95 #define         O_MONITOR       O_VERBOSE
96
97 #define         SIZETICKER      1024    /* print 1 dot per this many bytes */
98
99 /*
100  * We #ifdef this and use flag rather than bool
101  * to avoid a type clash with curses.h
102  */
103 #ifndef TRUE
104 #define FALSE   0
105 #define TRUE    1
106 #endif /* TRUE */
107 typedef char    flag;
108
109 /* we need to use zero as a flag-uninitialized value */
110 #define FLAG_TRUE       2
111 #define FLAG_FALSE      1
112
113 struct runctl
114 {
115     char        *logfile;
116     char        *idfile;
117     int         poll_interval;
118     char        *postmaster;
119     flag        bouncemail;
120     flag        spambounce;
121     char        *properties;
122     flag        use_syslog;
123     flag        invisible;
124     flag        showdots;
125 };
126
127 struct idlist
128 {
129     unsigned char *id;
130     union
131     {
132         struct
133         {
134             short       num;
135             flag        mark;           /* UID-index information */
136 #define UID_UNSEEN      0               /* hasn't been seen */
137 #define UID_SEEN        1               /* seen, but not deleted */
138 #define UID_DELETED     2               /* this message has been deleted */
139 #define UID_EXPUNGED    3               /* this message has been expunged */ 
140         }
141         status;
142         unsigned char *id2;
143     } val;
144     struct idlist *next;
145 };
146
147 struct query;
148
149 struct method           /* describe methods for protocol state machine */
150 {
151     const char *name;           /* protocol name */
152 #if INET6_ENABLE
153     const char *service;
154     const char *sslservice;
155 #else /* INET6_ENABLE */
156     int port;                   /* service port */
157     int sslport;                /* service port for ssl */
158 #endif /* INET6_ENABLE */
159     flag tagged;                /* if true, generate & expect command tags */
160     flag delimited;             /* if true, accept "." message delimiter */
161     int (*parse_response)(int, char *);
162                                 /* response_parsing function */
163     int (*password_canonify)(char *, char *, int);
164                                 /* canonicalize password */
165     int (*getauth)(int, struct query *, char *);
166                                 /* authorization fetcher */
167     int (*getrange)(int, struct query *, const char *, int *, int *, int *);
168                                 /* get message range to fetch */
169     int (*getsizes)(int, int, int *);
170                                 /* get sizes of messages */
171     int (*is_old)(int, struct query *, int);
172                                 /* check for old message */
173     int (*fetch_headers)(int, struct query *, int, int *);
174                                 /* fetch FROM headera given message */
175     int (*fetch_body)(int, struct query *, int, int *);
176                                 /* fetch a given message */
177     int (*trail)(int, struct query *, int);
178                                 /* eat trailer of a message */
179     int (*delete)(int, struct query *, int);
180                                 /* delete method */
181     int (*logout_cmd)(int, struct query *);
182                                 /* logout command */
183     flag retry;                 /* can getrange poll for new messages? */
184 };
185
186 struct hostdata         /* shared among all user connections to given server */
187 {
188     /* rc file data */
189     char *pollname;                     /* poll label of host */
190     char *via;                          /* "true" server name if non-NULL */
191     struct idlist *akalist;             /* server name first, then akas */
192     struct idlist *localdomains;        /* list of pass-through domains */
193     int protocol;                       /* protocol type */
194 #if INET6_ENABLE
195     char *service;                      /* IPv6 service name */
196     void *netsec;                       /* IPv6 security request */
197 #else /* INET6_ENABLE */
198     int port;                           /* TCP/IP service port number */
199 #endif /* INET6_ENABLE */
200     int interval;                       /* # cycles to skip between polls */
201     int authenticate;                   /* authentication mode to try */
202     int timeout;                        /* inactivity timout in seconds */
203     char *envelope;                     /* envelope address list header */
204     int envskip;                        /* skip to numbered envelope header */
205     char *qvirtual;                     /* prefix removed from local user id */
206     flag skip;                          /* suppress poll in implicit mode? */
207     flag dns;                           /* do DNS lookup on multidrop? */
208     flag uidl;                          /* use RFC1725 UIDLs? */
209 #ifdef SDPS_ENABLE
210     flag sdps;                          /* use Demon Internet SDPS *ENV */
211 #endif /* SDPS_ENABLE */
212     flag checkalias;                    /* resolve aliases by comparing IPs? */
213     char *principal;                    /* Kerberos principal for mail service */
214
215
216 #if defined(linux) || defined(__FreeBSD__)
217     char *interface;
218     char *monitor;
219     int  monitor_io;
220     struct interface_pair_s *interface_pair;
221 #endif /* linux */
222
223     char *plugin,*plugout;
224
225     /* computed for internal use */
226     const struct method *base_protocol; /* relevant protocol method table */
227     int poll_count;                     /* count of polls so far */
228     char *queryname;                    /* name to attempt DNS lookup on */
229     char *truename;                     /* "true name" of server host */
230     char *trueaddr;                     /* IP address of truename, as char */
231     struct hostdata *lead_server;       /* ptr to lead query for this server */
232     int esmtp_options;
233 };
234
235 struct query
236 {
237     /* mailserver connection controls */
238     struct hostdata server;
239
240     /* per-user data */
241     struct idlist *localnames;  /* including calling user's name */
242     int wildcard;               /* should unmatched names be passed through */
243     char *remotename;           /* remote login name to use */
244     char *password;             /* remote password to use */
245     struct idlist *mailboxes;   /* list of mailboxes to check */
246
247     /* per-forwarding-target data */
248     struct idlist *smtphunt;    /* list of SMTP hosts to try forwarding to */
249     char *smtpaddress;          /* address to force in RCPT TO */ 
250     char *smtpname;             /* full RCPT TO name, including domain */
251     struct idlist *antispam;    /* list of listener's antispam response */
252     char *mda;                  /* local MDA to pass mail to */
253     char *bsmtp;                /* BSMTP output file */
254     char listener;              /* what's the listener's wire protocol? */
255 #define SMTP_MODE       'S'
256 #define LMTP_MODE       'L'
257     char *preconnect;           /* pre-connection command to execute */
258     char *postconnect;          /* post-connection command to execute */
259
260     /* per-user control flags */
261     flag keep;                  /* if TRUE, leave messages undeleted */
262     flag fetchall;              /* if TRUE, fetch all (not just unseen) */
263     flag flush;                 /* if TRUE, delete messages already seen */
264     flag rewrite;               /* if TRUE, canonicalize recipient addresses */
265     flag stripcr;               /* if TRUE, strip CRs in text */
266     flag forcecr;               /* if TRUE, force CRs before LFs in text */
267     flag pass8bits;             /* if TRUE, ignore Content-Transfer-Encoding */
268     flag dropstatus;            /* if TRUE, drop Status lines in mail */
269     flag dropdelivered;         /* if TRUE, drop Delivered-To lines in mail */
270     flag mimedecode;            /* if TRUE, decode MIME-armored messages */
271     flag idle;                  /* if TRUE, idle after each poll */
272     int limit;                  /* limit size of retrieved messages */
273     int warnings;               /* size warning interval */
274     int fetchlimit;             /* max # msgs to get in single poll */
275     int batchlimit;             /* max # msgs to pass in single SMTP session */
276     int expunge;                /* max # msgs to pass between expunges */
277     flag use_ssl;               /* use SSL encrypted session */
278     char *sslkey;               /* optional SSL private key file */
279     char *sslcert;              /* optional SSL certificate file */
280     char *properties;           /* passthrough properties for extensions */
281
282     /* internal use -- per-poll state */
283     flag active;                /* should we actually poll this server? */
284     const char *destaddr;       /* destination host for this query */
285     int errcount;               /* count transient errors in last pass */
286     int authfailcount;          /* count of authorization failures */
287     int wedged;                 /* wedged by auth failures or timeouts? */
288     char *smtphost;             /* actual SMTP host we connected to */
289     int smtp_socket;            /* socket descriptor for SMTP connection */
290     unsigned int uid;           /* UID of user to deliver to */
291     struct idlist *skipped;     /* messages skipped on the mail server */
292     struct idlist *oldsaved, *newsaved;
293     char *lastid;               /* last Message-ID seen on this connection */
294
295     /* internal use -- per-message state */
296     int mimemsg;                /* bitmask indicating MIME body-type */
297     char digest [DIGESTLEN];    /* md5 digest buffer */
298
299     /* internal use -- housekeeping */
300     struct query *next;         /* next query control block in chain */
301 };
302
303 struct msgblk                   /* message header parsed for open_sink() */
304 {
305     char                *headers;       /* raw message headers */
306     struct idlist       *recipients;    /* addressees */
307     char                return_path[HOSTLEN + USERNAMELEN + 4]; 
308     int                 reallen;
309 };
310
311
312 /*
313  * Numeric option handling.  Numeric option value of zero actually means
314  * it's unspecified.  Value less than zero is zero.  The reason for this
315  * screwy encoding is so we can zero out an option block in order to set the
316  * numeric flags in it to unspecified.
317  */
318 #define NUM_VALUE_IN(n)         (((n) == 0) ? -1 : (n))
319 #define NUM_VALUE_OUT(n)        (((n) < 0) ? 0 : (n))
320 #define NUM_NONZERO(n)          ((n) > 0)
321 #define NUM_ZERO(n)             ((n) < 0)
322 #define NUM_SPECIFIED(n)        ((n) != 0)
323
324 #define MULTIDROP(ctl)  (ctl->wildcard || \
325                                 ((ctl)->localnames && (ctl)->localnames->next))
326
327 /*
328  * Note: tags are generated with an a%04d format from a 1-origin
329  * integer sequence number.  Length 4 permits transaction numbers
330  * up to 9999, so we force rollover with % 10000.  There's no special
331  * reason for this format other than to look like the exmples in the
332  * IMAP RFCs.
333  */
334 #define TAGLEN  6               /* 'a' + 4 digits + NUL */
335 extern char tag[TAGLEN];
336 #define TAGMOD  10000
337
338 /* list of hosts assembled from run control file and command line */
339 extern struct query cmd_opts, *querylist;
340
341 /* what's returned by envquery */
342 extern void envquery(int, char **);
343
344 /* controls the detail level of status/progress messages written to stderr */
345 extern int outlevel;            /* see the O_.* constants above */
346 extern int yydebug;             /* enable parse debugging */
347
348 /* these get computed */
349 extern int batchcount;          /* count of messages sent in current batch */
350 extern flag peek_capable;       /* can we read msgs without setting seen? */
351
352 /* miscellaneous global controls */
353 extern struct runctl run;       /* global controls for this run */
354 extern flag nodetach;           /* if TRUE, don't detach daemon process */
355 extern flag quitmode;           /* if --quit was set */
356 extern flag check_only;         /* if --check was set */
357 extern char *rcfile;            /* path name of rc file */
358 extern int linelimit;           /* limit # lines retrieved per site */
359 extern flag versioninfo;        /* emit only version info */
360 extern char *user;              /* name of invoking user */
361 extern char *home;              /* home directory of invoking user */
362 extern char *fmhome;            /* fetchmail home directory */
363 extern int pass;                /* number of re-polling pass */
364 extern flag configdump;         /* dump control blocks as Python dictionary */
365 extern const char *fetchmailhost;
366                                 /* either "localhost" or an FQDN */
367 extern int suppress_tags;       /* suppress tags in tagged protocols? */
368 #ifdef SDPS_ENABLE
369 extern char *sdps_envfrom;
370 extern char *sdps_envto;
371 #endif /* SDPS_ENABLE */
372
373 /* prototypes for globally callable functions */
374
375 /* error.c: Error reporting */
376 #if defined(HAVE_STDARG_H)
377 void report_init(int foreground);
378 void report (FILE *fp, const char *format, ...);
379 void report_build (FILE *fp, const char *format, ...);
380 void report_complete (FILE *fp, const char *format, ...);
381 void report_at_line (FILE *fp, int, const char *, unsigned int, const char *, ...);
382 #else
383 void report ();
384 void report_build ();
385 void report_complete ();
386 void report_at_line ();
387 #endif
388
389 /* driver.c: transaction support */
390 void set_timeout(int);
391 #if defined(HAVE_STDARG_H)
392 void gen_send (int sock, const char *, ... );
393 int gen_recv(int sock, char *buf, int size);
394 int gen_transact (int sock, const char *, ... );
395 #else
396 void gen_send ();
397 int gen_recv();
398 int gen_transact ();
399 #endif
400
401 /* use these to track what was happening when the nonresponse timer fired */
402 #define GENERAL_WAIT    0       /* unknown wait type */
403 #define OPEN_WAIT       1       /* waiting from mailserver open */
404 #define SERVER_WAIT     2       /* waiting for mailserver response */
405 #define LISTENER_WAIT   3       /* waiting for listener initialization */
406 #define FORWARDING_WAIT 4       /* waiting for listener response */
407 extern int phase;
408
409 /* response hooks can use this to identify the query stage */
410 #define STAGE_GETAUTH   0
411 #define STAGE_GETRANGE  1
412 #define STAGE_GETSIZES  2
413 #define STAGE_FETCH     3
414 #define STAGE_IDLE      4
415 #define STAGE_LOGOUT    5
416 extern int stage;
417
418 extern int mytimeout;
419
420 /* mark values for name lists */
421 #define XMIT_ACCEPT     1       /* accepted; matches local domain or name */
422 #define XMIT_REJECT     2       /* rejected; no match */
423 #define XMIT_RCPTBAD    3       /* SMTP listener rejected the name */ 
424
425 /* idle.c */
426 int interruptible_idle(int interval);
427
428 /* sink.c: forwarding */
429 int stuffline(struct query *, char *);
430 int open_sink(struct query*, struct msgblk *, int*, int*);
431 void release_sink(struct query *);
432 int close_sink(struct query *, struct msgblk *, flag);
433 int open_warning_by_mail(struct query *, struct msgblk *);
434 #if defined(HAVE_STDARG_H)
435 void stuff_warning(struct query *, const char *, ... );
436 #else
437 void stuff_warning();
438 #endif
439 void close_warning_by_mail(struct query *, struct msgblk *);
440
441 /* rfc822.c: RFC822 header parsing */
442 unsigned char *reply_hack(unsigned char *, const unsigned char *);
443 unsigned char *nxtaddr(const unsigned char *);
444
445 /* uid.c: UID support */
446 void initialize_saved_lists(struct query *, const char *);
447 struct idlist *save_str(struct idlist **, const char *, flag);
448 void free_str_list(struct idlist **);
449 struct idlist *copy_str_list(struct idlist *idl);
450 void save_str_pair(struct idlist **, const char *, const char *);
451 void free_str_pair_list(struct idlist **);
452 int delete_str(struct idlist **, int);
453 int str_in_list(struct idlist **, const char *, const flag);
454 int str_nr_in_list(struct idlist **, const char *);
455 int str_nr_last_in_list(struct idlist **, const char *);
456 void str_set_mark( struct idlist **, const char *, const flag);
457 int count_list( struct idlist **idl );
458 char *str_from_nr_list( struct idlist **idl, int number );
459 char *str_find(struct idlist **, int);
460 char *idpair_find(struct idlist **, const char *);
461 void append_str_list(struct idlist **, struct idlist **);
462 void expunge_uids(struct query *);
463 void uid_swap_lists(struct query *);
464 void write_saved_lists(struct query *, const char *);
465
466 /* rcfile_y.y */
467 int prc_parse_file(const char *, const flag);
468 int prc_filecheck(const char *, const flag);
469
470 /* base64.c */
471 void to64frombits(unsigned char *, const unsigned char *, int);
472 int from64tobits(char *, const char *);
473
474 /* unmime.c */
475 /* Bit-mask returned by MimeBodyType */
476 #define MSG_IS_7BIT       0x01
477 #define MSG_IS_8BIT       0x02
478 #define MSG_NEEDS_DECODE  0x80
479 extern void UnMimeHeader(unsigned char *buf);
480 extern int  MimeBodyType(unsigned char *hdrs, int WantDecode);
481 extern int  UnMimeBodyline(unsigned char **buf, flag delimited, flag issoftline);
482
483 /* interface.c */
484 void interface_init(void);
485 void interface_parse(char *, struct hostdata *);
486 void interface_note_activity(struct hostdata *);
487 int interface_approve(struct hostdata *, flag domonitor);
488
489 /* xmalloc.c */
490 #if defined(HAVE_VOIDPOINTER)
491 #define XMALLOCTYPE void
492 #else
493 #define XMALLOCTYPE char
494 #endif
495 XMALLOCTYPE *xmalloc(int);
496 XMALLOCTYPE *xrealloc(XMALLOCTYPE *, int);
497 char *xstrdup(const char *);
498 #if defined(HAVE_ALLOCA_H)
499 #include <alloca.h>
500 #else
501 #ifdef _AIX
502  #pragma alloca
503 #endif
504 #endif
505 #define xalloca(ptr, t, n)      if (!(ptr = (t) alloca(n)))\
506        {report(stderr, _("alloca failed")); exit(PS_UNDEFINED);}
507 #if FALSE
508 /*
509  * This is a hack to help xgettext which cannot find strings in
510  * macro definitions like the one for xalloca above.
511  */
512 static char *dummy = gettext_noop("alloca failed");
513 #endif
514
515 /* protocol driver and methods */
516 int do_protocol(struct query *, const struct method *);
517 int doPOP2 (struct query *); 
518 int doPOP3 (struct query *);
519 int doIMAP (struct query *);
520 int doETRN (struct query *);
521
522 /* authentication functions */
523 int do_cram_md5(int sock, char *command, struct query *ctl);
524 int do_rfc1731(int sock, char *command, char *truename);
525 int do_gssauth(int sock, char *command, char *hostname, char *username);
526 int do_otp(int sock, char *command, struct query *ctl);
527
528 /* miscellanea */
529 struct query *hostalloc(struct query *); 
530 int parsecmdline (int, char **, struct runctl *, struct query *);
531 char *MD5Digest (unsigned char *);
532 int POP3_auth_rpa(unsigned char *, unsigned char *, int socket);
533 void deal_with_sigchld(void);
534 int daemonize(const char *, void (*)(int));
535 char *fm_getpassword(char *);
536 void escapes(const char *, char *);
537 char *visbuf(const char *);
538 const char *showproto(int);
539 void dump_config(struct runctl *runp, struct query *querylist);
540 int is_host_alias(const char *, struct query *);
541 char *host_fqdn(void);
542 char *rfc822timestamp(void);
543 flag isafile(int);
544
545 void yyerror(const char *);
546 int yylex(void);
547
548 #ifdef __EMX__
549 void itimerthread(void*);
550 /* Have to include these first to avoid errors from redefining getcwd
551    and chdir.  They're re-include protected in EMX, so it's okay, I
552    guess.  */
553 #include <stdlib.h>
554 #include <unistd.h>
555 /* Redefine getcwd and chdir to get drive-letter support so we can
556    find all of our lock files and stuff. */
557 #define getcwd _getcwd2
558 #define chdir _chdir2
559 #endif /* _EMX_ */
560
561 # if HAVE_STRERROR
562 #  ifndef strerror              /* On some systems, strerror is a macro */
563 char *strerror ();
564 #  endif
565 # endif /* HAVE_STRERROR */
566
567 #define STRING_DISABLED (char *)-1
568 #define STRING_DUMMY    ""
569
570 #ifdef NeXT
571 #ifndef S_IXGRP
572 #define S_IXGRP 0000010
573 #endif
574 #endif
575
576 #ifdef FETCHMAIL_DEBUG
577 #define exit(e) do { \
578        FILE *out; \
579        out = fopen("/tmp/fetchmail.log", "a"); \
580        fprintf(out, \
581                "Exiting fetchmail from file %s, line %d with status %d\n", \
582                __FILE__, __LINE__, e); \
583        fclose(out); \
584        _exit(e); \
585        } while(0)
586 #endif /* FETCHMAIL_DEBUG */
587
588 /* fetchmail.h ends here */