aboutsummaryrefslogtreecommitdiff
path: root/src/http_server.cpp
blob: cc8e3b44567df8f482719123e61c4b1f9b98ef24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#include <sstream>
#include <ws2tcpip.h>

#include "http_server.h"
#include "ns_plugin.h"

#define BUFFER_SIZE 128
#define HTTP_LF "\r\n"
#define BODY_SEP HTTP_LF HTTP_LF

HTTPRequest::HTTPRequest(SOCKET socket):
    socket(socket)
{
}

HTTPRequest::~HTTPRequest()
{
    this->close();
}

size_t HTTPRequest::content_length()
{
    auto& map = this->headers;
    header_map::const_iterator pos = map.find("Content-Length");
    if (pos == map.end())
        return 0;

    size_t result;
    std::istringstream sstream(pos->second);
    sstream >> result;

    return result;
}

void HTTPRequest::parse_headers(std::string raw)
{
    // @TODO validate first line for correct method and path
    std::istringstream iss(raw);

    for (std::string line; std::getline(iss, line, HTTP_LF[1]); )
    {
        if (line[line.size()-1] != HTTP_LF[0])
            break;

        line = line.substr(0, line.size()-1);
        if (line.empty())
            break;

        std::string::size_type sep_pos = line.find(":");

        if (line.size() <= sep_pos)
            continue;

        std::string key = line.substr(0, sep_pos);
        std::string value = line.substr(sep_pos+1);

        this->headers.try_emplace(key, value);
    }
}

void HTTPRequest::respond(std::string status_code, header_map response_headers, std::string response_body)
{
    if (this->socket == -1)
    {
        spdlog::error("Attempted to send response when socket is already closed");
        return;
    }

    std::ostringstream response;

    response << "HTTP/1.1 " << status_code << HTTP_LF;

    for (auto const& [key, val] : response_headers)
    {
        response << key << ": " << val << HTTP_LF;
    }

    response << HTTP_LF << response_body;

    std::string response_data = response.str(); 
    send(this->socket, response_data.c_str(), response_data.size(), 0);
}

void HTTPRequest::close()
{
    if (this->socket != -1)
    {
        closesocket(this->socket);
        this->socket = -1;
    }
}

HTTPServer::HTTPServer(unsigned long addr, unsigned short port)
{
    this->sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET)
    {
        spdlog::error("Failed to create socket");
        return;
    }

    struct sockaddr_in local = { 0 };
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = addr;
    local.sin_port = htons(port);

    if (bind(this->sock, (struct sockaddr*)&local, sizeof(local)) == SOCKET_ERROR)
    {
        spdlog::error("Failed to bindsocket ({})", WSAGetLastError());
        this->close();
        return;
    }

    if (listen(this->sock, 10) == SOCKET_ERROR)
    {
        spdlog::error("Failed to listen to socket");
        this->close();
        return;
    }

    spdlog::info("Initialized HTTPServer");
}

HTTPServer::~HTTPServer()
{
    this->close();
}

void HTTPServer::close()
{
    if (this->sock != -1)
    {
        closesocket(this->sock);
        this->sock = -1;
    }
}

HTTPRequest* HTTPServer::receive_request()
{
    if (this->sock == -1)
    {
        spdlog::error("Attempted to receive request without running web server");
        return nullptr;
    }

    struct sockaddr_in addr;
    int addr_len = sizeof(addr);

    spdlog::debug("awaiting HTTP request");

    SOCKET msg = accept(this->sock, (struct sockaddr*)&addr, &addr_len);
    if (msg == INVALID_SOCKET || msg == -1)
    {
        spdlog::error("Failed to receive packet ({})", WSAGetLastError());
        return nullptr;
    };

    spdlog::info("Connection opened by {}", inet_ntoa(addr.sin_addr));

    std::string content;
    char buffer[BUFFER_SIZE];
    memset(buffer, 0, sizeof(buffer));

    bool parsed_header = false;
    std::string::size_type header_end;
    std::string::size_type expected_size;
    HTTPRequest* req = new HTTPRequest(msg);
    do
    {
        spdlog::debug("receiving buffer");
        int len = recv(msg, buffer, BUFFER_SIZE-1, 0);
        spdlog::debug("received buffer ({})", len);

        if (len == SOCKET_ERROR || len == 0)
            break;

        buffer[len] = '\0';

        content += buffer;

        if (!parsed_header && strstr(buffer, BODY_SEP))
        {
            parsed_header = true;
            req->parse_headers(content);

            header_end = content.find(BODY_SEP);
            expected_size = header_end + req->content_length() + strlen(BODY_SEP);
            spdlog::debug("Expecting size {}", expected_size);
        }

        if (parsed_header)
        {
            if (expected_size <= content.length())
            {
                req->set_body(content.substr(header_end+strlen(HTTP_LF)));
                break;
            }
        }
    }
    while(1);

    if (content.empty())
    {
        spdlog::error("Received no data ({})", WSAGetLastError());
        delete req;
        return nullptr;
    }

    spdlog::debug("Received Data ({})", content.length());

    return req;
}