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 $
47 #include "stg_timer.h"
51 extern const volatile time_t stgTime;
53 //#define USERS_DEBUG 1
55 //-----------------------------------------------------------------------------
56 USERS::USERS(SETTINGS * s, BASE_STORE * st, TARIFFS * t, const ADMIN & sa)
59 userIPNotifiersBefore(),
60 userIPNotifiersAfter(),
67 WriteServLog(GetStgLogger()),
77 pthread_mutexattr_t attr;
78 pthread_mutexattr_init(&attr);
79 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
80 pthread_mutex_init(&mutex, &attr);
82 //-----------------------------------------------------------------------------
85 pthread_mutex_destroy(&mutex);
87 //-----------------------------------------------------------------------------
88 int USERS::FindByNameNonLock(const string & login, user_iter * user) const
90 map<string, user_iter>::const_iterator iter;
91 iter = loginIndex.find(login);
92 if (iter != loginIndex.end())
100 //-----------------------------------------------------------------------------
101 int USERS::FindByName(const string & login, user_iter * user) const
103 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
104 return FindByNameNonLock(login, user);
106 //-----------------------------------------------------------------------------
107 bool USERS::TariffInUse(const string & tariffName)
109 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
110 list<USER>::iterator iter;
111 iter = users.begin();
112 while (iter != users.end())
114 if (iter->property.tariffName.Get() == tariffName)
120 //-----------------------------------------------------------------------------
121 int USERS::Add(const string & login, const ADMIN & admin)
123 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
124 const PRIV * priv = admin.GetPriv();
126 if (!priv->userAddDel)
128 WriteServLog("%s tried to add user \'%s\'. Access denied.",
129 admin.GetLogStr().c_str(), login.c_str());
130 /*errorStr = "Admin \'" + admin.GetLogin() +
131 "\': tried to add user \'" + ud->login + "\'. Access denied.";*/
136 if (store->AddUser(login))
139 //WriteServLog("Admin \'%s\': tried to add user \'%s\'. Access denied.",
140 // admin.GetLogin().c_str(), ud->login.c_str());
145 USER u(settings, store, tariffs, sysAdmin, &ipIndex);
156 if (settings->GetDayResetTraff() > tms->tm_mday)
159 tms->tm_mday = settings->GetDayResetTraff();*/
163 u.SetPassiveTimeAsNewUser();
168 WriteServLog("%s User \'%s\' added.",
169 admin.GetLogStr().c_str(), login.c_str());
175 AddUserIntoIndexes(users.begin());
176 SetUserNotifiers(users.begin());
178 // õ×ÅÄÏÍÌÑÅÍ ×ÓÅÈ ÖÅÌÁÀÝÉÈ, ÞÔÏ ÄÏÂÁ×ÌÅÎ ÎÏ×ÙÊ ÐÏÌØÚÏ×ÁÔÅÌØ
179 set<NOTIFIER_BASE<user_iter> *>::iterator ni = onAddNotifiers.begin();
180 while (ni != onAddNotifiers.end())
182 (*ni)->Notify(users.begin());
188 //-----------------------------------------------------------------------------
189 void USERS::Del(const string & login, const ADMIN & admin)
191 const PRIV * priv = admin.GetPriv();
194 if (!priv->userAddDel)
196 WriteServLog("%s tried to remove user \'%s\'. Access denied.",
197 admin.GetLogStr().c_str(), login.c_str());
203 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
205 if (FindByNameNonLock(login, &u))
207 WriteServLog("%s tried to delete user \'%s\': not found.",
208 admin.GetLogStr().c_str(),
214 set<NOTIFIER_BASE<user_iter> *>::iterator ni = onDelNotifiers.begin();
215 while (ni != onDelNotifiers.end())
222 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
229 utd.delTime = stgTime;
230 usersToDelete.push_back(utd);
232 UnSetUserNotifiers(u);
233 DelUserFromIndexes(u);
235 WriteServLog("%s User \'%s\' deleted.",
236 admin.GetLogStr().c_str(), login.c_str());
240 //-----------------------------------------------------------------------------
241 int USERS::ReadUsers()
243 vector<string> usersList;
245 if (store->GetUsersList(&usersList) < 0)
247 WriteServLog(store->GetStrError().c_str());
253 for (unsigned int i = 0; i < usersList.size(); i++)
255 USER u(settings, store, tariffs, sysAdmin, &ipIndex);
257 u.SetLogin(usersList[i]);
261 AddUserIntoIndexes(ui);
262 SetUserNotifiers(ui);
264 if (ui->ReadConf() < 0)
267 if (ui->ReadStat() < 0)
273 //-----------------------------------------------------------------------------
274 void * USERS::Run(void * d)
276 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
277 USERS * us = (USERS*) d;
281 localtime_r(&tt, &t);
286 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
288 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
289 string monFile = us->settings->GetMonitorDir() + "/users_r";
290 printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
292 us->isRunning = true;
295 //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
296 //printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
298 for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER::Run));
301 localtime_r(&tt, &t);
305 printfd(__FILE__,"Sec = %d\n", stgTime);
306 printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
312 if (day != t.tm_mday)
314 printfd(__FILE__,"Sec = %d\n", stgTime);
315 printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
320 if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
322 //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
324 TouchFile(monFile.c_str());
328 } //while (us->nonstop)
330 user_iter ui = us->users.begin();
331 while (ui != us->users.end())
333 us->UnSetUserNotifiers(ui);
334 us->DelUserFromIndexes(ui);
338 list<USER_TO_DEL>::iterator iter;
339 iter = us->usersToDelete.begin();
340 while (iter != us->usersToDelete.end())
342 iter->delTime -= 2 * userDeleteDelayTime;
347 us->isRunning = false;
351 //-----------------------------------------------------------------------------
352 void USERS::NewMinute(const struct tm & t)
354 //Write traff, reset session traff. Fake disconnect-connect
355 if (t.tm_hour == 23 && t.tm_min == 59)
357 printfd(__FILE__,"MidnightResetSessionStat\n");
358 for_each(users.begin(), users.end(), mem_fun_ref(&USER::MidnightResetSessionStat));
361 if (TimeToWriteDetailStat(t))
363 //printfd(__FILE__, "USER::WriteInetStat\n");
366 // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
367 list<USER>::iterator usr = users.begin();
368 while (usr != users.end())
371 usr->WriteDetailStat();
373 if (usersCnt % 10 == 0)
374 for_each(users.begin(), users.end(), mem_fun_ref(&USER::Run));
380 //-----------------------------------------------------------------------------
381 void USERS::NewDay(const struct tm & t)
385 localtime_r(&tt, &t1);
386 int dayFee = settings->GetDayFee();
389 dayFee = DaysInCurrentMonth();
391 printfd(__FILE__, "DayFee = %d\n", dayFee);
392 printfd(__FILE__, "Today = %d DayResetTraff = %d\n", t1.tm_mday, settings->GetDayResetTraff());
393 printfd(__FILE__, "DayFeeIsLastDay = %d\n", settings->GetDayFeeIsLastDay());
395 if (!settings->GetDayFeeIsLastDay())
397 printfd(__FILE__, "DayResetTraff - 1 -\n");
399 //printfd(__FILE__, "DayResetTraff - 1 - 1 -\n");
402 if (settings->GetSpreadFee())
404 printfd(__FILE__, "Spread DayFee\n");
405 for_each(users.begin(), users.end(), mem_fun_ref(&USER::ProcessDayFeeSpread));
409 if (t.tm_mday == dayFee)
411 printfd(__FILE__, "DayFee\n");
412 for_each(users.begin(), users.end(), mem_fun_ref(&USER::ProcessDayFee));
416 if (settings->GetDayFeeIsLastDay())
418 printfd(__FILE__, "DayResetTraff - 2 -\n");
422 //-----------------------------------------------------------------------------
423 void USERS::DayResetTraff(const struct tm & t1)
425 int dayResetTraff = settings->GetDayResetTraff();
426 if (dayResetTraff == 0)
427 dayResetTraff = DaysInCurrentMonth();
428 if (t1.tm_mday == dayResetTraff)
430 printfd(__FILE__, "ResetTraff\n");
431 for_each(users.begin(), users.end(), mem_fun_ref(&USER::ProcessNewMonth));
432 for_each(users.begin(), users.end(), mem_fun_ref(&USER::SetPrepaidTraff));
435 //-----------------------------------------------------------------------------
440 WriteServLog("USERS: Error: Cannot read users!");
445 if (pthread_create(&thread, NULL, Run, this))
447 WriteServLog("USERS: Error: Cannot start thread!");
452 //-----------------------------------------------------------------------------
455 printfd(__FILE__, "USERS::Stop()\n");
459 //printfd(__FILE__, "Alredy stopped\n");
465 //5 seconds to thread stops itself
467 for (i = 0; i < 25 * (users.size() / 50 + 1); i++)
475 //after 5 seconds waiting thread still running. now kill it
478 printfd(__FILE__, "kill USERS thread.\n");
479 //TODO pthread_cancel()
480 if (pthread_kill(thread, SIGINT))
482 //errorStr = "Cannot kill USERS thread.";
483 //printfd(__FILE__, "Cannot kill USERS thread.\n");
486 printfd(__FILE__, "USERS killed\n");
489 printfd(__FILE__, "Before USERS::Run()\n");
490 for_each(users.begin(), users.end(), mem_fun_ref(&USER::Run));
492 // 'cause bind2st accepts only constant first param
493 for (list<USER>::iterator it = users.begin();
496 it->WriteDetailStat(true);
498 for_each(users.begin(), users.end(), mem_fun_ref(&USER::WriteStat));
499 for_each(users.begin(), users.end(), mem_fun_ref(&USER::WriteConf));
501 printfd(__FILE__, "USERS::Stop()\n");
504 //-----------------------------------------------------------------------------
505 void USERS::RealDelUser()
507 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
509 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
511 list<USER_TO_DEL>::iterator iter;
512 iter = usersToDelete.begin();
513 while (iter != usersToDelete.end())
515 printfd(__FILE__, "RealDelUser() user=%s\n", iter->iter->GetLogin().c_str());
516 if (iter->delTime + userDeleteDelayTime < stgTime)
518 printfd(__FILE__, "RealDelUser() user=%s removed from DB\n", iter->iter->GetLogin().c_str());
519 if (store->DelUser(iter->iter->GetLogin()))
521 WriteServLog("Error removing user \'%s\' from database.", iter->iter->GetLogin().c_str());
523 users.erase(iter->iter);
524 usersToDelete.erase(iter++);
533 //-----------------------------------------------------------------------------
534 int USERS::GetUserNum()
536 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
539 //-----------------------------------------------------------------------------
540 void USERS::AddToIPIdx(user_iter user)
542 printfd(__FILE__, "USERS: Add IP Idx\n");
543 uint32_t ip = user->GetCurrIP();
544 //assert(ip && "User has non-null ip");
546 return; // User has disconnected
548 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
550 const map<uint32_t, user_iter>::iterator it(
551 ipIndex.lower_bound(ip)
554 assert((it == ipIndex.end() || it->first != ip) && "User is not in index");
556 ipIndex.insert(it, std::make_pair(ip, user));
558 //-----------------------------------------------------------------------------
559 void USERS::DelFromIPIdx(uint32_t ip)
561 printfd(__FILE__, "USERS: Del IP Idx\n");
562 assert(ip && "User has non-null ip");
564 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
566 const map<uint32_t, user_iter>::iterator it(
570 //assert(it != ipIndex.end() && "User is in index");
571 if (it == ipIndex.end())
572 return; // User has not been added
576 //-----------------------------------------------------------------------------
577 int USERS::FindByIPIdx(uint32_t ip, user_iter * usr)
579 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
581 map<uint32_t, user_iter>::iterator it;
582 it = ipIndex.find(ip);
584 if (it == ipIndex.end())
586 //printfd(__FILE__, "User NOT found in IP_Index!!!\n");
590 //printfd(__FILE__, "User found in IP_Index\n");
593 //-----------------------------------------------------------------------------
594 void USERS::AddNotifierUserAdd(NOTIFIER_BASE<user_iter> * n)
596 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
597 onAddNotifiers.insert(n);
599 //-----------------------------------------------------------------------------
600 void USERS::DelNotifierUserAdd(NOTIFIER_BASE<user_iter> * n)
602 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
603 //printfd(__FILE__, "DelNotifierUserAdd\n");
604 onAddNotifiers.erase(n);
606 //-----------------------------------------------------------------------------
607 void USERS::AddNotifierUserDel(NOTIFIER_BASE<user_iter> * n)
609 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
610 onDelNotifiers.insert(n);
612 //-----------------------------------------------------------------------------
613 void USERS::DelNotifierUserDel(NOTIFIER_BASE<user_iter> * n)
615 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
616 onDelNotifiers.erase(n);
618 //-----------------------------------------------------------------------------
619 int USERS::OpenSearch()
621 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
623 searchDescriptors[handle] = users.begin();
626 //-----------------------------------------------------------------------------
627 int USERS::SearchNext(int h, user_iter * u)
629 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
631 if (searchDescriptors.find(h) == searchDescriptors.end())
633 WriteServLog("USERS. Incorrect search handle.");
637 if (searchDescriptors[h] == users.end())
640 while (searchDescriptors[h]->GetDeleted())
642 ++searchDescriptors[h];
643 if (searchDescriptors[h] == users.end())
649 *u = searchDescriptors[h];
651 ++searchDescriptors[h];
655 //-----------------------------------------------------------------------------
656 int USERS::CloseSearch(int h)
658 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
659 if (searchDescriptors.find(h) != searchDescriptors.end())
661 searchDescriptors.erase(searchDescriptors.find(h));
665 WriteServLog("USERS. Incorrect search handle.");
668 //-----------------------------------------------------------------------------
669 void USERS::SetUserNotifiers(user_iter user)
671 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
673 PROPERTY_NOTIFER_IP_BEFORE nb(*this, user);
674 PROPERTY_NOTIFER_IP_AFTER na(*this, user);
676 userIPNotifiersBefore.push_front(nb);
677 userIPNotifiersAfter.push_front(na);
679 user->AddCurrIPBeforeNotifier(&(*userIPNotifiersBefore.begin()));
680 user->AddCurrIPAfterNotifier(&(*userIPNotifiersAfter.begin()));
682 //-----------------------------------------------------------------------------
683 void USERS::UnSetUserNotifiers(user_iter user)
685 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
687 list<PROPERTY_NOTIFER_IP_BEFORE>::iterator bi;
688 list<PROPERTY_NOTIFER_IP_AFTER>::iterator ai;
690 bi = userIPNotifiersBefore.begin();
691 while (bi != userIPNotifiersBefore.end())
693 if (bi->GetUser() == user)
695 bi->GetUser()->DelCurrIPBeforeNotifier(&(*bi));
696 userIPNotifiersBefore.erase(bi);
697 //printfd(__FILE__, "Notifier Before removed. User %s\n", bi->GetUser()->GetLogin().c_str());
703 ai = userIPNotifiersAfter.begin();
704 while (ai != userIPNotifiersAfter.end())
706 if (ai->GetUser() == user)
708 ai->GetUser()->DelCurrIPAfterNotifier(&(*ai));
709 userIPNotifiersAfter.erase(ai);
710 //printfd(__FILE__, "Notifier After removed. User %s\n", ai->GetUser()->GetLogin().c_str());
716 //-----------------------------------------------------------------------------
717 void USERS::AddUserIntoIndexes(user_iter user)
719 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
720 loginIndex.insert(pair<string, user_iter>(user->GetLogin(), user));
722 //-----------------------------------------------------------------------------
723 void USERS::DelUserFromIndexes(user_iter user)
725 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
726 loginIndex.erase(user->GetLogin());
728 //-----------------------------------------------------------------------------
729 bool USERS::TimeToWriteDetailStat(const struct tm & t)
731 int statTime = settings->GetDetailStatWritePeriod();
740 if (t.tm_min % 30 == 0)
744 if (t.tm_min % 15 == 0)
748 if (t.tm_min % 10 == 0)