summaryrefslogtreecommitdiff
path: root/src/ClientConnection.cpp
blob: 6a0670c5ef3c51cf55d1a75bcdb9f7b5d513ee2e (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
#include "ClientConnection.h"

#include <cstring>
#include <iostream>
#include <sstream>
#include <unistd.h>

ClientConnection::ClientConnection(int socket)
	: m_socket_fd(socket)
{
}

HttpRequest ClientConnection::read_request()
{
	// TODO: Clean up this code to ensure it works with multiple lines
	//       and not risk a buffer overflow.
	constexpr int BUFFER_SIZE = 4096;
	char buffer[BUFFER_SIZE + 1];
	int n;

	memset(buffer, 0, BUFFER_SIZE);
	while ((n = read(m_socket_fd, buffer, BUFFER_SIZE - 1)) > 0) {
		if (buffer[n - 1] == '\n')
			break;

		memset(buffer, 0, BUFFER_SIZE);
	}

	return HttpRequest(buffer);
}

bool ClientConnection::send(const HttpResponse& response)
{
	if (!m_is_open)
		return false;

	std::string result = response.to_string();
	write(m_socket_fd, result.c_str(), result.length());

	return true;
}

void ClientConnection::close_connection()
{
	m_is_open = false;
	close(m_socket_fd);
}