+typedef const char *(*finder_t) PARAMS ((const char *, int, int));
+
+/* Driver for fd_read_line and fd_read_head: keeps reading data until
+ a terminator (as decided by FINDER) occurs in the data. The trick
+ is that the data is first peeked at, and only then actually read.
+ That way the data after the terminator is never read. */
+
+static char *
+fd_read_until (int fd, finder_t finder, int bufsize)
+{
+ int size = bufsize, tail = 0;
+ char *buf = xmalloc (size);
+
+ while (1)
+ {
+ const char *end;
+ int pklen, rdlen, remain;
+
+ /* First, peek at the available data. */
+
+ pklen = fd_peek (fd, buf + tail, size - tail, -1);
+ if (pklen < 0)
+ {
+ xfree (buf);
+ return NULL;
+ }
+ end = finder (buf, tail, pklen);
+ if (end)
+ {
+ /* The data contains the terminator: we'll read the data up
+ to the end of the terminator. */
+ remain = end - (buf + tail);
+ /* Note +1 for trailing \0. */
+ if (size < tail + remain + 1)
+ {
+ size = tail + remain + 1;
+ buf = xrealloc (buf, size);
+ }
+ }
+ else
+ /* No terminator: simply read the data we know is (or should
+ be) available. */
+ remain = pklen;
+
+ /* Now, read the data. Note that we make no assumptions about
+ how much data we'll get. (Some TCP stacks are notorious for
+ read returning less data than the previous MSG_PEEK.) */
+
+ rdlen = fd_read (fd, buf + tail, remain, 0);
+ if (rdlen < 0)
+ {
+ xfree_null (buf);
+ return NULL;
+ }
+ if (rdlen == 0)
+ {
+ if (tail == 0)
+ {
+ /* EOF without anything having been read */
+ xfree (buf);
+ errno = 0;
+ return NULL;
+ }
+ /* Return what we received so far. */
+ if (size < tail + 1)
+ {
+ size = tail + 1; /* expand the buffer to receive the
+ terminating \0 */
+ buf = xrealloc (buf, size);
+ }
+ buf[tail] = '\0';
+ return buf;
+ }
+ tail += rdlen;
+ if (end && rdlen == remain)
+ {
+ /* The end was seen and the data read -- we got what we came
+ for. */
+ buf[tail] = '\0';
+ return buf;
+ }
+
+ /* Keep looping until all the data arrives. */
+
+ if (tail == size)
+ {
+ size <<= 1;
+ buf = xrealloc (buf, size);
+ }
+ }
+}
+
+static const char *
+line_terminator (const char *buf, int tail, int peeklen)
+{
+ const char *p = memchr (buf + tail, '\n', peeklen);
+ if (p)
+ /* p+1 because we want the line to include '\n' */
+ return p + 1;
+ return NULL;
+}
+
+/* Read one line from FD and return it. The line is allocated using
+ malloc.
+
+ If an error occurs, or if no data can be read, NULL is returned.
+ In the former case errno indicates the error condition, and in the
+ latter case, errno is NULL. */