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,
55 TARIFFS * t, SERVICES & svcs,
62 WriteServLog(GetStgLogger()),
67 pthread_mutexattr_t attr;
68 pthread_mutexattr_init(&attr);
69 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
70 pthread_mutex_init(&mutex, &attr);
72 //-----------------------------------------------------------------------------
73 USERS_IMPL::~USERS_IMPL()
75 pthread_mutex_destroy(&mutex);
77 //-----------------------------------------------------------------------------
78 int USERS_IMPL::FindByNameNonLock(const std::string & login, user_iter * user)
80 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
81 if (iter == loginIndex.end())
87 //-----------------------------------------------------------------------------
88 int USERS_IMPL::FindByNameNonLock(const std::string & login, const_user_iter * user) const
90 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
91 if (iter == loginIndex.end())
97 //-----------------------------------------------------------------------------
98 int USERS_IMPL::FindByName(const std::string & login, USER_PTR * user)
100 STG_LOCKER lock(&mutex);
102 if (FindByNameNonLock(login, &u))
107 //-----------------------------------------------------------------------------
108 int USERS_IMPL::FindByName(const std::string & login, CONST_USER_PTR * user) const
110 STG_LOCKER lock(&mutex);
112 if (FindByNameNonLock(login, &u))
117 //-----------------------------------------------------------------------------
118 bool USERS_IMPL::Exists(const std::string & login) const
120 STG_LOCKER lock(&mutex);
121 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
122 return iter != loginIndex.end();
124 //-----------------------------------------------------------------------------
125 bool USERS_IMPL::TariffInUse(const std::string & tariffName) const
127 STG_LOCKER lock(&mutex);
128 std::list<USER_IMPL>::const_iterator iter;
129 iter = users.begin();
130 while (iter != users.end())
132 if (iter->GetProperty().tariffName.Get() == tariffName)
138 //-----------------------------------------------------------------------------
139 int USERS_IMPL::Add(const std::string & login, const ADMIN * admin)
141 STG_LOCKER lock(&mutex);
142 const PRIV * priv = admin->GetPriv();
144 if (!priv->userAddDel)
146 WriteServLog("%s tried to add user \'%s\'. Access denied.",
147 admin->GetLogStr().c_str(), login.c_str());
148 /*errorStr = "Admin \'" + admin->GetLogin() +
149 "\': tried to add user \'" + ud->login + "\'. Access denied.";*/
154 if (store->AddUser(login))
157 //WriteServLog("Admin \'%s\': tried to add user \'%s\'. Access denied.",
158 // admin->GetLogin().c_str(), ud->login.c_str());
163 USER_IMPL u(settings, store, tariffs, sysAdmin, this, m_services);
174 if (settings->GetDayResetTraff() > tms->tm_mday)
177 tms->tm_mday = settings->GetDayResetTraff();*/
181 u.SetPassiveTimeAsNewUser();
186 WriteServLog("%s User \'%s\' added.",
187 admin->GetLogStr().c_str(), login.c_str());
193 AddUserIntoIndexes(users.begin());
196 // Fire all "on add" notifiers
197 std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
198 while (ni != onAddNotifiers.end())
200 (*ni)->Notify(&users.front());
206 // Fire all "on add" implementation notifiers
207 std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
208 while (ni != onAddNotifiersImpl.end())
210 (*ni)->Notify(&users.front());
217 //-----------------------------------------------------------------------------
218 void USERS_IMPL::Del(const std::string & login, const ADMIN * admin)
220 const PRIV * priv = admin->GetPriv();
223 if (!priv->userAddDel)
225 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
226 admin->GetLogStr().c_str(), login.c_str());
232 STG_LOCKER lock(&mutex);
234 if (FindByNameNonLock(login, &u))
236 WriteServLog("%s tried to delete user \'%s\': not found.",
237 admin->GetLogStr().c_str(),
246 std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
247 while (ni != onDelNotifiers.end())
249 (*ni)->Notify(&(*u));
255 std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
256 while (ni != onDelNotifiersImpl.end())
258 (*ni)->Notify(&(*u));
264 STG_LOCKER lock(&mutex);
270 utd.delTime = stgTime;
271 usersToDelete.push_back(utd);
273 DelUserFromIndexes(u);
275 WriteServLog("%s User \'%s\' deleted.",
276 admin->GetLogStr().c_str(), login.c_str());
280 //-----------------------------------------------------------------------------
281 bool USERS_IMPL::Authorize(const std::string & login, uint32_t ip,
282 uint32_t enabledDirs, const AUTH * auth)
285 STG_LOCKER lock(&mutex);
286 if (FindByNameNonLock(login, &iter))
288 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
292 if (FindByIPIdx(ip, iter))
294 if (iter->GetLogin() != login)
296 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
297 login.c_str(), inet_ntostring(ip).c_str(),
298 iter->GetLogin().c_str());
301 if (iter->Authorize(ip, enabledDirs, auth))
306 if (iter->Authorize(ip, enabledDirs, auth))
312 //-----------------------------------------------------------------------------
313 bool USERS_IMPL::Unauthorize(const std::string & login,
315 const std::string & reason)
318 STG_LOCKER lock(&mutex);
319 if (FindByNameNonLock(login, &iter))
321 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
325 uint32_t ip = iter->GetCurrIP();
327 iter->Unauthorize(auth, reason);
329 if (!iter->GetAuthorized())
334 //-----------------------------------------------------------------------------
335 int USERS_IMPL::ReadUsers()
337 std::vector<std::string> usersList;
339 if (store->GetUsersList(&usersList) < 0)
341 WriteServLog(store->GetStrError().c_str());
348 for (unsigned int i = 0; i < usersList.size(); i++)
350 USER_IMPL u(settings, store, tariffs, sysAdmin, this, m_services);
352 u.SetLogin(usersList[i]);
356 AddUserIntoIndexes(ui);
358 if (settings->GetStopOnError())
360 if (ui->ReadConf() < 0)
363 if (ui->ReadStat() < 0)
368 if (ui->ReadConf() < 0)
371 if (ui->ReadStat() < 0)
380 //-----------------------------------------------------------------------------
381 void * USERS_IMPL::Run(void * d)
384 sigfillset(&signalSet);
385 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
387 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
388 USERS_IMPL * us = static_cast<USERS_IMPL *>(d);
392 localtime_r(&tt, &t);
397 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
399 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
400 std::string monFile = us->settings->GetMonitorDir() + "/users_r";
401 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
403 us->isRunning = true;
406 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
407 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
409 for_each(us->users.begin(), us->users.end(), std::mem_fun_ref(&USER_IMPL::Run));
412 localtime_r(&tt, &t);
416 printfd(__FILE__,"Sec = %d\n", stgTime);
417 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
423 if (day != t.tm_mday)
425 printfd(__FILE__,"Sec = %d\n", stgTime);
426 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
431 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
433 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
435 TouchFile(monFile.c_str());
439 } //while (us->nonstop)
441 user_iter ui = us->users.begin();
442 while (ui != us->users.end())
444 us->DelUserFromIndexes(ui);
448 std::list<USER_TO_DEL>::iterator iter;
449 iter = us->usersToDelete.begin();
450 while (iter != us->usersToDelete.end())
452 iter->delTime -= 2 * userDeleteDelayTime;
457 us->isRunning = false;
461 //-----------------------------------------------------------------------------
462 void USERS_IMPL::NewMinute(const struct tm & t)
464 //Write traff, reset session traff. Fake disconnect-connect
465 if (t.tm_hour == 23 && t.tm_min == 59)
467 printfd(__FILE__,"MidnightResetSessionStat\n");
468 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
471 if (TimeToWriteDetailStat(t))
473 //printfd(__FILE__, "USER::WriteInetStat\n");
476 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
477 std::list<USER_IMPL>::iterator usr = users.begin();
478 while (usr != users.end())
481 usr->WriteDetailStat();
483 if (usersCnt % 10 == 0)
484 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
490 //-----------------------------------------------------------------------------
491 void USERS_IMPL::NewDay(const struct tm & t)
495 localtime_r(&tt, &t1);
496 int dayFee = settings->GetDayFee();
499 dayFee = DaysInCurrentMonth();
501 printfd(__FILE__, "DayFee = %d\n", dayFee);
502 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
503 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
505 if (!settings->GetDayFeeIsLastDay())
507 printfd(__FILE__, "DayResetTraff - 1 -\n");
509 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
512 if (settings->GetSpreadFee())
514 printfd(__FILE__, "Spread DayFee\n");
515 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
519 if (t.tm_mday == dayFee)
521 printfd(__FILE__, "DayFee\n");
522 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFee));
526 std::for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDailyFee));
527 std::for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessServices));
529 if (settings->GetDayFeeIsLastDay())
531 printfd(__FILE__, "DayResetTraff - 2 -\n");
535 //-----------------------------------------------------------------------------
536 void USERS_IMPL::DayResetTraff(const struct tm & t1)
538 int dayResetTraff = settings->GetDayResetTraff();
539 if (dayResetTraff == 0)
540 dayResetTraff = DaysInCurrentMonth();
541 if (t1.tm_mday == dayResetTraff)
543 printfd(__FILE__, "ResetTraff\n");
544 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessNewMonth));
545 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
548 //-----------------------------------------------------------------------------
549 int USERS_IMPL::Start()
553 WriteServLog("USERS: Error: Cannot read users!");
558 if (pthread_create(&thread, NULL, Run, this))
560 WriteServLog("USERS: Error: Cannot start thread!");
565 //-----------------------------------------------------------------------------
566 int USERS_IMPL::Stop()
568 printfd(__FILE__, "USERS::Stop()\n");
572 //printfd(__FILE__, "Alredy stopped\n");
578 //5 seconds to thread stops itself
579 struct timespec ts = {0, 200000000};
580 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
585 nanosleep(&ts, NULL);
588 //after 5 seconds waiting thread still running. now kill it
591 printfd(__FILE__, "kill USERS thread.\n");
592 //TODO pthread_cancel()
593 if (pthread_kill(thread, SIGINT))
595 //errorStr = "Cannot kill USERS thread.";
596 //printfd(__FILE__, "Cannot kill USERS thread.\n");
599 printfd(__FILE__, "USERS killed\n");
602 printfd(__FILE__, "Before USERS::Run()\n");
603 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
605 // 'cause bind2st accepts only constant first param
606 for (std::list<USER_IMPL>::iterator it = users.begin();
609 it->WriteDetailStat(true);
611 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::WriteStat));
612 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
614 printfd(__FILE__, "USERS::Stop()\n");
617 //-----------------------------------------------------------------------------
618 void USERS_IMPL::RealDelUser()
620 STG_LOCKER lock(&mutex);
622 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
624 std::list<USER_TO_DEL>::iterator iter;
625 iter = usersToDelete.begin();
626 while (iter != usersToDelete.end())
628 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
629 if (iter->delTime + userDeleteDelayTime < stgTime)
631 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
632 if (store->DelUser(iter->iter->GetLogin()))
634 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
636 users.erase(iter->iter);
637 usersToDelete.erase(iter++);
646 //-----------------------------------------------------------------------------
647 void USERS_IMPL::AddToIPIdx(user_iter user)
649 printfd(__FILE__, "USERS: Add IP Idx\n");
650 uint32_t ip = user->GetCurrIP();
651 //assert(ip && "User has non-null ip");
653 return; // User has disconnected
655 STG_LOCKER lock(&mutex);
657 const std::map<uint32_t, user_iter>::iterator it(
658 ipIndex.lower_bound(ip)
661 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
663 ipIndex.insert(it, std::make_pair(ip, user));
665 //-----------------------------------------------------------------------------
666 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
668 printfd(__FILE__, "USERS: Del IP Idx\n");
669 assert(ip && "User has non-null ip");
671 STG_LOCKER lock(&mutex);
673 const std::map<uint32_t, user_iter>::iterator it(
677 if (it == ipIndex.end())
682 //-----------------------------------------------------------------------------
683 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
685 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
686 if (it == ipIndex.end())
691 //-----------------------------------------------------------------------------
692 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
694 STG_LOCKER lock(&mutex);
697 if (FindByIPIdx(ip, iter))
705 //-----------------------------------------------------------------------------
706 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
708 STG_LOCKER lock(&mutex);
711 if (FindByIPIdx(ip, iter))
719 //-----------------------------------------------------------------------------
720 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
722 STG_LOCKER lock(&mutex);
724 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
726 return it != ipIndex.end();
728 //-----------------------------------------------------------------------------
729 bool USERS_IMPL::IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const
731 STG_LOCKER lock(&mutex);
732 std::list<USER_IMPL>::const_iterator iter;
733 iter = users.begin();
734 while (iter != users.end())
736 if (iter->GetLogin() != login &&
737 !iter->GetProperty().ips.Get().IsAnyIP() &&
738 iter->GetProperty().ips.Get().IsIPInIPS(ip))
748 //-----------------------------------------------------------------------------
749 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
751 STG_LOCKER lock(&mutex);
752 onAddNotifiers.insert(n);
754 //-----------------------------------------------------------------------------
755 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
757 STG_LOCKER lock(&mutex);
758 onAddNotifiers.erase(n);
760 //-----------------------------------------------------------------------------
761 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
763 STG_LOCKER lock(&mutex);
764 onDelNotifiers.insert(n);
766 //-----------------------------------------------------------------------------
767 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
769 STG_LOCKER lock(&mutex);
770 onDelNotifiers.erase(n);
772 //-----------------------------------------------------------------------------
773 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
775 STG_LOCKER lock(&mutex);
776 onAddNotifiersImpl.insert(n);
778 //-----------------------------------------------------------------------------
779 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
781 STG_LOCKER lock(&mutex);
782 onAddNotifiersImpl.erase(n);
784 //-----------------------------------------------------------------------------
785 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
787 STG_LOCKER lock(&mutex);
788 onDelNotifiersImpl.insert(n);
790 //-----------------------------------------------------------------------------
791 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
793 STG_LOCKER lock(&mutex);
794 onDelNotifiersImpl.erase(n);
796 //-----------------------------------------------------------------------------
797 int USERS_IMPL::OpenSearch()
799 STG_LOCKER lock(&mutex);
801 searchDescriptors[handle] = users.begin();
804 //-----------------------------------------------------------------------------
805 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
807 USER_IMPL * ptr = NULL;
808 if (SearchNext(h, &ptr))
813 //-----------------------------------------------------------------------------
814 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
816 STG_LOCKER lock(&mutex);
818 if (searchDescriptors.find(h) == searchDescriptors.end())
820 WriteServLog("USERS. Incorrect search handle.");
824 if (searchDescriptors[h] == users.end())
827 while (searchDescriptors[h]->GetDeleted())
829 ++searchDescriptors[h];
830 if (searchDescriptors[h] == users.end())
836 *user = &(*searchDescriptors[h]);
838 ++searchDescriptors[h];
842 //-----------------------------------------------------------------------------
843 int USERS_IMPL::CloseSearch(int h)
845 STG_LOCKER lock(&mutex);
846 if (searchDescriptors.find(h) != searchDescriptors.end())
848 searchDescriptors.erase(searchDescriptors.find(h));
852 WriteServLog("USERS. Incorrect search handle.");
855 //-----------------------------------------------------------------------------
856 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
858 STG_LOCKER lock(&mutex);
859 loginIndex.insert(make_pair(user->GetLogin(), user));
861 //-----------------------------------------------------------------------------
862 void USERS_IMPL::DelUserFromIndexes(user_iter user)
864 STG_LOCKER lock(&mutex);
865 loginIndex.erase(user->GetLogin());
867 //-----------------------------------------------------------------------------
868 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
870 int statTime = settings->GetDetailStatWritePeriod();
879 if (t.tm_min % 30 == 0)
883 if (t.tm_min % 15 == 0)
887 if (t.tm_min % 10 == 0)