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