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;
59 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
62 extern "C" PLUGIN * GetPlugin();
63 //-----------------------------------------------------------------------------
64 //-----------------------------------------------------------------------------
65 //-----------------------------------------------------------------------------
68 return iac.GetPlugin();
70 //-----------------------------------------------------------------------------
71 //-----------------------------------------------------------------------------
72 //-----------------------------------------------------------------------------
73 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
78 freeMbShowType(freeMbCash),
79 logProtocolErrors(false)
82 //-----------------------------------------------------------------------------
83 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
87 std::vector<PARAM_VALUE>::const_iterator pvi;
88 ///////////////////////////
90 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
91 if (pvi == s.moduleParams.end())
93 errorStr = "Parameter \'Port\' not found.";
94 printfd(__FILE__, "Parameter 'Port' not found\n");
97 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
99 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
100 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
103 port = static_cast<uint16_t>(p);
104 ///////////////////////////
105 pv.param = "UserDelay";
106 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
107 if (pvi == s.moduleParams.end())
109 errorStr = "Parameter \'UserDelay\' not found.";
110 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
114 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
116 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
117 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
120 ///////////////////////////
121 pv.param = "UserTimeout";
122 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
123 if (pvi == s.moduleParams.end())
125 errorStr = "Parameter \'UserTimeout\' not found.";
126 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
130 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
132 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
133 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
136 ///////////////////////////
137 pv.param = "LogProtocolErrors";
138 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
139 if (pvi == s.moduleParams.end())
140 logProtocolErrors = false;
141 else if (ParseYesNo(pvi->value[0], &logProtocolErrors))
143 errorStr = "Cannot parse parameter \'LogProtocolErrors\': " + errorStr;
144 printfd(__FILE__, "Cannot parse parameter 'LogProtocolErrors'\n");
147 /////////////////////////////////////////////////////////////
148 std::string freeMbType;
151 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
152 if (pvi == s.moduleParams.end())
154 errorStr = "Parameter \'FreeMb\' not found.";
155 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
158 freeMbType = pvi->value[0];
160 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
162 freeMbShowType = freeMbCash;
164 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
166 freeMbShowType = freeMbNone;
168 else if (!str2x(freeMbType.c_str(), n))
170 if (n < 0 || n >= DIR_NUM)
172 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
173 printfd(__FILE__, "%s\n", errorStr.c_str());
176 freeMbShowType = (FREEMB)(freeMb0 + n);
180 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
181 printfd(__FILE__, "%s\n", errorStr.c_str());
184 /////////////////////////////////////////////////////////////
187 //-----------------------------------------------------------------------------
188 //-----------------------------------------------------------------------------
189 //-----------------------------------------------------------------------------
190 #ifdef IA_PHASE_DEBUG
196 gettimeofday(&phaseTime, NULL);
203 gettimeofday(&phaseTime, NULL);
206 //-----------------------------------------------------------------------------
207 IA_PHASE::~IA_PHASE()
209 #ifdef IA_PHASE_DEBUG
210 flog = fopen(log.c_str(), "at");
213 fprintf(flog, "IA %s D\n", login.c_str());
218 //-----------------------------------------------------------------------------
219 #ifdef IA_PHASE_DEBUG
220 void IA_PHASE::SetLogFileName(const string & logFileName)
222 log = logFileName + ".ia.log";
224 //-----------------------------------------------------------------------------
225 void IA_PHASE::SetUserLogin(const string & login)
227 IA_PHASE::login = login;
229 //-----------------------------------------------------------------------------
230 void IA_PHASE::WritePhaseChange(int newPhase)
233 gettimeofday(&newPhaseTime, NULL);
234 flog = fopen(log.c_str(), "at");
237 string action = newPhase == phase ? "U" : "C";
238 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
239 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
240 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
250 //-----------------------------------------------------------------------------
251 void IA_PHASE::SetPhase1()
253 #ifdef IA_PHASE_DEBUG
257 gettimeofday(&phaseTime, NULL);
259 //-----------------------------------------------------------------------------
260 void IA_PHASE::SetPhase2()
262 #ifdef IA_PHASE_DEBUG
266 gettimeofday(&phaseTime, NULL);
268 //-----------------------------------------------------------------------------
269 void IA_PHASE::SetPhase3()
271 #ifdef IA_PHASE_DEBUG
275 gettimeofday(&phaseTime, NULL);
277 //-----------------------------------------------------------------------------
278 void IA_PHASE::SetPhase4()
280 #ifdef IA_PHASE_DEBUG
284 gettimeofday(&phaseTime, NULL);
286 //-----------------------------------------------------------------------------
287 int IA_PHASE::GetPhase() const
291 //-----------------------------------------------------------------------------
292 void IA_PHASE::UpdateTime()
294 #ifdef IA_PHASE_DEBUG
295 WritePhaseChange(phase);
297 gettimeofday(&phaseTime, NULL);
299 //-----------------------------------------------------------------------------
300 const UTIME & IA_PHASE::GetTime() const
304 //-----------------------------------------------------------------------------
305 //-----------------------------------------------------------------------------
306 //-----------------------------------------------------------------------------
314 isRunningRunTimeouter(false),
331 enabledDirs(0xFFffFFff),
332 onDelUserNotifier(*this),
333 logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
335 InitContext("pr7Hhen", 7, &ctxS);
337 pthread_mutexattr_t attr;
338 pthread_mutexattr_init(&attr);
339 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
340 pthread_mutex_init(&mutex, &attr);
342 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
343 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
344 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
345 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
346 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
347 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
348 memset(&fin6, 0, sizeof(FIN_6));
349 memset(&fin8, 0, sizeof(FIN_8));
351 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
352 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
353 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
354 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
355 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
356 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
357 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
358 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
359 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
360 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
361 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
362 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
363 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
364 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
365 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
366 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
367 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
368 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
370 packetTypes["CONN_SYN"] = CONN_SYN_N;
371 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
372 packetTypes["CONN_ACK"] = CONN_ACK_N;
373 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
374 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
375 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
376 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
377 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
378 packetTypes["FIN"] = FIN_N;
379 packetTypes["ERR"] = ERROR_N;
381 //-----------------------------------------------------------------------------
384 pthread_mutex_destroy(&mutex);
386 //-----------------------------------------------------------------------------
389 users->AddNotifierUserDel(&onDelUserNotifier);
399 if (pthread_create(&recvThread, NULL, Run, this))
401 errorStr = "Cannot create thread.";
402 printfd(__FILE__, "Cannot create recv thread\n");
403 logger("Cannot create recv thread.");
408 if (!isRunningRunTimeouter)
410 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
412 errorStr = "Cannot create thread.";
413 printfd(__FILE__, "Cannot create timeouter thread\n");
414 logger("Cannot create timeouter thread.");
421 //-----------------------------------------------------------------------------
432 UnauthorizeUser(this)
437 //5 seconds to thread stops itself
438 for (int i = 0; i < 25 && isRunningRun; i++)
440 struct timespec ts = {0, 200000000};
441 nanosleep(&ts, NULL);
447 if (isRunningRunTimeouter)
449 //5 seconds to thread stops itself
450 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
452 struct timespec ts = {0, 200000000};
453 nanosleep(&ts, NULL);
457 users->DelNotifierUserDel(&onDelUserNotifier);
459 if (isRunningRun || isRunningRunTimeouter)
462 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
465 //-----------------------------------------------------------------------------
466 void * AUTH_IA::Run(void * d)
469 sigfillset(&signalSet);
470 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
472 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
474 ia->isRunningRun = true;
478 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
482 ia->RecvData(buffer, sizeof(buffer));
483 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
486 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
487 TouchFile(monFile.c_str());
491 ia->isRunningRun = false;
494 //-----------------------------------------------------------------------------
495 void * AUTH_IA::RunTimeouter(void * d)
498 sigfillset(&signalSet);
499 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
501 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
503 ia->isRunningRunTimeouter = true;
506 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
509 struct timespec ts = {0, 20000000};
510 nanosleep(&ts, NULL);
512 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
513 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
515 TouchFile(monFile.c_str());
519 ia->isRunningRunTimeouter = false;
522 //-----------------------------------------------------------------------------
523 int AUTH_IA::ParseSettings()
525 int ret = iaSettings.ParseSettings(settings);
527 errorStr = iaSettings.GetStrError();
530 //-----------------------------------------------------------------------------
531 int AUTH_IA::PrepareNet()
533 struct sockaddr_in listenAddr;
535 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
537 if (listenSocket < 0)
539 errorStr = "Cannot create socket.";
540 logger("Cannot create a socket: %s", strerror(errno));
544 listenAddr.sin_family = AF_INET;
545 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
546 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
548 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
550 errorStr = "AUTH_IA: Bind failed.";
551 logger("Cannot bind the socket: %s", strerror(errno));
557 //-----------------------------------------------------------------------------
558 int AUTH_IA::FinalizeNet()
563 //-----------------------------------------------------------------------------
564 int AUTH_IA::RecvData(char * buffer, int bufferSize)
566 if (!WaitPackets(listenSocket)) // Timeout
571 struct sockaddr_in outerAddr;
572 socklen_t outerAddrLen(sizeof(outerAddr));
573 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
580 if (dataLen <= 0) // Error
584 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
585 logger("recvfrom error: %s", strerror(errno));
594 uint32_t sip = outerAddr.sin_addr.s_addr;
595 uint16_t sport = htons(outerAddr.sin_port);
598 if (CheckHeader(buffer, sip, &protoVer))
601 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
602 memset(login, 0, PASSWD_LEN);
604 DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS);
607 if (users->FindByName(login, &user))
609 logger("User's connect failed: user '%s' not found. IP %s",
611 inet_ntostring(sip).c_str());
612 printfd(__FILE__, "User '%s' NOT found!\n", login);
613 SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
617 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
619 if (user->GetProperty().disabled.Get())
621 logger("Cannont authorize '%s', user is disabled.", login);
622 SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
626 if (user->GetProperty().passive.Get())
628 logger("Cannont authorize '%s', user is passive.", login);
629 SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
633 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
635 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
636 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
637 logger("User %s. IP address is incorrect. IP %s",
638 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
639 SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
643 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
645 //-----------------------------------------------------------------------------
646 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
648 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
650 printfd(__FILE__, "update needed - IA_ID\n");
651 if (iaSettings.LogProtocolErrors())
652 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
656 if (buffer[6] != 0) //proto[0] shoud be 0
658 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
659 if (iaSettings.LogProtocolErrors())
660 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
667 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
668 if (iaSettings.LogProtocolErrors())
669 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
674 *protoVer = buffer[7];
678 //-----------------------------------------------------------------------------
679 int AUTH_IA::Timeouter()
681 STG_LOCKER lock(&mutex);
683 std::map<uint32_t, IA_USER>::iterator it;
684 it = ip2user.begin();
686 while (it != ip2user.end())
688 uint32_t sip = it->first;
690 static UTIME currTime;
691 gettimeofday(&currTime, NULL);
693 if ((it->second.phase.GetPhase() == 2)
694 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
696 if (iaSettings.LogProtocolErrors())
697 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());
698 it->second.phase.SetPhase1();
699 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
704 if (it->second.phase.GetPhase() == 3)
706 if (!it->second.messagesToSend.empty())
708 if (it->second.protoVer == 6)
709 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
711 if (it->second.protoVer == 7)
712 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
714 if (it->second.protoVer == 8)
715 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
717 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
720 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
722 switch (it->second.protoVer)
725 Send_ALIVE_SYN_6(&(it->second), sip);
728 Send_ALIVE_SYN_7(&(it->second), sip);
731 Send_ALIVE_SYN_8(&(it->second), sip);
735 gettimeofday(&it->second.lastSendAlive, NULL);
738 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
740 if (iaSettings.LogProtocolErrors())
741 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());
742 users->Unauthorize(it->second.user->GetLogin(), this);
748 if ((it->second.phase.GetPhase() == 4)
749 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
751 if (iaSettings.LogProtocolErrors())
752 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());
753 it->second.phase.SetPhase3();
754 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
762 //-----------------------------------------------------------------------------
763 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
765 std::string login(user->GetLogin());
766 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
768 STG_LOCKER lock(&mutex);
769 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
771 if (it == ip2user.end())
774 if (!users->FindByIPIdx(sip, &userPtr))
776 if (userPtr->GetID() != user->GetID())
778 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
779 userPtr->GetLogin().c_str(),
780 inet_ntostring(sip).c_str(),
782 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
783 userPtr->GetLogin().c_str(),
784 inet_ntostring(sip).c_str(),
786 SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
791 printfd(__FILE__, "Add new user '%s' from ip %s\n",
792 login.c_str(), inet_ntostring(sip).c_str());
793 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
794 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
796 #ifdef IA_PHASE_DEBUG
797 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
798 it->second.phase.SetUserLogin(login);
801 else if (user->GetID() != it->second.user->GetID())
803 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
804 it->second.user->GetLogin().c_str(),
805 inet_ntostring(sip).c_str(),
806 user->GetLogin().c_str());
807 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
808 it->second.user->GetLogin().c_str(),
809 inet_ntostring(sip).c_str(),
810 user->GetLogin().c_str());
811 SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
815 IA_USER * iaUser = &(it->second);
817 if (iaUser->password != user->GetProperty().password.Get())
819 const std::string & password = user->GetProperty().password.Get();
820 InitContext(password.c_str(), password.length(), &iaUser->ctx);
821 iaUser->password = user->GetProperty().password.Get();
824 DecryptString(static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
826 char packetName[IA_MAX_TYPE_LEN];
827 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
828 packetName[IA_MAX_TYPE_LEN - 1] = 0;
830 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
831 if (pi == packetTypes.end())
833 SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
834 printfd(__FILE__, "Login or password is wrong!\n");
835 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
837 inet_ntostring(sip).c_str());
842 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
844 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
845 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
846 inet_ntostring(sip).c_str());
847 logger("Login '%s' is already in use from ip %s. IP %s",
849 inet_ntostring(user->GetCurrIP()).c_str(),
850 inet_ntostring(sip).c_str());
851 SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
862 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
864 return Send_CONN_SYN_ACK_6(iaUser, sip);
866 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
868 return Send_CONN_SYN_ACK_7(iaUser, sip);
870 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
872 return Send_CONN_SYN_ACK_8(iaUser, sip);
880 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
882 return Send_ALIVE_SYN_6(iaUser, sip);
884 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
886 return Send_ALIVE_SYN_7(iaUser, sip);
888 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
890 return Send_ALIVE_SYN_8(iaUser, sip);
898 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
900 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
902 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
910 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
912 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
914 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
916 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
918 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
920 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
928 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
930 return Send_FIN_6(iaUser, sip, it);
932 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
934 return Send_FIN_7(iaUser, sip, it);
936 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
938 return Send_FIN_8(iaUser, sip, it);
945 //-----------------------------------------------------------------------------
946 void AUTH_IA::DelUser(USER_PTR u)
949 uint32_t ip = u->GetCurrIP();
954 std::map<uint32_t, IA_USER>::iterator it;
956 STG_LOCKER lock(&mutex);
957 it = ip2user.find(ip);
958 if (it == ip2user.end())
961 printfd(__FILE__, "Nothing to delete\n");
965 if (it->second.user == u)
967 printfd(__FILE__, "User removed!\n");
968 users->Unauthorize(u->GetLogin(), this);
972 //-----------------------------------------------------------------------------
973 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
975 struct sockaddr_in sendAddr;
982 memset(&err, 0, sizeof(ERR));
984 sendAddr.sin_family = AF_INET;
985 sendAddr.sin_port = htons(port);
986 sendAddr.sin_addr.s_addr = ip;
989 strncpy((char*)err.type, "ERR", 16);
990 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
996 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
997 printfd(__FILE__, "SendError %d bytes sent\n", res);
1002 memset(&err8, 0, sizeof(ERR_8));
1004 sendAddr.sin_family = AF_INET;
1005 sendAddr.sin_port = htons(port);
1006 sendAddr.sin_addr.s_addr = ip;
1009 strncpy((char*)err8.type, "ERR", 16);
1010 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1013 SwapBytes(err8.len);
1016 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1017 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1023 //-----------------------------------------------------------------------------
1024 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1026 struct sockaddr_in sendAddr;
1028 sendAddr.sin_family = AF_INET;
1029 sendAddr.sin_port = htons(port);
1030 sendAddr.sin_addr.s_addr = ip;
1032 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1037 //-----------------------------------------------------------------------------
1038 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1040 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1042 std::map<uint32_t, IA_USER>::iterator it;
1044 STG_LOCKER lock(&mutex);
1045 it = ip2user.find(ip);
1046 if (it == ip2user.end())
1048 errorStr = "Unknown user.";
1051 it->second.messagesToSend.push_back(msg);
1054 //-----------------------------------------------------------------------------
1055 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1057 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1060 memset(&info, 0, sizeof(INFO_6));
1063 strncpy((char*)info.type, "INFO", 16);
1064 info.infoType = 'I';
1065 strncpy((char*)info.text, msg.text.c_str(), 235);
1068 size_t len = info.len;
1070 SwapBytes(info.len);
1074 memcpy(buffer, &info, sizeof(INFO_6));
1075 EncryptString(buffer, buffer, len, &user.ctx);
1076 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1078 //-----------------------------------------------------------------------------
1079 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1081 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1084 memset(&info, 0, sizeof(INFO_7));
1087 strncpy((char*)info.type, "INFO_7", 16);
1088 info.infoType = static_cast<int8_t>(msg.header.type);
1089 info.showTime = static_cast<int8_t>(msg.header.showTime);
1090 info.sendTime = msg.header.creationTime;
1092 size_t len = info.len;
1094 SwapBytes(info.len);
1095 SwapBytes(info.sendTime);
1098 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1099 info.text[MAX_MSG_LEN - 1] = 0;
1102 memcpy(buffer, &info, sizeof(INFO_7));
1104 EncryptString(buffer, buffer, len, &user.ctx);
1105 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1107 //-----------------------------------------------------------------------------
1108 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1110 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1113 memset(&info, 0, sizeof(INFO_8));
1116 strncpy((char*)info.type, "INFO_8", 16);
1117 info.infoType = static_cast<int8_t>(msg.header.type);
1118 info.showTime = static_cast<int8_t>(msg.header.showTime);
1119 info.sendTime = msg.header.creationTime;
1121 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1122 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1124 size_t len = info.len;
1126 SwapBytes(info.len);
1127 SwapBytes(info.sendTime);
1131 memcpy(buffer, &info, sizeof(INFO_8));
1133 EncryptString(buffer, buffer, len, &user.ctx);
1134 return Send(ip, user.port, buffer, len);
1136 //-----------------------------------------------------------------------------
1137 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1139 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1142 enabledDirs = 0xFFffFFff;
1144 iaUser->phase.SetPhase2();
1145 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1148 //-----------------------------------------------------------------------------
1149 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1151 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1153 //-----------------------------------------------------------------------------
1154 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1157 SwapBytes(connSyn->dirs);
1159 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1160 enabledDirs = connSyn->dirs;
1163 //-----------------------------------------------------------------------------
1164 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1167 SwapBytes(connAck->len);
1168 SwapBytes(connAck->rnd);
1170 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1172 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1174 iaUser->phase.UpdateTime();
1176 iaUser->lastSendAlive = iaUser->phase.GetTime();
1177 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1179 iaUser->phase.SetPhase3();
1180 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1185 errorStr = iaUser->user->GetStrError();
1186 if (iaSettings.LogProtocolErrors())
1187 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());
1188 iaUser->phase.SetPhase1();
1190 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1194 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1195 if (iaSettings.LogProtocolErrors())
1197 if (iaUser->phase.GetPhase() != 2)
1198 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());
1199 if (connAck->rnd != iaUser->rnd + 1)
1200 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);
1204 //-----------------------------------------------------------------------------
1205 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1207 return Process_CONN_ACK_6(connAck, iaUser, sip);
1209 //-----------------------------------------------------------------------------
1210 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1213 SwapBytes(connAck->len);
1214 SwapBytes(connAck->rnd);
1216 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1218 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1220 iaUser->phase.UpdateTime();
1221 iaUser->lastSendAlive = iaUser->phase.GetTime();
1222 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1224 iaUser->phase.SetPhase3();
1225 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1230 errorStr = iaUser->user->GetStrError();
1231 if (iaSettings.LogProtocolErrors())
1232 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());
1233 iaUser->phase.SetPhase1();
1235 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1239 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1240 if (iaSettings.LogProtocolErrors())
1242 if (iaUser->phase.GetPhase() != 2)
1243 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());
1244 if (connAck->rnd != iaUser->rnd + 1)
1245 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);
1249 //-----------------------------------------------------------------------------
1250 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1253 SwapBytes(aliveAck->len);
1254 SwapBytes(aliveAck->rnd);
1256 printfd(__FILE__, "ALIVE_ACK_6\n");
1257 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1259 iaUser->phase.UpdateTime();
1261 iaUser->aliveSent = false;
1266 //-----------------------------------------------------------------------------
1267 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1269 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1271 //-----------------------------------------------------------------------------
1272 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1275 SwapBytes(aliveAck->len);
1276 SwapBytes(aliveAck->rnd);
1278 printfd(__FILE__, "ALIVE_ACK_8\n");
1279 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1281 iaUser->phase.UpdateTime();
1283 iaUser->aliveSent = false;
1288 //-----------------------------------------------------------------------------
1289 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1291 printfd(__FILE__, "DISCONN_SYN_6\n");
1292 if (iaUser->phase.GetPhase() != 3)
1294 if (iaSettings.LogProtocolErrors())
1295 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_SYN: invalid phase, expected 3, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1296 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1297 errorStr = "Incorrect request DISCONN_SYN";
1301 iaUser->phase.SetPhase4();
1302 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1306 //-----------------------------------------------------------------------------
1307 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1309 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1311 //-----------------------------------------------------------------------------
1312 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1314 if (iaUser->phase.GetPhase() != 3)
1316 if (iaSettings.LogProtocolErrors())
1317 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());
1318 errorStr = "Incorrect request DISCONN_SYN";
1319 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1323 iaUser->phase.SetPhase4();
1324 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1328 //-----------------------------------------------------------------------------
1329 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1332 std::map<uint32_t, IA_USER>::iterator)
1335 SwapBytes(disconnAck->len);
1336 SwapBytes(disconnAck->rnd);
1338 printfd(__FILE__, "DISCONN_ACK_6\n");
1339 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1341 if (iaSettings.LogProtocolErrors())
1343 if (iaUser->phase.GetPhase() != 4)
1344 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());
1345 if (disconnAck->rnd != iaUser->rnd + 1)
1346 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);
1348 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1354 //-----------------------------------------------------------------------------
1355 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)
1357 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1359 //-----------------------------------------------------------------------------
1360 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1363 SwapBytes(disconnAck->len);
1364 SwapBytes(disconnAck->rnd);
1366 printfd(__FILE__, "DISCONN_ACK_8\n");
1367 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1369 if (iaSettings.LogProtocolErrors())
1371 if (iaUser->phase.GetPhase() != 4)
1372 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());
1373 if (disconnAck->rnd != iaUser->rnd + 1)
1374 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);
1376 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1382 //-----------------------------------------------------------------------------
1383 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1385 //+++ Fill static data in connSynAck +++
1386 // TODO Move this code. It must be executed only once
1387 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1388 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1389 for (int j = 0; j < DIR_NUM; j++)
1391 strncpy((char*)connSynAck6.dirName[j],
1392 stgSettings->GetDirName(j).c_str(),
1395 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1397 //--- Fill static data in connSynAck ---
1399 iaUser->rnd = static_cast<uint32_t>(random());
1400 connSynAck6.rnd = iaUser->rnd;
1402 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1403 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1406 SwapBytes(connSynAck6.len);
1407 SwapBytes(connSynAck6.rnd);
1408 SwapBytes(connSynAck6.userTimeOut);
1409 SwapBytes(connSynAck6.aliveDelay);
1412 EncryptString((char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)), &iaUser->ctx);
1413 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1415 //-----------------------------------------------------------------------------
1416 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1418 return Send_CONN_SYN_ACK_6(iaUser, sip);
1420 //-----------------------------------------------------------------------------
1421 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1423 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1424 connSynAck8.hdr.protoVer[0] = 0;
1425 connSynAck8.hdr.protoVer[1] = 8;
1427 //+++ Fill static data in connSynAck +++
1428 // TODO Move this code. It must be executed only once
1429 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1430 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1431 for (int j = 0; j < DIR_NUM; j++)
1433 strncpy((char*)connSynAck8.dirName[j],
1434 stgSettings->GetDirName(j).c_str(),
1437 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1439 //--- Fill static data in connSynAck ---
1441 iaUser->rnd = static_cast<uint32_t>(random());
1442 connSynAck8.rnd = iaUser->rnd;
1444 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1445 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1448 SwapBytes(connSynAck8.len);
1449 SwapBytes(connSynAck8.rnd);
1450 SwapBytes(connSynAck8.userTimeOut);
1451 SwapBytes(connSynAck8.aliveDelay);
1454 EncryptString((char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)), &iaUser->ctx);
1455 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1457 //-----------------------------------------------------------------------------
1458 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1460 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1461 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1463 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1465 for (int i = 0; i < DIR_NUM; i++)
1467 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1468 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1470 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1471 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1475 int dn = iaSettings.GetFreeMbShowType();
1476 const TARIFF * tf = iaUser->user->GetTariff();
1480 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1485 if (std::fabs(p) < 1.0e-3)
1487 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1491 double fmb = iaUser->user->GetProperty().freeMb;
1492 fmb = fmb < 0 ? 0 : fmb;
1493 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1498 if (freeMbNone == iaSettings.GetFreeMbShowType())
1500 aliveSyn6.freeMb[0] = 0;
1504 double fmb = iaUser->user->GetProperty().freeMb;
1505 fmb = fmb < 0 ? 0 : fmb;
1506 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1511 if (iaUser->aliveSent)
1513 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1515 iaUser->aliveSent = true;
1518 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1519 if (!stgSettings->GetShowFeeInCash())
1520 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1523 SwapBytes(aliveSyn6.len);
1524 SwapBytes(aliveSyn6.rnd);
1525 SwapBytes(aliveSyn6.cash);
1526 for (int i = 0; i < DIR_NUM; ++i)
1528 SwapBytes(aliveSyn6.mu[i]);
1529 SwapBytes(aliveSyn6.md[i]);
1530 SwapBytes(aliveSyn6.su[i]);
1531 SwapBytes(aliveSyn6.sd[i]);
1535 EncryptString((char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)), &iaUser->ctx);
1536 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1538 //-----------------------------------------------------------------------------
1539 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1541 return Send_ALIVE_SYN_6(iaUser, sip);
1543 //-----------------------------------------------------------------------------
1544 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1546 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1547 aliveSyn8.hdr.protoVer[0] = 0;
1548 aliveSyn8.hdr.protoVer[1] = 8;
1550 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1551 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1553 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1555 for (int i = 0; i < DIR_NUM; i++)
1557 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1558 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1560 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1561 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1565 int dn = iaSettings.GetFreeMbShowType();
1569 const TARIFF * tf = iaUser->user->GetTariff();
1570 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1575 if (std::fabs(p) < 1.0e-3)
1577 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1581 double fmb = iaUser->user->GetProperty().freeMb;
1582 fmb = fmb < 0 ? 0 : fmb;
1583 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1588 if (freeMbNone == iaSettings.GetFreeMbShowType())
1590 aliveSyn8.freeMb[0] = 0;
1594 double fmb = iaUser->user->GetProperty().freeMb;
1595 fmb = fmb < 0 ? 0 : fmb;
1596 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1601 if (iaUser->aliveSent)
1603 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1605 iaUser->aliveSent = true;
1608 const TARIFF * tf = iaUser->user->GetTariff();
1610 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1611 if (!stgSettings->GetShowFeeInCash())
1612 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1615 SwapBytes(aliveSyn8.len);
1616 SwapBytes(aliveSyn8.rnd);
1617 SwapBytes(aliveSyn8.cash);
1618 SwapBytes(aliveSyn8.status);
1619 for (int i = 0; i < DIR_NUM; ++i)
1621 SwapBytes(aliveSyn8.mu[i]);
1622 SwapBytes(aliveSyn8.md[i]);
1623 SwapBytes(aliveSyn8.su[i]);
1624 SwapBytes(aliveSyn8.sd[i]);
1628 EncryptString((char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)), &iaUser->ctx);
1629 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1631 //-----------------------------------------------------------------------------
1632 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1634 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1635 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1636 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1639 SwapBytes(disconnSynAck6.len);
1640 SwapBytes(disconnSynAck6.rnd);
1643 EncryptString((char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)), &iaUser->ctx);
1644 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1646 //-----------------------------------------------------------------------------
1647 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1649 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1651 //-----------------------------------------------------------------------------
1652 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1654 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1655 disconnSynAck8.hdr.protoVer[0] = 0;
1656 disconnSynAck8.hdr.protoVer[1] = 8;
1658 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1659 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1660 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1663 SwapBytes(disconnSynAck8.len);
1664 SwapBytes(disconnSynAck8.rnd);
1667 EncryptString((char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)), &iaUser->ctx);
1668 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1670 //-----------------------------------------------------------------------------
1671 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1673 fin6.len = Min8(sizeof(FIN_6));
1674 strcpy((char*)fin6.type, "FIN");
1675 strcpy((char*)fin6.ok, "OK");
1678 SwapBytes(fin6.len);
1681 EncryptString((char*)&fin6, (char*)&fin6, Min8(sizeof(fin6)), &iaUser->ctx);
1683 users->Unauthorize(iaUser->login, this);
1685 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1691 //-----------------------------------------------------------------------------
1692 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1694 return Send_FIN_6(iaUser, sip, it);
1696 //-----------------------------------------------------------------------------
1697 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1699 strcpy((char*)fin8.hdr.magic, IA_ID);
1700 fin8.hdr.protoVer[0] = 0;
1701 fin8.hdr.protoVer[1] = 8;
1703 fin8.len = Min8(sizeof(FIN_8));
1704 strcpy((char*)fin8.type, "FIN");
1705 strcpy((char*)fin8.ok, "OK");
1708 SwapBytes(fin8.len);
1711 EncryptString((char*)&fin8, (char*)&fin8, Min8(sizeof(fin8)), &iaUser->ctx);
1713 users->Unauthorize(iaUser->login, this);
1715 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1723 //-----------------------------------------------------------------------------
1725 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
1727 unsigned char keyL[PASSWD_LEN];
1728 memset(keyL, 0, PASSWD_LEN);
1729 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1730 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1732 //-----------------------------------------------------------------------------