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