-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathDomainStream.h
More file actions
75 lines (60 loc) · 1.87 KB
/
DomainStream.h
File metadata and controls
75 lines (60 loc) · 1.87 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
#ifndef DOMAINSTREAM_H
#define DOMAINSTREAM_H
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdexcept>
class DomainStream {
public:
DomainStream(const std::string &filename) {
fd = open(filename.c_str(), O_CREAT | O_LARGEFILE | O_TRUNC | O_WRONLY, 0644);
if(fd < 0) throw std::runtime_error("could not open " + filename + ": " + strerror(errno));
outBufferFill = outBuffer;
}
~DomainStream() {
flush();
close(fd);
}
void handleRequest(const std::string &hostname, const char *b, const char *e) {
buffer("==== PnRaIMfLIPytQUqGtmbDfHOtyOfdPJSgawuCgSjvQKUOGJgOqgkrEgLGUQsAcqJD ====\nhttp://", 82);
buffer(hostname.c_str(), hostname.length());
buffer(b, e - b);
buffer("\n", 1);
}
void handleLine(const char *b, const char *e) {
buffer(b, e - b);
}
private:
static const int BUFFER_SIZE = 1024 * 512;
int fd;
char outBuffer[BUFFER_SIZE];
char *outBufferFill;
void buffer(const char *s, int len) {
buffer(s, s + len);
}
void buffer(const char *b, const char *e) {
if(e - b > BUFFER_SIZE - (outBufferFill - outBuffer)) flush();
if(e - b > BUFFER_SIZE) {
while(b != e) {
int len = write(fd, b, e - b);
if(len <= 0) throw std::runtime_error("write failed in weird way, 2" + std::string(strerror(errno)));
b += len;
}
} else {
memcpy(outBufferFill, b, e - b);
outBufferFill += e - b;
}
}
void flush() {
const char *pos = outBuffer;
while(pos != outBufferFill) {
int len = write(fd, pos, outBufferFill - pos);
if(len <= 0) throw std::runtime_error("write failed in weird way, 3" + std::string(strerror(errno)));
pos += len;
}
outBufferFill = outBuffer;
}
};
#endif