-
Notifications
You must be signed in to change notification settings - Fork 2
/
gateway.h
640 lines (556 loc) · 21.6 KB
/
gateway.h
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
#ifndef GATEWAY_T_H
#define GATEWAY_T_H
#include <trantor/net/TcpClient.h>
#include <trantor/net/TcpServer.h>
#include <trantor/net/EventLoop.h>
#include <drogon/HttpAppFramework.h>
#include <drogon/HttpClient.h>
#include "pdu/pdu.h"
#include "misc.h"
#include "config.h"
using namespace trantor;
using namespace drogon;
using cchar_t = const char*;
using namespace cuap;
namespace gateway
{
using tcp_client_t = std::shared_ptr<trantor::TcpClient>;
using tcp_conn_t = const TcpConnectionPtr&;
using msg_buffer_t = MsgBuffer*;
using http_request_t = const HttpRequestPtr&;
using http_response_t = const HttpResponsePtr&;
void setup_bind(config::config_t& cfg, pdu::bind_msg_t& bindmsg)
{
bindmsg.set_system_id(cfg.gateway.system_id);
bindmsg.set_password(cfg.gateway.password);
bindmsg.set_system_type(cfg.gateway.system_type);
bindmsg.set_command_id(pdu::CommandIDs::Bind);
bindmsg.set_command_status(0);
bindmsg.set_sender_id(0xFFFFFFFF);
bindmsg.set_receiver_id(0xFFFFFFFF);
bindmsg.set_command_len(64);
bindmsg.encode_header();
}
template <typename T>
concept bool pdu_type = requires (T x)
{
{ x.command_len() }; { x.command_id() };
T::buffer;
};
namespace send
{
namespace samples
{
uint8_t unbind[] =
{
0x14, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff
};
uint8_t shake[] =
{
0x14, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff
};
}
void shake(tcp_client_t client, tcp_conn_t conn, msg_buffer_t msg)
{
pdu::shake_msg_t shake (samples::shake, sizeof(samples::shake));
shake.encode_header();
conn->send(shake, shake.capacity());
#ifdef ENABLE_PDU_LOG
fmt::print_cyan("\n{}. [ {}::shake info ]: Sent Shake Message to: {}\n",
misc::current_time(), client->name(), conn->peerAddr().toIpPort()
);
misc::print_pdu(samples::shake, sizeof(samples::shake));
#endif
std::this_thread::sleep_for (std::chrono::milliseconds(250));
}
void unbind(tcp_client_t client, tcp_conn_t conn, msg_buffer_t msg)
{
pdu::unbind_msg_t unbind (samples::unbind, sizeof(samples::unbind));
unbind.encode_header();
conn->send(unbind, unbind.capacity());
fmt::print_cyan("\n{}. [{}::on_message]: Sent UnBind Message to: {}\n",
misc::current_time(), client->name(), conn->peerAddr().toIpPort()
);
#ifdef ENABLE_PDU_LOG
misc::print_pdu(unbind);
#endif
}
void db_request(HttpClientPtr& http, string_view_t body)
{
HttpRequestPtr req = HttpRequest::newHttpRequest();
req->setBody(body.data());
http->sendRequest(req, [ & ](ReqResult result, const HttpResponsePtr& response)
{
if (result == ReqResult::Ok && response)
{
fmt::print_green("{}. [ send::db_request info ]: Data submitted to dB handler\n", misc::current_time());
}
else
{
fmt::print_yellow("{}. [ send::db_request info ]: Data not submitted to dB handler, saving...\n", misc::current_time());
}
fmt::print(std::flush(std::cout), "");
});
}
}
struct gateway_t
{
enum class data_transfer_mode_t { json, xml };
gateway_t(misc::cli_config_t& config);
void build_whitelist();
void build_abort(pdu_type&, auto&&);
void build_begin(pdu_type&, pdu_type&, auto&&);
void build_continue(pdu_type&, pdu_type&, auto&&);
template <command_id request_type = command_id::begin>
auto build_http_request(pdu_type& packet);
void send_http_request(HttpRequestPtr& req);
void init();
void on_connect(tcp_conn_t conn);
void on_conn_error();
void on_message(tcp_conn_t conn, msg_buffer_t msg);
void setup_config();
void setup_data_transfer_mode();
void run();
misc::cli_config_t cli_cfg;
config::config_t cfg;
EventLoopThread evloop_tcp = EventLoopThread{"eventloop.thread.tcp"};
EventLoopThread evloop_http = EventLoopThread{"eventloop.thread.http"};
InetAddress addr;
tcp_client_t tcp_client;
HttpClientPtr http_client;
pdu::bind_msg_t bindmsg;
pdu::unbind_msg_t unbindmsg;
std::set<string> white_list;
data_transfer_mode_t data_transfer_mode = data_transfer_mode_t::json;
};
gateway_t::gateway_t(misc::cli_config_t& config) : cli_cfg(config)
{
}
void gateway_t::build_whitelist()
{
auto& config = this->cfg;
string tmp, file = config["gateway"]["white-list"].asString();
fstream ifs (file, fstream::in);
if (!ifs.is_open())
{
fmt::print_yellow("{}. [ gateway_t::build_whitelist info ]: '{}' not found.\n", misc::current_time(), file);
return;
}
while (getline(ifs, tmp))
{
white_list.insert(tmp);
#ifdef ENABLE_PDU_LOG
fmt::print("{}\n", tmp);
#endif
}
fmt::print_green("{}. [ gateway_t::build_whitelist info ]: Whitelist built from '{}'\n", misc::current_time(), file);
}
void gateway_t::build_abort(pdu_type& pdu_req, auto&& fn)
{
static char fn_name[] = "build_abort";
pdu_req.decode_header();
auto sender_id = pdu_req.sender_id();
auto receiver_id = pdu_req.receiver_id();
fmt::print("{}. [ gateway::build_abort info ]: request: {}", misc::current_time(),
fmt::format(fmt_req_begin, sender_id, receiver_id, "", "", "")
);
HttpRequestPtr req = build_http_request<command_id::abort>(pdu_req);
http_client->sendRequest(req, [&/*, tconn = std::move(conn)*/](ReqResult result, const HttpResponsePtr& response)
{
if (result == ReqResult::Ok && response)
{
Json::Value json;
if (misc::parse_json(json, response->getBody()) and misc::check_json(json))
{
fmt::print_green("{}. [ gateway::build_abort info ]: response: {}\n", misc::current_time(), response->getBody());
}
else
{
fmt::print_red("{}. [ gateway::build_abort error ]: Unable to parse JSON response: {}\n", misc::current_time(), response->body());
}
}
else
{
fmt::print_red("{}. [ gateway::build_abort error ]: request to {} failed\n",
misc::current_time(), cfg.gateway.client.url
);
}
#ifdef ENABLE_PDU_LOG
misc::print_pdu(pdu_req, pdu_req.command_len());
#endif
fn();
});
}
void gateway_t::build_begin(pdu_type& pdu, pdu_type& pdu_req, auto&& fn)
{
static char fn_name[] = "build_begin";
pdu_req.decode_header();
string msisdn = pdu_req.msisdn();
if (!white_list.empty() and !white_list.contains(msisdn))
{
fmt::print_yellow("{}. [ gateway_t::build_begin warn ]: '{}' not found in white-list, not serving.\n", misc::current_time(), msisdn);
return ;
}
auto sender_id = pdu_req.sender_id();
auto receiver_id = pdu_req.receiver_id();
auto op = pdu_req.ussd_op_type();
string service_code = pdu_req.service_code();
string content = pdu_req.ussd_content();
fmt::print("{}. [ gateway::build_begin info ]: request: {}", misc::current_time(),
fmt::format(fmt_req_begin, sender_id, receiver_id, content, op_name(op), msisdn)
);
pdu.set_command_status(0);
pdu.set_receiver_id(sender_id);
pdu.set_ussd_ver(pdu::UssdVersion::PHASEII);
pdu.set_msisdn(msisdn);
pdu.set_service_code(service_code);
pdu.set_code_scheme(pdu::CodeScheme::Ox0F);
HttpRequestPtr req = build_http_request<command_id::begin>(pdu_req);
http_client->sendRequest(req, [&](ReqResult result, const HttpResponsePtr& response)
{
if (result == ReqResult::Ok && response)
{
Json::Value json;
if (misc::parse_json(json, response->getBody()) and misc::check_json(json))
{
try
{
fmt::print_green("{}. [ gateway::build_begin info ]: response: {}\n", misc::current_time(), response->getBody());
pdu.set_ussd_content(json["content"].asCString());
pdu.set_ussd_op_type(json["op_type"].asUInt());
pdu.set_command_id(json["command"].asUInt());
}
catch(std::exception& e)
{
fmt::print_red("{}. [ gateway::build_begin exception ]: {}\n", misc::current_time(), e.what());
pdu.set_command_id(pdu::CommandIDs::End);
}
}
else
{
fmt::print_red("{}. [ gateway::build_begin error ]: Unable to parse JSON response: {}\n",
misc::current_time(), response->body()
);
fmt::print_red(fmt_data_error, misc::current_time(), fn_name, sender_id, cfg.gateway.client.error.invalid_data);
pdu.set_command_id(pdu::CommandIDs::End);
pdu.set_ussd_op_type(pdu::USSDOperationTypes::USSN);
pdu.set_ussd_content(cfg.http.error.invalid_data);
}
}
else
{
fmt::print_red(fmt_req_error, misc::current_time(), fn_name, cfg.gateway.client.url, sender_id,
cfg.gateway.client.error.request_failed
);
pdu.set_ussd_op_type(pdu::USSDOperationTypes::USSN);
pdu.set_command_id(pdu::CommandIDs::End);
pdu.set_ussd_content(cfg.gateway.client.error.request_failed);
}
pdu.set_command_len();
pdu.encode_header();
#ifdef ENABLE_PDU_LOG
misc::print_pdu(pdu, be32toh(pdu.command_len()));
#endif
fn();
});
}
void gateway_t::build_continue(pdu_type& pdu, pdu_type& pdu_req, auto&& fn)
{
static char fn_name[] = "build_continue";
pdu_req.decode_header();
auto sender_id = pdu_req.sender_id();
auto receiver_id = pdu_req.receiver_id();
auto op = pdu_req.ussd_op_type();
string msisdn = pdu_req.msisdn();
string service_code = pdu_req.service_code();
string ussd_content = pdu_req.ussd_content();
fmt::print("{}. [ gateway::build_continue info ]: request: {}", misc::current_time(),
fmt::format(fmt_req_begin, sender_id, receiver_id, service_code, op_name(op), msisdn)
);
pdu.set_command_status(0);
pdu.set_receiver_id(sender_id);
pdu.set_ussd_ver(pdu::UssdVersion::PHASEII);
pdu.set_msisdn(msisdn);
pdu.set_service_code(service_code);
pdu.set_code_scheme(pdu::CodeScheme::Ox0F);
HttpRequestPtr req = build_http_request<command_id::continue_>(pdu_req);
http_client->sendRequest(req, [&](ReqResult result, const HttpResponsePtr& response)
{
if (result == ReqResult::Ok && response)
{
Json::Value json;
if (misc::parse_json(json, response->getBody()) and misc::check_json(json))
{
try
{
fmt::print_green("{}. [ gateway::build_continue info ]: response: {}\n", misc::current_time(), response->getBody());
pdu.set_ussd_content(json["content"].asString());
pdu.set_ussd_op_type(json["op_type"].asUInt());
pdu.set_command_id(json["command"].asUInt());
}
catch(std::exception& e)
{
fmt::print_red("{}. [ gateway::build_continue exception ]: {}\n", misc::current_time(), e.what());
pdu.set_command_id(pdu::CommandIDs::End);
}
}
else
{
fmt::print_red("{}. [ gateway::build_continue error ]: Unable to parse JSON response: {}\n", misc::current_time(), response->body());
fmt::print_red(fmt_data_error, misc::current_time(), fn_name, sender_id, cfg.gateway.client.error.invalid_data);
pdu.set_command_id(pdu::CommandIDs::End);
pdu.set_ussd_op_type(pdu::USSDOperationTypes::USSN);
pdu.set_ussd_content(cfg.gateway.client.error.invalid_data);
}
}
else
{
fmt::print_red(fmt_req_error, misc::current_time(), fn_name, cfg.gateway.client.url, sender_id,
cfg.gateway.client.error.could_not_fetch
);
pdu.set_ussd_op_type(pdu::USSDOperationTypes::USSN);
pdu.set_command_id(pdu::CommandIDs::End);
pdu.set_ussd_content(cfg.gateway.client.error.could_not_fetch);
}
pdu.set_command_len();
pdu.encode_header();
#ifdef ENABLE_PDU_LOG
misc::print_pdu(pdu, be32toh(pdu.command_len()));
#endif
fn();
});
}
template <command_id request_type = command_id::begin>
auto gateway_t::build_http_request(pdu_type& packet)
{
static char frmt_begin[] = R"({{ "command": {}, "sid": "0x{:08x}", "length": {}, "msisdn": "{}", "content": "{}" }})""\n";
HttpRequestPtr req = HttpRequest::newHttpRequest();
req->setMethod(drogon::Get);
req->setPath("/");
if constexpr (request_type == command_id::begin)
{
// When command_id = Begin, content is service code. Other times content stays content
req->setBody(fmt::format(frmt_begin,
command_id::begin, packet.sender_id(), packet.command_len(), packet.msisdn(), packet.ussd_content()
)
);
}
else if constexpr (request_type == command_id::continue_)
{
req->setBody(fmt::format(frmt_begin,
command_id::continue_, packet.sender_id(), packet.command_len(), packet.msisdn(), packet.ussd_content()
)
);
}
else if constexpr (request_type == command_id::abort)
{
static char frmt_abort[] = R"({{ "command": {}, "sid": "0x{:08x}", "length": {} }})""\n";
req->setBody(fmt::format(frmt_abort,
command_id::abort, packet.sender_id(), packet.command_len()
)
);
}
else if constexpr (request_type == command_id::bind)
{
req->setBody(fmt::format(R"({{ "command": {}, "pdu-status": {}, "length": {}, "system_id": "{}" }})""\n",
command_id::bind, packet.command_status(), packet.command_len(), packet.system_id()
)
);
}
fmt::print("{}. [ gateway::build_http_request info ]: request: {}", misc::current_time(), req->body());
return req;
}
void gateway_t::init()
{
tcp_client = std::make_shared<trantor::TcpClient>(evloop_tcp.getLoop(), addr, "gateway");
tcp_client->setConnectionCallback([&] (tcp_conn_t conn) { on_connect(conn); });
tcp_client->setConnectionErrorCallback([&] { on_conn_error(); });
tcp_client->setMessageCallback([&] (tcp_conn_t conn, msg_buffer_t msg) { on_message(conn, msg); } );
tcp_client->connect();
}
void gateway_t::send_http_request(HttpRequestPtr& req)
{
http_client->sendRequest(req, [&](ReqResult result, const HttpResponsePtr& response)
{
if (result == ReqResult::Ok && response)
{
fmt::print_green("{}. [ gateway::send_http_request info ]: response: {}\n", misc::current_time(), response->getBody());
}
else
{
fmt::print_red("{}. [ gateway::send_http_request error ]: request to {} failed\n",
misc::current_time(), cfg.gateway.client.url
);
/// TODO: Error to be displayed to mobile be defined in config file
}
});
}
void gateway_t::on_connect(tcp_conn_t conn)
{
if (conn->connected())
{
std::string raddr = conn->peerAddr().toIpPort();
fmt::print_cyan("{}. [ {}::on_connection info ]: Connected to: {}\n", misc::current_time(), tcp_client->name(), raddr);
setup_bind(cfg, bindmsg);
#ifdef ENABLE_PDU_LOG
misc::print_pdu(bindmsg);
#endif
conn->send(bindmsg, bindmsg.capacity());
fmt::print_green("{}. [ {}::on_connection info ]: Sent Bind Message to: {}\n", misc::current_time(), tcp_client->name(), raddr);
}
else
{
fmt::print_red("{}. [ gateway::on_connection error ]: Disconnected.\n", misc::current_time());
init();
}
fmt::print(std::flush(std::cout), "");
}
void gateway_t::on_conn_error()
{
using namespace std::literals;
fmt::print_red("{}. [ gateway_t::on_conn_error error ]: Connection Lost.\n", current_time());
fmt::print(std::flush(std::cout), "");
std::this_thread::sleep_for(10s);
init();
}
void gateway_t::on_message(tcp_conn_t conn, msg_buffer_t msg)
{
static std::atomic_int id = 0;
if (conn->connected())
{
string_view_t data { msg->peek(), msg->readableBytes() };
auto cmd = htobe32(header::command_id(data));
#ifdef ENABLE_PDU_LOG
//fmt::print_green(fmt_cmdid, cmd, pdu_name(cmd));
misc::print_pdu(data.data(), data.size());
#endif
switch (cmd)
{
case CommandIDs::BindResp:
{
pdu::bind_resp_t bindresp(msg->peek(), msg->readableBytes() );
bindresp.decode_header();
if (bindresp.command_status() == 0)
{
fmt::print_green("{}. [ {}::on_message info ]: Bind Successful!\n", misc::current_time(), tcp_client->name());
}
else
{
fmt::print_red("{}. [ {}::on_message error ]: Bind Failed!\n", misc::current_time(), tcp_client->name());
}
fmt::print(std::flush(std::cout), "");
HttpRequestPtr req = build_http_request<command_id::bind>(bindresp);
send_http_request(req);
msg->retrieveAll();
}
break;
case CommandIDs::ShakeResp:
send::shake(tcp_client, conn, msg);
msg->retrieveAll();
break;
/// Listens to Begin from USSDC
case CommandIDs::Begin:
{
continue_msg_t pdu, pdu_req { msg->peek(), msg->readableBytes() };
pdu.set_sender_id(++id);
build_begin(pdu, pdu_req, [&, tconn = std::move(conn)] {
tconn->send(pdu, pdu.capacity());
});
}
break;
/// Listens to Continue from USSDC
case CommandIDs::Continue:
{
continue_msg_t pdu, pdu_req { msg->peek(), msg->readableBytes() };
pdu.set_sender_id(id);
build_continue(pdu, pdu_req, [&, tconn = std::move(conn)] {
tconn->send(pdu, pdu.capacity());
});
} break;
case CommandIDs::End:
break;
case CommandIDs::Abort:
{
abort_msg_t pdu_req { msg->peek(), msg->readableBytes() };
build_abort(pdu_req, [&] {
//
});
} break;
/// UssdBindResp can be sent only by the USSDC to the service application.
case CommandIDs::UnBindResp:
{
msg->retrieveAll();
fmt::print_green("{}. [ {}::on_message info ]: UnBind Successful!\n", misc::current_time(), tcp_client->name());
} break;
default:
{
fmt::print_red("{}. [ {}::on_message info ]: Unknown Command\n", misc::current_time(), tcp_client->name());
msg->retrieveAll();
}
}
}
else
{
fmt::print_red("{}. [ gateway_t::on_message error ]: Not connected\n", current_time());
}
fmt::print(std::flush(std::cout), "");
msg->retrieveAll();
}
void gateway_t::setup_config()
{
if (!cli_cfg.config.empty())
{
cfg.read_then_parse<config::config_type::json>(cli_cfg.config);
addr = InetAddress(cfg.gateway.host, cfg.gateway.port);
http_client = HttpClient::newHttpClient(cfg.gateway.client.url, evloop_http.getLoop());
cli_cfg.rurl= cfg.gateway.client.url;
}
else
{
addr = InetAddress(cli_cfg.chost, cli_cfg.cport);
http_client = HttpClient::newHttpClient(cli_cfg.rurl, evloop_http.getLoop());
}
}
void gateway_t::setup_data_transfer_mode()
{
string md = cfg["data-transfer-mode"].asString();
if (md == "xml")
{
data_transfer_mode = data_transfer_mode_t::xml;
format::req_cont = R"(<continue>
<sid>{}</sid>
<rid>{}</rid>
<service_code>{}</service_code>
<operation>{}</operation>
<msisdn>{}</msisdn>
<content>{}</content>
</continue>)";
}
}
void gateway_t::run()
{
Logger::setLogLevel(Logger::LogLevel::kError);
setup_config();
setup_bind(cfg, bindmsg);
build_whitelist();
init();
evloop_tcp.run();
evloop_http.run();
evloop_tcp.wait();
}
void main(int argc, char* argv[])
{
if (misc::setup_cli(misc::args, argc, argv))
{
misc::cli_config_t cfg;
misc::setup_config(cfg);
gateway_t gateway(cfg);
gateway.run();
}
}
}
#endif // GATEWAY_T_H