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 int USERS_IMPL::GetUserNum() const
568 //-----------------------------------------------------------------------------
569 void USERS_IMPL::AddToIPIdx(user_iter user)
571 printfd(__FILE__, "USERS: Add IP Idx\n");
572 uint32_t ip = user->GetCurrIP();
573 //assert(ip && "User has non-null ip");
575 return; // User has disconnected
577 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
579 const map<uint32_t, user_iter>::iterator it(
580 ipIndex.lower_bound(ip)
583 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
585 ipIndex.insert(it, std::make_pair(ip, user));
587 //-----------------------------------------------------------------------------
588 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
590 printfd(__FILE__, "USERS: Del IP Idx\n");
591 assert(ip && "User has non-null ip");
593 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
595 const map<uint32_t, user_iter>::iterator it(
599 //assert(it != ipIndex.end() && "User is in index");
600 if (it == ipIndex.end())
601 return; // User has not been added
605 //-----------------------------------------------------------------------------
606 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
608 USER_IMPL * ptr = NULL;
609 if (FindByIPIdx(ip, &ptr))
614 //-----------------------------------------------------------------------------
615 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
617 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
619 map<uint32_t, user_iter>::const_iterator it;
620 it = ipIndex.find(ip);
622 if (it == ipIndex.end())
624 //printfd(__FILE__, "User NOT found in IP_Index!!!\n");
627 *usr = &(*it->second);
628 //printfd(__FILE__, "User found in IP_Index\n");
631 //-----------------------------------------------------------------------------
632 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
634 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
636 map<uint32_t, user_iter>::const_iterator it;
637 it = ipIndex.find(ip);
639 return it != ipIndex.end();
641 //-----------------------------------------------------------------------------
642 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
644 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
645 onAddNotifiers.insert(n);
647 //-----------------------------------------------------------------------------
648 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
650 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
651 onAddNotifiers.erase(n);
653 //-----------------------------------------------------------------------------
654 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
656 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
657 onDelNotifiers.insert(n);
659 //-----------------------------------------------------------------------------
660 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
662 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
663 onDelNotifiers.erase(n);
665 //-----------------------------------------------------------------------------
666 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
668 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
669 onAddNotifiersImpl.insert(n);
671 //-----------------------------------------------------------------------------
672 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
674 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
675 onAddNotifiersImpl.erase(n);
677 //-----------------------------------------------------------------------------
678 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
680 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
681 onDelNotifiersImpl.insert(n);
683 //-----------------------------------------------------------------------------
684 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
686 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
687 onDelNotifiersImpl.erase(n);
689 //-----------------------------------------------------------------------------
690 int USERS_IMPL::OpenSearch()
692 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
694 searchDescriptors[handle] = users.begin();
697 //-----------------------------------------------------------------------------
698 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
700 USER_IMPL * ptr = NULL;
701 if (SearchNext(h, &ptr))
706 //-----------------------------------------------------------------------------
707 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
709 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
711 if (searchDescriptors.find(h) == searchDescriptors.end())
713 WriteServLog("USERS. Incorrect search handle.");
717 if (searchDescriptors[h] == users.end())
720 while (searchDescriptors[h]->GetDeleted())
722 ++searchDescriptors[h];
723 if (searchDescriptors[h] == users.end())
729 *user = &(*searchDescriptors[h]);
731 ++searchDescriptors[h];
735 //-----------------------------------------------------------------------------
736 int USERS_IMPL::CloseSearch(int h)
738 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
739 if (searchDescriptors.find(h) != searchDescriptors.end())
741 searchDescriptors.erase(searchDescriptors.find(h));
745 WriteServLog("USERS. Incorrect search handle.");
748 //-----------------------------------------------------------------------------
749 void USERS_IMPL::SetUserNotifiers(user_iter user)
751 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
753 PROPERTY_NOTIFER_IP_BEFORE nb(*this, user);
754 PROPERTY_NOTIFER_IP_AFTER na(*this, user);
756 userIPNotifiersBefore.push_front(nb);
757 userIPNotifiersAfter.push_front(na);
759 user->AddCurrIPBeforeNotifier(&(*userIPNotifiersBefore.begin()));
760 user->AddCurrIPAfterNotifier(&(*userIPNotifiersAfter.begin()));
762 //-----------------------------------------------------------------------------
763 void USERS_IMPL::UnSetUserNotifiers(user_iter user)
765 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
767 list<PROPERTY_NOTIFER_IP_BEFORE>::iterator bi;
768 list<PROPERTY_NOTIFER_IP_AFTER>::iterator ai;
770 bi = userIPNotifiersBefore.begin();
771 while (bi != userIPNotifiersBefore.end())
773 if (bi->GetUser() == user)
775 bi->GetUser()->DelCurrIPBeforeNotifier(&(*bi));
776 userIPNotifiersBefore.erase(bi);
777 //printfd(__FILE__, "Notifier Before removed. User %s\n", bi->GetUser()->GetLogin().c_str());
783 ai = userIPNotifiersAfter.begin();
784 while (ai != userIPNotifiersAfter.end())
786 if (ai->GetUser() == user)
788 ai->GetUser()->DelCurrIPAfterNotifier(&(*ai));
789 userIPNotifiersAfter.erase(ai);
790 //printfd(__FILE__, "Notifier After removed. User %s\n", ai->GetUser()->GetLogin().c_str());
796 //-----------------------------------------------------------------------------
797 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
799 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
800 loginIndex.insert(make_pair(user->GetLogin(), user));
802 //-----------------------------------------------------------------------------
803 void USERS_IMPL::DelUserFromIndexes(user_iter user)
805 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
806 loginIndex.erase(user->GetLogin());
808 //-----------------------------------------------------------------------------
809 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
811 int statTime = settings->GetDetailStatWritePeriod();
820 if (t.tm_min % 30 == 0)
824 if (t.tm_min % 15 == 0)
828 if (t.tm_min % 10 == 0)