This repository has been archived by the owner on Jun 19, 2021. It is now read-only.
/
client.cpp
444 lines (416 loc) · 11.7 KB
/
client.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
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <iostream>
#include "cache.h"
#include "client.h"
static const std::string ERROR_MESSAGE_502 = "HTTP/1.0 502 Bad Gateway\r\n\
\r\n<html><head><title>502 Bad Gateway</title></head> \
<body><h2>502 Bad Gateway</h2><h3>Host not found or connection failed.</h3></body></html>\r\n";
static const std::string ERROR_MESSAGE_505 = "HTTP/1.0 505 HTTP Version not supported\r\n\
\r\n<html><head><title>505 HTTP Version not supported</title></head> \
<body><h2>505 HTTP Version not supported</h2><h3>Proxy server does not support the HTTP protocol version used in the request.</h3></body></html>\r\n";
static const std::string ERROR_MESSAGE_405 = "HTTP/1.0 405 Method Not Allowed\r\n\
\r\n<html><head><title>405 Method Not Allowed</title></head> \
<body><h2>405 Method Not Allowed</h2><h3>Proxy server does not support the HTTP method used in the request.</h3></body></html>\r\n";
static const std::string ERROR_MESSAGE_414 = "HTTP/1.0 414 Request-URL Too Long\r\n\
\r\n<html><head><title>414 Request-URL Too Long</title></head> \
<body><h2>414 Request-URL Too Long</h2><h3>The URL provided was too long for the server to process.</h3></body></html>\r\n";
static const std::string ERROR_MESSAGE_500 = "HTTP/1.0 500 Internal Server Error\r\n\
\r\n<html><head><title>500 Internal Server Error</title></head> \
<body><h2>500 Internal Server Error</h2></body></html>\r\n";
static const std::string SUPPORT_VERSION = "HTTP/1.0";
Client::Client(Connection *conn) : client(conn), remote(NULL) {
cacheState = CACHE_NO_SET;
headStart = true;
if(client == NULL || !client->isOpen()) {
errorState = INTERNAL_ERROR;
return;
}
errorState = OK;
contentLen = -1;
recvedLen = 0;
headerLen = 0;
}
bool Client::alive() {
if(client == NULL) {
return false;
}
if(client->isOpen() && remote != NULL && remote->isOpen()) {
return true;
}
if(client->isOpen() && remote != NULL && remote->getAvaliable() > 0) {
return true;
}
if(client->isOpen() && cacheState == CACHE_READ && Cache::getCache()->get(url) != NULL) {
return true;
}
if(client->isOpen() && errorState != OK) {
return true;
}
if(client->isOpen() && url.empty() && cacheState == CACHE_NO_SET) {
return true;
}
if(client->isOpen()) {
return false;
}
if(remote != NULL && remote->isOpen() && cacheState == CACHE_WRITE) {
return true;
}
return false;
}
Client::~Client() {
if(cacheState == CACHE_READ && Cache::getCache()->get(url) != NULL) {
Cache::getCache()->get(url)->readFinish();
}
delete remote;
delete client;
}
ErrorState Client::getErrorState() const {
return errorState;
}
void Client::continueWork(pollfd *ufds) {
if(!alive()) {
return;
}
if(client != NULL && client->isOpen() && client->getSocket() == ufds->fd && ufds->revents != 0) {
continueClient(ufds);
return;
}
if(remote != NULL && remote->isOpen() && remote->getSocket() == ufds->fd && ufds->revents != 0) {
continueRemote(ufds);
}
}
void Client::continueClient(pollfd * ufds) {
short revent = ufds->revents;
CacheEntry *cache = Cache::getCache()->get(url);
if( (revent & (POLLIN | POLLOUT)) == 0) {
client->closeSocket();
return ;
}
if(revent & POLLOUT) {
if(errorState != OK) {
sendError();
client->closeSocket();
return;
} else if(cacheState == CACHE_READ && cache != NULL) {
client->sendData(cache->getData(), cache->getLength());
if(cache->getLength() == client->getWritten() && cache->isFinished()) {
client->closeSocket();
}
} else if(remote != NULL && remote->getAvaliable() > 0) {
client->sendData(remote->getBuffer(), remote->getAvaliable());
client->resetWritten();
remote->resetAvaliable();
}
}
if(revent & POLLIN) {
client->recvData();
if(strstr(client->getBuffer(), "GET http://www.linux.org.ru/news/hardware/8497632")) {
int i = 5;
}
if(cacheState == CACHE_NO_SET && remote == NULL && url.empty() && errorState == OK) {
connectToRemote(client->getBuffer());
if(remote != NULL) {
//client->catBuf();
}
}
}
}
void Client::continueRemote(pollfd * ufds) {
short revent = ufds->revents;
if( (revent & (POLLIN | POLLOUT)) == 0) {
remote->closeSocket();
return ;
}
if(revent & POLLOUT) {
if(cacheState == CACHE_NO_SET && headStart) {
std::cerr<<client->getBuffer()<<std::endl;
client->setAvaliable(processHeaderCL(client->getBuffer(), client->getAvaliable()));
std::cerr<<client->getBuffer()<<std::endl;
}
remote->sendData(client->getBuffer(), client->getAvaliable());
remote->resetWritten();
client->resetAvaliable();
}
if(revent & POLLIN) {
int tmpr = remote->recvData();
if(tmpr > 0) {
recvedLen += tmpr;
}
if(cacheState == CACHE_NO_SET && headStart) {
std::cerr<<remote->getBuffer()<<std::endl;
headStart = false;
std::stringstream ss;
remote->getBuffer()[7] = '0';
ss<<remote->getBuffer();
std::string protocol;
int code = 0;
ss>>protocol>>code;
if(/*protocol.compare("HTTP/1.0") == 0 && */code == 200 && processHeader(remote->getBuffer()) == 0) {
if(contentLen >= 0 && contentLen <= 5*1024*1024) {
cacheState = CACHE_WRITE;
}
recvedLen -= headerLen;
}
}
if(contentLen >= 0 && contentLen <= recvedLen) {
remote->closeSocket();
}
if(cacheState == CACHE_WRITE) {
Cache::getCache()->put(url, remote->getBuffer(), remote->getAvaliable());
if(!remote->isOpen()) {
Cache::getCache()->get(url)->setFinished();
return;
}
if(client == NULL || !client->isOpen()) {
remote->resetAvaliable();
if(!Cache::getCache()->get(url)->isReaded()) {
remote->closeSocket();
Cache::getCache()->remove(url);
std::cout<<"remove cache "<<url<<std::endl;
}
}
}
}
}
void Client::sendError() {
switch(errorState) {
case CONNECT_ERROR:
client->sendData(ERROR_MESSAGE_502.c_str(), ERROR_MESSAGE_502.length());
break;
case UNSUPPORTED_VERSION:
client->sendData(ERROR_MESSAGE_505.c_str(), ERROR_MESSAGE_505.length());
break;
case LONG_URL:
client->sendData(ERROR_MESSAGE_414.c_str(), ERROR_MESSAGE_414.length());
break;
case INTERNAL_ERROR:
client->sendData(ERROR_MESSAGE_500.c_str(), ERROR_MESSAGE_500.length());
break;
case UNSUPPORTED_METHOD:
client->sendData(ERROR_MESSAGE_405.c_str(), ERROR_MESSAGE_405.length());
break;
}
}
size_t Client::setEventRequest(pollfd *ufds) {
if(!alive()) {
return 0;
}
size_t cn = 0;
size_t rn = 0;
if(client != NULL && client->isOpen()) {
ufds[0].fd = client->getSocket();
cn = 1;
if(remote == NULL && client->getAvaliable() < BUFSIZE) {
ufds[0].fd = client->getSocket();
ufds[0].events |= POLLIN;
cn = 1;
}
if((cacheState == CACHE_READ && Cache::getCache()->get(url)->getLength() > client->getWritten())
|| (remote != NULL && remote->getAvaliable() > 0)
|| errorState != OK) {
ufds[0].fd = client->getSocket();
ufds[0].events |= POLLOUT;
cn = 1;
}
}
if(remote != NULL && remote->isOpen()) {
ufds[cn].fd = remote->getSocket();
rn = 1;
if(remote->getAvaliable() < BUFSIZE) {
ufds[cn].fd = remote->getSocket();
ufds[cn].events |= POLLIN;
rn = 1;
}
if(client != NULL && client->getAvaliable() > 0) {
ufds[cn].fd = remote->getSocket();
ufds[cn].events |= POLLOUT;
rn = 1;
}
}
return cn + rn;
}
void Client::processRequest(const std::string &headStr, std::string &method, std::string &protocol, std::string &version, std::string &host, int &port) {
size_t res = headStr.find("\r\n");
if(res == std::string::npos) {
errorState = LONG_URL;
cacheState = CACHE_NO_SET;
return ;
}
port = 80;
std::stringstream ss;
ss << headStr.substr(0, res);
ss >> method >> url >> version;
res = url.find("://");
if(res != std::string::npos) {
protocol = url.substr(0, res);
}
res += 3;
size_t pslash = url.find("/", res);
size_t pport = url.find(':', res);
if (pport != std::string::npos && pport < pslash) {
host = url.substr(res, pport - res);
pport += 1;
std::string tmp = url.substr(pport, pslash - pport);
port = atoi(tmp.c_str());
} else if (res > 2) {
host = url.substr(res, pslash - res);
}
}
void Client::connectToRemote(const std::string &headStr) {
std::string method;
std::string protocol;
std::string version;
std::string host;
int port;
processRequest(headStr, method, protocol, version, host, port);
std::cout<<"try to connect :"<<url<<std::endl;
if(errorState != OK) {
return ;
}
if(protocol.compare("http") != 0) {
errorState = INTERNAL_ERROR;
cacheState = CACHE_NO_SET;
return;
}
if(method.compare("GET") != 0 && method.compare("HEAD") != 0) {
errorState = UNSUPPORTED_METHOD;
cacheState = CACHE_NO_SET;
std::cout<<method<<std::endl;
return;
}
if(version.compare(SUPPORT_VERSION) != 0) {
errorState = UNSUPPORTED_VERSION;
cacheState = CACHE_NO_SET;
return;
}
if(Cache::getCache()->get(url) != NULL) {
cacheState = CACHE_READ;
std::cout<<"route to cache"<<std::endl;
Cache::getCache()->get(url)->readStart();
return ;
}
std::cout<<"Connect to host: "<<host<<std::endl;
int s = -1;
sockaddr_in host_addr;
do {
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
break;
}
host_addr.sin_family = AF_INET;
if ((host_addr.sin_addr.s_addr = inet_addr(host.c_str())) == INADDR_NONE)
{
struct hostent *hp;
std::cout<<"ghbn"<<std::endl;
if ((hp = gethostbyname(host.c_str())) == NULL) {
std::cout<<"ghbn error"<<std::endl;
close(s);
s = -1;
break;
}
std::cout<<"ghbn end"<<std::endl;
host_addr.sin_family = hp->h_addrtype;
memcpy(&(host_addr.sin_addr), hp->h_addr, hp->h_length);
} else {
host_addr.sin_family = AF_INET;
}
host_addr.sin_port = htons(port);
if (connect(s, (struct sockaddr *)&host_addr, sizeof(host_addr)) < 0) {
close(s);
break;
}
} while(0);
if(s < 0) {
errorState = CONNECT_ERROR;
cacheState = CACHE_NO_SET;
return ;
}
remote = new Connection(s);
errorState = OK;
cacheState = CACHE_NO_SET;
std::cout<<"remote connected "<<url<<" on port "<<port<<" (socket "<<s<<" )"<<std::endl;
}
Connection * Client::getClient() {
return client;
}
Connection * Client::getRemote() {
return remote;
}
std::string Client::getURL() const {
return url;
}
void Client::remoteError() {
if(remote == NULL) {
return ;
}
remote->forceClose();
if(cacheState == CACHE_WRITE) {
//Cache::getCache()->remove(url);
}
if(client != NULL) {
client->forceClose();
}
}
void Client::clientError() {
if(client == NULL) {
return ;
}
client->forceClose();
}
int Client::processHeader(char *header) {
char *endStr = strstr(header, "\r\n\r\n");
if(endStr == NULL) {
return -1;
}
endStr += 4;
headerLen = endStr - header;
char *lenStr = strstr(header, "Content-Length: ");
if(lenStr != NULL) {
lenStr += 16;
contentLen = atoi(lenStr);
}
return 0;
}
int Client::processHeaderCL(char *header, size_t len) {
//{
char *startUrl = strstr(header, "http://");
if(startUrl == NULL) {
return len;
}
char *endUrl = strstr(startUrl, " ");
if(endUrl == NULL) {
return len;
}
char *startUri = strstr(startUrl + strlen("http://"), "/");
if(startUri == NULL) {
startUrl[0] = '/';
memmove(startUrl+1, endUrl, len - (endUrl - header));
len -= endUrl - startUrl - 1;
} else {
memmove(startUrl, startUri, len - (startUri - header));
len -= startUri - startUrl;
}
//header[len] = 0;
//}
char *ad = "Proxy-Connection:";
char *end = strstr(header, ad);
if(end == NULL) {
return len;
}
char *end2 = strstr(end, "\r\n");
if(end2 == NULL) {
return len;
}
end2 += 2;
memmove(end, end2, len - (end2 - header));
return len - (end2 - end);
}