]> Pileus Git - ~andy/fetchmail/blob - fetchmail.h
Work on multiple idle connections
[~andy/fetchmail] / fetchmail.h
1 /** \file fetchmail.h  header file for fetchmail */
2 #ifndef _FETCHMAIL_H
3 #define _FETCHMAIL_H
4 /*
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include "config.h"
9
10 #ifdef __NetBSD__
11 #define _NETBSD_SOURCE 1
12 #endif
13
14 #include "gettext.h"
15 #define GT_(String) gettext (String)
16 #define gettext_noop(String) String
17 #define N_(String) gettext_noop (String)
18
19 struct addrinfo;
20
21 /* We need this for size_t */
22 #include <sys/types.h>
23
24 #include <sys/time.h>
25 #include <time.h>
26
27 #include <sys/socket.h>
28 #include <netdb.h>
29 #include <stdio.h>
30
31 #include "fm_strl.h"
32
33 #include "uid_db.h"
34
35 #ifdef HAVE_LIBPWMD
36 #include <libpwmd.h>
37 #endif
38
39 /** constants designating the various supported protocols -- ordered */
40 enum protocols {
41     P_AUTO = 1  /**< probe IMAP and POP3 - deprecated */,
42     P_POP3      /**  POP3, including APOP and KPOP, RFC 1939 et al. */,
43     P_IMAP      /**  IMAP4, RFC 3501 */,
44     P_ETRN      /**  ETRN - SMTP Service Extension for Remote Message Queue Starting, "extended TURN", RFC 1985 */,
45     P_ODMR      /**  ODMR/ATRN - On-Demand Mail Relay SMTP with dynamic addresses/Authenticated TURN, RFC 2645 */
46 };
47
48 #define         SMTP_PORT       "smtp"
49 #define         SMTP_PORT_NUM   25
50 #define         KPOP_PORT       "kpop"
51
52 #ifdef SSL_ENABLE
53 #define         SIMAP_PORT      993
54 #define         SPOP3_PORT      995
55 #endif
56
57 /* 
58  * We need to distinguish between mailbox and mailbag protocols.
59  * Under a mailbox protocol wwe're pulling mail for a speecific user.
60  * Under a mailbag protocol we're fetching mail for an entire domain.
61  */
62 #define MAILBOX_PROTOCOL(ctl)   ((ctl)->server.protocol < P_ETRN)
63
64 /** authentication types */
65 enum authenticators {
66         A_ANY = 0       /**< use the first method that works */,
67         A_PASSWORD      /** password authentication */,
68         A_NTLM          /** Microsoft NTLM protocol */,
69         A_CRAM_MD5      /** CRAM-MD5 shrouding (RFC2195) */,
70         A_OTP           /** One-time password (RFC1508) */,
71         A_APOP          /** POP3 APOP */,
72         A_KERBEROS_V5   /** authenticate w/ Kerberos V5 */,
73         A_GSSAPI        /** authenticate with GSSAPI */,
74         A_SSH           /** authentication at session level */,
75         A_MSN           /** same as NTLM with keyword MSN */,
76         A_EXTERNAL      /** external authentication (client cert) */
77 };
78
79 /* some protocols or authentication types (KERBEROS, GSSAPI, SSH) don't
80  * require a password */
81 #define NO_PASSWORD(ctl) \
82     ((ctl)->server.authenticate == A_OTP \
83      || (ctl)->server.authenticate == A_KERBEROS_V5 \
84      || (ctl)->server.authenticate == A_GSSAPI \
85      || (ctl)->server.authenticate == A_SSH \
86      || (ctl)->server.authenticate == A_EXTERNAL \
87      || (ctl)->server.protocol == P_ETRN)
88
89 /*
90  * Definitions for buffer sizes.  We get little help on setting maxima
91  * from IMAP RFCs up to 2060, so these are mostly from POP3.
92  */
93 #define         HOSTLEN         635     /* max hostname length (RFC1123) */
94 #define         POPBUFSIZE      512     /* max length of response (RFC1939) */
95 #define         IDLEN           128     /* max length of UID (RFC1939) */
96
97 /* per RFC1939 this should be 40, but Microsoft Exchange ignores that limit */
98 #define         USERNAMELEN     128     /* max POP3 arg length */
99
100 /* clear a netBSD kernel parameter out of the way */ 
101 #undef          MSGBUFSIZE
102
103 /*
104  * The RFC822 limit on message line size is just 998.  But
105  * make this *way* oversized; idiot DOS-world mailers that
106  * don't line-wrap properly often ship entire paragraphs as
107  * lines.
108  */
109 #define         MSGBUFSIZE      8192
110
111 #define         NAMELEN         64      /* max username length */
112 #define         PASSWORDLEN     64      /* max password length */
113 #define         DIGESTLEN       33      /* length of MD5 digest */
114
115 /* exit code values */
116 /* NOTE THAT PS_SUCCESS MUST ALWAYS BE 0 - SOME PARTS OF THE CODE
117  * RELY ON THIS VALUE! */
118 #define         PS_SUCCESS      0       /* successful receipt of messages */
119 #define         PS_NOMAIL       1       /* no mail available */
120 #define         PS_SOCKET       2       /* socket I/O woes */
121 #define         PS_AUTHFAIL     3       /* user authorization failed */
122 #define         PS_PROTOCOL     4       /* protocol violation */
123 #define         PS_SYNTAX       5       /* command-line syntax error */
124 #define         PS_IOERR        6       /* bad permissions on rc file */
125 #define         PS_ERROR        7       /* protocol error */
126 #define         PS_EXCLUDE      8       /* client-side exclusion error */
127 #define         PS_LOCKBUSY     9       /* server responded lock busy */
128 #define         PS_SMTP         10      /* SMTP error */
129 #define         PS_DNS          11      /* fatal DNS error */
130 #define         PS_BSMTP        12      /* output batch could not be opened */
131 #define         PS_MAXFETCH     13      /* poll ended by fetch limit */
132 #define         PS_SERVBUSY     14      /* server is busy */
133 /* leave space for more codes */
134 #define         PS_UNDEFINED    23      /* something I hadn't thought of */
135 #define         PS_TRANSIENT    24      /* transient failure (internal use) */
136 #define         PS_REFUSED      25      /* mail refused (internal use) */
137 #define         PS_RETAINED     26      /* message retained (internal use) */
138 #define         PS_REPOLL       28      /* repoll immediately with changed parameters (internal use) */
139 #define         PS_IDLETIMEOUT  29      /* timeout on imap IDLE (internal use) */
140 #define         PS_UNTAGGED     30      /* untagged response on imap command (internal use) */
141
142 /* output noise level */
143 #define         O_SILENT        0       /* mute, max squelch, etc. */
144 #define         O_NORMAL        1       /* user-friendly */
145 #define         O_VERBOSE       2       /* chatty */
146 #define         O_DEBUG         3       /* prolix */
147 #define         O_MONITOR       O_VERBOSE
148
149 #define         SIZETICKER      1024    /* print 1 dot per this many bytes */
150
151 /*
152  * We #ifdef this and use flag rather than bool
153  * to avoid a type clash with curses.h
154  */
155 #ifndef TRUE
156 #define FALSE   0
157 #define TRUE    1
158 #endif /* TRUE */
159 typedef char    flag;
160
161 /* we need to use zero as a flag-uninitialized value */
162 #define FLAG_TRUE       2
163 #define FLAG_FALSE      1
164
165 /** run control data */
166 struct runctl
167 {
168     char        *logfile;       /** where to write log information */
169     char        *idfile;        /** where to store UID data */
170     char        *pidfile;       /** where to record the PID of daemon mode processes */
171     const char  *postmaster;
172     char        *properties;
173 #ifdef HAVE_LIBPWMD
174     int         pinentry_timeout;
175 #endif
176     int         poll_interval;  /** poll interval in seconds (daemon mode, 0 == off) */
177     flag        bouncemail;
178     flag        spambounce;
179     flag        softbounce;
180     flag        use_syslog;
181     flag        invisible;
182     flag        showdots;
183 };
184
185 /** \name idlist */
186 /** Dual-use entry of singly-linked list for storing id/status or id/id2
187  * pairs. */
188 struct idlist
189 {
190     char *id;   /**< key */
191     union
192     {
193         struct
194         {
195             int         num;
196             flag        mark;           /**< UID-index information */
197         }
198         status;                         /**< value for id/status pairs */
199         char *id2;                      /**< value for id/id2 pairs */
200     } val;                              /**< union to store value for key \a id */
201     struct idlist *next;                /**< pointer to next list element */
202 };
203
204 /** List of possible values for idlist::mark */
205 enum {
206 UID_UNSEEN=     0,              /**< id hasn't been seen */
207 UID_SEEN=       1,              /**< id was seen, but not deleted */
208 UID_DELETED=    2,              /**< this message has been marked deleted */
209 UID_EXPUNGED=   3               /**< this message has been expunged */
210 };
211 /**/
212
213
214 struct query;
215
216 struct method           /* describe methods for protocol state machine */
217 {
218     const char *name;           /* protocol name */
219     const char *service;        /* service port (unencrypted) */
220     const char *sslservice;     /* service port (SSL) */
221     flag tagged;                /* if true, generate & expect command tags */
222     flag delimited;             /* if true, accept "." message delimiter */
223     int (*parse_response)(int, char *);
224                                 /* response_parsing function */
225     int (*getauth)(int, struct query *, char *);
226                                 /* authorization fetcher */
227     int (*getrange)(int, struct query *, const char *, int *, int *, int *);
228                                 /* get message range to fetch */
229     int (*getsizes)(int, int, int *);
230                                 /* get sizes of messages */
231     int (*getpartialsizes)(int, int, int, int *);
232                                 /* get sizes of subset of messages */
233     int (*is_old)(int, struct query *, int);
234                                 /* check for old message */
235     int (*fetch_headers)(int, struct query *, int, int *);
236                                 /* fetch header from a given message */
237     int (*fetch_body)(int, struct query *, int, int *);
238                                 /* fetch a given message */
239     int (*trail)(int, struct query *, const char *);
240                                 /* eat trailer of a message */
241     int (*delete_msg)(int, struct query *, int);
242                                 /* delete method */
243     int (*mark_seen)(int, struct query *, int);
244                                 /* mark as seen method */
245     int (*end_mailbox_poll)(int, struct query *);
246                                 /* end-of-mailbox processing */
247     int (*start_idle)(int, struct query *);
248                                 /* enter idle state */
249     int (*finish_idle)(int, struct query *);
250                                 /* return from idle state */
251     int (*logout_cmd)(int, struct query *);
252                                 /* logout command */
253     flag retry;                 /* can getrange poll for new messages? */
254 };
255
256 enum badheader { BHREJECT = 0, BHACCEPT };
257
258 /* Message retrieval error mode */
259 enum retrieveerror { RE_ABORT = 0, RE_CONTINUE, RE_MARKSEEN };
260
261 struct hostdata         /* shared among all user connections to given server */
262 {
263     /* rc file data */
264     char *pollname;                     /* poll label of host */
265     char *via;                          /* "true" server name if non-NULL */
266     struct idlist *akalist;             /* server name first, then akas */
267     struct idlist *localdomains;        /* list of pass-through domains */
268     int protocol;                       /* protocol type */
269     char *service;                      /* service name */
270     int interval;                       /* # cycles to skip between polls */
271     int authenticate;                   /* authentication mode to try */
272     int timeout;                        /* inactivity timout in seconds */
273     char *envelope;                     /* envelope address list header */
274     int envskip;                        /* skip to numbered envelope header */
275     char *qvirtual;                     /* prefix removed from local user id */
276     flag skip;                          /* suppress poll in implicit mode? */
277     flag dns;                           /* do DNS lookup on multidrop? */
278 #ifdef SDPS_ENABLE
279     flag sdps;                          /* use Demon Internet SDPS *ENV */
280 #endif /* SDPS_ENABLE */
281     flag checkalias;                    /* resolve aliases by comparing IPs? */
282     flag tracepolls;                    /* if TRUE, add poll trace info to Received */
283     char *principal;                    /* Kerberos principal for mail service */
284     char *esmtp_name, *esmtp_password;  /* ESMTP AUTH information */
285     enum badheader badheader;           /* bad-header {pass|reject} */
286     enum retrieveerror retrieveerror;   /* retrieve-error (abort|continue|markseen) */
287
288 #if defined(linux) || defined(__FreeBSD__)
289 #define CAN_MONITOR
290 #endif
291
292 #ifdef CAN_MONITOR
293     char *interface;
294     char *monitor;
295     int  monitor_io;
296     struct interface_pair_s *interface_pair;
297 #endif
298
299     char *plugin,*plugout;
300
301     /* computed for internal use */
302     const struct method *base_protocol; /* relevant protocol method table */
303     int poll_count;                     /* count of polls so far */
304     char *queryname;                    /* name to attempt DNS lookup on */
305     char *truename;                     /* "true name" of server host */
306     struct sockaddr *trueaddr;          /* IP address of truename */
307     size_t trueaddr_len;                /* size of trueaddr data */
308     struct hostdata *lead_server;       /* ptr to lead query for this server */
309     int esmtp_options;
310     int workarounds;                    /* track which workarounds the user was warned about */
311     int true_idle;                      /* the server supports true idle connections */
312     int idle_socket;                    /* the open socket for idle connections */
313     flag idle_ready;                    /* true if the idle socket has data available */
314 };
315
316 /*
317  * bit flags to set in workarounds after the corresponding warning,
318  * which we assume to be server-specific, has been printed,
319  * so we don't spam our users in daemon mode.
320  */
321 #define WKA_TOP (1L << 0)               /* Maillennium TOP -> RETR override warning */
322
323 struct query
324 {
325     /* mailserver connection controls */
326     struct hostdata server;
327
328     /* per-user data */
329     struct idlist *localnames;  /* including calling user's name */
330     int wildcard;               /* should unmatched names be passed through */
331     char *remotename;           /* remote login name to use */
332     char *password;             /* remote password to use */
333     struct idlist *mailboxes;   /* list of mailboxes to check */
334
335 #ifdef HAVE_LIBPWMD
336     char *pwmd_socket;          /* socket to connect to */
337     char *pwmd_file;            /* file to open on the server */
338 #endif
339
340     /* per-forwarding-target data */
341     struct idlist *smtphunt;    /* list of SMTP hosts to try forwarding to */
342     struct idlist *domainlist;  /* domainlist to fetch from */
343     char *smtpaddress;          /* address to force in RCPT TO */ 
344     char *smtpname;             /* full RCPT TO name, including domain */
345     struct idlist *antispam;    /* list of listener's antispam response */
346     const char *mda;            /* local MDA to pass mail to */
347     char *bsmtp;                /* BSMTP output file */
348     char listener;              /* what's the listener's wire protocol? */
349 #define SMTP_MODE       'S'
350 #define LMTP_MODE       'L'
351     char *preconnect;           /* pre-connection command to execute */
352     char *postconnect;          /* post-connection command to execute */
353
354     /* per-user control flags */
355     flag keep;                  /* if TRUE, leave messages undeleted */
356     flag fetchall;              /* if TRUE, fetch all (not just unseen) */
357     flag flush;                 /* if TRUE, delete messages already seen */
358     flag limitflush;            /* if TRUE, delete oversized mails */
359     flag rewrite;               /* if TRUE, canonicalize recipient addresses */
360     flag stripcr;               /* if TRUE, strip CRs in text */
361     flag forcecr;               /* if TRUE, force CRs before LFs in text */
362     flag pass8bits;             /* if TRUE, ignore Content-Transfer-Encoding */
363     flag dropstatus;            /* if TRUE, drop Status lines in mail */
364     flag dropdelivered;         /* if TRUE, drop Delivered-To lines in mail */
365     flag mimedecode;            /* if TRUE, decode MIME-armored messages */
366     flag idle;                  /* if TRUE, idle after each poll */
367     int limit;                  /* limit size of retrieved messages */
368     int warnings;               /* size warning interval */
369     int fetchlimit;             /* max # msgs to get in single poll */
370     int fetchsizelimit;         /* max # msg sizes to get in a request */
371     int fastuidl;               /* do binary search for new UIDLs? */
372     int fastuidlcount;          /* internal count for frequency of binary search */
373     int batchlimit;             /* max # msgs to pass in single SMTP session */
374     int expunge;                /* max # msgs to pass between expunges */
375     flag use_ssl;               /* use SSL encrypted session */
376     char *sslkey;               /* optional SSL private key file */
377     char *sslcert;              /* optional SSL certificate file */
378     char *sslproto;             /** force transport protocol (ssl2|ssl3|ssl23|tls1) - if NULL,
379                                   use ssl23 for SSL and opportunistic tls1 for non-SSL connections. */
380     char *sslcertfile;          /* Trusted certificate file for checking the server cert */
381     char *sslcertpath;          /* Trusted certificate directory for checking the server cert */
382     flag sslcertck;             /* Strictly check the server cert. */
383     char *sslcommonname;        /* CommonName to expect from server */
384     char *sslfingerprint;       /* Fingerprint to check against */
385     char *properties;           /* passthrough properties for extensions */
386
387     /* internal use -- per-poll state */
388     flag active;                /* should we actually poll this server? */
389     char *destaddr;             /* destination host for this query */
390     int errcount;               /* count transient errors in last pass */
391     int authfailcount;          /* count of authorization failures */
392     int wehaveauthed;           /* We've managed to logon at least once! */
393     int wehavesentauthnote;     /* We've sent an authorization failure note */
394     int wedged;                 /* wedged by auth failures or timeouts? */
395     char *smtphost;             /* actual SMTP host we connected to */
396     char smtphostmode;          /* what's the actual SMTP host's wire protocol? */
397     int smtp_socket;            /* socket descriptor for SMTP connection */
398     unsigned int uid;           /* UID of user to deliver to */
399     struct idlist *skipped;     /* messages skipped on the mail server */
400     struct uid_db oldsaved, newsaved;
401     char lastdigest[DIGESTLEN]; /* last MD5 hash seen on this connection */
402     char *folder;               /* folder currently being polled */
403
404     /* internal use -- per-message state */
405     int mimemsg;                /* bitmask indicating MIME body-type */
406     unsigned char digest[DIGESTLEN];    /* md5 digest buffer */
407
408     /* internal use -- housekeeping */
409     struct query *next;         /* next query control block in chain */
410 };
411
412 struct msgblk                   /** message header parsed for open_sink() */
413 {
414     char                *headers;       /**< raw message headers */
415     struct idlist       *recipients;    /**< addressees */
416     char                return_path[HOSTLEN + USERNAMELEN + 4]; /**< envelope sender */
417     int                 msglen;
418     int                 reallen;
419 };
420
421
422 /*
423  * Numeric option handling.  Numeric option value of zero actually means
424  * it's unspecified.  Value less than zero is zero.  The reason for this
425  * screwy encoding is so we can zero out an option block in order to set the
426  * numeric flags in it to unspecified.
427  */
428 #define NUM_VALUE_IN(n)         (((n) == 0) ? -1 : (n))
429 #define NUM_VALUE_OUT(n)        (((n) < 0) ? 0 : (n))
430 #define NUM_NONZERO(n)          ((n) > 0)
431 #define NUM_ZERO(n)             ((n) < 0)
432 #define NUM_SPECIFIED(n)        ((n) != 0)
433
434 #define MULTIDROP(ctl)          ((ctl)->wildcard || \
435                                  ((ctl)->localnames && (ctl)->localnames->next))
436
437 /*
438  * Note: tags are generated with an a%04d format from a 1-origin
439  * integer sequence number.  Length 4 permits transaction numbers
440  * up to 9999, so we force rollover with % 10000.  There's no special
441  * reason for this format other than to look like the exmples in the
442  * IMAP RFCs.
443  */
444 #define TAGLEN  6               /* 'a' + 4 digits + NUL */
445 extern char tag[TAGLEN];
446 #define TAGMOD  10000
447
448 /* list of hosts assembled from run control file and command line */
449 extern struct query cmd_opts, *querylist;
450
451 /* what's returned by envquery */
452 extern void envquery(int, char **);
453
454 /* controls the detail level of status/progress messages written to stderr */
455 extern int outlevel;            /* see the O_.* constants above */
456 extern int yydebug;             /* enable parse debugging */
457
458 /* these get computed */
459 extern int batchcount;          /* count of messages sent in current batch */
460 extern flag peek_capable;       /* can we read msgs without setting seen? */
461
462 /* miscellaneous global controls */
463 extern struct runctl run;       /* global controls for this run */
464 extern flag nodetach;           /* if TRUE, don't detach daemon process */
465 extern flag quitmode;           /* if --quit was set */
466 extern int  quitind;            /* optind after position of last --quit option */
467 extern flag check_only;         /* if --check was set */
468 extern char *rcfile;            /* path name of rc file */
469 extern int linelimit;           /* limit # lines retrieved per site */
470 extern flag versioninfo;        /* emit only version info */
471 extern char *user;              /* name of invoking user */
472 extern char *home;              /* home directory of invoking user */
473 extern char *fmhome;            /* fetchmail home directory */
474 extern int pass;                /* number of re-polling pass */
475 extern flag configdump;         /* dump control blocks as Python dictionary */
476 extern const char *fetchmailhost; /* either "localhost" or an FQDN */
477 extern int suppress_tags;       /* suppress tags in tagged protocols? */
478 extern char shroud[PASSWORDLEN*2+3];    /* string to shroud in debug output */
479 #ifdef SDPS_ENABLE
480 extern char *sdps_envfrom;
481 extern char *sdps_envto;
482 #endif /* SDPS_ENABLE */
483
484 extern const char *iana_charset;        /* IANA assigned charset name */
485
486 /* from/for ucs/norm_charmap.c */
487 #include "ucs/norm_charmap.h"
488
489 /* prototypes for globally callable functions */
490
491 /* from /usr/include/sys/cdefs.h */
492 #if !defined __GNUC__
493 # define __attribute__(xyz)    /* Ignore. */
494 #endif
495
496 /* error.c: Error reporting */
497 void report_init(int foreground);
498  /** Flush partial message, suppress program name tag for next report printout. */
499 void report_flush(FILE *fp);
500 void report (FILE *fp, const char *format, ...)
501     __attribute__ ((format (printf, 2, 3)))
502     ;
503 void report_build (FILE *fp, const char *format, ...)
504     __attribute__ ((format (printf, 2, 3)))
505     ;
506 void report_complete (FILE *fp, const char *format, ...)
507     __attribute__ ((format (printf, 2, 3)))
508     ;
509 void report_at_line (FILE *fp, int, const char *, unsigned int, const char *, ...)
510     __attribute__ ((format (printf, 5, 6)))
511     ;
512
513 /* driver.c -- main driver loop */
514 void set_timeout(int);
515 int is_idletimeout(void);
516 void resetidletimeout(void);
517 int do_protocol(struct query *, const struct method *);
518
519 /* transact.c: transaction support */
520 /** \ingroup gen_recv_split
521  * Data structure to cache data between \func gen_recv_split calls,
522  * must be initialized before use by calling \func gen_recv_split_init. */
523 struct RecvSplit
524 {
525     char prefix[100];           /**< prefix to match/repeat when splitting lines */
526     int cached;                 /**< flag to record if we have data cached in \a buf */
527     char buf[MSGBUFSIZE];       /**< buffer for cached data */
528 };
529
530 void init_transact(const struct method *);
531 int readheaders(int sock,
532                        long fetchlen,
533                        long reallen,
534                        struct query *ctl,
535                        int num,
536                        flag *suppress_readbody);
537 int readbody(int sock, struct query *ctl, flag forward, int len);
538 void gen_send(int sock, const char *, ... )
539     __attribute__ ((format (printf, 2, 3)))
540     ;
541 int gen_recv(int sock, char *buf, int size);
542 void gen_recv_split_init(const char *prefix, struct RecvSplit *rs);
543 int gen_recv_split(int sock, char *buf, int size, struct RecvSplit *rs);
544 int gen_transact(int sock, const char *, ... )
545     __attribute__ ((format (printf, 2, 3)))
546     ;
547 extern struct msgblk msgblk;
548
549 /* use these to track what was happening when the nonresponse timer fired */
550 #define GENERAL_WAIT    0       /* unknown wait type */
551 #define OPEN_WAIT       1       /* waiting from mailserver open */
552 #define SERVER_WAIT     2       /* waiting for mailserver response */
553 #define LISTENER_WAIT   3       /* waiting for listener initialization */
554 #define FORWARDING_WAIT 4       /* waiting for listener response */
555 extern int phase;
556
557 /* response hooks can use this to identify the query stage */
558 #define STAGE_GETAUTH   0
559 #define STAGE_GETRANGE  1
560 #define STAGE_GETSIZES  2
561 #define STAGE_FETCH     3
562 #define STAGE_IDLE      4
563 #define STAGE_LOGOUT    5
564 extern int stage;
565
566 extern int mytimeout;
567
568 /* mark values for name lists */
569 #define XMIT_ACCEPT     1       /* accepted; matches local domain or name */
570 #define XMIT_REJECT     2       /* rejected; no match */
571 #define XMIT_RCPTBAD    3       /* SMTP listener rejected the name */ 
572
573 /* idle.c */
574 int interruptible_idle(int interval);
575 extern volatile int lastsig;
576
577 /* sink.c: forwarding */
578 void smtp_close(struct query *, int);
579 int smtp_open(struct query *);
580 int smtp_setup(struct query *);
581 char *rcpt_address(struct query *, const char *, int);
582 int stuffline(struct query *, char *);
583 int open_sink(struct query*, struct msgblk *, int*, int*);
584 void release_sink(struct query *);
585 int close_sink(struct query *, struct msgblk *, flag);
586 int open_warning_by_mail(struct query *);
587 void stuff_warning(const char *, struct query *, const char *, ... )
588     __attribute__ ((format (printf, 3, 4)))
589     ;
590 void close_warning_by_mail(struct query *, struct msgblk *);
591 void abort_message_sink(struct query *ctl);
592
593 /* rfc822.c: RFC822 header parsing */
594 char *reply_hack(char *, const char *, size_t *);
595 char *nxtaddr(const char *);
596
597 /* uid.c: UID support */
598 extern int dofastuidl;
599 void initialize_saved_lists(struct query *hostlist, const char *idfile);
600 void expunge_uids(struct query *ctl);
601 void uid_swap_lists(struct query *ctl);
602 void uid_discard_new_list(struct query *ctl);
603 void uid_reset_num(struct query *ctl);
604 void write_saved_lists(struct query *hostlist, const char *idfile);
605
606 /* idlist.c */
607 struct idlist *save_str(struct idlist **idl, const char *str, flag status);
608 void free_str_list(struct idlist **idl);
609 void save_str_pair(struct idlist **idl, const char *str1, const char *str2);
610 struct idlist *str_in_list(struct idlist **idl, const char *str, const flag caseblind);
611 int str_nr_in_list(struct idlist **idl, const char *str);
612 int str_nr_last_in_list(struct idlist **idl, const char *str);
613 void str_set_mark(struct idlist **idl, const char *str, const flag val);
614 int count_list(struct idlist **idl);
615 char *str_from_nr_list(struct idlist **idl, long number);
616 char *str_find(struct idlist **idl, long number);
617 struct idlist *id_find(struct idlist **idl, long number);
618 char *idpair_find(struct idlist **idl, const char *id);
619 int delete_str(struct idlist **idl, long num);
620 struct idlist *copy_str_list(struct idlist *idl);
621 void append_str_list(struct idlist **idl, struct idlist **nidl);
622
623 /* rcfile_y.y */
624 int prc_parse_file(const char *, const flag);
625 int prc_filecheck(const char *, const flag);
626
627 /* base64.c */
628 void to64frombits(char *, const void *, int);
629 int from64tobits(void *, const char *, int maxlen);
630
631 /* unmime.c */
632 /* Bit-mask returned by MimeBodyType */
633 #define MSG_IS_7BIT       0x01
634 #define MSG_IS_8BIT       0x02
635 #define MSG_NEEDS_DECODE  0x80
636 extern void UnMimeHeader(char *buf);
637 extern int  MimeBodyType(char *hdrs, int WantDecode);
638 extern int  UnMimeBodyline(char **buf, flag delimited, flag issoftline);
639
640 /* interface.c */
641 void interface_init(void);
642 void interface_parse(char *, struct hostdata *);
643 void interface_note_activity(struct hostdata *);
644 int interface_approve(struct hostdata *, flag domonitor);
645
646 #include "xmalloc.h"
647
648 /* protocol driver and methods */
649 int doPOP3 (struct query *);
650 int doIMAP (struct query *);
651 int doETRN (struct query *);
652 int doODMR (struct query *);
653
654 /* authentication functions */
655 int do_cram_md5(int sock, const char *command, struct query *ctl, const char *strip);
656 int check_gss_creds(const char *service, const char *hostname);
657 int do_gssauth(int sock, const char *command, const char *service, const char *hostname, const char *username);
658 int do_otp(int sock, const char *command, struct query *ctl);
659
660 /* miscellanea */
661
662 /* these should be of size PATH_MAX */
663 extern char currentwd[1024], rcfiledir[1024];
664
665 struct query *hostalloc(struct query *); 
666 int parsecmdline (int, char **, struct runctl *, struct query *, flag *);
667 char *prependdir (const char *, const char *);
668 char *MD5Digest (unsigned const char *);
669 void hmac_md5 (const unsigned char *, size_t, const unsigned char *, size_t, unsigned char *, size_t);
670 int POP3_auth_rpa(char *, char *, int socket);
671 typedef void (*SIGHANDLERTYPE) (int);
672 void deal_with_sigchld(void);
673 void null_signal_handler(int sig);
674 SIGHANDLERTYPE set_signal_handler(int sig, SIGHANDLERTYPE handler);
675 int daemonize(const char *);
676 char *fm_getpassword(char *);
677 void escapes(const char *, char *);
678 char *visbuf(const char *);
679 const char *showproto(int);
680 void dump_config(struct runctl *runp, struct query *querylist);
681 int is_host_alias(const char *, struct query *, struct addrinfo **);
682
683 extern struct addrinfo *ai0, *ai1;
684
685 /** Try to obtain fully qualified hostname of current host. Exit with
686  * PS_DNS if \a required is true and there is a DNS error. Exit with
687  * PS_DNS if gethostname() fails, independent of the value of \a
688  * required.
689  * \return
690  * - fully qualified hostname if \a required is non-zero.
691  * - unqualified or fully qualified hostname if \a required is zero (0).
692  */
693 char *host_fqdn(int required /** exit with PS_DNS if the name cannot be qualified */);
694 char *rfc822timestamp(void);
695 flag is_a_file(int);
696 char *rfc2047e(const char*, const char *);
697
698 void yyerror(const char *);
699 int yylex(void);
700
701 #define STRING_DISABLED (char *)-1
702 #define STRING_DUMMY    ""
703
704 #ifndef HAVE_STPCPY
705 char *stpcpy(char *, const char*);
706 #endif
707
708 #ifdef __CYGWIN__
709 #define ROOT_UID 18
710 #else /* !__CYGWIN__ */
711 #define ROOT_UID 0
712 #endif /* __CYGWIN__ */
713
714 extern int mailserver_socket_temp;
715 extern const char *program_name;
716
717 /* POSIX space characters,
718  * <tab>;<newline>;<vertical-tab>;<form-feed>;<carriage-return>;<space> */
719 #define POSIX_space "\t\n\v\f\r "
720
721 /** Resolve the a TCP service name or a string containing only a decimal
722  * positive integer to a port number. Returns -1 for error. */
723 int servport(const char *service);
724
725 #ifndef HAVE_GETNAMEINFO
726 # define NI_NUMERICHOST 1
727 # define NI_NUMERICSERV 2
728 # define NI_NOFQDN      4
729 # define NI_NAMEREQD    8
730 # define NI_DGRAM       16
731 #endif
732
733 int fm_getaddrinfo(const char *node, const char *serv, const struct addrinfo *hints, struct addrinfo **res);
734 void fm_freeaddrinfo(struct addrinfo *ai);
735
736 /* prototypes from tls.c */
737 int maybe_tls(struct query *ctl);
738 int must_tls(struct query *ctl);
739
740 /* prototype from rfc822valid.c */
741 int rfc822_valid_msgid(const unsigned char *);
742
743 /* prototype from x509_name_match.c */
744 int name_match(const char *p1, const char *p2);
745
746 /* prototype from ntlmsubr.c */
747 #ifdef NTLM_ENABLE
748 int ntlm_helper(int sock, struct query *ctl, const char *protocol);
749 #endif
750
751 /* macro to determine if we want to spam progress to stdout */
752 #define want_progress() \
753         ((outlevel >= O_VERBOSE || (outlevel > O_SILENT && run.showdots)) \
754         && !run.use_syslog \
755         && (run.showdots || !is_a_file(1)))
756
757 #endif
758 /* fetchmail.h ends here */