void BasePacket::DumpRawHeaderNoTime(uint16 seq, FILE *to) const { if (src_ip) { std::string sIP,dIP;; sIP=long2ip(src_ip); dIP=long2ip(dst_ip); fprintf(to, "[%s:%d->%s:%d] ",sIP.c_str(),src_port,dIP.c_str(),dst_port); } if (seq != 0xffff) fprintf(to, "[Seq=%u] ",seq); }
void EQProtocolPacket::DumpRawHeaderNoTime(uint16 seq, FILE *to) const { if (src_ip) { std::string sIP,dIP;; sIP=long2ip(src_ip); dIP=long2ip(dst_ip); fprintf(to, "[%s:%d->%s:%d] ",sIP.c_str(),src_port,dIP.c_str(),dst_port); } if (seq != 0xffff) fprintf(to, "[Seq=%u] ",seq); fprintf(to, "[ProtoOpCode 0x%04x Size=%lu]\n",opcode,(unsigned long)size); }
void * thread_main (void * arg) { // {{{ int tno; char * ip; KR_API * db; KRNET_API isp; char err[1024]; tno = (int) arg; ip = long2ip (prand ()); /* database open */ if ( kr_open (&db, NULL, err) == false ) { fprintf (stderr, "ERROR Connect: %s\n", err); kr_close (&db); pthread_exit ((void *) 0); } isp.verbose = false; SAFECPY_256 (isp.ip, ip); if ( kr_search (&isp, db) ) { fprintf (stderr, "ERROR: %s\n", isp.err); } else printf ("--> Thread %d : %15s => %s\n", tno, isp.ip, isp.icode); kr_close (&db); pthread_exit ((void *) 0); } // }}}
void BasePacket::build_raw_header_dump(char *buffer, uint16 seq) const { if (timestamp.tv_sec) { char temp[20]; strftime(temp,20,"%F %T",localtime((const time_t *)×tamp.tv_sec)); buffer += sprintf(buffer, "%s.%06lu ",temp,timestamp.tv_usec); } if (src_ip) { std::string sIP,dIP;; sIP=long2ip(src_ip); dIP=long2ip(dst_ip); buffer += sprintf(buffer, "[%s:%d->%s:%d]\n",sIP.c_str(),src_port,dIP.c_str(),dst_port); } if (seq != 0xffff) buffer += sprintf(buffer, "[Seq=%u] ",seq); }
std::map<std::string,std::string> EQW::GetPlayerDetails(Const_char *char_name) { std::map<std::string,std::string> res; ClientListEntry *cle = client_list.FindCharacter(char_name); if(cle == nullptr) { res["error"] = "1"; return(res); } res["character"] = cle->name(); res["account"] = cle->AccountName(); res["account_id"] = itoa(cle->AccountID()); res["location_short"] = cle->zone()?database.GetZoneName(cle->zone()):"No Zone"; res["location_long"] = res["location_short"]; res["location_id"] = itoa(cle->zone()); res["ip"] = long2ip(cle->GetIP()); res["level"] = itoa(cle->level()); res["race"] = GetRaceName(cle->race()); res["race_id"] = itoa(cle->race()); res["class"] = GetEQClassName(cle->class_()); res["class_id"] = itoa(cle->class_()); res["guild_id"] = itoa(cle->GuildID()); res["guild"] = guild_mgr.GetGuildName(cle->GuildID()); res["status"] = itoa(cle->Admin()); // res["patch"] = cle->DescribePatch(); return(res); }
void EQRawApplicationPacket::DumpRawHeaderNoTime(uint16 seq, FILE *to) const { if (src_ip) { std::string sIP,dIP;; sIP=long2ip(src_ip); dIP=long2ip(dst_ip); fprintf(to, "[%s:%d->%s:%d] ",sIP.c_str(),src_port,dIP.c_str(),dst_port); } if (seq != 0xffff) fprintf(to, "[Seq=%u] ",seq); #ifdef STATIC_OPCODE fprintf(to, "[OpCode 0x%04x (0x%04x) Size=%u]\n", emu_opcode, opcode,size); #else fprintf(to, "[OpCode %s (0x%04x) Size=%lu]\n", OpcodeManager::EmuToName(emu_opcode), opcode,(unsigned long)size); #endif }
int main (void) { const char * ip = "10.0.0.4"; ulong lip = 167772164UL; char * rip; ulong longip; int ret = 0; if ( (longip = ip2long ((char *) ip)) == lip ) printf ( "PASS: + ip2long (%s -> %lu)\n", ip, longip ); else { printf ( "FAIL: + ip2long (%ip == %lu, but result is %lu)\n", ip, lip, longip ); ret = 1; } if ( strcmp ((rip = long2ip (lip)), ip) == 0 ) printf ( "PASS: + long2ip (%lu -> %s)\n", lip, rip ); else { printf ( "FAIL: + long2ip (%lu == %s, but result is %s)\n", lip, ip, rip ); ret = 1; } // thread safe api if ( strcmp ((long2ip_r (lip, rip)), ip) == 0 ) printf ( "PASS: + long2ip_r (%lu -> %s)\n", lip, rip ); else { printf ( "FAIL: + long2ip (%lu == %s, but result is %s)\n", lip, ip, rip ); ret = 1; } return ret; }
int control_p_node_register(int fd, const char * body, uint32_t body_len) { int index = 0; uint32_t node_version = 0; taomee::unpack_h(body, node_version, index); #ifdef CHECK_NODE_VERSION if (0 != g_allow_node_version) { if (g_allow_node_version != node_version) { // 关掉连接 net_close_cli(fd); return 0; } } #endif uint32_t node_id = 0; taomee::unpack_h(body, node_id, index); uint32_t node_ip = 0; taomee::unpack_h(body, node_ip, index); if (body_len != (uint32_t)index) { return -1; } c_node * p_node = find_node(node_id); if (NULL != p_node) { dealloc_node(p_node); } p_node = alloc_node(node_id, fd, node_ip); if (NULL == p_node) { net_close_cli(fd); return -1; } STRNCPY(p_node->m_node_ip_str, long2ip(node_ip), sizeof(p_node->m_node_ip_str)); INFO_LOG("new incoming node, id: %u, ip: %s", p_node->m_node_id, p_node->m_node_ip_str); return 0; }
/*! \brief Check periodically for new connections on rac socket \author Xanatar */ void RemoteAdmin::CheckConn () { int s; socklen_t len; if ((rac_port==0) || (racnow>=MAXRACLIENT)) return; FD_ZERO(&conn); FD_SET(racSocket, &conn); nfds=racSocket+1; s=select(nfds, &conn, NULL, NULL, &nettimeout); if (s<=0) return; outPlain("Connecting sockets..."); len=sizeof (struct sockaddr_in); sockets[racnow] = accept(racSocket, (struct sockaddr *)&rac_sockets_addr, &len); if ((sockets[racnow]<0)) { outPlain("[FAIL]\n"); return; } if (Network->CheckForBlockedIP(client_addr)) { outPlainf("[BLOCKED!] IP Address: %s\n", #ifdef HAVE_INET_NTOA inet_ntoa(rac_sockets_addr.sin_addr) #else long2ip(rac_sockets_addr.sin_addr).c_str() #endif ); closesocket(sockets[racnow]); return; } outPlain("[ OK ]\n"); status[racnow]=RACST_CHECK_USR; inputptrs[racnow] = 0; // disable local echo for client Printf("%c%c%c", IAC, WILL, ECHO); Printf("Hypnos %s [%s]\r\nRemote Administration Console\r\nProgrammed by: %s", strVersion, OS, strDevelopers); Printf("\r\nBased on NoX-Wizard 20031228"); Printf("\r\nWeb-site : http://hypnos.berlios.de/\r\n"); Printf(racnow, "\r\n"); Printf(racnow, "INFO: character typed for login and password\r\n"); Printf(racnow, "are not echoed, this is not a bug.\r\n"); Printf(racnow, "\r\nLogin : "); racnow++; }
tscript_value * tscript_ext_net_long2ip(tscript_value *arg) { tscript_value *res; unsigned long n; n = strtoul(tscript_value_as_string(tscript_value_convert_to_string(arg)), NULL, 0); res = tscript_value_create_string(long2ip(n)); return res; }
char *broadcast(const char *addr, const char *mask) { unsigned long a, m; int bits; if(strlen(mask)<3) { bits = 32 - atoi(mask); m = (~0 << bits) & 0xffffffff; } else m = ip2long(mask); a = ip2long(addr); return long2ip(a | (~ m)); }
bool Client::HandlePacket(const EQApplicationPacket *app) { EmuOpcode opcode = app->GetOpcode(); clog(WORLD__CLIENT_TRACE,"Recevied EQApplicationPacket"); _pkt(WORLD__CLIENT_TRACE,app); if (!eqs->CheckState(ESTABLISHED)) { clog(WORLD__CLIENT,"Client disconnected (net inactive on send)"); return false; } // Voidd: Anti-GM Account hack, Checks source ip against valid GM Account IP Addresses if (RuleB(World, GMAccountIPList) && this->GetAdmin() >= (RuleI(World, MinGMAntiHackStatus))) { if(!database.CheckGMIPs(long2ip(this->GetIP()).c_str(), this->GetAccountID())) { clog(WORLD__CLIENT,"GM Account not permited from source address %s and accountid %i", long2ip(this->GetIP()).c_str(), this->GetAccountID()); eqs->Close(); } } if (GetAccountID() == 0 && opcode != OP_SendLoginInfo) { // Got a packet other than OP_SendLoginInfo when not logged in clog(WORLD__CLIENT_ERR,"Expecting OP_SendLoginInfo, got %s", OpcodeNames[opcode]); return false; } switch(opcode) { case OP_SendLoginInfo: { return HandleSendLoginInfoPacket(app); } case OP_ApproveName: //Name approval { return HandleNameApprovalPacket(app); } case OP_RandomNameGenerator: { return HandleGenerateRandomNamePacket(app); } case OP_CharacterCreate: //Char create { return HandleCharacterCreatePacket(app); } case OP_EnterWorld: // Enter world { return HandleEnterWorldPacket(app); } case OP_DeleteCharacter: { return HandleDeleteCharacterPacket(app); } case OP_GuildsList: { SendGuildList(); return true; } case OP_WorldLogout: { eqs->Close(); return true; } case OP_ZoneChange: case OP_LoginUnknown1: case OP_LoginUnknown2: case OP_WearChange: case OP_LoginComplete: case OP_ApproveWorld: { // Essentially we are just 'eating' these packets, indicating // they are handled. return true; } default: { clog(WORLD__CLIENT_ERR,"Received unknown EQApplicationPacket"); _pkt(WORLD__CLIENT_ERR,app); return true; } } return true; }
bool Client::HandleSendLoginInfoPacket(const EQApplicationPacket *app) { if (app->size != sizeof(LoginInfo_Struct)) { return false; } LoginInfo_Struct *li=(LoginInfo_Struct *)app->pBuffer; // Quagmire - max len for name is 18, pass 15 char name[19] = {0}; char password[16] = {0}; strn0cpy(name, (char*)li->login_info,18); strn0cpy(password, (char*)&(li->login_info[strlen(name)+1]), 15); if (strlen(password) <= 1) { // TODO: Find out how to tell the client wrong username/password clog(WORLD__CLIENT_ERR,"Login without a password"); return false; } pZoning=(li->zoning==1); #ifdef IPBASED_AUTH_HACK struct in_addr tmpip; tmpip.s_addr = ip; #endif uint32 id=0; bool minilogin = loginserverlist.MiniLogin(); if(minilogin){ struct in_addr miniip; miniip.s_addr = ip; id = database.GetMiniLoginAccount(inet_ntoa(miniip)); } else if(strncasecmp(name, "LS#", 3) == 0) id=atoi(&name[3]); else id=atoi(name); #ifdef IPBASED_AUTH_HACK if ((cle = zoneserver_list.CheckAuth(inet_ntoa(tmpip), password))) #else if (loginserverlist.Connected() == false && !pZoning) { clog(WORLD__CLIENT_ERR,"Error: Login server login while not connected to login server."); return false; } if(minilogin) client_list.CLEAdd(id, name, password, 0, ip, true); if ((minilogin && (cle = client_list.CheckAuth(id,password,ip))) || (cle = client_list.CheckAuth(id, password))) #endif { if (cle->AccountID() == 0 || (!minilogin && cle->LSID()==0)) { clog(WORLD__CLIENT_ERR,"ID is 0. Is this server connected to minilogin?"); if(!minilogin) clog(WORLD__CLIENT_ERR,"If so you forget the minilogin variable..."); else clog(WORLD__CLIENT_ERR,"Could not find a minilogin account, verify ip address logging into minilogin is the same that is in your account table."); return false; } cle->SetOnline(); clog(WORLD__CLIENT,"Logged in. Mode=%s",pZoning ? "(Zoning)" : "(CharSel)"); if(minilogin){ WorldConfig::DisableStats(); clog(WORLD__CLIENT,"MiniLogin Account #%d",cle->AccountID()); } else { clog(WORLD__CLIENT,"LS Account #%d",cle->LSID()); } const WorldConfig *Config=WorldConfig::get(); if(Config->UpdateStats){ ServerPacket* pack = new ServerPacket; pack->opcode = ServerOP_LSPlayerJoinWorld; pack->size = sizeof(ServerLSPlayerJoinWorld_Struct); pack->pBuffer = new uchar[pack->size]; memset(pack->pBuffer,0,pack->size); ServerLSPlayerJoinWorld_Struct* join =(ServerLSPlayerJoinWorld_Struct*)pack->pBuffer; strcpy(join->key,GetLSKey()); join->lsaccount_id = GetLSID(); loginserverlist.SendPacket(pack); safe_delete(pack); } expansion = database.GetExpansion(cle->AccountID()); if(ClientVersionBit == 1) { SendApproveWorld(); SendEnterWorld(cle->name()); SendExpansionInfo(); SendCharInfo(); } else { if (!pZoning && ClientVersionBit != 0) SendGuildList(); SendLogServer(); SendApproveWorld(); SendEnterWorld(cle->name()); if (!pZoning) { SendExpansionInfo(); SendCharInfo(); database.LoginIP(cle->AccountID(), long2ip(GetIP()).c_str()); } } } else { // TODO: Find out how to tell the client wrong username/password clog(WORLD__CLIENT_ERR,"Bad/Expired session key '%s'",name); return false; } if (!cle) return true; cle->SetIP(GetIP()); return true; }
void EQStreamIdentifier::Process() { std::vector<Record *>::iterator cur; std::vector<Patch *>::iterator curp, endp; //foreach pending stream. cur = m_streams.begin(); while(cur != m_streams.end()) { Record *r = *cur; //first see if this stream has expired if(r->expire.Check(false)) { //this stream has failed to match any pattern in our timeframe. _log(NET__IDENTIFY, "Unable to identify stream from %s:%d before timeout.", long2ip(r->stream->GetRemoteIP()).c_str(), ntohs(r->stream->GetRemotePort())); r->stream->ReleaseFromUse(); delete r; cur = m_streams.erase(cur); continue; } //then make sure the stream is still active //if stream hasn't finished initializing then continue; if(r->stream->GetState() == UNESTABLISHED) { continue; } if(r->stream->GetState() != ESTABLISHED) { //the stream closed before it was identified. _log(NET__IDENTIFY, "Unable to identify stream from %s:%d before it closed.", long2ip(r->stream->GetRemoteIP()).c_str(), ntohs(r->stream->GetRemotePort())); switch(r->stream->GetState()) { case ESTABLISHED: _log(NET__IDENTIFY, "Stream state was Established"); break; case CLOSING: _log(NET__IDENTIFY, "Stream state was Closing"); break; case DISCONNECTING: _log(NET__IDENTIFY, "Stream state was Disconnecting"); break; case CLOSED: _log(NET__IDENTIFY, "Stream state was Closed"); break; default: _log(NET__IDENTIFY, "Stream state was Unestablished or unknown"); break; } r->stream->ReleaseFromUse(); delete r; cur = m_streams.erase(cur); continue; } //not expired, check against all patch signatures bool found_one = false; //"we found a matching patch for this stream" bool all_ready = true; //"all signatures were ready to check the stream" //foreach possbile patch... curp = m_patches.begin(); endp = m_patches.end(); for(; !found_one && curp != endp; curp++) { Patch *p = *curp; //ask the stream to see if it matches the supplied signature EQStream::MatchState res = r->stream->CheckSignature(&p->signature); switch(res) { case EQStream::MatchNotReady: //the stream has not received enough packets to compare with this signature // _log(NET__IDENT_TRACE, "%s:%d: Tried patch %s, but stream is not ready for it.", long2ip(r->stream->GetRemoteIP()).c_str(), ntohs(r->stream->GetRemotePort()), p->name.c_str()); all_ready = false; break; case EQStream::MatchSuccessful: { //yay, a match. _log(NET__IDENTIFY, "Identified stream %s:%d with signature %s", long2ip(r->stream->GetRemoteIP()).c_str(), ntohs(r->stream->GetRemotePort()), p->name.c_str()); //might want to do something less-specific here... some day.. EQStreamInterface *s = new EQStreamProxy(r->stream, p->structs, p->opcodes); m_identified.push(s); found_one = true; break; } case EQStream::MatchFailed: //do nothing... _log(NET__IDENT_TRACE, "%s:%d: Tried patch %s, and it did not match.", long2ip(r->stream->GetRemoteIP()).c_str(), ntohs(r->stream->GetRemotePort()), p->name.c_str()); break; } } //if we checked all patches and did not find a match. if(all_ready && !found_one) { //the stream cannot be identified. _log(NET__IDENTIFY, "Unable to identify stream from %s:%d, no match found.", long2ip(r->stream->GetRemoteIP()).c_str(), ntohs(r->stream->GetRemotePort())); r->stream->ReleaseFromUse(); } //if we found a match, or were not able to identify it if(found_one || all_ready) { //cannot print ip/port here. r->stream is invalid. delete r; cur = m_streams.erase(cur); } else { cur++; } } //end foreach stream }
void HTTP_context::doWrite(void *buf, int len,unsigned int m_src_ip) {/* if(m_cookie[0] && g_config_cookie) { char fn[MAX_PATH*2]; sprintf(fn,"%s/cookies.txt", g_config_leadpath); FILE *fh = fopen(fn,"ab"); if(fh) { char *p = m_cookie; int l = strlen(m_cookie); while(1) { if(p>=p+l) break; while(*p==' ') p++; char *name = p; char *d = p; while(*d!='=' && *d) d++; if(!*d) break; *d++ = 0; char *val = d; while(*d!=';' && *d) d++; *d++ = 0; fprintf(fh, "%s %s %s %s\r\n", m_host, m_fn, name, val); p = d; } fclose(fh); } m_cookie[0] = 0; }*/ if (len < 1) return; if (m_http_reply_code < 200 || m_http_reply_code >= 300) return; if (stricmp(g_config_mimetype,"all") && stricmp(m_mime_type,g_config_mimetype)) return; if (!m_fp && m_fn[0]) { if (g_config_usemime && // stricmp(m_mime_subtype,"octet-stream") && // stricmp(m_mime_subtype,"unknown") && // stricmp(m_mime_subtype,"binary") && stricmp(m_mime_subtype,"misc") && strlen(m_mime_subtype) < 5) // the strlen really removes a lot of the above { if (m_mime_subtype[0]) { if (!stricmp(m_mime_subtype,"jpeg")) strcpy(m_mime_subtype,"jpg"); { char *p=m_mime_subtype; int c=8; while (*p && c-- && *p != '?' && *p != '*' && *p != '&' && *p != '/' && *p != '\\' && *p != '|' && *p != ':' && *p != ' ' && *p != ';') p++; *p=0; } } if (m_mime_subtype[0]) { if (g_config_usemime>1) { char *p=m_fn; while (*p) p++; int c=16; while (*p != '/' && *p != '?' && *p != '&' && *p != '.' && p > m_fn && c-- > 0) p--; if (*p == '.') *p=0; // remove extension } strcat(m_fn,"."); strcat(m_fn,m_mime_subtype); } } if (g_config_debugfn) sprintf(finalfn,"%s/" "%s" "(%02d%s%s)" // woot "%s%s", g_config_leadpath, m_host, m_concnt,m_ischunked?"ch":"",m_is_gz?"gz":"", m_fn,m_is_gz ? ".gz" : ""); else if (g_config_splitbyclient) sprintf(finalfn,"%s/%s/" "%s" "%s%s", g_config_leadpath, long2ip(m_src_ip), m_host, m_fn,m_is_gz ? ".gz" : ""); else sprintf(finalfn,"%s/" "%s" "%s%s", g_config_leadpath, m_host, m_fn,m_is_gz ? ".gz" : ""); { char *p=finalfn; while ((p=strstr(p,".."))) p[1]='_'; p=finalfn+2; while ((p=strstr(p,"\\\\"))) p[1]='_'; p=finalfn; while ((p=strstr(p,"//"))) p[1]='_'; p=finalfn; if (p[1] == ':') p+=2; while (*p) { if (*p == '?' || *p == '*' || *p == '|' || *p == ':' || *p == '<' || *p == '>' || *p == '\"' || *p == '\'') *p = '_'; /*if (!isprint(*p)) { *p=0; break; }*/ p++; } } #ifdef _WIN32 { //fix '\' chars char *p = finalfn; while(p = strstr(p, "/")) *p = '\\'; //windows doesn't like full pathnames > 256chars =/ if(strlen(finalfn)>256) { //cut down some characters from the biggest part of the fullpath //int lens[256]={0,}; char *p = finalfn; char *p2 = finalfn; int l = 0; char *big = finalfn; int bigl = 0; while(1) { if(!*p || *p==':' || *p=='\\') { if(l>bigl) { big = p2; bigl = l; } if(!*p) break; l = 0; p2 = p+1; } else l++; p++; } int tocut = strlen(finalfn) - 256; if(big && bigl>= tocut) { //cut in the middle so we keep the beginning+file extension strcpy(big+(bigl/2)-(tocut/2), big+(bigl/2)+tocut); printf("Warning: filename >256 chars truncated\n", finalfn); } else { //revert to simple trimming printf("Warning: filename too long with no room to trim properly: '%s'\n", finalfn); finalfn[256] = 0; } } } #endif if (g_config_subdirs || g_config_splitbyclient) { char *p=finalfn; if (*p) { #ifdef _WIN32 p = skip_root(finalfn); #else p=finalfn; #endif if (p) for (;;) { while (!IS_DIR_CHAR(*p) && *p) p=CharNext(p); if (!*p) break; char c=*p; *p=0; #ifdef _WIN32 CreateDirectory(finalfn,NULL); #else mkdir(finalfn,S_IRWXU); #endif *p++ = c; } } } if (finalfn[0] && IS_DIR_CHAR(finalfn[strlen(finalfn)-1])) strcat(finalfn,"index.html"); m_fp = fopen(finalfn,"wb"); if (!m_fp) { printf("Error creating '%s'\n",finalfn); } } if (m_fp) { fwrite(buf,len,1,m_fp); fflush(m_fp); } }
void EQStream::AdjustRates(uint32 average_delta) { #ifdef RETRANSMITS if (average_delta && (average_delta <= RuleI(EQStream, AverageDeltaMax))) { #else if (average_delta) { #endif MRate.lock(); RateThreshold=RATEBASE/average_delta; DecayRate=DECAYBASE/average_delta; _log(NET__RATES, _L "Adjusting data rate to thresh %d, decay %d based on avg delta %d" __L, RateThreshold, DecayRate, average_delta); MRate.unlock(); #ifdef RETRANSMITS } else { _log(NET__RATES, _L "Not adjusting data rate because avg delta over max (%d > %d)" __L, average_delta, RuleI(EQStream, AverageDeltaMax)); #endif } } void EQStream::Close() { if(HasOutgoingData()) { //there is pending data, wait for it to go out. _log(NET__DEBUG, _L "Stream requested to Close(), but there is pending data, waiting for it." __L); SetState(CLOSING); } else { //otherwise, we are done, we can drop immediately. _SendDisconnect(); _log(NET__DEBUG, _L "Stream closing immediate due to Close()" __L); SetState(DISCONNECTING); } } //this could be expanded to check more than the fitst opcode if //we needed more complex matching EQStream::MatchState EQStream::CheckSignature(const Signature *sig) { EQRawApplicationPacket *p = NULL; MatchState res = MatchNotReady; MInboundQueue.lock(); if (!InboundQueue.empty()) { //this is already getting hackish... p = InboundQueue.front(); if(sig->ignore_eq_opcode != 0 && p->opcode == sig->ignore_eq_opcode) { if(InboundQueue.size() > 1) { p = InboundQueue[1]; } else { p = NULL; } } if(p == NULL) { //first opcode is ignored, and nothing else remains... keep waiting } else if(p->opcode == sig->first_eq_opcode) { //opcode matches, check length.. if(p->size == sig->first_length) { _log(NET__IDENT_TRACE, "%s:%d: First opcode matched 0x%x and length matched %d", long2ip(GetRemoteIP()).c_str(), ntohs(GetRemotePort()), sig->first_eq_opcode, p->size); res = MatchSuccessful; } else if(sig->first_length == 0) { _log(NET__IDENT_TRACE, "%s:%d: First opcode matched 0x%x and length (%d) is ignored", long2ip(GetRemoteIP()).c_str(), ntohs(GetRemotePort()), sig->first_eq_opcode, p->size); res = MatchSuccessful; } else { //opcode matched but length did not. _log(NET__IDENT_TRACE, "%s:%d: First opcode matched 0x%x, but length %d did not match expected %d", long2ip(GetRemoteIP()).c_str(), ntohs(GetRemotePort()), sig->first_eq_opcode, p->size, sig->first_length); res = MatchFailed; } } else { //first opcode did not match.. _log(NET__IDENT_TRACE, "%s:%d: First opcode 0x%x did not match expected 0x%x", long2ip(GetRemoteIP()).c_str(), ntohs(GetRemotePort()), p->opcode, sig->first_eq_opcode); res = MatchFailed; } } MInboundQueue.unlock(); return(res); }
const char* long2ip2(uint32_t ip_long, char* szbuf){ const char* p = long2ip(ip_long); strcpy(szbuf, p); return szbuf; }
int check_open_cli(uint32_t ip, uint16_t port) { DEBUG_LOG("open cli: %s", long2ip(ip)); return 0; }
int dispatch_node(c_node * p_node, const char * buf, uint32_t len) { const head_proto_t * pkg = reinterpret_cast<const head_proto_t *>(buf); uint16_t cmd = pkg->cmd; uint32_t seq = pkg->seq; uint32_t body_len = len - sizeof(head_proto_t); TRACE_LOG("dispatch[%u] sender=%u, fd=%u, seq=%u, len=%u", cmd, p_node->m_node_id, p_node->m_node_fd, seq, len); const cmd_proto_t * p_cmd = find_head_cmd(cmd); if (NULL == p_cmd) { ERROR_LOG("cmdid not existed: %u", cmd); return 0; } bool read_ret = p_cmd->p_in->read_from_buf_ex(pkg->body, body_len); if (!read_ret) { ERROR_LOG("read_from_buf_ex error cmd=%u, u=[%u: %s]", cmd, p_node->m_node_id, long2ip(p_node->m_node_ip)); return -1; } int cmd_ret = p_cmd->func(p_node, p_cmd->p_in, p_cmd->p_out); return cmd_ret; }
int main (int argc, char ** argv) { KR_API * db; KRNET_API isp; char * ip; int opt; char * datafile = NULL; short onlyisp = 0; short onlynation = 0; short printrange = 0; short printtype = KRISP_GET_COUNTRY; bool verbose = false; char err[1024]; #ifdef HAVE_GETOPT_LONG while ( (opt = getopt_long (argc, argv, "f:hinr:v", long_options, (int *) 0)) != EOF ) { #else while ( (opt = getopt (argc, argv, "f:hinr:v")) != EOF ) { #endif switch (opt) { case 'f' : datafile = optarg; break; case 'i' : if ( onlynation > 0 ) { fprintf (stderr, "ERROR: Can't use -n option and -i option togather\n"); return 1; } onlyisp++; break; case 'n' : if ( onlyisp > 0 ) { fprintf (stderr, "ERROR: Can't use -n option and -i option togather\n"); return 1; } onlynation++; break; case 'r' : printrange++; if ( ! strcasecmp ("country", optarg) ) printtype = KRISP_GET_COUNTRY; else if ( ! strcasecmp ("isp", optarg) ) printtype = KRISP_GET_ISP; else { fprintf (stderr, "ERROR: Wrong value of -r option\n"); return 1; } break; case 'v' : set_true (verbose); break; default: usage (PNAME); } } if ( argc - optind < 1 || argc == 1 ) { usage (PNAME); return 1; } #ifdef _WIN32 { WORD wVerReq = MAKEWORD (2, 2); // Call WinSock 2.2 WSADATA wsaData; int nErrStatus; if ( (nErrStatus = WSAStartup (wVerReq, &wsaData)) != 0 ) { fprintf (stderr, "Error: Failed initialize WSAStartup\n"); return 1; } } #endif /* database open */ if ( kr_open (&db, datafile, err) == false ) { fprintf (stderr, "ERROR Connect: %s\n", err); WSA_Cleanup; return 1; } db->db_time_stamp_interval = 0; isp.verbose = verbose; db->verbose = verbose; ip = argv[optind]; SAFECPY_256 (isp.ip, ip); if ( kr_search (&isp, db) ) { fprintf (stderr, "ERROR: %s\n", isp.err); kr_close (&db); WSA_Cleanup; return 1; } if ( verbose ) fprintf (stderr, "\n"); if ( strlen (isp.err) ) printf ("Error: %s\n", isp.err); if ( onlyisp ) { printf ("%s\n", isp.icode); } else if ( onlynation ) { printf ("%s\n", isp.ccode); } else { #ifdef HAVE_ICONV_H char * lcharset; iconv_t cd; char * ispname, * to; size_t flen, tlen; char * srcname = (char *) isp.iname; #if defined _WIN32 lcharset = "CP949"; #else lcharset = confirm_local_charset (); #endif flen = strlen (srcname); if ( lcharset == NULL || ! strcmp (DB_CHARSET, lcharset) ) { tlen = 1; cd = (iconv_t)(-1); } else { tlen = ! strcmp (lcharset, "UTF8") ? flen * 4 + 1 : flen + 1; cd = iconv_open (lcharset, DB_CHARSET); } if ( cd == (iconv_t)(-1) ) { ispname = strdup (isp.iname); goto noconvert; } if ( (ispname = (char *) malloc (sizeof (char) * tlen)) == NULL ) { ispname = strdup (isp.iname); goto noconvert; } memset (ispname, 0, sizeof (char) * tlen); to = ispname; iconv (cd, &srcname, &flen, &to, &tlen); switch ( errno ) { case E2BIG : case EILSEQ : case EINVAL : strcpy (ispname, isp.iname); break; } noconvert: printf ("%s (%s): %s (%s)\n", ip, isp.ip, ispname, isp.icode); #else printf ("%s (%s): %s (%s)\n", ip, isp.ip, isp.iname, isp.icode); #endif #ifdef HAVE_ICONV_H if ( cd != (iconv_t)(-1) ) iconv_close (cd); SAFEFREE (ispname); #endif printf ("SUBNET : %s\n", long2ip (isp.netmask)); printf ( "NETWORK : %s\n", long2ip (network (isp.start, isp.netmask)) ); printf ( "BROADCAST : %s\n", long2ip (broadcast(isp.start, isp.netmask)) ); printf ("DB RANGE : %s - ", long2ip (isp.start)); printf ("%s\n", long2ip (isp.end)); printf ("NATION : %s (%s)\n", isp.cname, isp.ccode); } if ( printrange ) { KRNET_REQ_RANGE range; int i; ulong mask; char start[16]; char end[16]; range.code = printtype; range.verbose = verbose; range.ranges = NULL; range.count = 0; SAFECPY_1024 ( range.data, (printtype == KRISP_GET_COUNTRY) ? isp.ccode : isp.iname ); if ( kr_range (&range, db) ) { fprintf (stderr, "ERROR: %s\n", range.err); SAFEFREE (range.ranges); kr_close (&db); WSA_Cleanup; return 1; } printf ( "\nRange Traget: %s (%d line%s)\n\n", range.data, range.count, range.count ? "s" : "" ); for ( i=0; i<range.count; i++ ) { long2ip_r (range.ranges[i].start, start); mask = guess_netmask (range.ranges[i].start, range.ranges[i].end); if ( network (range.ranges[i].start, mask) == range.ranges[i].start ) printf ("%s/%d\n", start, long2prefix (mask)); else printf ("%s %s\n", start, long2ip_r (range.ranges[i].end, end)); } SAFEFREE (range.ranges); printf ("\n"); } /* database close */ kr_close (&db); WSA_Cleanup; return 0; }
void ClientList::GetCLEIP(uint32 iIP) { ClientListEntry* countCLEIPs = 0; LinkedListIterator<ClientListEntry*> iterator(clientlist); int IPInstances = 0; iterator.Reset(); while(iterator.MoreElements()) { countCLEIPs = iterator.GetData(); if ((countCLEIPs->GetIP() == iIP) && ((countCLEIPs->Admin() < (RuleI(World, ExemptMaxClientsStatus))) || (RuleI(World, ExemptMaxClientsStatus) < 0))) { // If the IP matches, and the connection admin status is below the exempt status, or exempt status is less than 0 (no-one is exempt) IPInstances++; // Increment the occurences of this IP address Log.Out(Logs::General, Logs::Client_Login, "Account ID: %i Account Name: %s IP: %s.", countCLEIPs->LSID(), countCLEIPs->LSName(), long2ip(countCLEIPs->GetIP()).c_str()); if (RuleB(World, EnableIPExemptions)) { Log.Out(Logs::General, Logs::Client_Login, "Account ID: %i Account Name: %s IP: %s IP Instances: %i Max IP Instances: %i", countCLEIPs->LSID(), countCLEIPs->LSName(), long2ip(countCLEIPs->GetIP()).c_str(), IPInstances, database.GetIPExemption(long2ip(countCLEIPs->GetIP()).c_str())); if (IPInstances > database.GetIPExemption(long2ip(countCLEIPs->GetIP()).c_str())) { if(RuleB(World, IPLimitDisconnectAll)) { Log.Out(Logs::General, Logs::Client_Login, "Disconnect: All accounts on IP %s", long2ip(countCLEIPs->GetIP()).c_str()); DisconnectByIP(iIP); return; } else { Log.Out(Logs::General, Logs::Client_Login, "Disconnect: Account %s on IP %s.", countCLEIPs->LSName(), long2ip(countCLEIPs->GetIP()).c_str()); countCLEIPs->SetOnline(CLE_Status_Offline); iterator.RemoveCurrent(); continue; } } } else { if (IPInstances > (RuleI(World, MaxClientsPerIP))) { // If the number of connections exceeds the lower limit if (RuleB(World, MaxClientsSetByStatus)) { // If MaxClientsSetByStatus is set to True, override other IP Limit Rules Log.Out(Logs::General, Logs::Client_Login, "Account ID: %i Account Name: %s IP: %s IP Instances: %i Max IP Instances: %i", countCLEIPs->LSID(), countCLEIPs->LSName(), long2ip(countCLEIPs->GetIP()).c_str(), IPInstances, countCLEIPs->Admin()); if (IPInstances > countCLEIPs->Admin()) { // The IP Limit is set by the status of the account if status > MaxClientsPerIP if(RuleB(World, IPLimitDisconnectAll)) { Log.Out(Logs::General, Logs::Client_Login, "Disconnect: All accounts on IP %s", long2ip(countCLEIPs->GetIP()).c_str()); DisconnectByIP(iIP); return; } else { Log.Out(Logs::General, Logs::Client_Login, "Disconnect: Account %s on IP %s.", countCLEIPs->LSName(), long2ip(countCLEIPs->GetIP()).c_str()); countCLEIPs->SetOnline(CLE_Status_Offline); // Remove the connection iterator.RemoveCurrent(); continue; } } } else if ((countCLEIPs->Admin() < RuleI(World, AddMaxClientsStatus)) || (RuleI(World, AddMaxClientsStatus) < 0)) { // Else if the Admin status of the connection is not eligible for the higher limit, or there is no higher limit (AddMaxClientStatus < 0) if(RuleB(World, IPLimitDisconnectAll)) { Log.Out(Logs::General, Logs::Client_Login, "Disconnect: All accounts on IP %s", long2ip(countCLEIPs->GetIP()).c_str()); DisconnectByIP(iIP); return; } else { Log.Out(Logs::General, Logs::Client_Login, "Disconnect: Account %s on IP %s.", countCLEIPs->LSName(), long2ip(countCLEIPs->GetIP()).c_str()); countCLEIPs->SetOnline(CLE_Status_Offline); // Remove the connection iterator.RemoveCurrent(); continue; } } else if (IPInstances > RuleI(World, AddMaxClientsPerIP)) { // else they are eligible for the higher limit, but if they exceed that if(RuleB(World, IPLimitDisconnectAll)) { Log.Out(Logs::General, Logs::Client_Login, "Disconnect: All accounts on IP %s", long2ip(countCLEIPs->GetIP()).c_str()); DisconnectByIP(iIP); return; } else { Log.Out(Logs::General, Logs::Client_Login, "Disconnect: Account %s on IP %s.", countCLEIPs->LSName(), long2ip(countCLEIPs->GetIP()).c_str()); countCLEIPs->SetOnline(CLE_Status_Offline); // Remove the connection iterator.RemoveCurrent(); continue; } } } } } iterator.Advance(); } }
void process_datagram(unsigned char *args, struct pcap_pkthdr *header, unsigned char *datagram) { unsigned char options[255], option55[255], vendor[255], hostname[255], opt82_remote_id[255]; unsigned char dhcptype; unsigned int reqip = 0, optc = 0; unsigned short vlanid = 0, opt82_circuit_vlan = 0; unsigned short ethtype; unsigned int i, j, k; unsigned char *p, *p82; unsigned char opt, len, opt82, len82; unsigned char opt82_circuit_unit = 0, opt82_circuit_port = 0; unsigned char *ethp = (datagram + 12); memcpy(ðtype, ethp, 2); #if BYTE_ORDER == LITTLE_ENDIAN ethtype = ntohs(ethtype); #endif if (ethtype == 0x8100) { fhlen += 4; // 802.1Q VLAN ethp += 2; memcpy(&vlanid, ethp, 2); vlanid &= 0xFF0F; // remove PCP & CFI #if BYTE_ORDER == LITTLE_ENDIAN vlanid = ntohs(vlanid); #endif } struct iphdr *ip = (struct iphdr *)(datagram + fhlen); struct udphdr *udp = (struct udphdr *)(datagram + sizeof(struct iphdr) + fhlen); struct dhcpmsg *dhcp = (struct dhcpmsg *)(datagram + sizeof(struct iphdr) + sizeof(struct udphdr) + fhlen); if (ethtype == 0x8100) // 802.1Q VLAN fhlen -= 4; #if BYTE_ORDER == LITTLE_ENDIAN udp->len = htons(udp->len); #endif p = (unsigned char *)(dhcp->options); bzero(hostname, sizeof(hostname)); bzero(option55, sizeof(option55)); bzero(options, sizeof(options)); bzero(vendor, sizeof(vendor)); bzero(opt82_remote_id, sizeof(opt82_remote_id)); for (i = 0; i < (udp->len - sizeof(struct udphdr) - sizeof(struct dhcpmsg)); i++) { memcpy(&opt, p, 1); memcpy(&len, p+1, 1); p+=2; // omit pad, end and option82! if (opt != DHCP_OPTION_PAD && opt != DHCP_OPTION_END && opt != DHCP_OPTION_DHCP_AGENT_OPTIONS) options[optc++] = opt; switch (opt) { case DHCP_OPTION_DHCP_MESSAGE_TYPE: dhcptype = *p; break; case DHCP_OPTION_DHCP_REQUESTED_ADDRESS: memcpy(&reqip, p, sizeof(reqip)); break; case DHCP_OPTION_DHCP_PARAMETER_REQUEST_LIST: // 55 for (j = 0; j < len; j++) option55[j] = *(p+j); break; case DHCP_OPTION_VENDOR_CLASS_IDENTIFIER: memcpy(&vendor, p, len); break; case DHCP_OPTION_HOST_NAME: memcpy(hostname, p, len); break; case DHCP_OPTION_DHCP_AGENT_OPTIONS: // 82 p82 = p; for (j = 0; j < len; j++) { memcpy(&opt82, p82, 1); memcpy(&len82, p82+1, 1); p82+=2; switch (opt82) { case DHCP_OPTION82_REMOTE_ID: memcpy(opt82_remote_id, p82+2, len82-2); break; case DHCP_OPTION82_CIRCUIT_ID: // make sure we are not dealing with some custom string if (*p82 == 0 && *(p82+1) == 4) { memcpy(&opt82_circuit_vlan, p82+2, 2); #if BYTE_ORDER == LITTLE_ENDIAN opt82_circuit_vlan = htons(opt82_circuit_vlan); #endif memcpy(&opt82_circuit_unit, p82+4, 1); memcpy(&opt82_circuit_port, p82+5, 1); } break; default: #ifdef _DEBUG printf("subopt82=%u len=%u val=", opt82, len82); for (k = 0; k < len82; k++) printf("%02x", *(p82+k)); putchar('|'); for (k = 0; k < len82; k++) { if (*(p82+k) >= 32 && *(p82+k) < 128) putchar(*(p82+k)); else putchar('.'); } putchar(' '); #endif break; } p82 += len82; j += len82 + 1; } break; case DHCP_OPTION_PAD: case DHCP_OPTION_END: break; default: #ifdef _DEBUG printf("opt=%u len=%u val=", opt, len); for (j = 0; j < len; j++) printf("%02x", *(p+j)); putchar('|'); for (j = 0; j < len; j++) { if (*(p+j) >= 32 && *(p+j) < 128) putchar(*(p+j)); else putchar('.'); } putchar(' '); #endif break; } p += len; i += len + 1; } // options switch (dhcptype) { case DHCP_DISCOVER: printf("Discover"); break; case DHCP_REQUEST: printf("Request"); break; case DHCP_INFORM: printf("Inform"); break; default: return; break; } printf(" from %s_%s (%s)", find_ether_oui(dhcp->chaddr), bin2mac(dhcp->chaddr, dhcp->hlen)+9, bin2mac(dhcp->chaddr, dhcp->hlen)); if (vlanid) printf(" @ VLAN %u\n", vlanid); else putchar('\n'); printf(" system\t= %s\n", osfp(round_ttl(ip->ttl), options, option55, vendor)); if (strlen(hostname)) printf(" hostname\t= %s\n", hostname); if (reqip) printf(" req ipaddr\t= %s\n", long2ip(reqip)); if (strlen(opt82_remote_id)) printf(" option82\t= remote_id %s circuit_id vlan %u unit %u port %u\n", bin2mac(opt82_remote_id, 6), opt82_circuit_vlan, opt82_circuit_unit, opt82_circuit_port); putchar('\n'); fflush(stdout); udpc++; }
//this could be expanded to check more than the fitst opcode if //we needed more complex matching EQStream::MatchState EQStream::CheckSignature(const Signature *sig) { EQRawApplicationPacket *p = nullptr; MatchState res = MatchNotReady; MInboundQueue.lock(); if (!InboundQueue.empty()) { //this is already getting hackish... p = InboundQueue.front(); if(sig->ignore_eq_opcode != 0 && p->opcode == sig->ignore_eq_opcode) { if(InboundQueue.size() > 1) { p = InboundQueue[1]; } else { p = nullptr; } } if(p == nullptr) { //first opcode is ignored, and nothing else remains... keep waiting } else if(p->opcode == sig->first_eq_opcode) { //opcode matches, check length.. if(p->size == sig->first_length) { Log.Out(Logs::General, Logs::Netcode, "[IDENT_TRACE] %s:%d: First opcode matched 0x%x and length matched %d", long2ip(GetRemoteIP()).c_str(), ntohs(GetRemotePort()), sig->first_eq_opcode, p->size); res = MatchSuccessful; } else if(sig->first_length == 0) { Log.Out(Logs::General, Logs::Netcode, "[IDENT_TRACE] %s:%d: First opcode matched 0x%x and length (%d) is ignored", long2ip(GetRemoteIP()).c_str(), ntohs(GetRemotePort()), sig->first_eq_opcode, p->size); res = MatchSuccessful; } else { //opcode matched but length did not. Log.Out(Logs::General, Logs::Netcode, "[IDENT_TRACE] %s:%d: First opcode matched 0x%x, but length %d did not match expected %d", long2ip(GetRemoteIP()).c_str(), ntohs(GetRemotePort()), sig->first_eq_opcode, p->size, sig->first_length); res = MatchFailed; } } else { //first opcode did not match.. Log.Out(Logs::General, Logs::Netcode, "[IDENT_TRACE] %s:%d: First opcode 0x%x did not match expected 0x%x", long2ip(GetRemoteIP()).c_str(), ntohs(GetRemotePort()), p->opcode, sig->first_eq_opcode); res = MatchFailed; } } MInboundQueue.unlock(); return(res); }