]> git.stg.codes - stg.git/blob - projects/stargazer/users_impl.cpp
Use std::lock_guard instead of STG_LOCKER.
[stg.git] / projects / stargazer / users_impl.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18  *    Date: 27.10.2002
19  */
20
21 /*
22  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
23  */
24
25 #include <pthread.h>
26
27 #include <csignal>
28 #include <cassert>
29 #include <algorithm>
30 #include <utility>
31 #include <string>
32 #include <vector>
33
34 #include "stg/settings.h"
35 #include "stg/common.h"
36
37 #include "users_impl.h"
38 #include "stg_timer.h"
39
40 extern volatile time_t stgTime;
41
42 using STG::UsersImpl;
43
44 //-----------------------------------------------------------------------------
45 UsersImpl::UsersImpl(SettingsImpl * s, Store * store,
46                     Tariffs * tariffs, Services & svcs,
47                     const Admin& sysAdmin)
48     : settings(s),
49       m_tariffs(tariffs),
50       m_services(svcs),
51       m_store(store),
52       m_sysAdmin(sysAdmin),
53       WriteServLog(Logger::get()),
54       isRunning(false),
55       handle(0)
56 {
57 }
58 //-----------------------------------------------------------------------------
59 bool UsersImpl::FindByNameNonLock(const std::string & login, user_iter * user)
60 {
61 const auto iter = loginIndex.find(login);
62 if (iter == loginIndex.end())
63     return false;
64 if (user != nullptr)
65     *user = iter->second;
66 return true;
67 }
68 //-----------------------------------------------------------------------------
69 bool UsersImpl::FindByNameNonLock(const std::string & login, const_user_iter * user) const
70 {
71 const auto iter = loginIndex.find(login);
72 if (iter == loginIndex.end())
73     return false;
74 if (user != nullptr)
75     *user = iter->second;
76 return true;
77 }
78 //-----------------------------------------------------------------------------
79 int UsersImpl::FindByName(const std::string & login, UserPtr * user)
80 {
81 std::lock_guard<std::mutex> lock(m_mutex);
82 user_iter u;
83 if (!FindByNameNonLock(login, &u))
84     return -1;
85 *user = &(*u);
86 return 0;
87 }
88 //-----------------------------------------------------------------------------
89 int UsersImpl::FindByName(const std::string & login, ConstUserPtr * user) const
90 {
91 std::lock_guard<std::mutex> lock(m_mutex);
92 const_user_iter u;
93 if (!FindByNameNonLock(login, &u))
94     return -1;
95 *user = &(*u);
96 return 0;
97 }
98 //-----------------------------------------------------------------------------
99 bool UsersImpl::Exists(const std::string & login) const
100 {
101 std::lock_guard<std::mutex> lock(m_mutex);
102 const auto iter = loginIndex.find(login);
103 return iter != loginIndex.end();
104 }
105 //-----------------------------------------------------------------------------
106 bool UsersImpl::TariffInUse(const std::string & tariffName) const
107 {
108 std::lock_guard<std::mutex> lock(m_mutex);
109 auto iter = users.begin();
110 while (iter != users.end())
111     {
112     if (iter->GetProperties().tariffName.Get() == tariffName)
113         return true;
114     ++iter;
115     }
116 return false;
117 }
118 //-----------------------------------------------------------------------------
119 int UsersImpl::Add(const std::string & login, const Admin * admin)
120 {
121 std::lock_guard<std::mutex> lock(m_mutex);
122 const auto& priv = admin->priv();
123
124 if (priv.userAddDel == 0)
125     {
126     WriteServLog("%s tried to add user \'%s\'. Access denied.",
127                  admin->logStr().c_str(), login.c_str());
128     return -1;
129     }
130
131 if (m_store->AddUser(login) != 0)
132     return -1;
133
134 UserImpl u(settings, m_store, m_tariffs, &m_sysAdmin, this, m_services);
135
136 u.SetLogin(login);
137
138 u.SetPassiveTimeAsNewUser();
139
140 u.WriteConf();
141 u.WriteStat();
142
143 WriteServLog("%s User \'%s\' added.",
144              admin->logStr().c_str(), login.c_str());
145
146 u.OnAdd();
147
148 users.push_front(u);
149
150 AddUserIntoIndexes(users.begin());
151 m_onAddCallbacks.notify(&users.front());
152 m_onAddImplCallbacks.notify(&users.front());
153
154 return 0;
155 }
156 //-----------------------------------------------------------------------------
157 void UsersImpl::Del(const std::string & login, const Admin * admin)
158 {
159 const auto& priv = admin->priv();
160 user_iter u;
161
162 if (priv.userAddDel == 0)
163     {
164     WriteServLog("%s tried to remove user \'%s\'. Access denied.",
165                  admin->logStr().c_str(), login.c_str());
166     return;
167     }
168
169
170     {
171     std::lock_guard<std::mutex> lock(m_mutex);
172
173     if (!FindByNameNonLock(login, &u))
174         {
175         WriteServLog("%s tried to delete user \'%s\': not found.",
176                      admin->logStr().c_str(),
177                      login.c_str());
178         return;
179         }
180
181     u->SetDeleted();
182     }
183
184     m_onDelCallbacks.notify(&(*u));
185     m_onDelImplCallbacks.notify(&(*u));
186
187     {
188     std::lock_guard<std::mutex> lock(m_mutex);
189
190     u->OnDelete();
191
192     USER_TO_DEL utd;
193     utd.iter = u;
194     utd.delTime = stgTime;
195     usersToDelete.push_back(utd);
196
197     DelUserFromIndexes(u);
198
199     WriteServLog("%s User \'%s\' deleted.",
200                  admin->logStr().c_str(), login.c_str());
201
202     }
203 }
204 //-----------------------------------------------------------------------------
205 bool UsersImpl::Authorize(const std::string & login, uint32_t ip,
206                            uint32_t enabledDirs, const Auth * auth)
207 {
208 user_iter iter;
209 std::lock_guard<std::mutex> lock(m_mutex);
210 if (!FindByNameNonLock(login, &iter))
211     {
212     WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
213     return false;
214     }
215
216 if (FindByIPIdx(ip, iter))
217     {
218     if (iter->GetLogin() != login)
219         {
220         WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
221                      login.c_str(), inet_ntostring(ip).c_str(),
222                      iter->GetLogin().c_str());
223         return false;
224         }
225     return iter->Authorize(ip, enabledDirs, auth) == 0;
226     }
227
228 if (iter->Authorize(ip, enabledDirs, auth) != 0)
229     return false;
230
231 AddToIPIdx(iter);
232 return true;
233 }
234 //-----------------------------------------------------------------------------
235 bool UsersImpl::Unauthorize(const std::string & login,
236                              const Auth * auth,
237                              const std::string & reason)
238 {
239 user_iter iter;
240 std::lock_guard<std::mutex> lock(m_mutex);
241 if (!FindByNameNonLock(login, &iter))
242     {
243     WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
244     printfd(__FILE__, "Attempt to unauthorize non-existant user '%s'", login.c_str());
245     return false;
246     }
247
248 uint32_t ip = iter->GetCurrIP();
249
250 iter->Unauthorize(auth, reason);
251
252 if (iter->GetAuthorized() == 0)
253     DelFromIPIdx(ip);
254
255 return true;
256 }
257 //-----------------------------------------------------------------------------
258 int UsersImpl::ReadUsers()
259 {
260 std::vector<std::string> usersList;
261 usersList.clear();
262 if (m_store->GetUsersList(&usersList) < 0)
263     {
264     WriteServLog(m_store->GetStrError().c_str());
265     return -1;
266     }
267
268 user_iter ui;
269
270 unsigned errors = 0;
271 for (const auto& user : usersList)
272     {
273     UserImpl u(settings, m_store, m_tariffs, &m_sysAdmin, this, m_services);
274
275     u.SetLogin(user);
276     users.push_front(u);
277     ui = users.begin();
278
279     AddUserIntoIndexes(ui);
280
281     if (settings->GetStopOnError())
282         {
283         if (ui->ReadConf() < 0)
284             return -1;
285
286         if (ui->ReadStat() < 0)
287             return -1;
288         }
289     else
290         {
291         if (ui->ReadConf() < 0)
292             errors++;
293
294         if (ui->ReadStat() < 0)
295             errors++;
296         }
297     }
298
299 if (errors > 0)
300     return -1;
301 return 0;
302 }
303 //-----------------------------------------------------------------------------
304 void UsersImpl::Run(std::stop_token token)
305 {
306 sigset_t signalSet;
307 sigfillset(&signalSet);
308 pthread_sigmask(SIG_BLOCK, &signalSet, nullptr);
309
310 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
311
312 struct tm t;
313 time_t tt = stgTime;
314 localtime_r(&tt, &t);
315
316 int min = t.tm_min;
317 int day = t.tm_mday;
318
319 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
320
321 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
322 std::string monFile = settings->GetMonitorDir() + "/users_r";
323 printfd(__FILE__, "Monitor=%d file USERS %s\n", settings->GetMonitoring(), monFile.c_str());
324
325 isRunning = true;
326 while (!token.stop_requested())
327     {
328     //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
329     //printfd(__FILE__,"New Day.    old = %2d current = %2d\n", day, t->tm_mday);
330
331     for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
332
333     tt = stgTime;
334     localtime_r(&tt, &t);
335
336     if (min != t.tm_min)
337         {
338         printfd(__FILE__,"Sec = %d\n", stgTime);
339         printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
340         min = t.tm_min;
341
342         NewMinute(t);
343         }
344
345     if (day != t.tm_mday)
346         {
347         printfd(__FILE__,"Sec = %d\n", stgTime);
348         printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
349         day = t.tm_mday;
350         NewDay(t);
351         }
352
353     if (settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
354         {
355         //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
356         touchTime = stgTime;
357         TouchFile(monFile);
358         }
359
360     stgUsleep(100000);
361     }
362
363 auto iter = usersToDelete.begin();
364 while (iter != usersToDelete.end())
365     {
366     iter->delTime -= 2 * userDeleteDelayTime;
367     ++iter;
368     }
369 RealDelUser();
370
371 isRunning = false;
372
373 }
374 //-----------------------------------------------------------------------------
375 void UsersImpl::NewMinute(const struct tm & t)
376 {
377 //Write traff, reset session traff. Fake disconnect-connect
378 if (t.tm_hour == 23 && t.tm_min == 59)
379     {
380     printfd(__FILE__,"MidnightResetSessionStat\n");
381     for_each(users.begin(), users.end(), [](auto& user){ user.MidnightResetSessionStat(); });
382     }
383
384 if (TimeToWriteDetailStat(t))
385     {
386     //printfd(__FILE__, "USER::WriteInetStat\n");
387     int usersCnt = 0;
388
389     auto usr = users.begin();
390     while (usr != users.end())
391         {
392         usersCnt++;
393         usr->WriteDetailStat();
394         ++usr;
395         if (usersCnt % 10 == 0)
396             for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
397         }
398     }
399
400 RealDelUser();
401 }
402 //-----------------------------------------------------------------------------
403 void UsersImpl::NewDay(const struct tm & t)
404 {
405 struct tm t1;
406 time_t tt = stgTime;
407 localtime_r(&tt, &t1);
408 int dayFee = settings->GetDayFee();
409
410 if (dayFee == 0)
411     dayFee = DaysInCurrentMonth();
412
413 printfd(__FILE__, "DayFee = %d\n", dayFee);
414 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
415 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
416
417 if (!settings->GetDayFeeIsLastDay())
418     {
419     printfd(__FILE__, "DayResetTraff - 1 -\n");
420     DayResetTraff(t1);
421     //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
422     }
423
424 if (settings->GetSpreadFee())
425     {
426     printfd(__FILE__, "Spread DayFee\n");
427     for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFeeSpread(); });
428     }
429 else
430     {
431     if (t.tm_mday == dayFee)
432         {
433         printfd(__FILE__, "DayFee\n");
434         for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFee(); });
435         }
436     }
437
438 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDailyFee(); });
439 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessServices(); });
440
441 if (settings->GetDayFeeIsLastDay())
442     {
443     printfd(__FILE__, "DayResetTraff - 2 -\n");
444     DayResetTraff(t1);
445     }
446 }
447 //-----------------------------------------------------------------------------
448 void UsersImpl::DayResetTraff(const struct tm & t1)
449 {
450 auto dayResetTraff = settings->GetDayResetTraff();
451 if (dayResetTraff == 0)
452     dayResetTraff = DaysInCurrentMonth();
453 if (static_cast<unsigned>(t1.tm_mday) == dayResetTraff)
454     {
455     printfd(__FILE__, "ResetTraff\n");
456     for_each(users.begin(), users.end(), [](auto& user){ user.ProcessNewMonth(); });
457     //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::SetPrepaidTraff));
458     }
459 }
460 //-----------------------------------------------------------------------------
461 int UsersImpl::Start()
462 {
463 if (ReadUsers() != 0)
464     {
465     WriteServLog("USERS: Error: Cannot read users!");
466     return -1;
467     }
468
469 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
470 return 0;
471 }
472 //-----------------------------------------------------------------------------
473 int UsersImpl::Stop()
474 {
475 printfd(__FILE__, "USERS::Stop()\n");
476
477 m_thread.request_stop();
478
479 //5 seconds to thread stops itself
480 struct timespec ts = {0, 200000000};
481 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
482     {
483     if (!isRunning)
484         break;
485
486     nanosleep(&ts, nullptr);
487     }
488
489 //after 5 seconds waiting thread still running. now kill it
490 if (isRunning)
491     {
492     printfd(__FILE__, "Detach USERS thread.\n");
493     //TODO pthread_cancel()
494     m_thread.detach();
495     }
496 else
497     m_thread.join();
498
499 printfd(__FILE__, "Before USERS::Run()\n");
500 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
501
502 for (auto& user : users)
503     user.WriteDetailStat(true);
504
505 for_each(users.begin(), users.end(), [](auto& user){ user.WriteStat(); });
506 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::WriteConf));
507
508 printfd(__FILE__, "USERS::Stop()\n");
509 return 0;
510 }
511 //-----------------------------------------------------------------------------
512 void UsersImpl::RealDelUser()
513 {
514 std::lock_guard<std::mutex> lock(m_mutex);
515
516 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
517
518 auto iter = usersToDelete.begin();
519 while (iter != usersToDelete.end())
520     {
521     printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
522     if (iter->delTime + userDeleteDelayTime < stgTime)
523         {
524         printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
525         if (m_store->DelUser(iter->iter->GetLogin()) != 0)
526             {
527             WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
528             }
529         users.erase(iter->iter);
530         usersToDelete.erase(iter++);
531         }
532     else
533         {
534         ++iter;
535         }
536     }
537 }
538 //-----------------------------------------------------------------------------
539 void UsersImpl::AddToIPIdx(user_iter user)
540 {
541 printfd(__FILE__, "USERS: Add IP Idx\n");
542 uint32_t ip = user->GetCurrIP();
543 //assert(ip && "User has non-null ip");
544 if (ip == 0)
545     return; // User has disconnected
546
547 std::lock_guard<std::mutex> lock(m_mutex);
548
549 const auto it = ipIndex.lower_bound(ip);
550
551 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
552
553 ipIndex.insert(it, std::make_pair(ip, user));
554 }
555 //-----------------------------------------------------------------------------
556 void UsersImpl::DelFromIPIdx(uint32_t ip)
557 {
558 printfd(__FILE__, "USERS: Del IP Idx\n");
559 assert(ip && "User has non-null ip");
560
561 std::lock_guard<std::mutex> lock(m_mutex);
562
563 const auto it = ipIndex.find(ip);
564
565 if (it == ipIndex.end())
566     return;
567
568 ipIndex.erase(it);
569 }
570 //-----------------------------------------------------------------------------
571 bool UsersImpl::FindByIPIdx(uint32_t ip, user_iter & iter) const
572 {
573 auto it = ipIndex.find(ip);
574 if (it == ipIndex.end())
575     return false;
576 iter = it->second;
577 return true;
578 }
579 //-----------------------------------------------------------------------------
580 int UsersImpl::FindByIPIdx(uint32_t ip, UserPtr * user) const
581 {
582 std::lock_guard<std::mutex> lock(m_mutex);
583
584 user_iter iter;
585 if (FindByIPIdx(ip, iter))
586     {
587     *user = &(*iter);
588     return 0;
589     }
590
591 return -1;
592 }
593 //-----------------------------------------------------------------------------
594 int UsersImpl::FindByIPIdx(uint32_t ip, UserImpl ** user) const
595 {
596 std::lock_guard<std::mutex> lock(m_mutex);
597
598 user_iter iter;
599 if (FindByIPIdx(ip, iter))
600     {
601     *user = &(*iter);
602     return 0;
603     }
604
605 return -1;
606 }
607 //-----------------------------------------------------------------------------
608 bool UsersImpl::IsIPInIndex(uint32_t ip) const
609 {
610 std::lock_guard<std::mutex> lock(m_mutex);
611
612 return ipIndex.find(ip) != ipIndex.end();
613 }
614 //-----------------------------------------------------------------------------
615 bool UsersImpl::IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const
616 {
617 std::lock_guard<std::mutex> lock(m_mutex);
618 auto iter = users.begin();
619 while (iter != users.end())
620     {
621     if (iter->GetLogin() != login &&
622         !iter->GetProperties().ips.Get().isAnyIP() &&
623         iter->GetProperties().ips.Get().find(ip))
624         {
625         if (user != nullptr)
626             *user = &(*iter);
627         return true;
628         }
629     ++iter;
630     }
631 return false;
632 }
633 //-----------------------------------------------------------------------------
634 unsigned int UsersImpl::OpenSearch()
635 {
636 std::lock_guard<std::mutex> lock(m_mutex);
637 handle++;
638 searchDescriptors[handle] = users.begin();
639 return handle;
640 }
641 //-----------------------------------------------------------------------------
642 int UsersImpl::SearchNext(int h, UserPtr * user)
643 {
644     UserImpl * ptr = nullptr;
645     if (SearchNext(h, &ptr) != 0)
646         return -1;
647     *user = ptr;
648     return 0;
649 }
650 //-----------------------------------------------------------------------------
651 int UsersImpl::SearchNext(int h, UserImpl ** user)
652 {
653 std::lock_guard<std::mutex> lock(m_mutex);
654
655 if (searchDescriptors.find(h) == searchDescriptors.end())
656     {
657     WriteServLog("USERS. Incorrect search handle.");
658     return -1;
659     }
660
661 if (searchDescriptors[h] == users.end())
662     return -1;
663
664 while (searchDescriptors[h]->GetDeleted())
665     {
666     ++searchDescriptors[h];
667     if (searchDescriptors[h] == users.end())
668         {
669         return -1;
670         }
671     }
672
673 *user = &(*searchDescriptors[h]);
674
675 ++searchDescriptors[h];
676
677 return 0;
678 }
679 //-----------------------------------------------------------------------------
680 int UsersImpl::CloseSearch(int h)
681 {
682 std::lock_guard<std::mutex> lock(m_mutex);
683 if (searchDescriptors.find(h) != searchDescriptors.end())
684     {
685     searchDescriptors.erase(searchDescriptors.find(h));
686     return 0;
687     }
688
689 WriteServLog("USERS. Incorrect search handle.");
690 return -1;
691 }
692 //-----------------------------------------------------------------------------
693 void UsersImpl::AddUserIntoIndexes(user_iter user)
694 {
695 std::lock_guard<std::mutex> lock(m_mutex);
696 loginIndex.insert(make_pair(user->GetLogin(), user));
697 }
698 //-----------------------------------------------------------------------------
699 void UsersImpl::DelUserFromIndexes(user_iter user)
700 {
701 std::lock_guard<std::mutex> lock(m_mutex);
702 loginIndex.erase(user->GetLogin());
703 }
704 //-----------------------------------------------------------------------------
705 bool UsersImpl::TimeToWriteDetailStat(const struct tm & t)
706 {
707 auto statTime = settings->GetDetailStatWritePeriod();
708
709 switch (statTime)
710     {
711     case dsPeriod_1:
712         if (t.tm_min == 0)
713             return true;
714         break;
715     case dsPeriod_1_2:
716         if (t.tm_min % 30 == 0)
717             return true;
718         break;
719     case dsPeriod_1_4:
720         if (t.tm_min % 15 == 0)
721             return true;
722         break;
723     case dsPeriod_1_6:
724         if (t.tm_min % 10 == 0)
725             return true;
726         break;
727     }
728 return false;
729 }