//------------------------------------------------------------------------------------- int NavMeshHandle::findStraightPath(int layer, const Position3D& start, const Position3D& end, std::vector<Position3D>& paths) { std::map<int, NavmeshLayer>::iterator iter = navmeshLayer.find(layer); if(iter == navmeshLayer.end()) { ERROR_MSG(fmt::format("NavMeshHandle::findStraightPath: not found layer({})\n", layer)); return NAV_ERROR; } dtNavMeshQuery* navmeshQuery = iter->second.pNavmeshQuery; // dtNavMesh* float spos[3]; spos[0] = start.x; spos[1] = start.y; spos[2] = start.z; float epos[3]; epos[0] = end.x; epos[1] = end.y; epos[2] = end.z; dtQueryFilter filter; filter.setIncludeFlags(0xffff); filter.setExcludeFlags(0); const float extents[3] = {2.f, 4.f, 2.f}; dtPolyRef startRef = INVALID_NAVMESH_POLYREF; dtPolyRef endRef = INVALID_NAVMESH_POLYREF; float startNearestPt[3]; float endNearestPt[3]; navmeshQuery->findNearestPoly(spos, extents, &filter, &startRef, startNearestPt); navmeshQuery->findNearestPoly(epos, extents, &filter, &endRef, endNearestPt); if (!startRef || !endRef) { ERROR_MSG(fmt::format("NavMeshHandle::findStraightPath({2}): Could not find any nearby poly's ({0}, {1})\n", startRef, endRef, resPath)); return NAV_ERROR_NEARESTPOLY; } dtPolyRef polys[MAX_POLYS]; int npolys; float straightPath[MAX_POLYS * 3]; unsigned char straightPathFlags[MAX_POLYS]; dtPolyRef straightPathPolys[MAX_POLYS]; int nstraightPath; int pos = 0; navmeshQuery->findPath(startRef, endRef, startNearestPt, endNearestPt, &filter, polys, &npolys, MAX_POLYS); nstraightPath = 0; if (npolys) { float epos1[3]; dtVcopy(epos1, endNearestPt); if (polys[npolys-1] != endRef) navmeshQuery->closestPointOnPoly(polys[npolys-1], endNearestPt, epos1); navmeshQuery->findStraightPath(startNearestPt, endNearestPt, polys, npolys, straightPath, straightPathFlags, straightPathPolys, &nstraightPath, MAX_POLYS); Position3D currpos; for(int i = 0; i < nstraightPath * 3; ) { currpos.x = straightPath[i++]; currpos.y = straightPath[i++]; currpos.z = straightPath[i++]; paths.push_back(currpos); pos++; //DEBUG_MSG(fmt::format("NavMeshHandle::findStraightPath: {}->{}, {}, {}\n", pos, currpos.x, currpos.y, currpos.z)); } } return pos; }
int render_export_obj(char **buffer) { IF_FAILED0(init && buffer); int element_buffer_size = 0, vertex_buffer_size = 0, normal_buffer_size = 0; GLuint vertex_vbo, index_vbo, normal_vbo; GLint last_array_buffer, last_element_array_buffer; glBindVertexArray(0); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); glGenBuffers(1, &vertex_vbo); glGenBuffers(1, &index_vbo); glGenBuffers(1, &normal_vbo); if(!marching_cubes_create_vbos(volume, volume_size, grid_size, isolevel, vertex_vbo, index_vbo, normal_vbo, volume_func, NULL)) { ERROR_MSG("Marching Cubes: nothing to generate"); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); return 0; } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_vbo); glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &element_buffer_size); glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo); glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &vertex_buffer_size); glBindBuffer(GL_ARRAY_BUFFER, normal_vbo); glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &normal_buffer_size); if(element_buffer_size <= 0 || vertex_buffer_size <= 0 || normal_buffer_size <= 0) { glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); return 0; } float *vertex_data = (float*) malloc(vertex_buffer_size); float *normal_data = (float*) malloc(normal_buffer_size); unsigned int *element_data = (unsigned int*) malloc(element_buffer_size); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_vbo); glGetBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, element_buffer_size, element_data); glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo); glGetBufferSubData(GL_ARRAY_BUFFER, 0, vertex_buffer_size, vertex_data); glBindBuffer(GL_ARRAY_BUFFER, normal_vbo); glGetBufferSubData(GL_ARRAY_BUFFER, 0, normal_buffer_size, normal_data); // выделяем как можно больше памяти, чтобы вместились все данные *buffer = (char*) malloc(sizeof(char) * (element_buffer_size + vertex_buffer_size + normal_buffer_size)*8); *buffer[0] = '\0'; strcat(*buffer, "# Generated via VRender\n"); char *temp = (char*) malloc(sizeof(char) * 64); sprintf(temp, "# isolevel: %.3f\n", isolevel); strcat(*buffer, temp); sprintf(temp, "# volume size: x %i y %i z %i\n", volume_size.x, volume_size.y, volume_size.z); strcat(*buffer, temp); sprintf(temp, "# grid size: x %i y %i z %i\n", grid_size.x, grid_size.y, grid_size.z); strcat(*buffer, temp); unsigned buffer_begin = strlen(*buffer); unsigned num_chars = 0; char *ptr = *buffer; ptr += buffer_begin; num_chars = sprintf(temp, "\n# Vertices\n"); strcat(ptr, temp); ptr += num_chars; for(unsigned i = 0; i < (vertex_buffer_size / sizeof(float)); i += 3) { num_chars = sprintf(temp, "v %f %f %f\n", vertex_data[i], vertex_data[i+1], vertex_data[i+2]); strcat(ptr, temp); ptr += num_chars; } num_chars = sprintf(temp, "\n# Normals\n"); strcat(ptr, temp); ptr += num_chars; for(unsigned i = 0; i < (normal_buffer_size / sizeof(float)); i += 3) { num_chars = sprintf(temp, "vn %f %f %f\n", normal_data[i], normal_data[i+1], normal_data[i+2]); strcat(ptr, temp); ptr += num_chars; } num_chars = sprintf(temp, "\n# Faces\n"); strcat(ptr, temp); ptr += num_chars; for(unsigned i = 0; i < (element_buffer_size / sizeof(unsigned int)) - 3; i += 3) { num_chars = sprintf(temp, "f %i//%i %i//%i %i//%i\n", element_data[i]+1, element_data[i]+1, element_data[i+1]+1, element_data[i+1]+1, element_data[i+2]+1, element_data[i+2]+1); strcat(ptr, temp); ptr += num_chars; } num_chars = sprintf(temp, "\n# End\n"); strcat(ptr, temp); ptr += num_chars; free(vertex_data); free(element_data); free(normal_data); free(temp); glDeleteBuffers(1, &vertex_vbo); glDeleteBuffers(1, &index_vbo); glDeleteBuffers(1, &normal_vbo); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); return 1; }
meterd_rv meterd_createdb_counters(int force_overwrite) { counter_spec* counters = NULL; char* db_name = NULL; char* gas_id = NULL; char* gas_description = NULL; meterd_rv rv = MRV_OK; void* db_handle = NULL; /* Check if the database type is configured */ if ((rv = meterd_conf_get_string("database", "total_consumed", &db_name, NULL)) != MRV_OK) { ERROR_MSG("Failed to retrieve configuration option database.counters"); return rv; } if (db_name == NULL) { INFO_MSG("No database for consumption and production counters specified, skipping"); return MRV_OK; } /* Retrieve the consumption counters */ if ((rv = meterd_conf_get_counter_specs("database", "consumption", COUNTER_TYPE_CONSUMED, &counters)) != MRV_OK) { ERROR_MSG("Failed to retrieve consumption counter configuration"); return rv; } /* Retrieve the production counters */ if ((rv = meterd_conf_get_counter_specs("database", "production", COUNTER_TYPE_PRODUCED, &counters)) != MRV_OK) { ERROR_MSG("Failed to retrieve production counter configuration"); return rv; } /* Check if there is a gas counter configured */ if (((rv = meterd_conf_get_string("database.gascounter", "id", &gas_id, NULL)) != MRV_OK) || ((rv = meterd_conf_get_string("database.gascounter", "description", &gas_description, NULL)) != MRV_OK)) { ERROR_MSG("Failed to retrieve gas counter configuration"); free(db_name); free(gas_id); free(gas_description); meterd_conf_free_counter_specs(counters); return rv; } /* Add the gas counter if specified */ if (gas_id != NULL) { counter_spec* new_counter = NULL; if (gas_description == NULL) { gas_description = strdup("Gas"); } new_counter = (counter_spec*) malloc(sizeof(counter_spec)); if (new_counter == NULL) { free(db_name); free(gas_id); free(gas_description); meterd_conf_free_counter_specs(counters); return MRV_MEMORY; } new_counter->id = gas_id; new_counter->description = gas_description; new_counter->table_name = meterd_conf_create_table_name(gas_id, COUNTER_TYPE_CONSUMED); new_counter->type = COUNTER_TYPE_CONSUMED; LL_APPEND(counters, new_counter); } /* Create and open the database */ if ((rv = meterd_db_create(db_name, force_overwrite, &db_handle)) != MRV_OK) { ERROR_MSG("Failed to create database %s for counters", db_name); free(db_name); meterd_conf_free_counter_specs(counters); return rv; } INFO_MSG("Created database %s for counters", db_name); /* Create data tables */ if ((rv = meterd_db_create_tables(db_handle, counters)) != MRV_OK) { ERROR_MSG("Error during table creation"); unlink(db_name); } free(db_name); meterd_conf_free_counter_specs(counters); /* Close the database */ meterd_db_close(db_handle); return rv; }
//------------------------------------------------------------------------------------- bool PythonApp::installPyModules() { // 安装入口模块 PyObject *entryScriptFileName = NULL; if(componentType() == BASEAPP_TYPE) { ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getBaseApp(); entryScriptFileName = PyUnicode_FromString(info.entryScriptFile); } else if(componentType() == CELLAPP_TYPE) { ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getCellApp(); entryScriptFileName = PyUnicode_FromString(info.entryScriptFile); } else if(componentType() == INTERFACES_TYPE) { ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getInterfaces(); entryScriptFileName = PyUnicode_FromString(info.entryScriptFile); } else if (componentType() == LOGINAPP_TYPE) { ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getLoginApp(); entryScriptFileName = PyUnicode_FromString(info.entryScriptFile); } else if (componentType() == DBMGR_TYPE) { ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getDBMgr(); entryScriptFileName = PyUnicode_FromString(info.entryScriptFile); } else { ERROR_MSG("PythonApp::installPyModules: entryScriptFileName is NULL!\n"); } // 注册创建entity的方法到py // 向脚本注册app发布状态 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), publish, __py_getAppPublish, METH_VARARGS, 0); // 注册设置脚本输出类型 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), scriptLogType, __py_setScriptLogType, METH_VARARGS, 0); // 获得资源全路径 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), getResFullPath, __py_getResFullPath, METH_VARARGS, 0); // 是否存在某个资源 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), hasRes, __py_hasRes, METH_VARARGS, 0); // 打开一个文件 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), open, __py_kbeOpen, METH_VARARGS, 0); // 列出目录下所有文件 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), listPathRes, __py_listPathRes, METH_VARARGS, 0); // 匹配相对路径获得全路径 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), matchPath, __py_matchPath, METH_VARARGS, 0); // debug追踪kbe封装的py对象计数 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), debugTracing, script::PyGC::__py_debugTracing, METH_VARARGS, 0); if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_NORMAL", log4cxx::ScriptLevel::SCRIPT_INT)) { ERROR_MSG( "PythonApp::installPyModules: Unable to set KBEngine.LOG_TYPE_NORMAL.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_INFO", log4cxx::ScriptLevel::SCRIPT_INFO)) { ERROR_MSG( "PythonApp::installPyModules: Unable to set KBEngine.LOG_TYPE_INFO.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_ERR", log4cxx::ScriptLevel::SCRIPT_ERR)) { ERROR_MSG( "PythonApp::installPyModules: Unable to set KBEngine.LOG_TYPE_ERR.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_DBG", log4cxx::ScriptLevel::SCRIPT_DBG)) { ERROR_MSG( "PythonApp::installPyModules: Unable to set KBEngine.LOG_TYPE_DBG.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_WAR", log4cxx::ScriptLevel::SCRIPT_WAR)) { ERROR_MSG( "PythonApp::installPyModules: Unable to set KBEngine.LOG_TYPE_WAR.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "NEXT_ONLY", KBE_NEXT_ONLY)) { ERROR_MSG( "PythonApp::installPyModules: Unable to set KBEngine.NEXT_ONLY.\n"); } onInstallPyModules(); if (entryScriptFileName != NULL) { entryScript_ = PyImport_Import(entryScriptFileName); SCRIPT_ERROR_CHECK(); S_RELEASE(entryScriptFileName); if(entryScript_.get() == NULL) { return false; } } return true; }
//------------------------------------------------------------------------------------- bool Components::updateComponentInfos(const Components::ComponentInfos* info) { // 不对其他machine做处理 if(info->componentType == MACHINE_TYPE) { return true; } Network::EndPoint epListen; epListen.socket(SOCK_STREAM); if (!epListen.good()) { ERROR_MSG("Components::updateComponentInfos: couldn't create a socket\n"); return true; } epListen.setnonblocking(true); while(true) { fd_set frds, fwds; struct timeval tv = { 0, 300000 }; // 100ms FD_ZERO( &frds ); FD_ZERO( &fwds ); FD_SET((int)epListen, &frds); FD_SET((int)epListen, &fwds); if(epListen.connect(info->pIntAddr->port, info->pIntAddr->ip) == -1) { int selgot = select(epListen+1, &frds, &fwds, NULL, &tv); if(selgot > 0) { break; } WARNING_MSG(fmt::format("Components::updateComponentInfos: couldn't connect to:{}\n", info->pIntAddr->c_str())); return false; } } epListen.setnodelay(true); Network::Bundle* pBundle = Network::Bundle::ObjPool().createObject(); // 由于COMMON_NETWORK_MESSAGE不包含client, 如果是bots, 我们需要单独处理 if(info->componentType != BOTS_TYPE) { COMMON_NETWORK_MESSAGE(info->componentType, (*pBundle), lookApp); } else { (*pBundle).newMessage(BotsInterface::lookApp); } epListen.send(pBundle->pCurrPacket()->data(), pBundle->pCurrPacket()->wpos()); Network::Bundle::ObjPool().reclaimObject(pBundle); fd_set fds; struct timeval tv = { 0, 300000 }; // 100ms FD_ZERO( &fds ); FD_SET((int)epListen, &fds); int selgot = select(epListen+1, &fds, NULL, NULL, &tv); if(selgot == 0) { // 超时, 可能对方繁忙 return true; } else if(selgot == -1) { return true; } else { COMPONENT_TYPE ctype; COMPONENT_ID cid; int8 istate = 0; ArraySize entitySize = 0, cellSize = 0; int32 clientsSize = 0, proxicesSize = 0; uint32 telnet_port = 0; Network::TCPPacket packet; packet.resize(255); int recvsize = sizeof(ctype) + sizeof(cid) + sizeof(istate); if(info->componentType == CELLAPP_TYPE) { recvsize += sizeof(entitySize) + sizeof(cellSize) + sizeof(telnet_port); } if(info->componentType == BASEAPP_TYPE) { recvsize += sizeof(entitySize) + sizeof(clientsSize) + sizeof(proxicesSize) + sizeof(telnet_port); } int len = epListen.recv(packet.data(), recvsize); packet.wpos(len); if(recvsize != len) { WARNING_MSG(fmt::format("Components::updateComponentInfos: packet invalid(recvsize({}) != ctype_cid_len({}).\n" , len, recvsize)); if(len == 0) return false; return true; } packet >> ctype >> cid >> istate; if(ctype == CELLAPP_TYPE) { packet >> entitySize >> cellSize >> telnet_port; } if(ctype == BASEAPP_TYPE) { packet >> entitySize >> clientsSize >> proxicesSize >> telnet_port; }
/* * var_apGeneralInfo(): * This function is called every time the agent gets a request for * a scalar variable that might be found within your mib section * registered above. It is up to you to do the right thing and * return the correct value. * You should also correct the value of "var_len" if necessary. * * Please see the documentation for more information about writing * module extensions, and check out the examples in the examples * and mibII directories. */ unsigned char * var_apGeneralInfo(struct variable *vp, oid *name, size_t *length, int exact, size_t *var_len, WriteMethod **write_method) { /* variables we may use later */ static long long_ret; static u_long ulong_ret; static unsigned char string[256]; static unsigned char string1[2048]; char string2[2048]; static char str_tmp[1024]; static unsigned char ap_parameter[256]; static unsigned char para[256]; static unsigned char ipaddr[32]; prop_data properties[255]; int prop_count=0; static oid objid[128]; static struct counter64 c64; FILE *stream; static char buffer[4][32]; static char strBuf[2][32]; static char MACWork[17]; static char *token; static char *pos; static int retu_addr=0; int byte_read=0; int memTotal=0; int i=0; if (header_generic(vp,name,length,exact,var_len,write_method) == MATCH_FAILED ) return NULL; /* * this is where we do the value assignments for the mib results. */ switch(vp->magic) { case SYSTIME: *write_method = write_SysTime; stream=popen("date","r"); if(stream) { memset( string, 0, 256 ); fgets(string,sizeof(string),stream); string[strlen(string)-1] = '\0'; pclose(stream); *var_len = strlen (string ); return (u_char*)string; } case PRIMDNSSERVERIPADD: memset( string, 0, 256 ); *write_method = write_PrimDNSServerIPAdd; network_get_dns(string,1,20 ); retu_addr=inet_addr(string); *var_len = 4; return (u_char*)&retu_addr; case SECONDNSSERVERIPADD: memset( string, 0, 256 ); *write_method = write_SeconDNSServerIPAdd; network_get_dns(string,2,20 ); retu_addr=inet_addr(string); *var_len = 4; return (u_char*)&retu_addr; case SNMPPORT: ulong_ret =161; return (u_char*) &ulong_ret; case READCOMMUNITYNAME: *write_method = write_ReadCommunityName; memset(string,0,256); memset(para,0,256); memset(buffer[0],0,32); memset(buffer[1],0,32); memset(buffer[2],0,32); memset(buffer[3],0,32); stream=fopen("/etc/snmp/snmpd.conf","r"); if(stream) { fgets(string,64,stream); token=strtok(string," "); while(NULL!=token) { strcpy(buffer[i],token); token=strtok(NULL," "); i++; } strcpy(para,buffer[3]); para[strlen(para)-1] = '\0'; fclose(stream); } *var_len = strlen(para); return (u_char *) para; case WRITECOMMUNITYNAME: *write_method = write_WriteCommunityName; memset(string,0,256); memset(para,0,256); memset(buffer[0],0,32); memset(buffer[1],0,32); memset(buffer[2],0,32); memset(buffer[3],0,32); stream=fopen("/etc/snmp/snmpd.conf","r"); if(stream) { fgets(string,64,stream); fgets(string,64,stream); token=strtok(string," "); while(NULL!=token) { strcpy(buffer[i],token); token=strtok(NULL," "); i++; } strcpy(para,buffer[3]); para[strlen(para)-1] = '\0'; fclose(stream); } *var_len = strlen(para); return (u_char *) para; case STATWINDOWTIME: *write_method = write_StatWindowTime; memset(ap_parameter,0,256); prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("STAT_WINDOW_TIME",ap_parameter,properties,prop_count); free_prop(properties,prop_count) ; long_ret =atoi(ap_parameter); return (u_char*) &long_ret; case SAMPLETIME: memset(ap_parameter,0,256); *write_method = write_SampleTime; prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("SAMPLE_TIME",ap_parameter,properties,prop_count); free_prop(properties,prop_count) ; ulong_ret =atoi(ap_parameter); return (u_char*) &ulong_ret; case HEARTBEATPERIOD: memset(ap_parameter,0,256); *write_method = write_HeartbeatPeriod; prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("HEART_BEAT_PERIOD",ap_parameter,properties,prop_count); free_prop(properties,prop_count) ; ulong_ret =atoi(ap_parameter); return (u_char*) &ulong_ret; case SYSREMOTERESTART: *write_method = write_SysRemoteRestart; ulong_ret =1; return (u_char*) &ulong_ret; case SYSRESTART: *write_method = write_SysRestart; ulong_ret =1; return (u_char*) &ulong_ret; case SYSRESET: *write_method = write_SysReset; ulong_ret =1; return (u_char*) &ulong_ret; case SOFTWARENAME: memset(para,0,256); sprintf(para,"%s","/usr/sbin/showsysinfo |awk -F \":\" '/Device/{print $2}' "); stream=popen(para,"r"); if(stream) { memset(string,0,256); fgets(string,sizeof(string),stream); string[strlen(string)-1]='\0'; pclose(stream); } *var_len = strlen(string); return (u_char*) string; case SOFTWAREVERSION: memset(para,0,256); sprintf(para,"%s","/usr/sbin/showsysinfo |awk -F \":\" '/Software/{print $2}'"); stream=popen(para,"r"); if(stream) { memset(string,0,256); fgets(string,sizeof(string),stream); string[strlen(string)-1]='\0'; pclose(stream); } *var_len = strlen(string); return (u_char*) string; case SOFTWAREVENDOR: memset(para,0,256); sprintf(para,"%s","/usr/sbin/showsysinfo |awk -F \":\" '/Company/{print $2}' "); stream=popen(para,"r"); if(stream) { memset(string,0,256); fgets(string,sizeof(string),stream); string[strlen(string)-1]='\0'; pclose(stream); } *var_len = strlen(string); return (u_char*) string; case CPUTYPE: stream = fopen("/proc/cpuinfo", "r"); if(stream) { fgets(string,64,stream); token=strtok(string,":"); while(NULL!=token) { strcpy(strBuf[i],token); token=strtok(NULL,":"); i++; } strcpy(para,strBuf[1]); para[strlen(para)-1] = '\0'; fclose(stream); } *var_len = strlen(para); return (u_char*) para; case CPUUSAGETHRESHHD: *write_method = write_CPUusageThreshhd; prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("CPU_USAGE_THRESHHD",ap_parameter,properties,prop_count); free_prop(properties,prop_count) ; ulong_ret =atoi(ap_parameter); return (u_char*) &ulong_ret; case APMEMORYTYPE: memset(ap_parameter,0,256); prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("AP_MEMORY",ap_parameter,properties,prop_count); free_prop(properties,prop_count) ; *var_len = strlen(ap_parameter); return (u_char*) ap_parameter; case MEMORYSIZE: stream = fopen("/proc/meminfo", "r"); byte_read=fread(str_tmp, 1, sizeof(str_tmp), stream); fclose(stream); if (byte_read==0||byte_read==sizeof(str_tmp)) return -1; str_tmp[byte_read] = '\0'; pos = strstr(str_tmp, "MemTotal:"); if (NULL==pos) return -1; sscanf(pos, "MemTotal: %d kB", &memTotal); printf("memTotal:%d\n",memTotal); long_ret =memTotal*1024; return (u_char *) &long_ret; case MEMUSAGETHRESHHD: memset(ap_parameter,0,256); *write_method = write_MemUsageThreshhd; prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("MEM_USAGE_THRESHHD",ap_parameter,properties,prop_count); free_prop(properties,prop_count) ; ulong_ret =atoi(ap_parameter); return (u_char*) &ulong_ret; case APFLASHSIZE: long_ret =32*1024*1024; return (u_char *) &long_ret; case ROGUEAPTRIGGER: *write_method = write_RogueApTrigger; memset(string,0,256); strcpy(string,"trigger rogue ap"); *var_len = strlen(string); return (u_char*) string; //heyanhua add for setPingIPaddr ---2010-4-23 case SETPINGIPADDR: memset(ipaddr,0,32); *write_method = write_setPingIPaddr; prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("PING_ADDR",ipaddr,properties,prop_count); free_prop(properties,prop_count) ; printf("setPingIPaddr:%s\n",ipaddr); retu_addr=inet_addr(ipaddr); *var_len = 4; return ( UCHAR * )&retu_addr; //heyanhua add for ping testing ---2010-4-22 case SYSPINGTESTING: { FILE *fp; char cmd[128]; memset(cmd, 0, 128); memset(string1,0,2048); memset(string2,0,2048); prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("PING_ADDR",para,properties,prop_count); free_prop(properties,prop_count) ; printf("The PING_ADDR is :%s\n",para); // retu_addr=inet_addr(para); sprintf(cmd,"%s %s","/bin/ping -c 4",para); fp=popen(cmd,"r"); if(fp) { while(NULL!=fgets(string1,sizeof(string1),fp)) strcat(string2,string1); printf("heyanhua test! string1:%s\n",string1); pclose(fp); } *var_len=strlen(string2); printf("heyanhua test 1:string2:%s\n",string2); return (u_char *)string2; } case HARDWAREVERSION: //heyanhua add 2010-4-30 { FILE *fp; fp=popen("/usr/sbin/showsysinfo |awk -F : '/Hardware/ {print $2}'","r"); if(fp) { memset(string,0,256); fgets(string,sizeof(string),fp); pclose(fp); } *var_len=strlen(string); return (u_char *)string; } case SETPINGIPV6ADDR: memset(string,0,256); *write_method=write_setPingIPv6addr; prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("PING_IPv6_ADDR",string,properties,prop_count); free_prop(properties,prop_count) ; printf("setPingIPaddr:%s\n",string); *var_len = strlen(string); return ( UCHAR * )string; case SYSPINGIPV6TESTING: { FILE *fp; char cmd[128]; memset(cmd, 0, 128); memset(string1,0,2048); memset(string2,0,2048); prop_count=load_prop(SEP_EQUAL,SNMP_AGENT_CONF,properties); get_prop("PING_IPv6_ADDR",para,properties,prop_count); free_prop(properties,prop_count) ; printf("The PING_IPv6_ADDR is :%s\n",para); sprintf(cmd,"%s %s","/bin/ping6 -c 4",para); fp=popen(cmd,"r"); if(fp) { while(NULL!=fgets(string1,sizeof(string1),fp)) strcat(string2,string1); printf("heyanhua test! string1:%s\n",string1); pclose(fp); } *var_len=strlen(string2); printf("heyanhua test 1:string2:%s\n",string2); return (u_char *)string2; } default: ERROR_MSG(""); } return NULL; }
//------------------------------------------------------------------------------------- void Machine::startserver(Mercury::Channel* pChannel, KBEngine::MemoryStream& s) { int32 uid = 0; COMPONENT_TYPE componentType; uint32 recvip; uint16 recvport; Mercury::Bundle bundle; bool success = true; s >> uid; s >> componentType; s >> recvip; s >> recvport; INFO_MSG("Machine::startserver: uid=%d, [%s], addr:%s, recvPort:%u.\n", uid, COMPONENT_NAME[componentType], inet_ntoa((struct in_addr&)recvip), ntohs(recvport)); Mercury::EndPoint ep; ep.socket(SOCK_DGRAM); if (!ep.good()) { ERROR_MSG("Machine::startserver: Failed to create socket.\n"); return; } #if KBE_PLATFORM == PLATFORM_WIN32 STARTUPINFO si; PROCESS_INFORMATION pi; std::string str = Resmgr::getEnv().hybrid_path; str += COMPONENT_NAME[componentType]; str += ".exe"; wchar_t* szCmdline = KBEngine::char2wchar(str.c_str()); wchar_t* currdir = KBEngine::char2wchar(Resmgr::getEnv().hybrid_path.c_str()); ZeroMemory( &si, sizeof(si)); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi)); if(!CreateProcess( NULL, // No module name (use command line) szCmdline, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE CREATE_NEW_CONSOLE, // No creation flags NULL, // Use parent's environment block currdir, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { ERROR_MSG( "Machine::startserver:CreateProcess failed (%d).\n", GetLastError()); success = false; } free(szCmdline); free(currdir); #else #endif bundle << success; bundle.sendto(ep, recvport, recvip); }
//------------------------------------------------------------------------------------- bool Loginapp::_createAccount(Network::Channel* pChannel, std::string& accountName, std::string& password, std::string& datas, ACCOUNT_TYPE type) { AUTO_SCOPED_PROFILE("createAccount"); ACCOUNT_TYPE oldType = type; if(!g_kbeSrvConfig.getDBMgr().account_registration_enable) { WARNING_MSG(fmt::format("Loginapp::_createAccount({}): not available!\n", accountName)); std::string retdatas = ""; Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); SERVER_ERROR_CODE retcode = SERVER_ERR_ACCOUNT_REGISTER_NOT_AVAILABLE; (*pBundle) << retcode; (*pBundle).appendBlob(retdatas); pChannel->send(pBundle); return false; } accountName = KBEngine::strutil::kbe_trim(accountName); password = KBEngine::strutil::kbe_trim(password); if(accountName.size() > ACCOUNT_NAME_MAX_LENGTH) { ERROR_MSG(fmt::format("Loginapp::_createAccount: accountName too big, size={}, limit={}.\n", accountName.size(), ACCOUNT_NAME_MAX_LENGTH)); return false; } if(password.size() > ACCOUNT_PASSWD_MAX_LENGTH) { ERROR_MSG(fmt::format("Loginapp::_createAccount: password too big, size={}, limit={}.\n", password.size(), ACCOUNT_PASSWD_MAX_LENGTH)); return false; } if(datas.size() > ACCOUNT_DATA_MAX_LENGTH) { ERROR_MSG(fmt::format("Loginapp::_createAccount: bindatas too big, size={}, limit={}.\n", datas.size(), ACCOUNT_DATA_MAX_LENGTH)); return false; } std::string retdatas = ""; if(shuttingdown_ != SHUTDOWN_STATE_STOP) { WARNING_MSG(fmt::format("Loginapp::_createAccount: shutting down, create {} failed!\n", accountName)); Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); SERVER_ERROR_CODE retcode = SERVER_ERR_IN_SHUTTINGDOWN; (*pBundle) << retcode; (*pBundle).appendBlob(retdatas); pChannel->send(pBundle); return false; } PendingLoginMgr::PLInfos* ptinfos = pendingCreateMgr_.find(const_cast<std::string&>(accountName)); if(ptinfos != NULL) { WARNING_MSG(fmt::format("Loginapp::_createAccount: pendingCreateMgr has {}, request create failed!\n", accountName)); Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); SERVER_ERROR_CODE retcode = SERVER_ERR_BUSY; (*pBundle) << retcode; (*pBundle).appendBlob(retdatas); pChannel->send(pBundle); return false; } { // 把请求交由脚本处理 SERVER_ERROR_CODE retcode = SERVER_SUCCESS; SCOPED_PROFILE(SCRIPTCALL_PROFILE); PyObject* pyResult = PyObject_CallMethod(getEntryScript().get(), const_cast<char*>("onRequestCreateAccount"), const_cast<char*>("ssy#"), accountName.c_str(), password.c_str(), datas.c_str(), datas.length()); if(pyResult != NULL) { if(PySequence_Check(pyResult) && PySequence_Size(pyResult) == 4) { char* sname; char* spassword; char *extraDatas; Py_ssize_t extraDatas_size = 0; if(PyArg_ParseTuple(pyResult, "H|s|s|y#", &retcode, &sname, &spassword, &extraDatas, &extraDatas_size) == -1) { ERROR_MSG(fmt::format("Loginapp::_createAccount: {}.onReuqestLogin, Return value error! accountName={}\n", g_kbeSrvConfig.getLoginApp().entryScriptFile, accountName)); retcode = SERVER_ERR_OP_FAILED; } else { accountName = sname; password = spassword; if (extraDatas && extraDatas_size > 0) datas.assign(extraDatas, extraDatas_size); else SCRIPT_ERROR_CHECK(); } } else { ERROR_MSG(fmt::format("Loginapp::_createAccount: {}.onReuqestLogin, Return value error, must be errorcode or tuple! accountName={}\n", g_kbeSrvConfig.getLoginApp().entryScriptFile, accountName)); retcode = SERVER_ERR_OP_FAILED; } Py_DECREF(pyResult); } else { SCRIPT_ERROR_CHECK(); retcode = SERVER_ERR_OP_FAILED; } if(retcode != SERVER_SUCCESS) { Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); (*pBundle) << retcode; (*pBundle).appendBlob(retdatas); pChannel->send(pBundle); return false; } else { if(accountName.size() == 0) { ERROR_MSG(fmt::format("Loginapp::_createAccount: accountName is empty!\n")); retcode = SERVER_ERR_NAME; Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); (*pBundle) << retcode; (*pBundle).appendBlob(retdatas); pChannel->send(pBundle); return false; } } } if(type == ACCOUNT_TYPE_SMART) { if (email_isvalid(accountName.c_str())) { type = ACCOUNT_TYPE_MAIL; } else { if(!validName(accountName)) { ERROR_MSG(fmt::format("Loginapp::_createAccount: invalid accountName({})\n", accountName)); Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); SERVER_ERROR_CODE retcode = SERVER_ERR_NAME; (*pBundle) << retcode; (*pBundle).appendBlob(retdatas); pChannel->send(pBundle); return false; } type = ACCOUNT_TYPE_NORMAL; } } else if(type == ACCOUNT_TYPE_NORMAL) { if(!validName(accountName)) { ERROR_MSG(fmt::format("Loginapp::_createAccount: invalid accountName({})\n", accountName)); Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); SERVER_ERROR_CODE retcode = SERVER_ERR_NAME; (*pBundle) << retcode; (*pBundle).appendBlob(retdatas); pChannel->send(pBundle); return false; } } else if (!email_isvalid(accountName.c_str())) { /* std::string user_name, domain_name; user_name = regex_replace(accountName, _g_mail_pattern, std::string("$1") ); domain_name = regex_replace(accountName, _g_mail_pattern, std::string("$2") ); */ WARNING_MSG(fmt::format("Loginapp::_createAccount: invalid mail={}\n", accountName)); Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); SERVER_ERROR_CODE retcode = SERVER_ERR_NAME_MAIL; (*pBundle) << retcode; (*pBundle).appendBlob(retdatas); pChannel->send(pBundle); return false; } DEBUG_MSG(fmt::format("Loginapp::_createAccount: accountName={}, passwordsize={}, type={}, oldType={}.\n", accountName.c_str(), password.size(), type, oldType)); ptinfos = new PendingLoginMgr::PLInfos; ptinfos->accountName = accountName; ptinfos->password = password; ptinfos->datas = datas; ptinfos->addr = pChannel->addr(); pendingCreateMgr_.add(ptinfos); Components::COMPONENTS& cts = Components::getSingleton().getComponents(DBMGR_TYPE); Components::ComponentInfos* dbmgrinfos = NULL; if(cts.size() > 0) dbmgrinfos = &(*cts.begin()); if(dbmgrinfos == NULL || dbmgrinfos->pChannel == NULL || dbmgrinfos->cid == 0) { ERROR_MSG(fmt::format("Loginapp::_createAccount: create({}), not found dbmgr!\n", accountName)); Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); SERVER_ERROR_CODE retcode = SERVER_ERR_SRV_NO_READY; (*pBundle) << retcode; (*pBundle).appendBlob(retdatas); pChannel->send(pBundle); return false; } pChannel->extra(accountName); Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(DbmgrInterface::reqCreateAccount); uint8 uatype = uint8(type); (*pBundle) << accountName << password << uatype; (*pBundle).appendBlob(datas); dbmgrinfos->pChannel->send(pBundle); return true; }
//------------------------------------------------------------------------------------- bool ClientObject::initCreate() { Network::EndPoint* pEndpoint = Network::EndPoint::createPoolObject(); pEndpoint->socket(SOCK_STREAM); if (!pEndpoint->good()) { ERROR_MSG("ClientObject::initNetwork: couldn't create a socket\n"); Network::EndPoint::reclaimPoolObject(pEndpoint); error_ = C_ERROR_INIT_NETWORK_FAILED; return false; } ENGINE_COMPONENT_INFO& infos = g_kbeSrvConfig.getBots(); u_int32_t address; Network::Address::string2ip(infos.login_ip, address); if(pEndpoint->connect(htons(infos.login_port), address) == -1) { ERROR_MSG(fmt::format("ClientObject::initNetwork({1}): connect server({2}:{3}) is error({0})!\n", kbe_strerror(), name_, infos.login_ip, infos.login_port)); Network::EndPoint::reclaimPoolObject(pEndpoint); // error_ = C_ERROR_INIT_NETWORK_FAILED; state_ = C_STATE_INIT; return false; } Network::Address addr(infos.login_ip, infos.login_port); pEndpoint->addr(addr); pServerChannel_->pEndPoint(pEndpoint); pEndpoint->setnonblocking(true); pEndpoint->setnodelay(true); pServerChannel_->pMsgHandlers(&ClientInterface::messageHandlers); pTCPPacketSenderEx_ = new Network::TCPPacketSenderEx(*pEndpoint, this->networkInterface_, this); pTCPPacketReceiverEx_ = new Network::TCPPacketReceiverEx(*pEndpoint, this->networkInterface_, this); Bots::getSingleton().networkInterface().dispatcher().registerReadFileDescriptor((*pEndpoint), pTCPPacketReceiverEx_); //²»ÔÚÕâÀï×¢²á //Bots::getSingleton().networkInterface().dispatcher().registerWriteFileDescriptor((*pEndpoint), pTCPPacketSenderEx_); pServerChannel_->pPacketSender(pTCPPacketSenderEx_); Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(LoginappInterface::hello); (*pBundle) << KBEVersion::versionString() << KBEVersion::scriptVersionString(); if(Network::g_channelExternalEncryptType == 1) { pBlowfishFilter_ = new Network::BlowfishFilter(); (*pBundle).appendBlob(pBlowfishFilter_->key()); } else { std::string key = ""; (*pBundle).appendBlob(key); } pEndpoint->send(pBundle); Network::Bundle::reclaimPoolObject(pBundle); return true; }
/* * var_tcpConnTable(): * Handle this table separately from the scalar value case. * The workings of this are basically the same as for var_tcpConnTable above. */ unsigned char * var_tcpConnTable(struct variable *vp, oid *name, size_t *length, int exact, size_t *var_len, WriteMethod **write_method) { static long long_ret; static unsigned char string[SPRINT_MAX_LEN]; register struct inpcb *inp; register struct inpcb *low_inp = NULL; oid lowest[24]; oid newname[24]; u_char *cp; oid *op; struct tcpcb *tp; // This is indexed by local-address, local-port, remote-address, remport // at 1,3,6,1,2,1,6,13,1 // so we get 1,3,6,1,2,1,6,13,1,?,A,B,C,D,lport,P,Q,R,S,rport // initial length is 10, out-length is 20, // Local address is offsets 10-13, port is offset 14. // Remote address is offsets 15-18, port is offset 19. // starting from udbtable, look in // low_pcb->inp_laddr.s_addr // and low_pcb->inp_lport // /_l/_f/ for foreign port,address. /* fill in object part of name for current (less sizeof instance part) */ memcpy((char *)newname, (char *)vp->name, (int)vp->namelen * sizeof(oid)); for ( #ifdef CYGPKG_NET_OPENBSD_STACK inp = tcbtable.inpt_queue.cqh_first; inp != (struct inpcb *)&tcbtable.inpt_queue; inp = inp->inp_queue.cqe_next #endif #ifdef CYGPKG_NET_FREEBSD_STACK inp = tcb.lh_first; inp; inp = inp->inp_list.le_next #endif ) { cp = (u_char *)&inp->inp_laddr.s_addr; op = newname + 10; *op++ = *cp++; *op++ = *cp++; *op++ = *cp++; *op++ = *cp++; newname[14] = ntohs(inp->inp_lport); cp = (u_char *)&inp->inp_faddr.s_addr; op = newname + 15; *op++ = *cp++; *op++ = *cp++; *op++ = *cp++; *op++ = *cp++; newname[19] = ntohs(inp->inp_fport); if (exact){ if (snmp_oid_compare(newname, 20, name, *length) == 0){ memcpy( (char *)lowest,(char *)newname, 20 * sizeof(oid)); low_inp = inp; break; /* no need to search further */ } } else { if ((snmp_oid_compare(newname, 20, name, *length) > 0) && (!low_inp || (snmp_oid_compare(newname, 20, lowest, 20) < 0))){ /* * if new one is greater than input and closer to input than * previous lowest, save this one as the "next" one. */ memcpy( (char *)lowest,(char *)newname, 20 * sizeof(oid)); low_inp = inp; } } } if ( ! low_inp ) return NULL; tp = intotcpcb( low_inp ); if ( ! tp ) return NULL; // Shouldn't happen memcpy( (char *)name,(char *)lowest, 20 * sizeof(oid)); *length = 20; *var_len = sizeof( long_ret ); *write_method = 0; switch(vp->magic) { case TCPCONNSTATE: // NOTSUPPORTED: *write_method = write_tcpConnState; switch ( tp->t_state ) { case TCPS_CLOSED : // 0 /* closed */ long_ret = 1; break; case TCPS_LISTEN : // 1 /* listening for connection */ long_ret = 2; break; case TCPS_SYN_SENT : // 2 /* active, have sent syn */ long_ret = 3; break; case TCPS_SYN_RECEIVED : // 3 /* have sent and received syn */ long_ret = 4; break; case TCPS_ESTABLISHED : // 4 /* established */ long_ret = 5; break; case TCPS_CLOSE_WAIT : // 5 /* rcvd fin, waiting for close */ long_ret = 8; break; case TCPS_FIN_WAIT_1 : // 6 /* have closed, sent fin */ long_ret = 6; break; case TCPS_CLOSING : // 7 /* closed xchd FIN; await ACK */ long_ret = 10; break; case TCPS_LAST_ACK : // 8 /* had fin and close; await FIN ACK */ long_ret = 9; break; case TCPS_FIN_WAIT_2 : // 9 /* have closed, fin is acked */ long_ret = 7; break; case TCPS_TIME_WAIT : // 10 /* in 2*msl quiet wait after close */ long_ret = 11; break; default: long_ret = 1; } return (unsigned char *) &long_ret; case TCPCONNLOCALADDRESS: cp = (u_char *)&low_inp->inp_laddr.s_addr; string[0] = *cp++; string[1] = *cp++; string[2] = *cp++; string[3] = *cp++; *var_len = 4; return (unsigned char *) string; case TCPCONNLOCALPORT: long_ret = (long)ntohs(low_inp->inp_lport); return (unsigned char *) &long_ret; case TCPCONNREMADDRESS: cp = (u_char *)&low_inp->inp_faddr.s_addr; string[0] = *cp++; string[1] = *cp++; string[2] = *cp++; string[3] = *cp++; *var_len = 4; return (unsigned char *) string; case TCPCONNREMPORT: long_ret = (long)ntohs(low_inp->inp_fport); return (unsigned char *) &long_ret; default: ERROR_MSG(""); } return NULL; }
void soclEnqueueNDRangeKernel_task(void *descr[], void *args) { command_ndrange_kernel cmd = (command_ndrange_kernel)args; cl_command_queue cq; int wid; cl_int err; cl_event ev = command_event_get(cmd); ev->prof_start = _socl_nanotime(); gc_entity_release(ev); wid = starpu_worker_get_id(); starpu_opencl_get_queue(wid, &cq); DEBUG_MSG("[worker %d] [kernel %d] Executing kernel...\n", wid, cmd->kernel->id); int range = starpu_worker_get_range(); /* Set arguments */ { unsigned int i; int buf = 0; for (i=0; i<cmd->num_args; i++) { switch (cmd->arg_types[i]) { case Null: err = clSetKernelArg(cmd->kernel->cl_kernels[range], i, cmd->arg_sizes[i], NULL); break; case Buffer: { cl_mem mem; mem = (cl_mem)STARPU_VARIABLE_GET_PTR(descr[buf]); err = clSetKernelArg(cmd->kernel->cl_kernels[range], i, cmd->arg_sizes[i], &mem); buf++; } break; case Immediate: err = clSetKernelArg(cmd->kernel->cl_kernels[range], i, cmd->arg_sizes[i], cmd->args[i]); break; } if (err != CL_SUCCESS) { DEBUG_CL("clSetKernelArg", err); DEBUG_ERROR("Aborting\n"); } } } /* Calling Kernel */ cl_event event; err = clEnqueueNDRangeKernel(cq, cmd->kernel->cl_kernels[range], cmd->work_dim, cmd->global_work_offset, cmd->global_work_size, cmd->local_work_size, 0, NULL, &event); if (err != CL_SUCCESS) { ERROR_MSG("Worker[%d] Unable to Enqueue kernel (error %d)\n", wid, err); DEBUG_CL("clEnqueueNDRangeKernel", err); DEBUG_MSG("Workdim %d, global_work_offset %p, global_work_size %p, local_work_size %p\n", cmd->work_dim, cmd->global_work_offset, cmd->global_work_size, cmd->local_work_size); DEBUG_MSG("Global work size: %ld %ld %ld\n", cmd->global_work_size[0], (cmd->work_dim > 1 ? cmd->global_work_size[1] : 1), (cmd->work_dim > 2 ? cmd->global_work_size[2] : 1)); if (cmd->local_work_size != NULL) DEBUG_MSG("Local work size: %ld %ld %ld\n", cmd->local_work_size[0], (cmd->work_dim > 1 ? cmd->local_work_size[1] : 1), (cmd->work_dim > 2 ? cmd->local_work_size[2] : 1)); } else { /* Waiting for kernel to terminate */ clWaitForEvents(1, &event); clReleaseEvent(event); } }
/* * var_tcp(): * This function is called every time the agent gets a request for * a scalar variable that might be found within your mib section * registered above. It is up to you to do the right thing and * return the correct value. * You should also correct the value of "var_len" if necessary. * * Please see the documentation for more information about writing * module extensions, and check out the examples in the examples * and mibII directories. */ unsigned char * var_tcp(struct variable *vp, oid *name, size_t *length, int exact, size_t *var_len, WriteMethod **write_method) { static long long_ret; if (header_generic(vp,name,length,exact,var_len,write_method) == MATCH_FAILED ) return NULL; switch(vp->magic) { case TCPRTOALGORITHM: long_ret = 1; // meaning "other" return (unsigned char *) &long_ret; case TCPRTOMIN: long_ret = TCPTV_MIN / PR_SLOWHZ * 1000;; return (unsigned char *) &long_ret; case TCPRTOMAX: long_ret = TCPTV_REXMTMAX / PR_SLOWHZ * 1000;; return (unsigned char *) &long_ret; case TCPMAXCONN: long_ret = -1; // It is dynamic. return (unsigned char *) &long_ret; case TCPACTIVEOPENS: long_ret = tcpstat.tcps_connattempt; return (unsigned char *) &long_ret; case TCPPASSIVEOPENS: long_ret = tcpstat.tcps_accepts; return (unsigned char *) &long_ret; case TCPATTEMPTFAILS: long_ret = tcpstat.tcps_conndrops; return (unsigned char *) &long_ret; case TCPESTABRESETS: long_ret = tcpstat.tcps_drops; return (unsigned char *) &long_ret; case TCPCURRESTAB: { struct inpcb *inp; long_ret = 0; for ( #ifdef CYGPKG_NET_OPENBSD_STACK inp = tcbtable.inpt_queue.cqh_first; inp != (struct inpcb *)&tcbtable.inpt_queue; inp = inp->inp_queue.cqe_next #endif #ifdef CYGPKG_NET_FREEBSD_STACK inp = tcb.lh_first; inp; inp = inp->inp_list.le_next #endif ) { struct tcpcb *tp = intotcpcb( inp ); if ( tp && (TCPS_ESTABLISHED == tp->t_state || TCPS_CLOSE_WAIT == tp->t_state) ) long_ret++; } return (unsigned char *) &long_ret; } case TCPINSEGS: long_ret = tcpstat.tcps_rcvtotal; return (unsigned char *) &long_ret; case TCPOUTSEGS: long_ret = tcpstat.tcps_sndtotal - tcpstat.tcps_sndrexmitpack; if ( long_ret < 0 ) long_ret = 0; return (unsigned char *) &long_ret; case TCPRETRANSSEGS: long_ret = tcpstat.tcps_sndrexmitpack; return (unsigned char *) &long_ret; case TCPINERRS: long_ret = tcpstat.tcps_rcvbadsum + tcpstat.tcps_rcvbadoff + tcpstat.tcps_rcvshort + tcpstat.tcps_rcvmemdrop; // Is that last one an input error? return (unsigned char *) &long_ret; case TCPOUTRSTS: long_ret = tcpstat.tcps_sndctrl - tcpstat.tcps_closed; if ( long_ret < 0 ) long_ret = 0; return (unsigned char *) &long_ret; default: ERROR_MSG(""); } return NULL; }
//------------------------------------------------------------------------------------- void Entity::teleportFromBaseapp(Mercury::Channel* pChannel, COMPONENT_ID cellAppID, ENTITY_ID targetEntityID, COMPONENT_ID sourceBaseAppID) { DEBUG_MSG(boost::format("%1%::teleportFromBaseapp: %2%, targetEntityID=%3%, cell=%4%, sourceBaseAppID=%5%.\n") % this->getScriptName() % this->getID() % targetEntityID % cellAppID % sourceBaseAppID); SPACE_ID lastSpaceID = this->getSpaceID(); // 如果不在一个cell上 if(cellAppID != g_componentID) { Components::ComponentInfos* cinfos = Components::getSingleton().findComponent(cellAppID); if(cinfos == NULL || cinfos->pChannel == NULL) { ERROR_MSG(boost::format("%1%::teleportFromBaseapp: %2%, teleport is error, not found cellapp, targetEntityID, cellAppID=%3%.\n") % this->getScriptName() % this->getID() % targetEntityID % cellAppID); _sendBaseTeleportResult(this->getID(), sourceBaseAppID, 0, lastSpaceID); return; } } else { Entity* entity = Cellapp::getSingleton().findEntity(targetEntityID); if(entity == NULL || entity->isDestroyed()) { ERROR_MSG(boost::format("%1%::teleportFromBaseapp: %2%, can't found targetEntity(%3%).\n") % this->getScriptName() % this->getID() % targetEntityID); _sendBaseTeleportResult(this->getID(), sourceBaseAppID, 0, lastSpaceID); return; } // 找到space SPACE_ID spaceID = entity->getSpaceID(); // 如果是不同space跳转 if(spaceID != this->getSpaceID()) { Space* space = Spaces::findSpace(spaceID); if(space == NULL) { ERROR_MSG(boost::format("%1%::teleportFromBaseapp: %2%, can't found space(%3%).\n") % this->getScriptName() % this->getID() % spaceID); _sendBaseTeleportResult(this->getID(), sourceBaseAppID, 0, lastSpaceID); return; } Space* currspace = Spaces::findSpace(this->getSpaceID()); currspace->removeEntity(this); space->addEntity(this); _sendBaseTeleportResult(this->getID(), sourceBaseAppID, spaceID, lastSpaceID); } else { WARNING_MSG(boost::format("%1%::teleportFromBaseapp: %2% targetSpace(%3%) == currSpaceID(%4%).\n") % this->getScriptName() % this->getID() % spaceID % this->getSpaceID()); _sendBaseTeleportResult(this->getID(), sourceBaseAppID, spaceID, lastSpaceID); } } }
int fw_thread_id() { pthread_t current_thread; ttglobal tg = gglobal(); current_thread = pthread_self(); #ifdef _MSC_VER if (!current_thread.p) { #else if (!current_thread) { #endif ERROR_MSG("Critical: pthread_self returned 0\n"); return 0; } if (pthread_equal(current_thread, tg->threads.mainThread)) return FREEWRL_THREAD_MAIN; if (pthread_equal(current_thread, tg->threads.DispThrd)) return FREEWRL_THREAD_DISPLAY; if (pthread_equal(current_thread, tg->threads.PCthread)) return FREEWRL_THREAD_PARSER; if (pthread_equal(current_thread, tg->threads.loadThread)) return FREEWRL_THREAD_TEXTURE; /*#endif*/ return -1; } #ifdef FREEWRL_THREAD_COLORIZED int fw_thread_color(int thread_id) { /* id will range from 1 to 5 */ if ((thread_id > 0) && (thread_id <= FREEWRL_MAX_THREADS)) { return threads_colors[ thread_id - 1 ]; } return FREEWRL_DEFAULT_COLOR; } #endif /* FREEWRL_THREAD_COLORIZED */ void fwl_thread_dump() { if (gglobal()->internalc.global_trace_threads) { /* Synchronize trace/error log... */ fflush(stdout); fflush(stderr); TRACE_MSG("FreeWRL CURRENT THREAD: %d\n", fw_thread_id()); } } void trace_enter_thread(const char *str) { int nloops = 0; ttglobal tg = gglobal0(); // get the value if we can while(tg == NULL){ usleep(50); tg = gglobal0(); //<< new function ttglobal0() just returns NULL if thread not registered yet nloops++; } //printf("trace_enter_thread spent %d loops\n",nloops); if (gglobal()->internalc.global_trace_threads) { /* Synchronize trace/error log... */ fflush(stdout); fflush(stderr); sync(); #ifdef _MSC_VER TRACE_MSG("*** ENTERING THREAD: %s, ID=%d self=%p\n", str, fw_thread_id(), (void*) pthread_self().p); #else TRACE_MSG("*** ENTERING THREAD: %s, ID=%d self=%p\n", str, fw_thread_id(), (void*) pthread_self()); #endif } }
/* * var_serviceTable(): * Handle this table separately from the scalar value case. * The workings of this are basically the same as for var_cyrusMasterMIB above. */ unsigned char * var_serviceTable(struct variable *vp, oid *name, size_t *length, int exact, size_t *var_len, WriteMethod **write_method) { /* variables we may use later */ static long long_ret; static char string[SPRINT_MAX_LEN]; /* static oid objid[MAX_OID_LEN]; */ /* static struct counter64 c64; */ int index; /* * This assumes that the table is a 'simple' table. * See the implementation documentation for the meaning of this. * You will need to provide the correct value for the TABLE_SIZE parameter * * If this table does not meet the requirements for a simple table, * you will need to provide the replacement code yourself. * Mib2c is not smart enough to write this for you. * Again, see the implementation documentation for what is required. */ if (header_simple_table(vp,name,length,exact,var_len,write_method, nservices) == MATCH_FAILED ) return NULL; index = name[*length - 1]; /* * this is where we do the value assignments for the mib results. */ switch(vp->magic) { case SERVICEFORKS: long_ret = Services[index - 1].nforks; return (unsigned char *) &long_ret; case SERVICEACTIVE: long_ret = Services[index - 1].nactive; return (unsigned char *) &long_ret; case SERVICENAME: if (Services[index - 1].name != NULL) { strlcpy(string, Services[index - 1].name, sizeof(string)); if (Services[index - 1].family == AF_INET6) { strlcat(string, "[v6]", sizeof(string)); } } else { strlcpy(string, "", sizeof(string)); } *var_len = strlen(string); return (unsigned char *) string; case SERVICEID: long_ret = index; return (unsigned char *) &long_ret; case SERVICECONNS: long_ret = Services[index - 1].nconnections; return (unsigned char *) &long_ret; default: ERROR_MSG(""); } return NULL; }
//------------------------------------------------------------------------------------- bool ClientObject::initLoginBaseapp() { Bots::getSingleton().networkInterface().dispatcher().deregisterReadFileDescriptor(*pTCPPacketReceiverEx_->pEndPoint()); pServerChannel_->stopSend(); pServerChannel_->pPacketSender(NULL); SAFE_RELEASE(pTCPPacketSenderEx_); SAFE_RELEASE(pTCPPacketReceiverEx_); Network::EndPoint* pEndpoint = Network::EndPoint::createPoolObject(); pEndpoint->socket(SOCK_STREAM); if (!pEndpoint->good()) { ERROR_MSG("ClientObject::initLogin: couldn't create a socket\n"); Network::EndPoint::reclaimPoolObject(pEndpoint); error_ = C_ERROR_INIT_NETWORK_FAILED; return false; } u_int32_t address; Network::Address::string2ip(ip_.c_str(), address); if(pEndpoint->connect(htons(port_), address) == -1) { ERROR_MSG(fmt::format("ClientObject::initLogin({}): connect server is error({})!\n", kbe_strerror(), name_)); Network::EndPoint::reclaimPoolObject(pEndpoint); // error_ = C_ERROR_INIT_NETWORK_FAILED; state_ = C_STATE_LOGIN_BASEAPP_CREATE; return false; } Network::Address addr(ip_.c_str(), port_); pEndpoint->addr(addr); pServerChannel_->pEndPoint(pEndpoint); pEndpoint->setnonblocking(true); pEndpoint->setnodelay(true); pTCPPacketSenderEx_ = new Network::TCPPacketSenderEx(*pEndpoint, this->networkInterface_, this); pTCPPacketReceiverEx_ = new Network::TCPPacketReceiverEx(*pEndpoint, this->networkInterface_, this); Bots::getSingleton().networkInterface().dispatcher().registerReadFileDescriptor((*pEndpoint), pTCPPacketReceiverEx_); //²»ÔÚÕâÀï×¢²á //Bots::getSingleton().networkInterface().dispatcher().registerWriteFileDescriptor((*pEndpoint), pTCPPacketSenderEx_); pServerChannel_->pPacketSender(pTCPPacketSenderEx_); connectedBaseapp_ = true; Network::Bundle* pBundle = Network::Bundle::createPoolObject(); (*pBundle).newMessage(BaseappInterface::hello); (*pBundle) << KBEVersion::versionString() << KBEVersion::scriptVersionString(); if(Network::g_channelExternalEncryptType == 1) { pBlowfishFilter_ = new Network::BlowfishFilter(); (*pBundle).appendBlob(pBlowfishFilter_->key()); pServerChannel_->pFilter(NULL); } else { std::string key = ""; (*pBundle).appendBlob(key); } pEndpoint->send(pBundle); Network::Bundle::reclaimPoolObject(pBundle); return true; }
static Bool create_buffer(DrawablePtr pDraw, struct ARMSOCDRI2BufferRec *buf) { ScreenPtr pScreen = pDraw->pScreen; ScrnInfoPtr pScrn = xf86ScreenToScrn(pScreen); struct ARMSOCRec *pARMSOC = ARMSOCPTR(pScrn); DRI2BufferPtr buffer = DRIBUF(buf); PixmapPtr pPixmap = NULL; struct armsoc_bo *bo; int ret; if (buffer->attachment == DRI2BufferFrontLeft) { pPixmap = draw2pix(pDraw); pPixmap->refcnt++; } else { pPixmap = createpix(pDraw); } if (!pPixmap) { assert(buffer->attachment != DRI2BufferFrontLeft); ERROR_MSG("Failed to create back buffer for window"); goto fail; } if (buffer->attachment == DRI2BufferBackLeft && pARMSOC->driNumBufs > 2) { buf->pPixmaps = calloc(pARMSOC->driNumBufs-1, sizeof(PixmapPtr)); buf->numPixmaps = pARMSOC->driNumBufs-1; } else { buf->pPixmaps = malloc(sizeof(PixmapPtr)); buf->numPixmaps = 1; } if (!buf->pPixmaps) { ERROR_MSG("Failed to allocate PixmapPtr array for DRI2Buffer"); goto fail; } buf->pPixmaps[0] = pPixmap; assert(buf->currentPixmap == 0); bo = ARMSOCPixmapBo(pPixmap); if (!bo) { ERROR_MSG( "Attempting to DRI2 wrap a pixmap with no DRM buffer object backing"); goto fail; } DRIBUF(buf)->pitch = exaGetPixmapPitch(pPixmap); DRIBUF(buf)->cpp = pPixmap->drawable.bitsPerPixel / 8; DRIBUF(buf)->flags = 0; buf->refcnt = 1; buf->previous_canflip = canflip(pDraw); ret = armsoc_bo_get_name(bo, &DRIBUF(buf)->name); if (ret) { ERROR_MSG("could not get buffer name: %d", ret); goto fail; } if (canflip(pDraw) && buffer->attachment != DRI2BufferFrontLeft) { /* Create an fb around this buffer. This will fail and we will * fall back to blitting if the display controller hardware * cannot scan out this buffer (for example, if it doesn't * support the format or there was insufficient scanout memory * at buffer creation time). */ int ret = armsoc_bo_add_fb(bo); if (ret) { WARNING_MSG( "Falling back to blitting a flippable window"); } #if DRI2INFOREC_VERSION >= 6 else if (FALSE == DRI2SwapLimit(pDraw, pARMSOC->swap_chain_size)) { WARNING_MSG( "Failed to set DRI2SwapLimit(%x,%d)", (unsigned int)pDraw, pARMSOC->swap_chain_size); } #endif /* DRI2INFOREC_VERSION >= 6 */ } DRI2_BUFFER_SET_FB(DRIBUF(buf)->flags, armsoc_bo_get_fb(bo) > 0 ? 1 : 0); DRI2_BUFFER_SET_REUSED(DRIBUF(buf)->flags, 0); /* Register Pixmap as having a buffer that can be accessed externally, * so needs synchronised access */ ARMSOCRegisterExternalAccess(pPixmap); return TRUE; fail: if (pPixmap != NULL) { if (buffer->attachment != DRI2BufferFrontLeft) pScreen->DestroyPixmap(pPixmap); else pPixmap->refcnt--; } return FALSE; }
//------------------------------------------------------------------------------------- bool Config::loadConfig(std::string fileName) { fileName_ = fileName; TiXmlNode* rootNode = NULL; XmlPlus* xml = new XmlPlus(Resmgr::getSingleton().matchRes(fileName_).c_str()); if(!xml->isGood()) { ERROR_MSG(boost::format("Config::loadConfig: load %1% is failed!\n") % fileName.c_str()); SAFE_RELEASE(xml); return false; } rootNode = xml->getRootNode("packetAlwaysContainLength"); if(rootNode != NULL){ Mercury::g_packetAlwaysContainLength = xml->getValInt(rootNode) != 0; } rootNode = xml->getRootNode("trace_packet"); if(rootNode != NULL) { TiXmlNode* childnode = xml->enterNode(rootNode, "debug_type"); if(childnode) Mercury::g_trace_packet = xml->getValInt(childnode); if(Mercury::g_trace_packet > 3) Mercury::g_trace_packet = 0; childnode = xml->enterNode(rootNode, "use_logfile"); if(childnode) Mercury::g_trace_packet_use_logfile = (xml->getValStr(childnode) == "true"); childnode = xml->enterNode(rootNode, "disables"); if(childnode) { do { if(childnode->FirstChild() != NULL) { std::string c = childnode->FirstChild()->Value(); c = strutil::kbe_trim(c); if(c.size() > 0) { Mercury::g_trace_packet_disables.push_back(c); } } }while((childnode = childnode->NextSibling())); } } rootNode = xml->getRootNode("debugEntity"); if(rootNode != NULL) { g_debugEntity = xml->getValInt(rootNode) > 0; } rootNode = xml->getRootNode("publish"); if(rootNode != NULL) { TiXmlNode* childnode = xml->enterNode(rootNode, "state"); if(childnode) { g_appPublish = xml->getValInt(childnode); } childnode = xml->enterNode(rootNode, "script_version"); if(childnode) { KBEVersion::setScriptVersion(xml->getValStr(childnode)); } } rootNode = xml->getRootNode("channelCommon"); if(rootNode != NULL) { TiXmlNode* childnode = xml->enterNode(rootNode, "timeout"); if(childnode) { TiXmlNode* childnode1 = xml->enterNode(childnode, "internal"); if(childnode1) { channelInternalTimeout_ = KBE_MAX(1.f, float(xml->getValFloat(childnode1))); Mercury::g_channelInternalTimeout = channelInternalTimeout_; } childnode1 = xml->enterNode(childnode, "external"); if(childnode) { channelExternalTimeout_ = KBE_MAX(1.f, float(xml->getValFloat(childnode1))); Mercury::g_channelExternalTimeout = channelExternalTimeout_; } } childnode = xml->enterNode(rootNode, "resend"); if(childnode) { TiXmlNode* childnode1 = xml->enterNode(childnode, "internal"); if(childnode1) { TiXmlNode* childnode2 = xml->enterNode(childnode1, "interval"); if(childnode2) { Mercury::g_intReSendInterval = uint32(xml->getValInt(childnode2)); } childnode2 = xml->enterNode(childnode1, "retries"); if(childnode2) { Mercury::g_intReSendRetries = uint32(xml->getValInt(childnode2)); } } childnode1 = xml->enterNode(childnode, "external"); if(childnode) { TiXmlNode* childnode2 = xml->enterNode(childnode1, "interval"); if(childnode2) { Mercury::g_extReSendInterval = uint32(xml->getValInt(childnode2)); } childnode2 = xml->enterNode(childnode1, "retries"); if(childnode2) { Mercury::g_extReSendRetries = uint32(xml->getValInt(childnode2)); } } } childnode = xml->enterNode(rootNode, "receiveWindowOverflow"); if(childnode) { TiXmlNode* childnode1 = xml->enterNode(childnode, "messages"); if(childnode1) { childnode1 = xml->enterNode(childnode, "internal"); if(childnode1) Mercury::g_intReceiveWindowMessagesOverflow = KBE_MAX(16, xml->getValInt(childnode1)); childnode1 = xml->enterNode(childnode, "external"); if(childnode1) Mercury::g_extReceiveWindowMessagesOverflow = KBE_MAX(16, xml->getValInt(childnode1)); } childnode1 = xml->enterNode(childnode, "bytes"); if(childnode1) { childnode1 = xml->enterNode(childnode, "internal"); if(childnode1) Mercury::g_intReceiveWindowBytesOverflow = KBE_MAX(16, xml->getValInt(childnode1)); childnode1 = xml->enterNode(childnode, "external"); if(childnode1) Mercury::g_extReceiveWindowBytesOverflow = KBE_MAX(16, xml->getValInt(childnode1)); } }; childnode = xml->enterNode(rootNode, "encrypt_type"); if(childnode) { Mercury::g_channelExternalEncryptType = xml->getValInt(childnode); } } rootNode = xml->getRootNode("telnet_service"); if(rootNode != NULL) { TiXmlNode* childnode = xml->enterNode(rootNode, "port"); if(childnode) { telnet_port = xml->getValInt(childnode); } childnode = xml->enterNode(rootNode, "password"); if(childnode) { telnet_passwd = xml->getValStr(childnode); } childnode = xml->enterNode(rootNode, "default_layer"); if(childnode) { telnet_deflayer = xml->getValStr(childnode); } } rootNode = xml->getRootNode("gameUpdateHertz"); if(rootNode != NULL){ gameUpdateHertz_ = xml->getValInt(rootNode); } rootNode = xml->getRootNode("ip"); if(rootNode != NULL) { strcpy(ip_, xml->getValStr(rootNode).c_str()); } rootNode = xml->getRootNode("port"); if(rootNode != NULL){ port_ = xml->getValInt(rootNode); } rootNode = xml->getRootNode("entryScriptFile"); if(rootNode != NULL) { strcpy(entryScriptFile_, xml->getValStr(rootNode).c_str()); } rootNode = xml->getRootNode("accountName"); if(rootNode != NULL) { strcpy(accountName_, xml->getValStr(rootNode).c_str()); } rootNode = xml->getRootNode("useLastAccountName"); if(rootNode != NULL) { useLastAccountName_ = xml->getValStr(rootNode) != "false"; } rootNode = xml->getRootNode("encrypt_login"); if(rootNode != NULL) { encrypt_login_ = xml->getValInt(rootNode); } rootNode = xml->getRootNode("aliasEntityID"); if(rootNode != NULL) { EntityDef::entityAliasID((xml->getValStr(rootNode) == "true")); } rootNode = xml->getRootNode("entitydefAliasID"); if(rootNode != NULL){ EntityDef::entitydefAliasID((xml->getValStr(rootNode) == "true")); } SAFE_RELEASE(xml); return true; }
//------------------------------------------------------------------------------------- bool Machine::initNetwork() { epBroadcast_.socket(SOCK_DGRAM); ep_.socket(SOCK_DGRAM); epLocal_.socket(SOCK_DGRAM); Mercury::Address address; address.ip = 0; address.port = 0; if (broadcastAddr_ == 0 && !this->findBroadcastInterface()) { ERROR_MSG("Machine::initNetwork: Failed to determine default broadcast interface. " "Make sure that your broadcast route is set correctly. " "e.g. /sbin/ip route add broadcast 255.255.255.255 dev eth0\n" ); return false; } if (!ep_.good() || ep_.bind(htons(KBE_MACHINE_BRAODCAST_SEND_PORT), broadcastAddr_) == -1) { ERROR_MSG("Machine::initNetwork: Failed to bind socket to '%s:%d'. %s.\n", inet_ntoa((struct in_addr &)broadcastAddr_), KBE_MACHINE_BRAODCAST_SEND_PORT, kbe_strerror()); return false; } address.ip = broadcastAddr_; address.port = htons(KBE_MACHINE_BRAODCAST_SEND_PORT); ep_.setbroadcast( true ); ep_.setnonblocking(true); ep_.addr(address); pEPPacketReceiver_ = new Mercury::UDPPacketReceiver(ep_, this->getNetworkInterface()); if(!this->getMainDispatcher().registerFileDescriptor(ep_, pEPPacketReceiver_)) { ERROR_MSG("Machine::initNetwork: registerFileDescriptor ep is failed!\n"); return false; } #if KBE_PLATFORM == PLATFORM_WIN32 u_int32_t baddr = htonl(INADDR_ANY); #else u_int32_t baddr = Mercury::BROADCAST; #endif if (!epBroadcast_.good() || epBroadcast_.bind(htons(KBE_MACHINE_BRAODCAST_SEND_PORT), baddr) == -1) { ERROR_MSG("Machine::initNetwork: Failed to bind socket to '%s:%d'. %s.\n", inet_ntoa((struct in_addr &)baddr), KBE_MACHINE_BRAODCAST_SEND_PORT, kbe_strerror()); #if KBE_PLATFORM != PLATFORM_WIN32 return false; #endif } else { address.ip = baddr; address.port = htons(KBE_MACHINE_BRAODCAST_SEND_PORT); epBroadcast_.setnonblocking(true); epBroadcast_.addr(address); pEBPacketReceiver_ = new Mercury::UDPPacketReceiver(epBroadcast_, this->getNetworkInterface()); if(!this->getMainDispatcher().registerFileDescriptor(epBroadcast_, pEBPacketReceiver_)) { ERROR_MSG("Machine::initNetwork: registerFileDescriptor epBroadcast is failed!\n"); return false; } } if (!epLocal_.good() || epLocal_.bind(htons(KBE_MACHINE_BRAODCAST_SEND_PORT), Mercury::LOCALHOST) == -1) { ERROR_MSG("Machine::initNetwork: Failed to bind socket to (lo). %s.\n", kbe_strerror() ); return false; } address.ip = Mercury::LOCALHOST; address.port = htons(KBE_MACHINE_BRAODCAST_SEND_PORT); epLocal_.setnonblocking(true); epLocal_.addr(address); pEPLocalPacketReceiver_ = new Mercury::UDPPacketReceiver(epLocal_, this->getNetworkInterface()); if(!this->getMainDispatcher().registerFileDescriptor(epLocal_, pEPLocalPacketReceiver_)) { ERROR_MSG("Machine::initNetwork: registerFileDescriptor epLocal is failed!\n"); return false; } INFO_MSG("Machine::initNetwork: bind broadcast successfully! addr:%s\n", ep_.addr().c_str()); return true; }
//------------------------------------------------------------------------------------- bool KBEAccountTableMysql::logAccount(DBInterface * dbi, ACCOUNT_INFOS& info) { std::string sqlstr = "insert into kbe_accountinfos (accountName, password, bindata, email, entityDBID, flags, deadline, regtime, lasttime) values("; char* tbuf = new char[MAX_BUF > info.datas.size() ? MAX_BUF * 3 : info.datas.size() * 3]; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, info.name.c_str(), info.name.size()); sqlstr += "\""; sqlstr += tbuf; sqlstr += "\","; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, info.password.c_str(), info.password.size()); sqlstr += "md5(\""; sqlstr += tbuf; sqlstr += "\"),"; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, info.datas.data(), info.datas.size()); sqlstr += "\""; sqlstr += tbuf; sqlstr += "\","; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, info.email.c_str(), info.email.size()); sqlstr += "\""; sqlstr += tbuf; sqlstr += "\","; kbe_snprintf(tbuf, MAX_BUF, "%"PRDBID, info.dbid); sqlstr += tbuf; sqlstr += ","; kbe_snprintf(tbuf, MAX_BUF, "%u", info.flags); sqlstr += tbuf; sqlstr += ","; kbe_snprintf(tbuf, MAX_BUF, "%"PRIu64, info.deadline); sqlstr += tbuf; sqlstr += ","; kbe_snprintf(tbuf, MAX_BUF, "%"PRTime, time(NULL)); sqlstr += tbuf; sqlstr += ","; kbe_snprintf(tbuf, MAX_BUF, "%"PRTime, time(NULL)); sqlstr += tbuf; sqlstr += ")"; SAFE_RELEASE_ARRAY(tbuf); // 如果查询失败则返回存在, 避免可能产生的错误 if(!dbi->query(sqlstr.c_str(), sqlstr.size(), false)) { ERROR_MSG(fmt::format("KBEAccountTableMysql::logAccount({}): sql({}) is failed({})!\n", info.name, sqlstr, dbi->getstrerror())); return false; } return true; }
//------------------------------------------------------------------------------------- void Machine::stopserver(Mercury::Channel* pChannel, KBEngine::MemoryStream& s) { int32 uid = 0; COMPONENT_TYPE componentType; uint32 recvip; uint16 recvport; Mercury::Bundle bundle; bool success = true; s >> uid; s >> componentType; s >> recvip; s >> recvport; Mercury::EndPoint ep; ep.socket(SOCK_DGRAM); if (!ep.good()) { ERROR_MSG("Machine::stopserver: Failed to create socket.\n"); return; } Components::COMPONENTS& components = Componentbridge::getComponents().getComponents(componentType); Components::COMPONENTS::iterator iter = components.begin(); Components::ComponentInfos* cinfos = NULL; for(; iter != components.end(); ) { if((*iter).uid != uid) continue; if(componentType != (*iter).componentType) { continue; } bool usable = Componentbridge::getComponents().checkComponentUsable(&(*iter)); if(!usable) { success = true; break; } cinfos = &(*iter); Mercury::Bundle closebundle; COMMON_MERCURY_MESSAGE(componentType, closebundle, reqCloseServer); Mercury::EndPoint ep1; ep1.socket(SOCK_STREAM); if (!ep1.good()) { ERROR_MSG("Machine::stopserver: Failed to create socket.\n"); success = false; break; } if(ep1.connect((*iter).pIntAddr.get()->port, (*iter).pIntAddr.get()->ip) == -1) { ERROR_MSG("Machine::stopserver: connect server is error(%s)!\n", kbe_strerror()); success = false; break; } closebundle.send(ep1); Mercury::TCPPacket recvpacket; recvpacket.resize(255); int len = ep1.recv(recvpacket.data(), 1); if(len != 1) { success = false; break; } recvpacket >> success; break; } bundle << success; bundle.sendto(ep, recvport, recvip); }
//------------------------------------------------------------------------------------- bool KBEEmailVerificationTableMysql::activateAccount(DBInterface * dbi, const std::string& code, ACCOUNT_INFOS& info) { std::string sqlstr = "select accountName, datas, logtime from kbe_email_verification where code like \""; char* tbuf = new char[code.size() * 2 + 1]; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, code.c_str(), code.size()); sqlstr += tbuf; sqlstr += "\" and type="; kbe_snprintf(tbuf, MAX_BUF, "%d", (int)KBEEmailVerificationTable::V_TYPE_CREATEACCOUNT); sqlstr += tbuf; SAFE_RELEASE_ARRAY(tbuf); if(!dbi->query(sqlstr.c_str(), sqlstr.size(), false)) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::activateAccount({}): sql({}) is failed({})!\n", code, sqlstr, dbi->getstrerror())); return false; } uint64 logtime = 1; MYSQL_RES * pResult = mysql_store_result(static_cast<DBInterfaceMysql*>(dbi)->mysql()); if(pResult) { MYSQL_ROW arow; while((arow = mysql_fetch_row(pResult)) != NULL) { info.name = arow[0]; info.password = arow[1]; KBEngine::StringConv::str2value(logtime, arow[2]); } mysql_free_result(pResult); } if(logtime > 0 && time(NULL) - logtime > g_kbeSrvConfig.emailAtivationInfo_.deadline) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::activateAccount({}): is expired! {} > {}.\n", code, (time(NULL) - logtime), g_kbeSrvConfig.emailAtivationInfo_.deadline)); return false; } if(info.name.size() == 0) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::activateAccount({}): name is NULL.\n", code)); return false; } std::string password = info.password; // 寻找dblog是否有此账号 KBEAccountTable* pTable = static_cast<KBEAccountTable*>(EntityTables::getSingleton().findKBETable("kbe_accountinfos")); KBE_ASSERT(pTable); info.flags = 0; if(!pTable->queryAccount(dbi, info.name, info)) { return false; } if((info.flags & ACCOUNT_FLAG_NOT_ACTIVATED) <= 0) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::activateAccount({}): Has been activated, flags={}.\n", code, info.flags)); return false; } info.flags &= ~ACCOUNT_FLAG_NOT_ACTIVATED; if(!pTable->setFlagsDeadline(dbi, info.name, info.flags, info.deadline)) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::activateAccount({}): set deadline is error({})!\n", code, dbi->getstrerror())); return false; } if(!pTable->updatePassword(dbi, info.name, password)) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::activateAccount({}): update password is error({})!\n", code, dbi->getstrerror())); return false; } info.dbid = 0; ScriptDefModule* pModule = EntityDef::findScriptModule(DBUtil::accountScriptName()); // 防止多线程问题, 这里做一个拷贝。 MemoryStream copyAccountDefMemoryStream(pTable->accountDefMemoryStream()); info.dbid = EntityTables::getSingleton().writeEntity(dbi, 0, -1, ©AccountDefMemoryStream, pModule); KBE_ASSERT(info.dbid > 0); // 如果查询失败则返回存在, 避免可能产生的错误 tbuf = new char[MAX_BUF * 3]; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, info.name.c_str(), info.name.size()); if(!dbi->query(fmt::format("update kbe_accountinfos set entityDBID={} where accountName like \"{}\"", info.dbid, tbuf), false)) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::activateAccount({}): update kbe_accountinfos is error({})!\n", code, dbi->getstrerror())); SAFE_RELEASE_ARRAY(tbuf); return false; } SAFE_RELEASE_ARRAY(tbuf); try { delAccount(dbi, (int8)V_TYPE_CREATEACCOUNT, info.name); } catch (...) { } return true; }
//------------------------------------------------------------------------------------- int Components::connectComponent(COMPONENT_TYPE componentType, int32 uid, COMPONENT_ID componentID) { Components::ComponentInfos* pComponentInfos = findComponent(componentType, uid, componentID); KBE_ASSERT(pComponentInfos != NULL); Network::EndPoint * pEndpoint = Network::EndPoint::ObjPool().createObject(); pEndpoint->socket(SOCK_STREAM); if (!pEndpoint->good()) { ERROR_MSG("Components::connectComponent: couldn't create a socket\n"); Network::EndPoint::ObjPool().reclaimObject(pEndpoint); return -1; } pEndpoint->addr(*pComponentInfos->pIntAddr); int ret = pEndpoint->connect(pComponentInfos->pIntAddr->port, pComponentInfos->pIntAddr->ip); if(ret == 0) { Network::Channel* pChannel = Network::Channel::ObjPool().createObject(); bool ret = pChannel->initialize(*_pNetworkInterface, pEndpoint, Network::Channel::INTERNAL); if(!ret) { ERROR_MSG(fmt::format("Components::connectComponent: initialize({}) is failed!\n", pChannel->c_str())); pChannel->destroy(); Network::Channel::ObjPool().reclaimObject(pChannel); return -1; } pComponentInfos->pChannel = pChannel; pComponentInfos->pChannel->componentID(componentID); if(!_pNetworkInterface->registerChannel(pComponentInfos->pChannel)) { ERROR_MSG(fmt::format("Components::connectComponent: registerChannel({}) is failed!\n", pComponentInfos->pChannel->c_str())); pComponentInfos->pChannel->destroy(); Network::Channel::ObjPool().reclaimObject(pComponentInfos->pChannel); // 此时不可强制释放内存,destroy中已经对其减引用 // SAFE_RELEASE(pComponentInfos->pChannel); pComponentInfos->pChannel = NULL; return -1; } else { Network::Bundle* pBundle = Network::Bundle::ObjPool().createObject(); if(componentType == BASEAPPMGR_TYPE) { (*pBundle).newMessage(BaseappmgrInterface::onRegisterNewApp); BaseappmgrInterface::onRegisterNewAppArgs11::staticAddToBundle((*pBundle), getUserUID(), getUsername(), componentType_, componentID_, g_componentGlobalOrder, g_componentGroupOrder, _pNetworkInterface->intaddr().ip, _pNetworkInterface->intaddr().port, _pNetworkInterface->extaddr().ip, _pNetworkInterface->extaddr().port, g_kbeSrvConfig.getConfig().externalAddress); } else if(componentType == CELLAPPMGR_TYPE) { (*pBundle).newMessage(CellappmgrInterface::onRegisterNewApp); CellappmgrInterface::onRegisterNewAppArgs11::staticAddToBundle((*pBundle), getUserUID(), getUsername(), componentType_, componentID_, g_componentGlobalOrder, g_componentGroupOrder, _pNetworkInterface->intaddr().ip, _pNetworkInterface->intaddr().port, _pNetworkInterface->extaddr().ip, _pNetworkInterface->extaddr().port, g_kbeSrvConfig.getConfig().externalAddress); } else if(componentType == CELLAPP_TYPE) { (*pBundle).newMessage(CellappInterface::onRegisterNewApp); CellappInterface::onRegisterNewAppArgs11::staticAddToBundle((*pBundle), getUserUID(), getUsername(), componentType_, componentID_, g_componentGlobalOrder, g_componentGroupOrder, _pNetworkInterface->intaddr().ip, _pNetworkInterface->intaddr().port, _pNetworkInterface->extaddr().ip, _pNetworkInterface->extaddr().port, g_kbeSrvConfig.getConfig().externalAddress); } else if(componentType == BASEAPP_TYPE) { (*pBundle).newMessage(BaseappInterface::onRegisterNewApp); BaseappInterface::onRegisterNewAppArgs11::staticAddToBundle((*pBundle), getUserUID(), getUsername(), componentType_, componentID_, g_componentGlobalOrder, g_componentGroupOrder, _pNetworkInterface->intaddr().ip, _pNetworkInterface->intaddr().port, _pNetworkInterface->extaddr().ip, _pNetworkInterface->extaddr().port, g_kbeSrvConfig.getConfig().externalAddress); } else if(componentType == DBMGR_TYPE) { (*pBundle).newMessage(DbmgrInterface::onRegisterNewApp); DbmgrInterface::onRegisterNewAppArgs11::staticAddToBundle((*pBundle), getUserUID(), getUsername(), componentType_, componentID_, g_componentGlobalOrder, g_componentGroupOrder, _pNetworkInterface->intaddr().ip, _pNetworkInterface->intaddr().port, _pNetworkInterface->extaddr().ip, _pNetworkInterface->extaddr().port, g_kbeSrvConfig.getConfig().externalAddress); } else if(componentType == LOGGER_TYPE) { (*pBundle).newMessage(LoggerInterface::onRegisterNewApp); LoggerInterface::onRegisterNewAppArgs11::staticAddToBundle((*pBundle), getUserUID(), getUsername(), componentType_, componentID_, g_componentGlobalOrder, g_componentGroupOrder, _pNetworkInterface->intaddr().ip, _pNetworkInterface->intaddr().port, _pNetworkInterface->extaddr().ip, _pNetworkInterface->extaddr().port, g_kbeSrvConfig.getConfig().externalAddress); } else { KBE_ASSERT(false && "invalid componentType.\n"); } pComponentInfos->pChannel->send(pBundle); } } else { ERROR_MSG(fmt::format("Components::connectComponent: connect({}) is failed! {}.\n", pComponentInfos->pIntAddr->c_str(), kbe_strerror())); Network::EndPoint::ObjPool().reclaimObject(pEndpoint); return -1; } return ret; }
//------------------------------------------------------------------------------------- bool KBEEmailVerificationTableMysql::bindEMail(DBInterface * dbi, const std::string& name, const std::string& code) { std::string sqlstr = "select accountName, datas, logtime from kbe_email_verification where code like \""; char* tbuf = new char[code.size() * 2 + 1]; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, code.c_str(), code.size()); sqlstr += tbuf; sqlstr += "\" and type="; kbe_snprintf(tbuf, MAX_BUF, "%d", (int)KBEEmailVerificationTable::V_TYPE_BIND_MAIL); sqlstr += tbuf; SAFE_RELEASE_ARRAY(tbuf); if(!dbi->query(sqlstr.c_str(), sqlstr.size(), false)) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::bindEMail({}): sql({}) is failed({})!\n", code, sqlstr, dbi->getstrerror())); return false; } uint64 logtime = 1; std::string qname, qemail; MYSQL_RES * pResult = mysql_store_result(static_cast<DBInterfaceMysql*>(dbi)->mysql()); if(pResult) { MYSQL_ROW arow; while((arow = mysql_fetch_row(pResult)) != NULL) { qname = arow[0]; qemail = arow[1]; KBEngine::StringConv::str2value(logtime, arow[2]); } mysql_free_result(pResult); } if(logtime > 0 && time(NULL) - logtime > g_kbeSrvConfig.emailBindInfo_.deadline) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::bindEMail({}): is expired! {} > {}.\n", code, (time(NULL) - logtime), g_kbeSrvConfig.emailBindInfo_.deadline)); return false; } if(qname.size() == 0 || qemail.size() == 0) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::bindEMail({}): name or email is NULL.\n", code)); return false; } if(qname != name) { WARNING_MSG(fmt::format("KBEEmailVerificationTableMysql::bindEMail: code({}) username({}, {}) not match.\n" , code, name, qname)); return false; } tbuf = new char[code.size() * 2 + 1]; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, qemail.c_str(), qemail.size()); sqlstr = "update kbe_accountinfos set email=\""; sqlstr += tbuf; sqlstr += "\" where accountName like \""; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, name.c_str(), name.size()); sqlstr += tbuf; sqlstr += "\""; SAFE_RELEASE_ARRAY(tbuf); if(!dbi->query(sqlstr, false)) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::bindEMail({}): update kbe_accountinfos is error({})!\n", code, dbi->getstrerror())); return false; } try { delAccount(dbi, (int8)V_TYPE_BIND_MAIL, name); } catch (...) { } return true; }
int render_init(void) { IF_FAILED0(!init); if(!init_opengl) { ERROR_MSG("OpenGL not initialised\n"); return 0; } log_init(); TRACE_MSG("init base render system\n"); TRACE_MSG("init noise\n"); noise_init(); glViewport(0, 0, window_width, window_height); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glEnable(GL_DEPTH_TEST); glClearDepth(1.0f); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_CLAMP); DEBUG_MSG("OpenGL version: %s\n", glGetString(GL_VERSION)); DEBUG_MSG("GLSL version: %s\n", (char*) glGetString(GL_SHADING_LANGUAGE_VERSION)); // настраиваем основную камеру TRACE_MSG("init main camera\n"); camera_init(&camera, vec3f(0.0f, 0.0f, 0.5f), vec3f(0.0f, 1.0f, 0.0f), vec3f(0.0f, 0.0f, -1.0f)); camera_set_limit(&camera, -95.0f, 95.0f, -360.0f, 360.0f); camera_set_fov(&camera, camera_fov); camera_set_move_velocity(&camera, camera_move_speed); camera_set_rotate_velocity(&camera, camera_rotate_speed); camera_set_aspect(&camera, (float) window_width / (float) window_height); camera_set_zplanes(&camera, 0.001f, 1000.0f); camera_update(&camera, 0.0); isolevel = 30.0f; isolevel_animate = 0; // устанавливаем функцию по-умолчанию parser_create(&parser); const char *default_func = "d = y;"; str_function = (char*) malloc(sizeof(char) * (strlen(default_func) + 1)); strcpy(str_function, default_func); // настраиваем и создаем скалярное поле render_set_volume_size(vec3ui(128, 128, 128), 1); render_set_grid_size(vec3ui(64, 64, 64)); render_update_volume_tex(); CHECK_GL_ERRORS(); // инициализируем шейдер if(!init_shader()) return 0; // инициализируем буферы с данными init_buffers(); // устанавливаем параметры по-умолчанию new_light_position = light_position = vec3f(1.0f, 1.0f, 1.0f); rot_axis = vec3f(0.0f, 1.0f, 0.0f); num_threads = 1; rot_angle = 0.0f; light_animate = 0; light_rot_angle = 0.0f; mat4(rotmat, 1.0f); mat4(modelmat, 1.0f); material_front_color = vec3f(0.5f, 0.5f, 0.5f); material_back_color = vec3f(0.5f, 0.0f, 0.0f); light_color = vec3f(1.0f, 1.0f, 1.0f); light_spec_color = vec3f(1.0f, 1.0f, 1.0f); input_set_wheel_limits(20, 150); init = 1; // полигонизируем ск. п. render_update_mc(); // обновляем рендер render_update(0.0f); return 1; }
//------------------------------------------------------------------------------------- bool KBEEmailVerificationTableMysql::resetpassword(DBInterface * dbi, const std::string& name, const std::string& password, const std::string& code) { std::string sqlstr = "select accountName, logtime from kbe_email_verification where code like \""; char* tbuf = new char[code.size() * 2 + 1]; mysql_real_escape_string(static_cast<DBInterfaceMysql*>(dbi)->mysql(), tbuf, code.c_str(), code.size()); sqlstr += tbuf; sqlstr += "\" and type="; kbe_snprintf(tbuf, MAX_BUF, "%d", (int)KBEEmailVerificationTable::V_TYPE_RESETPASSWORD); sqlstr += tbuf; SAFE_RELEASE_ARRAY(tbuf); if(!dbi->query(sqlstr.c_str(), sqlstr.size(), false)) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::resetpassword({}): sql({}) is failed({})!\n", code, sqlstr, dbi->getstrerror())); return false; } uint64 logtime = 1; std::string qname; MYSQL_RES * pResult = mysql_store_result(static_cast<DBInterfaceMysql*>(dbi)->mysql()); if(pResult) { MYSQL_ROW arow; while((arow = mysql_fetch_row(pResult)) != NULL) { qname = arow[0]; KBEngine::StringConv::str2value(logtime, arow[1]); } mysql_free_result(pResult); } if(logtime > 0 && time(NULL) - logtime > g_kbeSrvConfig.emailResetPasswordInfo_.deadline) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::bindEMail({}): is expired! {} > {}.\n", code, (time(NULL) - logtime), g_kbeSrvConfig.emailResetPasswordInfo_.deadline)); return false; } if(qname.size() == 0 || password.size() == 0) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::resetpassword({}): name or password is NULL.\n", code)); return false; } if(qname != name) { WARNING_MSG(fmt::format("KBEEmailVerificationTableMysql::resetpassword: code({}) username({}, {}) not match.\n" , code, name, qname)); return false; } // 寻找dblog是否有此账号 KBEAccountTable* pTable = static_cast<KBEAccountTable*>(EntityTables::getSingleton().findKBETable("kbe_accountinfos")); KBE_ASSERT(pTable); if(!pTable->updatePassword(dbi, name, KBE_MD5::getDigest(password.data(), password.length()))) { ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::resetpassword({}): update password is error({})!\n", code, dbi->getstrerror())); return false; } try { delAccount(dbi, (int8)V_TYPE_RESETPASSWORD, name); } catch (...) { } return true; }
/** * Create Buffer. * * Note that 'format' is used from the client side to specify the DRI buffer * format, which could differ from the drawable format. For example, the * drawable could be 32b RGB, but the DRI buffer some YUV format (video) or * perhaps lower bit depth RGB (GL). The color conversion is handled when * blitting to front buffer, and page-flipping (overlay or flipchain) can * only be used if the display supports. */ static DRI2BufferPtr ARMSOCDRI2CreateBuffer(DrawablePtr pDraw, unsigned int attachment, unsigned int format) { ScreenPtr pScreen = pDraw->pScreen; ScrnInfoPtr pScrn = xf86ScreenToScrn(pScreen); struct ARMSOCDRI2BufferRec *buf = calloc(1, sizeof(*buf)); struct ARMSOCRec *pARMSOC = ARMSOCPTR(pScrn); struct armsoc_bo *bo; DEBUG_MSG("pDraw=%p, attachment=%d, format=%08x", pDraw, attachment, format); if (!buf) { ERROR_MSG("Couldn't allocate internal buffer structure"); return NULL; } buf->refcnt = 1; buf->previous_canflip = canflip(pDraw); DRIBUF(buf)->attachment = attachment; DRIBUF(buf)->cpp = pDraw->bitsPerPixel / 8; DRIBUF(buf)->format = format + 1; /* suppress DRI2 buffer reuse */ DRIBUF(buf)->flags = 0; /* If it is a pixmap, just migrate to a GEM buffer */ if (pDraw->type == DRAWABLE_PIXMAP) { if (!(bo = MigratePixmapToGEM(pARMSOC, pDraw))) { ErrorF("ARMSOCDRI2CreateBuffer: MigratePixmapToUMP failed\n"); free(buf); return NULL; } DRIBUF(buf)->pitch = armsoc_bo_pitch(bo); DRIBUF(buf)->name = armsoc_bo_name(bo); buf->bo = bo; return DRIBUF(buf); } /* We are not interested in anything other than back buffer requests ... */ if (attachment != DRI2BufferBackLeft || pDraw->type != DRAWABLE_WINDOW) { /* ... and just return some dummy UMP buffer */ bo = pARMSOC->scanout; DRIBUF(buf)->pitch = armsoc_bo_pitch(bo); DRIBUF(buf)->name = armsoc_bo_name(bo); buf->bo = bo; armsoc_bo_reference(bo); return DRIBUF(buf); } bo = armsoc_bo_from_drawable(pDraw); if (bo && armsoc_bo_width(bo) == pDraw->width && armsoc_bo_height(bo) == pDraw->height && armsoc_bo_bpp(bo) == pDraw->bitsPerPixel) { // Reuse existing DRIBUF(buf)->pitch = armsoc_bo_pitch(bo); DRIBUF(buf)->name = armsoc_bo_name(bo); buf->bo = bo; armsoc_bo_reference(bo); return DRIBUF(buf); } bo = armsoc_bo_new_with_dim(pARMSOC->dev, pDraw->width, pDraw->height, pDraw->depth, pDraw->bitsPerPixel, canflip(pDraw) ? ARMSOC_BO_SCANOUT : ARMSOC_BO_NON_SCANOUT); if (!bo) { ErrorF("ARMSOCDRI2CreateBuffer: BO alloc failed\n"); free(buf); return NULL; } armsoc_bo_set_drawable(bo, pDraw); DRIBUF(buf)->name = armsoc_bo_name(bo); DRIBUF(buf)->pitch = armsoc_bo_pitch(bo); buf->bo = bo; if (canflip(pDraw) && attachment != DRI2BufferFrontLeft) { /* Create an fb around this buffer. This will fail and we will * fall back to blitting if the display controller hardware * cannot scan out this buffer (for example, if it doesn't * support the format or there was insufficient scanout memory * at buffer creation time). */ int ret = armsoc_bo_add_fb(bo); if (ret) { WARNING_MSG( "Falling back to blitting a flippable window"); } } /* Register Pixmap as having a buffer that can be accessed externally, * so needs synchronised access */ // FIXME ARMSOCRegisterExternalAccess(pPixmap); return DRIBUF(buf); }
/* * var_traceRouteResultsTable(): * Handle this table separately from the scalar value case. * The workings of this are basically the same as for var_traceRouteResultsTable above. */ unsigned char * var_traceRouteResultsTable(struct variable *vp, oid * name, size_t *length, int exact, size_t *var_len, WriteMethod ** write_method) { struct traceRouteResultsTable_data *StorageTmp = NULL; *write_method = NULL; /* * this assumes you have registered all your data properly */ if ((StorageTmp = header_complex(traceRouteResultsTableStorage, vp, name, length, exact, var_len, write_method)) == NULL) { return NULL; } /* * this is where we do the value assignments for the mib results. */ switch (vp->magic) { case COLUMN_TRACEROUTERESULTSOPERSTATUS: *var_len = sizeof(StorageTmp->traceRouteResultsOperStatus); return (u_char *) & StorageTmp->traceRouteResultsOperStatus; case COLUMN_TRACEROUTERESULTSCURHOPCOUNT: *var_len = sizeof(StorageTmp->traceRouteResultsCurHopCount); return (u_char *) & StorageTmp->traceRouteResultsCurHopCount; case COLUMN_TRACEROUTERESULTSCURPROBECOUNT: *var_len = sizeof(StorageTmp->traceRouteResultsCurProbeCount); return (u_char *) & StorageTmp->traceRouteResultsCurProbeCount; case COLUMN_TRACEROUTERESULTSIPTGTADDRTYPE: *var_len = sizeof(StorageTmp->traceRouteResultsIpTgtAddrType); return (u_char *) & StorageTmp->traceRouteResultsIpTgtAddrType; case COLUMN_TRACEROUTERESULTSIPTGTADDR: *var_len = (StorageTmp->traceRouteResultsIpTgtAddrLen); return (u_char *) StorageTmp->traceRouteResultsIpTgtAddr; case COLUMN_TRACEROUTERESULTSTESTATTEMPTS: *var_len = sizeof(StorageTmp->traceRouteResultsTestAttempts); return (u_char *) & StorageTmp->traceRouteResultsTestAttempts; case COLUMN_TRACEROUTERESULTSTESTSUCCESSES: *var_len = sizeof(StorageTmp->traceRouteResultsTestSuccesses); return (u_char *) & StorageTmp->traceRouteResultsTestSuccesses; case COLUMN_TRACEROUTERESULTSLASTGOODPATH: *var_len = (StorageTmp->traceRouteResultsLastGoodPathLen); return (u_char *) StorageTmp->traceRouteResultsLastGoodPath; default: ERROR_MSG(""); } return NULL; }
int main(int argc, char* argv[]) { char* config_path = NULL; int force_overwrite = 0; int c = 0; while ((c = getopt(argc, argv, "c:fhv")) != -1) { switch(c) { case 'c': config_path = strdup(optarg); if (config_path == NULL) { fprintf(stderr, "Error allocating memory, exiting\n"); return MRV_MEMORY; } break; case 'f': force_overwrite = 1; break; case 'h': usage(); return 0; case 'v': version(); return 0; } } if (config_path == NULL) { config_path = strdup(DEFAULT_METERD_CONF); if (config_path == NULL) { fprintf(stderr, "Error allocating memory, exiting\n"); return MRV_MEMORY; } } /* Load the configuration */ if (meterd_init_config_handling(config_path) != MRV_OK) { fprintf(stderr, "Failed to load the configuration, exiting\n"); return MRV_CONFIG_ERROR; } /* Initialise logging */ if (meterd_init_log() != MRV_OK) { fprintf(stderr, "Failed to initialise logging, exiting\n"); return MRV_LOG_INIT_FAIL; } INFO_MSG("Smart Meter Monitoring Daemon (meterd) version %s", VERSION); INFO_MSG("Starting database creation"); /* Initialise database handling */ if (meterd_db_init() != MRV_OK) { ERROR_MSG("Failed to initialise database handling, giving up"); return MRV_DB_ERROR; } if (force_overwrite) { INFO_MSG("Will overwrite existing databases"); } /* Create raw databases and counter databases */ if ((meterd_createdb_raw("raw_db", force_overwrite) != MRV_OK) || (meterd_createdb_raw("fivemin_avg", force_overwrite) != MRV_OK) || (meterd_createdb_raw("hourly_avg", force_overwrite) != MRV_OK) || (meterd_createdb_counters(force_overwrite) != MRV_OK)) { ERROR_MSG("Errors occurred during database creation"); } else { INFO_MSG("Finished database creation"); } /* Uninitialise database handling */ meterd_db_finalize(); /* Uninitialise logging */ if (meterd_uninit_log() != MRV_OK) { fprintf(stderr, "Failed to uninitialise logging\n"); } free(config_path); return MRV_OK; }
//------------------------------------------------------------------------------------- bool NavMeshHandle::_create(int layer, const std::string& resPath, const std::string& res, NavMeshHandle* pNavMeshHandle) { KBE_ASSERT(pNavMeshHandle); FILE* fp = fopen(res.c_str(), "rb"); if (!fp) { ERROR_MSG(fmt::format("NavMeshHandle::create: open({}) is error!\n", Resmgr::getSingleton().matchRes(res))); return false; } DEBUG_MSG(fmt::format("NavMeshHandle::create: ({}), layer={}\n", res, layer)); bool safeStorage = true; int pos = 0; int size = sizeof(NavMeshSetHeader); fseek(fp, 0, SEEK_END); size_t flen = ftell(fp); fseek(fp, 0, SEEK_SET); uint8* data = new uint8[flen]; if(data == NULL) { ERROR_MSG(fmt::format("NavMeshHandle::create: open({}), memory(size={}) error!\n", Resmgr::getSingleton().matchRes(res), flen)); fclose(fp); SAFE_RELEASE_ARRAY(data); return false; } size_t readsize = fread(data, 1, flen, fp); if(readsize != flen) { ERROR_MSG(fmt::format("NavMeshHandle::create: open({}), read(size={} != {}) error!\n", Resmgr::getSingleton().matchRes(res), readsize, flen)); fclose(fp); SAFE_RELEASE_ARRAY(data); return false; } if (readsize < sizeof(NavMeshSetHeader)) { ERROR_MSG(fmt::format("NavMeshHandle::create: open({}), NavMeshSetHeader is error!\n", Resmgr::getSingleton().matchRes(res))); fclose(fp); SAFE_RELEASE_ARRAY(data); return false; } NavMeshSetHeader header; memcpy(&header, data, size); pos += size; if (header.version != NavMeshHandle::RCN_NAVMESH_VERSION) { ERROR_MSG(fmt::format("NavMeshHandle::create: navmesh version({}) is not match({})!\n", header.version, ((int)NavMeshHandle::RCN_NAVMESH_VERSION))); fclose(fp); SAFE_RELEASE_ARRAY(data); return false; } dtNavMesh* mesh = dtAllocNavMesh(); if (!mesh) { ERROR_MSG("NavMeshHandle::create: dtAllocNavMesh is failed!\n"); fclose(fp); SAFE_RELEASE_ARRAY(data); return false; } dtStatus status = mesh->init(&header.params); if (dtStatusFailed(status)) { ERROR_MSG(fmt::format("NavMeshHandle::create: mesh init is error({})!\n", status)); fclose(fp); SAFE_RELEASE_ARRAY(data); return false; } // Read tiles. bool success = true; for (int i = 0; i < header.tileCount; ++i) { NavMeshTileHeader tileHeader; size = sizeof(NavMeshTileHeader); memcpy(&tileHeader, &data[pos], size); pos += size; size = tileHeader.dataSize; if (!tileHeader.tileRef || !tileHeader.dataSize) { success = false; status = DT_FAILURE + DT_INVALID_PARAM; break; } unsigned char* tileData = (unsigned char*)dtAlloc(size, DT_ALLOC_PERM); if (!tileData) { success = false; status = DT_FAILURE + DT_OUT_OF_MEMORY; break; } memcpy(tileData, &data[pos], size); pos += size; status = mesh->addTile(tileData , size , (safeStorage ? DT_TILE_FREE_DATA : 0) , tileHeader.tileRef , 0); if (dtStatusFailed(status)) { success = false; break; } } fclose(fp); SAFE_RELEASE_ARRAY(data); if (!success) { ERROR_MSG(fmt::format("NavMeshHandle::create: error({})!\n", status)); dtFreeNavMesh(mesh); return false; } dtNavMeshQuery* pMavmeshQuery = new dtNavMeshQuery(); pMavmeshQuery->init(mesh, 1024); pNavMeshHandle->resPath = resPath; pNavMeshHandle->navmeshLayer[layer].pNavmeshQuery = pMavmeshQuery; pNavMeshHandle->navmeshLayer[layer].pNavmesh = mesh; uint32 tileCount = 0; uint32 nodeCount = 0; uint32 polyCount = 0; uint32 vertCount = 0; uint32 triCount = 0; uint32 triVertCount = 0; uint32 dataSize = 0; const dtNavMesh* navmesh = mesh; for (int32 i = 0; i < navmesh->getMaxTiles(); ++i) { const dtMeshTile* tile = navmesh->getTile(i); if (!tile || !tile->header) continue; tileCount ++; nodeCount += tile->header->bvNodeCount; polyCount += tile->header->polyCount; vertCount += tile->header->vertCount; triCount += tile->header->detailTriCount; triVertCount += tile->header->detailVertCount; dataSize += tile->dataSize; // DEBUG_MSG(fmt::format("NavMeshHandle::create: verts({}, {}, {})\n", tile->verts[0], tile->verts[1], tile->verts[2])); } DEBUG_MSG(fmt::format("\t==> tiles loaded: {}\n", tileCount)); DEBUG_MSG(fmt::format("\t==> BVTree nodes: {}\n", nodeCount)); DEBUG_MSG(fmt::format("\t==> {} polygons ({} vertices)\n", polyCount, vertCount)); DEBUG_MSG(fmt::format("\t==> {} triangles ({} vertices)\n", triCount, triVertCount)); DEBUG_MSG(fmt::format("\t==> {:.2f} MB of data (not including pointers)\n", (((float)dataSize / sizeof(unsigned char)) / 1048576))); return true; }