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