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 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
92 if (iter == loginIndex.end())
98 //-----------------------------------------------------------------------------
99 int USERS_IMPL::FindByNameNonLock(const std::string & login, const_user_iter * user) const
101 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
102 if (iter == loginIndex.end())
105 *user = iter->second;
108 //-----------------------------------------------------------------------------
109 int USERS_IMPL::FindByName(const std::string & login, USER_PTR * user)
111 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
113 if (FindByNameNonLock(login, &u))
118 //-----------------------------------------------------------------------------
119 int USERS_IMPL::FindByName(const std::string & login, CONST_USER_PTR * user) const
121 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
123 if (FindByNameNonLock(login, &u))
128 //-----------------------------------------------------------------------------
129 bool USERS_IMPL::TariffInUse(const std::string & tariffName) const
131 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
132 std::list<USER_IMPL>::const_iterator iter;
133 iter = users.begin();
134 while (iter != users.end())
136 if (iter->GetProperty().tariffName.Get() == tariffName)
142 //-----------------------------------------------------------------------------
143 int USERS_IMPL::Add(const std::string & login, const ADMIN * admin)
145 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
146 const PRIV * priv = admin->GetPriv();
148 if (!priv->userAddDel)
150 WriteServLog("%s tried to add user \'%s\'. Access denied.",
151 admin->GetLogStr().c_str(), login.c_str());
152 /*errorStr = "Admin \'" + admin->GetLogin() +
153 "\': tried to add user \'" + ud->login + "\'. Access denied.";*/
158 if (store->AddUser(login))
161 //WriteServLog("Admin \'%s\': tried to add user \'%s\'. Access denied.",
162 // admin->GetLogin().c_str(), ud->login.c_str());
167 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
178 if (settings->GetDayResetTraff() > tms->tm_mday)
181 tms->tm_mday = settings->GetDayResetTraff();*/
185 u.SetPassiveTimeAsNewUser();
190 WriteServLog("%s User \'%s\' added.",
191 admin->GetLogStr().c_str(), login.c_str());
197 AddUserIntoIndexes(users.begin());
200 // Fire all "on add" notifiers
201 std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
202 while (ni != onAddNotifiers.end())
204 (*ni)->Notify(&users.front());
210 // Fire all "on add" implementation notifiers
211 std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
212 while (ni != onAddNotifiersImpl.end())
214 (*ni)->Notify(&users.front());
221 //-----------------------------------------------------------------------------
222 void USERS_IMPL::Del(const std::string & login, const ADMIN * admin)
224 const PRIV * priv = admin->GetPriv();
227 if (!priv->userAddDel)
229 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
230 admin->GetLogStr().c_str(), login.c_str());
236 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
238 if (FindByNameNonLock(login, &u))
240 WriteServLog("%s tried to delete user \'%s\': not found.",
241 admin->GetLogStr().c_str(),
250 std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
251 while (ni != onDelNotifiers.end())
253 (*ni)->Notify(&(*u));
259 std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
260 while (ni != onDelNotifiersImpl.end())
262 (*ni)->Notify(&(*u));
268 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
274 utd.delTime = stgTime;
275 usersToDelete.push_back(utd);
277 DelUserFromIndexes(u);
279 WriteServLog("%s User \'%s\' deleted.",
280 admin->GetLogStr().c_str(), login.c_str());
284 //-----------------------------------------------------------------------------
285 bool USERS_IMPL::Authorize(const std::string & login, uint32_t ip,
286 uint32_t enabledDirs, const AUTH * auth)
289 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
290 if (FindByNameNonLock(login, &iter))
292 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
296 if (FindByIPIdx(ip, iter))
298 if (iter->GetLogin() != login)
300 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
301 login.c_str(), inet_ntostring(ip).c_str(),
302 iter->GetLogin().c_str());
305 if (iter->Authorize(ip, enabledDirs, auth))
310 if (iter->Authorize(ip, enabledDirs, auth))
316 //-----------------------------------------------------------------------------
317 bool USERS_IMPL::Unauthorize(const std::string & login,
319 const std::string & reason)
322 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
323 if (FindByNameNonLock(login, &iter))
325 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
329 uint32_t ip = iter->GetCurrIP();
331 iter->Unauthorize(auth, reason);
333 if (!iter->GetAuthorized())
338 //-----------------------------------------------------------------------------
339 int USERS_IMPL::ReadUsers()
341 std::vector<std::string> usersList;
343 if (store->GetUsersList(&usersList) < 0)
345 WriteServLog(store->GetStrError().c_str());
351 for (unsigned int i = 0; i < usersList.size(); i++)
353 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
355 u.SetLogin(usersList[i]);
359 AddUserIntoIndexes(ui);
361 if (ui->ReadConf() < 0)
364 if (ui->ReadStat() < 0)
370 //-----------------------------------------------------------------------------
371 void * USERS_IMPL::Run(void * d)
374 sigfillset(&signalSet);
375 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
377 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
378 USERS_IMPL * us = static_cast<USERS_IMPL *>(d);
382 localtime_r(&tt, &t);
387 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
389 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
390 std::string monFile = us->settings->GetMonitorDir() + "/users_r";
391 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
393 us->isRunning = true;
396 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
397 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
399 for_each(us->users.begin(), us->users.end(), std::mem_fun_ref(&USER_IMPL::Run));
402 localtime_r(&tt, &t);
406 printfd(__FILE__,"Sec = %d\n", stgTime);
407 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
413 if (day != t.tm_mday)
415 printfd(__FILE__,"Sec = %d\n", stgTime);
416 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
421 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
423 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
425 TouchFile(monFile.c_str());
429 } //while (us->nonstop)
431 user_iter ui = us->users.begin();
432 while (ui != us->users.end())
434 us->DelUserFromIndexes(ui);
438 std::list<USER_TO_DEL>::iterator iter;
439 iter = us->usersToDelete.begin();
440 while (iter != us->usersToDelete.end())
442 iter->delTime -= 2 * userDeleteDelayTime;
447 us->isRunning = false;
451 //-----------------------------------------------------------------------------
452 void USERS_IMPL::NewMinute(const struct tm & t)
454 //Write traff, reset session traff. Fake disconnect-connect
455 if (t.tm_hour == 23 && t.tm_min == 59)
457 printfd(__FILE__,"MidnightResetSessionStat\n");
458 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
461 if (TimeToWriteDetailStat(t))
463 //printfd(__FILE__, "USER::WriteInetStat\n");
466 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
467 std::list<USER_IMPL>::iterator usr = users.begin();
468 while (usr != users.end())
471 usr->WriteDetailStat();
473 if (usersCnt % 10 == 0)
474 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
480 //-----------------------------------------------------------------------------
481 void USERS_IMPL::NewDay(const struct tm & t)
485 localtime_r(&tt, &t1);
486 int dayFee = settings->GetDayFee();
489 dayFee = DaysInCurrentMonth();
491 printfd(__FILE__, "DayFee = %d\n", dayFee);
492 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
493 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
495 if (!settings->GetDayFeeIsLastDay())
497 printfd(__FILE__, "DayResetTraff - 1 -\n");
499 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
502 if (settings->GetSpreadFee())
504 printfd(__FILE__, "Spread DayFee\n");
505 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
509 if (t.tm_mday == dayFee)
511 printfd(__FILE__, "DayFee\n");
512 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFee));
516 std::for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDailyFee));
518 if (settings->GetDayFeeIsLastDay())
520 printfd(__FILE__, "DayResetTraff - 2 -\n");
524 //-----------------------------------------------------------------------------
525 void USERS_IMPL::DayResetTraff(const struct tm & t1)
527 int dayResetTraff = settings->GetDayResetTraff();
528 if (dayResetTraff == 0)
529 dayResetTraff = DaysInCurrentMonth();
530 if (t1.tm_mday == dayResetTraff)
532 printfd(__FILE__, "ResetTraff\n");
533 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessNewMonth));
534 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
537 //-----------------------------------------------------------------------------
538 int USERS_IMPL::Start()
542 WriteServLog("USERS: Error: Cannot read users!");
547 if (pthread_create(&thread, NULL, Run, this))
549 WriteServLog("USERS: Error: Cannot start thread!");
554 //-----------------------------------------------------------------------------
555 int USERS_IMPL::Stop()
557 printfd(__FILE__, "USERS::Stop()\n");
561 //printfd(__FILE__, "Alredy stopped\n");
567 //5 seconds to thread stops itself
568 struct timespec ts = {0, 200000000};
569 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
574 nanosleep(&ts, NULL);
577 //after 5 seconds waiting thread still running. now kill it
580 printfd(__FILE__, "kill USERS thread.\n");
581 //TODO pthread_cancel()
582 if (pthread_kill(thread, SIGINT))
584 //errorStr = "Cannot kill USERS thread.";
585 //printfd(__FILE__, "Cannot kill USERS thread.\n");
588 printfd(__FILE__, "USERS killed\n");
591 printfd(__FILE__, "Before USERS::Run()\n");
592 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
594 // 'cause bind2st accepts only constant first param
595 for (std::list<USER_IMPL>::iterator it = users.begin();
598 it->WriteDetailStat(true);
600 for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::WriteStat));
601 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
603 printfd(__FILE__, "USERS::Stop()\n");
606 //-----------------------------------------------------------------------------
607 void USERS_IMPL::RealDelUser()
609 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
611 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
613 std::list<USER_TO_DEL>::iterator iter;
614 iter = usersToDelete.begin();
615 while (iter != usersToDelete.end())
617 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
618 if (iter->delTime + userDeleteDelayTime < stgTime)
620 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
621 if (store->DelUser(iter->iter->GetLogin()))
623 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
625 users.erase(iter->iter);
626 usersToDelete.erase(iter++);
635 //-----------------------------------------------------------------------------
636 void USERS_IMPL::AddToIPIdx(user_iter user)
638 printfd(__FILE__, "USERS: Add IP Idx\n");
639 uint32_t ip = user->GetCurrIP();
640 //assert(ip && "User has non-null ip");
642 return; // User has disconnected
644 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
646 const std::map<uint32_t, user_iter>::iterator it(
647 ipIndex.lower_bound(ip)
650 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
652 ipIndex.insert(it, std::make_pair(ip, user));
654 //-----------------------------------------------------------------------------
655 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
657 printfd(__FILE__, "USERS: Del IP Idx\n");
658 assert(ip && "User has non-null ip");
660 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
662 const std::map<uint32_t, user_iter>::iterator it(
666 if (it == ipIndex.end())
671 //-----------------------------------------------------------------------------
672 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
674 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
675 if (it == ipIndex.end())
680 //-----------------------------------------------------------------------------
681 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
683 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
686 if (FindByIPIdx(ip, iter))
694 //-----------------------------------------------------------------------------
695 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
697 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
700 if (FindByIPIdx(ip, iter))
708 //-----------------------------------------------------------------------------
709 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
711 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
713 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
715 return it != ipIndex.end();
717 //-----------------------------------------------------------------------------
718 bool USERS_IMPL::IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const
720 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
721 std::list<USER_IMPL>::const_iterator iter;
722 iter = users.begin();
723 while (iter != users.end())
725 if (iter->GetLogin() != login &&
726 !iter->GetProperty().ips.Get().IsAnyIP() &&
727 iter->GetProperty().ips.Get().IsIPInIPS(ip))
737 //-----------------------------------------------------------------------------
738 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
740 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
741 onAddNotifiers.insert(n);
743 //-----------------------------------------------------------------------------
744 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
746 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
747 onAddNotifiers.erase(n);
749 //-----------------------------------------------------------------------------
750 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
752 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
753 onDelNotifiers.insert(n);
755 //-----------------------------------------------------------------------------
756 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
758 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
759 onDelNotifiers.erase(n);
761 //-----------------------------------------------------------------------------
762 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
764 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
765 onAddNotifiersImpl.insert(n);
767 //-----------------------------------------------------------------------------
768 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
770 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
771 onAddNotifiersImpl.erase(n);
773 //-----------------------------------------------------------------------------
774 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
776 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
777 onDelNotifiersImpl.insert(n);
779 //-----------------------------------------------------------------------------
780 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
782 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
783 onDelNotifiersImpl.erase(n);
785 //-----------------------------------------------------------------------------
786 int USERS_IMPL::OpenSearch()
788 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
790 searchDescriptors[handle] = users.begin();
793 //-----------------------------------------------------------------------------
794 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
796 USER_IMPL * ptr = NULL;
797 if (SearchNext(h, &ptr))
802 //-----------------------------------------------------------------------------
803 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
805 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
807 if (searchDescriptors.find(h) == searchDescriptors.end())
809 WriteServLog("USERS. Incorrect search handle.");
813 if (searchDescriptors[h] == users.end())
816 while (searchDescriptors[h]->GetDeleted())
818 ++searchDescriptors[h];
819 if (searchDescriptors[h] == users.end())
825 *user = &(*searchDescriptors[h]);
827 ++searchDescriptors[h];
831 //-----------------------------------------------------------------------------
832 int USERS_IMPL::CloseSearch(int h)
834 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
835 if (searchDescriptors.find(h) != searchDescriptors.end())
837 searchDescriptors.erase(searchDescriptors.find(h));
841 WriteServLog("USERS. Incorrect search handle.");
844 //-----------------------------------------------------------------------------
845 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
847 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
848 loginIndex.insert(make_pair(user->GetLogin(), user));
850 //-----------------------------------------------------------------------------
851 void USERS_IMPL::DelUserFromIndexes(user_iter user)
853 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
854 loginIndex.erase(user->GetLogin());
856 //-----------------------------------------------------------------------------
857 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
859 int statTime = settings->GetDetailStatWritePeriod();
868 if (t.tm_min % 30 == 0)
872 if (t.tm_min % 15 == 0)
876 if (t.tm_min % 10 == 0)