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 <sys/select.h>
34 #include <unistd.h> // usleep, close
38 #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 "inetaccess.h"
49 extern volatile const time_t stgTime;
51 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password);
52 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
53 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
55 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
77 //-----------------------------------------------------------------------------
78 //-----------------------------------------------------------------------------
80 //-----------------------------------------------------------------------------
81 //-----------------------------------------------------------------------------
82 //-----------------------------------------------------------------------------
85 return iac.GetPlugin();
87 //-----------------------------------------------------------------------------
88 //-----------------------------------------------------------------------------
89 //-----------------------------------------------------------------------------
90 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
94 freeMbShowType(freeMbCash)
97 //-----------------------------------------------------------------------------
98 int AUTH_IA_SETTINGS::ParseIntInRange(const string & str, int min, int max, int * val)
100 if (str2x(str.c_str(), *val))
102 errorStr = "Incorrect value \'" + str + "\'.";
105 if (*val < min || *val > max)
107 errorStr = "Value \'" + str + "\' out of range.";
112 //-----------------------------------------------------------------------------
113 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
117 vector<PARAM_VALUE>::const_iterator pvi;
118 ///////////////////////////
120 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
121 if (pvi == s.moduleParams.end())
123 errorStr = "Parameter \'Port\' not found.";
124 printfd(__FILE__, "Parameter 'Port' not found\n");
127 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
129 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
130 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
134 ///////////////////////////
135 pv.param = "UserDelay";
136 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
137 if (pvi == s.moduleParams.end())
139 errorStr = "Parameter \'UserDelay\' not found.";
140 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
144 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
146 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
147 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
150 ///////////////////////////
151 pv.param = "UserTimeout";
152 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
153 if (pvi == s.moduleParams.end())
155 errorStr = "Parameter \'UserTimeout\' not found.";
156 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
160 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
162 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
163 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
166 /////////////////////////////////////////////////////////////
170 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
171 if (pvi == s.moduleParams.end())
173 errorStr = "Parameter \'FreeMb\' not found.";
174 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
177 freeMbType = pvi->value[0];
179 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
181 freeMbShowType = freeMbCash;
183 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
185 freeMbShowType = freeMbNone;
187 else if (!str2x(freeMbType.c_str(), n))
189 if (n < 0 || n >= DIR_NUM)
191 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
192 printfd(__FILE__, "%s\n", errorStr.c_str());
195 freeMbShowType = (FREEMB)(freeMb0 + n);
199 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
200 printfd(__FILE__, "%s\n", errorStr.c_str());
203 /////////////////////////////////////////////////////////////
206 //-----------------------------------------------------------------------------
207 //-----------------------------------------------------------------------------
208 //-----------------------------------------------------------------------------
209 #ifdef IA_PHASE_DEBUG
214 gettimeofday(&phaseTime, NULL);
220 gettimeofday(&phaseTime, NULL);
223 //-----------------------------------------------------------------------------
224 IA_PHASE::~IA_PHASE()
226 #ifdef IA_PHASE_DEBUG
227 flog = fopen(log.c_str(), "at");
230 fprintf(flog, "IA %s D\n", login.c_str());
235 //-----------------------------------------------------------------------------
236 #ifdef IA_PHASE_DEBUG
237 void IA_PHASE::SetLogFileName(const string & logFileName)
239 log = logFileName + ".ia.log";
241 //-----------------------------------------------------------------------------
242 void IA_PHASE::SetUserLogin(const string & login)
244 IA_PHASE::login = login;
246 //-----------------------------------------------------------------------------
247 void IA_PHASE::WritePhaseChange(int newPhase)
250 gettimeofday(&newPhaseTime, NULL);
251 flog = fopen(log.c_str(), "at");
252 /*int64_t tn = newPhaseTime.GetSec()*1000000 + newPhaseTime.GetUSec();
253 int64_t to = phaseTime.GetSec()*1000000 + phaseTime.GetUSec();*/
256 string action = newPhase == phase ? "U" : "C";
257 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
258 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
259 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
269 //-----------------------------------------------------------------------------
270 void IA_PHASE::SetPhase1()
272 #ifdef IA_PHASE_DEBUG
276 gettimeofday(&phaseTime, NULL);
278 //-----------------------------------------------------------------------------
279 void IA_PHASE::SetPhase2()
281 #ifdef IA_PHASE_DEBUG
285 gettimeofday(&phaseTime, NULL);
287 //-----------------------------------------------------------------------------
288 void IA_PHASE::SetPhase3()
290 #ifdef IA_PHASE_DEBUG
294 gettimeofday(&phaseTime, NULL);
296 //-----------------------------------------------------------------------------
297 void IA_PHASE::SetPhase4()
299 #ifdef IA_PHASE_DEBUG
303 gettimeofday(&phaseTime, NULL);
305 //-----------------------------------------------------------------------------
306 void IA_PHASE::SetPhase5()
308 #ifdef IA_PHASE_DEBUG
312 gettimeofday(&phaseTime, NULL);
314 //-----------------------------------------------------------------------------
315 int IA_PHASE::GetPhase() const
319 //-----------------------------------------------------------------------------
320 void IA_PHASE::UpdateTime()
322 #ifdef IA_PHASE_DEBUG
323 WritePhaseChange(phase);
325 gettimeofday(&phaseTime, NULL);
327 //-----------------------------------------------------------------------------
328 const UTIME & IA_PHASE::GetTime() const
332 //-----------------------------------------------------------------------------
333 //-----------------------------------------------------------------------------
334 //-----------------------------------------------------------------------------
338 isRunningRunTimeouter(false),
342 WriteServLog(GetStgLogger()),
343 enabledDirs(0xFFffFFff),
344 onDelUserNotifier(*this)
346 InitEncrypt(&ctxS, "pr7Hhen");
348 pthread_mutexattr_t attr;
349 pthread_mutexattr_init(&attr);
350 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
351 pthread_mutex_init(&mutex, &attr);
353 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
354 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
355 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
356 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
357 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
358 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
359 memset(&fin6, 0, sizeof(FIN_6));
360 memset(&fin8, 0, sizeof(FIN_8));
362 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
363 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
364 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
365 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
366 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
367 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
368 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
369 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
370 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
371 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
372 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
373 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
374 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
375 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
376 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
377 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
378 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
379 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
381 packetTypes["CONN_SYN"] = CONN_SYN_N;
382 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
383 packetTypes["CONN_ACK"] = CONN_ACK_N;
384 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
385 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
386 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
387 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
388 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
389 packetTypes["FIN"] = FIN_N;
390 packetTypes["ERR"] = ERROR_N;
392 //-----------------------------------------------------------------------------
395 pthread_mutex_destroy(&mutex);
397 //-----------------------------------------------------------------------------
400 users->AddNotifierUserDel(&onDelUserNotifier);
410 if (pthread_create(&recvThread, NULL, Run, this))
412 errorStr = "Cannot create thread.";
413 printfd(__FILE__, "Cannot create recv thread\n");
418 if (!isRunningRunTimeouter)
420 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
422 errorStr = "Cannot create thread.";
423 printfd(__FILE__, "Cannot create timeouter thread\n");
430 //-----------------------------------------------------------------------------
441 UnauthorizeUser(this)
446 //5 seconds to thread stops itself
447 for (int i = 0; i < 25 && isRunningRun; i++)
452 //after 5 seconds waiting thread still running. now killing it
455 //TODO pthread_cancel()
456 if (pthread_kill(recvThread, SIGINT))
458 errorStr = "Cannot kill thread.";
459 printfd(__FILE__, "Cannot kill thread\n");
462 for (int i = 0; i < 25 && isRunningRun; ++i)
466 printfd(__FILE__, "Failed to stop recv thread\n");
470 pthread_join(recvThread, NULL);
472 printfd(__FILE__, "AUTH_IA killed Run\n");
478 if (isRunningRunTimeouter)
480 //5 seconds to thread stops itself
481 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
486 //after 5 seconds waiting thread still running. now killing it
487 if (isRunningRunTimeouter)
489 //TODO pthread_cancel()
490 if (pthread_kill(timeouterThread, SIGINT))
492 errorStr = "Cannot kill thread.";
495 for (int i = 0; i < 25 && isRunningRunTimeouter; ++i)
497 if (isRunningRunTimeouter)
499 printfd(__FILE__, "Failed to stop timeouter thread\n");
503 pthread_join(timeouterThread, NULL);
505 printfd(__FILE__, "AUTH_IA killed Timeouter\n");
508 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
509 users->DelNotifierUserDel(&onDelUserNotifier);
512 //-----------------------------------------------------------------------------
513 void * AUTH_IA::Run(void * d)
515 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
517 ia->isRunningRun = true;
521 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
525 ia->RecvData(buffer, sizeof(buffer));
526 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
529 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
530 TouchFile(monFile.c_str());
534 ia->isRunningRun = false;
537 //-----------------------------------------------------------------------------
538 void * AUTH_IA::RunTimeouter(void * d)
540 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
542 ia->isRunningRunTimeouter = true;
545 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
550 // TODO cahange counter to timer and MONITOR_TIME_DELAY_SEC
551 if (++a % (50*60) == 0 && ia->stgSettings->GetMonitoring())
553 TouchFile(monFile.c_str());
557 ia->isRunningRunTimeouter = false;
560 //-----------------------------------------------------------------------------
561 int AUTH_IA::ParseSettings()
563 int ret = iaSettings.ParseSettings(settings);
565 errorStr = iaSettings.GetStrError();
568 //-----------------------------------------------------------------------------
569 int AUTH_IA::PrepareNet()
571 struct sockaddr_in listenAddr;
573 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
575 if (listenSocket < 0)
577 errorStr = "Cannot create socket.";
581 listenAddr.sin_family = AF_INET;
582 listenAddr.sin_port = htons(iaSettings.GetUserPort());
583 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
585 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
587 errorStr = "AUTH_IA: Bind failed.";
592 if (getsockopt(listenSocket, SOL_SOCKET, SO_SNDBUF, &buffLen, sizeof(buffLen)) < 0)
595 errorStr = "Getsockopt failed. " + string(strerror(errno));
599 //WriteServLog("buffLen = %d", buffLen);
603 //-----------------------------------------------------------------------------
604 int AUTH_IA::FinalizeNet()
609 //-----------------------------------------------------------------------------
610 int AUTH_IA::RecvData(char * buffer, int bufferSize)
612 if (!WaitPackets(listenSocket)) // Timeout
617 struct sockaddr_in outerAddr;
618 socklen_t outerAddrLen(sizeof(outerAddr));
619 int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
626 if (dataLen <= 0) // Error
630 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
640 if (CheckHeader(buffer, &protoVer))
643 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
644 memset(login, 0, PASSWD_LEN);
646 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
648 uint32_t sip = *((uint32_t*)&outerAddr.sin_addr);
649 uint16_t sport = htons(outerAddr.sin_port);
652 if (users->FindByName(login, &user) == 0)
654 printfd(__FILE__, "User %s FOUND!\n", user->GetLogin().c_str());
655 PacketProcessor(buffer, dataLen, sip, sport, protoVer, &user);
659 WriteServLog("User\'s connect failed:: user \'%s\' not found. IP \'%s\'",
661 inet_ntostring(sip).c_str());
662 printfd(__FILE__, "User %s NOT found!\n", login);
663 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
669 //-----------------------------------------------------------------------------
670 int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
672 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
674 //SendError(userIP, updateMsg);
675 printfd(__FILE__, "update needed - IA_ID\n");
676 //SendError(userIP, "Incorrect header!");
680 if (buffer[6] != 0) //proto[0] shoud be 0
682 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
683 //SendError(userIP, updateMsg);
690 //SendError(userIP, updateMsg);
691 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
696 *protoVer = buffer[7];
700 //-----------------------------------------------------------------------------
701 int AUTH_IA::Timeouter()
703 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
705 map<uint32_t, IA_USER>::iterator it;
706 it = ip2user.begin();
709 while (it != ip2user.end())
713 static UTIME currTime;
714 gettimeofday(&currTime, NULL);
716 if ((it->second.phase.GetPhase() == 2)
717 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
719 it->second.phase.SetPhase1();
720 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
723 if (it->second.phase.GetPhase() == 3)
725 if (!it->second.messagesToSend.empty())
727 if (it->second.protoVer == 6)
728 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
730 if (it->second.protoVer == 7)
731 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
733 if (it->second.protoVer == 8)
734 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
736 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
739 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
741 switch (it->second.protoVer)
744 Send_ALIVE_SYN_6(&(it->second), sip);
747 Send_ALIVE_SYN_7(&(it->second), sip);
750 Send_ALIVE_SYN_8(&(it->second), sip);
754 gettimeofday(&it->second.lastSendAlive, NULL);
757 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
759 it->second.user->Unauthorize(this);
765 if ((it->second.phase.GetPhase() == 4)
766 && ((currTime - it->second.phase.GetTime()) > 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(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR * user)
780 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
781 // ôÕÔ ÓÏÂÒÁÎÙ ÏÂÒÁÂÏÔÞÉËÉ ÒÁÚÎÙÈ ÐÁËÅÔÏ×
783 const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
785 IA_USER * iaUser = NULL;
787 CONN_SYN_6 * connSyn6;
788 CONN_SYN_7 * connSyn7;
789 CONN_SYN_8 * connSyn8;
791 CONN_ACK_6 * connAck;
792 ALIVE_ACK_6 * aliveAck;
793 DISCONN_SYN_6 * disconnSyn;
794 DISCONN_ACK_6 * disconnAck;
796 map<uint32_t, IA_USER>::iterator it;
797 it = ip2user.find(sip);
799 if (it == ip2user.end() || (*user)->GetID() != it->second.user->GetID())
801 // åÝÅ ÎÅ ÂÙÌÏ ÚÁÐÒÏÓÏ× Ó ÜÔÏÇÏ IP
802 printfd(__FILE__, "Add new user\n");
803 ip2user[sip].protoVer = protoVer;
804 ip2user[sip].user = *user;
805 ip2user[sip].port = sport;
806 #ifdef IA_PHASE_DEBUG
807 ip2user[sip].phase.SetLogFileName(stgSettings->GetLogFileName());
808 ip2user[sip].phase.SetUserLogin((*user)->GetLogin());
812 it = ip2user.find(sip); //TODO
813 if (it == ip2user.end())
815 printfd(__FILE__, "+++ ERROR +++\n");
820 iaUser = &(it->second);
822 if (iaUser->port != sport)
823 iaUser->port = sport;
825 if (iaUser->password != (*user)->GetProperty().password.Get())
827 InitEncrypt(&iaUser->ctx, (*user)->GetProperty().password.Get());
828 iaUser->password = (*user)->GetProperty().password.Get();
832 Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
834 char packetName[IA_MAX_TYPE_LEN];
835 strncpy(packetName, buff + 4, IA_MAX_TYPE_LEN);
836 packetName[IA_MAX_TYPE_LEN - 1] = 0;
838 map<string, int>::iterator pi;
839 pi = packetTypes.find(packetName);
840 if (pi == packetTypes.end())
842 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
843 printfd(__FILE__, "Login or password is wrong!\n");
844 WriteServLog("User's connect failed. IP \'%s\'. Wrong login or password", inet_ntostring(sip).c_str());
852 if ((*user)->GetProperty().disabled.Get())
854 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
858 if ((*user)->GetProperty().passive.Get())
860 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
864 if ((*user)->GetAuthorized() && (*user)->GetCurrIP() != sip)
866 printfd(__FILE__, "Login %s already in use. IP \'%s\'\n", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
867 WriteServLog("Login %s already in use. IP \'%s\'", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
868 SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
873 if (users->FindByIPIdx(sip, &u) == 0 && u->GetLogin() != (*user)->GetLogin())
875 printfd(__FILE__, "IP address already in use. IP \'%s\'", inet_ntostring(sip).c_str());
876 WriteServLog("IP address already in use. IP \'%s\'", inet_ntostring(sip).c_str());
877 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
881 // ôÅÐÅÒØ ÍÙ ÄÏÌÖÎÙ ÐÒÏ×ÅÒÉÔØ, ÍÏÖÅÔ ÌÉ ÐÏÌØÚÏ×ÁÔÅÌØ ÐÏÄËÌÀÞÉÔÓÑ Ó ÜÔÏÇÏ ÁÄÒÅÓÁ.
882 int ipFound = (*user)->GetProperty().ips.Get().IsIPInIPS(sip);
885 printfd(__FILE__, "User %s. IP address is incorrect. IP \'%s\'\n", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
886 WriteServLog("User %s. IP address is incorrect. IP \'%s\'", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
887 SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
899 connSyn6 = (CONN_SYN_6*)(buff - offset);
900 ret = Process_CONN_SYN_6(connSyn6, &(it->second), sip);
903 connSyn7 = (CONN_SYN_7*)(buff - offset);
904 ret = Process_CONN_SYN_7(connSyn7, &(it->second), sip);
907 connSyn8 = (CONN_SYN_8*)(buff - offset);
908 ret = Process_CONN_SYN_8(connSyn8, &(it->second), sip);
919 Send_CONN_SYN_ACK_6(iaUser, sip);
922 Send_CONN_SYN_ACK_7(iaUser, sip);
925 Send_CONN_SYN_ACK_8(iaUser, sip);
931 connAck = (CONN_ACK_6*)(buff - offset);
935 ret = Process_CONN_ACK_6(connAck, iaUser, sip);
938 ret = Process_CONN_ACK_7(connAck, iaUser, sip);
941 ret = Process_CONN_ACK_8((CONN_ACK_8*)(buff - offset), iaUser, sip);
947 SendError(sip, sport, protoVer, errorStr);
954 Send_ALIVE_SYN_6(iaUser, sip);
957 Send_ALIVE_SYN_7(iaUser, sip);
960 Send_ALIVE_SYN_8(iaUser, sip);
966 // ðÒÉÂÙÌ ÏÔ×ÅÔ Ó ÐÏÄÔ×ÅÒÖÄÅÎÉÅÍ ALIVE
968 aliveAck = (ALIVE_ACK_6*)(buff - offset);
972 ret = Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
975 ret = Process_ALIVE_ACK_7(aliveAck, iaUser, sip);
978 ret = Process_ALIVE_ACK_8((ALIVE_ACK_8*)(buff - offset), iaUser, sip);
983 // úÁÐÒÏÓ ÎÁ ÏÔËÌÀÞÅÎÉÅ
986 disconnSyn = (DISCONN_SYN_6*)(buff - offset);
990 ret = Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
993 ret = Process_DISCONN_SYN_7(disconnSyn, iaUser, sip);
996 ret = Process_DISCONN_SYN_8((DISCONN_SYN_8*)(buff - offset), iaUser, sip);
1006 Send_DISCONN_SYN_ACK_6(iaUser, sip);
1009 Send_DISCONN_SYN_ACK_7(iaUser, sip);
1012 Send_DISCONN_SYN_ACK_8(iaUser, sip);
1018 disconnAck = (DISCONN_ACK_6*)(buff - offset);
1023 ret = Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1026 ret = Process_DISCONN_ACK_7(disconnAck, iaUser, sip, it);
1029 ret = Process_DISCONN_ACK_8((DISCONN_ACK_8*)(buff - offset), iaUser, sip, it);
1036 Send_FIN_6(iaUser, sip, it);
1039 Send_FIN_7(iaUser, sip, it);
1042 Send_FIN_8(iaUser, sip, it);
1050 //-----------------------------------------------------------------------------
1051 void AUTH_IA::DelUser(USER_PTR u)
1053 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1055 uint32_t ip = u->GetCurrIP();
1060 map<uint32_t, IA_USER>::iterator it;
1061 it = ip2user.find(ip);
1062 if (it == ip2user.end())
1065 printfd(__FILE__, "Nothing to delete\n");
1069 if (it->second.user == u)
1071 printfd(__FILE__, "User removed!\n");
1072 it->second.user->Unauthorize(this);
1076 //-----------------------------------------------------------------------------
1077 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
1079 struct sockaddr_in sendAddr;
1086 memset(&err, 0, sizeof(ERR));
1088 sendAddr.sin_family = AF_INET;
1089 sendAddr.sin_port = htons(port);
1091 sendAddr.sin_addr.s_addr = ip;// IP ÐÏÌØÚÏ×ÁÔÅÌÑ
1094 strncpy((char*)err.type, "ERR", 16);
1095 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1101 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1102 printfd(__FILE__, "SendError %d bytes sent\n", res);
1107 memset(&err8, 0, sizeof(ERR_8));
1109 sendAddr.sin_family = AF_INET;
1110 sendAddr.sin_port = htons(port);
1112 sendAddr.sin_addr.s_addr = ip;// IP ÐÏÌØÚÏ×ÁÔÅÌÑ
1115 strncpy((char*)err8.type, "ERR", 16);
1116 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1119 SwapBytes(err8.len);
1122 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1123 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1129 //-----------------------------------------------------------------------------
1130 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
1132 struct sockaddr_in sendAddr;
1135 sendAddr.sin_family = AF_INET;
1136 sendAddr.sin_port = htons(port);
1137 sendAddr.sin_addr.s_addr = ip;
1139 res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1141 static struct timeval tv;
1142 gettimeofday(&tv, NULL);
1146 //-----------------------------------------------------------------------------
1147 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1149 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1151 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1153 map<uint32_t, IA_USER>::iterator it;
1154 it = ip2user.find(ip);
1155 if (it == ip2user.end())
1157 errorStr = "Unknown user.";
1160 it->second.messagesToSend.push_back(msg);
1163 //-----------------------------------------------------------------------------
1164 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1166 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.user->GetLogin().c_str());
1171 memset(&info, 0, sizeof(INFO_6));
1174 strncpy((char*)info.type, "INFO", 16);
1175 info.infoType = 'I';
1176 strncpy((char*)info.text, msg.text.c_str(), 235);
1179 size_t len = info.len;
1181 SwapBytes(info.len);
1184 memcpy(buffer, &info, sizeof(INFO_6));
1185 Encrypt(&user.ctx, buffer, buffer, len / 8);
1186 Send(ip, iaSettings.GetUserPort(), buffer, len);
1190 //-----------------------------------------------------------------------------
1191 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1193 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.user->GetLogin().c_str());
1198 memset(&info, 0, sizeof(INFO_7));
1201 strncpy((char*)info.type, "INFO_7", 16);
1202 info.infoType = msg.header.type;
1203 info.showTime = msg.header.showTime;
1205 info.sendTime = msg.header.creationTime;
1207 size_t len = info.len;
1209 SwapBytes(info.len);
1210 SwapBytes(info.sendTime);
1213 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1214 info.text[MAX_MSG_LEN - 1] = 0;
1216 memcpy(buffer, &info, sizeof(INFO_7));
1218 Encrypt(&user.ctx, buffer, buffer, len / 8);
1219 Send(ip, iaSettings.GetUserPort(), buffer, len);
1223 //-----------------------------------------------------------------------------
1224 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1226 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.user->GetLogin().c_str());
1229 memset(buffer, 0, sizeof(buffer));
1233 memset(&info, 0, sizeof(INFO_8));
1236 strncpy((char*)info.type, "INFO_8", 16);
1237 info.infoType = msg.header.type;
1238 info.showTime = msg.header.showTime;
1239 info.sendTime = msg.header.creationTime;
1241 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1242 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1244 size_t len = info.len;
1246 SwapBytes(info.len);
1247 SwapBytes(info.sendTime);
1250 memcpy(buffer, &info, sizeof(INFO_8));
1252 Encrypt(&user.ctx, buffer, buffer, len / 8);
1253 Send(ip, user.port, buffer, len);
1257 //-----------------------------------------------------------------------------
1258 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1260 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1263 enabledDirs = 0xFFffFFff;
1265 iaUser->phase.SetPhase2();
1266 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1269 //-----------------------------------------------------------------------------
1270 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1272 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1274 //-----------------------------------------------------------------------------
1275 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1278 SwapBytes(connSyn->dirs);
1280 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, sip);
1281 enabledDirs = connSyn->dirs;
1284 //-----------------------------------------------------------------------------
1285 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1288 SwapBytes(connAck->len);
1289 SwapBytes(connAck->rnd);
1291 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1292 // ÕÓÔÁÎÏ×ÉÔØ ÎÏ×ÕÀ ÆÁÚÕ É ×ÒÅÍÑ É ÒÁÚÒÅÛÉÔØ ÉÎÅÔ
1293 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1295 iaUser->phase.UpdateTime();
1297 iaUser->lastSendAlive = iaUser->phase.GetTime();
1298 if (iaUser->user->Authorize(sip, enabledDirs, this) == 0)
1300 iaUser->phase.SetPhase3();
1301 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1306 errorStr = iaUser->user->GetStrError();
1307 iaUser->phase.SetPhase1();
1308 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1312 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1315 //-----------------------------------------------------------------------------
1316 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1318 return Process_CONN_ACK_6(connAck, iaUser, sip);
1320 //-----------------------------------------------------------------------------
1321 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1324 SwapBytes(connAck->len);
1325 SwapBytes(connAck->rnd);
1327 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1329 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1331 iaUser->phase.UpdateTime();
1332 iaUser->lastSendAlive = iaUser->phase.GetTime();
1333 if (iaUser->user->Authorize(sip, enabledDirs, this) == 0)
1335 iaUser->phase.SetPhase3();
1336 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1341 errorStr = iaUser->user->GetStrError();
1342 iaUser->phase.SetPhase1();
1343 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1347 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1350 //-----------------------------------------------------------------------------
1351 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1354 SwapBytes(aliveAck->len);
1355 SwapBytes(aliveAck->rnd);
1357 printfd(__FILE__, "ALIVE_ACK_6\n");
1358 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1360 iaUser->phase.UpdateTime();
1362 iaUser->aliveSent = false;
1367 //-----------------------------------------------------------------------------
1368 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1370 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1372 //-----------------------------------------------------------------------------
1373 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1376 SwapBytes(aliveAck->len);
1377 SwapBytes(aliveAck->rnd);
1379 printfd(__FILE__, "ALIVE_ACK_8\n");
1380 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1382 iaUser->phase.UpdateTime();
1384 iaUser->aliveSent = false;
1389 //-----------------------------------------------------------------------------
1390 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1392 printfd(__FILE__, "DISCONN_SYN_6\n");
1393 if (iaUser->phase.GetPhase() != 3)
1395 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1396 errorStr = "Incorrect request DISCONN_SYN";
1400 iaUser->phase.SetPhase4();
1401 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1405 //-----------------------------------------------------------------------------
1406 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1408 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1410 //-----------------------------------------------------------------------------
1411 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t)
1413 if (iaUser->phase.GetPhase() != 3)
1415 errorStr = "Incorrect request DISCONN_SYN";
1416 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1420 iaUser->phase.SetPhase4();
1421 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1425 //-----------------------------------------------------------------------------
1426 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1429 map<uint32_t, IA_USER>::iterator)
1432 SwapBytes(disconnAck->len);
1433 SwapBytes(disconnAck->rnd);
1435 printfd(__FILE__, "DISCONN_ACK_6\n");
1436 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1438 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1444 //-----------------------------------------------------------------------------
1445 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1447 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1449 //-----------------------------------------------------------------------------
1450 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, map<uint32_t, IA_USER>::iterator)
1453 SwapBytes(disconnAck->len);
1454 SwapBytes(disconnAck->rnd);
1456 printfd(__FILE__, "DISCONN_ACK_8\n");
1457 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1459 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1465 //-----------------------------------------------------------------------------
1466 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1468 //+++ Fill static data in connSynAck +++
1469 // TODO Move this code. It must be executed only once
1470 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1471 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1472 for (int j = 0; j < DIR_NUM; j++)
1474 strncpy((char*)connSynAck6.dirName[j],
1475 stgSettings->GetDirName(j).c_str(),
1478 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1480 //--- Fill static data in connSynAck ---
1482 iaUser->rnd = random();
1483 connSynAck6.rnd = iaUser->rnd;
1485 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1486 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1489 SwapBytes(connSynAck6.len);
1490 SwapBytes(connSynAck6.rnd);
1491 SwapBytes(connSynAck6.userTimeOut);
1492 SwapBytes(connSynAck6.aliveDelay);
1495 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1496 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1498 //-----------------------------------------------------------------------------
1499 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1501 return Send_CONN_SYN_ACK_6(iaUser, sip);
1503 //-----------------------------------------------------------------------------
1504 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1506 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1507 connSynAck8.hdr.protoVer[0] = 0;
1508 connSynAck8.hdr.protoVer[1] = 8;
1510 //+++ Fill static data in connSynAck +++
1511 // TODO Move this code. It must be executed only once
1512 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1513 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1514 for (int j = 0; j < DIR_NUM; j++)
1516 strncpy((char*)connSynAck8.dirName[j],
1517 stgSettings->GetDirName(j).c_str(),
1520 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1522 //--- Fill static data in connSynAck ---
1524 iaUser->rnd = random();
1525 connSynAck8.rnd = iaUser->rnd;
1527 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1528 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1531 SwapBytes(connSynAck8.len);
1532 SwapBytes(connSynAck8.rnd);
1533 SwapBytes(connSynAck8.userTimeOut);
1534 SwapBytes(connSynAck8.aliveDelay);
1537 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1538 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1539 //return Send(sip, iaUser->port, (char*)&connSynAck8, 384);
1541 //-----------------------------------------------------------------------------
1542 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1544 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1545 aliveSyn6.rnd = iaUser->rnd = random();
1547 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1549 for (int i = 0; i < DIR_NUM; i++)
1551 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1552 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1554 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1555 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1559 int dn = iaSettings.GetFreeMbShowType();
1560 const TARIFF * tf = iaUser->user->GetTariff();
1564 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1571 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1575 double fmb = iaUser->user->GetProperty().freeMb;
1576 fmb = fmb < 0 ? 0 : fmb;
1577 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1582 if (freeMbNone == iaSettings.GetFreeMbShowType())
1584 aliveSyn6.freeMb[0] = 0;
1588 double fmb = iaUser->user->GetProperty().freeMb;
1589 fmb = fmb < 0 ? 0 : fmb;
1590 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1595 if (iaUser->aliveSent)
1597 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->user->GetLogin().c_str());
1599 iaUser->aliveSent = true;
1602 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1603 if (!stgSettings->GetShowFeeInCash())
1604 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1607 SwapBytes(aliveSyn6.len);
1608 SwapBytes(aliveSyn6.rnd);
1609 SwapBytes(aliveSyn6.cash);
1610 for (int i = 0; i < DIR_NUM; ++i)
1612 SwapBytes(aliveSyn6.mu[i]);
1613 SwapBytes(aliveSyn6.md[i]);
1614 SwapBytes(aliveSyn6.su[i]);
1615 SwapBytes(aliveSyn6.sd[i]);
1619 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1620 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1622 //-----------------------------------------------------------------------------
1623 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1625 return Send_ALIVE_SYN_6(iaUser, sip);
1627 //-----------------------------------------------------------------------------
1628 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1630 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1631 aliveSyn8.hdr.protoVer[0] = 0;
1632 aliveSyn8.hdr.protoVer[1] = 8;
1634 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1635 aliveSyn8.rnd = iaUser->rnd = random();
1637 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1639 for (int i = 0; i < DIR_NUM; i++)
1641 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1642 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1644 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1645 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1649 int dn = iaSettings.GetFreeMbShowType();
1653 const TARIFF * tf = iaUser->user->GetTariff();
1654 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1661 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1665 double fmb = iaUser->user->GetProperty().freeMb;
1666 fmb = fmb < 0 ? 0 : fmb;
1667 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1672 if (freeMbNone == iaSettings.GetFreeMbShowType())
1674 aliveSyn8.freeMb[0] = 0;
1678 double fmb = iaUser->user->GetProperty().freeMb;
1679 fmb = fmb < 0 ? 0 : fmb;
1680 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1685 if (iaUser->aliveSent)
1687 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1689 iaUser->aliveSent = true;
1692 const TARIFF * tf = iaUser->user->GetTariff();
1694 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1695 if (!stgSettings->GetShowFeeInCash())
1696 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1699 SwapBytes(aliveSyn8.len);
1700 SwapBytes(aliveSyn8.rnd);
1701 SwapBytes(aliveSyn8.cash);
1702 SwapBytes(aliveSyn8.status);
1703 for (int i = 0; i < DIR_NUM; ++i)
1705 SwapBytes(aliveSyn8.mu[i]);
1706 SwapBytes(aliveSyn8.md[i]);
1707 SwapBytes(aliveSyn8.su[i]);
1708 SwapBytes(aliveSyn8.sd[i]);
1712 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1713 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1715 //-----------------------------------------------------------------------------
1716 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1718 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1719 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1720 disconnSynAck6.rnd = iaUser->rnd = random();
1723 SwapBytes(disconnSynAck6.len);
1724 SwapBytes(disconnSynAck6.rnd);
1727 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1728 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1730 //-----------------------------------------------------------------------------
1731 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1733 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1735 //-----------------------------------------------------------------------------
1736 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1738 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1739 disconnSynAck8.hdr.protoVer[0] = 0;
1740 disconnSynAck8.hdr.protoVer[1] = 8;
1742 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1743 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1744 disconnSynAck8.rnd = iaUser->rnd = random();
1747 SwapBytes(disconnSynAck8.len);
1748 SwapBytes(disconnSynAck8.rnd);
1751 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1752 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1754 //-----------------------------------------------------------------------------
1755 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1757 fin6.len = Min8(sizeof(FIN_6));
1758 strcpy((char*)fin6.type, "FIN");
1759 strcpy((char*)fin6.ok, "OK");
1762 SwapBytes(fin6.len);
1765 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1767 iaUser->user->Unauthorize(this);
1769 int ret = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1773 //-----------------------------------------------------------------------------
1774 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1776 return Send_FIN_6(iaUser, sip, it);
1778 //-----------------------------------------------------------------------------
1779 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1781 strcpy((char*)fin8.hdr.magic, IA_ID);
1782 fin8.hdr.protoVer[0] = 0;
1783 fin8.hdr.protoVer[1] = 8;
1785 fin8.len = Min8(sizeof(FIN_8));
1786 strcpy((char*)fin8.type, "FIN");
1787 strcpy((char*)fin8.ok, "OK");
1790 SwapBytes(fin8.len);
1793 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1795 iaUser->user->Unauthorize(this);
1797 int ret = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1801 //-----------------------------------------------------------------------------
1802 bool AUTH_IA::WaitPackets(int sd) const
1810 tv.tv_usec = 500000;
1812 int res = select(sd + 1, &rfds, NULL, NULL, &tv);
1813 if (res == -1) // Error
1817 printfd(__FILE__, "Error on select: '%s'\n", strerror(errno));
1822 if (res == 0) // Timeout
1829 //-----------------------------------------------------------------------------
1831 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
1833 unsigned char keyL[PASSWD_LEN]; // ðÁÒÏÌØ ÄÌÑ ÛÉÆÒÏ×ËÉ
1834 memset(keyL, 0, PASSWD_LEN);
1835 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1836 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1838 //-----------------------------------------------------------------------------
1840 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1842 // len8 - ÄÌÉÎÁ × 8-ÍÉ ÂÁÊÔÏ×ÙÈ ÂÌÏËÁÈ
1844 for (int i = 0; i < len8; i++)
1845 DecodeString(dst + i * 8, src + i * 8, ctx);
1847 //-----------------------------------------------------------------------------
1849 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1851 // len8 - ÄÌÉÎÁ × 8-ÍÉ ÂÁÊÔÏ×ÙÈ ÂÌÏËÁÈ
1853 for (int i = 0; i < len8; i++)
1854 EncodeString(dst + i * 8, src + i * 8, ctx);