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