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 = (FREEMB)(freeMb0 + 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 //-----------------------------------------------------------------------------
289 isRunningRunTimeouter(false),
293 enabledDirs(0xFFffFFff),
294 onDelUserNotifier(*this),
295 logger(STG::PluginLogger::get("auth_ia"))
297 InitContext("pr7Hhen", 7, &ctxS);
299 pthread_mutexattr_t attr;
300 pthread_mutexattr_init(&attr);
301 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
302 pthread_mutex_init(&mutex, &attr);
304 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
305 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
306 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
307 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
308 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
309 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
310 memset(&fin6, 0, sizeof(FIN_6));
311 memset(&fin8, 0, sizeof(FIN_8));
313 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
314 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
315 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
316 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
317 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
318 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
319 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
320 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
321 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
322 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
323 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
324 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
325 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
326 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
327 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
328 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
329 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
330 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
332 packetTypes["CONN_SYN"] = CONN_SYN_N;
333 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
334 packetTypes["CONN_ACK"] = CONN_ACK_N;
335 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
336 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
337 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
338 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
339 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
340 packetTypes["FIN"] = FIN_N;
341 packetTypes["ERR"] = ERROR_N;
343 //-----------------------------------------------------------------------------
346 pthread_mutex_destroy(&mutex);
348 //-----------------------------------------------------------------------------
351 users->AddNotifierUserDel(&onDelUserNotifier);
361 if (pthread_create(&recvThread, NULL, Run, this))
363 errorStr = "Cannot create thread.";
364 printfd(__FILE__, "Cannot create recv thread\n");
365 logger("Cannot create recv thread.");
370 if (!isRunningRunTimeouter)
372 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
374 errorStr = "Cannot create thread.";
375 printfd(__FILE__, "Cannot create timeouter thread\n");
376 logger("Cannot create timeouter thread.");
383 //-----------------------------------------------------------------------------
394 UnauthorizeUser(this)
399 //5 seconds to thread stops itself
400 for (int i = 0; i < 25 && isRunningRun; i++)
402 struct timespec ts = {0, 200000000};
403 nanosleep(&ts, NULL);
409 if (isRunningRunTimeouter)
411 //5 seconds to thread stops itself
412 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
414 struct timespec ts = {0, 200000000};
415 nanosleep(&ts, NULL);
419 users->DelNotifierUserDel(&onDelUserNotifier);
421 if (isRunningRun || isRunningRunTimeouter)
424 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
427 //-----------------------------------------------------------------------------
428 void * AUTH_IA::Run(void * d)
431 sigfillset(&signalSet);
432 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
434 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
436 ia->isRunningRun = true;
440 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
444 ia->RecvData(buffer, sizeof(buffer));
445 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
448 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
453 ia->isRunningRun = false;
456 //-----------------------------------------------------------------------------
457 void * AUTH_IA::RunTimeouter(void * d)
460 sigfillset(&signalSet);
461 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
463 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
465 ia->isRunningRunTimeouter = true;
468 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
471 struct timespec ts = {0, 20000000};
472 nanosleep(&ts, NULL);
474 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
475 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
481 ia->isRunningRunTimeouter = false;
484 //-----------------------------------------------------------------------------
485 int AUTH_IA::ParseSettings()
487 int ret = iaSettings.ParseSettings(settings);
489 errorStr = iaSettings.GetStrError();
492 //-----------------------------------------------------------------------------
493 int AUTH_IA::Reload(const STG::ModuleSettings & ms)
495 AUTH_IA_SETTINGS newIaSettings;
496 if (newIaSettings.ParseSettings(ms))
498 printfd(__FILE__, "AUTH_IA::Reload() - Failed to reload InetAccess.\n");
499 logger("AUTH_IA: Cannot reload InetAccess. Errors found.");
503 printfd(__FILE__, "AUTH_IA::Reload() - Reloaded InetAccess successfully.\n");
504 logger("AUTH_IA: Reloaded InetAccess successfully.");
505 iaSettings = newIaSettings;
508 //-----------------------------------------------------------------------------
509 int AUTH_IA::PrepareNet()
511 struct sockaddr_in listenAddr;
513 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
515 if (listenSocket < 0)
517 errorStr = "Cannot create socket.";
518 logger("Cannot create a socket: %s", strerror(errno));
522 listenAddr.sin_family = AF_INET;
523 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
524 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
526 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
528 errorStr = "AUTH_IA: Bind failed.";
529 logger("Cannot bind the socket: %s", strerror(errno));
535 //-----------------------------------------------------------------------------
536 int AUTH_IA::FinalizeNet()
541 //-----------------------------------------------------------------------------
542 int AUTH_IA::RecvData(char * buffer, int bufferSize)
544 if (!WaitPackets(listenSocket)) // Timeout
549 struct sockaddr_in outerAddr;
550 socklen_t outerAddrLen(sizeof(outerAddr));
551 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
558 if (dataLen <= 0) // Error
562 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
563 logger("recvfrom error: %s", strerror(errno));
572 uint32_t sip = outerAddr.sin_addr.s_addr;
573 uint16_t sport = htons(outerAddr.sin_port);
576 if (CheckHeader(buffer, sip, &protoVer))
579 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
580 memset(login, 0, PASSWD_LEN);
582 DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS);
585 if (users->FindByName(login, &user))
587 logger("User's connect failed: user '%s' not found. IP %s",
589 inet_ntostring(sip).c_str());
590 printfd(__FILE__, "User '%s' NOT found!\n", login);
591 SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
595 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
597 if (user->GetProperties().disabled.Get())
599 logger("Cannont authorize '%s', user is disabled.", login);
600 SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
604 if (user->GetProperties().passive.Get())
606 logger("Cannont authorize '%s', user is passive.", login);
607 SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
611 if (!user->GetProperties().ips.Get().find(sip))
613 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
614 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
615 logger("User %s. IP address is incorrect. IP %s",
616 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
617 SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
621 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
623 //-----------------------------------------------------------------------------
624 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
626 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
628 printfd(__FILE__, "update needed - IA_ID\n");
629 if (iaSettings.LogProtocolErrors())
630 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
634 if (buffer[6] != 0) //proto[0] shoud be 0
636 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
637 if (iaSettings.LogProtocolErrors())
638 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
645 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
646 if (iaSettings.LogProtocolErrors())
647 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
652 *protoVer = buffer[7];
656 //-----------------------------------------------------------------------------
657 int AUTH_IA::Timeouter()
659 STG_LOCKER lock(&mutex);
661 std::map<uint32_t, IA_USER>::iterator it;
662 it = ip2user.begin();
664 while (it != ip2user.end())
666 uint32_t sip = it->first;
668 static UTIME currTime;
669 gettimeofday(&currTime, NULL);
671 if ((it->second.phase.GetPhase() == 2)
672 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
674 if (iaSettings.LogProtocolErrors())
675 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());
676 it->second.phase.SetPhase1();
677 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
682 if (it->second.phase.GetPhase() == 3)
684 if (!it->second.messagesToSend.empty())
686 if (it->second.protoVer == 6)
687 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
689 if (it->second.protoVer == 7)
690 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
692 if (it->second.protoVer == 8)
693 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
695 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
698 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
700 switch (it->second.protoVer)
703 Send_ALIVE_SYN_6(&(it->second), sip);
706 Send_ALIVE_SYN_7(&(it->second), sip);
709 Send_ALIVE_SYN_8(&(it->second), sip);
713 gettimeofday(&it->second.lastSendAlive, NULL);
716 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
718 if (iaSettings.LogProtocolErrors())
719 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());
720 users->Unauthorize(it->second.user->GetLogin(), this);
726 if ((it->second.phase.GetPhase() == 4)
727 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
729 if (iaSettings.LogProtocolErrors())
730 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());
731 it->second.phase.SetPhase3();
732 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
740 //-----------------------------------------------------------------------------
741 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, UserPtr user)
743 std::string login(user->GetLogin());
744 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
746 STG_LOCKER lock(&mutex);
747 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
749 if (it == ip2user.end())
752 if (!users->FindByIPIdx(sip, &userPtr))
754 if (userPtr->GetID() != user->GetID())
756 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
757 userPtr->GetLogin().c_str(),
758 inet_ntostring(sip).c_str(),
760 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
761 userPtr->GetLogin().c_str(),
762 inet_ntostring(sip).c_str(),
764 SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
769 printfd(__FILE__, "Add new user '%s' from ip %s\n",
770 login.c_str(), inet_ntostring(sip).c_str());
771 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
772 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
774 #ifdef IA_PHASE_DEBUG
775 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
776 it->second.phase.SetUserLogin(login);
779 else if (user->GetID() != it->second.user->GetID())
781 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
782 it->second.user->GetLogin().c_str(),
783 inet_ntostring(sip).c_str(),
784 user->GetLogin().c_str());
785 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
786 it->second.user->GetLogin().c_str(),
787 inet_ntostring(sip).c_str(),
788 user->GetLogin().c_str());
789 SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
793 IA_USER * iaUser = &(it->second);
795 if (iaUser->password != user->GetProperties().password.Get())
797 const std::string & password = user->GetProperties().password.Get();
798 InitContext(password.c_str(), password.length(), &iaUser->ctx);
799 iaUser->password = user->GetProperties().password.Get();
802 DecryptString(static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
804 char packetName[IA_MAX_TYPE_LEN];
805 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
806 packetName[IA_MAX_TYPE_LEN - 1] = 0;
808 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
809 if (pi == packetTypes.end())
811 SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
812 printfd(__FILE__, "Login or password is wrong!\n");
813 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
815 inet_ntostring(sip).c_str());
820 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
822 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
823 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
824 inet_ntostring(sip).c_str());
825 logger("Login '%s' is already in use from ip %s. IP %s",
827 inet_ntostring(user->GetCurrIP()).c_str(),
828 inet_ntostring(sip).c_str());
829 SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
840 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
842 return Send_CONN_SYN_ACK_6(iaUser, sip);
844 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
846 return Send_CONN_SYN_ACK_7(iaUser, sip);
848 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
850 return Send_CONN_SYN_ACK_8(iaUser, sip);
858 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
860 return Send_ALIVE_SYN_6(iaUser, sip);
862 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
864 return Send_ALIVE_SYN_7(iaUser, sip);
866 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
868 return Send_ALIVE_SYN_8(iaUser, sip);
876 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
878 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
880 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
888 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
890 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
892 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
894 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
896 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
898 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
906 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
908 return Send_FIN_6(iaUser, sip, it);
910 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
912 return Send_FIN_7(iaUser, sip, it);
914 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
916 return Send_FIN_8(iaUser, sip, it);
923 //-----------------------------------------------------------------------------
924 void AUTH_IA::DelUser(UserPtr u)
927 uint32_t ip = u->GetCurrIP();
932 std::map<uint32_t, IA_USER>::iterator it;
934 STG_LOCKER lock(&mutex);
935 it = ip2user.find(ip);
936 if (it == ip2user.end())
939 printfd(__FILE__, "Nothing to delete\n");
943 if (it->second.user == u)
945 printfd(__FILE__, "User removed!\n");
946 users->Unauthorize(u->GetLogin(), this);
950 //-----------------------------------------------------------------------------
951 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
953 struct sockaddr_in sendAddr;
960 memset(&err, 0, sizeof(ERR));
962 sendAddr.sin_family = AF_INET;
963 sendAddr.sin_port = htons(port);
964 sendAddr.sin_addr.s_addr = ip;
967 strncpy((char*)err.type, "ERR", 16);
968 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
974 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
975 printfd(__FILE__, "SendError %d bytes sent\n", res);
980 memset(&err8, 0, sizeof(ERR_8));
982 sendAddr.sin_family = AF_INET;
983 sendAddr.sin_port = htons(port);
984 sendAddr.sin_addr.s_addr = ip;
987 strncpy((char*)err8.type, "ERR", 16);
988 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
994 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
995 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1001 //-----------------------------------------------------------------------------
1002 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1004 struct sockaddr_in sendAddr;
1006 sendAddr.sin_family = AF_INET;
1007 sendAddr.sin_port = htons(port);
1008 sendAddr.sin_addr.s_addr = ip;
1010 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1015 //-----------------------------------------------------------------------------
1016 int AUTH_IA::SendMessage(const STG::Message & msg, uint32_t ip) const
1018 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1020 std::map<uint32_t, IA_USER>::iterator it;
1022 STG_LOCKER lock(&mutex);
1023 it = ip2user.find(ip);
1024 if (it == ip2user.end())
1026 errorStr = "Unknown user.";
1029 it->second.messagesToSend.push_back(msg);
1032 //-----------------------------------------------------------------------------
1033 int AUTH_IA::RealSendMessage6(const STG::Message & msg, uint32_t ip, IA_USER & user)
1035 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1038 memset(&info, 0, sizeof(INFO_6));
1041 strncpy((char*)info.type, "INFO", 16);
1042 info.infoType = 'I';
1043 strncpy((char*)info.text, msg.text.c_str(), 235);
1046 size_t len = info.len;
1048 SwapBytes(info.len);
1052 memcpy(buffer, &info, sizeof(INFO_6));
1053 EncryptString(buffer, buffer, len, &user.ctx);
1054 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1056 //-----------------------------------------------------------------------------
1057 int AUTH_IA::RealSendMessage7(const STG::Message & msg, uint32_t ip, IA_USER & user)
1059 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1062 memset(&info, 0, sizeof(INFO_7));
1065 strncpy((char*)info.type, "INFO_7", 16);
1066 info.infoType = static_cast<int8_t>(msg.header.type);
1067 info.showTime = static_cast<int8_t>(msg.header.showTime);
1068 info.sendTime = msg.header.creationTime;
1070 size_t len = info.len;
1072 SwapBytes(info.len);
1073 SwapBytes(info.sendTime);
1076 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1077 info.text[MAX_MSG_LEN - 1] = 0;
1080 memcpy(buffer, &info, sizeof(INFO_7));
1082 EncryptString(buffer, buffer, len, &user.ctx);
1083 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1085 //-----------------------------------------------------------------------------
1086 int AUTH_IA::RealSendMessage8(const STG::Message & msg, uint32_t ip, IA_USER & user)
1088 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1091 memset(&info, 0, sizeof(INFO_8));
1094 strncpy((char*)info.type, "INFO_8", 16);
1095 info.infoType = static_cast<int8_t>(msg.header.type);
1096 info.showTime = static_cast<int8_t>(msg.header.showTime);
1097 info.sendTime = msg.header.creationTime;
1099 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1100 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1102 size_t len = info.len;
1104 SwapBytes(info.len);
1105 SwapBytes(info.sendTime);
1109 memcpy(buffer, &info, sizeof(INFO_8));
1111 EncryptString(buffer, buffer, len, &user.ctx);
1112 return Send(ip, user.port, buffer, len);
1114 //-----------------------------------------------------------------------------
1115 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1117 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1120 enabledDirs = 0xFFffFFff;
1122 iaUser->phase.SetPhase2();
1123 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1126 //-----------------------------------------------------------------------------
1127 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1129 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1131 //-----------------------------------------------------------------------------
1132 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1135 SwapBytes(connSyn->dirs);
1137 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1138 enabledDirs = connSyn->dirs;
1141 //-----------------------------------------------------------------------------
1142 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1145 SwapBytes(connAck->len);
1146 SwapBytes(connAck->rnd);
1148 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1150 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1152 iaUser->phase.UpdateTime();
1154 iaUser->lastSendAlive = iaUser->phase.GetTime();
1155 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1157 iaUser->phase.SetPhase3();
1158 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1163 errorStr = iaUser->user->GetStrError();
1164 if (iaSettings.LogProtocolErrors())
1165 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());
1166 iaUser->phase.SetPhase1();
1168 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1172 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d, expected: %d\n", iaUser->phase.GetPhase(), connAck->rnd, iaUser->rnd + 1);
1173 if (iaSettings.LogProtocolErrors())
1175 if (iaUser->phase.GetPhase() != 2)
1176 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());
1177 if (connAck->rnd != iaUser->rnd + 1)
1178 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);
1182 //-----------------------------------------------------------------------------
1183 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1185 return Process_CONN_ACK_6(connAck, iaUser, sip);
1187 //-----------------------------------------------------------------------------
1188 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1191 SwapBytes(connAck->len);
1192 SwapBytes(connAck->rnd);
1194 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1196 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1198 iaUser->phase.UpdateTime();
1199 iaUser->lastSendAlive = iaUser->phase.GetTime();
1200 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1202 iaUser->phase.SetPhase3();
1203 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1208 errorStr = iaUser->user->GetStrError();
1209 if (iaSettings.LogProtocolErrors())
1210 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());
1211 iaUser->phase.SetPhase1();
1213 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1217 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d, expected: %d\n", iaUser->phase.GetPhase(), connAck->rnd, iaUser->rnd + 1);
1218 if (iaSettings.LogProtocolErrors())
1220 if (iaUser->phase.GetPhase() != 2)
1221 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());
1222 if (connAck->rnd != iaUser->rnd + 1)
1223 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);
1227 //-----------------------------------------------------------------------------
1228 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1231 SwapBytes(aliveAck->len);
1232 SwapBytes(aliveAck->rnd);
1234 printfd(__FILE__, "ALIVE_ACK_6\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_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1247 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1249 //-----------------------------------------------------------------------------
1250 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1253 SwapBytes(aliveAck->len);
1254 SwapBytes(aliveAck->rnd);
1256 printfd(__FILE__, "ALIVE_ACK_8\n");
1257 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1259 iaUser->phase.UpdateTime();
1261 iaUser->aliveSent = false;
1266 //-----------------------------------------------------------------------------
1267 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1269 printfd(__FILE__, "DISCONN_SYN_6\n");
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 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1275 errorStr = "Incorrect request DISCONN_SYN";
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_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1287 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1289 //-----------------------------------------------------------------------------
1290 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1292 if (iaUser->phase.GetPhase() != 3)
1294 if (iaSettings.LogProtocolErrors())
1295 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());
1296 errorStr = "Incorrect request DISCONN_SYN";
1297 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1301 iaUser->phase.SetPhase4();
1302 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1306 //-----------------------------------------------------------------------------
1307 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1310 std::map<uint32_t, IA_USER>::iterator)
1313 SwapBytes(disconnAck->len);
1314 SwapBytes(disconnAck->rnd);
1316 printfd(__FILE__, "DISCONN_ACK_6\n");
1317 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1319 if (iaSettings.LogProtocolErrors())
1321 if (iaUser->phase.GetPhase() != 4)
1322 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());
1323 if (disconnAck->rnd != iaUser->rnd + 1)
1324 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);
1326 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1332 //-----------------------------------------------------------------------------
1333 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)
1335 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1337 //-----------------------------------------------------------------------------
1338 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1341 SwapBytes(disconnAck->len);
1342 SwapBytes(disconnAck->rnd);
1344 printfd(__FILE__, "DISCONN_ACK_8\n");
1345 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1347 if (iaSettings.LogProtocolErrors())
1349 if (iaUser->phase.GetPhase() != 4)
1350 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());
1351 if (disconnAck->rnd != iaUser->rnd + 1)
1352 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);
1354 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1360 //-----------------------------------------------------------------------------
1361 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1363 //+++ Fill static data in connSynAck +++
1364 // TODO Move this code. It must be executed only once
1365 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1366 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1367 for (int j = 0; j < DIR_NUM; j++)
1369 strncpy((char*)connSynAck6.dirName[j],
1370 stgSettings->GetDirName(j).c_str(),
1373 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1375 //--- Fill static data in connSynAck ---
1377 iaUser->rnd = static_cast<uint32_t>(random());
1378 connSynAck6.rnd = iaUser->rnd;
1380 printfd(__FILE__, "Sending CONN_SYN_ACK with control number %d.\n", iaUser->rnd);
1382 connSynAck6.userTimeOut = iaSettings.GetUserTimeout().GetSec();
1383 connSynAck6.aliveDelay = iaSettings.GetUserDelay().GetSec();
1386 SwapBytes(connSynAck6.len);
1387 SwapBytes(connSynAck6.rnd);
1388 SwapBytes(connSynAck6.userTimeOut);
1389 SwapBytes(connSynAck6.aliveDelay);
1392 EncryptString((char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)), &iaUser->ctx);
1393 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1395 //-----------------------------------------------------------------------------
1396 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1398 return Send_CONN_SYN_ACK_6(iaUser, sip);
1400 //-----------------------------------------------------------------------------
1401 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1403 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1404 connSynAck8.hdr.protoVer[0] = 0;
1405 connSynAck8.hdr.protoVer[1] = 8;
1407 //+++ Fill static data in connSynAck +++
1408 // TODO Move this code. It must be executed only once
1409 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1410 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1411 for (int j = 0; j < DIR_NUM; j++)
1413 strncpy((char*)connSynAck8.dirName[j],
1414 stgSettings->GetDirName(j).c_str(),
1417 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1419 //--- Fill static data in connSynAck ---
1421 iaUser->rnd = static_cast<uint32_t>(random());
1422 connSynAck8.rnd = iaUser->rnd;
1424 printfd(__FILE__, "Sending CONN_SYN_ACK with control number %d.\n", iaUser->rnd);
1426 connSynAck8.userTimeOut = iaSettings.GetUserTimeout().GetSec();
1427 connSynAck8.aliveDelay = iaSettings.GetUserDelay().GetSec();
1430 SwapBytes(connSynAck8.len);
1431 SwapBytes(connSynAck8.rnd);
1432 SwapBytes(connSynAck8.userTimeOut);
1433 SwapBytes(connSynAck8.aliveDelay);
1436 EncryptString((char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)), &iaUser->ctx);
1437 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1439 //-----------------------------------------------------------------------------
1440 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1442 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1443 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1445 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1447 for (int i = 0; i < DIR_NUM; i++)
1449 aliveSyn6.md[i] = iaUser->user->GetProperties().down.Get()[i];
1450 aliveSyn6.mu[i] = iaUser->user->GetProperties().up.Get()[i];
1452 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1453 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1457 int dn = iaSettings.GetFreeMbShowType();
1458 const auto tf = iaUser->user->GetTariff();
1462 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1467 if (std::fabs(p) < 1.0e-3)
1469 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1473 double fmb = iaUser->user->GetProperties().freeMb;
1474 fmb = fmb < 0 ? 0 : fmb;
1475 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1480 if (freeMbNone == iaSettings.GetFreeMbShowType())
1482 aliveSyn6.freeMb[0] = 0;
1486 double fmb = iaUser->user->GetProperties().freeMb;
1487 fmb = fmb < 0 ? 0 : fmb;
1488 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1493 if (iaUser->aliveSent)
1495 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1497 iaUser->aliveSent = true;
1500 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperties().cash.Get() * 1000.0);
1501 if (!stgSettings->GetShowFeeInCash())
1502 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1505 SwapBytes(aliveSyn6.len);
1506 SwapBytes(aliveSyn6.rnd);
1507 SwapBytes(aliveSyn6.cash);
1508 for (int i = 0; i < DIR_NUM; ++i)
1510 SwapBytes(aliveSyn6.mu[i]);
1511 SwapBytes(aliveSyn6.md[i]);
1512 SwapBytes(aliveSyn6.su[i]);
1513 SwapBytes(aliveSyn6.sd[i]);
1517 EncryptString((char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)), &iaUser->ctx);
1518 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1520 //-----------------------------------------------------------------------------
1521 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1523 return Send_ALIVE_SYN_6(iaUser, sip);
1525 //-----------------------------------------------------------------------------
1526 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1528 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1529 aliveSyn8.hdr.protoVer[0] = 0;
1530 aliveSyn8.hdr.protoVer[1] = 8;
1532 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1533 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1535 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1537 for (int i = 0; i < DIR_NUM; i++)
1539 aliveSyn8.md[i] = iaUser->user->GetProperties().down.Get()[i];
1540 aliveSyn8.mu[i] = iaUser->user->GetProperties().up.Get()[i];
1542 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1543 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1547 int dn = iaSettings.GetFreeMbShowType();
1551 const auto tf = iaUser->user->GetTariff();
1552 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1557 if (std::fabs(p) < 1.0e-3)
1559 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1563 double fmb = iaUser->user->GetProperties().freeMb;
1564 fmb = fmb < 0 ? 0 : fmb;
1565 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1570 if (freeMbNone == iaSettings.GetFreeMbShowType())
1572 aliveSyn8.freeMb[0] = 0;
1576 double fmb = iaUser->user->GetProperties().freeMb;
1577 fmb = fmb < 0 ? 0 : fmb;
1578 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1583 if (iaUser->aliveSent)
1585 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1587 iaUser->aliveSent = true;
1590 const auto tf = iaUser->user->GetTariff();
1592 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperties().cash.Get() * 1000.0);
1593 if (!stgSettings->GetShowFeeInCash())
1594 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1597 SwapBytes(aliveSyn8.len);
1598 SwapBytes(aliveSyn8.rnd);
1599 SwapBytes(aliveSyn8.cash);
1600 SwapBytes(aliveSyn8.status);
1601 for (int i = 0; i < DIR_NUM; ++i)
1603 SwapBytes(aliveSyn8.mu[i]);
1604 SwapBytes(aliveSyn8.md[i]);
1605 SwapBytes(aliveSyn8.su[i]);
1606 SwapBytes(aliveSyn8.sd[i]);
1610 EncryptString((char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)), &iaUser->ctx);
1611 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1613 //-----------------------------------------------------------------------------
1614 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1616 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1617 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1618 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1621 SwapBytes(disconnSynAck6.len);
1622 SwapBytes(disconnSynAck6.rnd);
1625 EncryptString((char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)), &iaUser->ctx);
1626 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1628 //-----------------------------------------------------------------------------
1629 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1631 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1633 //-----------------------------------------------------------------------------
1634 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1636 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1637 disconnSynAck8.hdr.protoVer[0] = 0;
1638 disconnSynAck8.hdr.protoVer[1] = 8;
1640 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1641 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1642 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1645 SwapBytes(disconnSynAck8.len);
1646 SwapBytes(disconnSynAck8.rnd);
1649 EncryptString((char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)), &iaUser->ctx);
1650 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1652 //-----------------------------------------------------------------------------
1653 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1655 fin6.len = Min8(sizeof(FIN_6));
1656 strcpy((char*)fin6.type, "FIN");
1657 strcpy((char*)fin6.ok, "OK");
1660 SwapBytes(fin6.len);
1663 EncryptString((char*)&fin6, (char*)&fin6, Min8(sizeof(fin6)), &iaUser->ctx);
1665 users->Unauthorize(iaUser->login, this);
1667 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1673 //-----------------------------------------------------------------------------
1674 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1676 return Send_FIN_6(iaUser, sip, it);
1678 //-----------------------------------------------------------------------------
1679 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1681 strcpy((char*)fin8.hdr.magic, IA_ID);
1682 fin8.hdr.protoVer[0] = 0;
1683 fin8.hdr.protoVer[1] = 8;
1685 fin8.len = Min8(sizeof(FIN_8));
1686 strcpy((char*)fin8.type, "FIN");
1687 strcpy((char*)fin8.ok, "OK");
1690 SwapBytes(fin8.len);
1693 EncryptString((char*)&fin8, (char*)&fin8, Min8(sizeof(fin8)), &iaUser->ctx);
1695 users->Unauthorize(iaUser->login, this);
1697 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));