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>
36 #include <cstdio> // snprintf
40 #include "inetaccess.h"
43 extern volatile const time_t stgTime;
45 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password);
46 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
47 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
49 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
71 //-----------------------------------------------------------------------------
72 //-----------------------------------------------------------------------------
74 //-----------------------------------------------------------------------------
75 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
77 BASE_PLUGIN * GetPlugin()
79 return iac.GetPlugin();
81 //-----------------------------------------------------------------------------
82 //-----------------------------------------------------------------------------
83 //-----------------------------------------------------------------------------
84 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
88 freeMbShowType(freeMbCash)
91 //-----------------------------------------------------------------------------
92 int AUTH_IA_SETTINGS::ParseIntInRange(const string & str, int min, int max, int * val)
94 if (str2x(str.c_str(), *val))
96 errorStr = "Incorrect value \'" + str + "\'.";
99 if (*val < min || *val > max)
101 errorStr = "Value \'" + str + "\' out of range.";
106 //-----------------------------------------------------------------------------
107 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
111 vector<PARAM_VALUE>::const_iterator pvi;
112 ///////////////////////////
114 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
115 if (pvi == s.moduleParams.end())
117 errorStr = "Parameter \'Port\' not found.";
118 printfd(__FILE__, "Parameter 'Port' not found\n");
121 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
123 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
124 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
128 ///////////////////////////
129 pv.param = "UserDelay";
130 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
131 if (pvi == s.moduleParams.end())
133 errorStr = "Parameter \'UserDelay\' not found.";
134 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
138 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
140 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
141 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
144 ///////////////////////////
145 pv.param = "UserTimeout";
146 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
147 if (pvi == s.moduleParams.end())
149 errorStr = "Parameter \'UserTimeout\' not found.";
150 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
154 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
156 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
157 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
160 /////////////////////////////////////////////////////////////
164 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
165 if (pvi == s.moduleParams.end())
167 errorStr = "Parameter \'FreeMb\' not found.";
168 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
171 freeMbType = pvi->value[0];
173 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
175 freeMbShowType = freeMbCash;
177 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
179 freeMbShowType = freeMbNone;
181 else if (!str2x(freeMbType.c_str(), n))
183 if (n < 0 || n >= DIR_NUM)
185 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
186 printfd(__FILE__, "%s\n", errorStr.c_str());
189 freeMbShowType = (FREEMB)(freeMb0 + n);
193 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
194 printfd(__FILE__, "%s\n", errorStr.c_str());
197 /////////////////////////////////////////////////////////////
200 //-----------------------------------------------------------------------------
201 //-----------------------------------------------------------------------------
202 //-----------------------------------------------------------------------------
203 #ifdef IA_PHASE_DEBUG
208 gettimeofday(&phaseTime, NULL);
214 gettimeofday(&phaseTime, NULL);
217 //-----------------------------------------------------------------------------
218 IA_PHASE::~IA_PHASE()
220 #ifdef IA_PHASE_DEBUG
221 flog = fopen(log.c_str(), "at");
224 fprintf(flog, "IA %s D\n", login.c_str());
229 //-----------------------------------------------------------------------------
230 #ifdef IA_PHASE_DEBUG
231 void IA_PHASE::SetLogFileName(const string & logFileName)
233 log = logFileName + ".ia.log";
235 //-----------------------------------------------------------------------------
236 void IA_PHASE::SetUserLogin(const string & login)
238 IA_PHASE::login = login;
240 //-----------------------------------------------------------------------------
241 void IA_PHASE::WritePhaseChange(int newPhase)
244 gettimeofday(&newPhaseTime, NULL);
245 flog = fopen(log.c_str(), "at");
246 /*int64_t tn = newPhaseTime.GetSec()*1000000 + newPhaseTime.GetUSec();
247 int64_t to = phaseTime.GetSec()*1000000 + phaseTime.GetUSec();*/
250 string action = newPhase == phase ? "U" : "C";
251 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
252 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
253 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
263 //-----------------------------------------------------------------------------
264 void IA_PHASE::SetPhase1()
266 #ifdef IA_PHASE_DEBUG
270 gettimeofday(&phaseTime, NULL);
272 //-----------------------------------------------------------------------------
273 void IA_PHASE::SetPhase2()
275 #ifdef IA_PHASE_DEBUG
279 gettimeofday(&phaseTime, NULL);
281 //-----------------------------------------------------------------------------
282 void IA_PHASE::SetPhase3()
284 #ifdef IA_PHASE_DEBUG
288 gettimeofday(&phaseTime, NULL);
290 //-----------------------------------------------------------------------------
291 void IA_PHASE::SetPhase4()
293 #ifdef IA_PHASE_DEBUG
297 gettimeofday(&phaseTime, NULL);
299 //-----------------------------------------------------------------------------
300 void IA_PHASE::SetPhase5()
302 #ifdef IA_PHASE_DEBUG
306 gettimeofday(&phaseTime, NULL);
308 //-----------------------------------------------------------------------------
309 int IA_PHASE::GetPhase() const
313 //-----------------------------------------------------------------------------
314 void IA_PHASE::UpdateTime()
316 #ifdef IA_PHASE_DEBUG
317 WritePhaseChange(phase);
319 gettimeofday(&phaseTime, NULL);
321 //-----------------------------------------------------------------------------
322 const UTIME & IA_PHASE::GetTime() const
326 //-----------------------------------------------------------------------------
327 //-----------------------------------------------------------------------------
328 //-----------------------------------------------------------------------------
332 isRunningRunTimeouter(false),
336 WriteServLog(GetStgLogger()),
337 enabledDirs(0xFFffFFff),
338 onDelUserNotifier(*this)
340 InitEncrypt(&ctxS, "pr7Hhen");
342 pthread_mutexattr_t attr;
343 pthread_mutexattr_init(&attr);
344 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
345 pthread_mutex_init(&mutex, &attr);
347 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
348 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
349 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
350 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
351 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
352 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
353 memset(&fin6, 0, sizeof(FIN_6));
354 memset(&fin8, 0, sizeof(FIN_8));
356 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
357 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
358 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
359 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
360 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
361 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
362 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
363 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
364 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
365 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
366 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
367 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
368 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
369 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
370 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
371 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
372 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
373 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
375 packetTypes["CONN_SYN"] = CONN_SYN_N;
376 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
377 packetTypes["CONN_ACK"] = CONN_ACK_N;
378 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
379 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
380 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
381 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
382 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
383 packetTypes["FIN"] = FIN_N;
384 packetTypes["ERR"] = ERROR_N;
386 //-----------------------------------------------------------------------------
389 pthread_mutex_destroy(&mutex);
391 //-----------------------------------------------------------------------------
394 users->AddNotifierUserDel(&onDelUserNotifier);
404 if (pthread_create(&recvThread, NULL, Run, this))
406 errorStr = "Cannot create thread.";
407 printfd(__FILE__, "Cannot create recv thread\n");
412 if (!isRunningRunTimeouter)
414 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
416 errorStr = "Cannot create thread.";
417 printfd(__FILE__, "Cannot create timeouter thread\n");
424 //-----------------------------------------------------------------------------
435 UnauthorizeUser(this)
440 //5 seconds to thread stops itself
441 for (int i = 0; i < 25 && isRunningRun; i++)
446 //after 5 seconds waiting thread still running. now killing it
449 //TODO pthread_cancel()
450 if (pthread_kill(recvThread, SIGINT))
452 errorStr = "Cannot kill thread.";
453 printfd(__FILE__, "Cannot kill thread\n");
456 for (int i = 0; i < 25 && isRunningRun; ++i)
460 printfd(__FILE__, "Failed to stop recv thread\n");
464 pthread_join(recvThread, NULL);
466 printfd(__FILE__, "AUTH_IA killed Run\n");
472 if (isRunningRunTimeouter)
474 //5 seconds to thread stops itself
475 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
480 //after 5 seconds waiting thread still running. now killing it
481 if (isRunningRunTimeouter)
483 //TODO pthread_cancel()
484 if (pthread_kill(timeouterThread, SIGINT))
486 errorStr = "Cannot kill thread.";
489 for (int i = 0; i < 25 && isRunningRunTimeouter; ++i)
491 if (isRunningRunTimeouter)
493 printfd(__FILE__, "Failed to stop timeouter thread\n");
497 pthread_join(timeouterThread, NULL);
499 printfd(__FILE__, "AUTH_IA killed Timeouter\n");
502 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
503 users->DelNotifierUserDel(&onDelUserNotifier);
506 //-----------------------------------------------------------------------------
507 void * AUTH_IA::Run(void * d)
509 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
511 ia->isRunningRun = true;
515 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
519 ia->RecvData(buffer, sizeof(buffer));
520 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
523 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
524 TouchFile(monFile.c_str());
528 ia->isRunningRun = false;
531 //-----------------------------------------------------------------------------
532 void * AUTH_IA::RunTimeouter(void * d)
534 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
536 ia->isRunningRunTimeouter = true;
539 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
544 // TODO cahange counter to timer and MONITOR_TIME_DELAY_SEC
545 if (++a % (50*60) == 0 && ia->stgSettings->GetMonitoring())
547 TouchFile(monFile.c_str());
551 ia->isRunningRunTimeouter = false;
554 //-----------------------------------------------------------------------------
555 int AUTH_IA::ParseSettings()
557 int ret = iaSettings.ParseSettings(settings);
559 errorStr = iaSettings.GetStrError();
562 //-----------------------------------------------------------------------------
563 int AUTH_IA::PrepareNet()
565 struct sockaddr_in listenAddr;
567 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
569 if (listenSocket < 0)
571 errorStr = "Cannot create socket.";
575 listenAddr.sin_family = AF_INET;
576 listenAddr.sin_port = htons(iaSettings.GetUserPort());
577 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
579 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
581 errorStr = "AUTH_IA: Bind failed.";
586 if (getsockopt(listenSocket, SOL_SOCKET, SO_SNDBUF, &buffLen, sizeof(buffLen)) < 0)
589 errorStr = "Getsockopt failed. " + string(strerror(errno));
593 //WriteServLog("buffLen = %d", buffLen);
597 //-----------------------------------------------------------------------------
598 int AUTH_IA::FinalizeNet()
603 //-----------------------------------------------------------------------------
604 int AUTH_IA::RecvData(char * buffer, int bufferSize)
606 if (!WaitPackets(listenSocket)) // Timeout
611 struct sockaddr_in outerAddr;
612 socklen_t outerAddrLen(sizeof(outerAddr));
613 int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
620 if (dataLen <= 0) // Error
624 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
634 if (CheckHeader(buffer, &protoVer))
637 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
638 memset(login, 0, PASSWD_LEN);
640 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
642 uint32_t sip = *((uint32_t*)&outerAddr.sin_addr);
643 uint16_t sport = htons(outerAddr.sin_port);
646 if (users->FindByName(login, &user) == 0)
648 printfd(__FILE__, "User %s FOUND!\n", user->GetLogin().c_str());
649 PacketProcessor(buffer, dataLen, sip, sport, protoVer, &user);
653 WriteServLog("User\'s connect failed:: user \'%s\' not found. IP \'%s\'",
655 inet_ntostring(sip).c_str());
656 printfd(__FILE__, "User %s NOT found!\n", login);
657 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
663 //-----------------------------------------------------------------------------
664 int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
666 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
668 //SendError(userIP, updateMsg);
669 printfd(__FILE__, "update needed - IA_ID\n");
670 //SendError(userIP, "Incorrect header!");
674 if (buffer[6] != 0) //proto[0] shoud be 0
676 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
677 //SendError(userIP, updateMsg);
684 //SendError(userIP, updateMsg);
685 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
690 *protoVer = buffer[7];
694 //-----------------------------------------------------------------------------
695 int AUTH_IA::Timeouter()
697 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
699 map<uint32_t, IA_USER>::iterator it;
700 it = ip2user.begin();
703 while (it != ip2user.end())
707 static UTIME currTime;
708 gettimeofday(&currTime, NULL);
710 if ((it->second.phase.GetPhase() == 2)
711 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
713 it->second.phase.SetPhase1();
714 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
717 if (it->second.phase.GetPhase() == 3)
719 if (!it->second.messagesToSend.empty())
721 if (it->second.protoVer == 6)
722 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
724 if (it->second.protoVer == 7)
725 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
727 if (it->second.protoVer == 8)
728 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
730 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
733 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
735 switch (it->second.protoVer)
738 Send_ALIVE_SYN_6(&(it->second), sip);
741 Send_ALIVE_SYN_7(&(it->second), sip);
744 Send_ALIVE_SYN_8(&(it->second), sip);
748 gettimeofday(&it->second.lastSendAlive, NULL);
751 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
753 it->second.user->Unauthorize(this);
759 if ((it->second.phase.GetPhase() == 4)
760 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
762 it->second.phase.SetPhase3();
763 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
771 //-----------------------------------------------------------------------------
772 int AUTH_IA::PacketProcessor(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, user_iter * user)
774 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
775 // ôÕÔ ÓÏÂÒÁÎÙ ÏÂÒÁÂÏÔÞÉËÉ ÒÁÚÎÙÈ ÐÁËÅÔÏ×
777 const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
779 IA_USER * iaUser = NULL;
781 CONN_SYN_6 * connSyn6;
782 CONN_SYN_7 * connSyn7;
783 CONN_SYN_8 * connSyn8;
785 CONN_ACK_6 * connAck;
786 ALIVE_ACK_6 * aliveAck;
787 DISCONN_SYN_6 * disconnSyn;
788 DISCONN_ACK_6 * disconnAck;
790 map<uint32_t, IA_USER>::iterator it;
791 it = ip2user.find(sip);
793 if (it == ip2user.end() || (*user)->GetID() != it->second.user->GetID())
795 // åÝÅ ÎÅ ÂÙÌÏ ÚÁÐÒÏÓÏ× Ó ÜÔÏÇÏ IP
796 printfd(__FILE__, "Add new user\n");
797 ip2user[sip].protoVer = protoVer;
798 ip2user[sip].user = *user;
799 ip2user[sip].port = sport;
800 #ifdef IA_PHASE_DEBUG
801 ip2user[sip].phase.SetLogFileName(stgSettings->GetLogFileName());
802 ip2user[sip].phase.SetUserLogin((*user)->GetLogin());
806 it = ip2user.find(sip); //TODO
807 if (it == ip2user.end())
809 printfd(__FILE__, "+++ ERROR +++\n");
814 iaUser = &(it->second);
816 if (iaUser->port != sport)
817 iaUser->port = sport;
819 if (iaUser->password != (*user)->property.password.Get())
821 InitEncrypt(&iaUser->ctx, (*user)->property.password.Get());
822 iaUser->password = (*user)->property.password.Get();
826 Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
828 char packetName[IA_MAX_TYPE_LEN];
829 strncpy(packetName, buff + 4, IA_MAX_TYPE_LEN);
830 packetName[IA_MAX_TYPE_LEN - 1] = 0;
832 map<string, int>::iterator pi;
833 pi = packetTypes.find(packetName);
834 if (pi == packetTypes.end())
836 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
837 printfd(__FILE__, "Login or password is wrong!\n");
838 WriteServLog("User's connect failed. IP \'%s\'. Wrong login or password", inet_ntostring(sip).c_str());
846 if ((*user)->property.disabled.Get())
848 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
852 if ((*user)->property.passive.Get())
854 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
858 if ((*user)->GetAuthorized() && (*user)->GetCurrIP() != sip)
860 printfd(__FILE__, "Login %s alredy in use. IP \'%s\'\n", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
861 WriteServLog("Login %s alredy in use. IP \'%s\'", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
862 SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
867 if (users->FindByIPIdx(sip, &u) == 0 && u->GetLogin() != (*user)->GetLogin())
869 printfd(__FILE__, "IP address alredy in use. IP \'%s\'", inet_ntostring(sip).c_str());
870 WriteServLog("IP address alredy in use. IP \'%s\'", inet_ntostring(sip).c_str());
871 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
875 // ôÅÐÅÒØ ÍÙ ÄÏÌÖÎÙ ÐÒÏ×ÅÒÉÔØ, ÍÏÖÅÔ ÌÉ ÐÏÌØÚÏ×ÁÔÅÌØ ÐÏÄËÌÀÞÉÔÓÑ Ó ÜÔÏÇÏ ÁÄÒÅÓÁ.
876 int ipFound = (*user)->property.ips.Get().IsIPInIPS(sip);
879 printfd(__FILE__, "User %s. IP address is incorrect. IP \'%s\'\n", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
880 WriteServLog("User %s. IP address is incorrect. IP \'%s\'", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
881 SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
893 connSyn6 = (CONN_SYN_6*)(buff - offset);
894 ret = Process_CONN_SYN_6(connSyn6, &(it->second), user, sip);
897 connSyn7 = (CONN_SYN_7*)(buff - offset);
898 ret = Process_CONN_SYN_7(connSyn7, &(it->second), user, sip);
901 connSyn8 = (CONN_SYN_8*)(buff - offset);
902 ret = Process_CONN_SYN_8(connSyn8, &(it->second), user, sip);
913 Send_CONN_SYN_ACK_6(iaUser, user, sip);
916 Send_CONN_SYN_ACK_7(iaUser, user, sip);
919 Send_CONN_SYN_ACK_8(iaUser, user, sip);
925 connAck = (CONN_ACK_6*)(buff - offset);
929 ret = Process_CONN_ACK_6(connAck, iaUser, user, sip);
932 ret = Process_CONN_ACK_7(connAck, iaUser, user, sip);
935 ret = Process_CONN_ACK_8((CONN_ACK_8*)(buff - offset), iaUser, user, sip);
941 SendError(sip, sport, protoVer, errorStr);
948 Send_ALIVE_SYN_6(iaUser, sip);
951 Send_ALIVE_SYN_7(iaUser, sip);
954 Send_ALIVE_SYN_8(iaUser, sip);
960 // ðÒÉÂÙÌ ÏÔ×ÅÔ Ó ÐÏÄÔ×ÅÒÖÄÅÎÉÅÍ ALIVE
962 aliveAck = (ALIVE_ACK_6*)(buff - offset);
966 ret = Process_ALIVE_ACK_6(aliveAck, iaUser, user, sip);
969 ret = Process_ALIVE_ACK_7(aliveAck, iaUser, user, sip);
972 ret = Process_ALIVE_ACK_8((ALIVE_ACK_8*)(buff - offset), iaUser, user, sip);
977 // úÁÐÒÏÓ ÎÁ ÏÔËÌÀÞÅÎÉÅ
980 disconnSyn = (DISCONN_SYN_6*)(buff - offset);
984 ret = Process_DISCONN_SYN_6(disconnSyn, iaUser, user, sip);
987 ret = Process_DISCONN_SYN_7(disconnSyn, iaUser, user, sip);
990 ret = Process_DISCONN_SYN_8((DISCONN_SYN_8*)(buff - offset), iaUser, user, sip);
1000 Send_DISCONN_SYN_ACK_6(iaUser, sip);
1003 Send_DISCONN_SYN_ACK_7(iaUser, sip);
1006 Send_DISCONN_SYN_ACK_8(iaUser, sip);
1012 disconnAck = (DISCONN_ACK_6*)(buff - offset);
1017 ret = Process_DISCONN_ACK_6(disconnAck, iaUser, user, sip, it);
1020 ret = Process_DISCONN_ACK_7(disconnAck, iaUser, user, sip, it);
1023 ret = Process_DISCONN_ACK_8((DISCONN_ACK_8*)(buff - offset), iaUser, user, sip, it);
1030 Send_FIN_6(iaUser, sip, it);
1033 Send_FIN_7(iaUser, sip, it);
1036 Send_FIN_8(iaUser, sip, it);
1044 //-----------------------------------------------------------------------------
1045 void AUTH_IA::DelUser(user_iter u)
1047 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1049 uint32_t ip = u->GetCurrIP();
1054 map<uint32_t, IA_USER>::iterator it;
1055 it = ip2user.find(ip);
1056 if (it == ip2user.end())
1059 printfd(__FILE__, "Nothing to delete\n");
1063 if (it->second.user == u)
1065 printfd(__FILE__, "User removed!\n");
1066 it->second.user->Unauthorize(this);
1070 //-----------------------------------------------------------------------------
1071 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
1073 struct sockaddr_in sendAddr;
1080 memset(&err, 0, sizeof(ERR));
1082 sendAddr.sin_family = AF_INET;
1083 sendAddr.sin_port = htons(port);
1085 sendAddr.sin_addr.s_addr = ip;// IP ÐÏÌØÚÏ×ÁÔÅÌÑ
1088 strncpy((char*)err.type, "ERR", 16);
1089 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1095 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1096 printfd(__FILE__, "SendError %d bytes sent\n", res);
1101 memset(&err8, 0, sizeof(ERR_8));
1103 sendAddr.sin_family = AF_INET;
1104 sendAddr.sin_port = htons(port);
1106 sendAddr.sin_addr.s_addr = ip;// IP ÐÏÌØÚÏ×ÁÔÅÌÑ
1109 strncpy((char*)err8.type, "ERR", 16);
1110 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1113 SwapBytes(err8.len);
1116 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1117 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1123 //-----------------------------------------------------------------------------
1124 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
1126 struct sockaddr_in sendAddr;
1129 sendAddr.sin_family = AF_INET;
1130 sendAddr.sin_port = htons(port);
1131 sendAddr.sin_addr.s_addr = ip;
1133 res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1135 static struct timeval tv;
1136 gettimeofday(&tv, NULL);
1140 //-----------------------------------------------------------------------------
1141 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1143 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1145 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1147 map<uint32_t, IA_USER>::iterator it;
1148 it = ip2user.find(ip);
1149 if (it == ip2user.end())
1151 errorStr = "Unknown user.";
1154 it->second.messagesToSend.push_back(msg);
1157 //-----------------------------------------------------------------------------
1158 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1160 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.user->GetLogin().c_str());
1165 memset(&info, 0, sizeof(INFO_6));
1168 strncpy((char*)info.type, "INFO", 16);
1169 info.infoType = 'I';
1170 strncpy((char*)info.text, msg.text.c_str(), 235);
1173 size_t len = info.len;
1175 SwapBytes(info.len);
1178 memcpy(buffer, &info, sizeof(INFO_6));
1179 Encrypt(&user.ctx, buffer, buffer, len / 8);
1180 Send(ip, iaSettings.GetUserPort(), buffer, len);
1184 //-----------------------------------------------------------------------------
1185 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1187 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.user->GetLogin().c_str());
1192 memset(&info, 0, sizeof(INFO_7));
1195 strncpy((char*)info.type, "INFO_7", 16);
1196 info.infoType = msg.header.type;
1197 info.showTime = msg.header.showTime;
1199 info.sendTime = msg.header.creationTime;
1201 size_t len = info.len;
1203 SwapBytes(info.len);
1204 SwapBytes(info.sendTime);
1207 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1208 info.text[MAX_MSG_LEN - 1] = 0;
1210 memcpy(buffer, &info, sizeof(INFO_7));
1212 Encrypt(&user.ctx, buffer, buffer, len / 8);
1213 Send(ip, iaSettings.GetUserPort(), buffer, len);
1217 //-----------------------------------------------------------------------------
1218 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1220 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.user->GetLogin().c_str());
1223 memset(buffer, 0, sizeof(buffer));
1227 memset(&info, 0, sizeof(INFO_8));
1230 strncpy((char*)info.type, "INFO_8", 16);
1231 info.infoType = msg.header.type;
1232 info.showTime = msg.header.showTime;
1233 info.sendTime = msg.header.creationTime;
1235 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1236 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1238 size_t len = info.len;
1240 SwapBytes(info.len);
1241 SwapBytes(info.sendTime);
1244 memcpy(buffer, &info, sizeof(INFO_8));
1246 Encrypt(&user.ctx, buffer, buffer, len / 8);
1247 Send(ip, user.port, buffer, len);
1251 //-----------------------------------------------------------------------------
1252 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, user_iter *, uint32_t)
1254 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1257 enabledDirs = 0xFFffFFff;
1259 iaUser->phase.SetPhase2();
1260 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1263 //-----------------------------------------------------------------------------
1264 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, user_iter * user, uint32_t sip)
1266 return Process_CONN_SYN_6(connSyn, iaUser, user, sip);
1268 //-----------------------------------------------------------------------------
1269 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, user_iter * user, uint32_t sip)
1272 SwapBytes(connSyn->dirs);
1274 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, user, sip);
1275 enabledDirs = connSyn->dirs;
1278 //-----------------------------------------------------------------------------
1279 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, user_iter *, uint32_t sip)
1282 SwapBytes(connAck->len);
1283 SwapBytes(connAck->rnd);
1285 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1286 // ÕÓÔÁÎÏ×ÉÔØ ÎÏ×ÕÀ ÆÁÚÕ É ×ÒÅÍÑ É ÒÁÚÒÅÛÉÔØ ÉÎÅÔ
1287 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1289 iaUser->phase.UpdateTime();
1291 iaUser->lastSendAlive = iaUser->phase.GetTime();
1292 if (iaUser->user->Authorize(sip, "", enabledDirs, this) == 0)
1294 iaUser->phase.SetPhase3();
1295 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1300 errorStr = iaUser->user->GetStrError();
1301 iaUser->phase.SetPhase1();
1302 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1306 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1309 //-----------------------------------------------------------------------------
1310 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, user_iter * user, uint32_t sip)
1312 return Process_CONN_ACK_6(connAck, iaUser, user, sip);
1314 //-----------------------------------------------------------------------------
1315 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, user_iter *, uint32_t sip)
1318 SwapBytes(connAck->len);
1319 SwapBytes(connAck->rnd);
1321 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1323 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1325 iaUser->phase.UpdateTime();
1326 iaUser->lastSendAlive = iaUser->phase.GetTime();
1327 if (iaUser->user->Authorize(sip, "", enabledDirs, this) == 0)
1329 iaUser->phase.SetPhase3();
1330 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1335 errorStr = iaUser->user->GetStrError();
1336 iaUser->phase.SetPhase1();
1337 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1341 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1344 //-----------------------------------------------------------------------------
1345 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, user_iter *, uint32_t)
1348 SwapBytes(aliveAck->len);
1349 SwapBytes(aliveAck->rnd);
1351 printfd(__FILE__, "ALIVE_ACK_6\n");
1352 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1354 iaUser->phase.UpdateTime();
1356 iaUser->aliveSent = false;
1361 //-----------------------------------------------------------------------------
1362 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, user_iter * user, uint32_t sip)
1364 return Process_ALIVE_ACK_6(aliveAck, iaUser, user, sip);
1366 //-----------------------------------------------------------------------------
1367 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, user_iter *, uint32_t)
1370 SwapBytes(aliveAck->len);
1371 SwapBytes(aliveAck->rnd);
1373 printfd(__FILE__, "ALIVE_ACK_8\n");
1374 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1376 iaUser->phase.UpdateTime();
1378 iaUser->aliveSent = false;
1383 //-----------------------------------------------------------------------------
1384 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, user_iter *, uint32_t)
1386 printfd(__FILE__, "DISCONN_SYN_6\n");
1387 if (iaUser->phase.GetPhase() != 3)
1389 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1390 errorStr = "Incorrect request DISCONN_SYN";
1394 iaUser->phase.SetPhase4();
1395 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1399 //-----------------------------------------------------------------------------
1400 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, user_iter * user, uint32_t sip)
1402 return Process_DISCONN_SYN_6(disconnSyn, iaUser, user, sip);
1404 //-----------------------------------------------------------------------------
1405 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, user_iter *, uint32_t)
1407 if (iaUser->phase.GetPhase() != 3)
1409 errorStr = "Incorrect request DISCONN_SYN";
1410 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1414 iaUser->phase.SetPhase4();
1415 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1419 //-----------------------------------------------------------------------------
1420 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1424 map<uint32_t, IA_USER>::iterator)
1427 SwapBytes(disconnAck->len);
1428 SwapBytes(disconnAck->rnd);
1430 printfd(__FILE__, "DISCONN_ACK_6\n");
1431 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1433 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1439 //-----------------------------------------------------------------------------
1440 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, user_iter * user, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1442 return Process_DISCONN_ACK_6(disconnAck, iaUser, user, sip, it);
1444 //-----------------------------------------------------------------------------
1445 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, user_iter *, uint32_t, map<uint32_t, IA_USER>::iterator)
1448 SwapBytes(disconnAck->len);
1449 SwapBytes(disconnAck->rnd);
1451 printfd(__FILE__, "DISCONN_ACK_8\n");
1452 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1454 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1460 //-----------------------------------------------------------------------------
1461 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, user_iter *, uint32_t sip)
1463 //+++ Fill static data in connSynAck +++
1464 // TODO Move this code. It must be executed only once
1465 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1466 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1467 for (int j = 0; j < DIR_NUM; j++)
1469 strncpy((char*)connSynAck6.dirName[j],
1470 stgSettings->GetDirName(j).c_str(),
1473 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1475 //--- Fill static data in connSynAck ---
1477 iaUser->rnd = random();
1478 connSynAck6.rnd = iaUser->rnd;
1480 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1481 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1484 SwapBytes(connSynAck6.len);
1485 SwapBytes(connSynAck6.rnd);
1486 SwapBytes(connSynAck6.userTimeOut);
1487 SwapBytes(connSynAck6.aliveDelay);
1490 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1491 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1493 //-----------------------------------------------------------------------------
1494 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, user_iter * user, uint32_t sip)
1496 return Send_CONN_SYN_ACK_6(iaUser, user, sip);
1498 //-----------------------------------------------------------------------------
1499 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, user_iter *, uint32_t sip)
1501 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1502 connSynAck8.hdr.protoVer[0] = 0;
1503 connSynAck8.hdr.protoVer[1] = 8;
1505 //+++ Fill static data in connSynAck +++
1506 // TODO Move this code. It must be executed only once
1507 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1508 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1509 for (int j = 0; j < DIR_NUM; j++)
1511 strncpy((char*)connSynAck8.dirName[j],
1512 stgSettings->GetDirName(j).c_str(),
1515 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1517 //--- Fill static data in connSynAck ---
1519 iaUser->rnd = random();
1520 connSynAck8.rnd = iaUser->rnd;
1522 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1523 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1526 SwapBytes(connSynAck8.len);
1527 SwapBytes(connSynAck8.rnd);
1528 SwapBytes(connSynAck8.userTimeOut);
1529 SwapBytes(connSynAck8.aliveDelay);
1532 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1533 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1534 //return Send(sip, iaUser->port, (char*)&connSynAck8, 384);
1536 //-----------------------------------------------------------------------------
1537 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1539 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1540 aliveSyn6.rnd = iaUser->rnd = random();
1542 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1544 for (int i = 0; i < DIR_NUM; i++)
1546 aliveSyn6.md[i] = iaUser->user->property.down.Get()[i];
1547 aliveSyn6.mu[i] = iaUser->user->property.up.Get()[i];
1549 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1550 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1554 int dn = iaSettings.GetFreeMbShowType();
1555 const TARIFF * tf = iaUser->user->GetTariff();
1559 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1566 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1570 double fmb = iaUser->user->property.freeMb;
1571 fmb = fmb < 0 ? 0 : fmb;
1572 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1577 if (freeMbNone == iaSettings.GetFreeMbShowType())
1579 aliveSyn6.freeMb[0] = 0;
1583 double fmb = iaUser->user->property.freeMb;
1584 fmb = fmb < 0 ? 0 : fmb;
1585 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1590 if (iaUser->aliveSent)
1592 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->user->GetLogin().c_str());
1594 iaUser->aliveSent = true;
1597 aliveSyn6.cash =(int64_t) (iaUser->user->property.cash.Get() * 1000.0);
1598 if (!stgSettings->GetShowFeeInCash())
1599 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1602 SwapBytes(aliveSyn6.len);
1603 SwapBytes(aliveSyn6.rnd);
1604 SwapBytes(aliveSyn6.cash);
1605 for (int i = 0; i < DIR_NUM; ++i)
1607 SwapBytes(aliveSyn6.mu[i]);
1608 SwapBytes(aliveSyn6.md[i]);
1609 SwapBytes(aliveSyn6.su[i]);
1610 SwapBytes(aliveSyn6.sd[i]);
1614 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1615 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1617 //-----------------------------------------------------------------------------
1618 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1620 return Send_ALIVE_SYN_6(iaUser, sip);
1622 //-----------------------------------------------------------------------------
1623 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1625 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1626 aliveSyn8.hdr.protoVer[0] = 0;
1627 aliveSyn8.hdr.protoVer[1] = 8;
1629 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1630 aliveSyn8.rnd = iaUser->rnd = random();
1632 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1634 for (int i = 0; i < DIR_NUM; i++)
1636 aliveSyn8.md[i] = iaUser->user->property.down.Get()[i];
1637 aliveSyn8.mu[i] = iaUser->user->property.up.Get()[i];
1639 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1640 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1644 int dn = iaSettings.GetFreeMbShowType();
1648 const TARIFF * tf = iaUser->user->GetTariff();
1649 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1656 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1660 double fmb = iaUser->user->property.freeMb;
1661 fmb = fmb < 0 ? 0 : fmb;
1662 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1667 if (freeMbNone == iaSettings.GetFreeMbShowType())
1669 aliveSyn8.freeMb[0] = 0;
1673 double fmb = iaUser->user->property.freeMb;
1674 fmb = fmb < 0 ? 0 : fmb;
1675 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1680 if (iaUser->aliveSent)
1682 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1684 iaUser->aliveSent = true;
1687 const TARIFF * tf = iaUser->user->GetTariff();
1689 aliveSyn8.cash =(int64_t) (iaUser->user->property.cash.Get() * 1000.0);
1690 if (!stgSettings->GetShowFeeInCash())
1691 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1694 SwapBytes(aliveSyn8.len);
1695 SwapBytes(aliveSyn8.rnd);
1696 SwapBytes(aliveSyn8.cash);
1697 SwapBytes(aliveSyn8.status);
1698 for (int i = 0; i < DIR_NUM; ++i)
1700 SwapBytes(aliveSyn8.mu[i]);
1701 SwapBytes(aliveSyn8.md[i]);
1702 SwapBytes(aliveSyn8.su[i]);
1703 SwapBytes(aliveSyn8.sd[i]);
1707 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1708 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1710 //-----------------------------------------------------------------------------
1711 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1713 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1714 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1715 disconnSynAck6.rnd = iaUser->rnd = random();
1718 SwapBytes(disconnSynAck6.len);
1719 SwapBytes(disconnSynAck6.rnd);
1722 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1723 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1725 //-----------------------------------------------------------------------------
1726 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1728 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1730 //-----------------------------------------------------------------------------
1731 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1733 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1734 disconnSynAck8.hdr.protoVer[0] = 0;
1735 disconnSynAck8.hdr.protoVer[1] = 8;
1737 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1738 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1739 disconnSynAck8.rnd = iaUser->rnd = random();
1742 SwapBytes(disconnSynAck8.len);
1743 SwapBytes(disconnSynAck8.rnd);
1746 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1747 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1749 //-----------------------------------------------------------------------------
1750 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1752 fin6.len = Min8(sizeof(FIN_6));
1753 strcpy((char*)fin6.type, "FIN");
1754 strcpy((char*)fin6.ok, "OK");
1757 SwapBytes(fin6.len);
1760 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1762 iaUser->user->Unauthorize(this);
1764 int ret = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1768 //-----------------------------------------------------------------------------
1769 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1771 return Send_FIN_6(iaUser, sip, it);
1773 //-----------------------------------------------------------------------------
1774 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1776 strcpy((char*)fin8.hdr.magic, IA_ID);
1777 fin8.hdr.protoVer[0] = 0;
1778 fin8.hdr.protoVer[1] = 8;
1780 fin8.len = Min8(sizeof(FIN_8));
1781 strcpy((char*)fin8.type, "FIN");
1782 strcpy((char*)fin8.ok, "OK");
1785 SwapBytes(fin8.len);
1788 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1790 iaUser->user->Unauthorize(this);
1792 int ret = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1796 //-----------------------------------------------------------------------------
1797 bool AUTH_IA::WaitPackets(int sd) const
1805 tv.tv_usec = 500000;
1807 int res = select(sd + 1, &rfds, NULL, NULL, &tv);
1808 if (res == -1) // Error
1812 printfd(__FILE__, "Error on select: '%s'\n", strerror(errno));
1817 if (res == 0) // Timeout
1824 //-----------------------------------------------------------------------------
1826 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
1828 unsigned char keyL[PASSWD_LEN]; // ðÁÒÏÌØ ÄÌÑ ÛÉÆÒÏ×ËÉ
1829 memset(keyL, 0, PASSWD_LEN);
1830 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1831 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1833 //-----------------------------------------------------------------------------
1835 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1837 // len8 - ÄÌÉÎÁ × 8-ÍÉ ÂÁÊÔÏ×ÙÈ ÂÌÏËÁÈ
1839 for (int i = 0; i < len8; i++)
1840 DecodeString(dst + i * 8, src + i * 8, ctx);
1842 //-----------------------------------------------------------------------------
1844 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1846 // len8 - ÄÌÉÎÁ × 8-ÍÉ ÂÁÊÔÏ×ÙÈ ÂÌÏËÁÈ
1848 for (int i = 0; i < len8; i++)
1849 EncodeString(dst + i * 8, src + i * 8, ctx);