Ejemplo n.º 1
0
int confWrite()
{
    if (config_buffer) {
        char conffile[1024];
        char tempfile[1024];
        FILE *outf = NULL;
        if (!FORM_SERVAL_INSTANCE_PATH(conffile, "serval.conf"))
            return -1;
        if (!FORM_SERVAL_INSTANCE_PATH(tempfile, "serval.conf.temp"))
            return -1;
        if ((outf = fopen(tempfile, "w")) == NULL)
            return WHYF_perror("fopen(%s, \"w\")", tempfile);
        unsigned int i;
        for (i = 0; i != confc; ++i)
            fprintf(outf, "%s=%s\n", confvar[i], confvalue[i]);
        if (fclose(outf) == EOF)
            return WHYF_perror("fclose(%s)", tempfile);
        if (rename(tempfile, conffile)) {
            WHYF_perror("rename(%s, %s)", tempfile, conffile);
            unlink(tempfile);
            return -1;
        }
    }
    return 0;
}
Ejemplo n.º 2
0
static char *grow_config_buffer(size_t needed)
{
    size_t cursize = config_buffer_end - config_buffer;
    size_t used = config_buffer_top - config_buffer;
    size_t newsize = used + needed;
    if (newsize > cursize) {
        // Round up to nearest multiple of CONFIG_BUFFER_ALLOCSIZE.
        newsize = newsize + CONFIG_BUFFER_ALLOCSIZE - ((newsize - 1) % CONFIG_BUFFER_ALLOCSIZE + 1);
        char *newbuf = realloc(config_buffer, newsize);
        if (newbuf == NULL) {
            WHYF_perror("realloc(%llu)", newsize);
            return NULL;
        }
        ssize_t dif = newbuf - config_buffer;
        unsigned int i;
        for (i = 0; i != confc; ++i) {
            confvar[i] += dif;
            confvalue[i] += dif;
        }
        config_buffer_end = newbuf + newsize;
        config_buffer_top = newbuf + used;
        config_buffer = newbuf;
    }
    char *ret = config_buffer_top;
    config_buffer_top += needed;
    return ret;
}
Ejemplo n.º 3
0
static int
dna_helper_harvest(int blocking)
{
  if (dna_helper_pid > 0) {
    if (blocking && (config.debug.dnahelper))
      DEBUGF("DNAHELPER waiting for pid=%d to die", dna_helper_pid);
    int status;
    pid_t pid = waitpid(dna_helper_pid, &status, blocking ? 0 : WNOHANG);
    if (pid == dna_helper_pid) {
      strbuf b = strbuf_alloca(80);
      INFOF("DNAHELPER process pid=%u %s", pid, strbuf_str(strbuf_append_exit_status(b, status)));
      unschedule(&sched_harvester);
      dna_helper_pid = -1;
      if (awaiting_reply) {
	unschedule(&sched_timeout);
	awaiting_reply = 0;
      }
      return 1;
    } else if (pid == -1) {
      return WHYF_perror("waitpid(%d, %s)", dna_helper_pid, blocking ? "0" : "WNOHANG");
    } else if (pid) {
      return WHYF("waitpid(%d, %s) returned %d", dna_helper_pid, blocking ? "0" : "WNOHANG", pid);
    }
  }
  return 0;
}
Ejemplo n.º 4
0
/* Read the symbolic link into the supplied buffer and add a terminating nul.  Return -1 if the
 * buffer is too short to hold the link content and the nul.  If readlink(2) returns an error, then
 * logs it and returns -1.  Otherwise, returns the number of bytes read, including the terminating
 * nul, ie, returns what readlink(2) returns plus one.  If the 'len' argument is given as zero, then
 * returns the number of bytes that would be read, by calling lstat(2) instead of readlink(2), plus
 * one for the terminating nul.  Beware of the following race condition: a symbolic link may be
 * altered between calling the lstat(2) and readlink(2), so the following apparently overflow-proof
 * code may still fail from a buffer overflow in the second call to read_symlink():
 *
 *    char *readlink_malloc(const char *path) {
 *	ssize_t len = read_symlink(path, NULL, 0);
 *	if (len == -1)
 *	  return NULL;
 *	char *buf = malloc(len);
 *	if (buf == NULL)
 *	  return NULL;
 *	if (read_symlink(path, buf, len) == -1) {
 *	  free(buf);
 *	  return NULL;
 *	}
 *	return buf;
 *    }
 *
 * @author Andrew Bettison <*****@*****.**>
 */
ssize_t read_symlink(const char *path, char *buf, size_t len)
{
    if (len == 0) {
        struct stat stat;
        if (lstat(path, &stat) == -1)
            return WHYF_perror("lstat(%s)", path);
        return stat.st_size;
    }
    ssize_t nr = readlink(path, buf, len);
    if (nr == -1)
        return WHYF_perror("readlink(%s)", path);
    if (nr >= len)
        return WHYF("buffer overrun from readlink(%s, len=%lu)", path, (unsigned long) len);
    buf[nr] = '\0';
    return nr;
}
Ejemplo n.º 5
0
static int receive_http_response(int sock, char *buffer, size_t buffer_len, struct http_response_parts *parts)
{
  int len = 0;
  int count;
  do {
      if ((count = read(sock, &buffer[len], buffer_len - len)) == -1)
	return WHYF_perror("read(%d, %p, %d)", sock, &buffer[len], buffer_len - len);
      len += count;
  } while (len < buffer_len && count != 0 && !http_header_complete(buffer, len, len));
  if (debug & DEBUG_RHIZOME_RX)
    DEBUGF("Received HTTP response %s", alloca_toprint(-1, buffer, len));
  if (unpack_http_response(buffer, parts) == -1)
    return -1;
  if (parts->code != 200 && parts->code != 201) {
    INFOF("Failed HTTP request: server returned %003u %s", parts->code, parts->reason);
    return -1;
  }
  if (parts->content_length == -1) {
    if (debug & DEBUG_RHIZOME_RX)
      DEBUGF("Invalid HTTP reply: missing Content-Length header");
    return -1;
  }
  DEBUGF("content_length=%d", parts->content_length);
  return 0;
}
Ejemplo n.º 6
0
static int rhizome_server_set_response(rhizome_http_request *r, const struct http_response *h)
{
  strbuf b = strbuf_local((char *) r->buffer, r->buffer_size);
  strbuf_build_http_response(b, h);
  if (r->buffer == NULL || strbuf_overrun(b)) {
    // Need a bigger buffer
    if (r->buffer)
      free(r->buffer);
    r->buffer_size = strbuf_count(b) + 1;
    r->buffer = malloc(r->buffer_size);
    if (r->buffer == NULL) {
      WHYF_perror("malloc(%u)", r->buffer_size);
      r->buffer_size = 0;
      return WHY("Cannot send response, out of memory");
    }
    strbuf_init(b, (char *) r->buffer, r->buffer_size);
    strbuf_build_http_response(b, h);
    if (strbuf_overrun(b))
      return WHYF("Bug! Cannot send response, buffer not big enough");
  }
  r->buffer_length = strbuf_len(b);
  r->buffer_offset = 0;
  r->request_type |= RHIZOME_HTTP_REQUEST_FROMBUFFER;
  if (debug & DEBUG_RHIZOME_TX)
    DEBUGF("Sending HTTP response: %s", alloca_toprint(120, (const char *)r->buffer, r->buffer_length));
  return 0;
}
Ejemplo n.º 7
0
int rhizome_manifest_check_file(rhizome_manifest *m_in)
{
  long long gotfile = 0;
  if (sqlite_exec_int64(&gotfile, "SELECT COUNT(*) FROM FILES WHERE ID='%s' and datavalid=1;", m_in->fileHexHash) != 1) {
    WHYF("Failed to count files");
    return 0;
  }
  if (gotfile) {
    DEBUGF("Skipping file checks for bundle, as file is already in the database");
    return 0;
  }

  /* Find out whether the payload is expected to be encrypted or not */
  m_in->payloadEncryption=rhizome_manifest_get_ll(m_in, "crypt");
  
  /* Check payload file is accessible and discover its length, then check that it matches
     the file size stored in the manifest */
  long long mfilesize = rhizome_manifest_get_ll(m_in, "filesize");
  m_in->fileLength = 0;
  if (m_in->dataFileName[0]) {
    struct stat stat;
    if (lstat(m_in->dataFileName,&stat) == -1) {
      if (errno != ENOENT || mfilesize != 0)
	return WHYF_perror("stat(%s)", m_in->dataFileName);
    } else {
      m_in->fileLength = stat.st_size;
    }
  }
  if (debug & DEBUG_RHIZOME)
    DEBUGF("filename=%s, fileLength=%lld", m_in->dataFileName, m_in->fileLength);
  if (mfilesize != -1 && mfilesize != m_in->fileLength) {
    WHYF("Manifest.filesize (%lld) != actual file size (%lld)", mfilesize, m_in->fileLength);
    return -1;
  }

  /* If payload is empty, ensure manifest has not file hash, otherwis compute the hash of the
     payload and check that it matches manifest. */
  const char *mhexhash = rhizome_manifest_get(m_in, "filehash", NULL, 0);
  if (m_in->fileLength != 0) {
    char hexhashbuf[RHIZOME_FILEHASH_STRLEN + 1];
    if (rhizome_hash_file(m_in,m_in->dataFileName, hexhashbuf))
      return WHY("Could not hash file.");
    memcpy(&m_in->fileHexHash[0], &hexhashbuf[0], sizeof hexhashbuf);
    m_in->fileHashedP = 1;
    if (!mhexhash) return WHY("manifest contains no file hash");
    if (mhexhash && strcmp(m_in->fileHexHash, mhexhash)) {
      WHYF("Manifest.filehash (%s) does not match payload hash (%s)", mhexhash, m_in->fileHexHash);
      return -1;
    }
  } else {
    if (mhexhash != NULL) {
      WHYF("Manifest.filehash (%s) should be absent for empty payload", mhexhash);
      return -1;
    }
  }

  return 0;
}
Ejemplo n.º 8
0
/* for when all other options fail, as can happen on Android,
   if the permissions for the socket-based method are broken.
   Down side is that it while it gets the interface name and
   broadcast, it doesn't get the local address for that
   interface. 
*/
int scrapeProcNetRoute()
{
  if (config.debug.overlayinterfaces) DEBUG("called");

  FILE *f=fopen("/proc/net/route","r");
  if (!f)
    return WHY_perror("fopen(\"/proc/net/route\")");

  char line[1024],name[1024],dest[1024],mask[1024];

  /* skip header line */
  line[0] = '\0';
  if (fgets(line,1024,f) == NULL)
    return WHYF_perror("fgets(%p,1024,\"/proc/net/route\")", line);

  line[0] = '\0';
  if (fgets(line,1024,f) == NULL)
    return WHYF_perror("fgets(%p,1024,\"/proc/net/route\")", line);
    
  struct socket_address addr, broadcast;
  bzero(&addr, sizeof(addr));
  bzero(&broadcast, sizeof(broadcast));
  addr.addrlen = sizeof(addr.inet);
  addr.inet.sin_family = AF_INET;
  broadcast.addrlen = sizeof(addr.inet);
  broadcast.inet.sin_family = AF_INET;
  
  while(line[0]) {
    int r;
    if ((r=sscanf(line,"%s %s %*s %*s %*s %*s %*s %s",name,dest,mask))==3) {
      addr.inet.sin_addr.s_addr=strtol(dest,NULL,16);
      struct in_addr netmask = {.s_addr=strtol(mask,NULL,16)};
      broadcast.inet.sin_addr.s_addr=addr.inet.sin_addr.s_addr | ~netmask.s_addr;
      overlay_interface_register(name,&addr,&broadcast);
    }
    line[0] = '\0';
    if (fgets(line,1024,f) == NULL)
      return WHYF_perror("fgets(%p,1024,\"/proc/net/route\")", line);
  }
  fclose(f);
  return 0;
}
Ejemplo n.º 9
0
ssize_t recvwithttl(int sock,unsigned char *buffer, size_t bufferlen,int *ttl, struct socket_address *recvaddr)
{
  struct msghdr msg;
  struct iovec iov[1];
  struct cmsghdr cmsgcmsg[16];
  iov[0].iov_base=buffer;
  iov[0].iov_len=bufferlen;
  bzero(&msg,sizeof(msg));
  msg.msg_name = &recvaddr->store;
  msg.msg_namelen = recvaddr->addrlen;
  msg.msg_iov = &iov[0];
  msg.msg_iovlen = 1;
  msg.msg_control = cmsgcmsg;
  msg.msg_controllen = sizeof cmsgcmsg;
  msg.msg_flags = 0;
  
  ssize_t len = recvmsg(sock,&msg,0);
  if (len == -1 && errno != EAGAIN && errno != EWOULDBLOCK)
    return WHYF_perror("recvmsg(%d,%p,0)", sock, &msg);
  
#if 0
  if (config.debug.packetrx) {
    DEBUGF("recvmsg returned %d (flags=%d, msg_controllen=%d)", (int) len, msg.msg_flags, (int)msg.msg_controllen);
    dump("received data", buffer, len);
  }
#endif
  
  if (len > 0) {
    struct cmsghdr *cmsg;
    for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
      if (   cmsg->cmsg_level == IPPROTO_IP
	  && ((cmsg->cmsg_type == IP_RECVTTL) || (cmsg->cmsg_type == IP_TTL))
	  && cmsg->cmsg_len
      ) {
	if (config.debug.packetrx)
	  DEBUGF("  TTL (%p) data location resolves to %p", ttl,CMSG_DATA(cmsg));
	if (CMSG_DATA(cmsg)) {
	  *ttl = *(unsigned char *) CMSG_DATA(cmsg);
	  if (config.debug.packetrx)
	    DEBUGF("  TTL of packet is %d", *ttl);
	} 
      } else {
	if (config.debug.packetrx)
	  DEBUGF("I didn't expect to see level=%02x, type=%02x",
		 cmsg->cmsg_level,cmsg->cmsg_type);
      }	 
    }
  }
  recvaddr->addrlen = msg.msg_namelen;
  
  return len;
}
Ejemplo n.º 10
0
void rhizome_server_poll(struct sched_ent *alarm)
{
  if (alarm->poll.revents & (POLLIN | POLLOUT)) {
    struct sockaddr addr;
    unsigned int addr_len = sizeof addr;
    int sock;
    while ((sock = accept(rhizome_server_socket, &addr, &addr_len)) != -1) {
      if (addr.sa_family == AF_INET) {
	struct sockaddr_in *peerip = (struct sockaddr_in *)&addr;
	INFOF("RHIZOME HTTP SERVER, ACCEPT addrlen=%u family=%u port=%u addr=%u.%u.%u.%u",
	    addr_len, peerip->sin_family, peerip->sin_port,
	    ((unsigned char*)&peerip->sin_addr.s_addr)[0],
	    ((unsigned char*)&peerip->sin_addr.s_addr)[1],
	    ((unsigned char*)&peerip->sin_addr.s_addr)[2],
	    ((unsigned char*)&peerip->sin_addr.s_addr)[3]
	  );
      } else {
	INFOF("RHIZOME HTTP SERVER, ACCEPT addrlen=%u family=%u data=%s",
	  addr_len, addr.sa_family, alloca_tohex((unsigned char *)addr.sa_data, sizeof addr.sa_data)
	);
      }
      rhizome_http_request *request = calloc(sizeof(rhizome_http_request), 1);
      if (request == NULL) {
	WHYF_perror("calloc(%u, 1)", sizeof(rhizome_http_request));
	WHY("Cannot respond to request, out of memory");
      } else {
	/* We are now trying to read the HTTP request */
	request->request_type=RHIZOME_HTTP_REQUEST_RECEIVING;
	request->alarm.function = rhizome_client_poll;
	connection_stats.name="rhizome_client_poll";
	request->alarm.stats=&connection_stats;
	request->alarm.poll.fd=sock;
	request->alarm.poll.events=POLLIN;
	request->alarm.alarm = gettime_ms()+RHIZOME_IDLE_TIMEOUT;
	request->alarm.deadline = request->alarm.alarm+RHIZOME_IDLE_TIMEOUT;
	// watch for the incoming http request
	watch(&request->alarm);
	// set an inactivity timeout to close the connection
	schedule(&request->alarm);
      }
    }
    if (errno != EAGAIN) {
      WARN_perror("accept");
    }
  }
  
  if (alarm->poll.revents & (POLLHUP | POLLERR)) {
    INFO("Error on tcp listen socket");
  }
}
Ejemplo n.º 11
0
static int
dna_helper_kill()
{
  if (awaiting_reply) {
    unschedule(&sched_timeout);
    awaiting_reply = 0;
  }
  if (dna_helper_pid > 0) {
    if (config.debug.dnahelper)
      DEBUGF("DNAHELPER sending SIGTERM to pid=%d", dna_helper_pid);
    if (kill(dna_helper_pid, SIGTERM) == -1)
      WHYF_perror("kill(%d, SIGTERM)", dna_helper_pid);
    // The process is wait()ed for in dna_helper_monitor() so that we do not block here.
    return 1;
  }
  return 0;
}
Ejemplo n.º 12
0
int log_backtrace(int level, struct __sourceloc whence)
{
#ifndef NO_BACKTRACE
  _log_iterator it;
  _log_iterator_start(&it);
  _rotate_log_file(&it);
  char execpath[MAXPATHLEN];
  if (get_self_executable_path(execpath, sizeof execpath) == -1)
    return WHY("cannot log backtrace: own executable path unknown");
  char tempfile[MAXPATHLEN];
  if (!FORM_SERVAL_INSTANCE_PATH(tempfile, "servalgdb.XXXXXX"))
    return -1;
  int tmpfd = mkstemp(tempfile);
  if (tmpfd == -1)
    return WHYF_perror("mkstemp(%s)", alloca_str_toprint(tempfile));
  if (write_str(tmpfd, "backtrace\n") == -1) {
    close(tmpfd);
    unlink(tempfile);
    return -1;
  }
  if (close(tmpfd) == -1) {
    WHY_perror("close");
    unlink(tempfile);
    return -1;
  }
  char pidstr[12];
  snprintf(pidstr, sizeof pidstr, "%jd", (intmax_t)getpid());
  int stdout_fds[2];
  if (pipe(stdout_fds) == -1)
    return WHY_perror("pipe");
  pid_t child_pid;
  switch (child_pid = fork()) {
  case -1: // error
    WHY_perror("fork");
    close(stdout_fds[0]);
    close(stdout_fds[1]);
    return WHY("cannot log backtrace: fork failed");
  case 0: // child
    if (dup2(stdout_fds[1], 1) == -1 || dup2(stdout_fds[1], 2) == -1) {
      perror("dup2");
      _exit(-1);
    }
    close(0);
    if (open("/dev/null", O_RDONLY) != 0) {
      perror("open(\"/dev/null\")");
      _exit(-2);
    }
    close(stdout_fds[0]);
    /* XXX: Need the cast on Solaris because it defins NULL as 0L and gcc doesn't
     * see it as a sentinal */
    execlp("gdb", "gdb", "-n", "-batch", "-x", tempfile, execpath, pidstr, (void*)NULL);
    perror("execlp(\"gdb\")");
    do { _exit(-3); } while (1);
    break;
  }
  // parent
  close(stdout_fds[1]);
  _log_iterator_printf_nl(&it, level, whence, "GDB BACKTRACE");
  char buf[1024];
  char *const bufe = buf + sizeof buf;
  char *linep = buf;
  char *readp = buf;
  ssize_t nr;
  while ((nr = read(stdout_fds[0], readp, bufe - readp)) > 0) {
    char *p = readp;
    readp = readp + nr;
    for (; p < readp; ++p)
      if (*p == '\n' || *p == '\0') {
	*p = '\0';
	_log_iterator_printf_nl(&it, level, __NOWHERE__, "%s", linep);
	linep = p + 1;
      }
    if (readp >= bufe && linep == buf) {
      // Line does not fit into buffer.
      char t = bufe[-1];
      bufe[-1] = '\0';
      _log_iterator_printf_nl(&it, level, __NOWHERE__, "%s", buf);
      buf[0] = t;
      readp = buf + 1;
    } else if (readp + 120 >= bufe && linep != buf) {
      // Buffer low on space.
      if (linep < readp)
	memmove(buf, linep, readp - linep);
      readp -= linep - buf;
      linep = buf;
    }
    // Invariant: readp < bufe
  }
  if (nr == -1)
    WHY_perror("read");
  if (readp > linep) {
    *readp = '\0';
    _log_iterator_printf_nl(&it, level, __NOWHERE__, "%s", linep);
  }
  close(stdout_fds[0]);
  int status = 0;
  if (waitpid(child_pid, &status, 0) == -1)
    WHY_perror("waitpid");
  strbuf b = strbuf_local(buf, sizeof buf);
  strbuf_append_exit_status(b, status);
  _log_iterator_printf_nl(&it, level, __NOWHERE__, "gdb %s", buf);
  unlink(tempfile);
#endif
  return 0;
}
Ejemplo n.º 13
0
static int _read_config()
{
    char conffile[1024];
    if (!FORM_SERVAL_INSTANCE_PATH(conffile, "serval.conf"))
        return -1;
    size_t size = 0;
    confc = 0;
    FILE *f = fopen(conffile, "r");
    if (f == NULL) {
        if (errno != ENOENT)
            return WHYF_perror("fopen(%s)", conffile);
    } else {
        if (fseeko(f, (off_t) 0, SEEK_END) == -1) {
            WHYF_perror("fseeko(%s, 0, SEEK_END)", conffile);
            fclose(f);
            return -1;
        }
        off_t tell = ftello(f);
        if (tell == -1) {
            WHYF_perror("ftello(%s)", conffile);
            fclose(f);
            return -1;
        }
        size = tell;
        if (fseeko(f, (off_t) 0, SEEK_SET) == -1) {
            WHYF_perror("fseeko(%s, 0, SEEK_SET)", conffile);
            fclose(f);
            return -1;
        }
        if (grow_config_buffer(size) == NULL) {
            fclose(f);
            return -1;
        }
        if (fread(config_buffer, size, 1, f) != 1) {
            if (ferror(f))
                WHYF_perror("fread(%s, %llu)", conffile, (unsigned long long) size);
            else
                WHYF("fread(%s, %llu) hit EOF", conffile, (unsigned long long) size);
            free(config_buffer);
            config_buffer = NULL;
            fclose(f);
            return -1;
        }
        if (fclose(f) == EOF)
            return WHYF_perror("fclose(%s)", conffile);
    }
    config_buffer_top = config_buffer_end = config_buffer + size;
    char *c = config_buffer;
    char *e = config_buffer_top;
    unsigned int linenum;
    char *problem = NULL;
    char *extra = "";
    for (linenum = 1; !problem && c < e; ++linenum) {
        if (*c == '#') {
            // skip comment lines
            while (c < e && *c != '\n')
                ++c;
        } else if (*c == '\n') {
            // skip empty lines
            ++c;
        } else if (c < e - 1 && *c == '\r' && c[1] == '\n') {
            // skip empty lines
            c += 2;
        } else if (confc < MAX_CONFIG_VARS) {
            char *var = confvar[confc] = c;
            while (c < e && *c != '=' && *c != '\r' && *c != '\n')
                ++c;
            if (c < e && *c == '=') {
                *c++ = '\0';
                if (is_configvarname(var)) {
                    confvalue[confc] = c;
                    while (c < e && *c != '\r' && *c != '\n')
                        ++c;
                    if (c < e && *c == '\n') {
                        *c++ = '\0';
                        ++confc;
                    } else if (c < e - 1 && *c == '\r' && c[1] == '\n') {
                        *c++ = '\0';
                        *c++ = '\0';
                        ++confc;
                    } else {
                        problem = "missing end-of-line";
                    }
                } else {
                    problem = "invalid variable name: ";
                    extra = var;
                }
            } else {
                problem = "missing '='";
            }
        } else {
            problem = "too many variables";
        }
    }
    if (problem)
        return WHYF("Error in %s at line %u: %s%s", conffile, linenum, problem, extra);
    return 0;
}
Ejemplo n.º 14
0
void rhizome_direct_http_dispatch(rhizome_direct_sync_request *r)
{
  DEBUGF("Dispatch size_high=%lld",r->cursor->size_high);
  rhizome_direct_transport_state_http *state = r->transport_specific_state;

  int sock=socket(AF_INET, SOCK_STREAM, 0);
  if (sock==-1) {
    WHY_perror("socket");    
    goto end;
  } 

  struct hostent *hostent;
  hostent = gethostbyname(state->host);
  if (!hostent) {
    DEBUGF("could not resolve hostname");
    goto end;
  }

  struct sockaddr_in addr;  
  addr.sin_family = AF_INET;     
  addr.sin_port = htons(state->port);   
  addr.sin_addr = *((struct in_addr *)hostent->h_addr);
  bzero(&(addr.sin_zero),8);     

  if (connect(sock,(struct sockaddr *)&addr,sizeof(struct sockaddr)) == -1) {
    WHY_perror("connect");
    close(sock);
    goto end;
  }
 
  char boundary[20];
  char buffer[8192];

  strbuf bb = strbuf_local(boundary, sizeof boundary);
  strbuf_sprintf(bb, "%08lx%08lx", random(), random());
  assert(!strbuf_overrun(bb));
  strbuf content_preamble = strbuf_alloca(200);
  strbuf content_postamble = strbuf_alloca(40);
  strbuf_sprintf(content_preamble,
      "--%s\r\n"
      "Content-Disposition: form-data; name=\"data\"; filename=\"IHAVEs\"\r\n"
      "Content-Type: application/octet-stream\r\n"
      "\r\n",
      boundary
    );
  strbuf_sprintf(content_postamble, "\r\n--%s--\r\n", boundary);
  assert(!strbuf_overrun(content_preamble));
  assert(!strbuf_overrun(content_postamble));
  int content_length = strbuf_len(content_preamble)
		     + r->cursor->buffer_offset_bytes
		     + r->cursor->buffer_used
		     + strbuf_len(content_postamble);
  strbuf request = strbuf_local(buffer, sizeof buffer);
  strbuf_sprintf(request,
      "POST /rhizome/enquiry HTTP/1.0\r\n"
      "Content-Length: %d\r\n"
      "Content-Type: multipart/form-data; boundary=%s\r\n"
      "\r\n%s",
      content_length, boundary, strbuf_str(content_preamble)
    );
  assert(!strbuf_overrun(request));

  /* TODO: Refactor this code so that it uses our asynchronous framework.
   */
  int len = strbuf_len(request);
  int sent=0;
  while(sent<len) {
    DEBUGF("write(%d, %s, %d)", sock, alloca_toprint(-1, &buffer[sent], len-sent), len-sent);
    int count=write(sock,&buffer[sent],len-sent);
    if (count == -1) {
      if (errno==EPIPE) goto rx;
      WHYF_perror("write(%d)", len - sent);
      close(sock);
      goto end;
    }
    sent+=count;
  }

  len=r->cursor->buffer_offset_bytes+r->cursor->buffer_used;
  sent=0;
  while(sent<len) {
    int count=write(sock,&r->cursor->buffer[sent],len-sent);
    if (count == -1) {
      if (errno == EPIPE)
	goto rx;
      WHYF_perror("write(%d)", count);
      close(sock);
      goto end;
    }
    sent+=count;
  }

  strbuf_reset(request);
  strbuf_puts(request, strbuf_str(content_postamble));
  len = strbuf_len(request);
  sent=0;
  while(sent<len) {
    DEBUGF("write(%d, %s, %d)", sock, alloca_toprint(-1, &buffer[sent], len-sent), len-sent);
    int count=write(sock,&buffer[sent],len-sent);
    if (count == -1) {
      if (errno==EPIPE) goto rx;
      WHYF_perror("write(%d)", len - sent);
      close(sock);
      goto end;
    }
    sent+=count;
  }

  struct http_response_parts parts;
 rx:
  /* request sent, now get response back. */
  if (receive_http_response(sock, buffer, sizeof buffer, &parts) == -1) {
    close(sock);
    goto end;
  }

  /* For some reason the response data gets overwritten during a push,
     so we need to copy it, and use the copy instead. */
  unsigned char *actionlist=alloca(parts.content_length);
  bcopy(parts.content_start, actionlist, parts.content_length);
  dump("response", actionlist, parts.content_length);

  /* We now have the list of (1+RHIZOME_BAR_PREFIX_BYTES)-byte records that indicate
     the list of BAR prefixes that differ between the two nodes.  We can now action
     those which are relevant, i.e., based on whether we are pushing, pulling or 
     synchronising (both).

     I am currently undecided as to whether it is cleaner to have some general
     rhizome direct function for doing that, or whether it just adds unnecessary
     complication, and the responses should just be handled in here.

     For now, I am just going to implement it in here, and we can generalise later.
  */
  int i;
  for(i=10;i<content_length;i+=(1+RHIZOME_BAR_PREFIX_BYTES))
    {
      int type=actionlist[i];
      unsigned long long 
	bid_prefix_ll=rhizome_bar_bidprefix_ll((unsigned char *)&actionlist[i+1]);
      DEBUGF("%s %016llx* @ 0x%x",type==1?"push":"pull",bid_prefix_ll,i);
      if (type==2&&r->pullP) {
	/* Need to fetch manifest.  Once we have the manifest, then we can
	   use our normal bundle fetch routines from rhizome_fetch.c	 

	   Generate a request like: GET /rhizome/manifestbybar/<hex of bar>
	   and add it to our list of HTTP fetch requests, then watch
	   until the request is finished.  That will give us the manifest.
	   Then as noted above, we can use that to pull the file down using
	   existing routines.
	*/
	if (!rhizome_fetch_request_manifest_by_prefix
	    (&addr,&actionlist[i+1],RHIZOME_BAR_PREFIX_BYTES,
	     1 /* import, getting file if needed */))
	  {
	    /* Fetching the manifest, and then using it to see if we want to 
	       fetch the file for import is all handled asynchronously, so just
	       wait for it to finish. */
	    while(rhizome_file_fetch_queue_count) fd_poll();
	  }
	
      } else if (type==1&&r->pushP) {
	/* Form up the POST request to submit the appropriate bundle. */

	/* Start by getting the manifest, which is the main thing we need, and also
	   gives us the information we need for sending any associated file. */
	rhizome_manifest 
	  *m=rhizome_direct_get_manifest(&actionlist[i+1],
					 RHIZOME_BAR_PREFIX_BYTES);
	if (!m) {
	  WHY("This should never happen.  The manifest exists, but when I went looking for it, it doesn't appear to be there.");
	  goto next_item;
	}

	/* Get filehash and size from manifest if present */
	const char *id = rhizome_manifest_get(m, "id", NULL, 0);
	DEBUGF("bundle id = '%s'",id);
	const char *hash = rhizome_manifest_get(m, "filehash", NULL, 0);
	DEBUGF("bundle file hash = '%s'",hash);
	long long filesize = rhizome_manifest_get_ll(m, "filesize");
	DEBUGF("file size = %lld",filesize);

	/* We now have everything we need to compose the POST request and send it.
	 */
	char *template="POST /rhizome/import HTTP/1.0\r\n"
Ejemplo n.º 15
0
int rhizome_direct_form_received(rhizome_http_request *r)
{
  const char *submitBareFileURI=confValueGet("rhizome.api.addfile.uri", NULL);

  /* Process completed form based on the set of fields seen */
  if (!strcmp(r->path,"/rhizome/import")) {
    switch(r->fields_seen) {
    case RD_MIME_STATE_MANIFESTHEADERS | RD_MIME_STATE_DATAHEADERS: {
	/* Got a bundle to import */
	DEBUGF("Call bundle import for rhizomedata.%d.{data,file}",
	       r->alarm.poll.fd);
	strbuf manifest_path = strbuf_alloca(50);
	strbuf payload_path = strbuf_alloca(50);
	strbuf_sprintf(manifest_path, "rhizomedirect.%d.manifest", r->alarm.poll.fd);
	strbuf_sprintf(payload_path, "rhizomedirect.%d.data", r->alarm.poll.fd);
	int ret = rhizome_bundle_import_files(strbuf_str(manifest_path), strbuf_str(payload_path), 1); // ttl = 1
	
	DEBUGF("Import returned %d",ret);
	
	rhizome_direct_clear_temporary_files(r);
	/* report back to caller.
	  200 = ok, which is probably appropriate for when we already had the bundle.
	  201 = content created, which is probably appropriate for when we successfully
	  import a bundle (or if we already have it).
	  403 = forbidden, which might be appropriate if we refuse to accept it, e.g.,
	  the import fails due to malformed data etc.
	  (should probably also indicate if we have a newer version if possible)
	*/
	switch (ret) {
	case 0:
	  return rhizome_server_simple_http_response(r, 201, "Bundle succesfully imported.");
	case 2:
	  return rhizome_server_simple_http_response(r, 200, "Bundle already imported.");
	}
	return rhizome_server_simple_http_response(r, 500, "Server error: Rhizome import command failed.");
      }
      break;     
    default:
      /* Clean up after ourselves */
      rhizome_direct_clear_temporary_files(r);	     
    }
  } else if (!strcmp(r->path,"/rhizome/enquiry")) {
    int fd=-1;
    char file[1024];
    switch(r->fields_seen) {
    case RD_MIME_STATE_DATAHEADERS:
      /* Read data buffer in, pass to rhizome direct for comparison with local
	 rhizome database, and send back responses. */
      snprintf(file,1024,"rhizomedirect.%d.%s",r->alarm.poll.fd,"data");
      fd=open(file,O_RDONLY);
      if (fd == -1) {
	WHYF_perror("open(%s, O_RDONLY)", alloca_str_toprint(file));
	/* Clean up after ourselves */
	rhizome_direct_clear_temporary_files(r);	     
	return rhizome_server_simple_http_response(r,500,"Couldn't read a file");
      }
      struct stat stat;
      if (fstat(fd, &stat) == -1) {
	WHYF_perror("stat(%d)", fd);
	/* Clean up after ourselves */
	close(fd);
	rhizome_direct_clear_temporary_files(r);	     
	return rhizome_server_simple_http_response(r,500,"Couldn't stat a file");
      }
      unsigned char *addr = mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
      if (addr==MAP_FAILED) {
	WHYF_perror("mmap(NULL, %lld, PROT_READ, MAP_SHARED, %d, 0)", (long long) stat.st_size, fd);
	/* Clean up after ourselves */
	close(fd);
	rhizome_direct_clear_temporary_files(r);	     
	return rhizome_server_simple_http_response(r,500,"Couldn't mmap() a file");
      }
      /* Ask for a fill response.  Regardless of the size of the set of BARs passed
	 to us, we will allow up to 64KB of response. */
      rhizome_direct_bundle_cursor 
	*c=rhizome_direct_get_fill_response(addr,stat.st_size,65536);
      munmap(addr,stat.st_size);
      close(fd);

      if (c)
	{
	  /* TODO: Write out_buffer as the body of the response.
	     We should be able to do this using the async framework fairly easily.
	  */
	  
	  int bytes=c->buffer_offset_bytes+c->buffer_used;
	  r->buffer=malloc(bytes+1024);
	  r->buffer_size=bytes+1024;
	  r->buffer_offset=0;
	  assert(r->buffer);

	  /* Write HTTP response header */
	  struct http_response hr;
	  hr.result_code=200;
	  hr.content_type="binary/octet-stream";
	  hr.content_length=bytes;
	  hr.body=NULL;
	  r->request_type=0;
	  rhizome_server_set_response(r,&hr);
	  assert(r->buffer_offset<1024);

	  /* Now append body and send it back. */
	  bcopy(c->buffer,&r->buffer[r->buffer_length],bytes);
	  r->buffer_length+=bytes;
	  r->buffer_offset=0;

	  /* Clean up cursor after sending response */
	  rhizome_direct_bundle_iterator_free(&c);
	  /* Clean up after ourselves */
	  rhizome_direct_clear_temporary_files(r);	     

	  return 0;
	}
      else
	{
	  return rhizome_server_simple_http_response(r,500,"Could not get response to enquiry");
	}

      /* Clean up after ourselves */
      rhizome_direct_clear_temporary_files(r);	     
      break;
    default:
      /* Clean up after ourselves */
      rhizome_direct_clear_temporary_files(r);	     

      return rhizome_server_simple_http_response(r, 404, "/rhizome/enquiry requires 'data' field");
    }
  }  
  /* Allow servald to be configured to accept files without manifests via HTTP
     from localhost, so that rhizome bundles can be created programatically.
     There are probably still some security loop-holes here, which is part of
     why we leave it disabled by default, but it will be sufficient for testing
     possible uses, including integration with OpenDataKit.
  */
  else if (submitBareFileURI&&(!strcmp(r->path,submitBareFileURI))) {
    if (strcmp(inet_ntoa(r->requestor.sin_addr),
	       confValueGet("rhizome.api.addfile.allowedaddress","127.0.0.1")))
      {	
	DEBUGF("rhizome.api.addfile request received from %s, but is only allowed from %s",
	       inet_ntoa(r->requestor.sin_addr),
	       confValueGet("rhizome.api.addfile.allowedaddress", "127.0.0.1"));

	rhizome_direct_clear_temporary_files(r);	     
	return rhizome_server_simple_http_response(r,404,"Not available from here.");
      }

    switch(r->fields_seen) {
    case RD_MIME_STATE_DATAHEADERS:
      /* We have been given a file without a manifest, we should only
	 accept if it we are configured to do so, and the connection is from
	 localhost.  Otherwise people could cause your servald to create
	 arbitrary bundles, which would be bad.
      */
      /* A bundle to import */
      DEBUGF("Call bundle import sans-manifest for rhizomedata.%d.{data,file}",
	     r->alarm.poll.fd);
      
      char filepath[1024];
      snprintf(filepath,1024,"rhizomedirect.%d.data",r->alarm.poll.fd);

      const char *manifestTemplate
	=confValueGet("rhizome.api.addfile.manifesttemplate", NULL);
      
      if (manifestTemplate&&access(manifestTemplate, R_OK) != 0)
	{
	  rhizome_direct_clear_temporary_files(r);	     
	  return rhizome_server_simple_http_response(r,500,"rhizome.api.addfile.manifesttemplate points to a file I could not read.");
	}

      rhizome_manifest *m = rhizome_new_manifest();
      if (!m)
	{
	  rhizome_server_simple_http_response(r,500,"No free manifest slots. Try again later.");
	  rhizome_direct_clear_temporary_files(r);	     
	  return WHY("Manifest struct could not be allocated -- not added to rhizome");
	}

      if (manifestTemplate)
	if (rhizome_read_manifest_file(m, manifestTemplate, 0) == -1) {
	  rhizome_manifest_free(m);
	  rhizome_direct_clear_temporary_files(r);	     
	  return rhizome_server_simple_http_response(r,500,"rhizome.api.addfile.manifesttemplate can't be read as a manifest.");
	}

      /* Fill in a few missing manifest fields, to make it easier to use when adding new files:
	 - the default service is FILE
	 - use the current time for "date"
	 - if service is file, then use the payload file's basename for "name"
      */
      const char *service = rhizome_manifest_get(m, "service", NULL, 0);
      if (service == NULL) {
	rhizome_manifest_set(m, "service", (service = RHIZOME_SERVICE_FILE));
	if (debug & DEBUG_RHIZOME) DEBUGF("missing 'service', set default service=%s", service);
      } else {
	if (debug & DEBUG_RHIZOME) DEBUGF("manifest contains service=%s", service);
      }
      if (rhizome_manifest_get(m, "date", NULL, 0) == NULL) {
	rhizome_manifest_set_ll(m, "date", (long long) gettime_ms());
	if (debug & DEBUG_RHIZOME) DEBUGF("missing 'date', set default date=%s", rhizome_manifest_get(m, "date", NULL, 0));
      }

      const char *name = rhizome_manifest_get(m, "name", NULL, 0);
      if (name == NULL) {
	name=r->data_file_name;
	rhizome_manifest_set(m, "name", r->data_file_name);
	if (debug & DEBUG_RHIZOME) DEBUGF("missing 'name', set name=\"%s\" from HTTP post field filename specification", name);
      } else {
	if (debug & DEBUG_RHIZOME) DEBUGF("manifest contains name=\"%s\"", name);
      }

      const char *senderhex
	= rhizome_manifest_get(m, "sender", NULL, 0);
      if (!senderhex) senderhex=confValueGet("rhizome.api.addfile.author",NULL);
      unsigned char authorSid[SID_SIZE];
      if (senderhex) fromhexstr(authorSid,senderhex,SID_SIZE);
      const char *bskhex
	=confValueGet("rhizome.api.addfile.bundlesecretkey", NULL);   

      /* Bind an ID to the manifest, and also bind the file.  Then finalise the 
	 manifest. But if the manifest already contains an ID, don't override it. */
      if (rhizome_manifest_get(m, "id", NULL, 0) == NULL) {
	if (rhizome_manifest_bind_id(m, senderhex ? authorSid : NULL)) {
	  rhizome_manifest_free(m);
	  m = NULL;
	  rhizome_direct_clear_temporary_files(r);
	  return rhizome_server_simple_http_response(r,500,"Could not bind manifest to an ID");
	}	
      } else if (bskhex) {
	/* Allow user to specify a bundle secret key so that the same bundle can
	   be updated, rather than creating a new bundle each time. */
	unsigned char bsk[RHIZOME_BUNDLE_KEY_BYTES];
	fromhexstr(bsk,bskhex,RHIZOME_BUNDLE_KEY_BYTES);
	memcpy(m->cryptoSignSecret, bsk, RHIZOME_BUNDLE_KEY_BYTES);
	if (rhizome_verify_bundle_privatekey(m) == -1) {
	  rhizome_manifest_free(m);
	  m = NULL;
	  rhizome_direct_clear_temporary_files(r);
	  return rhizome_server_simple_http_response(r,500,"rhizome.api.addfile.bundlesecretkey did not verify.  Using the right key for the right bundle?");
	}
      } else {
	/* Bundle ID specified, but without a BSK or sender SID specified.
	   Therefore we cannot work out the bundle key, and cannot update the
	   bundle. */
	rhizome_manifest_free(m);
	m = NULL;
	rhizome_direct_clear_temporary_files(r);
	return rhizome_server_simple_http_response(r,500,"rhizome.api.addfile.bundlesecretkey not set, and manifest template contains no sender, but template contains a hard-wired bundle ID.  You must specify at least one, or not supply id= in the manifest template.");
	
      }
      
      int encryptP = 0; // TODO Determine here whether payload is to be encrypted.
      if (rhizome_manifest_bind_file(m, filepath, encryptP)) {
	rhizome_manifest_free(m);
	rhizome_direct_clear_temporary_files(r);
	return rhizome_server_simple_http_response(r,500,"Could not bind manifest to file");
      }      
      if (rhizome_manifest_finalise(m)) {
	rhizome_manifest_free(m);
	rhizome_direct_clear_temporary_files(r);
	return rhizome_server_simple_http_response(r,500,
						   "Could not finalise manifest");
      }
      if (rhizome_add_manifest(m,255 /* TTL */)) {
	rhizome_manifest_free(m);
	rhizome_direct_clear_temporary_files(r);
	return rhizome_server_simple_http_response(r,500,
						   "Add manifest operation failed");
      }
            
      DEBUGF("Import sans-manifest appeared to succeed");
      
      /* Respond with the manifest that was added. */
      rhizome_server_simple_http_response(r, 200, (char *)m->manifestdata);

      /* clean up after ourselves */
      rhizome_manifest_free(m);
      rhizome_direct_clear_temporary_files(r);

      return 0;
      break;
    default:
      /* Clean up after ourselves */
      rhizome_direct_clear_temporary_files(r);	     
      
      return rhizome_server_simple_http_response(r, 400, "Rhizome create bundle from file API requires 'data' field");     
    }
  }  

  /* Clean up after ourselves */
  rhizome_direct_clear_temporary_files(r);	     
  /* Report error */
  return rhizome_server_simple_http_response(r, 500, "Something went wrong.  Probably a missing data or manifest part, or invalid combination of URI and data/manifest provision.");

}
Ejemplo n.º 16
0
int rhizome_direct_process_mime_line(rhizome_http_request *r,char *buffer,int count)
{
  /* Check for boundary line at start of buffer.
     Boundary line = CRLF + "--" + boundary_string + optional whitespace + CRLF
     EXCEPT end of form boundary, which is:
     CRLF + "--" + boundary_string + "--" + CRLF

     NOTE: We attach the "--" to boundary_string when setting things up so that
     we don't have to keep manually checking for it here.

     NOTE: The parser eats the CRLF from the front, and attaches it to the end
     of the previous line.  This means we need to rewind 2 bytes from whatever
     file we were writing to whenever we encounter a boundary line, at least
     if those last two bytes were CRLF. That can be safely assumed if we
     assume that the boundary string has been chosen to be a string never appearing
     anywhere in the contents of the form.  In practice, that is only "almost
     certain" (according to the mathematical meaning of that phrase) if boundary
     strings are randomly selected and are of sufficient length.
   
     NOTE: We are not supporting nested/mixed parts, as that would considerably
     complicate the parser.  If the need arises in future, we will deal with it
     then.  In the meantime, we will have something that meets our immediate
     needs for Rhizome Direct and a variety of use cases.
  */

  /* Regardless of the state of the parser, the presence of boundary lines
     is significant, so lets just check once, and remember the result.
     Similarly check a few other conditions. */
  int boundaryLine=0;
  if (!memcmp(buffer,r->boundary_string,r->boundary_string_length))
    boundaryLine=1;

  int endOfForm=0;
  if (boundaryLine&&
      buffer[r->boundary_string_length]=='-'&&
      buffer[r->boundary_string_length+1]=='-')
    endOfForm=1;
  int blankLine=0;
  if (!strcmp(buffer,"\r\n")) blankLine=1;

  switch(r->source_flags) {
  case RD_MIME_STATE_INITIAL:
    if (boundaryLine) r->source_flags=RD_MIME_STATE_PARTHEADERS;
    break;
  case RD_MIME_STATE_PARTHEADERS:
  case RD_MIME_STATE_MANIFESTHEADERS:
  case RD_MIME_STATE_DATAHEADERS:
    if (blankLine) {
      /* End of headers */
      if (r->source_flags==RD_MIME_STATE_PARTHEADERS)
	{
	  /* Multiple content-disposition lines.  This is very naughty. */
	  rhizome_server_simple_http_response
	    (r, 400, "<html><h1>Malformed multi-part form POST: Missing content-disposition lines in MIME encoded part.</h1></html>\r\n");
	  return -1;
	}
      
      /* Prepare to write to file for field.
	 We may have multiple rhizome direct transactions running at the same
	 time on different TCP connections.  So serialise using file descriptor.
	 We could use the boundary string or some other random thing, but using
	 the file descriptor places a reasonable upper limit on the clutter that
	 is possible, while still preventing collisions -- provided that we don't
	 close the file descriptor until we have completed processing the 
	 request. */
      r->field_file=NULL;
      char filename[1024];
      char *field="unknown";
      switch(r->source_flags) {
      case RD_MIME_STATE_DATAHEADERS: field="data"; break;
      case RD_MIME_STATE_MANIFESTHEADERS: field="manifest"; break;
      }
      snprintf(filename,1024,"rhizomedirect.%d.%s",r->alarm.poll.fd,field);
      filename[1023]=0;
      r->field_file=fopen(filename,"w");
      if (!r->field_file) {
	WHYF_perror("fopen(%s, \"w\")", alloca_str_toprint(filename));
	rhizome_direct_clear_temporary_files(r);
	rhizome_server_simple_http_response
	  (r, 500, "<html><h1>Sorry, couldn't complete your request, reasonable as it was.  Perhaps try again later.</h1></html>\r\n");
	return -1;
      }
      r->source_flags=RD_MIME_STATE_BODY;
    } else {
      char name[1024];
      char field[1024];
      if (sscanf(buffer,
		 "Content-Disposition: form-data; name=\"%[^\"]\";"
		 " filename=\"%[^\"]\"",field,name)==2)
	{
	  if (r->source_flags!=RD_MIME_STATE_PARTHEADERS)
	    {
	      /* Multiple content-disposition lines.  This is very naughty. */
	      rhizome_server_simple_http_response
		(r, 400, "<html><h1>Malformed multi-part form POST: Multiple content-disposition lines in single MIME encoded part.</h1></html>\r\n");
	      return -1;
	    }
	  if (!strcasecmp(field,"manifest")) 
	    r->source_flags=RD_MIME_STATE_MANIFESTHEADERS;
	  if (!strcasecmp(field,"data")) {
	    r->source_flags=RD_MIME_STATE_DATAHEADERS;
	    /* record file name of data field for HTTP manifest-less import */
	    strncpy(r->data_file_name,name,1023);
	    r->data_file_name[1023]=0;
	  }
	  if (r->source_flags!=RD_MIME_STATE_PARTHEADERS)
	    r->fields_seen|=r->source_flags;
	} 
    }
    break;
  case RD_MIME_STATE_BODY:
    if (boundaryLine) {
      r->source_flags=RD_MIME_STATE_PARTHEADERS;

      /* We will have written an extra CRLF to the end of the file,
	 so prune that off. */
      fflush(r->field_file);
      int fd=fileno(r->field_file);
      off_t correct_size=ftell(r->field_file)-2;
      ftruncate(fd,correct_size);
      fclose(r->field_file);
      r->field_file=NULL;
    }
    else {
      int written=fwrite(r->request,count,1,r->field_file);
      if (written<1) 
	DEBUGF("Short write for multi-part form file -- %d bytes may be missing",
	       count);
    }
    break;
  }

  if (endOfForm) {
    /* End of form marker found. 
       Pass it to function that deals with what has been received,
       and will also send response or close the http request if required. */

    /* XXX Rewind last two bytes from file if open, and close file */

    return rhizome_direct_form_received(r);
  }
  return 0;
}