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>
25 #include "inetaccess.h"
27 #include "stg/common.h"
28 #include "stg/locker.h"
29 #include "stg/tariff.h"
30 #include "stg/settings.h"
35 #include <cstdio> // snprintf
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <unistd.h> // close
43 #define IA_PROTO_VER (6)
45 extern volatile time_t stgTime;
47 extern "C" STG::Plugin* GetPlugin()
49 static AUTH_IA plugin;
52 //-----------------------------------------------------------------------------
53 //-----------------------------------------------------------------------------
54 //-----------------------------------------------------------------------------
55 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
59 freeMbShowType(freeMbCash),
60 logProtocolErrors(false)
63 //-----------------------------------------------------------------------------
64 int AUTH_IA_SETTINGS::ParseSettings(const STG::ModuleSettings & s)
68 std::vector<STG::ParamValue>::const_iterator pvi;
69 ///////////////////////////
71 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
72 if (pvi == s.moduleParams.end() || pvi->value.empty())
74 errorStr = "Parameter \'Port\' not found.";
75 printfd(__FILE__, "Parameter 'Port' not found\n");
78 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
80 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
81 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
84 port = static_cast<uint16_t>(p);
85 ///////////////////////////
86 pv.param = "UserDelay";
87 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
88 if (pvi == s.moduleParams.end() || pvi->value.empty())
90 errorStr = "Parameter \'UserDelay\' not found.";
91 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
95 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
97 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
98 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
101 ///////////////////////////
102 pv.param = "UserTimeout";
103 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
104 if (pvi == s.moduleParams.end() || pvi->value.empty())
106 errorStr = "Parameter \'UserTimeout\' not found.";
107 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
111 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
113 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
114 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
117 ///////////////////////////
118 pv.param = "LogProtocolErrors";
119 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
120 if (pvi == s.moduleParams.end() || pvi->value.empty())
121 logProtocolErrors = false;
122 else if (ParseYesNo(pvi->value[0], &logProtocolErrors))
124 errorStr = "Cannot parse parameter \'LogProtocolErrors\': " + errorStr;
125 printfd(__FILE__, "Cannot parse parameter 'LogProtocolErrors'\n");
128 /////////////////////////////////////////////////////////////
129 std::string freeMbType;
132 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
133 if (pvi == s.moduleParams.end() || pvi->value.empty())
135 errorStr = "Parameter \'FreeMb\' not found.";
136 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
139 freeMbType = pvi->value[0];
141 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
143 freeMbShowType = freeMbCash;
145 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
147 freeMbShowType = freeMbNone;
149 else if (!str2x(freeMbType.c_str(), n))
151 if (n < 0 || n >= DIR_NUM)
153 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
154 printfd(__FILE__, "%s\n", errorStr.c_str());
157 freeMbShowType = static_cast<FREEMB>(n);
161 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
162 printfd(__FILE__, "%s\n", errorStr.c_str());
165 /////////////////////////////////////////////////////////////
168 //-----------------------------------------------------------------------------
169 //-----------------------------------------------------------------------------
170 //-----------------------------------------------------------------------------
171 #ifdef IA_PHASE_DEBUG
176 gettimeofday(&phaseTime, NULL);
182 gettimeofday(&phaseTime, NULL);
185 //-----------------------------------------------------------------------------
186 IA_PHASE::~IA_PHASE()
188 #ifdef IA_PHASE_DEBUG
189 flog = fopen(log.c_str(), "at");
192 fprintf(flog, "IA %s D\n", login.c_str());
197 //-----------------------------------------------------------------------------
198 #ifdef IA_PHASE_DEBUG
199 void IA_PHASE::SetLogFileName(const string & logFileName)
201 log = logFileName + ".ia.log";
203 //-----------------------------------------------------------------------------
204 void IA_PHASE::SetUserLogin(const string & login)
206 IA_PHASE::login = login;
208 //-----------------------------------------------------------------------------
209 void IA_PHASE::WritePhaseChange(int newPhase)
212 gettimeofday(&newPhaseTime, NULL);
213 flog = fopen(log.c_str(), "at");
216 string action = newPhase == phase ? "U" : "C";
217 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
218 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
219 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
229 //-----------------------------------------------------------------------------
230 void IA_PHASE::SetPhase1()
232 #ifdef IA_PHASE_DEBUG
236 gettimeofday(&phaseTime, NULL);
238 //-----------------------------------------------------------------------------
239 void IA_PHASE::SetPhase2()
241 #ifdef IA_PHASE_DEBUG
245 gettimeofday(&phaseTime, NULL);
247 //-----------------------------------------------------------------------------
248 void IA_PHASE::SetPhase3()
250 #ifdef IA_PHASE_DEBUG
254 gettimeofday(&phaseTime, NULL);
256 //-----------------------------------------------------------------------------
257 void IA_PHASE::SetPhase4()
259 #ifdef IA_PHASE_DEBUG
263 gettimeofday(&phaseTime, NULL);
265 //-----------------------------------------------------------------------------
266 int IA_PHASE::GetPhase() const
270 //-----------------------------------------------------------------------------
271 void IA_PHASE::UpdateTime()
273 #ifdef IA_PHASE_DEBUG
274 WritePhaseChange(phase);
276 gettimeofday(&phaseTime, NULL);
278 //-----------------------------------------------------------------------------
279 const UTIME & IA_PHASE::GetTime() const
283 //-----------------------------------------------------------------------------
284 //-----------------------------------------------------------------------------
285 //-----------------------------------------------------------------------------
287 : isRunningRun(false),
288 isRunningRunTimeouter(false),
292 enabledDirs(0xFFffFFff),
293 onDelUserNotifier(*this),
294 logger(STG::PluginLogger::get("auth_ia"))
296 InitContext("pr7Hhen", 7, &ctxS);
298 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
299 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
300 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
301 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
302 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
303 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
304 memset(&fin6, 0, sizeof(FIN_6));
305 memset(&fin8, 0, sizeof(FIN_8));
307 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
308 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
309 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
310 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
311 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
312 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
313 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
314 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
315 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
316 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
317 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
318 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
319 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
320 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
321 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
322 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
323 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
324 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
326 packetTypes["CONN_SYN"] = CONN_SYN_N;
327 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
328 packetTypes["CONN_ACK"] = CONN_ACK_N;
329 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
330 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
331 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
332 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
333 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
334 packetTypes["FIN"] = FIN_N;
335 packetTypes["ERR"] = ERROR_N;
337 //-----------------------------------------------------------------------------
341 //-----------------------------------------------------------------------------
344 users->AddNotifierUserDel(&onDelUserNotifier);
351 if (!m_thread.joinable())
352 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
354 if (!m_timeouterThread.joinable())
355 m_timeouterThread = std::jthread([this](auto token){ RunTimeouter(std::move(token)); });
360 //-----------------------------------------------------------------------------
366 m_thread.request_stop();
367 m_timeouterThread.request_stop();
372 UnauthorizeUser(this)
377 //5 seconds to thread stops itself
378 for (int i = 0; i < 25 && isRunningRun; i++)
380 struct timespec ts = {0, 200000000};
381 nanosleep(&ts, NULL);
387 if (isRunningRunTimeouter)
389 //5 seconds to thread stops itself
390 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
392 struct timespec ts = {0, 200000000};
393 nanosleep(&ts, NULL);
397 users->DelNotifierUserDel(&onDelUserNotifier);
404 if (isRunningRunTimeouter)
405 m_timeouterThread.detach();
407 m_timeouterThread.join();
409 if (isRunningRun || isRunningRunTimeouter)
412 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
415 //-----------------------------------------------------------------------------
416 void AUTH_IA::Run(std::stop_token token)
419 sigfillset(&signalSet);
420 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
426 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
428 while (!token.stop_requested())
430 RecvData(buffer, sizeof(buffer));
431 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && stgSettings->GetMonitoring())
434 std::string monFile = stgSettings->GetMonitorDir() + "/inetaccess_r";
439 isRunningRun = false;
441 //-----------------------------------------------------------------------------
442 void AUTH_IA::RunTimeouter(std::stop_token token)
445 sigfillset(&signalSet);
446 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
448 isRunningRunTimeouter = true;
451 std::string monFile = stgSettings->GetMonitorDir() + "/inetaccess_t";
452 while (!token.stop_requested())
454 struct timespec ts = {0, 20000000};
455 nanosleep(&ts, NULL);
457 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
458 if (++a % (50 * 60) == 0 && stgSettings->GetMonitoring())
464 isRunningRunTimeouter = false;
466 //-----------------------------------------------------------------------------
467 int AUTH_IA::ParseSettings()
469 int ret = iaSettings.ParseSettings(settings);
471 errorStr = iaSettings.GetStrError();
474 //-----------------------------------------------------------------------------
475 int AUTH_IA::Reload(const STG::ModuleSettings & ms)
477 AUTH_IA_SETTINGS newIaSettings;
478 if (newIaSettings.ParseSettings(ms))
480 printfd(__FILE__, "AUTH_IA::Reload() - Failed to reload InetAccess.\n");
481 logger("AUTH_IA: Cannot reload InetAccess. Errors found.");
485 printfd(__FILE__, "AUTH_IA::Reload() - Reloaded InetAccess successfully.\n");
486 logger("AUTH_IA: Reloaded InetAccess successfully.");
487 iaSettings = newIaSettings;
490 //-----------------------------------------------------------------------------
491 int AUTH_IA::PrepareNet()
493 struct sockaddr_in listenAddr;
495 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
497 if (listenSocket < 0)
499 errorStr = "Cannot create socket.";
500 logger("Cannot create a socket: %s", strerror(errno));
504 listenAddr.sin_family = AF_INET;
505 listenAddr.sin_port = htons(iaSettings.GetUserPort());
506 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
508 if (bind(listenSocket, reinterpret_cast<sockaddr*>(&listenAddr), sizeof(listenAddr)) < 0)
510 errorStr = "AUTH_IA: Bind failed.";
511 logger("Cannot bind the socket: %s", strerror(errno));
517 //-----------------------------------------------------------------------------
518 int AUTH_IA::FinalizeNet()
523 //-----------------------------------------------------------------------------
524 int AUTH_IA::RecvData(char * buffer, int bufferSize)
526 if (!WaitPackets(listenSocket)) // Timeout
531 struct sockaddr_in outerAddr;
532 socklen_t outerAddrLen(sizeof(outerAddr));
533 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, reinterpret_cast<sockaddr *>(&outerAddr), &outerAddrLen);
540 if (dataLen <= 0) // Error
544 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
545 logger("recvfrom error: %s", strerror(errno));
554 uint32_t sip = outerAddr.sin_addr.s_addr;
555 uint16_t sport = htons(outerAddr.sin_port);
558 if (CheckHeader(buffer, sip, &protoVer))
561 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
562 memset(login, 0, PASSWD_LEN);
564 DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS);
567 if (users->FindByName(login, &user))
569 logger("User's connect failed: user '%s' not found. IP %s",
571 inet_ntostring(sip).c_str());
572 printfd(__FILE__, "User '%s' NOT found!\n", login);
573 SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
577 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
579 if (user->GetProperties().disabled.Get())
581 logger("Cannont authorize '%s', user is disabled.", login);
582 SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
586 if (user->GetProperties().passive.Get())
588 logger("Cannont authorize '%s', user is passive.", login);
589 SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
593 if (!user->GetProperties().ips.Get().find(sip))
595 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
596 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
597 logger("User %s. IP address is incorrect. IP %s",
598 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
599 SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
603 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
605 //-----------------------------------------------------------------------------
606 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
608 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
610 printfd(__FILE__, "update needed - IA_ID\n");
611 if (iaSettings.LogProtocolErrors())
612 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
616 if (buffer[6] != 0) //proto[0] shoud be 0
618 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
619 if (iaSettings.LogProtocolErrors())
620 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
627 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
628 if (iaSettings.LogProtocolErrors())
629 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
634 *protoVer = buffer[7];
638 //-----------------------------------------------------------------------------
639 int AUTH_IA::Timeouter()
641 std::lock_guard lock(m_mutex);
643 std::map<uint32_t, IA_USER>::iterator it;
644 it = ip2user.begin();
646 while (it != ip2user.end())
648 uint32_t sip = it->first;
650 static UTIME currTime;
651 gettimeofday(&currTime, NULL);
653 if ((it->second.phase.GetPhase() == 2)
654 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
656 if (iaSettings.LogProtocolErrors())
657 logger("User '%s'. Protocol version: %d. Phase 2: connect request timeout (%f > %d).", it->second.login.c_str(), it->second.protoVer, (currTime - it->second.phase.GetTime()).AsDouble(), iaSettings.GetUserDelay().GetSec());
658 it->second.phase.SetPhase1();
659 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
664 if (it->second.phase.GetPhase() == 3)
666 if (!it->second.messagesToSend.empty())
668 if (it->second.protoVer == 6)
669 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
671 if (it->second.protoVer == 7)
672 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
674 if (it->second.protoVer == 8)
675 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
677 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
680 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
682 switch (it->second.protoVer)
685 Send_ALIVE_SYN_6(&(it->second), sip);
688 Send_ALIVE_SYN_7(&(it->second), sip);
691 Send_ALIVE_SYN_8(&(it->second), sip);
695 gettimeofday(&it->second.lastSendAlive, NULL);
698 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
700 if (iaSettings.LogProtocolErrors())
701 logger("User '%s'. Protocol version: %d. Phase 3: alive timeout (%f > %d).", it->second.login.c_str(), it->second.protoVer, (currTime - it->second.phase.GetTime()).AsDouble(), iaSettings.GetUserTimeout().GetSec());
702 users->Unauthorize(it->second.user->GetLogin(), this);
708 if ((it->second.phase.GetPhase() == 4)
709 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
711 if (iaSettings.LogProtocolErrors())
712 logger("User '%s'. Protocol version: %d. Phase 4: disconnect request timeout (%f > %d).", it->second.login.c_str(), it->second.protoVer, (currTime - it->second.phase.GetTime()).AsDouble(), iaSettings.GetUserDelay().GetSec());
713 it->second.phase.SetPhase3();
714 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
722 //-----------------------------------------------------------------------------
723 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, UserPtr user)
725 std::string login(user->GetLogin());
726 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
728 std::lock_guard lock(m_mutex);
729 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
731 if (it == ip2user.end())
734 if (!users->FindByIPIdx(sip, &userPtr))
736 if (userPtr->GetID() != user->GetID())
738 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
739 userPtr->GetLogin().c_str(),
740 inet_ntostring(sip).c_str(),
742 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
743 userPtr->GetLogin().c_str(),
744 inet_ntostring(sip).c_str(),
746 SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
751 printfd(__FILE__, "Add new user '%s' from ip %s\n",
752 login.c_str(), inet_ntostring(sip).c_str());
753 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
754 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
756 #ifdef IA_PHASE_DEBUG
757 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
758 it->second.phase.SetUserLogin(login);
761 else if (user->GetID() != it->second.user->GetID())
763 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
764 it->second.user->GetLogin().c_str(),
765 inet_ntostring(sip).c_str(),
766 user->GetLogin().c_str());
767 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
768 it->second.user->GetLogin().c_str(),
769 inet_ntostring(sip).c_str(),
770 user->GetLogin().c_str());
771 SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
775 IA_USER * iaUser = &(it->second);
777 if (iaUser->password != user->GetProperties().password.Get())
779 const std::string & password = user->GetProperties().password.Get();
780 InitContext(password.c_str(), password.length(), &iaUser->ctx);
781 iaUser->password = user->GetProperties().password.Get();
784 DecryptString(static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
786 char packetName[IA_MAX_TYPE_LEN];
787 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
788 packetName[IA_MAX_TYPE_LEN - 1] = 0;
790 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
791 if (pi == packetTypes.end())
793 SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
794 printfd(__FILE__, "Login or password is wrong!\n");
795 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
797 inet_ntostring(sip).c_str());
802 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
804 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
805 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
806 inet_ntostring(sip).c_str());
807 logger("Login '%s' is already in use from ip %s. IP %s",
809 inet_ntostring(user->GetCurrIP()).c_str(),
810 inet_ntostring(sip).c_str());
811 SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
822 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
824 return Send_CONN_SYN_ACK_6(iaUser, sip);
826 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
828 return Send_CONN_SYN_ACK_7(iaUser, sip);
830 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
832 return Send_CONN_SYN_ACK_8(iaUser, sip);
840 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
842 return Send_ALIVE_SYN_6(iaUser, sip);
844 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
846 return Send_ALIVE_SYN_7(iaUser, sip);
848 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
850 return Send_ALIVE_SYN_8(iaUser, sip);
858 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
860 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
862 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
870 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
872 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
874 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
876 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
878 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
880 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
888 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
890 return Send_FIN_6(iaUser, sip, it);
892 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
894 return Send_FIN_7(iaUser, sip, it);
896 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
898 return Send_FIN_8(iaUser, sip, it);
905 //-----------------------------------------------------------------------------
906 void AUTH_IA::DelUser(UserPtr u)
909 uint32_t ip = u->GetCurrIP();
914 std::map<uint32_t, IA_USER>::iterator it;
916 std::lock_guard lock(m_mutex);
917 it = ip2user.find(ip);
918 if (it == ip2user.end())
921 printfd(__FILE__, "Nothing to delete\n");
925 if (it->second.user == u)
927 printfd(__FILE__, "User removed!\n");
928 users->Unauthorize(u->GetLogin(), this);
932 //-----------------------------------------------------------------------------
933 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
935 struct sockaddr_in sendAddr;
942 memset(&err, 0, sizeof(ERR));
944 sendAddr.sin_family = AF_INET;
945 sendAddr.sin_port = htons(port);
946 sendAddr.sin_addr.s_addr = ip;
949 memcpy(err.type, "ERR", 3);
950 memcpy(err.text, text.c_str(), std::min<size_t>(text.length(), MAX_MSG_LEN));
956 res = sendto(listenSocket, &err, sizeof(err), 0, reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr));
957 printfd(__FILE__, "SendError %d bytes sent\n", res);
962 memset(&err8, 0, sizeof(ERR_8));
964 sendAddr.sin_family = AF_INET;
965 sendAddr.sin_port = htons(port);
966 sendAddr.sin_addr.s_addr = ip;
969 memcpy(err8.type, "ERR", 3);
970 memcpy(err8.text, text.c_str(), std::min<size_t>(text.length(), MAX_MSG_LEN));
976 res = sendto(listenSocket, &err8, sizeof(err8), 0, reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr));
977 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
983 //-----------------------------------------------------------------------------
984 int AUTH_IA::Send(uint32_t ip, uint16_t port, const void* buffer, size_t len)
986 struct sockaddr_in sendAddr;
988 sendAddr.sin_family = AF_INET;
989 sendAddr.sin_port = htons(port);
990 sendAddr.sin_addr.s_addr = ip;
992 if (sendto(listenSocket, buffer, len, 0, reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)) == static_cast<ssize_t>(len))
997 //-----------------------------------------------------------------------------
998 int AUTH_IA::SendMessage(const STG::Message & msg, uint32_t ip) const
1000 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1002 std::map<uint32_t, IA_USER>::iterator it;
1004 std::lock_guard lock(m_mutex);
1005 it = ip2user.find(ip);
1006 if (it == ip2user.end())
1008 errorStr = "Unknown user.";
1011 it->second.messagesToSend.push_back(msg);
1014 //-----------------------------------------------------------------------------
1015 int AUTH_IA::RealSendMessage6(const STG::Message & msg, uint32_t ip, IA_USER & user)
1017 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1020 memset(&info, 0, sizeof(INFO_6));
1023 memcpy(info.type, "INFO", 4);
1024 info.infoType = 'I';
1025 memcpy(info.text, msg.text.c_str(), std::min<size_t>(msg.text.length(), 235));
1028 size_t len = info.len;
1030 SwapBytes(info.len);
1034 memcpy(buffer, &info, sizeof(INFO_6));
1035 EncryptString(buffer, buffer, len, &user.ctx);
1036 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1038 //-----------------------------------------------------------------------------
1039 int AUTH_IA::RealSendMessage7(const STG::Message & msg, uint32_t ip, IA_USER & user)
1041 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1044 memset(&info, 0, sizeof(INFO_7));
1047 memcpy(info.type, "INFO_7", 6);
1048 info.infoType = static_cast<int8_t>(msg.header.type);
1049 info.showTime = static_cast<int8_t>(msg.header.showTime);
1050 info.sendTime = msg.header.creationTime;
1052 size_t len = info.len;
1054 SwapBytes(info.len);
1055 SwapBytes(info.sendTime);
1058 memcpy(info.text, msg.text.c_str(), std::min<size_t>(msg.text.length(), MAX_MSG_LEN - 1));
1059 info.text[MAX_MSG_LEN - 1] = 0;
1062 memcpy(buffer, &info, sizeof(INFO_7));
1064 EncryptString(buffer, buffer, len, &user.ctx);
1065 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1067 //-----------------------------------------------------------------------------
1068 int AUTH_IA::RealSendMessage8(const STG::Message & msg, uint32_t ip, IA_USER & user)
1070 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1073 memset(&info, 0, sizeof(INFO_8));
1076 memcpy(info.type, "INFO_8", 6);
1077 info.infoType = static_cast<int8_t>(msg.header.type);
1078 info.showTime = static_cast<int8_t>(msg.header.showTime);
1079 info.sendTime = msg.header.creationTime;
1081 memcpy(info.text, msg.text.c_str(), std::min<size_t>(msg.text.length(), IA_MAX_MSG_LEN_8 - 1));
1082 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1084 size_t len = info.len;
1086 SwapBytes(info.len);
1087 SwapBytes(info.sendTime);
1091 memcpy(buffer, &info, sizeof(INFO_8));
1093 EncryptString(buffer, buffer, len, &user.ctx);
1094 return Send(ip, user.port, buffer, len);
1096 //-----------------------------------------------------------------------------
1097 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1099 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1102 enabledDirs = 0xFFffFFff;
1104 iaUser->phase.SetPhase2();
1105 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1108 //-----------------------------------------------------------------------------
1109 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1111 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1113 //-----------------------------------------------------------------------------
1114 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1117 SwapBytes(connSyn->dirs);
1119 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1120 enabledDirs = connSyn->dirs;
1123 //-----------------------------------------------------------------------------
1124 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1127 SwapBytes(connAck->len);
1128 SwapBytes(connAck->rnd);
1130 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1132 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1134 iaUser->phase.UpdateTime();
1136 iaUser->lastSendAlive = iaUser->phase.GetTime();
1137 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1139 iaUser->phase.SetPhase3();
1140 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1145 errorStr = iaUser->user->GetStrError();
1146 if (iaSettings.LogProtocolErrors())
1147 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: phase 2, authorization error ('%s').", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, errorStr.c_str());
1148 iaUser->phase.SetPhase1();
1150 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1154 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d, expected: %d\n", iaUser->phase.GetPhase(), connAck->rnd, iaUser->rnd + 1);
1155 if (iaSettings.LogProtocolErrors())
1157 if (iaUser->phase.GetPhase() != 2)
1158 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid phase, expected 2, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1159 if (connAck->rnd != iaUser->rnd + 1)
1160 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), connAck->rnd);
1164 //-----------------------------------------------------------------------------
1165 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1167 return Process_CONN_ACK_6(connAck, iaUser, sip);
1169 //-----------------------------------------------------------------------------
1170 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1173 SwapBytes(connAck->len);
1174 SwapBytes(connAck->rnd);
1176 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1178 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1180 iaUser->phase.UpdateTime();
1181 iaUser->lastSendAlive = iaUser->phase.GetTime();
1182 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1184 iaUser->phase.SetPhase3();
1185 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1190 errorStr = iaUser->user->GetStrError();
1191 if (iaSettings.LogProtocolErrors())
1192 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: phase 2, authorization error ('%s').", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, errorStr.c_str());
1193 iaUser->phase.SetPhase1();
1195 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1199 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d, expected: %d\n", iaUser->phase.GetPhase(), connAck->rnd, iaUser->rnd + 1);
1200 if (iaSettings.LogProtocolErrors())
1202 if (iaUser->phase.GetPhase() != 2)
1203 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid phase, expected 2, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1204 if (connAck->rnd != iaUser->rnd + 1)
1205 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), connAck->rnd);
1209 //-----------------------------------------------------------------------------
1210 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1213 SwapBytes(aliveAck->len);
1214 SwapBytes(aliveAck->rnd);
1216 printfd(__FILE__, "ALIVE_ACK_6\n");
1217 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1219 iaUser->phase.UpdateTime();
1221 iaUser->aliveSent = false;
1226 //-----------------------------------------------------------------------------
1227 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1229 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1231 //-----------------------------------------------------------------------------
1232 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1235 SwapBytes(aliveAck->len);
1236 SwapBytes(aliveAck->rnd);
1238 printfd(__FILE__, "ALIVE_ACK_8\n");
1239 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1241 iaUser->phase.UpdateTime();
1243 iaUser->aliveSent = false;
1248 //-----------------------------------------------------------------------------
1249 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1251 printfd(__FILE__, "DISCONN_SYN_6\n");
1252 if (iaUser->phase.GetPhase() != 3)
1254 if (iaSettings.LogProtocolErrors())
1255 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_SYN: invalid phase, expected 3, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1256 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1257 errorStr = "Incorrect request DISCONN_SYN";
1261 iaUser->phase.SetPhase4();
1262 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1266 //-----------------------------------------------------------------------------
1267 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1269 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1271 //-----------------------------------------------------------------------------
1272 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1274 if (iaUser->phase.GetPhase() != 3)
1276 if (iaSettings.LogProtocolErrors())
1277 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_SYN: invalid phase, expected 3, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1278 errorStr = "Incorrect request DISCONN_SYN";
1279 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1283 iaUser->phase.SetPhase4();
1284 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1288 //-----------------------------------------------------------------------------
1289 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1292 std::map<uint32_t, IA_USER>::iterator)
1295 SwapBytes(disconnAck->len);
1296 SwapBytes(disconnAck->rnd);
1298 printfd(__FILE__, "DISCONN_ACK_6\n");
1299 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1301 if (iaSettings.LogProtocolErrors())
1303 if (iaUser->phase.GetPhase() != 4)
1304 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid phase, expected 4, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1305 if (disconnAck->rnd != iaUser->rnd + 1)
1306 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), disconnAck->rnd);
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, std::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 sip, std::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 if (iaSettings.LogProtocolErrors())
1331 if (iaUser->phase.GetPhase() != 4)
1332 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid phase, expected 4, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1333 if (disconnAck->rnd != iaUser->rnd + 1)
1334 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), disconnAck->rnd);
1336 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1342 //-----------------------------------------------------------------------------
1343 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1345 //+++ Fill static data in connSynAck +++
1346 // TODO Move this code. It must be executed only once
1347 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1348 memcpy(connSynAck6.type, "CONN_SYN_ACK", 12);
1349 for (int j = 0; j < DIR_NUM; j++)
1351 memcpy(connSynAck6.dirName[j],
1352 stgSettings->GetDirName(j).c_str(),
1353 std::min(stgSettings->GetDirName(j).length(), sizeof(string16)));
1355 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1357 //--- Fill static data in connSynAck ---
1359 iaUser->rnd = static_cast<uint32_t>(random());
1360 connSynAck6.rnd = iaUser->rnd;
1362 printfd(__FILE__, "Sending CONN_SYN_ACK with control number %d.\n", iaUser->rnd);
1364 connSynAck6.userTimeOut = iaSettings.GetUserTimeout().GetSec();
1365 connSynAck6.aliveDelay = iaSettings.GetUserDelay().GetSec();
1368 SwapBytes(connSynAck6.len);
1369 SwapBytes(connSynAck6.rnd);
1370 SwapBytes(connSynAck6.userTimeOut);
1371 SwapBytes(connSynAck6.aliveDelay);
1374 EncryptString(&connSynAck6, &connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)), &iaUser->ctx);
1375 return Send(sip, iaSettings.GetUserPort(), &connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1377 //-----------------------------------------------------------------------------
1378 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1380 return Send_CONN_SYN_ACK_6(iaUser, sip);
1382 //-----------------------------------------------------------------------------
1383 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1385 memcpy(connSynAck8.hdr.magic, IA_ID, strlen(IA_ID));
1386 connSynAck8.hdr.protoVer[0] = 0;
1387 connSynAck8.hdr.protoVer[1] = 8;
1389 //+++ Fill static data in connSynAck +++
1390 // TODO Move this code. It must be executed only once
1391 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1392 memcpy(connSynAck8.type, "CONN_SYN_ACK", 12);
1393 for (int j = 0; j < DIR_NUM; j++)
1395 memcpy(connSynAck8.dirName[j],
1396 stgSettings->GetDirName(j).c_str(),
1397 std::min(stgSettings->GetDirName(j).length(), sizeof(string16)));
1399 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1401 //--- Fill static data in connSynAck ---
1403 iaUser->rnd = static_cast<uint32_t>(random());
1404 connSynAck8.rnd = iaUser->rnd;
1406 printfd(__FILE__, "Sending CONN_SYN_ACK with control number %d.\n", iaUser->rnd);
1408 connSynAck8.userTimeOut = iaSettings.GetUserTimeout().GetSec();
1409 connSynAck8.aliveDelay = iaSettings.GetUserDelay().GetSec();
1412 SwapBytes(connSynAck8.len);
1413 SwapBytes(connSynAck8.rnd);
1414 SwapBytes(connSynAck8.userTimeOut);
1415 SwapBytes(connSynAck8.aliveDelay);
1418 EncryptString(&connSynAck8, &connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)), &iaUser->ctx);
1419 return Send(sip, iaUser->port, &connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1421 //-----------------------------------------------------------------------------
1422 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1424 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1425 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1427 memcpy(aliveSyn6.type, "ALIVE_SYN", 9);
1429 for (int i = 0; i < DIR_NUM; i++)
1431 aliveSyn6.md[i] = iaUser->user->GetProperties().down.Get()[i];
1432 aliveSyn6.mu[i] = iaUser->user->GetProperties().up.Get()[i];
1434 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1435 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1439 int dn = iaSettings.GetFreeMbShowType();
1440 const auto tf = iaUser->user->GetTariff();
1444 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1449 if (std::fabs(p) < 1.0e-3)
1451 memcpy(aliveSyn6.freeMb, "---", 3);
1455 double fmb = iaUser->user->GetProperties().freeMb;
1456 fmb = fmb < 0 ? 0 : fmb;
1457 snprintf(reinterpret_cast<char*>(aliveSyn6.freeMb), IA_FREEMB_LEN, "%.3f", fmb / p);
1462 if (freeMbNone == iaSettings.GetFreeMbShowType())
1464 aliveSyn6.freeMb[0] = 0;
1468 double fmb = iaUser->user->GetProperties().freeMb;
1469 fmb = fmb < 0 ? 0 : fmb;
1470 snprintf(reinterpret_cast<char*>(aliveSyn6.freeMb), IA_FREEMB_LEN, "C%.3f", fmb);
1475 if (iaUser->aliveSent)
1477 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1479 iaUser->aliveSent = true;
1482 aliveSyn6.cash = static_cast<int64_t>(iaUser->user->GetProperties().cash.Get() * 1000.0);
1483 if (!stgSettings->GetShowFeeInCash())
1484 aliveSyn6.cash -= static_cast<int64_t>((tf->GetFee() * 1000.0));
1487 SwapBytes(aliveSyn6.len);
1488 SwapBytes(aliveSyn6.rnd);
1489 SwapBytes(aliveSyn6.cash);
1490 for (int i = 0; i < DIR_NUM; ++i)
1492 SwapBytes(aliveSyn6.mu[i]);
1493 SwapBytes(aliveSyn6.md[i]);
1494 SwapBytes(aliveSyn6.su[i]);
1495 SwapBytes(aliveSyn6.sd[i]);
1499 EncryptString(&aliveSyn6, &aliveSyn6, Min8(sizeof(aliveSyn6)), &iaUser->ctx);
1500 return Send(sip, iaSettings.GetUserPort(), &aliveSyn6, Min8(sizeof(aliveSyn6)));
1502 //-----------------------------------------------------------------------------
1503 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1505 return Send_ALIVE_SYN_6(iaUser, sip);
1507 //-----------------------------------------------------------------------------
1508 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1510 memcpy(aliveSyn8.hdr.magic, IA_ID, strlen(IA_ID));
1511 aliveSyn8.hdr.protoVer[0] = 0;
1512 aliveSyn8.hdr.protoVer[1] = 8;
1514 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1515 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1517 memcpy(aliveSyn8.type, "ALIVE_SYN", 9);
1519 for (int i = 0; i < DIR_NUM; i++)
1521 aliveSyn8.md[i] = iaUser->user->GetProperties().down.Get()[i];
1522 aliveSyn8.mu[i] = iaUser->user->GetProperties().up.Get()[i];
1524 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1525 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1529 int dn = iaSettings.GetFreeMbShowType();
1533 const auto tf = iaUser->user->GetTariff();
1534 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1539 if (std::fabs(p) < 1.0e-3)
1541 memcpy(aliveSyn8.freeMb, "---", 3);
1545 double fmb = iaUser->user->GetProperties().freeMb;
1546 fmb = fmb < 0 ? 0 : fmb;
1547 snprintf(reinterpret_cast<char*>(aliveSyn8.freeMb), IA_FREEMB_LEN, "%.3f", fmb / p);
1552 if (freeMbNone == iaSettings.GetFreeMbShowType())
1554 aliveSyn8.freeMb[0] = 0;
1558 double fmb = iaUser->user->GetProperties().freeMb;
1559 fmb = fmb < 0 ? 0 : fmb;
1560 snprintf(reinterpret_cast<char*>(aliveSyn8.freeMb), IA_FREEMB_LEN, "C%.3f", fmb);
1565 if (iaUser->aliveSent)
1567 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1569 iaUser->aliveSent = true;
1572 const auto tf = iaUser->user->GetTariff();
1574 aliveSyn8.cash = static_cast<int64_t>(iaUser->user->GetProperties().cash.Get() * 1000.0);
1575 if (!stgSettings->GetShowFeeInCash())
1576 aliveSyn8.cash -= static_cast<int64_t>(tf->GetFee() * 1000.0);
1579 SwapBytes(aliveSyn8.len);
1580 SwapBytes(aliveSyn8.rnd);
1581 SwapBytes(aliveSyn8.cash);
1582 SwapBytes(aliveSyn8.status);
1583 for (int i = 0; i < DIR_NUM; ++i)
1585 SwapBytes(aliveSyn8.mu[i]);
1586 SwapBytes(aliveSyn8.md[i]);
1587 SwapBytes(aliveSyn8.su[i]);
1588 SwapBytes(aliveSyn8.sd[i]);
1592 EncryptString(&aliveSyn8, &aliveSyn8, Min8(sizeof(aliveSyn8)), &iaUser->ctx);
1593 return Send(sip, iaUser->port, &aliveSyn8, Min8(sizeof(aliveSyn8)));
1595 //-----------------------------------------------------------------------------
1596 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1598 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1599 memcpy(disconnSynAck6.type, "DISCONN_SYN_ACK", 15);
1600 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1603 SwapBytes(disconnSynAck6.len);
1604 SwapBytes(disconnSynAck6.rnd);
1607 EncryptString(&disconnSynAck6, &disconnSynAck6, Min8(sizeof(disconnSynAck6)), &iaUser->ctx);
1608 return Send(sip, iaSettings.GetUserPort(), &disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1610 //-----------------------------------------------------------------------------
1611 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1613 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1615 //-----------------------------------------------------------------------------
1616 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1618 memcpy(disconnSynAck8.hdr.magic, IA_ID, strlen(IA_ID));
1619 disconnSynAck8.hdr.protoVer[0] = 0;
1620 disconnSynAck8.hdr.protoVer[1] = 8;
1622 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1623 memcpy(disconnSynAck8.type, "DISCONN_SYN_ACK", 15);
1624 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1627 SwapBytes(disconnSynAck8.len);
1628 SwapBytes(disconnSynAck8.rnd);
1631 EncryptString(&disconnSynAck8, &disconnSynAck8, Min8(sizeof(disconnSynAck8)), &iaUser->ctx);
1632 return Send(sip, iaUser->port, &disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1634 //-----------------------------------------------------------------------------
1635 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1637 fin6.len = Min8(sizeof(FIN_6));
1638 memcpy(fin6.type, "FIN", 3);
1639 memcpy(fin6.ok, "OK", 2);
1642 SwapBytes(fin6.len);
1645 EncryptString(&fin6, &fin6, Min8(sizeof(fin6)), &iaUser->ctx);
1647 users->Unauthorize(iaUser->login, this);
1649 int res = Send(sip, iaSettings.GetUserPort(), &fin6, Min8(sizeof(fin6)));
1655 //-----------------------------------------------------------------------------
1656 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1658 return Send_FIN_6(iaUser, sip, it);
1660 //-----------------------------------------------------------------------------
1661 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1663 memcpy(fin8.hdr.magic, IA_ID, strlen(IA_ID));
1664 fin8.hdr.protoVer[0] = 0;
1665 fin8.hdr.protoVer[1] = 8;
1667 fin8.len = Min8(sizeof(FIN_8));
1668 memcpy(fin8.type, "FIN", 3);
1669 memcpy(fin8.ok, "OK", 2);
1672 SwapBytes(fin8.len);
1675 EncryptString(&fin8, &fin8, Min8(sizeof(fin8)), &iaUser->ctx);
1677 users->Unauthorize(iaUser->login, this);
1679 int res = Send(sip, iaUser->port, &fin8, Min8(sizeof(fin8)));