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"
51 extern const volatile time_t stgTime;
53 //#define USERS_DEBUG 1
55 //-----------------------------------------------------------------------------
56 USERS_IMPL::USERS_IMPL(SETTINGS_IMPL * s, STORE * st, TARIFFS * t, const ADMIN * sa)
60 /*userIPNotifiersBefore(),
61 userIPNotifiersAfter(),*/
68 WriteServLog(GetStgLogger()),
80 pthread_mutexattr_t attr;
81 pthread_mutexattr_init(&attr);
82 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
83 pthread_mutex_init(&mutex, &attr);
85 //-----------------------------------------------------------------------------
86 USERS_IMPL::~USERS_IMPL()
88 pthread_mutex_destroy(&mutex);
90 //-----------------------------------------------------------------------------
91 int USERS_IMPL::FindByNameNonLock(const string & login, user_iter * user)
93 map<string, user_iter>::iterator iter;
94 iter = loginIndex.find(login);
95 if (iter != loginIndex.end())
103 //-----------------------------------------------------------------------------
104 int USERS_IMPL::FindByName(const string & login, USER_PTR * user)
106 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
108 int res = FindByNameNonLock(login, &u);
114 //-----------------------------------------------------------------------------
115 bool USERS_IMPL::TariffInUse(const string & tariffName) const
117 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
118 list<USER_IMPL>::const_iterator iter;
119 iter = users.begin();
120 while (iter != users.end())
122 if (iter->GetProperty().tariffName.Get() == tariffName)
128 //-----------------------------------------------------------------------------
129 int USERS_IMPL::Add(const string & login, const ADMIN * admin)
131 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
132 const PRIV * priv = admin->GetPriv();
134 if (!priv->userAddDel)
136 WriteServLog("%s tried to add user \'%s\'. Access denied.",
137 admin->GetLogStr().c_str(), login.c_str());
138 /*errorStr = "Admin \'" + admin->GetLogin() +
139 "\': tried to add user \'" + ud->login + "\'. Access denied.";*/
144 if (store->AddUser(login))
147 //WriteServLog("Admin \'%s\': tried to add user \'%s\'. Access denied.",
148 // admin->GetLogin().c_str(), ud->login.c_str());
153 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
164 if (settings->GetDayResetTraff() > tms->tm_mday)
167 tms->tm_mday = settings->GetDayResetTraff();*/
171 u.SetPassiveTimeAsNewUser();
176 WriteServLog("%s User \'%s\' added.",
177 admin->GetLogStr().c_str(), login.c_str());
183 AddUserIntoIndexes(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 DelUserFromIndexes(u);
265 WriteServLog("%s User \'%s\' deleted.",
266 admin->GetLogStr().c_str(), login.c_str());
270 //-----------------------------------------------------------------------------
271 bool USERS_IMPL::Authorize(const std::string & login, uint32_t ip,
272 uint32_t enabledDirs, const AUTH * auth)
275 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
276 if (FindByNameNonLock(login, &iter))
278 WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
282 if (FindByIPIdx(ip, iter))
284 if (iter->GetLogin() != login)
286 WriteServLog("Attempt to authorize user '%s' from ip %s which already occupied by '%s'",
287 login.c_str(), inet_ntostring(ip).c_str(),
288 iter->GetLogin().c_str());
291 if (iter->Authorize(ip, enabledDirs, auth))
296 if (iter->Authorize(ip, enabledDirs, auth))
302 //-----------------------------------------------------------------------------
303 bool USERS_IMPL::Unauthorize(const std::string & login, const AUTH * auth)
306 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
307 if (FindByNameNonLock(login, &iter))
309 WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
313 uint32_t ip = iter->GetCurrIP();
315 iter->Unauthorize(auth);
317 if (!iter->GetAuthorized())
322 //-----------------------------------------------------------------------------
323 int USERS_IMPL::ReadUsers()
325 vector<string> usersList;
327 if (store->GetUsersList(&usersList) < 0)
329 WriteServLog(store->GetStrError().c_str());
335 for (unsigned int i = 0; i < usersList.size(); i++)
337 USER_IMPL u(settings, store, tariffs, sysAdmin, this);
339 u.SetLogin(usersList[i]);
343 AddUserIntoIndexes(ui);
345 if (ui->ReadConf() < 0)
348 if (ui->ReadStat() < 0)
354 //-----------------------------------------------------------------------------
355 void * USERS_IMPL::Run(void * d)
358 sigfillset(&signalSet);
359 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
361 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
362 USERS_IMPL * us = static_cast<USERS_IMPL *>(d);
366 localtime_r(&tt, &t);
371 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
373 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
374 string monFile = us->settings->GetMonitorDir() + "/users_r";
375 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
377 us->isRunning = true;
380 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
381 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
383 for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER_IMPL::Run));
386 localtime_r(&tt, &t);
390 printfd(__FILE__,"Sec = %d\n", stgTime);
391 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
397 if (day != t.tm_mday)
399 printfd(__FILE__,"Sec = %d\n", stgTime);
400 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
405 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
407 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
409 TouchFile(monFile.c_str());
413 } //while (us->nonstop)
415 user_iter ui = us->users.begin();
416 while (ui != us->users.end())
418 us->DelUserFromIndexes(ui);
422 list<USER_TO_DEL>::iterator iter;
423 iter = us->usersToDelete.begin();
424 while (iter != us->usersToDelete.end())
426 iter->delTime -= 2 * userDeleteDelayTime;
431 us->isRunning = false;
435 //-----------------------------------------------------------------------------
436 void USERS_IMPL::NewMinute(const struct tm & t)
438 //Write traff, reset session traff. Fake disconnect-connect
439 if (t.tm_hour == 23 && t.tm_min == 59)
441 printfd(__FILE__,"MidnightResetSessionStat\n");
442 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
445 if (TimeToWriteDetailStat(t))
447 //printfd(__FILE__, "USER::WriteInetStat\n");
450 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
451 list<USER_IMPL>::iterator usr = users.begin();
452 while (usr != users.end())
455 usr->WriteDetailStat();
457 if (usersCnt % 10 == 0)
458 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
464 //-----------------------------------------------------------------------------
465 void USERS_IMPL::NewDay(const struct tm & t)
469 localtime_r(&tt, &t1);
470 int dayFee = settings->GetDayFee();
473 dayFee = DaysInCurrentMonth();
475 printfd(__FILE__, "DayFee = %d\n", dayFee);
476 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
477 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
479 if (!settings->GetDayFeeIsLastDay())
481 printfd(__FILE__, "DayResetTraff - 1 -\n");
483 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
486 if (settings->GetSpreadFee())
488 printfd(__FILE__, "Spread DayFee\n");
489 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
493 if (t.tm_mday == dayFee)
495 printfd(__FILE__, "DayFee\n");
496 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFee));
500 if (settings->GetDayFeeIsLastDay())
502 printfd(__FILE__, "DayResetTraff - 2 -\n");
506 //-----------------------------------------------------------------------------
507 void USERS_IMPL::DayResetTraff(const struct tm & t1)
509 int dayResetTraff = settings->GetDayResetTraff();
510 if (dayResetTraff == 0)
511 dayResetTraff = DaysInCurrentMonth();
512 if (t1.tm_mday == dayResetTraff)
514 printfd(__FILE__, "ResetTraff\n");
515 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessNewMonth));
516 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
519 //-----------------------------------------------------------------------------
520 int USERS_IMPL::Start()
524 WriteServLog("USERS: Error: Cannot read users!");
529 if (pthread_create(&thread, NULL, Run, this))
531 WriteServLog("USERS: Error: Cannot start thread!");
536 //-----------------------------------------------------------------------------
537 int USERS_IMPL::Stop()
539 printfd(__FILE__, "USERS::Stop()\n");
543 //printfd(__FILE__, "Alredy stopped\n");
549 //5 seconds to thread stops itself
550 struct timespec ts = {0, 200000000};
551 for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
556 nanosleep(&ts, NULL);
559 //after 5 seconds waiting thread still running. now kill it
562 printfd(__FILE__, "kill USERS thread.\n");
563 //TODO pthread_cancel()
564 if (pthread_kill(thread, SIGINT))
566 //errorStr = "Cannot kill USERS thread.";
567 //printfd(__FILE__, "Cannot kill USERS thread.\n");
570 printfd(__FILE__, "USERS killed\n");
573 printfd(__FILE__, "Before USERS::Run()\n");
574 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
576 // 'cause bind2st accepts only constant first param
577 for (list<USER_IMPL>::iterator it = users.begin();
580 it->WriteDetailStat(true);
582 for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteStat));
583 //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
585 printfd(__FILE__, "USERS::Stop()\n");
588 //-----------------------------------------------------------------------------
589 void USERS_IMPL::RealDelUser()
591 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
593 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
595 list<USER_TO_DEL>::iterator iter;
596 iter = usersToDelete.begin();
597 while (iter != usersToDelete.end())
599 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
600 if (iter->delTime + userDeleteDelayTime < stgTime)
602 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
603 if (store->DelUser(iter->iter->GetLogin()))
605 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
607 users.erase(iter->iter);
608 usersToDelete.erase(iter++);
617 //-----------------------------------------------------------------------------
618 void USERS_IMPL::AddToIPIdx(user_iter user)
620 printfd(__FILE__, "USERS: Add IP Idx\n");
621 uint32_t ip = user->GetCurrIP();
622 //assert(ip && "User has non-null ip");
624 return; // User has disconnected
626 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
628 const map<uint32_t, user_iter>::iterator it(
629 ipIndex.lower_bound(ip)
632 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
634 ipIndex.insert(it, std::make_pair(ip, user));
636 //-----------------------------------------------------------------------------
637 void USERS_IMPL::DelFromIPIdx(uint32_t ip)
639 printfd(__FILE__, "USERS: Del IP Idx\n");
640 assert(ip && "User has non-null ip");
642 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
644 const map<uint32_t, user_iter>::iterator it(
648 if (it == ipIndex.end())
653 //-----------------------------------------------------------------------------
654 bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
656 map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
657 if (it == ipIndex.end())
662 //-----------------------------------------------------------------------------
663 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const
665 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
668 if (FindByIPIdx(ip, iter))
676 //-----------------------------------------------------------------------------
677 int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const
679 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
682 if (FindByIPIdx(ip, iter))
690 //-----------------------------------------------------------------------------
691 bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
693 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
695 map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
697 return it != ipIndex.end();
699 //-----------------------------------------------------------------------------
700 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
702 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
703 onAddNotifiers.insert(n);
705 //-----------------------------------------------------------------------------
706 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
708 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
709 onAddNotifiers.erase(n);
711 //-----------------------------------------------------------------------------
712 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
714 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
715 onDelNotifiers.insert(n);
717 //-----------------------------------------------------------------------------
718 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
720 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
721 onDelNotifiers.erase(n);
723 //-----------------------------------------------------------------------------
724 void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
726 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
727 onAddNotifiersImpl.insert(n);
729 //-----------------------------------------------------------------------------
730 void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
732 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
733 onAddNotifiersImpl.erase(n);
735 //-----------------------------------------------------------------------------
736 void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
738 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
739 onDelNotifiersImpl.insert(n);
741 //-----------------------------------------------------------------------------
742 void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
744 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
745 onDelNotifiersImpl.erase(n);
747 //-----------------------------------------------------------------------------
748 int USERS_IMPL::OpenSearch()
750 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
752 searchDescriptors[handle] = users.begin();
755 //-----------------------------------------------------------------------------
756 int USERS_IMPL::SearchNext(int h, USER_PTR * user)
758 USER_IMPL * ptr = NULL;
759 if (SearchNext(h, &ptr))
764 //-----------------------------------------------------------------------------
765 int USERS_IMPL::SearchNext(int h, USER_IMPL ** user)
767 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
769 if (searchDescriptors.find(h) == searchDescriptors.end())
771 WriteServLog("USERS. Incorrect search handle.");
775 if (searchDescriptors[h] == users.end())
778 while (searchDescriptors[h]->GetDeleted())
780 ++searchDescriptors[h];
781 if (searchDescriptors[h] == users.end())
787 *user = &(*searchDescriptors[h]);
789 ++searchDescriptors[h];
793 //-----------------------------------------------------------------------------
794 int USERS_IMPL::CloseSearch(int h)
796 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
797 if (searchDescriptors.find(h) != searchDescriptors.end())
799 searchDescriptors.erase(searchDescriptors.find(h));
803 WriteServLog("USERS. Incorrect search handle.");
806 //-----------------------------------------------------------------------------
807 void USERS_IMPL::AddUserIntoIndexes(user_iter user)
809 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
810 loginIndex.insert(make_pair(user->GetLogin(), user));
812 //-----------------------------------------------------------------------------
813 void USERS_IMPL::DelUserFromIndexes(user_iter user)
815 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
816 loginIndex.erase(user->GetLogin());
818 //-----------------------------------------------------------------------------
819 bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t)
821 int statTime = settings->GetDetailStatWritePeriod();
830 if (t.tm_min % 30 == 0)
834 if (t.tm_min % 15 == 0)
838 if (t.tm_min % 10 == 0)