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)
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 string & login, user_iter * user)
91 map<string, user_iter>::iterator iter;
92 iter = loginIndex.find(login);
93 if (iter != loginIndex.end())
101 //-----------------------------------------------------------------------------
102 int USERS_IMPL::FindByName(const string & login, USER_PTR * user)
104 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
106 int res = FindByNameNonLock(login, &u);
112 //-----------------------------------------------------------------------------
113 bool USERS_IMPL::TariffInUse(const string & tariffName) const
115 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
116 list<USER_IMPL>::const_iterator iter;
117 iter = users.begin();
118 while (iter != users.end())
120 if (iter->GetProperty().tariffName.Get() == tariffName)
126 //-----------------------------------------------------------------------------
127 int USERS_IMPL::Add(const string & login, const ADMIN * admin)
129 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
130 const PRIV * priv = admin->GetPriv();
132 if (!priv->userAddDel)
134 WriteServLog("%s tried to add user \'%s\'. Access denied.",
135 admin->GetLogStr().c_str(), login.c_str());
136 /*errorStr = "Admin \'" + admin->GetLogin() +
137 "\': tried to add user \'" + ud->login + "\'. Access denied.";*/
142 if (store->AddUser(login))
145 //WriteServLog("Admin \'%s\': tried to add user \'%s\'. Access denied.",
146 // admin->GetLogin().c_str(), ud->login.c_str());
151 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
162 if (settings->GetDayResetTraff() > tms->tm_mday)
165 tms->tm_mday = settings->GetDayResetTraff();*/
169 u.SetPassiveTimeAsNewUser();
174 WriteServLog("%s User \'%s\' added.",
175 admin->GetLogStr().c_str(), login.c_str());
181 AddUserIntoIndexes(users.begin());
182 SetUserNotifiers(users.begin());
185 // Fire all "on add" notifiers
186 set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
187 while (ni != onAddNotifiers.end())
189 (*ni)->Notify(&users.front());
195 // Fire all "on add" implementation notifiers
196 set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
197 while (ni != onAddNotifiersImpl.end())
199 (*ni)->Notify(&users.front());
206 //-----------------------------------------------------------------------------
207 void USERS_IMPL::Del(const string & login, const ADMIN * admin)
209 const PRIV * priv = admin->GetPriv();
212 if (!priv->userAddDel)
214 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
215 admin->GetLogStr().c_str(), login.c_str());
221 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
223 if (FindByNameNonLock(login, &u))
225 WriteServLog("%s tried to delete user \'%s\': not found.",
226 admin->GetLogStr().c_str(),
233 set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
234 while (ni != onDelNotifiers.end())
236 (*ni)->Notify(&(*u));
242 set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
243 while (ni != onDelNotifiersImpl.end())
245 (*ni)->Notify(&(*u));
251 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
258 utd.delTime = stgTime;
259 usersToDelete.push_back(utd);
261 UnSetUserNotifiers(u);
262 DelUserFromIndexes(u);
264 WriteServLog("%s User \'%s\' deleted.",
265 admin->GetLogStr().c_str(), login.c_str());
269 //-----------------------------------------------------------------------------
270 int USERS_IMPL::ReadUsers()
272 vector<string> usersList;
274 if (store->GetUsersList(&usersList) < 0)
276 WriteServLog(store->GetStrError().c_str());
282 for (unsigned int i = 0; i < usersList.size(); i++)
284 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
286 u.SetLogin(usersList[i]);
290 AddUserIntoIndexes(ui);
291 SetUserNotifiers(ui);
293 if (ui->ReadConf() < 0)
296 if (ui->ReadStat() < 0)
302 //-----------------------------------------------------------------------------
303 void * USERS_IMPL::Run(void * d)
305 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
306 USERS_IMPL * us = (USERS_IMPL*) d;
310 localtime_r(&tt, &t);
315 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
317 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
318 string monFile = us->settings->GetMonitorDir() + "/users_r";
319 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
321 us->isRunning = true;
324 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
325 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
327 for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER_IMPL::Run));
330 localtime_r(&tt, &t);
334 printfd(__FILE__,"Sec = %d\n", stgTime);
335 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
341 if (day != t.tm_mday)
343 printfd(__FILE__,"Sec = %d\n", stgTime);
344 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
349 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
351 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
353 TouchFile(monFile.c_str());
357 } //while (us->nonstop)
359 user_iter ui = us->users.begin();
360 while (ui != us->users.end())
362 us->UnSetUserNotifiers(ui);
363 us->DelUserFromIndexes(ui);
367 list<USER_TO_DEL>::iterator iter;
368 iter = us->usersToDelete.begin();
369 while (iter != us->usersToDelete.end())
371 iter->delTime -= 2 * userDeleteDelayTime;
376 us->isRunning = false;
380 //-----------------------------------------------------------------------------
381 void USERS_IMPL::NewMinute(const struct tm & t)
383 //Write traff, reset session traff. Fake disconnect-connect
384 if (t.tm_hour == 23 && t.tm_min == 59)
386 printfd(__FILE__,"MidnightResetSessionStat\n");
387 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
390 if (TimeToWriteDetailStat(t))
392 //printfd(__FILE__, "USER::WriteInetStat\n");
395 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
396 list<USER_IMPL>::iterator usr = users.begin();
397 while (usr != users.end())
400 usr->WriteDetailStat();
402 if (usersCnt % 10 == 0)
403 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
409 //-----------------------------------------------------------------------------
410 void USERS_IMPL::NewDay(const struct tm & t)
414 localtime_r(&tt, &t1);
415 int dayFee = settings->GetDayFee();
418 dayFee = DaysInCurrentMonth();
420 printfd(__FILE__, "DayFee = %d\n", dayFee);
421 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
422 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
424 if (!settings->GetDayFeeIsLastDay())
426 printfd(__FILE__, "DayResetTraff - 1 -\n");
428 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
431 if (settings->GetSpreadFee())
433 printfd(__FILE__, "Spread DayFee\n");
434 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
438 if (t.tm_mday == dayFee)
440 printfd(__FILE__, "DayFee\n");
441 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFee));
445 if (settings->GetDayFeeIsLastDay())
447 printfd(__FILE__, "DayResetTraff - 2 -\n");
451 //-----------------------------------------------------------------------------
452 void USERS_IMPL::DayResetTraff(const struct tm & t1)
454 int dayResetTraff = settings->GetDayResetTraff();
455 if (dayResetTraff == 0)
456 dayResetTraff = DaysInCurrentMonth();
457 if (t1.tm_mday == dayResetTraff)
459 printfd(__FILE__, "ResetTraff\n");
460 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessNewMonth));
461 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
464 //-----------------------------------------------------------------------------
465 int USERS_IMPL::Start()
469 WriteServLog("USERS: Error: Cannot read users!");
474 if (pthread_create(&thread, NULL, Run, this))
476 WriteServLog("USERS: Error: Cannot start thread!");
481 //-----------------------------------------------------------------------------
482 int USERS_IMPL::Stop()
484 printfd(__FILE__, "USERS::Stop()\n");
488 //printfd(__FILE__, "Alredy stopped\n");
494 //5 seconds to thread stops itself
495 struct timespec ts = {0, 200000000};
496 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
501 nanosleep(&ts, NULL);
504 //after 5 seconds waiting thread still running. now kill it
507 printfd(__FILE__, "kill USERS thread.\n");
508 //TODO pthread_cancel()
509 if (pthread_kill(thread, SIGINT))
511 //errorStr = "Cannot kill USERS thread.";
512 //printfd(__FILE__, "Cannot kill USERS thread.\n");
515 printfd(__FILE__, "USERS killed\n");
518 printfd(__FILE__, "Before USERS::Run()\n");
519 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
521 // 'cause bind2st accepts only constant first param
522 for (list<USER_IMPL>::iterator it = users.begin();
525 it->WriteDetailStat(true);
527 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteStat));
528 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
530 printfd(__FILE__, "USERS::Stop()\n");
533 //-----------------------------------------------------------------------------
534 void USERS_IMPL::RealDelUser()
536 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
538 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
540 list<USER_TO_DEL>::iterator iter;
541 iter = usersToDelete.begin();
542 while (iter != usersToDelete.end())
544 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
545 if (iter->delTime + userDeleteDelayTime < stgTime)
547 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
548 if (store->DelUser(iter->iter->GetLogin()))
550 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
552 users.erase(iter->iter);
553 usersToDelete.erase(iter++);
562 //-----------------------------------------------------------------------------
563 int USERS_IMPL::GetUserNum() const
567 //-----------------------------------------------------------------------------
568 void USERS_IMPL::AddToIPIdx(user_iter user)
570 printfd(__FILE__, "USERS: Add IP Idx\n");
571 uint32_t ip = user->GetCurrIP();
572 //assert(ip && "User has non-null ip");
574 return; // User has disconnected
576 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
578 const map<uint32_t, user_iter>::iterator it(
579 ipIndex.lower_bound(ip)
582 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
584 ipIndex.insert(it, std::make_pair(ip, user));
586 //-----------------------------------------------------------------------------
587 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
589 printfd(__FILE__, "USERS: Del IP Idx\n");
590 assert(ip && "User has non-null ip");
592 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
594 const map<uint32_t, user_iter>::iterator it(
598 //assert(it != ipIndex.end() && "User is in index");
599 if (it == ipIndex.end())
600 return; // User has not been added
604 //-----------------------------------------------------------------------------
605 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
607 USER_IMPL * ptr = NULL;
608 if (FindByIPIdx(ip, &ptr))
613 //-----------------------------------------------------------------------------
614 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
616 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
618 map<uint32_t, user_iter>::const_iterator it;
619 it = ipIndex.find(ip);
621 if (it == ipIndex.end())
623 //printfd(__FILE__, "User NOT found in IP_Index!!!\n");
626 *usr = &(*it->second);
627 //printfd(__FILE__, "User found in IP_Index\n");
630 //-----------------------------------------------------------------------------
631 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
633 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
635 map<uint32_t, user_iter>::const_iterator it;
636 it = ipIndex.find(ip);
638 return it != ipIndex.end();
640 //-----------------------------------------------------------------------------
641 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
643 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
644 onAddNotifiers.insert(n);
646 //-----------------------------------------------------------------------------
647 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
649 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
650 onAddNotifiers.erase(n);
652 //-----------------------------------------------------------------------------
653 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
655 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
656 onDelNotifiers.insert(n);
658 //-----------------------------------------------------------------------------
659 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
661 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
662 onDelNotifiers.erase(n);
664 //-----------------------------------------------------------------------------
665 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
667 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
668 onAddNotifiersImpl.insert(n);
670 //-----------------------------------------------------------------------------
671 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
673 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
674 onAddNotifiersImpl.erase(n);
676 //-----------------------------------------------------------------------------
677 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
679 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
680 onDelNotifiersImpl.insert(n);
682 //-----------------------------------------------------------------------------
683 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
685 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
686 onDelNotifiersImpl.erase(n);
688 //-----------------------------------------------------------------------------
689 int USERS_IMPL::OpenSearch()
691 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
693 searchDescriptors[handle] = users.begin();
696 //-----------------------------------------------------------------------------
697 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
699 USER_IMPL * ptr = NULL;
700 if (SearchNext(h, &ptr))
705 //-----------------------------------------------------------------------------
706 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
708 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
710 if (searchDescriptors.find(h) == searchDescriptors.end())
712 WriteServLog("USERS. Incorrect search handle.");
716 if (searchDescriptors[h] == users.end())
719 while (searchDescriptors[h]->GetDeleted())
721 ++searchDescriptors[h];
722 if (searchDescriptors[h] == users.end())
728 *user = &(*searchDescriptors[h]);
730 ++searchDescriptors[h];
734 //-----------------------------------------------------------------------------
735 int USERS_IMPL::CloseSearch(int h)
737 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
738 if (searchDescriptors.find(h) != searchDescriptors.end())
740 searchDescriptors.erase(searchDescriptors.find(h));
744 WriteServLog("USERS. Incorrect search handle.");
747 //-----------------------------------------------------------------------------
748 void USERS_IMPL::SetUserNotifiers(user_iter user)
750 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
752 PROPERTY_NOTIFER_IP_BEFORE nb(*this, user);
753 PROPERTY_NOTIFER_IP_AFTER na(*this, user);
755 userIPNotifiersBefore.push_front(nb);
756 userIPNotifiersAfter.push_front(na);
758 user->AddCurrIPBeforeNotifier(&(*userIPNotifiersBefore.begin()));
759 user->AddCurrIPAfterNotifier(&(*userIPNotifiersAfter.begin()));
761 //-----------------------------------------------------------------------------
762 void USERS_IMPL::UnSetUserNotifiers(user_iter user)
764 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
766 list<PROPERTY_NOTIFER_IP_BEFORE>::iterator bi;
767 list<PROPERTY_NOTIFER_IP_AFTER>::iterator ai;
769 bi = userIPNotifiersBefore.begin();
770 while (bi != userIPNotifiersBefore.end())
772 if (bi->GetUser() == user)
774 bi->GetUser()->DelCurrIPBeforeNotifier(&(*bi));
775 userIPNotifiersBefore.erase(bi);
776 //printfd(__FILE__, "Notifier Before removed. User %s\n", bi->GetUser()->GetLogin().c_str());
782 ai = userIPNotifiersAfter.begin();
783 while (ai != userIPNotifiersAfter.end())
785 if (ai->GetUser() == user)
787 ai->GetUser()->DelCurrIPAfterNotifier(&(*ai));
788 userIPNotifiersAfter.erase(ai);
789 //printfd(__FILE__, "Notifier After removed. User %s\n", ai->GetUser()->GetLogin().c_str());
795 //-----------------------------------------------------------------------------
796 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
798 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
799 loginIndex.insert(make_pair(user->GetLogin(), user));
801 //-----------------------------------------------------------------------------
802 void USERS_IMPL::DelUserFromIndexes(user_iter user)
804 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
805 loginIndex.erase(user->GetLogin());
807 //-----------------------------------------------------------------------------
808 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
810 int statTime = settings->GetDetailStatWritePeriod();
819 if (t.tm_min % 30 == 0)
823 if (t.tm_min % 15 == 0)
827 if (t.tm_min % 10 == 0)