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