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