Import release 0.1.4
[secnet] / util.c
CommitLineData
2fe58dfd
SE
1/* $Log: util.c,v $
2 * Revision 1.2 1996/04/14 16:34:36 sde1000
3 * Added syslog support
4 * mpbin/mpstring functions moved from dh.c
5 *
6 * Revision 1.1 1996/03/14 17:05:03 sde1000
7 * Initial revision
8 *
9 */
10
8689b3a9 11#include "secnet.h"
2fe58dfd 12#include <stdio.h>
2fe58dfd
SE
13#include <string.h>
14#include <errno.h>
2fe58dfd 15#include <unistd.h>
59635212 16#include <limits.h>
2fe58dfd 17#include <assert.h>
4efd681a 18#include <sys/wait.h>
2fe58dfd 19#include "util.h"
59635212 20#include "unaligned.h"
2fe58dfd
SE
21
22#define MIN_BUFFER_SIZE 64
23#define DEFAULT_BUFFER_SIZE 4096
24#define MAX_BUFFER_SIZE 131072
25
26static char *hexdigits="0123456789abcdef";
27
28uint32_t message_level=M_WARNING|M_ERROR|M_FATAL;
29uint32_t syslog_level=M_WARNING|M_ERROR|M_FATAL;
30static uint32_t current_phase=0;
31
32struct phase_hook {
33 hook_fn *fn;
34 void *state;
35 struct phase_hook *next;
36};
37
38static struct phase_hook *hooks[NR_PHASES]={NULL,};
39
40static void vMessage(uint32_t class, char *message, va_list args)
41{
42 FILE *dest=stdout;
43 if (class & message_level) {
44 if (class&M_FATAL || class&M_ERROR || class&M_WARNING) {
45 dest=stderr;
46 }
47 vfprintf(dest,message,args);
48 }
49/* XXX do something about syslog output here */
50#if 0
51 /* Maybe send message to syslog */
52 vsprintf(buff, message, args);
53 /* XXX Send each line as a separate log entry */
54 log(syslog_prio[level], buff);
55#endif /* 0 */
56}
57
58void Message(uint32_t class, char *message, ...)
59{
60 va_list ap;
61
62 va_start(ap,message);
63
64 vMessage(class,message,ap);
65
66 va_end(ap);
67}
68
69static void vfatal(int status, bool_t perror, char *message, va_list args)
70{
71 int err;
72
73 err=errno;
74
75 enter_phase(PHASE_SHUTDOWN);
76 if (perror) {
77 Message(M_FATAL, "secnet fatal error: ");
78 vMessage(M_FATAL, message, args);
79 Message(M_FATAL, ": %s\n",strerror(err));
80 }
81 else {
82 Message(M_FATAL, "secnet fatal error: ");
83 vMessage(M_FATAL,message,args);
84 }
85 exit(status);
86}
87
88void fatal(char *message, ...)
89{
90 va_list args;
91 va_start(args,message);
92 vfatal(current_phase,False,message,args);
93 va_end(args);
94}
95
96void fatal_status(int status, char *message, ...)
97{
98 va_list args;
99 va_start(args,message);
100 vfatal(status,False,message,args);
101 va_end(args);
102}
103
104void fatal_perror(char *message, ...)
105{
106 va_list args;
107 va_start(args,message);
108 vfatal(current_phase,True,message,args);
109 va_end(args);
110}
111
112void fatal_perror_status(int status, char *message, ...)
113{
114 va_list args;
115 va_start(args,message);
116 vfatal(status,True,message,args);
117 va_end(args);
118}
119
120void cfgfatal(struct cloc loc, string_t facility, char *message, ...)
121{
122 va_list args;
123
124 va_start(args,message);
125
126 enter_phase(PHASE_SHUTDOWN);
127
128 if (loc.file && loc.line) {
129 Message(M_FATAL, "config error (%s, %s:%d): ",facility,loc.file,
130 loc.line);
131 } else if (!loc.file && loc.line) {
132 Message(M_FATAL, "config error (%s, line %d): ",facility,loc.line);
133 } else {
134 Message(M_FATAL, "config error (%s): ",facility);
135 }
136
137 vMessage(M_FATAL,message,args);
138 va_end(args);
139 exit(current_phase);
140}
141
142char *safe_strdup(char *s, char *message)
143{
144 char *d;
145 d=strdup(s);
146 if (!d) {
147 fatal_perror(message);
148 }
149 return d;
150}
151
152void *safe_malloc(size_t size, char *message)
153{
154 void *r;
155 r=malloc(size);
156 if (!r) {
157 fatal_perror(message);
158 }
159 return r;
160}
161
162/* Convert a buffer into its MP_INT representation */
163void read_mpbin(MP_INT *a, uint8_t *bin, int binsize)
164{
165 char *buff;
166 int i;
167
168 buff=safe_malloc(binsize*2 + 1,"read_mpbin");
169
170 for (i=0; i<binsize; i++) {
171 buff[i*2]=hexdigits[(bin[i] & 0xf0) >> 4];
172 buff[i*2+1]=hexdigits[(bin[i] & 0xf)];
173 }
174 buff[binsize*2]=0;
175
176 mpz_set_str(a, buff, 16);
177 free(buff);
178}
179
180/* Convert a MP_INT into a hex string */
181char *write_mpstring(MP_INT *a)
182{
183 char *buff;
184
185 buff=safe_malloc(mpz_sizeinbase(a,16)+2,"write_mpstring");
186 mpz_get_str(buff, 16, a);
187 return buff;
188}
189
190static uint8_t hexval(uint8_t c)
191{
192 switch (c) {
193 case '0': return 0;
194 case '1': return 1;
195 case '2': return 2;
196 case '3': return 3;
197 case '4': return 4;
198 case '5': return 5;
199 case '6': return 6;
200 case '7': return 7;
201 case '8': return 8;
202 case '9': return 9;
203 case 'a': return 10;
204 case 'A': return 10;
205 case 'b': return 11;
206 case 'B': return 11;
207 case 'c': return 12;
208 case 'C': return 12;
209 case 'd': return 13;
210 case 'D': return 13;
211 case 'e': return 14;
212 case 'E': return 14;
213 case 'f': return 15;
214 case 'F': return 15;
215 }
216 return -1;
217}
218
219/* Convert a MP_INT into a buffer; return length; truncate if necessary */
220uint32_t write_mpbin(MP_INT *a, uint8_t *buffer, uint32_t buflen)
221{
222 char *hb;
223 int i,j,l;
224
225 if (buflen==0) return 0;
226 hb=write_mpstring(a);
227
228 l=strlen(hb);
229 i=0; j=0;
230 if (l&1) {
231 /* The number starts with a half-byte */
232 buffer[i++]=hexval(hb[j++]);
233 }
234 for (; hb[j] && i<buflen; i++) {
235 buffer[i]=(hexval(hb[j])<<4)|hexval(hb[j+1]);
236 j+=2;
237 }
238 free(hb);
239 return i;
240}
241
70dc107b
SE
242bool_t subnet_match(struct subnet *s, uint32_t address)
243{
244 return (s->prefix==(address&s->mask));
245}
246
247bool_t subnet_matches_list(struct subnet_list *list, uint32_t address)
2fe58dfd
SE
248{
249 uint32_t i;
250 for (i=0; i<list->entries; i++) {
251 if (list->list[i].prefix == (address&list->list[i].mask)) return True;
252 }
253 return False;
254}
255
baa06aeb
SE
256bool_t subnets_intersect(struct subnet a, struct subnet b)
257{
258 uint32_t mask=a.mask&b.mask;
259 return ((a.prefix&mask)==(b.prefix&mask));
260}
261
262bool_t subnet_intersects_with_list(struct subnet a, struct subnet_list *b)
263{
264 uint32_t i;
265
266 for (i=0; i<b->entries; i++) {
267 if (subnets_intersect(a,b->list[i])) return True;
268 }
269 return False;
270}
271
272bool_t subnet_lists_intersect(struct subnet_list *a, struct subnet_list *b)
273{
274 uint32_t i;
275 for (i=0; i<a->entries; i++) {
276 if (subnet_intersects_with_list(a->list[i],b)) return True;
277 }
278 return False;
279}
280
2fe58dfd
SE
281/* The string buffer must be at least 16 bytes long */
282string_t ipaddr_to_string(uint32_t addr)
283{
284 uint8_t a,b,c,d;
285 string_t s;
286
287 s=safe_malloc(16,"ipaddr_to_string");
288 a=addr>>24;
289 b=addr>>16;
290 c=addr>>8;
291 d=addr;
292 snprintf(s, 16, "%d.%d.%d.%d", a, b, c, d);
293 return s;
294}
295
296string_t subnet_to_string(struct subnet *sn)
297{
298 uint32_t mask=sn->mask, addr=sn->prefix;
299 uint8_t a,b,c,d;
300 string_t s;
301 int i;
302
303 s=safe_malloc(19,"subnet_to_string");
304 a=addr>>24;
305 b=addr>>16;
306 c=addr>>8;
307 d=addr;
308 for (i=0; mask; i++) {
309 mask=(mask<<1);
310 }
70dc107b
SE
311 if (i!=sn->len) {
312 fatal("subnet_to_string: invalid subnet structure!\n");
313 }
314 snprintf(s, 19, "%d.%d.%d.%d/%d", a, b, c, d, sn->len);
2fe58dfd
SE
315 return s;
316}
317
4efd681a
SE
318int sys_cmd(const char *path, char *arg, ...)
319{
320 va_list ap;
321 int rv;
322 pid_t c;
323
324 va_start(ap,arg);
325 c=fork();
326 if (c) {
327 /* Parent -> wait for child */
328 waitpid(c,&rv,0);
329 } else if (c==0) {
330 char *args[100];
331 int i;
332 /* Child -> exec command */
333 args[0]=arg;
334 i=1;
335 while ((args[i++]=va_arg(ap,char *)));
336 execvp(path,args);
337 exit(1);
338 } else {
339 /* Error */
340 fatal_perror("sys_cmd(%s,%s,...)");
341 }
342
343 va_end(ap);
344 return rv;
345}
346
2fe58dfd
SE
347/* Take a list of log closures and merge them */
348struct loglist {
349 struct log_if *l;
350 struct loglist *next;
351};
352
353static void log_vmulti(void *state, int priority, char *message, va_list args)
354{
355 struct loglist *st=state, *i;
356
357 for (i=st; i; i=i->next) {
358 i->l->vlog(i->l->st,priority,message,args);
359 }
360}
361
362static void log_multi(void *st, int priority, char *message, ...)
363{
364 va_list ap;
365
366 va_start(ap,message);
367
368 log_vmulti(st,priority,message,ap);
369
370 va_end(ap);
371}
372
373struct log_if *init_log(list_t *ll)
374{
375 int i=0;
376 item_t *item;
377 closure_t *cl;
378 struct loglist *l=NULL, *n;
379 struct log_if *r;
380
381 while ((item=list_elem(ll,i++))) {
382 if (item->type!=t_closure) {
383 cfgfatal(item->loc,"init_log","item is not a closure");
384 }
385 cl=item->data.closure;
386 if (cl->type!=CL_LOG) {
387 cfgfatal(item->loc,"init_log","closure is not a logger");
388 }
389 n=safe_malloc(sizeof(*n),"init_log");
390 n->l=cl->interface;
391 n->next=l;
392 l=n;
393 }
394 if (!l) {
395 fatal("init_log: none of the items in the list are loggers");
396 }
397 r=safe_malloc(sizeof(*r), "init_log");
398 r->st=l;
399 r->log=log_multi;
400 r->vlog=log_vmulti;
401 return r;
402}
403
404struct logfile {
405 closure_t cl;
406 struct log_if ops;
407 FILE *f;
408};
409
410static void logfile_vlog(void *state, int priority, char *message,
411 va_list args)
412{
413 struct logfile *st=state;
414
415 vfprintf(st->f,message,args);
416 fprintf(st->f,"\n");
417}
418
419static void logfile_log(void *state, int priority, char *message, ...)
420{
421 va_list ap;
422
423 va_start(ap,message);
424 logfile_vlog(state,priority,message,ap);
425 va_end(ap);
426}
427
428static list_t *logfile_apply(closure_t *self, struct cloc loc, dict_t *context,
429 list_t *data)
430{
431 struct logfile *st;
432
433 st=safe_malloc(sizeof(*st),"logfile_apply");
434 st->cl.description="logfile";
435 st->cl.type=CL_LOG;
436 st->cl.apply=NULL;
437 st->cl.interface=&st->ops;
438 st->ops.st=st;
439 st->ops.log=logfile_log;
440 st->ops.vlog=logfile_vlog;
441 st->f=stderr; /* XXX ignore args */
442
443 return new_closure(&st->cl);
444}
445
446static char *phases[NR_PHASES]={
447 "PHASE_INIT",
448 "PHASE_GETOPTS",
449 "PHASE_READCONFIG",
450 "PHASE_SETUP",
baa06aeb 451 "PHASE_GETRESOURCES",
2fe58dfd
SE
452 "PHASE_DROPPRIV",
453 "PHASE_RUN",
454 "PHASE_SHUTDOWN"
455};
456
457void enter_phase(uint32_t new_phase)
458{
459 struct phase_hook *i;
460
baa06aeb
SE
461 if (hooks[new_phase])
462 Message(M_DEBUG_PHASE,"Running hooks for %s...\n", phases[new_phase]);
2fe58dfd
SE
463 current_phase=new_phase;
464
465 for (i=hooks[new_phase]; i; i=i->next)
466 i->fn(i->state, new_phase);
baa06aeb 467 Message(M_DEBUG_PHASE,"Now in %s\n",phases[new_phase]);
2fe58dfd
SE
468}
469
470bool_t add_hook(uint32_t phase, hook_fn *fn, void *state)
471{
472 struct phase_hook *h;
473
474 h=safe_malloc(sizeof(*h),"add_hook");
475 h->fn=fn;
476 h->state=state;
477 h->next=hooks[phase];
478 hooks[phase]=h;
479 return True;
480}
481
482bool_t remove_hook(uint32_t phase, hook_fn *fn, void *state)
483{
484 fatal("remove_hook: not implemented\n");
485
486 return False;
487}
488
489void log(struct log_if *lf, int priority, char *message, ...)
490{
491 va_list ap;
492
493 va_start(ap,message);
494 lf->vlog(lf->st,priority,message,ap);
495 va_end(ap);
496}
497
498struct buffer {
499 closure_t cl;
500 struct buffer_if ops;
501};
502
503void buffer_assert_free(struct buffer_if *buffer, string_t file, uint32_t line)
504{
505 if (!buffer->free) {
506 fatal("BUF_ASSERT_FREE, %s line %d, owned by %s\n",
507 file,line,buffer->owner);
508 }
509}
510
511void buffer_assert_used(struct buffer_if *buffer, string_t file, uint32_t line)
512{
513 if (buffer->free) {
514 fatal("BUF_ASSERT_USED, %s line %d, last owned by %s\n",
515 file,line,buffer->owner);
516 }
517}
518
519void buffer_init(struct buffer_if *buffer, uint32_t max_start_pad)
520{
521 buffer->start=buffer->base+max_start_pad;
522 buffer->size=0;
523}
524
525void *buf_append(struct buffer_if *buf, uint32_t amount) {
526 void *p;
527 p=buf->start + buf->size;
528 buf->size+=amount;
529 return p;
530}
531
532void *buf_prepend(struct buffer_if *buf, uint32_t amount) {
533 buf->size+=amount;
534 return buf->start-=amount;
535}
536
537void *buf_unappend(struct buffer_if *buf, uint32_t amount) {
538 if (buf->size < amount) return 0;
539 return buf->start+(buf->size-=amount);
540}
541
542void *buf_unprepend(struct buffer_if *buf, uint32_t amount) {
543 void *p;
544 p=buf->start;
545 buf->start+=amount;
546 buf->size-=amount;
547 return p;
548}
549
550/* Append a two-byte length and the string to the buffer. Length is in
551 network byte order. */
552void buf_append_string(struct buffer_if *buf, string_t s)
553{
554 uint16_t len;
555
556 len=strlen(s);
59635212 557 buf_append_uint16(buf,len);
2fe58dfd
SE
558 memcpy(buf_append(buf,len),s,len);
559}
560
561void buffer_new(struct buffer_if *buf, uint32_t len)
562{
563 buf->free=True;
564 buf->owner=NULL;
565 buf->flags=0;
566 buf->loc.file=NULL;
567 buf->loc.line=0;
568 buf->size=0;
569 buf->len=len;
570 buf->start=NULL;
571 buf->base=safe_malloc(len,"buffer_new");
572}
573
574static list_t *buffer_apply(closure_t *self, struct cloc loc, dict_t *context,
575 list_t *args)
576{
577 struct buffer *st;
578 item_t *item;
579 dict_t *dict;
580 bool_t lockdown=False;
4efd681a 581 uint32_t len=DEFAULT_BUFFER_SIZE;
2fe58dfd
SE
582
583 st=safe_malloc(sizeof(*st),"buffer_apply");
584 st->cl.description="buffer";
585 st->cl.type=CL_BUFFER;
586 st->cl.apply=NULL;
587 st->cl.interface=&st->ops;
2fe58dfd
SE
588
589 /* First argument, if present, is buffer length */
590 item=list_elem(args,0);
591 if (item) {
592 if (item->type!=t_number) {
593 cfgfatal(st->ops.loc,"buffer","first parameter must be a "
594 "number (buffer size)\n");
595 }
4efd681a
SE
596 len=item->data.number;
597 if (len<MIN_BUFFER_SIZE) {
2fe58dfd
SE
598 cfgfatal(st->ops.loc,"buffer","ludicrously small buffer size\n");
599 }
4efd681a 600 if (len>MAX_BUFFER_SIZE) {
2fe58dfd
SE
601 cfgfatal(st->ops.loc,"buffer","ludicrously large buffer size\n");
602 }
603 }
604 /* Second argument, if present, is a dictionary */
605 item=list_elem(args,1);
606 if (item) {
607 if (item->type!=t_dict) {
608 cfgfatal(st->ops.loc,"buffer","second parameter must be a "
609 "dictionary\n");
610 }
611 dict=item->data.dict;
612 lockdown=dict_read_bool(dict,"lockdown",False,"buffer",st->ops.loc,
613 False);
614 }
615
4efd681a 616 buffer_new(&st->ops,len);
2fe58dfd 617 if (lockdown) {
70dc107b 618 /* XXX mlock the buffer if possible */
2fe58dfd
SE
619 }
620
621 return new_closure(&st->cl);
622}
623
624init_module util_module;
625void util_module(dict_t *dict)
626{
627 add_closure(dict,"logfile",logfile_apply);
628 add_closure(dict,"sysbuffer",buffer_apply);
629}