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