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 time_t stgTime;
52 //-----------------------------------------------------------------------------
53 //-----------------------------------------------------------------------------
54 //-----------------------------------------------------------------------------
57 PLUGIN_CREATOR<AUTH_IA> iac;
59 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
60 void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8);
61 void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8);
64 extern "C" PLUGIN * GetPlugin();
65 //-----------------------------------------------------------------------------
66 //-----------------------------------------------------------------------------
67 //-----------------------------------------------------------------------------
70 return iac.GetPlugin();
72 //-----------------------------------------------------------------------------
73 //-----------------------------------------------------------------------------
74 //-----------------------------------------------------------------------------
75 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
80 freeMbShowType(freeMbCash)
83 //-----------------------------------------------------------------------------
84 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
88 std::vector<PARAM_VALUE>::const_iterator pvi;
89 ///////////////////////////
91 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
92 if (pvi == s.moduleParams.end())
94 errorStr = "Parameter \'Port\' not found.";
95 printfd(__FILE__, "Parameter 'Port' not found\n");
98 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
100 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
101 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
104 port = static_cast<uint16_t>(p);
105 ///////////////////////////
106 pv.param = "UserDelay";
107 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
108 if (pvi == s.moduleParams.end())
110 errorStr = "Parameter \'UserDelay\' not found.";
111 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
115 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
117 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
118 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
121 ///////////////////////////
122 pv.param = "UserTimeout";
123 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
124 if (pvi == s.moduleParams.end())
126 errorStr = "Parameter \'UserTimeout\' not found.";
127 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
131 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
133 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
134 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
137 /////////////////////////////////////////////////////////////
138 std::string freeMbType;
141 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
142 if (pvi == s.moduleParams.end())
144 errorStr = "Parameter \'FreeMb\' not found.";
145 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
148 freeMbType = pvi->value[0];
150 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
152 freeMbShowType = freeMbCash;
154 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
156 freeMbShowType = freeMbNone;
158 else if (!str2x(freeMbType.c_str(), n))
160 if (n < 0 || n >= DIR_NUM)
162 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
163 printfd(__FILE__, "%s\n", errorStr.c_str());
166 freeMbShowType = (FREEMB)(freeMb0 + n);
170 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
171 printfd(__FILE__, "%s\n", errorStr.c_str());
174 /////////////////////////////////////////////////////////////
177 //-----------------------------------------------------------------------------
178 //-----------------------------------------------------------------------------
179 //-----------------------------------------------------------------------------
180 #ifdef IA_PHASE_DEBUG
186 gettimeofday(&phaseTime, NULL);
193 gettimeofday(&phaseTime, NULL);
196 //-----------------------------------------------------------------------------
197 IA_PHASE::~IA_PHASE()
199 #ifdef IA_PHASE_DEBUG
200 flog = fopen(log.c_str(), "at");
203 fprintf(flog, "IA %s D\n", login.c_str());
208 //-----------------------------------------------------------------------------
209 #ifdef IA_PHASE_DEBUG
210 void IA_PHASE::SetLogFileName(const string & logFileName)
212 log = logFileName + ".ia.log";
214 //-----------------------------------------------------------------------------
215 void IA_PHASE::SetUserLogin(const string & login)
217 IA_PHASE::login = login;
219 //-----------------------------------------------------------------------------
220 void IA_PHASE::WritePhaseChange(int newPhase)
223 gettimeofday(&newPhaseTime, NULL);
224 flog = fopen(log.c_str(), "at");
227 string action = newPhase == phase ? "U" : "C";
228 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
229 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
230 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
240 //-----------------------------------------------------------------------------
241 void IA_PHASE::SetPhase1()
243 #ifdef IA_PHASE_DEBUG
247 gettimeofday(&phaseTime, NULL);
249 //-----------------------------------------------------------------------------
250 void IA_PHASE::SetPhase2()
252 #ifdef IA_PHASE_DEBUG
256 gettimeofday(&phaseTime, NULL);
258 //-----------------------------------------------------------------------------
259 void IA_PHASE::SetPhase3()
261 #ifdef IA_PHASE_DEBUG
265 gettimeofday(&phaseTime, NULL);
267 //-----------------------------------------------------------------------------
268 void IA_PHASE::SetPhase4()
270 #ifdef IA_PHASE_DEBUG
274 gettimeofday(&phaseTime, NULL);
276 //-----------------------------------------------------------------------------
277 void IA_PHASE::SetPhase5()
279 #ifdef IA_PHASE_DEBUG
283 gettimeofday(&phaseTime, NULL);
285 //-----------------------------------------------------------------------------
286 int IA_PHASE::GetPhase() const
290 //-----------------------------------------------------------------------------
291 void IA_PHASE::UpdateTime()
293 #ifdef IA_PHASE_DEBUG
294 WritePhaseChange(phase);
296 gettimeofday(&phaseTime, NULL);
298 //-----------------------------------------------------------------------------
299 const UTIME & IA_PHASE::GetTime() const
303 //-----------------------------------------------------------------------------
304 //-----------------------------------------------------------------------------
305 //-----------------------------------------------------------------------------
313 isRunningRunTimeouter(false),
330 enabledDirs(0xFFffFFff),
331 onDelUserNotifier(*this),
332 logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
334 InitEncrypt(&ctxS, "pr7Hhen");
336 pthread_mutexattr_t attr;
337 pthread_mutexattr_init(&attr);
338 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
339 pthread_mutex_init(&mutex, &attr);
341 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
342 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
343 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
344 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
345 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
346 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
347 memset(&fin6, 0, sizeof(FIN_6));
348 memset(&fin8, 0, sizeof(FIN_8));
350 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
351 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
352 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
353 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
354 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
355 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
356 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
357 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
358 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
359 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
360 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
361 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
362 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
363 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
364 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
365 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
366 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
367 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
369 packetTypes["CONN_SYN"] = CONN_SYN_N;
370 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
371 packetTypes["CONN_ACK"] = CONN_ACK_N;
372 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
373 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
374 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
375 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
376 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
377 packetTypes["FIN"] = FIN_N;
378 packetTypes["ERR"] = ERROR_N;
380 //-----------------------------------------------------------------------------
383 pthread_mutex_destroy(&mutex);
385 //-----------------------------------------------------------------------------
388 users->AddNotifierUserDel(&onDelUserNotifier);
398 if (pthread_create(&recvThread, NULL, Run, this))
400 errorStr = "Cannot create thread.";
401 printfd(__FILE__, "Cannot create recv thread\n");
402 logger("Cannot create recv thread.");
407 if (!isRunningRunTimeouter)
409 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
411 errorStr = "Cannot create thread.";
412 printfd(__FILE__, "Cannot create timeouter thread\n");
413 logger("Cannot create timeouter thread.");
420 //-----------------------------------------------------------------------------
431 UnauthorizeUser(this)
436 //5 seconds to thread stops itself
437 for (int i = 0; i < 25 && isRunningRun; i++)
439 struct timespec ts = {0, 200000000};
440 nanosleep(&ts, NULL);
446 if (isRunningRunTimeouter)
448 //5 seconds to thread stops itself
449 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
451 struct timespec ts = {0, 200000000};
452 nanosleep(&ts, NULL);
456 users->DelNotifierUserDel(&onDelUserNotifier);
458 if (isRunningRun || isRunningRunTimeouter)
461 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
464 //-----------------------------------------------------------------------------
465 void * AUTH_IA::Run(void * d)
468 sigfillset(&signalSet);
469 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
471 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
473 ia->isRunningRun = true;
477 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
481 ia->RecvData(buffer, sizeof(buffer));
482 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
485 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
486 TouchFile(monFile.c_str());
490 ia->isRunningRun = false;
493 //-----------------------------------------------------------------------------
494 void * AUTH_IA::RunTimeouter(void * d)
497 sigfillset(&signalSet);
498 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
500 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
502 ia->isRunningRunTimeouter = true;
505 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
508 struct timespec ts = {0, 20000000};
509 nanosleep(&ts, NULL);
511 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
512 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
514 TouchFile(monFile.c_str());
518 ia->isRunningRunTimeouter = false;
521 //-----------------------------------------------------------------------------
522 int AUTH_IA::ParseSettings()
524 int ret = iaSettings.ParseSettings(settings);
526 errorStr = iaSettings.GetStrError();
529 //-----------------------------------------------------------------------------
530 int AUTH_IA::PrepareNet()
532 struct sockaddr_in listenAddr;
534 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
536 if (listenSocket < 0)
538 errorStr = "Cannot create socket.";
539 logger("Cannot create a socket: %s", strerror(errno));
543 listenAddr.sin_family = AF_INET;
544 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
545 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
547 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
549 errorStr = "AUTH_IA: Bind failed.";
550 logger("Cannot bind the socket: %s", strerror(errno));
556 //-----------------------------------------------------------------------------
557 int AUTH_IA::FinalizeNet()
562 //-----------------------------------------------------------------------------
563 int AUTH_IA::RecvData(char * buffer, int bufferSize)
565 if (!WaitPackets(listenSocket)) // Timeout
570 struct sockaddr_in outerAddr;
571 socklen_t outerAddrLen(sizeof(outerAddr));
572 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
579 if (dataLen <= 0) // Error
583 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
584 logger("recvfrom error: %s", strerror(errno));
594 if (CheckHeader(buffer, &protoVer))
597 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
598 memset(login, 0, PASSWD_LEN);
600 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
602 uint32_t sip = outerAddr.sin_addr.s_addr;
603 uint16_t sport = htons(outerAddr.sin_port);
606 if (users->FindByName(login, &user))
608 logger("User's connect failed: user '%s' not found. IP %s",
610 inet_ntostring(sip).c_str());
611 printfd(__FILE__, "User '%s' NOT found!\n", login);
612 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ!");
616 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
618 if (user->GetProperty().disabled.Get())
620 logger("Cannont authorize '%s', user is disabled.", login);
621 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
625 if (user->GetProperty().passive.Get())
627 logger("Cannont authorize '%s', user is passive.", login);
628 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
632 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
634 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
635 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
636 logger("User %s. IP address is incorrect. IP %s",
637 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
638 SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
642 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
644 //-----------------------------------------------------------------------------
645 int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
647 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
649 //SendError(userIP, updateMsg);
650 printfd(__FILE__, "update needed - IA_ID\n");
651 //SendError(userIP, "Incorrect header!");
655 if (buffer[6] != 0) //proto[0] shoud be 0
657 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
658 //SendError(userIP, updateMsg);
665 //SendError(userIP, updateMsg);
666 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
671 *protoVer = buffer[7];
675 //-----------------------------------------------------------------------------
676 int AUTH_IA::Timeouter()
678 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
680 std::map<uint32_t, IA_USER>::iterator it;
681 it = ip2user.begin();
684 while (it != ip2user.end())
688 static UTIME currTime;
689 gettimeofday(&currTime, NULL);
691 if ((it->second.phase.GetPhase() == 2)
692 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
694 it->second.phase.SetPhase1();
695 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
700 if (it->second.phase.GetPhase() == 3)
702 if (!it->second.messagesToSend.empty())
704 if (it->second.protoVer == 6)
705 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
707 if (it->second.protoVer == 7)
708 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
710 if (it->second.protoVer == 8)
711 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
713 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
716 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
718 switch (it->second.protoVer)
721 Send_ALIVE_SYN_6(&(it->second), sip);
724 Send_ALIVE_SYN_7(&(it->second), sip);
727 Send_ALIVE_SYN_8(&(it->second), sip);
731 gettimeofday(&it->second.lastSendAlive, NULL);
734 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
736 users->Unauthorize(it->second.user->GetLogin(), this);
742 if ((it->second.phase.GetPhase() == 4)
743 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
745 it->second.phase.SetPhase3();
746 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
754 //-----------------------------------------------------------------------------
755 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
757 std::string login(user->GetLogin());
758 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
760 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
761 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
763 if (it == ip2user.end())
766 if (!users->FindByIPIdx(sip, &userPtr))
768 if (userPtr->GetID() != user->GetID())
770 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
771 userPtr->GetLogin().c_str(),
772 inet_ntostring(sip).c_str(),
774 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
775 userPtr->GetLogin().c_str(),
776 inet_ntostring(sip).c_str(),
778 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
783 printfd(__FILE__, "Add new user '%s' from ip %s\n",
784 login.c_str(), inet_ntostring(sip).c_str());
785 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
786 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
788 #ifdef IA_PHASE_DEBUG
789 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
790 it->second.phase.SetUserLogin(login);
793 else if (user->GetID() != it->second.user->GetID())
795 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
796 it->second.user->GetLogin().c_str(),
797 inet_ntostring(sip).c_str(),
798 user->GetLogin().c_str());
799 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
800 it->second.user->GetLogin().c_str(),
801 inet_ntostring(sip).c_str(),
802 user->GetLogin().c_str());
803 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
807 IA_USER * iaUser = &(it->second);
809 if (iaUser->password != user->GetProperty().password.Get())
811 InitEncrypt(&iaUser->ctx, user->GetProperty().password.Get());
812 iaUser->password = user->GetProperty().password.Get();
815 Decrypt(&iaUser->ctx, static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset) / 8);
817 char packetName[IA_MAX_TYPE_LEN];
818 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
819 packetName[IA_MAX_TYPE_LEN - 1] = 0;
821 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
822 if (pi == packetTypes.end())
824 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
825 printfd(__FILE__, "Login or password is wrong!\n");
826 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
828 inet_ntostring(sip).c_str());
833 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
835 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
836 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
837 inet_ntostring(sip).c_str());
838 logger("Login '%s' is already in use from ip %s. IP %s",
840 inet_ntostring(user->GetCurrIP()).c_str(),
841 inet_ntostring(sip).c_str());
842 SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
853 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
855 return Send_CONN_SYN_ACK_6(iaUser, sip);
857 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
859 return Send_CONN_SYN_ACK_7(iaUser, sip);
861 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
863 return Send_CONN_SYN_ACK_8(iaUser, sip);
871 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
873 return Send_ALIVE_SYN_6(iaUser, sip);
875 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
877 return Send_ALIVE_SYN_7(iaUser, sip);
879 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
881 return Send_ALIVE_SYN_8(iaUser, sip);
889 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
891 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
893 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
901 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
903 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
905 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
907 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
909 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
911 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
919 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
921 return Send_FIN_6(iaUser, sip, it);
923 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
925 return Send_FIN_7(iaUser, sip, it);
927 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
929 return Send_FIN_8(iaUser, sip, it);
936 //-----------------------------------------------------------------------------
937 void AUTH_IA::DelUser(USER_PTR u)
940 uint32_t ip = u->GetCurrIP();
945 std::map<uint32_t, IA_USER>::iterator it;
947 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
948 it = ip2user.find(ip);
949 if (it == ip2user.end())
952 printfd(__FILE__, "Nothing to delete\n");
956 if (it->second.user == u)
958 printfd(__FILE__, "User removed!\n");
959 users->Unauthorize(u->GetLogin(), this);
963 //-----------------------------------------------------------------------------
964 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
966 struct sockaddr_in sendAddr;
973 memset(&err, 0, sizeof(ERR));
975 sendAddr.sin_family = AF_INET;
976 sendAddr.sin_port = htons(port);
977 sendAddr.sin_addr.s_addr = ip;
980 strncpy((char*)err.type, "ERR", 16);
981 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
987 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
988 printfd(__FILE__, "SendError %d bytes sent\n", res);
993 memset(&err8, 0, sizeof(ERR_8));
995 sendAddr.sin_family = AF_INET;
996 sendAddr.sin_port = htons(port);
997 sendAddr.sin_addr.s_addr = ip;
1000 strncpy((char*)err8.type, "ERR", 16);
1001 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1004 SwapBytes(err8.len);
1007 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1008 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1014 //-----------------------------------------------------------------------------
1015 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1017 struct sockaddr_in sendAddr;
1019 sendAddr.sin_family = AF_INET;
1020 sendAddr.sin_port = htons(port);
1021 sendAddr.sin_addr.s_addr = ip;
1023 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1028 //-----------------------------------------------------------------------------
1029 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1031 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1033 std::map<uint32_t, IA_USER>::iterator it;
1035 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1036 it = ip2user.find(ip);
1037 if (it == ip2user.end())
1039 errorStr = "Unknown user.";
1042 it->second.messagesToSend.push_back(msg);
1045 //-----------------------------------------------------------------------------
1046 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1048 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1051 memset(&info, 0, sizeof(INFO_6));
1054 strncpy((char*)info.type, "INFO", 16);
1055 info.infoType = 'I';
1056 strncpy((char*)info.text, msg.text.c_str(), 235);
1059 size_t len = info.len;
1061 SwapBytes(info.len);
1065 memcpy(buffer, &info, sizeof(INFO_6));
1066 Encrypt(&user.ctx, buffer, buffer, len / 8);
1067 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1069 //-----------------------------------------------------------------------------
1070 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1072 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1075 memset(&info, 0, sizeof(INFO_7));
1078 strncpy((char*)info.type, "INFO_7", 16);
1079 info.infoType = static_cast<int8_t>(msg.header.type);
1080 info.showTime = static_cast<int8_t>(msg.header.showTime);
1081 info.sendTime = msg.header.creationTime;
1083 size_t len = info.len;
1085 SwapBytes(info.len);
1086 SwapBytes(info.sendTime);
1089 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1090 info.text[MAX_MSG_LEN - 1] = 0;
1093 memcpy(buffer, &info, sizeof(INFO_7));
1095 Encrypt(&user.ctx, buffer, buffer, len / 8);
1096 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1098 //-----------------------------------------------------------------------------
1099 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1101 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1104 memset(&info, 0, sizeof(INFO_8));
1107 strncpy((char*)info.type, "INFO_8", 16);
1108 info.infoType = static_cast<int8_t>(msg.header.type);
1109 info.showTime = static_cast<int8_t>(msg.header.showTime);
1110 info.sendTime = msg.header.creationTime;
1112 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1113 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1115 size_t len = info.len;
1117 SwapBytes(info.len);
1118 SwapBytes(info.sendTime);
1122 memcpy(buffer, &info, sizeof(INFO_8));
1124 Encrypt(&user.ctx, buffer, buffer, len / 8);
1125 return Send(ip, user.port, buffer, len);
1127 //-----------------------------------------------------------------------------
1128 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1130 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1133 enabledDirs = 0xFFffFFff;
1135 iaUser->phase.SetPhase2();
1136 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1139 //-----------------------------------------------------------------------------
1140 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1142 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1144 //-----------------------------------------------------------------------------
1145 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1148 SwapBytes(connSyn->dirs);
1150 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, sip);
1151 enabledDirs = connSyn->dirs;
1154 //-----------------------------------------------------------------------------
1155 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1158 SwapBytes(connAck->len);
1159 SwapBytes(connAck->rnd);
1161 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1163 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1165 iaUser->phase.UpdateTime();
1167 iaUser->lastSendAlive = iaUser->phase.GetTime();
1168 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1170 iaUser->phase.SetPhase3();
1171 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1176 errorStr = iaUser->user->GetStrError();
1177 iaUser->phase.SetPhase1();
1179 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1183 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1186 //-----------------------------------------------------------------------------
1187 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1189 return Process_CONN_ACK_6(connAck, iaUser, sip);
1191 //-----------------------------------------------------------------------------
1192 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1195 SwapBytes(connAck->len);
1196 SwapBytes(connAck->rnd);
1198 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1200 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1202 iaUser->phase.UpdateTime();
1203 iaUser->lastSendAlive = iaUser->phase.GetTime();
1204 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1206 iaUser->phase.SetPhase3();
1207 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1212 errorStr = iaUser->user->GetStrError();
1213 iaUser->phase.SetPhase1();
1215 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1219 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1222 //-----------------------------------------------------------------------------
1223 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1226 SwapBytes(aliveAck->len);
1227 SwapBytes(aliveAck->rnd);
1229 printfd(__FILE__, "ALIVE_ACK_6\n");
1230 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1232 iaUser->phase.UpdateTime();
1234 iaUser->aliveSent = false;
1239 //-----------------------------------------------------------------------------
1240 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1242 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1244 //-----------------------------------------------------------------------------
1245 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1248 SwapBytes(aliveAck->len);
1249 SwapBytes(aliveAck->rnd);
1251 printfd(__FILE__, "ALIVE_ACK_8\n");
1252 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1254 iaUser->phase.UpdateTime();
1256 iaUser->aliveSent = false;
1261 //-----------------------------------------------------------------------------
1262 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1264 printfd(__FILE__, "DISCONN_SYN_6\n");
1265 if (iaUser->phase.GetPhase() != 3)
1267 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1268 errorStr = "Incorrect request DISCONN_SYN";
1272 iaUser->phase.SetPhase4();
1273 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1277 //-----------------------------------------------------------------------------
1278 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1280 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1282 //-----------------------------------------------------------------------------
1283 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t)
1285 if (iaUser->phase.GetPhase() != 3)
1287 errorStr = "Incorrect request DISCONN_SYN";
1288 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1292 iaUser->phase.SetPhase4();
1293 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1297 //-----------------------------------------------------------------------------
1298 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1301 std::map<uint32_t, IA_USER>::iterator)
1304 SwapBytes(disconnAck->len);
1305 SwapBytes(disconnAck->rnd);
1307 printfd(__FILE__, "DISCONN_ACK_6\n");
1308 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1310 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1316 //-----------------------------------------------------------------------------
1317 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1319 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1321 //-----------------------------------------------------------------------------
1322 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, std::map<uint32_t, IA_USER>::iterator)
1325 SwapBytes(disconnAck->len);
1326 SwapBytes(disconnAck->rnd);
1328 printfd(__FILE__, "DISCONN_ACK_8\n");
1329 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1331 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1337 //-----------------------------------------------------------------------------
1338 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1340 //+++ Fill static data in connSynAck +++
1341 // TODO Move this code. It must be executed only once
1342 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1343 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1344 for (int j = 0; j < DIR_NUM; j++)
1346 strncpy((char*)connSynAck6.dirName[j],
1347 stgSettings->GetDirName(j).c_str(),
1350 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1352 //--- Fill static data in connSynAck ---
1354 iaUser->rnd = static_cast<uint32_t>(random());
1355 connSynAck6.rnd = iaUser->rnd;
1357 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1358 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1361 SwapBytes(connSynAck6.len);
1362 SwapBytes(connSynAck6.rnd);
1363 SwapBytes(connSynAck6.userTimeOut);
1364 SwapBytes(connSynAck6.aliveDelay);
1367 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1368 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1370 //-----------------------------------------------------------------------------
1371 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1373 return Send_CONN_SYN_ACK_6(iaUser, sip);
1375 //-----------------------------------------------------------------------------
1376 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1378 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1379 connSynAck8.hdr.protoVer[0] = 0;
1380 connSynAck8.hdr.protoVer[1] = 8;
1382 //+++ Fill static data in connSynAck +++
1383 // TODO Move this code. It must be executed only once
1384 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1385 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1386 for (int j = 0; j < DIR_NUM; j++)
1388 strncpy((char*)connSynAck8.dirName[j],
1389 stgSettings->GetDirName(j).c_str(),
1392 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1394 //--- Fill static data in connSynAck ---
1396 iaUser->rnd = static_cast<uint32_t>(random());
1397 connSynAck8.rnd = iaUser->rnd;
1399 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1400 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1403 SwapBytes(connSynAck8.len);
1404 SwapBytes(connSynAck8.rnd);
1405 SwapBytes(connSynAck8.userTimeOut);
1406 SwapBytes(connSynAck8.aliveDelay);
1409 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1410 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1412 //-----------------------------------------------------------------------------
1413 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1415 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1416 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1418 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1420 for (int i = 0; i < DIR_NUM; i++)
1422 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1423 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1425 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1426 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1430 int dn = iaSettings.GetFreeMbShowType();
1431 const TARIFF * tf = iaUser->user->GetTariff();
1435 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1440 if (std::fabs(p) < 1.0e-3)
1442 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1446 double fmb = iaUser->user->GetProperty().freeMb;
1447 fmb = fmb < 0 ? 0 : fmb;
1448 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1453 if (freeMbNone == iaSettings.GetFreeMbShowType())
1455 aliveSyn6.freeMb[0] = 0;
1459 double fmb = iaUser->user->GetProperty().freeMb;
1460 fmb = fmb < 0 ? 0 : fmb;
1461 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1466 if (iaUser->aliveSent)
1468 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1470 iaUser->aliveSent = true;
1473 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1474 if (!stgSettings->GetShowFeeInCash())
1475 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1478 SwapBytes(aliveSyn6.len);
1479 SwapBytes(aliveSyn6.rnd);
1480 SwapBytes(aliveSyn6.cash);
1481 for (int i = 0; i < DIR_NUM; ++i)
1483 SwapBytes(aliveSyn6.mu[i]);
1484 SwapBytes(aliveSyn6.md[i]);
1485 SwapBytes(aliveSyn6.su[i]);
1486 SwapBytes(aliveSyn6.sd[i]);
1490 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1491 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1493 //-----------------------------------------------------------------------------
1494 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1496 return Send_ALIVE_SYN_6(iaUser, sip);
1498 //-----------------------------------------------------------------------------
1499 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1501 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1502 aliveSyn8.hdr.protoVer[0] = 0;
1503 aliveSyn8.hdr.protoVer[1] = 8;
1505 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1506 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1508 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1510 for (int i = 0; i < DIR_NUM; i++)
1512 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1513 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1515 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1516 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1520 int dn = iaSettings.GetFreeMbShowType();
1524 const TARIFF * tf = iaUser->user->GetTariff();
1525 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1530 if (std::fabs(p) < 1.0e-3)
1532 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1536 double fmb = iaUser->user->GetProperty().freeMb;
1537 fmb = fmb < 0 ? 0 : fmb;
1538 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1543 if (freeMbNone == iaSettings.GetFreeMbShowType())
1545 aliveSyn8.freeMb[0] = 0;
1549 double fmb = iaUser->user->GetProperty().freeMb;
1550 fmb = fmb < 0 ? 0 : fmb;
1551 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1556 if (iaUser->aliveSent)
1558 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1560 iaUser->aliveSent = true;
1563 const TARIFF * tf = iaUser->user->GetTariff();
1565 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1566 if (!stgSettings->GetShowFeeInCash())
1567 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1570 SwapBytes(aliveSyn8.len);
1571 SwapBytes(aliveSyn8.rnd);
1572 SwapBytes(aliveSyn8.cash);
1573 SwapBytes(aliveSyn8.status);
1574 for (int i = 0; i < DIR_NUM; ++i)
1576 SwapBytes(aliveSyn8.mu[i]);
1577 SwapBytes(aliveSyn8.md[i]);
1578 SwapBytes(aliveSyn8.su[i]);
1579 SwapBytes(aliveSyn8.sd[i]);
1583 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1584 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1586 //-----------------------------------------------------------------------------
1587 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1589 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1590 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1591 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1594 SwapBytes(disconnSynAck6.len);
1595 SwapBytes(disconnSynAck6.rnd);
1598 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1599 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1601 //-----------------------------------------------------------------------------
1602 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1604 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1606 //-----------------------------------------------------------------------------
1607 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1609 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1610 disconnSynAck8.hdr.protoVer[0] = 0;
1611 disconnSynAck8.hdr.protoVer[1] = 8;
1613 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1614 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1615 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1618 SwapBytes(disconnSynAck8.len);
1619 SwapBytes(disconnSynAck8.rnd);
1622 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1623 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1625 //-----------------------------------------------------------------------------
1626 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1628 fin6.len = Min8(sizeof(FIN_6));
1629 strcpy((char*)fin6.type, "FIN");
1630 strcpy((char*)fin6.ok, "OK");
1633 SwapBytes(fin6.len);
1636 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1638 users->Unauthorize(iaUser->login, this);
1640 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1646 //-----------------------------------------------------------------------------
1647 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1649 return Send_FIN_6(iaUser, sip, it);
1651 //-----------------------------------------------------------------------------
1652 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1654 strcpy((char*)fin8.hdr.magic, IA_ID);
1655 fin8.hdr.protoVer[0] = 0;
1656 fin8.hdr.protoVer[1] = 8;
1658 fin8.len = Min8(sizeof(FIN_8));
1659 strcpy((char*)fin8.type, "FIN");
1660 strcpy((char*)fin8.ok, "OK");
1663 SwapBytes(fin8.len);
1666 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1668 users->Unauthorize(iaUser->login, this);
1670 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1678 //-----------------------------------------------------------------------------
1680 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
1682 unsigned char keyL[PASSWD_LEN];
1683 memset(keyL, 0, PASSWD_LEN);
1684 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1685 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1687 //-----------------------------------------------------------------------------
1689 void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
1691 for (size_t i = 0; i < len8; i++)
1692 DecodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
1694 //-----------------------------------------------------------------------------
1696 void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
1698 for (size_t i = 0; i < len8; i++)
1699 EncodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
1701 //-----------------------------------------------------------------------------