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 $
44 #include "stg/settings.h"
45 #include "stg/common.h"
46 #include "users_impl.h"
47 #include "stg_timer.h"
49 extern volatile time_t stgTime;
51 //#define USERS_DEBUG 1
53 //-----------------------------------------------------------------------------
54 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 std::string & login, user_iter * user)
91 std::map<std::string, user_iter>::iterator iter;
92 iter = loginIndex.find(login);
93 if (iter != loginIndex.end())
101 //-----------------------------------------------------------------------------
102 int USERS_IMPL::FindByName(const std::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 std::string & tariffName) const
115 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
116 std::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 std::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());
184 // Fire all "on add" notifiers
185 std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
186 while (ni != onAddNotifiers.end())
188 (*ni)->Notify(&users.front());
194 // Fire all "on add" implementation notifiers
195 std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
196 while (ni != onAddNotifiersImpl.end())
198 (*ni)->Notify(&users.front());
205 //-----------------------------------------------------------------------------
206 void USERS_IMPL::Del(const std::string & login, const ADMIN * admin)
208 const PRIV * priv = admin->GetPriv();
211 if (!priv->userAddDel)
213 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
214 admin->GetLogStr().c_str(), login.c_str());
220 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
222 if (FindByNameNonLock(login, &u))
224 WriteServLog("%s tried to delete user \'%s\': not found.",
225 admin->GetLogStr().c_str(),
234 std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
235 while (ni != onDelNotifiers.end())
237 (*ni)->Notify(&(*u));
243 std::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__);
258 utd.delTime = stgTime;
259 usersToDelete.push_back(utd);
261 DelUserFromIndexes(u);
263 WriteServLog("%s User \'%s\' deleted.",
264 admin->GetLogStr().c_str(), login.c_str());
268 //-----------------------------------------------------------------------------
269 bool USERS_IMPL::Authorize(const std::string & login, uint32_t ip,
270 uint32_t enabledDirs, const AUTH * auth)
273 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
274 if (FindByNameNonLock(login, &iter))
276 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
280 if (FindByIPIdx(ip, iter))
282 if (iter->GetLogin() != login)
284 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
285 login.c_str(), inet_ntostring(ip).c_str(),
286 iter->GetLogin().c_str());
289 if (iter->Authorize(ip, enabledDirs, auth))
294 if (iter->Authorize(ip, enabledDirs, auth))
300 //-----------------------------------------------------------------------------
301 bool USERS_IMPL::Unauthorize(const std::string & login, const AUTH * auth)
304 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
305 if (FindByNameNonLock(login, &iter))
307 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
311 uint32_t ip = iter->GetCurrIP();
313 iter->Unauthorize(auth);
315 if (!iter->GetAuthorized())
320 //-----------------------------------------------------------------------------
321 int USERS_IMPL::ReadUsers()
323 std::vector<std::string> usersList;
325 if (store->GetUsersList(&usersList) < 0)
327 WriteServLog(store->GetStrError().c_str());
333 for (unsigned int i = 0; i < usersList.size(); i++)
335 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
337 u.SetLogin(usersList[i]);
341 AddUserIntoIndexes(ui);
343 if (ui->ReadConf() < 0)
346 if (ui->ReadStat() < 0)
352 //-----------------------------------------------------------------------------
353 void * USERS_IMPL::Run(void * d)
356 sigfillset(&signalSet);
357 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
359 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
360 USERS_IMPL * us = static_cast<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 std::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(), std::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->DelUserFromIndexes(ui);
420 std::list<USER_TO_DEL>::iterator iter;
421 iter = us->usersToDelete.begin();
422 while (iter != us->usersToDelete.end())
424 iter->delTime -= 2 * userDeleteDelayTime;
429 us->isRunning = false;
433 //-----------------------------------------------------------------------------
434 void USERS_IMPL::NewMinute(const struct tm & t)
436 //Write traff, reset session traff. Fake disconnect-connect
437 if (t.tm_hour == 23 && t.tm_min == 59)
439 printfd(__FILE__,"MidnightResetSessionStat\n");
440 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
443 if (TimeToWriteDetailStat(t))
445 //printfd(__FILE__, "USER::WriteInetStat\n");
448 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
449 std::list<USER_IMPL>::iterator usr = users.begin();
450 while (usr != users.end())
453 usr->WriteDetailStat();
455 if (usersCnt % 10 == 0)
456 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
462 //-----------------------------------------------------------------------------
463 void USERS_IMPL::NewDay(const struct tm & t)
467 localtime_r(&tt, &t1);
468 int dayFee = settings->GetDayFee();
471 dayFee = DaysInCurrentMonth();
473 printfd(__FILE__, "DayFee = %d\n", dayFee);
474 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
475 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
477 if (!settings->GetDayFeeIsLastDay())
479 printfd(__FILE__, "DayResetTraff - 1 -\n");
481 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
484 if (settings->GetSpreadFee())
486 printfd(__FILE__, "Spread DayFee\n");
487 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
491 if (t.tm_mday == dayFee)
493 printfd(__FILE__, "DayFee\n");
494 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFee));
498 if (settings->GetDayFeeIsLastDay())
500 printfd(__FILE__, "DayResetTraff - 2 -\n");
504 //-----------------------------------------------------------------------------
505 void USERS_IMPL::DayResetTraff(const struct tm & t1)
507 int dayResetTraff = settings->GetDayResetTraff();
508 if (dayResetTraff == 0)
509 dayResetTraff = DaysInCurrentMonth();
510 if (t1.tm_mday == dayResetTraff)
512 printfd(__FILE__, "ResetTraff\n");
513 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessNewMonth));
514 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
517 //-----------------------------------------------------------------------------
518 int USERS_IMPL::Start()
522 WriteServLog("USERS: Error: Cannot read users!");
527 if (pthread_create(&thread, NULL, Run, this))
529 WriteServLog("USERS: Error: Cannot start thread!");
534 //-----------------------------------------------------------------------------
535 int USERS_IMPL::Stop()
537 printfd(__FILE__, "USERS::Stop()\n");
541 //printfd(__FILE__, "Alredy stopped\n");
547 //5 seconds to thread stops itself
548 struct timespec ts = {0, 200000000};
549 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
554 nanosleep(&ts, NULL);
557 //after 5 seconds waiting thread still running. now kill it
560 printfd(__FILE__, "kill USERS thread.\n");
561 //TODO pthread_cancel()
562 if (pthread_kill(thread, SIGINT))
564 //errorStr = "Cannot kill USERS thread.";
565 //printfd(__FILE__, "Cannot kill USERS thread.\n");
568 printfd(__FILE__, "USERS killed\n");
571 printfd(__FILE__, "Before USERS::Run()\n");
572 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
574 // 'cause bind2st accepts only constant first param
575 for (std::list<USER_IMPL>::iterator it = users.begin();
578 it->WriteDetailStat(true);
580 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::WriteStat));
581 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
583 printfd(__FILE__, "USERS::Stop()\n");
586 //-----------------------------------------------------------------------------
587 void USERS_IMPL::RealDelUser()
589 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
591 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
593 std::list<USER_TO_DEL>::iterator iter;
594 iter = usersToDelete.begin();
595 while (iter != usersToDelete.end())
597 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
598 if (iter->delTime + userDeleteDelayTime < stgTime)
600 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
601 if (store->DelUser(iter->iter->GetLogin()))
603 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
605 users.erase(iter->iter);
606 usersToDelete.erase(iter++);
615 //-----------------------------------------------------------------------------
616 void USERS_IMPL::AddToIPIdx(user_iter user)
618 printfd(__FILE__, "USERS: Add IP Idx\n");
619 uint32_t ip = user->GetCurrIP();
620 //assert(ip && "User has non-null ip");
622 return; // User has disconnected
624 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
626 const std::map<uint32_t, user_iter>::iterator it(
627 ipIndex.lower_bound(ip)
630 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
632 ipIndex.insert(it, std::make_pair(ip, user));
634 //-----------------------------------------------------------------------------
635 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
637 printfd(__FILE__, "USERS: Del IP Idx\n");
638 assert(ip && "User has non-null ip");
640 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
642 const std::map<uint32_t, user_iter>::iterator it(
646 if (it == ipIndex.end())
651 //-----------------------------------------------------------------------------
652 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
654 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
655 if (it == ipIndex.end())
660 //-----------------------------------------------------------------------------
661 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
663 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
666 if (FindByIPIdx(ip, iter))
674 //-----------------------------------------------------------------------------
675 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
677 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
680 if (FindByIPIdx(ip, iter))
688 //-----------------------------------------------------------------------------
689 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
691 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
693 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
695 return it != ipIndex.end();
697 //-----------------------------------------------------------------------------
698 bool USERS_IMPL::IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const
700 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
701 std::list<USER_IMPL>::const_iterator iter;
702 iter = users.begin();
703 while (iter != users.end())
705 if (iter->GetLogin() != login && iter->GetProperty().ips.Get().IsIPInIPS(ip))
715 //-----------------------------------------------------------------------------
716 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
718 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
719 onAddNotifiers.insert(n);
721 //-----------------------------------------------------------------------------
722 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
724 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
725 onAddNotifiers.erase(n);
727 //-----------------------------------------------------------------------------
728 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
730 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
731 onDelNotifiers.insert(n);
733 //-----------------------------------------------------------------------------
734 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
736 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
737 onDelNotifiers.erase(n);
739 //-----------------------------------------------------------------------------
740 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
742 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
743 onAddNotifiersImpl.insert(n);
745 //-----------------------------------------------------------------------------
746 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
748 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
749 onAddNotifiersImpl.erase(n);
751 //-----------------------------------------------------------------------------
752 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
754 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
755 onDelNotifiersImpl.insert(n);
757 //-----------------------------------------------------------------------------
758 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
760 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
761 onDelNotifiersImpl.erase(n);
763 //-----------------------------------------------------------------------------
764 int USERS_IMPL::OpenSearch()
766 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
768 searchDescriptors[handle] = users.begin();
771 //-----------------------------------------------------------------------------
772 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
774 USER_IMPL * ptr = NULL;
775 if (SearchNext(h, &ptr))
780 //-----------------------------------------------------------------------------
781 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
783 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
785 if (searchDescriptors.find(h) == searchDescriptors.end())
787 WriteServLog("USERS. Incorrect search handle.");
791 if (searchDescriptors[h] == users.end())
794 while (searchDescriptors[h]->GetDeleted())
796 ++searchDescriptors[h];
797 if (searchDescriptors[h] == users.end())
803 *user = &(*searchDescriptors[h]);
805 ++searchDescriptors[h];
809 //-----------------------------------------------------------------------------
810 int USERS_IMPL::CloseSearch(int h)
812 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
813 if (searchDescriptors.find(h) != searchDescriptors.end())
815 searchDescriptors.erase(searchDescriptors.find(h));
819 WriteServLog("USERS. Incorrect search handle.");
822 //-----------------------------------------------------------------------------
823 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
825 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
826 loginIndex.insert(make_pair(user->GetLogin(), user));
828 //-----------------------------------------------------------------------------
829 void USERS_IMPL::DelUserFromIndexes(user_iter user)
831 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
832 loginIndex.erase(user->GetLogin());
834 //-----------------------------------------------------------------------------
835 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
837 int statTime = settings->GetDetailStatWritePeriod();
846 if (t.tm_min % 30 == 0)
850 if (t.tm_min % 15 == 0)
854 if (t.tm_min % 10 == 0)