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
42 #include "stg/common.h"
43 #include "stg/locker.h"
44 #include "stg/tariff.h"
45 #include "stg/user_property.h"
46 #include "stg/settings.h"
47 #include "stg/plugin_creator.h"
48 #include "inetaccess.h"
50 extern volatile const time_t stgTime;
52 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password);
53 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
54 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
56 //-----------------------------------------------------------------------------
57 //-----------------------------------------------------------------------------
58 //-----------------------------------------------------------------------------
59 PLUGIN_CREATOR<AUTH_IA> iac;
60 //-----------------------------------------------------------------------------
61 //-----------------------------------------------------------------------------
62 //-----------------------------------------------------------------------------
65 return iac.GetPlugin();
67 //-----------------------------------------------------------------------------
68 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
70 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
75 freeMbShowType(freeMbCash)
78 //-----------------------------------------------------------------------------
79 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
83 vector<PARAM_VALUE>::const_iterator pvi;
84 ///////////////////////////
86 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
87 if (pvi == s.moduleParams.end())
89 errorStr = "Parameter \'Port\' not found.";
90 printfd(__FILE__, "Parameter 'Port' not found\n");
93 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
95 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
96 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
100 ///////////////////////////
101 pv.param = "UserDelay";
102 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
103 if (pvi == s.moduleParams.end())
105 errorStr = "Parameter \'UserDelay\' not found.";
106 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
110 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
112 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
113 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
116 ///////////////////////////
117 pv.param = "UserTimeout";
118 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
119 if (pvi == s.moduleParams.end())
121 errorStr = "Parameter \'UserTimeout\' not found.";
122 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
126 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
128 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
129 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
132 /////////////////////////////////////////////////////////////
136 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
137 if (pvi == s.moduleParams.end())
139 errorStr = "Parameter \'FreeMb\' not found.";
140 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
143 freeMbType = pvi->value[0];
145 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
147 freeMbShowType = freeMbCash;
149 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
151 freeMbShowType = freeMbNone;
153 else if (!str2x(freeMbType.c_str(), n))
155 if (n < 0 || n >= DIR_NUM)
157 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
158 printfd(__FILE__, "%s\n", errorStr.c_str());
161 freeMbShowType = (FREEMB)(freeMb0 + n);
165 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
166 printfd(__FILE__, "%s\n", errorStr.c_str());
169 /////////////////////////////////////////////////////////////
172 //-----------------------------------------------------------------------------
173 //-----------------------------------------------------------------------------
174 //-----------------------------------------------------------------------------
175 #ifdef IA_PHASE_DEBUG
181 gettimeofday(&phaseTime, NULL);
188 gettimeofday(&phaseTime, NULL);
191 //-----------------------------------------------------------------------------
192 IA_PHASE::~IA_PHASE()
194 #ifdef IA_PHASE_DEBUG
195 flog = fopen(log.c_str(), "at");
198 fprintf(flog, "IA %s D\n", login.c_str());
203 //-----------------------------------------------------------------------------
204 #ifdef IA_PHASE_DEBUG
205 void IA_PHASE::SetLogFileName(const string & logFileName)
207 log = logFileName + ".ia.log";
209 //-----------------------------------------------------------------------------
210 void IA_PHASE::SetUserLogin(const string & login)
212 IA_PHASE::login = login;
214 //-----------------------------------------------------------------------------
215 void IA_PHASE::WritePhaseChange(int newPhase)
218 gettimeofday(&newPhaseTime, NULL);
219 flog = fopen(log.c_str(), "at");
222 string action = newPhase == phase ? "U" : "C";
223 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
224 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
225 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
235 //-----------------------------------------------------------------------------
236 void IA_PHASE::SetPhase1()
238 #ifdef IA_PHASE_DEBUG
242 gettimeofday(&phaseTime, NULL);
244 //-----------------------------------------------------------------------------
245 void IA_PHASE::SetPhase2()
247 #ifdef IA_PHASE_DEBUG
251 gettimeofday(&phaseTime, NULL);
253 //-----------------------------------------------------------------------------
254 void IA_PHASE::SetPhase3()
256 #ifdef IA_PHASE_DEBUG
260 gettimeofday(&phaseTime, NULL);
262 //-----------------------------------------------------------------------------
263 void IA_PHASE::SetPhase4()
265 #ifdef IA_PHASE_DEBUG
269 gettimeofday(&phaseTime, NULL);
271 //-----------------------------------------------------------------------------
272 void IA_PHASE::SetPhase5()
274 #ifdef IA_PHASE_DEBUG
278 gettimeofday(&phaseTime, NULL);
280 //-----------------------------------------------------------------------------
281 int IA_PHASE::GetPhase() const
285 //-----------------------------------------------------------------------------
286 void IA_PHASE::UpdateTime()
288 #ifdef IA_PHASE_DEBUG
289 WritePhaseChange(phase);
291 gettimeofday(&phaseTime, NULL);
293 //-----------------------------------------------------------------------------
294 const UTIME & IA_PHASE::GetTime() const
298 //-----------------------------------------------------------------------------
299 //-----------------------------------------------------------------------------
300 //-----------------------------------------------------------------------------
308 isRunningRunTimeouter(false),
325 enabledDirs(0xFFffFFff),
326 onDelUserNotifier(*this),
327 logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
329 InitEncrypt(&ctxS, "pr7Hhen");
331 pthread_mutexattr_t attr;
332 pthread_mutexattr_init(&attr);
333 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
334 pthread_mutex_init(&mutex, &attr);
336 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
337 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
338 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
339 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
340 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
341 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
342 memset(&fin6, 0, sizeof(FIN_6));
343 memset(&fin8, 0, sizeof(FIN_8));
345 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
346 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
347 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
348 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
349 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
350 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
351 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
352 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
353 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
354 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
355 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
356 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
357 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
358 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
359 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
360 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
361 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
362 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
364 packetTypes["CONN_SYN"] = CONN_SYN_N;
365 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
366 packetTypes["CONN_ACK"] = CONN_ACK_N;
367 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
368 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
369 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
370 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
371 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
372 packetTypes["FIN"] = FIN_N;
373 packetTypes["ERR"] = ERROR_N;
375 //-----------------------------------------------------------------------------
378 pthread_mutex_destroy(&mutex);
380 //-----------------------------------------------------------------------------
383 users->AddNotifierUserDel(&onDelUserNotifier);
393 if (pthread_create(&recvThread, NULL, Run, this))
395 errorStr = "Cannot create thread.";
396 printfd(__FILE__, "Cannot create recv thread\n");
397 logger("Cannot create recv thread.");
402 if (!isRunningRunTimeouter)
404 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
406 errorStr = "Cannot create thread.";
407 printfd(__FILE__, "Cannot create timeouter thread\n");
408 logger("Cannot create timeouter thread.");
415 //-----------------------------------------------------------------------------
426 UnauthorizeUser(this)
431 //5 seconds to thread stops itself
432 for (int i = 0; i < 25 && isRunningRun; i++)
434 struct timespec ts = {0, 200000000};
435 nanosleep(&ts, NULL);
441 if (isRunningRunTimeouter)
443 //5 seconds to thread stops itself
444 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
446 struct timespec ts = {0, 200000000};
447 nanosleep(&ts, NULL);
451 users->DelNotifierUserDel(&onDelUserNotifier);
453 if (isRunningRun || isRunningRunTimeouter)
456 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
459 //-----------------------------------------------------------------------------
460 void * AUTH_IA::Run(void * d)
463 sigfillset(&signalSet);
464 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
466 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
468 ia->isRunningRun = true;
472 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
476 ia->RecvData(buffer, sizeof(buffer));
477 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
480 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
481 TouchFile(monFile.c_str());
485 ia->isRunningRun = false;
488 //-----------------------------------------------------------------------------
489 void * AUTH_IA::RunTimeouter(void * d)
492 sigfillset(&signalSet);
493 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
495 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
497 ia->isRunningRunTimeouter = true;
500 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
503 struct timespec ts = {0, 20000000};
504 nanosleep(&ts, NULL);
506 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
507 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
509 TouchFile(monFile.c_str());
513 ia->isRunningRunTimeouter = false;
516 //-----------------------------------------------------------------------------
517 int AUTH_IA::ParseSettings()
519 int ret = iaSettings.ParseSettings(settings);
521 errorStr = iaSettings.GetStrError();
524 //-----------------------------------------------------------------------------
525 int AUTH_IA::PrepareNet()
527 struct sockaddr_in listenAddr;
529 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
531 if (listenSocket < 0)
533 errorStr = "Cannot create socket.";
534 logger("Cannot create a socket: %s", strerror(errno));
538 listenAddr.sin_family = AF_INET;
539 listenAddr.sin_port = htons(iaSettings.GetUserPort());
540 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
542 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
544 errorStr = "AUTH_IA: Bind failed.";
545 logger("Cannot bind the socket: %s", strerror(errno));
551 //-----------------------------------------------------------------------------
552 int AUTH_IA::FinalizeNet()
557 //-----------------------------------------------------------------------------
558 int AUTH_IA::RecvData(char * buffer, int bufferSize)
560 if (!WaitPackets(listenSocket)) // Timeout
565 struct sockaddr_in outerAddr;
566 socklen_t outerAddrLen(sizeof(outerAddr));
567 int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
574 if (dataLen <= 0) // Error
578 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
579 logger("recvfrom error: %s", strerror(errno));
589 if (CheckHeader(buffer, &protoVer))
592 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
593 memset(login, 0, PASSWD_LEN);
595 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
597 uint32_t sip = outerAddr.sin_addr.s_addr;
598 uint16_t sport = htons(outerAddr.sin_port);
601 if (users->FindByName(login, &user))
603 logger("User's connect failed: user '%s' not found. IP %s",
605 inet_ntostring(sip).c_str());
606 printfd(__FILE__, "User '%s' NOT found!\n", login);
607 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ!");
611 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
613 if (user->GetProperty().disabled.Get())
615 logger("Cannont authorize '%s', user is disabled.", login);
616 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
620 if (user->GetProperty().passive.Get())
622 logger("Cannont authorize '%s', user is passive.", login);
623 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
627 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
629 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
630 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
631 logger("User %s. IP address is incorrect. IP %s",
632 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
633 SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
637 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
639 //-----------------------------------------------------------------------------
640 int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
642 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
644 //SendError(userIP, updateMsg);
645 printfd(__FILE__, "update needed - IA_ID\n");
646 //SendError(userIP, "Incorrect header!");
650 if (buffer[6] != 0) //proto[0] shoud be 0
652 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
653 //SendError(userIP, updateMsg);
660 //SendError(userIP, updateMsg);
661 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
666 *protoVer = buffer[7];
670 //-----------------------------------------------------------------------------
671 int AUTH_IA::Timeouter()
673 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
675 map<uint32_t, IA_USER>::iterator it;
676 it = ip2user.begin();
679 while (it != ip2user.end())
683 static UTIME currTime;
684 gettimeofday(&currTime, NULL);
686 if ((it->second.phase.GetPhase() == 2)
687 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
689 it->second.phase.SetPhase1();
690 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
695 if (it->second.phase.GetPhase() == 3)
697 if (!it->second.messagesToSend.empty())
699 if (it->second.protoVer == 6)
700 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
702 if (it->second.protoVer == 7)
703 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
705 if (it->second.protoVer == 8)
706 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
708 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
711 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
713 switch (it->second.protoVer)
716 Send_ALIVE_SYN_6(&(it->second), sip);
719 Send_ALIVE_SYN_7(&(it->second), sip);
722 Send_ALIVE_SYN_8(&(it->second), sip);
726 gettimeofday(&it->second.lastSendAlive, NULL);
729 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
731 users->Unauthorize(it->second.user->GetLogin(), this);
737 if ((it->second.phase.GetPhase() == 4)
738 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
740 it->second.phase.SetPhase3();
741 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
749 //-----------------------------------------------------------------------------
750 int AUTH_IA::PacketProcessor(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
752 std::string login(user->GetLogin());
753 const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
755 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
756 map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
758 if (it == ip2user.end())
761 if (!users->FindByIPIdx(sip, &userPtr))
763 if (userPtr->GetID() != user->GetID())
765 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
766 userPtr->GetLogin().c_str(),
767 inet_ntostring(sip).c_str(),
769 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
770 userPtr->GetLogin().c_str(),
771 inet_ntostring(sip).c_str(),
773 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
778 printfd(__FILE__, "Add new user '%s' from ip %s\n",
779 login.c_str(), inet_ntostring(sip).c_str());
780 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
781 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
783 #ifdef IA_PHASE_DEBUG
784 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
785 it->second.phase.SetUserLogin(login);
788 else if (user->GetID() != it->second.user->GetID())
790 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
791 it->second.user->GetLogin().c_str(),
792 inet_ntostring(sip).c_str(),
793 user->GetLogin().c_str());
794 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
795 it->second.user->GetLogin().c_str(),
796 inet_ntostring(sip).c_str(),
797 user->GetLogin().c_str());
798 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
802 IA_USER * iaUser = &(it->second);
804 if (iaUser->password != user->GetProperty().password.Get())
806 InitEncrypt(&iaUser->ctx, user->GetProperty().password.Get());
807 iaUser->password = user->GetProperty().password.Get();
811 Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
813 char packetName[IA_MAX_TYPE_LEN];
814 strncpy(packetName, buff + 4, IA_MAX_TYPE_LEN);
815 packetName[IA_MAX_TYPE_LEN - 1] = 0;
817 map<string, int>::iterator pi(packetTypes.find(packetName));
818 if (pi == packetTypes.end())
820 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
821 printfd(__FILE__, "Login or password is wrong!\n");
822 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
824 inet_ntostring(sip).c_str());
829 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
831 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
832 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
833 inet_ntostring(sip).c_str());
834 logger("Login '%s' is already in use from ip %s. IP %s",
836 inet_ntostring(user->GetCurrIP()).c_str(),
837 inet_ntostring(sip).c_str());
838 SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
849 if (Process_CONN_SYN_6((CONN_SYN_6 *)(buff - offset), &(it->second), sip))
851 return Send_CONN_SYN_ACK_6(iaUser, sip);
853 if (Process_CONN_SYN_7((CONN_SYN_7 *)(buff - offset), &(it->second), sip))
855 return Send_CONN_SYN_ACK_7(iaUser, sip);
857 if (Process_CONN_SYN_8((CONN_SYN_8 *)(buff - offset), &(it->second), sip))
859 return Send_CONN_SYN_ACK_8(iaUser, sip);
867 if (Process_CONN_ACK_6((CONN_ACK_6 *)(buff - offset), iaUser, sip))
869 return Send_ALIVE_SYN_6(iaUser, sip);
871 if (Process_CONN_ACK_7((CONN_ACK_6 *)(buff - offset), iaUser, sip))
873 return Send_ALIVE_SYN_7(iaUser, sip);
875 if (Process_CONN_ACK_8((CONN_ACK_8 *)(buff - offset), iaUser, sip))
877 return Send_ALIVE_SYN_8(iaUser, sip);
885 return Process_ALIVE_ACK_6((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
887 return Process_ALIVE_ACK_7((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
889 return Process_ALIVE_ACK_8((ALIVE_ACK_8 *)(buff - offset), iaUser, sip);
897 if (Process_DISCONN_SYN_6((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
899 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
901 if (Process_DISCONN_SYN_7((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
903 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
905 if (Process_DISCONN_SYN_8((DISCONN_SYN_8 *)(buff - offset), iaUser, sip))
907 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
915 if (Process_DISCONN_ACK_6((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
917 return Send_FIN_6(iaUser, sip, it);
919 if (Process_DISCONN_ACK_7((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
921 return Send_FIN_7(iaUser, sip, it);
923 if (Process_DISCONN_ACK_8((DISCONN_ACK_8 *)(buff - offset), iaUser, sip, it))
925 return Send_FIN_8(iaUser, sip, it);
932 //-----------------------------------------------------------------------------
933 void AUTH_IA::DelUser(USER_PTR u)
936 uint32_t ip = u->GetCurrIP();
941 map<uint32_t, IA_USER>::iterator it;
943 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
944 it = ip2user.find(ip);
945 if (it == ip2user.end())
948 printfd(__FILE__, "Nothing to delete\n");
952 if (it->second.user == u)
954 printfd(__FILE__, "User removed!\n");
955 users->Unauthorize(u->GetLogin(), this);
959 //-----------------------------------------------------------------------------
960 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
962 struct sockaddr_in sendAddr;
969 memset(&err, 0, sizeof(ERR));
971 sendAddr.sin_family = AF_INET;
972 sendAddr.sin_port = htons(port);
973 sendAddr.sin_addr.s_addr = ip;
976 strncpy((char*)err.type, "ERR", 16);
977 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
983 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
984 printfd(__FILE__, "SendError %d bytes sent\n", res);
989 memset(&err8, 0, sizeof(ERR_8));
991 sendAddr.sin_family = AF_INET;
992 sendAddr.sin_port = htons(port);
993 sendAddr.sin_addr.s_addr = ip;
996 strncpy((char*)err8.type, "ERR", 16);
997 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1000 SwapBytes(err8.len);
1003 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1004 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1010 //-----------------------------------------------------------------------------
1011 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
1013 struct sockaddr_in sendAddr;
1015 sendAddr.sin_family = AF_INET;
1016 sendAddr.sin_port = htons(port);
1017 sendAddr.sin_addr.s_addr = ip;
1019 int res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1026 //-----------------------------------------------------------------------------
1027 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1029 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1031 map<uint32_t, IA_USER>::iterator it;
1033 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1034 it = ip2user.find(ip);
1035 if (it == ip2user.end())
1037 errorStr = "Unknown user.";
1040 it->second.messagesToSend.push_back(msg);
1043 //-----------------------------------------------------------------------------
1044 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1046 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1049 memset(&info, 0, sizeof(INFO_6));
1052 strncpy((char*)info.type, "INFO", 16);
1053 info.infoType = 'I';
1054 strncpy((char*)info.text, msg.text.c_str(), 235);
1057 size_t len = info.len;
1059 SwapBytes(info.len);
1063 memcpy(buffer, &info, sizeof(INFO_6));
1064 Encrypt(&user.ctx, buffer, buffer, len / 8);
1065 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1067 //-----------------------------------------------------------------------------
1068 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1070 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1073 memset(&info, 0, sizeof(INFO_7));
1076 strncpy((char*)info.type, "INFO_7", 16);
1077 info.infoType = msg.header.type;
1078 info.showTime = msg.header.showTime;
1079 info.sendTime = msg.header.creationTime;
1081 size_t len = info.len;
1083 SwapBytes(info.len);
1084 SwapBytes(info.sendTime);
1087 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1088 info.text[MAX_MSG_LEN - 1] = 0;
1091 memcpy(buffer, &info, sizeof(INFO_7));
1093 Encrypt(&user.ctx, buffer, buffer, len / 8);
1094 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1096 //-----------------------------------------------------------------------------
1097 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1099 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1102 memset(&info, 0, sizeof(INFO_8));
1105 strncpy((char*)info.type, "INFO_8", 16);
1106 info.infoType = msg.header.type;
1107 info.showTime = msg.header.showTime;
1108 info.sendTime = msg.header.creationTime;
1110 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1111 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1113 size_t len = info.len;
1115 SwapBytes(info.len);
1116 SwapBytes(info.sendTime);
1120 memcpy(buffer, &info, sizeof(INFO_8));
1122 Encrypt(&user.ctx, buffer, buffer, len / 8);
1123 return Send(ip, user.port, buffer, len);
1125 //-----------------------------------------------------------------------------
1126 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1128 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1131 enabledDirs = 0xFFffFFff;
1133 iaUser->phase.SetPhase2();
1134 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1137 //-----------------------------------------------------------------------------
1138 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1140 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1142 //-----------------------------------------------------------------------------
1143 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1146 SwapBytes(connSyn->dirs);
1148 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, sip);
1149 enabledDirs = connSyn->dirs;
1152 //-----------------------------------------------------------------------------
1153 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1156 SwapBytes(connAck->len);
1157 SwapBytes(connAck->rnd);
1159 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1161 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1163 iaUser->phase.UpdateTime();
1165 iaUser->lastSendAlive = iaUser->phase.GetTime();
1166 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1168 iaUser->phase.SetPhase3();
1169 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1174 errorStr = iaUser->user->GetStrError();
1175 iaUser->phase.SetPhase1();
1177 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1181 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1184 //-----------------------------------------------------------------------------
1185 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1187 return Process_CONN_ACK_6(connAck, iaUser, sip);
1189 //-----------------------------------------------------------------------------
1190 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1193 SwapBytes(connAck->len);
1194 SwapBytes(connAck->rnd);
1196 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1198 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1200 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_8\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_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1224 SwapBytes(aliveAck->len);
1225 SwapBytes(aliveAck->rnd);
1227 printfd(__FILE__, "ALIVE_ACK_6\n");
1228 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1230 iaUser->phase.UpdateTime();
1232 iaUser->aliveSent = false;
1237 //-----------------------------------------------------------------------------
1238 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1240 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1242 //-----------------------------------------------------------------------------
1243 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1246 SwapBytes(aliveAck->len);
1247 SwapBytes(aliveAck->rnd);
1249 printfd(__FILE__, "ALIVE_ACK_8\n");
1250 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1252 iaUser->phase.UpdateTime();
1254 iaUser->aliveSent = false;
1259 //-----------------------------------------------------------------------------
1260 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1262 printfd(__FILE__, "DISCONN_SYN_6\n");
1263 if (iaUser->phase.GetPhase() != 3)
1265 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1266 errorStr = "Incorrect request DISCONN_SYN";
1270 iaUser->phase.SetPhase4();
1271 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1275 //-----------------------------------------------------------------------------
1276 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1278 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1280 //-----------------------------------------------------------------------------
1281 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t)
1283 if (iaUser->phase.GetPhase() != 3)
1285 errorStr = "Incorrect request DISCONN_SYN";
1286 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1290 iaUser->phase.SetPhase4();
1291 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1295 //-----------------------------------------------------------------------------
1296 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1299 map<uint32_t, IA_USER>::iterator)
1302 SwapBytes(disconnAck->len);
1303 SwapBytes(disconnAck->rnd);
1305 printfd(__FILE__, "DISCONN_ACK_6\n");
1306 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1308 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1314 //-----------------------------------------------------------------------------
1315 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1317 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1319 //-----------------------------------------------------------------------------
1320 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, map<uint32_t, IA_USER>::iterator)
1323 SwapBytes(disconnAck->len);
1324 SwapBytes(disconnAck->rnd);
1326 printfd(__FILE__, "DISCONN_ACK_8\n");
1327 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1329 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1335 //-----------------------------------------------------------------------------
1336 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1338 //+++ Fill static data in connSynAck +++
1339 // TODO Move this code. It must be executed only once
1340 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1341 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1342 for (int j = 0; j < DIR_NUM; j++)
1344 strncpy((char*)connSynAck6.dirName[j],
1345 stgSettings->GetDirName(j).c_str(),
1348 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1350 //--- Fill static data in connSynAck ---
1352 iaUser->rnd = random();
1353 connSynAck6.rnd = iaUser->rnd;
1355 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1356 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1359 SwapBytes(connSynAck6.len);
1360 SwapBytes(connSynAck6.rnd);
1361 SwapBytes(connSynAck6.userTimeOut);
1362 SwapBytes(connSynAck6.aliveDelay);
1365 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1366 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1368 //-----------------------------------------------------------------------------
1369 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1371 return Send_CONN_SYN_ACK_6(iaUser, sip);
1373 //-----------------------------------------------------------------------------
1374 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1376 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1377 connSynAck8.hdr.protoVer[0] = 0;
1378 connSynAck8.hdr.protoVer[1] = 8;
1380 //+++ Fill static data in connSynAck +++
1381 // TODO Move this code. It must be executed only once
1382 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1383 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1384 for (int j = 0; j < DIR_NUM; j++)
1386 strncpy((char*)connSynAck8.dirName[j],
1387 stgSettings->GetDirName(j).c_str(),
1390 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1392 //--- Fill static data in connSynAck ---
1394 iaUser->rnd = random();
1395 connSynAck8.rnd = iaUser->rnd;
1397 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1398 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1401 SwapBytes(connSynAck8.len);
1402 SwapBytes(connSynAck8.rnd);
1403 SwapBytes(connSynAck8.userTimeOut);
1404 SwapBytes(connSynAck8.aliveDelay);
1407 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1408 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1410 //-----------------------------------------------------------------------------
1411 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1413 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1414 aliveSyn6.rnd = iaUser->rnd = random();
1416 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1418 for (int i = 0; i < DIR_NUM; i++)
1420 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1421 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1423 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1424 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1428 int dn = iaSettings.GetFreeMbShowType();
1429 const TARIFF * tf = iaUser->user->GetTariff();
1433 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1438 if (std::fabs(p) < 1.0e-3)
1440 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1444 double fmb = iaUser->user->GetProperty().freeMb;
1445 fmb = fmb < 0 ? 0 : fmb;
1446 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1451 if (freeMbNone == iaSettings.GetFreeMbShowType())
1453 aliveSyn6.freeMb[0] = 0;
1457 double fmb = iaUser->user->GetProperty().freeMb;
1458 fmb = fmb < 0 ? 0 : fmb;
1459 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1464 if (iaUser->aliveSent)
1466 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1468 iaUser->aliveSent = true;
1471 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1472 if (!stgSettings->GetShowFeeInCash())
1473 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1476 SwapBytes(aliveSyn6.len);
1477 SwapBytes(aliveSyn6.rnd);
1478 SwapBytes(aliveSyn6.cash);
1479 for (int i = 0; i < DIR_NUM; ++i)
1481 SwapBytes(aliveSyn6.mu[i]);
1482 SwapBytes(aliveSyn6.md[i]);
1483 SwapBytes(aliveSyn6.su[i]);
1484 SwapBytes(aliveSyn6.sd[i]);
1488 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1489 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1491 //-----------------------------------------------------------------------------
1492 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1494 return Send_ALIVE_SYN_6(iaUser, sip);
1496 //-----------------------------------------------------------------------------
1497 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1499 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1500 aliveSyn8.hdr.protoVer[0] = 0;
1501 aliveSyn8.hdr.protoVer[1] = 8;
1503 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1504 aliveSyn8.rnd = iaUser->rnd = random();
1506 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1508 for (int i = 0; i < DIR_NUM; i++)
1510 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1511 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1513 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1514 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1518 int dn = iaSettings.GetFreeMbShowType();
1522 const TARIFF * tf = iaUser->user->GetTariff();
1523 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1528 if (std::fabs(p) < 1.0e-3)
1530 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1534 double fmb = iaUser->user->GetProperty().freeMb;
1535 fmb = fmb < 0 ? 0 : fmb;
1536 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1541 if (freeMbNone == iaSettings.GetFreeMbShowType())
1543 aliveSyn8.freeMb[0] = 0;
1547 double fmb = iaUser->user->GetProperty().freeMb;
1548 fmb = fmb < 0 ? 0 : fmb;
1549 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1554 if (iaUser->aliveSent)
1556 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1558 iaUser->aliveSent = true;
1561 const TARIFF * tf = iaUser->user->GetTariff();
1563 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1564 if (!stgSettings->GetShowFeeInCash())
1565 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1568 SwapBytes(aliveSyn8.len);
1569 SwapBytes(aliveSyn8.rnd);
1570 SwapBytes(aliveSyn8.cash);
1571 SwapBytes(aliveSyn8.status);
1572 for (int i = 0; i < DIR_NUM; ++i)
1574 SwapBytes(aliveSyn8.mu[i]);
1575 SwapBytes(aliveSyn8.md[i]);
1576 SwapBytes(aliveSyn8.su[i]);
1577 SwapBytes(aliveSyn8.sd[i]);
1581 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1582 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1584 //-----------------------------------------------------------------------------
1585 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1587 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1588 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1589 disconnSynAck6.rnd = iaUser->rnd = random();
1592 SwapBytes(disconnSynAck6.len);
1593 SwapBytes(disconnSynAck6.rnd);
1596 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1597 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1599 //-----------------------------------------------------------------------------
1600 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1602 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1604 //-----------------------------------------------------------------------------
1605 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1607 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1608 disconnSynAck8.hdr.protoVer[0] = 0;
1609 disconnSynAck8.hdr.protoVer[1] = 8;
1611 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1612 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1613 disconnSynAck8.rnd = iaUser->rnd = random();
1616 SwapBytes(disconnSynAck8.len);
1617 SwapBytes(disconnSynAck8.rnd);
1620 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1621 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1623 //-----------------------------------------------------------------------------
1624 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1626 fin6.len = Min8(sizeof(FIN_6));
1627 strcpy((char*)fin6.type, "FIN");
1628 strcpy((char*)fin6.ok, "OK");
1631 SwapBytes(fin6.len);
1634 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1636 users->Unauthorize(iaUser->login, this);
1638 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1644 //-----------------------------------------------------------------------------
1645 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1647 return Send_FIN_6(iaUser, sip, it);
1649 //-----------------------------------------------------------------------------
1650 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1652 strcpy((char*)fin8.hdr.magic, IA_ID);
1653 fin8.hdr.protoVer[0] = 0;
1654 fin8.hdr.protoVer[1] = 8;
1656 fin8.len = Min8(sizeof(FIN_8));
1657 strcpy((char*)fin8.type, "FIN");
1658 strcpy((char*)fin8.ok, "OK");
1661 SwapBytes(fin8.len);
1664 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1666 users->Unauthorize(iaUser->login, this);
1668 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1674 //-----------------------------------------------------------------------------
1676 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
1678 unsigned char keyL[PASSWD_LEN];
1679 memset(keyL, 0, PASSWD_LEN);
1680 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1681 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1683 //-----------------------------------------------------------------------------
1685 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1687 for (int i = 0; i < len8; i++)
1688 DecodeString(dst + i * 8, src + i * 8, ctx);
1690 //-----------------------------------------------------------------------------
1692 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1694 for (int i = 0; i < len8; i++)
1695 EncodeString(dst + i * 8, src + i * 8, ctx);