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 pthread_mutexattr_t attr;
59 pthread_mutexattr_init(&attr);
60 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
61 pthread_mutex_init(&mutex, &attr);
63 //-----------------------------------------------------------------------------
64 UsersImpl::~UsersImpl()
66 pthread_mutex_destroy(&mutex);
68 //-----------------------------------------------------------------------------
69 int UsersImpl::FindByNameNonLock(const std::string & login, user_iter * user)
71 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
72 if (iter == loginIndex.end())
78 //-----------------------------------------------------------------------------
79 int UsersImpl::FindByNameNonLock(const std::string & login, const_user_iter * user) const
81 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
82 if (iter == loginIndex.end())
88 //-----------------------------------------------------------------------------
89 int UsersImpl::FindByName(const std::string & login, UserPtr * user)
91 STG_LOCKER lock(&mutex);
93 if (FindByNameNonLock(login, &u))
98 //-----------------------------------------------------------------------------
99 int UsersImpl::FindByName(const std::string & login, ConstUserPtr * user) const
101 STG_LOCKER lock(&mutex);
103 if (FindByNameNonLock(login, &u))
108 //-----------------------------------------------------------------------------
109 bool UsersImpl::Exists(const std::string & login) const
111 STG_LOCKER lock(&mutex);
112 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
113 return iter != loginIndex.end();
115 //-----------------------------------------------------------------------------
116 bool UsersImpl::TariffInUse(const std::string & tariffName) const
118 STG_LOCKER lock(&mutex);
119 std::list<UserImpl>::const_iterator iter;
120 iter = users.begin();
121 while (iter != users.end())
123 if (iter->GetProperties().tariffName.Get() == tariffName)
129 //-----------------------------------------------------------------------------
130 int UsersImpl::Add(const std::string & login, const Admin * admin)
132 STG_LOCKER lock(&mutex);
133 const auto& priv = admin->priv();
135 if (!priv.userAddDel)
137 WriteServLog("%s tried to add user \'%s\'. Access denied.",
138 admin->logStr().c_str(), login.c_str());
142 if (store->AddUser(login))
145 UserImpl u(settings, store, tariffs, &sysAdmin, this, m_services);
149 u.SetPassiveTimeAsNewUser();
154 WriteServLog("%s User \'%s\' added.",
155 admin->logStr().c_str(), login.c_str());
161 AddUserIntoIndexes(users.begin());
164 // Fire all "on add" notifiers
165 std::set<NotifierBase<UserPtr> *>::iterator ni = onAddNotifiers.begin();
166 while (ni != onAddNotifiers.end())
168 (*ni)->Notify(&users.front());
174 // Fire all "on add" implementation notifiers
175 std::set<NotifierBase<UserImplPtr> *>::iterator ni = onAddNotifiersImpl.begin();
176 while (ni != onAddNotifiersImpl.end())
178 (*ni)->Notify(&users.front());
185 //-----------------------------------------------------------------------------
186 void UsersImpl::Del(const std::string & login, const Admin * admin)
188 const auto& priv = admin->priv();
191 if (!priv.userAddDel)
193 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
194 admin->logStr().c_str(), login.c_str());
200 STG_LOCKER lock(&mutex);
202 if (FindByNameNonLock(login, &u))
204 WriteServLog("%s tried to delete user \'%s\': not found.",
205 admin->logStr().c_str(),
214 std::set<NotifierBase<UserPtr> *>::iterator ni = onDelNotifiers.begin();
215 while (ni != onDelNotifiers.end())
217 (*ni)->Notify(&(*u));
223 std::set<NotifierBase<UserImplPtr> *>::iterator ni = onDelNotifiersImpl.begin();
224 while (ni != onDelNotifiersImpl.end())
226 (*ni)->Notify(&(*u));
232 STG_LOCKER lock(&mutex);
238 utd.delTime = stgTime;
239 usersToDelete.push_back(utd);
241 DelUserFromIndexes(u);
243 WriteServLog("%s User \'%s\' deleted.",
244 admin->logStr().c_str(), login.c_str());
248 //-----------------------------------------------------------------------------
249 bool UsersImpl::Authorize(const std::string & login, uint32_t ip,
250 uint32_t enabledDirs, const Auth * auth)
253 STG_LOCKER lock(&mutex);
254 if (FindByNameNonLock(login, &iter))
256 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
260 if (FindByIPIdx(ip, iter))
262 if (iter->GetLogin() != login)
264 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
265 login.c_str(), inet_ntostring(ip).c_str(),
266 iter->GetLogin().c_str());
269 if (iter->Authorize(ip, enabledDirs, auth))
274 if (iter->Authorize(ip, enabledDirs, auth))
280 //-----------------------------------------------------------------------------
281 bool UsersImpl::Unauthorize(const std::string & login,
283 const std::string & reason)
286 STG_LOCKER lock(&mutex);
287 if (FindByNameNonLock(login, &iter))
289 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
290 printfd(__FILE__, "Attempt to unauthorize non-existant user '%s'", login.c_str());
294 uint32_t ip = iter->GetCurrIP();
296 iter->Unauthorize(auth, reason);
298 if (!iter->GetAuthorized())
303 //-----------------------------------------------------------------------------
304 int UsersImpl::ReadUsers()
306 std::vector<std::string> usersList;
308 if (store->GetUsersList(&usersList) < 0)
310 WriteServLog(store->GetStrError().c_str());
317 for (unsigned int i = 0; i < usersList.size(); i++)
319 UserImpl u(settings, store, tariffs, &sysAdmin, this, m_services);
321 u.SetLogin(usersList[i]);
325 AddUserIntoIndexes(ui);
327 if (settings->GetStopOnError())
329 if (ui->ReadConf() < 0)
332 if (ui->ReadStat() < 0)
337 if (ui->ReadConf() < 0)
340 if (ui->ReadStat() < 0)
349 //-----------------------------------------------------------------------------
350 void * UsersImpl::Run(void * d)
353 sigfillset(&signalSet);
354 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
356 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
357 UsersImpl * us = static_cast<UsersImpl *>(d);
361 localtime_r(&tt, &t);
366 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
368 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
369 std::string monFile = us->settings->GetMonitorDir() + "/users_r";
370 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
372 us->isRunning = true;
375 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
376 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
378 for_each(us->users.begin(), us->users.end(), [](auto& user){ user.Run(); });
381 localtime_r(&tt, &t);
385 printfd(__FILE__,"Sec = %d\n", stgTime);
386 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
392 if (day != t.tm_mday)
394 printfd(__FILE__,"Sec = %d\n", stgTime);
395 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
400 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
402 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
408 } //while (us->nonstop)
410 std::list<USER_TO_DEL>::iterator iter(us->usersToDelete.begin());
411 while (iter != us->usersToDelete.end())
413 iter->delTime -= 2 * userDeleteDelayTime;
418 us->isRunning = false;
422 //-----------------------------------------------------------------------------
423 void UsersImpl::NewMinute(const struct tm & t)
425 //Write traff, reset session traff. Fake disconnect-connect
426 if (t.tm_hour == 23 && t.tm_min == 59)
428 printfd(__FILE__,"MidnightResetSessionStat\n");
429 for_each(users.begin(), users.end(), [](auto& user){ user.MidnightResetSessionStat(); });
432 if (TimeToWriteDetailStat(t))
434 //printfd(__FILE__, "USER::WriteInetStat\n");
437 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
438 std::list<UserImpl>::iterator usr = users.begin();
439 while (usr != users.end())
442 usr->WriteDetailStat();
444 if (usersCnt % 10 == 0)
445 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
451 //-----------------------------------------------------------------------------
452 void UsersImpl::NewDay(const struct tm & t)
456 localtime_r(&tt, &t1);
457 int dayFee = settings->GetDayFee();
460 dayFee = DaysInCurrentMonth();
462 printfd(__FILE__, "DayFee = %d\n", dayFee);
463 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
464 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
466 if (!settings->GetDayFeeIsLastDay())
468 printfd(__FILE__, "DayResetTraff - 1 -\n");
470 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
473 if (settings->GetSpreadFee())
475 printfd(__FILE__, "Spread DayFee\n");
476 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFeeSpread(); });
480 if (t.tm_mday == dayFee)
482 printfd(__FILE__, "DayFee\n");
483 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFee(); });
487 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDailyFee(); });
488 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessServices(); });
490 if (settings->GetDayFeeIsLastDay())
492 printfd(__FILE__, "DayResetTraff - 2 -\n");
496 //-----------------------------------------------------------------------------
497 void UsersImpl::DayResetTraff(const struct tm & t1)
499 int dayResetTraff = settings->GetDayResetTraff();
500 if (dayResetTraff == 0)
501 dayResetTraff = DaysInCurrentMonth();
502 if (t1.tm_mday == dayResetTraff)
504 printfd(__FILE__, "ResetTraff\n");
505 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessNewMonth(); });
506 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::SetPrepaidTraff));
509 //-----------------------------------------------------------------------------
510 int UsersImpl::Start()
514 WriteServLog("USERS: Error: Cannot read users!");
519 if (pthread_create(&thread, NULL, Run, this))
521 WriteServLog("USERS: Error: Cannot start thread!");
526 //-----------------------------------------------------------------------------
527 int UsersImpl::Stop()
529 printfd(__FILE__, "USERS::Stop()\n");
533 //printfd(__FILE__, "Alredy stopped\n");
539 //5 seconds to thread stops itself
540 struct timespec ts = {0, 200000000};
541 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
546 nanosleep(&ts, NULL);
549 //after 5 seconds waiting thread still running. now kill it
552 printfd(__FILE__, "kill USERS thread.\n");
553 //TODO pthread_cancel()
554 if (pthread_kill(thread, SIGINT))
556 //errorStr = "Cannot kill USERS thread.";
557 //printfd(__FILE__, "Cannot kill USERS thread.\n");
560 printfd(__FILE__, "USERS killed\n");
563 printfd(__FILE__, "Before USERS::Run()\n");
564 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
566 // 'cause bind2st accepts only constant first param
567 for (std::list<UserImpl>::iterator it = users.begin();
570 it->WriteDetailStat(true);
572 for_each(users.begin(), users.end(), [](auto& user){ user.WriteStat(); });
573 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::WriteConf));
575 printfd(__FILE__, "USERS::Stop()\n");
578 //-----------------------------------------------------------------------------
579 void UsersImpl::RealDelUser()
581 STG_LOCKER lock(&mutex);
583 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
585 std::list<USER_TO_DEL>::iterator iter;
586 iter = usersToDelete.begin();
587 while (iter != usersToDelete.end())
589 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
590 if (iter->delTime + userDeleteDelayTime < stgTime)
592 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
593 if (store->DelUser(iter->iter->GetLogin()))
595 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
597 users.erase(iter->iter);
598 usersToDelete.erase(iter++);
607 //-----------------------------------------------------------------------------
608 void UsersImpl::AddToIPIdx(user_iter user)
610 printfd(__FILE__, "USERS: Add IP Idx\n");
611 uint32_t ip = user->GetCurrIP();
612 //assert(ip && "User has non-null ip");
614 return; // User has disconnected
616 STG_LOCKER lock(&mutex);
618 const std::map<uint32_t, user_iter>::iterator it(
619 ipIndex.lower_bound(ip)
622 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
624 ipIndex.insert(it, std::make_pair(ip, user));
626 //-----------------------------------------------------------------------------
627 void UsersImpl::DelFromIPIdx(uint32_t ip)
629 printfd(__FILE__, "USERS: Del IP Idx\n");
630 assert(ip && "User has non-null ip");
632 STG_LOCKER lock(&mutex);
634 const std::map<uint32_t, user_iter>::iterator it(
638 if (it == ipIndex.end())
643 //-----------------------------------------------------------------------------
644 bool UsersImpl::FindByIPIdx(uint32_t ip, user_iter & iter) const
646 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
647 if (it == ipIndex.end())
652 //-----------------------------------------------------------------------------
653 int UsersImpl::FindByIPIdx(uint32_t ip, UserPtr * usr) const
655 STG_LOCKER lock(&mutex);
658 if (FindByIPIdx(ip, iter))
666 //-----------------------------------------------------------------------------
667 int UsersImpl::FindByIPIdx(uint32_t ip, UserImpl ** usr) const
669 STG_LOCKER lock(&mutex);
672 if (FindByIPIdx(ip, iter))
680 //-----------------------------------------------------------------------------
681 bool UsersImpl::IsIPInIndex(uint32_t ip) const
683 STG_LOCKER lock(&mutex);
685 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
687 return it != ipIndex.end();
689 //-----------------------------------------------------------------------------
690 bool UsersImpl::IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const
692 STG_LOCKER lock(&mutex);
693 std::list<UserImpl>::const_iterator iter;
694 iter = users.begin();
695 while (iter != users.end())
697 if (iter->GetLogin() != login &&
698 !iter->GetProperties().ips.Get().isAnyIP() &&
699 iter->GetProperties().ips.Get().find(ip))
709 //-----------------------------------------------------------------------------
710 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserPtr> * n)
712 STG_LOCKER lock(&mutex);
713 onAddNotifiers.insert(n);
715 //-----------------------------------------------------------------------------
716 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserPtr> * n)
718 STG_LOCKER lock(&mutex);
719 onAddNotifiers.erase(n);
721 //-----------------------------------------------------------------------------
722 void UsersImpl::AddNotifierUserDel(NotifierBase<UserPtr> * n)
724 STG_LOCKER lock(&mutex);
725 onDelNotifiers.insert(n);
727 //-----------------------------------------------------------------------------
728 void UsersImpl::DelNotifierUserDel(NotifierBase<UserPtr> * n)
730 STG_LOCKER lock(&mutex);
731 onDelNotifiers.erase(n);
733 //-----------------------------------------------------------------------------
734 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserImplPtr> * n)
736 STG_LOCKER lock(&mutex);
737 onAddNotifiersImpl.insert(n);
739 //-----------------------------------------------------------------------------
740 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserImplPtr> * n)
742 STG_LOCKER lock(&mutex);
743 onAddNotifiersImpl.erase(n);
745 //-----------------------------------------------------------------------------
746 void UsersImpl::AddNotifierUserDel(NotifierBase<UserImplPtr> * n)
748 STG_LOCKER lock(&mutex);
749 onDelNotifiersImpl.insert(n);
751 //-----------------------------------------------------------------------------
752 void UsersImpl::DelNotifierUserDel(NotifierBase<UserImplPtr> * n)
754 STG_LOCKER lock(&mutex);
755 onDelNotifiersImpl.erase(n);
757 //-----------------------------------------------------------------------------
758 int UsersImpl::OpenSearch()
760 STG_LOCKER lock(&mutex);
762 searchDescriptors[handle] = users.begin();
765 //-----------------------------------------------------------------------------
766 int UsersImpl::SearchNext(int h, UserPtr * user)
768 UserImpl * ptr = NULL;
769 if (SearchNext(h, &ptr))
774 //-----------------------------------------------------------------------------
775 int UsersImpl::SearchNext(int h, UserImpl ** user)
777 STG_LOCKER lock(&mutex);
779 if (searchDescriptors.find(h) == searchDescriptors.end())
781 WriteServLog("USERS. Incorrect search handle.");
785 if (searchDescriptors[h] == users.end())
788 while (searchDescriptors[h]->GetDeleted())
790 ++searchDescriptors[h];
791 if (searchDescriptors[h] == users.end())
797 *user = &(*searchDescriptors[h]);
799 ++searchDescriptors[h];
803 //-----------------------------------------------------------------------------
804 int UsersImpl::CloseSearch(int h)
806 STG_LOCKER lock(&mutex);
807 if (searchDescriptors.find(h) != searchDescriptors.end())
809 searchDescriptors.erase(searchDescriptors.find(h));
813 WriteServLog("USERS. Incorrect search handle.");
816 //-----------------------------------------------------------------------------
817 void UsersImpl::AddUserIntoIndexes(user_iter user)
819 STG_LOCKER lock(&mutex);
820 loginIndex.insert(make_pair(user->GetLogin(), user));
822 //-----------------------------------------------------------------------------
823 void UsersImpl::DelUserFromIndexes(user_iter user)
825 STG_LOCKER lock(&mutex);
826 loginIndex.erase(user->GetLogin());
828 //-----------------------------------------------------------------------------
829 bool UsersImpl::TimeToWriteDetailStat(const struct tm & t)
831 int statTime = settings->GetDetailStatWritePeriod();
840 if (t.tm_min % 30 == 0)
844 if (t.tm_min % 15 == 0)
848 if (t.tm_min % 10 == 0)