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 (FindByIPIdx(ip, iter))
285 if (iter->GetLogin() != login)
287 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
288 login.c_str(), inet_ntostring(ip).c_str(),
289 iter->GetLogin().c_str());
292 if (iter->Authorize(ip, enabledDirs, auth))
297 if (iter->Authorize(ip, enabledDirs, auth))
303 //-----------------------------------------------------------------------------
304 bool USERS_IMPL::Unauthorize(const std::string & login, const AUTH * auth)
307 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
308 if (FindByNameNonLock(login, &iter))
310 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
314 uint32_t ip = iter->GetCurrIP();
316 iter->Unauthorize(auth);
318 if (!iter->GetAuthorized())
323 //-----------------------------------------------------------------------------
324 int USERS_IMPL::ReadUsers()
326 vector<string> usersList;
328 if (store->GetUsersList(&usersList) < 0)
330 WriteServLog(store->GetStrError().c_str());
336 for (unsigned int i = 0; i < usersList.size(); i++)
338 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
340 u.SetLogin(usersList[i]);
344 AddUserIntoIndexes(ui);
345 SetUserNotifiers(ui);
347 if (ui->ReadConf() < 0)
350 if (ui->ReadStat() < 0)
356 //-----------------------------------------------------------------------------
357 void * USERS_IMPL::Run(void * d)
359 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
360 USERS_IMPL * us = (USERS_IMPL*) d;
364 localtime_r(&tt, &t);
369 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
371 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
372 string monFile = us->settings->GetMonitorDir() + "/users_r";
373 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
375 us->isRunning = true;
378 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
379 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
381 for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER_IMPL::Run));
384 localtime_r(&tt, &t);
388 printfd(__FILE__,"Sec = %d\n", stgTime);
389 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
395 if (day != t.tm_mday)
397 printfd(__FILE__,"Sec = %d\n", stgTime);
398 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
403 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
405 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
407 TouchFile(monFile.c_str());
411 } //while (us->nonstop)
413 user_iter ui = us->users.begin();
414 while (ui != us->users.end())
416 us->UnSetUserNotifiers(ui);
417 us->DelUserFromIndexes(ui);
421 list<USER_TO_DEL>::iterator iter;
422 iter = us->usersToDelete.begin();
423 while (iter != us->usersToDelete.end())
425 iter->delTime -= 2 * userDeleteDelayTime;
430 us->isRunning = false;
434 //-----------------------------------------------------------------------------
435 void USERS_IMPL::NewMinute(const struct tm & t)
437 //Write traff, reset session traff. Fake disconnect-connect
438 if (t.tm_hour == 23 && t.tm_min == 59)
440 printfd(__FILE__,"MidnightResetSessionStat\n");
441 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
444 if (TimeToWriteDetailStat(t))
446 //printfd(__FILE__, "USER::WriteInetStat\n");
449 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
450 list<USER_IMPL>::iterator usr = users.begin();
451 while (usr != users.end())
454 usr->WriteDetailStat();
456 if (usersCnt % 10 == 0)
457 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
463 //-----------------------------------------------------------------------------
464 void USERS_IMPL::NewDay(const struct tm & t)
468 localtime_r(&tt, &t1);
469 int dayFee = settings->GetDayFee();
472 dayFee = DaysInCurrentMonth();
474 printfd(__FILE__, "DayFee = %d\n", dayFee);
475 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
476 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
478 if (!settings->GetDayFeeIsLastDay())
480 printfd(__FILE__, "DayResetTraff - 1 -\n");
482 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
485 if (settings->GetSpreadFee())
487 printfd(__FILE__, "Spread DayFee\n");
488 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
492 if (t.tm_mday == dayFee)
494 printfd(__FILE__, "DayFee\n");
495 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFee));
499 if (settings->GetDayFeeIsLastDay())
501 printfd(__FILE__, "DayResetTraff - 2 -\n");
505 //-----------------------------------------------------------------------------
506 void USERS_IMPL::DayResetTraff(const struct tm & t1)
508 int dayResetTraff = settings->GetDayResetTraff();
509 if (dayResetTraff == 0)
510 dayResetTraff = DaysInCurrentMonth();
511 if (t1.tm_mday == dayResetTraff)
513 printfd(__FILE__, "ResetTraff\n");
514 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessNewMonth));
515 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
518 //-----------------------------------------------------------------------------
519 int USERS_IMPL::Start()
523 WriteServLog("USERS: Error: Cannot read users!");
528 if (pthread_create(&thread, NULL, Run, this))
530 WriteServLog("USERS: Error: Cannot start thread!");
535 //-----------------------------------------------------------------------------
536 int USERS_IMPL::Stop()
538 printfd(__FILE__, "USERS::Stop()\n");
542 //printfd(__FILE__, "Alredy stopped\n");
548 //5 seconds to thread stops itself
549 struct timespec ts = {0, 200000000};
550 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
555 nanosleep(&ts, NULL);
558 //after 5 seconds waiting thread still running. now kill it
561 printfd(__FILE__, "kill USERS thread.\n");
562 //TODO pthread_cancel()
563 if (pthread_kill(thread, SIGINT))
565 //errorStr = "Cannot kill USERS thread.";
566 //printfd(__FILE__, "Cannot kill USERS thread.\n");
569 printfd(__FILE__, "USERS killed\n");
572 printfd(__FILE__, "Before USERS::Run()\n");
573 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
575 // 'cause bind2st accepts only constant first param
576 for (list<USER_IMPL>::iterator it = users.begin();
579 it->WriteDetailStat(true);
581 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteStat));
582 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
584 printfd(__FILE__, "USERS::Stop()\n");
587 //-----------------------------------------------------------------------------
588 void USERS_IMPL::RealDelUser()
590 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
592 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
594 list<USER_TO_DEL>::iterator iter;
595 iter = usersToDelete.begin();
596 while (iter != usersToDelete.end())
598 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
599 if (iter->delTime + userDeleteDelayTime < stgTime)
601 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
602 if (store->DelUser(iter->iter->GetLogin()))
604 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
606 users.erase(iter->iter);
607 usersToDelete.erase(iter++);
616 //-----------------------------------------------------------------------------
617 void USERS_IMPL::AddToIPIdx(user_iter user)
619 printfd(__FILE__, "USERS: Add IP Idx\n");
620 uint32_t ip = user->GetCurrIP();
621 //assert(ip && "User has non-null ip");
623 return; // User has disconnected
625 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
627 const map<uint32_t, user_iter>::iterator it(
628 ipIndex.lower_bound(ip)
631 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
633 ipIndex.insert(it, std::make_pair(ip, user));
635 //-----------------------------------------------------------------------------
636 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
638 printfd(__FILE__, "USERS: Del IP Idx\n");
639 assert(ip && "User has non-null ip");
641 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
643 const map<uint32_t, user_iter>::iterator it(
647 if (it == ipIndex.end())
652 //-----------------------------------------------------------------------------
653 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
655 map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
656 if (it == ipIndex.end())
661 //-----------------------------------------------------------------------------
662 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
664 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
667 if (FindByIPIdx(ip, iter))
675 //-----------------------------------------------------------------------------
676 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
678 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
681 if (FindByIPIdx(ip, iter))
689 //-----------------------------------------------------------------------------
690 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
692 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
694 map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
696 return it != ipIndex.end();
698 //-----------------------------------------------------------------------------
699 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
701 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
702 onAddNotifiers.insert(n);
704 //-----------------------------------------------------------------------------
705 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
707 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
708 onAddNotifiers.erase(n);
710 //-----------------------------------------------------------------------------
711 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
713 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
714 onDelNotifiers.insert(n);
716 //-----------------------------------------------------------------------------
717 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
719 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
720 onDelNotifiers.erase(n);
722 //-----------------------------------------------------------------------------
723 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
725 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
726 onAddNotifiersImpl.insert(n);
728 //-----------------------------------------------------------------------------
729 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
731 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
732 onAddNotifiersImpl.erase(n);
734 //-----------------------------------------------------------------------------
735 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
737 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
738 onDelNotifiersImpl.insert(n);
740 //-----------------------------------------------------------------------------
741 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
743 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
744 onDelNotifiersImpl.erase(n);
746 //-----------------------------------------------------------------------------
747 int USERS_IMPL::OpenSearch()
749 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
751 searchDescriptors[handle] = users.begin();
754 //-----------------------------------------------------------------------------
755 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
757 USER_IMPL * ptr = NULL;
758 if (SearchNext(h, &ptr))
763 //-----------------------------------------------------------------------------
764 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
766 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
768 if (searchDescriptors.find(h) == searchDescriptors.end())
770 WriteServLog("USERS. Incorrect search handle.");
774 if (searchDescriptors[h] == users.end())
777 while (searchDescriptors[h]->GetDeleted())
779 ++searchDescriptors[h];
780 if (searchDescriptors[h] == users.end())
786 *user = &(*searchDescriptors[h]);
788 ++searchDescriptors[h];
792 //-----------------------------------------------------------------------------
793 int USERS_IMPL::CloseSearch(int h)
795 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
796 if (searchDescriptors.find(h) != searchDescriptors.end())
798 searchDescriptors.erase(searchDescriptors.find(h));
802 WriteServLog("USERS. Incorrect search handle.");
805 //-----------------------------------------------------------------------------
806 void USERS_IMPL::SetUserNotifiers(user_iter user)
808 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
810 /*PROPERTY_NOTIFER_IP_BEFORE nb(*this, user);
811 PROPERTY_NOTIFER_IP_AFTER na(*this, user);
813 userIPNotifiersBefore.push_front(nb);
814 userIPNotifiersAfter.push_front(na);
816 user->AddCurrIPBeforeNotifier(&(*userIPNotifiersBefore.begin()));
817 user->AddCurrIPAfterNotifier(&(*userIPNotifiersAfter.begin()));*/
819 //-----------------------------------------------------------------------------
820 void USERS_IMPL::UnSetUserNotifiers(user_iter user)
822 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
824 /*list<PROPERTY_NOTIFER_IP_BEFORE>::iterator bi;
825 list<PROPERTY_NOTIFER_IP_AFTER>::iterator ai;
827 bi = userIPNotifiersBefore.begin();
828 while (bi != userIPNotifiersBefore.end())
830 if (bi->GetUser() == user)
832 bi->GetUser()->DelCurrIPBeforeNotifier(&(*bi));
833 userIPNotifiersBefore.erase(bi);
834 //printfd(__FILE__, "Notifier Before removed. User %s\n", bi->GetUser()->GetLogin().c_str());
840 ai = userIPNotifiersAfter.begin();
841 while (ai != userIPNotifiersAfter.end())
843 if (ai->GetUser() == user)
845 ai->GetUser()->DelCurrIPAfterNotifier(&(*ai));
846 userIPNotifiersAfter.erase(ai);
847 //printfd(__FILE__, "Notifier After removed. User %s\n", ai->GetUser()->GetLogin().c_str());
853 //-----------------------------------------------------------------------------
854 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
856 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
857 loginIndex.insert(make_pair(user->GetLogin(), user));
859 //-----------------------------------------------------------------------------
860 void USERS_IMPL::DelUserFromIndexes(user_iter user)
862 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
863 loginIndex.erase(user->GetLogin());
865 //-----------------------------------------------------------------------------
866 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
868 int statTime = settings->GetDetailStatWritePeriod();
877 if (t.tm_min % 30 == 0)
881 if (t.tm_min % 15 == 0)
885 if (t.tm_min % 10 == 0)