#include "extreme.h"

char *esock_read(int sockfd) {
  int got, pos = 0;
  char *buffer;

  if ((buffer = malloc(BUFLEN)) == NULL) {
    errno = ENOMEM;
    return NULL;
  }

  while ((got = read(sockfd, buffer + pos, BUFLEN)) == BUFLEN) {
    pos += got;
    if ((buffer = realloc(buffer, BUFLEN + pos + 1)) == NULL) {
      errno = ENOMEM;
      return NULL;
    }
  }
  pos += got;

  *(buffer + pos) = '\0';

  return (buffer);
}
