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