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());
151 m_onAddCallbacks.notify(&users.front());
152 m_onAddImplCallbacks.notify(&users.front());
156 //-----------------------------------------------------------------------------
157 void UsersImpl::Del(const std::string & login, const Admin * admin)
159 const auto& priv = admin->priv();
162 if (priv.userAddDel == 0)
164 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
165 admin->logStr().c_str(), login.c_str());
171 std::lock_guard<std::mutex> lock(m_mutex);
173 if (!FindByNameNonLock(login, &u))
175 WriteServLog("%s tried to delete user \'%s\': not found.",
176 admin->logStr().c_str(),
184 m_onDelCallbacks.notify(&(*u));
185 m_onDelImplCallbacks.notify(&(*u));
188 std::lock_guard<std::mutex> lock(m_mutex);
194 utd.delTime = stgTime;
195 usersToDelete.push_back(utd);
197 DelUserFromIndexes(u);
199 WriteServLog("%s User \'%s\' deleted.",
200 admin->logStr().c_str(), login.c_str());
204 //-----------------------------------------------------------------------------
205 bool UsersImpl::Authorize(const std::string & login, uint32_t ip,
206 uint32_t enabledDirs, const Auth * auth)
209 std::lock_guard<std::mutex> lock(m_mutex);
210 if (!FindByNameNonLock(login, &iter))
212 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
216 if (FindByIPIdx(ip, iter))
218 if (iter->GetLogin() != login)
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());
225 return iter->Authorize(ip, enabledDirs, auth) == 0;
228 if (iter->Authorize(ip, enabledDirs, auth) != 0)
234 //-----------------------------------------------------------------------------
235 bool UsersImpl::Unauthorize(const std::string & login,
237 const std::string & reason)
240 std::lock_guard<std::mutex> lock(m_mutex);
241 if (!FindByNameNonLock(login, &iter))
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());
248 uint32_t ip = iter->GetCurrIP();
250 iter->Unauthorize(auth, reason);
252 if (iter->GetAuthorized() == 0)
257 //-----------------------------------------------------------------------------
258 int UsersImpl::ReadUsers()
260 std::vector<std::string> usersList;
262 if (m_store->GetUsersList(&usersList) < 0)
264 WriteServLog(m_store->GetStrError().c_str());
271 for (const auto& user : usersList)
273 UserImpl u(settings, m_store, m_tariffs, &m_sysAdmin, this, m_services);
279 AddUserIntoIndexes(ui);
281 if (settings->GetStopOnError())
283 if (ui->ReadConf() < 0)
286 if (ui->ReadStat() < 0)
291 if (ui->ReadConf() < 0)
294 if (ui->ReadStat() < 0)
303 //-----------------------------------------------------------------------------
304 void UsersImpl::Run(std::stop_token token)
307 sigfillset(&signalSet);
308 pthread_sigmask(SIG_BLOCK, &signalSet, nullptr);
310 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
314 localtime_r(&tt, &t);
319 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
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());
326 while (!token.stop_requested())
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);
331 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
334 localtime_r(&tt, &t);
338 printfd(__FILE__,"Sec = %d\n", stgTime);
339 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
345 if (day != t.tm_mday)
347 printfd(__FILE__,"Sec = %d\n", stgTime);
348 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
353 if (settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
355 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
363 auto iter = usersToDelete.begin();
364 while (iter != usersToDelete.end())
366 iter->delTime -= 2 * userDeleteDelayTime;
374 //-----------------------------------------------------------------------------
375 void UsersImpl::NewMinute(const struct tm & t)
377 //Write traff, reset session traff. Fake disconnect-connect
378 if (t.tm_hour == 23 && t.tm_min == 59)
380 printfd(__FILE__,"MidnightResetSessionStat\n");
381 for_each(users.begin(), users.end(), [](auto& user){ user.MidnightResetSessionStat(); });
384 if (TimeToWriteDetailStat(t))
386 //printfd(__FILE__, "USER::WriteInetStat\n");
389 auto usr = users.begin();
390 while (usr != users.end())
393 usr->WriteDetailStat();
395 if (usersCnt % 10 == 0)
396 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
402 //-----------------------------------------------------------------------------
403 void UsersImpl::NewDay(const struct tm & t)
407 localtime_r(&tt, &t1);
408 int dayFee = settings->GetDayFee();
411 dayFee = DaysInCurrentMonth();
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());
417 if (!settings->GetDayFeeIsLastDay())
419 printfd(__FILE__, "DayResetTraff - 1 -\n");
421 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
424 if (settings->GetSpreadFee())
426 printfd(__FILE__, "Spread DayFee\n");
427 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFeeSpread(); });
431 if (t.tm_mday == dayFee)
433 printfd(__FILE__, "DayFee\n");
434 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFee(); });
438 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDailyFee(); });
439 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessServices(); });
441 if (settings->GetDayFeeIsLastDay())
443 printfd(__FILE__, "DayResetTraff - 2 -\n");
447 //-----------------------------------------------------------------------------
448 void UsersImpl::DayResetTraff(const struct tm & t1)
450 auto dayResetTraff = settings->GetDayResetTraff();
451 if (dayResetTraff == 0)
452 dayResetTraff = DaysInCurrentMonth();
453 if (static_cast<unsigned>(t1.tm_mday) == dayResetTraff)
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));
460 //-----------------------------------------------------------------------------
461 int UsersImpl::Start()
463 if (ReadUsers() != 0)
465 WriteServLog("USERS: Error: Cannot read users!");
469 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
472 //-----------------------------------------------------------------------------
473 int UsersImpl::Stop()
475 printfd(__FILE__, "USERS::Stop()\n");
477 m_thread.request_stop();
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++)
486 nanosleep(&ts, nullptr);
489 //after 5 seconds waiting thread still running. now kill it
492 printfd(__FILE__, "Detach USERS thread.\n");
493 //TODO pthread_cancel()
499 printfd(__FILE__, "Before USERS::Run()\n");
500 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
502 for (auto& user : users)
503 user.WriteDetailStat(true);
505 for_each(users.begin(), users.end(), [](auto& user){ user.WriteStat(); });
506 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::WriteConf));
508 printfd(__FILE__, "USERS::Stop()\n");
511 //-----------------------------------------------------------------------------
512 void UsersImpl::RealDelUser()
514 std::lock_guard<std::mutex> lock(m_mutex);
516 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
518 auto iter = usersToDelete.begin();
519 while (iter != usersToDelete.end())
521 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
522 if (iter->delTime + userDeleteDelayTime < stgTime)
524 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
525 if (m_store->DelUser(iter->iter->GetLogin()) != 0)
527 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
529 users.erase(iter->iter);
530 usersToDelete.erase(iter++);
538 //-----------------------------------------------------------------------------
539 void UsersImpl::AddToIPIdx(user_iter user)
541 printfd(__FILE__, "USERS: Add IP Idx\n");
542 uint32_t ip = user->GetCurrIP();
543 //assert(ip && "User has non-null ip");
545 return; // User has disconnected
547 std::lock_guard<std::mutex> lock(m_mutex);
549 const auto it = ipIndex.lower_bound(ip);
551 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
553 ipIndex.insert(it, std::make_pair(ip, user));
555 //-----------------------------------------------------------------------------
556 void UsersImpl::DelFromIPIdx(uint32_t ip)
558 printfd(__FILE__, "USERS: Del IP Idx\n");
559 assert(ip && "User has non-null ip");
561 std::lock_guard<std::mutex> lock(m_mutex);
563 const auto it = ipIndex.find(ip);
565 if (it == ipIndex.end())
570 //-----------------------------------------------------------------------------
571 bool UsersImpl::FindByIPIdx(uint32_t ip, user_iter & iter) const
573 auto it = ipIndex.find(ip);
574 if (it == ipIndex.end())
579 //-----------------------------------------------------------------------------
580 int UsersImpl::FindByIPIdx(uint32_t ip, UserPtr * user) const
582 std::lock_guard<std::mutex> lock(m_mutex);
585 if (FindByIPIdx(ip, iter))
593 //-----------------------------------------------------------------------------
594 int UsersImpl::FindByIPIdx(uint32_t ip, UserImpl ** user) const
596 std::lock_guard<std::mutex> lock(m_mutex);
599 if (FindByIPIdx(ip, iter))
607 //-----------------------------------------------------------------------------
608 bool UsersImpl::IsIPInIndex(uint32_t ip) const
610 std::lock_guard<std::mutex> lock(m_mutex);
612 return ipIndex.find(ip) != ipIndex.end();
614 //-----------------------------------------------------------------------------
615 bool UsersImpl::IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const
617 std::lock_guard<std::mutex> lock(m_mutex);
618 auto iter = users.begin();
619 while (iter != users.end())
621 if (iter->GetLogin() != login &&
622 !iter->GetProperties().ips.Get().isAnyIP() &&
623 iter->GetProperties().ips.Get().find(ip))
633 //-----------------------------------------------------------------------------
634 unsigned int UsersImpl::OpenSearch()
636 std::lock_guard<std::mutex> lock(m_mutex);
638 searchDescriptors[handle] = users.begin();
641 //-----------------------------------------------------------------------------
642 int UsersImpl::SearchNext(int h, UserPtr * user)
644 UserImpl * ptr = nullptr;
645 if (SearchNext(h, &ptr) != 0)
650 //-----------------------------------------------------------------------------
651 int UsersImpl::SearchNext(int h, UserImpl ** user)
653 std::lock_guard<std::mutex> lock(m_mutex);
655 if (searchDescriptors.find(h) == searchDescriptors.end())
657 WriteServLog("USERS. Incorrect search handle.");
661 if (searchDescriptors[h] == users.end())
664 while (searchDescriptors[h]->GetDeleted())
666 ++searchDescriptors[h];
667 if (searchDescriptors[h] == users.end())
673 *user = &(*searchDescriptors[h]);
675 ++searchDescriptors[h];
679 //-----------------------------------------------------------------------------
680 int UsersImpl::CloseSearch(int h)
682 std::lock_guard<std::mutex> lock(m_mutex);
683 if (searchDescriptors.find(h) != searchDescriptors.end())
685 searchDescriptors.erase(searchDescriptors.find(h));
689 WriteServLog("USERS. Incorrect search handle.");
692 //-----------------------------------------------------------------------------
693 void UsersImpl::AddUserIntoIndexes(user_iter user)
695 std::lock_guard<std::mutex> lock(m_mutex);
696 loginIndex.insert(make_pair(user->GetLogin(), user));
698 //-----------------------------------------------------------------------------
699 void UsersImpl::DelUserFromIndexes(user_iter user)
701 std::lock_guard<std::mutex> lock(m_mutex);
702 loginIndex.erase(user->GetLogin());
704 //-----------------------------------------------------------------------------
705 bool UsersImpl::TimeToWriteDetailStat(const struct tm & t)
707 auto statTime = settings->GetDetailStatWritePeriod();
716 if (t.tm_min % 30 == 0)
720 if (t.tm_min % 15 == 0)
724 if (t.tm_min % 10 == 0)