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
18 * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
23 $Date: 2010/03/25 15:18:48 $
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <unistd.h> // close
37 #include <cstdio> // snprintf
41 #include "stg/common.h"
42 #include "stg/locker.h"
43 #include "stg/tariff.h"
44 #include "stg/user_property.h"
45 #include "stg/settings.h"
46 #include "stg/plugin_creator.h"
47 #include "inetaccess.h"
49 extern volatile const time_t stgTime;
51 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password);
52 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
53 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
55 //-----------------------------------------------------------------------------
56 //-----------------------------------------------------------------------------
57 //-----------------------------------------------------------------------------
58 PLUGIN_CREATOR<AUTH_IA> iac;
59 //-----------------------------------------------------------------------------
60 //-----------------------------------------------------------------------------
61 //-----------------------------------------------------------------------------
64 return iac.GetPlugin();
66 //-----------------------------------------------------------------------------
67 //-----------------------------------------------------------------------------
68 //-----------------------------------------------------------------------------
69 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
74 freeMbShowType(freeMbCash)
77 //-----------------------------------------------------------------------------
78 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
82 vector<PARAM_VALUE>::const_iterator pvi;
83 ///////////////////////////
85 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
86 if (pvi == s.moduleParams.end())
88 errorStr = "Parameter \'Port\' not found.";
89 printfd(__FILE__, "Parameter 'Port' not found\n");
92 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
94 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
95 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
99 ///////////////////////////
100 pv.param = "UserDelay";
101 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
102 if (pvi == s.moduleParams.end())
104 errorStr = "Parameter \'UserDelay\' not found.";
105 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
109 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
111 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
112 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
115 ///////////////////////////
116 pv.param = "UserTimeout";
117 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
118 if (pvi == s.moduleParams.end())
120 errorStr = "Parameter \'UserTimeout\' not found.";
121 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
125 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
127 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
128 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
131 /////////////////////////////////////////////////////////////
135 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
136 if (pvi == s.moduleParams.end())
138 errorStr = "Parameter \'FreeMb\' not found.";
139 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
142 freeMbType = pvi->value[0];
144 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
146 freeMbShowType = freeMbCash;
148 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
150 freeMbShowType = freeMbNone;
152 else if (!str2x(freeMbType.c_str(), n))
154 if (n < 0 || n >= DIR_NUM)
156 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
157 printfd(__FILE__, "%s\n", errorStr.c_str());
160 freeMbShowType = (FREEMB)(freeMb0 + n);
164 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
165 printfd(__FILE__, "%s\n", errorStr.c_str());
168 /////////////////////////////////////////////////////////////
171 //-----------------------------------------------------------------------------
172 //-----------------------------------------------------------------------------
173 //-----------------------------------------------------------------------------
174 #ifdef IA_PHASE_DEBUG
180 gettimeofday(&phaseTime, NULL);
187 gettimeofday(&phaseTime, NULL);
190 //-----------------------------------------------------------------------------
191 IA_PHASE::~IA_PHASE()
193 #ifdef IA_PHASE_DEBUG
194 flog = fopen(log.c_str(), "at");
197 fprintf(flog, "IA %s D\n", login.c_str());
202 //-----------------------------------------------------------------------------
203 #ifdef IA_PHASE_DEBUG
204 void IA_PHASE::SetLogFileName(const string & logFileName)
206 log = logFileName + ".ia.log";
208 //-----------------------------------------------------------------------------
209 void IA_PHASE::SetUserLogin(const string & login)
211 IA_PHASE::login = login;
213 //-----------------------------------------------------------------------------
214 void IA_PHASE::WritePhaseChange(int newPhase)
217 gettimeofday(&newPhaseTime, NULL);
218 flog = fopen(log.c_str(), "at");
221 string action = newPhase == phase ? "U" : "C";
222 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
223 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
224 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
234 //-----------------------------------------------------------------------------
235 void IA_PHASE::SetPhase1()
237 #ifdef IA_PHASE_DEBUG
241 gettimeofday(&phaseTime, NULL);
243 //-----------------------------------------------------------------------------
244 void IA_PHASE::SetPhase2()
246 #ifdef IA_PHASE_DEBUG
250 gettimeofday(&phaseTime, NULL);
252 //-----------------------------------------------------------------------------
253 void IA_PHASE::SetPhase3()
255 #ifdef IA_PHASE_DEBUG
259 gettimeofday(&phaseTime, NULL);
261 //-----------------------------------------------------------------------------
262 void IA_PHASE::SetPhase4()
264 #ifdef IA_PHASE_DEBUG
268 gettimeofday(&phaseTime, NULL);
270 //-----------------------------------------------------------------------------
271 void IA_PHASE::SetPhase5()
273 #ifdef IA_PHASE_DEBUG
277 gettimeofday(&phaseTime, NULL);
279 //-----------------------------------------------------------------------------
280 int IA_PHASE::GetPhase() const
284 //-----------------------------------------------------------------------------
285 void IA_PHASE::UpdateTime()
287 #ifdef IA_PHASE_DEBUG
288 WritePhaseChange(phase);
290 gettimeofday(&phaseTime, NULL);
292 //-----------------------------------------------------------------------------
293 const UTIME & IA_PHASE::GetTime() const
297 //-----------------------------------------------------------------------------
298 //-----------------------------------------------------------------------------
299 //-----------------------------------------------------------------------------
307 isRunningRunTimeouter(false),
324 WriteServLog(GetStgLogger()),
325 enabledDirs(0xFFffFFff),
326 onDelUserNotifier(*this)
328 InitEncrypt(&ctxS, "pr7Hhen");
330 pthread_mutexattr_t attr;
331 pthread_mutexattr_init(&attr);
332 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
333 pthread_mutex_init(&mutex, &attr);
335 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
336 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
337 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
338 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
339 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
340 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
341 memset(&fin6, 0, sizeof(FIN_6));
342 memset(&fin8, 0, sizeof(FIN_8));
344 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
345 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
346 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
347 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
348 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
349 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
350 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
351 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
352 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
353 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
354 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
355 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
356 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
357 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
358 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
359 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
360 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
361 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
363 packetTypes["CONN_SYN"] = CONN_SYN_N;
364 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
365 packetTypes["CONN_ACK"] = CONN_ACK_N;
366 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
367 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
368 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
369 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
370 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
371 packetTypes["FIN"] = FIN_N;
372 packetTypes["ERR"] = ERROR_N;
374 //-----------------------------------------------------------------------------
377 pthread_mutex_destroy(&mutex);
379 //-----------------------------------------------------------------------------
382 users->AddNotifierUserDel(&onDelUserNotifier);
392 if (pthread_create(&recvThread, NULL, Run, this))
394 errorStr = "Cannot create thread.";
395 printfd(__FILE__, "Cannot create recv thread\n");
400 if (!isRunningRunTimeouter)
402 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
404 errorStr = "Cannot create thread.";
405 printfd(__FILE__, "Cannot create timeouter thread\n");
412 //-----------------------------------------------------------------------------
423 UnauthorizeUser(this)
428 //5 seconds to thread stops itself
429 for (int i = 0; i < 25 && isRunningRun; i++)
431 struct timespec ts = {0, 200000000};
432 nanosleep(&ts, NULL);
435 //after 5 seconds waiting thread still running. now killing it
438 if (pthread_kill(recvThread, SIGINT))
440 errorStr = "Cannot kill thread.";
441 printfd(__FILE__, "Cannot kill thread\n");
444 for (int i = 0; i < 25 && isRunningRun; ++i)
446 struct timespec ts = {0, 200000000};
447 nanosleep(&ts, NULL);
451 printfd(__FILE__, "Failed to stop recv thread\n");
455 pthread_join(recvThread, NULL);
457 printfd(__FILE__, "AUTH_IA killed Run\n");
463 if (isRunningRunTimeouter)
465 //5 seconds to thread stops itself
466 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
468 struct timespec ts = {0, 200000000};
469 nanosleep(&ts, NULL);
472 //after 5 seconds waiting thread still running. now killing it
473 if (isRunningRunTimeouter)
475 if (pthread_kill(timeouterThread, SIGINT))
477 errorStr = "Cannot kill thread.";
480 for (int i = 0; i < 25 && isRunningRunTimeouter; ++i)
482 struct timespec ts = {0, 200000000};
483 nanosleep(&ts, NULL);
485 if (isRunningRunTimeouter)
487 printfd(__FILE__, "Failed to stop timeouter thread\n");
491 pthread_join(timeouterThread, NULL);
493 printfd(__FILE__, "AUTH_IA killed Timeouter\n");
496 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
497 users->DelNotifierUserDel(&onDelUserNotifier);
500 //-----------------------------------------------------------------------------
501 void * AUTH_IA::Run(void * d)
504 sigfillset(&signalSet);
505 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
507 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
509 ia->isRunningRun = true;
513 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
517 ia->RecvData(buffer, sizeof(buffer));
518 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
521 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
522 TouchFile(monFile.c_str());
526 ia->isRunningRun = false;
529 //-----------------------------------------------------------------------------
530 void * AUTH_IA::RunTimeouter(void * d)
533 sigfillset(&signalSet);
534 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
536 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
538 ia->isRunningRunTimeouter = true;
541 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
544 struct timespec ts = {0, 20000000};
545 nanosleep(&ts, NULL);
547 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
548 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
550 TouchFile(monFile.c_str());
554 ia->isRunningRunTimeouter = false;
557 //-----------------------------------------------------------------------------
558 int AUTH_IA::ParseSettings()
560 int ret = iaSettings.ParseSettings(settings);
562 errorStr = iaSettings.GetStrError();
565 //-----------------------------------------------------------------------------
566 int AUTH_IA::PrepareNet()
568 struct sockaddr_in listenAddr;
570 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
572 if (listenSocket < 0)
574 errorStr = "Cannot create socket.";
578 listenAddr.sin_family = AF_INET;
579 listenAddr.sin_port = htons(iaSettings.GetUserPort());
580 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
582 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
584 errorStr = "AUTH_IA: Bind failed.";
590 //-----------------------------------------------------------------------------
591 int AUTH_IA::FinalizeNet()
596 //-----------------------------------------------------------------------------
597 int AUTH_IA::RecvData(char * buffer, int bufferSize)
599 if (!WaitPackets(listenSocket)) // Timeout
604 struct sockaddr_in outerAddr;
605 socklen_t outerAddrLen(sizeof(outerAddr));
606 int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
613 if (dataLen <= 0) // Error
617 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
627 if (CheckHeader(buffer, &protoVer))
630 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
631 memset(login, 0, PASSWD_LEN);
633 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
635 uint32_t sip = outerAddr.sin_addr.s_addr;
636 uint16_t sport = htons(outerAddr.sin_port);
639 if (users->FindByName(login, &user))
641 WriteServLog("User's connect failed: user '%s' not found. IP %s",
643 inet_ntostring(sip).c_str());
644 printfd(__FILE__, "User '%s' NOT found!\n", login);
645 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ!");
649 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
651 if (user->GetProperty().disabled.Get())
653 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
657 if (user->GetProperty().passive.Get())
659 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
663 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
665 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
666 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
667 WriteServLog("User %s. IP address is incorrect. IP %s",
668 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
669 SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
673 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
675 //-----------------------------------------------------------------------------
676 int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
678 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
680 //SendError(userIP, updateMsg);
681 printfd(__FILE__, "update needed - IA_ID\n");
682 //SendError(userIP, "Incorrect header!");
686 if (buffer[6] != 0) //proto[0] shoud be 0
688 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
689 //SendError(userIP, updateMsg);
696 //SendError(userIP, updateMsg);
697 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
702 *protoVer = buffer[7];
706 //-----------------------------------------------------------------------------
707 int AUTH_IA::Timeouter()
709 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
711 map<uint32_t, IA_USER>::iterator it;
712 it = ip2user.begin();
715 while (it != ip2user.end())
719 static UTIME currTime;
720 gettimeofday(&currTime, NULL);
722 if ((it->second.phase.GetPhase() == 2)
723 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
725 it->second.phase.SetPhase1();
726 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
731 if (it->second.phase.GetPhase() == 3)
733 if (!it->second.messagesToSend.empty())
735 if (it->second.protoVer == 6)
736 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
738 if (it->second.protoVer == 7)
739 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
741 if (it->second.protoVer == 8)
742 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
744 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
747 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
749 switch (it->second.protoVer)
752 Send_ALIVE_SYN_6(&(it->second), sip);
755 Send_ALIVE_SYN_7(&(it->second), sip);
758 Send_ALIVE_SYN_8(&(it->second), sip);
762 gettimeofday(&it->second.lastSendAlive, NULL);
765 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
767 users->Unauthorize(it->second.user->GetLogin(), this);
773 if ((it->second.phase.GetPhase() == 4)
774 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
776 it->second.phase.SetPhase3();
777 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
785 //-----------------------------------------------------------------------------
786 int AUTH_IA::PacketProcessor(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
788 std::string login(user->GetLogin());
789 const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
791 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
792 map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
794 if (it == ip2user.end())
797 if (!users->FindByIPIdx(sip, &userPtr))
799 if (userPtr->GetID() != user->GetID())
801 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
802 userPtr->GetLogin().c_str(),
803 inet_ntostring(sip).c_str(),
805 WriteServLog("IP address already in use by user '%s'. IP %s, login: '%s'",
806 userPtr->GetLogin().c_str(),
807 inet_ntostring(sip).c_str(),
809 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
814 printfd(__FILE__, "Add new user '%s' from ip %s\n",
815 login.c_str(), inet_ntostring(sip).c_str());
816 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
817 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
819 #ifdef IA_PHASE_DEBUG
820 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
821 it->second.phase.SetUserLogin(login);
824 else if (user->GetID() != it->second.user->GetID())
826 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
827 it->second.user->GetLogin().c_str(),
828 inet_ntostring(sip).c_str(),
829 user->GetLogin().c_str());
830 WriteServLog("IP address already in use by user '%s'. IP %s, login: '%s'",
831 it->second.user->GetLogin().c_str(),
832 inet_ntostring(sip).c_str(),
833 user->GetLogin().c_str());
834 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
838 IA_USER * iaUser = &(it->second);
840 if (iaUser->password != user->GetProperty().password.Get())
842 InitEncrypt(&iaUser->ctx, user->GetProperty().password.Get());
843 iaUser->password = user->GetProperty().password.Get();
847 Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
849 char packetName[IA_MAX_TYPE_LEN];
850 strncpy(packetName, buff + 4, IA_MAX_TYPE_LEN);
851 packetName[IA_MAX_TYPE_LEN - 1] = 0;
853 map<string, int>::iterator pi(packetTypes.find(packetName));
854 if (pi == packetTypes.end())
856 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
857 printfd(__FILE__, "Login or password is wrong!\n");
858 WriteServLog("User's connect failed. User: '%s', ip %s. Wrong login or password",
860 inet_ntostring(sip).c_str());
865 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
867 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
868 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
869 inet_ntostring(sip).c_str());
870 WriteServLog("Login %s already in use from ip %s. IP %s",
872 inet_ntostring(user->GetCurrIP()).c_str(),
873 inet_ntostring(sip).c_str());
874 SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
885 if (Process_CONN_SYN_6((CONN_SYN_6 *)(buff - offset), &(it->second), sip))
887 return Send_CONN_SYN_ACK_6(iaUser, sip);
889 if (Process_CONN_SYN_7((CONN_SYN_7 *)(buff - offset), &(it->second), sip))
891 return Send_CONN_SYN_ACK_7(iaUser, sip);
893 if (Process_CONN_SYN_8((CONN_SYN_8 *)(buff - offset), &(it->second), sip))
895 return Send_CONN_SYN_ACK_8(iaUser, sip);
903 if (Process_CONN_ACK_6((CONN_ACK_6 *)(buff - offset), iaUser, sip))
905 return Send_ALIVE_SYN_6(iaUser, sip);
907 if (Process_CONN_ACK_7((CONN_ACK_6 *)(buff - offset), iaUser, sip))
909 return Send_ALIVE_SYN_7(iaUser, sip);
911 if (Process_CONN_ACK_8((CONN_ACK_8 *)(buff - offset), iaUser, sip))
913 return Send_ALIVE_SYN_8(iaUser, sip);
921 return Process_ALIVE_ACK_6((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
923 return Process_ALIVE_ACK_7((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
925 return Process_ALIVE_ACK_8((ALIVE_ACK_8 *)(buff - offset), iaUser, sip);
933 if (Process_DISCONN_SYN_6((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
935 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
937 if (Process_DISCONN_SYN_7((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
939 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
941 if (Process_DISCONN_SYN_8((DISCONN_SYN_8 *)(buff - offset), iaUser, sip))
943 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
951 if (Process_DISCONN_ACK_6((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
953 return Send_FIN_6(iaUser, sip, it);
955 if (Process_DISCONN_ACK_7((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
957 return Send_FIN_7(iaUser, sip, it);
959 if (Process_DISCONN_ACK_8((DISCONN_ACK_8 *)(buff - offset), iaUser, sip, it))
961 return Send_FIN_8(iaUser, sip, it);
968 //-----------------------------------------------------------------------------
969 void AUTH_IA::DelUser(USER_PTR u)
972 uint32_t ip = u->GetCurrIP();
977 map<uint32_t, IA_USER>::iterator it;
979 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
980 it = ip2user.find(ip);
981 if (it == ip2user.end())
984 printfd(__FILE__, "Nothing to delete\n");
988 if (it->second.user == u)
990 printfd(__FILE__, "User removed!\n");
991 users->Unauthorize(u->GetLogin(), this);
995 //-----------------------------------------------------------------------------
996 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
998 struct sockaddr_in sendAddr;
1005 memset(&err, 0, sizeof(ERR));
1007 sendAddr.sin_family = AF_INET;
1008 sendAddr.sin_port = htons(port);
1009 sendAddr.sin_addr.s_addr = ip;
1012 strncpy((char*)err.type, "ERR", 16);
1013 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1019 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1020 printfd(__FILE__, "SendError %d bytes sent\n", res);
1025 memset(&err8, 0, sizeof(ERR_8));
1027 sendAddr.sin_family = AF_INET;
1028 sendAddr.sin_port = htons(port);
1029 sendAddr.sin_addr.s_addr = ip;
1032 strncpy((char*)err8.type, "ERR", 16);
1033 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1036 SwapBytes(err8.len);
1039 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1040 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1046 //-----------------------------------------------------------------------------
1047 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
1049 struct sockaddr_in sendAddr;
1051 sendAddr.sin_family = AF_INET;
1052 sendAddr.sin_port = htons(port);
1053 sendAddr.sin_addr.s_addr = ip;
1055 int res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1062 //-----------------------------------------------------------------------------
1063 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1065 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1067 map<uint32_t, IA_USER>::iterator it;
1069 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1070 it = ip2user.find(ip);
1071 if (it == ip2user.end())
1073 errorStr = "Unknown user.";
1076 it->second.messagesToSend.push_back(msg);
1079 //-----------------------------------------------------------------------------
1080 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1082 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1085 memset(&info, 0, sizeof(INFO_6));
1088 strncpy((char*)info.type, "INFO", 16);
1089 info.infoType = 'I';
1090 strncpy((char*)info.text, msg.text.c_str(), 235);
1093 size_t len = info.len;
1095 SwapBytes(info.len);
1099 memcpy(buffer, &info, sizeof(INFO_6));
1100 Encrypt(&user.ctx, buffer, buffer, len / 8);
1101 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1103 //-----------------------------------------------------------------------------
1104 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1106 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1109 memset(&info, 0, sizeof(INFO_7));
1112 strncpy((char*)info.type, "INFO_7", 16);
1113 info.infoType = msg.header.type;
1114 info.showTime = msg.header.showTime;
1115 info.sendTime = msg.header.creationTime;
1117 size_t len = info.len;
1119 SwapBytes(info.len);
1120 SwapBytes(info.sendTime);
1123 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1124 info.text[MAX_MSG_LEN - 1] = 0;
1127 memcpy(buffer, &info, sizeof(INFO_7));
1129 Encrypt(&user.ctx, buffer, buffer, len / 8);
1130 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1132 //-----------------------------------------------------------------------------
1133 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1135 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1138 memset(&info, 0, sizeof(INFO_8));
1141 strncpy((char*)info.type, "INFO_8", 16);
1142 info.infoType = msg.header.type;
1143 info.showTime = msg.header.showTime;
1144 info.sendTime = msg.header.creationTime;
1146 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1147 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1149 size_t len = info.len;
1151 SwapBytes(info.len);
1152 SwapBytes(info.sendTime);
1156 memcpy(buffer, &info, sizeof(INFO_8));
1158 Encrypt(&user.ctx, buffer, buffer, len / 8);
1159 return Send(ip, user.port, buffer, len);
1161 //-----------------------------------------------------------------------------
1162 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1164 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1167 enabledDirs = 0xFFffFFff;
1169 iaUser->phase.SetPhase2();
1170 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1173 //-----------------------------------------------------------------------------
1174 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1176 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1178 //-----------------------------------------------------------------------------
1179 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1182 SwapBytes(connSyn->dirs);
1184 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, sip);
1185 enabledDirs = connSyn->dirs;
1188 //-----------------------------------------------------------------------------
1189 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1192 SwapBytes(connAck->len);
1193 SwapBytes(connAck->rnd);
1195 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1197 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1199 iaUser->phase.UpdateTime();
1201 iaUser->lastSendAlive = iaUser->phase.GetTime();
1202 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1204 iaUser->phase.SetPhase3();
1205 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1210 errorStr = iaUser->user->GetStrError();
1211 iaUser->phase.SetPhase1();
1213 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1217 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1220 //-----------------------------------------------------------------------------
1221 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1223 return Process_CONN_ACK_6(connAck, iaUser, sip);
1225 //-----------------------------------------------------------------------------
1226 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1229 SwapBytes(connAck->len);
1230 SwapBytes(connAck->rnd);
1232 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1234 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1236 iaUser->phase.UpdateTime();
1237 iaUser->lastSendAlive = iaUser->phase.GetTime();
1238 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1240 iaUser->phase.SetPhase3();
1241 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1246 errorStr = iaUser->user->GetStrError();
1247 iaUser->phase.SetPhase1();
1249 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1253 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1256 //-----------------------------------------------------------------------------
1257 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1260 SwapBytes(aliveAck->len);
1261 SwapBytes(aliveAck->rnd);
1263 printfd(__FILE__, "ALIVE_ACK_6\n");
1264 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1266 iaUser->phase.UpdateTime();
1268 iaUser->aliveSent = false;
1273 //-----------------------------------------------------------------------------
1274 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1276 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1278 //-----------------------------------------------------------------------------
1279 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1282 SwapBytes(aliveAck->len);
1283 SwapBytes(aliveAck->rnd);
1285 printfd(__FILE__, "ALIVE_ACK_8\n");
1286 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1288 iaUser->phase.UpdateTime();
1290 iaUser->aliveSent = false;
1295 //-----------------------------------------------------------------------------
1296 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1298 printfd(__FILE__, "DISCONN_SYN_6\n");
1299 if (iaUser->phase.GetPhase() != 3)
1301 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1302 errorStr = "Incorrect request DISCONN_SYN";
1306 iaUser->phase.SetPhase4();
1307 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1311 //-----------------------------------------------------------------------------
1312 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1314 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1316 //-----------------------------------------------------------------------------
1317 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t)
1319 if (iaUser->phase.GetPhase() != 3)
1321 errorStr = "Incorrect request DISCONN_SYN";
1322 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1326 iaUser->phase.SetPhase4();
1327 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1331 //-----------------------------------------------------------------------------
1332 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1335 map<uint32_t, IA_USER>::iterator)
1338 SwapBytes(disconnAck->len);
1339 SwapBytes(disconnAck->rnd);
1341 printfd(__FILE__, "DISCONN_ACK_6\n");
1342 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1344 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1350 //-----------------------------------------------------------------------------
1351 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1353 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1355 //-----------------------------------------------------------------------------
1356 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, map<uint32_t, IA_USER>::iterator)
1359 SwapBytes(disconnAck->len);
1360 SwapBytes(disconnAck->rnd);
1362 printfd(__FILE__, "DISCONN_ACK_8\n");
1363 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1365 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1371 //-----------------------------------------------------------------------------
1372 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1374 //+++ Fill static data in connSynAck +++
1375 // TODO Move this code. It must be executed only once
1376 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1377 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1378 for (int j = 0; j < DIR_NUM; j++)
1380 strncpy((char*)connSynAck6.dirName[j],
1381 stgSettings->GetDirName(j).c_str(),
1384 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1386 //--- Fill static data in connSynAck ---
1388 iaUser->rnd = random();
1389 connSynAck6.rnd = iaUser->rnd;
1391 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1392 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1395 SwapBytes(connSynAck6.len);
1396 SwapBytes(connSynAck6.rnd);
1397 SwapBytes(connSynAck6.userTimeOut);
1398 SwapBytes(connSynAck6.aliveDelay);
1401 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1402 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1404 //-----------------------------------------------------------------------------
1405 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1407 return Send_CONN_SYN_ACK_6(iaUser, sip);
1409 //-----------------------------------------------------------------------------
1410 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1412 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1413 connSynAck8.hdr.protoVer[0] = 0;
1414 connSynAck8.hdr.protoVer[1] = 8;
1416 //+++ Fill static data in connSynAck +++
1417 // TODO Move this code. It must be executed only once
1418 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1419 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1420 for (int j = 0; j < DIR_NUM; j++)
1422 strncpy((char*)connSynAck8.dirName[j],
1423 stgSettings->GetDirName(j).c_str(),
1426 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1428 //--- Fill static data in connSynAck ---
1430 iaUser->rnd = random();
1431 connSynAck8.rnd = iaUser->rnd;
1433 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1434 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1437 SwapBytes(connSynAck8.len);
1438 SwapBytes(connSynAck8.rnd);
1439 SwapBytes(connSynAck8.userTimeOut);
1440 SwapBytes(connSynAck8.aliveDelay);
1443 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1444 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1446 //-----------------------------------------------------------------------------
1447 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1449 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1450 aliveSyn6.rnd = iaUser->rnd = random();
1452 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1454 for (int i = 0; i < DIR_NUM; i++)
1456 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1457 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1459 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1460 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1464 int dn = iaSettings.GetFreeMbShowType();
1465 const TARIFF * tf = iaUser->user->GetTariff();
1469 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1476 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1480 double fmb = iaUser->user->GetProperty().freeMb;
1481 fmb = fmb < 0 ? 0 : fmb;
1482 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1487 if (freeMbNone == iaSettings.GetFreeMbShowType())
1489 aliveSyn6.freeMb[0] = 0;
1493 double fmb = iaUser->user->GetProperty().freeMb;
1494 fmb = fmb < 0 ? 0 : fmb;
1495 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1500 if (iaUser->aliveSent)
1502 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1504 iaUser->aliveSent = true;
1507 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1508 if (!stgSettings->GetShowFeeInCash())
1509 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1512 SwapBytes(aliveSyn6.len);
1513 SwapBytes(aliveSyn6.rnd);
1514 SwapBytes(aliveSyn6.cash);
1515 for (int i = 0; i < DIR_NUM; ++i)
1517 SwapBytes(aliveSyn6.mu[i]);
1518 SwapBytes(aliveSyn6.md[i]);
1519 SwapBytes(aliveSyn6.su[i]);
1520 SwapBytes(aliveSyn6.sd[i]);
1524 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1525 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1527 //-----------------------------------------------------------------------------
1528 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1530 return Send_ALIVE_SYN_6(iaUser, sip);
1532 //-----------------------------------------------------------------------------
1533 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1535 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1536 aliveSyn8.hdr.protoVer[0] = 0;
1537 aliveSyn8.hdr.protoVer[1] = 8;
1539 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1540 aliveSyn8.rnd = iaUser->rnd = random();
1542 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1544 for (int i = 0; i < DIR_NUM; i++)
1546 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1547 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1549 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1550 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1554 int dn = iaSettings.GetFreeMbShowType();
1558 const TARIFF * tf = iaUser->user->GetTariff();
1559 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1566 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1570 double fmb = iaUser->user->GetProperty().freeMb;
1571 fmb = fmb < 0 ? 0 : fmb;
1572 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1577 if (freeMbNone == iaSettings.GetFreeMbShowType())
1579 aliveSyn8.freeMb[0] = 0;
1583 double fmb = iaUser->user->GetProperty().freeMb;
1584 fmb = fmb < 0 ? 0 : fmb;
1585 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1590 if (iaUser->aliveSent)
1592 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1594 iaUser->aliveSent = true;
1597 const TARIFF * tf = iaUser->user->GetTariff();
1599 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1600 if (!stgSettings->GetShowFeeInCash())
1601 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1604 SwapBytes(aliveSyn8.len);
1605 SwapBytes(aliveSyn8.rnd);
1606 SwapBytes(aliveSyn8.cash);
1607 SwapBytes(aliveSyn8.status);
1608 for (int i = 0; i < DIR_NUM; ++i)
1610 SwapBytes(aliveSyn8.mu[i]);
1611 SwapBytes(aliveSyn8.md[i]);
1612 SwapBytes(aliveSyn8.su[i]);
1613 SwapBytes(aliveSyn8.sd[i]);
1617 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1618 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1620 //-----------------------------------------------------------------------------
1621 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1623 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1624 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1625 disconnSynAck6.rnd = iaUser->rnd = random();
1628 SwapBytes(disconnSynAck6.len);
1629 SwapBytes(disconnSynAck6.rnd);
1632 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1633 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1635 //-----------------------------------------------------------------------------
1636 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1638 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1640 //-----------------------------------------------------------------------------
1641 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1643 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1644 disconnSynAck8.hdr.protoVer[0] = 0;
1645 disconnSynAck8.hdr.protoVer[1] = 8;
1647 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1648 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1649 disconnSynAck8.rnd = iaUser->rnd = random();
1652 SwapBytes(disconnSynAck8.len);
1653 SwapBytes(disconnSynAck8.rnd);
1656 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1657 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1659 //-----------------------------------------------------------------------------
1660 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1662 fin6.len = Min8(sizeof(FIN_6));
1663 strcpy((char*)fin6.type, "FIN");
1664 strcpy((char*)fin6.ok, "OK");
1667 SwapBytes(fin6.len);
1670 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1672 users->Unauthorize(iaUser->login, this);
1674 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1680 //-----------------------------------------------------------------------------
1681 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1683 return Send_FIN_6(iaUser, sip, it);
1685 //-----------------------------------------------------------------------------
1686 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1688 strcpy((char*)fin8.hdr.magic, IA_ID);
1689 fin8.hdr.protoVer[0] = 0;
1690 fin8.hdr.protoVer[1] = 8;
1692 fin8.len = Min8(sizeof(FIN_8));
1693 strcpy((char*)fin8.type, "FIN");
1694 strcpy((char*)fin8.ok, "OK");
1697 SwapBytes(fin8.len);
1700 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1702 users->Unauthorize(iaUser->login, this);
1704 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1710 //-----------------------------------------------------------------------------
1712 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
1714 unsigned char keyL[PASSWD_LEN];
1715 memset(keyL, 0, PASSWD_LEN);
1716 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1717 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1719 //-----------------------------------------------------------------------------
1721 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1723 for (int i = 0; i < len8; i++)
1724 DecodeString(dst + i * 8, src + i * 8, ctx);
1726 //-----------------------------------------------------------------------------
1728 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1730 for (int i = 0; i < len8; i++)
1731 EncodeString(dst + i * 8, src + i * 8, ctx);