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 $
43 #include "stg/settings.h"
44 #include "stg/common.h"
45 #include "users_impl.h"
46 #include "stg_timer.h"
50 extern const volatile time_t stgTime;
52 //#define USERS_DEBUG 1
54 //-----------------------------------------------------------------------------
55 USERS_IMPL::USERS_IMPL(SETTINGS_IMPL * s, STORE * st, TARIFFS * t, const ADMIN * sa)
59 /*userIPNotifiersBefore(),
60 userIPNotifiersAfter(),*/
67 WriteServLog(GetStgLogger()),
79 pthread_mutexattr_t attr;
80 pthread_mutexattr_init(&attr);
81 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
82 pthread_mutex_init(&mutex, &attr);
84 //-----------------------------------------------------------------------------
85 USERS_IMPL::~USERS_IMPL()
87 pthread_mutex_destroy(&mutex);
89 //-----------------------------------------------------------------------------
90 int USERS_IMPL::FindByNameNonLock(const string & login, user_iter * user)
92 map<string, user_iter>::iterator iter;
93 iter = loginIndex.find(login);
94 if (iter != loginIndex.end())
102 //-----------------------------------------------------------------------------
103 int USERS_IMPL::FindByName(const string & login, USER_PTR * user)
105 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
107 int res = FindByNameNonLock(login, &u);
113 //-----------------------------------------------------------------------------
114 bool USERS_IMPL::TariffInUse(const string & tariffName) const
116 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
117 list<USER_IMPL>::const_iterator iter;
118 iter = users.begin();
119 while (iter != users.end())
121 if (iter->GetProperty().tariffName.Get() == tariffName)
127 //-----------------------------------------------------------------------------
128 int USERS_IMPL::Add(const string & login, const ADMIN * admin)
130 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
131 const PRIV * priv = admin->GetPriv();
133 if (!priv->userAddDel)
135 WriteServLog("%s tried to add user \'%s\'. Access denied.",
136 admin->GetLogStr().c_str(), login.c_str());
137 /*errorStr = "Admin \'" + admin->GetLogin() +
138 "\': tried to add user \'" + ud->login + "\'. Access denied.";*/
143 if (store->AddUser(login))
146 //WriteServLog("Admin \'%s\': tried to add user \'%s\'. Access denied.",
147 // admin->GetLogin().c_str(), ud->login.c_str());
152 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
163 if (settings->GetDayResetTraff() > tms->tm_mday)
166 tms->tm_mday = settings->GetDayResetTraff();*/
170 u.SetPassiveTimeAsNewUser();
175 WriteServLog("%s User \'%s\' added.",
176 admin->GetLogStr().c_str(), login.c_str());
182 AddUserIntoIndexes(users.begin());
183 SetUserNotifiers(users.begin());
186 // Fire all "on add" notifiers
187 set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
188 while (ni != onAddNotifiers.end())
190 (*ni)->Notify(&users.front());
196 // Fire all "on add" implementation notifiers
197 set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
198 while (ni != onAddNotifiersImpl.end())
200 (*ni)->Notify(&users.front());
207 //-----------------------------------------------------------------------------
208 void USERS_IMPL::Del(const string & login, const ADMIN * admin)
210 const PRIV * priv = admin->GetPriv();
213 if (!priv->userAddDel)
215 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
216 admin->GetLogStr().c_str(), login.c_str());
222 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
224 if (FindByNameNonLock(login, &u))
226 WriteServLog("%s tried to delete user \'%s\': not found.",
227 admin->GetLogStr().c_str(),
236 set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
237 while (ni != onDelNotifiers.end())
239 (*ni)->Notify(&(*u));
245 set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
246 while (ni != onDelNotifiersImpl.end())
248 (*ni)->Notify(&(*u));
254 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
260 utd.delTime = stgTime;
261 usersToDelete.push_back(utd);
263 UnSetUserNotifiers(u);
264 DelUserFromIndexes(u);
266 WriteServLog("%s User \'%s\' deleted.",
267 admin->GetLogStr().c_str(), login.c_str());
271 //-----------------------------------------------------------------------------
272 bool USERS_IMPL::Authorize(const std::string & login, uint32_t ip,
273 uint32_t enabledDirs, const AUTH * auth)
276 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
277 if (FindByNameNonLock(login, &iter))
279 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
283 if (iter->Authorize(ip, enabledDirs, auth))
286 if (FindByIPIdx(ip, iter))
288 if (iter->GetLogin() != login)
290 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
291 login.c_str(), inet_ntostring(ip).c_str(),
292 iter->GetLogin().c_str());
301 //-----------------------------------------------------------------------------
302 bool USERS_IMPL::Unauthorize(const std::string & login, const AUTH * auth)
305 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
306 if (FindByNameNonLock(login, &iter))
308 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
312 uint32_t ip = iter->GetCurrIP();
314 iter->Unauthorize(auth);
316 if (!iter->GetAuthorized())
321 //-----------------------------------------------------------------------------
322 int USERS_IMPL::ReadUsers()
324 vector<string> usersList;
326 if (store->GetUsersList(&usersList) < 0)
328 WriteServLog(store->GetStrError().c_str());
334 for (unsigned int i = 0; i < usersList.size(); i++)
336 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
338 u.SetLogin(usersList[i]);
342 AddUserIntoIndexes(ui);
343 SetUserNotifiers(ui);
345 if (ui->ReadConf() < 0)
348 if (ui->ReadStat() < 0)
354 //-----------------------------------------------------------------------------
355 void * USERS_IMPL::Run(void * d)
357 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
358 USERS_IMPL * us = (USERS_IMPL*) d;
362 localtime_r(&tt, &t);
367 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
369 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
370 string monFile = us->settings->GetMonitorDir() + "/users_r";
371 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
373 us->isRunning = true;
376 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
377 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
379 for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER_IMPL::Run));
382 localtime_r(&tt, &t);
386 printfd(__FILE__,"Sec = %d\n", stgTime);
387 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
393 if (day != t.tm_mday)
395 printfd(__FILE__,"Sec = %d\n", stgTime);
396 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
401 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
403 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
405 TouchFile(monFile.c_str());
409 } //while (us->nonstop)
411 user_iter ui = us->users.begin();
412 while (ui != us->users.end())
414 us->UnSetUserNotifiers(ui);
415 us->DelUserFromIndexes(ui);
419 list<USER_TO_DEL>::iterator iter;
420 iter = us->usersToDelete.begin();
421 while (iter != us->usersToDelete.end())
423 iter->delTime -= 2 * userDeleteDelayTime;
428 us->isRunning = false;
432 //-----------------------------------------------------------------------------
433 void USERS_IMPL::NewMinute(const struct tm & t)
435 //Write traff, reset session traff. Fake disconnect-connect
436 if (t.tm_hour == 23 && t.tm_min == 59)
438 printfd(__FILE__,"MidnightResetSessionStat\n");
439 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
442 if (TimeToWriteDetailStat(t))
444 //printfd(__FILE__, "USER::WriteInetStat\n");
447 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
448 list<USER_IMPL>::iterator usr = users.begin();
449 while (usr != users.end())
452 usr->WriteDetailStat();
454 if (usersCnt % 10 == 0)
455 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
461 //-----------------------------------------------------------------------------
462 void USERS_IMPL::NewDay(const struct tm & t)
466 localtime_r(&tt, &t1);
467 int dayFee = settings->GetDayFee();
470 dayFee = DaysInCurrentMonth();
472 printfd(__FILE__, "DayFee = %d\n", dayFee);
473 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
474 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
476 if (!settings->GetDayFeeIsLastDay())
478 printfd(__FILE__, "DayResetTraff - 1 -\n");
480 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
483 if (settings->GetSpreadFee())
485 printfd(__FILE__, "Spread DayFee\n");
486 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
490 if (t.tm_mday == dayFee)
492 printfd(__FILE__, "DayFee\n");
493 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFee));
497 if (settings->GetDayFeeIsLastDay())
499 printfd(__FILE__, "DayResetTraff - 2 -\n");
503 //-----------------------------------------------------------------------------
504 void USERS_IMPL::DayResetTraff(const struct tm & t1)
506 int dayResetTraff = settings->GetDayResetTraff();
507 if (dayResetTraff == 0)
508 dayResetTraff = DaysInCurrentMonth();
509 if (t1.tm_mday == dayResetTraff)
511 printfd(__FILE__, "ResetTraff\n");
512 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessNewMonth));
513 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
516 //-----------------------------------------------------------------------------
517 int USERS_IMPL::Start()
521 WriteServLog("USERS: Error: Cannot read users!");
526 if (pthread_create(&thread, NULL, Run, this))
528 WriteServLog("USERS: Error: Cannot start thread!");
533 //-----------------------------------------------------------------------------
534 int USERS_IMPL::Stop()
536 printfd(__FILE__, "USERS::Stop()\n");
540 //printfd(__FILE__, "Alredy stopped\n");
546 //5 seconds to thread stops itself
547 struct timespec ts = {0, 200000000};
548 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
553 nanosleep(&ts, NULL);
556 //after 5 seconds waiting thread still running. now kill it
559 printfd(__FILE__, "kill USERS thread.\n");
560 //TODO pthread_cancel()
561 if (pthread_kill(thread, SIGINT))
563 //errorStr = "Cannot kill USERS thread.";
564 //printfd(__FILE__, "Cannot kill USERS thread.\n");
567 printfd(__FILE__, "USERS killed\n");
570 printfd(__FILE__, "Before USERS::Run()\n");
571 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
573 // 'cause bind2st accepts only constant first param
574 for (list<USER_IMPL>::iterator it = users.begin();
577 it->WriteDetailStat(true);
579 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteStat));
580 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
582 printfd(__FILE__, "USERS::Stop()\n");
585 //-----------------------------------------------------------------------------
586 void USERS_IMPL::RealDelUser()
588 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
590 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
592 list<USER_TO_DEL>::iterator iter;
593 iter = usersToDelete.begin();
594 while (iter != usersToDelete.end())
596 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
597 if (iter->delTime + userDeleteDelayTime < stgTime)
599 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
600 if (store->DelUser(iter->iter->GetLogin()))
602 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
604 users.erase(iter->iter);
605 usersToDelete.erase(iter++);
614 //-----------------------------------------------------------------------------
615 void USERS_IMPL::AddToIPIdx(user_iter user)
617 printfd(__FILE__, "USERS: Add IP Idx\n");
618 uint32_t ip = user->GetCurrIP();
619 //assert(ip && "User has non-null ip");
621 return; // User has disconnected
623 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
625 const map<uint32_t, user_iter>::iterator it(
626 ipIndex.lower_bound(ip)
629 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
631 ipIndex.insert(it, std::make_pair(ip, user));
633 //-----------------------------------------------------------------------------
634 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
636 printfd(__FILE__, "USERS: Del IP Idx\n");
637 assert(ip && "User has non-null ip");
639 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
641 const map<uint32_t, user_iter>::iterator it(
645 if (it == ipIndex.end())
650 //-----------------------------------------------------------------------------
651 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
653 map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
654 if (it == ipIndex.end())
659 //-----------------------------------------------------------------------------
660 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
662 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
665 if (FindByIPIdx(ip, iter))
673 //-----------------------------------------------------------------------------
674 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
676 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
679 if (FindByIPIdx(ip, iter))
687 //-----------------------------------------------------------------------------
688 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
690 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
692 map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
694 return it != ipIndex.end();
696 //-----------------------------------------------------------------------------
697 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
699 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
700 onAddNotifiers.insert(n);
702 //-----------------------------------------------------------------------------
703 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
705 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
706 onAddNotifiers.erase(n);
708 //-----------------------------------------------------------------------------
709 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
711 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
712 onDelNotifiers.insert(n);
714 //-----------------------------------------------------------------------------
715 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
717 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
718 onDelNotifiers.erase(n);
720 //-----------------------------------------------------------------------------
721 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
723 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
724 onAddNotifiersImpl.insert(n);
726 //-----------------------------------------------------------------------------
727 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
729 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
730 onAddNotifiersImpl.erase(n);
732 //-----------------------------------------------------------------------------
733 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
735 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
736 onDelNotifiersImpl.insert(n);
738 //-----------------------------------------------------------------------------
739 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
741 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
742 onDelNotifiersImpl.erase(n);
744 //-----------------------------------------------------------------------------
745 int USERS_IMPL::OpenSearch()
747 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
749 searchDescriptors[handle] = users.begin();
752 //-----------------------------------------------------------------------------
753 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
755 USER_IMPL * ptr = NULL;
756 if (SearchNext(h, &ptr))
761 //-----------------------------------------------------------------------------
762 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
764 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
766 if (searchDescriptors.find(h) == searchDescriptors.end())
768 WriteServLog("USERS. Incorrect search handle.");
772 if (searchDescriptors[h] == users.end())
775 while (searchDescriptors[h]->GetDeleted())
777 ++searchDescriptors[h];
778 if (searchDescriptors[h] == users.end())
784 *user = &(*searchDescriptors[h]);
786 ++searchDescriptors[h];
790 //-----------------------------------------------------------------------------
791 int USERS_IMPL::CloseSearch(int h)
793 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
794 if (searchDescriptors.find(h) != searchDescriptors.end())
796 searchDescriptors.erase(searchDescriptors.find(h));
800 WriteServLog("USERS. Incorrect search handle.");
803 //-----------------------------------------------------------------------------
804 void USERS_IMPL::SetUserNotifiers(user_iter user)
806 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
808 /*PROPERTY_NOTIFER_IP_BEFORE nb(*this, user);
809 PROPERTY_NOTIFER_IP_AFTER na(*this, user);
811 userIPNotifiersBefore.push_front(nb);
812 userIPNotifiersAfter.push_front(na);
814 user->AddCurrIPBeforeNotifier(&(*userIPNotifiersBefore.begin()));
815 user->AddCurrIPAfterNotifier(&(*userIPNotifiersAfter.begin()));*/
817 //-----------------------------------------------------------------------------
818 void USERS_IMPL::UnSetUserNotifiers(user_iter user)
820 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
822 /*list<PROPERTY_NOTIFER_IP_BEFORE>::iterator bi;
823 list<PROPERTY_NOTIFER_IP_AFTER>::iterator ai;
825 bi = userIPNotifiersBefore.begin();
826 while (bi != userIPNotifiersBefore.end())
828 if (bi->GetUser() == user)
830 bi->GetUser()->DelCurrIPBeforeNotifier(&(*bi));
831 userIPNotifiersBefore.erase(bi);
832 //printfd(__FILE__, "Notifier Before removed. User %s\n", bi->GetUser()->GetLogin().c_str());
838 ai = userIPNotifiersAfter.begin();
839 while (ai != userIPNotifiersAfter.end())
841 if (ai->GetUser() == user)
843 ai->GetUser()->DelCurrIPAfterNotifier(&(*ai));
844 userIPNotifiersAfter.erase(ai);
845 //printfd(__FILE__, "Notifier After removed. User %s\n", ai->GetUser()->GetLogin().c_str());
851 //-----------------------------------------------------------------------------
852 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
854 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
855 loginIndex.insert(make_pair(user->GetLogin(), user));
857 //-----------------------------------------------------------------------------
858 void USERS_IMPL::DelUserFromIndexes(user_iter user)
860 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
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)