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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
|
//
// Created by luqiu on 2018-5-17.
//
#include <cassert>
#include <vector>
#include <pcrecpp.h>
#include "httpaction.h"
#include "http.h"
#include "util.h"
#include "logger.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// 结构化日志记录
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HttpLogger::HttpLogger(StructLogger * st_logger, unsigned int service_id, unsigned int cfg_id)
: st_logger_(st_logger), service_id_(service_id), cfg_id_(cfg_id)
{
return;
}
HttpLogger::~HttpLogger()
{
if (auto_sendlog_ && need_to_sendlog_) SendLog();
}
/* From: PanGu数据库表设计文件
* Version:
=======================================================================================================================
数据名称 数据类型 字段说明 可空 备注
=======================================================================================================================
url string url地址 N
req_hdr_file string 请求头转储文件 Y 后缀名为”.txt”
req_body_file string 请求体转储文件 Y 无后缀名
res_hdr_file string 应答头转储文件 Y 后缀名为”.txt”
res_body_file string 应答体体转储文件 Y 无后缀名
======================================================================================================================
数据名称 数据类型 字段说明 可空 备注
=======================================================================================================================
isn int TCP初始序列号 Y 用于单向流对准
proxy_flag int 是否HTTP代理标志 Y 用于单向流对准
http_seq int HTTP会话序列号 Y 用于单向流对准
req_line string 请求行 Y
res_line string 应答行 Y
cookie string Cookie值 Y
referer string Referer值 Y
user_agent string UA值 Y
user_define_key string 用户自定义头域名称 Y 记录命中的用户自定义域名称,如X-header
user_define_value string 用户自定义域值 Y 记录命中的用户自定义域值,如xxx.cloudfront.net
*/
void HttpLogger::ConstructByConnection(const HttpConnection & conn)
{
sk_src_ = conn.SockAddrSource();
sk_dst_ = conn.SockAddrDest();
}
void HttpLogger::ConstructByRequestHeader(const HttpRequest & request)
{
/* 请求侧数据 */
st_log_["url"] = request.Url();
const auto & c_headers = request.cHeaders();
/* 取头部特定字段
* TODO: User-defined字段暂不填写 */
c_headers.ForEachValueOfHeader("Cookie", [this](const std::string & field, const std::string & value)
{
st_log_["cookie"] = value;
return false;
});
c_headers.ForEachValueOfHeader("Referer", [this](const std::string & field, const std::string & value)
{
st_log_["referer"] = value;
return false;
});
c_headers.ForEachValueOfHeader("User-Agent", [this](const std::string & field, const std::string & value)
{
st_log_["user_agent"] = value;
return false;
});
need_to_sendlog_ = true;
return;
}
void HttpLogger::ConstructByRequestBody(const HttpRequest & request)
{
return;
}
void HttpLogger::ConstructByResponseHeader(const HttpResponse & resp)
{
/* TODO: 应答侧数据暂不填写,待HttpResponse完善后再开发 */
return;
}
void HttpLogger::ConstructByResponseBody(const HttpResponse & resp)
{
return;
}
void HttpLogger::SendLog()
{
st_logger_->CommonLogMake(sk_src_, sk_dst_, service_id_, cfg_id_, st_log_);
st_logger_->SendLog(topic_id_, std::move(st_log_));
}
class HttpActionCommon : public HttpAction
{
public:
void OnRequestHeader(HttpSession * session) override
{
if (logger_ != nullptr)
{
logger_->ConstructByRequestHeader(session->request());
}
return __on_request_header(session);
}
void OnRequestBody(HttpSession * session) override
{
if (logger_ != nullptr)
{
logger_->ConstructByRequestBody(session->request());
}
return __on_request_body(session);
}
void OnResponseHeader(HttpSession * session) override
{
if (logger_ != nullptr)
{
logger_->ConstructByResponseHeader(session->response());
}
return __on_response_header(session);
}
void OnResponseBody(HttpSession * session) override
{
if (logger_ != nullptr)
{
logger_->ConstructByResponseBody(session->response());
}
return __on_response_body(session);
}
void LoggerSetup(std::unique_ptr<HttpLogger> logger) override
{ logger_ = std::move(logger); }
void LoggerClear() override
{ logger_ = nullptr; }
protected:
std::unique_ptr<HttpLogger> logger_{};
protected:
virtual void __on_request_header(HttpSession * session) = 0;
virtual void __on_request_body(HttpSession * session) = 0;
virtual void __on_response_header(HttpSession * session) = 0;
virtual void __on_response_body(HttpSession * session) = 0;
};
class HttpActionMonitor : public HttpActionCommon
{
public:
virtual void Construct(const std::string & str_service_define);
virtual void OnRequestHeader(HttpSession * session);
virtual void OnRequestBody(HttpSession * session);
virtual void OnResponseHeader();
virtual void OnResponseBody();
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// HTTP白名单,不进行任何处理
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class HttpActionBypass : public HttpAction
{
public:
void Construct(const std::string & str_service_define) override
{}
void OnRequestHeader(HttpSession * session) override
{}
void OnRequestBody(HttpSession * session) override
{}
void OnResponseHeader(HttpSession * session) override
{}
void OnResponseBody(HttpSession * session) override
{}
void LoggerSetup(std::unique_ptr<HttpLogger> logger) override
{}
void LoggerClear() override
{}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// HTTP重定向
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class HttpActionRedirect : public HttpActionCommon
{
public:
void Construct(const std::string & str_service_define) override;
protected:
void __on_request_header(HttpSession * session) override
{ return do_redirect_action(session); }
void __on_request_body(HttpSession * session) override
{ return do_redirect_action(session); }
void __on_response_header(HttpSession * session) override
{};
void __on_response_body(HttpSession * session) override
{};
private:
unsigned int resp_code_{500};
std::string resp_location_{""};
std::string resp_content_{""};
void do_redirect_action(HttpSession * session);
};
void HttpActionRedirect::Construct(const std::string & str_kv)
{
std::vector<std::string> __split_token;
tokenize(str_kv, __split_token, ";", true);
if (__split_token.size() != 2)
{
throw std::invalid_argument(string_format(
"Not enough tokens: %s, need two tokens.", str_kv.c_str()));
}
for (const auto & kv_iterate : __split_token)
{
std::vector<std::string> __kv_tokens;
tokenize(kv_iterate, __kv_tokens, "=", false);
if (__kv_tokens.size() != 2)
{
throw std::invalid_argument(string_format(
"Token %s must be conposed by key and value", kv_iterate.c_str()));
}
const std::string & __str_key = __kv_tokens[0];
const std::string & __str_value = __kv_tokens[1];
if (__str_key == "code")
{
resp_code_ = static_cast<unsigned int>(std::stoul(__str_value));
continue;
}
if (__str_key == "url")
{
resp_location_ = __str_value;
continue;
}
assert(0);
}
}
void HttpActionRedirect::do_redirect_action(HttpSession * session)
{
auto & http_connection = session->connection();
/* 创建新的HttpResponse */
auto http_session = std::make_unique<HttpSession>(http_connection);
http_session->request(HttpRequestFactory(1, 0));
http_session->response(HttpResponseFactory(1, 0));
/* 构建Redirect Response */
auto & http_response = http_session->response();
http_response.ResponseCode(resp_code_);
/* TODO: 正文 */
http_response.Headers().Add("Location", resp_location_);
http_response.Construct();
/* 写新构建的HttpSession */
http_connection.Write(std::move(http_session));
/* 禁用后续的调用流程 */
session->SetRequestHeaderTag(HttpSession::kCallbackTagIgnore);
session->SetRequestBodyTag(HttpSession::kCallbackTagIgnore);
session->SetResponseHeaderTag(HttpSession::kCallbackTagIgnore);
session->SetResponseBodyTag(HttpSession::kCallbackTagIgnore);
/* 丢弃当前的HTTP Session */
session->DropMe();
return;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// HTTP连接阻断
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class HttpActionBlock : public HttpActionCommon
{
public:
void Construct(const std::string & str_service_define) override
{}
protected:
void __on_request_header(HttpSession * session) override
{ do_block_action(session); }
void __on_request_body(HttpSession * session) override
{ do_block_action(session); }
void __on_response_header(HttpSession * session) override
{ do_block_action(session); };
void __on_response_body(HttpSession * session) override
{ do_block_action(session); };
private:
void do_block_action(HttpSession * session);
};
void HttpActionBlock::do_block_action(HttpSession * session)
{
session->connection().Close();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class HttpActionDrop : public HttpActionCommon
{
public:
void Construct(const std::string & str_service_define) override
{}
protected:
void __on_request_header(HttpSession * session) override
{ do_drop_action(session); }
void __on_request_body(HttpSession * session) override
{ do_drop_action(session); }
void __on_response_header(HttpSession * session) override
{ do_drop_action(session); };
void __on_response_body(HttpSession * session) override
{ do_drop_action(session); };
private:
void do_drop_action(HttpSession * session);
};
void HttpActionDrop::do_drop_action(HttpSession * session)
{
session->DropMe();
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// HTTP内容编辑功能实现
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class HttpActionReplace : public HttpActionCommon
{
public:
void Construct(const std::string & str_kv) override;
protected:
void __on_request_header(HttpSession * session) override;
void __on_request_body(HttpSession * session) override;
void __on_response_header(HttpSession * session) override;
void __on_response_body(HttpSession * session) override;
private:
enum edit_zone
{
kZoneRequestUri,
kZoneRequestHeaders,
kZoneRequestBody,
kZoneResponseHeader,
kZoneResponseBody,
kZoneMax
};
struct edit_rule
{
pcrecpp::RE regex;
std::string fmt;
};
/* Edit Zone to string, define in maat service define */
static std::array<std::string, kZoneMax> map_edit_zone_to_str;
std::array<std::vector<struct edit_rule>, kZoneMax> edit_rules_{};
/* Scan and Replace */
bool __scan_and_replace(enum edit_zone, std::string & raw);
};
std::array<std::string, HttpActionReplace::kZoneMax> HttpActionReplace::map_edit_zone_to_str =
{
"http_req_uri",
"http_req_headers",
"http_req_body",
"http_resp_headers",
"http_resp_body"
};
void HttpActionReplace::Construct(const std::string & str_kv)
{
std::vector<std::string> __split_token;
tokenize(str_kv, __split_token, ";", true);
if (__split_token.size() % 2 != 0)
{
throw std::invalid_argument(string_format(
"Invalid edit rule: %s, the count of tokens must be even numbers.", str_kv.c_str()));
}
for (auto __iterate_zone = __split_token.cbegin(), __iterate_regex = __split_token.cbegin() + 1;
__iterate_zone != __split_token.cend(); __iterate_zone += 2, __iterate_regex += 2)
{
std::vector<std::string> __kv_tokens_zone;
std::vector<std::string> __kv_tokens_regex;
tokenize(*__iterate_zone, __kv_tokens_zone, "=");
tokenize(*__iterate_regex, __kv_tokens_regex, "=");
if (__kv_tokens_zone.size() != 2 || __kv_tokens_regex.size() != 2)
{
throw std::invalid_argument(string_format(
"Invalid edit rule: %s, the tokens must composed by key-value. ", str_kv.c_str()));
}
if (__kv_tokens_zone[0] != "zone" || __kv_tokens_regex[0] != "regex")
{
throw std::invalid_argument(string_format(
"Invalid edit rule: %s, the tokens' key must be 'zone' or 'regex'", str_kv.c_str()));
}
const std::string & __kv_zone = __kv_tokens_zone[1];
const std::string & __kv_regex = __kv_tokens_regex[1];
LOG(DEBUG) << "KvZone = " << __kv_zone << " " << "KvRegex = " << __kv_regex;
/* 查找strZone对应的Zone数值 */
auto zone_iterate = std::find(map_edit_zone_to_str.cbegin(), map_edit_zone_to_str.cend(), __kv_zone);
if (zone_iterate == map_edit_zone_to_str.cend())
{
throw std::invalid_argument("Invalid edit rule: %s, illegal zone. ");
}
auto zone_id = static_cast<edit_zone>(zone_iterate - map_edit_zone_to_str.cbegin());
auto & zone_rule_ref = edit_rules_[zone_id];
std::vector<std::string> __token_regex;
/* 按'/'拆分正则串,判断转义字符,若/前面是\,则不认为该字符为拆分字符 */
tokenize(__kv_regex, __token_regex, "/", false, [](const std::string & str, std::string::size_type pos)
{
return (pos == 0 || str[pos - 1] != '\\');
});
if (__token_regex.size() != 3)
{
throw std::invalid_argument(string_format(
"Invalid edit rule: %s, the regex must composed by two args.", str_kv.c_str()));
}
const std::string & __kv_regex_base = __token_regex[1];
const std::string & __kv_regex_fmt = __token_regex[2];
/* 编译正则表达式 */
pcrecpp::RE __re(__kv_regex_base);
if (__re.error() != "")
{
throw std::invalid_argument(string_format(
"Invalid edit rule: %s, illegal regex expr, %s", str_kv.c_str(), __re.error().c_str()));
}
struct edit_rule __temp_edit_rule = {std::move(__re), std::move(__kv_regex_fmt)};
zone_rule_ref.push_back(std::move(__temp_edit_rule));
}
return;
}
void HttpActionReplace::__on_request_header(HttpSession * session)
{
auto & request = session->request();
bool replaced = false;
/* 对URI替换 */
std::string str_uri = request.Uri();
if (__scan_and_replace(kZoneRequestUri, str_uri))
{
request.Uri(str_uri);
replaced = true;
}
/* 对Headers替换 */
request.Headers().ForEachHeader([this, &request, &replaced]
(const std::string & str_field, const std::string str_value) -> bool
{
/* Field, Value组合成字符串,整体调用正则扫描 */
std::string __combine_header = str_field + ":" + str_value;
/* 没有命中,继续调用本函数处理后面的Headers */
if (!__scan_and_replace(kZoneRequestHeaders, __combine_header))
return true;
/* 替换标志 */
replaced = true;
/* 命中,若替换后的长度为0,删除该头部 */
if (__combine_header.length() == 0)
{
request.Headers().Remove(str_field);
return true;
}
/* 按分号拆分成Field和Value */
auto first_comma_pos = __combine_header.find_first_of(':');
if (first_comma_pos == std::string::npos)
{
throw std::runtime_error("Invalid regex replacement for http headers, no comma found.");
}
auto __replaced_field = __combine_header.substr(0, first_comma_pos);
auto __replaced_value = __combine_header.substr(first_comma_pos + 1);
request.Headers().Set(__replaced_field, __replaced_value);
return true;
});
if (replaced) request.Construct();
return;
}
void HttpActionReplace::__on_request_body(HttpSession * session)
{
/* Request Object */
auto & request = session->request();
/* Request Body */
auto * request_body = request.Body();
/* Replace Result */
std::string str_output(request_body->begin(), request_body->end());
/* Replace Tag */
if (__scan_and_replace(kZoneRequestBody, str_output))
{
auto new_body_content = std::make_unique<HttpRequest::body_content_t>();
std::copy(str_output.cbegin(), str_output.cend(), std::back_inserter(*new_body_content));
request.Headers().Set("Content-Length", std::to_string(new_body_content->size()));
request.Body(std::move(new_body_content));
request.Construct();
}
return;
}
void HttpActionReplace::__on_response_header(HttpSession * session)
{
return;
}
void HttpActionReplace::__on_response_body(HttpSession * session)
{
return;
}
bool HttpActionReplace::__scan_and_replace(enum edit_zone zone, std::string & raw)
{
/* 扫描规则库,逐条执行 */
const auto & edit_rule = edit_rules_[zone];
bool replaced = false;
for (const auto & edit_rule_iter : edit_rule)
{
/* 正则表达式,确定要替换的内容 */
const auto & __edit_regex = edit_rule_iter.regex;
/* 替换表达式,替换方法 */
const auto & __edit_fmt = edit_rule_iter.fmt;
/* 执行替换 */
replaced = __edit_regex.Replace(__edit_fmt, &raw);
if (replaced) break;
}
return replaced;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// 工厂函数
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<HttpAction> HttpActionFactory(enum HttpActionType type, std::string str_service_define)
{
std::shared_ptr<HttpAction> __http_action_object;
switch (type)
{
case kActionBypass:
{
__http_action_object = std::make_shared<HttpActionBypass>();
break;
}
case kActionReplace:
{
__http_action_object = std::make_shared<HttpActionReplace>();
break;
}
case kActionBlock:
{
__http_action_object = std::make_shared<HttpActionBlock>();
break;
}
case kActionDrop:
{
__http_action_object = std::make_shared<HttpActionDrop>();
break;
}
case kActionRedirect:
{
__http_action_object = std::make_shared<HttpActionRedirect>();
break;
}
default: assert(0);
}
__http_action_object->Construct(str_service_define);
return std::move(__http_action_object);
}
std::unique_ptr<HttpLogger> HttpLoggerFactory(int service_id, int cfg_id)
{
return std::make_unique<HttpLogger>(g_tfe_instance->struct_logger_module.get(),
static_cast<unsigned int>(service_id), static_cast<unsigned int>(cfg_id));
}
|