chiark / gitweb /
style: util.[ch]: Move doc comments into header file
[secnet.git] / util.c
1 /*
2  * util.c
3  * - output and logging support
4  * - program lifetime support
5  * - IP address and subnet munging routines
6  * - MPI convenience functions
7  */
8 /*
9  * This file is part of secnet.
10  * See README for full list of copyright holders.
11  *
12  * secnet is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 3 of the License, or
15  * (at your option) any later version.
16  * 
17  * secnet is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  * 
22  * You should have received a copy of the GNU General Public License
23  * version 3 along with secnet; if not, see
24  * https://www.gnu.org/licenses/gpl.html.
25  */
26
27 #include "secnet.h"
28 #include <stdio.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <limits.h>
33 #include <assert.h>
34 #include <sys/wait.h>
35 #include <adns.h>
36 #include "util.h"
37 #include "unaligned.h"
38 #include "magic.h"
39 #include "ipaddr.h"
40
41 #define MIN_BUFFER_SIZE 64
42 #define DEFAULT_BUFFER_SIZE 4096
43 #define MAX_BUFFER_SIZE 131072
44
45 static const char *hexdigits="0123456789abcdef";
46
47 uint32_t current_phase=0;
48
49 struct phase_hook {
50     hook_fn *fn;
51     void *state;
52     LIST_ENTRY(phase_hook) entry;
53 };
54
55 static LIST_HEAD(, phase_hook) hooks[NR_PHASES];
56
57 char *safe_strdup(const char *s, const char *message)
58 {
59     char *d;
60     d=strdup(s);
61     if (!d) {
62         fatal_perror("%s",message);
63     }
64     return d;
65 }
66
67 void *safe_malloc(size_t size, const char *message)
68 {
69     void *r;
70     if (!size)
71         return 0;
72     r=malloc(size);
73     if (!r) {
74         fatal_perror("%s",message);
75     }
76     return r;
77 }
78 void *safe_realloc_ary(void *p, size_t size, size_t count,
79                        const char *message) {
80     if (count >= INT_MAX/size) {
81         fatal("array allocation overflow: %s", message);
82     }
83     assert(size && count);
84     p = realloc(p, size*count);
85     if (!p)
86         fatal_perror("%s", message);
87     return p;
88 }
89
90 void *safe_malloc_ary(size_t size, size_t count, const char *message) {
91     if (!size || !count)
92         return 0;
93     return safe_realloc_ary(0,size,count,message);
94 }
95
96 string_t hex_encode(const uint8_t *bin, int binsize)
97 {
98     char *buff;
99     int i;
100
101     buff=safe_malloc(binsize*2 + 1,"hex_encode");
102
103     for (i=0; i<binsize; i++) {
104         buff[i*2]=hexdigits[(bin[i] & 0xf0) >> 4];
105         buff[i*2+1]=hexdigits[(bin[i] & 0xf)];
106     }
107     buff[binsize*2]=0;
108     return buff;
109 }
110
111 static uint8_t hexval(uint8_t c)
112 {
113     switch (c) {
114     case '0': return 0;
115     case '1': return 1;
116     case '2': return 2;
117     case '3': return 3;
118     case '4': return 4;
119     case '5': return 5;
120     case '6': return 6;
121     case '7': return 7;
122     case '8': return 8;
123     case '9': return 9;
124     case 'a': return 10;
125     case 'A': return 10;
126     case 'b': return 11;
127     case 'B': return 11;
128     case 'c': return 12;
129     case 'C': return 12;
130     case 'd': return 13;
131     case 'D': return 13;
132     case 'e': return 14;
133     case 'E': return 14;
134     case 'f': return 15;
135     case 'F': return 15;
136     }
137     return -1;
138 }
139
140 bool_t hex_decode(uint8_t *buffer, int32_t buflen, int32_t *outlen,
141                   cstring_t hb, bool_t allow_odd_nibble)
142 {
143     int i = 0, j = 0, l = strlen(hb), hi, lo;
144     bool_t ok = False;
145
146     if (!l || !buflen) { ok = !l; goto done; }
147     if (l&1) {
148         /* The number starts with a half-byte */
149         if (!allow_odd_nibble) goto done;
150         lo = hexval(hb[j++]); if (lo < 0) goto done;
151         buffer[i++] = lo;
152     }
153     for (; hb[j] && i < buflen; i++) {
154         hi = hexval(hb[j++]);
155         lo = hexval(hb[j++]);
156         if (hi < 0 || lo < 0) goto done;
157         buffer[i] = (hi << 4) | lo;
158     }
159     ok = !hb[j];
160 done:
161     *outlen = i;
162     return ok;
163 }
164
165 void read_mpbin(MP_INT *a, uint8_t *bin, int binsize)
166 {
167     char *buff = hex_encode(bin, binsize);
168     mpz_set_str(a, buff, 16);
169     free(buff);
170 }
171
172 char *write_mpstring(MP_INT *a)
173 {
174     char *buff;
175
176     buff=safe_malloc(mpz_sizeinbase(a,16)+2,"write_mpstring");
177     mpz_get_str(buff, 16, a);
178     return buff;
179 }
180
181 int32_t write_mpbin(MP_INT *a, uint8_t *buffer, int32_t buflen)
182 {
183     char *hb = write_mpstring(a);
184     int32_t len;
185     hex_decode(buffer, buflen, &len, hb, True);
186     free(hb);
187     return len;
188 }
189
190 #define DEFINE_SETFDFLAG(fn,FL,FLAG)                                    \
191 void fn(int fd) {                                                       \
192     int r=fcntl(fd, F_GET##FL);                                         \
193     if (r<0) fatal_perror("fcntl(,F_GET" #FL ") failed");               \
194     r=fcntl(fd, F_SET##FL, r|FLAG);                                     \
195     if (r<0) fatal_perror("fcntl(,F_SET" #FL ",|" #FLAG ") failed");    \
196 }
197
198 DEFINE_SETFDFLAG(setcloexec,FD,FD_CLOEXEC);
199 DEFINE_SETFDFLAG(setnonblock,FL,O_NONBLOCK);
200
201 void pipe_cloexec(int fd[2]) {
202     int r=pipe(fd);
203     if (r) fatal_perror("pipe");
204     setcloexec(fd[0]);
205     setcloexec(fd[1]);
206 }
207
208 static const char *phases[NR_PHASES]={
209     "PHASE_INIT",
210     "PHASE_GETOPTS",
211     "PHASE_READCONFIG",
212     "PHASE_SETUP",
213     "PHASE_DAEMONIZE",
214     "PHASE_GETRESOURCES",
215     "PHASE_DROPPRIV",
216     "PHASE_RUN",
217     "PHASE_SHUTDOWN",
218     "PHASE_CHILDPERSIST"
219 };
220
221 void enter_phase(uint32_t new_phase)
222 {
223     struct phase_hook *i;
224
225     if (!LIST_EMPTY(&hooks[new_phase]))
226         Message(M_DEBUG_PHASE,"Running hooks for %s...\n", phases[new_phase]);
227     current_phase=new_phase;
228
229     LIST_FOREACH(i, &hooks[new_phase], entry)
230         i->fn(i->state, new_phase);
231     Message(M_DEBUG_PHASE,"Now in %s\n",phases[new_phase]);
232 }
233
234 void phase_hooks_init(void)
235 {
236     int i;
237     for (i=0; i<NR_PHASES; i++)
238         LIST_INIT(&hooks[i]);
239 }
240
241 void clear_phase_hooks(uint32_t phase)
242 {
243     struct phase_hook *h, *htmp;
244     LIST_FOREACH_SAFE(h, &hooks[phase], entry, htmp)
245         free(h);
246     LIST_INIT(&hooks[phase]);
247 }
248
249 bool_t add_hook(uint32_t phase, hook_fn *fn, void *state)
250 {
251     struct phase_hook *h;
252
253     NEW(h);
254     h->fn=fn;
255     h->state=state;
256     LIST_INSERT_HEAD(&hooks[phase],h,entry);
257     return True;
258 }
259
260 bool_t remove_hook(uint32_t phase, hook_fn *fn, void *state)
261 {
262     fatal("remove_hook: not implemented");
263
264     return False;
265 }
266
267 void vslilog(struct log_if *lf, int priority, const char *message, va_list ap)
268 {
269     lf->vlogfn(lf->st,priority,message,ap);
270 }
271
272 void slilog(struct log_if *lf, int priority, const char *message, ...)
273 {
274     va_list ap;
275     
276     va_start(ap,message);
277     vslilog(lf,priority,message,ap);
278     va_end(ap);
279 }
280
281 struct buffer {
282     closure_t cl;
283     struct buffer_if ops;
284 };
285
286 void buffer_assert_free(struct buffer_if *buffer, cstring_t file,
287                         int line)
288 {
289     if (!buffer->free) {
290         fprintf(stderr,"secnet: BUF_ASSERT_FREE, %s line %d, owned by %s",
291                 file,line,buffer->owner);
292         assert(!"buffer_assert_free failure");
293     }
294 }
295
296 void buffer_assert_used(struct buffer_if *buffer, cstring_t file,
297                         int line)
298 {
299     if (buffer->free) {
300         fprintf(stderr,"secnet: BUF_ASSERT_USED, %s line %d, last owned by %s",
301                 file,line,buffer->owner);
302         assert(!"buffer_assert_used failure");
303     }
304 }
305
306 void buffer_init(struct buffer_if *buffer, int32_t max_start_pad)
307 {
308     assert(max_start_pad<=buffer->alloclen);
309     buffer->start=buffer->base+max_start_pad;
310     buffer->size=0;
311 }
312
313 void buffer_destroy(struct buffer_if *buf)
314 {
315     BUF_ASSERT_FREE(buf);
316     free(buf->base);
317     buf->start=buf->base=0;
318     buf->size=buf->alloclen=0;
319 }
320
321 void *buf_append(struct buffer_if *buf, int32_t amount) {
322     void *p;
323     assert(amount <= buf_remaining_space(buf));
324     p=buf->start + buf->size;
325     buf->size+=amount;
326     return p;
327 }
328
329 void *buf_prepend(struct buffer_if *buf, int32_t amount) {
330     assert(amount <= buf->start - buf->base);
331     buf->size+=amount;
332     return buf->start-=amount;
333 }
334
335 void *buf_unappend(struct buffer_if *buf, int32_t amount) {
336     if (buf->size < amount) return 0;
337     return buf->start+(buf->size-=amount);
338 }
339
340 void *buf_unprepend(struct buffer_if *buf, int32_t amount) {
341     void *p;
342     if (buf->size < amount) return 0;
343     p=buf->start;
344     buf->start+=amount;
345     buf->size-=amount;
346     return p;
347 }
348
349 void buf_append_string(struct buffer_if *buf, cstring_t s)
350 {
351     size_t len;
352
353     len=strlen(s);
354     /* fixme: if string is longer than 65535, result is a corrupted packet */
355     buf_append_uint16(buf,len);
356     BUF_ADD_BYTES(append,buf,s,len);
357 }
358
359 void buffer_new(struct buffer_if *buf, int32_t len)
360 {
361     buf->free=True;
362     buf->owner=NULL;
363     buf->flags=0;
364     buf->loc.file=NULL;
365     buf->loc.line=0;
366     buf->size=0;
367     buf->alloclen=len;
368     buf->start=NULL;
369     buf->base=safe_malloc(len,"buffer_new");
370 }
371
372 void buffer_readonly_view(struct buffer_if *buf, const void *data, int32_t len)
373 {
374     buf->free=False;
375     buf->owner="READONLY";
376     buf->flags=0;
377     buf->loc.file=NULL;
378     buf->loc.line=0;
379     buf->size=buf->alloclen=len;
380     buf->base=buf->start=(uint8_t*)data;
381 }
382
383 void buffer_readonly_clone(struct buffer_if *out, const struct buffer_if *in)
384 {
385     buffer_readonly_view(out,in->start,in->size);
386 }
387
388 void buffer_copy(struct buffer_if *dst, const struct buffer_if *src)
389 {
390     if (dst->alloclen < src->alloclen) {
391         dst->base=realloc(dst->base,src->alloclen);
392         if (!dst->base) fatal_perror("buffer_copy");
393         dst->alloclen = src->alloclen;
394     }
395     dst->start = dst->base + (src->start - src->base);
396     dst->size = src->size;
397     memcpy(dst->start, src->start, dst->size);
398 }
399
400 static list_t *buffer_apply(closure_t *self, struct cloc loc, dict_t *context,
401                             list_t *args)
402 {
403     struct buffer *st;
404     item_t *item;
405     dict_t *dict;
406     bool_t lockdown=False;
407     uint32_t len=DEFAULT_BUFFER_SIZE;
408     
409     NEW(st);
410     st->cl.description="buffer";
411     st->cl.type=CL_BUFFER;
412     st->cl.apply=NULL;
413     st->cl.interface=&st->ops;
414
415     /* First argument, if present, is buffer length */
416     item=list_elem(args,0);
417     if (item) {
418         if (item->type!=t_number) {
419             cfgfatal(st->ops.loc,"buffer","first parameter must be a "
420                      "number (buffer size)\n");
421         }
422         len=item->data.number;
423         if (len<MIN_BUFFER_SIZE) {
424             cfgfatal(st->ops.loc,"buffer","ludicrously small buffer size\n");
425         }
426         if (len>MAX_BUFFER_SIZE) {
427             cfgfatal(st->ops.loc,"buffer","ludicrously large buffer size\n");
428         }
429     }
430     /* Second argument, if present, is a dictionary */
431     item=list_elem(args,1);
432     if (item) {
433         if (item->type!=t_dict) {
434             cfgfatal(st->ops.loc,"buffer","second parameter must be a "
435                      "dictionary\n");
436         }
437         dict=item->data.dict;
438         lockdown=dict_read_bool(dict,"lockdown",False,"buffer",st->ops.loc,
439                                 False);
440     }
441
442     buffer_new(&st->ops,len);
443     if (lockdown) {
444         /* XXX mlock the buffer if possible */
445     }
446     
447     return new_closure(&st->cl);
448 }
449
450 void send_nak(const struct comm_addr *dest, uint32_t our_index,
451               uint32_t their_index, uint32_t msgtype,
452               struct buffer_if *buf, const char *logwhy)
453 {
454     buffer_init(buf,calculate_max_start_pad());
455     buf_append_uint32(buf,their_index);
456     buf_append_uint32(buf,our_index);
457     buf_append_uint32(buf,LABEL_NAK);
458     if (logwhy)
459         Message(M_INFO,"%s: %08"PRIx32"<-%08"PRIx32": %08"PRIx32":"
460                 " %s; sending NAK\n",
461                 comm_addr_to_string(dest),
462                 our_index, their_index, msgtype, logwhy);
463     dest->comm->sendmsg(dest->comm->st, buf, dest, 0);
464 }
465
466 int consttime_memeq(const void *s1in, const void *s2in, size_t n)
467 {
468     const uint8_t *s1=s1in, *s2=s2in;
469     register volatile uint8_t accumulator=0;
470
471     while (n-- > 0) {
472         accumulator |= (*s1++ ^ *s2++);
473     }
474     accumulator |= accumulator >> 4; /* constant-time             */
475     accumulator |= accumulator >> 2; /*  boolean canonicalisation */
476     accumulator |= accumulator >> 1;
477     accumulator &= 1;
478     accumulator ^= 1;
479     return accumulator;
480 }
481
482 void util_module(dict_t *dict)
483 {
484     add_closure(dict,"sysbuffer",buffer_apply);
485 }
486
487 void update_max_start_pad(int32_t *our_module_global, int32_t our_instance)
488 {
489     if (*our_module_global < our_instance)
490         *our_module_global=our_instance;
491 }
492
493 int32_t transform_max_start_pad, comm_max_start_pad;
494
495 int32_t calculate_max_start_pad(void)
496 {
497     return
498         site_max_start_pad +
499         transform_max_start_pad +
500         comm_max_start_pad;
501 }
502
503 void vslilog_part(struct log_if *lf, int priority, const char *message, va_list ap)
504 {
505     char *buff=lf->buff;
506     size_t bp;
507     char *nlp;
508
509     bp=strlen(buff);
510     assert(bp < LOG_MESSAGE_BUFLEN);
511     vsnprintf(buff+bp,LOG_MESSAGE_BUFLEN-bp,message,ap);
512     buff[LOG_MESSAGE_BUFLEN-1] = '\n';
513     buff[LOG_MESSAGE_BUFLEN] = '\0';
514     /* Each line is sent separately */
515     while ((nlp=strchr(buff,'\n'))) {
516         *nlp=0;
517         slilog(lf,priority,"%s",buff);
518         memmove(buff,nlp+1,strlen(nlp+1)+1);
519     }
520 }
521
522 extern void slilog_part(struct log_if *lf, int priority, const char *message, ...)
523 {
524     va_list ap;
525     va_start(ap,message);
526     vslilog_part(lf,priority,message,ap);
527     va_end(ap);
528 }
529
530 void string_item_to_iaddr(const item_t *item, uint16_t port, union iaddr *ia,
531                           const char *desc)
532 {
533 #ifndef CONFIG_IPV6
534
535     ia->sin.sin_family=AF_INET;
536     ia->sin.sin_addr.s_addr=htonl(string_item_to_ipaddr(item,desc));
537     ia->sin.sin_port=htons(port);
538
539 #else /* CONFIG_IPV6 => we have adns_text2addr */
540
541     if (item->type!=t_string)
542         cfgfatal(item->loc,desc,"expecting a string IP (v4 or v6) address\n");
543     socklen_t salen=sizeof(*ia);
544     int r=adns_text2addr(item->data.string, port,
545                          adns_qf_addrlit_ipv4_quadonly,
546                          &ia->sa, &salen);
547     assert(r!=ENOSPC);
548     if (r) cfgfatal(item->loc,desc,"invalid IP (v4 or v6) address: %s\n",
549                     strerror(r));
550
551 #endif /* CONFIG_IPV6 */
552 }
553
554 #define IADDR_NBUFS 8
555
556 const char *iaddr_to_string(const union iaddr *ia)
557 {
558 #ifndef CONFIG_IPV6
559
560     SBUF_DEFINE(IADDR_NBUFS, 100);
561
562     assert(ia->sa.sa_family == AF_INET);
563
564     snprintf(SBUF, sizeof(SBUF), "[%s]:%d",
565              inet_ntoa(ia->sin.sin_addr),
566              ntohs(ia->sin.sin_port));
567
568 #else /* CONFIG_IPV6 => we have adns_addr2text */
569
570     SBUF_DEFINE(IADDR_NBUFS, 1+ADNS_ADDR2TEXT_BUFLEN+20);
571
572     int port;
573
574     char *addrbuf = SBUF;
575     *addrbuf++ = '[';
576     int addrbuflen = ADNS_ADDR2TEXT_BUFLEN;
577
578     int r = adns_addr2text(&ia->sa, 0, addrbuf, &addrbuflen, &port);
579     if (r) {
580         const char fmt[]= "scoped IPv6 addr, error: %.*s";
581         sprintf(addrbuf, fmt,
582                 (int)(ADNS_ADDR2TEXT_BUFLEN - sizeof(fmt)) /* underestimate */,
583                 strerror(r));
584     }
585
586     char *portbuf = addrbuf;
587     int addrl = strlen(addrbuf);
588     portbuf += addrl;
589
590     snprintf(portbuf, sizeof(SBUF)-addrl, "]:%d", port);
591
592 #endif /* CONFIG_IPV6 */
593
594     return SBUF;
595 }
596
597 bool_t iaddr_equal(const union iaddr *ia, const union iaddr *ib,
598                    bool_t ignoreport)
599 {
600     if (ia->sa.sa_family != ib->sa.sa_family)
601         return 0;
602     switch (ia->sa.sa_family) {
603     case AF_INET:
604         return ia->sin.sin_addr.s_addr == ib->sin.sin_addr.s_addr
605            && (ignoreport ||
606                ia->sin.sin_port        == ib->sin.sin_port);
607 #ifdef CONFIG_IPV6
608     case AF_INET6:
609         return !memcmp(&ia->sin6.sin6_addr, &ib->sin6.sin6_addr, 16)
610            &&  ia->sin6.sin6_scope_id  == ib->sin6.sin6_scope_id
611            && (ignoreport ||
612                ia->sin6.sin6_port      == ib->sin6.sin6_port)
613             /* we ignore the flowinfo field */;
614 #endif /* CONFIG_IPV6 */
615     default:
616         abort();
617     }
618 }
619
620 int iaddr_socklen(const union iaddr *ia)
621 {
622     switch (ia->sa.sa_family) {
623     case AF_INET:  return sizeof(ia->sin);
624 #ifdef CONFIG_IPV6
625     case AF_INET6: return sizeof(ia->sin6);
626 #endif /* CONFIG_IPV6 */
627     default:       abort();
628     }
629 }
630
631 const char *pollbadbit(int revents)
632 {
633 #define BADBIT(b) \
634     if ((revents & b)) return #b
635     BADBIT(POLLERR);
636     BADBIT(POLLHUP);
637     /* POLLNVAL is handled by the event loop - see afterpoll_fn comment */
638 #undef BADBIT
639     return 0;
640 }
641
642 enum async_linebuf_result
643 async_linebuf_read(struct pollfd *pfd, struct buffer_if *buf,
644                    const char **emsg_out)
645 {
646     int revents=pfd->revents;
647
648 #define BAD(m) do{ *emsg_out=(m); return async_linebuf_broken; }while(0)
649
650     const char *badbit=pollbadbit(revents);
651     if (badbit) BAD(badbit);
652
653     if (!(revents & POLLIN))
654         return async_linebuf_nothing;
655
656     /*
657      * Data structure: A line which has been returned to the user is
658      * stored in buf at base before start.  But we retain the usual
659      * buffer meaning of size.  So:
660      *
661      *   | returned :    | input read,   |    unused    |
662      *   |  to user : \0 |  awaiting     |     buffer   |
663      *   |          :    |  processing   |      space   |
664      *   |          :    |               |              |
665      *   ^base           ^start          ^start+size    ^base+alloclen
666      */
667
668     BUF_ASSERT_USED(buf);
669
670     /* firstly, eat any previous */
671     if (buf->start != buf->base) {
672         memmove(buf->base,buf->start,buf->size);
673         buf->start=buf->base;
674     }
675
676     uint8_t *searched=buf->base;
677
678     /*
679      * During the workings here we do not use start.  We set start
680      * when we return some actual data.  So we have this:
681      *
682      *   | searched     | read, might   |  unused      |
683      *   |  for \n      |  contain \n   |   buffer     |
684      *   |  none found  |  but not \0   |    space     |
685      *   |              |               |              |
686      *   ^base          ^searched       ^base+size     ^base+alloclen
687      *  [^start]                        ^dataend
688      *
689      */
690     for (;;) {
691         uint8_t *dataend=buf->base+buf->size;
692         char *newline=memchr(searched,'\n',dataend-searched);
693         if (newline) {
694             *newline=0;
695             buf->start=newline+1;
696             buf->size=dataend-buf->start;
697             return async_linebuf_ok;
698         }
699         searched=dataend;
700         ssize_t space=(buf->base+buf->alloclen)-dataend;
701         if (!space) BAD("input line too long");
702         ssize_t r=read(pfd->fd,searched,space);
703         if (r==0) {
704             *searched=0;
705             *emsg_out=buf->size?"no newline at eof":0;
706             buf->start=searched+1;
707             buf->size=0;
708             return async_linebuf_eof;
709         }
710         if (r<0) {
711             if (errno==EINTR)
712                 continue;
713             if (iswouldblock(errno))
714                 return async_linebuf_nothing;
715             BAD(strerror(errno));
716         }
717         assert(r<=space);
718         if (memchr(searched,0,r)) BAD("nul in input data");
719         buf->size+=r;
720     }
721
722 #undef BAD
723 }