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.
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.
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
22 * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
34 #include "stg/settings.h"
35 #include "stg/common.h"
37 #include "users_impl.h"
38 #include "stg_timer.h"
40 extern volatile time_t stgTime;
44 //-----------------------------------------------------------------------------
45 UsersImpl::UsersImpl(SettingsImpl * s, Store * st,
46 Tariffs * t, Services & svcs,
53 WriteServLog(Logger::get()),
58 //-----------------------------------------------------------------------------
59 UsersImpl::~UsersImpl()
62 //-----------------------------------------------------------------------------
63 int UsersImpl::FindByNameNonLock(const std::string & login, user_iter * user)
65 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
66 if (iter == loginIndex.end())
72 //-----------------------------------------------------------------------------
73 int UsersImpl::FindByNameNonLock(const std::string & login, const_user_iter * user) const
75 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
76 if (iter == loginIndex.end())
82 //-----------------------------------------------------------------------------
83 int UsersImpl::FindByName(const std::string & login, UserPtr * user)
85 std::lock_guard<std::mutex> lock(m_mutex);
87 if (FindByNameNonLock(login, &u))
92 //-----------------------------------------------------------------------------
93 int UsersImpl::FindByName(const std::string & login, ConstUserPtr * user) const
95 std::lock_guard<std::mutex> lock(m_mutex);
97 if (FindByNameNonLock(login, &u))
102 //-----------------------------------------------------------------------------
103 bool UsersImpl::Exists(const std::string & login) const
105 std::lock_guard<std::mutex> lock(m_mutex);
106 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
107 return iter != loginIndex.end();
109 //-----------------------------------------------------------------------------
110 bool UsersImpl::TariffInUse(const std::string & tariffName) const
112 std::lock_guard<std::mutex> lock(m_mutex);
113 std::list<UserImpl>::const_iterator iter;
114 iter = users.begin();
115 while (iter != users.end())
117 if (iter->GetProperties().tariffName.Get() == tariffName)
123 //-----------------------------------------------------------------------------
124 int UsersImpl::Add(const std::string & login, const Admin * admin)
126 std::lock_guard<std::mutex> lock(m_mutex);
127 const auto& priv = admin->priv();
129 if (!priv.userAddDel)
131 WriteServLog("%s tried to add user \'%s\'. Access denied.",
132 admin->logStr().c_str(), login.c_str());
136 if (store->AddUser(login))
139 UserImpl u(settings, store, tariffs, &sysAdmin, this, m_services);
143 u.SetPassiveTimeAsNewUser();
148 WriteServLog("%s User \'%s\' added.",
149 admin->logStr().c_str(), login.c_str());
155 AddUserIntoIndexes(users.begin());
158 // Fire all "on add" notifiers
159 std::set<NotifierBase<UserPtr> *>::iterator ni = onAddNotifiers.begin();
160 while (ni != onAddNotifiers.end())
162 (*ni)->Notify(&users.front());
168 // Fire all "on add" implementation notifiers
169 std::set<NotifierBase<UserImplPtr> *>::iterator ni = onAddNotifiersImpl.begin();
170 while (ni != onAddNotifiersImpl.end())
172 (*ni)->Notify(&users.front());
179 //-----------------------------------------------------------------------------
180 void UsersImpl::Del(const std::string & login, const Admin * admin)
182 const auto& priv = admin->priv();
185 if (!priv.userAddDel)
187 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
188 admin->logStr().c_str(), login.c_str());
194 std::lock_guard<std::mutex> lock(m_mutex);
196 if (FindByNameNonLock(login, &u))
198 WriteServLog("%s tried to delete user \'%s\': not found.",
199 admin->logStr().c_str(),
208 std::set<NotifierBase<UserPtr> *>::iterator ni = onDelNotifiers.begin();
209 while (ni != onDelNotifiers.end())
211 (*ni)->Notify(&(*u));
217 std::set<NotifierBase<UserImplPtr> *>::iterator ni = onDelNotifiersImpl.begin();
218 while (ni != onDelNotifiersImpl.end())
220 (*ni)->Notify(&(*u));
226 std::lock_guard<std::mutex> lock(m_mutex);
232 utd.delTime = stgTime;
233 usersToDelete.push_back(utd);
235 DelUserFromIndexes(u);
237 WriteServLog("%s User \'%s\' deleted.",
238 admin->logStr().c_str(), login.c_str());
242 //-----------------------------------------------------------------------------
243 bool UsersImpl::Authorize(const std::string & login, uint32_t ip,
244 uint32_t enabledDirs, const Auth * auth)
247 std::lock_guard<std::mutex> lock(m_mutex);
248 if (FindByNameNonLock(login, &iter))
250 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
254 if (FindByIPIdx(ip, iter))
256 if (iter->GetLogin() != login)
258 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
259 login.c_str(), inet_ntostring(ip).c_str(),
260 iter->GetLogin().c_str());
263 if (iter->Authorize(ip, enabledDirs, auth))
268 if (iter->Authorize(ip, enabledDirs, auth))
274 //-----------------------------------------------------------------------------
275 bool UsersImpl::Unauthorize(const std::string & login,
277 const std::string & reason)
280 std::lock_guard<std::mutex> lock(m_mutex);
281 if (FindByNameNonLock(login, &iter))
283 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
284 printfd(__FILE__, "Attempt to unauthorize non-existant user '%s'", login.c_str());
288 uint32_t ip = iter->GetCurrIP();
290 iter->Unauthorize(auth, reason);
292 if (!iter->GetAuthorized())
297 //-----------------------------------------------------------------------------
298 int UsersImpl::ReadUsers()
300 std::vector<std::string> usersList;
302 if (store->GetUsersList(&usersList) < 0)
304 WriteServLog(store->GetStrError().c_str());
311 for (unsigned int i = 0; i < usersList.size(); i++)
313 UserImpl u(settings, store, tariffs, &sysAdmin, this, m_services);
315 u.SetLogin(usersList[i]);
319 AddUserIntoIndexes(ui);
321 if (settings->GetStopOnError())
323 if (ui->ReadConf() < 0)
326 if (ui->ReadStat() < 0)
331 if (ui->ReadConf() < 0)
334 if (ui->ReadStat() < 0)
343 //-----------------------------------------------------------------------------
344 void UsersImpl::Run(std::stop_token token)
347 sigfillset(&signalSet);
348 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
350 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
354 localtime_r(&tt, &t);
359 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
361 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
362 std::string monFile = settings->GetMonitorDir() + "/users_r";
363 printfd(__FILE__, "Monitor=%d file USERS %s\n", settings->GetMonitoring(), monFile.c_str());
366 while (!token.stop_requested())
368 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
369 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
371 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
374 localtime_r(&tt, &t);
378 printfd(__FILE__,"Sec = %d\n", stgTime);
379 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
385 if (day != t.tm_mday)
387 printfd(__FILE__,"Sec = %d\n", stgTime);
388 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
393 if (settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
395 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
403 std::list<USER_TO_DEL>::iterator iter(usersToDelete.begin());
404 while (iter != usersToDelete.end())
406 iter->delTime -= 2 * userDeleteDelayTime;
414 //-----------------------------------------------------------------------------
415 void UsersImpl::NewMinute(const struct tm & t)
417 //Write traff, reset session traff. Fake disconnect-connect
418 if (t.tm_hour == 23 && t.tm_min == 59)
420 printfd(__FILE__,"MidnightResetSessionStat\n");
421 for_each(users.begin(), users.end(), [](auto& user){ user.MidnightResetSessionStat(); });
424 if (TimeToWriteDetailStat(t))
426 //printfd(__FILE__, "USER::WriteInetStat\n");
429 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
430 std::list<UserImpl>::iterator usr = users.begin();
431 while (usr != users.end())
434 usr->WriteDetailStat();
436 if (usersCnt % 10 == 0)
437 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
443 //-----------------------------------------------------------------------------
444 void UsersImpl::NewDay(const struct tm & t)
448 localtime_r(&tt, &t1);
449 int dayFee = settings->GetDayFee();
452 dayFee = DaysInCurrentMonth();
454 printfd(__FILE__, "DayFee = %d\n", dayFee);
455 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
456 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
458 if (!settings->GetDayFeeIsLastDay())
460 printfd(__FILE__, "DayResetTraff - 1 -\n");
462 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
465 if (settings->GetSpreadFee())
467 printfd(__FILE__, "Spread DayFee\n");
468 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFeeSpread(); });
472 if (t.tm_mday == dayFee)
474 printfd(__FILE__, "DayFee\n");
475 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFee(); });
479 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDailyFee(); });
480 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessServices(); });
482 if (settings->GetDayFeeIsLastDay())
484 printfd(__FILE__, "DayResetTraff - 2 -\n");
488 //-----------------------------------------------------------------------------
489 void UsersImpl::DayResetTraff(const struct tm & t1)
491 int dayResetTraff = settings->GetDayResetTraff();
492 if (dayResetTraff == 0)
493 dayResetTraff = DaysInCurrentMonth();
494 if (t1.tm_mday == dayResetTraff)
496 printfd(__FILE__, "ResetTraff\n");
497 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessNewMonth(); });
498 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::SetPrepaidTraff));
501 //-----------------------------------------------------------------------------
502 int UsersImpl::Start()
506 WriteServLog("USERS: Error: Cannot read users!");
510 m_thread = std::jthread([this](auto token){ Run(token); });
513 //-----------------------------------------------------------------------------
514 int UsersImpl::Stop()
516 printfd(__FILE__, "USERS::Stop()\n");
518 m_thread.request_stop();
520 //5 seconds to thread stops itself
521 struct timespec ts = {0, 200000000};
522 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
527 nanosleep(&ts, NULL);
530 //after 5 seconds waiting thread still running. now kill it
533 printfd(__FILE__, "Detach USERS thread.\n");
534 //TODO pthread_cancel()
540 printfd(__FILE__, "Before USERS::Run()\n");
541 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
543 // 'cause bind2st accepts only constant first param
544 for (std::list<UserImpl>::iterator it = users.begin();
547 it->WriteDetailStat(true);
549 for_each(users.begin(), users.end(), [](auto& user){ user.WriteStat(); });
550 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::WriteConf));
552 printfd(__FILE__, "USERS::Stop()\n");
555 //-----------------------------------------------------------------------------
556 void UsersImpl::RealDelUser()
558 std::lock_guard<std::mutex> lock(m_mutex);
560 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
562 std::list<USER_TO_DEL>::iterator iter;
563 iter = usersToDelete.begin();
564 while (iter != usersToDelete.end())
566 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
567 if (iter->delTime + userDeleteDelayTime < stgTime)
569 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
570 if (store->DelUser(iter->iter->GetLogin()))
572 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
574 users.erase(iter->iter);
575 usersToDelete.erase(iter++);
584 //-----------------------------------------------------------------------------
585 void UsersImpl::AddToIPIdx(user_iter user)
587 printfd(__FILE__, "USERS: Add IP Idx\n");
588 uint32_t ip = user->GetCurrIP();
589 //assert(ip && "User has non-null ip");
591 return; // User has disconnected
593 std::lock_guard<std::mutex> lock(m_mutex);
595 const std::map<uint32_t, user_iter>::iterator it(
596 ipIndex.lower_bound(ip)
599 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
601 ipIndex.insert(it, std::make_pair(ip, user));
603 //-----------------------------------------------------------------------------
604 void UsersImpl::DelFromIPIdx(uint32_t ip)
606 printfd(__FILE__, "USERS: Del IP Idx\n");
607 assert(ip && "User has non-null ip");
609 std::lock_guard<std::mutex> lock(m_mutex);
611 const std::map<uint32_t, user_iter>::iterator it(
615 if (it == ipIndex.end())
620 //-----------------------------------------------------------------------------
621 bool UsersImpl::FindByIPIdx(uint32_t ip, user_iter & iter) const
623 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
624 if (it == ipIndex.end())
629 //-----------------------------------------------------------------------------
630 int UsersImpl::FindByIPIdx(uint32_t ip, UserPtr * usr) const
632 std::lock_guard<std::mutex> lock(m_mutex);
635 if (FindByIPIdx(ip, iter))
643 //-----------------------------------------------------------------------------
644 int UsersImpl::FindByIPIdx(uint32_t ip, UserImpl ** usr) const
646 std::lock_guard<std::mutex> lock(m_mutex);
649 if (FindByIPIdx(ip, iter))
657 //-----------------------------------------------------------------------------
658 bool UsersImpl::IsIPInIndex(uint32_t ip) const
660 std::lock_guard<std::mutex> lock(m_mutex);
662 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
664 return it != ipIndex.end();
666 //-----------------------------------------------------------------------------
667 bool UsersImpl::IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const
669 std::lock_guard<std::mutex> lock(m_mutex);
670 std::list<UserImpl>::const_iterator iter;
671 iter = users.begin();
672 while (iter != users.end())
674 if (iter->GetLogin() != login &&
675 !iter->GetProperties().ips.Get().isAnyIP() &&
676 iter->GetProperties().ips.Get().find(ip))
686 //-----------------------------------------------------------------------------
687 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserPtr> * n)
689 std::lock_guard<std::mutex> lock(m_mutex);
690 onAddNotifiers.insert(n);
692 //-----------------------------------------------------------------------------
693 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserPtr> * n)
695 std::lock_guard<std::mutex> lock(m_mutex);
696 onAddNotifiers.erase(n);
698 //-----------------------------------------------------------------------------
699 void UsersImpl::AddNotifierUserDel(NotifierBase<UserPtr> * n)
701 std::lock_guard<std::mutex> lock(m_mutex);
702 onDelNotifiers.insert(n);
704 //-----------------------------------------------------------------------------
705 void UsersImpl::DelNotifierUserDel(NotifierBase<UserPtr> * n)
707 std::lock_guard<std::mutex> lock(m_mutex);
708 onDelNotifiers.erase(n);
710 //-----------------------------------------------------------------------------
711 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserImplPtr> * n)
713 std::lock_guard<std::mutex> lock(m_mutex);
714 onAddNotifiersImpl.insert(n);
716 //-----------------------------------------------------------------------------
717 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserImplPtr> * n)
719 std::lock_guard<std::mutex> lock(m_mutex);
720 onAddNotifiersImpl.erase(n);
722 //-----------------------------------------------------------------------------
723 void UsersImpl::AddNotifierUserDel(NotifierBase<UserImplPtr> * n)
725 std::lock_guard<std::mutex> lock(m_mutex);
726 onDelNotifiersImpl.insert(n);
728 //-----------------------------------------------------------------------------
729 void UsersImpl::DelNotifierUserDel(NotifierBase<UserImplPtr> * n)
731 std::lock_guard<std::mutex> lock(m_mutex);
732 onDelNotifiersImpl.erase(n);
734 //-----------------------------------------------------------------------------
735 int UsersImpl::OpenSearch()
737 std::lock_guard<std::mutex> lock(m_mutex);
739 searchDescriptors[handle] = users.begin();
742 //-----------------------------------------------------------------------------
743 int UsersImpl::SearchNext(int h, UserPtr * user)
745 UserImpl * ptr = NULL;
746 if (SearchNext(h, &ptr))
751 //-----------------------------------------------------------------------------
752 int UsersImpl::SearchNext(int h, UserImpl ** user)
754 std::lock_guard<std::mutex> lock(m_mutex);
756 if (searchDescriptors.find(h) == searchDescriptors.end())
758 WriteServLog("USERS. Incorrect search handle.");
762 if (searchDescriptors[h] == users.end())
765 while (searchDescriptors[h]->GetDeleted())
767 ++searchDescriptors[h];
768 if (searchDescriptors[h] == users.end())
774 *user = &(*searchDescriptors[h]);
776 ++searchDescriptors[h];
780 //-----------------------------------------------------------------------------
781 int UsersImpl::CloseSearch(int h)
783 std::lock_guard<std::mutex> lock(m_mutex);
784 if (searchDescriptors.find(h) != searchDescriptors.end())
786 searchDescriptors.erase(searchDescriptors.find(h));
790 WriteServLog("USERS. Incorrect search handle.");
793 //-----------------------------------------------------------------------------
794 void UsersImpl::AddUserIntoIndexes(user_iter user)
796 std::lock_guard<std::mutex> lock(m_mutex);
797 loginIndex.insert(make_pair(user->GetLogin(), user));
799 //-----------------------------------------------------------------------------
800 void UsersImpl::DelUserFromIndexes(user_iter user)
802 std::lock_guard<std::mutex> lock(m_mutex);
803 loginIndex.erase(user->GetLogin());
805 //-----------------------------------------------------------------------------
806 bool UsersImpl::TimeToWriteDetailStat(const struct tm & t)
808 int statTime = settings->GetDetailStatWritePeriod();
817 if (t.tm_min % 30 == 0)
821 if (t.tm_min % 15 == 0)
825 if (t.tm_min % 10 == 0)