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());
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(),
235 set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
236 while (ni != onDelNotifiers.end())
238 (*ni)->Notify(&(*u));
244 set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
245 while (ni != onDelNotifiersImpl.end())
247 (*ni)->Notify(&(*u));
253 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
259 utd.delTime = stgTime;
260 usersToDelete.push_back(utd);
262 DelUserFromIndexes(u);
264 WriteServLog("%s User \'%s\' deleted.",
265 admin->GetLogStr().c_str(), login.c_str());
269 //-----------------------------------------------------------------------------
270 bool USERS_IMPL::Authorize(const std::string & login, uint32_t ip,
271 uint32_t enabledDirs, const AUTH * auth)
274 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
275 if (FindByNameNonLock(login, &iter))
277 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
281 if (FindByIPIdx(ip, iter))
283 if (iter->GetLogin() != login)
285 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
286 login.c_str(), inet_ntostring(ip).c_str(),
287 iter->GetLogin().c_str());
290 if (iter->Authorize(ip, enabledDirs, auth))
295 if (iter->Authorize(ip, enabledDirs, auth))
301 //-----------------------------------------------------------------------------
302 bool USERS_IMPL::Unauthorize(const std::string & login, const AUTH * auth)
305 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
306 if (FindByNameNonLock(login, &iter))
308 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
312 uint32_t ip = iter->GetCurrIP();
314 iter->Unauthorize(auth);
316 if (!iter->GetAuthorized())
321 //-----------------------------------------------------------------------------
322 int USERS_IMPL::ReadUsers()
324 vector<string> usersList;
326 if (store->GetUsersList(&usersList) < 0)
328 WriteServLog(store->GetStrError().c_str());
334 for (unsigned int i = 0; i < usersList.size(); i++)
336 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
338 u.SetLogin(usersList[i]);
342 AddUserIntoIndexes(ui);
344 if (ui->ReadConf() < 0)
347 if (ui->ReadStat() < 0)
353 //-----------------------------------------------------------------------------
354 void * USERS_IMPL::Run(void * d)
356 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
357 USERS_IMPL * us = (USERS_IMPL*) d;
361 localtime_r(&tt, &t);
366 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
368 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
369 string monFile = us->settings->GetMonitorDir() + "/users_r";
370 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
372 us->isRunning = true;
375 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
376 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
378 for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER_IMPL::Run));
381 localtime_r(&tt, &t);
385 printfd(__FILE__,"Sec = %d\n", stgTime);
386 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
392 if (day != t.tm_mday)
394 printfd(__FILE__,"Sec = %d\n", stgTime);
395 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
400 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
402 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
404 TouchFile(monFile.c_str());
408 } //while (us->nonstop)
410 user_iter ui = us->users.begin();
411 while (ui != us->users.end())
413 us->DelUserFromIndexes(ui);
417 list<USER_TO_DEL>::iterator iter;
418 iter = us->usersToDelete.begin();
419 while (iter != us->usersToDelete.end())
421 iter->delTime -= 2 * userDeleteDelayTime;
426 us->isRunning = false;
430 //-----------------------------------------------------------------------------
431 void USERS_IMPL::NewMinute(const struct tm & t)
433 //Write traff, reset session traff. Fake disconnect-connect
434 if (t.tm_hour == 23 && t.tm_min == 59)
436 printfd(__FILE__,"MidnightResetSessionStat\n");
437 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
440 if (TimeToWriteDetailStat(t))
442 //printfd(__FILE__, "USER::WriteInetStat\n");
445 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
446 list<USER_IMPL>::iterator usr = users.begin();
447 while (usr != users.end())
450 usr->WriteDetailStat();
452 if (usersCnt % 10 == 0)
453 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
459 //-----------------------------------------------------------------------------
460 void USERS_IMPL::NewDay(const struct tm & t)
464 localtime_r(&tt, &t1);
465 int dayFee = settings->GetDayFee();
468 dayFee = DaysInCurrentMonth();
470 printfd(__FILE__, "DayFee = %d\n", dayFee);
471 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
472 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
474 if (!settings->GetDayFeeIsLastDay())
476 printfd(__FILE__, "DayResetTraff - 1 -\n");
478 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
481 if (settings->GetSpreadFee())
483 printfd(__FILE__, "Spread DayFee\n");
484 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
488 if (t.tm_mday == dayFee)
490 printfd(__FILE__, "DayFee\n");
491 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFee));
495 if (settings->GetDayFeeIsLastDay())
497 printfd(__FILE__, "DayResetTraff - 2 -\n");
501 //-----------------------------------------------------------------------------
502 void USERS_IMPL::DayResetTraff(const struct tm & t1)
504 int dayResetTraff = settings->GetDayResetTraff();
505 if (dayResetTraff == 0)
506 dayResetTraff = DaysInCurrentMonth();
507 if (t1.tm_mday == dayResetTraff)
509 printfd(__FILE__, "ResetTraff\n");
510 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessNewMonth));
511 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
514 //-----------------------------------------------------------------------------
515 int USERS_IMPL::Start()
519 WriteServLog("USERS: Error: Cannot read users!");
524 if (pthread_create(&thread, NULL, Run, this))
526 WriteServLog("USERS: Error: Cannot start thread!");
531 //-----------------------------------------------------------------------------
532 int USERS_IMPL::Stop()
534 printfd(__FILE__, "USERS::Stop()\n");
538 //printfd(__FILE__, "Alredy stopped\n");
544 //5 seconds to thread stops itself
545 struct timespec ts = {0, 200000000};
546 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
551 nanosleep(&ts, NULL);
554 //after 5 seconds waiting thread still running. now kill it
557 printfd(__FILE__, "kill USERS thread.\n");
558 //TODO pthread_cancel()
559 if (pthread_kill(thread, SIGINT))
561 //errorStr = "Cannot kill USERS thread.";
562 //printfd(__FILE__, "Cannot kill USERS thread.\n");
565 printfd(__FILE__, "USERS killed\n");
568 printfd(__FILE__, "Before USERS::Run()\n");
569 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
571 // 'cause bind2st accepts only constant first param
572 for (list<USER_IMPL>::iterator it = users.begin();
575 it->WriteDetailStat(true);
577 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteStat));
578 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
580 printfd(__FILE__, "USERS::Stop()\n");
583 //-----------------------------------------------------------------------------
584 void USERS_IMPL::RealDelUser()
586 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
588 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
590 list<USER_TO_DEL>::iterator iter;
591 iter = usersToDelete.begin();
592 while (iter != usersToDelete.end())
594 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
595 if (iter->delTime + userDeleteDelayTime < stgTime)
597 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
598 if (store->DelUser(iter->iter->GetLogin()))
600 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
602 users.erase(iter->iter);
603 usersToDelete.erase(iter++);
612 //-----------------------------------------------------------------------------
613 void USERS_IMPL::AddToIPIdx(user_iter user)
615 printfd(__FILE__, "USERS: Add IP Idx\n");
616 uint32_t ip = user->GetCurrIP();
617 //assert(ip && "User has non-null ip");
619 return; // User has disconnected
621 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
623 const map<uint32_t, user_iter>::iterator it(
624 ipIndex.lower_bound(ip)
627 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
629 ipIndex.insert(it, std::make_pair(ip, user));
631 //-----------------------------------------------------------------------------
632 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
634 printfd(__FILE__, "USERS: Del IP Idx\n");
635 assert(ip && "User has non-null ip");
637 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
639 const map<uint32_t, user_iter>::iterator it(
643 if (it == ipIndex.end())
648 //-----------------------------------------------------------------------------
649 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
651 map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
652 if (it == ipIndex.end())
657 //-----------------------------------------------------------------------------
658 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
660 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
663 if (FindByIPIdx(ip, iter))
671 //-----------------------------------------------------------------------------
672 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
674 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
677 if (FindByIPIdx(ip, iter))
685 //-----------------------------------------------------------------------------
686 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
688 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
690 map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
692 return it != ipIndex.end();
694 //-----------------------------------------------------------------------------
695 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
697 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
698 onAddNotifiers.insert(n);
700 //-----------------------------------------------------------------------------
701 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
703 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
704 onAddNotifiers.erase(n);
706 //-----------------------------------------------------------------------------
707 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
709 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
710 onDelNotifiers.insert(n);
712 //-----------------------------------------------------------------------------
713 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
715 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
716 onDelNotifiers.erase(n);
718 //-----------------------------------------------------------------------------
719 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
721 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
722 onAddNotifiersImpl.insert(n);
724 //-----------------------------------------------------------------------------
725 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
727 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
728 onAddNotifiersImpl.erase(n);
730 //-----------------------------------------------------------------------------
731 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
733 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
734 onDelNotifiersImpl.insert(n);
736 //-----------------------------------------------------------------------------
737 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
739 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
740 onDelNotifiersImpl.erase(n);
742 //-----------------------------------------------------------------------------
743 int USERS_IMPL::OpenSearch()
745 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
747 searchDescriptors[handle] = users.begin();
750 //-----------------------------------------------------------------------------
751 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
753 USER_IMPL * ptr = NULL;
754 if (SearchNext(h, &ptr))
759 //-----------------------------------------------------------------------------
760 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
762 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
764 if (searchDescriptors.find(h) == searchDescriptors.end())
766 WriteServLog("USERS. Incorrect search handle.");
770 if (searchDescriptors[h] == users.end())
773 while (searchDescriptors[h]->GetDeleted())
775 ++searchDescriptors[h];
776 if (searchDescriptors[h] == users.end())
782 *user = &(*searchDescriptors[h]);
784 ++searchDescriptors[h];
788 //-----------------------------------------------------------------------------
789 int USERS_IMPL::CloseSearch(int h)
791 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
792 if (searchDescriptors.find(h) != searchDescriptors.end())
794 searchDescriptors.erase(searchDescriptors.find(h));
798 WriteServLog("USERS. Incorrect search handle.");
801 //-----------------------------------------------------------------------------
802 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
804 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
805 loginIndex.insert(make_pair(user->GetLogin(), user));
807 //-----------------------------------------------------------------------------
808 void USERS_IMPL::DelUserFromIndexes(user_iter user)
810 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
811 loginIndex.erase(user->GetLogin());
813 //-----------------------------------------------------------------------------
814 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
816 int statTime = settings->GetDetailStatWritePeriod();
825 if (t.tm_min % 30 == 0)
829 if (t.tm_min % 15 == 0)
833 if (t.tm_min % 10 == 0)