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(),
234 set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
235 while (ni != onDelNotifiers.end())
237 (*ni)->Notify(&(*u));
243 set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
244 while (ni != onDelNotifiersImpl.end())
246 (*ni)->Notify(&(*u));
252 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
259 utd.delTime = stgTime;
260 usersToDelete.push_back(utd);
262 UnSetUserNotifiers(u);
263 DelUserFromIndexes(u);
265 WriteServLog("%s User \'%s\' deleted.",
266 admin->GetLogStr().c_str(), login.c_str());
270 //-----------------------------------------------------------------------------
271 int USERS_IMPL::ReadUsers()
273 vector<string> usersList;
275 if (store->GetUsersList(&usersList) < 0)
277 WriteServLog(store->GetStrError().c_str());
283 for (unsigned int i = 0; i < usersList.size(); i++)
285 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
287 u.SetLogin(usersList[i]);
291 AddUserIntoIndexes(ui);
292 SetUserNotifiers(ui);
294 if (ui->ReadConf() < 0)
297 if (ui->ReadStat() < 0)
303 //-----------------------------------------------------------------------------
304 void * USERS_IMPL::Run(void * d)
306 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
307 USERS_IMPL * us = (USERS_IMPL*) d;
311 localtime_r(&tt, &t);
316 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
318 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
319 string monFile = us->settings->GetMonitorDir() + "/users_r";
320 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
322 us->isRunning = true;
325 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
326 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
328 for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER_IMPL::Run));
331 localtime_r(&tt, &t);
335 printfd(__FILE__,"Sec = %d\n", stgTime);
336 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
342 if (day != t.tm_mday)
344 printfd(__FILE__,"Sec = %d\n", stgTime);
345 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
350 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
352 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
354 TouchFile(monFile.c_str());
358 } //while (us->nonstop)
360 user_iter ui = us->users.begin();
361 while (ui != us->users.end())
363 us->UnSetUserNotifiers(ui);
364 us->DelUserFromIndexes(ui);
368 list<USER_TO_DEL>::iterator iter;
369 iter = us->usersToDelete.begin();
370 while (iter != us->usersToDelete.end())
372 iter->delTime -= 2 * userDeleteDelayTime;
377 us->isRunning = false;
381 //-----------------------------------------------------------------------------
382 void USERS_IMPL::NewMinute(const struct tm & t)
384 //Write traff, reset session traff. Fake disconnect-connect
385 if (t.tm_hour == 23 && t.tm_min == 59)
387 printfd(__FILE__,"MidnightResetSessionStat\n");
388 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
391 if (TimeToWriteDetailStat(t))
393 //printfd(__FILE__, "USER::WriteInetStat\n");
396 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
397 list<USER_IMPL>::iterator usr = users.begin();
398 while (usr != users.end())
401 usr->WriteDetailStat();
403 if (usersCnt % 10 == 0)
404 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
410 //-----------------------------------------------------------------------------
411 void USERS_IMPL::NewDay(const struct tm & t)
415 localtime_r(&tt, &t1);
416 int dayFee = settings->GetDayFee();
419 dayFee = DaysInCurrentMonth();
421 printfd(__FILE__, "DayFee = %d\n", dayFee);
422 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
423 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
425 if (!settings->GetDayFeeIsLastDay())
427 printfd(__FILE__, "DayResetTraff - 1 -\n");
429 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
432 if (settings->GetSpreadFee())
434 printfd(__FILE__, "Spread DayFee\n");
435 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
439 if (t.tm_mday == dayFee)
441 printfd(__FILE__, "DayFee\n");
442 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFee));
446 if (settings->GetDayFeeIsLastDay())
448 printfd(__FILE__, "DayResetTraff - 2 -\n");
452 //-----------------------------------------------------------------------------
453 void USERS_IMPL::DayResetTraff(const struct tm & t1)
455 int dayResetTraff = settings->GetDayResetTraff();
456 if (dayResetTraff == 0)
457 dayResetTraff = DaysInCurrentMonth();
458 if (t1.tm_mday == dayResetTraff)
460 printfd(__FILE__, "ResetTraff\n");
461 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessNewMonth));
462 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
465 //-----------------------------------------------------------------------------
466 int USERS_IMPL::Start()
470 WriteServLog("USERS: Error: Cannot read users!");
475 if (pthread_create(&thread, NULL, Run, this))
477 WriteServLog("USERS: Error: Cannot start thread!");
482 //-----------------------------------------------------------------------------
483 int USERS_IMPL::Stop()
485 printfd(__FILE__, "USERS::Stop()\n");
489 //printfd(__FILE__, "Alredy stopped\n");
495 //5 seconds to thread stops itself
496 struct timespec ts = {0, 200000000};
497 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
502 nanosleep(&ts, NULL);
505 //after 5 seconds waiting thread still running. now kill it
508 printfd(__FILE__, "kill USERS thread.\n");
509 //TODO pthread_cancel()
510 if (pthread_kill(thread, SIGINT))
512 //errorStr = "Cannot kill USERS thread.";
513 //printfd(__FILE__, "Cannot kill USERS thread.\n");
516 printfd(__FILE__, "USERS killed\n");
519 printfd(__FILE__, "Before USERS::Run()\n");
520 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
522 // 'cause bind2st accepts only constant first param
523 for (list<USER_IMPL>::iterator it = users.begin();
526 it->WriteDetailStat(true);
528 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteStat));
529 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
531 printfd(__FILE__, "USERS::Stop()\n");
534 //-----------------------------------------------------------------------------
535 void USERS_IMPL::RealDelUser()
537 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
539 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
541 list<USER_TO_DEL>::iterator iter;
542 iter = usersToDelete.begin();
543 while (iter != usersToDelete.end())
545 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
546 if (iter->delTime + userDeleteDelayTime < stgTime)
548 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
549 if (store->DelUser(iter->iter->GetLogin()))
551 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
553 users.erase(iter->iter);
554 usersToDelete.erase(iter++);
563 //-----------------------------------------------------------------------------
564 void USERS_IMPL::AddToIPIdx(user_iter user)
566 printfd(__FILE__, "USERS: Add IP Idx\n");
567 uint32_t ip = user->GetCurrIP();
568 //assert(ip && "User has non-null ip");
570 return; // User has disconnected
572 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
574 const map<uint32_t, user_iter>::iterator it(
575 ipIndex.lower_bound(ip)
578 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
580 ipIndex.insert(it, std::make_pair(ip, user));
582 //-----------------------------------------------------------------------------
583 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
585 printfd(__FILE__, "USERS: Del IP Idx\n");
586 assert(ip && "User has non-null ip");
588 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
590 const map<uint32_t, user_iter>::iterator it(
594 //assert(it != ipIndex.end() && "User is in index");
595 if (it == ipIndex.end())
596 return; // User has not been added
600 //-----------------------------------------------------------------------------
601 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
603 USER_IMPL * ptr = NULL;
604 if (FindByIPIdx(ip, &ptr))
609 //-----------------------------------------------------------------------------
610 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
612 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
614 map<uint32_t, user_iter>::const_iterator it;
615 it = ipIndex.find(ip);
617 if (it == ipIndex.end())
619 //printfd(__FILE__, "User NOT found in IP_Index!!!\n");
622 *usr = &(*it->second);
623 //printfd(__FILE__, "User found in IP_Index\n");
626 //-----------------------------------------------------------------------------
627 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
629 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
631 map<uint32_t, user_iter>::const_iterator it;
632 it = ipIndex.find(ip);
634 return it != ipIndex.end();
636 //-----------------------------------------------------------------------------
637 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
639 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
640 onAddNotifiers.insert(n);
642 //-----------------------------------------------------------------------------
643 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
645 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
646 onAddNotifiers.erase(n);
648 //-----------------------------------------------------------------------------
649 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
651 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
652 onDelNotifiers.insert(n);
654 //-----------------------------------------------------------------------------
655 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
657 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
658 onDelNotifiers.erase(n);
660 //-----------------------------------------------------------------------------
661 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
663 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
664 onAddNotifiersImpl.insert(n);
666 //-----------------------------------------------------------------------------
667 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
669 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
670 onAddNotifiersImpl.erase(n);
672 //-----------------------------------------------------------------------------
673 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
675 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
676 onDelNotifiersImpl.insert(n);
678 //-----------------------------------------------------------------------------
679 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
681 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
682 onDelNotifiersImpl.erase(n);
684 //-----------------------------------------------------------------------------
685 int USERS_IMPL::OpenSearch()
687 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
689 searchDescriptors[handle] = users.begin();
692 //-----------------------------------------------------------------------------
693 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
695 USER_IMPL * ptr = NULL;
696 if (SearchNext(h, &ptr))
701 //-----------------------------------------------------------------------------
702 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
704 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
706 if (searchDescriptors.find(h) == searchDescriptors.end())
708 WriteServLog("USERS. Incorrect search handle.");
712 if (searchDescriptors[h] == users.end())
715 while (searchDescriptors[h]->GetDeleted())
717 ++searchDescriptors[h];
718 if (searchDescriptors[h] == users.end())
724 *user = &(*searchDescriptors[h]);
726 ++searchDescriptors[h];
730 //-----------------------------------------------------------------------------
731 int USERS_IMPL::CloseSearch(int h)
733 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
734 if (searchDescriptors.find(h) != searchDescriptors.end())
736 searchDescriptors.erase(searchDescriptors.find(h));
740 WriteServLog("USERS. Incorrect search handle.");
743 //-----------------------------------------------------------------------------
744 void USERS_IMPL::SetUserNotifiers(user_iter user)
746 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
748 PROPERTY_NOTIFER_IP_BEFORE nb(*this, user);
749 PROPERTY_NOTIFER_IP_AFTER na(*this, user);
751 userIPNotifiersBefore.push_front(nb);
752 userIPNotifiersAfter.push_front(na);
754 user->AddCurrIPBeforeNotifier(&(*userIPNotifiersBefore.begin()));
755 user->AddCurrIPAfterNotifier(&(*userIPNotifiersAfter.begin()));
757 //-----------------------------------------------------------------------------
758 void USERS_IMPL::UnSetUserNotifiers(user_iter user)
760 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
762 list<PROPERTY_NOTIFER_IP_BEFORE>::iterator bi;
763 list<PROPERTY_NOTIFER_IP_AFTER>::iterator ai;
765 bi = userIPNotifiersBefore.begin();
766 while (bi != userIPNotifiersBefore.end())
768 if (bi->GetUser() == user)
770 bi->GetUser()->DelCurrIPBeforeNotifier(&(*bi));
771 userIPNotifiersBefore.erase(bi);
772 //printfd(__FILE__, "Notifier Before removed. User %s\n", bi->GetUser()->GetLogin().c_str());
778 ai = userIPNotifiersAfter.begin();
779 while (ai != userIPNotifiersAfter.end())
781 if (ai->GetUser() == user)
783 ai->GetUser()->DelCurrIPAfterNotifier(&(*ai));
784 userIPNotifiersAfter.erase(ai);
785 //printfd(__FILE__, "Notifier After removed. User %s\n", ai->GetUser()->GetLogin().c_str());
791 //-----------------------------------------------------------------------------
792 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
794 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
795 loginIndex.insert(make_pair(user->GetLogin(), user));
797 //-----------------------------------------------------------------------------
798 void USERS_IMPL::DelUserFromIndexes(user_iter user)
800 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
801 loginIndex.erase(user->GetLogin());
803 //-----------------------------------------------------------------------------
804 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
806 int statTime = settings->GetDetailStatWritePeriod();
815 if (t.tm_min % 30 == 0)
819 if (t.tm_min % 15 == 0)
823 if (t.tm_min % 10 == 0)