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