void Ddos::render() { if(m_state != STOPED) { if(m_state == ACTIVE_CONFIRMED) { printw(" Active "); } else { printw(" Possible "); } printw(boost::str(boost::format ("DDOS at %1% during %2% seconds with %3% kbits/s, possible type: %4%\n") % ipToString(m_ip) % m_duration % bytesToKBits(m_totalBytes/m_duration) % m_ddosType).c_str()); } else { printw(boost::str(boost::format (" %1% At %2% during %3% seconds with %4% kbits/s, possible type: %5%") % unixTimeToTimeString(m_startedTime/1000) % ipToString(m_ip) % (m_duration - 5) % bytesToKBits(m_totalBytes/(m_duration-5)) % m_ddosType).c_str()); if(m_offlined) { printw(" (offlined)"); } printw("\n"); } }
void Ddos::update(TrafficStats *trafficStats) { uint32_t kbits = trafficStats->getKBits(); uint32_t packets = trafficStats->getPackets(); m_duration++; m_totalBytes += trafficStats->getBytes(); // force ip offline when threshold > allowed threshold if(!m_offlined && (kbits >= ConfigManager::instance()->getNumber(ConfigManager::IP_TRAFFIC_THRESHOLD) || packets >= ConfigManager::instance()->getNumber(ConfigManager::IP_PACKETS_THRESHOLD))) { if(m_state == ACTIVE_NOT_CONFIRMED) { m_state = ACTIVE_CONFIRMED; Screen::instance()->notificate(boost::str(boost::format("DDoS at %1% instantanealy confirmed with %2% kbits/s, possible type: %3%") % ipToString(m_ip) % kbits % trafficStats->getPossibleFloodType()), true); } Screen::instance()->notificate( boost::str(boost::format("Not allowed threshold at %1% (%2% kbits/s) ip offline forced") % ipToString(m_ip) % kbits)); IpSwitcher::instance()->blockIp(m_ip); m_offlined = true; } // active/stop algorithm if(kbits >= ConfigManager::instance()->getNumber(ConfigManager::NOTIFICATION_TRAFFIC_THRESHOLD) || packets >= ConfigManager::instance()->getNumber(ConfigManager::NOTIFICATION_PACKETS_THRESHOLD)) { m_stopTicks = 0; if(m_state == ACTIVE_NOT_CONFIRMED && ++m_activeTicks >= DDOS_CONFIRM_SECONDS) { m_state = ACTIVE_CONFIRMED; Screen::instance()->notificate(boost::str(boost::format("DDoS at %1% confirmed with %2% kbits/s, possible type: %3%") % ipToString(m_ip) % kbits % trafficStats->getPossibleFloodType()), true); } else { m_ddosType = trafficStats->getPossibleFloodType(); } } else { m_activeTicks = 0; if(++m_stopTicks >= DDOS_CONFIRM_SECONDS) { if(m_state == ACTIVE_CONFIRMED) { Screen::instance()->notificate(boost::str(boost::format("DDoS at %1% stopped") % ipToString(m_ip))); } else { Screen::instance()->notificate(boost::str(boost::format("False DDoS alarm at %1%") % ipToString(m_ip))); } m_state = STOPED; } } }
void LoginHandler::chooseServer(const unsigned int server, const bool persistentIp) const { if (static_cast<size_t>(server) >= LoginRecv::mWorlds.size() || !LoginRecv::mWorlds[server]) { return; } ServerInfo *const charServer = getCharServer(); if (charServer) { if (config.getBoolValue("usePersistentIP") || persistentIp) { charServer->hostname = settings.serverName; } else { charServer->hostname = ipToString( LoginRecv::mWorlds[server]->address); } charServer->port = LoginRecv::mWorlds[server]->port; } client->setState(STATE_UPDATE); }
int send_simple_record_to_monitor(int monitor, int index, unsigned long type, unsigned long value) { int buffer_size = 3*SIZEOF_LONG + 2*sizeof(unsigned short); char outbuf_delay[buffer_size]; // Insert the address info char * buf = save_receiver_address(outbuf_delay, index); logWrite(CONTROL_SEND, NULL, "Sending type(%d) value(%d) about stream(%hu:%s:%hu)", type, value, rcvdb[index].source_port, ipToString(rcvdb[index].ip), rcvdb[index].dest_port); // Insert the code number for delay type = htonl(type); memcpy(buf, &type, SIZEOF_LONG); buf += SIZEOF_LONG; // Insert the delay value value = htonl(value); memcpy(buf, &value, SIZEOF_LONG); buf += SIZEOF_LONG; return send_all(monitor, outbuf_delay, buffer_size) != 0; }
// Get info about the next packet to send packet_info packet_buffer_front(void) { packet_info result; static char * lastAddress = NULL; char * thisAddress = packet_buffer_head->buffer + packet_buffer_index; if (packet_buffer_head == NULL) { printf("packet_buffer_head == NULL in front\n"); clean_exit(1); } else { read_packet_info(&result, packet_buffer_head->buffer + packet_buffer_index); } if (thisAddress != lastAddress) { logWrite(PACKET_BUFFER_DETAIL, NULL, "Looking at packet: type(%hu) value(%lu) delta(%lu) " "source_port(%hu) dest_port(%hu) ip(%s)", result.type, result.value, result.delta, result.source_port, result.dest_port, ipToString(result.ip)); } lastAddress = thisAddress; return result; }
bool Network::realConnect() { IPaddress ipAddress; if (SDLNet_ResolveHost(&ipAddress, mServer.hostname.c_str(), mServer.port) == -1) { std::string errorMessage = _("Unable to resolve host \"") + mServer.hostname + "\""; setError(errorMessage); logger->log("SDLNet_ResolveHost: %s", errorMessage.c_str()); return false; } mState = CONNECTING; mSocket = SDLNet_TCP_Open(&ipAddress); if (!mSocket) { logger->log("Error in SDLNet_TCP_Open(): %s", SDLNet_GetError()); setError(SDLNet_GetError()); return false; } logger->log("Network::Started session with %s:%i", ipToString(ipAddress.host), ipAddress.port); mState = CONNECTED; return true; }
int send_bandwidth_to_monitor(int monitor, int index) { int buffer_size = 3*SIZEOF_LONG + 2*sizeof(unsigned short); char outbuf[buffer_size]; unsigned long code = htonl(CODE_BANDWIDTH); unsigned long bandwidth; if (bandwidth_method == BANDWIDTH_AVERAGE) { bandwidth = throughputTick(&throughput[index]); } else if (bandwidth_method == BANDWIDTH_MAX || bandwidth_method == BANDWIDTH_VEGAS) { bandwidth = max_throughput[index]; } else if (bandwidth_method == BANDWIDTH_BUFFER) { bandwidth = throughputTick(&throughput[index]); if (buffer_full[index] == 0 && bandwidth <= last_through[index]) { bandwidth = last_through[index]; } } if (bandwidth != 0 && bandwidth != last_through[index]) { // Insert the address info char * buf = save_receiver_address(outbuf, index); logWrite(CONTROL_SEND, NULL, "Sending bandwidth(%lukbps) about stream(%hu:%s:%hu)", bandwidth, rcvdb[index].source_port, ipToString(rcvdb[index].ip), rcvdb[index].dest_port); // Insert the code number for bandwidth memcpy(buf, &code, SIZEOF_LONG); buf += SIZEOF_LONG; // Insert the bandwidth bandwidth = htonl(bandwidth); memcpy(buf, &bandwidth, SIZEOF_LONG); buf += SIZEOF_LONG; if (send_all(monitor, outbuf, buffer_size) == 0){ return 0; } { struct timeval now; unsigned long hostBand = ntohl(bandwidth); gettimeofday(&now, NULL); logWrite(TCPTRACE_SEND, NULL, "BANDWIDTH!purple"); logWrite(TCPTRACE_SEND, NULL, "BANDWIDTH!line %.6f %d %.6f %d", now.tv_sec + now.tv_usec/1000000000.0, 0, now.tv_sec + now.tv_usec/1000000000.0, hostBand*1000/8); } last_through[index] = bandwidth; } max_throughput[index] = 0; return 1; }
// Returns the number of bytes remaining. This means a 0 if everything // goes OK, and a positive number if some of the bytes couldn't be // written. Returns -1 if the connection was reset and reconnection failed. int send_with_reconnect(int index, int size) { int result = 0; int bytes_remaining = size; int done = 0; int error = 0; int sockfd = rcvdb[index].sockfd; if (bytes_remaining <= 0) { bytes_remaining = 1; } while (!done && bytes_remaining > 0) { int retry = 0; int write_size = bytes_remaining; if (write_size > MAX_PAYLOAD_SIZE) { write_size = MAX_PAYLOAD_SIZE; } error = send(sockfd, random_buffer, write_size, MSG_DONTWAIT); logWrite(PEER_WRITE, NULL, "Wrote %d bytes", error); // Handle failed connection while (error == -1 && errno == ECONNRESET && retry < 3) { reconnect_receiver(index); sockfd= rcvdb[index].sockfd; error = send(sockfd, random_buffer, size, MSG_DONTWAIT); logWrite(PEER_WRITE, NULL, "Wrote %d reconnected bytes", error); retry++; } //if still disconnected, reset if (error == -1 && errno == ECONNRESET) { remove_index(index, &write_fds); printf("Error: send_receiver() - failed send to %s three times. \n", ipToString(rcvdb[index].ip)); result = -1; } else if (error == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { result = bytes_remaining; done = 1; } else if (error == -1) { perror("send_receiver: send"); clean_exit(1); } else { total_size += error; bytes_remaining -= error; if (error < write_size) { done = 1; } result = bytes_remaining; // printf("Total: %d, Pending: %d\n", total_size, rcvdb[index].pending); } } return result; }
void LoginHandler::chooseServer(unsigned int server) { if (server >= mWorlds.size()) return; charServer.clear(); charServer.hostname = ipToString(mWorlds[server]->address); charServer.port = mWorlds[server]->port; Client::setState(STATE_UPDATE); }
void ServerSelectDialog::action(const gcn::ActionEvent &event) { if (event.getId() == "ok") { mOkButton->setEnabled(false); const SERVER_INFO *si = server_info[mServerList->getSelected()]; mLoginData->hostname = ipToString(si->address); mLoginData->port = si->port; mLoginData->updateHost = si->updateHost; state = mNextState; } else if (event.getId() == "cancel") state = STATE_LOGIN; }
void LoginHandler::chooseServer(const unsigned int server) const { if (server >= mWorlds.size() || !mWorlds[server]) return; ServerInfo *const charServer = getCharServer(); if (charServer) { if (config.getBoolValue("usePersistentIP")) charServer->hostname = client->getServerName(); else charServer->hostname = ipToString(mWorlds[server]->address); charServer->port = mWorlds[server]->port; } client->setState(STATE_UPDATE); }
void Being::showName() { delete mDispName; mDispName = 0; std::string mDisplayName(mName); Being* player = static_cast<Being*>(this); if (player) { if (config.getBoolValue("showgender")) { if (getGender() == GENDER_FEMALE) mDisplayName += " \u2640"; else if (getGender() == GENDER_MALE) mDisplayName += " \u2642"; } // Display the IP when under tmw-Athena (GM only). if (Net::getNetworkType() == ServerInfo::TMWATHENA && local_player && local_player->getShowIp() && player->getIp()) { mDisplayName += strprintf(" %s", ipToString(player->getIp())); } } if (getType() == MONSTER) { if (config.getBoolValue("showMonstersTakedDamage")) { mDisplayName += ", " + toString(getDamageTaken()); } } gcn::Font *font = 0; if (local_player && local_player->getTarget() == this && getType() != MONSTER) { font = boldFont; } mDispName = new FlashText(mDisplayName, getPixelX(), getPixelY(), gcn::Graphics::CENTER, mNameColor, font); updateCoords(); }
void LoginHandler::processLoginData(Net::MessageIn &msg) { // Skip the length word msg.skip(2); // size clearWorlds(); const int worldCount = (msg.getLength() - 47) / 32; mToken.session_ID1 = msg.readInt32(); mToken.account_ID = msg.readInt32(); mToken.session_ID2 = msg.readInt32(); msg.skip(4); // old ip loginData.lastLogin = msg.readString(24); msg.skip(2); // 0 unused bytes // msg.skip(30); // unknown // reserve bits for future usage mToken.sex = Being::intToGender(static_cast<uint8_t>( msg.readUInt8() & 3U)); for (int i = 0; i < worldCount; i++) { WorldInfo *const world = new WorldInfo; world->address = msg.readInt32(); world->port = msg.readInt16(); world->name = msg.readString(20); world->online_users = msg.readInt16(); config.setValue("updatehost", mUpdateHost); world->updateHost = mUpdateHost; msg.skip(2); // maintenance msg.skip(2); // new logger->log("Network: Server: %s (%s:%d)", world->name.c_str(), ipToString(world->address), world->port); mWorlds.push_back(world); } client->setState(STATE_WORLD_SELECT); }
void IpSwitcher::checkIps() { if(!m_blockedIps.empty()) { int64_t timeNow = getSystemTime(); int retryTime = ConfigManager::instance()->getNumber(ConfigManager::IPBLOCK_RETRY_TICKS); BlockedIpsMap mapBackup = m_blockedIps; for(BlockedIpsMap::iterator it = mapBackup.begin(); it != mapBackup.end(); ++it) { const uint32_t &ip = (it->first); const int64_t &timeBlocked = (it->second); if(timeNow - timeBlocked >= retryTime) { unblockIp(ip); Screen::instance()->notificate(boost::str(boost::format("Ip %1% offlined is back after %2% minutes") % ipToString(ip) % ((timeNow - timeBlocked)/(60*1000)))); } } } Scheduler::instance()->addEvent(createSchedulerTask(CHECK_IP_INTERVAL, boost::bind(&IpSwitcher::checkIps, this))); }
int send_delay_list_to_monitor(int monitor, int index) { enum { maxSend = 9000 }; enum { buffer_size = SIZEOF_LONG + 2*sizeof(unsigned short) + SIZEOF_LONG + 2*SIZEOF_LONG*maxSend }; static char outbuf[buffer_size]; unsigned long code = htonl(CODE_LIST_DELAY); unsigned long count = htonl(delay_records[index].sample_number); int sending_size = SIZEOF_LONG + 2*sizeof(unsigned short) + SIZEOF_LONG + 2*SIZEOF_LONG*delay_records[index].sample_number; int error = 1; if (delay_records[index].sample_number > 0) { char * buf = save_receiver_address(outbuf, index); logWrite(CONTROL_SEND, NULL, "Sending delay list of size(%d) to monitor(%s)", delay_records[index].sample_number, ipToString(rcvdb[index].ip)); memcpy(buf, &code, SIZEOF_LONG); buf += SIZEOF_LONG; memcpy(buf, &count, SIZEOF_LONG); buf += SIZEOF_LONG; save_delay_samples(index, buf, maxSend); error = send_all(monitor, outbuf, sending_size) == 0; logWrite(CONTROL_SEND, NULL, "Sending delay list finished with code(%d)", error); } remove_delay_samples(index); return error; }
int PcapWrapper::retrieveAdapters() { freeAdapters(); // free potentially opened adapters char error_buffer[PCAP_ERRBUF_SIZE]; // pcap error buffer // find all openable devices if (pcap_findalldevs(&m_adapter_raw_data, error_buffer) == -1) { fprintf(stderr, "Error: Failed to retrieve network adapters: %s\n", error_buffer); RETURN_CODE(RC(ERROR_RETRIEVING_ADAPTERS)); } if ( m_adapter_raw_data == NULL ) { fprintf(stderr, "Error: No network adapters found or insufficient permissions.\n"); RETURN_CODE(RC(NO_ADAPTERS_FOUND)); } for (pcap_if_t* adapter = m_adapter_raw_data; adapter; adapter = adapter->next) { /* Only include adapters with a pcap address This prevents inactive or slave devices (aggregation/bonding slaves) from being added and we only get the intermediate drivers instead. */ if (!adapter->addresses) { continue; } std::vector<std::string> current_adapter; current_adapter.push_back(adapter->name); // adapter/device name in the system (for example /dev/eth0) if (adapter->description) { current_adapter.push_back(adapter->description); // adapter descriptional name (usually the product name of the network card o.s.) } else { current_adapter.push_back(""); } bpf_u_int32 netmask; bpf_u_int32 ip4_address; if (pcap_lookupnet(adapter->name, &netmask, &ip4_address, error_buffer) < 0) { netmask = 0; } m_adapter_netmasks.push_back(netmask); DEBUG(1, "Device Name: %s\nDescription: %s\nFlags: #%d\n", adapter->name, adapter->description, adapter->flags); // get adapter addresses char* address_buffer; size_t buffer_size = 0; for (pcap_addr* address = adapter->addresses; address; address = address->next) { buffer_size = 0; switch (address->addr->sa_family) { // address families with 32 bit addresses case AF_INET: { // UDP, TCP, ... buffer_size = 16; // usual size of a ipv4 string representation break; } // address families with 128 bit addresses case AF_INET6: { // IPv6 buffer_size = 45; // usual size of a ipv6 string representation break; } // unknown or unspecified families default: { DEBUG(1, "Device Address Unknown\n\n"); // Currently no point in adding adapter addresses of unknown families. continue; } } // deallocation in freeAdapters buffer_size *= sizeof(char); // byte size address_buffer = static_cast<char*>(malloc(buffer_size)); if (!address_buffer) { fprintf(stderr, "Error: Out of memory.\n"); RETURN_CODE(RC(OUT_OF_MEMORY)); } // currently only addresses up to 128bit and known to getnameinfo are supported by ipToString ipToString(address->addr, address_buffer, buffer_size); if (address_buffer) { current_adapter.push_back(std::string(address_buffer)); } free(address_buffer); } // Set global adapter_data m_adapter_data.push_back(current_adapter); } RETURN_CODE(RC(NORMAL_EXECUTION)); }
void StateManager::setState(const State state) { if (mState == state) return; Window* currentDialog; gcn::Container *top = static_cast<gcn::Container*>(gui->getTop()); mState = state; switch (mState) { case ERROR_STATE: logger->log("State: ERROR"); if (desktop) desktop->resetProgressBar(); errorDialog = new OkDialog(_("Error"), mError, NULL, true); errorDialog->addActionListener(&errorListener); errorDialog->requestMoveToTop(); break; case WARNING_STATE: logger->log("State: WARNING"); if (desktop) desktop->resetProgressBar(); warningDialog = new ConfirmDialog(_("Warning"), mError, NULL, true); warningDialog->addActionListener(&warningListener); warningDialog->requestMoveToTop(); break; case START_STATE: logger->log("State: START"); destroy(desktop); desktop = new Desktop(); top->add(desktop); sound.playMusic("Magick - Real.ogg"); #ifdef USE_OPENGL if (options.promptForGraphicsMode) setState(MODE_SELECTION_STATE); else #endif setState(LOGIN_STATE); break; case MODE_SELECTION_STATE: logger->log("State: MODE_SELECTION"); selectionDialog = new SelectionDialog(_("Welcome to Aethyra"), _("You haven't selected a " "graphical mode to use yet. " "Which mode would you like " "to use?"), NULL, false); selectionDialog->addOption("sdl", "SDL"); selectionDialog->addOption("opengl", "OpenGL"); selectionDialog->addActionListener(&selectionListener); selectionDialog->requestMoveToTop(); break; case LOGIN_STATE: logger->log("State: LOGIN"); desktop->resetProgressBar(); if (loginData.skipLogin) { loginData.registerLogin = false; setState(LOGINSERV_CONNECT_STATE); } else desktop->changeCurrentDialog(new LoginDialog()); break; case REGISTER_STATE: logger->log("State: REGISTER"); desktop->changeCurrentDialog(new RegisterDialog()); break; case LOGINSERV_CONNECT_STATE: logger->log("State: ACCT_CONNECT"); desktop->useProgressBar(_("Connecting to account server...")); mLoginHandler.get()->login(); break; case SERVER_SELECT_STATE: logger->log("State: SERVER_SELECT"); // Only save the login data after a valid login if (loginData.remember) { config.setValue("host", loginData.hostname); config.setValue("username", loginData.username); } config.setValue("remember", loginData.remember); if (loginData.servers == 1) { loginData.hostname = ipToString(server_info[0]->address); loginData.port = server_info[0]->port; loginData.updateHost = server_info[0]->updateHost; setState(UPDATE_STATE); } else { desktop->changeCurrentDialog(new ServerListDialog()); if (options.chooseDefault || !options.playername.empty()) { currentDialog = desktop->getCurrentDialog(); ((ServerListDialog*) currentDialog)->action( gcn::ActionEvent(NULL, "ok")); } } break; case UPDATE_STATE: { logger->log("State: UPDATE"); const std::string &updateHost = (!options.updateHost.empty() ? options.updateHost : loginData.updateHost); if (!options.skipUpdate) { desktop->resetProgressBar(); desktop->changeCurrentDialog(new UpdaterWindow(updateHost)); } else { DownloadUpdates *download = new DownloadUpdates(updateHost, NULL); download->addUpdatesToResman(); destroy(download); setState(LOADDATA_STATE); } } break; case LOADDATA_STATE: logger->log("State: LOADDATA"); // Add customdata directory ResourceManager::getInstance()->searchAndAddArchives("customdata/", "zip", false); // Load XML databases ColorDB::load(); EffectDB::load(); EmoteDB::load(); ItemDB::load(); MonsterDB::load(); NPCDB::load(); SkillDB::load(); Being::load(); // Hairstyles // Reload in case there was a different wallpaper in the updates. desktop->reload(); setState(CHARSERV_CONNECT_STATE); break; case CHARSERV_CONNECT_STATE: logger->log("State: CHARSERV_CONNECT"); desktop->useProgressBar(_("Connecting to character server...")); network->unregisterHandler(mLoginHandler.get()); mCharServerHandler.get()->login(&mCharInfo); break; case CHAR_SELECT_STATE: logger->log("State: CHAR_SELECT"); desktop->resetProgressBar(); desktop->changeCurrentDialog(new CharSelectDialog(&mCharInfo, (loginData.sex == 0) ? GENDER_FEMALE : GENDER_MALE)); currentDialog = desktop->getCurrentDialog(); if (((CharSelectDialog*) currentDialog)->selectByName(options.playername)) options.chooseDefault = true; else ((CharSelectDialog*) currentDialog)->selectByName( config.getValue("lastCharacter", "")); if (options.chooseDefault) ((CharSelectDialog*) currentDialog)->action( gcn::ActionEvent(NULL, "ok")); break; case MAPSERV_CONNECT_STATE: logger->log("State: MAPSERV_CONNECT"); desktop->useProgressBar(_("Connecting to map server...")); network->unregisterHandler(mCharServerHandler.get()); mMapLoginHandler.get()->login(); break; case GAME_STATE: logger->log("State: GAME"); sound.fadeOutMusic(1000); game = new Game(); destroy(desktop); break; case QUIT_STATE: case LOGOUT_STATE: if (mState == QUIT_STATE) logger->log("State: QUIT"); else logger->log("State: LOGOUT"); sound.fadeOutMusic(1000); destroy(game); ColorDB::unload(); EffectDB::unload(); EmoteDB::unload(); ItemDB::unload(); MonsterDB::unload(); NPCDB::unload(); SkillDB::unload(); network->disconnect(); network->clearHandlers(); setState(mState == QUIT_STATE ? EXIT_STATE : START_STATE); break; case EXIT_STATE: logger->log("State: EXIT"); destroy(desktop); break; default: logger->log("State: Unknown state"); handleException(_("Unknown program state. Exiting."), EXIT_STATE); break; } }
void IpSwitcher::blockIp(uint32_t ip) { system(boost::str(boost::format(ConfigManager::instance()->getString(ConfigManager::ONBLOCKIP_COMMAND)) % ipToString(ip)).c_str()); m_blockedIps[ip] = getSystemTime(); }
void LoginHandler::handleMessage(Net::MessageIn &msg) { int code, worldCount; switch (msg.getId()) { case SMSG_CHAR_PASSWORD_RESPONSE: { // 0: acc not found, 1: success, 2: password mismatch, 3: pass too short int errMsg = msg.readInt8(); // Successful pass change if (errMsg == 1) { Client::setState(STATE_CHANGEPASSWORD_SUCCESS); } // pass change failed else { switch (errMsg) { case 0: errorMessage = _("Account was not found. Please re-login."); break; case 2: errorMessage = _("Old password incorrect."); break; case 3: errorMessage = _("New password too short."); break; default: errorMessage = _("Unknown error."); break; } Client::setState(STATE_ACCOUNTCHANGE_ERROR); } } break; case SMSG_UPDATE_HOST: int len; len = msg.readInt16() - 4; mUpdateHost = msg.readString(len); loginData.updateHost = mUpdateHost; logger->log("Received update host \"%s\" from login server.", mUpdateHost.c_str()); break; case SMSG_LOGIN_DATA: // Skip the length word msg.skip(2); clearWorlds(); worldCount = (msg.getLength() - 47) / 32; mToken.session_ID1 = msg.readInt32(); mToken.account_ID = msg.readInt32(); mToken.session_ID2 = msg.readInt32(); msg.skip(30); // unknown mToken.sex = msg.readInt8() ? GENDER_MALE : GENDER_FEMALE; for (int i = 0; i < worldCount; i++) { WorldInfo *world = new WorldInfo; world->address = msg.readInt32(); world->port = msg.readInt16(); world->name = msg.readString(20); world->online_users = msg.readInt32(); world->updateHost = mUpdateHost; msg.skip(2); // unknown logger->log("Network: Server: %s (%s:%d)", world->name.c_str(), ipToString(world->address), world->port); mWorlds.push_back(world); } Client::setState(STATE_WORLD_SELECT); break; case SMSG_LOGIN_ERROR: code = msg.readInt8(); logger->log("Login::error code: %i", code); switch (code) { case 0: errorMessage = _("Unregistered ID."); break; case 1: errorMessage = _("Wrong password."); break; case 2: errorMessage = _("Account expired."); break; case 3: errorMessage = _("Rejected from server."); break; case 4: errorMessage = _("You have been permanently banned from " "the game. Please contact the GM team."); break; case 5: errorMessage = _("Client too old."); break; case 6: errorMessage = strprintf(_("You have been temporarily " "banned from the game until " "%s.\nPlease contact the GM " "team via the forums."), msg.readString(20).c_str()); break; case 7: errorMessage = _("Server overpopulated."); break; case 9: errorMessage = _("This user name is already taken."); break; case 99: errorMessage = _("Username permanently erased."); break; default: errorMessage = _("Unknown error."); break; } Client::setState(STATE_ERROR); break; case SMSG_SERVER_VERSION_RESPONSE: { // TODO: verify these! msg.readInt8(); // -1 msg.readInt8(); // T msg.readInt8(); // M msg.readInt8(); // W unsigned int options = msg.readInt32(); mRegistrationEnabled = (options & 1); // Leave this last mVersionResponse = true; } break; } }
void CharServerHandler::handleMessage(Net::MessageIn &msg) { switch (msg.getId()) { case SMSG_CHAR_LOGIN: { msg.skip(2); // Length word msg.skip(20); // Unused // Derive number of characters from message length const int count = (msg.getLength() - 24) / 106; for (int i = 0; i < count; ++i) { Net::Character *character = new Net::Character; readPlayerData(msg, character); mCharacters.push_back(character); logger->log("CharServer: Player: %s (%d)", character->dummy->getName().c_str(), character->slot); } Client::setState(STATE_CHAR_SELECT); } break; case SMSG_CHAR_LOGIN_ERROR: switch (msg.readInt8()) { case 0: errorMessage = _("Access denied. Most likely, there are " "too many players on this server."); break; case 1: errorMessage = _("Cannot use this ID."); break; default: errorMessage = _("Unknown char-server failure."); break; } Client::setState(STATE_ERROR); break; case SMSG_CHAR_CREATE_SUCCEEDED: { Net::Character *character = new Net::Character; readPlayerData(msg, character); mCharacters.push_back(character); updateCharSelectDialog(); // Close the character create dialog if (mCharCreateDialog) { mCharCreateDialog->scheduleDelete(); mCharCreateDialog = 0; } } break; case SMSG_CHAR_CREATE_FAILED: new OkDialog(_("Error"), _("Failed to create character. Most " "likely the name is already taken.")); if (mCharCreateDialog) mCharCreateDialog->unlock(); break; case SMSG_CHAR_DELETE_SUCCEEDED: delete mSelectedCharacter; mCharacters.remove(mSelectedCharacter); mSelectedCharacter = 0; updateCharSelectDialog(); unlockCharSelectDialog(); new OkDialog(_("Info"), _("Character deleted.")); break; case SMSG_CHAR_DELETE_FAILED: unlockCharSelectDialog(); new OkDialog(_("Error"), _("Failed to delete character.")); break; case SMSG_CHAR_MAP_INFO: { msg.skip(4); // CharID, must be the same as player_node->charID GameHandler *gh = static_cast<GameHandler*>(Net::getGameHandler()); gh->setMap(msg.readString(16)); mapServer.hostname = ipToString(msg.readInt32()); mapServer.port = msg.readInt16(); // Prevent the selected local player from being deleted player_node = mSelectedCharacter->dummy; PlayerInfo::setBackend(mSelectedCharacter->data); mSelectedCharacter->dummy = 0; delete_all(mCharacters); mCharacters.clear(); updateCharSelectDialog(); mNetwork->disconnect(); Client::setState(STATE_CONNECT_GAME); } break; case SMSG_CHANGE_MAP_SERVER: { GameHandler *gh = static_cast<GameHandler*>(Net::getGameHandler()); gh->setMap(msg.readString(16)); int x = msg.readInt16(); int y = msg.readInt16(); mapServer.hostname = ipToString(msg.readInt32()); mapServer.port = msg.readInt16(); mNetwork->disconnect(); Client::setState(STATE_CHANGE_MAP); player_node->setTileCoords(x, y); player_node->setMap(0); } break; } }
void LoginRecv::processLoginData(Net::MessageIn &msg) { msg.readInt16("len"); loginHandler->clearWorlds(); int offset = 0; int serverLen = 0; if (msg.getVersion() >= 20170315) { offset = 47 + 17; serverLen = 32 + 128; } else { offset = 47; serverLen = 32; } const int worldCount = (msg.getLength() - offset) / serverLen; Ea::LoginRecv::mToken.session_ID1 = msg.readInt32("session id1"); Ea::LoginRecv::mToken.account_ID = msg.readBeingId("accound id"); Ea::LoginRecv::mToken.session_ID2 = msg.readInt32("session id2"); msg.readInt32("old ip"); loginData.lastLogin = msg.readString(24, "last login"); msg.readInt16("unused"); // reserve bits for future usage Ea::LoginRecv::mToken.sex = Being::intToGender(CAST_U8( msg.readUInt8("gender") & 3U)); if (msg.getVersion() >= 20170315) { msg.readString(16, "twitter auth token"); msg.readUInt8("twitter flag"); } for (int i = 0; i < worldCount; i++) { WorldInfo *const world = new WorldInfo; world->address = msg.readInt32("ip address"); world->port = msg.readInt16("port"); world->name = msg.readString(20, "name"); world->online_users = msg.readInt16("online number"); config.setValue("updatehost", Ea::LoginRecv::mUpdateHost); world->updateHost = Ea::LoginRecv::mUpdateHost; msg.readInt16("maintenance"); msg.readInt16("new"); if (msg.getVersion() >= 20170315) { for (int f = 0; f < 32; f ++) msg.readInt32("unused2"); } logger->log("Network: Server: %s (%s:%d)", world->name.c_str(), ipToString(world->address), world->port); Ea::LoginRecv::mWorlds.push_back(world); } client->setState(State::WORLD_SELECT); }
void LoginHandler::handleMessage(MessageIn *msg) { int code; switch (msg->getId()) { case SMSG_CONNECTION_PROBLEM: code = msg->readInt8(); logger->log("Connection problem: %i", code); switch (code) { case 0: errorMessage = _("Authentication failed"); break; case 1: errorMessage = _("No servers available"); break; case 2: errorMessage = _("This account is already logged in"); break; default: errorMessage = _("Unknown connection error"); break; } state = ERROR_STATE; break; case SMSG_UPDATE_HOST: int len; len = msg->readInt16() - 4; mUpdateHost = msg->readString(len); logger->log("Received update host \"%s\" from login server", mUpdateHost.c_str()); break; case 0x0069: // Skip the length word msg->skip(2); n_server = (msg->getLength() - 47) / 32; server_info = (SERVER_INFO**) malloc(sizeof(SERVER_INFO*) * n_server); mLoginData->session_ID1 = msg->readInt32(); mLoginData->account_ID = msg->readInt32(); mLoginData->session_ID2 = msg->readInt32(); msg->skip(30); // unknown mLoginData->sex = msg->readInt8(); for (int i = 0; i < n_server; i++) { server_info[i] = new SERVER_INFO; server_info[i]->address = msg->readInt32(); server_info[i]->port = msg->readInt16(); server_info[i]->name = msg->readString(20); server_info[i]->online_users = msg->readInt32(); server_info[i]->updateHost = mUpdateHost; msg->skip(2); // unknown logger->log("Network: Server: %s (%s:%d)", server_info[i]->name.c_str(), ipToString(server_info[i]->address), server_info[i]->port); } state = CHAR_SERVER_STATE; break; case 0x006a: code = msg->readInt8(); logger->log("Login::error code: %i", code); switch (code) { case 0: errorMessage = _("Unregistered ID"); break; case 1: errorMessage = _("Wrong password"); break; case 2: errorMessage = _("Account expired"); break; case 3: errorMessage = _("Rejected from server"); break; case 4: errorMessage = _("You have been permanently banned from " "the game. Please contact the GM Team."); break; case 6: errorMessage = strprintf(_("You have been temporarily " "banned from the game until " "%s.\nPlease contact the GM " "team via the forums."), msg->readString(20).c_str()); break; case 9: errorMessage = _("This user name is already taken"); break; default: errorMessage = _("Unknown error"); break; } state = ERROR_STATE; break; } }
void CharServerHandler::handleMessage(Net::MessageIn &msg) { switch (msg.getId()) { case SMSG_CHAR_LOGIN: processCharLogin(msg); break; case SMSG_CHAR_LOGIN_ERROR: processCharLoginError(msg); break; case SMSG_CHAR_CREATE_SUCCEEDED: processCharCreate(msg, false); break; case SMSG_CHAR_CREATE_SUCCEEDED2: processCharCreate(msg, true); break; case SMSG_CHAR_CREATE_FAILED: processCharCreateFailed(msg); break; case SMSG_CHAR_DELETE_SUCCEEDED: processCharDelete(msg); break; case SMSG_CHAR_DELETE_FAILED: processCharDeleteFailed(msg); break; case SMSG_CHAR_MAP_INFO: { // msg.skip(4); // CharID, must be the same as player_node->charID PlayerInfo::setCharId(msg.readInt32()); GameHandler *gh = static_cast<GameHandler*>(Net::getGameHandler()); gh->setMap(msg.readString(16)); if (config.getBoolValue("usePersistentIP")) { msg.readInt32(); mapServer.hostname = Client::getServerName(); } else { mapServer.hostname = ipToString(msg.readInt32()); } mapServer.port = msg.readInt16(); // Prevent the selected local player from being deleted player_node = mSelectedCharacter->dummy; PlayerInfo::setBackend(mSelectedCharacter->data); mSelectedCharacter->dummy = nullptr; delete_all(mCharacters); mCharacters.clear(); updateCharSelectDialog(); if (mNetwork) mNetwork->disconnect(); Client::setState(STATE_CONNECT_GAME); } break; case SMSG_CHANGE_MAP_SERVER: { GameHandler *gh = static_cast<GameHandler*>(Net::getGameHandler()); if (!gh || !mNetwork) return; gh->setMap(msg.readString(16)); int x = msg.readInt16(); int y = msg.readInt16(); mapServer.hostname = ipToString(msg.readInt32()); mapServer.port = msg.readInt16(); mNetwork->disconnect(); Client::setState(STATE_CHANGE_MAP); if (player_node) { player_node->setTileCoords(x, y); player_node->setMap(nullptr); } } break; default: break; } }
void OlsrEventClient::handleRead ( const boost::system::error_code& error ) { string addr1, addr2; //std::cout << ">>> OlsrEventClient::handleRead (error " << error << ")" << std::endl; if ( !error ) { if (m_messageRead.type>=OlsrEventMessage::DEV_CMD_RESET_TC && m_messageRead.type<=OlsrEventMessage::DEV_CMD_SET_ALIAS_ADDR) DBG_DEV(3,"Received event %ld (%s)",m_messageRead.type, g_tabCmdName[m_messageRead.type-1]); else DBG_DEV(3,"Received unknown event %ld",m_messageRead.type); switch(m_messageRead.type) { case OlsrEventMessage::DEV_CMD_RESET_TC : tc_free_data(0); break; case OlsrEventMessage::DEV_CMD_ADD_NODE : DBG_DEV(2,"Add node (%s)", ipToString(m_messageRead.addr_1)); tc_add_node(m_messageRead.addr_1); break; case OlsrEventMessage::DEV_CMD_REMOVE_NODE : DBG_DEV(2,"Remove node (%s)", ipToString(m_messageRead.addr_1)); tc_remove_node(m_messageRead.addr_1); break; case OlsrEventMessage::DEV_CMD_ADD_LINK : addr1 = ipToString(m_messageRead.addr_1); addr2 = ipToString(m_messageRead.addr_2); DBG_DEV(2,"Add link (%s --> %s)", addr1.c_str(), addr2.c_str()); tc_add_link(m_messageRead.addr_1,m_messageRead.addr_2,m_messageRead.value); break; case OlsrEventMessage::DEV_CMD_REMOVE_LINK : DBG_DEV(2,"Remove link (%s --> %s)", ipToString(m_messageRead.addr_1), ipToString(m_messageRead.addr_2)); tc_remove_link(m_messageRead.addr_1,m_messageRead.addr_2); break; case OlsrEventMessage::DEV_CMD_ADD_ALIAS : DBG_DEV(2,"Add alias (%s --> %s)", ipToString(m_messageRead.addr_1), ipToString(m_messageRead.addr_2)); tc_add_alias(m_messageRead.addr_1,m_messageRead.addr_2); break; case OlsrEventMessage::DEV_CMD_REMOVE_ALIAS : DBG_DEV(2,"Remove alias (%s --> %s)", ipToString(m_messageRead.addr_1), ipToString(m_messageRead.addr_2)); tc_remove_alias(m_messageRead.addr_1,m_messageRead.addr_2); break; case OlsrEventMessage::DEV_CMD_SET_LOCAL_ADDR : DBG_DEV(2,"Set local Ip %s mask %s", ipToString(m_messageRead.addr_1), ipToString(m_messageRead.addr_2)); tc_set_local_addr(m_messageRead.addr_1,m_messageRead.addr_2); break; case OlsrEventMessage::DEV_CMD_SET_ALIAS_ADDR : DBG_DEV(2,"Set local alias %s mask %s", ipToString(m_messageRead.addr_1), ipToString(m_messageRead.addr_2)); tc_set_local_alias(m_messageRead.addr_1,m_messageRead.addr_2); break; case OlsrEventMessage::DEV_CMD_SET_DEBUG_LEVEL : DBG_DEV(2,"Set debug level to %d for component %d", m_messageRead.addr_2, m_messageRead.addr_1); switch(m_messageRead.addr_1) { case 1: g_dbg_hook = m_messageRead.addr_2; break; case 2: g_dbg_device = m_messageRead.addr_2; break; case 3: g_dbg_module = m_messageRead.addr_2; break; case 4: g_dbg_djk = m_messageRead.addr_2; break; default: g_dbg_hook = m_messageRead.addr_2; g_dbg_device = m_messageRead.addr_2; g_dbg_module = m_messageRead.addr_2; g_dbg_djk = m_messageRead.addr_2; break; }; break; default: MSG_FAILED("SEREADEMO invalid cmd type : %ld",m_messageRead.type); } //m_messageRead.reset(); // On réécoute m_tcpConnection->async_read ( m_messageRead, boost::bind ( &OlsrEventClient::handleRead, this, boost::asio::placeholders::error ) ); } else { doClose(); } }