8 #include "stg/common.h"
12 int WaitPacket(int sd, int timeout)
22 int res = select(sd + 1, &rfds, NULL, NULL, &tv);
23 if (res == -1) // Error
27 printfd(__FILE__, "Error on select: '%s'\n", strerror(errno));
32 if (res == 0) // Timeout
40 PROTO::PROTO(const std::string & server,
48 uint32_t ip = inet_addr(server.c_str());
49 if (ip == INADDR_NONE)
51 struct hostent * hePtr = gethostbyname(server.c_str());
54 ip = *((uint32_t *)hePtr->h_addr_list[0]);
58 errorStr = "Unknown host: '";
61 printfd(__FILE__, "PROTO::PROTO() - %s\n", errorStr.c_str());
62 throw std::runtime_error(errorStr);
66 sock = socket(AF_INET, SOCK_DGRAM, 0);
68 localAddr.sin_family = AF_INET;
69 localAddr.sin_port = htons(localPort);
70 localAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
72 serverAddr.sin_family = AF_INET;
73 serverAddr.sin_port = htons(port);
74 serverAddr.sin_addr.s_addr = ip;
76 unsigned char key[IA_PASSWD_LEN];
77 memset(key, 0, IA_PASSWD_LEN);
78 strncpy(reinterpret_cast<char *>(key), "pr7Hhen", 8);
79 Blowfish_Init(&ctx, key, IA_PASSWD_LEN);
81 processors["CONN_SYN_ACK"] = &PROTO::CONN_SYN_ACK_Proc;
82 processors["ALIVE_SYN"] = &PROTO::ALIVE_SYN_Proc;
83 processors["DISCONN_SYN_ACK"] = &PROTO::DISCONN_SYN_ACK_Proc;
84 processors["FIN"] = &PROTO::FIN_Proc;
85 processors["INFO"] = &PROTO::INFO_Proc;
86 // ERR_Proc will be handled explicitly
94 void * PROTO::Runner(void * data)
96 PROTO * protoPtr = static_cast<PROTO *>(data);
104 if (pthread_create(&tid, NULL, &Runner, NULL))
106 errorStr = "Failed to create listening thread: '";
107 errorStr += strerror(errno);
109 printfd(__FILE__, "PROTO::Start() - %s\n", errorStr.c_str());
119 while (!stopped && time < timeout)
121 struct timespec ts = {1, 0};
122 nanosleep(&ts, NULL);
127 errorStr = "Failed to stop listening thread - timed out";
128 printfd(__FILE__, "PROTO::Stop() - %s\n", errorStr.c_str());
131 if (pthread_join(tid, NULL))
133 errorStr = "Failed to join listening thread after stop: '";
134 errorStr += strerror(errno);
136 printfd(__FILE__, "PROTO::Stop() - %s\n", errorStr.c_str());
142 bool PROTO::Connect(const std::string & login)
144 std::map<std::string, USER>::const_iterator it;
145 it = users.find(login);
146 if (it == users.end())
154 bool PROTO::Disconnect(const std::string & login)
156 std::map<std::string, USER>::const_iterator it;
157 it = users.find(login);
158 if (it == users.end())
170 int res = WaitPacket(sock, timeout);
182 bool PROTO::RecvPacket()
184 struct sockaddr_in addr;
185 socklen_t fromLen = sizeof(addr);
187 int res = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr*)&addr, &fromLen);
192 return HandlePacket(buffer);
195 bool PROTO::HandlePacket(char * buffer)
197 if (strcmp(buffer + 4 + sizeof(HDR_8), "ERR"))
199 return ERR_Proc(buffer);
202 std::string packetName(buffer + 12);
203 std::map<std::string, PacketProcessor>::const_iterator it;
204 it = processors.find(packetName);
205 if (it != processors.end())
206 return (this->*it->second)(buffer);