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