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