#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>

#define K	1024

#define min(a,b)	((a) < (b)? (a) : (b))

struct url {
  char *host;
  uint16_t port;
  char *path;
};

/*
 * wget.c: 10 points
 *   A program to connect to a server and receive data into a file.
 */

/*
 * http://<host>[:<port>][/<path>]
 */
struct url *processurl(char *str)
{
  static struct url *u;
  char buf[K], *s;
  int i;

  if (strncasecmp("http://", str, 7) != 0)
    return NULL;
  
  u = malloc(sizeof(struct url));
  for(s = str+7, i=0; (*s && *s != ':' && *s != '/'); i++)
    buf[i] = *s++;
  buf[i] = '\0';
  u->host = strdup(buf);

  if (*s == ':') {
    u->port = (uint16_t)atoi(++s);
    while (*s && *s != '/') s++;
  } else u->port = 80;

  if (*s == '/') u->path = strdup(s);
  else u->path = strdup("/");

  return u;
}

void freeurl(struct url *u)
{
  free(u->host);
  free(u->path);
  free(u);
}

FILE *webopen(struct url *u)
{
  struct sockaddr_in server;
  struct hostent *he;
  FILE *sock;
  int sfd;

  // Create a SOCK_STREAM internet socket:
  if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("socket");
    return NULL;
  }

  // Setup the severs address, use gethostbyname() to get the address:
  server.sin_family = AF_INET;
  if ((he = gethostbyname(u->host)) == NULL) {
    fprintf(stderr,"Unknown host: %s\n", u->host);
    return NULL;
  }
  memcpy(&server.sin_addr, he->h_addr, he->h_length);
  server.sin_port = htons(u->port);

  // Use connect() to connect to the server:
  if (connect(sfd, (struct sockaddr *)&server, sizeof(server)) < 0) {
    perror("connect");
    return NULL;
  }
  if ((sock = fdopen(sfd, "r+")) == NULL) {
    perror("fdopen()");
    return NULL;
  }
  return sock;
}

struct url *getheader(FILE *sock, int *status, int *clen)
{
  char buf[K], *s;
  struct url *u = NULL;
  int i =0;
  
  *clen = -1;

  while(fgets(buf, K, sock) != NULL) {
    s = strtok(buf, " \r\n");
    if (s == NULL) break;
    if (strncasecmp(s,"HTTP/1.1",8) == 0) {
      s = strtok(NULL, " \r\n");
      if (s) *status = atoi(s);
    } else if (strncasecmp(s,"Location:",9) == 0) {
      s = strtok(NULL, "\r\n");
      if (s) u = processurl(s);
    } else if (strncasecmp(s,"Content-Length:", 15) == 0) {
      if (*clen == -2) continue;
      s = strtok(NULL, " \r\n");
      if (s) *clen = atoi(s);
    } else if (strncasecmp(s,"Transfer-Encoding:", 18) == 0) {
      s = strtok(NULL, " \r\n");
      if (s && strncasecmp(s,"chunked", 7) == 0) *clen = -2;
    }

  }
  return u;
}

int readchunk(FILE *sock, int fd, int len)
{
  char buf[K];
  int w;

  do {
    w = fread(buf, 1, min(K,len), sock);
    if (w == 0) return -1;
    if ((w = write(fd, buf, w)) == 0) return -1;
    len -= w;
  } while (len > 0);
  return len;
}


void save(FILE *sock, char *file, int clen)
{
  char buf[K];
  int fd, w = 0;

  // Use open to open the file specified by argv[2] for writing, create the
  // file if it doesn't exist and truncate the file if it does.
  // Print an error message and exit if the open fails.
  if ((fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) {
    perror("open");
    exit(1);
  }

  switch(clen) {
    case -2:
      do {
	if (fgets(buf, K, sock) == NULL) break;
	clen = strtol(buf,NULL, 16);
	if (clen == 0) break;
	readchunk(sock, fd, clen);
	if (fgets(buf,K,sock) == NULL) break; // eats newline at end of chunk
      } while (!feof(sock) && !ferror(sock));
      break;
    case -1:
      do {
	w = fread(buf, 1, K, sock);
	if (w == 0) break;
	if ((w = write(fd, buf, w)) == 0) break;
      } while (!feof(sock) && !ferror(sock));
      break;
    default:
      readchunk(sock, fd, clen);
      break;
  }
  close(fd);
}

int main(int argc, char *argv[])
{
  struct url *u;
  FILE *sock;
  char buf[K];
  int fd, r, n, status, clen;

  if (argc < 3) {
    fprintf(stderr,"Usage: wget <URL> <filename>\n");
    return 0;
  }

  u = processurl(argv[1]);

  do {
    if ((sock = webopen(u)) == NULL) exit(1);

    fprintf(sock, "GET %s HTTP/1.1\nHost: %s\n\n", u->path, u->host);
    freeurl(u);

    u = getheader(sock, &status, &clen);
    if (status == 404) {
      fprintf(stderr,"Error 404 File not found.\n");
      break;
    }
    if (status == 200) save(sock, argv[2], clen);
    fclose(sock);
  } while(u);

  return 0;
}

/*

Example OK (200) header:
=======================
HTTP/1.1 200 OK
Date: Mon, 15 Feb 2016 18:34:30 GMT
Server: Apache/2.4.17 (Unix) OpenSSL/1.0.2f PHP/5.6.17
Last-Modified: Tue, 02 Feb 2016 21:27:46 GMT
ETag: "a88-52ad02c32abea"
Accept-Ranges: bytes
Content-Length: 2696
Content-Type: text/html

Example redirect (302) header:
=============================
HTTP/1.1 302 Found
Date: Mon, 15 Feb 2016 18:31:11 GMT
Server: Apache/2.4.17 (Unix) OpenSSL/1.0.2f PHP/5.6.17
X-Powered-By: PHP/5.6.17
Location: http://cs.indstate.edu/info/
Content-Length: 0
Content-Type: text/html; charset=UTF-8

Chunked transfer header:
=======================
HTTP/1.1 200 OK
Date: Tue, 16 Feb 2016 17:35:16 GMT
Server: Apache/2.4.17 (Unix) OpenSSL/1.0.2f PHP/5.6.17
Accept-Ranges: bytes
Transfer-Encoding: chunked
Content-Type: text/html

297a
...

*/
