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 * store,
46 Tariffs * tariffs, Services & svcs,
47 const Admin& sysAdmin)
53 WriteServLog(Logger::get()),
58 //-----------------------------------------------------------------------------
59 bool UsersImpl::FindByNameNonLock(const std::string & login, user_iter * user)
61 const auto iter = loginIndex.find(login);
62 if (iter == loginIndex.end())
68 //-----------------------------------------------------------------------------
69 bool UsersImpl::FindByNameNonLock(const std::string & login, const_user_iter * user) const
71 const auto iter = loginIndex.find(login);
72 if (iter == loginIndex.end())
78 //-----------------------------------------------------------------------------
79 int UsersImpl::FindByName(const std::string & login, UserPtr * user)
81 std::lock_guard<std::mutex> lock(m_mutex);
83 if (!FindByNameNonLock(login, &u))
88 //-----------------------------------------------------------------------------
89 int UsersImpl::FindByName(const std::string & login, ConstUserPtr * user) const
91 std::lock_guard<std::mutex> lock(m_mutex);
93 if (!FindByNameNonLock(login, &u))
98 //-----------------------------------------------------------------------------
99 bool UsersImpl::Exists(const std::string & login) const
101 std::lock_guard<std::mutex> lock(m_mutex);
102 const auto iter = loginIndex.find(login);
103 return iter != loginIndex.end();
105 //-----------------------------------------------------------------------------
106 bool UsersImpl::TariffInUse(const std::string & tariffName) const
108 std::lock_guard<std::mutex> lock(m_mutex);
109 auto iter = users.begin();
110 while (iter != users.end())
112 if (iter->GetProperties().tariffName.Get() == tariffName)
118 //-----------------------------------------------------------------------------
119 int UsersImpl::Add(const std::string & login, const Admin * admin)
121 std::lock_guard<std::mutex> lock(m_mutex);
122 const auto& priv = admin->priv();
124 if (priv.userAddDel == 0)
126 WriteServLog("%s tried to add user \'%s\'. Access denied.",
127 admin->logStr().c_str(), login.c_str());
131 if (m_store->AddUser(login) != 0)
134 UserImpl u(settings, m_store, m_tariffs, &m_sysAdmin, this, m_services);
138 u.SetPassiveTimeAsNewUser();
143 WriteServLog("%s User \'%s\' added.",
144 admin->logStr().c_str(), login.c_str());
150 AddUserIntoIndexes(users.begin());
153 // Fire all "on add" notifiers
154 auto ni = onAddNotifiers.begin();
155 while (ni != onAddNotifiers.end())
157 (*ni)->Notify(&users.front());
163 // Fire all "on add" implementation notifiers
164 auto ni = onAddNotifiersImpl.begin();
165 while (ni != onAddNotifiersImpl.end())
167 (*ni)->Notify(&users.front());
174 //-----------------------------------------------------------------------------
175 void UsersImpl::Del(const std::string & login, const Admin * admin)
177 const auto& priv = admin->priv();
180 if (priv.userAddDel == 0)
182 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
183 admin->logStr().c_str(), login.c_str());
189 std::lock_guard<std::mutex> lock(m_mutex);
191 if (!FindByNameNonLock(login, &u))
193 WriteServLog("%s tried to delete user \'%s\': not found.",
194 admin->logStr().c_str(),
203 auto ni = onDelNotifiers.begin();
204 while (ni != onDelNotifiers.end())
206 (*ni)->Notify(&(*u));
212 auto ni = onDelNotifiersImpl.begin();
213 while (ni != onDelNotifiersImpl.end())
215 (*ni)->Notify(&(*u));
221 std::lock_guard<std::mutex> lock(m_mutex);
227 utd.delTime = stgTime;
228 usersToDelete.push_back(utd);
230 DelUserFromIndexes(u);
232 WriteServLog("%s User \'%s\' deleted.",
233 admin->logStr().c_str(), login.c_str());
237 //-----------------------------------------------------------------------------
238 bool UsersImpl::Authorize(const std::string & login, uint32_t ip,
239 uint32_t enabledDirs, const Auth * auth)
242 std::lock_guard<std::mutex> lock(m_mutex);
243 if (!FindByNameNonLock(login, &iter))
245 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
249 if (FindByIPIdx(ip, iter))
251 if (iter->GetLogin() != login)
253 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
254 login.c_str(), inet_ntostring(ip).c_str(),
255 iter->GetLogin().c_str());
258 return iter->Authorize(ip, enabledDirs, auth) == 0;
261 if (iter->Authorize(ip, enabledDirs, auth) != 0)
267 //-----------------------------------------------------------------------------
268 bool UsersImpl::Unauthorize(const std::string & login,
270 const std::string & reason)
273 std::lock_guard<std::mutex> lock(m_mutex);
274 if (!FindByNameNonLock(login, &iter))
276 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
277 printfd(__FILE__, "Attempt to unauthorize non-existant user '%s'", login.c_str());
281 uint32_t ip = iter->GetCurrIP();
283 iter->Unauthorize(auth, reason);
285 if (iter->GetAuthorized() == 0)
290 //-----------------------------------------------------------------------------
291 int UsersImpl::ReadUsers()
293 std::vector<std::string> usersList;
295 if (m_store->GetUsersList(&usersList) < 0)
297 WriteServLog(m_store->GetStrError().c_str());
304 for (const auto& user : usersList)
306 UserImpl u(settings, m_store, m_tariffs, &m_sysAdmin, this, m_services);
312 AddUserIntoIndexes(ui);
314 if (settings->GetStopOnError())
316 if (ui->ReadConf() < 0)
319 if (ui->ReadStat() < 0)
324 if (ui->ReadConf() < 0)
327 if (ui->ReadStat() < 0)
336 //-----------------------------------------------------------------------------
337 void UsersImpl::Run(std::stop_token token)
340 sigfillset(&signalSet);
341 pthread_sigmask(SIG_BLOCK, &signalSet, nullptr);
343 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
347 localtime_r(&tt, &t);
352 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
354 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
355 std::string monFile = settings->GetMonitorDir() + "/users_r";
356 printfd(__FILE__, "Monitor=%d file USERS %s\n", settings->GetMonitoring(), monFile.c_str());
359 while (!token.stop_requested())
361 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
362 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
364 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
367 localtime_r(&tt, &t);
371 printfd(__FILE__,"Sec = %d\n", stgTime);
372 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
378 if (day != t.tm_mday)
380 printfd(__FILE__,"Sec = %d\n", stgTime);
381 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
386 if (settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
388 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
396 auto iter = usersToDelete.begin();
397 while (iter != usersToDelete.end())
399 iter->delTime -= 2 * userDeleteDelayTime;
407 //-----------------------------------------------------------------------------
408 void UsersImpl::NewMinute(const struct tm & t)
410 //Write traff, reset session traff. Fake disconnect-connect
411 if (t.tm_hour == 23 && t.tm_min == 59)
413 printfd(__FILE__,"MidnightResetSessionStat\n");
414 for_each(users.begin(), users.end(), [](auto& user){ user.MidnightResetSessionStat(); });
417 if (TimeToWriteDetailStat(t))
419 //printfd(__FILE__, "USER::WriteInetStat\n");
422 auto usr = users.begin();
423 while (usr != users.end())
426 usr->WriteDetailStat();
428 if (usersCnt % 10 == 0)
429 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
435 //-----------------------------------------------------------------------------
436 void UsersImpl::NewDay(const struct tm & t)
440 localtime_r(&tt, &t1);
441 int dayFee = settings->GetDayFee();
444 dayFee = DaysInCurrentMonth();
446 printfd(__FILE__, "DayFee = %d\n", dayFee);
447 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
448 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
450 if (!settings->GetDayFeeIsLastDay())
452 printfd(__FILE__, "DayResetTraff - 1 -\n");
454 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
457 if (settings->GetSpreadFee())
459 printfd(__FILE__, "Spread DayFee\n");
460 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFeeSpread(); });
464 if (t.tm_mday == dayFee)
466 printfd(__FILE__, "DayFee\n");
467 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFee(); });
471 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDailyFee(); });
472 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessServices(); });
474 if (settings->GetDayFeeIsLastDay())
476 printfd(__FILE__, "DayResetTraff - 2 -\n");
480 //-----------------------------------------------------------------------------
481 void UsersImpl::DayResetTraff(const struct tm & t1)
483 auto dayResetTraff = settings->GetDayResetTraff();
484 if (dayResetTraff == 0)
485 dayResetTraff = DaysInCurrentMonth();
486 if (t1.tm_mday == dayResetTraff)
488 printfd(__FILE__, "ResetTraff\n");
489 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessNewMonth(); });
490 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::SetPrepaidTraff));
493 //-----------------------------------------------------------------------------
494 int UsersImpl::Start()
496 if (ReadUsers() != 0)
498 WriteServLog("USERS: Error: Cannot read users!");
502 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
505 //-----------------------------------------------------------------------------
506 int UsersImpl::Stop()
508 printfd(__FILE__, "USERS::Stop()\n");
510 m_thread.request_stop();
512 //5 seconds to thread stops itself
513 struct timespec ts = {0, 200000000};
514 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
519 nanosleep(&ts, nullptr);
522 //after 5 seconds waiting thread still running. now kill it
525 printfd(__FILE__, "Detach USERS thread.\n");
526 //TODO pthread_cancel()
532 printfd(__FILE__, "Before USERS::Run()\n");
533 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
535 for (auto& user : users)
536 user.WriteDetailStat(true);
538 for_each(users.begin(), users.end(), [](auto& user){ user.WriteStat(); });
539 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::WriteConf));
541 printfd(__FILE__, "USERS::Stop()\n");
544 //-----------------------------------------------------------------------------
545 void UsersImpl::RealDelUser()
547 std::lock_guard<std::mutex> lock(m_mutex);
549 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
551 auto iter = usersToDelete.begin();
552 while (iter != usersToDelete.end())
554 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
555 if (iter->delTime + userDeleteDelayTime < stgTime)
557 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
558 if (m_store->DelUser(iter->iter->GetLogin()) != 0)
560 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
562 users.erase(iter->iter);
563 usersToDelete.erase(iter++);
571 //-----------------------------------------------------------------------------
572 void UsersImpl::AddToIPIdx(user_iter user)
574 printfd(__FILE__, "USERS: Add IP Idx\n");
575 uint32_t ip = user->GetCurrIP();
576 //assert(ip && "User has non-null ip");
578 return; // User has disconnected
580 std::lock_guard<std::mutex> lock(m_mutex);
582 const auto it = ipIndex.lower_bound(ip);
584 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
586 ipIndex.insert(it, std::make_pair(ip, user));
588 //-----------------------------------------------------------------------------
589 void UsersImpl::DelFromIPIdx(uint32_t ip)
591 printfd(__FILE__, "USERS: Del IP Idx\n");
592 assert(ip && "User has non-null ip");
594 std::lock_guard<std::mutex> lock(m_mutex);
596 const auto it = ipIndex.find(ip);
598 if (it == ipIndex.end())
603 //-----------------------------------------------------------------------------
604 bool UsersImpl::FindByIPIdx(uint32_t ip, user_iter & iter) const
606 auto it = ipIndex.find(ip);
607 if (it == ipIndex.end())
612 //-----------------------------------------------------------------------------
613 int UsersImpl::FindByIPIdx(uint32_t ip, UserPtr * user) const
615 std::lock_guard<std::mutex> lock(m_mutex);
618 if (FindByIPIdx(ip, iter))
626 //-----------------------------------------------------------------------------
627 int UsersImpl::FindByIPIdx(uint32_t ip, UserImpl ** user) const
629 std::lock_guard<std::mutex> lock(m_mutex);
632 if (FindByIPIdx(ip, iter))
640 //-----------------------------------------------------------------------------
641 bool UsersImpl::IsIPInIndex(uint32_t ip) const
643 std::lock_guard<std::mutex> lock(m_mutex);
645 return ipIndex.find(ip) != ipIndex.end();
647 //-----------------------------------------------------------------------------
648 bool UsersImpl::IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const
650 std::lock_guard<std::mutex> lock(m_mutex);
651 auto iter = users.begin();
652 while (iter != users.end())
654 if (iter->GetLogin() != login &&
655 !iter->GetProperties().ips.Get().isAnyIP() &&
656 iter->GetProperties().ips.Get().find(ip))
666 //-----------------------------------------------------------------------------
667 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserPtr> * n)
669 std::lock_guard<std::mutex> lock(m_mutex);
670 onAddNotifiers.insert(n);
672 //-----------------------------------------------------------------------------
673 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserPtr> * n)
675 std::lock_guard<std::mutex> lock(m_mutex);
676 onAddNotifiers.erase(n);
678 //-----------------------------------------------------------------------------
679 void UsersImpl::AddNotifierUserDel(NotifierBase<UserPtr> * n)
681 std::lock_guard<std::mutex> lock(m_mutex);
682 onDelNotifiers.insert(n);
684 //-----------------------------------------------------------------------------
685 void UsersImpl::DelNotifierUserDel(NotifierBase<UserPtr> * n)
687 std::lock_guard<std::mutex> lock(m_mutex);
688 onDelNotifiers.erase(n);
690 //-----------------------------------------------------------------------------
691 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserImplPtr> * n)
693 std::lock_guard<std::mutex> lock(m_mutex);
694 onAddNotifiersImpl.insert(n);
696 //-----------------------------------------------------------------------------
697 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserImplPtr> * n)
699 std::lock_guard<std::mutex> lock(m_mutex);
700 onAddNotifiersImpl.erase(n);
702 //-----------------------------------------------------------------------------
703 void UsersImpl::AddNotifierUserDel(NotifierBase<UserImplPtr> * n)
705 std::lock_guard<std::mutex> lock(m_mutex);
706 onDelNotifiersImpl.insert(n);
708 //-----------------------------------------------------------------------------
709 void UsersImpl::DelNotifierUserDel(NotifierBase<UserImplPtr> * n)
711 std::lock_guard<std::mutex> lock(m_mutex);
712 onDelNotifiersImpl.erase(n);
714 //-----------------------------------------------------------------------------
715 unsigned int UsersImpl::OpenSearch()
717 std::lock_guard<std::mutex> lock(m_mutex);
719 searchDescriptors[handle] = users.begin();
722 //-----------------------------------------------------------------------------
723 int UsersImpl::SearchNext(int h, UserPtr * user)
725 UserImpl * ptr = nullptr;
726 if (SearchNext(h, &ptr) != 0)
731 //-----------------------------------------------------------------------------
732 int UsersImpl::SearchNext(int h, UserImpl ** user)
734 std::lock_guard<std::mutex> lock(m_mutex);
736 if (searchDescriptors.find(h) == searchDescriptors.end())
738 WriteServLog("USERS. Incorrect search handle.");
742 if (searchDescriptors[h] == users.end())
745 while (searchDescriptors[h]->GetDeleted())
747 ++searchDescriptors[h];
748 if (searchDescriptors[h] == users.end())
754 *user = &(*searchDescriptors[h]);
756 ++searchDescriptors[h];
760 //-----------------------------------------------------------------------------
761 int UsersImpl::CloseSearch(int h)
763 std::lock_guard<std::mutex> lock(m_mutex);
764 if (searchDescriptors.find(h) != searchDescriptors.end())
766 searchDescriptors.erase(searchDescriptors.find(h));
770 WriteServLog("USERS. Incorrect search handle.");
773 //-----------------------------------------------------------------------------
774 void UsersImpl::AddUserIntoIndexes(user_iter user)
776 std::lock_guard<std::mutex> lock(m_mutex);
777 loginIndex.insert(make_pair(user->GetLogin(), user));
779 //-----------------------------------------------------------------------------
780 void UsersImpl::DelUserFromIndexes(user_iter user)
782 std::lock_guard<std::mutex> lock(m_mutex);
783 loginIndex.erase(user->GetLogin());
785 //-----------------------------------------------------------------------------
786 bool UsersImpl::TimeToWriteDetailStat(const struct tm & t)
788 auto statTime = settings->GetDetailStatWritePeriod();
797 if (t.tm_min % 30 == 0)
801 if (t.tm_min % 15 == 0)
805 if (t.tm_min % 10 == 0)