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 if (logProtocolErrors)
146 printfd(__FILE__, "LogProtocolErrors: true\n");
148 printfd(__FILE__, "LogProtocolErrors: false\n");
149 /////////////////////////////////////////////////////////////
150 std::string freeMbType;
153 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
154 if (pvi == s.moduleParams.end())
156 errorStr = "Parameter \'FreeMb\' not found.";
157 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
160 freeMbType = pvi->value[0];
162 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
164 freeMbShowType = freeMbCash;
166 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
168 freeMbShowType = freeMbNone;
170 else if (!str2x(freeMbType.c_str(), n))
172 if (n < 0 || n >= DIR_NUM)
174 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
175 printfd(__FILE__, "%s\n", errorStr.c_str());
178 freeMbShowType = (FREEMB)(freeMb0 + n);
182 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
183 printfd(__FILE__, "%s\n", errorStr.c_str());
186 /////////////////////////////////////////////////////////////
189 //-----------------------------------------------------------------------------
190 //-----------------------------------------------------------------------------
191 //-----------------------------------------------------------------------------
192 #ifdef IA_PHASE_DEBUG
198 gettimeofday(&phaseTime, NULL);
205 gettimeofday(&phaseTime, NULL);
208 //-----------------------------------------------------------------------------
209 IA_PHASE::~IA_PHASE()
211 #ifdef IA_PHASE_DEBUG
212 flog = fopen(log.c_str(), "at");
215 fprintf(flog, "IA %s D\n", login.c_str());
220 //-----------------------------------------------------------------------------
221 #ifdef IA_PHASE_DEBUG
222 void IA_PHASE::SetLogFileName(const string & logFileName)
224 log = logFileName + ".ia.log";
226 //-----------------------------------------------------------------------------
227 void IA_PHASE::SetUserLogin(const string & login)
229 IA_PHASE::login = login;
231 //-----------------------------------------------------------------------------
232 void IA_PHASE::WritePhaseChange(int newPhase)
235 gettimeofday(&newPhaseTime, NULL);
236 flog = fopen(log.c_str(), "at");
239 string action = newPhase == phase ? "U" : "C";
240 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
241 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
242 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
252 //-----------------------------------------------------------------------------
253 void IA_PHASE::SetPhase1()
255 #ifdef IA_PHASE_DEBUG
259 gettimeofday(&phaseTime, NULL);
261 //-----------------------------------------------------------------------------
262 void IA_PHASE::SetPhase2()
264 #ifdef IA_PHASE_DEBUG
268 gettimeofday(&phaseTime, NULL);
270 //-----------------------------------------------------------------------------
271 void IA_PHASE::SetPhase3()
273 #ifdef IA_PHASE_DEBUG
277 gettimeofday(&phaseTime, NULL);
279 //-----------------------------------------------------------------------------
280 void IA_PHASE::SetPhase4()
282 #ifdef IA_PHASE_DEBUG
286 gettimeofday(&phaseTime, NULL);
288 //-----------------------------------------------------------------------------
289 int IA_PHASE::GetPhase() const
293 //-----------------------------------------------------------------------------
294 void IA_PHASE::UpdateTime()
296 #ifdef IA_PHASE_DEBUG
297 WritePhaseChange(phase);
299 gettimeofday(&phaseTime, NULL);
301 //-----------------------------------------------------------------------------
302 const UTIME & IA_PHASE::GetTime() const
306 //-----------------------------------------------------------------------------
307 //-----------------------------------------------------------------------------
308 //-----------------------------------------------------------------------------
316 isRunningRunTimeouter(false),
333 enabledDirs(0xFFffFFff),
334 onDelUserNotifier(*this),
335 logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
337 InitContext("pr7Hhen", 7, &ctxS);
339 pthread_mutexattr_t attr;
340 pthread_mutexattr_init(&attr);
341 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
342 pthread_mutex_init(&mutex, &attr);
344 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
345 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
346 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
347 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
348 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
349 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
350 memset(&fin6, 0, sizeof(FIN_6));
351 memset(&fin8, 0, sizeof(FIN_8));
353 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
354 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
355 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
356 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
357 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
358 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
359 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
360 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
361 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
362 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
363 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
364 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
365 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
366 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
367 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
368 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
369 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
370 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
372 packetTypes["CONN_SYN"] = CONN_SYN_N;
373 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
374 packetTypes["CONN_ACK"] = CONN_ACK_N;
375 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
376 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
377 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
378 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
379 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
380 packetTypes["FIN"] = FIN_N;
381 packetTypes["ERR"] = ERROR_N;
383 //-----------------------------------------------------------------------------
386 pthread_mutex_destroy(&mutex);
388 //-----------------------------------------------------------------------------
391 users->AddNotifierUserDel(&onDelUserNotifier);
401 if (pthread_create(&recvThread, NULL, Run, this))
403 errorStr = "Cannot create thread.";
404 printfd(__FILE__, "Cannot create recv thread\n");
405 logger("Cannot create recv thread.");
410 if (!isRunningRunTimeouter)
412 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
414 errorStr = "Cannot create thread.";
415 printfd(__FILE__, "Cannot create timeouter thread\n");
416 logger("Cannot create timeouter thread.");
423 //-----------------------------------------------------------------------------
434 UnauthorizeUser(this)
439 //5 seconds to thread stops itself
440 for (int i = 0; i < 25 && isRunningRun; i++)
442 struct timespec ts = {0, 200000000};
443 nanosleep(&ts, NULL);
449 if (isRunningRunTimeouter)
451 //5 seconds to thread stops itself
452 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
454 struct timespec ts = {0, 200000000};
455 nanosleep(&ts, NULL);
459 users->DelNotifierUserDel(&onDelUserNotifier);
461 if (isRunningRun || isRunningRunTimeouter)
464 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
467 //-----------------------------------------------------------------------------
468 void * AUTH_IA::Run(void * d)
471 sigfillset(&signalSet);
472 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
474 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
476 ia->isRunningRun = true;
480 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
484 ia->RecvData(buffer, sizeof(buffer));
485 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
488 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
489 TouchFile(monFile.c_str());
493 ia->isRunningRun = false;
496 //-----------------------------------------------------------------------------
497 void * AUTH_IA::RunTimeouter(void * d)
500 sigfillset(&signalSet);
501 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
503 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
505 ia->isRunningRunTimeouter = true;
508 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
511 struct timespec ts = {0, 20000000};
512 nanosleep(&ts, NULL);
514 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
515 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
517 TouchFile(monFile.c_str());
521 ia->isRunningRunTimeouter = false;
524 //-----------------------------------------------------------------------------
525 int AUTH_IA::ParseSettings()
527 int ret = iaSettings.ParseSettings(settings);
529 errorStr = iaSettings.GetStrError();
532 //-----------------------------------------------------------------------------
533 int AUTH_IA::Reload(const MODULE_SETTINGS & ms)
535 AUTH_IA_SETTINGS newIaSettings;
536 if (newIaSettings.ParseSettings(ms))
538 STG_LOGGER & WriteServLog = GetStgLogger();
539 printfd(__FILE__, "AUTH_IA::Reload() - Failed to reload InetAccess.\n");
540 WriteServLog("AUTH_IA: Cannot reload InetAccess. Errors found.");
544 STG_LOGGER & WriteServLog = GetStgLogger();
545 printfd(__FILE__, "AUTH_IA::Reload() - Reloaded InetAccess successfully.\n");
546 WriteServLog("AUTH_IA: Reloaded InetAccess successfully.");
549 //-----------------------------------------------------------------------------
550 int AUTH_IA::PrepareNet()
552 struct sockaddr_in listenAddr;
554 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
556 if (listenSocket < 0)
558 errorStr = "Cannot create socket.";
559 logger("Cannot create a socket: %s", strerror(errno));
563 listenAddr.sin_family = AF_INET;
564 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
565 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
567 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
569 errorStr = "AUTH_IA: Bind failed.";
570 logger("Cannot bind the socket: %s", strerror(errno));
576 //-----------------------------------------------------------------------------
577 int AUTH_IA::FinalizeNet()
582 //-----------------------------------------------------------------------------
583 int AUTH_IA::RecvData(char * buffer, int bufferSize)
585 if (!WaitPackets(listenSocket)) // Timeout
590 struct sockaddr_in outerAddr;
591 socklen_t outerAddrLen(sizeof(outerAddr));
592 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
599 if (dataLen <= 0) // Error
603 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
604 logger("recvfrom error: %s", strerror(errno));
613 uint32_t sip = outerAddr.sin_addr.s_addr;
614 uint16_t sport = htons(outerAddr.sin_port);
617 if (CheckHeader(buffer, sip, &protoVer))
620 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
621 memset(login, 0, PASSWD_LEN);
623 DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS);
626 if (users->FindByName(login, &user))
628 logger("User's connect failed: user '%s' not found. IP %s",
630 inet_ntostring(sip).c_str());
631 printfd(__FILE__, "User '%s' NOT found!\n", login);
632 SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
636 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
638 if (user->GetProperty().disabled.Get())
640 logger("Cannont authorize '%s', user is disabled.", login);
641 SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
645 if (user->GetProperty().passive.Get())
647 logger("Cannont authorize '%s', user is passive.", login);
648 SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
652 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
654 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
655 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
656 logger("User %s. IP address is incorrect. IP %s",
657 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
658 SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
662 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
664 //-----------------------------------------------------------------------------
665 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
667 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
669 printfd(__FILE__, "update needed - IA_ID\n");
670 if (iaSettings.LogProtocolErrors())
671 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
675 if (buffer[6] != 0) //proto[0] shoud be 0
677 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
678 if (iaSettings.LogProtocolErrors())
679 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
686 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
687 if (iaSettings.LogProtocolErrors())
688 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
693 *protoVer = buffer[7];
697 //-----------------------------------------------------------------------------
698 int AUTH_IA::Timeouter()
700 STG_LOCKER lock(&mutex);
702 std::map<uint32_t, IA_USER>::iterator it;
703 it = ip2user.begin();
705 while (it != ip2user.end())
707 uint32_t sip = it->first;
709 static UTIME currTime;
710 gettimeofday(&currTime, NULL);
712 if ((it->second.phase.GetPhase() == 2)
713 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
715 if (iaSettings.LogProtocolErrors())
716 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());
717 it->second.phase.SetPhase1();
718 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
723 if (it->second.phase.GetPhase() == 3)
725 if (!it->second.messagesToSend.empty())
727 if (it->second.protoVer == 6)
728 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
730 if (it->second.protoVer == 7)
731 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
733 if (it->second.protoVer == 8)
734 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
736 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
739 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
741 switch (it->second.protoVer)
744 Send_ALIVE_SYN_6(&(it->second), sip);
747 Send_ALIVE_SYN_7(&(it->second), sip);
750 Send_ALIVE_SYN_8(&(it->second), sip);
754 gettimeofday(&it->second.lastSendAlive, NULL);
757 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
759 if (iaSettings.LogProtocolErrors())
760 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());
761 users->Unauthorize(it->second.user->GetLogin(), this);
767 if ((it->second.phase.GetPhase() == 4)
768 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
770 if (iaSettings.LogProtocolErrors())
771 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());
772 it->second.phase.SetPhase3();
773 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
781 //-----------------------------------------------------------------------------
782 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
784 std::string login(user->GetLogin());
785 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
787 STG_LOCKER lock(&mutex);
788 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
790 if (it == ip2user.end())
793 if (!users->FindByIPIdx(sip, &userPtr))
795 if (userPtr->GetID() != user->GetID())
797 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
798 userPtr->GetLogin().c_str(),
799 inet_ntostring(sip).c_str(),
801 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
802 userPtr->GetLogin().c_str(),
803 inet_ntostring(sip).c_str(),
805 SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
810 printfd(__FILE__, "Add new user '%s' from ip %s\n",
811 login.c_str(), inet_ntostring(sip).c_str());
812 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
813 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
815 #ifdef IA_PHASE_DEBUG
816 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
817 it->second.phase.SetUserLogin(login);
820 else if (user->GetID() != it->second.user->GetID())
822 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
823 it->second.user->GetLogin().c_str(),
824 inet_ntostring(sip).c_str(),
825 user->GetLogin().c_str());
826 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
827 it->second.user->GetLogin().c_str(),
828 inet_ntostring(sip).c_str(),
829 user->GetLogin().c_str());
830 SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
834 IA_USER * iaUser = &(it->second);
836 if (iaUser->password != user->GetProperty().password.Get())
838 const std::string & password = user->GetProperty().password.Get();
839 InitContext(password.c_str(), password.length(), &iaUser->ctx);
840 iaUser->password = user->GetProperty().password.Get();
843 DecryptString(static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
845 char packetName[IA_MAX_TYPE_LEN];
846 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
847 packetName[IA_MAX_TYPE_LEN - 1] = 0;
849 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
850 if (pi == packetTypes.end())
852 SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
853 printfd(__FILE__, "Login or password is wrong!\n");
854 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
856 inet_ntostring(sip).c_str());
861 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
863 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
864 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
865 inet_ntostring(sip).c_str());
866 logger("Login '%s' is already in use from ip %s. IP %s",
868 inet_ntostring(user->GetCurrIP()).c_str(),
869 inet_ntostring(sip).c_str());
870 SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
881 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
883 return Send_CONN_SYN_ACK_6(iaUser, sip);
885 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
887 return Send_CONN_SYN_ACK_7(iaUser, sip);
889 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
891 return Send_CONN_SYN_ACK_8(iaUser, sip);
899 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
901 return Send_ALIVE_SYN_6(iaUser, sip);
903 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
905 return Send_ALIVE_SYN_7(iaUser, sip);
907 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
909 return Send_ALIVE_SYN_8(iaUser, sip);
917 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
919 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
921 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
929 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
931 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
933 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
935 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
937 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
939 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
947 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
949 return Send_FIN_6(iaUser, sip, it);
951 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
953 return Send_FIN_7(iaUser, sip, it);
955 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
957 return Send_FIN_8(iaUser, sip, it);
964 //-----------------------------------------------------------------------------
965 void AUTH_IA::DelUser(USER_PTR u)
968 uint32_t ip = u->GetCurrIP();
973 std::map<uint32_t, IA_USER>::iterator it;
975 STG_LOCKER lock(&mutex);
976 it = ip2user.find(ip);
977 if (it == ip2user.end())
980 printfd(__FILE__, "Nothing to delete\n");
984 if (it->second.user == u)
986 printfd(__FILE__, "User removed!\n");
987 users->Unauthorize(u->GetLogin(), this);
991 //-----------------------------------------------------------------------------
992 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
994 struct sockaddr_in sendAddr;
1001 memset(&err, 0, sizeof(ERR));
1003 sendAddr.sin_family = AF_INET;
1004 sendAddr.sin_port = htons(port);
1005 sendAddr.sin_addr.s_addr = ip;
1008 strncpy((char*)err.type, "ERR", 16);
1009 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1015 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1016 printfd(__FILE__, "SendError %d bytes sent\n", res);
1021 memset(&err8, 0, sizeof(ERR_8));
1023 sendAddr.sin_family = AF_INET;
1024 sendAddr.sin_port = htons(port);
1025 sendAddr.sin_addr.s_addr = ip;
1028 strncpy((char*)err8.type, "ERR", 16);
1029 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1032 SwapBytes(err8.len);
1035 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1036 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1042 //-----------------------------------------------------------------------------
1043 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1045 struct sockaddr_in sendAddr;
1047 sendAddr.sin_family = AF_INET;
1048 sendAddr.sin_port = htons(port);
1049 sendAddr.sin_addr.s_addr = ip;
1051 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1056 //-----------------------------------------------------------------------------
1057 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1059 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1061 std::map<uint32_t, IA_USER>::iterator it;
1063 STG_LOCKER lock(&mutex);
1064 it = ip2user.find(ip);
1065 if (it == ip2user.end())
1067 errorStr = "Unknown user.";
1070 it->second.messagesToSend.push_back(msg);
1073 //-----------------------------------------------------------------------------
1074 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1076 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1079 memset(&info, 0, sizeof(INFO_6));
1082 strncpy((char*)info.type, "INFO", 16);
1083 info.infoType = 'I';
1084 strncpy((char*)info.text, msg.text.c_str(), 235);
1087 size_t len = info.len;
1089 SwapBytes(info.len);
1093 memcpy(buffer, &info, sizeof(INFO_6));
1094 EncryptString(buffer, buffer, len, &user.ctx);
1095 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1097 //-----------------------------------------------------------------------------
1098 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1100 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1103 memset(&info, 0, sizeof(INFO_7));
1106 strncpy((char*)info.type, "INFO_7", 16);
1107 info.infoType = static_cast<int8_t>(msg.header.type);
1108 info.showTime = static_cast<int8_t>(msg.header.showTime);
1109 info.sendTime = msg.header.creationTime;
1111 size_t len = info.len;
1113 SwapBytes(info.len);
1114 SwapBytes(info.sendTime);
1117 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1118 info.text[MAX_MSG_LEN - 1] = 0;
1121 memcpy(buffer, &info, sizeof(INFO_7));
1123 EncryptString(buffer, buffer, len, &user.ctx);
1124 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1126 //-----------------------------------------------------------------------------
1127 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1129 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1132 memset(&info, 0, sizeof(INFO_8));
1135 strncpy((char*)info.type, "INFO_8", 16);
1136 info.infoType = static_cast<int8_t>(msg.header.type);
1137 info.showTime = static_cast<int8_t>(msg.header.showTime);
1138 info.sendTime = msg.header.creationTime;
1140 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1141 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1143 size_t len = info.len;
1145 SwapBytes(info.len);
1146 SwapBytes(info.sendTime);
1150 memcpy(buffer, &info, sizeof(INFO_8));
1152 EncryptString(buffer, buffer, len, &user.ctx);
1153 return Send(ip, user.port, buffer, len);
1155 //-----------------------------------------------------------------------------
1156 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1158 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1161 enabledDirs = 0xFFffFFff;
1163 iaUser->phase.SetPhase2();
1164 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1167 //-----------------------------------------------------------------------------
1168 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1170 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1172 //-----------------------------------------------------------------------------
1173 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1176 SwapBytes(connSyn->dirs);
1178 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1179 enabledDirs = connSyn->dirs;
1182 //-----------------------------------------------------------------------------
1183 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1186 SwapBytes(connAck->len);
1187 SwapBytes(connAck->rnd);
1189 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1191 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1193 iaUser->phase.UpdateTime();
1195 iaUser->lastSendAlive = iaUser->phase.GetTime();
1196 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1198 iaUser->phase.SetPhase3();
1199 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1204 errorStr = iaUser->user->GetStrError();
1205 if (iaSettings.LogProtocolErrors())
1206 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());
1207 iaUser->phase.SetPhase1();
1209 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1213 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1214 if (iaSettings.LogProtocolErrors())
1216 if (iaUser->phase.GetPhase() != 2)
1217 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());
1218 if (connAck->rnd != iaUser->rnd + 1)
1219 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);
1223 //-----------------------------------------------------------------------------
1224 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1226 return Process_CONN_ACK_6(connAck, iaUser, sip);
1228 //-----------------------------------------------------------------------------
1229 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1232 SwapBytes(connAck->len);
1233 SwapBytes(connAck->rnd);
1235 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1237 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1239 iaUser->phase.UpdateTime();
1240 iaUser->lastSendAlive = iaUser->phase.GetTime();
1241 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1243 iaUser->phase.SetPhase3();
1244 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1249 errorStr = iaUser->user->GetStrError();
1250 if (iaSettings.LogProtocolErrors())
1251 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());
1252 iaUser->phase.SetPhase1();
1254 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1258 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1259 if (iaSettings.LogProtocolErrors())
1261 if (iaUser->phase.GetPhase() != 2)
1262 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());
1263 if (connAck->rnd != iaUser->rnd + 1)
1264 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);
1268 //-----------------------------------------------------------------------------
1269 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1272 SwapBytes(aliveAck->len);
1273 SwapBytes(aliveAck->rnd);
1275 printfd(__FILE__, "ALIVE_ACK_6\n");
1276 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1278 iaUser->phase.UpdateTime();
1280 iaUser->aliveSent = false;
1285 //-----------------------------------------------------------------------------
1286 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1288 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1290 //-----------------------------------------------------------------------------
1291 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1294 SwapBytes(aliveAck->len);
1295 SwapBytes(aliveAck->rnd);
1297 printfd(__FILE__, "ALIVE_ACK_8\n");
1298 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1300 iaUser->phase.UpdateTime();
1302 iaUser->aliveSent = false;
1307 //-----------------------------------------------------------------------------
1308 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1310 printfd(__FILE__, "DISCONN_SYN_6\n");
1311 if (iaUser->phase.GetPhase() != 3)
1313 if (iaSettings.LogProtocolErrors())
1314 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());
1315 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1316 errorStr = "Incorrect request DISCONN_SYN";
1320 iaUser->phase.SetPhase4();
1321 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1325 //-----------------------------------------------------------------------------
1326 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1328 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1330 //-----------------------------------------------------------------------------
1331 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1333 if (iaUser->phase.GetPhase() != 3)
1335 if (iaSettings.LogProtocolErrors())
1336 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());
1337 errorStr = "Incorrect request DISCONN_SYN";
1338 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1342 iaUser->phase.SetPhase4();
1343 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1347 //-----------------------------------------------------------------------------
1348 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1351 std::map<uint32_t, IA_USER>::iterator)
1354 SwapBytes(disconnAck->len);
1355 SwapBytes(disconnAck->rnd);
1357 printfd(__FILE__, "DISCONN_ACK_6\n");
1358 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1360 if (iaSettings.LogProtocolErrors())
1362 if (iaUser->phase.GetPhase() != 4)
1363 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());
1364 if (disconnAck->rnd != iaUser->rnd + 1)
1365 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);
1367 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1373 //-----------------------------------------------------------------------------
1374 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)
1376 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1378 //-----------------------------------------------------------------------------
1379 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1382 SwapBytes(disconnAck->len);
1383 SwapBytes(disconnAck->rnd);
1385 printfd(__FILE__, "DISCONN_ACK_8\n");
1386 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1388 if (iaSettings.LogProtocolErrors())
1390 if (iaUser->phase.GetPhase() != 4)
1391 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());
1392 if (disconnAck->rnd != iaUser->rnd + 1)
1393 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);
1395 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1401 //-----------------------------------------------------------------------------
1402 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1404 //+++ Fill static data in connSynAck +++
1405 // TODO Move this code. It must be executed only once
1406 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1407 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1408 for (int j = 0; j < DIR_NUM; j++)
1410 strncpy((char*)connSynAck6.dirName[j],
1411 stgSettings->GetDirName(j).c_str(),
1414 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1416 //--- Fill static data in connSynAck ---
1418 iaUser->rnd = static_cast<uint32_t>(random());
1419 connSynAck6.rnd = iaUser->rnd;
1421 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1422 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1425 SwapBytes(connSynAck6.len);
1426 SwapBytes(connSynAck6.rnd);
1427 SwapBytes(connSynAck6.userTimeOut);
1428 SwapBytes(connSynAck6.aliveDelay);
1431 EncryptString((char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)), &iaUser->ctx);
1432 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1434 //-----------------------------------------------------------------------------
1435 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1437 return Send_CONN_SYN_ACK_6(iaUser, sip);
1439 //-----------------------------------------------------------------------------
1440 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1442 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1443 connSynAck8.hdr.protoVer[0] = 0;
1444 connSynAck8.hdr.protoVer[1] = 8;
1446 //+++ Fill static data in connSynAck +++
1447 // TODO Move this code. It must be executed only once
1448 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1449 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1450 for (int j = 0; j < DIR_NUM; j++)
1452 strncpy((char*)connSynAck8.dirName[j],
1453 stgSettings->GetDirName(j).c_str(),
1456 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1458 //--- Fill static data in connSynAck ---
1460 iaUser->rnd = static_cast<uint32_t>(random());
1461 connSynAck8.rnd = iaUser->rnd;
1463 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1464 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1467 SwapBytes(connSynAck8.len);
1468 SwapBytes(connSynAck8.rnd);
1469 SwapBytes(connSynAck8.userTimeOut);
1470 SwapBytes(connSynAck8.aliveDelay);
1473 EncryptString((char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)), &iaUser->ctx);
1474 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1476 //-----------------------------------------------------------------------------
1477 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1479 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1480 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1482 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1484 for (int i = 0; i < DIR_NUM; i++)
1486 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1487 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1489 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1490 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1494 int dn = iaSettings.GetFreeMbShowType();
1495 const TARIFF * tf = iaUser->user->GetTariff();
1499 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1504 if (std::fabs(p) < 1.0e-3)
1506 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1510 double fmb = iaUser->user->GetProperty().freeMb;
1511 fmb = fmb < 0 ? 0 : fmb;
1512 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1517 if (freeMbNone == iaSettings.GetFreeMbShowType())
1519 aliveSyn6.freeMb[0] = 0;
1523 double fmb = iaUser->user->GetProperty().freeMb;
1524 fmb = fmb < 0 ? 0 : fmb;
1525 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1530 if (iaUser->aliveSent)
1532 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1534 iaUser->aliveSent = true;
1537 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1538 if (!stgSettings->GetShowFeeInCash())
1539 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1542 SwapBytes(aliveSyn6.len);
1543 SwapBytes(aliveSyn6.rnd);
1544 SwapBytes(aliveSyn6.cash);
1545 for (int i = 0; i < DIR_NUM; ++i)
1547 SwapBytes(aliveSyn6.mu[i]);
1548 SwapBytes(aliveSyn6.md[i]);
1549 SwapBytes(aliveSyn6.su[i]);
1550 SwapBytes(aliveSyn6.sd[i]);
1554 EncryptString((char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)), &iaUser->ctx);
1555 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1557 //-----------------------------------------------------------------------------
1558 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1560 return Send_ALIVE_SYN_6(iaUser, sip);
1562 //-----------------------------------------------------------------------------
1563 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1565 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1566 aliveSyn8.hdr.protoVer[0] = 0;
1567 aliveSyn8.hdr.protoVer[1] = 8;
1569 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1570 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1572 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1574 for (int i = 0; i < DIR_NUM; i++)
1576 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1577 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1579 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1580 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1584 int dn = iaSettings.GetFreeMbShowType();
1588 const TARIFF * tf = iaUser->user->GetTariff();
1589 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1594 if (std::fabs(p) < 1.0e-3)
1596 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1600 double fmb = iaUser->user->GetProperty().freeMb;
1601 fmb = fmb < 0 ? 0 : fmb;
1602 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1607 if (freeMbNone == iaSettings.GetFreeMbShowType())
1609 aliveSyn8.freeMb[0] = 0;
1613 double fmb = iaUser->user->GetProperty().freeMb;
1614 fmb = fmb < 0 ? 0 : fmb;
1615 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1620 if (iaUser->aliveSent)
1622 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1624 iaUser->aliveSent = true;
1627 const TARIFF * tf = iaUser->user->GetTariff();
1629 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1630 if (!stgSettings->GetShowFeeInCash())
1631 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1634 SwapBytes(aliveSyn8.len);
1635 SwapBytes(aliveSyn8.rnd);
1636 SwapBytes(aliveSyn8.cash);
1637 SwapBytes(aliveSyn8.status);
1638 for (int i = 0; i < DIR_NUM; ++i)
1640 SwapBytes(aliveSyn8.mu[i]);
1641 SwapBytes(aliveSyn8.md[i]);
1642 SwapBytes(aliveSyn8.su[i]);
1643 SwapBytes(aliveSyn8.sd[i]);
1647 EncryptString((char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)), &iaUser->ctx);
1648 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1650 //-----------------------------------------------------------------------------
1651 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1653 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1654 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1655 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1658 SwapBytes(disconnSynAck6.len);
1659 SwapBytes(disconnSynAck6.rnd);
1662 EncryptString((char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)), &iaUser->ctx);
1663 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1665 //-----------------------------------------------------------------------------
1666 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1668 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1670 //-----------------------------------------------------------------------------
1671 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1673 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1674 disconnSynAck8.hdr.protoVer[0] = 0;
1675 disconnSynAck8.hdr.protoVer[1] = 8;
1677 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1678 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1679 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1682 SwapBytes(disconnSynAck8.len);
1683 SwapBytes(disconnSynAck8.rnd);
1686 EncryptString((char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)), &iaUser->ctx);
1687 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1689 //-----------------------------------------------------------------------------
1690 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1692 fin6.len = Min8(sizeof(FIN_6));
1693 strcpy((char*)fin6.type, "FIN");
1694 strcpy((char*)fin6.ok, "OK");
1697 SwapBytes(fin6.len);
1700 EncryptString((char*)&fin6, (char*)&fin6, Min8(sizeof(fin6)), &iaUser->ctx);
1702 users->Unauthorize(iaUser->login, this);
1704 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1710 //-----------------------------------------------------------------------------
1711 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1713 return Send_FIN_6(iaUser, sip, it);
1715 //-----------------------------------------------------------------------------
1716 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1718 strcpy((char*)fin8.hdr.magic, IA_ID);
1719 fin8.hdr.protoVer[0] = 0;
1720 fin8.hdr.protoVer[1] = 8;
1722 fin8.len = Min8(sizeof(FIN_8));
1723 strcpy((char*)fin8.type, "FIN");
1724 strcpy((char*)fin8.ok, "OK");
1727 SwapBytes(fin8.len);
1730 EncryptString((char*)&fin8, (char*)&fin8, Min8(sizeof(fin8)), &iaUser->ctx);
1732 users->Unauthorize(iaUser->login, this);
1734 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));