OVR_PUBLIC_FUNCTION(void) ovr_GetLastErrorInfo(ovrErrorInfo* errorInfo) { const char* error = VR_GetVRInitErrorAsEnglishDescription(g_InitError); strncpy_s(errorInfo->ErrorString, error, sizeof(ovrErrorInfo::ErrorString)); errorInfo->Result = REV_InitErrorToOvrError(g_InitError); }
void CDlgCapCam::Active(void) { printf("capcam active\r\n"); CString str; m_flg_process = 0; //init cfg para algo_cfg_path = config_path + _T("\\advanced_parameters_default.ini"); strncpy_s(_vsv_dll_path, config_path.GetBuffer(), 256); memset(&m_algo_cfg, 0, sizeof(m_algo_cfg)); memset(m_algo_cfg.scene, 0xFF, STE_IMAGE_HEIGH*STE_IMAGE_WIDTH); m_algo_cfg.val_sense = GetPrivateProfileInt(_T("SMOKETRACE"), _T("sensitivity"), 2, algo_cfg_path); m_algo_cfg.val_delay = GetPrivateProfileInt(_T("SMOKETRACE"), _T("delay"), 2, algo_cfg_path); m_algo_cfg.val_fov = GetPrivateProfileInt(_T("SMOKETRACE"), _T("fov"), 1, algo_cfg_path); m_algo_cfg.val_static_det = GetPrivateProfileInt(_T("SMOKETRACE"), _T("sdet"), 1, algo_cfg_path); m_algo_cfg.alarm_delay = GetPrivateProfileInt(_T("SMOKETRACE"), _T("alarmdelay"), 1, algo_cfg_path); video_file_info_frame = 0; video_file_info_fps = 25; video_file_info_fourcc = 0; video_file_info_width = 0; video_file_info_height = 0; //清空交换内存 m_proc_result_buf.target_set.num = 0; m_proc_result_buf.event_set.num = 0; m_proc_result_buf.frame_index = 0; m_proc_result_buf.fps = 0; m_trigger_snatch_time = 0; m_trigger_index = 0; //抓拍参数 m_snatch_count =0 ; m_snatch_intertime = 0; m_snatch_pretime = 0; m_start_time = 0; //枚举所有有效地摄像机 //m_combo_list_device.ResetContent(); TCHAR szDeviceName[80]; TCHAR szDeviceVersion[80]; for (int wIndex = 0; wIndex < 10; wIndex++) { if (capGetDriverDescription (wIndex, szDeviceName, sizeof (szDeviceName), szDeviceVersion, sizeof (szDeviceVersion))) { m_combo_list_device.AddString(szDeviceName); } } if (m_combo_list_device.GetCount()>0) { m_combo_list_device.SetCurSel(0); } else { AfxMessageBox(_T("Error!You have no installed video capture device!")); } Invalidate(); }
int CJabberProto::FileSendParse(JABBER_SOCKET s, filetransfer *ft, char* buffer, int datalen) { char* p, *q, *t, *eob; char* str; int num; int currentFile; int fileId; int numRead; eob = buffer + datalen; p = buffer; num = 0; while (ft->state == FT_CONNECTING || ft->state == FT_INITIALIZING) { for (q = p; q + 1 < eob && (*q != '\r' || *(q + 1) != '\n'); q++); if (q + 1 >= eob) break; if ((str = (char*)mir_alloc(q - p + 1)) == NULL) { ft->state = FT_ERROR; break; } strncpy_s(str, q - p, p, _TRUNCATE); str[q - p] = '\0'; debugLogA("FT Got: %s", str); if (ft->state == FT_CONNECTING) { // looking for "GET filename.ext HTTP/1.1" if (!strncmp(str, "GET ", 4)) { for (t = str + 4; *t != '\0' && *t != ' '; t++); *t = '\0'; for (t = str + 4; *t != '\0' && *t == '/'; t++); ft->httpPath = mir_a2t(t); JabberHttpUrlDecode(ft->httpPath); ft->state = FT_INITIALIZING; debugLogA("Change to FT_INITIALIZING"); } } else { // FT_INITIALIZING if (str[0] == '\0') { struct _stati64 statbuf; mir_free(str); num += 2; currentFile = ft->std.currentFileNumber; TCHAR *t = _tcsrchr(ft->std.ptszFiles[currentFile], '\\'); if (t != NULL) t++; else t = ft->std.ptszFiles[currentFile]; if (ft->httpPath == NULL || mir_tstrcmp(ft->httpPath, t)) { if (ft->httpPath == NULL) debugLogA("Requested file name does not matched (httpPath == NULL)"); else debugLog(_T("Requested file name does not matched ('%s' vs. '%s')"), ft->httpPath, t); ft->state = FT_ERROR; break; } debugLog(_T("Sending [%s]"), ft->std.ptszFiles[currentFile]); _tstati64(ft->std.ptszFiles[currentFile], &statbuf); // file size in statbuf.st_size if ((fileId = _topen(ft->std.ptszFiles[currentFile], _O_BINARY | _O_RDONLY)) < 0) { debugLogA("File cannot be opened"); ft->state = FT_ERROR; mir_free(ft->httpPath); ft->httpPath = NULL; break; } char fileBuffer[2048]; int bytes = mir_snprintf(fileBuffer, _countof(fileBuffer), "HTTP/1.1 200 OK\r\nContent-Length: %I64u\r\n\r\n", statbuf.st_size); WsSend(s, fileBuffer, bytes, MSG_DUMPASTEXT); ft->std.flags |= PFTS_SENDING; ft->std.currentFileProgress = 0; debugLogA("Sending file data..."); while ((numRead = _read(fileId, fileBuffer, 2048)) > 0) { if (Netlib_Send(s, fileBuffer, numRead, 0) != numRead) { ft->state = FT_ERROR; break; } ft->std.currentFileProgress += numRead; ft->std.totalProgress += numRead; ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->std); } _close(fileId); if (ft->state != FT_ERROR) ft->state = FT_DONE; debugLogA("Finishing this file..."); mir_free(ft->httpPath); ft->httpPath = NULL; break; } } mir_free(str); q += 2; num += (q-p); p = q; } return num; }
int CreateFileListInfo(FileListInfoPtr pFileListInfo, char* path, int flag) { int pathLen, basePathLength; char *basePath, *pChar; WIN32_FIND_DATAA winFindData; HANDLE findHandle; if(path == NULL) { return FAILURE; } if(strlen(path) == 0) { /* In this case we will send the list of entries in ftp root*/ sprintf(path, "%s%s", GetFtpRoot(), "/"); } /* Create a search string, like C:\folder\* */ pathLen = strlen(path); basePath = malloc(pathLen + 3); memcpy(basePath, path, pathLen); basePathLength = pathLen; basePath[basePathLength] = '\\'; basePath[basePathLength + 1] = '*'; basePath[basePathLength + 2] = '\0'; /* Start a search */ memset(&winFindData, 0, sizeof(winFindData)); findHandle = FindFirstFileA(path, &winFindData); basePath[basePathLength] = '\0'; /* Restore to a basePath + \ */ /* Convert \ to / */ for(pChar = basePath; *pChar; pChar++) { if (*pChar == '\\') { *pChar = '/'; } } /* While we can find a next file do... But ignore \. and '.. entries, which are current folder and parent folder respectively */ while(findHandle != INVALID_HANDLE_VALUE && winFindData.cFileName[0] == '.' && (winFindData.cFileName[1] == '\0' || (winFindData.cFileName[1] == '.' && winFindData.cFileName[2] == '\0'))) { char fullpath[PATH_MAX]; fullpath[0] = 0; strncpy_s(fullpath, PATH_MAX, basePath, basePathLength); strncpy_s(fullpath + basePathLength, PATH_MAX - basePathLength, winFindData.cFileName, (int)strlen(winFindData.cFileName)); if(IS_FOLDER(winFindData.dwFileAttributes)) { if (AddFileListItemInfo(pFileListInfo, winFindData.cFileName, -1, 0) == 0) { rfbLog("File [%s]: Method [%s]: Add directory %s in the" " list failed\n", __FILE__, __FUNCTION__, fullpath); continue; } } else if(IS_REGULAR_FILE(winFindData.dwFileAttributes)) { if(flag) { unsigned int fileSize = (winFindData.nFileSizeHigh * (MAXDWORD+1)) + winFindData.nFileSizeLow; if(AddFileListItemInfo(pFileListInfo, winFindData.cFileName, fileSize, FILETIME_TO_TIME_T(winFindData.ftLastWriteTime)) == 0) { rfbLog("File [%s]: Method [%s]: Add file %s in the " "list failed\n", __FILE__, __FUNCTION__, fullpath); continue; } } } if(FindNextFileA(findHandle, &winFindData) == 0) { FindClose(findHandle); findHandle = INVALID_HANDLE_VALUE; } } if(findHandle != INVALID_HANDLE_VALUE) { FindClose(findHandle); } free(basePath); return SUCCESS; }
bool CModelToolCharDataTable::LoadProperty(const char * lpszFullPathFileName) { CNtlXMLDoc doc; if(doc.Create() == false) { _ASSERT(0); return false; } if(doc.Load( const_cast<char *>(lpszFullPathFileName) ) == false) { _ASSERT(0); return false; } char szBuffer[1024]; if( !doc.GetDataWithXPath(const_cast<char *>(XML_PROP_NAME_ATTRIBUTE), szBuffer, sizeof(szBuffer)) ) { _ASSERT(0); return false; } sMODELTOOL_CHAR_TBLDAT *pModelToolCharData = new sMODELTOOL_CHAR_TBLDAT; Add(szBuffer, pModelToolCharData); IXMLDOMNodeList *pAnimDataList = doc.SelectNodeList(XML_PROP_ANIM_DATA_ELEMENT); IXMLDOMNode* pAnimDataNode = NULL; IXMLDOMNodeList *pAnimEventList = NULL; IXMLDOMNode* pAnimEventNode = NULL; long lAnimDataNodeNum = 0; long lAnimEventNodeNum = 0; int nAnimKeyID = 0; float fDurationTime = 0.f; BYTE byPushCount = 0; BYTE byKnockDownCount = 0; bool bKB2Push = false; BYTE byHitCount = 0; float aHitTime[NTL_MAX_SIZE_HIT]; pAnimDataList->get_length(&lAnimDataNodeNum); for(long m = 0; m < lAnimDataNodeNum ; ++m) { pAnimDataList->get_item(m,&pAnimDataNode); if(!doc.GetTextWithAttributeName(pAnimDataNode, XML_PROP_ANIM_DATA_ELEMENT_KEYID_ATTRIBUTE, szBuffer, sizeof(szBuffer))) { _ASSERT(0); return false; } nAnimKeyID = atoi(szBuffer); if(!doc.GetTextWithAttributeName(pAnimDataNode, XML_PROP_ANIM_DATA_ELEMENT_PLAYTIME_ATTRIBUTE, szBuffer, sizeof(szBuffer))) { _ASSERT(0); return false; } fDurationTime = (float)atof(szBuffer); pAnimDataNode->selectNodes(L"ANIM_EVENT", &pAnimEventList); pAnimEventList->get_length(&lAnimEventNodeNum); memset(aHitTime, 0, sizeof(aHitTime)); for(long n = 0; n < lAnimEventNodeNum; ++n) { pAnimEventList->get_item(n, &pAnimEventNode); if(!doc.GetTextWithAttributeName(pAnimEventNode, XML_PROP_ANIM_DATA_ELEMENT_EVENTID_ATTRIBUTE, szBuffer, sizeof(szBuffer))) { _ASSERT(0); return false; } int nAnimEventID = EVENT_ANIM_NONE; int nBehavior = TARGET_BEHAVIOR_NONE; nAnimEventID = atoi(szBuffer); if(nAnimEventID == EVENT_ANIM_HIT) { if(!doc.GetTextWithAttributeName(pAnimEventNode, XML_PROP_ANIM_DATA_ELEMENT_HITBEHAVIOR_ATTRIBUTE, szBuffer, sizeof(szBuffer))) { _ASSERT(0); return false; } nBehavior = atoi(szBuffer); if(nBehavior == TARGET_BEHAVIOR_PUSH) { byPushCount++; } else if(nBehavior == TARGET_BEHAVIOR_KNOCK_DOWN) { byKnockDownCount++; if( byKnockDownCount > 1 ) { _ASSERT(0); return false; } } // Hit time if(!doc.GetTextWithAttributeName(pAnimEventNode, XML_PROP_ANIM_DATA_ELEMENT_HITTIME_ATTRIBUTE, szBuffer, sizeof(szBuffer))) { _ASSERT(0); return false; } aHitTime[byHitCount] = (float)atof(szBuffer); byHitCount++; if(byHitCount > NTL_MAX_SIZE_HIT) _ASSERT(0); // KB2PUSH if(!doc.GetTextWithAttributeName(pAnimEventNode, XML_PROP_ANIM_DATA_ELEMENT_HITKB2PUSH_ATTRIBUTE, szBuffer, sizeof(szBuffer))) { _ASSERT(0); return false; } if(atoi(szBuffer) == 0) { bKB2Push = false; } else { bKB2Push = true; } } else if(nAnimEventID == EVENT_ANIM_SKILL_CANCEL) { // time if(!doc.GetTextWithAttributeName(pAnimEventNode, XML_PROP_ANIM_DATA_ELEMENT_HITTIME_ATTRIBUTE, szBuffer, sizeof(szBuffer))) { _ASSERT(0); return false; } pModelToolCharData->AddSkillCancelTime(nAnimKeyID, (float)atof(szBuffer)); } if(pAnimEventNode) { pAnimEventNode->Release(); pAnimEventNode = NULL; } } if( nAnimKeyID != -1 ) pModelToolCharData->Add(nAnimKeyID, fDurationTime, byPushCount, byKnockDownCount, byHitCount, aHitTime, bKB2Push); nAnimKeyID = 0; fDurationTime = 0; byPushCount = 0; byKnockDownCount = 0; byHitCount = 0; if(pAnimEventList) { pAnimEventList->Release(); pAnimEventList = NULL; } if(pAnimDataNode) { pAnimDataNode->Release(); pAnimDataNode = NULL; } } //pModelToolCharData->GetChainAttack(PC_CLASS_HUMAN_FIGHTER, ITEM_TYPE_UNKNOWN, 6); if(pAnimDataList) { pAnimDataList->Release(); pAnimDataList = NULL; } char *pTokenStart = NULL; char *pTokenEnd = NULL; char szToken[64]; if( !doc.GetDataWithXPath("MODEL_SCRIPT/HEADER/ANIM_BBOX", szBuffer, sizeof(szBuffer)) ) { _ASSERT(0); return false; } CNtlVector vTemp; pTokenStart = szBuffer; pTokenEnd = strstr( szBuffer, ";"); strncpy_s(szToken, sizeof(szToken), pTokenStart, pTokenEnd - pTokenStart); vTemp.x = (float) atof(szToken); pTokenStart = pTokenEnd + 1; pTokenEnd = strstr( pTokenStart, ";"); strncpy_s(szToken, sizeof(szToken), pTokenStart, pTokenEnd - pTokenStart); vTemp.y = (float) atof(szToken); pTokenStart = pTokenEnd + 1; strncpy_s(szToken, sizeof(szToken), pTokenStart, strlen(szBuffer)); vTemp.z = (float) atof(szToken); pModelToolCharData->m_vMin.x = -(vTemp.x / 2.0f); pModelToolCharData->m_vMin.y = 0.0f; pModelToolCharData->m_vMin.z = -(vTemp.z / 2.0f); pModelToolCharData->m_vMax.x = vTemp.x / 2.0f; pModelToolCharData->m_vMax.y = vTemp.y; pModelToolCharData->m_vMax.z = vTemp.z / 2.0f; if( !doc.GetDataWithXPath("MODEL_SCRIPT/BONE_DATA/BASE_SCALE", szBuffer, sizeof(szBuffer)) ) { _ASSERT(0); return false; } pModelToolCharData->m_fScale = (float) atof(szBuffer); return true; }
bool Model::LoadAssimp(const char *filename) { Assimp::Importer importer; // remove unused data importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, aiComponent_COLORS | aiComponent_LIGHTS | aiComponent_CAMERAS); // max triangles and vertices per mesh, splits above this threshold importer.SetPropertyInteger(AI_CONFIG_PP_SLM_TRIANGLE_LIMIT, INT_MAX); importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, 0xfffe); // avoid the primitive restart index // remove points and lines importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE); const aiScene *scene = importer.ReadFile(filename, aiProcess_CalcTangentSpace | aiProcess_JoinIdenticalVertices | aiProcess_Triangulate | aiProcess_RemoveComponent | aiProcess_GenSmoothNormals | aiProcess_SplitLargeMeshes | aiProcess_ValidateDataStructure | //aiProcess_ImproveCacheLocality | // handled by optimizePostTransform() aiProcess_RemoveRedundantMaterials | aiProcess_SortByPType | aiProcess_FindInvalidData | aiProcess_GenUVCoords | aiProcess_TransformUVCoords | aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph); if (scene == nullptr) return false; if (scene->HasTextures()) { // embedded textures... } if (scene->HasAnimations()) { // todo } m_Header.materialCount = scene->mNumMaterials; m_pMaterial = new Material [m_Header.materialCount]; memset(m_pMaterial, 0, sizeof(Material) * m_Header.materialCount); for (unsigned int materialIndex = 0; materialIndex < scene->mNumMaterials; materialIndex++) { const aiMaterial *srcMat = scene->mMaterials[materialIndex]; Material *dstMat = m_pMaterial + materialIndex; aiColor3D diffuse(1.0f, 1.0f, 1.0f); aiColor3D specular(1.0f, 1.0f, 1.0f); aiColor3D ambient(1.0f, 1.0f, 1.0f); aiColor3D emissive(0.0f, 0.0f, 0.0f); aiColor3D transparent(1.0f, 1.0f, 1.0f); float opacity = 1.0f; float shininess = 0.0f; float specularStrength = 1.0f; aiString texDiffusePath; aiString texSpecularPath; aiString texEmissivePath; aiString texNormalPath; aiString texLightmapPath; aiString texReflectionPath; srcMat->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse); srcMat->Get(AI_MATKEY_COLOR_SPECULAR, specular); srcMat->Get(AI_MATKEY_COLOR_AMBIENT, ambient); srcMat->Get(AI_MATKEY_COLOR_EMISSIVE, emissive); srcMat->Get(AI_MATKEY_COLOR_TRANSPARENT, transparent); srcMat->Get(AI_MATKEY_OPACITY, opacity); srcMat->Get(AI_MATKEY_SHININESS, shininess); srcMat->Get(AI_MATKEY_SHININESS_STRENGTH, specularStrength); srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), texDiffusePath); srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), texSpecularPath); srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), texEmissivePath); srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), texNormalPath); srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), texLightmapPath); srcMat->Get(AI_MATKEY_TEXTURE(aiTextureType_REFLECTION, 0), texReflectionPath); dstMat->diffuse = Vector3(diffuse.r, diffuse.g, diffuse.b); dstMat->specular = Vector3(specular.r, specular.g, specular.b); dstMat->ambient = Vector3(ambient.r, ambient.g, ambient.b); dstMat->emissive = Vector3(emissive.r, emissive.g, emissive.b); dstMat->transparent = Vector3(transparent.r, transparent.g, transparent.b); dstMat->opacity = opacity; dstMat->shininess = shininess; dstMat->specularStrength = specularStrength; char *pRem = nullptr; strncpy_s(dstMat->texDiffusePath, "models/", Material::maxTexPath - 1); strncat_s(dstMat->texDiffusePath, texDiffusePath.C_Str(), Material::maxTexPath - 1); pRem = strrchr(dstMat->texDiffusePath, '.'); while (pRem != nullptr && *pRem != 0) *(pRem++) = 0; // remove extension strncpy_s(dstMat->texSpecularPath, "models/", Material::maxTexPath - 1); strncat_s(dstMat->texSpecularPath, texSpecularPath.C_Str(), Material::maxTexPath - 1); pRem = strrchr(dstMat->texSpecularPath, '.'); while (pRem != nullptr && *pRem != 0) *(pRem++) = 0; // remove extension strncpy_s(dstMat->texEmissivePath, "models/", Material::maxTexPath - 1); strncat_s(dstMat->texEmissivePath, texEmissivePath.C_Str(), Material::maxTexPath - 1); pRem = strrchr(dstMat->texEmissivePath, '.'); while (pRem != nullptr && *pRem != 0) *(pRem++) = 0; // remove extension strncpy_s(dstMat->texNormalPath, "models/", Material::maxTexPath - 1); strncat_s(dstMat->texNormalPath, texNormalPath.C_Str(), Material::maxTexPath - 1); pRem = strrchr(dstMat->texNormalPath, '.'); while (pRem != nullptr && *pRem != 0) *(pRem++) = 0; // remove extension strncpy_s(dstMat->texLightmapPath, "models/", Material::maxTexPath - 1); strncat_s(dstMat->texLightmapPath, texLightmapPath.C_Str(), Material::maxTexPath - 1); pRem = strrchr(dstMat->texLightmapPath, '.'); while (pRem != nullptr && *pRem != 0) *(pRem++) = 0; // remove extension strncpy_s(dstMat->texReflectionPath, "models/", Material::maxTexPath - 1); strncat_s(dstMat->texReflectionPath, texReflectionPath.C_Str(), Material::maxTexPath - 1); pRem = strrchr(dstMat->texReflectionPath, '.'); while (pRem != nullptr && *pRem != 0) *(pRem++) = 0; // remove extension aiString matName; srcMat->Get(AI_MATKEY_NAME, matName); strncpy_s(dstMat->name, matName.C_Str(), Material::maxMaterialName - 1); } m_Header.meshCount = scene->mNumMeshes; m_pMesh = new Mesh [m_Header.meshCount]; memset(m_pMesh, 0, sizeof(Mesh) * m_Header.meshCount); // first pass, count everything for (unsigned int meshIndex = 0; meshIndex < scene->mNumMeshes; meshIndex++) { const aiMesh *srcMesh = scene->mMeshes[meshIndex]; Mesh *dstMesh = m_pMesh + meshIndex; assert(srcMesh->mPrimitiveTypes == aiPrimitiveType_TRIANGLE); dstMesh->materialIndex = srcMesh->mMaterialIndex; // just store everything as float. Can quantize in Model::optimize() dstMesh->attribsEnabled |= attrib_mask_position; dstMesh->attrib[attrib_position].offset = dstMesh->vertexStride; dstMesh->attrib[attrib_position].normalized = 0; dstMesh->attrib[attrib_position].components = 3; dstMesh->attrib[attrib_position].format = attrib_format_float; dstMesh->vertexStride += sizeof(float) * 3; dstMesh->attribsEnabled |= attrib_mask_texcoord0; dstMesh->attrib[attrib_texcoord0].offset = dstMesh->vertexStride; dstMesh->attrib[attrib_texcoord0].normalized = 0; dstMesh->attrib[attrib_texcoord0].components = 2; dstMesh->attrib[attrib_texcoord0].format = attrib_format_float; dstMesh->vertexStride += sizeof(float) * 2; dstMesh->attribsEnabled |= attrib_mask_normal; dstMesh->attrib[attrib_normal].offset = dstMesh->vertexStride; dstMesh->attrib[attrib_normal].normalized = 0; dstMesh->attrib[attrib_normal].components = 3; dstMesh->attrib[attrib_normal].format = attrib_format_float; dstMesh->vertexStride += sizeof(float) * 3; dstMesh->attribsEnabled |= attrib_mask_tangent; dstMesh->attrib[attrib_tangent].offset = dstMesh->vertexStride; dstMesh->attrib[attrib_tangent].normalized = 0; dstMesh->attrib[attrib_tangent].components = 3; dstMesh->attrib[attrib_tangent].format = attrib_format_float; dstMesh->vertexStride += sizeof(float) * 3; dstMesh->attribsEnabled |= attrib_mask_bitangent; dstMesh->attrib[attrib_bitangent].offset = dstMesh->vertexStride; dstMesh->attrib[attrib_bitangent].normalized = 0; dstMesh->attrib[attrib_bitangent].components = 3; dstMesh->attrib[attrib_bitangent].format = attrib_format_float; dstMesh->vertexStride += sizeof(float) * 3; // depth-only dstMesh->attribsEnabledDepth |= attrib_mask_position; dstMesh->attribDepth[attrib_position].offset = dstMesh->vertexStrideDepth; dstMesh->attribDepth[attrib_position].normalized = 0; dstMesh->attribDepth[attrib_position].components = 3; dstMesh->attribDepth[attrib_position].format = attrib_format_float; dstMesh->vertexStrideDepth += sizeof(float) * 3; // color rendering dstMesh->vertexDataByteOffset = m_Header.vertexDataByteSize; dstMesh->vertexCount = srcMesh->mNumVertices; dstMesh->indexDataByteOffset = m_Header.indexDataByteSize; dstMesh->indexCount = srcMesh->mNumFaces * 3; m_Header.vertexDataByteSize += dstMesh->vertexStride * dstMesh->vertexCount; m_Header.indexDataByteSize += sizeof(uint16_t) * dstMesh->indexCount; // depth-only rendering dstMesh->vertexDataByteOffsetDepth = m_Header.vertexDataByteSizeDepth; dstMesh->vertexCountDepth = srcMesh->mNumVertices; m_Header.vertexDataByteSizeDepth += dstMesh->vertexStrideDepth * dstMesh->vertexCountDepth; } // allocate storage m_pVertexData = new unsigned char [m_Header.vertexDataByteSize]; m_pIndexData = new unsigned char [m_Header.indexDataByteSize]; m_pVertexDataDepth = new unsigned char [m_Header.vertexDataByteSizeDepth]; m_pIndexDataDepth = new unsigned char [m_Header.indexDataByteSize]; // second pass, fill in vertex and index data for (unsigned int meshIndex = 0; meshIndex < scene->mNumMeshes; meshIndex++) { const aiMesh *srcMesh = scene->mMeshes[meshIndex]; Mesh *dstMesh = m_pMesh + meshIndex; float *dstPos = (float*)(m_pVertexData + dstMesh->vertexDataByteOffset + dstMesh->attrib[attrib_position].offset); float *dstTexcoord0 = (float*)(m_pVertexData + dstMesh->vertexDataByteOffset + dstMesh->attrib[attrib_texcoord0].offset); float *dstNormal = (float*)(m_pVertexData + dstMesh->vertexDataByteOffset + dstMesh->attrib[attrib_normal].offset); float *dstTangent = (float*)(m_pVertexData + dstMesh->vertexDataByteOffset + dstMesh->attrib[attrib_tangent].offset); float *dstBitangent = (float*)(m_pVertexData + dstMesh->vertexDataByteOffset + dstMesh->attrib[attrib_bitangent].offset); float *dstPosDepth = (float*)(m_pVertexDataDepth + dstMesh->vertexDataByteOffsetDepth + dstMesh->attribDepth[attrib_position].offset); for (unsigned int v = 0; v < dstMesh->vertexCount; v++) { if (srcMesh->mVertices) { dstPos[0] = srcMesh->mVertices[v].x; dstPos[1] = srcMesh->mVertices[v].y; dstPos[2] = srcMesh->mVertices[v].z; dstPosDepth[0] = srcMesh->mVertices[v].x; dstPosDepth[1] = srcMesh->mVertices[v].y; dstPosDepth[2] = srcMesh->mVertices[v].z; } else { // no position? That's kind of bad. assert(0); } dstPos = (float*)((unsigned char*)dstPos + dstMesh->vertexStride); dstPosDepth = (float*)((unsigned char*)dstPosDepth + dstMesh->vertexStrideDepth); if (srcMesh->mTextureCoords[0]) { dstTexcoord0[0] = srcMesh->mTextureCoords[0][v].x; dstTexcoord0[1] = srcMesh->mTextureCoords[0][v].y; } else { dstTexcoord0[0] = 0.0f; dstTexcoord0[1] = 0.0f; } dstTexcoord0 = (float*)((unsigned char*)dstTexcoord0 + dstMesh->vertexStride); if (srcMesh->mNormals) { dstNormal[0] = srcMesh->mNormals[v].x; dstNormal[1] = srcMesh->mNormals[v].y; dstNormal[2] = srcMesh->mNormals[v].z; } else { // Assimp should generate normals if they are missing, according to the postprocessing flag specified on load, // so we should never get here. assert(0); } dstNormal = (float*)((unsigned char*)dstNormal + dstMesh->vertexStride); if (srcMesh->mTangents) { dstTangent[0] = srcMesh->mTangents[v].x; dstTangent[1] = srcMesh->mTangents[v].y; dstTangent[2] = srcMesh->mTangents[v].z; } else { // TODO: generate tangents/bitangents if missing dstTangent[0] = 1.0f; dstTangent[1] = 0.0f; dstTangent[2] = 0.0f; } dstTangent = (float*)((unsigned char*)dstTangent + dstMesh->vertexStride); if (srcMesh->mBitangents) { dstBitangent[0] = srcMesh->mBitangents[v].x; dstBitangent[1] = srcMesh->mBitangents[v].y; dstBitangent[2] = srcMesh->mBitangents[v].z; } else { // TODO: generate tangents/bitangents if missing dstBitangent[0] = 0.0f; dstBitangent[1] = 1.0f; dstBitangent[2] = 0.0f; } dstBitangent = (float*)((unsigned char*)dstBitangent + dstMesh->vertexStride); } uint16_t *dstIndex = (uint16_t*)(m_pIndexData + dstMesh->indexDataByteOffset); uint16_t *dstIndexDepth = (uint16_t*)(m_pIndexDataDepth + dstMesh->indexDataByteOffset); for (unsigned int f = 0; f < srcMesh->mNumFaces; f++) { assert(srcMesh->mFaces[f].mNumIndices == 3); *dstIndex++ = srcMesh->mFaces[f].mIndices[0]; *dstIndex++ = srcMesh->mFaces[f].mIndices[1]; *dstIndex++ = srcMesh->mFaces[f].mIndices[2]; *dstIndexDepth++ = srcMesh->mFaces[f].mIndices[0]; *dstIndexDepth++ = srcMesh->mFaces[f].mIndices[1]; *dstIndexDepth++ = srcMesh->mFaces[f].mIndices[2]; } } ComputeAllBoundingBoxes(); return true; }
// Is the process black(listed)? static bool dllmainProcAttachCheckProcessIsBlacklisted(char procname[], char *p) { DWORD buffsize = MAX_PATH * 20; // Initial buffer size for registry operation bool usewhitelist = false; HKEY key = NULL; char *buffer = new char[buffsize]; // check if we're using a whitelist or a blacklist DWORD tmpsize = buffsize - 1; bool success = (RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Mumble\\Mumble\\overlay", NULL, KEY_READ, &key) == ERROR_SUCCESS) && (RegQueryValueExA(key, "usewhitelist", NULL, NULL, (LPBYTE)buffer, &tmpsize) == ERROR_SUCCESS); if (success) { buffer[tmpsize] = '\0'; usewhitelist = (_stricmp(buffer, "true") == 0); // reset tmpsize to the buffers size (minus 1 char for str-termination), as it was changed by RegQuery tmpsize = buffsize - 1; // read the whitelist or blacklist (depending on which one we use) DWORD ret; while ((ret = RegQueryValueExA(key, usewhitelist ? "whitelist" : "blacklist", NULL, NULL, (LPBYTE)buffer, &tmpsize)) == ERROR_MORE_DATA) { // Increase the buffsize according to the required size RegQuery wrote into tmpsize, so we can read the whole value delete []buffer; buffsize = tmpsize + 1; buffer = new char[buffsize]; } success = (ret == ERROR_SUCCESS); } if (key) RegCloseKey(key); if (success) { buffer[tmpsize] = '\0'; unsigned int pos = 0; if (usewhitelist) { // check if process is whitelisted bool onwhitelist = false; while (pos < buffsize && buffer[pos] != 0) { if (_stricmp(procname, buffer + pos) == 0 || _stricmp(p+1, buffer + pos) == 0) { ods("Lib: Overlay enabled for whitelisted '%s'", buffer + pos); onwhitelist = true; break; } pos += static_cast<unsigned int>(strlen(buffer + pos)) + 1; } if (!onwhitelist) { ods("Lib: No whitelist entry found for '%s', auto-blacklisted", procname); bBlackListed = TRUE; return true; } } else { // check if process is blacklisted while (pos < buffsize && buffer[pos] != 0) { if (_stricmp(procname, buffer + pos) == 0 || _stricmp(p+1, buffer + pos) == 0) { ods("Lib: Overlay blacklist entry found for '%s'", buffer + pos); bBlackListed = TRUE; return true; } pos += static_cast<unsigned int>(strlen(buffer + pos)) + 1; } } } else { ods("Lib: no blacklist/whitelist found in the registry"); } // As a last resort, if we're using blacklisting, check the built-in blacklist. // // If the registry query failed this means we're guaranteed to check the // built-in list. // // If the list in the registry is out of sync, for example because the built- // in list in overlay_blacklist.h was updated got updated, we're also // guaranteed that we include all built-in blacklisted items in our check. if (!usewhitelist) { ods("Lib: Overlay fallback to default blacklist"); int i = 0; while (overlayBlacklist[i]) { if (_stricmp(procname, overlayBlacklist[i]) == 0 || _stricmp(p+1, overlayBlacklist[i])==0) { ods("Lib: Overlay default blacklist entry found for '%s'", overlayBlacklist[i]); bBlackListed = TRUE; return true; } i++; } } // Make sure to always free/destroy buffer & heap delete []buffer; // if the processname is already found to be blacklisted, we can stop here if (bBlackListed) return true; // check if there is a "nooverlay" file in the executables folder, which would disable/blacklist the overlay // Same buffersize as procname; which we copy from. char fname[PROCNAMEFILEPATH_EXTENDED_BUFFER_BUFLEN]; size_t pathlength = static_cast<size_t>(p - procname); p = fname + pathlength; strncpy_s(fname, sizeof(fname), procname, pathlength + 1); strcpy_s(p+1, PROCNAMEFILEPATH_EXTENDED_EXTLEN, "nooverlay"); HANDLE h = CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (h != INVALID_HANDLE_VALUE) { CloseHandle(h); ods("Lib: Overlay disable %s found", fname); bBlackListed = TRUE; return true; } // check for "debugoverlay" file, which would enable overlay debugging strcpy_s(p+1, PROCNAMEFILEPATH_EXTENDED_EXTLEN, "debugoverlay"); h = CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (h != INVALID_HANDLE_VALUE) { CloseHandle(h); ods("Lib: Overlay debug %s found", fname); bDebug = TRUE; } // check for blacklisting for loading WPF library checkForWPF(); if (bBlackListed) return true; return false; }
INT_PTR NetlibHttpTransaction(WPARAM wParam, LPARAM lParam) { NetlibUser *nlu = (NetlibUser*)wParam; NETLIBHTTPREQUEST *nlhr = (NETLIBHTTPREQUEST*)lParam, *nlhrReply; if (GetNetlibHandleType(nlu) != NLH_USER || !(nlu->user.flags & NUF_OUTGOING) || nlhr == NULL || nlhr->cbSize != sizeof(NETLIBHTTPREQUEST) || nlhr->szUrl == NULL || nlhr->szUrl[0] == 0) { SetLastError(ERROR_INVALID_PARAMETER); return 0; } if (nlhr->nlc != NULL && GetNetlibHandleType(nlhr->nlc) != NLH_CONNECTION) nlhr->nlc = NULL; NetlibConnection *nlc = NetlibHttpProcessUrl(nlhr, nlu, (NetlibConnection*)nlhr->nlc); if (nlc == NULL) return 0; NETLIBHTTPREQUEST nlhrSend; char szUserAgent[64]; nlhrSend = *nlhr; nlhrSend.flags &= ~NLHRF_REMOVEHOST; nlhrSend.flags |= NLHRF_GENERATEHOST | NLHRF_SMARTREMOVEHOST | NLHRF_SMARTAUTHHEADER; bool doneUserAgentHeader = NetlibHttpFindHeader(nlhr, "User-Agent") != NULL; bool doneAcceptEncoding = NetlibHttpFindHeader(nlhr, "Accept-Encoding") != NULL; if (!doneUserAgentHeader || !doneAcceptEncoding) { nlhrSend.headers = (NETLIBHTTPHEADER*)mir_alloc(sizeof(NETLIBHTTPHEADER) * (nlhrSend.headersCount + 2)); memcpy(nlhrSend.headers, nlhr->headers, sizeof(NETLIBHTTPHEADER) * nlhr->headersCount); } if (!doneUserAgentHeader) { nlhrSend.headers[nlhrSend.headersCount].szName = "User-Agent"; nlhrSend.headers[nlhrSend.headersCount].szValue = szUserAgent; ++nlhrSend.headersCount; char szMirandaVer[64]; strncpy_s(szMirandaVer, MIRANDA_VERSION_STRING, _TRUNCATE); #if defined(_WIN64) strncat_s(szMirandaVer, " x64", _TRUNCATE); #endif char *pspace = strchr(szMirandaVer, ' '); if (pspace) { *pspace++ = '\0'; mir_snprintf(szUserAgent, "Miranda/%s (%s)", szMirandaVer, pspace); } else mir_snprintf(szUserAgent, "Miranda/%s", szMirandaVer); } if (!doneAcceptEncoding) { nlhrSend.headers[nlhrSend.headersCount].szName = "Accept-Encoding"; nlhrSend.headers[nlhrSend.headersCount].szValue = "deflate, gzip"; ++nlhrSend.headersCount; } if (NetlibHttpSendRequest((WPARAM)nlc, (LPARAM)&nlhrSend) == SOCKET_ERROR) { if (!doneUserAgentHeader || !doneAcceptEncoding) mir_free(nlhrSend.headers); nlhr->resultCode = nlhrSend.resultCode; NetlibCloseHandle((WPARAM)nlc, 0); return 0; } if (!doneUserAgentHeader || !doneAcceptEncoding) mir_free(nlhrSend.headers); DWORD dflags = (nlhr->flags & NLHRF_DUMPASTEXT ? MSG_DUMPASTEXT : 0) | (nlhr->flags & NLHRF_NODUMP ? MSG_NODUMP : (nlhr->flags & NLHRF_DUMPPROXY ? MSG_DUMPPROXY : 0)) | (nlhr->flags & NLHRF_NOPROXY ? MSG_RAW : 0); DWORD hflags = (nlhr->flags & NLHRF_NODUMP ? MSG_NODUMP : (nlhr->flags & NLHRF_DUMPPROXY ? MSG_DUMPPROXY : 0)) | (nlhr->flags & NLHRF_NOPROXY ? MSG_RAW : 0); if (nlhr->requestType == REQUEST_HEAD) nlhrReply = (NETLIBHTTPREQUEST*)NetlibHttpRecvHeaders((WPARAM)nlc, 0); else nlhrReply = NetlibHttpRecv(nlc, hflags, dflags); if (nlhrReply) { nlhrReply->szUrl = nlc->szNewUrl; nlc->szNewUrl = NULL; } if ((nlhr->flags & NLHRF_PERSISTENT) == 0 || nlhrReply == NULL) { NetlibCloseHandle((WPARAM)nlc, 0); if (nlhrReply) nlhrReply->nlc = NULL; } else nlhrReply->nlc = nlc; return (INT_PTR)nlhrReply; }
static int do_fwupgrade(struct cmd_ctx *cmdctx, int argc, char * const argv[]) { struct mtd_info *mtd = NULL; const char *filename = NULL; int ret; int oob = 0; switch(argc) { case 4: oob = (argv[3][0] == 'y');; if (oob) printf("FWU: Will write oob data!\n"); /* pass through */ case 3: filename = argv[2]; /* pass through */ case 2: mtd = mtd_by_name(argv[1]); break; default: return cmd_usage(cmdctx->cmdtp); } if(mtd == NULL) { printf("FWU mtd device is not available (bad part name?)\n"); return -1; } if(mtd->erasesize > CONFIG_CMD_FWUPGRADE_BUFFER_SIZE) { printf("FWU internal buffer is smaller than size of eraseblock\n"); return -ENOMEM; }; u8 *block = (u8*)CONFIG_CMD_FWUPGRADE_BUFFER_ADDR; if(block == NULL) { printf("FWU unable to allocate memory\n"); return -ENOMEM; } struct fwu_tftp_ctx ctx; memset(&ctx, 0, sizeof(struct fwu_tftp_ctx)); ctx.mtd = mtd; ctx.block = block; ctx.flash_offset = 0; ctx.flash_end = mtd->size; ctx.oob = oob; struct NetTask task; net_init_task_def(&task, TFTP); task.u.tftp.data_cb = fwu_tftp_cb; task.u.tftp.data_ctx = &ctx; char dir[MAXPATH]; extract_dirname(dir, task.bootfile); if(filename) { if(filename[0] == '/') { strncpy_s(task.bootfile, filename, MAXPATH); } else { sprintf(task.bootfile, "%s%s", dir, filename); } } else { if(0 == strcmp(mtd->name, "boot")) { sprintf(task.bootfile, "%smboot.img", dir); } else if(0 == strcmp(mtd->name, "kernel")) { sprintf(task.bootfile, "%suImage", dir); } else { sprintf(task.bootfile, "%smboot-%s.bin", dir, mtd->name); } } ret = erase_part(mtd, 0, 1); if (ret) { printf("FW: Partition erase failed, aborting..."); goto out; } ret = NetLoop(&task); if (ret < 0) { printf("FWU net trasfer failed: ret %d\n", ret); goto out; } printf("FWU complete: tftp_bytes %lu hex 0x%08lX flash_area 0x%012llX flash_bb %d\n", task.out_filesize, task.out_filesize, ctx.flash_offset, ctx.bb); out: return 0; }
/*! * @brief Get the name of the extension. * @param buffer Pointer to the buffer to write the name to. * @param bufferSize Size of the \c buffer parameter. * @return Indication of success or failure. */ DWORD __declspec(dllexport) GetExtensionName(char* buffer, int bufferSize) { strncpy_s(buffer, bufferSize, "kiwi", bufferSize - 1); return ERROR_SUCCESS; }
void CGameState::CaptureState() { bool playing = true; unsigned char card = CARD_NOCARD; // figure out if I am playing int sym_chair = p_symbol_engine_userchair->userchair(); if (!p_symbol_engine_userchair->userchair_confirmed()) { playing = false; } else if (!p_table_state->User()->HasKnownCards()) { playing = false; } // Poker window title char title[MAX_WINDOW_TITLE]; GetWindowText(p_autoconnector->attached_hwnd(), title, MAX_WINDOW_TITLE); strncpy_s(state[state_index&0xff].m_title, 64, title, _TRUNCATE); state[state_index&0xff].m_title[63] = '\0'; // Pot information for (int i=0; i<kMaxNumberOfPlayers; i++) { state[state_index&0xff].m_pot[i] = p_table_state->Pot(i); } // Common cards for (int i=0; i<kNumberOfCommunityCards; i++) { int common_card = p_table_state->CommonCards(i)->GetValue(); write_log(preferences.debug_dll_extension(), "[CGameState] Common card %i = %i\n", i, common_card); state[state_index&0xff].m_cards[i] = common_card; } // playing, posting, dealerchair int sym_dealerchair = p_symbol_engine_dealerchair->dealerchair(); bool sym_isautopost = p_symbol_engine_autoplayer->isautopost(); state[state_index&0xff].m_is_playing = playing; state[state_index&0xff].m_is_posting = sym_isautopost; state[state_index&0xff].m_fillerbits = 0; state[state_index&0xff].m_fillerbyte = 0; state[state_index&0xff].m_dealer_chair = sym_dealerchair; // loop through all 10 player chairs for (int i=0; i<kMaxNumberOfPlayers; i++) { // player name, balance, currentbet strncpy_s(state[state_index&0xff].m_player[i].m_name, 16, p_table_state->Player(i)->name().GetString(), _TRUNCATE); state[state_index&0xff].m_player[i].m_balance = p_table_state->Player(i)->balance(); state[state_index&0xff].m_player[i].m_currentbet = p_table_state->Player(i)->bet(); // player cards for (int j=0; j<kNumberOfCardsPerPlayer; j++) { Card* player_card = p_table_state->Player(i)->hole_cards(j); int card = player_card->GetValue(); write_log(preferences.debug_dll_extension(), "[CGameState] Player card [%i][%i] = %i\n", i, j, card); //!!!!!state[state_index&0xff].m_player[i].m_cards[j] = card; } // player name known, balance known state[state_index&0xff].m_player[i].m_name_known = p_scraper_access->IsGoodPlayername(i); state[state_index&0xff].m_player[i].m_balance_known = true; state[state_index&0xff].m_player[i].m_fillerbits = 0; state[state_index&0xff].m_player[i].m_fillerbyte = 0; } state_index++; }
BOOL ProtectedStorage::EnumOutlookExpressAccounts(void) { // Define important registry keys const char* OUTLOOK_KEY = "Software\\Microsoft\\Internet Account Manager\\Accounts"; int oIndex = 0; HKEY hkey, hkey2; long nEnumResult = 0; char name[MAX_KEY_SIZE], skey[MAX_KEY_SIZE]; DWORD dwKeyLen; FILETIME timeLastWrite; BYTE Data[150]; BYTE Data1[150]; DWORD size; int j = 0, i = 0; LONG lResult; DWORD type = REG_BINARY; strncpy_s(skey, MAX_KEY_SIZE, OUTLOOK_KEY, MAX_KEY_SIZE); lResult = RegOpenKeyEx(HKEY_CURRENT_USER, (LPCTSTR)skey, 0, KEY_ALL_ACCESS, &hkey); if(ERROR_SUCCESS != lResult) { printf("Unable to enumerate Outlook Express accounts: could not open HKCU\\%s\n", OUTLOOK_KEY); return FALSE; } while(nEnumResult != ERROR_NO_MORE_ITEMS) { dwKeyLen = MAX_KEY_SIZE; nEnumResult = RegEnumKeyEx(hkey, i, name, &dwKeyLen, NULL, NULL, NULL, &timeLastWrite); strncpy_s(skey, MAX_KEY_SIZE, OUTLOOK_KEY, MAX_KEY_SIZE - strlen(OUTLOOK_KEY) - 2); strcat_s(skey, MAX_KEY_SIZE, "\\"); strcat_s(skey, MAX_KEY_SIZE, name); if (RegOpenKeyEx(HKEY_CURRENT_USER, (LPCTSTR)skey, 0, KEY_ALL_ACCESS, &hkey2) == ERROR_SUCCESS) { size = sizeof(Data); if(RegQueryValueEx(hkey2, "HTTPMail User Name" , 0, &type, Data, &size) == ERROR_SUCCESS) { ++m_nOutlookCount; if (m_pOutlookDataHead == NULL) { OutlookData = (OEDATA*)malloc(sizeof(OEDATA)); m_pOutlookDataHead = OutlookData; } else { OutlookData = (OEDATA*)realloc(m_pOutlookDataHead, m_nOutlookCount * sizeof(OEDATA)); OutlookData += (m_nOutlookCount - 1); } strcpy_s(OutlookData->POPuser, sizeof(Data), (char*)Data); ZeroMemory(Data, sizeof(Data)); strcpy_s(OutlookData->POPserver, 7, "Hotmail"); size = sizeof(Data); if(RegQueryValueEx(hkey2, "HTTPMail Password2" , 0, &type, Data1, &size) == ERROR_SUCCESS) { int pass = 0; for(DWORD i = 2; i < size; i++) { if(IsCharAlphaNumeric(Data1[i])||(Data1[i]=='(')||(Data1[i]==')')||(Data1[i]=='.')||(Data1[i]==' ')||(Data1[i]=='-')) { OutlookData->POPpass[pass] = Data1[i]; } } pass++; OutlookData->POPpass[pass]=0; } ZeroMemory(Data1, sizeof(Data)); oIndex++; } else if(RegQueryValueEx(hkey2, "POP3 User Name" , 0, &type, Data, &size) == ERROR_SUCCESS) { ++m_nOutlookCount; if (m_pOutlookDataHead == NULL) { OutlookData = (OEDATA*)malloc(sizeof(OEDATA)); m_pOutlookDataHead = OutlookData; } else { m_pOutlookDataHead = OutlookData = (OEDATA*)realloc(m_pOutlookDataHead, m_nOutlookCount * sizeof(OEDATA)); OutlookData += (m_nOutlookCount - 1); } lstrcpy(OutlookData->POPuser,(char*)Data); ZeroMemory(Data,sizeof(Data)); size = sizeof(Data); RegQueryValueEx (hkey2, "POP3 Server" , 0, &type, Data, &size); lstrcpy(OutlookData->POPserver,(char*)Data); ZeroMemory(Data,sizeof(Data)); size = sizeof(Data); if(RegQueryValueEx(hkey2, "POP3 Password2" , 0, &type, Data1, &size) == ERROR_SUCCESS) { int pass = 0; for(DWORD i = 2; i < size; i++) { if(IsCharAlphaNumeric(Data1[i])||(Data1[i]=='(')||(Data1[i]==')')||(Data1[i]=='.')||(Data1[i]==' ')||(Data1[i]=='-')) { OutlookData->POPpass[pass] = Data1[i]; pass++; } } OutlookData->POPpass[pass] = 0; } } RegCloseKey(hkey2); } ZeroMemory(Data1, sizeof(Data1)); oIndex++; j++; i++; } RegCloseKey(hkey); return TRUE; }
BOOL ProtectedStorage::EnumProtectedStorage(void) { IPStorePtr pStore; IEnumPStoreTypesPtr EnumPStoreTypes; IEnumPStoreTypesPtr EnumSubTypes; IEnumPStoreItemsPtr spEnumItems; PSTORECREATEINSTANCE pPStoreCreateInstance; HMODULE hpsDLL = LoadLibrary("pstorec.dll"); HRESULT hr; GUID TypeGUID, subTypeGUID; LPWSTR itemName; unsigned long psDataLen = 0; unsigned char *psData = NULL; int i = 0; char szItemName[512]; char szItemData[512]; char szResName[512]; char szResData[512]; char szItemGUID[50]; char szTemp[256]; pPStoreCreateInstance = (PSTORECREATEINSTANCE)GetProcAddress(hpsDLL, "PStoreCreateInstance"); if (pPStoreCreateInstance == NULL) { printf("Unable to obtain handle to PStoreCreateInstance in pstorec.dll\n"); return FALSE; } hr = pPStoreCreateInstance(&pStore, 0, 0, 0); if (FAILED(hr)) { printf("Unable to create protected storage instance (error code %X)\n", hr); return FALSE; } hr = pStore->EnumTypes(0, 0, &EnumPStoreTypes); if (FAILED(hr)) { printf("Unable to enumerate protected storage types (error code %X)\n", hr); return FALSE; } while(EnumPStoreTypes->raw_Next(1, &TypeGUID, 0) == S_OK) { wsprintf(szItemGUID, "%x", TypeGUID); hr = pStore->EnumSubtypes(0, &TypeGUID, 0, &EnumSubTypes); if (FAILED(hr)) { printf("Unable to enumerate protected storage subtypes for GUID %S (error code %X)\n", szItemGUID, hr); continue; } while(EnumSubTypes->raw_Next(1, &subTypeGUID, 0) == S_OK) { hr = pStore->EnumItems(0, &TypeGUID, &subTypeGUID, 0, &spEnumItems); if (FAILED(hr)) { printf("Unable to enumerate protected storage items for GUID %S (error code %X)\n", szItemGUID, hr); continue; } while(spEnumItems->raw_Next(1,&itemName,0) == S_OK) { _PST_PROMPTINFO *pstiinfo = NULL; psDataLen = 0; psData = NULL; wsprintf(szItemName, "%ws", itemName); hr = pStore->ReadItem(0, &TypeGUID, &subTypeGUID, itemName, &psDataLen, &psData, pstiinfo, 0); if (FAILED(hr)) { printf("Unable to read protected storage item %S (error code %X)\n", szItemName, hr); continue; } if(strlen((char*)psData) < (psDataLen - 1)) { i = 0; for(DWORD m = 0; m < psDataLen; m += 2) { if(psData[m] == 0) szItemData[i] = ','; else szItemData[i] = psData[m]; i++; } if (i > 0) szItemData[i - 1] = 0; else szItemData[0] = 0; } else { wsprintf(szItemData, "%s", psData); } strcpy_s(szResName, 512, ""); strcpy_s(szResData, 512, ""); if(_stricmp(szItemGUID, "220d5cc1") == 0) { // GUIDs beginning with "220d5cc1" are Outlook Express BOOL bDeletedOEAccount = TRUE; for(i = 0; i < m_nOutlookCount; i++) { if(strcmp(m_pOutlookDataHead[i].POPpass, szItemName) == 0) { bDeletedOEAccount = FALSE; printf(OUTPUT_FORMAT, m_pOutlookDataHead[i].POPserver, "Outlook Express Account", m_pOutlookDataHead[i].POPuser, szItemData); break; } } if(bDeletedOEAccount) printf(OUTPUT_FORMAT, szItemName, "Deleted Outlook Express Account", m_pOutlookDataHead[i].POPuser, szItemData); } else if(_stricmp(szItemGUID, "5e7e8100") == 0) { // GUIDs beginning with 5e7e8100 are IE password-protected sites strcpy_s(szTemp, 512, ""); // If the item begins with DPAPI, it has been protected using the CryptProtectData call. // Decrypt it using the opposite call. This is a HUGE assumption on my part, but so far // appears to be the case if (strncmp(szItemName, "DPAPI:", 6) == 0) { char* szDecryptedPassword = DecryptData(psDataLen, psData); if (szDecryptedPassword != NULL) { char szUser[200]; memset(szUser, 0, 200); // Also have to figure out the user name. This section may need some work if (strncmp(szItemName + 7, "ftp://", 6) == 0) { size_t nPos = strcspn(szItemName + 13, "@"); if (nPos > 0 && nPos < strlen(szItemName + 13)) { // Found the @ sign - copy everything between ftp:// and the @ sign strncpy_s(szUser, 200, szItemName + 13, nPos); } else { strcpy_s(szUser, 200, szItemName + 13); } } else { // Just copy user name verbatim I guess strcpy_s(szUser, 200, szItemName); } printf(OUTPUT_FORMAT, szItemName, "IE Password-Protected Site", szUser, szDecryptedPassword); free(szDecryptedPassword); } else { printf(OUTPUT_FORMAT, szItemName, "IE Password-Protected Site", szItemName, "ERROR DECRYPTING"); //printf("Decryption error for item %s: error %d\n", szItemName, GetLastError()); } } else if(strstr(szItemData, ":") != 0) { strcpy_s(szTemp, 512, strstr(szItemData, ":") + 1); *(strstr(szItemData, ":")) = 0; printf(OUTPUT_FORMAT, szItemName, "IE Password-Protected Site", szItemData, szTemp); } } else if(_stricmp(szItemGUID, "b9819c52") == 0) { // GUIDs beginning with b9819c52 are MSN Explorer Signup char msnid[100]; char msnpass[100]; BOOL first = TRUE; char *p; for(DWORD m = 0; m < psDataLen; m += 2) { if(psData[m] == 0) { szItemData[i] = ','; i++; } else { if(IsCharAlphaNumeric(psData[m])||(psData[m]=='@')||(psData[m]=='.')||(psData[m]=='_')) { szItemData[i] = psData[m]; i++; } } } szItemData[i - 1] = 0; p = szItemData + 2; //psData[4] - number of msn accounts for(int ii = 0; ii < psData[4]; ii++) { strcpy_s(msnid, 100, p + 1); if(strstr(msnid,",") != 0) *strstr(msnid,",") = 0; if(strstr(p + 1, ",") != 0) strcpy_s(msnpass, 100, strstr(p + 1, ",") + 2); if(strstr(msnpass, ",") != 0) *strstr(msnpass, ",") = 0; p = strstr(p + 1, ",") + 2 + strlen(msnpass) + 7; printf(OUTPUT_FORMAT, msnid, "MSN Explorer Signup", msnid, msnpass); } } else if(_stricmp(szItemGUID, "e161255a") == 0) { // GUIDs beginning with e161255a are other stored IE credentials if(strstr(szItemName, "StringIndex") == 0) { if(strstr(szItemName, ":String") != 0) *strstr(szItemName, ":String") = 0; strncpy_s(szTemp, 512, szItemName, 8); if((strstr(szTemp, "http:/") == 0) && (strstr(szTemp, "https:/") == 0)) printf(OUTPUT_FORMAT, szItemName, "IE Auto Complete Fields", szItemData, ""); else { strcpy_s(szTemp, 512, ""); if(strstr(szItemData, ",") != 0) { strcpy_s(szTemp, 512, strstr(szItemData, ",") + 1); *(strstr(szItemData, ",")) = 0; } printf(OUTPUT_FORMAT, szItemName, "AutoComplete Passwords", szItemData, szTemp); } } } else if(_stricmp(szItemGUID, "89c39569") == 0) { // IdentitiesPass info. It's already been displayed, so just supress these } else { // Catch-all for miscellaneous data strcpy_s(szTemp, 512, ""); if(strstr(szItemData, ":") != 0) { strcpy_s(szTemp, 512, strstr(szItemData, ":") + 1); *(strstr(szItemData, ":")) = 0; } printf(OUTPUT_FORMAT, szItemName, "Unknown", szItemData, szTemp); } ZeroMemory(szItemName, sizeof(szItemName)); ZeroMemory(szItemData, sizeof(szItemData)); } } } return TRUE; }
void _tmain(int argc, char **argv) { CMyP2p client; if (!client.Init()) { printf(" CP2PClient::Init() failed \n"); return ; } char szServerIp[20]; char szUserName[MAX_USERNAME]; printf(" Please input server ip: "); gets_s(szServerIp,sizeof(szServerIp)); printf(" Please input your name: "); gets_s(szUserName,sizeof(szUserName)); if(!client.Login(szUserName, szServerIp)) { printf(" CP2PClient::Login() failed \n"); return ; } client.GetUserList(); // first login get list printf(" %s has successfully logined server \n", szUserName); //display user name and usage printf("\n Commands are: \"getu\", \"send\", \"exit\" \n"); //------------------------------------------- // handle command recyclely char szCommandLine[256]; while (TRUE) { gets_s(szCommandLine, sizeof(szCommandLine)); if (strlen(szCommandLine) < 4) { continue; } //------------------------------------------- // analysis the cmd char szCommand[10]; strncpy_s(szCommand, sizeof(szCommand), szCommandLine, 4); szCommand[4] = '\0'; if(_stricmp(szCommand, "getu") == 0) { if(client.GetUserList()) { printf(" Have %d users logined server: \n", client.m_PeerList.m_nCurrentSize); for(int i=0; i<client.m_PeerList.m_nCurrentSize; i++) { PEER_INFO *pInfo = &client.m_PeerList.m_pPeer[i]; printf(" Username: %s(%s:%ld) \n", pInfo->szUserName, ::inet_ntoa(*((in_addr*)&pInfo->addr[pInfo->AddrNum -1].dwIp)), pInfo->addr[pInfo->AddrNum - 1].nPort); } } else { printf(" Get User List Failure !\n"); } } else if(_stricmp(szCommand, "send") == 0) { //------------------------------------------- // analysis opposite name int i; char szPeer[MAX_USERNAME]; for(i = 5; ; i++) { if(szCommandLine[i] != ' ') szPeer[i-5] = szCommandLine[i]; else { szPeer[i-5] = '\0'; break; } } // analysis msg char szMsg[56]; strncpy_s(szMsg, sizeof(szMsg), &szCommandLine[i+1],sizeof(szCommandLine)+1); if(client.SendText(szPeer, szMsg, strlen(szMsg))) printf(" Send OK! \n"); else printf(" Send Failure! \n"); } else if(_stricmp(szCommand, "exit") == 0) { break; } } }
// ============================================================================ // ============================================================================== std::vector<std::vector<std::string> > CMySQLMgr::QueryFields(const char *pszQueryFields, const char *pszTable) { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ std::vector<std::vector<std::string> > vecRet; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (NULL == pszQueryFields) { return vecRet; } //~~~~~~~~~~~~~~~~~~~~~~ char szFields[MAX_STRING]; //~~~~~~~~~~~~~~~~~~~~~~ strncpy_s(szFields, pszQueryFields, sizeof(szFields)); MyTrim(szFields); //~~~~~~~~~~~~~~~~~~~~~~~~ char szQueryCmd[MAX_STRING]; //~~~~~~~~~~~~~~~~~~~~~~~~ if (szFields[0] == 34) { _snprintf_s(szQueryCmd, sizeof(szQueryCmd), "select %s from %s ", pszQueryFields, pszTable); return this->Query(szQueryCmd); } //~~~~~~~~~~~~~~~~~~~ char szKey[MAX_STRING]; //~~~~~~~~~~~~~~~~~~~ strncpy_s(szKey, pszQueryFields, sizeof(szKey)); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ char *pszPos = strstr(szKey, ","); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (pszPos) { *pszPos = 0; } _snprintf_s(szQueryCmd, sizeof(szQueryCmd), "select %s from %s group by %s having COUNT(%s) > 1 ", pszQueryFields, pszTable, szKey, szKey); vecRet = this->Query(szQueryCmd); if (!vecRet.empty()) { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ std::vector<std::vector<std::string> >::const_iterator it = vecRet.begin(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for (; it != vecRet.end(); ++it) { if (!it->empty()) { LogInfoIn(" 警告: 数据库表 %s 含有两行以上 %s = %s 的数据", pszTable, szKey, it->front().c_str()); } } } _snprintf_s(szQueryCmd, sizeof(szQueryCmd), "select %s from %s group by %s having COUNT(%s) = 1 ", pszQueryFields, pszTable, szKey, szKey); return this->Query(szQueryCmd); }
//Configuration class constructor ConfigurationTable::ConfigurationTable(void) { memset(this, 0, sizeof(CONFIGURATION_TABLE)); try { //[Listen] block PcapDevicesBlacklist = new std::vector<std::string>(); ListenPort = new std::vector<uint16_t>(); //[Addresses] block ListenAddress_IPv6 = new std::vector<sockaddr_storage>(); ListenAddress_IPv4 = new std::vector<sockaddr_storage>(); LocalhostSubnet.IPv6 = new ADDRESS_PREFIX_BLOCK(); LocalhostSubnet.IPv4 = new ADDRESS_PREFIX_BLOCK(); DNSTarget.IPv6_Multi = new std::vector<DNS_SERVER_DATA>(); DNSTarget.IPv4_Multi = new std::vector<DNS_SERVER_DATA>(); //[Data] block(A part) #if defined(ENABLE_PCAP) ICMP_PaddingData = new char[ICMP_PADDING_MAXSIZE](); DomainTest_Data = new char[DOMAIN_MAXSIZE](); #endif //[Data] block(B part) LocalFQDN_Response = new char[DOMAIN_MAXSIZE](); LocalFQDN_String = new std::string(); #if !defined(PLATFORM_MACX) LocalServer_Response = new char[DOMAIN_MAXSIZE + sizeof(dns_record_ptr) + sizeof(dns_record_opt)](); #endif LocalAddress_Response[0] = new char[PACKET_MAXSIZE](); LocalAddress_Response[1U] = new char[PACKET_MAXSIZE](); #if !defined(PLATFORM_MACX) LocalAddress_ResponsePTR[0] = new std::vector<std::string>(); LocalAddress_ResponsePTR[1U] = new std::vector<std::string>(); #endif //Global block LocalSocket = new std::vector<SYSTEM_SOCKET>(); RamdomEngine = new std::default_random_engine(); Path_Global = new std::vector<std::wstring>(); Path_ErrorLog = new std::wstring(); FileList_Hosts = new std::vector<std::wstring>(); FileList_IPFilter = new std::vector<std::wstring>(); #if (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) sPath_Global = new std::vector<std::string>(); sPath_ErrorLog = new std::string(); sFileList_Hosts = new std::vector<std::string>(); sFileList_IPFilter = new std::vector<std::string>(); #endif DomainTable = new char[strlen(RFC_DOMAIN_TABLE) + 1U](); AcceptTypeList = new std::vector<uint16_t>(); } catch (std::bad_alloc) { //[Listen] block delete PcapDevicesBlacklist; delete ListenPort; //[Addresses] block delete ListenAddress_IPv6; delete ListenAddress_IPv4; delete LocalhostSubnet.IPv6; delete LocalhostSubnet.IPv4; delete DNSTarget.IPv6_Multi; delete DNSTarget.IPv4_Multi; //[Data] block(A part) #if defined(ENABLE_PCAP) delete[] ICMP_PaddingData; delete[] DomainTest_Data; #endif //[Data] block(B part) delete[] LocalFQDN_Response; delete LocalFQDN_String; #if !defined(PLATFORM_MACX) delete[] LocalServer_Response; #endif delete[] LocalAddress_Response[0]; delete[] LocalAddress_Response[1U]; #if !defined(PLATFORM_MACX) delete LocalAddress_ResponsePTR[0]; delete LocalAddress_ResponsePTR[1U]; #endif //Global block delete LocalSocket; delete RamdomEngine; delete Path_Global; delete Path_ErrorLog; delete FileList_Hosts; delete FileList_IPFilter; delete[] DomainTable; delete AcceptTypeList; exit(EXIT_FAILURE); return; } //Initialization BufferQueueSize = DEFAULT_BUFFER_QUEUE; //[Data] block(A part) #if defined(ENABLE_PCAP) memset(ICMP_PaddingData, 0, ICMP_PADDING_MAXSIZE); memset(DomainTest_Data, 0, DOMAIN_MAXSIZE); #endif //[Data] block(B part) memset(LocalFQDN_Response, 0, DOMAIN_MAXSIZE); #if !defined(PLATFORM_MACX) memset(LocalServer_Response, 0, DOMAIN_MAXSIZE + sizeof(dns_record_ptr) + sizeof(dns_record_opt)); #endif memset(LocalAddress_Response[0], 0, PACKET_MAXSIZE); memset(LocalAddress_Response[1U], 0, PACKET_MAXSIZE); //Global block memset(DomainTable, 0, strlen(RFC_DOMAIN_TABLE) + 1U); //Default settings strncpy_s(DomainTable, strlen(RFC_DOMAIN_TABLE) + 1U, RFC_DOMAIN_TABLE, strlen(RFC_DOMAIN_TABLE)); std::random_device RamdomDevice; RamdomEngine->seed(RamdomDevice()); //Default values FileRefreshTime = DEFAULT_FILEREFRESH_TIME * SECOND_TO_MILLISECOND; LogMaxSize = DEFAULT_LOG_MAXSIZE; HostsDefaultTTL = DEFAULT_HOSTS_TTL; AlternateTimes = DEFAULT_ALTERNATE_TIMES; AlternateTimeRange = DEFAULT_ALTERNATE_RANGE * SECOND_TO_MILLISECOND; AlternateResetTime = DEFAULT_ALTERNATE_RESET_TIME * SECOND_TO_MILLISECOND; #if defined(PLATFORM_WIN) SocketTimeout_Reliable = DEFAULT_RELIABLE_SOCKET_TIMEOUT; SocketTimeout_Unreliable = DEFAULT_UNRELIABLE_SOCKET_TIMEOUT; #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) SocketTimeout_Reliable.tv_sec = DEFAULT_RELIABLE_SOCKET_TIMEOUT; SocketTimeout_Unreliable.tv_sec = DEFAULT_UNRELIABLE_SOCKET_TIMEOUT; #endif #if defined(PLATFORM_LINUX) Daemon = true; #endif #if defined(ENABLE_PCAP) PcapReadingTimeout = DEFAULT_PCAP_CAPTURE_TIMEOUT; #if defined(PLATFORM_MACX) ICMP_ID = htons(*(uint16_t *)pthread_self()); #else ICMP_ID = htons((uint16_t)GetCurrentProcessId()); //Default ICMP ID is current process ID. #endif ICMP_Sequence = htons(DEFAULT_SEQUENCE); DomainTest_Speed = DEFAULT_DOMAINTEST_INTERVAL_TIME * SECOND_TO_MILLISECOND; #if defined(PLATFORM_MACX) DomainTest_ID = htons(*(uint16_t *)pthread_self()); #else DomainTest_ID = htons((uint16_t)GetCurrentProcessId()); //Default DNS ID is current process ID. #endif #if defined(PLATFORM_WIN) ICMP_PaddingLength = strlen(DEFAULT_PADDING_DATA) + 1U; memcpy_s(ICMP_PaddingData, ICMP_PADDING_MAXSIZE, DEFAULT_PADDING_DATA, Parameter.ICMP_PaddingLength - 1U); //Load default padding data. #elif defined(PLATFORM_LINUX) size_t CharData = ICMP_STRING_START_NUM_LINUX; for (size_t Index = 0;Index < ICMP_PADDING_LENGTH_LINUX;++Index, ++CharData) ICMP_PaddingData[Index] = CharData; ICMP_PaddingLength = strlen(ICMP_PaddingData) + 1U; #elif defined(PLATFORM_MACX) size_t CharData = ICMP_STRING_START_NUM_MAC; for (size_t Index = 0;Index < ICMP_PADDING_LENGTH_MAC;++Index, ++CharData) ICMP_PaddingData[Index] = CharData; ICMP_PaddingLength = strlen(ICMP_PaddingData) + 1U; #endif #endif //Default status GatewayAvailable_IPv4 = true; //Windows XP with SP3 support #if (defined(PLATFORM_WIN32) && !defined(PLATFORM_WIN64)) GetFunctionPointer(FUNCTION_GETTICKCOUNT64); GetFunctionPointer(FUNCTION_INET_NTOP); GetFunctionPointer(FUNCTION_INET_PTON); #endif return; }
void CluiProtocolStatusChanged(int, const char*) { int maxOnline = 0, onlineness = 0; WORD maxStatus = ID_STATUS_OFFLINE; DBVARIANT dbv = { 0 }; int iIcon = 0; HICON hIcon = 0; int rdelta = cfg::dat.bCLeft + cfg::dat.bCRight; BYTE windowStyle; if (pcli->hwndStatus == 0 || cfg::shutDown) return; int protoCount; PROTOACCOUNT **accs; Proto_EnumAccounts(&protoCount, &accs); if (protoCount == 0) return; FreeProtocolData(); g_maxStatus = ID_STATUS_OFFLINE; g_maxProto[0] = 0; int borders[3]; SendMessage(pcli->hwndStatus, SB_GETBORDERS, 0, (LPARAM)&borders); int *partWidths = (int*)_alloca((protoCount + 1)*sizeof(int)); int partCount; if (cfg::dat.bEqualSections) { RECT rc; GetClientRect(pcli->hwndStatus, &rc); rc.right -= borders[0] * 2; int toshow = 0; for (int i = 0; i < protoCount; i++) if (pcli->pfnGetProtocolVisibility(accs[i]->szModuleName)) toshow++; if (toshow > 0) { for (int part = 0, i = 0; i < protoCount; i++) { if (!pcli->pfnGetProtocolVisibility(accs[i]->szModuleName)) continue; partWidths[part] = ((rc.right - rc.left - rdelta) / toshow)*(part + 1) + cfg::dat.bCLeft; if (part == toshow - 1) partWidths[part] += cfg::dat.bCRight; part++; } } partCount = toshow; } else { SIZE textSize; BYTE showOpts = cfg::getByte("CLUI", "SBarShow", 1); TCHAR szName[32]; HDC hdc = GetDC(NULL); HFONT hofont = reinterpret_cast<HFONT>(SelectObject(hdc, (HFONT)SendMessage(pcli->hwndStatus, WM_GETFONT, 0, 0))); // count down since built in ones tend to go at the end partCount = 0; for (int i = 0; i < protoCount; i++) { int idx = pcli->pfnGetAccountIndexByPos(i); if (idx == -1) continue; PROTOACCOUNT *pa = accs[idx]; if (!pcli->pfnGetProtocolVisibility(pa->szModuleName)) continue; int x = 2; if (showOpts & 1) x += 16; if (showOpts & 2) { mir_tstrncpy(szName, pa->tszAccountName, _countof(szName)); szName[_countof(szName) - 1] = 0; if ((showOpts & 4) && mir_tstrlen(szName) < sizeof(szName) - 1) mir_tstrcat(szName, _T(" ")); GetTextExtentPoint32(hdc, szName, (int)mir_tstrlen(szName), &textSize); x += textSize.cx + GetSystemMetrics(SM_CXBORDER) * 4; // The SB panel doesnt allocate enough room } if (showOpts & 4) { TCHAR* modeDescr = pcli->pfnGetStatusModeDescription(CallProtoService(accs[i]->szModuleName, PS_GETSTATUS, 0, 0), 0); GetTextExtentPoint32(hdc, modeDescr, (int)mir_tstrlen(modeDescr), &textSize); x += textSize.cx + GetSystemMetrics(SM_CXBORDER) * 4; // The SB panel doesnt allocate enough room } partWidths[partCount] = (partCount ? partWidths[partCount - 1] : cfg::dat.bCLeft) + x + 2; partCount++; } SelectObject(hdc, hofont); ReleaseDC(NULL, hdc); } if (partCount == 0) { SendMessage(pcli->hwndStatus, SB_SIMPLE, TRUE, 0); return; } SendMessage(pcli->hwndStatus, SB_SIMPLE, FALSE, 0); partWidths[partCount - 1] = -1; windowStyle = cfg::getByte("CLUI", "WindowStyle", 0); SendMessage(pcli->hwndStatus, SB_SETMINHEIGHT, 18 + cfg::dat.bClipBorder + ((windowStyle == SETTING_WINDOWSTYLE_THINBORDER || windowStyle == SETTING_WINDOWSTYLE_NOBORDER) ? 3 : 0), 0); SendMessage(pcli->hwndStatus, SB_SETPARTS, partCount, (LPARAM)partWidths); // count down since built in ones tend to go at the end char *szMaxProto = NULL; partCount = 0; for (int i = 0; i < protoCount; i++) { int idx = pcli->pfnGetAccountIndexByPos(i); if (idx == -1) continue; PROTOACCOUNT *pa = accs[idx]; if (!pcli->pfnGetProtocolVisibility(pa->szModuleName)) continue; int status = CallProtoService(pa->szModuleName, PS_GETSTATUS, 0, 0); ProtocolData *PD = (ProtocolData*)mir_alloc(sizeof(ProtocolData)); PD->RealName = mir_strdup(pa->szModuleName); PD->protopos = partCount; { int flags; flags = SBT_OWNERDRAW; if (cfg::getByte("CLUI", "SBarBevel", 1) == 0) flags |= SBT_NOBORDERS; SendMessageA(pcli->hwndStatus, SB_SETTEXTA, partCount | flags, (LPARAM)PD); } int caps2 = CallProtoService(pa->szModuleName, PS_GETCAPS, PFLAGNUM_2, 0); int caps1 = CallProtoService(pa->szModuleName, PS_GETCAPS, PFLAGNUM_1, 0); if ((caps1 & PF1_IM) && (caps2 & (PF2_LONGAWAY | PF2_SHORTAWAY))) { onlineness = GetStatusOnlineness(status); if (onlineness > maxOnline) { maxStatus = status; maxOnline = onlineness; szMaxProto = pa->szModuleName; } } partCount++; } // update the clui button WORD wStatus = 0; if (!db_get(NULL, "CList", "PrimaryStatus", &dbv)) { if (dbv.type == DBVT_ASCIIZ && mir_strlen(dbv.pszVal) > 1) { wStatus = (WORD)CallProtoService(dbv.pszVal, PS_GETSTATUS, 0, 0); iIcon = IconFromStatusMode(dbv.pszVal, (int)wStatus, 0, &hIcon); } mir_free(dbv.pszVal); } else { wStatus = maxStatus; iIcon = IconFromStatusMode((wStatus >= ID_STATUS_CONNECTING && wStatus < ID_STATUS_OFFLINE) ? szMaxProto : NULL, (int)wStatus, 0, &hIcon); g_maxStatus = (int)wStatus; if (szMaxProto) strncpy_s(g_maxProto, _countof(g_maxProto), szMaxProto, _TRUNCATE); } /* * this is used globally (actually, by the clist control only) to determine if * any protocol is "in connection" state. If true, then the clist discards redraws * and uses timer based sort and redraw handling. This can improve performance * when connecting multiple protocols significantly. */ TCHAR *szStatus = pcli->pfnGetStatusModeDescription(wStatus, 0); /* * set the global status icon and display the global (most online) status mode on the * status mode button */ if (szStatus && pcli->hwndContactList) { HWND hwndClistBtn = GetDlgItem(pcli->hwndContactList, IDC_TBGLOBALSTATUS); if (IsWindow(hwndClistBtn)) { SetWindowText(hwndClistBtn, szStatus); if (!hIcon) SendMessage(hwndClistBtn, BUTTONSETIMLICON, (WPARAM)hCListImages, (LPARAM)iIcon); else SendMessage(hwndClistBtn, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon); InvalidateRect(hwndClistBtn, NULL, TRUE); } HWND hwndTtbStatus = ClcGetButtonWindow(IDC_TBTOPSTATUS); if (IsWindow(hwndTtbStatus)) { if (g_ButtonItems == NULL) { if (!hIcon) SendMessage(hwndTtbStatus, BUTTONSETIMLICON, (WPARAM)hCListImages, (LPARAM)iIcon); else SendMessage(hwndTtbStatus, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon); } InvalidateRect(hwndTtbStatus, NULL, TRUE); } } }
IC void mk_mark(MARK& M, const char* S) { strncpy_s(M, sizeof(M), S, 8); }
// This is the raw NTDS command function. When the remote user // sends a command request for extapi_ntds_parse, this function fires. // It calls the setup routines for our Jet Instance, attaches the isntance // to the NTDS.dit database the user specified, and creates our channel. // The user interacts with the NTDS database through that channel from that point on. DWORD ntds_parse(Remote *remote, Packet *packet) { Packet *response = packet_create_response(packet); DWORD res = ERROR_SUCCESS; struct jetState *ntdsState = calloc(1,sizeof(struct jetState)); PCHAR filePath = packet_get_tlv_value_string(packet, TLV_TYPE_NTDS_PATH); // Check if the File exists if (0xffffffff == GetFileAttributes(filePath)) { res = 2; goto out; } strncpy_s(ntdsState->ntdsPath, 255, filePath, 254); // Attempt to get the SysKey from the Registry unsigned char sysKey[17]; if (!get_syskey(sysKey)) { res = GetLastError(); goto out; } JET_ERR startupStatus = engine_startup(ntdsState); if (startupStatus != JET_errSuccess) { res = startupStatus; goto out; } // Start a Session in the Jet Instance JET_ERR sessionStatus = JetBeginSession(ntdsState->jetEngine, &ntdsState->jetSession, NULL, NULL); if (sessionStatus != JET_errSuccess) { JetTerm(ntdsState->jetEngine); res = sessionStatus; goto out; } JET_ERR openStatus = open_database(ntdsState); if (openStatus != JET_errSuccess) { JetEndSession(ntdsState->jetSession, (JET_GRBIT)NULL); JetTerm(ntdsState->jetEngine); res = openStatus; goto out; } JET_ERR tableStatus = JetOpenTable(ntdsState->jetSession, ntdsState->jetDatabase, "datatable", NULL, 0, JET_bitTableReadOnly | JET_bitTableSequential, &ntdsState->jetTable); if (tableStatus != JET_errSuccess) { engine_shutdown(ntdsState); res = tableStatus; goto out; } // Create the structure for holding all of the Column Definitions we need struct ntdsColumns *accountColumns = calloc(1, sizeof(struct ntdsColumns)); JET_ERR columnStatus = get_column_info(ntdsState, accountColumns); if (columnStatus != JET_errSuccess) { engine_shutdown(ntdsState); free(accountColumns); res = columnStatus; goto out; } JET_ERR pekStatus; struct encryptedPEK *pekEncrypted = calloc(1,sizeof(struct encryptedPEK)); struct decryptedPEK *pekDecrypted = calloc(1,sizeof(struct decryptedPEK)); // Get and Decrypt the Password Encryption Key (PEK) pekStatus = get_PEK(ntdsState, accountColumns, pekEncrypted); if (pekStatus != JET_errSuccess) { res = pekStatus; free(accountColumns); free(pekEncrypted); free(pekDecrypted); engine_shutdown(ntdsState); goto out; } if (!decrypt_PEK(sysKey, pekEncrypted, pekDecrypted)) { res = GetLastError(); free(accountColumns); free(pekEncrypted); free(pekDecrypted); engine_shutdown(ntdsState); goto out; } // Set our Cursor on the first User record JET_ERR cursorStatus = find_first(ntdsState); if (cursorStatus != JET_errSuccess) { res = cursorStatus; free(accountColumns); free(pekEncrypted); free(pekDecrypted); engine_shutdown(ntdsState); goto out; } cursorStatus = next_user(ntdsState, accountColumns); if (cursorStatus != JET_errSuccess) { res = cursorStatus; free(accountColumns); free(pekEncrypted); free(pekDecrypted); engine_shutdown(ntdsState); goto out; } // If we made it this far, it's time to set up our channel PoolChannelOps chops; Channel *newChannel; memset(&chops, 0, sizeof(chops)); NTDSContext *ctx; // Allocate storage for the NTDS context if (!(ctx = calloc(1, sizeof(NTDSContext)))) { res = ERROR_NOT_ENOUGH_MEMORY; free(accountColumns); free(pekEncrypted); free(pekDecrypted); engine_shutdown(ntdsState); goto out; } ctx->accountColumns = accountColumns; ctx->ntdsState = ntdsState; ctx->pekDecrypted = pekDecrypted; // Initialize the pool operation handlers chops.native.context = ctx; chops.native.close = ntds_channel_close; chops.read = ntds_channel_read; if (!(newChannel = channel_create_pool(0, CHANNEL_FLAG_SYNCHRONOUS | CHANNEL_FLAG_COMPRESS, &chops))) { res = ERROR_NOT_ENOUGH_MEMORY; free(accountColumns); free(pekEncrypted); free(pekDecrypted); engine_shutdown(ntdsState); goto out; } channel_set_type(newChannel, "ntds"); packet_add_tlv_uint(response, TLV_TYPE_CHANNEL_ID, channel_get_id(newChannel)); out: packet_transmit_response(res, remote, response); return ERROR_SUCCESS; }
int main(int argc, char* argv[]) { // nice title :) SetConsoleTitle("SzimatSzatyor, WoW injector sniffer"); // some info printf("Welcome to SzimatSzatyor, a WoW injector sniffer.\n"); printf("SzimatSzatyor is distributed under the GNU GPLv3 license.\n"); printf("Source code is available at: "); printf("http://github.com/Konctantin/SzimatSzatyor\n\n"); if (argc > 3) { printf("ERROR: Invalid parameters. "); printf("\"szatyor.exe [wow_exe_name] [dll_name]\" should be used.\n\n"); system("pause"); return 0; } // custom process' name else if (argc > 1) lookingProcessName = argv[1]; else if (argc > 2) injectDLLName = argv[2]; // this process will be injected DWORD processID = 0; // tries to get the PIDs PIDList& pids = GetProcessIDsByName(lookingProcessName); if (pids.empty()) { printf("'%s' process NOT found.\n", lookingProcessName); printf("Note: be sure the process which you looking for "); printf("is must be a 32 bit process.\n\n"); system("pause"); return 0; } // just one PID found else if (pids.size() == 1) { processID = pids.front(); printf("'%s' process found, PID: %u\n", lookingProcessName, processID); // checks this process is already injected or not if (IsProcessAlreadyInjected(processID, injectDLLName)) { printf("Process is already injected.\n\n"); system("pause"); return 0; } } // size > 1, multiple possible processes else { printf("Multiple '%s' processes found.\n", lookingProcessName); printf("Please select one which will be injected.\n\n"); // stores the PIDs which are already injected // so these are "invalid" PIDList injectedPIDs; unsigned int idx = 1; for (PIDList_ConstItr itr = pids.begin(); itr != pids.end(); ++itr) { DWORD pid = *itr; printf("[%u] PID: %u\n", idx++, pid); if (IsProcessAlreadyInjected(pid, injectDLLName)) { printf("Already injected!\n\n"); injectedPIDs.push_back(pid); } } // same size: there is no non-injected PID if (pids.size() == injectedPIDs.size()) { printf("All the processes are already injected.\n\n"); system("pause"); return 0; } unsigned int selectedIndex = 0; // loops until has correct PID while (1) { processID = 0; selectedIndex = 0; printf("Please select a process, use [index]: "); scanf("%u", &selectedIndex); // bigger than max index if (selectedIndex > idx - 1) { printf("Your index is too big, max index is %u.\n", idx - 1); continue; } // 0 or non int used else if (selectedIndex == 0) { printf("Your index is invalid, 1-%u should be used.\n", idx - 1); continue; } // gets PID via index PIDList_ConstItr itr = pids.begin(); std::advance(itr, selectedIndex - 1); processID = *itr; // if already injected if (std::find(injectedPIDs.begin(), injectedPIDs.end(), processID) != injectedPIDs.end()) { printf("This process is already injected. "); printf("Please choose a different one.\n"); continue; } // looks like all good break; } printf("\n"); } // stores where the injector is, so location/path of the current process char injectorPath[MAX_PATH] = { 0 }; // gets where the injector is DWORD injectorPathSize = GetModuleFileName(NULL, injectorPath, MAX_PATH); if (!injectorPathSize) { printf("ERROR: Can't get the injector's path, "); printf("ErrorCode: %u\n\n", GetLastError()); system("pause"); return 0; } // full path of the DLL char* dllPath = new char[MAX_PATH]; // copies injector's full path to dllPath strncpy_s(dllPath, MAX_PATH, injectorPath, injectorPathSize); // some magic to replace path/szatyor.exe to path/szimat.dll // removes injector's name PathRemoveFileSpec(dllPath); // appends DLL's name PathAppend(dllPath, injectDLLName); printf("DLL: %s\n", dllPath); if (InjectDLL(processID, dllPath)) { printf("\nInjection of '%s' is successful.\n\n", injectDLLName); } else { printf("\nInjection of '%s' is NOT successful.\n\n", injectDLLName); system("pause"); } delete[] dllPath; //system("pause"); return 0; }
bool stackcommentget(duint addr, STACK_COMMENT* comment) { SHARED_ACQUIRE(LockSehCache); const auto found = SehCache.find(addr); if(found != SehCache.end()) { *comment = found->second; return true; } SHARED_RELEASE(); duint data = 0; memset(comment, 0, sizeof(STACK_COMMENT)); MemRead(addr, &data, sizeof(duint)); if(!MemIsValidReadPtr(data)) //the stack value is no pointer return false; duint size = 0; duint base = MemFindBaseAddr(data, &size); duint readStart = data - 16 * 4; if(readStart < base) readStart = base; unsigned char disasmData[256]; MemRead(readStart, disasmData, sizeof(disasmData)); duint prev = disasmback(disasmData, 0, sizeof(disasmData), data - readStart, 1); duint previousInstr = readStart + prev; BASIC_INSTRUCTION_INFO basicinfo; bool valid = disasmfast(disasmData + prev, previousInstr, &basicinfo); if(valid && basicinfo.call) //call { char label[MAX_LABEL_SIZE] = ""; ADDRINFO addrinfo; addrinfo.flags = flaglabel; if(_dbg_addrinfoget(data, SEG_DEFAULT, &addrinfo)) strcpy_s(label, addrinfo.label); char module[MAX_MODULE_SIZE] = ""; ModNameFromAddr(data, module, false); char returnToAddr[MAX_COMMENT_SIZE] = ""; if(*module) sprintf(returnToAddr, "%s.", module); if(!*label) sprintf_s(label, "%p", data); strcat(returnToAddr, label); data = basicinfo.addr; if(data) { *label = 0; addrinfo.flags = flaglabel; if(_dbg_addrinfoget(data, SEG_DEFAULT, &addrinfo)) strcpy_s(label, addrinfo.label); *module = 0; ModNameFromAddr(data, module, false); char returnFromAddr[MAX_COMMENT_SIZE] = ""; if(*module) sprintf_s(returnFromAddr, "%s.", module); if(!*label) sprintf_s(label, "%p", data); strcat_s(returnFromAddr, label); sprintf_s(comment->comment, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "return to %s from %s")), returnToAddr, returnFromAddr); } else sprintf_s(comment->comment, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "return to %s from ???")), returnToAddr); strcpy_s(comment->color, "!rtnclr"); // Special token for return address color; return true; } //string char string[MAX_STRING_SIZE] = ""; if(DbgGetStringAt(data, string)) { strncpy_s(comment->comment, string, _TRUNCATE); return true; } //label char label[MAX_LABEL_SIZE] = ""; ADDRINFO addrinfo; addrinfo.flags = flaglabel; if(_dbg_addrinfoget(data, SEG_DEFAULT, &addrinfo)) strcpy_s(label, addrinfo.label); char module[MAX_MODULE_SIZE] = ""; ModNameFromAddr(data, module, false); if(*module) //module { if(*label) //+label sprintf_s(comment->comment, "%s.%s", module, label); else //module only sprintf_s(comment->comment, "%s.%p", module, data); return true; } else if(*label) //label only { sprintf_s(comment->comment, "<%s>", label); return true; } return false; }
DWORD Q4_Get_ServerStatus(SERVER_INFO *pSI,long (*UpdatePlayerListView)(PLAYERDATA *q4players),long (*UpdateRulesListView)(SERVER_RULES *pServRules)) { if(pSI==NULL) { dbg_print("Invalid pointer argument @Get_ServerStatus!\n"); return -1; } SOCKET pSocket = getsockudp(pSI->szIPaddress ,(unsigned short)pSI->usPort); if(pSocket==INVALID_SOCKET) { dbg_print("Error at getsockudp()\n"); return -1; } char sendbuf[]={"\xFF\xFFgetInfo\x00\x01\x00\x00\x00"}; size_t packetlen = 0; //Some default values pSI->dwPing = 9999; //If country shortname is EU or zz (Unknown) try to find a country based on the IP address. if( ((pSI->szShortCountryName[0]=='E') && (pSI->szShortCountryName[1]=='U')) || ((pSI->szShortCountryName[0]=='z') && (pSI->szShortCountryName[1]=='z'))) { char szShortName[4]; g_IPtoCountry.IPtoCountry(pSI->dwIP,szShortName); strncpy_s(pSI->szShortCountryName,sizeof(pSI->szShortCountryName),szShortName,_TRUNCATE); } DWORD dwRetries=0; retry: packetlen = send(pSocket, sendbuf, 14, 0); if(packetlen==SOCKET_ERROR) { dbg_print("Error at send()\n"); closesocket(pSocket); pSI->cPurge++; // pSI->bLocked = FALSE; return -1; } unsigned char *packet=NULL; DWORD dwStartTick=0; dwStartTick = GetTickCount(); packet=(unsigned char*)getpacket(pSocket, &packetlen); if(packet==NULL) { if(dwRetries<AppCFG.dwRetries) { dwRetries++; goto retry; } } if(packet) { pSI->dwPing = (GetTickCount() - dwStartTick); //pSI->cPure=0; //dbg_dumpbuf("dump.bin", packet, packetlen); SERVER_RULES *pServRules=NULL; char *end = (char*)((packet)+packetlen); GetServerLock(pSI); CleanUp_ServerInfo(pSI); char *pCurrPointer=NULL; //will contain the start address for the player data pCurrPointer = Q4_ParseServerRules(pSI,pServRules,(char*)packet,packetlen); pSI->pServerRules = pServRules; if(pServRules!=NULL) { char *szVarValue = NULL; pSI->szServerName = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_SERVERNAME).sRuleValue.c_str(),pSI->pServerRules); pSI->szMap = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_MAP).sRuleValue.c_str(),pSI->pServerRules); pSI->szMod = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_MOD).sRuleValue.c_str(),pSI->pServerRules); pSI->szGameTypeName = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_GAMETYPE).sRuleValue.c_str(),pSI->pServerRules); pSI->szVersion = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_VERSION).sRuleValue.c_str(),pSI->pServerRules); pSI->szFS_GAME = Get_RuleValue("fs_game",pSI->pServerRules); szVarValue= Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_PRIVATE).sRuleValue.c_str(),pSI->pServerRules); if(szVarValue!=NULL) pSI->bPrivate = (char)atoi(szVarValue); if(Get_RuleValue("net_serverPunkbusterEnabled",pServRules)!=NULL) pSI->bPunkbuster = (char)atoi(Get_RuleValue("net_serverPunkbusterEnabled",pServRules)); else if(Get_RuleValue("sv_punkbuster",pServRules)!=NULL) pSI->bPunkbuster = (char)atoi(Get_RuleValue("sv_punkbuster",pServRules)); PLAYERDATA *pQ4Players=NULL; DWORD nPlayers=0; //--------------------------------- //Retrieve players if any exsist... //--------------------------------- pQ4Players = Q4_ParsePlayers(pSI,pCurrPointer,end,&nPlayers); pSI->pPlayerData = pQ4Players; //----------------------------------- //Update server info from rule values //----------------------------------- time(&pSI->timeLastScan); pSI->bUpdated = 1; pSI->nPlayers = nPlayers; pSI->cPurge = 0; if(Get_RuleValue("si_maxPlayers",pServRules)!=NULL) pSI->nMaxPlayers = atoi(Get_RuleValue("si_maxPlayers",pServRules)); // if(Get_RuleValue("si_tv",pServRules)!=NULL) // pSI->bTV = atoi(Get_RuleValue("si_tv",pServRules)); if(Get_RuleValue("si_privatePlayers",pServRules)!=NULL) pSI->nPrivateClients = atoi(Get_RuleValue("si_privatePlayers",pServRules)); else if(Get_RuleValue("si_privateClients",pServRules)!=NULL) //ETQW { pSI->nPrivateClients = atoi(Get_RuleValue("si_privateClients",pServRules)); pSI->nMaxPlayers -= pSI->nPrivateClients; } } //end if(pServRules!=NULL) ReleaseServerLock(pSI); if(Q4_Callback_CheckForBuddy!=NULL) Q4_Callback_CheckForBuddy(pSI->pPlayerData,pSI); free(packet); } //end if(packet) else pSI->cPurge++; if(UpdatePlayerListView!=NULL) UpdatePlayerListView(pSI->pPlayerData); if(UpdateRulesListView!=NULL) UpdateRulesListView(pSI->pServerRules); //pSI->bLocked = FALSE; closesocket(pSocket); return 0; }
void RegBash(void) { char chbuf[BufLen]; //读取数据 char NewStr[BufLen]; //转编码缓存 char RootPath[BufLen]; //cygwin安装路径 char BinPath[BufLen]; //cygwin安装的bin目录 char IcoPath[BufLen]; //cygwin的图标位置 int NewLen = 0; //转编码后的具体长度 HKEY hkey; DWORD type = 0; DWORD len = BufLen; //每次读内容时len都要重置为BufLen一次 memset(chbuf, '\0', BufLen); // 获取cygwin安装路径 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Cygnus Solutions\\Cygwin\\mounts v2\\/"), 0, KEY_ALL_ACCESS, &hkey) == ERROR_SUCCESS) { len = BufLen; if (RegQueryValueEx(hkey, _T("native"), NULL, &type, (LPBYTE)chbuf, &len)) { printf("have error!"); } memset(RootPath, '\0', BufLen); UnicodetoANSI(chbuf, RootPath, len); strncpy_s(BinPath ,RootPath, BufLen); strncpy_s(IcoPath ,RootPath, BufLen); strcat_s(IcoPath, "\\Cygwin.ico,0"); RegCloseKey(hkey); } // 写入注册表信息 DWORD Disposition; len = BufLen; // 创建键 try { RegCreateKeyEx(HKEY_CLASSES_ROOT, _T(".sh"), NULL, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hkey, &Disposition); RegCreateKeyEx(HKEY_CLASSES_ROOT, _T("ybtx_bash\\DefaultIcon"), NULL, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hkey, &Disposition); RegCreateKeyEx(HKEY_CLASSES_ROOT, _T("ybtx_bash\\shell"), NULL, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hkey, &Disposition); RegCreateKeyEx(HKEY_CLASSES_ROOT, _T("ybtx_bash\\shell\\open"), NULL, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hkey, &Disposition); RegCreateKeyEx(HKEY_CLASSES_ROOT, _T("ybtx_bash\\shell\\open\\command"), NULL, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hkey, &Disposition); } catch(...) { printf("Create new key error!"); } memset(NewStr, '\0', BufLen); NewLen = ANSItoUnicode("ybtx_bash", NewStr); if (RegOpenKeyEx(HKEY_CLASSES_ROOT, _T(".sh"), 0, KEY_ALL_ACCESS, &hkey) == ERROR_SUCCESS) { RegSetValueEx(hkey, NULL, NULL, REG_SZ, (LPBYTE)NewStr, NewLen); RegCloseKey(hkey); } memset(NewStr, '\0', BufLen); NewLen = ANSItoUnicode(IcoPath, NewStr); if (RegOpenKeyEx(HKEY_CLASSES_ROOT, _T("ybtx_bash\\DefaultIcon"), 0, KEY_ALL_ACCESS, &hkey) == ERROR_SUCCESS) { RegSetValueEx(hkey, NULL, NULL, REG_SZ, (LPBYTE)NewStr, NewLen); RegCloseKey(hkey); } memset(NewStr, '\0', BufLen); NewLen = ANSItoUnicode("open", NewStr); if (RegOpenKeyEx(HKEY_CLASSES_ROOT, _T("ybtx_bash\\shell"), 0, KEY_ALL_ACCESS, &hkey) == ERROR_SUCCESS) { RegSetValueEx(hkey, NULL, NULL, REG_SZ, (LPBYTE)NewStr, NewLen); RegCloseKey(hkey); } memset(NewStr, '\0', BufLen); char* command = "\\bin\\bash.exe --login -c \"f='%1';f=${f//\\\\//};cd \\\"$(dirname \\\"$f\\\")\\\";bash \\\"$(basename \\\"$f\\\")\\\";unset f\""; strcat_s(BinPath, command); NewLen = ANSItoUnicode(BinPath, NewStr); if (RegOpenKeyEx(HKEY_CLASSES_ROOT, _T("ybtx_bash\\shell\\open\\command"), 0, KEY_ALL_ACCESS, &hkey) == ERROR_SUCCESS) { RegSetValueEx(hkey, NULL, NULL, REG_SZ, (LPBYTE)NewStr, NewLen); RegCloseKey(hkey); } printf("文件关联完毕!"); }
str_t* WelsStrncpy(str_t * pDest, int32_t iSizeInBytes, const str_t * kpSrc, int32_t iCount) { strncpy_s(pDest, iSizeInBytes, kpSrc, iCount); return pDest; }
void Profile::init(const char* profileName) { char file[_MAX_FNAME+MAX_PATH], difficulty[10], _maxLoginTime[10], _maxCharTime[10], mode[256]; int tmp; if(profileName == NULL) throw "Can't open null profile name."; if(profileName[0] == '\0') throw "Can't open empty profile name."; sprintf_s(file, sizeof(file), "%sd2bs.ini", Vars.szPath); GetPrivateProfileString(profileName, "mode", "single", mode, sizeof(mode), file); GetPrivateProfileString(profileName, "character", "ERROR", charname, sizeof(charname), file); GetPrivateProfileString(profileName, "spdifficulty", "0", difficulty, sizeof(difficulty), file); GetPrivateProfileString(profileName, "username", "ERROR", username, sizeof(username), file); GetPrivateProfileString(profileName, "password", "ERROR", password, sizeof(password), file); GetPrivateProfileString(profileName, "gateway", "ERROR", gateway, sizeof(gateway), file); GetPrivateProfileString("settings", "MaxLoginTime", "5", _maxLoginTime, sizeof(maxLoginTime), file); GetPrivateProfileString("settings", "MaxCharSelectTime", "5", _maxCharTime, sizeof(maxCharTime), file); maxLoginTime = abs(atoi(_maxLoginTime) * 1000); maxCharTime = abs(atoi(_maxCharTime) * 1000); tmp = atoi(difficulty); if(tmp < 0 || tmp > 2) throw "Invalid difficulty."; diff = (char)tmp; type = PROFILETYPE_INVALID; switch(tolower(mode[0])) { case 's': type = PROFILETYPE_SINGLEPLAYER; break; case 'b': type = PROFILETYPE_BATTLENET; break; case 'o': switch(tolower(mode[18])) { case 'o': type = PROFILETYPE_OPEN_BATTLENET; break; case 't': switch(tolower(mode[25])) { case 'h': type = PROFILETYPE_TCPIP_HOST; break; case 'j': type = PROFILETYPE_TCPIP_JOIN; strncpy_s (ip, &mode[30], (size_t)16); break; } break; } break; } }
errno_t PLAT_strncpy( char *dest, const char *src, rsize_t max ) { return strncpy_s( dest, max+1, src, _TRUNCATE ); }
void CBuddyManager::NotifyBuddyIsOnline(BUDDY_INFO *pBI, SERVER_INFO *pServerInfo) { if(pBI==NULL) return; if(pServerInfo==NULL) return; vecBI::iterator it = FindBuddyInfoByID(pBI->dwID); if(it==BuddyList.end()) return; if(pServerInfo->szServerName!=NULL) strncpy_s(it->szServerName,sizeof(pBI->szServerName),pServerInfo->szServerName,_TRUNCATE); it->cGAMEINDEX = pServerInfo->cGAMEINDEX; it->sIndex = (int) pServerInfo->dwIndex; //have to change the Buddy index to a new var that can hold bigger numbers such as DWORD HWND hwndLV = g_hwndListBuddy; LV_FINDINFO lvfi; char szText[250]; memset(&lvfi,0,sizeof(LV_FINDINFO)); lvfi.flags = LVFI_PARAM; lvfi.lParam = (LPARAM)pBI->dwID; int index = ListView_FindItem(hwndLV , -1, &lvfi); if(index!=-1) { LVITEM item; item.mask = LVIF_TEXT | LVIF_IMAGE; item.iItem = index; memset(szText,0,sizeof(szText)); if(gm.GamesInfo[it->cGAMEINDEX].colorfilter!=NULL) { gm.GamesInfo[it->cGAMEINDEX].colorfilter(it->szServerName,szText,249); item.pszText = szText; item.cchTextMax = (int)strlen(szText); } else { item.pszText = it->szServerName; item.cchTextMax = (int)strlen(it->szServerName); } item.iSubItem = 1; item.iImage = gm.Get_GameIcon(it->cGAMEINDEX); ListView_SetItem(g_hwndListBuddy,&item); sprintf_s(szText,"%s:%d",pServerInfo->szIPaddress,pServerInfo->usPort); strcpy_s(it->szIPaddress,szText); ListView_SetItemText(g_hwndListBuddy,index ,2,szText); } if(gm.GamesInfo[it->cGAMEINDEX].colorfilter!=NULL) gm.GamesInfo[it->cGAMEINDEX].colorfilter(it->szServerName,szText,249); else strcpy_s(szText,it->szPlayerName); if(g_bRunningQueryServerList && g_bPlayedNotify==false) PlayNotifySound(0 ); if(AppCFG.bBuddyNotify) ShowBalloonTip("A buddy is online!",szText); }
bool CMountProg::GetPath(char **returnPath) { unsigned long i, nSize; static char path[MAXPATHLEN + 1]; static char finalPath[MAXPATHLEN + 1]; bool foundPath = false; m_pInStream->Read(&nSize); if (nSize > MAXPATHLEN) { nSize = MAXPATHLEN; } typedef std::map<std::string, std::string>::iterator it_type; m_pInStream->Read(path, nSize); for (it_type iterator = m_PathMap.begin(); iterator != m_PathMap.end(); iterator++) { char* pathAlias = const_cast<char*>(iterator->first.c_str()); char* windowsPath = const_cast<char*>(iterator->second.c_str()); size_t aliasPathSize = strlen(pathAlias); size_t windowsPathSize = strlen(windowsPath); size_t requestedPathSize = nSize; if ((requestedPathSize < windowsPathSize) && (strncmp(path, pathAlias, aliasPathSize) == 0)) { foundPath = true; //The requested path starts with the alias. Let's replace the alias with the real path strncpy_s(finalPath, windowsPath, sizeof(finalPath)); //strncpy_s(finalPath + windowsPathSize, (path + aliasPathSize), (sizeof(finalPath)-windowsPathSize)); finalPath[windowsPathSize + requestedPathSize - aliasPathSize] = '\0'; for (i = 0; i < requestedPathSize; i++) { //transform path to Windows format if (finalPath[windowsPathSize + i] == '/') { finalPath[windowsPathSize + i] = '\\'; } } } else if ((strlen(path) == strlen(pathAlias)) && (strncmp(path, pathAlias, aliasPathSize) == 0)) { foundPath = true; //The requested path IS the alias strncpy_s(finalPath, windowsPath, sizeof(finalPath)); finalPath[windowsPathSize] = '\0'; } else if ((strlen(path) == strlen(windowsPath)) && (strncmp(path, pathAlias, windowsPathSize) == 0)) { foundPath = true; //The requested path does not start with the alias, let's treat it normally strncpy_s(finalPath, path, sizeof(finalPath)); finalPath[0] = finalPath[1]; //transform mount path to Windows format finalPath[1] = ':'; for (i = 2; i < nSize; i++) { if (finalPath[i] == '/') { finalPath[i] = '\\'; } } finalPath[nSize] = '\0'; } if (foundPath == true) { break; } } PrintLog("Final local requested path: %s\n", finalPath); if ((nSize & 3) != 0) { m_pInStream->Read(&i, 4 - (nSize & 3)); //skip opaque bytes } *returnPath = finalPath; return foundPath; }
void __stdcall RVExtension(char *output, int outputSize, const char *function) { ZERO_OUTPUT(); std::stringstream outputStr; if (!strcmp(function, "version")) { strncpy_s(output, outputSize, ACE_FULL_VERSION_STR, _TRUNCATE); EXTENSION_RETURN(); } char* input = _strdup(function); char* token = NULL; char* next_token = NULL; char* mode = strtok_s(input, ":", &next_token); if (!strcmp(mode, "retard")) { double ballisticCoefficient = 1.0; int dragModel = 1; double velocity = 0.0; double retard = 0.0; dragModel = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); ballisticCoefficient = strtod(strtok_s(NULL, ":", &next_token), NULL); velocity = strtod(strtok_s(NULL, ":", &next_token), NULL); retard = calculateRetard(dragModel, ballisticCoefficient, velocity); // int n = sprintf(output, "%f", retard); outputStr << retard; strncpy_s(output, outputSize, outputStr.str().c_str(), _TRUNCATE); EXTENSION_RETURN(); } else if (!strcmp(mode, "atmosphericCorrection")) { double ballisticCoefficient = 1.0; double temperature = 15.0; double pressure = 1013.25; double humidity = 0.0; char* atmosphereModel; ballisticCoefficient = strtod(strtok_s(NULL, ":", &next_token), NULL); temperature = strtod(strtok_s(NULL, ":", &next_token), NULL); pressure = strtod(strtok_s(NULL, ":", &next_token), NULL); humidity = strtod(strtok_s(NULL, ":", &next_token), NULL); atmosphereModel = strtok_s(NULL, ":", &next_token); ballisticCoefficient = calculateAtmosphericCorrection(ballisticCoefficient, temperature, pressure, humidity, atmosphereModel); //int n = sprintf(output, "%f", ballisticCoefficient); outputStr << ballisticCoefficient; strncpy_s(output, outputSize, outputStr.str().c_str(), _TRUNCATE); EXTENSION_RETURN(); } else if (!strcmp(mode, "new")) { unsigned int index = 0; double airFriction = 0.0; char* ballisticCoefficientArray; char* ballisticCoefficient; std::vector<double> ballisticCoefficients; char* velocityBoundaryArray; char* velocityBoundary; std::vector<double> velocityBoundaries; char* atmosphereModel; int dragModel = 1; double stabilityFactor = 1.5; int twistDirection = 1; double transonicStabilityCoef = 1; double muzzleVelocity = 850; char* originArray; char* originEntry; std::vector<double> origin; double latitude = 0.0; double temperature = 0.0; double altitude = 0.0; double humidity = 0.0; double overcast = 0.0; double tickTime = 0.0; index = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); airFriction = strtod(strtok_s(NULL, ":", &next_token), NULL); ballisticCoefficientArray = strtok_s(NULL, ":", &next_token); ballisticCoefficientArray++; ballisticCoefficientArray[strlen(ballisticCoefficientArray) - 1] = 0; ballisticCoefficient = strtok_s(ballisticCoefficientArray, ",", &token); while (ballisticCoefficient != NULL) { ballisticCoefficients.push_back(strtod(ballisticCoefficient, NULL)); ballisticCoefficient = strtok_s(NULL, ",", &token); } velocityBoundaryArray = strtok_s(NULL, ":", &next_token); velocityBoundaryArray++; velocityBoundaryArray[strlen(velocityBoundaryArray) - 1] = 0; velocityBoundary = strtok_s(velocityBoundaryArray, ",", &token); while (velocityBoundary != NULL) { velocityBoundaries.push_back(strtod(velocityBoundary, NULL)); velocityBoundary = strtok_s(NULL, ",", &token); } atmosphereModel = strtok_s(NULL, ":", &next_token); dragModel = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); stabilityFactor = strtod(strtok_s(NULL, ":", &next_token), NULL); twistDirection = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); muzzleVelocity = strtod(strtok_s(NULL, ":", &next_token), NULL); transonicStabilityCoef = strtod(strtok_s(NULL, ":", &next_token), NULL); originArray = strtok_s(NULL, ":", &next_token); originArray++; originArray[strlen(originArray) - 1] = 0; originEntry = strtok_s(originArray, ",", &token); while (originEntry != NULL) { origin.push_back(strtod(originEntry, NULL)); originEntry = strtok_s(NULL, ",", &token); } latitude = strtod(strtok_s(NULL, ":", &next_token), NULL); temperature = strtod(strtok_s(NULL, ":", &next_token), NULL); altitude = strtod(strtok_s(NULL, ":", &next_token), NULL); humidity = strtod(strtok_s(NULL, ":", &next_token), NULL); overcast = strtod(strtok_s(NULL, ":", &next_token), NULL); tickTime = strtod(strtok_s(NULL, ":", &next_token), NULL); tickTime += strtod(strtok_s(NULL, ":", &next_token), NULL); while (index >= bulletDatabase.size()) { Bullet bullet; bulletDatabase.push_back(bullet); } bulletDatabase[index].airFriction = airFriction; bulletDatabase[index].ballisticCoefficients = ballisticCoefficients; bulletDatabase[index].velocityBoundaries = velocityBoundaries; bulletDatabase[index].atmosphereModel = atmosphereModel; bulletDatabase[index].dragModel = dragModel; bulletDatabase[index].stabilityFactor = stabilityFactor; bulletDatabase[index].twistDirection = twistDirection; bulletDatabase[index].transonicStabilityCoef = transonicStabilityCoef; bulletDatabase[index].muzzleVelocity = muzzleVelocity; bulletDatabase[index].origin = origin; bulletDatabase[index].latitude = latitude / 180 * M_PI; bulletDatabase[index].temperature = temperature; bulletDatabase[index].altitude = altitude; bulletDatabase[index].humidity = humidity; bulletDatabase[index].overcast = overcast; bulletDatabase[index].startTime = tickTime; bulletDatabase[index].lastFrame = tickTime; bulletDatabase[index].bcDegradation = 1.0; bulletDatabase[index].randSeed = 0; strncpy_s(output, outputSize, "", _TRUNCATE); EXTENSION_RETURN(); } else if (!strcmp(mode, "simulate")) { // simulate:0:[-0.109985,542.529,-3.98301]:[3751.57,5332.23,214.252]:[0.598153,2.38829,0]:28.6:0:0.481542:0:215.16 unsigned int index = 0; char* velocityArray; double velocity[3] = { 0.0, 0.0, 0.0 }; char* positionArray; double position[3] = { 0.0, 0.0, 0.0 }; char* windArray; double wind[3]; double heightAGL = 0.0; double tickTime = 0.0; index = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); velocityArray = strtok_s(NULL, ":", &next_token); velocityArray++; velocityArray[strlen(velocityArray) - 1] = 0; velocity[0] = strtod(strtok_s(velocityArray, ",", &token), NULL); velocity[1] = strtod(strtok_s(NULL, ",", &token), NULL); velocity[2] = strtod(strtok_s(NULL, ",", &token), NULL); positionArray = strtok_s(NULL, ":", &next_token); positionArray++; positionArray[strlen(positionArray) - 1] = 0; position[0] = strtod(strtok_s(positionArray, ",", &token), NULL); position[1] = strtod(strtok_s(NULL, ",", &token), NULL); position[2] = strtod(strtok_s(NULL, ",", &token), NULL); windArray = strtok_s(NULL, ":", &next_token); windArray++; windArray[strlen(windArray) - 1] = 0; wind[0] = strtod(strtok_s(windArray, ",", &token), NULL); wind[1] = strtod(strtok_s(NULL, ",", &token), NULL); wind[2] = strtod(strtok_s(NULL, ",", &token), NULL); heightAGL = strtod(strtok_s(NULL, ":", &next_token), NULL); tickTime = strtod(strtok_s(NULL, ":", &next_token), NULL); tickTime += strtod(strtok_s(NULL, ":", &next_token), NULL); if (bulletDatabase[index].randSeed == 0) { int angle = (int)round(atan2(velocity[0], velocity[1]) * 360 / M_PI); bulletDatabase[index].randSeed = (unsigned)(720 + angle) % 720; bulletDatabase[index].randSeed *= 3; bulletDatabase[index].randSeed += (unsigned)round(abs(velocity[2]) / 2); bulletDatabase[index].randSeed *= 3; bulletDatabase[index].randSeed += (unsigned)round(abs(bulletDatabase[index].origin[0] / 2)); bulletDatabase[index].randSeed *= 3; bulletDatabase[index].randSeed += (unsigned)round(abs(bulletDatabase[index].origin[1] / 2)); bulletDatabase[index].randSeed *= 3; bulletDatabase[index].randSeed += (unsigned)abs(bulletDatabase[index].temperature) * 10; bulletDatabase[index].randSeed *= 3; bulletDatabase[index].randSeed += (unsigned)abs(bulletDatabase[index].humidity) * 10; bulletDatabase[index].randGenerator.seed(bulletDatabase[index].randSeed); } double ballisticCoefficient = 1.0; double dragRef = 0.0; double drag = 0.0; double accelRef[3] = { 0.0, 0.0, 0.0 }; double accel[3] = { 0.0, 0.0, 0.0 }; double TOF = 0.0; double deltaT = 0.0; double bulletSpeed; double trueVelocity[3] = { 0.0, 0.0, 0.0 }; double trueSpeed = 0.0; double temperature = 0.0; double pressure = 1013.25; double windSpeed = 0.0; double windAttenuation = 1.0; double velocityOffset[3] = { 0.0, 0.0, 0.0 }; TOF = tickTime - bulletDatabase[index].startTime; deltaT = tickTime - bulletDatabase[index].lastFrame; bulletDatabase[index].lastFrame = tickTime; bulletSpeed = sqrt(pow(velocity[0], 2) + pow(velocity[1], 2) + pow(velocity[2], 2)); windSpeed = sqrt(pow(wind[0], 2) + pow(wind[1], 2) + pow(wind[2], 2)); if (windSpeed > 0.1) { double windSourceTerrain[3]; windSourceTerrain[0] = position[0] - wind[0] / windSpeed * 100; windSourceTerrain[1] = position[1] - wind[1] / windSpeed * 100; windSourceTerrain[2] = position[2] - wind[2] / windSpeed * 100; int gridX = (int)floor(windSourceTerrain[0] / 50); int gridY = (int)floor(windSourceTerrain[1] / 50); int gridCell = gridX * map->mapGrids + gridY; if (gridCell >= 0 && (std::size_t)gridCell < map->gridHeights.size() && (std::size_t)gridCell < map->gridBuildingNums.size()) { double gridHeight = map->gridHeights[gridCell]; if (gridHeight > position[2]) { double angle = atan((gridHeight - position[2]) / 100); windAttenuation *= pow(abs(cos(angle)), 2); } } } if (windSpeed > 0.1) { double windSourceObstacles[3]; windSourceObstacles[0] = position[0] - wind[0] / windSpeed * 25; windSourceObstacles[1] = position[1] - wind[1] / windSpeed * 25; windSourceObstacles[2] = position[2] - wind[2] / windSpeed * 25; if (heightAGL > 0 && heightAGL < 20) { double roughnessLength = calculateRoughnessLength(windSourceObstacles[0], windSourceObstacles[1]); windAttenuation *= abs(log(heightAGL / roughnessLength) / log(20 / roughnessLength)); } } if (windAttenuation < 1) { wind[0] *= windAttenuation; wind[1] *= windAttenuation; wind[2] *= windAttenuation; windSpeed = sqrt(pow(wind[0], 2) + pow(wind[1], 2) + pow(wind[2], 2)); } trueVelocity[0] = velocity[0] - wind[0]; trueVelocity[1] = velocity[1] - wind[1]; trueVelocity[2] = velocity[2] - wind[2]; trueSpeed = sqrt(pow(trueVelocity[0], 2) + pow(trueVelocity[1], 2) + pow(trueVelocity[2], 2)); double speedOfSound = 331.3 + (0.6 * temperature); double transonicSpeed = 394 + (0.6 * temperature); if (bulletDatabase[index].transonicStabilityCoef < 1.0f && bulletSpeed < transonicSpeed && bulletSpeed > speedOfSound) { std::uniform_real_distribution<double> distribution(-10.0, 10.0); double coef = 1.0f - bulletDatabase[index].transonicStabilityCoef; trueVelocity[0] += distribution(bulletDatabase[index].randGenerator) * coef; trueVelocity[1] += distribution(bulletDatabase[index].randGenerator) * coef; trueVelocity[2] += distribution(bulletDatabase[index].randGenerator) * coef; double speed = sqrt(pow(trueVelocity[0], 2) + pow(trueVelocity[1], 2) + pow(trueVelocity[2], 2)); trueVelocity[0] *= trueSpeed / speed; trueVelocity[1] *= trueSpeed / speed; trueVelocity[2] *= trueSpeed / speed; bulletDatabase[index].bcDegradation *= pow(0.993, coef); }; temperature = bulletDatabase[index].temperature - 0.0065 * position[2]; pressure = (1013.25 - 10 * bulletDatabase[index].overcast) * pow(1 - (0.0065 * (bulletDatabase[index].altitude + position[2])) / (273.15 + temperature + 0.0065 * bulletDatabase[index].altitude), 5.255754495); if (bulletDatabase[index].ballisticCoefficients.size() == bulletDatabase[index].velocityBoundaries.size() + 1) { dragRef = deltaT * bulletDatabase[index].airFriction * bulletSpeed * bulletSpeed; accelRef[0] = (velocity[0] / bulletSpeed) * dragRef; accelRef[1] = (velocity[1] / bulletSpeed) * dragRef; accelRef[2] = (velocity[2] / bulletSpeed) * dragRef; velocityOffset[0] -= accelRef[0]; velocityOffset[1] -= accelRef[1]; velocityOffset[2] -= accelRef[2]; ballisticCoefficient = bulletDatabase[index].ballisticCoefficients[0]; for (int i = (int)bulletDatabase[index].velocityBoundaries.size() - 1; i >= 0; i = i - 1) { if (bulletSpeed < bulletDatabase[index].velocityBoundaries[i]) { ballisticCoefficient = bulletDatabase[index].ballisticCoefficients[i + 1]; break; } } ballisticCoefficient = calculateAtmosphericCorrection(ballisticCoefficient, temperature, pressure, bulletDatabase[index].humidity, bulletDatabase[index].atmosphereModel); ballisticCoefficient *= bulletDatabase[index].bcDegradation; drag = deltaT * calculateRetard(bulletDatabase[index].dragModel, ballisticCoefficient, trueSpeed); accel[0] = (trueVelocity[0] / trueSpeed) * drag; accel[1] = (trueVelocity[1] / trueSpeed) * drag; accel[2] = (trueVelocity[2] / trueSpeed) * drag; velocityOffset[0] -= accel[0]; velocityOffset[1] -= accel[1]; velocityOffset[2] -= accel[2]; } else { double airDensity = calculateAirDensity(temperature, pressure, bulletDatabase[index].humidity); double airFriction = bulletDatabase[index].airFriction * airDensity / STD_AIR_DENSITY_ICAO; if (airFriction != bulletDatabase[index].airFriction || windSpeed > 0) { dragRef = deltaT * bulletDatabase[index].airFriction * bulletSpeed * bulletSpeed; accelRef[0] = (velocity[0] / bulletSpeed) * dragRef; accelRef[1] = (velocity[1] / bulletSpeed) * dragRef; accelRef[2] = (velocity[2] / bulletSpeed) * dragRef; velocityOffset[0] -= accelRef[0]; velocityOffset[1] -= accelRef[1]; velocityOffset[2] -= accelRef[2]; drag = deltaT * airFriction * trueSpeed * trueSpeed; accel[0] = (trueVelocity[0] / trueSpeed) * drag; accel[1] = (trueVelocity[1] / trueSpeed) * drag; accel[2] = (trueVelocity[2] / trueSpeed) * drag; velocityOffset[0] += accel[0]; velocityOffset[1] += accel[1]; velocityOffset[2] += accel[2]; } } if (TOF > 0) { double bulletDir = atan2(velocity[0], velocity[1]); double spinAccel = bulletDatabase[index].twistDirection * (0.0482251 * (bulletDatabase[index].stabilityFactor + 1.2)) / pow(TOF, 0.17); velocityOffset[0] += sin(bulletDir + M_PI / 2) * spinAccel * deltaT; velocityOffset[1] += cos(bulletDir + M_PI / 2) * spinAccel * deltaT; } double lat = bulletDatabase[index].latitude; accel[0] = 2 * EARTH_ANGULAR_SPEED * +(velocity[1] * sin(lat) - velocity[2] * cos(lat)); accel[1] = 2 * EARTH_ANGULAR_SPEED * -(velocity[0] * sin(lat)); accel[2] = 2 * EARTH_ANGULAR_SPEED * +(velocity[0] * cos(lat)); velocityOffset[0] += accel[0] * deltaT; velocityOffset[1] += accel[1] * deltaT; velocityOffset[2] += accel[2] * deltaT; outputStr << "_bullet setVelocity (_bulletVelocity vectorAdd [" << velocityOffset[0] << "," << velocityOffset[1] << "," << velocityOffset[2] << "]);"; strncpy_s(output, outputSize, outputStr.str().c_str(), _TRUNCATE); EXTENSION_RETURN(); } else if (!strcmp(mode, "set")) { int height = 0; int numObjects = 0; int surfaceIsWater = 0; height = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); numObjects = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); surfaceIsWater = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); map->gridHeights.push_back(height); map->gridBuildingNums.push_back(numObjects); map->gridSurfaceIsWater.push_back(surfaceIsWater); strncpy_s(output, outputSize, outputStr.str().c_str(), _TRUNCATE); EXTENSION_RETURN(); } else if (!strcmp(mode, "init")) { int mapSize = 0; int mapGrids = 0; unsigned int gridCells = 0; worldName = strtok_s(NULL, ":", &next_token); mapSize = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); mapGrids = (int)ceil((double)mapSize / 50.0) + 1; gridCells = mapGrids * mapGrids; map = &mapDatabase[worldName]; if (map->gridHeights.size() == gridCells) { outputStr << "Terrain already initialized"; strncpy_s(output, outputSize, outputStr.str().c_str(), _TRUNCATE); EXTENSION_RETURN(); } map->mapSize = mapSize; map->mapGrids = mapGrids; map->gridHeights.clear(); map->gridBuildingNums.clear(); map->gridSurfaceIsWater.clear(); map->gridHeights.reserve(gridCells); map->gridBuildingNums.reserve(gridCells); map->gridSurfaceIsWater.reserve(gridCells); strncpy_s(output, outputSize, outputStr.str().c_str(), _TRUNCATE); EXTENSION_RETURN(); } else if (!strcmp(mode, "zeroAngleVanilla")) { double zeroRange = strtod(strtok_s(NULL, ":", &next_token), NULL); double initSpeed = strtod(strtok_s(NULL, ":", &next_token), NULL); double airFriction = strtod(strtok_s(NULL, ":", &next_token), NULL); double boreHeight = strtod(strtok_s(NULL, ":", &next_token), NULL); double zeroAngle = calculateVanillaZeroAngle(zeroRange, initSpeed, airFriction, boreHeight); outputStr << DEGREES(zeroAngle); strncpy_s(output, outputSize, outputStr.str().c_str(), _TRUNCATE); EXTENSION_RETURN(); } else if (!strcmp(mode, "zeroAngle")) { double zeroRange = strtod(strtok_s(NULL, ":", &next_token), NULL); double muzzleVelocity = strtod(strtok_s(NULL, ":", &next_token), NULL); double boreHeight = strtod(strtok_s(NULL, ":", &next_token), NULL); double temperature = strtod(strtok_s(NULL, ":", &next_token), NULL); double pressure = strtod(strtok_s(NULL, ":", &next_token), NULL); double humidity = strtod(strtok_s(NULL, ":", &next_token), NULL); double ballisticCoefficient = strtod(strtok_s(NULL, ":", &next_token), NULL); int dragModel = strtol(strtok_s(NULL, ":", &next_token), NULL, 10); char* atmosphereModel = strtok_s(NULL, ":", &next_token); double zeroAngle = calculateZeroAngle(zeroRange, muzzleVelocity, boreHeight, temperature, pressure, humidity, ballisticCoefficient, dragModel, atmosphereModel); outputStr << DEGREES(zeroAngle); strncpy_s(output, outputSize, outputStr.str().c_str(), _TRUNCATE); EXTENSION_RETURN(); } strncpy_s(output, outputSize, outputStr.str().c_str(), _TRUNCATE); EXTENSION_RETURN(); }
int CDbxKV::GetContactSettingWorker(MCONTACT contactID, LPCSTR szModule, LPCSTR szSetting, DBVARIANT *dbv, int isStatic) { if (szSetting == NULL || szModule == NULL) return 1; // the db format can't tolerate more than 255 bytes of space (incl. null) for settings+module name int settingNameLen = (int)strlen(szSetting); int moduleNameLen = (int)strlen(szModule); if (settingNameLen > 0xFE) { #ifdef _DEBUG OutputDebugStringA("GetContactSettingWorker() got a > 255 setting name length. \n"); #endif return 1; } if (moduleNameLen > 0xFE) { #ifdef _DEBUG OutputDebugStringA("GetContactSettingWorker() got a > 255 module name length. \n"); #endif return 1; } mir_cslock lck(m_csDbAccess); LBL_Seek: char *szCachedSettingName = m_cache->GetCachedSetting(szModule, szSetting, moduleNameLen, settingNameLen); DBVARIANT *pCachedValue = m_cache->GetCachedValuePtr(contactID, szCachedSettingName, 0); if (pCachedValue != NULL) { if (pCachedValue->type == DBVT_ASCIIZ || pCachedValue->type == DBVT_UTF8) { int cbOrigLen = dbv->cchVal; char *cbOrigPtr = dbv->pszVal; memcpy(dbv, pCachedValue, sizeof(DBVARIANT)); if (isStatic) { int cbLen = 0; if (pCachedValue->pszVal != NULL) cbLen = (int)strlen(pCachedValue->pszVal); cbOrigLen--; dbv->pszVal = cbOrigPtr; if (cbLen < cbOrigLen) cbOrigLen = cbLen; memcpy(dbv->pszVal, pCachedValue->pszVal, cbOrigLen); dbv->pszVal[cbOrigLen] = 0; dbv->cchVal = cbLen; } else { dbv->pszVal = (char*)mir_alloc(strlen(pCachedValue->pszVal) + 1); strcpy(dbv->pszVal, pCachedValue->pszVal); } } else memcpy(dbv, pCachedValue, sizeof(DBVARIANT)); return (pCachedValue->type == DBVT_DELETED) ? 1 : 0; } // never look db for the resident variable if (szCachedSettingName[-1] != 0) return 1; DBCachedContact *cc = (contactID) ? m_cache->GetCachedContact(contactID) : NULL; DBSettingSortingKey keySearch; keySearch.dwContactID = contactID; keySearch.dwOfsModule = GetModuleNameOfs(szModule); strncpy_s(keySearch.szSettingName, szSetting, _TRUNCATE); ham_key_t key = { 2 * sizeof(DWORD) + settingNameLen, &keySearch }; ham_record_t rec = { 0 }; if (ham_db_find(m_dbSettings, NULL, &key, &rec, 0)) { // try to get the missing mc setting from the active sub if (cc && cc->IsMeta() && ValidLookupName(szModule, szSetting)) { if (contactID = db_mc_getDefault(contactID)) { if (szModule = GetContactProto(contactID)) { moduleNameLen = (int)strlen(szModule); goto LBL_Seek; } } } return 1; } BYTE *pBlob = (BYTE*)rec.data; if (isStatic && (pBlob[0] & DBVTF_VARIABLELENGTH) && VLT(dbv->type) != VLT(pBlob[0])) return 1; int varLen; BYTE iType = dbv->type = pBlob[0]; pBlob++; switch (iType) { case DBVT_DELETED: /* this setting is deleted */ dbv->type = DBVT_DELETED; return 2; case DBVT_BYTE: dbv->bVal = *pBlob; break; case DBVT_WORD: dbv->wVal = *(WORD*)pBlob; break; case DBVT_DWORD: dbv->dVal = *(DWORD*)pBlob; break; case DBVT_UTF8: case DBVT_ASCIIZ: varLen = *(WORD*)pBlob; pBlob += 2; if (isStatic) { dbv->cchVal--; if (varLen < dbv->cchVal) dbv->cchVal = varLen; memmove(dbv->pszVal, pBlob, dbv->cchVal); // decode dbv->pszVal[dbv->cchVal] = 0; dbv->cchVal = varLen; } else { dbv->pszVal = (char*)mir_alloc(1 + varLen); memmove(dbv->pszVal, pBlob, varLen); dbv->pszVal[varLen] = 0; } break; case DBVT_BLOB: varLen = *(WORD*)pBlob; pBlob += 2; if (isStatic) { if (varLen < dbv->cpbVal) dbv->cpbVal = varLen; memmove(dbv->pbVal, pBlob, dbv->cpbVal); } else { dbv->pbVal = (BYTE *)mir_alloc(varLen); memmove(dbv->pbVal, pBlob, varLen); } dbv->cpbVal = varLen; break; case DBVT_ENCRYPTED: if (m_crypto == NULL) return 1; varLen = *(WORD*)pBlob; pBlob += 2; size_t realLen; ptrA decoded(m_crypto->decodeString(pBlob, varLen, &realLen)); if (decoded == NULL) return 1; varLen = (WORD)realLen; dbv->type = DBVT_UTF8; if (isStatic) { dbv->cchVal--; if (varLen < dbv->cchVal) dbv->cchVal = varLen; memmove(dbv->pszVal, decoded, dbv->cchVal); dbv->pszVal[dbv->cchVal] = 0; dbv->cchVal = varLen; } else { dbv->pszVal = (char*)mir_alloc(1 + varLen); memmove(dbv->pszVal, decoded, varLen); dbv->pszVal[varLen] = 0; } break; } /**** add to cache **********************/ if (iType != DBVT_BLOB && iType != DBVT_ENCRYPTED) { DBVARIANT *pCachedValue = m_cache->GetCachedValuePtr(contactID, szCachedSettingName, 1); if (pCachedValue != NULL) m_cache->SetCachedVariant(dbv, pCachedValue); } return 0; }