chiark / gitweb /
Build system: Use -lnsl only if inet_ntoa is not found otherwise.
[secnet.git] / secnet.h
1 /* Core interface of secnet, to be used by all modules */
2 /*
3  * This file is part of secnet.
4  * See README for full list of copyright holders.
5  *
6  * secnet is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version d of the License, or
9  * (at your option) any later version.
10  * 
11  * secnet is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License
17  * version 3 along with secnet; if not, see
18  * https://www.gnu.org/licenses/gpl.html.
19  */
20
21 #ifndef secnet_h
22 #define secnet_h
23
24 #define ADNS_FEATURE_MANYAF
25
26 #include "config.h"
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <errno.h>
35 #include <fnmatch.h>
36 #include <sys/poll.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 #include <sys/time.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42
43 #include <bsd/sys/queue.h>
44
45 #define MAX_PEER_ADDRS 5
46 /* send at most this many copies; honour at most that many addresses */
47
48 struct comm_if;
49 struct comm_addr;
50
51 typedef char *string_t;
52 typedef const char *cstring_t;
53
54 #define False (_Bool)0
55 #define True  (_Bool)1
56 typedef _Bool bool_t;
57
58 union iaddr {
59     struct sockaddr sa;
60     struct sockaddr_in sin;
61 #ifdef CONFIG_IPV6
62     struct sockaddr_in6 sin6;
63 #endif
64 };
65
66 #define ASSERT(x) do { if (!(x)) { fatal("assertion failed line %d file " \
67                                          __FILE__,__LINE__); } } while(0)
68
69 /* from version.c */
70
71 extern char version[];
72
73 /* from logmsg.c */
74 extern uint32_t message_level;
75 extern bool_t secnet_is_daemon;
76 extern struct log_if *system_log;
77
78 /* from process.c */
79 extern void start_signal_handling(void);
80
81 void afterfork(void);
82 /* Must be called before exec in every child made after
83    start_signal_handling.  Safe to call in earlier children too. */
84
85 void childpersist_closefd_hook(void *fd_p, uint32_t newphase);
86 /* Convenience hook function for use with add_hook PHASE_CHILDPERSIST.
87    With `int fd' in your state struct, pass fd_p=&fd.  The hook checks
88    whether fd>=0, so you can use it for an fd which is only sometimes
89    open.  This function will set fd to -1, so it is idempotent. */
90
91 /***** CONFIGURATION support *****/
92
93 extern bool_t just_check_config; /* If True then we're going to exit after
94                                     reading the configuration file */
95 extern bool_t background; /* If True then we'll eventually run as a daemon */
96
97 typedef struct dict dict_t;        /* Configuration dictionary */
98 typedef struct closure closure_t;
99 typedef struct item item_t;
100 typedef struct list list_t;        /* A list of items */
101
102 /* Configuration file location, for error-reporting */
103 struct cloc {
104     cstring_t file;
105     int line;
106 };
107
108 /* Modules export closures, which can be invoked from the configuration file.
109    "Invoking" a closure usually returns another closure (of a different
110    type), but can actually return any configuration object. */
111 typedef list_t *(apply_fn)(closure_t *self, struct cloc loc,
112                            dict_t *context, list_t *data);
113 struct closure {
114     cstring_t description; /* For debugging */
115     uint32_t type; /* Central registry... */
116     apply_fn *apply;
117     void *interface; /* Interface for use inside secnet; depends on type */
118 };
119
120 enum types { t_null, t_bool, t_string, t_number, t_dict, t_closure };
121 struct item {
122     enum types type;
123     union {
124         bool_t bool;
125         string_t string;
126         uint32_t number;
127         dict_t *dict;
128         closure_t *closure;
129     } data;
130     struct cloc loc;
131 };
132
133 /* Note that it is unwise to use this structure directly; use the list
134    manipulation functions instead. */
135 struct list {
136     item_t *item;
137     struct list *next;
138 };
139
140 /* In the following two lookup functions, NULL means 'not found' */
141 /* Lookup a value in the specified dictionary, or its parents */
142 extern list_t *dict_lookup(dict_t *dict, cstring_t key);
143 /* Lookup a value in just the specified dictionary */
144 extern list_t *dict_lookup_primitive(dict_t *dict, cstring_t key);
145 /* Add a value to the specified dictionary */
146 extern void dict_add(dict_t *dict, cstring_t key, list_t *val);
147 /* Obtain an array of keys in the dictionary. malloced; caller frees */
148 extern cstring_t *dict_keys(dict_t *dict);
149
150 /* List-manipulation functions */
151 extern list_t *list_new(void);
152 extern int32_t list_length(const list_t *a);
153 extern list_t *list_append(list_t *a, item_t *i);
154 extern list_t *list_append_list(list_t *a, list_t *b);
155 /* Returns an item from the list (index starts at 0), or NULL */
156 extern item_t *list_elem(list_t *l, int32_t index);
157
158 /* Convenience functions */
159 extern list_t *new_closure(closure_t *cl);
160 extern void add_closure(dict_t *dict, cstring_t name, apply_fn apply);
161 extern void *find_cl_if(dict_t *dict, cstring_t name, uint32_t type,
162                         bool_t fail_if_invalid, cstring_t desc,
163                         struct cloc loc);
164 extern item_t *dict_find_item(dict_t *dict, cstring_t key, bool_t required,
165                               cstring_t desc, struct cloc loc);
166 extern string_t dict_read_string(dict_t *dict, cstring_t key, bool_t required,
167                                  cstring_t desc, struct cloc loc);
168 extern uint32_t dict_read_number(dict_t *dict, cstring_t key, bool_t required,
169                                  cstring_t desc, struct cloc loc,
170                                  uint32_t def);
171   /* return value can safely be assigned to int32_t */
172 extern bool_t dict_read_bool(dict_t *dict, cstring_t key, bool_t required,
173                              cstring_t desc, struct cloc loc, bool_t def);
174 const char **dict_read_string_array(dict_t *dict, cstring_t key,
175                                     bool_t required, cstring_t desc,
176                                     struct cloc loc, const char *const *def);
177   /* Return value is a NULL-terminated array obtained from malloc;
178    * Individual string values are still owned by config file machinery
179    * and must not be modified or freed.  Returns NULL if key not
180    * found. */
181
182 struct flagstr {
183     cstring_t name;
184     uint32_t value;
185 };
186 extern uint32_t string_to_word(cstring_t s, struct cloc loc,
187                                struct flagstr *f, cstring_t desc);
188 extern uint32_t string_list_to_word(list_t *l, struct flagstr *f,
189                                     cstring_t desc);
190
191 /***** END of configuration support *****/
192
193 /***** UTILITY functions *****/
194
195 extern char *safe_strdup(const char *string, const char *message);
196 extern void *safe_malloc(size_t size, const char *message);
197 extern void *safe_malloc_ary(size_t size, size_t count, const char *message);
198 extern void *safe_realloc_ary(void *p, size_t size, size_t count,
199                               const char *message);
200
201 #define NEW(p)                                  \
202     ((p)=safe_malloc(sizeof(*(p)),              \
203                      __FILE__ ":" #p))
204 #define NEW_ARY(p,count)                                        \
205     ((p)=safe_malloc_ary(sizeof(*(p)),(count),                  \
206                          __FILE__ ":" #p "[" #count "]"))
207 #define REALLOC_ARY(p,count)                                    \
208     ((p)=safe_realloc_ary((p),sizeof(*(p)),(count),             \
209                           __FILE__ ":" #p "[" #count "]"))
210
211 void setcloexec(int fd); /* cannot fail */
212 void setnonblock(int fd); /* cannot fail */
213 void pipe_cloexec(int fd[2]); /* pipe(), setcloexec() twice; cannot fail */
214
215 extern int sys_cmd(const char *file, const char *argc, ...);
216
217 extern uint64_t now_global;
218 extern struct timeval tv_now_global;
219
220 static const uint64_t       *const now    = &now_global;
221 static const struct timeval *const tv_now = &tv_now_global;
222
223 /* "now" is current program time, in milliseconds. It is derived
224    from tv_now. Both are provided by the event loop. */
225
226 /***** END of utility functions *****/
227
228 /***** START of max_start_pad handling *****/
229
230 extern int32_t site_max_start_pad, transform_max_start_pad,
231     comm_max_start_pad;
232
233 void update_max_start_pad(int32_t *our_module_global, int32_t our_instance);
234 int32_t calculate_max_start_pad(void);
235
236 /***** END of max_start_pad handling *****/
237
238 /***** SCHEDULING support */
239
240 /* If nfds_io is insufficient for your needs, set it to the required
241    number and return ERANGE. timeout is in milliseconds; if it is too
242    high then lower it. It starts at -1 (==infinite). */
243 /* Note that beforepoll_fn may NOT do anything which might change the
244    fds or timeouts wanted by other registered poll loop loopers.
245    Callers should make sure of this by not making any calls into other
246    modules from the beforepoll_fn; the easiest way to ensure this is
247    for beforepoll_fn to only retreive information and not take any
248    action.
249  */
250 typedef int beforepoll_fn(void *st, struct pollfd *fds, int *nfds_io,
251                           int *timeout_io);
252 typedef void afterpoll_fn(void *st, struct pollfd *fds, int nfds);
253   /* If beforepoll_fn returned ERANGE, afterpoll_fn gets nfds==0.
254      afterpoll_fn never gets !!(fds[].revents & POLLNVAL) - such
255      a report is detected as a fatal error by the event loop. */
256
257 /* void BEFOREPOLL_WANT_FDS(int want);
258  *   Expects: int *nfds_io;
259  *   Can perform non-local exit.
260  * Checks whether there is space for want fds.  If so, sets *nfds_io.
261  * If not, sets *nfds_io and returns. */
262 #define BEFOREPOLL_WANT_FDS(want) do{                           \
263     if (*nfds_io<(want)) { *nfds_io=(want); return ERANGE; }    \
264     *nfds_io=(want);                                            \
265   }while(0)
266
267 /* Register interest in the main loop of the program. Before a call
268    to poll() your supplied beforepoll function will be called. After
269    the call to poll() the supplied afterpoll function will be called. */
270 struct poll_interest *register_for_poll(void *st, beforepoll_fn *before,
271                               afterpoll_fn *after, cstring_t desc);
272 void deregister_for_poll(struct poll_interest *i);
273
274 /***** END of scheduling support */
275
276 /***** PROGRAM LIFETIME support */
277
278 /* The secnet program goes through a number of phases in its lifetime.
279    Module code may arrange to be called just as various phases are
280    entered.
281  
282    Remember to update the table in util.c if changing the set of
283    phases. */
284
285 enum phase {
286     PHASE_INIT,
287     PHASE_GETOPTS,             /* Process command-line arguments */
288     PHASE_READCONFIG,          /* Parse and process configuration file */
289     PHASE_SETUP,               /* Process information in configuration */
290     PHASE_DAEMONIZE,           /* Become a daemon (if necessary) */
291     PHASE_GETRESOURCES,        /* Obtain all external resources */
292     PHASE_DROPPRIV,            /* Last chance for privileged operations */
293     PHASE_RUN,
294     PHASE_SHUTDOWN,            /* About to die; delete key material, etc. */
295     PHASE_CHILDPERSIST,        /* Forked long-term child: close fds, etc. */
296     /* Keep this last: */
297     NR_PHASES,
298 };
299
300 /* Each module should, in its CHILDPERSIST hooks, close all fds which
301    constitute ownership of important operating system resources, or
302    which are used for IPC with other processes who want to get the
303    usual disconnection effects if the main secnet process dies.
304    CHILDPERSIST hooks are not run if the child is going to exec;
305    so fds such as described above should be CLOEXEC too. */
306
307 typedef void hook_fn(void *self, uint32_t newphase);
308 bool_t add_hook(uint32_t phase, hook_fn *f, void *state);
309 bool_t remove_hook(uint32_t phase, hook_fn *f, void *state);
310
311 extern uint32_t current_phase;
312 extern void enter_phase(uint32_t new_phase);
313
314 void phase_hooks_init(void); /* for main() only */
315 void clear_phase_hooks(uint32_t phase); /* for afterfork() */
316
317 /* Some features (like netlink 'soft' routes) require that secnet
318    retain root privileges.  They should indicate that here when
319    appropriate. */
320 extern bool_t require_root_privileges;
321 extern cstring_t require_root_privileges_explanation;
322
323 /* Some modules may want to know whether secnet is going to drop
324    privilege, so that they know whether to do privsep.  Call only
325    in phases SETUP and later. */
326 bool_t will_droppriv(void);
327
328 /***** END of program lifetime support *****/
329
330 /***** MODULE support *****/
331
332 /* Module initialisation function type - modules export one function of
333    this type which is called to initialise them. For dynamically loaded
334    modules it's called "secnet_module". */
335 typedef void init_module(dict_t *dict);
336
337 extern void init_builtin_modules(dict_t *dict);
338
339 extern init_module resolver_module;
340 extern init_module random_module;
341 extern init_module udp_module;
342 extern init_module polypath_module;
343 extern init_module util_module;
344 extern init_module site_module;
345 extern init_module transform_eax_module;
346 extern init_module transform_cbcmac_module;
347 extern init_module netlink_module;
348 extern init_module rsa_module;
349 extern init_module dh_module;
350 extern init_module md5_module;
351 extern init_module slip_module;
352 extern init_module tun_module;
353 extern init_module sha1_module;
354 extern init_module log_module;
355
356 /***** END of module support *****/
357
358 /***** CLOSURE TYPES and interface definitions *****/
359
360 #define CL_PURE         0
361 #define CL_RESOLVER     1
362 #define CL_RANDOMSRC    2
363 #define CL_RSAPUBKEY    3
364 #define CL_RSAPRIVKEY   4
365 #define CL_COMM         5
366 #define CL_IPIF         6
367 #define CL_LOG          7
368 #define CL_SITE         8
369 #define CL_TRANSFORM    9
370 #define CL_DH          11
371 #define CL_HASH        12
372 #define CL_BUFFER      13
373 #define CL_NETLINK     14
374
375 struct buffer_if;
376
377 /* PURE closure requires no interface */
378
379 /* RESOLVER interface */
380
381 /* Answers to queries are delivered to a function of this
382    type. 'address' will be NULL if there was a problem with the query. It
383    will be freed once resolve_answer_fn returns.  naddrs is the actual
384    size of the array at addrs; was_naddrs is the number of addresses
385    actually found in the DNS, which may be bigger if addrs is equal
386    to MAX_PEER_ADDRS (ie there were too many). */
387 typedef void resolve_answer_fn(void *st, const struct comm_addr *addrs,
388                                int naddrs, int was_naddrs,
389                                const char *name, const char *failwhy);
390   /* name is the same ptr as passed to request, so its lifetime must
391    * be suitable*/
392 typedef bool_t resolve_request_fn(void *st, cstring_t name,
393                                   int remoteport, struct comm_if *comm,
394                                   resolve_answer_fn *cb, void *cst);
395 struct resolver_if {
396     void *st;
397     resolve_request_fn *request;
398 };
399
400 /* RANDOMSRC interface */
401
402 /* Return some random data. Returns TRUE for success. */
403 typedef bool_t random_fn(void *st, int32_t bytes, uint8_t *buff);
404
405 struct random_if {
406     void *st;
407     bool_t blocking;
408     random_fn *generate;
409 };
410
411 /* RSAPUBKEY interface */
412
413 typedef bool_t rsa_checksig_fn(void *st, uint8_t *data, int32_t datalen,
414                                cstring_t signature);
415 struct rsapubkey_if {
416     void *st;
417     rsa_checksig_fn *check;
418 };
419
420 /* RSAPRIVKEY interface */
421
422 typedef string_t rsa_makesig_fn(void *st, uint8_t *data, int32_t datalen);
423 struct rsaprivkey_if {
424     void *st;
425     rsa_makesig_fn *sign;
426 };
427
428 /* COMM interface */
429
430 struct comm_addr {
431     /* This struct is pure data; in particular comm's clients may
432        freely copy it. */
433     struct comm_if *comm;
434     union iaddr ia;
435     int ix; /* see comment `Re comm_addr.ix' in udp.c */
436 };
437
438 /* Return True if the packet was processed, and shouldn't be passed to
439    any other potential receivers. (buf is freed iff True returned.) */
440 typedef bool_t comm_notify_fn(void *state, struct buffer_if *buf,
441                               const struct comm_addr *source);
442 typedef void comm_request_notify_fn(void *commst, void *nst,
443                                     comm_notify_fn *fn);
444 typedef void comm_release_notify_fn(void *commst, void *nst,
445                                     comm_notify_fn *fn);
446 typedef bool_t comm_sendmsg_fn(void *commst, struct buffer_if *buf,
447                                const struct comm_addr *dest);
448   /* Only returns false if (we know that) the local network
449    * environment is such that this address cannot work; transient
450    * or unknown/unexpected failures return true. */
451 typedef const char *comm_addr_to_string_fn(void *commst,
452                                            const struct comm_addr *ca);
453         /* Returned string is in a static buffer. */
454 struct comm_if {
455     void *st;
456     comm_request_notify_fn *request_notify;
457     comm_release_notify_fn *release_notify;
458     comm_sendmsg_fn *sendmsg;
459     comm_addr_to_string_fn *addr_to_string;
460 };
461
462 bool_t iaddr_equal(const union iaddr *ia, const union iaddr *ib,
463                    bool_t ignoreport);
464
465 static inline const char *comm_addr_to_string(const struct comm_addr *ca)
466 {
467     return ca->comm->addr_to_string(ca->comm->st, ca);
468 }
469
470 static inline bool_t comm_addr_equal(const struct comm_addr *a,
471                                      const struct comm_addr *b)
472 {
473     return a->comm==b->comm && iaddr_equal(&a->ia,&b->ia,False);
474 }
475
476 /* LOG interface */
477
478 #define LOG_MESSAGE_BUFLEN 1023
479
480 typedef void log_msg_fn(void *st, int class, const char *message, ...);
481 typedef void log_vmsg_fn(void *st, int class, const char *message,
482                          va_list args);
483 struct log_if {
484     void *st;
485     log_vmsg_fn *vlogfn; /* printf format checking.  Use [v]slilog instead */
486     char buff[LOG_MESSAGE_BUFLEN+1];
487 };
488 /* (convenience functions, defined in util.c) */
489 extern void slilog(struct log_if *lf, int class, const char *message, ...)
490 FORMAT(printf,3,4);
491 extern void vslilog(struct log_if *lf, int class, const char *message, va_list)
492 FORMAT(printf,3,0);
493
494 /* Versions which take (parts of) (multiple) messages, using \n to
495  * distinguish one message from another. */
496 extern void slilog_part(struct log_if *lf, int class, const char *message, ...)
497 FORMAT(printf,3,4);
498 extern void vslilog_part(struct log_if *lf, int class, const char *message,
499                          va_list) FORMAT(printf,3,0);
500
501 /* SITE interface */
502
503 /* Pretty much a placeholder; allows starting and stopping of processing,
504    key expiry, etc. */
505 typedef void site_control_fn(void *st, bool_t run);
506 typedef uint32_t site_status_fn(void *st);
507 struct site_if {
508     void *st;
509     site_control_fn *control;
510     site_status_fn *status;
511 };
512
513 /* TRANSFORM interface */
514
515 /* A reversable transformation. Transforms buffer in-place; may add
516    data to start or end. (Reverse transformations decrease
517    length, of course.)  Transformations may be key-dependent, in which
518    case key material is passed in at initialisation time. They may
519    also depend on internal factors (eg. time) and keep internal
520    state. A struct transform_if only represents a particular type of
521    transformation; instances of the transformation (eg. with
522    particular key material) have a different C type. The same
523    secret key will be used in opposite directions between a pair of
524    secnets; one of these pairs will get direction==False, the other True. */
525
526 typedef struct transform_inst_if *transform_createinstance_fn(void *st);
527 typedef bool_t transform_setkey_fn(void *st, uint8_t *key, int32_t keylen,
528                                    bool_t direction);
529 typedef bool_t transform_valid_fn(void *st); /* 0: no key; 1: ok */
530 typedef void transform_delkey_fn(void *st);
531 typedef void transform_destroyinstance_fn(void *st);
532 /* Returns:
533  *   0: all is well
534  *   1: for any other problem
535  *   2: message decrypted but sequence number was out of range
536  */
537 typedef uint32_t transform_apply_fn(void *st, struct buffer_if *buf,
538                                     const char **errmsg);
539
540 struct transform_inst_if {
541     void *st;
542     transform_setkey_fn *setkey;
543     transform_valid_fn *valid;
544     transform_delkey_fn *delkey;
545     transform_apply_fn *forwards;
546     transform_apply_fn *reverse;
547     transform_destroyinstance_fn *destroy;
548 };
549
550 struct transform_if {
551     void *st;
552     int capab_transformnum;
553     int32_t keylen; /* <<< INT_MAX */
554     transform_createinstance_fn *create;
555 };
556
557 /* NETLINK interface */
558
559 /* Used by netlink to deliver to site, and by site to deliver to
560    netlink.  cid is the client identifier returned by
561    netlink_regnets_fn.  If buf has size 0 then the function is just
562    being called for its site-effects (eg. making the site code attempt
563    to bring up a network link) */
564 typedef void netlink_deliver_fn(void *st, struct buffer_if *buf);
565 /* site code can tell netlink when outgoing packets will be dropped,
566    so netlink can generate appropriate ICMP and make routing decisions */
567 #define LINK_QUALITY_UNUSED 0   /* This link is unused, do not make this netlink */
568 #define LINK_QUALITY_DOWN 1   /* No chance of a packet being delivered right away*/
569 #define LINK_QUALITY_DOWN_STALE_ADDRESS 2 /* Link down, old address information */
570 #define LINK_QUALITY_DOWN_CURRENT_ADDRESS 3 /* Link down, current address information */
571 #define LINK_QUALITY_UP 4     /* Link active */
572 #define MAXIMUM_LINK_QUALITY 3
573 typedef void netlink_link_quality_fn(void *st, uint32_t quality);
574 typedef void netlink_register_fn(void *st, netlink_deliver_fn *deliver,
575                                  void *dst, uint32_t *localmtu_r /* NULL ok */);
576 typedef void netlink_output_config_fn(void *st, struct buffer_if *buf);
577 typedef bool_t netlink_check_config_fn(void *st, struct buffer_if *buf);
578 typedef void netlink_set_mtu_fn(void *st, int32_t new_mtu);
579 struct netlink_if {
580     void *st;
581     netlink_register_fn *reg;
582     netlink_deliver_fn *deliver;
583     netlink_link_quality_fn *set_quality;
584     netlink_set_mtu_fn *set_mtu;
585 };
586
587 /* DH interface */
588
589 /* Returns public key as a malloced hex string */
590 typedef string_t dh_makepublic_fn(void *st, uint8_t *secret,
591                                   int32_t secretlen);
592 /* Fills buffer (up to buflen) with shared secret */
593 typedef void dh_makeshared_fn(void *st, uint8_t *secret,
594                               int32_t secretlen, cstring_t rempublic,
595                               uint8_t *sharedsecret, int32_t buflen);
596 struct dh_if {
597     void *st;
598     int32_t len; /* Approximate size of modulus in bytes */
599     int32_t ceil_len; /* Number of bytes just sufficient to contain modulus */
600     dh_makepublic_fn *makepublic;
601     dh_makeshared_fn *makeshared;
602 };
603
604 /* HASH interface */
605
606 typedef void *hash_init_fn(void);
607 typedef void hash_update_fn(void *st, const void *buf, int32_t len);
608 typedef void hash_final_fn(void *st, uint8_t *digest);
609 struct hash_if {
610     int32_t len; /* Hash output length in bytes */
611     hash_init_fn *init;
612     hash_update_fn *update;
613     hash_final_fn *final;
614 };
615
616 /* BUFFER interface */
617
618 struct buffer_if {
619     bool_t free;
620     cstring_t owner; /* Set to constant string */
621     uint32_t flags; /* How paranoid should we be? */
622     struct cloc loc; /* Where we were defined */
623     uint8_t *base;
624     uint8_t *start;
625     int32_t size; /* Size of buffer contents */
626     int32_t alloclen; /* Total length allocated at base */
627 };
628
629 /***** LOG functions *****/
630
631 #define M_DEBUG_CONFIG 0x001
632 #define M_DEBUG_PHASE  0x002
633 #define M_DEBUG        0x004
634 #define M_INFO         0x008
635 #define M_NOTICE       0x010
636 #define M_WARNING      0x020
637 #define M_ERR          0x040
638 #define M_SECURITY     0x080
639 #define M_FATAL        0x100
640
641 /* The fatal() family of functions require messages that do not end in '\n' */
642 extern NORETURN(fatal(const char *message, ...)) FORMAT(printf,1,2);
643 extern NORETURN(fatal_perror(const char *message, ...)) FORMAT(printf,1,2);
644 extern NORETURN(fatal_status(int status, const char *message, ...))
645        FORMAT(printf,2,3);
646 extern NORETURN(fatal_perror_status(int status, const char *message, ...))
647        FORMAT(printf,2,3);
648
649 /* Convenient nonfatal logging.  Requires message that does not end in '\n'.
650  * If class contains M_FATAL, exits (after entering PHASE_SHUTDOWN).
651  * lg, errnoval and loc may sensibly be 0.  desc must NOT be 0.
652  * lg_[v]perror save and restore errno. */
653 void lg_vperror(struct log_if *lg, const char *desc, struct cloc *loc,
654                 int class, int errnoval, const char *fmt, va_list al)
655     FORMAT(printf,6,0);
656 void lg_perror(struct log_if *lg, const char *desc, struct cloc *loc,
657                int class, int errnoval, const char *fmt, ...)
658     FORMAT(printf,6,7);
659 void lg_exitstatus(struct log_if *lg, const char *desc, struct cloc *loc,
660                    int class, int status, const char *progname);
661
662 /* The cfgfatal() family of functions require messages that end in '\n' */
663 extern NORETURN(cfgfatal(struct cloc loc, cstring_t facility,
664                          const char *message, ...)) FORMAT(printf,3,4);
665 extern void cfgfile_postreadcheck(struct cloc loc, FILE *f);
666 extern NORETURN(vcfgfatal_maybefile(FILE *maybe_f, struct cloc loc,
667                                     cstring_t facility, const char *message,
668                                     va_list))
669     FORMAT(printf,4,0);
670 extern NORETURN(cfgfatal_maybefile(FILE *maybe_f, struct cloc loc,
671                                    cstring_t facility,
672                                    const char *message, ...))
673     FORMAT(printf,4,5);
674
675 extern void Message(uint32_t class, const char *message, ...)
676     FORMAT(printf,2,3);
677 extern void log_from_fd(int fd, cstring_t prefix, struct log_if *log);
678
679 /***** END of log functions *****/
680
681 #define STRING2(x) #x
682 #define STRING(x) STRING2(x)
683
684 #define FILLZERO(obj) (memset(&(obj),0,sizeof((obj))))
685 #define ARRAY_SIZE(ary) (sizeof((ary))/sizeof((ary)[0]))
686
687 /*
688  * void COPY_OBJ(  OBJECT& dst, const OBJECT& src);
689  * void COPY_ARRAY(OBJECT *dst, const OBJECT *src, INTEGER count);
690  *   // Typesafe: we check that the type OBJECT is the same in both cases.
691  *   // It is OK to use COPY_OBJ on an array object, provided it's
692  *   // _actually_ the whole array object and not decayed into a
693  *   // pointer (e.g. a formal parameter).
694  */
695 #define COPY_OBJ(dst,src) \
696     (&(dst)==&(src), memcpy(&(dst),&(src),sizeof((dst))))
697 #define COPY_ARRAY(dst,src,count) \
698     (&(dst)[0]==&(src)[0], memcpy((dst),(src),sizeof((dst)[0])*(count)))
699
700 #endif /* secnet_h */