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)
83 //-----------------------------------------------------------------------------
84 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
88 std::vector<PARAM_VALUE>::const_iterator pvi;
89 ///////////////////////////
91 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
92 if (pvi == s.moduleParams.end())
94 errorStr = "Parameter \'Port\' not found.";
95 printfd(__FILE__, "Parameter 'Port' not found\n");
98 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
100 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
101 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
104 port = static_cast<uint16_t>(p);
105 ///////////////////////////
106 pv.param = "UserDelay";
107 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
108 if (pvi == s.moduleParams.end())
110 errorStr = "Parameter \'UserDelay\' not found.";
111 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
115 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
117 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
118 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
121 ///////////////////////////
122 pv.param = "UserTimeout";
123 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
124 if (pvi == s.moduleParams.end())
126 errorStr = "Parameter \'UserTimeout\' not found.";
127 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
131 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
133 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
134 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
137 ///////////////////////////
138 pv.param = "LogProtocolErrors";
139 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
140 if (pvi == s.moduleParams.end())
141 logProtocolErrors = false;
142 else if (ParseYesNo(pvi->value[0], &logProtocolErrors))
144 errorStr = "Cannot parse parameter \'LogProtocolErrors\': " + errorStr;
145 printfd(__FILE__, "Cannot parse parameter 'LogProtocolErrors'\n");
148 /////////////////////////////////////////////////////////////
149 std::string freeMbType;
152 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
153 if (pvi == s.moduleParams.end())
155 errorStr = "Parameter \'FreeMb\' not found.";
156 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
159 freeMbType = pvi->value[0];
161 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
163 freeMbShowType = freeMbCash;
165 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
167 freeMbShowType = freeMbNone;
169 else if (!str2x(freeMbType.c_str(), n))
171 if (n < 0 || n >= DIR_NUM)
173 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
174 printfd(__FILE__, "%s\n", errorStr.c_str());
177 freeMbShowType = (FREEMB)(freeMb0 + n);
181 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
182 printfd(__FILE__, "%s\n", errorStr.c_str());
185 /////////////////////////////////////////////////////////////
188 //-----------------------------------------------------------------------------
189 //-----------------------------------------------------------------------------
190 //-----------------------------------------------------------------------------
191 #ifdef IA_PHASE_DEBUG
197 gettimeofday(&phaseTime, NULL);
204 gettimeofday(&phaseTime, NULL);
207 //-----------------------------------------------------------------------------
208 IA_PHASE::~IA_PHASE()
210 #ifdef IA_PHASE_DEBUG
211 flog = fopen(log.c_str(), "at");
214 fprintf(flog, "IA %s D\n", login.c_str());
219 //-----------------------------------------------------------------------------
220 #ifdef IA_PHASE_DEBUG
221 void IA_PHASE::SetLogFileName(const string & logFileName)
223 log = logFileName + ".ia.log";
225 //-----------------------------------------------------------------------------
226 void IA_PHASE::SetUserLogin(const string & login)
228 IA_PHASE::login = login;
230 //-----------------------------------------------------------------------------
231 void IA_PHASE::WritePhaseChange(int newPhase)
234 gettimeofday(&newPhaseTime, NULL);
235 flog = fopen(log.c_str(), "at");
238 string action = newPhase == phase ? "U" : "C";
239 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
240 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
241 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
251 //-----------------------------------------------------------------------------
252 void IA_PHASE::SetPhase1()
254 #ifdef IA_PHASE_DEBUG
258 gettimeofday(&phaseTime, NULL);
260 //-----------------------------------------------------------------------------
261 void IA_PHASE::SetPhase2()
263 #ifdef IA_PHASE_DEBUG
267 gettimeofday(&phaseTime, NULL);
269 //-----------------------------------------------------------------------------
270 void IA_PHASE::SetPhase3()
272 #ifdef IA_PHASE_DEBUG
276 gettimeofday(&phaseTime, NULL);
278 //-----------------------------------------------------------------------------
279 void IA_PHASE::SetPhase4()
281 #ifdef IA_PHASE_DEBUG
285 gettimeofday(&phaseTime, NULL);
287 //-----------------------------------------------------------------------------
288 void IA_PHASE::SetPhase5()
290 #ifdef IA_PHASE_DEBUG
294 gettimeofday(&phaseTime, NULL);
296 //-----------------------------------------------------------------------------
297 int IA_PHASE::GetPhase() const
301 //-----------------------------------------------------------------------------
302 void IA_PHASE::UpdateTime()
304 #ifdef IA_PHASE_DEBUG
305 WritePhaseChange(phase);
307 gettimeofday(&phaseTime, NULL);
309 //-----------------------------------------------------------------------------
310 const UTIME & IA_PHASE::GetTime() const
314 //-----------------------------------------------------------------------------
315 //-----------------------------------------------------------------------------
316 //-----------------------------------------------------------------------------
324 isRunningRunTimeouter(false),
341 enabledDirs(0xFFffFFff),
342 onDelUserNotifier(*this),
343 logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
345 InitEncrypt(&ctxS, "pr7Hhen");
347 pthread_mutexattr_t attr;
348 pthread_mutexattr_init(&attr);
349 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
350 pthread_mutex_init(&mutex, &attr);
352 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
353 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
354 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
355 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
356 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
357 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
358 memset(&fin6, 0, sizeof(FIN_6));
359 memset(&fin8, 0, sizeof(FIN_8));
361 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
362 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
363 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
364 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
365 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
366 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
367 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
368 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
369 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
370 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
371 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
372 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
373 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
374 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
375 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
376 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
377 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
378 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
380 packetTypes["CONN_SYN"] = CONN_SYN_N;
381 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
382 packetTypes["CONN_ACK"] = CONN_ACK_N;
383 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
384 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
385 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
386 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
387 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
388 packetTypes["FIN"] = FIN_N;
389 packetTypes["ERR"] = ERROR_N;
391 //-----------------------------------------------------------------------------
394 pthread_mutex_destroy(&mutex);
396 //-----------------------------------------------------------------------------
399 users->AddNotifierUserDel(&onDelUserNotifier);
409 if (pthread_create(&recvThread, NULL, Run, this))
411 errorStr = "Cannot create thread.";
412 printfd(__FILE__, "Cannot create recv thread\n");
413 logger("Cannot create recv thread.");
418 if (!isRunningRunTimeouter)
420 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
422 errorStr = "Cannot create thread.";
423 printfd(__FILE__, "Cannot create timeouter thread\n");
424 logger("Cannot create timeouter thread.");
431 //-----------------------------------------------------------------------------
442 UnauthorizeUser(this)
447 //5 seconds to thread stops itself
448 for (int i = 0; i < 25 && isRunningRun; i++)
450 struct timespec ts = {0, 200000000};
451 nanosleep(&ts, NULL);
457 if (isRunningRunTimeouter)
459 //5 seconds to thread stops itself
460 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
462 struct timespec ts = {0, 200000000};
463 nanosleep(&ts, NULL);
467 users->DelNotifierUserDel(&onDelUserNotifier);
469 if (isRunningRun || isRunningRunTimeouter)
472 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
475 //-----------------------------------------------------------------------------
476 void * AUTH_IA::Run(void * d)
479 sigfillset(&signalSet);
480 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
482 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
484 ia->isRunningRun = true;
488 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
492 ia->RecvData(buffer, sizeof(buffer));
493 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
496 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
497 TouchFile(monFile.c_str());
501 ia->isRunningRun = false;
504 //-----------------------------------------------------------------------------
505 void * AUTH_IA::RunTimeouter(void * d)
508 sigfillset(&signalSet);
509 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
511 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
513 ia->isRunningRunTimeouter = true;
516 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
519 struct timespec ts = {0, 20000000};
520 nanosleep(&ts, NULL);
522 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
523 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
525 TouchFile(monFile.c_str());
529 ia->isRunningRunTimeouter = false;
532 //-----------------------------------------------------------------------------
533 int AUTH_IA::ParseSettings()
535 int ret = iaSettings.ParseSettings(settings);
537 errorStr = iaSettings.GetStrError();
540 //-----------------------------------------------------------------------------
541 int AUTH_IA::PrepareNet()
543 struct sockaddr_in listenAddr;
545 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
547 if (listenSocket < 0)
549 errorStr = "Cannot create socket.";
550 logger("Cannot create a socket: %s", strerror(errno));
554 listenAddr.sin_family = AF_INET;
555 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
556 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
558 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
560 errorStr = "AUTH_IA: Bind failed.";
561 logger("Cannot bind the socket: %s", strerror(errno));
567 //-----------------------------------------------------------------------------
568 int AUTH_IA::FinalizeNet()
573 //-----------------------------------------------------------------------------
574 int AUTH_IA::RecvData(char * buffer, int bufferSize)
576 if (!WaitPackets(listenSocket)) // Timeout
581 struct sockaddr_in outerAddr;
582 socklen_t outerAddrLen(sizeof(outerAddr));
583 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
590 if (dataLen <= 0) // Error
594 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
595 logger("recvfrom error: %s", strerror(errno));
604 uint32_t sip = outerAddr.sin_addr.s_addr;
605 uint16_t sport = htons(outerAddr.sin_port);
608 if (CheckHeader(buffer, sip, &protoVer))
611 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
612 memset(login, 0, PASSWD_LEN);
614 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
617 if (users->FindByName(login, &user))
619 logger("User's connect failed: user '%s' not found. IP %s",
621 inet_ntostring(sip).c_str());
622 printfd(__FILE__, "User '%s' NOT found!\n", login);
623 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ!");
627 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
629 if (user->GetProperty().disabled.Get())
631 logger("Cannont authorize '%s', user is disabled.", login);
632 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
636 if (user->GetProperty().passive.Get())
638 logger("Cannont authorize '%s', user is passive.", login);
639 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
643 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
645 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
646 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
647 logger("User %s. IP address is incorrect. IP %s",
648 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
649 SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
653 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
655 //-----------------------------------------------------------------------------
656 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
658 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
660 //SendError(userIP, updateMsg);
661 printfd(__FILE__, "update needed - IA_ID\n");
662 if (iaSettings.LogProtocolErrors())
663 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
664 //SendError(userIP, "Incorrect header!");
668 if (buffer[6] != 0) //proto[0] shoud be 0
670 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
671 if (iaSettings.LogProtocolErrors())
672 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
673 //SendError(userIP, updateMsg);
680 //SendError(userIP, updateMsg);
681 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
682 if (iaSettings.LogProtocolErrors())
683 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
688 *protoVer = buffer[7];
692 //-----------------------------------------------------------------------------
693 int AUTH_IA::Timeouter()
695 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
697 std::map<uint32_t, IA_USER>::iterator it;
698 it = ip2user.begin();
701 while (it != ip2user.end())
705 static UTIME currTime;
706 gettimeofday(&currTime, NULL);
708 if ((it->second.phase.GetPhase() == 2)
709 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
711 if (iaSettings.LogProtocolErrors())
712 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());
713 it->second.phase.SetPhase1();
714 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
719 if (it->second.phase.GetPhase() == 3)
721 if (!it->second.messagesToSend.empty())
723 if (it->second.protoVer == 6)
724 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
726 if (it->second.protoVer == 7)
727 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
729 if (it->second.protoVer == 8)
730 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
732 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
735 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
737 switch (it->second.protoVer)
740 Send_ALIVE_SYN_6(&(it->second), sip);
743 Send_ALIVE_SYN_7(&(it->second), sip);
746 Send_ALIVE_SYN_8(&(it->second), sip);
750 gettimeofday(&it->second.lastSendAlive, NULL);
753 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
755 if (iaSettings.LogProtocolErrors())
756 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());
757 users->Unauthorize(it->second.user->GetLogin(), this);
763 if ((it->second.phase.GetPhase() == 4)
764 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
766 if (iaSettings.LogProtocolErrors())
767 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());
768 it->second.phase.SetPhase3();
769 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
777 //-----------------------------------------------------------------------------
778 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
780 std::string login(user->GetLogin());
781 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
783 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
784 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
786 if (it == ip2user.end())
789 if (!users->FindByIPIdx(sip, &userPtr))
791 if (userPtr->GetID() != user->GetID())
793 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
794 userPtr->GetLogin().c_str(),
795 inet_ntostring(sip).c_str(),
797 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
798 userPtr->GetLogin().c_str(),
799 inet_ntostring(sip).c_str(),
801 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
806 printfd(__FILE__, "Add new user '%s' from ip %s\n",
807 login.c_str(), inet_ntostring(sip).c_str());
808 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
809 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
811 #ifdef IA_PHASE_DEBUG
812 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
813 it->second.phase.SetUserLogin(login);
816 else if (user->GetID() != it->second.user->GetID())
818 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
819 it->second.user->GetLogin().c_str(),
820 inet_ntostring(sip).c_str(),
821 user->GetLogin().c_str());
822 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
823 it->second.user->GetLogin().c_str(),
824 inet_ntostring(sip).c_str(),
825 user->GetLogin().c_str());
826 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
830 IA_USER * iaUser = &(it->second);
832 if (iaUser->password != user->GetProperty().password.Get())
834 InitEncrypt(&iaUser->ctx, user->GetProperty().password.Get());
835 iaUser->password = user->GetProperty().password.Get();
838 Decrypt(&iaUser->ctx, static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset) / 8);
840 char packetName[IA_MAX_TYPE_LEN];
841 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
842 packetName[IA_MAX_TYPE_LEN - 1] = 0;
844 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
845 if (pi == packetTypes.end())
847 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
848 printfd(__FILE__, "Login or password is wrong!\n");
849 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
851 inet_ntostring(sip).c_str());
856 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
858 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
859 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
860 inet_ntostring(sip).c_str());
861 logger("Login '%s' is already in use from ip %s. IP %s",
863 inet_ntostring(user->GetCurrIP()).c_str(),
864 inet_ntostring(sip).c_str());
865 SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
876 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
878 return Send_CONN_SYN_ACK_6(iaUser, sip);
880 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
882 return Send_CONN_SYN_ACK_7(iaUser, sip);
884 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
886 return Send_CONN_SYN_ACK_8(iaUser, sip);
894 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
896 return Send_ALIVE_SYN_6(iaUser, sip);
898 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
900 return Send_ALIVE_SYN_7(iaUser, sip);
902 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
904 return Send_ALIVE_SYN_8(iaUser, sip);
912 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
914 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
916 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
924 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
926 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
928 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
930 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
932 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
934 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
942 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
944 return Send_FIN_6(iaUser, sip, it);
946 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
948 return Send_FIN_7(iaUser, sip, it);
950 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
952 return Send_FIN_8(iaUser, sip, it);
959 //-----------------------------------------------------------------------------
960 void AUTH_IA::DelUser(USER_PTR u)
963 uint32_t ip = u->GetCurrIP();
968 std::map<uint32_t, IA_USER>::iterator it;
970 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
971 it = ip2user.find(ip);
972 if (it == ip2user.end())
975 printfd(__FILE__, "Nothing to delete\n");
979 if (it->second.user == u)
981 printfd(__FILE__, "User removed!\n");
982 users->Unauthorize(u->GetLogin(), this);
986 //-----------------------------------------------------------------------------
987 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
989 struct sockaddr_in sendAddr;
996 memset(&err, 0, sizeof(ERR));
998 sendAddr.sin_family = AF_INET;
999 sendAddr.sin_port = htons(port);
1000 sendAddr.sin_addr.s_addr = ip;
1003 strncpy((char*)err.type, "ERR", 16);
1004 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1010 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1011 printfd(__FILE__, "SendError %d bytes sent\n", res);
1016 memset(&err8, 0, sizeof(ERR_8));
1018 sendAddr.sin_family = AF_INET;
1019 sendAddr.sin_port = htons(port);
1020 sendAddr.sin_addr.s_addr = ip;
1023 strncpy((char*)err8.type, "ERR", 16);
1024 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1027 SwapBytes(err8.len);
1030 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1031 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1037 //-----------------------------------------------------------------------------
1038 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1040 struct sockaddr_in sendAddr;
1042 sendAddr.sin_family = AF_INET;
1043 sendAddr.sin_port = htons(port);
1044 sendAddr.sin_addr.s_addr = ip;
1046 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1051 //-----------------------------------------------------------------------------
1052 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1054 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1056 std::map<uint32_t, IA_USER>::iterator it;
1058 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1059 it = ip2user.find(ip);
1060 if (it == ip2user.end())
1062 errorStr = "Unknown user.";
1065 it->second.messagesToSend.push_back(msg);
1068 //-----------------------------------------------------------------------------
1069 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1071 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1074 memset(&info, 0, sizeof(INFO_6));
1077 strncpy((char*)info.type, "INFO", 16);
1078 info.infoType = 'I';
1079 strncpy((char*)info.text, msg.text.c_str(), 235);
1082 size_t len = info.len;
1084 SwapBytes(info.len);
1088 memcpy(buffer, &info, sizeof(INFO_6));
1089 Encrypt(&user.ctx, buffer, buffer, len / 8);
1090 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1092 //-----------------------------------------------------------------------------
1093 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1095 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1098 memset(&info, 0, sizeof(INFO_7));
1101 strncpy((char*)info.type, "INFO_7", 16);
1102 info.infoType = static_cast<int8_t>(msg.header.type);
1103 info.showTime = static_cast<int8_t>(msg.header.showTime);
1104 info.sendTime = msg.header.creationTime;
1106 size_t len = info.len;
1108 SwapBytes(info.len);
1109 SwapBytes(info.sendTime);
1112 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1113 info.text[MAX_MSG_LEN - 1] = 0;
1116 memcpy(buffer, &info, sizeof(INFO_7));
1118 Encrypt(&user.ctx, buffer, buffer, len / 8);
1119 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1121 //-----------------------------------------------------------------------------
1122 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1124 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1127 memset(&info, 0, sizeof(INFO_8));
1130 strncpy((char*)info.type, "INFO_8", 16);
1131 info.infoType = static_cast<int8_t>(msg.header.type);
1132 info.showTime = static_cast<int8_t>(msg.header.showTime);
1133 info.sendTime = msg.header.creationTime;
1135 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1136 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1138 size_t len = info.len;
1140 SwapBytes(info.len);
1141 SwapBytes(info.sendTime);
1145 memcpy(buffer, &info, sizeof(INFO_8));
1147 Encrypt(&user.ctx, buffer, buffer, len / 8);
1148 return Send(ip, user.port, buffer, len);
1150 //-----------------------------------------------------------------------------
1151 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1153 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1156 enabledDirs = 0xFFffFFff;
1158 iaUser->phase.SetPhase2();
1159 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1162 //-----------------------------------------------------------------------------
1163 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1165 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1167 //-----------------------------------------------------------------------------
1168 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1171 SwapBytes(connSyn->dirs);
1173 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, sip);
1174 enabledDirs = connSyn->dirs;
1177 //-----------------------------------------------------------------------------
1178 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1181 SwapBytes(connAck->len);
1182 SwapBytes(connAck->rnd);
1184 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1186 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1188 iaUser->phase.UpdateTime();
1190 iaUser->lastSendAlive = iaUser->phase.GetTime();
1191 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1193 iaUser->phase.SetPhase3();
1194 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1199 errorStr = iaUser->user->GetStrError();
1200 if (iaSettings.LogProtocolErrors())
1201 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());
1202 iaUser->phase.SetPhase1();
1204 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1208 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1209 if (iaSettings.LogProtocolErrors())
1211 if (iaUser->phase.GetPhase() != 2)
1212 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());
1213 if (connAck->rnd != iaUser->rnd + 1)
1214 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);
1218 //-----------------------------------------------------------------------------
1219 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1221 return Process_CONN_ACK_6(connAck, iaUser, sip);
1223 //-----------------------------------------------------------------------------
1224 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1227 SwapBytes(connAck->len);
1228 SwapBytes(connAck->rnd);
1230 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1232 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1234 iaUser->phase.UpdateTime();
1235 iaUser->lastSendAlive = iaUser->phase.GetTime();
1236 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1238 iaUser->phase.SetPhase3();
1239 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1244 errorStr = iaUser->user->GetStrError();
1245 if (iaSettings.LogProtocolErrors())
1246 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());
1247 iaUser->phase.SetPhase1();
1249 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1253 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1254 if (iaSettings.LogProtocolErrors())
1256 if (iaUser->phase.GetPhase() != 2)
1257 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());
1258 if (connAck->rnd != iaUser->rnd + 1)
1259 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);
1263 //-----------------------------------------------------------------------------
1264 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1267 SwapBytes(aliveAck->len);
1268 SwapBytes(aliveAck->rnd);
1270 printfd(__FILE__, "ALIVE_ACK_6\n");
1271 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1273 iaUser->phase.UpdateTime();
1275 iaUser->aliveSent = false;
1280 //-----------------------------------------------------------------------------
1281 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1283 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1285 //-----------------------------------------------------------------------------
1286 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1289 SwapBytes(aliveAck->len);
1290 SwapBytes(aliveAck->rnd);
1292 printfd(__FILE__, "ALIVE_ACK_8\n");
1293 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1295 iaUser->phase.UpdateTime();
1297 iaUser->aliveSent = false;
1302 //-----------------------------------------------------------------------------
1303 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1305 printfd(__FILE__, "DISCONN_SYN_6\n");
1306 if (iaUser->phase.GetPhase() != 3)
1308 if (iaSettings.LogProtocolErrors())
1309 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());
1310 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1311 errorStr = "Incorrect request DISCONN_SYN";
1315 iaUser->phase.SetPhase4();
1316 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1320 //-----------------------------------------------------------------------------
1321 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1323 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1325 //-----------------------------------------------------------------------------
1326 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1328 if (iaUser->phase.GetPhase() != 3)
1330 if (iaSettings.LogProtocolErrors())
1331 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());
1332 errorStr = "Incorrect request DISCONN_SYN";
1333 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1337 iaUser->phase.SetPhase4();
1338 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1342 //-----------------------------------------------------------------------------
1343 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1346 std::map<uint32_t, IA_USER>::iterator)
1349 SwapBytes(disconnAck->len);
1350 SwapBytes(disconnAck->rnd);
1352 printfd(__FILE__, "DISCONN_ACK_6\n");
1353 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1355 if (iaSettings.LogProtocolErrors())
1357 if (iaUser->phase.GetPhase() != 4)
1358 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());
1359 if (disconnAck->rnd != iaUser->rnd + 1)
1360 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);
1362 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1368 //-----------------------------------------------------------------------------
1369 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)
1371 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1373 //-----------------------------------------------------------------------------
1374 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1377 SwapBytes(disconnAck->len);
1378 SwapBytes(disconnAck->rnd);
1380 printfd(__FILE__, "DISCONN_ACK_8\n");
1381 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1383 if (iaSettings.LogProtocolErrors())
1385 if (iaUser->phase.GetPhase() != 4)
1386 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());
1387 if (disconnAck->rnd != iaUser->rnd + 1)
1388 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);
1390 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1396 //-----------------------------------------------------------------------------
1397 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1399 //+++ Fill static data in connSynAck +++
1400 // TODO Move this code. It must be executed only once
1401 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1402 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1403 for (int j = 0; j < DIR_NUM; j++)
1405 strncpy((char*)connSynAck6.dirName[j],
1406 stgSettings->GetDirName(j).c_str(),
1409 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1411 //--- Fill static data in connSynAck ---
1413 iaUser->rnd = static_cast<uint32_t>(random());
1414 connSynAck6.rnd = iaUser->rnd;
1416 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1417 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1420 SwapBytes(connSynAck6.len);
1421 SwapBytes(connSynAck6.rnd);
1422 SwapBytes(connSynAck6.userTimeOut);
1423 SwapBytes(connSynAck6.aliveDelay);
1426 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1427 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1429 //-----------------------------------------------------------------------------
1430 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1432 return Send_CONN_SYN_ACK_6(iaUser, sip);
1434 //-----------------------------------------------------------------------------
1435 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1437 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1438 connSynAck8.hdr.protoVer[0] = 0;
1439 connSynAck8.hdr.protoVer[1] = 8;
1441 //+++ Fill static data in connSynAck +++
1442 // TODO Move this code. It must be executed only once
1443 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1444 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1445 for (int j = 0; j < DIR_NUM; j++)
1447 strncpy((char*)connSynAck8.dirName[j],
1448 stgSettings->GetDirName(j).c_str(),
1451 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1453 //--- Fill static data in connSynAck ---
1455 iaUser->rnd = static_cast<uint32_t>(random());
1456 connSynAck8.rnd = iaUser->rnd;
1458 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1459 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1462 SwapBytes(connSynAck8.len);
1463 SwapBytes(connSynAck8.rnd);
1464 SwapBytes(connSynAck8.userTimeOut);
1465 SwapBytes(connSynAck8.aliveDelay);
1468 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1469 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1471 //-----------------------------------------------------------------------------
1472 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1474 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1475 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1477 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1479 for (int i = 0; i < DIR_NUM; i++)
1481 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1482 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1484 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1485 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1489 int dn = iaSettings.GetFreeMbShowType();
1490 const TARIFF * tf = iaUser->user->GetTariff();
1494 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1499 if (std::fabs(p) < 1.0e-3)
1501 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1505 double fmb = iaUser->user->GetProperty().freeMb;
1506 fmb = fmb < 0 ? 0 : fmb;
1507 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1512 if (freeMbNone == iaSettings.GetFreeMbShowType())
1514 aliveSyn6.freeMb[0] = 0;
1518 double fmb = iaUser->user->GetProperty().freeMb;
1519 fmb = fmb < 0 ? 0 : fmb;
1520 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1525 if (iaUser->aliveSent)
1527 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1529 iaUser->aliveSent = true;
1532 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1533 if (!stgSettings->GetShowFeeInCash())
1534 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1537 SwapBytes(aliveSyn6.len);
1538 SwapBytes(aliveSyn6.rnd);
1539 SwapBytes(aliveSyn6.cash);
1540 for (int i = 0; i < DIR_NUM; ++i)
1542 SwapBytes(aliveSyn6.mu[i]);
1543 SwapBytes(aliveSyn6.md[i]);
1544 SwapBytes(aliveSyn6.su[i]);
1545 SwapBytes(aliveSyn6.sd[i]);
1549 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1550 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1552 //-----------------------------------------------------------------------------
1553 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1555 return Send_ALIVE_SYN_6(iaUser, sip);
1557 //-----------------------------------------------------------------------------
1558 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1560 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1561 aliveSyn8.hdr.protoVer[0] = 0;
1562 aliveSyn8.hdr.protoVer[1] = 8;
1564 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1565 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1567 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1569 for (int i = 0; i < DIR_NUM; i++)
1571 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1572 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1574 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1575 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1579 int dn = iaSettings.GetFreeMbShowType();
1583 const TARIFF * tf = iaUser->user->GetTariff();
1584 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1589 if (std::fabs(p) < 1.0e-3)
1591 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1595 double fmb = iaUser->user->GetProperty().freeMb;
1596 fmb = fmb < 0 ? 0 : fmb;
1597 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1602 if (freeMbNone == iaSettings.GetFreeMbShowType())
1604 aliveSyn8.freeMb[0] = 0;
1608 double fmb = iaUser->user->GetProperty().freeMb;
1609 fmb = fmb < 0 ? 0 : fmb;
1610 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1615 if (iaUser->aliveSent)
1617 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1619 iaUser->aliveSent = true;
1622 const TARIFF * tf = iaUser->user->GetTariff();
1624 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1625 if (!stgSettings->GetShowFeeInCash())
1626 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1629 SwapBytes(aliveSyn8.len);
1630 SwapBytes(aliveSyn8.rnd);
1631 SwapBytes(aliveSyn8.cash);
1632 SwapBytes(aliveSyn8.status);
1633 for (int i = 0; i < DIR_NUM; ++i)
1635 SwapBytes(aliveSyn8.mu[i]);
1636 SwapBytes(aliveSyn8.md[i]);
1637 SwapBytes(aliveSyn8.su[i]);
1638 SwapBytes(aliveSyn8.sd[i]);
1642 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1643 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1645 //-----------------------------------------------------------------------------
1646 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1648 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1649 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1650 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1653 SwapBytes(disconnSynAck6.len);
1654 SwapBytes(disconnSynAck6.rnd);
1657 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1658 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1660 //-----------------------------------------------------------------------------
1661 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1663 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1665 //-----------------------------------------------------------------------------
1666 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1668 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1669 disconnSynAck8.hdr.protoVer[0] = 0;
1670 disconnSynAck8.hdr.protoVer[1] = 8;
1672 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1673 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1674 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1677 SwapBytes(disconnSynAck8.len);
1678 SwapBytes(disconnSynAck8.rnd);
1681 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1682 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1684 //-----------------------------------------------------------------------------
1685 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1687 fin6.len = Min8(sizeof(FIN_6));
1688 strcpy((char*)fin6.type, "FIN");
1689 strcpy((char*)fin6.ok, "OK");
1692 SwapBytes(fin6.len);
1695 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1697 users->Unauthorize(iaUser->login, this);
1699 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1705 //-----------------------------------------------------------------------------
1706 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1708 return Send_FIN_6(iaUser, sip, it);
1710 //-----------------------------------------------------------------------------
1711 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1713 strcpy((char*)fin8.hdr.magic, IA_ID);
1714 fin8.hdr.protoVer[0] = 0;
1715 fin8.hdr.protoVer[1] = 8;
1717 fin8.len = Min8(sizeof(FIN_8));
1718 strcpy((char*)fin8.type, "FIN");
1719 strcpy((char*)fin8.ok, "OK");
1722 SwapBytes(fin8.len);
1725 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1727 users->Unauthorize(iaUser->login, this);
1729 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1737 //-----------------------------------------------------------------------------
1739 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
1741 unsigned char keyL[PASSWD_LEN];
1742 memset(keyL, 0, PASSWD_LEN);
1743 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1744 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1746 //-----------------------------------------------------------------------------
1748 void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
1750 for (size_t i = 0; i < len8; i++)
1751 DecodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
1753 //-----------------------------------------------------------------------------
1755 void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
1757 for (size_t i = 0; i < len8; i++)
1758 EncodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
1760 //-----------------------------------------------------------------------------