-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_server.h
More file actions
124 lines (85 loc) · 2.33 KB
/
http_server.h
File metadata and controls
124 lines (85 loc) · 2.33 KB
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
#ifndef HTTP_SERVER_H
#define HTTP_SERVER_H
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdarg.h>
#include <memory>
#include <fstream>
#include <vector>
#define DEFAULT_VERBOSITY 1
#define CLOSE_CONNECTION 0
#define QUITE_PROGRAM 1
#define INVALID_RESPONSE_STRING "HTTP/1.1 %s\r\n\r\n"
#define VALID_RESPONSE_STRING "HTTP/1.1 %s\r\ncontent-type: %s\r\ncontent-length: %lu\r\n\r\n"
#define RESPONSE_400 "400 Bad Request"
#define RESPONSE_404 "404 File Not Found"
#define RESPONSE_200 "200 OK"
#define CONTENT_TEXT "text/html"
#define CONTENT_IMAGE "image/jpeg"
#define DEFAULT_RESPONSE_SIZE sizeof(VALID_RESPONSE_STRING) + sizeof(RESPONSE_200) + sizeof(CONTENT_IMAGE)
#define BUFFER_SIZE 32768
#define MIN_HTTP_REQUEST 16
/*
* HELPER CLASSES
*/
class Logger {
public:
Logger(int verbosity = 1);
void info(const int level, const std::string &msg);
void error(const int level, const std::string &msg);
void info(const int level, const char *format , ... );
void error(const int level, const char *format , ... );
private:
const int VERBOSITY_LEVEL;
};
class http_response {
public:
http_response() = default;
explicit http_response(int code);
size_t bytes = 0;
std::unique_ptr<char[]> buffer;
enum content_type {
TEXT, BINARY, IMAGE
};
void build_response(int code, char *data, size_t bytes, content_type type);
void build_response(int code);
private:
};
/*
* SOCKET CLASSES
*/
class TcpServer {
public:
TcpServer(std::shared_ptr<Logger> lggr);
~TcpServer();
void accept_connections();
int bind_port ();
protected:
virtual int on_connection_ (int fd) = 0;
std::shared_ptr<Logger> logger_;
int fd_;
};
class TcpEcho : public TcpServer {
public:
TcpEcho(std::shared_ptr<Logger>& lggr);
protected:
virtual int on_connection_ (int fd) override;
};
class HttpServer : public TcpServer {
public:
HttpServer(std::shared_ptr<Logger>& lggr);
private:
virtual int on_connection_ (int fd) override;
http_response parse_http_ (char* buff, size_t bytes);
http_response on_get_ (char* filename, size_t size);
bool verify_name_ (char* filename, size_t size);
};
#endif