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 int USERS_IMPL::ReadUsers()
274 vector<string> usersList;
276 if (store->GetUsersList(&usersList) < 0)
278 WriteServLog(store->GetStrError().c_str());
284 for (unsigned int i = 0; i < usersList.size(); i++)
286 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
288 u.SetLogin(usersList[i]);
292 AddUserIntoIndexes(ui);
293 SetUserNotifiers(ui);
295 if (ui->ReadConf() < 0)
298 if (ui->ReadStat() < 0)
304 //-----------------------------------------------------------------------------
305 void * USERS_IMPL::Run(void * d)
307 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
308 USERS_IMPL * us = (USERS_IMPL*) d;
312 localtime_r(&tt, &t);
317 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
319 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
320 string monFile = us->settings->GetMonitorDir() + "/users_r";
321 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
323 us->isRunning = true;
326 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
327 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
329 for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER_IMPL::Run));
332 localtime_r(&tt, &t);
336 printfd(__FILE__,"Sec = %d\n", stgTime);
337 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
343 if (day != t.tm_mday)
345 printfd(__FILE__,"Sec = %d\n", stgTime);
346 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
351 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
353 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
355 TouchFile(monFile.c_str());
359 } //while (us->nonstop)
361 user_iter ui = us->users.begin();
362 while (ui != us->users.end())
364 us->UnSetUserNotifiers(ui);
365 us->DelUserFromIndexes(ui);
369 list<USER_TO_DEL>::iterator iter;
370 iter = us->usersToDelete.begin();
371 while (iter != us->usersToDelete.end())
373 iter->delTime -= 2 * userDeleteDelayTime;
378 us->isRunning = false;
382 //-----------------------------------------------------------------------------
383 void USERS_IMPL::NewMinute(const struct tm & t)
385 //Write traff, reset session traff. Fake disconnect-connect
386 if (t.tm_hour == 23 && t.tm_min == 59)
388 printfd(__FILE__,"MidnightResetSessionStat\n");
389 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
392 if (TimeToWriteDetailStat(t))
394 //printfd(__FILE__, "USER::WriteInetStat\n");
397 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
398 list<USER_IMPL>::iterator usr = users.begin();
399 while (usr != users.end())
402 usr->WriteDetailStat();
404 if (usersCnt % 10 == 0)
405 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
411 //-----------------------------------------------------------------------------
412 void USERS_IMPL::NewDay(const struct tm & t)
416 localtime_r(&tt, &t1);
417 int dayFee = settings->GetDayFee();
420 dayFee = DaysInCurrentMonth();
422 printfd(__FILE__, "DayFee = %d\n", dayFee);
423 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
424 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
426 if (!settings->GetDayFeeIsLastDay())
428 printfd(__FILE__, "DayResetTraff - 1 -\n");
430 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
433 if (settings->GetSpreadFee())
435 printfd(__FILE__, "Spread DayFee\n");
436 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
440 if (t.tm_mday == dayFee)
442 printfd(__FILE__, "DayFee\n");
443 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFee));
447 if (settings->GetDayFeeIsLastDay())
449 printfd(__FILE__, "DayResetTraff - 2 -\n");
453 //-----------------------------------------------------------------------------
454 void USERS_IMPL::DayResetTraff(const struct tm & t1)
456 int dayResetTraff = settings->GetDayResetTraff();
457 if (dayResetTraff == 0)
458 dayResetTraff = DaysInCurrentMonth();
459 if (t1.tm_mday == dayResetTraff)
461 printfd(__FILE__, "ResetTraff\n");
462 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessNewMonth));
463 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
466 //-----------------------------------------------------------------------------
467 int USERS_IMPL::Start()
471 WriteServLog("USERS: Error: Cannot read users!");
476 if (pthread_create(&thread, NULL, Run, this))
478 WriteServLog("USERS: Error: Cannot start thread!");
483 //-----------------------------------------------------------------------------
484 int USERS_IMPL::Stop()
486 printfd(__FILE__, "USERS::Stop()\n");
490 //printfd(__FILE__, "Alredy stopped\n");
496 //5 seconds to thread stops itself
497 struct timespec ts = {0, 200000000};
498 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
503 nanosleep(&ts, NULL);
506 //after 5 seconds waiting thread still running. now kill it
509 printfd(__FILE__, "kill USERS thread.\n");
510 //TODO pthread_cancel()
511 if (pthread_kill(thread, SIGINT))
513 //errorStr = "Cannot kill USERS thread.";
514 //printfd(__FILE__, "Cannot kill USERS thread.\n");
517 printfd(__FILE__, "USERS killed\n");
520 printfd(__FILE__, "Before USERS::Run()\n");
521 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
523 // 'cause bind2st accepts only constant first param
524 for (list<USER_IMPL>::iterator it = users.begin();
527 it->WriteDetailStat(true);
529 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteStat));
530 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
532 printfd(__FILE__, "USERS::Stop()\n");
535 //-----------------------------------------------------------------------------
536 void USERS_IMPL::RealDelUser()
538 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
540 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
542 list<USER_TO_DEL>::iterator iter;
543 iter = usersToDelete.begin();
544 while (iter != usersToDelete.end())
546 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
547 if (iter->delTime + userDeleteDelayTime < stgTime)
549 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
550 if (store->DelUser(iter->iter->GetLogin()))
552 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
554 users.erase(iter->iter);
555 usersToDelete.erase(iter++);
564 //-----------------------------------------------------------------------------
565 void USERS_IMPL::AddToIPIdx(user_iter user)
567 printfd(__FILE__, "USERS: Add IP Idx\n");
568 uint32_t ip = user->GetCurrIP();
569 //assert(ip && "User has non-null ip");
571 return; // User has disconnected
573 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
575 const map<uint32_t, user_iter>::iterator it(
576 ipIndex.lower_bound(ip)
579 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
581 ipIndex.insert(it, std::make_pair(ip, user));
583 //-----------------------------------------------------------------------------
584 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
586 printfd(__FILE__, "USERS: Del IP Idx\n");
587 assert(ip && "User has non-null ip");
589 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
591 const map<uint32_t, user_iter>::iterator it(
595 //assert(it != ipIndex.end() && "User is in index");
596 if (it == ipIndex.end())
597 return; // User has not been added
601 //-----------------------------------------------------------------------------
602 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
604 USER_IMPL * ptr = NULL;
605 if (FindByIPIdx(ip, &ptr))
610 //-----------------------------------------------------------------------------
611 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
613 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
615 map<uint32_t, user_iter>::const_iterator it;
616 it = ipIndex.find(ip);
618 if (it == ipIndex.end())
620 //printfd(__FILE__, "User NOT found in IP_Index!!!\n");
623 *usr = &(*it->second);
624 //printfd(__FILE__, "User found in IP_Index\n");
627 //-----------------------------------------------------------------------------
628 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
630 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
632 map<uint32_t, user_iter>::const_iterator it;
633 it = ipIndex.find(ip);
635 return it != ipIndex.end();
637 //-----------------------------------------------------------------------------
638 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
640 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
641 onAddNotifiers.insert(n);
643 //-----------------------------------------------------------------------------
644 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
646 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
647 onAddNotifiers.erase(n);
649 //-----------------------------------------------------------------------------
650 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
652 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
653 onDelNotifiers.insert(n);
655 //-----------------------------------------------------------------------------
656 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
658 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
659 onDelNotifiers.erase(n);
661 //-----------------------------------------------------------------------------
662 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
664 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
665 onAddNotifiersImpl.insert(n);
667 //-----------------------------------------------------------------------------
668 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
670 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
671 onAddNotifiersImpl.erase(n);
673 //-----------------------------------------------------------------------------
674 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
676 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
677 onDelNotifiersImpl.insert(n);
679 //-----------------------------------------------------------------------------
680 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
682 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
683 onDelNotifiersImpl.erase(n);
685 //-----------------------------------------------------------------------------
686 int USERS_IMPL::OpenSearch()
688 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
690 searchDescriptors[handle] = users.begin();
693 //-----------------------------------------------------------------------------
694 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
696 USER_IMPL * ptr = NULL;
697 if (SearchNext(h, &ptr))
702 //-----------------------------------------------------------------------------
703 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
705 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
707 if (searchDescriptors.find(h) == searchDescriptors.end())
709 WriteServLog("USERS. Incorrect search handle.");
713 if (searchDescriptors[h] == users.end())
716 while (searchDescriptors[h]->GetDeleted())
718 ++searchDescriptors[h];
719 if (searchDescriptors[h] == users.end())
725 *user = &(*searchDescriptors[h]);
727 ++searchDescriptors[h];
731 //-----------------------------------------------------------------------------
732 int USERS_IMPL::CloseSearch(int h)
734 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
735 if (searchDescriptors.find(h) != searchDescriptors.end())
737 searchDescriptors.erase(searchDescriptors.find(h));
741 WriteServLog("USERS. Incorrect search handle.");
744 //-----------------------------------------------------------------------------
745 void USERS_IMPL::SetUserNotifiers(user_iter user)
747 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
749 PROPERTY_NOTIFER_IP_BEFORE nb(*this, user);
750 PROPERTY_NOTIFER_IP_AFTER na(*this, user);
752 userIPNotifiersBefore.push_front(nb);
753 userIPNotifiersAfter.push_front(na);
755 user->AddCurrIPBeforeNotifier(&(*userIPNotifiersBefore.begin()));
756 user->AddCurrIPAfterNotifier(&(*userIPNotifiersAfter.begin()));
758 //-----------------------------------------------------------------------------
759 void USERS_IMPL::UnSetUserNotifiers(user_iter user)
761 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
763 list<PROPERTY_NOTIFER_IP_BEFORE>::iterator bi;
764 list<PROPERTY_NOTIFER_IP_AFTER>::iterator ai;
766 bi = userIPNotifiersBefore.begin();
767 while (bi != userIPNotifiersBefore.end())
769 if (bi->GetUser() == user)
771 bi->GetUser()->DelCurrIPBeforeNotifier(&(*bi));
772 userIPNotifiersBefore.erase(bi);
773 //printfd(__FILE__, "Notifier Before removed. User %s\n", bi->GetUser()->GetLogin().c_str());
779 ai = userIPNotifiersAfter.begin();
780 while (ai != userIPNotifiersAfter.end())
782 if (ai->GetUser() == user)
784 ai->GetUser()->DelCurrIPAfterNotifier(&(*ai));
785 userIPNotifiersAfter.erase(ai);
786 //printfd(__FILE__, "Notifier After removed. User %s\n", ai->GetUser()->GetLogin().c_str());
792 //-----------------------------------------------------------------------------
793 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
795 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
796 loginIndex.insert(make_pair(user->GetLogin(), user));
798 //-----------------------------------------------------------------------------
799 void USERS_IMPL::DelUserFromIndexes(user_iter user)
801 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
802 loginIndex.erase(user->GetLogin());
804 //-----------------------------------------------------------------------------
805 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
807 int statTime = settings->GetDetailStatWritePeriod();
816 if (t.tm_min % 30 == 0)
820 if (t.tm_min % 15 == 0)
824 if (t.tm_min % 10 == 0)