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));
525 if (settings->GetDayFeeIsLastDay())
527 printfd(__FILE__, "DayResetTraff - 2 -\n");
531 //-----------------------------------------------------------------------------
532 void USERS_IMPL::DayResetTraff(const struct tm & t1)
534 int dayResetTraff = settings->GetDayResetTraff();
535 if (dayResetTraff == 0)
536 dayResetTraff = DaysInCurrentMonth();
537 if (t1.tm_mday == dayResetTraff)
539 printfd(__FILE__, "ResetTraff\n");
540 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessNewMonth));
541 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
544 //-----------------------------------------------------------------------------
545 int USERS_IMPL::Start()
549 WriteServLog("USERS: Error: Cannot read users!");
554 if (pthread_create(&thread, NULL, Run, this))
556 WriteServLog("USERS: Error: Cannot start thread!");
561 //-----------------------------------------------------------------------------
562 int USERS_IMPL::Stop()
564 printfd(__FILE__, "USERS::Stop()\n");
568 //printfd(__FILE__, "Alredy stopped\n");
574 //5 seconds to thread stops itself
575 struct timespec ts = {0, 200000000};
576 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
581 nanosleep(&ts, NULL);
584 //after 5 seconds waiting thread still running. now kill it
587 printfd(__FILE__, "kill USERS thread.\n");
588 //TODO pthread_cancel()
589 if (pthread_kill(thread, SIGINT))
591 //errorStr = "Cannot kill USERS thread.";
592 //printfd(__FILE__, "Cannot kill USERS thread.\n");
595 printfd(__FILE__, "USERS killed\n");
598 printfd(__FILE__, "Before USERS::Run()\n");
599 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
601 // 'cause bind2st accepts only constant first param
602 for (std::list<USER_IMPL>::iterator it = users.begin();
605 it->WriteDetailStat(true);
607 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::WriteStat));
608 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
610 printfd(__FILE__, "USERS::Stop()\n");
613 //-----------------------------------------------------------------------------
614 void USERS_IMPL::RealDelUser()
616 STG_LOCKER lock(&mutex);
618 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
620 std::list<USER_TO_DEL>::iterator iter;
621 iter = usersToDelete.begin();
622 while (iter != usersToDelete.end())
624 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
625 if (iter->delTime + userDeleteDelayTime < stgTime)
627 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
628 if (store->DelUser(iter->iter->GetLogin()))
630 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
632 users.erase(iter->iter);
633 usersToDelete.erase(iter++);
642 //-----------------------------------------------------------------------------
643 void USERS_IMPL::AddToIPIdx(user_iter user)
645 printfd(__FILE__, "USERS: Add IP Idx\n");
646 uint32_t ip = user->GetCurrIP();
647 //assert(ip && "User has non-null ip");
649 return; // User has disconnected
651 STG_LOCKER lock(&mutex);
653 const std::map<uint32_t, user_iter>::iterator it(
654 ipIndex.lower_bound(ip)
657 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
659 ipIndex.insert(it, std::make_pair(ip, user));
661 //-----------------------------------------------------------------------------
662 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
664 printfd(__FILE__, "USERS: Del IP Idx\n");
665 assert(ip && "User has non-null ip");
667 STG_LOCKER lock(&mutex);
669 const std::map<uint32_t, user_iter>::iterator it(
673 if (it == ipIndex.end())
678 //-----------------------------------------------------------------------------
679 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
681 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
682 if (it == ipIndex.end())
687 //-----------------------------------------------------------------------------
688 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
690 STG_LOCKER lock(&mutex);
693 if (FindByIPIdx(ip, iter))
701 //-----------------------------------------------------------------------------
702 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
704 STG_LOCKER lock(&mutex);
707 if (FindByIPIdx(ip, iter))
715 //-----------------------------------------------------------------------------
716 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
718 STG_LOCKER lock(&mutex);
720 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
722 return it != ipIndex.end();
724 //-----------------------------------------------------------------------------
725 bool USERS_IMPL::IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const
727 STG_LOCKER lock(&mutex);
728 std::list<USER_IMPL>::const_iterator iter;
729 iter = users.begin();
730 while (iter != users.end())
732 if (iter->GetLogin() != login &&
733 !iter->GetProperty().ips.Get().IsAnyIP() &&
734 iter->GetProperty().ips.Get().IsIPInIPS(ip))
744 //-----------------------------------------------------------------------------
745 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
747 STG_LOCKER lock(&mutex);
748 onAddNotifiers.insert(n);
750 //-----------------------------------------------------------------------------
751 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
753 STG_LOCKER lock(&mutex);
754 onAddNotifiers.erase(n);
756 //-----------------------------------------------------------------------------
757 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
759 STG_LOCKER lock(&mutex);
760 onDelNotifiers.insert(n);
762 //-----------------------------------------------------------------------------
763 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
765 STG_LOCKER lock(&mutex);
766 onDelNotifiers.erase(n);
768 //-----------------------------------------------------------------------------
769 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
771 STG_LOCKER lock(&mutex);
772 onAddNotifiersImpl.insert(n);
774 //-----------------------------------------------------------------------------
775 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
777 STG_LOCKER lock(&mutex);
778 onAddNotifiersImpl.erase(n);
780 //-----------------------------------------------------------------------------
781 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
783 STG_LOCKER lock(&mutex);
784 onDelNotifiersImpl.insert(n);
786 //-----------------------------------------------------------------------------
787 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
789 STG_LOCKER lock(&mutex);
790 onDelNotifiersImpl.erase(n);
792 //-----------------------------------------------------------------------------
793 int USERS_IMPL::OpenSearch()
795 STG_LOCKER lock(&mutex);
797 searchDescriptors[handle] = users.begin();
800 //-----------------------------------------------------------------------------
801 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
803 USER_IMPL * ptr = NULL;
804 if (SearchNext(h, &ptr))
809 //-----------------------------------------------------------------------------
810 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
812 STG_LOCKER lock(&mutex);
814 if (searchDescriptors.find(h) == searchDescriptors.end())
816 WriteServLog("USERS. Incorrect search handle.");
820 if (searchDescriptors[h] == users.end())
823 while (searchDescriptors[h]->GetDeleted())
825 ++searchDescriptors[h];
826 if (searchDescriptors[h] == users.end())
832 *user = &(*searchDescriptors[h]);
834 ++searchDescriptors[h];
838 //-----------------------------------------------------------------------------
839 int USERS_IMPL::CloseSearch(int h)
841 STG_LOCKER lock(&mutex);
842 if (searchDescriptors.find(h) != searchDescriptors.end())
844 searchDescriptors.erase(searchDescriptors.find(h));
848 WriteServLog("USERS. Incorrect search handle.");
851 //-----------------------------------------------------------------------------
852 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
854 STG_LOCKER lock(&mutex);
855 loginIndex.insert(make_pair(user->GetLogin(), user));
857 //-----------------------------------------------------------------------------
858 void USERS_IMPL::DelUserFromIndexes(user_iter user)
860 STG_LOCKER lock(&mutex);
861 loginIndex.erase(user->GetLogin());
863 //-----------------------------------------------------------------------------
864 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
866 int statTime = settings->GetDetailStatWritePeriod();
875 if (t.tm_min % 30 == 0)
879 if (t.tm_min % 15 == 0)
883 if (t.tm_min % 10 == 0)