#include "http.hpp"
#include "common.hpp"


bool http_connect(int fd, const char* fdstr, const char* dst) {
    static char httpbuf[4096];
    int len = sprintf(httpbuf,
        "CONNECT %s HTTP/1.1\r\n"
        "Host: %s\r\n"
#ifdef USER_AGENT
        "User-Agent: " USER_AGENT "\r\n"
#endif
        "\r\n",
        dst, dst
    );
    if (write(fd, httpbuf, len) != len) {
        LOG_ERRNO("cannot send CONNECT to %s (for %s)", fdstr?:"-", dst);
        return false;
    }

    len = read(fd, httpbuf, sizeof(httpbuf));
    if (len == -1) {
        LOG_ERRNO("cannot read CONNECT reply from %s (for %s)", fdstr?:"-", dst);
        return false;
    }
    if (len < (int)sizeof("HTTP/1.1 200 ")-1 ||
        len >= (int)sizeof(httpbuf) ||
        (strncmp(httpbuf, "HTTP/1.1 200 ", sizeof("HTTP/1.1 200 ")-1) != 0 && strncmp(httpbuf, "HTTP/1.0 200 ", sizeof("HTTP/1.0 200 ")-1) != 0)) {
        int plen = 0;
        while (plen < 16 && httpbuf[plen] >= ' ' && httpbuf[plen] <= '~') ++plen;
        LOG("cannot parse CONNECT reply from %s (for %s) [#%d: '%.*s']", fdstr?:"-", dst, len, plen, httpbuf);
        return false;
    }
    httpbuf[len] = '\0';
    if (strstr(httpbuf, "\r\n\r\n") != httpbuf+len-4 && strstr(httpbuf, "\n\n") != httpbuf+len-2) {
        LOG("CONNECT reply unfinished from %s (for %s) [%d]", fdstr?:"-", dst, len);
        return false; // TODO: parse and re-read if no nlnl
    }
    return true;
}