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