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);
60 void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8);
61 void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8);
64 extern "C" PLUGIN * GetPlugin();
65 //-----------------------------------------------------------------------------
66 //-----------------------------------------------------------------------------
67 //-----------------------------------------------------------------------------
70 return iac.GetPlugin();
72 //-----------------------------------------------------------------------------
73 //-----------------------------------------------------------------------------
74 //-----------------------------------------------------------------------------
75 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
80 freeMbShowType(freeMbCash),
81 logProtocolErrors(false)
84 //-----------------------------------------------------------------------------
85 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
89 std::vector<PARAM_VALUE>::const_iterator pvi;
90 ///////////////////////////
92 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
93 if (pvi == s.moduleParams.end())
95 errorStr = "Parameter \'Port\' not found.";
96 printfd(__FILE__, "Parameter 'Port' not found\n");
99 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
101 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
102 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
105 port = static_cast<uint16_t>(p);
106 ///////////////////////////
107 pv.param = "UserDelay";
108 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
109 if (pvi == s.moduleParams.end())
111 errorStr = "Parameter \'UserDelay\' not found.";
112 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
116 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
118 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
119 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
122 ///////////////////////////
123 pv.param = "UserTimeout";
124 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
125 if (pvi == s.moduleParams.end())
127 errorStr = "Parameter \'UserTimeout\' not found.";
128 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
132 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
134 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
135 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
138 ///////////////////////////
139 pv.param = "LogProtocolErrors";
140 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
141 if (pvi == s.moduleParams.end())
142 logProtocolErrors = false;
143 else if (ParseYesNo(pvi->value[0], &logProtocolErrors))
145 errorStr = "Cannot parse parameter \'LogProtocolErrors\': " + errorStr;
146 printfd(__FILE__, "Cannot parse parameter 'LogProtocolErrors'\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 InitEncrypt(&ctxS, "pr7Hhen");
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::PrepareNet()
535 struct sockaddr_in listenAddr;
537 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
539 if (listenSocket < 0)
541 errorStr = "Cannot create socket.";
542 logger("Cannot create a socket: %s", strerror(errno));
546 listenAddr.sin_family = AF_INET;
547 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
548 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
550 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
552 errorStr = "AUTH_IA: Bind failed.";
553 logger("Cannot bind the socket: %s", strerror(errno));
559 //-----------------------------------------------------------------------------
560 int AUTH_IA::FinalizeNet()
565 //-----------------------------------------------------------------------------
566 int AUTH_IA::RecvData(char * buffer, int bufferSize)
568 if (!WaitPackets(listenSocket)) // Timeout
573 struct sockaddr_in outerAddr;
574 socklen_t outerAddrLen(sizeof(outerAddr));
575 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
582 if (dataLen <= 0) // Error
586 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
587 logger("recvfrom error: %s", strerror(errno));
596 uint32_t sip = outerAddr.sin_addr.s_addr;
597 uint16_t sport = htons(outerAddr.sin_port);
600 if (CheckHeader(buffer, sip, &protoVer))
603 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
604 memset(login, 0, PASSWD_LEN);
606 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
609 if (users->FindByName(login, &user))
611 logger("User's connect failed: user '%s' not found. IP %s",
613 inet_ntostring(sip).c_str());
614 printfd(__FILE__, "User '%s' NOT found!\n", login);
615 SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
619 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
621 if (user->GetProperty().disabled.Get())
623 logger("Cannont authorize '%s', user is disabled.", login);
624 SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
628 if (user->GetProperty().passive.Get())
630 logger("Cannont authorize '%s', user is passive.", login);
631 SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
635 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
637 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
638 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
639 logger("User %s. IP address is incorrect. IP %s",
640 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
641 SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
645 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
647 //-----------------------------------------------------------------------------
648 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
650 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
652 printfd(__FILE__, "update needed - IA_ID\n");
653 if (iaSettings.LogProtocolErrors())
654 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
658 if (buffer[6] != 0) //proto[0] shoud be 0
660 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
661 if (iaSettings.LogProtocolErrors())
662 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
669 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
670 if (iaSettings.LogProtocolErrors())
671 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
676 *protoVer = buffer[7];
680 //-----------------------------------------------------------------------------
681 int AUTH_IA::Timeouter()
683 STG_LOCKER lock(&mutex);
685 std::map<uint32_t, IA_USER>::iterator it;
686 it = ip2user.begin();
688 while (it != ip2user.end())
690 uint32_t sip = it->first;
692 static UTIME currTime;
693 gettimeofday(&currTime, NULL);
695 if ((it->second.phase.GetPhase() == 2)
696 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
698 if (iaSettings.LogProtocolErrors())
699 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());
700 it->second.phase.SetPhase1();
701 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
706 if (it->second.phase.GetPhase() == 3)
708 if (!it->second.messagesToSend.empty())
710 if (it->second.protoVer == 6)
711 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
713 if (it->second.protoVer == 7)
714 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
716 if (it->second.protoVer == 8)
717 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
719 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
722 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
724 switch (it->second.protoVer)
727 Send_ALIVE_SYN_6(&(it->second), sip);
730 Send_ALIVE_SYN_7(&(it->second), sip);
733 Send_ALIVE_SYN_8(&(it->second), sip);
737 gettimeofday(&it->second.lastSendAlive, NULL);
740 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
742 if (iaSettings.LogProtocolErrors())
743 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());
744 users->Unauthorize(it->second.user->GetLogin(), this);
750 if ((it->second.phase.GetPhase() == 4)
751 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
753 if (iaSettings.LogProtocolErrors())
754 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());
755 it->second.phase.SetPhase3();
756 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
764 //-----------------------------------------------------------------------------
765 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
767 std::string login(user->GetLogin());
768 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
770 STG_LOCKER lock(&mutex);
771 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
773 if (it == ip2user.end())
776 if (!users->FindByIPIdx(sip, &userPtr))
778 if (userPtr->GetID() != user->GetID())
780 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
781 userPtr->GetLogin().c_str(),
782 inet_ntostring(sip).c_str(),
784 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
785 userPtr->GetLogin().c_str(),
786 inet_ntostring(sip).c_str(),
788 SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
793 printfd(__FILE__, "Add new user '%s' from ip %s\n",
794 login.c_str(), inet_ntostring(sip).c_str());
795 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
796 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
798 #ifdef IA_PHASE_DEBUG
799 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
800 it->second.phase.SetUserLogin(login);
803 else if (user->GetID() != it->second.user->GetID())
805 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
806 it->second.user->GetLogin().c_str(),
807 inet_ntostring(sip).c_str(),
808 user->GetLogin().c_str());
809 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
810 it->second.user->GetLogin().c_str(),
811 inet_ntostring(sip).c_str(),
812 user->GetLogin().c_str());
813 SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
817 IA_USER * iaUser = &(it->second);
819 if (iaUser->password != user->GetProperty().password.Get())
821 InitEncrypt(&iaUser->ctx, user->GetProperty().password.Get());
822 iaUser->password = user->GetProperty().password.Get();
825 Decrypt(&iaUser->ctx, static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset) / 8);
827 char packetName[IA_MAX_TYPE_LEN];
828 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
829 packetName[IA_MAX_TYPE_LEN - 1] = 0;
831 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
832 if (pi == packetTypes.end())
834 SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
835 printfd(__FILE__, "Login or password is wrong!\n");
836 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
838 inet_ntostring(sip).c_str());
843 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
845 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
846 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
847 inet_ntostring(sip).c_str());
848 logger("Login '%s' is already in use from ip %s. IP %s",
850 inet_ntostring(user->GetCurrIP()).c_str(),
851 inet_ntostring(sip).c_str());
852 SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
863 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
865 return Send_CONN_SYN_ACK_6(iaUser, sip);
867 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
869 return Send_CONN_SYN_ACK_7(iaUser, sip);
871 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
873 return Send_CONN_SYN_ACK_8(iaUser, sip);
881 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
883 return Send_ALIVE_SYN_6(iaUser, sip);
885 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
887 return Send_ALIVE_SYN_7(iaUser, sip);
889 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
891 return Send_ALIVE_SYN_8(iaUser, sip);
899 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
901 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
903 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
911 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
913 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
915 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
917 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
919 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
921 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
929 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
931 return Send_FIN_6(iaUser, sip, it);
933 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
935 return Send_FIN_7(iaUser, sip, it);
937 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
939 return Send_FIN_8(iaUser, sip, it);
946 //-----------------------------------------------------------------------------
947 void AUTH_IA::DelUser(USER_PTR u)
950 uint32_t ip = u->GetCurrIP();
955 std::map<uint32_t, IA_USER>::iterator it;
957 STG_LOCKER lock(&mutex);
958 it = ip2user.find(ip);
959 if (it == ip2user.end())
962 printfd(__FILE__, "Nothing to delete\n");
966 if (it->second.user == u)
968 printfd(__FILE__, "User removed!\n");
969 users->Unauthorize(u->GetLogin(), this);
973 //-----------------------------------------------------------------------------
974 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
976 struct sockaddr_in sendAddr;
983 memset(&err, 0, sizeof(ERR));
985 sendAddr.sin_family = AF_INET;
986 sendAddr.sin_port = htons(port);
987 sendAddr.sin_addr.s_addr = ip;
990 strncpy((char*)err.type, "ERR", 16);
991 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
997 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
998 printfd(__FILE__, "SendError %d bytes sent\n", res);
1003 memset(&err8, 0, sizeof(ERR_8));
1005 sendAddr.sin_family = AF_INET;
1006 sendAddr.sin_port = htons(port);
1007 sendAddr.sin_addr.s_addr = ip;
1010 strncpy((char*)err8.type, "ERR", 16);
1011 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1014 SwapBytes(err8.len);
1017 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1018 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1024 //-----------------------------------------------------------------------------
1025 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1027 struct sockaddr_in sendAddr;
1029 sendAddr.sin_family = AF_INET;
1030 sendAddr.sin_port = htons(port);
1031 sendAddr.sin_addr.s_addr = ip;
1033 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1038 //-----------------------------------------------------------------------------
1039 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1041 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1043 std::map<uint32_t, IA_USER>::iterator it;
1045 STG_LOCKER lock(&mutex);
1046 it = ip2user.find(ip);
1047 if (it == ip2user.end())
1049 errorStr = "Unknown user.";
1052 it->second.messagesToSend.push_back(msg);
1055 //-----------------------------------------------------------------------------
1056 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1058 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1061 memset(&info, 0, sizeof(INFO_6));
1064 strncpy((char*)info.type, "INFO", 16);
1065 info.infoType = 'I';
1066 strncpy((char*)info.text, msg.text.c_str(), 235);
1069 size_t len = info.len;
1071 SwapBytes(info.len);
1075 memcpy(buffer, &info, sizeof(INFO_6));
1076 Encrypt(&user.ctx, buffer, buffer, len / 8);
1077 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1079 //-----------------------------------------------------------------------------
1080 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1082 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1085 memset(&info, 0, sizeof(INFO_7));
1088 strncpy((char*)info.type, "INFO_7", 16);
1089 info.infoType = static_cast<int8_t>(msg.header.type);
1090 info.showTime = static_cast<int8_t>(msg.header.showTime);
1091 info.sendTime = msg.header.creationTime;
1093 size_t len = info.len;
1095 SwapBytes(info.len);
1096 SwapBytes(info.sendTime);
1099 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1100 info.text[MAX_MSG_LEN - 1] = 0;
1103 memcpy(buffer, &info, sizeof(INFO_7));
1105 Encrypt(&user.ctx, buffer, buffer, len / 8);
1106 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1108 //-----------------------------------------------------------------------------
1109 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1111 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1114 memset(&info, 0, sizeof(INFO_8));
1117 strncpy((char*)info.type, "INFO_8", 16);
1118 info.infoType = static_cast<int8_t>(msg.header.type);
1119 info.showTime = static_cast<int8_t>(msg.header.showTime);
1120 info.sendTime = msg.header.creationTime;
1122 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1123 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1125 size_t len = info.len;
1127 SwapBytes(info.len);
1128 SwapBytes(info.sendTime);
1132 memcpy(buffer, &info, sizeof(INFO_8));
1134 Encrypt(&user.ctx, buffer, buffer, len / 8);
1135 return Send(ip, user.port, buffer, len);
1137 //-----------------------------------------------------------------------------
1138 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1140 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1143 enabledDirs = 0xFFffFFff;
1145 iaUser->phase.SetPhase2();
1146 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1149 //-----------------------------------------------------------------------------
1150 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1152 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1154 //-----------------------------------------------------------------------------
1155 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1158 SwapBytes(connSyn->dirs);
1160 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1161 enabledDirs = connSyn->dirs;
1164 //-----------------------------------------------------------------------------
1165 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1168 SwapBytes(connAck->len);
1169 SwapBytes(connAck->rnd);
1171 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1173 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1175 iaUser->phase.UpdateTime();
1177 iaUser->lastSendAlive = iaUser->phase.GetTime();
1178 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1180 iaUser->phase.SetPhase3();
1181 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1186 errorStr = iaUser->user->GetStrError();
1187 if (iaSettings.LogProtocolErrors())
1188 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());
1189 iaUser->phase.SetPhase1();
1191 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1195 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1196 if (iaSettings.LogProtocolErrors())
1198 if (iaUser->phase.GetPhase() != 2)
1199 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());
1200 if (connAck->rnd != iaUser->rnd + 1)
1201 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);
1205 //-----------------------------------------------------------------------------
1206 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1208 return Process_CONN_ACK_6(connAck, iaUser, sip);
1210 //-----------------------------------------------------------------------------
1211 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1214 SwapBytes(connAck->len);
1215 SwapBytes(connAck->rnd);
1217 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1219 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1221 iaUser->phase.UpdateTime();
1222 iaUser->lastSendAlive = iaUser->phase.GetTime();
1223 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1225 iaUser->phase.SetPhase3();
1226 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1231 errorStr = iaUser->user->GetStrError();
1232 if (iaSettings.LogProtocolErrors())
1233 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());
1234 iaUser->phase.SetPhase1();
1236 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1240 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1241 if (iaSettings.LogProtocolErrors())
1243 if (iaUser->phase.GetPhase() != 2)
1244 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());
1245 if (connAck->rnd != iaUser->rnd + 1)
1246 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);
1250 //-----------------------------------------------------------------------------
1251 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1254 SwapBytes(aliveAck->len);
1255 SwapBytes(aliveAck->rnd);
1257 printfd(__FILE__, "ALIVE_ACK_6\n");
1258 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1260 iaUser->phase.UpdateTime();
1262 iaUser->aliveSent = false;
1267 //-----------------------------------------------------------------------------
1268 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1270 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1272 //-----------------------------------------------------------------------------
1273 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1276 SwapBytes(aliveAck->len);
1277 SwapBytes(aliveAck->rnd);
1279 printfd(__FILE__, "ALIVE_ACK_8\n");
1280 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1282 iaUser->phase.UpdateTime();
1284 iaUser->aliveSent = false;
1289 //-----------------------------------------------------------------------------
1290 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1292 printfd(__FILE__, "DISCONN_SYN_6\n");
1293 if (iaUser->phase.GetPhase() != 3)
1295 if (iaSettings.LogProtocolErrors())
1296 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());
1297 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1298 errorStr = "Incorrect request DISCONN_SYN";
1302 iaUser->phase.SetPhase4();
1303 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1307 //-----------------------------------------------------------------------------
1308 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1310 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1312 //-----------------------------------------------------------------------------
1313 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1315 if (iaUser->phase.GetPhase() != 3)
1317 if (iaSettings.LogProtocolErrors())
1318 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());
1319 errorStr = "Incorrect request DISCONN_SYN";
1320 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1324 iaUser->phase.SetPhase4();
1325 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1329 //-----------------------------------------------------------------------------
1330 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1333 std::map<uint32_t, IA_USER>::iterator)
1336 SwapBytes(disconnAck->len);
1337 SwapBytes(disconnAck->rnd);
1339 printfd(__FILE__, "DISCONN_ACK_6\n");
1340 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1342 if (iaSettings.LogProtocolErrors())
1344 if (iaUser->phase.GetPhase() != 4)
1345 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());
1346 if (disconnAck->rnd != iaUser->rnd + 1)
1347 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);
1349 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1355 //-----------------------------------------------------------------------------
1356 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)
1358 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1360 //-----------------------------------------------------------------------------
1361 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1364 SwapBytes(disconnAck->len);
1365 SwapBytes(disconnAck->rnd);
1367 printfd(__FILE__, "DISCONN_ACK_8\n");
1368 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1370 if (iaSettings.LogProtocolErrors())
1372 if (iaUser->phase.GetPhase() != 4)
1373 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());
1374 if (disconnAck->rnd != iaUser->rnd + 1)
1375 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);
1377 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1383 //-----------------------------------------------------------------------------
1384 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1386 //+++ Fill static data in connSynAck +++
1387 // TODO Move this code. It must be executed only once
1388 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1389 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1390 for (int j = 0; j < DIR_NUM; j++)
1392 strncpy((char*)connSynAck6.dirName[j],
1393 stgSettings->GetDirName(j).c_str(),
1396 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1398 //--- Fill static data in connSynAck ---
1400 iaUser->rnd = static_cast<uint32_t>(random());
1401 connSynAck6.rnd = iaUser->rnd;
1403 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1404 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1407 SwapBytes(connSynAck6.len);
1408 SwapBytes(connSynAck6.rnd);
1409 SwapBytes(connSynAck6.userTimeOut);
1410 SwapBytes(connSynAck6.aliveDelay);
1413 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1414 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1416 //-----------------------------------------------------------------------------
1417 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1419 return Send_CONN_SYN_ACK_6(iaUser, sip);
1421 //-----------------------------------------------------------------------------
1422 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1424 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1425 connSynAck8.hdr.protoVer[0] = 0;
1426 connSynAck8.hdr.protoVer[1] = 8;
1428 //+++ Fill static data in connSynAck +++
1429 // TODO Move this code. It must be executed only once
1430 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1431 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1432 for (int j = 0; j < DIR_NUM; j++)
1434 strncpy((char*)connSynAck8.dirName[j],
1435 stgSettings->GetDirName(j).c_str(),
1438 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1440 //--- Fill static data in connSynAck ---
1442 iaUser->rnd = static_cast<uint32_t>(random());
1443 connSynAck8.rnd = iaUser->rnd;
1445 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1446 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1449 SwapBytes(connSynAck8.len);
1450 SwapBytes(connSynAck8.rnd);
1451 SwapBytes(connSynAck8.userTimeOut);
1452 SwapBytes(connSynAck8.aliveDelay);
1455 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1456 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1458 //-----------------------------------------------------------------------------
1459 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1461 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1462 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1464 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1466 for (int i = 0; i < DIR_NUM; i++)
1468 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1469 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1471 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1472 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1476 int dn = iaSettings.GetFreeMbShowType();
1477 const TARIFF * tf = iaUser->user->GetTariff();
1481 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1486 if (std::fabs(p) < 1.0e-3)
1488 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1492 double fmb = iaUser->user->GetProperty().freeMb;
1493 fmb = fmb < 0 ? 0 : fmb;
1494 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1499 if (freeMbNone == iaSettings.GetFreeMbShowType())
1501 aliveSyn6.freeMb[0] = 0;
1505 double fmb = iaUser->user->GetProperty().freeMb;
1506 fmb = fmb < 0 ? 0 : fmb;
1507 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1512 if (iaUser->aliveSent)
1514 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1516 iaUser->aliveSent = true;
1519 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1520 if (!stgSettings->GetShowFeeInCash())
1521 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1524 SwapBytes(aliveSyn6.len);
1525 SwapBytes(aliveSyn6.rnd);
1526 SwapBytes(aliveSyn6.cash);
1527 for (int i = 0; i < DIR_NUM; ++i)
1529 SwapBytes(aliveSyn6.mu[i]);
1530 SwapBytes(aliveSyn6.md[i]);
1531 SwapBytes(aliveSyn6.su[i]);
1532 SwapBytes(aliveSyn6.sd[i]);
1536 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1537 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1539 //-----------------------------------------------------------------------------
1540 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1542 return Send_ALIVE_SYN_6(iaUser, sip);
1544 //-----------------------------------------------------------------------------
1545 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1547 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1548 aliveSyn8.hdr.protoVer[0] = 0;
1549 aliveSyn8.hdr.protoVer[1] = 8;
1551 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1552 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1554 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1556 for (int i = 0; i < DIR_NUM; i++)
1558 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1559 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1561 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1562 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1566 int dn = iaSettings.GetFreeMbShowType();
1570 const TARIFF * tf = iaUser->user->GetTariff();
1571 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1576 if (std::fabs(p) < 1.0e-3)
1578 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1582 double fmb = iaUser->user->GetProperty().freeMb;
1583 fmb = fmb < 0 ? 0 : fmb;
1584 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1589 if (freeMbNone == iaSettings.GetFreeMbShowType())
1591 aliveSyn8.freeMb[0] = 0;
1595 double fmb = iaUser->user->GetProperty().freeMb;
1596 fmb = fmb < 0 ? 0 : fmb;
1597 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1602 if (iaUser->aliveSent)
1604 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1606 iaUser->aliveSent = true;
1609 const TARIFF * tf = iaUser->user->GetTariff();
1611 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1612 if (!stgSettings->GetShowFeeInCash())
1613 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1616 SwapBytes(aliveSyn8.len);
1617 SwapBytes(aliveSyn8.rnd);
1618 SwapBytes(aliveSyn8.cash);
1619 SwapBytes(aliveSyn8.status);
1620 for (int i = 0; i < DIR_NUM; ++i)
1622 SwapBytes(aliveSyn8.mu[i]);
1623 SwapBytes(aliveSyn8.md[i]);
1624 SwapBytes(aliveSyn8.su[i]);
1625 SwapBytes(aliveSyn8.sd[i]);
1629 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1630 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1632 //-----------------------------------------------------------------------------
1633 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1635 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1636 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1637 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1640 SwapBytes(disconnSynAck6.len);
1641 SwapBytes(disconnSynAck6.rnd);
1644 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1645 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1647 //-----------------------------------------------------------------------------
1648 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1650 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1652 //-----------------------------------------------------------------------------
1653 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1655 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1656 disconnSynAck8.hdr.protoVer[0] = 0;
1657 disconnSynAck8.hdr.protoVer[1] = 8;
1659 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1660 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1661 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1664 SwapBytes(disconnSynAck8.len);
1665 SwapBytes(disconnSynAck8.rnd);
1668 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1669 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1671 //-----------------------------------------------------------------------------
1672 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1674 fin6.len = Min8(sizeof(FIN_6));
1675 strcpy((char*)fin6.type, "FIN");
1676 strcpy((char*)fin6.ok, "OK");
1679 SwapBytes(fin6.len);
1682 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1684 users->Unauthorize(iaUser->login, this);
1686 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1692 //-----------------------------------------------------------------------------
1693 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1695 return Send_FIN_6(iaUser, sip, it);
1697 //-----------------------------------------------------------------------------
1698 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1700 strcpy((char*)fin8.hdr.magic, IA_ID);
1701 fin8.hdr.protoVer[0] = 0;
1702 fin8.hdr.protoVer[1] = 8;
1704 fin8.len = Min8(sizeof(FIN_8));
1705 strcpy((char*)fin8.type, "FIN");
1706 strcpy((char*)fin8.ok, "OK");
1709 SwapBytes(fin8.len);
1712 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1714 users->Unauthorize(iaUser->login, this);
1716 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1724 //-----------------------------------------------------------------------------
1726 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
1728 unsigned char keyL[PASSWD_LEN];
1729 memset(keyL, 0, PASSWD_LEN);
1730 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1731 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1733 //-----------------------------------------------------------------------------
1735 void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
1737 for (size_t i = 0; i < len8; i++)
1738 DecodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
1740 //-----------------------------------------------------------------------------
1742 void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
1744 for (size_t i = 0; i < len8; i++)
1745 EncodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
1747 //-----------------------------------------------------------------------------