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