Repository navigation
Expand file tree
/
Copy pathhttp.cpp
More file actions
466 lines (439 loc) · 15.5 KB
/
Copy pathhttp.cpp
File metadata and controls
466 lines (439 loc) · 15.5 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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
#include "http.h"
#include <string.h>
#include <climits>
#include <algorithm>
#include <vector>
#include "utils.h"
//协议解析
static int accessable(const char *pathname)
{
return access(pathname, F_OK | R_OK);
}
void HttpRequest::tryDecode(const std::string &buf)
{
this->parseInternal(buf.c_str(), buf.size());
}
//解析请求行
void HttpRequest::parseInternal(const char *buf, int size)
{
StringBuffer method;
StringBuffer url;
StringBuffer requestParamKey;
StringBuffer requestParamValue;
StringBuffer protocol;
StringBuffer version;
StringBuffer headerKey;
StringBuffer headerValue;
int bodyLength = 0;
char *p0 = const_cast<char *>(buf + _nextPos); //去掉const限制
while (_decodeState != HttpRequestDecodeState::INVALID &&
_decodeState != HttpRequestDecodeState::INVALID_METHOD &&
_decodeState != HttpRequestDecodeState::INVALID_URI &&
_decodeState != HttpRequestDecodeState::INVALID_VERSION &&
_decodeState != HttpRequestDecodeState::INVALID_HEADER &&
_decodeState != HttpRequestDecodeState::COMPLETE &&
_nextPos < size) {
char ch = *p0; //当前的字符
char *p = p0++; //指针偏移
int scanPos = _nextPos++; //下一个指针往后偏移
switch (_decodeState) {
case HttpRequestDecodeState::START: {
//空格 换行 回车都继续
if (ch == CR || ch == LF || isblank(ch)) {
// do nothing
} else if (isupper(ch)) { //判断是不是大写字符,不是的话是无效的
method.begin = p; //方法的起始点
_decodeState = HttpRequestDecodeState::
METHOD; //如果遇到第一个字符,开始解析方法
} else {
_decodeState = HttpRequestDecodeState::INVALID;
}
break;
}
case HttpRequestDecodeState::METHOD: {
//方法需要大写字母,大写字母就继续
if (isupper(ch)) {
// do nothing
} else if (isblank(
ch)) { //空格,说明方法解析结束,下一步开始解析URI
method.end = p; //方法解析结束
_method = method;
_decodeState = HttpRequestDecodeState::BEFORE_URI;
} else {
_decodeState = HttpRequestDecodeState::
INVALID_METHOD; //其他情况是无效的请求方法
}
break;
}
case HttpRequestDecodeState::BEFORE_URI: {
//请求连接前的处理,需要'/'开头
if (ch == '/') {
url.begin = p;
_decodeState =
HttpRequestDecodeState::IN_URI; //下一步就是开始处理连接
} else if (isblank(ch)) {
// do nothing
} else {
_decodeState = HttpRequestDecodeState::INVALID; //无效的
}
break;
}
case HttpRequestDecodeState::IN_URI: {
//开始处理请求路径的字符串
if (ch == '?') { //转为处理请求的key值
url.end = p;
_url = url;
_decodeState = HttpRequestDecodeState::BEFORE_URI_PARAM_KEY;
} else if (isblank(
ch)) { //遇到空格,请求路径解析完成,开始解析协议
url.end = p;
_url = url;
_decodeState = HttpRequestDecodeState::BEFORE_PROTOCOL;
} else {
// do nothing
}
break;
}
case HttpRequestDecodeState::BEFORE_URI_PARAM_KEY: {
if (isblank(ch) || ch == LF || ch == CR) {
_decodeState = HttpRequestDecodeState::INVALID_URI;
} else {
requestParamKey.begin = p;
_decodeState = HttpRequestDecodeState::URI_PARAM_KEY;
}
break;
}
case HttpRequestDecodeState::URI_PARAM_KEY: {
if (ch == '=') {
requestParamKey.end = p;
_decodeState = HttpRequestDecodeState::
BEFORE_URI_PARAM_VALUE; //开始解析参数值
} else if (isblank(ch)) {
_decodeState =
HttpRequestDecodeState::INVALID_URI; //无效的请求参数
} else {
// do nothing
}
break;
}
case HttpRequestDecodeState::BEFORE_URI_PARAM_VALUE: {
if (isblank(ch) || ch == LF || ch == CR) {
_decodeState = HttpRequestDecodeState::INVALID_URI;
} else {
requestParamValue.begin = p;
_decodeState = HttpRequestDecodeState::URI_PARAM_VALUE;
}
break;
}
case HttpRequestDecodeState::URI_PARAM_VALUE: {
if (ch == '&') {
requestParamValue.end = p;
//收获一个请求参数
_requestParams.insert({requestParamKey, requestParamValue});
_decodeState = HttpRequestDecodeState::BEFORE_URI_PARAM_KEY;
} else if (isblank(ch)) {
requestParamValue.end = p;
//空格也收获一个请求参数
_requestParams.insert({requestParamKey, requestParamValue});
_decodeState = HttpRequestDecodeState::BEFORE_PROTOCOL;
} else {
// do nothing
}
break;
}
case HttpRequestDecodeState::BEFORE_PROTOCOL: {
if (isblank(ch)) {
// do nothing
} else {
protocol.begin = p;
_decodeState = HttpRequestDecodeState::PROTOCOL;
}
break;
}
case HttpRequestDecodeState::PROTOCOL: {
//解析请求协议
if (ch == '/') {
protocol.end = p;
_protocol = protocol;
_decodeState = HttpRequestDecodeState::BEFORE_VERSION;
} else {
// do nothing
}
break;
}
case HttpRequestDecodeState::BEFORE_VERSION: {
if (isdigit(ch)) {
version.begin = p;
_decodeState = HttpRequestDecodeState::VERSION;
} else {
_decodeState = HttpRequestDecodeState::INVALID_VERSION;
}
break;
}
case HttpRequestDecodeState::VERSION: {
//协议解析,如果不是数字或者. 就不对
if (ch == CR) {
version.end = p;
_version = version;
_decodeState = HttpRequestDecodeState::WHEN_CR;
} else if (ch == '.') {
//遇到版本分割
_decodeState = HttpRequestDecodeState::VERSION_SPLIT;
} else if (isdigit(ch)) {
// do nothing
} else {
_decodeState =
HttpRequestDecodeState::INVALID_VERSION; //不能不是数字
}
break;
}
case HttpRequestDecodeState::VERSION_SPLIT: {
//遇到版本分割符,字符必须是数字,其他情况都是错误
if (isdigit(ch)) {
_decodeState = HttpRequestDecodeState::VERSION;
} else {
_decodeState = HttpRequestDecodeState::INVALID_VERSION;
}
break;
}
case HttpRequestDecodeState::HEADER_KEY: {
//冒号前后可能有空格
if (isblank(ch)) {
headerKey.end = p;
_decodeState = HttpRequestDecodeState::
HEADER_BEFORE_COLON; //冒号之前的状态
} else if (ch == ':') {
headerKey.end = p;
_decodeState = HttpRequestDecodeState::
HEADER_AFTER_COLON; //冒号之后的状态
} else {
// do nothing
}
break;
}
case HttpRequestDecodeState::HEADER_BEFORE_COLON: {
if (isblank(ch)) {
// do nothing
} else if (ch == ':') {
_decodeState = HttpRequestDecodeState::HEADER_AFTER_COLON;
} else {
//冒号之前的状态不能是空格之外的其他字符
_decodeState = HttpRequestDecodeState::INVALID_HEADER;
}
break;
}
case HttpRequestDecodeState::HEADER_AFTER_COLON: {
if (isblank(ch)) { //值之前遇到空格都是正常的
// do nothing
} else {
headerValue.begin = p;
_decodeState =
HttpRequestDecodeState::HEADER_VALUE; //开始处理值
}
break;
}
case HttpRequestDecodeState::HEADER_VALUE: {
if (ch == CR) {
headerValue.end = p;
_headers.insert({headerKey, headerValue});
_decodeState = HttpRequestDecodeState::WHEN_CR;
}
break;
}
case HttpRequestDecodeState::WHEN_CR: {
if (ch == LF) {
//如果是回车,可换成下一个
_decodeState = HttpRequestDecodeState::CR_LF;
} else {
_decodeState = HttpRequestDecodeState::INVALID;
}
break;
}
case HttpRequestDecodeState::CR_LF: {
if (ch == CR) {
//如果在CR_LF状态之后还有CR,那么便是有点结束的味道了
_decodeState = HttpRequestDecodeState::CR_LF_CR;
} else if (isblank(ch)) {
_decodeState = HttpRequestDecodeState::INVALID;
} else {
//如果不是,那么就可能又是一个请求头了,那就开始解析请求头
headerKey.begin = p;
_decodeState = HttpRequestDecodeState::HEADER_KEY;
}
break;
}
case HttpRequestDecodeState::CR_LF_CR: {
if (ch == LF) {
//如果是\r接着\n 那么判断是不是需要解析请求体
if (_headers.count("Content-Length") > 0) {
bodyLength = atoi(_headers["Content-Length"].c_str());
if (bodyLength > 0) {
_decodeState =
HttpRequestDecodeState::BODY; //解析请求体
} else {
_decodeState =
HttpRequestDecodeState::COMPLETE; //完成了
}
} else {
if (scanPos < size) {
bodyLength = size - scanPos;
_decodeState =
HttpRequestDecodeState::BODY; //解析请求体
} else {
_decodeState = HttpRequestDecodeState::COMPLETE;
}
}
} else {
_decodeState = HttpRequestDecodeState::INVALID_HEADER;
}
break;
}
case HttpRequestDecodeState::BODY: {
//解析请求体
_body.assign(p, bodyLength);
_decodeState = HttpRequestDecodeState::COMPLETE;
break;
}
default:
break;
}
}
}
const std::string &HttpRequest::getMethod() const
{
return _method;
}
const std::string &HttpRequest::getUrl() const
{
return _url;
}
const std::map<std::string, std::string> &HttpRequest::getRequestParams() const
{
return _requestParams;
}
const std::string &HttpRequest::getProtocol() const
{
return _protocol;
}
const std::string &HttpRequest::getVersion() const
{
return _version;
}
const std::map<std::string, std::string> &HttpRequest::getHeaders() const
{
return _headers;
}
const std::string &HttpRequest::getBody() const
{
return _body;
}
void process_header(HttpRequest &req, HttpResponse &res)
{
res.addHeader("Connection", "close");
if (accessable(res.filename) != 0) {
res.setStCode(404);
res.addHeader(CONTENT_LENGTH, "0");
return;
}
const size_t size = get_file_size(res.filename);
res.addHeader(CONTENT_LENGTH, std::to_string(size));
res.addHeader("Accept-Ranges", "bytes");
for (const auto &header : req._headers) {
std::string key = header.first;
for (char &ch : key) ch = std::tolower(static_cast<unsigned char>(ch));
if (key != "range") continue;
// Preserve the existing single explicit byte-range API.
std::smatch match;
if (!std::regex_match(header.second, match, std::regex("bytes=([0-9]+)-([0-9]+)")))
continue;
try {
const auto start = std::stoull(match[1].str());
const auto end = std::stoull(match[2].str());
if (start >= size || end < start || end > INT_MAX) throw std::out_of_range("range");
res.start_pos = static_cast<int>(start);
res.end_pos = static_cast<int>(std::min<unsigned long long>(end, size - 1));
res.is_range = true;
res.setStCode(206);
res.addHeader(CONTENT_LENGTH, std::to_string(res.end_pos - res.start_pos + 1));
res.addHeader(CONTENT_RANGE, "bytes " + std::to_string(res.start_pos) + "-" +
std::to_string(res.end_pos) + "/" + std::to_string(size));
} catch (const std::exception &) {
res.setStCode(416);
res.addHeader(CONTENT_LENGTH, "0");
res.addHeader(CONTENT_RANGE, "bytes */" + std::to_string(size));
}
}
}
HttpResponse::HttpResponse(HttpRequest &req, uint16_t type, const char *filename)
{
this->type = type;
switch (type) {
case 1: // html/txt
addHeader("Content-Type", "text/html");
break;
case 2: // binary
addHeader("Content-Type", "application/octet-stream");
addHeader("Content-Disposition", "attachment");
addHeader("filename", filename);
break;
default:
addHeader("Content-Type", "application/octet-stream");
break;
}
_version = req.getVersion();
_protocol = req.getProtocol();
// TODO:status
http_status status = HTTP_OK;
_status = "OK";
_status_code = 200;
_url = req.getUrl();
_fd = req.getFD();
outgoing = req.outgoing;
this->filename = filename;
// cout<<get_file_type("test.mp4")<<endl;
// addHeader(CONTENTTYPE, get_file_type(filename));
process_header(req, *this);
}
HttpResponse &HttpResponse::addHeader(const string &header_name,
const string &header_value)
{
_res_headers[header_name] = header_value;
return *this;
}
HttpResponse &HttpResponse::setBody(string &_body)
{
this->_body = _body;
return *this;
}
string HttpResponse::getHeaderStr()
{
string res("");
res.append(_protocol);
res.append("/");
res.append(_version);
res.append(" ");
res.append(std::to_string(_status_code));
res.append(" ");
res.append(mapCode2Status(_status_code));
res.append(CRLF);
for (auto item : _res_headers) {
res.append(item.first + ":" + item.second + CRLF);
}
res.append(CRLF);
return res;
}
string HttpResponse::getResponseStr()
{
return this->getHeaderStr() + _body;
}
void HttpResponse::setStCode(int code)
{
_status_code = code;
this->_status = mapCode2Status(code);
}
int HttpRequest::getFD(){
return _fd;
}
void HttpRequest::setFD(int fd){
_fd=fd;
}