]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/other/smux/smux.cpp
Use std::jthread and C++17.
[stg.git] / projects / stargazer / plugins / other / smux / smux.cpp
1 #include <sys/types.h>
2 #include <sys/socket.h>
3 #include <arpa/inet.h>
4
5 #include <cstring>
6 #include <cerrno>
7 #include <ctime>
8 #include <csignal>
9 #include <cassert>
10
11 #include <vector>
12 #include <algorithm>
13 #include <iterator>
14 #include <stdexcept>
15 #include <utility>
16
17 #include "stg/common.h"
18
19 #include "smux.h"
20 #include "utils.h"
21
22 namespace
23 {
24
25 bool SPrefixLess(const Sensors::value_type & a,
26                  const Sensors::value_type & b)
27 {
28 return a.first.PrefixLess(b.first);
29 }
30
31 }
32
33 extern "C" STG::Plugin* GetPlugin()
34 {
35     static SMUX plugin;
36     return &plugin;
37 }
38
39 SMUX_SETTINGS::SMUX_SETTINGS()
40     : errorStr(),
41       ip(0),
42       port(0),
43       password()
44 {}
45
46 int SMUX_SETTINGS::ParseSettings(const STG::ModuleSettings & s)
47 {
48 STG::ParamValue pv;
49 std::vector<STG::ParamValue>::const_iterator pvi;
50 int p;
51
52 pv.param = "Port";
53 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
54 if (pvi == s.moduleParams.end() || pvi->value.empty())
55     {
56     errorStr = "Parameter \'Port\' not found.";
57     printfd(__FILE__, "Parameter 'Port' not found\n");
58     return -1;
59     }
60 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
61     {
62     errorStr = "Cannot parse parameter \'Port\': " + errorStr;
63     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
64     return -1;
65     }
66 port = static_cast<uint16_t>(p);
67
68 pv.param = "Password";
69 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
70 if (pvi == s.moduleParams.end() || pvi->value.empty())
71     {
72     errorStr = "Parameter \'Password\' not found.";
73     printfd(__FILE__, "Parameter 'Password' not found\n");
74     password = "";
75     }
76 else
77     {
78     password = pvi->value[0];
79     }
80
81 pv.param = "Server";
82 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
83 if (pvi == s.moduleParams.end() || pvi->value.empty())
84     {
85     errorStr = "Parameter \'Server\' not found.";
86     printfd(__FILE__, "Parameter 'Server' not found\n");
87     return -1;
88     }
89 ip = inet_strington(pvi->value[0]);
90
91 return 0;
92 }
93
94 SMUX::SMUX()
95     : users(NULL),
96       tariffs(NULL),
97       admins(NULL),
98       services(NULL),
99       corporations(NULL),
100       traffcounter(NULL),
101       stopped(true),
102       needReconnect(false),
103       lastReconnectTry(0),
104       reconnectTimeout(1),
105       sock(-1),
106       addUserNotifier(*this),
107       delUserNotifier(*this),
108       addDelTariffNotifier(*this),
109       logger(STG::PluginLogger::get("smux"))
110 {
111 smuxHandlers[SMUX_PDUs_PR_close] = &SMUX::CloseHandler;
112 smuxHandlers[SMUX_PDUs_PR_registerResponse] = &SMUX::RegisterResponseHandler;
113 smuxHandlers[SMUX_PDUs_PR_pdus] = &SMUX::PDUsRequestHandler;
114 smuxHandlers[SMUX_PDUs_PR_commitOrRollback] = &SMUX::CommitOrRollbackHandler;
115
116 pdusHandlers[PDUs_PR_get_request] = &SMUX::GetRequestHandler;
117 pdusHandlers[PDUs_PR_get_next_request] = &SMUX::GetNextRequestHandler;
118 pdusHandlers[PDUs_PR_set_request] = &SMUX::SetRequestHandler;
119 }
120
121 SMUX::~SMUX()
122 {
123     {
124     Sensors::iterator it;
125     for (it = sensors.begin(); it != sensors.end(); ++it)
126         delete it->second;
127     }
128     {
129     Tables::iterator it;
130     for (it = tables.begin(); it != tables.end(); ++it)
131         delete it->second;
132     }
133 printfd(__FILE__, "SMUX::~SMUX()\n");
134 }
135
136 int SMUX::ParseSettings()
137 {
138 return smuxSettings.ParseSettings(settings);
139 }
140
141 int SMUX::Start()
142 {
143 assert(users != NULL && "users must not be NULL");
144 assert(tariffs != NULL && "tariffs must not be NULL");
145 assert(admins != NULL && "admins must not be NULL");
146 assert(services != NULL && "services must not be NULL");
147 assert(corporations != NULL && "corporations must not be NULL");
148 assert(traffcounter != NULL && "traffcounter must not be NULL");
149
150 if (PrepareNet())
151     needReconnect = true;
152
153 // Users
154 sensors[OID(".1.3.6.1.4.1.38313.1.1.1")] = new TotalUsersSensor(*users);
155 sensors[OID(".1.3.6.1.4.1.38313.1.1.2")] = new ConnectedUsersSensor(*users);
156 sensors[OID(".1.3.6.1.4.1.38313.1.1.3")] = new AuthorizedUsersSensor(*users);
157 sensors[OID(".1.3.6.1.4.1.38313.1.1.4")] = new AlwaysOnlineUsersSensor(*users);
158 sensors[OID(".1.3.6.1.4.1.38313.1.1.5")] = new NoCashUsersSensor(*users);
159 sensors[OID(".1.3.6.1.4.1.38313.1.1.6")] = new DisabledDetailStatsUsersSensor(*users);
160 sensors[OID(".1.3.6.1.4.1.38313.1.1.7")] = new DisabledUsersSensor(*users);
161 sensors[OID(".1.3.6.1.4.1.38313.1.1.8")] = new PassiveUsersSensor(*users);
162 sensors[OID(".1.3.6.1.4.1.38313.1.1.9")] = new CreditUsersSensor(*users);
163 sensors[OID(".1.3.6.1.4.1.38313.1.1.10")] = new FreeMbUsersSensor(*users);
164 sensors[OID(".1.3.6.1.4.1.38313.1.1.11")] = new TariffChangeUsersSensor(*users);
165 sensors[OID(".1.3.6.1.4.1.38313.1.1.12")] = new ActiveUsersSensor(*users);
166 // Tariffs
167 sensors[OID(".1.3.6.1.4.1.38313.1.2.1")] = new TotalTariffsSensor(*tariffs);
168 // Admins
169 sensors[OID(".1.3.6.1.4.1.38313.1.3.1")] = new TotalAdminsSensor(*admins);
170 // Services
171 sensors[OID(".1.3.6.1.4.1.38313.1.4.1")] = new TotalServicesSensor(*services);
172 // Corporations
173 sensors[OID(".1.3.6.1.4.1.38313.1.5.1")] = new TotalCorporationsSensor(*corporations);
174 // Traffcounter
175 sensors[OID(".1.3.6.1.4.1.38313.1.6.1")] = new TotalRulesSensor(*traffcounter);
176
177 // Table data
178 tables[".1.3.6.1.4.1.38313.1.2.2"] = new TariffUsersTable(".1.3.6.1.4.1.38313.1.2.2", *tariffs, *users);
179
180 UpdateTables();
181 SetNotifiers();
182
183 #ifdef SMUX_DEBUG
184 Sensors::const_iterator it(sensors.begin());
185 while (it != sensors.end())
186     {
187     printfd(__FILE__, "%s = %s\n",
188             it->first.ToString().c_str(),
189             it->second->ToString().c_str());
190     ++it;
191     }
192 #endif
193
194 if (!m_thread.joinable())
195     m_thread = std::jthread([this](auto token){ Run(token); });
196
197 return 0;
198 }
199
200 int SMUX::Stop()
201 {
202 printfd(__FILE__, "SMUX::Stop() - Before\n");
203 m_thread.request_stop();
204
205 if (!stopped)
206     {
207     //5 seconds to thread stops itself
208     for (int i = 0; i < 25 && !stopped; i++)
209         {
210         struct timespec ts = {0, 200000000};
211         nanosleep(&ts, NULL);
212         }
213     }
214
215 if (!stopped)
216     m_thread.detach();
217
218 ResetNotifiers();
219
220     {
221     Tables::iterator it;
222     for (it = tables.begin(); it != tables.end(); ++it)
223         delete it->second;
224     }
225     {
226     Sensors::iterator it;
227     for (it = sensors.begin(); it != sensors.end(); ++it)
228         delete it->second;
229     }
230
231 tables.erase(tables.begin(), tables.end());
232 sensors.erase(sensors.begin(), sensors.end());
233
234 close(sock);
235
236 if (!stopped)
237     {
238     return -1;
239     }
240
241 printfd(__FILE__, "SMUX::Stop() - After\n");
242 return 0;
243 }
244
245 int SMUX::Reload(const STG::ModuleSettings & /*ms*/)
246 {
247 if (Stop())
248     return -1;
249 if (Start())
250     return -1;
251 if (!needReconnect)
252     {
253     printfd(__FILE__, "SMUX reconnected succesfully.\n");
254     logger("Reconnected successfully.");
255     }
256 return 0;
257 }
258
259 void SMUX::Run(std::stop_token token)
260 {
261 stopped = true;
262 if (!SendOpenPDU(sock))
263     needReconnect = true;
264 if (!SendRReqPDU(sock))
265     needReconnect = true;
266 stopped = false;
267
268 while (!token.stop_requested())
269     {
270     if (WaitPackets(sock) && !needReconnect)
271         {
272         SMUX_PDUs_t * pdus = RecvSMUXPDUs(sock);
273         if (pdus)
274             {
275             DispatchPDUs(pdus);
276             ASN_STRUCT_FREE(asn_DEF_SMUX_PDUs, pdus);
277             }
278         else if (!token.stop_requested())
279             Reconnect();
280         }
281     else if (!token.stop_requested() && needReconnect)
282         Reconnect();
283     if (token.stop_requested())
284         break;
285     }
286 SendClosePDU(sock);
287 stopped = true;
288 }
289
290 bool SMUX::PrepareNet()
291 {
292 sock = socket(AF_INET, SOCK_STREAM, 0);
293
294 if (sock < 0)
295     {
296     errorStr = "Cannot create socket.";
297     logger("Cannot create a socket: %s", strerror(errno));
298     printfd(__FILE__, "Cannot create socket\n");
299     return true;
300     }
301
302 struct sockaddr_in addr;
303
304 addr.sin_family = AF_INET;
305 addr.sin_port = htons(smuxSettings.GetPort());
306 addr.sin_addr.s_addr = smuxSettings.GetIP();
307
308 if (connect(sock, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)))
309     {
310     errorStr = "Cannot connect.";
311     logger("Cannot connect the socket: %s", strerror(errno));
312     printfd(__FILE__, "Cannot connect. Message: '%s'\n", strerror(errno));
313     return true;
314     }
315
316 return false;
317 }
318
319 bool SMUX::Reconnect()
320 {
321 if (needReconnect && difftime(time(NULL), lastReconnectTry) < reconnectTimeout)
322     return true;
323
324 time(&lastReconnectTry);
325 SendClosePDU(sock);
326 close(sock);
327 if (!PrepareNet())
328     if (SendOpenPDU(sock))
329         if (SendRReqPDU(sock))
330             {
331             reconnectTimeout = 1;
332             needReconnect = false;
333             logger("Connected successfully");
334             printfd(__FILE__, "Connected successfully\n");
335             return false;
336             }
337
338 if (needReconnect)
339     if (reconnectTimeout < 60)
340         reconnectTimeout *= 2;
341
342 needReconnect = true;
343 return true;
344 }
345
346 bool SMUX::DispatchPDUs(const SMUX_PDUs_t * pdus)
347 {
348 SMUXHandlers::iterator it(smuxHandlers.find(pdus->present));
349 if (it != smuxHandlers.end())
350     {
351     return (this->*(it->second))(pdus);
352     }
353 #ifdef SMUX_DEBUG
354 else
355     {
356     switch (pdus->present)
357         {
358         case SMUX_PDUs_PR_NOTHING:
359             printfd(__FILE__, "PDUs: nothing\n");
360             break;
361         case SMUX_PDUs_PR_open:
362             printfd(__FILE__, "PDUs: open\n");
363             break;
364         case SMUX_PDUs_PR_registerRequest:
365             printfd(__FILE__, "PDUs: registerRequest\n");
366             break;
367         default:
368             printfd(__FILE__, "PDUs: undefined\n");
369         }
370     asn_fprint(stderr, &asn_DEF_SMUX_PDUs, pdus);
371     }
372 #endif
373 return false;
374 }
375
376 bool SMUX::UpdateTables()
377 {
378 Sensors newSensors;
379 bool done = true;
380 Tables::iterator it(tables.begin());
381 while (it != tables.end())
382     {
383     try
384         {
385         it->second->UpdateSensors(newSensors);
386         }
387     catch (const std::runtime_error & ex)
388         {
389         printfd(__FILE__,
390                 "SMUX::UpdateTables - failed to update table '%s': '%s'\n",
391                 it->first.c_str(), ex.what());
392         done = false;
393         break;
394         }
395     ++it;
396     }
397 if (!done)
398     {
399     Sensors::iterator sit(newSensors.begin());
400     while (sit != newSensors.end())
401         {
402         delete sit->second;
403         ++sit;
404         }
405     return false;
406     }
407
408 it = tables.begin();
409 while (it != tables.end())
410     {
411     std::pair<Sensors::iterator, Sensors::iterator> res;
412     res = std::equal_range(sensors.begin(),
413                            sensors.end(),
414                            std::pair<OID, Sensor *>(OID(it->first), NULL),
415                            SPrefixLess);
416     Sensors::iterator sit(res.first);
417     while (sit != res.second)
418         {
419         delete sit->second;
420         ++sit;
421         }
422     sensors.erase(res.first, res.second);
423     ++it;
424     }
425
426 sensors.insert(newSensors.begin(), newSensors.end());
427
428 return true;
429 }
430
431 void SMUX::SetNotifier(UserPtr userPtr)
432 {
433 notifiers.push_back(CHG_AFTER_NOTIFIER(*this, userPtr));
434 userPtr->GetProperties().tariffName.AddAfterNotifier(&notifiers.back());
435 }
436
437 void SMUX::UnsetNotifier(UserPtr userPtr)
438 {
439 std::list<CHG_AFTER_NOTIFIER>::iterator it = notifiers.begin();
440 while (it != notifiers.end())
441     {
442     if (it->GetUserPtr() == userPtr)
443         {
444         userPtr->GetProperties().tariffName.DelAfterNotifier(&(*it));
445         notifiers.erase(it);
446         break;
447         }
448     ++it;
449     }
450 }
451
452 void SMUX::SetNotifiers()
453 {
454 int h = users->OpenSearch();
455 assert(h && "USERS::OpenSearch is always correct");
456
457 UserPtr u;
458 while (!users->SearchNext(h, &u))
459     SetNotifier(u);
460
461 users->CloseSearch(h);
462
463 users->AddNotifierUserAdd(&addUserNotifier);
464 users->AddNotifierUserDel(&delUserNotifier);
465
466 tariffs->AddNotifierAdd(&addDelTariffNotifier);
467 tariffs->AddNotifierDel(&addDelTariffNotifier);
468 }
469
470 void SMUX::ResetNotifiers()
471 {
472 tariffs->DelNotifierDel(&addDelTariffNotifier);
473 tariffs->DelNotifierAdd(&addDelTariffNotifier);
474
475 users->DelNotifierUserDel(&delUserNotifier);
476 users->DelNotifierUserAdd(&addUserNotifier);
477
478 std::list<CHG_AFTER_NOTIFIER>::iterator it(notifiers.begin());
479 while (it != notifiers.end())
480     {
481     it->GetUserPtr()->GetProperties().tariffName.DelAfterNotifier(&(*it));
482     ++it;
483     }
484 notifiers.clear();
485 }