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, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ!");
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, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
628 if (user->GetProperty().passive.Get())
630 logger("Cannont authorize '%s', user is passive.", login);
631 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
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, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
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 //SendError(userIP, updateMsg);
653 printfd(__FILE__, "update needed - IA_ID\n");
654 if (iaSettings.LogProtocolErrors())
655 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
656 //SendError(userIP, "Incorrect header!");
660 if (buffer[6] != 0) //proto[0] shoud be 0
662 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
663 if (iaSettings.LogProtocolErrors())
664 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
665 //SendError(userIP, updateMsg);
672 //SendError(userIP, updateMsg);
673 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
674 if (iaSettings.LogProtocolErrors())
675 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
680 *protoVer = buffer[7];
684 //-----------------------------------------------------------------------------
685 int AUTH_IA::Timeouter()
687 STG_LOCKER lock(&mutex);
689 std::map<uint32_t, IA_USER>::iterator it;
690 it = ip2user.begin();
692 while (it != ip2user.end())
694 uint32_t sip = it->first;
696 static UTIME currTime;
697 gettimeofday(&currTime, NULL);
699 if ((it->second.phase.GetPhase() == 2)
700 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
702 if (iaSettings.LogProtocolErrors())
703 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());
704 it->second.phase.SetPhase1();
705 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
710 if (it->second.phase.GetPhase() == 3)
712 if (!it->second.messagesToSend.empty())
714 if (it->second.protoVer == 6)
715 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
717 if (it->second.protoVer == 7)
718 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
720 if (it->second.protoVer == 8)
721 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
723 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
726 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
728 switch (it->second.protoVer)
731 Send_ALIVE_SYN_6(&(it->second), sip);
734 Send_ALIVE_SYN_7(&(it->second), sip);
737 Send_ALIVE_SYN_8(&(it->second), sip);
741 gettimeofday(&it->second.lastSendAlive, NULL);
744 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
746 if (iaSettings.LogProtocolErrors())
747 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());
748 users->Unauthorize(it->second.user->GetLogin(), this);
754 if ((it->second.phase.GetPhase() == 4)
755 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
757 if (iaSettings.LogProtocolErrors())
758 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());
759 it->second.phase.SetPhase3();
760 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
768 //-----------------------------------------------------------------------------
769 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
771 std::string login(user->GetLogin());
772 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
774 STG_LOCKER lock(&mutex);
775 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
777 if (it == ip2user.end())
780 if (!users->FindByIPIdx(sip, &userPtr))
782 if (userPtr->GetID() != user->GetID())
784 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
785 userPtr->GetLogin().c_str(),
786 inet_ntostring(sip).c_str(),
788 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
789 userPtr->GetLogin().c_str(),
790 inet_ntostring(sip).c_str(),
792 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
797 printfd(__FILE__, "Add new user '%s' from ip %s\n",
798 login.c_str(), inet_ntostring(sip).c_str());
799 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
800 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
802 #ifdef IA_PHASE_DEBUG
803 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
804 it->second.phase.SetUserLogin(login);
807 else if (user->GetID() != it->second.user->GetID())
809 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
810 it->second.user->GetLogin().c_str(),
811 inet_ntostring(sip).c_str(),
812 user->GetLogin().c_str());
813 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
814 it->second.user->GetLogin().c_str(),
815 inet_ntostring(sip).c_str(),
816 user->GetLogin().c_str());
817 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
821 IA_USER * iaUser = &(it->second);
823 if (iaUser->password != user->GetProperty().password.Get())
825 InitEncrypt(&iaUser->ctx, user->GetProperty().password.Get());
826 iaUser->password = user->GetProperty().password.Get();
829 Decrypt(&iaUser->ctx, static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset) / 8);
831 char packetName[IA_MAX_TYPE_LEN];
832 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
833 packetName[IA_MAX_TYPE_LEN - 1] = 0;
835 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
836 if (pi == packetTypes.end())
838 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
839 printfd(__FILE__, "Login or password is wrong!\n");
840 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
842 inet_ntostring(sip).c_str());
847 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
849 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
850 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
851 inet_ntostring(sip).c_str());
852 logger("Login '%s' is already in use from ip %s. IP %s",
854 inet_ntostring(user->GetCurrIP()).c_str(),
855 inet_ntostring(sip).c_str());
856 SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
867 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
869 return Send_CONN_SYN_ACK_6(iaUser, sip);
871 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
873 return Send_CONN_SYN_ACK_7(iaUser, sip);
875 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
877 return Send_CONN_SYN_ACK_8(iaUser, sip);
885 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
887 return Send_ALIVE_SYN_6(iaUser, sip);
889 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
891 return Send_ALIVE_SYN_7(iaUser, sip);
893 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
895 return Send_ALIVE_SYN_8(iaUser, sip);
903 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
905 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
907 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
915 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
917 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
919 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
921 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
923 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
925 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
933 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
935 return Send_FIN_6(iaUser, sip, it);
937 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
939 return Send_FIN_7(iaUser, sip, it);
941 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
943 return Send_FIN_8(iaUser, sip, it);
950 //-----------------------------------------------------------------------------
951 void AUTH_IA::DelUser(USER_PTR u)
954 uint32_t ip = u->GetCurrIP();
959 std::map<uint32_t, IA_USER>::iterator it;
961 STG_LOCKER lock(&mutex);
962 it = ip2user.find(ip);
963 if (it == ip2user.end())
966 printfd(__FILE__, "Nothing to delete\n");
970 if (it->second.user == u)
972 printfd(__FILE__, "User removed!\n");
973 users->Unauthorize(u->GetLogin(), this);
977 //-----------------------------------------------------------------------------
978 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
980 struct sockaddr_in sendAddr;
987 memset(&err, 0, sizeof(ERR));
989 sendAddr.sin_family = AF_INET;
990 sendAddr.sin_port = htons(port);
991 sendAddr.sin_addr.s_addr = ip;
994 strncpy((char*)err.type, "ERR", 16);
995 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1001 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1002 printfd(__FILE__, "SendError %d bytes sent\n", res);
1007 memset(&err8, 0, sizeof(ERR_8));
1009 sendAddr.sin_family = AF_INET;
1010 sendAddr.sin_port = htons(port);
1011 sendAddr.sin_addr.s_addr = ip;
1014 strncpy((char*)err8.type, "ERR", 16);
1015 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1018 SwapBytes(err8.len);
1021 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1022 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1028 //-----------------------------------------------------------------------------
1029 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1031 struct sockaddr_in sendAddr;
1033 sendAddr.sin_family = AF_INET;
1034 sendAddr.sin_port = htons(port);
1035 sendAddr.sin_addr.s_addr = ip;
1037 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1042 //-----------------------------------------------------------------------------
1043 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1045 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1047 std::map<uint32_t, IA_USER>::iterator it;
1049 STG_LOCKER lock(&mutex);
1050 it = ip2user.find(ip);
1051 if (it == ip2user.end())
1053 errorStr = "Unknown user.";
1056 it->second.messagesToSend.push_back(msg);
1059 //-----------------------------------------------------------------------------
1060 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1062 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1065 memset(&info, 0, sizeof(INFO_6));
1068 strncpy((char*)info.type, "INFO", 16);
1069 info.infoType = 'I';
1070 strncpy((char*)info.text, msg.text.c_str(), 235);
1073 size_t len = info.len;
1075 SwapBytes(info.len);
1079 memcpy(buffer, &info, sizeof(INFO_6));
1080 Encrypt(&user.ctx, buffer, buffer, len / 8);
1081 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1083 //-----------------------------------------------------------------------------
1084 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1086 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1089 memset(&info, 0, sizeof(INFO_7));
1092 strncpy((char*)info.type, "INFO_7", 16);
1093 info.infoType = static_cast<int8_t>(msg.header.type);
1094 info.showTime = static_cast<int8_t>(msg.header.showTime);
1095 info.sendTime = msg.header.creationTime;
1097 size_t len = info.len;
1099 SwapBytes(info.len);
1100 SwapBytes(info.sendTime);
1103 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1104 info.text[MAX_MSG_LEN - 1] = 0;
1107 memcpy(buffer, &info, sizeof(INFO_7));
1109 Encrypt(&user.ctx, buffer, buffer, len / 8);
1110 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1112 //-----------------------------------------------------------------------------
1113 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1115 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1118 memset(&info, 0, sizeof(INFO_8));
1121 strncpy((char*)info.type, "INFO_8", 16);
1122 info.infoType = static_cast<int8_t>(msg.header.type);
1123 info.showTime = static_cast<int8_t>(msg.header.showTime);
1124 info.sendTime = msg.header.creationTime;
1126 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1127 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1129 size_t len = info.len;
1131 SwapBytes(info.len);
1132 SwapBytes(info.sendTime);
1136 memcpy(buffer, &info, sizeof(INFO_8));
1138 Encrypt(&user.ctx, buffer, buffer, len / 8);
1139 return Send(ip, user.port, buffer, len);
1141 //-----------------------------------------------------------------------------
1142 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1144 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1147 enabledDirs = 0xFFffFFff;
1149 iaUser->phase.SetPhase2();
1150 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1153 //-----------------------------------------------------------------------------
1154 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1156 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1158 //-----------------------------------------------------------------------------
1159 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1162 SwapBytes(connSyn->dirs);
1164 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1165 enabledDirs = connSyn->dirs;
1168 //-----------------------------------------------------------------------------
1169 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1172 SwapBytes(connAck->len);
1173 SwapBytes(connAck->rnd);
1175 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1177 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1179 iaUser->phase.UpdateTime();
1181 iaUser->lastSendAlive = iaUser->phase.GetTime();
1182 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1184 iaUser->phase.SetPhase3();
1185 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1190 errorStr = iaUser->user->GetStrError();
1191 if (iaSettings.LogProtocolErrors())
1192 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());
1193 iaUser->phase.SetPhase1();
1195 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1199 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1200 if (iaSettings.LogProtocolErrors())
1202 if (iaUser->phase.GetPhase() != 2)
1203 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());
1204 if (connAck->rnd != iaUser->rnd + 1)
1205 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);
1209 //-----------------------------------------------------------------------------
1210 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1212 return Process_CONN_ACK_6(connAck, iaUser, sip);
1214 //-----------------------------------------------------------------------------
1215 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1218 SwapBytes(connAck->len);
1219 SwapBytes(connAck->rnd);
1221 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1223 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1225 iaUser->phase.UpdateTime();
1226 iaUser->lastSendAlive = iaUser->phase.GetTime();
1227 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1229 iaUser->phase.SetPhase3();
1230 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1235 errorStr = iaUser->user->GetStrError();
1236 if (iaSettings.LogProtocolErrors())
1237 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());
1238 iaUser->phase.SetPhase1();
1240 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1244 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1245 if (iaSettings.LogProtocolErrors())
1247 if (iaUser->phase.GetPhase() != 2)
1248 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());
1249 if (connAck->rnd != iaUser->rnd + 1)
1250 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);
1254 //-----------------------------------------------------------------------------
1255 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1258 SwapBytes(aliveAck->len);
1259 SwapBytes(aliveAck->rnd);
1261 printfd(__FILE__, "ALIVE_ACK_6\n");
1262 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1264 iaUser->phase.UpdateTime();
1266 iaUser->aliveSent = false;
1271 //-----------------------------------------------------------------------------
1272 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1274 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1276 //-----------------------------------------------------------------------------
1277 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1280 SwapBytes(aliveAck->len);
1281 SwapBytes(aliveAck->rnd);
1283 printfd(__FILE__, "ALIVE_ACK_8\n");
1284 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1286 iaUser->phase.UpdateTime();
1288 iaUser->aliveSent = false;
1293 //-----------------------------------------------------------------------------
1294 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1296 printfd(__FILE__, "DISCONN_SYN_6\n");
1297 if (iaUser->phase.GetPhase() != 3)
1299 if (iaSettings.LogProtocolErrors())
1300 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());
1301 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1302 errorStr = "Incorrect request DISCONN_SYN";
1306 iaUser->phase.SetPhase4();
1307 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1311 //-----------------------------------------------------------------------------
1312 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1314 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1316 //-----------------------------------------------------------------------------
1317 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1319 if (iaUser->phase.GetPhase() != 3)
1321 if (iaSettings.LogProtocolErrors())
1322 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());
1323 errorStr = "Incorrect request DISCONN_SYN";
1324 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1328 iaUser->phase.SetPhase4();
1329 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1333 //-----------------------------------------------------------------------------
1334 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1337 std::map<uint32_t, IA_USER>::iterator)
1340 SwapBytes(disconnAck->len);
1341 SwapBytes(disconnAck->rnd);
1343 printfd(__FILE__, "DISCONN_ACK_6\n");
1344 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1346 if (iaSettings.LogProtocolErrors())
1348 if (iaUser->phase.GetPhase() != 4)
1349 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());
1350 if (disconnAck->rnd != iaUser->rnd + 1)
1351 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);
1353 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1359 //-----------------------------------------------------------------------------
1360 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)
1362 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1364 //-----------------------------------------------------------------------------
1365 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1368 SwapBytes(disconnAck->len);
1369 SwapBytes(disconnAck->rnd);
1371 printfd(__FILE__, "DISCONN_ACK_8\n");
1372 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1374 if (iaSettings.LogProtocolErrors())
1376 if (iaUser->phase.GetPhase() != 4)
1377 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());
1378 if (disconnAck->rnd != iaUser->rnd + 1)
1379 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);
1381 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1387 //-----------------------------------------------------------------------------
1388 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1390 //+++ Fill static data in connSynAck +++
1391 // TODO Move this code. It must be executed only once
1392 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1393 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1394 for (int j = 0; j < DIR_NUM; j++)
1396 strncpy((char*)connSynAck6.dirName[j],
1397 stgSettings->GetDirName(j).c_str(),
1400 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1402 //--- Fill static data in connSynAck ---
1404 iaUser->rnd = static_cast<uint32_t>(random());
1405 connSynAck6.rnd = iaUser->rnd;
1407 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1408 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1411 SwapBytes(connSynAck6.len);
1412 SwapBytes(connSynAck6.rnd);
1413 SwapBytes(connSynAck6.userTimeOut);
1414 SwapBytes(connSynAck6.aliveDelay);
1417 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1418 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1420 //-----------------------------------------------------------------------------
1421 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1423 return Send_CONN_SYN_ACK_6(iaUser, sip);
1425 //-----------------------------------------------------------------------------
1426 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1428 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1429 connSynAck8.hdr.protoVer[0] = 0;
1430 connSynAck8.hdr.protoVer[1] = 8;
1432 //+++ Fill static data in connSynAck +++
1433 // TODO Move this code. It must be executed only once
1434 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1435 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1436 for (int j = 0; j < DIR_NUM; j++)
1438 strncpy((char*)connSynAck8.dirName[j],
1439 stgSettings->GetDirName(j).c_str(),
1442 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1444 //--- Fill static data in connSynAck ---
1446 iaUser->rnd = static_cast<uint32_t>(random());
1447 connSynAck8.rnd = iaUser->rnd;
1449 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1450 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1453 SwapBytes(connSynAck8.len);
1454 SwapBytes(connSynAck8.rnd);
1455 SwapBytes(connSynAck8.userTimeOut);
1456 SwapBytes(connSynAck8.aliveDelay);
1459 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1460 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1462 //-----------------------------------------------------------------------------
1463 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1465 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1466 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1468 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1470 for (int i = 0; i < DIR_NUM; i++)
1472 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1473 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1475 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1476 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1480 int dn = iaSettings.GetFreeMbShowType();
1481 const TARIFF * tf = iaUser->user->GetTariff();
1485 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1490 if (std::fabs(p) < 1.0e-3)
1492 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1496 double fmb = iaUser->user->GetProperty().freeMb;
1497 fmb = fmb < 0 ? 0 : fmb;
1498 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1503 if (freeMbNone == iaSettings.GetFreeMbShowType())
1505 aliveSyn6.freeMb[0] = 0;
1509 double fmb = iaUser->user->GetProperty().freeMb;
1510 fmb = fmb < 0 ? 0 : fmb;
1511 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1516 if (iaUser->aliveSent)
1518 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1520 iaUser->aliveSent = true;
1523 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1524 if (!stgSettings->GetShowFeeInCash())
1525 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1528 SwapBytes(aliveSyn6.len);
1529 SwapBytes(aliveSyn6.rnd);
1530 SwapBytes(aliveSyn6.cash);
1531 for (int i = 0; i < DIR_NUM; ++i)
1533 SwapBytes(aliveSyn6.mu[i]);
1534 SwapBytes(aliveSyn6.md[i]);
1535 SwapBytes(aliveSyn6.su[i]);
1536 SwapBytes(aliveSyn6.sd[i]);
1540 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1541 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1543 //-----------------------------------------------------------------------------
1544 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1546 return Send_ALIVE_SYN_6(iaUser, sip);
1548 //-----------------------------------------------------------------------------
1549 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1551 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1552 aliveSyn8.hdr.protoVer[0] = 0;
1553 aliveSyn8.hdr.protoVer[1] = 8;
1555 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1556 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1558 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1560 for (int i = 0; i < DIR_NUM; i++)
1562 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1563 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1565 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1566 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1570 int dn = iaSettings.GetFreeMbShowType();
1574 const TARIFF * tf = iaUser->user->GetTariff();
1575 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1580 if (std::fabs(p) < 1.0e-3)
1582 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1586 double fmb = iaUser->user->GetProperty().freeMb;
1587 fmb = fmb < 0 ? 0 : fmb;
1588 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1593 if (freeMbNone == iaSettings.GetFreeMbShowType())
1595 aliveSyn8.freeMb[0] = 0;
1599 double fmb = iaUser->user->GetProperty().freeMb;
1600 fmb = fmb < 0 ? 0 : fmb;
1601 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1606 if (iaUser->aliveSent)
1608 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1610 iaUser->aliveSent = true;
1613 const TARIFF * tf = iaUser->user->GetTariff();
1615 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1616 if (!stgSettings->GetShowFeeInCash())
1617 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1620 SwapBytes(aliveSyn8.len);
1621 SwapBytes(aliveSyn8.rnd);
1622 SwapBytes(aliveSyn8.cash);
1623 SwapBytes(aliveSyn8.status);
1624 for (int i = 0; i < DIR_NUM; ++i)
1626 SwapBytes(aliveSyn8.mu[i]);
1627 SwapBytes(aliveSyn8.md[i]);
1628 SwapBytes(aliveSyn8.su[i]);
1629 SwapBytes(aliveSyn8.sd[i]);
1633 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1634 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1636 //-----------------------------------------------------------------------------
1637 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1639 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1640 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1641 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1644 SwapBytes(disconnSynAck6.len);
1645 SwapBytes(disconnSynAck6.rnd);
1648 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1649 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1651 //-----------------------------------------------------------------------------
1652 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1654 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1656 //-----------------------------------------------------------------------------
1657 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1659 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1660 disconnSynAck8.hdr.protoVer[0] = 0;
1661 disconnSynAck8.hdr.protoVer[1] = 8;
1663 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1664 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1665 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1668 SwapBytes(disconnSynAck8.len);
1669 SwapBytes(disconnSynAck8.rnd);
1672 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1673 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1675 //-----------------------------------------------------------------------------
1676 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1678 fin6.len = Min8(sizeof(FIN_6));
1679 strcpy((char*)fin6.type, "FIN");
1680 strcpy((char*)fin6.ok, "OK");
1683 SwapBytes(fin6.len);
1686 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1688 users->Unauthorize(iaUser->login, this);
1690 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1696 //-----------------------------------------------------------------------------
1697 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1699 return Send_FIN_6(iaUser, sip, it);
1701 //-----------------------------------------------------------------------------
1702 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1704 strcpy((char*)fin8.hdr.magic, IA_ID);
1705 fin8.hdr.protoVer[0] = 0;
1706 fin8.hdr.protoVer[1] = 8;
1708 fin8.len = Min8(sizeof(FIN_8));
1709 strcpy((char*)fin8.type, "FIN");
1710 strcpy((char*)fin8.ok, "OK");
1713 SwapBytes(fin8.len);
1716 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1718 users->Unauthorize(iaUser->login, this);
1720 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1728 //-----------------------------------------------------------------------------
1730 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
1732 unsigned char keyL[PASSWD_LEN];
1733 memset(keyL, 0, PASSWD_LEN);
1734 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1735 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1737 //-----------------------------------------------------------------------------
1739 void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
1741 for (size_t i = 0; i < len8; i++)
1742 DecodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
1744 //-----------------------------------------------------------------------------
1746 void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
1748 for (size_t i = 0; i < len8; i++)
1749 EncodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
1751 //-----------------------------------------------------------------------------