void pop_func(const char *funcname) { if (g_callstack_map.paddr){ int i ; ndthread_t self_id = nd_thread_self() ; struct callstack_info *pcs =(struct callstack_info *) g_callstack_map.paddr ; for(i=0; i<MAX_THREAD_NUM; i++, pcs++) { if (self_id == pcs->th_id) { if (pcs->stack_point<=0) { break; } nd_assert(pcs->stack_point); --(pcs->stack_point); nd_assert(ndstrncmp(funcname, pcs->names[pcs->stack_point], sizeof(functionname_t)) == 0); #ifdef ND_DEBUG #else pcs->names[pcs->stack_point][0] = 0; #endif return ; } else if (pcs->th_id == 0) { break; } } //nd_assert(0); } }
//connect remote host int nd_tcpnode_connect(const char *host, int port, struct nd_tcp_node *node, struct nd_proxy_info *proxy) { ENTER_FUNC() nd_assert(node); nd_assert(host); node->sys_error = 0; node->last_push = nd_time(); ndlbuf_reset(&(node->recv_buffer)); /* buffer store data recv from net */ ndlbuf_reset(&(node->send_buffer)); /* buffer store data send from net */ if (proxy && proxy->proxy_type != ND_PROXY_NOPROXY) { node->fd = nd_proxy_connect(host, port, &(node->remote_addr), proxy, 0); } else { node->fd = nd_socket_tcp_connect(host, (short)port, &(node->remote_addr)); } if (node->fd <= 0) { node->myerrno = NDERR_OPENFILE; LEAVE_FUNC(); return -1; } TCPNODE_SET_OK(node); nd_socket_nonblock(node->fd, 1); _set_ndtcp_conn_dft_option(node->fd); node->start_time = nd_time(); if (node->remote_addr.sin_family == AF_INET6) { node->is_ipv6 = 1; } LEAVE_FUNC(); return 0; }
NDThreadSessionIterator& NDThreadSessionIterator::operator ++ () { struct cm_manager * pcmmgr = nd_listensrv_get_cmmamager((nd_listen_handle)m_tpi->lh); nd_assert(pcmmgr) ; pcmmgr->unlock(pcmmgr,*first) ; ++first ; if (first < &m_tpi->sid_buf[m_tpi->session_num]){ void *p = pcmmgr->lock(pcmmgr,*first) ; nd_assert(p) ; second = GetSessionFromHandle((nd_netui_handle )p) ; } return *this; }
NDThreadSessionMgr::iterator NDThreadSessionMgr::begin() { NDSession *ps = NULL; NDUINT16 *p = m_tpi->sid_buf ; if (m_tpi->session_num > 0) { struct cm_manager * pcmmgr = nd_listensrv_get_cmmamager((nd_listen_handle)m_tpi->lh); nd_assert(pcmmgr) ; void *addr = pcmmgr->lock(pcmmgr,*p) ; nd_assert(addr) ; ps = GetSessionFromHandle((nd_netui_handle )addr) ; } return iterator(p,ps, m_tpi); }
//回复对方的连接请求 // 返回-1 出错,0 succes int _handle_syn(nd_udt_node *socket_node,struct ndudt_pocket *pocket) { if(socket_node->status==NETSTAT_LISTEN) { struct ndudt_pocket syn_ack ; init_udt_pocket(&syn_ack) ; SET_SYN(&syn_ack) ; socket_node->acknowledged_seq = socket_node->send_sequence ; socket_node->received_sequence = pocket->sequence + 1; //接受到对方的系列号+1以便回复对方 set_pocket_ack(&syn_ack,socket_node->received_sequence) ; syn_ack.sequence = socket_node->send_sequence ; write_pocket_to_socket(socket_node, &syn_ack, ndt_header_size(&syn_ack)); socket_node->status = NETSTAT_SYNRECV ; return 0 ; } else if(NETSTAT_SYNSEND==socket_node->status){ //connect (client side received syn ack if(!pocket->header.ack || socket_node->send_sequence+1!=pocket->ack_seq) { nd_object_seterror((nd_handle)socket_node,NDERR_BADPACKET); nd_assert(0) ; return -1; } socket_node->session_id = pocket->session_id ; socket_node->received_sequence = pocket->sequence +1 ; socket_node->acknowledged_seq = pocket->ack_seq ; socket_node->status = NETSTAT_ESTABLISHED; ++ (socket_node->send_sequence) ; udt_send_ack(socket_node) ; return 0 ; } else if(socket_node->status < NETSTAT_ACCEPT){ nd_assert(socket_node->received_sequence == pocket->sequence + 1) ; if(socket_node->received_sequence == pocket->sequence + 1) { udt_send_ack(socket_node) ; return 0 ; } return -1 ; } else { nd_object_seterror((nd_handle)socket_node,NDERR_BADPACKET); return -1; } }
static int __tcpnode_push_and_send(struct nd_tcp_node *node, void *msg_buf, size_t datalen, int is_write_all) { ENTER_FUNC(); signed int ret =0; nd_netbuf_t *pbuf = &(node->send_buffer); size_t length_in_buff = ndlbuf_datalen(pbuf); if (length_in_buff) { int flushlen = node->sock_write((nd_handle)node, ndlbuf_data(pbuf), length_in_buff); if (flushlen > 0) { nd_assert(flushlen <= length_in_buff); ndlbuf_sub_data(pbuf, (size_t)flushlen); } length_in_buff = ndlbuf_datalen(pbuf); } if (length_in_buff == 0) { ret = __tcpnode_send_with_save(node, msg_buf, datalen); } else { size_t space_len = ndlbuf_free_capacity(pbuf); if(is_write_all && space_len < datalen) { node->myerrno = NDERR_WOULD_BLOCK; ret = -1; } else { ret = ndlbuf_write(pbuf, (void*)msg_buf, datalen, EBUF_SPECIFIED); } } LEAVE_FUNC(); return ret ; }
/* create message table * @mainmsg_num * @base_msgid start-index * return value : 0 success on error return -1 */ int nd_msgtable_create(nd_handle handle, int mainmsg_num, int base_msgid) { void **p = NULL ; nd_assert(handle) ; if(mainmsg_num>MAX_MAIN_NUM || mainmsg_num <= 0) { return -1; } if(handle->type==NDHANDLE_TCPNODE){ p= (void **) & (((struct nd_tcp_node*)handle)->msg_handle ) ; } else if(handle->type==NDHANDLE_UDPNODE) { p = (void **) & (((nd_udt_node*)handle)->msg_handle ) ; } else { p = (void **) & ((struct nd_srv_node*) handle)->msg_handle ; } if (*p){ nd_msgtable_destroy(handle,0) ; *p = 0 ; } *p = create_msgroot(mainmsg_num, base_msgid) ; if(*p) { return 0 ; } else { return -1; } }
void nd_srv_close(struct nd_srv_node *node) { nd_assert(node) ; nd_socket_close(node->fd) ; node->status = 0 ; node->fd = 0 ; }
static int exp_enum(ndxml *node, FILE *pf) { int total =(int) ndxml_getsub_num(node) ; for (int i=0; i<total; ++i) { ndxml *sub = ndxml_getnodei(node, i); nd_assert(sub) ; const char *pcomment = ndxml_getattr_val(sub, "comment") ; if (pcomment) { fprintf(pf, "// %s \n", pcomment) ; } fprintf(pf, "enum %s { \n", ndxml_getname(sub)) ; for (int x=0; x< ndxml_getsub_num(sub); ++x) { ndxml *element = ndxml_getnodei(sub, x) ; pcomment = ndxml_getattr_val(element, "comment") ; const char *pvalue = ndxml_getattr_val(element, "value") ; if (pvalue && pvalue[0] ) { fprintf(pf, "\t%s =%s,//%s\n", ndxml_getname(element),pvalue, pcomment?pcomment:"\t " ) ; } else { fprintf(pf, "\t%s,//%s\n", ndxml_getname(element), pcomment?pcomment:"\t "); } } fprintf(pf, "};\n\n\n") ; } return 0; }
int nd_net_bind(int port, int listen_nums,nd_handle net_handle) { ndsocket_t fd; struct nd_netsocket *node = (struct nd_netsocket *)net_handle ; //SOCKADDR_IN *remote = NULL; nd_assert(node) ; node->myerrno = NDERR_SUCCESS ; fd = nd_socket_openport(port,node->sock_type, node->sock_protocol, node->bindip, listen_nums) ; if(-1==fd){ nd_logfatal("open port %s" AND nd_last_error()) ; node->myerrno = NDERR_OPENFILE ; return -1 ; } if(0==port && SOCK_DGRAM==node->sock_type) { short tmp = nd_sock_getport(fd) ; port =(int) ntohs(tmp); } node->fd = fd ; node->port = htons(port) ; node->status = 1 ; return 0 ; }
int nd_udp_close(struct nd_udp_node*node,int flag) { nd_assert(node) ; if (node->fd) { nd_socket_close(node->fd) ; node->fd = 0 ; node->status = 0 ; } return 0 ; }
NDSession *NDThreadSessionMgr::Search(OBJECTID_T sessionid) { struct cm_manager * pcmmgr = nd_listensrv_get_cmmamager((nd_listen_handle)m_tpi->lh); nd_assert(pcmmgr) ; void *p = pcmmgr->lock(pcmmgr,sessionid) ; if (p){ pcmmgr->unlock(pcmmgr,sessionid) ; return GetSessionFromHandle((nd_netui_handle )p) ; } return NULL; }
int read_remote_proxy(char *file, struct nd_proxy_info *proxy_info ) { int ret; ndxml *xml_node, *xml_read ; ndxml_root xmlroot; nd_assert(file) ; ret = ndxml_load(file, &xmlroot) ; if(0!=ret) { return -1; } xml_node = ndxml_getnode(&xmlroot,"server_config") ; if(!xml_node) { ndxml_destroy(&xmlroot); return -1; } //read proxy xml_read = ndxml_refsub(xml_node, "proxy") ; if(xml_read) { ndxml *xmltmp = ndxml_refsub(xml_read, "proxy_type") ; if (!xmltmp) goto CFG_EXIT ; proxy_info->proxy_type = ndxml_getval_int(xmltmp); if(0==proxy_info->proxy_type )goto CFG_EXIT ; xmltmp = ndxml_refsub(xml_read, "proxy_host") ; if (!xmltmp) goto CFG_EXIT ; ndxml_getval_buf(xmltmp, proxy_info->proxy_host, sizeof(proxy_info->proxy_host)) ; xmltmp = ndxml_refsub(xml_read, "proxy_port") ; if (!xmltmp) goto CFG_EXIT ; proxy_info->proxy_port = ndxml_getval_int(xmltmp) ; xmltmp = ndxml_refsub(xml_read, "proxy_user") ; if (xmltmp) ndxml_getval_buf(xmltmp, proxy_info->user, sizeof(proxy_info->user)) ; xmltmp = ndxml_refsub(xml_read, "proxy_password") ; if (xmltmp) ndxml_getval_buf(xmltmp, proxy_info->password, sizeof(proxy_info->password)) ; } CFG_EXIT: ndxml_destroy(&xmlroot); return 0; }
nd_sa_handle nd_sa_create(int node_num, size_t node_size, nd_handle mempool) { int i ; size_t raw_len; char *addr ; nd_static_alloc_t *allocator ; nd_handle pool ; node_size = GET_SA_ALLOC_MIN_SIZE(node_size) ; raw_len = node_num * node_size + sizeof(nd_static_alloc_t); if(mempool) pool =mempool ; else pool = nd_global_mmpool() ; nd_assert(pool) ; allocator = (nd_static_alloc_t *)nd_pool_alloc(pool, raw_len ) ; if(!allocator) { return NULL; } allocator->size = (NDUINT32) raw_len; /*句柄的大小*/ allocator->type =NDHANDLE_STATICALLOCATOR; /*句柄类型*/ allocator->close_entry =(nd_close_callback) nd_sa_destroy ; /*句柄释放函数*/ allocator->myerrno = NDERR_SUCCESS ; allocator->capacity =node_num; allocator->node_size = node_size ; allocator->allocated_num = 0 ; allocator->mem_pool = pool ; nd_mutex_init(&allocator->list_lock); INIT_LIST_HEAD(&allocator-> __free_list); addr = allocator->addr ; for (i=0; i<node_num; i++){ struct list_head *list = (struct list_head *)addr ; INIT_LIST_HEAD(list); list_add(list,&(allocator->__free_list)) ; addr += node_size ; } return (nd_sa_handle)allocator ; }
int ProxyInst::InitProxy() { if (-1==CreateUpdate()) return -1; NDListener *pLis = GetDeftListener() ; nd_assert(pLis) ; nd_handle h_listen = pLis->GetHandle() ; nd_hook_data(h_listen, listen_data_handle); read_remote_proxy(NDInstanceSrv::config_file, &g_remote_proxy ) ; return 0; }
int nd_tcpnode_close(struct nd_tcp_node *node, int force) { ENTER_FUNC() //nd_assert(0); nd_assert(node); node->status = ETS_DEAD; if (node->fd == 0) { LEAVE_FUNC(); return 0; } nd_socket_close(node->fd); node->fd = 0; LEAVE_FUNC(); return 0; }
nd_handle nd_get_msg_hadle(nd_netui_handle handle) { struct nd_msgentry_root *root_entry= NULL; nd_assert(handle) ; if(handle->type==NDHANDLE_TCPNODE){ root_entry = (struct nd_msgentry_root *) (((struct nd_tcp_node*)handle)->msg_handle ) ; } else if(handle->type==NDHANDLE_UDPNODE){ root_entry = (struct nd_msgentry_root *) (((nd_udt_node*)handle)->msg_handle ) ; } else if(handle->type==NDHANDLE_LISTEN){ root_entry = (struct nd_msgentry_root *) (((struct nd_srv_node* )handle )->msg_handle ) ; } else { return NULL; } return (nd_handle) root_entry ; }
void udp_node_init(struct nd_udp_node* node) { nd_assert(node) ; memset(node, 0, sizeof(*node)) ; node->type = NDHANDLE_UDPNODE ; node->size = sizeof(struct nd_udp_node) ; node->sock_write = (socket_write_entry) nd_udp_send ; node->close_entry = (nd_close_callback) nd_udp_close; node->sock_read = (socket_read_entry)nd_udp_read; node->status = ETS_DEAD; /*socket state in game 0 not read 1 ready*/ node->protocol = PROTOCOL_OTHER; node->sock_type = SOCK_DGRAM ; node->start_time =nd_time() ; node->last_push = nd_time() ; node->disconn_timeout = ND_DFT_DISSCONN_TIMEOUT ; node->msg_caller = node; init_crypt_key(&node->crypt_key); nd_net_connbuf_init((struct netui_info*)node) ; }
RESULT_T ApoClient::_connectHost(const char *host, int port) { if (!host || !*host){ nd_logerror("connect to host error, input host name is NULL\n"); return NDSYS_ERR_INVALID_INPUT; } CHECK_CONN_VALID(m_pconn) ; if (-1 == m_pconn->Open(host, port, "tcp-connector")){ return (RESULT_T)NDSYS_ERR_HOST_UNAVAILABLE; } int level = ndGetTimeoutVal(); int size = sizeof(int); m_pconn->ioctl(NDIOCTL_SET_TIMEOUT, &level, &size); if (m_login) { delete m_login; m_login = 0; } if (m_sessionFile.empty()){ m_login = new LoginApollo(m_pconn->GetHandle(), NULL); } else { m_login = new LoginApollo(m_pconn->GetHandle(), m_sessionFile.c_str()); } nd_assert(m_login); if (-1 == m_login->TrytoGetCryptKey()) { return (RESULT_T) NDERR_VERSION; } m_runningUpdate = ERUN_UP_NORMAL; onInit(); nd_logmsg("connect host:%s port:%d ok\n", host, port); return ESERVER_ERR_SUCCESS; }
//read udp socket data int nd_udp_read(struct nd_udp_node*node , char *buf, size_t buf_size, ndtime_t outval) { int ret ; int readlen = 0; nd_assert(buf && buf_size>0); TCPNODE_READ_AGAIN(node) = 0; if(outval ) { ret = nd_socket_wait_read(node->fd, outval) ; if(ret <= 0) { node->myerrno = (ret == 0) ? NDERR_WOULD_BLOCK: NDERR_IO; return ret ; } } readlen = nd_socket_udp_read(node->fd, buf, (int)buf_size, &node->last_read); if (-1 == readlen) { node->sys_error = nd_socket_last_error(); if (node->sys_error == ESOCKETTIMEOUT) { node->myerrno = NDERR_WOULD_BLOCK; return 0; } else { node->myerrno = NDERR_READ; nd_logdebug("recvfrom : %s\n", nd_last_error()); return -1; } } TCPNODE_READ_AGAIN(node) = 1; node->last_recv = nd_time(); node->recv_len += readlen; return readlen ; }
int ApoClient::Init() { #ifndef WITHOUT_LOGIC_PARSER //init message script handler LogicEngineRoot *scriptRoot = LogicEngineRoot::get_Instant(); nd_assert(scriptRoot); LogicParserEngine &parser = LogicEngineRoot::get_Instant()->getGlobalParser(); parser.setOwner(&__scriptObjOwner); scriptRoot->getGlobalParser().setSimulate(false); //scriptRoot->setPrint(NULL, NULL); ndInitNet(); //m_pconn = nd_object_create("tcp-connector"); m_pconn = _create_connector_object() ; parser.eventNtf(APOLLO_EVENT_SERVER_START, 0); //program start up #else ndInitNet(); #endif return 0; }
void nd_msgtable_destroy(nd_handle handle, int flag) { nd_assert(handle) ; if(handle->type==NDHANDLE_TCPNODE){ if(((struct nd_tcp_node*)handle)->msg_handle) { destroy_msgroot(((struct nd_tcp_node*)handle)->msg_handle); ((struct nd_tcp_node*)handle)->msg_handle = 0 ; } } else if(handle->type==NDHANDLE_UDPNODE) { if(((nd_udt_node*)handle)->msg_handle) { destroy_msgroot(((nd_udt_node*)handle)->msg_handle); ((nd_udt_node*)handle)->msg_handle = 0 ; } } else { struct nd_srv_node* srv_node = (struct nd_srv_node* )handle ; if(srv_node->msg_handle) { destroy_msgroot(srv_node->msg_handle); srv_node->msg_handle = 0 ; } } }
bool startDialog::compileScript(const char *scriptFile, const char *editorWorkingPath) { ndxml_root xmlScript; ndxml_initroot(&xmlScript); if (-1 == ndxml_load_ex(scriptFile, &xmlScript, apoEditorSetting::getInstant()->m_encodeName.c_str())) { return false; } const char*inFile = scriptFile; const char *outFile = getScriptSetting(&xmlScript, "out_file"); if (!outFile){ nd_logerror("compile %s error !!!\nMaybe file is destroyed\n", scriptFile); return false; } //get out file absolute path std::string curPath = nd_getcwd(); char outFilePath[ND_FILE_PATH_SIZE]; if (!nd_getpath(scriptFile, outFilePath, sizeof(outFilePath))) { nd_logerror("get out file path error 1\n"); return false; } if (-1 == nd_chdir(outFilePath)) { nd_logerror("get script file-path error 2\n"); return false; } if (!nd_absolute_filename(outFile, outFilePath, sizeof(outFilePath))) { nd_logerror("get out file path error 3\n"); nd_chdir(curPath.c_str()); return false; } nd_chdir(curPath.c_str()); outFile = outFilePath; // ---end get out file absolute path int outEncode = getScriptExpEncodeType(&xmlScript); bool withDebug = getScriptExpDebugInfo(&xmlScript); //std::string outPath = outFile; ndxml_destroy(&xmlScript); //outFile = outPath.c_str(); int orderType = ND_L_ENDIAN; const char *orderName = apoEditorSetting::getInstant()->getValueFromSetting("bin_data_byte_order"); if (orderName) { orderType = atoi(orderName); } LogicCompiler &lgcompile= *LogicCompiler::get_Instant(); if (!lgcompile.compileXml(inFile, outFile, outEncode, withDebug, orderType)) { const char *pFunc = lgcompile.m_cur_function.c_str(); const char *pStep = lgcompile.m_cur_step.c_str(); char func_name[256]; char step_name[256]; if (outEncode == E_SRC_CODE_GBK) { pFunc = nd_gbk_to_utf8(pFunc, func_name, sizeof(func_name)); pStep = nd_gbk_to_utf8(pStep, step_name, sizeof(step_name)); } nd_logerror("compile error file %s, function %s, step %s , stepindex %d\n", lgcompile.m_cur_file.c_str(), pFunc, pStep, lgcompile.m_cur_node_index); return false; } nd_logmsg("!!!!!!!!!!COMPILE %s success !!!!!!!!!!!\n begining run script...\n", scriptFile); ClientMsgHandler::ApoConnectScriptOwner apoOwner; LogicEngineRoot *scriptRoot = LogicEngineRoot::get_Instant(); nd_assert(scriptRoot); scriptRoot->setOutPutEncode(E_SRC_CODE_UTF_8); scriptRoot->setPrint(ND_LOG_WRAPPER_PRINT(startDialog), NULL); scriptRoot->getGlobalParser().setSimulate(true); //scriptRoot->getGlobalParser().setOwner(&apoOwner); if (0 != scriptRoot->LoadScript(outFile, &scriptRoot->getGlobalParser())){ WriteLog("load script error n"); LogicEngineRoot::destroy_Instant(); return false; } WriteLog("start run script...\n"); scriptRoot->setDftScriptModule(scriptRoot->getMainModuleName()); if (0 != scriptRoot->test()){ WriteLog("run script error\n"); const char *curErrNode = scriptRoot->getGlobalParser().getLastErrorNode(); if (curErrNode && *curErrNode) { showScriptError(scriptFile, curErrNode,editorWorkingPath); } LogicEngineRoot::destroy_Instant(); return false; } LogicEngineRoot::destroy_Instant(); nd_logmsg("!!!!!!!!!!!!!!!!!!!SCRIPT %s SUCCESS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n",scriptFile); return true; }
//直接处理来自socket的原始数据 int _listen_data_handle(nd_handle session, void *data, size_t size, nd_handle listener) { ProxySession *psession =(ProxySession*) NDGetSession( session) ; nd_assert(psession) ; switch(psession->GetStat()) { case 2: psession->SendRemote(data, size) ; break ; case 0 : { char *cmd =(char*) data ; char buf[128] ; if (size < 3){ goto PROXY_ERROR ; } if(cmd[0] != 5 ) goto PROXY_ERROR ; buf[0] = 5; buf[1] = 0 ; psession->SendRawData(buf, 2) ; psession->SetStat(1) ; return 0 ; } break ; case 1 : { short port; int is_udp = 0 ; int port_offset=8 ; char *cmd =(char*) data ; char host[256]; if (cmd[0]!=5) { goto PROXY_ERROR ; } //get host and port if(cmd[3]==1){ memset(host,0,sizeof(host)); snprintf(host,128,"%d.%d.%d.%d",0xff&cmd[4],0xff&cmd[5],0xff&cmd[6],0xff&cmd[7]); } else{ int host_len= cmd[4] ; if(host_len<=0) goto PROXY_ERROR ; memcpy(host,cmd+5,host_len); host[host_len]=0; port_offset=host_len+5; } port=(0xff&cmd[port_offset+1]) + ((0xff&cmd[port_offset]) << 8); if(cmd[1]==1) { //connect } else if(cmd[1]==2) { //bind not surport goto PROXY_ERROR ; } else if(cmd[1]==3) { //udp not surport is_udp = 1; } //get if(0==psession->ConnectRemote(host, port,is_udp) ) { SOCKADDR_IN *addr = psession->GetRemoteAddr() ; host[0] = 5 ; host[1]=0 ; host[2] = 0; host[3] = 1 ; *(unsigned int*)(&host[4]) = addr->sin_addr.s_addr ;//nd_sock_getip(fd) ; *(unsigned short*)(&host[8]) = addr->sin_port; psession->SendRawData(host, 10) ; } else goto PROXY_ERROR ; psession->SetStat(2); return 0 ; } break ; } return 0; PROXY_ERROR: { char res[2] ; res[0]= 5; res[1] = 1 ; psession->SendRawData(res, 2) ; return -1; } }