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() || pvi->value.empty())
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() || pvi->value.empty())
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() || pvi->value.empty())
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() || pvi->value.empty())
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() || pvi->value.empty())
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
193 gettimeofday(&phaseTime, NULL);
199 gettimeofday(&phaseTime, NULL);
202 //-----------------------------------------------------------------------------
203 IA_PHASE::~IA_PHASE()
205 #ifdef IA_PHASE_DEBUG
206 flog = fopen(log.c_str(), "at");
209 fprintf(flog, "IA %s D\n", login.c_str());
214 //-----------------------------------------------------------------------------
215 #ifdef IA_PHASE_DEBUG
216 void IA_PHASE::SetLogFileName(const string & logFileName)
218 log = logFileName + ".ia.log";
220 //-----------------------------------------------------------------------------
221 void IA_PHASE::SetUserLogin(const string & login)
223 IA_PHASE::login = login;
225 //-----------------------------------------------------------------------------
226 void IA_PHASE::WritePhaseChange(int newPhase)
229 gettimeofday(&newPhaseTime, NULL);
230 flog = fopen(log.c_str(), "at");
233 string action = newPhase == phase ? "U" : "C";
234 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
235 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
236 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
246 //-----------------------------------------------------------------------------
247 void IA_PHASE::SetPhase1()
249 #ifdef IA_PHASE_DEBUG
253 gettimeofday(&phaseTime, NULL);
255 //-----------------------------------------------------------------------------
256 void IA_PHASE::SetPhase2()
258 #ifdef IA_PHASE_DEBUG
262 gettimeofday(&phaseTime, NULL);
264 //-----------------------------------------------------------------------------
265 void IA_PHASE::SetPhase3()
267 #ifdef IA_PHASE_DEBUG
271 gettimeofday(&phaseTime, NULL);
273 //-----------------------------------------------------------------------------
274 void IA_PHASE::SetPhase4()
276 #ifdef IA_PHASE_DEBUG
280 gettimeofday(&phaseTime, NULL);
282 //-----------------------------------------------------------------------------
283 int IA_PHASE::GetPhase() const
287 //-----------------------------------------------------------------------------
288 void IA_PHASE::UpdateTime()
290 #ifdef IA_PHASE_DEBUG
291 WritePhaseChange(phase);
293 gettimeofday(&phaseTime, NULL);
295 //-----------------------------------------------------------------------------
296 const UTIME & IA_PHASE::GetTime() const
300 //-----------------------------------------------------------------------------
301 //-----------------------------------------------------------------------------
302 //-----------------------------------------------------------------------------
310 isRunningRunTimeouter(false),
327 enabledDirs(0xFFffFFff),
328 onDelUserNotifier(*this),
329 logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
331 InitContext("pr7Hhen", 7, &ctxS);
333 pthread_mutexattr_t attr;
334 pthread_mutexattr_init(&attr);
335 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
336 pthread_mutex_init(&mutex, &attr);
338 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
339 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
340 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
341 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
342 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
343 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
344 memset(&fin6, 0, sizeof(FIN_6));
345 memset(&fin8, 0, sizeof(FIN_8));
347 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
348 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
349 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
350 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
351 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
352 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
353 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
354 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
355 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
356 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
357 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
358 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
359 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
360 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
361 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
362 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
363 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
364 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
366 packetTypes["CONN_SYN"] = CONN_SYN_N;
367 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
368 packetTypes["CONN_ACK"] = CONN_ACK_N;
369 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
370 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
371 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
372 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
373 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
374 packetTypes["FIN"] = FIN_N;
375 packetTypes["ERR"] = ERROR_N;
377 //-----------------------------------------------------------------------------
380 pthread_mutex_destroy(&mutex);
382 //-----------------------------------------------------------------------------
385 users->AddNotifierUserDel(&onDelUserNotifier);
395 if (pthread_create(&recvThread, NULL, Run, this))
397 errorStr = "Cannot create thread.";
398 printfd(__FILE__, "Cannot create recv thread\n");
399 logger("Cannot create recv thread.");
404 if (!isRunningRunTimeouter)
406 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
408 errorStr = "Cannot create thread.";
409 printfd(__FILE__, "Cannot create timeouter thread\n");
410 logger("Cannot create timeouter thread.");
417 //-----------------------------------------------------------------------------
428 UnauthorizeUser(this)
433 //5 seconds to thread stops itself
434 for (int i = 0; i < 25 && isRunningRun; i++)
436 struct timespec ts = {0, 200000000};
437 nanosleep(&ts, NULL);
443 if (isRunningRunTimeouter)
445 //5 seconds to thread stops itself
446 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
448 struct timespec ts = {0, 200000000};
449 nanosleep(&ts, NULL);
453 users->DelNotifierUserDel(&onDelUserNotifier);
455 if (isRunningRun || isRunningRunTimeouter)
458 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
461 //-----------------------------------------------------------------------------
462 void * AUTH_IA::Run(void * d)
465 sigfillset(&signalSet);
466 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
468 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
470 ia->isRunningRun = true;
474 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
478 ia->RecvData(buffer, sizeof(buffer));
479 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
482 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
483 TouchFile(monFile.c_str());
487 ia->isRunningRun = false;
490 //-----------------------------------------------------------------------------
491 void * AUTH_IA::RunTimeouter(void * d)
494 sigfillset(&signalSet);
495 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
497 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
499 ia->isRunningRunTimeouter = true;
502 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
505 struct timespec ts = {0, 20000000};
506 nanosleep(&ts, NULL);
508 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
509 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
511 TouchFile(monFile.c_str());
515 ia->isRunningRunTimeouter = false;
518 //-----------------------------------------------------------------------------
519 int AUTH_IA::ParseSettings()
521 int ret = iaSettings.ParseSettings(settings);
523 errorStr = iaSettings.GetStrError();
526 //-----------------------------------------------------------------------------
527 int AUTH_IA::Reload(const MODULE_SETTINGS & ms)
529 AUTH_IA_SETTINGS newIaSettings;
530 if (newIaSettings.ParseSettings(ms))
532 STG_LOGGER & WriteServLog = GetStgLogger();
533 printfd(__FILE__, "AUTH_IA::Reload() - Failed to reload InetAccess.\n");
534 WriteServLog("AUTH_IA: Cannot reload InetAccess. Errors found.");
538 STG_LOGGER & WriteServLog = GetStgLogger();
539 printfd(__FILE__, "AUTH_IA::Reload() - Reloaded InetAccess successfully.\n");
540 WriteServLog("AUTH_IA: Reloaded InetAccess successfully.");
543 //-----------------------------------------------------------------------------
544 int AUTH_IA::PrepareNet()
546 struct sockaddr_in listenAddr;
548 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
550 if (listenSocket < 0)
552 errorStr = "Cannot create socket.";
553 logger("Cannot create a socket: %s", strerror(errno));
557 listenAddr.sin_family = AF_INET;
558 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
559 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
561 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
563 errorStr = "AUTH_IA: Bind failed.";
564 logger("Cannot bind the socket: %s", strerror(errno));
570 //-----------------------------------------------------------------------------
571 int AUTH_IA::FinalizeNet()
576 //-----------------------------------------------------------------------------
577 int AUTH_IA::RecvData(char * buffer, int bufferSize)
579 if (!WaitPackets(listenSocket)) // Timeout
584 struct sockaddr_in outerAddr;
585 socklen_t outerAddrLen(sizeof(outerAddr));
586 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
593 if (dataLen <= 0) // Error
597 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
598 logger("recvfrom error: %s", strerror(errno));
607 uint32_t sip = outerAddr.sin_addr.s_addr;
608 uint16_t sport = htons(outerAddr.sin_port);
611 if (CheckHeader(buffer, sip, &protoVer))
614 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
615 memset(login, 0, PASSWD_LEN);
617 DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS);
620 if (users->FindByName(login, &user))
622 logger("User's connect failed: user '%s' not found. IP %s",
624 inet_ntostring(sip).c_str());
625 printfd(__FILE__, "User '%s' NOT found!\n", login);
626 SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
630 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
632 if (user->GetProperty().disabled.Get())
634 logger("Cannont authorize '%s', user is disabled.", login);
635 SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
639 if (user->GetProperty().passive.Get())
641 logger("Cannont authorize '%s', user is passive.", login);
642 SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
646 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
648 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
649 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
650 logger("User %s. IP address is incorrect. IP %s",
651 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
652 SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
656 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
658 //-----------------------------------------------------------------------------
659 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
661 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
663 printfd(__FILE__, "update needed - IA_ID\n");
664 if (iaSettings.LogProtocolErrors())
665 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
669 if (buffer[6] != 0) //proto[0] shoud be 0
671 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
672 if (iaSettings.LogProtocolErrors())
673 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
680 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
681 if (iaSettings.LogProtocolErrors())
682 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
687 *protoVer = buffer[7];
691 //-----------------------------------------------------------------------------
692 int AUTH_IA::Timeouter()
694 STG_LOCKER lock(&mutex);
696 std::map<uint32_t, IA_USER>::iterator it;
697 it = ip2user.begin();
699 while (it != ip2user.end())
701 uint32_t sip = it->first;
703 static UTIME currTime;
704 gettimeofday(&currTime, NULL);
706 if ((it->second.phase.GetPhase() == 2)
707 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
709 if (iaSettings.LogProtocolErrors())
710 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());
711 it->second.phase.SetPhase1();
712 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
717 if (it->second.phase.GetPhase() == 3)
719 if (!it->second.messagesToSend.empty())
721 if (it->second.protoVer == 6)
722 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
724 if (it->second.protoVer == 7)
725 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
727 if (it->second.protoVer == 8)
728 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
730 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
733 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
735 switch (it->second.protoVer)
738 Send_ALIVE_SYN_6(&(it->second), sip);
741 Send_ALIVE_SYN_7(&(it->second), sip);
744 Send_ALIVE_SYN_8(&(it->second), sip);
748 gettimeofday(&it->second.lastSendAlive, NULL);
751 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
753 if (iaSettings.LogProtocolErrors())
754 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());
755 users->Unauthorize(it->second.user->GetLogin(), this);
761 if ((it->second.phase.GetPhase() == 4)
762 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
764 if (iaSettings.LogProtocolErrors())
765 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());
766 it->second.phase.SetPhase3();
767 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
775 //-----------------------------------------------------------------------------
776 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
778 std::string login(user->GetLogin());
779 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
781 STG_LOCKER lock(&mutex);
782 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
784 if (it == ip2user.end())
787 if (!users->FindByIPIdx(sip, &userPtr))
789 if (userPtr->GetID() != user->GetID())
791 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
792 userPtr->GetLogin().c_str(),
793 inet_ntostring(sip).c_str(),
795 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
796 userPtr->GetLogin().c_str(),
797 inet_ntostring(sip).c_str(),
799 SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
804 printfd(__FILE__, "Add new user '%s' from ip %s\n",
805 login.c_str(), inet_ntostring(sip).c_str());
806 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
807 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
809 #ifdef IA_PHASE_DEBUG
810 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
811 it->second.phase.SetUserLogin(login);
814 else if (user->GetID() != it->second.user->GetID())
816 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
817 it->second.user->GetLogin().c_str(),
818 inet_ntostring(sip).c_str(),
819 user->GetLogin().c_str());
820 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
821 it->second.user->GetLogin().c_str(),
822 inet_ntostring(sip).c_str(),
823 user->GetLogin().c_str());
824 SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
828 IA_USER * iaUser = &(it->second);
830 if (iaUser->password != user->GetProperty().password.Get())
832 const std::string & password = user->GetProperty().password.Get();
833 InitContext(password.c_str(), password.length(), &iaUser->ctx);
834 iaUser->password = user->GetProperty().password.Get();
837 DecryptString(static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
839 char packetName[IA_MAX_TYPE_LEN];
840 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
841 packetName[IA_MAX_TYPE_LEN - 1] = 0;
843 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
844 if (pi == packetTypes.end())
846 SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
847 printfd(__FILE__, "Login or password is wrong!\n");
848 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
850 inet_ntostring(sip).c_str());
855 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
857 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
858 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
859 inet_ntostring(sip).c_str());
860 logger("Login '%s' is already in use from ip %s. IP %s",
862 inet_ntostring(user->GetCurrIP()).c_str(),
863 inet_ntostring(sip).c_str());
864 SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
875 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
877 return Send_CONN_SYN_ACK_6(iaUser, sip);
879 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
881 return Send_CONN_SYN_ACK_7(iaUser, sip);
883 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
885 return Send_CONN_SYN_ACK_8(iaUser, sip);
893 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
895 return Send_ALIVE_SYN_6(iaUser, sip);
897 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
899 return Send_ALIVE_SYN_7(iaUser, sip);
901 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
903 return Send_ALIVE_SYN_8(iaUser, sip);
911 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
913 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
915 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
923 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
925 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
927 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
929 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
931 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
933 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
941 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
943 return Send_FIN_6(iaUser, sip, it);
945 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
947 return Send_FIN_7(iaUser, sip, it);
949 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
951 return Send_FIN_8(iaUser, sip, it);
958 //-----------------------------------------------------------------------------
959 void AUTH_IA::DelUser(USER_PTR u)
962 uint32_t ip = u->GetCurrIP();
967 std::map<uint32_t, IA_USER>::iterator it;
969 STG_LOCKER lock(&mutex);
970 it = ip2user.find(ip);
971 if (it == ip2user.end())
974 printfd(__FILE__, "Nothing to delete\n");
978 if (it->second.user == u)
980 printfd(__FILE__, "User removed!\n");
981 users->Unauthorize(u->GetLogin(), this);
985 //-----------------------------------------------------------------------------
986 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
988 struct sockaddr_in sendAddr;
995 memset(&err, 0, sizeof(ERR));
997 sendAddr.sin_family = AF_INET;
998 sendAddr.sin_port = htons(port);
999 sendAddr.sin_addr.s_addr = ip;
1002 strncpy((char*)err.type, "ERR", 16);
1003 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1009 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1010 printfd(__FILE__, "SendError %d bytes sent\n", res);
1015 memset(&err8, 0, sizeof(ERR_8));
1017 sendAddr.sin_family = AF_INET;
1018 sendAddr.sin_port = htons(port);
1019 sendAddr.sin_addr.s_addr = ip;
1022 strncpy((char*)err8.type, "ERR", 16);
1023 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1026 SwapBytes(err8.len);
1029 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1030 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1036 //-----------------------------------------------------------------------------
1037 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1039 struct sockaddr_in sendAddr;
1041 sendAddr.sin_family = AF_INET;
1042 sendAddr.sin_port = htons(port);
1043 sendAddr.sin_addr.s_addr = ip;
1045 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1050 //-----------------------------------------------------------------------------
1051 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1053 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1055 std::map<uint32_t, IA_USER>::iterator it;
1057 STG_LOCKER lock(&mutex);
1058 it = ip2user.find(ip);
1059 if (it == ip2user.end())
1061 errorStr = "Unknown user.";
1064 it->second.messagesToSend.push_back(msg);
1067 //-----------------------------------------------------------------------------
1068 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1070 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1073 memset(&info, 0, sizeof(INFO_6));
1076 strncpy((char*)info.type, "INFO", 16);
1077 info.infoType = 'I';
1078 strncpy((char*)info.text, msg.text.c_str(), 235);
1081 size_t len = info.len;
1083 SwapBytes(info.len);
1087 memcpy(buffer, &info, sizeof(INFO_6));
1088 EncryptString(buffer, buffer, len, &user.ctx);
1089 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1091 //-----------------------------------------------------------------------------
1092 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1094 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1097 memset(&info, 0, sizeof(INFO_7));
1100 strncpy((char*)info.type, "INFO_7", 16);
1101 info.infoType = static_cast<int8_t>(msg.header.type);
1102 info.showTime = static_cast<int8_t>(msg.header.showTime);
1103 info.sendTime = msg.header.creationTime;
1105 size_t len = info.len;
1107 SwapBytes(info.len);
1108 SwapBytes(info.sendTime);
1111 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1112 info.text[MAX_MSG_LEN - 1] = 0;
1115 memcpy(buffer, &info, sizeof(INFO_7));
1117 EncryptString(buffer, buffer, len, &user.ctx);
1118 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1120 //-----------------------------------------------------------------------------
1121 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1123 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1126 memset(&info, 0, sizeof(INFO_8));
1129 strncpy((char*)info.type, "INFO_8", 16);
1130 info.infoType = static_cast<int8_t>(msg.header.type);
1131 info.showTime = static_cast<int8_t>(msg.header.showTime);
1132 info.sendTime = msg.header.creationTime;
1134 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1135 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1137 size_t len = info.len;
1139 SwapBytes(info.len);
1140 SwapBytes(info.sendTime);
1144 memcpy(buffer, &info, sizeof(INFO_8));
1146 EncryptString(buffer, buffer, len, &user.ctx);
1147 return Send(ip, user.port, buffer, len);
1149 //-----------------------------------------------------------------------------
1150 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1152 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1155 enabledDirs = 0xFFffFFff;
1157 iaUser->phase.SetPhase2();
1158 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1161 //-----------------------------------------------------------------------------
1162 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1164 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1166 //-----------------------------------------------------------------------------
1167 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1170 SwapBytes(connSyn->dirs);
1172 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1173 enabledDirs = connSyn->dirs;
1176 //-----------------------------------------------------------------------------
1177 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1180 SwapBytes(connAck->len);
1181 SwapBytes(connAck->rnd);
1183 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1185 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1187 iaUser->phase.UpdateTime();
1189 iaUser->lastSendAlive = iaUser->phase.GetTime();
1190 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1192 iaUser->phase.SetPhase3();
1193 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1198 errorStr = iaUser->user->GetStrError();
1199 if (iaSettings.LogProtocolErrors())
1200 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());
1201 iaUser->phase.SetPhase1();
1203 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1207 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1208 if (iaSettings.LogProtocolErrors())
1210 if (iaUser->phase.GetPhase() != 2)
1211 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());
1212 if (connAck->rnd != iaUser->rnd + 1)
1213 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);
1217 //-----------------------------------------------------------------------------
1218 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1220 return Process_CONN_ACK_6(connAck, iaUser, sip);
1222 //-----------------------------------------------------------------------------
1223 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1226 SwapBytes(connAck->len);
1227 SwapBytes(connAck->rnd);
1229 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1231 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1233 iaUser->phase.UpdateTime();
1234 iaUser->lastSendAlive = iaUser->phase.GetTime();
1235 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1237 iaUser->phase.SetPhase3();
1238 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1243 errorStr = iaUser->user->GetStrError();
1244 if (iaSettings.LogProtocolErrors())
1245 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());
1246 iaUser->phase.SetPhase1();
1248 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1252 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1253 if (iaSettings.LogProtocolErrors())
1255 if (iaUser->phase.GetPhase() != 2)
1256 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());
1257 if (connAck->rnd != iaUser->rnd + 1)
1258 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);
1262 //-----------------------------------------------------------------------------
1263 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1266 SwapBytes(aliveAck->len);
1267 SwapBytes(aliveAck->rnd);
1269 printfd(__FILE__, "ALIVE_ACK_6\n");
1270 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1272 iaUser->phase.UpdateTime();
1274 iaUser->aliveSent = false;
1279 //-----------------------------------------------------------------------------
1280 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1282 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1284 //-----------------------------------------------------------------------------
1285 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1288 SwapBytes(aliveAck->len);
1289 SwapBytes(aliveAck->rnd);
1291 printfd(__FILE__, "ALIVE_ACK_8\n");
1292 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1294 iaUser->phase.UpdateTime();
1296 iaUser->aliveSent = false;
1301 //-----------------------------------------------------------------------------
1302 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1304 printfd(__FILE__, "DISCONN_SYN_6\n");
1305 if (iaUser->phase.GetPhase() != 3)
1307 if (iaSettings.LogProtocolErrors())
1308 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());
1309 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1310 errorStr = "Incorrect request DISCONN_SYN";
1314 iaUser->phase.SetPhase4();
1315 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1319 //-----------------------------------------------------------------------------
1320 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1322 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1324 //-----------------------------------------------------------------------------
1325 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1327 if (iaUser->phase.GetPhase() != 3)
1329 if (iaSettings.LogProtocolErrors())
1330 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());
1331 errorStr = "Incorrect request DISCONN_SYN";
1332 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1336 iaUser->phase.SetPhase4();
1337 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1341 //-----------------------------------------------------------------------------
1342 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1345 std::map<uint32_t, IA_USER>::iterator)
1348 SwapBytes(disconnAck->len);
1349 SwapBytes(disconnAck->rnd);
1351 printfd(__FILE__, "DISCONN_ACK_6\n");
1352 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1354 if (iaSettings.LogProtocolErrors())
1356 if (iaUser->phase.GetPhase() != 4)
1357 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());
1358 if (disconnAck->rnd != iaUser->rnd + 1)
1359 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);
1361 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1367 //-----------------------------------------------------------------------------
1368 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)
1370 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1372 //-----------------------------------------------------------------------------
1373 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1376 SwapBytes(disconnAck->len);
1377 SwapBytes(disconnAck->rnd);
1379 printfd(__FILE__, "DISCONN_ACK_8\n");
1380 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1382 if (iaSettings.LogProtocolErrors())
1384 if (iaUser->phase.GetPhase() != 4)
1385 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());
1386 if (disconnAck->rnd != iaUser->rnd + 1)
1387 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);
1389 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1395 //-----------------------------------------------------------------------------
1396 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1398 //+++ Fill static data in connSynAck +++
1399 // TODO Move this code. It must be executed only once
1400 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1401 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1402 for (int j = 0; j < DIR_NUM; j++)
1404 strncpy((char*)connSynAck6.dirName[j],
1405 stgSettings->GetDirName(j).c_str(),
1408 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1410 //--- Fill static data in connSynAck ---
1412 iaUser->rnd = static_cast<uint32_t>(random());
1413 connSynAck6.rnd = iaUser->rnd;
1415 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1416 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1419 SwapBytes(connSynAck6.len);
1420 SwapBytes(connSynAck6.rnd);
1421 SwapBytes(connSynAck6.userTimeOut);
1422 SwapBytes(connSynAck6.aliveDelay);
1425 EncryptString((char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)), &iaUser->ctx);
1426 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1428 //-----------------------------------------------------------------------------
1429 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1431 return Send_CONN_SYN_ACK_6(iaUser, sip);
1433 //-----------------------------------------------------------------------------
1434 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1436 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1437 connSynAck8.hdr.protoVer[0] = 0;
1438 connSynAck8.hdr.protoVer[1] = 8;
1440 //+++ Fill static data in connSynAck +++
1441 // TODO Move this code. It must be executed only once
1442 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1443 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1444 for (int j = 0; j < DIR_NUM; j++)
1446 strncpy((char*)connSynAck8.dirName[j],
1447 stgSettings->GetDirName(j).c_str(),
1450 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1452 //--- Fill static data in connSynAck ---
1454 iaUser->rnd = static_cast<uint32_t>(random());
1455 connSynAck8.rnd = iaUser->rnd;
1457 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1458 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1461 SwapBytes(connSynAck8.len);
1462 SwapBytes(connSynAck8.rnd);
1463 SwapBytes(connSynAck8.userTimeOut);
1464 SwapBytes(connSynAck8.aliveDelay);
1467 EncryptString((char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)), &iaUser->ctx);
1468 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1470 //-----------------------------------------------------------------------------
1471 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1473 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1474 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1476 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1478 for (int i = 0; i < DIR_NUM; i++)
1480 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1481 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1483 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1484 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1488 int dn = iaSettings.GetFreeMbShowType();
1489 const TARIFF * tf = iaUser->user->GetTariff();
1493 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1498 if (std::fabs(p) < 1.0e-3)
1500 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1504 double fmb = iaUser->user->GetProperty().freeMb;
1505 fmb = fmb < 0 ? 0 : fmb;
1506 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1511 if (freeMbNone == iaSettings.GetFreeMbShowType())
1513 aliveSyn6.freeMb[0] = 0;
1517 double fmb = iaUser->user->GetProperty().freeMb;
1518 fmb = fmb < 0 ? 0 : fmb;
1519 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1524 if (iaUser->aliveSent)
1526 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1528 iaUser->aliveSent = true;
1531 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1532 if (!stgSettings->GetShowFeeInCash())
1533 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1536 SwapBytes(aliveSyn6.len);
1537 SwapBytes(aliveSyn6.rnd);
1538 SwapBytes(aliveSyn6.cash);
1539 for (int i = 0; i < DIR_NUM; ++i)
1541 SwapBytes(aliveSyn6.mu[i]);
1542 SwapBytes(aliveSyn6.md[i]);
1543 SwapBytes(aliveSyn6.su[i]);
1544 SwapBytes(aliveSyn6.sd[i]);
1548 EncryptString((char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)), &iaUser->ctx);
1549 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1551 //-----------------------------------------------------------------------------
1552 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1554 return Send_ALIVE_SYN_6(iaUser, sip);
1556 //-----------------------------------------------------------------------------
1557 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1559 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1560 aliveSyn8.hdr.protoVer[0] = 0;
1561 aliveSyn8.hdr.protoVer[1] = 8;
1563 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1564 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1566 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1568 for (int i = 0; i < DIR_NUM; i++)
1570 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1571 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1573 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1574 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1578 int dn = iaSettings.GetFreeMbShowType();
1582 const TARIFF * tf = iaUser->user->GetTariff();
1583 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1588 if (std::fabs(p) < 1.0e-3)
1590 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1594 double fmb = iaUser->user->GetProperty().freeMb;
1595 fmb = fmb < 0 ? 0 : fmb;
1596 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1601 if (freeMbNone == iaSettings.GetFreeMbShowType())
1603 aliveSyn8.freeMb[0] = 0;
1607 double fmb = iaUser->user->GetProperty().freeMb;
1608 fmb = fmb < 0 ? 0 : fmb;
1609 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1614 if (iaUser->aliveSent)
1616 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1618 iaUser->aliveSent = true;
1621 const TARIFF * tf = iaUser->user->GetTariff();
1623 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1624 if (!stgSettings->GetShowFeeInCash())
1625 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1628 SwapBytes(aliveSyn8.len);
1629 SwapBytes(aliveSyn8.rnd);
1630 SwapBytes(aliveSyn8.cash);
1631 SwapBytes(aliveSyn8.status);
1632 for (int i = 0; i < DIR_NUM; ++i)
1634 SwapBytes(aliveSyn8.mu[i]);
1635 SwapBytes(aliveSyn8.md[i]);
1636 SwapBytes(aliveSyn8.su[i]);
1637 SwapBytes(aliveSyn8.sd[i]);
1641 EncryptString((char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)), &iaUser->ctx);
1642 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1644 //-----------------------------------------------------------------------------
1645 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1647 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1648 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1649 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1652 SwapBytes(disconnSynAck6.len);
1653 SwapBytes(disconnSynAck6.rnd);
1656 EncryptString((char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)), &iaUser->ctx);
1657 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1659 //-----------------------------------------------------------------------------
1660 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1662 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1664 //-----------------------------------------------------------------------------
1665 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1667 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1668 disconnSynAck8.hdr.protoVer[0] = 0;
1669 disconnSynAck8.hdr.protoVer[1] = 8;
1671 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1672 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1673 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1676 SwapBytes(disconnSynAck8.len);
1677 SwapBytes(disconnSynAck8.rnd);
1680 EncryptString((char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)), &iaUser->ctx);
1681 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1683 //-----------------------------------------------------------------------------
1684 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1686 fin6.len = Min8(sizeof(FIN_6));
1687 strcpy((char*)fin6.type, "FIN");
1688 strcpy((char*)fin6.ok, "OK");
1691 SwapBytes(fin6.len);
1694 EncryptString((char*)&fin6, (char*)&fin6, Min8(sizeof(fin6)), &iaUser->ctx);
1696 users->Unauthorize(iaUser->login, this);
1698 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1704 //-----------------------------------------------------------------------------
1705 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1707 return Send_FIN_6(iaUser, sip, it);
1709 //-----------------------------------------------------------------------------
1710 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1712 strcpy((char*)fin8.hdr.magic, IA_ID);
1713 fin8.hdr.protoVer[0] = 0;
1714 fin8.hdr.protoVer[1] = 8;
1716 fin8.len = Min8(sizeof(FIN_8));
1717 strcpy((char*)fin8.type, "FIN");
1718 strcpy((char*)fin8.ok, "OK");
1721 SwapBytes(fin8.len);
1724 EncryptString((char*)&fin8, (char*)&fin8, Min8(sizeof(fin8)), &iaUser->ctx);
1726 users->Unauthorize(iaUser->login, this);
1728 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));