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->GetPriv();
135 if (!priv->userAddDel)
137 WriteServLog("%s tried to add user \'%s\'. Access denied.",
138 admin->GetLogStr().c_str(), login.c_str());
139 /*errorStr = "Admin \'" + admin->GetLogin() +
140 "\': tried to add user \'" + ud->login + "\'. Access denied.";*/
145 if (store->AddUser(login))
148 //WriteServLog("Admin \'%s\': tried to add user \'%s\'. Access denied.",
149 // admin->GetLogin().c_str(), ud->login.c_str());
154 UserImpl u(settings, store, tariffs, sysAdmin, this, m_services);
165 if (settings->GetDayResetTraff() > tms->tm_mday)
168 tms->tm_mday = settings->GetDayResetTraff();*/
172 u.SetPassiveTimeAsNewUser();
177 WriteServLog("%s User \'%s\' added.",
178 admin->GetLogStr().c_str(), login.c_str());
184 AddUserIntoIndexes(users.begin());
187 // Fire all "on add" notifiers
188 std::set<NotifierBase<UserPtr> *>::iterator ni = onAddNotifiers.begin();
189 while (ni != onAddNotifiers.end())
191 (*ni)->Notify(&users.front());
197 // Fire all "on add" implementation notifiers
198 std::set<NotifierBase<UserImplPtr> *>::iterator ni = onAddNotifiersImpl.begin();
199 while (ni != onAddNotifiersImpl.end())
201 (*ni)->Notify(&users.front());
208 //-----------------------------------------------------------------------------
209 void UsersImpl::Del(const std::string & login, const Admin * admin)
211 const auto priv = admin->GetPriv();
214 if (!priv->userAddDel)
216 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
217 admin->GetLogStr().c_str(), login.c_str());
223 STG_LOCKER lock(&mutex);
225 if (FindByNameNonLock(login, &u))
227 WriteServLog("%s tried to delete user \'%s\': not found.",
228 admin->GetLogStr().c_str(),
237 std::set<NotifierBase<UserPtr> *>::iterator ni = onDelNotifiers.begin();
238 while (ni != onDelNotifiers.end())
240 (*ni)->Notify(&(*u));
246 std::set<NotifierBase<UserImplPtr> *>::iterator ni = onDelNotifiersImpl.begin();
247 while (ni != onDelNotifiersImpl.end())
249 (*ni)->Notify(&(*u));
255 STG_LOCKER lock(&mutex);
261 utd.delTime = stgTime;
262 usersToDelete.push_back(utd);
264 DelUserFromIndexes(u);
266 WriteServLog("%s User \'%s\' deleted.",
267 admin->GetLogStr().c_str(), login.c_str());
271 //-----------------------------------------------------------------------------
272 bool UsersImpl::Authorize(const std::string & login, uint32_t ip,
273 uint32_t enabledDirs, const Auth * auth)
276 STG_LOCKER lock(&mutex);
277 if (FindByNameNonLock(login, &iter))
279 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
283 if (FindByIPIdx(ip, iter))
285 if (iter->GetLogin() != login)
287 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
288 login.c_str(), inet_ntostring(ip).c_str(),
289 iter->GetLogin().c_str());
292 if (iter->Authorize(ip, enabledDirs, auth))
297 if (iter->Authorize(ip, enabledDirs, auth))
303 //-----------------------------------------------------------------------------
304 bool UsersImpl::Unauthorize(const std::string & login,
306 const std::string & reason)
309 STG_LOCKER lock(&mutex);
310 if (FindByNameNonLock(login, &iter))
312 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
313 printfd(__FILE__, "Attempt to unauthorize non-existant user '%s'", login.c_str());
317 uint32_t ip = iter->GetCurrIP();
319 iter->Unauthorize(auth, reason);
321 if (!iter->GetAuthorized())
326 //-----------------------------------------------------------------------------
327 int UsersImpl::ReadUsers()
329 std::vector<std::string> usersList;
331 if (store->GetUsersList(&usersList) < 0)
333 WriteServLog(store->GetStrError().c_str());
340 for (unsigned int i = 0; i < usersList.size(); i++)
342 UserImpl u(settings, store, tariffs, sysAdmin, this, m_services);
344 u.SetLogin(usersList[i]);
348 AddUserIntoIndexes(ui);
350 if (settings->GetStopOnError())
352 if (ui->ReadConf() < 0)
355 if (ui->ReadStat() < 0)
360 if (ui->ReadConf() < 0)
363 if (ui->ReadStat() < 0)
372 //-----------------------------------------------------------------------------
373 void * UsersImpl::Run(void * d)
376 sigfillset(&signalSet);
377 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
379 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
380 UsersImpl * us = static_cast<UsersImpl *>(d);
384 localtime_r(&tt, &t);
389 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
391 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
392 std::string monFile = us->settings->GetMonitorDir() + "/users_r";
393 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
395 us->isRunning = true;
398 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
399 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
401 for_each(us->users.begin(), us->users.end(), [](auto& user){ user.Run(); });
404 localtime_r(&tt, &t);
408 printfd(__FILE__,"Sec = %d\n", stgTime);
409 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
415 if (day != t.tm_mday)
417 printfd(__FILE__,"Sec = %d\n", stgTime);
418 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
423 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
425 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
431 } //while (us->nonstop)
433 std::list<USER_TO_DEL>::iterator iter(us->usersToDelete.begin());
434 while (iter != us->usersToDelete.end())
436 iter->delTime -= 2 * userDeleteDelayTime;
441 us->isRunning = false;
445 //-----------------------------------------------------------------------------
446 void UsersImpl::NewMinute(const struct tm & t)
448 //Write traff, reset session traff. Fake disconnect-connect
449 if (t.tm_hour == 23 && t.tm_min == 59)
451 printfd(__FILE__,"MidnightResetSessionStat\n");
452 for_each(users.begin(), users.end(), [](auto& user){ user.MidnightResetSessionStat(); });
455 if (TimeToWriteDetailStat(t))
457 //printfd(__FILE__, "USER::WriteInetStat\n");
460 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
461 std::list<UserImpl>::iterator usr = users.begin();
462 while (usr != users.end())
465 usr->WriteDetailStat();
467 if (usersCnt % 10 == 0)
468 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
474 //-----------------------------------------------------------------------------
475 void UsersImpl::NewDay(const struct tm & t)
479 localtime_r(&tt, &t1);
480 int dayFee = settings->GetDayFee();
483 dayFee = DaysInCurrentMonth();
485 printfd(__FILE__, "DayFee = %d\n", dayFee);
486 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
487 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
489 if (!settings->GetDayFeeIsLastDay())
491 printfd(__FILE__, "DayResetTraff - 1 -\n");
493 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
496 if (settings->GetSpreadFee())
498 printfd(__FILE__, "Spread DayFee\n");
499 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFeeSpread(); });
503 if (t.tm_mday == dayFee)
505 printfd(__FILE__, "DayFee\n");
506 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDayFee(); });
510 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessDailyFee(); });
511 std::for_each(users.begin(), users.end(), [](auto& user){ user.ProcessServices(); });
513 if (settings->GetDayFeeIsLastDay())
515 printfd(__FILE__, "DayResetTraff - 2 -\n");
519 //-----------------------------------------------------------------------------
520 void UsersImpl::DayResetTraff(const struct tm & t1)
522 int dayResetTraff = settings->GetDayResetTraff();
523 if (dayResetTraff == 0)
524 dayResetTraff = DaysInCurrentMonth();
525 if (t1.tm_mday == dayResetTraff)
527 printfd(__FILE__, "ResetTraff\n");
528 for_each(users.begin(), users.end(), [](auto& user){ user.ProcessNewMonth(); });
529 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::SetPrepaidTraff));
532 //-----------------------------------------------------------------------------
533 int UsersImpl::Start()
537 WriteServLog("USERS: Error: Cannot read users!");
542 if (pthread_create(&thread, NULL, Run, this))
544 WriteServLog("USERS: Error: Cannot start thread!");
549 //-----------------------------------------------------------------------------
550 int UsersImpl::Stop()
552 printfd(__FILE__, "USERS::Stop()\n");
556 //printfd(__FILE__, "Alredy stopped\n");
562 //5 seconds to thread stops itself
563 struct timespec ts = {0, 200000000};
564 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
569 nanosleep(&ts, NULL);
572 //after 5 seconds waiting thread still running. now kill it
575 printfd(__FILE__, "kill USERS thread.\n");
576 //TODO pthread_cancel()
577 if (pthread_kill(thread, SIGINT))
579 //errorStr = "Cannot kill USERS thread.";
580 //printfd(__FILE__, "Cannot kill USERS thread.\n");
583 printfd(__FILE__, "USERS killed\n");
586 printfd(__FILE__, "Before USERS::Run()\n");
587 for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
589 // 'cause bind2st accepts only constant first param
590 for (std::list<UserImpl>::iterator it = users.begin();
593 it->WriteDetailStat(true);
595 for_each(users.begin(), users.end(), [](auto& user){ user.WriteStat(); });
596 //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::WriteConf));
598 printfd(__FILE__, "USERS::Stop()\n");
601 //-----------------------------------------------------------------------------
602 void UsersImpl::RealDelUser()
604 STG_LOCKER lock(&mutex);
606 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
608 std::list<USER_TO_DEL>::iterator iter;
609 iter = usersToDelete.begin();
610 while (iter != usersToDelete.end())
612 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
613 if (iter->delTime + userDeleteDelayTime < stgTime)
615 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
616 if (store->DelUser(iter->iter->GetLogin()))
618 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
620 users.erase(iter->iter);
621 usersToDelete.erase(iter++);
630 //-----------------------------------------------------------------------------
631 void UsersImpl::AddToIPIdx(user_iter user)
633 printfd(__FILE__, "USERS: Add IP Idx\n");
634 uint32_t ip = user->GetCurrIP();
635 //assert(ip && "User has non-null ip");
637 return; // User has disconnected
639 STG_LOCKER lock(&mutex);
641 const std::map<uint32_t, user_iter>::iterator it(
642 ipIndex.lower_bound(ip)
645 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
647 ipIndex.insert(it, std::make_pair(ip, user));
649 //-----------------------------------------------------------------------------
650 void UsersImpl::DelFromIPIdx(uint32_t ip)
652 printfd(__FILE__, "USERS: Del IP Idx\n");
653 assert(ip && "User has non-null ip");
655 STG_LOCKER lock(&mutex);
657 const std::map<uint32_t, user_iter>::iterator it(
661 if (it == ipIndex.end())
666 //-----------------------------------------------------------------------------
667 bool UsersImpl::FindByIPIdx(uint32_t ip, user_iter & iter) const
669 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
670 if (it == ipIndex.end())
675 //-----------------------------------------------------------------------------
676 int UsersImpl::FindByIPIdx(uint32_t ip, UserPtr * usr) const
678 STG_LOCKER lock(&mutex);
681 if (FindByIPIdx(ip, iter))
689 //-----------------------------------------------------------------------------
690 int UsersImpl::FindByIPIdx(uint32_t ip, UserImpl ** usr) const
692 STG_LOCKER lock(&mutex);
695 if (FindByIPIdx(ip, iter))
703 //-----------------------------------------------------------------------------
704 bool UsersImpl::IsIPInIndex(uint32_t ip) const
706 STG_LOCKER lock(&mutex);
708 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
710 return it != ipIndex.end();
712 //-----------------------------------------------------------------------------
713 bool UsersImpl::IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const
715 STG_LOCKER lock(&mutex);
716 std::list<UserImpl>::const_iterator iter;
717 iter = users.begin();
718 while (iter != users.end())
720 if (iter->GetLogin() != login &&
721 !iter->GetProperties().ips.Get().isAnyIP() &&
722 iter->GetProperties().ips.Get().find(ip))
732 //-----------------------------------------------------------------------------
733 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserPtr> * n)
735 STG_LOCKER lock(&mutex);
736 onAddNotifiers.insert(n);
738 //-----------------------------------------------------------------------------
739 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserPtr> * n)
741 STG_LOCKER lock(&mutex);
742 onAddNotifiers.erase(n);
744 //-----------------------------------------------------------------------------
745 void UsersImpl::AddNotifierUserDel(NotifierBase<UserPtr> * n)
747 STG_LOCKER lock(&mutex);
748 onDelNotifiers.insert(n);
750 //-----------------------------------------------------------------------------
751 void UsersImpl::DelNotifierUserDel(NotifierBase<UserPtr> * n)
753 STG_LOCKER lock(&mutex);
754 onDelNotifiers.erase(n);
756 //-----------------------------------------------------------------------------
757 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserImplPtr> * n)
759 STG_LOCKER lock(&mutex);
760 onAddNotifiersImpl.insert(n);
762 //-----------------------------------------------------------------------------
763 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserImplPtr> * n)
765 STG_LOCKER lock(&mutex);
766 onAddNotifiersImpl.erase(n);
768 //-----------------------------------------------------------------------------
769 void UsersImpl::AddNotifierUserDel(NotifierBase<UserImplPtr> * n)
771 STG_LOCKER lock(&mutex);
772 onDelNotifiersImpl.insert(n);
774 //-----------------------------------------------------------------------------
775 void UsersImpl::DelNotifierUserDel(NotifierBase<UserImplPtr> * n)
777 STG_LOCKER lock(&mutex);
778 onDelNotifiersImpl.erase(n);
780 //-----------------------------------------------------------------------------
781 int UsersImpl::OpenSearch()
783 STG_LOCKER lock(&mutex);
785 searchDescriptors[handle] = users.begin();
788 //-----------------------------------------------------------------------------
789 int UsersImpl::SearchNext(int h, UserPtr * user)
791 UserImpl * ptr = NULL;
792 if (SearchNext(h, &ptr))
797 //-----------------------------------------------------------------------------
798 int UsersImpl::SearchNext(int h, UserImpl ** user)
800 STG_LOCKER lock(&mutex);
802 if (searchDescriptors.find(h) == searchDescriptors.end())
804 WriteServLog("USERS. Incorrect search handle.");
808 if (searchDescriptors[h] == users.end())
811 while (searchDescriptors[h]->GetDeleted())
813 ++searchDescriptors[h];
814 if (searchDescriptors[h] == users.end())
820 *user = &(*searchDescriptors[h]);
822 ++searchDescriptors[h];
826 //-----------------------------------------------------------------------------
827 int UsersImpl::CloseSearch(int h)
829 STG_LOCKER lock(&mutex);
830 if (searchDescriptors.find(h) != searchDescriptors.end())
832 searchDescriptors.erase(searchDescriptors.find(h));
836 WriteServLog("USERS. Incorrect search handle.");
839 //-----------------------------------------------------------------------------
840 void UsersImpl::AddUserIntoIndexes(user_iter user)
842 STG_LOCKER lock(&mutex);
843 loginIndex.insert(make_pair(user->GetLogin(), user));
845 //-----------------------------------------------------------------------------
846 void UsersImpl::DelUserFromIndexes(user_iter user)
848 STG_LOCKER lock(&mutex);
849 loginIndex.erase(user->GetLogin());
851 //-----------------------------------------------------------------------------
852 bool UsersImpl::TimeToWriteDetailStat(const struct tm & t)
854 int statTime = settings->GetDetailStatWritePeriod();
863 if (t.tm_min % 30 == 0)
867 if (t.tm_min % 15 == 0)
871 if (t.tm_min % 10 == 0)