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"
42 #include "stg_locker.h"
44 #include "user_property.h"
47 extern volatile const time_t stgTime;
49 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password);
50 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
51 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
53 //-----------------------------------------------------------------------------
74 //-----------------------------------------------------------------------------
75 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
78 //-----------------------------------------------------------------------------
79 //-----------------------------------------------------------------------------
80 //-----------------------------------------------------------------------------
83 return iac.GetPlugin();
85 //-----------------------------------------------------------------------------
86 //-----------------------------------------------------------------------------
87 //-----------------------------------------------------------------------------
88 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
92 freeMbShowType(freeMbCash)
95 //-----------------------------------------------------------------------------
96 int AUTH_IA_SETTINGS::ParseIntInRange(const string & str, int min, int max, int * val)
98 if (str2x(str.c_str(), *val))
100 errorStr = "Incorrect value \'" + str + "\'.";
103 if (*val < min || *val > max)
105 errorStr = "Value \'" + str + "\' out of range.";
110 //-----------------------------------------------------------------------------
111 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
115 vector<PARAM_VALUE>::const_iterator pvi;
116 ///////////////////////////
118 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
119 if (pvi == s.moduleParams.end())
121 errorStr = "Parameter \'Port\' not found.";
122 printfd(__FILE__, "Parameter 'Port' not found\n");
125 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
127 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
128 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
132 ///////////////////////////
133 pv.param = "UserDelay";
134 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
135 if (pvi == s.moduleParams.end())
137 errorStr = "Parameter \'UserDelay\' not found.";
138 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
142 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
144 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
145 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
148 ///////////////////////////
149 pv.param = "UserTimeout";
150 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
151 if (pvi == s.moduleParams.end())
153 errorStr = "Parameter \'UserTimeout\' not found.";
154 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
158 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
160 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
161 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
164 /////////////////////////////////////////////////////////////
168 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
169 if (pvi == s.moduleParams.end())
171 errorStr = "Parameter \'FreeMb\' not found.";
172 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
175 freeMbType = pvi->value[0];
177 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
179 freeMbShowType = freeMbCash;
181 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
183 freeMbShowType = freeMbNone;
185 else if (!str2x(freeMbType.c_str(), n))
187 if (n < 0 || n >= DIR_NUM)
189 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
190 printfd(__FILE__, "%s\n", errorStr.c_str());
193 freeMbShowType = (FREEMB)(freeMb0 + n);
197 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
198 printfd(__FILE__, "%s\n", errorStr.c_str());
201 /////////////////////////////////////////////////////////////
204 //-----------------------------------------------------------------------------
205 //-----------------------------------------------------------------------------
206 //-----------------------------------------------------------------------------
207 #ifdef IA_PHASE_DEBUG
212 gettimeofday(&phaseTime, NULL);
218 gettimeofday(&phaseTime, NULL);
221 //-----------------------------------------------------------------------------
222 IA_PHASE::~IA_PHASE()
224 #ifdef IA_PHASE_DEBUG
225 flog = fopen(log.c_str(), "at");
228 fprintf(flog, "IA %s D\n", login.c_str());
233 //-----------------------------------------------------------------------------
234 #ifdef IA_PHASE_DEBUG
235 void IA_PHASE::SetLogFileName(const string & logFileName)
237 log = logFileName + ".ia.log";
239 //-----------------------------------------------------------------------------
240 void IA_PHASE::SetUserLogin(const string & login)
242 IA_PHASE::login = login;
244 //-----------------------------------------------------------------------------
245 void IA_PHASE::WritePhaseChange(int newPhase)
248 gettimeofday(&newPhaseTime, NULL);
249 flog = fopen(log.c_str(), "at");
250 /*int64_t tn = newPhaseTime.GetSec()*1000000 + newPhaseTime.GetUSec();
251 int64_t to = phaseTime.GetSec()*1000000 + phaseTime.GetUSec();*/
254 string action = newPhase == phase ? "U" : "C";
255 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
256 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
257 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
267 //-----------------------------------------------------------------------------
268 void IA_PHASE::SetPhase1()
270 #ifdef IA_PHASE_DEBUG
274 gettimeofday(&phaseTime, NULL);
276 //-----------------------------------------------------------------------------
277 void IA_PHASE::SetPhase2()
279 #ifdef IA_PHASE_DEBUG
283 gettimeofday(&phaseTime, NULL);
285 //-----------------------------------------------------------------------------
286 void IA_PHASE::SetPhase3()
288 #ifdef IA_PHASE_DEBUG
292 gettimeofday(&phaseTime, NULL);
294 //-----------------------------------------------------------------------------
295 void IA_PHASE::SetPhase4()
297 #ifdef IA_PHASE_DEBUG
301 gettimeofday(&phaseTime, NULL);
303 //-----------------------------------------------------------------------------
304 void IA_PHASE::SetPhase5()
306 #ifdef IA_PHASE_DEBUG
310 gettimeofday(&phaseTime, NULL);
312 //-----------------------------------------------------------------------------
313 int IA_PHASE::GetPhase() const
317 //-----------------------------------------------------------------------------
318 void IA_PHASE::UpdateTime()
320 #ifdef IA_PHASE_DEBUG
321 WritePhaseChange(phase);
323 gettimeofday(&phaseTime, NULL);
325 //-----------------------------------------------------------------------------
326 const UTIME & IA_PHASE::GetTime() const
330 //-----------------------------------------------------------------------------
331 //-----------------------------------------------------------------------------
332 //-----------------------------------------------------------------------------
336 isRunningRunTimeouter(false),
340 WriteServLog(GetStgLogger()),
341 enabledDirs(0xFFffFFff),
342 onDelUserNotifier(*this)
344 InitEncrypt(&ctxS, "pr7Hhen");
346 pthread_mutexattr_t attr;
347 pthread_mutexattr_init(&attr);
348 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
349 pthread_mutex_init(&mutex, &attr);
351 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
352 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
353 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
354 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
355 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
356 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
357 memset(&fin6, 0, sizeof(FIN_6));
358 memset(&fin8, 0, sizeof(FIN_8));
360 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
361 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
362 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
363 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
364 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
365 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
366 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
367 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
368 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
369 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
370 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
371 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
372 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
373 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
374 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
375 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
376 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
377 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
379 packetTypes["CONN_SYN"] = CONN_SYN_N;
380 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
381 packetTypes["CONN_ACK"] = CONN_ACK_N;
382 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
383 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
384 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
385 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
386 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
387 packetTypes["FIN"] = FIN_N;
388 packetTypes["ERR"] = ERROR_N;
390 //-----------------------------------------------------------------------------
393 pthread_mutex_destroy(&mutex);
395 //-----------------------------------------------------------------------------
398 users->AddNotifierUserDel(&onDelUserNotifier);
408 if (pthread_create(&recvThread, NULL, Run, this))
410 errorStr = "Cannot create thread.";
411 printfd(__FILE__, "Cannot create recv thread\n");
416 if (!isRunningRunTimeouter)
418 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
420 errorStr = "Cannot create thread.";
421 printfd(__FILE__, "Cannot create timeouter thread\n");
428 //-----------------------------------------------------------------------------
439 UnauthorizeUser(this)
444 //5 seconds to thread stops itself
445 for (int i = 0; i < 25 && isRunningRun; i++)
450 //after 5 seconds waiting thread still running. now killing it
453 //TODO pthread_cancel()
454 if (pthread_kill(recvThread, SIGINT))
456 errorStr = "Cannot kill thread.";
457 printfd(__FILE__, "Cannot kill thread\n");
460 for (int i = 0; i < 25 && isRunningRun; ++i)
464 printfd(__FILE__, "Failed to stop recv thread\n");
468 pthread_join(recvThread, NULL);
470 printfd(__FILE__, "AUTH_IA killed Run\n");
476 if (isRunningRunTimeouter)
478 //5 seconds to thread stops itself
479 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
484 //after 5 seconds waiting thread still running. now killing it
485 if (isRunningRunTimeouter)
487 //TODO pthread_cancel()
488 if (pthread_kill(timeouterThread, SIGINT))
490 errorStr = "Cannot kill thread.";
493 for (int i = 0; i < 25 && isRunningRunTimeouter; ++i)
495 if (isRunningRunTimeouter)
497 printfd(__FILE__, "Failed to stop timeouter thread\n");
501 pthread_join(timeouterThread, NULL);
503 printfd(__FILE__, "AUTH_IA killed Timeouter\n");
506 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
507 users->DelNotifierUserDel(&onDelUserNotifier);
510 //-----------------------------------------------------------------------------
511 void * AUTH_IA::Run(void * d)
513 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
515 ia->isRunningRun = true;
519 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
523 ia->RecvData(buffer, sizeof(buffer));
524 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
527 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
528 TouchFile(monFile.c_str());
532 ia->isRunningRun = false;
535 //-----------------------------------------------------------------------------
536 void * AUTH_IA::RunTimeouter(void * d)
538 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
540 ia->isRunningRunTimeouter = true;
543 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
548 // TODO cahange counter to timer and MONITOR_TIME_DELAY_SEC
549 if (++a % (50*60) == 0 && ia->stgSettings->GetMonitoring())
551 TouchFile(monFile.c_str());
555 ia->isRunningRunTimeouter = false;
558 //-----------------------------------------------------------------------------
559 int AUTH_IA::ParseSettings()
561 int ret = iaSettings.ParseSettings(settings);
563 errorStr = iaSettings.GetStrError();
566 //-----------------------------------------------------------------------------
567 int AUTH_IA::PrepareNet()
569 struct sockaddr_in listenAddr;
571 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
573 if (listenSocket < 0)
575 errorStr = "Cannot create socket.";
579 listenAddr.sin_family = AF_INET;
580 listenAddr.sin_port = htons(iaSettings.GetUserPort());
581 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
583 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
585 errorStr = "AUTH_IA: Bind failed.";
590 if (getsockopt(listenSocket, SOL_SOCKET, SO_SNDBUF, &buffLen, sizeof(buffLen)) < 0)
593 errorStr = "Getsockopt failed. " + string(strerror(errno));
597 //WriteServLog("buffLen = %d", buffLen);
601 //-----------------------------------------------------------------------------
602 int AUTH_IA::FinalizeNet()
607 //-----------------------------------------------------------------------------
608 int AUTH_IA::RecvData(char * buffer, int bufferSize)
610 if (!WaitPackets(listenSocket)) // Timeout
615 struct sockaddr_in outerAddr;
616 socklen_t outerAddrLen(sizeof(outerAddr));
617 int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
624 if (dataLen <= 0) // Error
628 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
638 if (CheckHeader(buffer, &protoVer))
641 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
642 memset(login, 0, PASSWD_LEN);
644 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
646 uint32_t sip = *((uint32_t*)&outerAddr.sin_addr);
647 uint16_t sport = htons(outerAddr.sin_port);
650 if (users->FindByName(login, &user) == 0)
652 printfd(__FILE__, "User %s FOUND!\n", user->GetLogin().c_str());
653 PacketProcessor(buffer, dataLen, sip, sport, protoVer, &user);
657 WriteServLog("User\'s connect failed:: user \'%s\' not found. IP \'%s\'",
659 inet_ntostring(sip).c_str());
660 printfd(__FILE__, "User %s NOT found!\n", login);
661 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
667 //-----------------------------------------------------------------------------
668 int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
670 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
672 //SendError(userIP, updateMsg);
673 printfd(__FILE__, "update needed - IA_ID\n");
674 //SendError(userIP, "Incorrect header!");
678 if (buffer[6] != 0) //proto[0] shoud be 0
680 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
681 //SendError(userIP, updateMsg);
688 //SendError(userIP, updateMsg);
689 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
694 *protoVer = buffer[7];
698 //-----------------------------------------------------------------------------
699 int AUTH_IA::Timeouter()
701 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
703 map<uint32_t, IA_USER>::iterator it;
704 it = ip2user.begin();
707 while (it != ip2user.end())
711 static UTIME currTime;
712 gettimeofday(&currTime, NULL);
714 if ((it->second.phase.GetPhase() == 2)
715 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
717 it->second.phase.SetPhase1();
718 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
721 if (it->second.phase.GetPhase() == 3)
723 if (!it->second.messagesToSend.empty())
725 if (it->second.protoVer == 6)
726 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
728 if (it->second.protoVer == 7)
729 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
731 if (it->second.protoVer == 8)
732 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
734 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
737 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
739 switch (it->second.protoVer)
742 Send_ALIVE_SYN_6(&(it->second), sip);
745 Send_ALIVE_SYN_7(&(it->second), sip);
748 Send_ALIVE_SYN_8(&(it->second), sip);
752 gettimeofday(&it->second.lastSendAlive, NULL);
755 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
757 it->second.user->Unauthorize(this);
763 if ((it->second.phase.GetPhase() == 4)
764 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
766 it->second.phase.SetPhase3();
767 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
775 //-----------------------------------------------------------------------------
776 int AUTH_IA::PacketProcessor(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR * user)
778 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
779 // ôÕÔ ÓÏÂÒÁÎÙ ÏÂÒÁÂÏÔÞÉËÉ ÒÁÚÎÙÈ ÐÁËÅÔÏ×
781 const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
783 IA_USER * iaUser = NULL;
785 CONN_SYN_6 * connSyn6;
786 CONN_SYN_7 * connSyn7;
787 CONN_SYN_8 * connSyn8;
789 CONN_ACK_6 * connAck;
790 ALIVE_ACK_6 * aliveAck;
791 DISCONN_SYN_6 * disconnSyn;
792 DISCONN_ACK_6 * disconnAck;
794 map<uint32_t, IA_USER>::iterator it;
795 it = ip2user.find(sip);
797 if (it == ip2user.end() || (*user)->GetID() != it->second.user->GetID())
799 // åÝÅ ÎÅ ÂÙÌÏ ÚÁÐÒÏÓÏ× Ó ÜÔÏÇÏ IP
800 printfd(__FILE__, "Add new user\n");
801 ip2user[sip].protoVer = protoVer;
802 ip2user[sip].user = *user;
803 ip2user[sip].port = sport;
804 #ifdef IA_PHASE_DEBUG
805 ip2user[sip].phase.SetLogFileName(stgSettings->GetLogFileName());
806 ip2user[sip].phase.SetUserLogin((*user)->GetLogin());
810 it = ip2user.find(sip); //TODO
811 if (it == ip2user.end())
813 printfd(__FILE__, "+++ ERROR +++\n");
818 iaUser = &(it->second);
820 if (iaUser->port != sport)
821 iaUser->port = sport;
823 if (iaUser->password != (*user)->GetProperty().password.Get())
825 InitEncrypt(&iaUser->ctx, (*user)->GetProperty().password.Get());
826 iaUser->password = (*user)->GetProperty().password.Get();
830 Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
832 char packetName[IA_MAX_TYPE_LEN];
833 strncpy(packetName, buff + 4, IA_MAX_TYPE_LEN);
834 packetName[IA_MAX_TYPE_LEN - 1] = 0;
836 map<string, int>::iterator pi;
837 pi = packetTypes.find(packetName);
838 if (pi == packetTypes.end())
840 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
841 printfd(__FILE__, "Login or password is wrong!\n");
842 WriteServLog("User's connect failed. IP \'%s\'. Wrong login or password", inet_ntostring(sip).c_str());
850 if ((*user)->GetProperty().disabled.Get())
852 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
856 if ((*user)->GetProperty().passive.Get())
858 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
862 if ((*user)->GetAuthorized() && (*user)->GetCurrIP() != sip)
864 printfd(__FILE__, "Login %s alredy in use. IP \'%s\'\n", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
865 WriteServLog("Login %s alredy in use. IP \'%s\'", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
866 SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
871 if (users->FindByIPIdx(sip, &u) == 0 && u->GetLogin() != (*user)->GetLogin())
873 printfd(__FILE__, "IP address alredy in use. IP \'%s\'", inet_ntostring(sip).c_str());
874 WriteServLog("IP address alredy in use. IP \'%s\'", inet_ntostring(sip).c_str());
875 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
879 // ôÅÐÅÒØ ÍÙ ÄÏÌÖÎÙ ÐÒÏ×ÅÒÉÔØ, ÍÏÖÅÔ ÌÉ ÐÏÌØÚÏ×ÁÔÅÌØ ÐÏÄËÌÀÞÉÔÓÑ Ó ÜÔÏÇÏ ÁÄÒÅÓÁ.
880 int ipFound = (*user)->GetProperty().ips.Get().IsIPInIPS(sip);
883 printfd(__FILE__, "User %s. IP address is incorrect. IP \'%s\'\n", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
884 WriteServLog("User %s. IP address is incorrect. IP \'%s\'", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
885 SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
897 connSyn6 = (CONN_SYN_6*)(buff - offset);
898 ret = Process_CONN_SYN_6(connSyn6, &(it->second), sip);
901 connSyn7 = (CONN_SYN_7*)(buff - offset);
902 ret = Process_CONN_SYN_7(connSyn7, &(it->second), sip);
905 connSyn8 = (CONN_SYN_8*)(buff - offset);
906 ret = Process_CONN_SYN_8(connSyn8, &(it->second), sip);
917 Send_CONN_SYN_ACK_6(iaUser, sip);
920 Send_CONN_SYN_ACK_7(iaUser, sip);
923 Send_CONN_SYN_ACK_8(iaUser, sip);
929 connAck = (CONN_ACK_6*)(buff - offset);
933 ret = Process_CONN_ACK_6(connAck, iaUser, sip);
936 ret = Process_CONN_ACK_7(connAck, iaUser, sip);
939 ret = Process_CONN_ACK_8((CONN_ACK_8*)(buff - offset), iaUser, sip);
945 SendError(sip, sport, protoVer, errorStr);
952 Send_ALIVE_SYN_6(iaUser, sip);
955 Send_ALIVE_SYN_7(iaUser, sip);
958 Send_ALIVE_SYN_8(iaUser, sip);
964 // ðÒÉÂÙÌ ÏÔ×ÅÔ Ó ÐÏÄÔ×ÅÒÖÄÅÎÉÅÍ ALIVE
966 aliveAck = (ALIVE_ACK_6*)(buff - offset);
970 ret = Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
973 ret = Process_ALIVE_ACK_7(aliveAck, iaUser, sip);
976 ret = Process_ALIVE_ACK_8((ALIVE_ACK_8*)(buff - offset), iaUser, sip);
981 // úÁÐÒÏÓ ÎÁ ÏÔËÌÀÞÅÎÉÅ
984 disconnSyn = (DISCONN_SYN_6*)(buff - offset);
988 ret = Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
991 ret = Process_DISCONN_SYN_7(disconnSyn, iaUser, sip);
994 ret = Process_DISCONN_SYN_8((DISCONN_SYN_8*)(buff - offset), iaUser, sip);
1004 Send_DISCONN_SYN_ACK_6(iaUser, sip);
1007 Send_DISCONN_SYN_ACK_7(iaUser, sip);
1010 Send_DISCONN_SYN_ACK_8(iaUser, sip);
1016 disconnAck = (DISCONN_ACK_6*)(buff - offset);
1021 ret = Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1024 ret = Process_DISCONN_ACK_7(disconnAck, iaUser, sip, it);
1027 ret = Process_DISCONN_ACK_8((DISCONN_ACK_8*)(buff - offset), iaUser, sip, it);
1034 Send_FIN_6(iaUser, sip, it);
1037 Send_FIN_7(iaUser, sip, it);
1040 Send_FIN_8(iaUser, sip, it);
1048 //-----------------------------------------------------------------------------
1049 void AUTH_IA::DelUser(USER_PTR u)
1051 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1053 uint32_t ip = u->GetCurrIP();
1058 map<uint32_t, IA_USER>::iterator it;
1059 it = ip2user.find(ip);
1060 if (it == ip2user.end())
1063 printfd(__FILE__, "Nothing to delete\n");
1067 if (it->second.user == u)
1069 printfd(__FILE__, "User removed!\n");
1070 it->second.user->Unauthorize(this);
1074 //-----------------------------------------------------------------------------
1075 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
1077 struct sockaddr_in sendAddr;
1084 memset(&err, 0, sizeof(ERR));
1086 sendAddr.sin_family = AF_INET;
1087 sendAddr.sin_port = htons(port);
1089 sendAddr.sin_addr.s_addr = ip;// IP ÐÏÌØÚÏ×ÁÔÅÌÑ
1092 strncpy((char*)err.type, "ERR", 16);
1093 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1099 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1100 printfd(__FILE__, "SendError %d bytes sent\n", res);
1105 memset(&err8, 0, sizeof(ERR_8));
1107 sendAddr.sin_family = AF_INET;
1108 sendAddr.sin_port = htons(port);
1110 sendAddr.sin_addr.s_addr = ip;// IP ÐÏÌØÚÏ×ÁÔÅÌÑ
1113 strncpy((char*)err8.type, "ERR", 16);
1114 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1117 SwapBytes(err8.len);
1120 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1121 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1127 //-----------------------------------------------------------------------------
1128 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
1130 struct sockaddr_in sendAddr;
1133 sendAddr.sin_family = AF_INET;
1134 sendAddr.sin_port = htons(port);
1135 sendAddr.sin_addr.s_addr = ip;
1137 res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1139 static struct timeval tv;
1140 gettimeofday(&tv, NULL);
1144 //-----------------------------------------------------------------------------
1145 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1147 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1149 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1151 map<uint32_t, IA_USER>::iterator it;
1152 it = ip2user.find(ip);
1153 if (it == ip2user.end())
1155 errorStr = "Unknown user.";
1158 it->second.messagesToSend.push_back(msg);
1161 //-----------------------------------------------------------------------------
1162 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1164 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.user->GetLogin().c_str());
1169 memset(&info, 0, sizeof(INFO_6));
1172 strncpy((char*)info.type, "INFO", 16);
1173 info.infoType = 'I';
1174 strncpy((char*)info.text, msg.text.c_str(), 235);
1177 size_t len = info.len;
1179 SwapBytes(info.len);
1182 memcpy(buffer, &info, sizeof(INFO_6));
1183 Encrypt(&user.ctx, buffer, buffer, len / 8);
1184 Send(ip, iaSettings.GetUserPort(), buffer, len);
1188 //-----------------------------------------------------------------------------
1189 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1191 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.user->GetLogin().c_str());
1196 memset(&info, 0, sizeof(INFO_7));
1199 strncpy((char*)info.type, "INFO_7", 16);
1200 info.infoType = msg.header.type;
1201 info.showTime = msg.header.showTime;
1203 info.sendTime = msg.header.creationTime;
1205 size_t len = info.len;
1207 SwapBytes(info.len);
1208 SwapBytes(info.sendTime);
1211 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1212 info.text[MAX_MSG_LEN - 1] = 0;
1214 memcpy(buffer, &info, sizeof(INFO_7));
1216 Encrypt(&user.ctx, buffer, buffer, len / 8);
1217 Send(ip, iaSettings.GetUserPort(), buffer, len);
1221 //-----------------------------------------------------------------------------
1222 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1224 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.user->GetLogin().c_str());
1227 memset(buffer, 0, sizeof(buffer));
1231 memset(&info, 0, sizeof(INFO_8));
1234 strncpy((char*)info.type, "INFO_8", 16);
1235 info.infoType = msg.header.type;
1236 info.showTime = msg.header.showTime;
1237 info.sendTime = msg.header.creationTime;
1239 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1240 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1242 size_t len = info.len;
1244 SwapBytes(info.len);
1245 SwapBytes(info.sendTime);
1248 memcpy(buffer, &info, sizeof(INFO_8));
1250 Encrypt(&user.ctx, buffer, buffer, len / 8);
1251 Send(ip, user.port, buffer, len);
1255 //-----------------------------------------------------------------------------
1256 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1258 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1261 enabledDirs = 0xFFffFFff;
1263 iaUser->phase.SetPhase2();
1264 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1267 //-----------------------------------------------------------------------------
1268 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1270 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1272 //-----------------------------------------------------------------------------
1273 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1276 SwapBytes(connSyn->dirs);
1278 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, sip);
1279 enabledDirs = connSyn->dirs;
1282 //-----------------------------------------------------------------------------
1283 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1286 SwapBytes(connAck->len);
1287 SwapBytes(connAck->rnd);
1289 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1290 // ÕÓÔÁÎÏ×ÉÔØ ÎÏ×ÕÀ ÆÁÚÕ É ×ÒÅÍÑ É ÒÁÚÒÅÛÉÔØ ÉÎÅÔ
1291 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1293 iaUser->phase.UpdateTime();
1295 iaUser->lastSendAlive = iaUser->phase.GetTime();
1296 if (iaUser->user->Authorize(sip, enabledDirs, this) == 0)
1298 iaUser->phase.SetPhase3();
1299 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1304 errorStr = iaUser->user->GetStrError();
1305 iaUser->phase.SetPhase1();
1306 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1310 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1313 //-----------------------------------------------------------------------------
1314 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1316 return Process_CONN_ACK_6(connAck, iaUser, sip);
1318 //-----------------------------------------------------------------------------
1319 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1322 SwapBytes(connAck->len);
1323 SwapBytes(connAck->rnd);
1325 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1327 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1329 iaUser->phase.UpdateTime();
1330 iaUser->lastSendAlive = iaUser->phase.GetTime();
1331 if (iaUser->user->Authorize(sip, enabledDirs, this) == 0)
1333 iaUser->phase.SetPhase3();
1334 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1339 errorStr = iaUser->user->GetStrError();
1340 iaUser->phase.SetPhase1();
1341 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1345 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1348 //-----------------------------------------------------------------------------
1349 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1352 SwapBytes(aliveAck->len);
1353 SwapBytes(aliveAck->rnd);
1355 printfd(__FILE__, "ALIVE_ACK_6\n");
1356 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1358 iaUser->phase.UpdateTime();
1360 iaUser->aliveSent = false;
1365 //-----------------------------------------------------------------------------
1366 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1368 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1370 //-----------------------------------------------------------------------------
1371 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1374 SwapBytes(aliveAck->len);
1375 SwapBytes(aliveAck->rnd);
1377 printfd(__FILE__, "ALIVE_ACK_8\n");
1378 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1380 iaUser->phase.UpdateTime();
1382 iaUser->aliveSent = false;
1387 //-----------------------------------------------------------------------------
1388 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1390 printfd(__FILE__, "DISCONN_SYN_6\n");
1391 if (iaUser->phase.GetPhase() != 3)
1393 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1394 errorStr = "Incorrect request DISCONN_SYN";
1398 iaUser->phase.SetPhase4();
1399 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1403 //-----------------------------------------------------------------------------
1404 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1406 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1408 //-----------------------------------------------------------------------------
1409 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t)
1411 if (iaUser->phase.GetPhase() != 3)
1413 errorStr = "Incorrect request DISCONN_SYN";
1414 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1418 iaUser->phase.SetPhase4();
1419 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1423 //-----------------------------------------------------------------------------
1424 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1427 map<uint32_t, IA_USER>::iterator)
1430 SwapBytes(disconnAck->len);
1431 SwapBytes(disconnAck->rnd);
1433 printfd(__FILE__, "DISCONN_ACK_6\n");
1434 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1436 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1442 //-----------------------------------------------------------------------------
1443 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1445 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1447 //-----------------------------------------------------------------------------
1448 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, map<uint32_t, IA_USER>::iterator)
1451 SwapBytes(disconnAck->len);
1452 SwapBytes(disconnAck->rnd);
1454 printfd(__FILE__, "DISCONN_ACK_8\n");
1455 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1457 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1463 //-----------------------------------------------------------------------------
1464 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1466 //+++ Fill static data in connSynAck +++
1467 // TODO Move this code. It must be executed only once
1468 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1469 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1470 for (int j = 0; j < DIR_NUM; j++)
1472 strncpy((char*)connSynAck6.dirName[j],
1473 stgSettings->GetDirName(j).c_str(),
1476 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1478 //--- Fill static data in connSynAck ---
1480 iaUser->rnd = random();
1481 connSynAck6.rnd = iaUser->rnd;
1483 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1484 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1487 SwapBytes(connSynAck6.len);
1488 SwapBytes(connSynAck6.rnd);
1489 SwapBytes(connSynAck6.userTimeOut);
1490 SwapBytes(connSynAck6.aliveDelay);
1493 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1494 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1496 //-----------------------------------------------------------------------------
1497 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1499 return Send_CONN_SYN_ACK_6(iaUser, sip);
1501 //-----------------------------------------------------------------------------
1502 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1504 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1505 connSynAck8.hdr.protoVer[0] = 0;
1506 connSynAck8.hdr.protoVer[1] = 8;
1508 //+++ Fill static data in connSynAck +++
1509 // TODO Move this code. It must be executed only once
1510 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1511 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1512 for (int j = 0; j < DIR_NUM; j++)
1514 strncpy((char*)connSynAck8.dirName[j],
1515 stgSettings->GetDirName(j).c_str(),
1518 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1520 //--- Fill static data in connSynAck ---
1522 iaUser->rnd = random();
1523 connSynAck8.rnd = iaUser->rnd;
1525 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1526 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1529 SwapBytes(connSynAck8.len);
1530 SwapBytes(connSynAck8.rnd);
1531 SwapBytes(connSynAck8.userTimeOut);
1532 SwapBytes(connSynAck8.aliveDelay);
1535 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1536 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1537 //return Send(sip, iaUser->port, (char*)&connSynAck8, 384);
1539 //-----------------------------------------------------------------------------
1540 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1542 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1543 aliveSyn6.rnd = iaUser->rnd = random();
1545 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1547 for (int i = 0; i < DIR_NUM; i++)
1549 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1550 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1552 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1553 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1557 int dn = iaSettings.GetFreeMbShowType();
1558 const TARIFF * tf = iaUser->user->GetTariff();
1562 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1569 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1573 double fmb = iaUser->user->GetProperty().freeMb;
1574 fmb = fmb < 0 ? 0 : fmb;
1575 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1580 if (freeMbNone == iaSettings.GetFreeMbShowType())
1582 aliveSyn6.freeMb[0] = 0;
1586 double fmb = iaUser->user->GetProperty().freeMb;
1587 fmb = fmb < 0 ? 0 : fmb;
1588 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1593 if (iaUser->aliveSent)
1595 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->user->GetLogin().c_str());
1597 iaUser->aliveSent = true;
1600 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1601 if (!stgSettings->GetShowFeeInCash())
1602 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1605 SwapBytes(aliveSyn6.len);
1606 SwapBytes(aliveSyn6.rnd);
1607 SwapBytes(aliveSyn6.cash);
1608 for (int i = 0; i < DIR_NUM; ++i)
1610 SwapBytes(aliveSyn6.mu[i]);
1611 SwapBytes(aliveSyn6.md[i]);
1612 SwapBytes(aliveSyn6.su[i]);
1613 SwapBytes(aliveSyn6.sd[i]);
1617 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1618 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1620 //-----------------------------------------------------------------------------
1621 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1623 return Send_ALIVE_SYN_6(iaUser, sip);
1625 //-----------------------------------------------------------------------------
1626 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1628 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1629 aliveSyn8.hdr.protoVer[0] = 0;
1630 aliveSyn8.hdr.protoVer[1] = 8;
1632 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1633 aliveSyn8.rnd = iaUser->rnd = random();
1635 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1637 for (int i = 0; i < DIR_NUM; i++)
1639 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1640 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1642 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1643 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1647 int dn = iaSettings.GetFreeMbShowType();
1651 const TARIFF * tf = iaUser->user->GetTariff();
1652 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1659 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1663 double fmb = iaUser->user->GetProperty().freeMb;
1664 fmb = fmb < 0 ? 0 : fmb;
1665 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1670 if (freeMbNone == iaSettings.GetFreeMbShowType())
1672 aliveSyn8.freeMb[0] = 0;
1676 double fmb = iaUser->user->GetProperty().freeMb;
1677 fmb = fmb < 0 ? 0 : fmb;
1678 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1683 if (iaUser->aliveSent)
1685 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1687 iaUser->aliveSent = true;
1690 const TARIFF * tf = iaUser->user->GetTariff();
1692 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1693 if (!stgSettings->GetShowFeeInCash())
1694 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1697 SwapBytes(aliveSyn8.len);
1698 SwapBytes(aliveSyn8.rnd);
1699 SwapBytes(aliveSyn8.cash);
1700 SwapBytes(aliveSyn8.status);
1701 for (int i = 0; i < DIR_NUM; ++i)
1703 SwapBytes(aliveSyn8.mu[i]);
1704 SwapBytes(aliveSyn8.md[i]);
1705 SwapBytes(aliveSyn8.su[i]);
1706 SwapBytes(aliveSyn8.sd[i]);
1710 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1711 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1713 //-----------------------------------------------------------------------------
1714 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1716 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1717 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1718 disconnSynAck6.rnd = iaUser->rnd = random();
1721 SwapBytes(disconnSynAck6.len);
1722 SwapBytes(disconnSynAck6.rnd);
1725 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1726 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1728 //-----------------------------------------------------------------------------
1729 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1731 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1733 //-----------------------------------------------------------------------------
1734 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1736 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1737 disconnSynAck8.hdr.protoVer[0] = 0;
1738 disconnSynAck8.hdr.protoVer[1] = 8;
1740 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1741 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1742 disconnSynAck8.rnd = iaUser->rnd = random();
1745 SwapBytes(disconnSynAck8.len);
1746 SwapBytes(disconnSynAck8.rnd);
1749 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1750 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1752 //-----------------------------------------------------------------------------
1753 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1755 fin6.len = Min8(sizeof(FIN_6));
1756 strcpy((char*)fin6.type, "FIN");
1757 strcpy((char*)fin6.ok, "OK");
1760 SwapBytes(fin6.len);
1763 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1765 iaUser->user->Unauthorize(this);
1767 int ret = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1771 //-----------------------------------------------------------------------------
1772 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1774 return Send_FIN_6(iaUser, sip, it);
1776 //-----------------------------------------------------------------------------
1777 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1779 strcpy((char*)fin8.hdr.magic, IA_ID);
1780 fin8.hdr.protoVer[0] = 0;
1781 fin8.hdr.protoVer[1] = 8;
1783 fin8.len = Min8(sizeof(FIN_8));
1784 strcpy((char*)fin8.type, "FIN");
1785 strcpy((char*)fin8.ok, "OK");
1788 SwapBytes(fin8.len);
1791 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1793 iaUser->user->Unauthorize(this);
1795 int ret = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1799 //-----------------------------------------------------------------------------
1800 bool AUTH_IA::WaitPackets(int sd) const
1808 tv.tv_usec = 500000;
1810 int res = select(sd + 1, &rfds, NULL, NULL, &tv);
1811 if (res == -1) // Error
1815 printfd(__FILE__, "Error on select: '%s'\n", strerror(errno));
1820 if (res == 0) // Timeout
1827 //-----------------------------------------------------------------------------
1829 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
1831 unsigned char keyL[PASSWD_LEN]; // ðÁÒÏÌØ ÄÌÑ ÛÉÆÒÏ×ËÉ
1832 memset(keyL, 0, PASSWD_LEN);
1833 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1834 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1836 //-----------------------------------------------------------------------------
1838 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1840 // len8 - ÄÌÉÎÁ × 8-ÍÉ ÂÁÊÔÏ×ÙÈ ÂÌÏËÁÈ
1842 for (int i = 0; i < len8; i++)
1843 DecodeString(dst + i * 8, src + i * 8, ctx);
1845 //-----------------------------------------------------------------------------
1847 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1849 // len8 - ÄÌÉÎÁ × 8-ÍÉ ÂÁÊÔÏ×ÙÈ ÂÌÏËÁÈ
1851 for (int i = 0; i < len8; i++)
1852 EncodeString(dst + i * 8, src + i * 8, ctx);