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