/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/socket.h>
#include <netdb.h>
#include <unixio.h>
#include <errno.h>

#define HOST "localhost"
#define PORT "12345"

void format_header(char *head,
                   const char *method,
                   const char *path,
                   const char *host,
                   const char *contyp,
                   int bodylen,
                   const char *acctyp)
{
   sprintf(head, "%s %s HTTP/1.1\r\n"
                 "Host: %s\r\n"
                 "Content_encoding: 8bit\r\n"
                 "Content-Type: %s\r\n"
                 "Content-Length: %d\r\n"
                 "Accept-Type: %s\r\n"
                 "Connection: close\r\n"
                 "\r\n", method, path, host, contyp, bodylen, acctyp);
}

/* not super efficient to receive 1 char at a time, but it avoids a buffer */
int recv_line(int sd, char *inmsg, int inmsglen)
{
    int ix, len;
    ix = 0;
    inmsg[ix] = '\0';
    while(ix < inmsglen && strstr(inmsg, "\n") == NULL)
    {
        len = recv(sd, inmsg + ix, 1, 0);
        if(len == 0)
        {
            if(strlen(inmsg) == 0)
            {
                return -1;
            }
            else
            {
                break;
            }
        }
        ix = ix + len;
        inmsg[ix] = 0;
    }
    while(ix > 0 && (inmsg[ix - 1] == '\n' || inmsg[ix - 1] == '\r'))
    {
        inmsg[ix - 1] = 0;
        ix--;
    }
    return ix;
}

void skip_head(int sd, int *numcode)
{
   char buf[1000];
   recv_line(sd, buf, sizeof(buf));
   sscanf(buf + 9, "%d", numcode);
   do
   {
      recv_line(sd, buf, sizeof(buf));
   } while(strlen(buf) > 0);
}

void test(const char *host, const char *port, const char *path)
{
    int sd, stat, code;
    char head[1000], *outmsg, inmsg[100];
    struct addrinfo hints, *res;
    /* lookup host */
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = 0;
    stat = getaddrinfo(host, port, &hints, &res);
    if(stat != 0)  printf("getaddrinfo stat=%d\n", stat);
    /* create socket */
    sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if(sd < 0) printf("socket stat=%d (%s)\n", errno, strerror(errno));
    /* connect to host */
    stat = connect(sd, res->ai_addr, res->ai_addrlen);
    if(stat != 0) printf("connect stat=%d (%s)\n", errno, strerror(errno));
    /* write request message */
    outmsg = "Hi from C (direct socket)!\r\n";
    format_header(head, "POST", path, host, "text/plain", strlen(outmsg), "*/*");
    stat = send(sd, head, strlen(head), 0);
    if(stat < 0) printf("send stat=%d (%s)\n", errno, strerror(errno));
    stat = send(sd, outmsg, strlen(outmsg), 0);
    if(stat < 0) printf("send stat=%d (%s)\n", errno, strerror(errno));
    /* read response message */
    skip_head(sd, &code);
    if(code == 200)
    {
        while(recv_line(sd, inmsg, sizeof(inmsg)) >= 0)
        {
            printf("%s\n", inmsg);
        }
    }
    else
    {
        printf("HTTP error : %d\n", code);
    }
    /* close socket */
    close(sd);
}

int main()
{
    test("localhost", "12345", "/");
    test("localhost", "12346", "/");
    return 0;
}
