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