-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.cpp
84 lines (72 loc) · 1.91 KB
/
server.cpp
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
#include <sys/types.h>
#include <sys/time.h>
#include <sys/queue.h>
#include <stdlib.h>
#include <err.h>
#include <event.h>
#include <evhttp.h>
#include <fstream>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
typedef struct {
int port;
string folder;
} config;
int getPort() {
ifstream fs("config");
config ret;
fs >> ret.port;
fs >> ret.folder;
return ret.port;
}
string getFolder() {
ifstream fs("config");
config ret;
fs >> ret.port;
fs >> ret.folder;
return ret.folder;
}
void generic_handler(struct evhttp_request *req, void *arg) {
struct evbuffer *buf;
const char* s = evhttp_request_get_uri(req);
struct stat st;
buf = evbuffer_new();
int fd = -1;
string folder = getFolder();
string fullpath = folder.append(s);
if (fullpath[fullpath.length()-1] == '/') {
fullpath+="index.html";
}
cout << fullpath << endl;
if ((fd = open(fullpath.c_str(), O_RDONLY)) < 0) {
evhttp_send_error(req, 404, "Not found");
}
if (fstat(fd, &st)<0) {
/* Make sure the length still matches, now that we
* opened the file :/ */
evhttp_send_error(req, 404, "Not found");
}
if (buf == NULL)
err(1, "failed to create response buffer");
evbuffer_add_file(buf, fd, 0, st.st_size);
evhttp_send_reply(req, HTTP_OK, "OK", buf);
cout << fd << endl;
evbuffer_free(buf);
}
int main(int argc, char **argv) {
struct evhttp *httpd;
event_init();
int port = getPort();
httpd = evhttp_start("127.0.0.1", port);
// cout << conf.folder << endl;
/* Set a callback for requests to "/specific". */
/* evhttp_set_cb(httpd, "/specific", another_handler, NULL); */
/* Set a callback for all other requests. */
evhttp_set_gencb(httpd, generic_handler, NULL);
event_dispatch(); /* Not reached in this code as it is now. */
evhttp_free(httpd);
return 0;
}