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>
27 $Date: 2010/09/13 05:56:42 $
44 #include "stg/settings.h"
45 #include "stg/common.h"
46 #include "users_impl.h"
47 #include "stg_timer.h"
49 extern volatile time_t stgTime;
51 //#define USERS_DEBUG 1
53 //-----------------------------------------------------------------------------
54 USERS_IMPL::USERS_IMPL(SETTINGS_IMPL * s, STORE * st, TARIFFS * t, const ADMIN * sa)
58 /*userIPNotifiersBefore(),
59 userIPNotifiersAfter(),*/
66 WriteServLog(GetStgLogger()),
78 pthread_mutexattr_t attr;
79 pthread_mutexattr_init(&attr);
80 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
81 pthread_mutex_init(&mutex, &attr);
83 //-----------------------------------------------------------------------------
84 USERS_IMPL::~USERS_IMPL()
86 pthread_mutex_destroy(&mutex);
88 //-----------------------------------------------------------------------------
89 int USERS_IMPL::FindByNameNonLock(const std::string & login, user_iter * user)
91 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
92 if (iter == loginIndex.end())
98 //-----------------------------------------------------------------------------
99 int USERS_IMPL::FindByNameNonLock(const std::string & login, const_user_iter * user) const
101 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
102 if (iter == loginIndex.end())
105 *user = iter->second;
108 //-----------------------------------------------------------------------------
109 int USERS_IMPL::FindByName(const std::string & login, USER_PTR * user)
111 STG_LOCKER lock(&mutex);
113 if (FindByNameNonLock(login, &u))
118 //-----------------------------------------------------------------------------
119 int USERS_IMPL::FindByName(const std::string & login, CONST_USER_PTR * user) const
121 STG_LOCKER lock(&mutex);
123 if (FindByNameNonLock(login, &u))
128 //-----------------------------------------------------------------------------
129 bool USERS_IMPL::Exists(const std::string & login) const
131 STG_LOCKER lock(&mutex);
132 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
133 return iter != loginIndex.end();
135 //-----------------------------------------------------------------------------
136 bool USERS_IMPL::TariffInUse(const std::string & tariffName) const
138 STG_LOCKER lock(&mutex);
139 std::list<USER_IMPL>::const_iterator iter;
140 iter = users.begin();
141 while (iter != users.end())
143 if (iter->GetProperty().tariffName.Get() == tariffName)
149 //-----------------------------------------------------------------------------
150 int USERS_IMPL::Add(const std::string & login, const ADMIN * admin)
152 STG_LOCKER lock(&mutex);
153 const PRIV * priv = admin->GetPriv();
155 if (!priv->userAddDel)
157 WriteServLog("%s tried to add user \'%s\'. Access denied.",
158 admin->GetLogStr().c_str(), login.c_str());
159 /*errorStr = "Admin \'" + admin->GetLogin() +
160 "\': tried to add user \'" + ud->login + "\'. Access denied.";*/
165 if (store->AddUser(login))
168 //WriteServLog("Admin \'%s\': tried to add user \'%s\'. Access denied.",
169 // admin->GetLogin().c_str(), ud->login.c_str());
174 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
185 if (settings->GetDayResetTraff() > tms->tm_mday)
188 tms->tm_mday = settings->GetDayResetTraff();*/
192 u.SetPassiveTimeAsNewUser();
197 WriteServLog("%s User \'%s\' added.",
198 admin->GetLogStr().c_str(), login.c_str());
204 AddUserIntoIndexes(users.begin());
207 // Fire all "on add" notifiers
208 std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
209 while (ni != onAddNotifiers.end())
211 (*ni)->Notify(&users.front());
217 // Fire all "on add" implementation notifiers
218 std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
219 while (ni != onAddNotifiersImpl.end())
221 (*ni)->Notify(&users.front());
228 //-----------------------------------------------------------------------------
229 void USERS_IMPL::Del(const std::string & login, const ADMIN * admin)
231 const PRIV * priv = admin->GetPriv();
234 if (!priv->userAddDel)
236 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
237 admin->GetLogStr().c_str(), login.c_str());
243 STG_LOCKER lock(&mutex);
245 if (FindByNameNonLock(login, &u))
247 WriteServLog("%s tried to delete user \'%s\': not found.",
248 admin->GetLogStr().c_str(),
257 std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
258 while (ni != onDelNotifiers.end())
260 (*ni)->Notify(&(*u));
266 std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
267 while (ni != onDelNotifiersImpl.end())
269 (*ni)->Notify(&(*u));
275 STG_LOCKER lock(&mutex);
281 utd.delTime = stgTime;
282 usersToDelete.push_back(utd);
284 DelUserFromIndexes(u);
286 WriteServLog("%s User \'%s\' deleted.",
287 admin->GetLogStr().c_str(), login.c_str());
291 //-----------------------------------------------------------------------------
292 bool USERS_IMPL::Authorize(const std::string & login, uint32_t ip,
293 uint32_t enabledDirs, const AUTH * auth)
296 STG_LOCKER lock(&mutex);
297 if (FindByNameNonLock(login, &iter))
299 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
303 if (FindByIPIdx(ip, iter))
305 if (iter->GetLogin() != login)
307 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
308 login.c_str(), inet_ntostring(ip).c_str(),
309 iter->GetLogin().c_str());
312 if (iter->Authorize(ip, enabledDirs, auth))
317 if (iter->Authorize(ip, enabledDirs, auth))
323 //-----------------------------------------------------------------------------
324 bool USERS_IMPL::Unauthorize(const std::string & login,
326 const std::string & reason)
329 STG_LOCKER lock(&mutex);
330 if (FindByNameNonLock(login, &iter))
332 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
336 uint32_t ip = iter->GetCurrIP();
338 iter->Unauthorize(auth, reason);
340 if (!iter->GetAuthorized())
345 //-----------------------------------------------------------------------------
346 int USERS_IMPL::ReadUsers()
348 std::vector<std::string> usersList;
350 if (store->GetUsersList(&usersList) < 0)
352 WriteServLog(store->GetStrError().c_str());
358 for (unsigned int i = 0; i < usersList.size(); i++)
360 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
362 u.SetLogin(usersList[i]);
366 AddUserIntoIndexes(ui);
368 if (ui->ReadConf() < 0)
371 if (ui->ReadStat() < 0)
377 //-----------------------------------------------------------------------------
378 void * USERS_IMPL::Run(void * d)
381 sigfillset(&signalSet);
382 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
384 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
385 USERS_IMPL * us = static_cast<USERS_IMPL *>(d);
389 localtime_r(&tt, &t);
394 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
396 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
397 std::string monFile = us->settings->GetMonitorDir() + "/users_r";
398 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
400 us->isRunning = true;
403 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
404 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
406 for_each(us->users.begin(), us->users.end(), std::mem_fun_ref(&USER_IMPL::Run));
409 localtime_r(&tt, &t);
413 printfd(__FILE__,"Sec = %d\n", stgTime);
414 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
420 if (day != t.tm_mday)
422 printfd(__FILE__,"Sec = %d\n", stgTime);
423 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
428 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
430 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
432 TouchFile(monFile.c_str());
436 } //while (us->nonstop)
438 user_iter ui = us->users.begin();
439 while (ui != us->users.end())
441 us->DelUserFromIndexes(ui);
445 std::list<USER_TO_DEL>::iterator iter;
446 iter = us->usersToDelete.begin();
447 while (iter != us->usersToDelete.end())
449 iter->delTime -= 2 * userDeleteDelayTime;
454 us->isRunning = false;
458 //-----------------------------------------------------------------------------
459 void USERS_IMPL::NewMinute(const struct tm & t)
461 //Write traff, reset session traff. Fake disconnect-connect
462 if (t.tm_hour == 23 && t.tm_min == 59)
464 printfd(__FILE__,"MidnightResetSessionStat\n");
465 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
468 if (TimeToWriteDetailStat(t))
470 //printfd(__FILE__, "USER::WriteInetStat\n");
473 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
474 std::list<USER_IMPL>::iterator usr = users.begin();
475 while (usr != users.end())
478 usr->WriteDetailStat();
480 if (usersCnt % 10 == 0)
481 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
487 //-----------------------------------------------------------------------------
488 void USERS_IMPL::NewDay(const struct tm & t)
492 localtime_r(&tt, &t1);
493 int dayFee = settings->GetDayFee();
496 dayFee = DaysInCurrentMonth();
498 printfd(__FILE__, "DayFee = %d\n", dayFee);
499 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
500 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
502 if (!settings->GetDayFeeIsLastDay())
504 printfd(__FILE__, "DayResetTraff - 1 -\n");
506 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
509 if (settings->GetSpreadFee())
511 printfd(__FILE__, "Spread DayFee\n");
512 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
516 if (t.tm_mday == dayFee)
518 printfd(__FILE__, "DayFee\n");
519 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFee));
523 std::for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDailyFee));
524 std::for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessServices));
526 if (settings->GetDayFeeIsLastDay())
528 printfd(__FILE__, "DayResetTraff - 2 -\n");
532 //-----------------------------------------------------------------------------
533 void USERS_IMPL::DayResetTraff(const struct tm & t1)
535 int dayResetTraff = settings->GetDayResetTraff();
536 if (dayResetTraff == 0)
537 dayResetTraff = DaysInCurrentMonth();
538 if (t1.tm_mday == dayResetTraff)
540 printfd(__FILE__, "ResetTraff\n");
541 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessNewMonth));
542 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
545 //-----------------------------------------------------------------------------
546 int USERS_IMPL::Start()
550 WriteServLog("USERS: Error: Cannot read users!");
555 if (pthread_create(&thread, NULL, Run, this))
557 WriteServLog("USERS: Error: Cannot start thread!");
562 //-----------------------------------------------------------------------------
563 int USERS_IMPL::Stop()
565 printfd(__FILE__, "USERS::Stop()\n");
569 //printfd(__FILE__, "Alredy stopped\n");
575 //5 seconds to thread stops itself
576 struct timespec ts = {0, 200000000};
577 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
582 nanosleep(&ts, NULL);
585 //after 5 seconds waiting thread still running. now kill it
588 printfd(__FILE__, "kill USERS thread.\n");
589 //TODO pthread_cancel()
590 if (pthread_kill(thread, SIGINT))
592 //errorStr = "Cannot kill USERS thread.";
593 //printfd(__FILE__, "Cannot kill USERS thread.\n");
596 printfd(__FILE__, "USERS killed\n");
599 printfd(__FILE__, "Before USERS::Run()\n");
600 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
602 // 'cause bind2st accepts only constant first param
603 for (std::list<USER_IMPL>::iterator it = users.begin();
606 it->WriteDetailStat(true);
608 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::WriteStat));
609 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
611 printfd(__FILE__, "USERS::Stop()\n");
614 //-----------------------------------------------------------------------------
615 void USERS_IMPL::RealDelUser()
617 STG_LOCKER lock(&mutex);
619 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
621 std::list<USER_TO_DEL>::iterator iter;
622 iter = usersToDelete.begin();
623 while (iter != usersToDelete.end())
625 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
626 if (iter->delTime + userDeleteDelayTime < stgTime)
628 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
629 if (store->DelUser(iter->iter->GetLogin()))
631 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
633 users.erase(iter->iter);
634 usersToDelete.erase(iter++);
643 //-----------------------------------------------------------------------------
644 void USERS_IMPL::AddToIPIdx(user_iter user)
646 printfd(__FILE__, "USERS: Add IP Idx\n");
647 uint32_t ip = user->GetCurrIP();
648 //assert(ip && "User has non-null ip");
650 return; // User has disconnected
652 STG_LOCKER lock(&mutex);
654 const std::map<uint32_t, user_iter>::iterator it(
655 ipIndex.lower_bound(ip)
658 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
660 ipIndex.insert(it, std::make_pair(ip, user));
662 //-----------------------------------------------------------------------------
663 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
665 printfd(__FILE__, "USERS: Del IP Idx\n");
666 assert(ip && "User has non-null ip");
668 STG_LOCKER lock(&mutex);
670 const std::map<uint32_t, user_iter>::iterator it(
674 if (it == ipIndex.end())
679 //-----------------------------------------------------------------------------
680 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
682 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
683 if (it == ipIndex.end())
688 //-----------------------------------------------------------------------------
689 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
691 STG_LOCKER lock(&mutex);
694 if (FindByIPIdx(ip, iter))
702 //-----------------------------------------------------------------------------
703 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
705 STG_LOCKER lock(&mutex);
708 if (FindByIPIdx(ip, iter))
716 //-----------------------------------------------------------------------------
717 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
719 STG_LOCKER lock(&mutex);
721 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
723 return it != ipIndex.end();
725 //-----------------------------------------------------------------------------
726 bool USERS_IMPL::IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const
728 STG_LOCKER lock(&mutex);
729 std::list<USER_IMPL>::const_iterator iter;
730 iter = users.begin();
731 while (iter != users.end())
733 if (iter->GetLogin() != login &&
734 !iter->GetProperty().ips.Get().IsAnyIP() &&
735 iter->GetProperty().ips.Get().IsIPInIPS(ip))
745 //-----------------------------------------------------------------------------
746 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
748 STG_LOCKER lock(&mutex);
749 onAddNotifiers.insert(n);
751 //-----------------------------------------------------------------------------
752 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
754 STG_LOCKER lock(&mutex);
755 onAddNotifiers.erase(n);
757 //-----------------------------------------------------------------------------
758 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
760 STG_LOCKER lock(&mutex);
761 onDelNotifiers.insert(n);
763 //-----------------------------------------------------------------------------
764 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
766 STG_LOCKER lock(&mutex);
767 onDelNotifiers.erase(n);
769 //-----------------------------------------------------------------------------
770 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
772 STG_LOCKER lock(&mutex);
773 onAddNotifiersImpl.insert(n);
775 //-----------------------------------------------------------------------------
776 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
778 STG_LOCKER lock(&mutex);
779 onAddNotifiersImpl.erase(n);
781 //-----------------------------------------------------------------------------
782 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
784 STG_LOCKER lock(&mutex);
785 onDelNotifiersImpl.insert(n);
787 //-----------------------------------------------------------------------------
788 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
790 STG_LOCKER lock(&mutex);
791 onDelNotifiersImpl.erase(n);
793 //-----------------------------------------------------------------------------
794 int USERS_IMPL::OpenSearch()
796 STG_LOCKER lock(&mutex);
798 searchDescriptors[handle] = users.begin();
801 //-----------------------------------------------------------------------------
802 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
804 USER_IMPL * ptr = NULL;
805 if (SearchNext(h, &ptr))
810 //-----------------------------------------------------------------------------
811 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
813 STG_LOCKER lock(&mutex);
815 if (searchDescriptors.find(h) == searchDescriptors.end())
817 WriteServLog("USERS. Incorrect search handle.");
821 if (searchDescriptors[h] == users.end())
824 while (searchDescriptors[h]->GetDeleted())
826 ++searchDescriptors[h];
827 if (searchDescriptors[h] == users.end())
833 *user = &(*searchDescriptors[h]);
835 ++searchDescriptors[h];
839 //-----------------------------------------------------------------------------
840 int USERS_IMPL::CloseSearch(int h)
842 STG_LOCKER lock(&mutex);
843 if (searchDescriptors.find(h) != searchDescriptors.end())
845 searchDescriptors.erase(searchDescriptors.find(h));
849 WriteServLog("USERS. Incorrect search handle.");
852 //-----------------------------------------------------------------------------
853 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
855 STG_LOCKER lock(&mutex);
856 loginIndex.insert(make_pair(user->GetLogin(), user));
858 //-----------------------------------------------------------------------------
859 void USERS_IMPL::DelUserFromIndexes(user_iter user)
861 STG_LOCKER lock(&mutex);
862 loginIndex.erase(user->GetLogin());
864 //-----------------------------------------------------------------------------
865 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
867 int statTime = settings->GetDetailStatWritePeriod();
876 if (t.tm_min % 30 == 0)
880 if (t.tm_min % 15 == 0)
884 if (t.tm_min % 10 == 0)