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/tariff.h"
29 #include "stg/settings.h"
34 #include <cstdio> // snprintf
38 #include <sys/types.h>
39 #include <sys/socket.h>
40 #include <unistd.h> // close
42 #define IA_PROTO_VER (6)
44 extern volatile time_t stgTime;
46 extern "C" STG::Plugin* GetPlugin()
48 static AUTH_IA plugin;
51 //-----------------------------------------------------------------------------
52 //-----------------------------------------------------------------------------
53 //-----------------------------------------------------------------------------
54 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
58 freeMbShowType(freeMbCash),
59 logProtocolErrors(false)
62 //-----------------------------------------------------------------------------
63 int AUTH_IA_SETTINGS::ParseSettings(const STG::ModuleSettings & s)
67 std::vector<STG::ParamValue>::const_iterator pvi;
68 ///////////////////////////
70 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
71 if (pvi == s.moduleParams.end() || pvi->value.empty())
73 errorStr = "Parameter \'Port\' not found.";
74 printfd(__FILE__, "Parameter 'Port' not found\n");
77 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
79 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
80 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
83 port = static_cast<uint16_t>(p);
84 ///////////////////////////
85 pv.param = "UserDelay";
86 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
87 if (pvi == s.moduleParams.end() || pvi->value.empty())
89 errorStr = "Parameter \'UserDelay\' not found.";
90 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
94 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
96 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
97 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
100 ///////////////////////////
101 pv.param = "UserTimeout";
102 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
103 if (pvi == s.moduleParams.end() || pvi->value.empty())
105 errorStr = "Parameter \'UserTimeout\' not found.";
106 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
110 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
112 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
113 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
116 ///////////////////////////
117 pv.param = "LogProtocolErrors";
118 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
119 if (pvi == s.moduleParams.end() || pvi->value.empty())
120 logProtocolErrors = false;
121 else if (ParseYesNo(pvi->value[0], &logProtocolErrors))
123 errorStr = "Cannot parse parameter \'LogProtocolErrors\': " + errorStr;
124 printfd(__FILE__, "Cannot parse parameter 'LogProtocolErrors'\n");
127 /////////////////////////////////////////////////////////////
128 std::string freeMbType;
131 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
132 if (pvi == s.moduleParams.end() || pvi->value.empty())
134 errorStr = "Parameter \'FreeMb\' not found.";
135 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
138 freeMbType = pvi->value[0];
140 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
142 freeMbShowType = freeMbCash;
144 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
146 freeMbShowType = freeMbNone;
148 else if (!str2x(freeMbType.c_str(), n))
150 if (n < 0 || n >= DIR_NUM)
152 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
153 printfd(__FILE__, "%s\n", errorStr.c_str());
156 freeMbShowType = static_cast<FREEMB>(n);
160 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
161 printfd(__FILE__, "%s\n", errorStr.c_str());
164 /////////////////////////////////////////////////////////////
167 //-----------------------------------------------------------------------------
168 //-----------------------------------------------------------------------------
169 //-----------------------------------------------------------------------------
170 #ifdef IA_PHASE_DEBUG
175 gettimeofday(&phaseTime, NULL);
181 gettimeofday(&phaseTime, NULL);
184 //-----------------------------------------------------------------------------
185 IA_PHASE::~IA_PHASE()
187 #ifdef IA_PHASE_DEBUG
188 flog = fopen(log.c_str(), "at");
191 fprintf(flog, "IA %s D\n", login.c_str());
196 //-----------------------------------------------------------------------------
197 #ifdef IA_PHASE_DEBUG
198 void IA_PHASE::SetLogFileName(const string & logFileName)
200 log = logFileName + ".ia.log";
202 //-----------------------------------------------------------------------------
203 void IA_PHASE::SetUserLogin(const string & login)
205 IA_PHASE::login = login;
207 //-----------------------------------------------------------------------------
208 void IA_PHASE::WritePhaseChange(int newPhase)
211 gettimeofday(&newPhaseTime, NULL);
212 flog = fopen(log.c_str(), "at");
215 string action = newPhase == phase ? "U" : "C";
216 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
217 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
218 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
228 //-----------------------------------------------------------------------------
229 void IA_PHASE::SetPhase1()
231 #ifdef IA_PHASE_DEBUG
235 gettimeofday(&phaseTime, NULL);
237 //-----------------------------------------------------------------------------
238 void IA_PHASE::SetPhase2()
240 #ifdef IA_PHASE_DEBUG
244 gettimeofday(&phaseTime, NULL);
246 //-----------------------------------------------------------------------------
247 void IA_PHASE::SetPhase3()
249 #ifdef IA_PHASE_DEBUG
253 gettimeofday(&phaseTime, NULL);
255 //-----------------------------------------------------------------------------
256 void IA_PHASE::SetPhase4()
258 #ifdef IA_PHASE_DEBUG
262 gettimeofday(&phaseTime, NULL);
264 //-----------------------------------------------------------------------------
265 int IA_PHASE::GetPhase() const
269 //-----------------------------------------------------------------------------
270 void IA_PHASE::UpdateTime()
272 #ifdef IA_PHASE_DEBUG
273 WritePhaseChange(phase);
275 gettimeofday(&phaseTime, NULL);
277 //-----------------------------------------------------------------------------
278 const UTIME & IA_PHASE::GetTime() const
282 //-----------------------------------------------------------------------------
283 //-----------------------------------------------------------------------------
284 //-----------------------------------------------------------------------------
286 : isRunningRun(false),
287 isRunningRunTimeouter(false),
291 enabledDirs(0xFFffFFff),
292 logger(STG::PluginLogger::get("auth_ia"))
294 InitContext("pr7Hhen", 7, &ctxS);
296 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
297 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
298 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
299 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
300 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
301 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
302 memset(&fin6, 0, sizeof(FIN_6));
303 memset(&fin8, 0, sizeof(FIN_8));
305 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
306 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
307 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
308 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
309 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
310 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
311 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
312 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
313 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
314 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
315 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
316 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
317 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
318 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
319 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
320 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
321 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
322 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
324 packetTypes["CONN_SYN"] = CONN_SYN_N;
325 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
326 packetTypes["CONN_ACK"] = CONN_ACK_N;
327 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
328 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
329 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
330 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
331 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
332 packetTypes["FIN"] = FIN_N;
333 packetTypes["ERR"] = ERROR_N;
335 //-----------------------------------------------------------------------------
339 //-----------------------------------------------------------------------------
342 m_onDelUserConn = users->onDel([this](auto user){ DelUser(user); });
347 if (!m_thread.joinable())
348 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
350 if (!m_timeouterThread.joinable())
351 m_timeouterThread = std::jthread([this](auto token){ RunTimeouter(std::move(token)); });
356 //-----------------------------------------------------------------------------
362 m_thread.request_stop();
363 m_timeouterThread.request_stop();
368 UnauthorizeUser(this)
373 //5 seconds to thread stops itself
374 for (int i = 0; i < 25 && isRunningRun; i++)
376 struct timespec ts = {0, 200000000};
377 nanosleep(&ts, NULL);
383 if (isRunningRunTimeouter)
385 //5 seconds to thread stops itself
386 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
388 struct timespec ts = {0, 200000000};
389 nanosleep(&ts, NULL);
393 m_onDelUserConn.disconnect();
400 if (isRunningRunTimeouter)
401 m_timeouterThread.detach();
403 m_timeouterThread.join();
405 if (isRunningRun || isRunningRunTimeouter)
408 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
411 //-----------------------------------------------------------------------------
412 void AUTH_IA::Run(std::stop_token token)
415 sigfillset(&signalSet);
416 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
422 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
424 while (!token.stop_requested())
426 RecvData(buffer, sizeof(buffer));
427 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && stgSettings->GetMonitoring())
430 std::string monFile = stgSettings->GetMonitorDir() + "/inetaccess_r";
435 isRunningRun = false;
437 //-----------------------------------------------------------------------------
438 void AUTH_IA::RunTimeouter(std::stop_token token)
441 sigfillset(&signalSet);
442 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
444 isRunningRunTimeouter = true;
447 std::string monFile = stgSettings->GetMonitorDir() + "/inetaccess_t";
448 while (!token.stop_requested())
450 struct timespec ts = {0, 20000000};
451 nanosleep(&ts, NULL);
453 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
454 if (++a % (50 * 60) == 0 && stgSettings->GetMonitoring())
460 isRunningRunTimeouter = false;
462 //-----------------------------------------------------------------------------
463 int AUTH_IA::ParseSettings()
465 int ret = iaSettings.ParseSettings(settings);
467 errorStr = iaSettings.GetStrError();
470 //-----------------------------------------------------------------------------
471 int AUTH_IA::Reload(const STG::ModuleSettings & ms)
473 AUTH_IA_SETTINGS newIaSettings;
474 if (newIaSettings.ParseSettings(ms))
476 printfd(__FILE__, "AUTH_IA::Reload() - Failed to reload InetAccess.\n");
477 logger("AUTH_IA: Cannot reload InetAccess. Errors found.");
481 printfd(__FILE__, "AUTH_IA::Reload() - Reloaded InetAccess successfully.\n");
482 logger("AUTH_IA: Reloaded InetAccess successfully.");
483 iaSettings = newIaSettings;
486 //-----------------------------------------------------------------------------
487 int AUTH_IA::PrepareNet()
489 struct sockaddr_in listenAddr;
491 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
493 if (listenSocket < 0)
495 errorStr = "Cannot create socket.";
496 logger("Cannot create a socket: %s", strerror(errno));
500 listenAddr.sin_family = AF_INET;
501 listenAddr.sin_port = htons(iaSettings.GetUserPort());
502 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
504 if (bind(listenSocket, reinterpret_cast<sockaddr*>(&listenAddr), sizeof(listenAddr)) < 0)
506 errorStr = "AUTH_IA: Bind failed.";
507 logger("Cannot bind the socket: %s", strerror(errno));
513 //-----------------------------------------------------------------------------
514 int AUTH_IA::FinalizeNet()
519 //-----------------------------------------------------------------------------
520 int AUTH_IA::RecvData(char * buffer, int bufferSize)
522 if (!WaitPackets(listenSocket)) // Timeout
527 struct sockaddr_in outerAddr;
528 socklen_t outerAddrLen(sizeof(outerAddr));
529 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, reinterpret_cast<sockaddr *>(&outerAddr), &outerAddrLen);
536 if (dataLen <= 0) // Error
540 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
541 logger("recvfrom error: %s", strerror(errno));
550 uint32_t sip = outerAddr.sin_addr.s_addr;
551 uint16_t sport = htons(outerAddr.sin_port);
554 if (CheckHeader(buffer, sip, &protoVer))
557 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
558 memset(login, 0, PASSWD_LEN);
560 DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS);
563 if (users->FindByName(login, &user))
565 logger("User's connect failed: user '%s' not found. IP %s",
567 inet_ntostring(sip).c_str());
568 printfd(__FILE__, "User '%s' NOT found!\n", login);
569 SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
573 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
575 if (user->GetProperties().disabled.Get())
577 logger("Cannont authorize '%s', user is disabled.", login);
578 SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
582 if (user->GetProperties().passive.Get())
584 logger("Cannont authorize '%s', user is passive.", login);
585 SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
589 if (!user->GetProperties().ips.Get().find(sip))
591 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
592 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
593 logger("User %s. IP address is incorrect. IP %s",
594 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
595 SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
599 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
601 //-----------------------------------------------------------------------------
602 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
604 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
606 printfd(__FILE__, "update needed - IA_ID\n");
607 if (iaSettings.LogProtocolErrors())
608 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
612 if (buffer[6] != 0) //proto[0] shoud be 0
614 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
615 if (iaSettings.LogProtocolErrors())
616 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
623 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
624 if (iaSettings.LogProtocolErrors())
625 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
630 *protoVer = buffer[7];
634 //-----------------------------------------------------------------------------
635 int AUTH_IA::Timeouter()
637 std::lock_guard lock(m_mutex);
639 std::map<uint32_t, IA_USER>::iterator it;
640 it = ip2user.begin();
642 while (it != ip2user.end())
644 uint32_t sip = it->first;
646 static UTIME currTime;
647 gettimeofday(&currTime, NULL);
649 if ((it->second.phase.GetPhase() == 2)
650 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
652 if (iaSettings.LogProtocolErrors())
653 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());
654 it->second.phase.SetPhase1();
655 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
660 if (it->second.phase.GetPhase() == 3)
662 if (!it->second.messagesToSend.empty())
664 if (it->second.protoVer == 6)
665 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
667 if (it->second.protoVer == 7)
668 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
670 if (it->second.protoVer == 8)
671 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
673 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
676 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
678 switch (it->second.protoVer)
681 Send_ALIVE_SYN_6(&(it->second), sip);
684 Send_ALIVE_SYN_7(&(it->second), sip);
687 Send_ALIVE_SYN_8(&(it->second), sip);
691 gettimeofday(&it->second.lastSendAlive, NULL);
694 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
696 if (iaSettings.LogProtocolErrors())
697 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());
698 users->Unauthorize(it->second.user->GetLogin(), this);
704 if ((it->second.phase.GetPhase() == 4)
705 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
707 if (iaSettings.LogProtocolErrors())
708 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());
709 it->second.phase.SetPhase3();
710 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
718 //-----------------------------------------------------------------------------
719 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, UserPtr user)
721 std::string login(user->GetLogin());
722 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
724 std::lock_guard lock(m_mutex);
725 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
727 if (it == ip2user.end())
730 if (!users->FindByIPIdx(sip, &userPtr))
732 if (userPtr->GetID() != user->GetID())
734 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
735 userPtr->GetLogin().c_str(),
736 inet_ntostring(sip).c_str(),
738 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
739 userPtr->GetLogin().c_str(),
740 inet_ntostring(sip).c_str(),
742 SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
747 printfd(__FILE__, "Add new user '%s' from ip %s\n",
748 login.c_str(), inet_ntostring(sip).c_str());
749 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
750 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
752 #ifdef IA_PHASE_DEBUG
753 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
754 it->second.phase.SetUserLogin(login);
757 else if (user->GetID() != it->second.user->GetID())
759 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
760 it->second.user->GetLogin().c_str(),
761 inet_ntostring(sip).c_str(),
762 user->GetLogin().c_str());
763 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
764 it->second.user->GetLogin().c_str(),
765 inet_ntostring(sip).c_str(),
766 user->GetLogin().c_str());
767 SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
771 IA_USER * iaUser = &(it->second);
773 if (iaUser->password != user->GetProperties().password.Get())
775 const std::string & password = user->GetProperties().password.Get();
776 InitContext(password.c_str(), password.length(), &iaUser->ctx);
777 iaUser->password = user->GetProperties().password.Get();
780 DecryptString(static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
782 char packetName[IA_MAX_TYPE_LEN];
783 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
784 packetName[IA_MAX_TYPE_LEN - 1] = 0;
786 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
787 if (pi == packetTypes.end())
789 SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
790 printfd(__FILE__, "Login or password is wrong!\n");
791 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
793 inet_ntostring(sip).c_str());
798 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
800 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
801 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
802 inet_ntostring(sip).c_str());
803 logger("Login '%s' is already in use from ip %s. IP %s",
805 inet_ntostring(user->GetCurrIP()).c_str(),
806 inet_ntostring(sip).c_str());
807 SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
818 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
820 return Send_CONN_SYN_ACK_6(iaUser, sip);
822 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
824 return Send_CONN_SYN_ACK_7(iaUser, sip);
826 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
828 return Send_CONN_SYN_ACK_8(iaUser, sip);
836 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
838 return Send_ALIVE_SYN_6(iaUser, sip);
840 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
842 return Send_ALIVE_SYN_7(iaUser, sip);
844 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
846 return Send_ALIVE_SYN_8(iaUser, sip);
854 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
856 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
858 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
866 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
868 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
870 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
872 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
874 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
876 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
884 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
886 return Send_FIN_6(iaUser, sip, it);
888 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
890 return Send_FIN_7(iaUser, sip, it);
892 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
894 return Send_FIN_8(iaUser, sip, it);
901 //-----------------------------------------------------------------------------
902 void AUTH_IA::DelUser(UserPtr u)
905 uint32_t ip = u->GetCurrIP();
910 std::map<uint32_t, IA_USER>::iterator it;
912 std::lock_guard lock(m_mutex);
913 it = ip2user.find(ip);
914 if (it == ip2user.end())
917 printfd(__FILE__, "Nothing to delete\n");
921 if (it->second.user == u)
923 printfd(__FILE__, "User removed!\n");
924 users->Unauthorize(u->GetLogin(), this);
928 //-----------------------------------------------------------------------------
929 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
931 struct sockaddr_in sendAddr;
938 memset(&err, 0, sizeof(ERR));
940 sendAddr.sin_family = AF_INET;
941 sendAddr.sin_port = htons(port);
942 sendAddr.sin_addr.s_addr = ip;
945 memcpy(err.type, "ERR", 3);
946 memcpy(err.text, text.c_str(), std::min<size_t>(text.length(), MAX_MSG_LEN));
952 res = sendto(listenSocket, &err, sizeof(err), 0, reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr));
953 printfd(__FILE__, "SendError %d bytes sent\n", res);
958 memset(&err8, 0, sizeof(ERR_8));
960 sendAddr.sin_family = AF_INET;
961 sendAddr.sin_port = htons(port);
962 sendAddr.sin_addr.s_addr = ip;
965 memcpy(err8.type, "ERR", 3);
966 memcpy(err8.text, text.c_str(), std::min<size_t>(text.length(), MAX_MSG_LEN));
972 res = sendto(listenSocket, &err8, sizeof(err8), 0, reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr));
973 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
979 //-----------------------------------------------------------------------------
980 int AUTH_IA::Send(uint32_t ip, uint16_t port, const void* buffer, size_t len)
982 struct sockaddr_in sendAddr;
984 sendAddr.sin_family = AF_INET;
985 sendAddr.sin_port = htons(port);
986 sendAddr.sin_addr.s_addr = ip;
988 if (sendto(listenSocket, buffer, len, 0, reinterpret_cast<sockaddr*>(&sendAddr), sizeof(sendAddr)) == static_cast<ssize_t>(len))
993 //-----------------------------------------------------------------------------
994 int AUTH_IA::SendMessage(const STG::Message & msg, uint32_t ip) const
996 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
998 std::map<uint32_t, IA_USER>::iterator it;
1000 std::lock_guard lock(m_mutex);
1001 it = ip2user.find(ip);
1002 if (it == ip2user.end())
1004 errorStr = "Unknown user.";
1007 it->second.messagesToSend.push_back(msg);
1010 //-----------------------------------------------------------------------------
1011 int AUTH_IA::RealSendMessage6(const STG::Message & msg, uint32_t ip, IA_USER & user)
1013 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1016 memset(&info, 0, sizeof(INFO_6));
1019 memcpy(info.type, "INFO", 4);
1020 info.infoType = 'I';
1021 memcpy(info.text, msg.text.c_str(), std::min<size_t>(msg.text.length(), 235));
1024 size_t len = info.len;
1026 SwapBytes(info.len);
1030 memcpy(buffer, &info, sizeof(INFO_6));
1031 EncryptString(buffer, buffer, len, &user.ctx);
1032 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1034 //-----------------------------------------------------------------------------
1035 int AUTH_IA::RealSendMessage7(const STG::Message & msg, uint32_t ip, IA_USER & user)
1037 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1040 memset(&info, 0, sizeof(INFO_7));
1043 memcpy(info.type, "INFO_7", 6);
1044 info.infoType = static_cast<int8_t>(msg.header.type);
1045 info.showTime = static_cast<int8_t>(msg.header.showTime);
1046 info.sendTime = msg.header.creationTime;
1048 size_t len = info.len;
1050 SwapBytes(info.len);
1051 SwapBytes(info.sendTime);
1054 memcpy(info.text, msg.text.c_str(), std::min<size_t>(msg.text.length(), MAX_MSG_LEN - 1));
1055 info.text[MAX_MSG_LEN - 1] = 0;
1058 memcpy(buffer, &info, sizeof(INFO_7));
1060 EncryptString(buffer, buffer, len, &user.ctx);
1061 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1063 //-----------------------------------------------------------------------------
1064 int AUTH_IA::RealSendMessage8(const STG::Message & msg, uint32_t ip, IA_USER & user)
1066 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1069 memset(&info, 0, sizeof(INFO_8));
1072 memcpy(info.type, "INFO_8", 6);
1073 info.infoType = static_cast<int8_t>(msg.header.type);
1074 info.showTime = static_cast<int8_t>(msg.header.showTime);
1075 info.sendTime = msg.header.creationTime;
1077 memcpy(info.text, msg.text.c_str(), std::min<size_t>(msg.text.length(), IA_MAX_MSG_LEN_8 - 1));
1078 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1080 size_t len = info.len;
1082 SwapBytes(info.len);
1083 SwapBytes(info.sendTime);
1087 memcpy(buffer, &info, sizeof(INFO_8));
1089 EncryptString(buffer, buffer, len, &user.ctx);
1090 return Send(ip, user.port, buffer, len);
1092 //-----------------------------------------------------------------------------
1093 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1095 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1098 enabledDirs = 0xFFffFFff;
1100 iaUser->phase.SetPhase2();
1101 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1104 //-----------------------------------------------------------------------------
1105 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1107 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1109 //-----------------------------------------------------------------------------
1110 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1113 SwapBytes(connSyn->dirs);
1115 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1116 enabledDirs = connSyn->dirs;
1119 //-----------------------------------------------------------------------------
1120 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1123 SwapBytes(connAck->len);
1124 SwapBytes(connAck->rnd);
1126 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1128 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1130 iaUser->phase.UpdateTime();
1132 iaUser->lastSendAlive = iaUser->phase.GetTime();
1133 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1135 iaUser->phase.SetPhase3();
1136 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1141 errorStr = iaUser->user->GetStrError();
1142 if (iaSettings.LogProtocolErrors())
1143 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());
1144 iaUser->phase.SetPhase1();
1146 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1150 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d, expected: %d\n", iaUser->phase.GetPhase(), connAck->rnd, iaUser->rnd + 1);
1151 if (iaSettings.LogProtocolErrors())
1153 if (iaUser->phase.GetPhase() != 2)
1154 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());
1155 if (connAck->rnd != iaUser->rnd + 1)
1156 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);
1160 //-----------------------------------------------------------------------------
1161 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1163 return Process_CONN_ACK_6(connAck, iaUser, sip);
1165 //-----------------------------------------------------------------------------
1166 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1169 SwapBytes(connAck->len);
1170 SwapBytes(connAck->rnd);
1172 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1174 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1176 iaUser->phase.UpdateTime();
1177 iaUser->lastSendAlive = iaUser->phase.GetTime();
1178 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1180 iaUser->phase.SetPhase3();
1181 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1186 errorStr = iaUser->user->GetStrError();
1187 if (iaSettings.LogProtocolErrors())
1188 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());
1189 iaUser->phase.SetPhase1();
1191 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1195 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d, expected: %d\n", iaUser->phase.GetPhase(), connAck->rnd, iaUser->rnd + 1);
1196 if (iaSettings.LogProtocolErrors())
1198 if (iaUser->phase.GetPhase() != 2)
1199 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());
1200 if (connAck->rnd != iaUser->rnd + 1)
1201 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);
1205 //-----------------------------------------------------------------------------
1206 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1209 SwapBytes(aliveAck->len);
1210 SwapBytes(aliveAck->rnd);
1212 printfd(__FILE__, "ALIVE_ACK_6\n");
1213 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1215 iaUser->phase.UpdateTime();
1217 iaUser->aliveSent = false;
1222 //-----------------------------------------------------------------------------
1223 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1225 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1227 //-----------------------------------------------------------------------------
1228 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1231 SwapBytes(aliveAck->len);
1232 SwapBytes(aliveAck->rnd);
1234 printfd(__FILE__, "ALIVE_ACK_8\n");
1235 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1237 iaUser->phase.UpdateTime();
1239 iaUser->aliveSent = false;
1244 //-----------------------------------------------------------------------------
1245 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1247 printfd(__FILE__, "DISCONN_SYN_6\n");
1248 if (iaUser->phase.GetPhase() != 3)
1250 if (iaSettings.LogProtocolErrors())
1251 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());
1252 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1253 errorStr = "Incorrect request DISCONN_SYN";
1257 iaUser->phase.SetPhase4();
1258 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1262 //-----------------------------------------------------------------------------
1263 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1265 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1267 //-----------------------------------------------------------------------------
1268 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1270 if (iaUser->phase.GetPhase() != 3)
1272 if (iaSettings.LogProtocolErrors())
1273 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());
1274 errorStr = "Incorrect request DISCONN_SYN";
1275 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1279 iaUser->phase.SetPhase4();
1280 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1284 //-----------------------------------------------------------------------------
1285 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1288 std::map<uint32_t, IA_USER>::iterator)
1291 SwapBytes(disconnAck->len);
1292 SwapBytes(disconnAck->rnd);
1294 printfd(__FILE__, "DISCONN_ACK_6\n");
1295 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1297 if (iaSettings.LogProtocolErrors())
1299 if (iaUser->phase.GetPhase() != 4)
1300 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());
1301 if (disconnAck->rnd != iaUser->rnd + 1)
1302 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);
1304 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1310 //-----------------------------------------------------------------------------
1311 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)
1313 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1315 //-----------------------------------------------------------------------------
1316 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1319 SwapBytes(disconnAck->len);
1320 SwapBytes(disconnAck->rnd);
1322 printfd(__FILE__, "DISCONN_ACK_8\n");
1323 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1325 if (iaSettings.LogProtocolErrors())
1327 if (iaUser->phase.GetPhase() != 4)
1328 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());
1329 if (disconnAck->rnd != iaUser->rnd + 1)
1330 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);
1332 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1338 //-----------------------------------------------------------------------------
1339 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1341 //+++ Fill static data in connSynAck +++
1342 // TODO Move this code. It must be executed only once
1343 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1344 memcpy(connSynAck6.type, "CONN_SYN_ACK", 12);
1345 for (int j = 0; j < DIR_NUM; j++)
1347 memcpy(connSynAck6.dirName[j],
1348 stgSettings->GetDirName(j).c_str(),
1349 std::min(stgSettings->GetDirName(j).length(), sizeof(string16)));
1351 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1353 //--- Fill static data in connSynAck ---
1355 iaUser->rnd = static_cast<uint32_t>(random());
1356 connSynAck6.rnd = iaUser->rnd;
1358 printfd(__FILE__, "Sending CONN_SYN_ACK with control number %d.\n", iaUser->rnd);
1360 connSynAck6.userTimeOut = iaSettings.GetUserTimeout().GetSec();
1361 connSynAck6.aliveDelay = iaSettings.GetUserDelay().GetSec();
1364 SwapBytes(connSynAck6.len);
1365 SwapBytes(connSynAck6.rnd);
1366 SwapBytes(connSynAck6.userTimeOut);
1367 SwapBytes(connSynAck6.aliveDelay);
1370 EncryptString(&connSynAck6, &connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)), &iaUser->ctx);
1371 return Send(sip, iaSettings.GetUserPort(), &connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1373 //-----------------------------------------------------------------------------
1374 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1376 return Send_CONN_SYN_ACK_6(iaUser, sip);
1378 //-----------------------------------------------------------------------------
1379 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1381 memcpy(connSynAck8.hdr.magic, IA_ID, strlen(IA_ID));
1382 connSynAck8.hdr.protoVer[0] = 0;
1383 connSynAck8.hdr.protoVer[1] = 8;
1385 //+++ Fill static data in connSynAck +++
1386 // TODO Move this code. It must be executed only once
1387 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1388 memcpy(connSynAck8.type, "CONN_SYN_ACK", 12);
1389 for (int j = 0; j < DIR_NUM; j++)
1391 memcpy(connSynAck8.dirName[j],
1392 stgSettings->GetDirName(j).c_str(),
1393 std::min(stgSettings->GetDirName(j).length(), sizeof(string16)));
1395 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1397 //--- Fill static data in connSynAck ---
1399 iaUser->rnd = static_cast<uint32_t>(random());
1400 connSynAck8.rnd = iaUser->rnd;
1402 printfd(__FILE__, "Sending CONN_SYN_ACK with control number %d.\n", iaUser->rnd);
1404 connSynAck8.userTimeOut = iaSettings.GetUserTimeout().GetSec();
1405 connSynAck8.aliveDelay = iaSettings.GetUserDelay().GetSec();
1408 SwapBytes(connSynAck8.len);
1409 SwapBytes(connSynAck8.rnd);
1410 SwapBytes(connSynAck8.userTimeOut);
1411 SwapBytes(connSynAck8.aliveDelay);
1414 EncryptString(&connSynAck8, &connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)), &iaUser->ctx);
1415 return Send(sip, iaUser->port, &connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1417 //-----------------------------------------------------------------------------
1418 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1420 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1421 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1423 memcpy(aliveSyn6.type, "ALIVE_SYN", 9);
1425 for (int i = 0; i < DIR_NUM; i++)
1427 aliveSyn6.md[i] = iaUser->user->GetProperties().down.Get()[i];
1428 aliveSyn6.mu[i] = iaUser->user->GetProperties().up.Get()[i];
1430 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1431 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1435 int dn = iaSettings.GetFreeMbShowType();
1436 const auto tf = iaUser->user->GetTariff();
1440 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1445 if (std::fabs(p) < 1.0e-3)
1447 memcpy(aliveSyn6.freeMb, "---", 3);
1451 double fmb = iaUser->user->GetProperties().freeMb;
1452 fmb = fmb < 0 ? 0 : fmb;
1453 snprintf(reinterpret_cast<char*>(aliveSyn6.freeMb), IA_FREEMB_LEN, "%.3f", fmb / p);
1458 if (freeMbNone == iaSettings.GetFreeMbShowType())
1460 aliveSyn6.freeMb[0] = 0;
1464 double fmb = iaUser->user->GetProperties().freeMb;
1465 fmb = fmb < 0 ? 0 : fmb;
1466 snprintf(reinterpret_cast<char*>(aliveSyn6.freeMb), IA_FREEMB_LEN, "C%.3f", fmb);
1471 if (iaUser->aliveSent)
1473 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1475 iaUser->aliveSent = true;
1478 aliveSyn6.cash = static_cast<int64_t>(iaUser->user->GetProperties().cash.Get() * 1000.0);
1479 if (!stgSettings->GetShowFeeInCash())
1480 aliveSyn6.cash -= static_cast<int64_t>((tf->GetFee() * 1000.0));
1483 SwapBytes(aliveSyn6.len);
1484 SwapBytes(aliveSyn6.rnd);
1485 SwapBytes(aliveSyn6.cash);
1486 for (int i = 0; i < DIR_NUM; ++i)
1488 SwapBytes(aliveSyn6.mu[i]);
1489 SwapBytes(aliveSyn6.md[i]);
1490 SwapBytes(aliveSyn6.su[i]);
1491 SwapBytes(aliveSyn6.sd[i]);
1495 EncryptString(&aliveSyn6, &aliveSyn6, Min8(sizeof(aliveSyn6)), &iaUser->ctx);
1496 return Send(sip, iaSettings.GetUserPort(), &aliveSyn6, Min8(sizeof(aliveSyn6)));
1498 //-----------------------------------------------------------------------------
1499 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1501 return Send_ALIVE_SYN_6(iaUser, sip);
1503 //-----------------------------------------------------------------------------
1504 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1506 memcpy(aliveSyn8.hdr.magic, IA_ID, strlen(IA_ID));
1507 aliveSyn8.hdr.protoVer[0] = 0;
1508 aliveSyn8.hdr.protoVer[1] = 8;
1510 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1511 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1513 memcpy(aliveSyn8.type, "ALIVE_SYN", 9);
1515 for (int i = 0; i < DIR_NUM; i++)
1517 aliveSyn8.md[i] = iaUser->user->GetProperties().down.Get()[i];
1518 aliveSyn8.mu[i] = iaUser->user->GetProperties().up.Get()[i];
1520 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1521 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1525 int dn = iaSettings.GetFreeMbShowType();
1529 const auto tf = iaUser->user->GetTariff();
1530 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1535 if (std::fabs(p) < 1.0e-3)
1537 memcpy(aliveSyn8.freeMb, "---", 3);
1541 double fmb = iaUser->user->GetProperties().freeMb;
1542 fmb = fmb < 0 ? 0 : fmb;
1543 snprintf(reinterpret_cast<char*>(aliveSyn8.freeMb), IA_FREEMB_LEN, "%.3f", fmb / p);
1548 if (freeMbNone == iaSettings.GetFreeMbShowType())
1550 aliveSyn8.freeMb[0] = 0;
1554 double fmb = iaUser->user->GetProperties().freeMb;
1555 fmb = fmb < 0 ? 0 : fmb;
1556 snprintf(reinterpret_cast<char*>(aliveSyn8.freeMb), IA_FREEMB_LEN, "C%.3f", fmb);
1561 if (iaUser->aliveSent)
1563 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1565 iaUser->aliveSent = true;
1568 const auto tf = iaUser->user->GetTariff();
1570 aliveSyn8.cash = static_cast<int64_t>(iaUser->user->GetProperties().cash.Get() * 1000.0);
1571 if (!stgSettings->GetShowFeeInCash())
1572 aliveSyn8.cash -= static_cast<int64_t>(tf->GetFee() * 1000.0);
1575 SwapBytes(aliveSyn8.len);
1576 SwapBytes(aliveSyn8.rnd);
1577 SwapBytes(aliveSyn8.cash);
1578 SwapBytes(aliveSyn8.status);
1579 for (int i = 0; i < DIR_NUM; ++i)
1581 SwapBytes(aliveSyn8.mu[i]);
1582 SwapBytes(aliveSyn8.md[i]);
1583 SwapBytes(aliveSyn8.su[i]);
1584 SwapBytes(aliveSyn8.sd[i]);
1588 EncryptString(&aliveSyn8, &aliveSyn8, Min8(sizeof(aliveSyn8)), &iaUser->ctx);
1589 return Send(sip, iaUser->port, &aliveSyn8, Min8(sizeof(aliveSyn8)));
1591 //-----------------------------------------------------------------------------
1592 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1594 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1595 memcpy(disconnSynAck6.type, "DISCONN_SYN_ACK", 15);
1596 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1599 SwapBytes(disconnSynAck6.len);
1600 SwapBytes(disconnSynAck6.rnd);
1603 EncryptString(&disconnSynAck6, &disconnSynAck6, Min8(sizeof(disconnSynAck6)), &iaUser->ctx);
1604 return Send(sip, iaSettings.GetUserPort(), &disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1606 //-----------------------------------------------------------------------------
1607 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1609 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1611 //-----------------------------------------------------------------------------
1612 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1614 memcpy(disconnSynAck8.hdr.magic, IA_ID, strlen(IA_ID));
1615 disconnSynAck8.hdr.protoVer[0] = 0;
1616 disconnSynAck8.hdr.protoVer[1] = 8;
1618 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1619 memcpy(disconnSynAck8.type, "DISCONN_SYN_ACK", 15);
1620 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1623 SwapBytes(disconnSynAck8.len);
1624 SwapBytes(disconnSynAck8.rnd);
1627 EncryptString(&disconnSynAck8, &disconnSynAck8, Min8(sizeof(disconnSynAck8)), &iaUser->ctx);
1628 return Send(sip, iaUser->port, &disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1630 //-----------------------------------------------------------------------------
1631 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1633 fin6.len = Min8(sizeof(FIN_6));
1634 memcpy(fin6.type, "FIN", 3);
1635 memcpy(fin6.ok, "OK", 2);
1638 SwapBytes(fin6.len);
1641 EncryptString(&fin6, &fin6, Min8(sizeof(fin6)), &iaUser->ctx);
1643 users->Unauthorize(iaUser->login, this);
1645 int res = Send(sip, iaSettings.GetUserPort(), &fin6, Min8(sizeof(fin6)));
1651 //-----------------------------------------------------------------------------
1652 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1654 return Send_FIN_6(iaUser, sip, it);
1656 //-----------------------------------------------------------------------------
1657 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1659 memcpy(fin8.hdr.magic, IA_ID, strlen(IA_ID));
1660 fin8.hdr.protoVer[0] = 0;
1661 fin8.hdr.protoVer[1] = 8;
1663 fin8.len = Min8(sizeof(FIN_8));
1664 memcpy(fin8.type, "FIN", 3);
1665 memcpy(fin8.ok, "OK", 2);
1668 SwapBytes(fin8.len);
1671 EncryptString(&fin8, &fin8, Min8(sizeof(fin8)), &iaUser->ctx);
1673 users->Unauthorize(iaUser->login, this);
1675 int res = Send(sip, iaUser->port, &fin8, Min8(sizeof(fin8)));