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