2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
23 $Date: 2010/03/25 15:18:48 $
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <sys/select.h>
37 #include <cstdio> // snprintf
41 #include "inetaccess.h"
43 #include "stg_locker.h"
45 #include "user_property.h"
48 extern volatile const time_t stgTime;
50 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password);
51 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
52 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
54 //-----------------------------------------------------------------------------
75 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
77 //-----------------------------------------------------------------------------
79 //-----------------------------------------------------------------------------
80 //-----------------------------------------------------------------------------
81 //-----------------------------------------------------------------------------
84 return iac.GetPlugin();
86 //-----------------------------------------------------------------------------
87 //-----------------------------------------------------------------------------
88 //-----------------------------------------------------------------------------
89 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
93 freeMbShowType(freeMbCash)
96 //-----------------------------------------------------------------------------
97 int AUTH_IA_SETTINGS::ParseIntInRange(const string & str, int min, int max, int * val)
99 if (str2x(str.c_str(), *val))
101 errorStr = "Incorrect value \'" + str + "\'.";
104 if (*val < min || *val > max)
106 errorStr = "Value \'" + str + "\' out of range.";
111 //-----------------------------------------------------------------------------
112 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
116 vector<PARAM_VALUE>::const_iterator pvi;
117 ///////////////////////////
119 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
120 if (pvi == s.moduleParams.end())
122 errorStr = "Parameter \'Port\' not found.";
123 printfd(__FILE__, "Parameter 'Port' not found\n");
126 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
128 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
129 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
133 ///////////////////////////
134 pv.param = "UserDelay";
135 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
136 if (pvi == s.moduleParams.end())
138 errorStr = "Parameter \'UserDelay\' not found.";
139 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
143 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
145 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
146 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
149 ///////////////////////////
150 pv.param = "UserTimeout";
151 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
152 if (pvi == s.moduleParams.end())
154 errorStr = "Parameter \'UserTimeout\' not found.";
155 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
159 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
161 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
162 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
165 /////////////////////////////////////////////////////////////
169 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
170 if (pvi == s.moduleParams.end())
172 errorStr = "Parameter \'FreeMb\' not found.";
173 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
176 freeMbType = pvi->value[0];
178 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
180 freeMbShowType = freeMbCash;
182 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
184 freeMbShowType = freeMbNone;
186 else if (!str2x(freeMbType.c_str(), n))
188 if (n < 0 || n >= DIR_NUM)
190 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
191 printfd(__FILE__, "%s\n", errorStr.c_str());
194 freeMbShowType = (FREEMB)(freeMb0 + n);
198 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
199 printfd(__FILE__, "%s\n", errorStr.c_str());
202 /////////////////////////////////////////////////////////////
205 //-----------------------------------------------------------------------------
206 //-----------------------------------------------------------------------------
207 //-----------------------------------------------------------------------------
208 #ifdef IA_PHASE_DEBUG
213 gettimeofday(&phaseTime, NULL);
219 gettimeofday(&phaseTime, NULL);
222 //-----------------------------------------------------------------------------
223 IA_PHASE::~IA_PHASE()
225 #ifdef IA_PHASE_DEBUG
226 flog = fopen(log.c_str(), "at");
229 fprintf(flog, "IA %s D\n", login.c_str());
234 //-----------------------------------------------------------------------------
235 #ifdef IA_PHASE_DEBUG
236 void IA_PHASE::SetLogFileName(const string & logFileName)
238 log = logFileName + ".ia.log";
240 //-----------------------------------------------------------------------------
241 void IA_PHASE::SetUserLogin(const string & login)
243 IA_PHASE::login = login;
245 //-----------------------------------------------------------------------------
246 void IA_PHASE::WritePhaseChange(int newPhase)
249 gettimeofday(&newPhaseTime, NULL);
250 flog = fopen(log.c_str(), "at");
251 /*int64_t tn = newPhaseTime.GetSec()*1000000 + newPhaseTime.GetUSec();
252 int64_t to = phaseTime.GetSec()*1000000 + phaseTime.GetUSec();*/
255 string action = newPhase == phase ? "U" : "C";
256 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
257 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
258 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
268 //-----------------------------------------------------------------------------
269 void IA_PHASE::SetPhase1()
271 #ifdef IA_PHASE_DEBUG
275 gettimeofday(&phaseTime, NULL);
277 //-----------------------------------------------------------------------------
278 void IA_PHASE::SetPhase2()
280 #ifdef IA_PHASE_DEBUG
284 gettimeofday(&phaseTime, NULL);
286 //-----------------------------------------------------------------------------
287 void IA_PHASE::SetPhase3()
289 #ifdef IA_PHASE_DEBUG
293 gettimeofday(&phaseTime, NULL);
295 //-----------------------------------------------------------------------------
296 void IA_PHASE::SetPhase4()
298 #ifdef IA_PHASE_DEBUG
302 gettimeofday(&phaseTime, NULL);
304 //-----------------------------------------------------------------------------
305 void IA_PHASE::SetPhase5()
307 #ifdef IA_PHASE_DEBUG
311 gettimeofday(&phaseTime, NULL);
313 //-----------------------------------------------------------------------------
314 int IA_PHASE::GetPhase() const
318 //-----------------------------------------------------------------------------
319 void IA_PHASE::UpdateTime()
321 #ifdef IA_PHASE_DEBUG
322 WritePhaseChange(phase);
324 gettimeofday(&phaseTime, NULL);
326 //-----------------------------------------------------------------------------
327 const UTIME & IA_PHASE::GetTime() const
331 //-----------------------------------------------------------------------------
332 //-----------------------------------------------------------------------------
333 //-----------------------------------------------------------------------------
337 isRunningRunTimeouter(false),
341 WriteServLog(GetStgLogger()),
342 enabledDirs(0xFFffFFff),
343 onDelUserNotifier(*this)
345 InitEncrypt(&ctxS, "pr7Hhen");
347 pthread_mutexattr_t attr;
348 pthread_mutexattr_init(&attr);
349 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
350 pthread_mutex_init(&mutex, &attr);
352 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
353 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
354 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
355 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
356 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
357 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
358 memset(&fin6, 0, sizeof(FIN_6));
359 memset(&fin8, 0, sizeof(FIN_8));
361 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
362 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
363 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
364 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
365 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
366 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
367 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
368 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
369 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
370 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
371 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
372 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
373 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
374 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
375 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
376 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
377 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
378 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
380 packetTypes["CONN_SYN"] = CONN_SYN_N;
381 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
382 packetTypes["CONN_ACK"] = CONN_ACK_N;
383 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
384 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
385 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
386 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
387 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
388 packetTypes["FIN"] = FIN_N;
389 packetTypes["ERR"] = ERROR_N;
391 //-----------------------------------------------------------------------------
394 pthread_mutex_destroy(&mutex);
396 //-----------------------------------------------------------------------------
399 users->AddNotifierUserDel(&onDelUserNotifier);
409 if (pthread_create(&recvThread, NULL, Run, this))
411 errorStr = "Cannot create thread.";
412 printfd(__FILE__, "Cannot create recv thread\n");
417 if (!isRunningRunTimeouter)
419 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
421 errorStr = "Cannot create thread.";
422 printfd(__FILE__, "Cannot create timeouter thread\n");
429 //-----------------------------------------------------------------------------
440 UnauthorizeUser(this)
445 //5 seconds to thread stops itself
446 for (int i = 0; i < 25 && isRunningRun; i++)
451 //after 5 seconds waiting thread still running. now killing it
454 //TODO pthread_cancel()
455 if (pthread_kill(recvThread, SIGINT))
457 errorStr = "Cannot kill thread.";
458 printfd(__FILE__, "Cannot kill thread\n");
461 for (int i = 0; i < 25 && isRunningRun; ++i)
465 printfd(__FILE__, "Failed to stop recv thread\n");
469 pthread_join(recvThread, NULL);
471 printfd(__FILE__, "AUTH_IA killed Run\n");
477 if (isRunningRunTimeouter)
479 //5 seconds to thread stops itself
480 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
485 //after 5 seconds waiting thread still running. now killing it
486 if (isRunningRunTimeouter)
488 //TODO pthread_cancel()
489 if (pthread_kill(timeouterThread, SIGINT))
491 errorStr = "Cannot kill thread.";
494 for (int i = 0; i < 25 && isRunningRunTimeouter; ++i)
496 if (isRunningRunTimeouter)
498 printfd(__FILE__, "Failed to stop timeouter thread\n");
502 pthread_join(timeouterThread, NULL);
504 printfd(__FILE__, "AUTH_IA killed Timeouter\n");
507 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
508 users->DelNotifierUserDel(&onDelUserNotifier);
511 //-----------------------------------------------------------------------------
512 void * AUTH_IA::Run(void * d)
514 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
516 ia->isRunningRun = true;
520 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
524 ia->RecvData(buffer, sizeof(buffer));
525 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
528 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
529 TouchFile(monFile.c_str());
533 ia->isRunningRun = false;
536 //-----------------------------------------------------------------------------
537 void * AUTH_IA::RunTimeouter(void * d)
539 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
541 ia->isRunningRunTimeouter = true;
544 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
549 // TODO cahange counter to timer and MONITOR_TIME_DELAY_SEC
550 if (++a % (50*60) == 0 && ia->stgSettings->GetMonitoring())
552 TouchFile(monFile.c_str());
556 ia->isRunningRunTimeouter = false;
559 //-----------------------------------------------------------------------------
560 int AUTH_IA::ParseSettings()
562 int ret = iaSettings.ParseSettings(settings);
564 errorStr = iaSettings.GetStrError();
567 //-----------------------------------------------------------------------------
568 int AUTH_IA::PrepareNet()
570 struct sockaddr_in listenAddr;
572 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
574 if (listenSocket < 0)
576 errorStr = "Cannot create socket.";
580 listenAddr.sin_family = AF_INET;
581 listenAddr.sin_port = htons(iaSettings.GetUserPort());
582 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
584 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
586 errorStr = "AUTH_IA: Bind failed.";
591 if (getsockopt(listenSocket, SOL_SOCKET, SO_SNDBUF, &buffLen, sizeof(buffLen)) < 0)
594 errorStr = "Getsockopt failed. " + string(strerror(errno));
598 //WriteServLog("buffLen = %d", buffLen);
602 //-----------------------------------------------------------------------------
603 int AUTH_IA::FinalizeNet()
608 //-----------------------------------------------------------------------------
609 int AUTH_IA::RecvData(char * buffer, int bufferSize)
611 if (!WaitPackets(listenSocket)) // Timeout
616 struct sockaddr_in outerAddr;
617 socklen_t outerAddrLen(sizeof(outerAddr));
618 int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
625 if (dataLen <= 0) // Error
629 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
639 if (CheckHeader(buffer, &protoVer))
642 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
643 memset(login, 0, PASSWD_LEN);
645 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
647 uint32_t sip = *((uint32_t*)&outerAddr.sin_addr);
648 uint16_t sport = htons(outerAddr.sin_port);
651 if (users->FindByName(login, &user) == 0)
653 printfd(__FILE__, "User %s FOUND!\n", user->GetLogin().c_str());
654 PacketProcessor(buffer, dataLen, sip, sport, protoVer, &user);
658 WriteServLog("User\'s connect failed:: user \'%s\' not found. IP \'%s\'",
660 inet_ntostring(sip).c_str());
661 printfd(__FILE__, "User %s NOT found!\n", login);
662 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
668 //-----------------------------------------------------------------------------
669 int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
671 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
673 //SendError(userIP, updateMsg);
674 printfd(__FILE__, "update needed - IA_ID\n");
675 //SendError(userIP, "Incorrect header!");
679 if (buffer[6] != 0) //proto[0] shoud be 0
681 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
682 //SendError(userIP, updateMsg);
689 //SendError(userIP, updateMsg);
690 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
695 *protoVer = buffer[7];
699 //-----------------------------------------------------------------------------
700 int AUTH_IA::Timeouter()
702 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
704 map<uint32_t, IA_USER>::iterator it;
705 it = ip2user.begin();
708 while (it != ip2user.end())
712 static UTIME currTime;
713 gettimeofday(&currTime, NULL);
715 if ((it->second.phase.GetPhase() == 2)
716 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
718 it->second.phase.SetPhase1();
719 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
722 if (it->second.phase.GetPhase() == 3)
724 if (!it->second.messagesToSend.empty())
726 if (it->second.protoVer == 6)
727 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
729 if (it->second.protoVer == 7)
730 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
732 if (it->second.protoVer == 8)
733 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
735 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
738 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
740 switch (it->second.protoVer)
743 Send_ALIVE_SYN_6(&(it->second), sip);
746 Send_ALIVE_SYN_7(&(it->second), sip);
749 Send_ALIVE_SYN_8(&(it->second), sip);
753 gettimeofday(&it->second.lastSendAlive, NULL);
756 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
758 it->second.user->Unauthorize(this);
764 if ((it->second.phase.GetPhase() == 4)
765 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
767 it->second.phase.SetPhase3();
768 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
776 //-----------------------------------------------------------------------------
777 int AUTH_IA::PacketProcessor(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR * user)
779 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
780 // ôÕÔ ÓÏÂÒÁÎÙ ÏÂÒÁÂÏÔÞÉËÉ ÒÁÚÎÙÈ ÐÁËÅÔÏ×
782 const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
784 IA_USER * iaUser = NULL;
786 CONN_SYN_6 * connSyn6;
787 CONN_SYN_7 * connSyn7;
788 CONN_SYN_8 * connSyn8;
790 CONN_ACK_6 * connAck;
791 ALIVE_ACK_6 * aliveAck;
792 DISCONN_SYN_6 * disconnSyn;
793 DISCONN_ACK_6 * disconnAck;
795 map<uint32_t, IA_USER>::iterator it;
796 it = ip2user.find(sip);
798 if (it == ip2user.end() || (*user)->GetID() != it->second.user->GetID())
800 // åÝÅ ÎÅ ÂÙÌÏ ÚÁÐÒÏÓÏ× Ó ÜÔÏÇÏ IP
801 printfd(__FILE__, "Add new user\n");
802 ip2user[sip].protoVer = protoVer;
803 ip2user[sip].user = *user;
804 ip2user[sip].port = sport;
805 #ifdef IA_PHASE_DEBUG
806 ip2user[sip].phase.SetLogFileName(stgSettings->GetLogFileName());
807 ip2user[sip].phase.SetUserLogin((*user)->GetLogin());
811 it = ip2user.find(sip); //TODO
812 if (it == ip2user.end())
814 printfd(__FILE__, "+++ ERROR +++\n");
819 iaUser = &(it->second);
821 if (iaUser->port != sport)
822 iaUser->port = sport;
824 if (iaUser->password != (*user)->GetProperty().password.Get())
826 InitEncrypt(&iaUser->ctx, (*user)->GetProperty().password.Get());
827 iaUser->password = (*user)->GetProperty().password.Get();
831 Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
833 char packetName[IA_MAX_TYPE_LEN];
834 strncpy(packetName, buff + 4, IA_MAX_TYPE_LEN);
835 packetName[IA_MAX_TYPE_LEN - 1] = 0;
837 map<string, int>::iterator pi;
838 pi = packetTypes.find(packetName);
839 if (pi == packetTypes.end())
841 SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
842 printfd(__FILE__, "Login or password is wrong!\n");
843 WriteServLog("User's connect failed. IP \'%s\'. Wrong login or password", inet_ntostring(sip).c_str());
851 if ((*user)->GetProperty().disabled.Get())
853 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
857 if ((*user)->GetProperty().passive.Get())
859 SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
863 if ((*user)->GetAuthorized() && (*user)->GetCurrIP() != sip)
865 printfd(__FILE__, "Login %s alredy in use. IP \'%s\'\n", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
866 WriteServLog("Login %s alredy in use. IP \'%s\'", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
867 SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
872 if (users->FindByIPIdx(sip, &u) == 0 && u->GetLogin() != (*user)->GetLogin())
874 printfd(__FILE__, "IP address alredy in use. IP \'%s\'", inet_ntostring(sip).c_str());
875 WriteServLog("IP address alredy in use. IP \'%s\'", inet_ntostring(sip).c_str());
876 SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
880 // ôÅÐÅÒØ ÍÙ ÄÏÌÖÎÙ ÐÒÏ×ÅÒÉÔØ, ÍÏÖÅÔ ÌÉ ÐÏÌØÚÏ×ÁÔÅÌØ ÐÏÄËÌÀÞÉÔÓÑ Ó ÜÔÏÇÏ ÁÄÒÅÓÁ.
881 int ipFound = (*user)->GetProperty().ips.Get().IsIPInIPS(sip);
884 printfd(__FILE__, "User %s. IP address is incorrect. IP \'%s\'\n", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
885 WriteServLog("User %s. IP address is incorrect. IP \'%s\'", (*user)->GetLogin().c_str(), inet_ntostring(sip).c_str());
886 SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
898 connSyn6 = (CONN_SYN_6*)(buff - offset);
899 ret = Process_CONN_SYN_6(connSyn6, &(it->second), sip);
902 connSyn7 = (CONN_SYN_7*)(buff - offset);
903 ret = Process_CONN_SYN_7(connSyn7, &(it->second), sip);
906 connSyn8 = (CONN_SYN_8*)(buff - offset);
907 ret = Process_CONN_SYN_8(connSyn8, &(it->second), sip);
918 Send_CONN_SYN_ACK_6(iaUser, sip);
921 Send_CONN_SYN_ACK_7(iaUser, sip);
924 Send_CONN_SYN_ACK_8(iaUser, sip);
930 connAck = (CONN_ACK_6*)(buff - offset);
934 ret = Process_CONN_ACK_6(connAck, iaUser, sip);
937 ret = Process_CONN_ACK_7(connAck, iaUser, sip);
940 ret = Process_CONN_ACK_8((CONN_ACK_8*)(buff - offset), iaUser, sip);
946 SendError(sip, sport, protoVer, errorStr);
953 Send_ALIVE_SYN_6(iaUser, sip);
956 Send_ALIVE_SYN_7(iaUser, sip);
959 Send_ALIVE_SYN_8(iaUser, sip);
965 // ðÒÉÂÙÌ ÏÔ×ÅÔ Ó ÐÏÄÔ×ÅÒÖÄÅÎÉÅÍ ALIVE
967 aliveAck = (ALIVE_ACK_6*)(buff - offset);
971 ret = Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
974 ret = Process_ALIVE_ACK_7(aliveAck, iaUser, sip);
977 ret = Process_ALIVE_ACK_8((ALIVE_ACK_8*)(buff - offset), iaUser, sip);
982 // úÁÐÒÏÓ ÎÁ ÏÔËÌÀÞÅÎÉÅ
985 disconnSyn = (DISCONN_SYN_6*)(buff - offset);
989 ret = Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
992 ret = Process_DISCONN_SYN_7(disconnSyn, iaUser, sip);
995 ret = Process_DISCONN_SYN_8((DISCONN_SYN_8*)(buff - offset), iaUser, sip);
1005 Send_DISCONN_SYN_ACK_6(iaUser, sip);
1008 Send_DISCONN_SYN_ACK_7(iaUser, sip);
1011 Send_DISCONN_SYN_ACK_8(iaUser, sip);
1017 disconnAck = (DISCONN_ACK_6*)(buff - offset);
1022 ret = Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1025 ret = Process_DISCONN_ACK_7(disconnAck, iaUser, sip, it);
1028 ret = Process_DISCONN_ACK_8((DISCONN_ACK_8*)(buff - offset), iaUser, sip, it);
1035 Send_FIN_6(iaUser, sip, it);
1038 Send_FIN_7(iaUser, sip, it);
1041 Send_FIN_8(iaUser, sip, it);
1049 //-----------------------------------------------------------------------------
1050 void AUTH_IA::DelUser(USER_PTR u)
1052 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1054 uint32_t ip = u->GetCurrIP();
1059 map<uint32_t, IA_USER>::iterator it;
1060 it = ip2user.find(ip);
1061 if (it == ip2user.end())
1064 printfd(__FILE__, "Nothing to delete\n");
1068 if (it->second.user == u)
1070 printfd(__FILE__, "User removed!\n");
1071 it->second.user->Unauthorize(this);
1075 //-----------------------------------------------------------------------------
1076 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
1078 struct sockaddr_in sendAddr;
1085 memset(&err, 0, sizeof(ERR));
1087 sendAddr.sin_family = AF_INET;
1088 sendAddr.sin_port = htons(port);
1090 sendAddr.sin_addr.s_addr = ip;// IP ÐÏÌØÚÏ×ÁÔÅÌÑ
1093 strncpy((char*)err.type, "ERR", 16);
1094 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1100 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1101 printfd(__FILE__, "SendError %d bytes sent\n", res);
1106 memset(&err8, 0, sizeof(ERR_8));
1108 sendAddr.sin_family = AF_INET;
1109 sendAddr.sin_port = htons(port);
1111 sendAddr.sin_addr.s_addr = ip;// IP ÐÏÌØÚÏ×ÁÔÅÌÑ
1114 strncpy((char*)err8.type, "ERR", 16);
1115 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1118 SwapBytes(err8.len);
1121 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1122 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1128 //-----------------------------------------------------------------------------
1129 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
1131 struct sockaddr_in sendAddr;
1134 sendAddr.sin_family = AF_INET;
1135 sendAddr.sin_port = htons(port);
1136 sendAddr.sin_addr.s_addr = ip;
1138 res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1140 static struct timeval tv;
1141 gettimeofday(&tv, NULL);
1145 //-----------------------------------------------------------------------------
1146 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1148 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1150 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1152 map<uint32_t, IA_USER>::iterator it;
1153 it = ip2user.find(ip);
1154 if (it == ip2user.end())
1156 errorStr = "Unknown user.";
1159 it->second.messagesToSend.push_back(msg);
1162 //-----------------------------------------------------------------------------
1163 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1165 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.user->GetLogin().c_str());
1170 memset(&info, 0, sizeof(INFO_6));
1173 strncpy((char*)info.type, "INFO", 16);
1174 info.infoType = 'I';
1175 strncpy((char*)info.text, msg.text.c_str(), 235);
1178 size_t len = info.len;
1180 SwapBytes(info.len);
1183 memcpy(buffer, &info, sizeof(INFO_6));
1184 Encrypt(&user.ctx, buffer, buffer, len / 8);
1185 Send(ip, iaSettings.GetUserPort(), buffer, len);
1189 //-----------------------------------------------------------------------------
1190 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1192 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.user->GetLogin().c_str());
1197 memset(&info, 0, sizeof(INFO_7));
1200 strncpy((char*)info.type, "INFO_7", 16);
1201 info.infoType = msg.header.type;
1202 info.showTime = msg.header.showTime;
1204 info.sendTime = msg.header.creationTime;
1206 size_t len = info.len;
1208 SwapBytes(info.len);
1209 SwapBytes(info.sendTime);
1212 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1213 info.text[MAX_MSG_LEN - 1] = 0;
1215 memcpy(buffer, &info, sizeof(INFO_7));
1217 Encrypt(&user.ctx, buffer, buffer, len / 8);
1218 Send(ip, iaSettings.GetUserPort(), buffer, len);
1222 //-----------------------------------------------------------------------------
1223 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1225 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.user->GetLogin().c_str());
1228 memset(buffer, 0, sizeof(buffer));
1232 memset(&info, 0, sizeof(INFO_8));
1235 strncpy((char*)info.type, "INFO_8", 16);
1236 info.infoType = msg.header.type;
1237 info.showTime = msg.header.showTime;
1238 info.sendTime = msg.header.creationTime;
1240 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1241 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1243 size_t len = info.len;
1245 SwapBytes(info.len);
1246 SwapBytes(info.sendTime);
1249 memcpy(buffer, &info, sizeof(INFO_8));
1251 Encrypt(&user.ctx, buffer, buffer, len / 8);
1252 Send(ip, user.port, buffer, len);
1256 //-----------------------------------------------------------------------------
1257 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1259 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1262 enabledDirs = 0xFFffFFff;
1264 iaUser->phase.SetPhase2();
1265 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1268 //-----------------------------------------------------------------------------
1269 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1271 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1273 //-----------------------------------------------------------------------------
1274 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1277 SwapBytes(connSyn->dirs);
1279 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, sip);
1280 enabledDirs = connSyn->dirs;
1283 //-----------------------------------------------------------------------------
1284 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1287 SwapBytes(connAck->len);
1288 SwapBytes(connAck->rnd);
1290 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1291 // ÕÓÔÁÎÏ×ÉÔØ ÎÏ×ÕÀ ÆÁÚÕ É ×ÒÅÍÑ É ÒÁÚÒÅÛÉÔØ ÉÎÅÔ
1292 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1294 iaUser->phase.UpdateTime();
1296 iaUser->lastSendAlive = iaUser->phase.GetTime();
1297 if (iaUser->user->Authorize(sip, enabledDirs, this) == 0)
1299 iaUser->phase.SetPhase3();
1300 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1305 errorStr = iaUser->user->GetStrError();
1306 iaUser->phase.SetPhase1();
1307 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1311 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1314 //-----------------------------------------------------------------------------
1315 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1317 return Process_CONN_ACK_6(connAck, iaUser, sip);
1319 //-----------------------------------------------------------------------------
1320 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1323 SwapBytes(connAck->len);
1324 SwapBytes(connAck->rnd);
1326 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1328 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1330 iaUser->phase.UpdateTime();
1331 iaUser->lastSendAlive = iaUser->phase.GetTime();
1332 if (iaUser->user->Authorize(sip, enabledDirs, this) == 0)
1334 iaUser->phase.SetPhase3();
1335 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1340 errorStr = iaUser->user->GetStrError();
1341 iaUser->phase.SetPhase1();
1342 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1346 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1349 //-----------------------------------------------------------------------------
1350 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1353 SwapBytes(aliveAck->len);
1354 SwapBytes(aliveAck->rnd);
1356 printfd(__FILE__, "ALIVE_ACK_6\n");
1357 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1359 iaUser->phase.UpdateTime();
1361 iaUser->aliveSent = false;
1366 //-----------------------------------------------------------------------------
1367 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1369 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1371 //-----------------------------------------------------------------------------
1372 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1375 SwapBytes(aliveAck->len);
1376 SwapBytes(aliveAck->rnd);
1378 printfd(__FILE__, "ALIVE_ACK_8\n");
1379 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1381 iaUser->phase.UpdateTime();
1383 iaUser->aliveSent = false;
1388 //-----------------------------------------------------------------------------
1389 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1391 printfd(__FILE__, "DISCONN_SYN_6\n");
1392 if (iaUser->phase.GetPhase() != 3)
1394 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1395 errorStr = "Incorrect request DISCONN_SYN";
1399 iaUser->phase.SetPhase4();
1400 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1404 //-----------------------------------------------------------------------------
1405 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1407 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1409 //-----------------------------------------------------------------------------
1410 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t)
1412 if (iaUser->phase.GetPhase() != 3)
1414 errorStr = "Incorrect request DISCONN_SYN";
1415 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1419 iaUser->phase.SetPhase4();
1420 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1424 //-----------------------------------------------------------------------------
1425 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1428 map<uint32_t, IA_USER>::iterator)
1431 SwapBytes(disconnAck->len);
1432 SwapBytes(disconnAck->rnd);
1434 printfd(__FILE__, "DISCONN_ACK_6\n");
1435 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1437 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1443 //-----------------------------------------------------------------------------
1444 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1446 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1448 //-----------------------------------------------------------------------------
1449 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, map<uint32_t, IA_USER>::iterator)
1452 SwapBytes(disconnAck->len);
1453 SwapBytes(disconnAck->rnd);
1455 printfd(__FILE__, "DISCONN_ACK_8\n");
1456 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1458 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1464 //-----------------------------------------------------------------------------
1465 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1467 //+++ Fill static data in connSynAck +++
1468 // TODO Move this code. It must be executed only once
1469 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1470 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1471 for (int j = 0; j < DIR_NUM; j++)
1473 strncpy((char*)connSynAck6.dirName[j],
1474 stgSettings->GetDirName(j).c_str(),
1477 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1479 //--- Fill static data in connSynAck ---
1481 iaUser->rnd = random();
1482 connSynAck6.rnd = iaUser->rnd;
1484 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1485 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1488 SwapBytes(connSynAck6.len);
1489 SwapBytes(connSynAck6.rnd);
1490 SwapBytes(connSynAck6.userTimeOut);
1491 SwapBytes(connSynAck6.aliveDelay);
1494 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1495 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1497 //-----------------------------------------------------------------------------
1498 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1500 return Send_CONN_SYN_ACK_6(iaUser, sip);
1502 //-----------------------------------------------------------------------------
1503 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1505 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1506 connSynAck8.hdr.protoVer[0] = 0;
1507 connSynAck8.hdr.protoVer[1] = 8;
1509 //+++ Fill static data in connSynAck +++
1510 // TODO Move this code. It must be executed only once
1511 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1512 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1513 for (int j = 0; j < DIR_NUM; j++)
1515 strncpy((char*)connSynAck8.dirName[j],
1516 stgSettings->GetDirName(j).c_str(),
1519 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1521 //--- Fill static data in connSynAck ---
1523 iaUser->rnd = random();
1524 connSynAck8.rnd = iaUser->rnd;
1526 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1527 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1530 SwapBytes(connSynAck8.len);
1531 SwapBytes(connSynAck8.rnd);
1532 SwapBytes(connSynAck8.userTimeOut);
1533 SwapBytes(connSynAck8.aliveDelay);
1536 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1537 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1538 //return Send(sip, iaUser->port, (char*)&connSynAck8, 384);
1540 //-----------------------------------------------------------------------------
1541 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1543 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1544 aliveSyn6.rnd = iaUser->rnd = random();
1546 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1548 for (int i = 0; i < DIR_NUM; i++)
1550 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1551 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1553 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1554 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1558 int dn = iaSettings.GetFreeMbShowType();
1559 const TARIFF * tf = iaUser->user->GetTariff();
1563 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1570 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1574 double fmb = iaUser->user->GetProperty().freeMb;
1575 fmb = fmb < 0 ? 0 : fmb;
1576 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1581 if (freeMbNone == iaSettings.GetFreeMbShowType())
1583 aliveSyn6.freeMb[0] = 0;
1587 double fmb = iaUser->user->GetProperty().freeMb;
1588 fmb = fmb < 0 ? 0 : fmb;
1589 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1594 if (iaUser->aliveSent)
1596 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->user->GetLogin().c_str());
1598 iaUser->aliveSent = true;
1601 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1602 if (!stgSettings->GetShowFeeInCash())
1603 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1606 SwapBytes(aliveSyn6.len);
1607 SwapBytes(aliveSyn6.rnd);
1608 SwapBytes(aliveSyn6.cash);
1609 for (int i = 0; i < DIR_NUM; ++i)
1611 SwapBytes(aliveSyn6.mu[i]);
1612 SwapBytes(aliveSyn6.md[i]);
1613 SwapBytes(aliveSyn6.su[i]);
1614 SwapBytes(aliveSyn6.sd[i]);
1618 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1619 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1621 //-----------------------------------------------------------------------------
1622 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1624 return Send_ALIVE_SYN_6(iaUser, sip);
1626 //-----------------------------------------------------------------------------
1627 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1629 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1630 aliveSyn8.hdr.protoVer[0] = 0;
1631 aliveSyn8.hdr.protoVer[1] = 8;
1633 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1634 aliveSyn8.rnd = iaUser->rnd = random();
1636 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1638 for (int i = 0; i < DIR_NUM; i++)
1640 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1641 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1643 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1644 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1648 int dn = iaSettings.GetFreeMbShowType();
1652 const TARIFF * tf = iaUser->user->GetTariff();
1653 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1660 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1664 double fmb = iaUser->user->GetProperty().freeMb;
1665 fmb = fmb < 0 ? 0 : fmb;
1666 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1671 if (freeMbNone == iaSettings.GetFreeMbShowType())
1673 aliveSyn8.freeMb[0] = 0;
1677 double fmb = iaUser->user->GetProperty().freeMb;
1678 fmb = fmb < 0 ? 0 : fmb;
1679 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1684 if (iaUser->aliveSent)
1686 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1688 iaUser->aliveSent = true;
1691 const TARIFF * tf = iaUser->user->GetTariff();
1693 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1694 if (!stgSettings->GetShowFeeInCash())
1695 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1698 SwapBytes(aliveSyn8.len);
1699 SwapBytes(aliveSyn8.rnd);
1700 SwapBytes(aliveSyn8.cash);
1701 SwapBytes(aliveSyn8.status);
1702 for (int i = 0; i < DIR_NUM; ++i)
1704 SwapBytes(aliveSyn8.mu[i]);
1705 SwapBytes(aliveSyn8.md[i]);
1706 SwapBytes(aliveSyn8.su[i]);
1707 SwapBytes(aliveSyn8.sd[i]);
1711 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1712 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1714 //-----------------------------------------------------------------------------
1715 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1717 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1718 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1719 disconnSynAck6.rnd = iaUser->rnd = random();
1722 SwapBytes(disconnSynAck6.len);
1723 SwapBytes(disconnSynAck6.rnd);
1726 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1727 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1729 //-----------------------------------------------------------------------------
1730 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1732 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1734 //-----------------------------------------------------------------------------
1735 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1737 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1738 disconnSynAck8.hdr.protoVer[0] = 0;
1739 disconnSynAck8.hdr.protoVer[1] = 8;
1741 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1742 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1743 disconnSynAck8.rnd = iaUser->rnd = random();
1746 SwapBytes(disconnSynAck8.len);
1747 SwapBytes(disconnSynAck8.rnd);
1750 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1751 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1753 //-----------------------------------------------------------------------------
1754 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1756 fin6.len = Min8(sizeof(FIN_6));
1757 strcpy((char*)fin6.type, "FIN");
1758 strcpy((char*)fin6.ok, "OK");
1761 SwapBytes(fin6.len);
1764 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1766 iaUser->user->Unauthorize(this);
1768 int ret = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1772 //-----------------------------------------------------------------------------
1773 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1775 return Send_FIN_6(iaUser, sip, it);
1777 //-----------------------------------------------------------------------------
1778 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1780 strcpy((char*)fin8.hdr.magic, IA_ID);
1781 fin8.hdr.protoVer[0] = 0;
1782 fin8.hdr.protoVer[1] = 8;
1784 fin8.len = Min8(sizeof(FIN_8));
1785 strcpy((char*)fin8.type, "FIN");
1786 strcpy((char*)fin8.ok, "OK");
1789 SwapBytes(fin8.len);
1792 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1794 iaUser->user->Unauthorize(this);
1796 int ret = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1800 //-----------------------------------------------------------------------------
1801 bool AUTH_IA::WaitPackets(int sd) const
1809 tv.tv_usec = 500000;
1811 int res = select(sd + 1, &rfds, NULL, NULL, &tv);
1812 if (res == -1) // Error
1816 printfd(__FILE__, "Error on select: '%s'\n", strerror(errno));
1821 if (res == 0) // Timeout
1828 //-----------------------------------------------------------------------------
1830 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
1832 unsigned char keyL[PASSWD_LEN]; // ðÁÒÏÌØ ÄÌÑ ÛÉÆÒÏ×ËÉ
1833 memset(keyL, 0, PASSWD_LEN);
1834 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1835 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1837 //-----------------------------------------------------------------------------
1839 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1841 // len8 - ÄÌÉÎÁ × 8-ÍÉ ÂÁÊÔÏ×ÙÈ ÂÌÏËÁÈ
1843 for (int i = 0; i < len8; i++)
1844 DecodeString(dst + i * 8, src + i * 8, ctx);
1846 //-----------------------------------------------------------------------------
1848 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1850 // len8 - ÄÌÉÎÁ × 8-ÍÉ ÂÁÊÔÏ×ÙÈ ÂÌÏËÁÈ
1852 for (int i = 0; i < len8; i++)
1853 EncodeString(dst + i * 8, src + i * 8, ctx);