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