2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
23 $Date: 2010/03/25 15:18:48 $
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <unistd.h> // close
37 #include <cstdio> // snprintf
42 #include "stg/common.h"
43 #include "stg/locker.h"
44 #include "stg/tariff.h"
45 #include "stg/user_property.h"
46 #include "stg/settings.h"
47 #include "stg/plugin_creator.h"
48 #include "inetaccess.h"
50 extern volatile time_t stgTime;
52 //-----------------------------------------------------------------------------
53 //-----------------------------------------------------------------------------
54 //-----------------------------------------------------------------------------
57 PLUGIN_CREATOR<AUTH_IA> iac;
60 extern "C" PLUGIN * GetPlugin();
61 //-----------------------------------------------------------------------------
62 //-----------------------------------------------------------------------------
63 //-----------------------------------------------------------------------------
66 return iac.GetPlugin();
68 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
71 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
76 freeMbShowType(freeMbCash),
77 logProtocolErrors(false)
80 //-----------------------------------------------------------------------------
81 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
85 std::vector<PARAM_VALUE>::const_iterator pvi;
86 ///////////////////////////
88 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
89 if (pvi == s.moduleParams.end())
91 errorStr = "Parameter \'Port\' not found.";
92 printfd(__FILE__, "Parameter 'Port' not found\n");
95 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
97 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
98 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
101 port = static_cast<uint16_t>(p);
102 ///////////////////////////
103 pv.param = "UserDelay";
104 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
105 if (pvi == s.moduleParams.end())
107 errorStr = "Parameter \'UserDelay\' not found.";
108 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
112 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
114 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
115 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
118 ///////////////////////////
119 pv.param = "UserTimeout";
120 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
121 if (pvi == s.moduleParams.end())
123 errorStr = "Parameter \'UserTimeout\' not found.";
124 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
128 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
130 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
131 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
134 ///////////////////////////
135 pv.param = "LogProtocolErrors";
136 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
137 if (pvi == s.moduleParams.end())
138 logProtocolErrors = false;
139 else if (ParseYesNo(pvi->value[0], &logProtocolErrors))
141 errorStr = "Cannot parse parameter \'LogProtocolErrors\': " + errorStr;
142 printfd(__FILE__, "Cannot parse parameter 'LogProtocolErrors'\n");
145 /////////////////////////////////////////////////////////////
146 std::string freeMbType;
149 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
150 if (pvi == s.moduleParams.end())
152 errorStr = "Parameter \'FreeMb\' not found.";
153 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
156 freeMbType = pvi->value[0];
158 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
160 freeMbShowType = freeMbCash;
162 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
164 freeMbShowType = freeMbNone;
166 else if (!str2x(freeMbType.c_str(), n))
168 if (n < 0 || n >= DIR_NUM)
170 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
171 printfd(__FILE__, "%s\n", errorStr.c_str());
174 freeMbShowType = (FREEMB)(freeMb0 + n);
178 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
179 printfd(__FILE__, "%s\n", errorStr.c_str());
182 /////////////////////////////////////////////////////////////
185 //-----------------------------------------------------------------------------
186 //-----------------------------------------------------------------------------
187 //-----------------------------------------------------------------------------
188 #ifdef IA_PHASE_DEBUG
194 gettimeofday(&phaseTime, NULL);
201 gettimeofday(&phaseTime, NULL);
204 //-----------------------------------------------------------------------------
205 IA_PHASE::~IA_PHASE()
207 #ifdef IA_PHASE_DEBUG
208 flog = fopen(log.c_str(), "at");
211 fprintf(flog, "IA %s D\n", login.c_str());
216 //-----------------------------------------------------------------------------
217 #ifdef IA_PHASE_DEBUG
218 void IA_PHASE::SetLogFileName(const string & logFileName)
220 log = logFileName + ".ia.log";
222 //-----------------------------------------------------------------------------
223 void IA_PHASE::SetUserLogin(const string & login)
225 IA_PHASE::login = login;
227 //-----------------------------------------------------------------------------
228 void IA_PHASE::WritePhaseChange(int newPhase)
231 gettimeofday(&newPhaseTime, NULL);
232 flog = fopen(log.c_str(), "at");
235 string action = newPhase == phase ? "U" : "C";
236 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
237 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
238 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
248 //-----------------------------------------------------------------------------
249 void IA_PHASE::SetPhase1()
251 #ifdef IA_PHASE_DEBUG
255 gettimeofday(&phaseTime, NULL);
257 //-----------------------------------------------------------------------------
258 void IA_PHASE::SetPhase2()
260 #ifdef IA_PHASE_DEBUG
264 gettimeofday(&phaseTime, NULL);
266 //-----------------------------------------------------------------------------
267 void IA_PHASE::SetPhase3()
269 #ifdef IA_PHASE_DEBUG
273 gettimeofday(&phaseTime, NULL);
275 //-----------------------------------------------------------------------------
276 void IA_PHASE::SetPhase4()
278 #ifdef IA_PHASE_DEBUG
282 gettimeofday(&phaseTime, NULL);
284 //-----------------------------------------------------------------------------
285 int IA_PHASE::GetPhase() const
289 //-----------------------------------------------------------------------------
290 void IA_PHASE::UpdateTime()
292 #ifdef IA_PHASE_DEBUG
293 WritePhaseChange(phase);
295 gettimeofday(&phaseTime, NULL);
297 //-----------------------------------------------------------------------------
298 const UTIME & IA_PHASE::GetTime() const
302 //-----------------------------------------------------------------------------
303 //-----------------------------------------------------------------------------
304 //-----------------------------------------------------------------------------
312 isRunningRunTimeouter(false),
329 enabledDirs(0xFFffFFff),
330 onDelUserNotifier(*this),
331 logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
333 InitContext("pr7Hhen", 7, &ctxS);
335 pthread_mutexattr_t attr;
336 pthread_mutexattr_init(&attr);
337 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
338 pthread_mutex_init(&mutex, &attr);
340 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
341 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
342 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
343 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
344 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
345 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
346 memset(&fin6, 0, sizeof(FIN_6));
347 memset(&fin8, 0, sizeof(FIN_8));
349 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
350 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
351 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
352 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
353 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
354 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
355 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
356 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
357 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
358 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
359 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
360 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
361 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
362 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
363 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
364 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
365 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
366 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
368 packetTypes["CONN_SYN"] = CONN_SYN_N;
369 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
370 packetTypes["CONN_ACK"] = CONN_ACK_N;
371 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
372 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
373 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
374 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
375 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
376 packetTypes["FIN"] = FIN_N;
377 packetTypes["ERR"] = ERROR_N;
379 //-----------------------------------------------------------------------------
382 pthread_mutex_destroy(&mutex);
384 //-----------------------------------------------------------------------------
387 users->AddNotifierUserDel(&onDelUserNotifier);
397 if (pthread_create(&recvThread, NULL, Run, this))
399 errorStr = "Cannot create thread.";
400 printfd(__FILE__, "Cannot create recv thread\n");
401 logger("Cannot create recv thread.");
406 if (!isRunningRunTimeouter)
408 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
410 errorStr = "Cannot create thread.";
411 printfd(__FILE__, "Cannot create timeouter thread\n");
412 logger("Cannot create timeouter thread.");
419 //-----------------------------------------------------------------------------
430 UnauthorizeUser(this)
435 //5 seconds to thread stops itself
436 for (int i = 0; i < 25 && isRunningRun; i++)
438 struct timespec ts = {0, 200000000};
439 nanosleep(&ts, NULL);
445 if (isRunningRunTimeouter)
447 //5 seconds to thread stops itself
448 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
450 struct timespec ts = {0, 200000000};
451 nanosleep(&ts, NULL);
455 users->DelNotifierUserDel(&onDelUserNotifier);
457 if (isRunningRun || isRunningRunTimeouter)
460 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
463 //-----------------------------------------------------------------------------
464 void * AUTH_IA::Run(void * d)
467 sigfillset(&signalSet);
468 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
470 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
472 ia->isRunningRun = true;
476 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
480 ia->RecvData(buffer, sizeof(buffer));
481 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
484 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
485 TouchFile(monFile.c_str());
489 ia->isRunningRun = false;
492 //-----------------------------------------------------------------------------
493 void * AUTH_IA::RunTimeouter(void * d)
496 sigfillset(&signalSet);
497 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
499 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
501 ia->isRunningRunTimeouter = true;
504 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
507 struct timespec ts = {0, 20000000};
508 nanosleep(&ts, NULL);
510 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
511 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
513 TouchFile(monFile.c_str());
517 ia->isRunningRunTimeouter = false;
520 //-----------------------------------------------------------------------------
521 int AUTH_IA::ParseSettings()
523 int ret = iaSettings.ParseSettings(settings);
525 errorStr = iaSettings.GetStrError();
528 //-----------------------------------------------------------------------------
529 int AUTH_IA::Reload(const MODULE_SETTINGS & ms)
531 AUTH_IA_SETTINGS newIaSettings;
532 if (newIaSettings.ParseSettings(ms))
534 STG_LOGGER & WriteServLog = GetStgLogger();
535 printfd(__FILE__, "AUTH_IA::Reload() - Failed to reload InetAccess.\n");
536 WriteServLog("AUTH_IA: Cannot reload InetAccess. Errors found.");
540 STG_LOGGER & WriteServLog = GetStgLogger();
541 printfd(__FILE__, "AUTH_IA::Reload() - Reloaded InetAccess successfully.\n");
542 WriteServLog("AUTH_IA: Reloaded InetAccess successfully.");
545 //-----------------------------------------------------------------------------
546 int AUTH_IA::PrepareNet()
548 struct sockaddr_in listenAddr;
550 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
552 if (listenSocket < 0)
554 errorStr = "Cannot create socket.";
555 logger("Cannot create a socket: %s", strerror(errno));
559 listenAddr.sin_family = AF_INET;
560 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
561 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
563 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
565 errorStr = "AUTH_IA: Bind failed.";
566 logger("Cannot bind the socket: %s", strerror(errno));
572 //-----------------------------------------------------------------------------
573 int AUTH_IA::FinalizeNet()
578 //-----------------------------------------------------------------------------
579 int AUTH_IA::RecvData(char * buffer, int bufferSize)
581 if (!WaitPackets(listenSocket)) // Timeout
586 struct sockaddr_in outerAddr;
587 socklen_t outerAddrLen(sizeof(outerAddr));
588 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
595 if (dataLen <= 0) // Error
599 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
600 logger("recvfrom error: %s", strerror(errno));
609 uint32_t sip = outerAddr.sin_addr.s_addr;
610 uint16_t sport = htons(outerAddr.sin_port);
613 if (CheckHeader(buffer, sip, &protoVer))
616 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
617 memset(login, 0, PASSWD_LEN);
619 DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS);
622 if (users->FindByName(login, &user))
624 logger("User's connect failed: user '%s' not found. IP %s",
626 inet_ntostring(sip).c_str());
627 printfd(__FILE__, "User '%s' NOT found!\n", login);
628 SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
632 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
634 if (user->GetProperty().disabled.Get())
636 logger("Cannont authorize '%s', user is disabled.", login);
637 SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
641 if (user->GetProperty().passive.Get())
643 logger("Cannont authorize '%s', user is passive.", login);
644 SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
648 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
650 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
651 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
652 logger("User %s. IP address is incorrect. IP %s",
653 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
654 SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
658 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
660 //-----------------------------------------------------------------------------
661 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
663 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
665 printfd(__FILE__, "update needed - IA_ID\n");
666 if (iaSettings.LogProtocolErrors())
667 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
671 if (buffer[6] != 0) //proto[0] shoud be 0
673 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
674 if (iaSettings.LogProtocolErrors())
675 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
682 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
683 if (iaSettings.LogProtocolErrors())
684 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
689 *protoVer = buffer[7];
693 //-----------------------------------------------------------------------------
694 int AUTH_IA::Timeouter()
696 STG_LOCKER lock(&mutex);
698 std::map<uint32_t, IA_USER>::iterator it;
699 it = ip2user.begin();
701 while (it != ip2user.end())
703 uint32_t sip = it->first;
705 static UTIME currTime;
706 gettimeofday(&currTime, NULL);
708 if ((it->second.phase.GetPhase() == 2)
709 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
711 if (iaSettings.LogProtocolErrors())
712 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());
713 it->second.phase.SetPhase1();
714 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
719 if (it->second.phase.GetPhase() == 3)
721 if (!it->second.messagesToSend.empty())
723 if (it->second.protoVer == 6)
724 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
726 if (it->second.protoVer == 7)
727 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
729 if (it->second.protoVer == 8)
730 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
732 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
735 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
737 switch (it->second.protoVer)
740 Send_ALIVE_SYN_6(&(it->second), sip);
743 Send_ALIVE_SYN_7(&(it->second), sip);
746 Send_ALIVE_SYN_8(&(it->second), sip);
750 gettimeofday(&it->second.lastSendAlive, NULL);
753 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
755 if (iaSettings.LogProtocolErrors())
756 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());
757 users->Unauthorize(it->second.user->GetLogin(), this);
763 if ((it->second.phase.GetPhase() == 4)
764 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
766 if (iaSettings.LogProtocolErrors())
767 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());
768 it->second.phase.SetPhase3();
769 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
777 //-----------------------------------------------------------------------------
778 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
780 std::string login(user->GetLogin());
781 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
783 STG_LOCKER lock(&mutex);
784 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
786 if (it == ip2user.end())
789 if (!users->FindByIPIdx(sip, &userPtr))
791 if (userPtr->GetID() != user->GetID())
793 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
794 userPtr->GetLogin().c_str(),
795 inet_ntostring(sip).c_str(),
797 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
798 userPtr->GetLogin().c_str(),
799 inet_ntostring(sip).c_str(),
801 SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
806 printfd(__FILE__, "Add new user '%s' from ip %s\n",
807 login.c_str(), inet_ntostring(sip).c_str());
808 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
809 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
811 #ifdef IA_PHASE_DEBUG
812 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
813 it->second.phase.SetUserLogin(login);
816 else if (user->GetID() != it->second.user->GetID())
818 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
819 it->second.user->GetLogin().c_str(),
820 inet_ntostring(sip).c_str(),
821 user->GetLogin().c_str());
822 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
823 it->second.user->GetLogin().c_str(),
824 inet_ntostring(sip).c_str(),
825 user->GetLogin().c_str());
826 SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
830 IA_USER * iaUser = &(it->second);
832 if (iaUser->password != user->GetProperty().password.Get())
834 const std::string & password = user->GetProperty().password.Get();
835 InitContext(password.c_str(), password.length(), &iaUser->ctx);
836 iaUser->password = user->GetProperty().password.Get();
839 DecryptString(static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
841 char packetName[IA_MAX_TYPE_LEN];
842 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
843 packetName[IA_MAX_TYPE_LEN - 1] = 0;
845 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
846 if (pi == packetTypes.end())
848 SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
849 printfd(__FILE__, "Login or password is wrong!\n");
850 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
852 inet_ntostring(sip).c_str());
857 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
859 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
860 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
861 inet_ntostring(sip).c_str());
862 logger("Login '%s' is already in use from ip %s. IP %s",
864 inet_ntostring(user->GetCurrIP()).c_str(),
865 inet_ntostring(sip).c_str());
866 SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
877 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
879 return Send_CONN_SYN_ACK_6(iaUser, sip);
881 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
883 return Send_CONN_SYN_ACK_7(iaUser, sip);
885 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
887 return Send_CONN_SYN_ACK_8(iaUser, sip);
895 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
897 return Send_ALIVE_SYN_6(iaUser, sip);
899 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
901 return Send_ALIVE_SYN_7(iaUser, sip);
903 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
905 return Send_ALIVE_SYN_8(iaUser, sip);
913 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
915 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
917 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
925 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
927 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
929 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
931 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
933 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
935 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
943 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
945 return Send_FIN_6(iaUser, sip, it);
947 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
949 return Send_FIN_7(iaUser, sip, it);
951 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
953 return Send_FIN_8(iaUser, sip, it);
960 //-----------------------------------------------------------------------------
961 void AUTH_IA::DelUser(USER_PTR u)
964 uint32_t ip = u->GetCurrIP();
969 std::map<uint32_t, IA_USER>::iterator it;
971 STG_LOCKER lock(&mutex);
972 it = ip2user.find(ip);
973 if (it == ip2user.end())
976 printfd(__FILE__, "Nothing to delete\n");
980 if (it->second.user == u)
982 printfd(__FILE__, "User removed!\n");
983 users->Unauthorize(u->GetLogin(), this);
987 //-----------------------------------------------------------------------------
988 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
990 struct sockaddr_in sendAddr;
997 memset(&err, 0, sizeof(ERR));
999 sendAddr.sin_family = AF_INET;
1000 sendAddr.sin_port = htons(port);
1001 sendAddr.sin_addr.s_addr = ip;
1004 strncpy((char*)err.type, "ERR", 16);
1005 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1011 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1012 printfd(__FILE__, "SendError %d bytes sent\n", res);
1017 memset(&err8, 0, sizeof(ERR_8));
1019 sendAddr.sin_family = AF_INET;
1020 sendAddr.sin_port = htons(port);
1021 sendAddr.sin_addr.s_addr = ip;
1024 strncpy((char*)err8.type, "ERR", 16);
1025 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1028 SwapBytes(err8.len);
1031 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1032 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1038 //-----------------------------------------------------------------------------
1039 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1041 struct sockaddr_in sendAddr;
1043 sendAddr.sin_family = AF_INET;
1044 sendAddr.sin_port = htons(port);
1045 sendAddr.sin_addr.s_addr = ip;
1047 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1052 //-----------------------------------------------------------------------------
1053 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1055 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1057 std::map<uint32_t, IA_USER>::iterator it;
1059 STG_LOCKER lock(&mutex);
1060 it = ip2user.find(ip);
1061 if (it == ip2user.end())
1063 errorStr = "Unknown user.";
1066 it->second.messagesToSend.push_back(msg);
1069 //-----------------------------------------------------------------------------
1070 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1072 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1075 memset(&info, 0, sizeof(INFO_6));
1078 strncpy((char*)info.type, "INFO", 16);
1079 info.infoType = 'I';
1080 strncpy((char*)info.text, msg.text.c_str(), 235);
1083 size_t len = info.len;
1085 SwapBytes(info.len);
1089 memcpy(buffer, &info, sizeof(INFO_6));
1090 EncryptString(buffer, buffer, len, &user.ctx);
1091 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1093 //-----------------------------------------------------------------------------
1094 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1096 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1099 memset(&info, 0, sizeof(INFO_7));
1102 strncpy((char*)info.type, "INFO_7", 16);
1103 info.infoType = static_cast<int8_t>(msg.header.type);
1104 info.showTime = static_cast<int8_t>(msg.header.showTime);
1105 info.sendTime = msg.header.creationTime;
1107 size_t len = info.len;
1109 SwapBytes(info.len);
1110 SwapBytes(info.sendTime);
1113 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1114 info.text[MAX_MSG_LEN - 1] = 0;
1117 memcpy(buffer, &info, sizeof(INFO_7));
1119 EncryptString(buffer, buffer, len, &user.ctx);
1120 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1122 //-----------------------------------------------------------------------------
1123 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1125 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1128 memset(&info, 0, sizeof(INFO_8));
1131 strncpy((char*)info.type, "INFO_8", 16);
1132 info.infoType = static_cast<int8_t>(msg.header.type);
1133 info.showTime = static_cast<int8_t>(msg.header.showTime);
1134 info.sendTime = msg.header.creationTime;
1136 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1137 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1139 size_t len = info.len;
1141 SwapBytes(info.len);
1142 SwapBytes(info.sendTime);
1146 memcpy(buffer, &info, sizeof(INFO_8));
1148 EncryptString(buffer, buffer, len, &user.ctx);
1149 return Send(ip, user.port, buffer, len);
1151 //-----------------------------------------------------------------------------
1152 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1154 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1157 enabledDirs = 0xFFffFFff;
1159 iaUser->phase.SetPhase2();
1160 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1163 //-----------------------------------------------------------------------------
1164 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1166 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1168 //-----------------------------------------------------------------------------
1169 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1172 SwapBytes(connSyn->dirs);
1174 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1175 enabledDirs = connSyn->dirs;
1178 //-----------------------------------------------------------------------------
1179 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1182 SwapBytes(connAck->len);
1183 SwapBytes(connAck->rnd);
1185 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1187 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1189 iaUser->phase.UpdateTime();
1191 iaUser->lastSendAlive = iaUser->phase.GetTime();
1192 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1194 iaUser->phase.SetPhase3();
1195 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1200 errorStr = iaUser->user->GetStrError();
1201 if (iaSettings.LogProtocolErrors())
1202 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());
1203 iaUser->phase.SetPhase1();
1205 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1209 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1210 if (iaSettings.LogProtocolErrors())
1212 if (iaUser->phase.GetPhase() != 2)
1213 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());
1214 if (connAck->rnd != iaUser->rnd + 1)
1215 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);
1219 //-----------------------------------------------------------------------------
1220 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1222 return Process_CONN_ACK_6(connAck, iaUser, sip);
1224 //-----------------------------------------------------------------------------
1225 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1228 SwapBytes(connAck->len);
1229 SwapBytes(connAck->rnd);
1231 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1233 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1235 iaUser->phase.UpdateTime();
1236 iaUser->lastSendAlive = iaUser->phase.GetTime();
1237 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1239 iaUser->phase.SetPhase3();
1240 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1245 errorStr = iaUser->user->GetStrError();
1246 if (iaSettings.LogProtocolErrors())
1247 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());
1248 iaUser->phase.SetPhase1();
1250 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1254 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1255 if (iaSettings.LogProtocolErrors())
1257 if (iaUser->phase.GetPhase() != 2)
1258 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());
1259 if (connAck->rnd != iaUser->rnd + 1)
1260 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);
1264 //-----------------------------------------------------------------------------
1265 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1268 SwapBytes(aliveAck->len);
1269 SwapBytes(aliveAck->rnd);
1271 printfd(__FILE__, "ALIVE_ACK_6\n");
1272 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1274 iaUser->phase.UpdateTime();
1276 iaUser->aliveSent = false;
1281 //-----------------------------------------------------------------------------
1282 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1284 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1286 //-----------------------------------------------------------------------------
1287 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1290 SwapBytes(aliveAck->len);
1291 SwapBytes(aliveAck->rnd);
1293 printfd(__FILE__, "ALIVE_ACK_8\n");
1294 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1296 iaUser->phase.UpdateTime();
1298 iaUser->aliveSent = false;
1303 //-----------------------------------------------------------------------------
1304 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1306 printfd(__FILE__, "DISCONN_SYN_6\n");
1307 if (iaUser->phase.GetPhase() != 3)
1309 if (iaSettings.LogProtocolErrors())
1310 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());
1311 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1312 errorStr = "Incorrect request DISCONN_SYN";
1316 iaUser->phase.SetPhase4();
1317 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1321 //-----------------------------------------------------------------------------
1322 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1324 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1326 //-----------------------------------------------------------------------------
1327 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1329 if (iaUser->phase.GetPhase() != 3)
1331 if (iaSettings.LogProtocolErrors())
1332 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());
1333 errorStr = "Incorrect request DISCONN_SYN";
1334 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1338 iaUser->phase.SetPhase4();
1339 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1343 //-----------------------------------------------------------------------------
1344 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1347 std::map<uint32_t, IA_USER>::iterator)
1350 SwapBytes(disconnAck->len);
1351 SwapBytes(disconnAck->rnd);
1353 printfd(__FILE__, "DISCONN_ACK_6\n");
1354 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1356 if (iaSettings.LogProtocolErrors())
1358 if (iaUser->phase.GetPhase() != 4)
1359 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());
1360 if (disconnAck->rnd != iaUser->rnd + 1)
1361 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);
1363 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1369 //-----------------------------------------------------------------------------
1370 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)
1372 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1374 //-----------------------------------------------------------------------------
1375 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1378 SwapBytes(disconnAck->len);
1379 SwapBytes(disconnAck->rnd);
1381 printfd(__FILE__, "DISCONN_ACK_8\n");
1382 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1384 if (iaSettings.LogProtocolErrors())
1386 if (iaUser->phase.GetPhase() != 4)
1387 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());
1388 if (disconnAck->rnd != iaUser->rnd + 1)
1389 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);
1391 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1397 //-----------------------------------------------------------------------------
1398 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1400 //+++ Fill static data in connSynAck +++
1401 // TODO Move this code. It must be executed only once
1402 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1403 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1404 for (int j = 0; j < DIR_NUM; j++)
1406 strncpy((char*)connSynAck6.dirName[j],
1407 stgSettings->GetDirName(j).c_str(),
1410 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1412 //--- Fill static data in connSynAck ---
1414 iaUser->rnd = static_cast<uint32_t>(random());
1415 connSynAck6.rnd = iaUser->rnd;
1417 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1418 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1421 SwapBytes(connSynAck6.len);
1422 SwapBytes(connSynAck6.rnd);
1423 SwapBytes(connSynAck6.userTimeOut);
1424 SwapBytes(connSynAck6.aliveDelay);
1427 EncryptString((char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)), &iaUser->ctx);
1428 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1430 //-----------------------------------------------------------------------------
1431 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1433 return Send_CONN_SYN_ACK_6(iaUser, sip);
1435 //-----------------------------------------------------------------------------
1436 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1438 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1439 connSynAck8.hdr.protoVer[0] = 0;
1440 connSynAck8.hdr.protoVer[1] = 8;
1442 //+++ Fill static data in connSynAck +++
1443 // TODO Move this code. It must be executed only once
1444 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1445 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1446 for (int j = 0; j < DIR_NUM; j++)
1448 strncpy((char*)connSynAck8.dirName[j],
1449 stgSettings->GetDirName(j).c_str(),
1452 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1454 //--- Fill static data in connSynAck ---
1456 iaUser->rnd = static_cast<uint32_t>(random());
1457 connSynAck8.rnd = iaUser->rnd;
1459 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1460 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1463 SwapBytes(connSynAck8.len);
1464 SwapBytes(connSynAck8.rnd);
1465 SwapBytes(connSynAck8.userTimeOut);
1466 SwapBytes(connSynAck8.aliveDelay);
1469 EncryptString((char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)), &iaUser->ctx);
1470 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1472 //-----------------------------------------------------------------------------
1473 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1475 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1476 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1478 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1480 for (int i = 0; i < DIR_NUM; i++)
1482 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1483 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1485 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1486 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1490 int dn = iaSettings.GetFreeMbShowType();
1491 const TARIFF * tf = iaUser->user->GetTariff();
1495 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1500 if (std::fabs(p) < 1.0e-3)
1502 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1506 double fmb = iaUser->user->GetProperty().freeMb;
1507 fmb = fmb < 0 ? 0 : fmb;
1508 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1513 if (freeMbNone == iaSettings.GetFreeMbShowType())
1515 aliveSyn6.freeMb[0] = 0;
1519 double fmb = iaUser->user->GetProperty().freeMb;
1520 fmb = fmb < 0 ? 0 : fmb;
1521 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1526 if (iaUser->aliveSent)
1528 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1530 iaUser->aliveSent = true;
1533 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1534 if (!stgSettings->GetShowFeeInCash())
1535 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1538 SwapBytes(aliveSyn6.len);
1539 SwapBytes(aliveSyn6.rnd);
1540 SwapBytes(aliveSyn6.cash);
1541 for (int i = 0; i < DIR_NUM; ++i)
1543 SwapBytes(aliveSyn6.mu[i]);
1544 SwapBytes(aliveSyn6.md[i]);
1545 SwapBytes(aliveSyn6.su[i]);
1546 SwapBytes(aliveSyn6.sd[i]);
1550 EncryptString((char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)), &iaUser->ctx);
1551 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1553 //-----------------------------------------------------------------------------
1554 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1556 return Send_ALIVE_SYN_6(iaUser, sip);
1558 //-----------------------------------------------------------------------------
1559 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1561 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1562 aliveSyn8.hdr.protoVer[0] = 0;
1563 aliveSyn8.hdr.protoVer[1] = 8;
1565 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1566 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1568 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1570 for (int i = 0; i < DIR_NUM; i++)
1572 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1573 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1575 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1576 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1580 int dn = iaSettings.GetFreeMbShowType();
1584 const TARIFF * tf = iaUser->user->GetTariff();
1585 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1590 if (std::fabs(p) < 1.0e-3)
1592 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1596 double fmb = iaUser->user->GetProperty().freeMb;
1597 fmb = fmb < 0 ? 0 : fmb;
1598 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1603 if (freeMbNone == iaSettings.GetFreeMbShowType())
1605 aliveSyn8.freeMb[0] = 0;
1609 double fmb = iaUser->user->GetProperty().freeMb;
1610 fmb = fmb < 0 ? 0 : fmb;
1611 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1616 if (iaUser->aliveSent)
1618 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1620 iaUser->aliveSent = true;
1623 const TARIFF * tf = iaUser->user->GetTariff();
1625 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1626 if (!stgSettings->GetShowFeeInCash())
1627 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1630 SwapBytes(aliveSyn8.len);
1631 SwapBytes(aliveSyn8.rnd);
1632 SwapBytes(aliveSyn8.cash);
1633 SwapBytes(aliveSyn8.status);
1634 for (int i = 0; i < DIR_NUM; ++i)
1636 SwapBytes(aliveSyn8.mu[i]);
1637 SwapBytes(aliveSyn8.md[i]);
1638 SwapBytes(aliveSyn8.su[i]);
1639 SwapBytes(aliveSyn8.sd[i]);
1643 EncryptString((char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)), &iaUser->ctx);
1644 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1646 //-----------------------------------------------------------------------------
1647 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1649 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1650 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1651 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1654 SwapBytes(disconnSynAck6.len);
1655 SwapBytes(disconnSynAck6.rnd);
1658 EncryptString((char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)), &iaUser->ctx);
1659 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1661 //-----------------------------------------------------------------------------
1662 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1664 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1666 //-----------------------------------------------------------------------------
1667 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1669 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1670 disconnSynAck8.hdr.protoVer[0] = 0;
1671 disconnSynAck8.hdr.protoVer[1] = 8;
1673 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1674 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1675 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1678 SwapBytes(disconnSynAck8.len);
1679 SwapBytes(disconnSynAck8.rnd);
1682 EncryptString((char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)), &iaUser->ctx);
1683 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1685 //-----------------------------------------------------------------------------
1686 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1688 fin6.len = Min8(sizeof(FIN_6));
1689 strcpy((char*)fin6.type, "FIN");
1690 strcpy((char*)fin6.ok, "OK");
1693 SwapBytes(fin6.len);
1696 EncryptString((char*)&fin6, (char*)&fin6, Min8(sizeof(fin6)), &iaUser->ctx);
1698 users->Unauthorize(iaUser->login, this);
1700 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1706 //-----------------------------------------------------------------------------
1707 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1709 return Send_FIN_6(iaUser, sip, it);
1711 //-----------------------------------------------------------------------------
1712 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1714 strcpy((char*)fin8.hdr.magic, IA_ID);
1715 fin8.hdr.protoVer[0] = 0;
1716 fin8.hdr.protoVer[1] = 8;
1718 fin8.len = Min8(sizeof(FIN_8));
1719 strcpy((char*)fin8.type, "FIN");
1720 strcpy((char*)fin8.ok, "OK");
1723 SwapBytes(fin8.len);
1726 EncryptString((char*)&fin8, (char*)&fin8, Min8(sizeof(fin8)), &iaUser->ctx);
1728 users->Unauthorize(iaUser->login, this);
1730 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));