bool CRes::PackFiles(CStringArray& FilesList, CString PackName /* = _T */) { RESHEADER Header; ZeroMemory(&Header, RHSize); CFile File, tmpFile; DWORD dwFilesCount = FilesList.GetCount(); DWORD dwTableSize = dwFilesCount * RESize, dwFreeOffset = RHSize; unique_ptr<BYTE[]> upTable(new BYTE[dwTableSize]); auto pTable = upTable.get(); memmove_s(Header.Header, 3, "PRF", 3); Header.FilesCount = dwFilesCount; Header.TableSize = dwTableSize; File.Open(PackName, CFile::modeCreate|CFile::modeReadWrite); File.Write(&Header, RHSize); for (DWORD i = 0; i < dwFilesCount; i++) { CString FileName; unique_ptr<BYTE> upBuffer, upzBuffer; RESENTRY Table; ZeroMemory(&Table, RESize); tmpFile.Open(FilesList[i], CFile::modeRead); DWORD dwFileSize = tmpFile.GetLength(); upBuffer = unique_ptr<BYTE>(new BYTE[dwFileSize+1]); auto pBuffer = upBuffer.get(); tmpFile.Read(pBuffer, dwFileSize); DWORD dwzFileSize = compressBound(dwFileSize); upzBuffer = unique_ptr<BYTE>(new BYTE[dwzFileSize]); auto pzBuffer = upzBuffer.get(); compress(pzBuffer, &dwzFileSize, pBuffer, dwFileSize); File.Write(pzBuffer, dwzFileSize); tmpFile.Close(); FileName = GetName(FilesList[i]); size_t iRet = 0; wcstombs_s(&iRet, Table.ResName, 32, FileName, FileName.GetLength()); Table.ResOffset = dwFreeOffset; Table.ResSize = dwFileSize; Table.zResSize = dwzFileSize; dwFreeOffset += dwzFileSize; memmove_s(pTable, dwTableSize, &Table, RESize); pTable += RESize; } Header.TableOffset = dwFreeOffset; File.Write(upTable.get(), dwTableSize); File.SeekToBegin(); File.Write(&Header, RHSize); File.Close(); return true; }
// Append to the signal buffer and compute resulting times void XTime::Signal() { // make room for the new signal memmove_s(localStack.signals+1u, sizeof(LARGE_INTEGER) * 255, localStack.signals, sizeof(LARGE_INTEGER) * localStack.numSamples); // append to the front of signals and up the count (no more than the last index tho) QueryPerformanceCounter( localStack.signals ); localStack.signalCount = min( localStack.signalCount+1, 255 ); // with our signal buffer updated, we can now compute our timing values localStack.totalTime = double((*localStack.signals).QuadPart - localStack.start.QuadPart) / double(localStack.frequency.QuadPart); localStack.deltaTime = double(localStack.signals[0].QuadPart - localStack.signals[1].QuadPart) / double(localStack.frequency.QuadPart); // with our signal buffer updated we can compute our weighted average for a smoother delta curve. double totalWeight = 0, runningWeight = 1; LONGLONG totalValue = 0, sampleDelta; // loop up to num samples or as many as we have available for(unsigned char i = 0; i < min(localStack.numSamples, localStack.signalCount-1); ++i) { // determine each delta as we go sampleDelta = localStack.signals[i].QuadPart - localStack.signals[i+1].QuadPart; totalValue += LONGLONG(sampleDelta * runningWeight); // this cast is expensive, need to look into optimizing totalWeight += runningWeight; // tally all the weights used runningWeight *= localStack.blendWeight; // adjust the weight of next delta } // with our totals calculated, determine the weighted average. localStack.smoothDelta = (totalValue / totalWeight) / double(localStack.frequency.QuadPart); // done calculating deltas }
HRESULT PathCchStripPrefixA(PSTR pszPath, size_t cchPath) { BOOL hasPrefix; BOOL deviceNamespace; if (!pszPath) return S_FALSE; if (cchPath < 4) return S_FALSE; hasPrefix = ((pszPath[0] == '\\') && (pszPath[1] == '\\') && (pszPath[2] == '?') && (pszPath[3] == '\\')) ? TRUE : FALSE; if (hasPrefix) { if (cchPath < 7) return S_FALSE; deviceNamespace = ((pszPath[5] == ':') && (pszPath[6] == '\\')) ? TRUE : FALSE; if (deviceNamespace) { memmove_s(pszPath, cchPath, &pszPath[4], cchPath - 4); return S_OK; } } return S_FALSE; }
int _vector_move_right(Vector* vector, size_t index) { assert(vector->size < vector->capacity); /* The location where to start to move from. */ void* offset = _vector_offset(vector, index); /* How many to move to the right. */ size_t elements_in_bytes = (vector->size - index) * vector->element_size; #ifdef __STDC_LIB_EXT1__ size_t right_capacity_in_bytes = (vector->capacity - (index + 1)) * vector->element_size; /* clang-format off */ int return_code = memmove_s( offset + vector->element_size, right_capacity_in_bytes, offset, elements_in_bytes ); /* clang-format on */ return return_code == 0 ? VECTOR_SUCCESS : VECTOR_ERROR; #else memmove(offset + vector->element_size, offset, elements_in_bytes); return VECTOR_SUCCESS; #endif }
// For better speed directly handle memory instead of std::string void HashCrackerUtils::IncreasePassword(char *p_password, const unsigned int p_bufferCapacity, const std::string &p_alphabet) { bool finished = false; char nc = '?'; unsigned int i; i = static_cast<int>(strlen( p_password )); if( i < p_bufferCapacity ) { while ( !finished ) { nc = (i == 0 ? '\0' : NextAlphabetChar( p_alphabet, p_password[i - 1] )); if( nc != '\0' ) { // Not yet reached the end of alphabet, nc is the next character p_password[i - 1] = nc; finished = true; } else { // Reached the end of the alphabet if( i == 0 ) { // Shift 1 character to the right memmove_s(p_password + 1, p_bufferCapacity - 1, p_password, p_bufferCapacity - 1); p_password[0] = p_alphabet[0]; finished = true; } else { p_password[i - 1] = p_alphabet[0]; } } i--; } } else { throw _CException( "Buffer too small to store next password. 2 characters are required after the last password character.", 0 ); } }
HRESULT PathCchStripPrefixA(PSTR pszPath, size_t cchPath) { BOOL hasPrefix; if (!pszPath) return E_INVALIDARG; if (cchPath < 4 || cchPath > PATHCCH_MAX_CCH) return E_INVALIDARG; hasPrefix = ((pszPath[0] == '\\') && (pszPath[1] == '\\') && (pszPath[2] == '?') && (pszPath[3] == '\\')) ? TRUE : FALSE; if (hasPrefix) { if (cchPath < 6) return S_FALSE; if (IsCharAlpha(pszPath[4]) && (pszPath[5] == ':')) /* like C: */ { memmove_s(pszPath, cchPath, &pszPath[4], cchPath - 4); /* since the passed pszPath must not necessarily be null terminated * and we always have enough space after the strip we can always * ensure the null termination of the stripped result */ pszPath[cchPath - 4] = 0; return S_OK; } } return S_FALSE; }
void addLeadingZeros(char* buffer, int desiredLength) { while ( (int)strlen(buffer) < desiredLength ) { memmove_s(&buffer[1], desiredLength+1, buffer, strlen(buffer)); buffer[0] = '0'; } }
void CFB_ModePolicy::TransformRegister() { CRYPTOPP_ASSERT(m_cipher->IsForwardTransformation()); // CFB mode needs the "encrypt" direction of the underlying block cipher, even to decrypt m_cipher->ProcessBlock(m_register, m_temp); unsigned int updateSize = BlockSize()-m_feedbackSize; memmove_s(m_register, m_register.size(), m_register+m_feedbackSize, updateSize); memcpy_s(m_register+updateSize, m_register.size()-updateSize, m_temp, m_feedbackSize); }
void main( void ) { char buffer[80] = "0123456789"; memmove_s( buffer + 1, sizeof( buffer ), buffer, 79 ); buffer[0] = '*'; printf( buffer ); }
void RedisNet::HandleWrite(const boost::system::error_code& error, size_t bytes_transferred) { // boost::lock_guard<boost::mutex> lock(mutex_); boost::mutex::scoped_lock lock(mutex_); // cerr << "HandleWrite() bytes_transferred : " << bytes_transferred << endl; // memmove_s(&writeBuffer_[position_ - bytes_transferred], REDIS_NET_BUFFER_SIZE, &writeBuffer_[position_], bytes_transferred); memmove_s(&writeBuffer_[0], REDIS_NET_BUFFER_SIZE, &writeBuffer_[bytes_transferred], bytes_transferred); position_ -= bytes_transferred; }
void PingReply(Host Session_SN, ushort Reply2ID) { uchar Request[0xFF]; ushort TransID; uchar *PRequest, *Mark; uint Size, SizeSz; ObjectDesc ObjNbr; PRequest = Request; ZeroMemory(Request, 0xFF); TransID = BytesRandomWord(); if (0xFFFF - TransID < 0x1000) TransID -= 0x1000; *(unsigned short *)PRequest = htons(TransID); PRequest += 2; Mark = PRequest; WriteValue(&PRequest, 0x0A); WriteValue(&PRequest, 0x293); *(unsigned short *)PRequest = htons(Reply2ID); PRequest += 2; *PRequest++ = RAW_PARAMS; WriteValue(&PRequest, 0x02); ObjNbr.Family = OBJ_FAMILY_NBR; ObjNbr.Id = 0x01; ObjNbr.Value.Nbr = 0x02; WriteObject(&PRequest, ObjNbr); ObjNbr.Family = OBJ_FAMILY_NBR; ObjNbr.Id = 0x08; ObjNbr.Value.Nbr = 0x0A; WriteObject(&PRequest, ObjNbr); Size = (uint)(PRequest - Request); SizeSz = GetWrittenSz(Size << 1); PRequest = Request; memmove_s(Request + SizeSz, 0xFF, Request, 0xFF - SizeSz); WriteValue(&PRequest , Size << 1); Size += SizeSz; CipherTCP(&(Keys.SendStream), Request, 3); CipherTCP(&(Keys.SendStream), Request + 3, Size - 3); printf("Sending Ping Response..\n"); NoWait = 1; SendPacketTCP(Session_SN.socket, Session_SN, Request, Size, HTTPS_PORT, &(Session_SN.Connected)); }
void SessionPropReply(Host Session_SN, ushort Reply2ID) { uchar Request[0xFF]; ushort TransID; uchar *PRequest, *Mark; uint Size, SizeSz; PRequest = Request; ZeroMemory(Request, 0xFF); TransID = BytesRandomWord(); if (0xFFFF - TransID < 0x1000) TransID -= 0x1000; *(unsigned short *)PRequest = htons(TransID); PRequest += 2; Mark = PRequest; WriteValue(&PRequest, 0x04); WriteValue(&PRequest, 0x233); *(unsigned short *)PRequest = htons(Reply2ID); PRequest += 2; *PRequest++ = RAW_PARAMS; WriteValue(&PRequest, 0x00); Size = (uint)(PRequest - Request); SizeSz = GetWrittenSz(Size << 1); PRequest = Request; memmove_s(Request + SizeSz, 0xFF, Request, 0xFF - SizeSz); WriteValue(&PRequest , Size << 1); Size += SizeSz; CipherTCP(&(Keys.SendStream), Request, 3); CipherTCP(&(Keys.SendStream), Request + 3, Size - 3); printf("Sending Session Accept..\n"); NoWait = 1; SendPacketTCP(Session_SN.socket, Session_SN, Request, Size, HTTPS_PORT, &(Session_SN.Connected)); }
DAPI_(HRESULT) PathPrefix( __inout LPWSTR *psczFullPath ) { Assert(psczFullPath && *psczFullPath); HRESULT hr = S_OK; LPWSTR wzFullPath = *psczFullPath; DWORD_PTR cbFullPath = 0; if (((L'a' <= wzFullPath[0] && L'z' >= wzFullPath[0]) || (L'A' <= wzFullPath[0] && L'Z' >= wzFullPath[0])) && L':' == wzFullPath[1] && L'\\' == wzFullPath[2]) // normal path { hr = StrAllocPrefix(psczFullPath, L"\\\\?\\", 4); ExitOnFailure(hr, "Failed to add prefix to file path."); } else if (L'\\' == wzFullPath[0] && L'\\' == wzFullPath[1]) // UNC { // ensure that we're not already prefixed if (!(L'?' == wzFullPath[2] && L'\\' == wzFullPath[3])) { hr = StrSize(*psczFullPath, &cbFullPath); ExitOnFailure(hr, "Failed to get size of full path."); memmove_s(wzFullPath, cbFullPath, wzFullPath + 1, cbFullPath - sizeof(WCHAR)); hr = StrAllocPrefix(psczFullPath, L"\\\\?\\UNC", 7); ExitOnFailure(hr, "Failed to add prefix to UNC path."); } } else { hr = E_INVALIDARG; ExitOnFailure1(hr, "Invalid path provided to prefix: %ls.", wzFullPath); } LExit: return hr; }
void CZQCustomClient::DoSend(pBlock data, int buflen) { int SendLen = 0; // 发送部分一定有个发送的队列 pClientSendData Node; memset(&m_SendData, 0, sizeof(m_SendData)); while (m_SendNodeCount > 0) { Node = m_beginpSendData; if (Node) { if ((SendLen + Node->buflen) < 4096) { memmove_s(Node->Buf, Node->buflen, &m_SendData.MsgBuf, Node->buflen); SendLen += Node->buflen; DeleteBeginNode(); } } if (SendLen >0) ReadySendNextData(&m_SendData, SendLen); } }
DWORD VmDnsForwarderRemoveAt( PVMDNS_FORWARDER_CONTEXT pForwarder, int nIndex ) { DWORD dwError = 0; if ((DWORD)nIndex >= pForwarder->dwCount) { dwError = ERROR_OUT_OF_RANGE; BAIL_ON_VMDNS_ERROR(dwError); } VmDnsFreeForwarderEntry(pForwarder->pForwarderEntries[nIndex]); pForwarder->pForwarderEntries[nIndex] = NULL; #ifndef WIN32 memmove(&pForwarder->pForwarderEntries[nIndex], &pForwarder->pForwarderEntries[nIndex+1], sizeof(PVMDNS_FORWARDER_ENTRY) * (pForwarder->dwCount - (nIndex + 1))); #else memmove_s(&pForwarder->pForwarderEntries[nIndex], sizeof(PVMDNS_FORWARDER_ENTRY) * (pForwarder->dwCount - nIndex), &pForwarder->pForwarderEntries[nIndex + 1], sizeof(PVMDNS_FORWARDER_ENTRY) * (pForwarder->dwCount - (nIndex + 1))); #endif pForwarder->pForwarderEntries[--pForwarder->dwCount] = NULL; cleanup: return dwError; error: goto cleanup; }
//Read texts bool ReadSupport_ReadText( const FILE * const FileHandle, const READ_TEXT_TYPE InputType, const size_t FileIndex) { //Initialization const auto FileBuffer = std::make_unique<uint8_t[]>(FILE_BUFFER_SIZE + MEMORY_RESERVED_BYTES); const auto TextBuffer = std::make_unique<uint8_t[]>(FILE_BUFFER_SIZE + MEMORY_RESERVED_BYTES); memset(FileBuffer.get(), 0, FILE_BUFFER_SIZE + MEMORY_RESERVED_BYTES); memset(TextBuffer.get(), 0, FILE_BUFFER_SIZE + MEMORY_RESERVED_BYTES); std::string TextData; auto LabelType_IPFilter = LABEL_IPFILTER_TYPE::NONE; auto LabelType_Hosts = LABEL_HOSTS_TYPE::NONE; size_t Encoding = 0, Index = 0, Line = 0; auto IsEraseBOM = true, NewLinePoint = false, IsStopLabel = false; //Reset global variables. if (InputType == READ_TEXT_TYPE::PARAMETER_NORMAL || InputType == READ_TEXT_TYPE::PARAMETER_MONITOR) { ParameterHopLimitsIndex.at(NETWORK_LAYER_TYPE_IPV6) = 0; ParameterHopLimitsIndex.at(NETWORK_LAYER_TYPE_IPV4) = 0; } //Read data. while (!feof(const_cast<FILE *>(FileHandle))) { //Read file and mark last read. _set_errno(0); auto ReadLength = fread_s(FileBuffer.get(), FILE_BUFFER_SIZE, sizeof(uint8_t), FILE_BUFFER_SIZE, const_cast<FILE *>(FileHandle)); if (ReadLength == 0) { if (errno != 0) { PrintLog_ReadText(InputType, FileIndex, Line); return false; } else { continue; } } //Erase BOM of Unicode Transformation Format/UTF at first. if (IsEraseBOM) { if (ReadLength <= READ_DATA_MINSIZE) { PrintLog_ReadText(InputType, FileIndex, Line); return false; } else { IsEraseBOM = false; } //8-bit Unicode Transformation Format/UTF-8 with BOM if (FileBuffer.get()[0] == 0xEF && FileBuffer.get()[1U] == 0xBB && FileBuffer.get()[2U] == 0xBF) //0xEF, 0xBB, 0xBF { memmove_s(FileBuffer.get(), FILE_BUFFER_SIZE, FileBuffer.get() + BOM_UTF_8_LENGTH, FILE_BUFFER_SIZE - BOM_UTF_8_LENGTH); memset(FileBuffer.get() + FILE_BUFFER_SIZE - BOM_UTF_8_LENGTH, 0, BOM_UTF_8_LENGTH); ReadLength -= BOM_UTF_8_LENGTH; Encoding = CODEPAGE_UTF_8; } //32-bit Unicode Transformation Format/UTF-32 Little Endian/LE else if (FileBuffer.get()[0] == 0xFF && FileBuffer.get()[1U] == 0xFE && FileBuffer.get()[2U] == 0 && FileBuffer.get()[3U] == 0) //0xFF, 0xFE, 0x00, 0x00 { memmove_s(FileBuffer.get(), FILE_BUFFER_SIZE, FileBuffer.get() + BOM_UTF_32_LENGTH, FILE_BUFFER_SIZE - BOM_UTF_32_LENGTH); memset(FileBuffer.get() + FILE_BUFFER_SIZE - BOM_UTF_32_LENGTH, 0, BOM_UTF_32_LENGTH); ReadLength -= BOM_UTF_32_LENGTH; Encoding = CODEPAGE_UTF_32_LE; } //32-bit Unicode Transformation Format/UTF-32 Big Endian/BE else if (FileBuffer.get()[0] == 0 && FileBuffer.get()[1U] == 0 && FileBuffer.get()[2U] == 0xFE && FileBuffer.get()[3U] == 0xFF) //0x00, 0x00, 0xFE, 0xFF { memmove_s(FileBuffer.get(), FILE_BUFFER_SIZE, FileBuffer.get() + BOM_UTF_32_LENGTH, FILE_BUFFER_SIZE - BOM_UTF_32_LENGTH); memset(FileBuffer.get() + FILE_BUFFER_SIZE - BOM_UTF_32_LENGTH, 0, BOM_UTF_32_LENGTH); ReadLength -= BOM_UTF_32_LENGTH; Encoding = CODEPAGE_UTF_32_BE; } //16-bit Unicode Transformation Format/UTF-16 Little Endian/LE else if (FileBuffer.get()[0] == 0xFF && FileBuffer.get()[1U] == 0xFE) //0xFF, 0xFE { memmove_s(FileBuffer.get(), FILE_BUFFER_SIZE, FileBuffer.get() + BOM_UTF_16_LENGTH, FILE_BUFFER_SIZE - BOM_UTF_16_LENGTH); memset(FileBuffer.get() + FILE_BUFFER_SIZE - BOM_UTF_16_LENGTH, 0, BOM_UTF_16_LENGTH); ReadLength -= BOM_UTF_16_LENGTH; Encoding = CODEPAGE_UTF_16_LE; } //16-bit Unicode Transformation Format/UTF-16 Big Endian/BE else if (FileBuffer.get()[0] == 0xFE && FileBuffer.get()[1U] == 0xFF) //0xFE, 0xFF { memmove_s(FileBuffer.get(), FILE_BUFFER_SIZE, FileBuffer.get() + BOM_UTF_16_LENGTH, FILE_BUFFER_SIZE - BOM_UTF_16_LENGTH); memset(FileBuffer.get() + FILE_BUFFER_SIZE - BOM_UTF_16_LENGTH, 0, BOM_UTF_16_LENGTH); ReadLength -= BOM_UTF_16_LENGTH; Encoding = CODEPAGE_UTF_16_BE; } //8-bit Unicode Transformation Format/UTF-8 without BOM or other ASCII part of encoding else { Encoding = CODEPAGE_ASCII; } } //Text check if (Encoding == CODEPAGE_ASCII || Encoding == CODEPAGE_UTF_8) { uint16_t SingleText = 0; for (Index = 0;Index < ReadLength;) { //About this check process, please visit https://en.wikipedia.org/wiki/UTF-8. if (FileBuffer.get()[Index] > 0xE0 && Index >= 3U) { SingleText = ((static_cast<const uint16_t>(FileBuffer.get()[Index] & 0x0F)) << 12U) + ((static_cast<const uint16_t>(FileBuffer.get()[Index + 1U] & 0x3F)) << 6U) + static_cast<const uint16_t>(FileBuffer.get()[Index + 2U] & 0x3F); //Next line format if (SingleText == UNICODE_LINE_SEPARATOR || SingleText == UNICODE_PARAGRAPH_SEPARATOR) { FileBuffer.get()[Index] = 0; FileBuffer.get()[Index + 1U] = 0; FileBuffer.get()[Index + 2U] = ASCII_LF; Index += 3U; continue; } //Space format else if (SingleText == UNICODE_MONGOLIAN_VOWEL_SEPARATOR || SingleText == UNICODE_EN_SPACE || SingleText == UNICODE_EM_SPACE || SingleText == UNICODE_THICK_SPACE || SingleText == UNICODE_MID_SPACE || SingleText == UNICODE_SIX_PER_EM_SPACE || SingleText == UNICODE_FIGURE_SPACE || SingleText == UNICODE_PUNCTUATION_SPACE || SingleText == UNICODE_THIN_SPACE || SingleText == UNICODE_HAIR_SPACE || SingleText == UNICODE_ZERO_WIDTH_SPACE || SingleText == UNICODE_ZERO_WIDTH_NON_JOINER || SingleText == UNICODE_ZERO_WIDTH_JOINER || SingleText == UNICODE_NARROW_NO_BREAK_SPACE || SingleText == UNICODE_MEDIUM_MATHEMATICAL_SPACE || SingleText == UNICODE_WORD_JOINER || SingleText == UNICODE_IDEOGRAPHIC_SPACE) { FileBuffer.get()[Index] = ASCII_SPACE; FileBuffer.get()[Index + 1U] = 0; FileBuffer.get()[Index + 2U] = 0; Index += 3U; continue; } } else if (FileBuffer.get()[Index] > 0xC0 && Index >= 2U) { SingleText = ((static_cast<const uint16_t>(FileBuffer.get()[Index] & 0x1F)) << 6U) + static_cast<const uint16_t>(FileBuffer.get()[Index] & 0x3F); //Next line format if (SingleText == UNICODE_NEXT_LINE) { FileBuffer.get()[Index] = 0; FileBuffer.get()[Index + 1U] = ASCII_LF; Index += 2U; continue; } //Space format else if (SingleText == UNICODE_NO_BREAK_SPACE) { FileBuffer.get()[Index] = ASCII_SPACE; FileBuffer.get()[Index + 1U] = 0; Index += 2U; continue; } } //Remove all Non-ASCII. if (FileBuffer.get()[Index] > ASCII_MAX_NUM) FileBuffer.get()[Index] = 0; //Next line format else if (FileBuffer.get()[Index] == ASCII_CR) FileBuffer.get()[Index] = 0; else if (FileBuffer.get()[Index] == ASCII_VT || FileBuffer.get()[Index] == ASCII_FF) FileBuffer.get()[Index] = ASCII_LF; //Next text ++Index; } } else if (Encoding == CODEPAGE_UTF_16_LE || Encoding == CODEPAGE_UTF_16_BE) { for (Index = 0;Index < ReadLength;Index += sizeof(uint16_t)) { auto SingleText = reinterpret_cast<uint16_t *>(FileBuffer.get() + Index); //Endian #if BYTE_ORDER == LITTLE_ENDIAN if (Encoding == CODEPAGE_UTF_16_BE) *SingleText = ntoh16_Force(*SingleText); #else if (Encoding == CODEPAGE_UTF_16_LE) *SingleText = ntoh16_Force(*SingleText); #endif //Next line format if (*SingleText == ASCII_CR) *SingleText = 0; else if (*SingleText == ASCII_CR || *SingleText == ASCII_VT || *SingleText == ASCII_FF || *SingleText == UNICODE_NEXT_LINE || *SingleText == UNICODE_LINE_SEPARATOR || *SingleText == UNICODE_PARAGRAPH_SEPARATOR) *SingleText = ASCII_LF; //Space format else if (*SingleText == UNICODE_NO_BREAK_SPACE || *SingleText == UNICODE_MONGOLIAN_VOWEL_SEPARATOR || *SingleText == UNICODE_EN_SPACE || *SingleText == UNICODE_EM_SPACE || *SingleText == UNICODE_THICK_SPACE || *SingleText == UNICODE_MID_SPACE || *SingleText == UNICODE_SIX_PER_EM_SPACE || *SingleText == UNICODE_FIGURE_SPACE || *SingleText == UNICODE_PUNCTUATION_SPACE || *SingleText == UNICODE_THIN_SPACE || *SingleText == UNICODE_HAIR_SPACE || *SingleText == UNICODE_ZERO_WIDTH_SPACE || *SingleText == UNICODE_ZERO_WIDTH_NON_JOINER || *SingleText == UNICODE_ZERO_WIDTH_JOINER || *SingleText == UNICODE_NARROW_NO_BREAK_SPACE || *SingleText == UNICODE_MEDIUM_MATHEMATICAL_SPACE || *SingleText == UNICODE_WORD_JOINER || *SingleText == UNICODE_IDEOGRAPHIC_SPACE) *SingleText = ASCII_SPACE; //Remove all Non-ASCII. else if (*SingleText > ASCII_MAX_NUM) *SingleText = 0; } } else if (Encoding == CODEPAGE_UTF_32_LE || Encoding == CODEPAGE_UTF_32_BE) { for (Index = 0;Index < ReadLength;Index += sizeof(uint32_t)) { auto SingleText = reinterpret_cast<uint32_t *>(FileBuffer.get() + Index); //Endian #if BYTE_ORDER == LITTLE_ENDIAN if (Encoding == CODEPAGE_UTF_32_BE) *SingleText = ntoh32_Force(*SingleText); #else if (Encoding == CODEPAGE_UTF_32_LE) *SingleText = ntoh32_Force(*SingleText); #endif //Next line format if (*SingleText == ASCII_CR) *SingleText = 0; else if (*SingleText == ASCII_CR || *SingleText == ASCII_VT || *SingleText == ASCII_FF || *SingleText == UNICODE_NEXT_LINE || *SingleText == UNICODE_LINE_SEPARATOR || *SingleText == UNICODE_PARAGRAPH_SEPARATOR) *SingleText = ASCII_LF; //Space format else if (*SingleText == UNICODE_NO_BREAK_SPACE || *SingleText == UNICODE_MONGOLIAN_VOWEL_SEPARATOR || *SingleText == UNICODE_EN_SPACE || *SingleText == UNICODE_EM_SPACE || *SingleText == UNICODE_THICK_SPACE || *SingleText == UNICODE_MID_SPACE || *SingleText == UNICODE_SIX_PER_EM_SPACE || *SingleText == UNICODE_FIGURE_SPACE || *SingleText == UNICODE_PUNCTUATION_SPACE || *SingleText == UNICODE_THIN_SPACE || *SingleText == UNICODE_HAIR_SPACE || *SingleText == UNICODE_ZERO_WIDTH_SPACE || *SingleText == UNICODE_ZERO_WIDTH_NON_JOINER || *SingleText == UNICODE_ZERO_WIDTH_JOINER || *SingleText == UNICODE_NARROW_NO_BREAK_SPACE || *SingleText == UNICODE_MEDIUM_MATHEMATICAL_SPACE || *SingleText == UNICODE_WORD_JOINER || *SingleText == UNICODE_IDEOGRAPHIC_SPACE) *SingleText = ASCII_SPACE; //Remove all Non-ASCII. else if (*SingleText > ASCII_MAX_NUM) *SingleText = 0; } } else { switch (InputType) { case READ_TEXT_TYPE::HOSTS: //ReadHosts { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::HOSTS, L"Text encoding error", 0, FileList_Hosts.at(FileIndex).FileName.c_str(), 0); }break; case READ_TEXT_TYPE::IPFILTER: //ReadIPFilter { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::IPFILTER, L"Text encoding error", 0, FileList_IPFilter.at(FileIndex).FileName.c_str(), 0); }break; case READ_TEXT_TYPE::PARAMETER_NORMAL: //ReadParameter { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::PARAMETER, L"Text encoding error", 0, FileList_Config.at(FileIndex).FileName.c_str(), 0); }break; case READ_TEXT_TYPE::PARAMETER_MONITOR: //ReadParameter(Monitor mode) { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::PARAMETER, L"Text encoding error", 0, FileList_Config.at(FileIndex).FileName.c_str(), 0); }break; #if defined(ENABLE_LIBSODIUM) case READ_TEXT_TYPE::DNSCURVE_DATABASE: //ReadDNSCurveDatabase { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::DNSCURVE, L"Text encoding error", 0, FileList_DNSCurveDatabase.at(FileIndex).FileName.c_str(), 0); }break; case READ_TEXT_TYPE::DNSCURVE_MONITOR: //ReadDNSCurveDatabase(Monitor mode) { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::DNSCURVE, L"Text encoding error", 0, FileList_DNSCurveDatabase.at(FileIndex).FileName.c_str(), 0); }break; #endif } return false; } //Remove all null characters. for (Index = 0;Index < ReadLength;++Index) { if (FileBuffer.get()[Index] > 0) { TextBuffer.get()[strnlen_s(reinterpret_cast<const char *>(TextBuffer.get()), FILE_BUFFER_SIZE)] = FileBuffer.get()[Index]; //Mark next line format. if (!NewLinePoint && FileBuffer.get()[Index] == ASCII_LF) NewLinePoint = true; } } //Clean file buffer. memset(FileBuffer.get(), 0, FILE_BUFFER_SIZE + MEMORY_RESERVED_BYTES); //Line length check if (!NewLinePoint && ReadLength == FILE_BUFFER_SIZE) { switch (InputType) { case READ_TEXT_TYPE::HOSTS: //ReadHosts { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::HOSTS, L"Data of a line is too long", 0, FileList_Hosts.at(FileIndex).FileName.c_str(), Line); }break; case READ_TEXT_TYPE::IPFILTER: //ReadIPFilter { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::IPFILTER, L"Data of a line is too long", 0, FileList_IPFilter.at(FileIndex).FileName.c_str(), Line); }break; case READ_TEXT_TYPE::PARAMETER_NORMAL: //ReadParameter { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::PARAMETER, L"Data of a line is too long", 0, FileList_Config.at(FileIndex).FileName.c_str(), Line); }break; case READ_TEXT_TYPE::PARAMETER_MONITOR: //ReadParameter(Monitor mode) { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::PARAMETER, L"Data of a line is too long", 0, FileList_Config.at(FileIndex).FileName.c_str(), Line); }break; #if defined(ENABLE_LIBSODIUM) case READ_TEXT_TYPE::DNSCURVE_DATABASE: //ReadDNSCurveDatabase { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::DNSCURVE, L"Data of a line is too long", 0, FileList_DNSCurveDatabase.at(FileIndex).FileName.c_str(), Line); }break; case READ_TEXT_TYPE::DNSCURVE_MONITOR: //ReadDNSCurveDatabase(Monitor mode) { PrintError(LOG_LEVEL_TYPE::LEVEL_2, LOG_ERROR_TYPE::DNSCURVE, L"Data of a line is too long", 0, FileList_DNSCurveDatabase.at(FileIndex).FileName.c_str(), Line); }break; #endif } return false; } else { NewLinePoint = false; } //Read data. for (Index = 0;Index < strnlen_s(reinterpret_cast<const char *>(TextBuffer.get()), FILE_BUFFER_SIZE);++Index) { //New line if (TextBuffer.get()[Index] == ASCII_LF || (Index + 1U == strnlen_s(reinterpret_cast<const char *>(TextBuffer.get()), FILE_BUFFER_SIZE) && feof(const_cast<FILE *>(FileHandle)))) { ++Line; //Add the last character. if (TextBuffer.get()[Index] != ASCII_LF && Index + 1U == strnlen_s(reinterpret_cast<const char *>(TextBuffer.get()), FILE_BUFFER_SIZE) && feof(const_cast<FILE *>(FileHandle))) TextData.append(1U, TextBuffer.get()[Index]); //Read texts. if (TextData.length() > READ_TEXT_MINSIZE) { switch (InputType) { case READ_TEXT_TYPE::HOSTS: //ReadHosts { ReadHostsData(TextData, FileIndex, Line, LabelType_Hosts, IsStopLabel); }break; case READ_TEXT_TYPE::IPFILTER: //ReadIPFilter { ReadIPFilterData(TextData, FileIndex, Line, LabelType_IPFilter, IsStopLabel); }break; case READ_TEXT_TYPE::PARAMETER_NORMAL: //ReadParameter { if (!ReadParameterData_Whole(TextData, FileIndex, true, Line)) return false; }break; case READ_TEXT_TYPE::PARAMETER_MONITOR: //ReadParameter(Monitor mode) { if (!ReadParameterData_Whole(TextData, FileIndex, false, Line)) return false; }break; #if defined(ENABLE_LIBSODIUM) case READ_TEXT_TYPE::DNSCURVE_DATABASE: //ReadDNSCurveDatabase { ReadSupport_DNSCurveDatabaseData(TextData, READ_TEXT_TYPE::DNSCURVE_DATABASE, FileIndex, Line); }break; case READ_TEXT_TYPE::DNSCURVE_MONITOR: //ReadDNSCurveDatabase(Monitor mode) { ReadSupport_DNSCurveDatabaseData(TextData, READ_TEXT_TYPE::DNSCURVE_MONITOR, FileIndex, Line); }break; #endif } } //Next step if (Index + 1U == strnlen_s(reinterpret_cast<const char *>(TextBuffer.get()), FILE_BUFFER_SIZE) && feof(const_cast<FILE *>(FileHandle))) return true; else TextData.clear(); } else { TextData.append(1U, TextBuffer.get()[Index]); } } memset(TextBuffer.get(), 0, FILE_BUFFER_SIZE + MEMORY_RESERVED_BYTES); } return true; }
void __cdecl handleConnection(void *param) { SOCKET clientSocket = (SOCKET)param; // Receive until the peer shuts down the connection // recv spooling borrowed from http://stackoverflow.com/a/6090610 // in a loop, we recv() off the network, handle complete lines, then shift the remainder down char recvbuf[RECVBUFSIZE] = { '\0' }; size_t recvbufUsed = 0; const char* msgPleaseSendShorterLines = "Please send shorter lines."; const char* msgBye = "Bye!"; while (1) { // establish how much room we have left in recvbuf size_t buf_remain = sizeof(recvbuf) - recvbufUsed; // check that we still have room for another recv if (buf_remain < 1) { printf("[!] recvbuf exhausted. Giving up.\n"); send(clientSocket, msgPleaseSendShorterLines, strlen(msgPleaseSendShorterLines), 0); break; } // recv() up to buf_remain bytes, put them after pending data in recvbuf int result = recv(clientSocket, (void*)&recvbuf[recvbufUsed], buf_remain, 0); if (result == 0) { printf("Client disconnected.\n"); break; } else if (result < 0) { printf("recv() failed: %d.\n", WSAGetLastError()); break; } printf("Bytes received: %d\n", result); // we're now using more of recvbuf than we were before recvbufUsed += result; // starting at recvbuf[0] look for newlines, pass each found line off to doResponse() char *line_start = recvbuf; char *line_end; while ((line_end = (char*)memchr((void*)line_start, '\n', recvbufUsed - (line_start - recvbuf))) != 0) { // we found a line // null-terminate it *line_end = '\0'; // if the user is done with us, disconnect them if (strcmp(line_start, "exit") == 0) { printf("Client requested exit.\n"); send(clientSocket, msgBye, strlen(msgBye), 0); closesocket(clientSocket); return; } // process the line doResponse(clientSocket, line_start); // continue looking for lines from after the now-processed line line_start = line_end + 1; } // having (perhaps) processed some data we are (perhaps) using less of recvbuf than we were before recvbufUsed -= (line_start - recvbuf); // slide unprocessed data down to start of recvbuf memmove_s(recvbuf, sizeof(recvbuf), line_start, recvbufUsed); } closesocket(clientSocket); return; }
//Transmission and reception of HTTP protocol size_t __fastcall HTTPRequest( const char *OriginalSend, const size_t SendSize, char *OriginalRecv, const size_t RecvSize) { //Initialization SOCKET_DATA HTTPSocketData = {0}; memset(OriginalRecv, 0, RecvSize); //Socket initialization if (Parameter.HTTP_Address_IPv6.Storage.ss_family > 0 && //IPv6 (Parameter.HTTP_Protocol == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv6 || //Auto select Parameter.HTTP_Protocol == REQUEST_MODE_IPV6 || //IPv6 Parameter.HTTP_Protocol == REQUEST_MODE_IPV4 && Parameter.HTTP_Address_IPv4.Storage.ss_family == 0)) //Non-IPv4 { HTTPSocketData.SockAddr.ss_family = AF_INET6; ((PSOCKADDR_IN6)&HTTPSocketData.SockAddr)->sin6_addr = Parameter.HTTP_Address_IPv6.IPv6.sin6_addr; ((PSOCKADDR_IN6)&HTTPSocketData.SockAddr)->sin6_port = Parameter.HTTP_Address_IPv6.IPv6.sin6_port; HTTPSocketData.AddrLen = sizeof(sockaddr_in6); HTTPSocketData.Socket = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); } else if (Parameter.HTTP_Address_IPv4.Storage.ss_family > 0 && //IPv4 (Parameter.HTTP_Protocol == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv4 || //Auto select Parameter.HTTP_Protocol == REQUEST_MODE_IPV4 || //IPv4 Parameter.HTTP_Protocol == REQUEST_MODE_IPV6 && Parameter.HTTP_Address_IPv6.Storage.ss_family == 0)) //Non-IPv6 { HTTPSocketData.SockAddr.ss_family = AF_INET; ((PSOCKADDR_IN)&HTTPSocketData.SockAddr)->sin_addr = Parameter.HTTP_Address_IPv4.IPv4.sin_addr; ((PSOCKADDR_IN)&HTTPSocketData.SockAddr)->sin_port = Parameter.HTTP_Address_IPv4.IPv4.sin_port; HTTPSocketData.AddrLen = sizeof(sockaddr_in); HTTPSocketData.Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } else { return EXIT_FAILURE; } //Socket check if (!SocketSetting(HTTPSocketData.Socket, SOCKET_SETTING_INVALID_CHECK, nullptr)) { PrintError(LOG_ERROR_NETWORK, L"HTTP socket initialization error", 0, nullptr, 0); return EXIT_FAILURE; } //Non-blocking mode setting if (!SocketSetting(HTTPSocketData.Socket, SOCKET_SETTING_NON_BLOCKING_MODE, nullptr)) { shutdown(HTTPSocketData.Socket, SD_BOTH); closesocket(HTTPSocketData.Socket); PrintError(LOG_ERROR_NETWORK, L"Socket non-blocking mode setting error", 0, nullptr, 0); return EXIT_FAILURE; } //Selecting structure setting fd_set ReadFDS = {0}, WriteFDS = {0}; timeval Timeout = {0}; //HTTP CONNECT request if (Parameter.HTTP_TargetDomain == nullptr || Parameter.HTTP_Version == nullptr || !HTTP_CONNECTRequest(&HTTPSocketData, &ReadFDS, &WriteFDS, &Timeout, OriginalRecv, RecvSize)) { shutdown(HTTPSocketData.Socket, SD_BOTH); closesocket(HTTPSocketData.Socket); return EXIT_FAILURE; } //Add length of request packet(It must be written in header when transpot with TCP protocol). std::shared_ptr<char> SendBuffer(new char[LARGE_PACKET_MAXSIZE]()); memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); memcpy_s(SendBuffer.get(), RecvSize, OriginalSend, SendSize); SSIZE_T RecvLen = AddLengthDataToHeader(SendBuffer.get(), SendSize, RecvSize); if (RecvLen < (SSIZE_T)DNS_PACKET_MINSIZE) { shutdown(HTTPSocketData.Socket, SD_BOTH); closesocket(HTTPSocketData.Socket); return EXIT_FAILURE; } //Socket timeout setting #if defined(PLATFORM_WIN) Timeout.tv_sec = Parameter.HTTP_SocketTimeout / SECOND_TO_MILLISECOND; Timeout.tv_usec = Parameter.HTTP_SocketTimeout % SECOND_TO_MILLISECOND * MICROSECOND_TO_MILLISECOND; #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) Timeout.tv_sec = Parameter.HTTP_SocketTimeout.tv_sec; Timeout.tv_usec = Parameter.HTTP_SocketTimeout.tv_usec; #endif //Data exchange RecvLen = ProxySocketSelecting(HTTPSocketData.Socket, &ReadFDS, &WriteFDS, &Timeout, SendBuffer.get(), RecvLen, OriginalRecv, RecvSize, DNS_PACKET_MINSIZE, nullptr); shutdown(HTTPSocketData.Socket, SD_BOTH); closesocket(HTTPSocketData.Socket); //Server response check if (RecvLen >= (SSIZE_T)DNS_PACKET_MINSIZE && ntohs(((uint16_t *)OriginalRecv)[0]) >= DNS_PACKET_MINSIZE && RecvLen >= ntohs(((uint16_t *)OriginalRecv)[0])) { RecvLen = ntohs(((uint16_t *)OriginalRecv)[0]); memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(uint16_t), RecvLen); //Responses check RecvLen = CheckResponseData( REQUEST_PROCESS_HTTP, OriginalRecv, RecvLen, RecvSize, nullptr); if (RecvLen < (SSIZE_T)DNS_PACKET_MINSIZE) return EXIT_FAILURE; //Mark DNS cache. if (Parameter.CacheType > 0) MarkDomainCache(OriginalRecv, RecvLen); return RecvLen; } return EXIT_FAILURE; }
void CFormatTabDlg::RemoveTabFromArrayByIndex(int nIndex) { memmove_s(&m_tabarray[nIndex], sizeof(LONG), &m_tabarray[nIndex+1], (m_nCount-nIndex-1)*sizeof(LONG)); m_nCount--; }
static int get_dev_func( void ) { char * end = NULL; int i; size_t position; size_t scanned; size_t unscanned; if( cur_file->scanptr == NULL ) { /* First call: start by getting data into the buffer. */ cur_file->usedlen = fread( cur_file->filebuf, 1, \ cur_file->buflen, cur_file->fp ); if( ferror( cur_file->fp ) ) return( FAILURE ); if( cur_file->usedlen == 0 ) return( FAILURE ); cur_file->scanptr = cur_file->filebuf; } /* Initialize the output values to clear any old data. */ cur_token->start = NULL; cur_token->count = 0; for( ;; ) { /* Find the next device function name. */ position = cur_file->scanptr - cur_file->filebuf; for( i = 0; i < cur_file->usedlen - position; i++ ){ if( *cur_file->scanptr == '%' ) break; cur_file->scanptr++; } if( *cur_file->scanptr == '%' ) { /* cur_file->scanptr points to the start of a device * function name. */ cur_token->start = cur_file->scanptr; /* Find the length of the device function name. */ end = cur_token->start; position = cur_file->scanptr - cur_file->filebuf; for( i = 0; i < cur_file->usedlen - position; i++ ){ if( *end == '(' ) break; end++; } if( *end == '(' ) { /* end points to one position beyond the end of the name. */ cur_file->scanptr = end; cur_token->count = end - cur_token->start; break; } if( feof( cur_file->fp ) ) return( FAILURE ); /* If we get here, we ran out of data before finding the end of * the device function name: reset the buffer to start with the * start of the device function name and read more data in. */ scanned = cur_token->start - cur_file->filebuf; unscanned = &cur_file->filebuf[cur_file->usedlen] - \ cur_token->start; memmove_s( cur_file->filebuf, cur_file->buflen, \ cur_token->start, unscanned ); cur_file->usedlen = fread( &cur_file->filebuf[ unscanned ], 1, \ cur_file->buflen - unscanned, cur_file->fp ); cur_file->usedlen += unscanned; if( ferror( cur_file->fp ) ) return( FAILURE ); if( cur_file->usedlen == 0 ) return( FAILURE ); cur_file->scanptr = cur_file->filebuf; continue; } if( feof( cur_file->fp ) ) return( FAILURE ); /* If we get here, then we ran out of buffer before finding the start * of a device function name: replace the entire buffer. */ cur_file->usedlen = fread( cur_file->filebuf, 1, \ cur_file->buflen, cur_file->fp ); if( ferror( cur_file->fp ) ) return( FAILURE ); if( cur_file->usedlen == 0 ) return( FAILURE ); cur_file->scanptr = cur_file->filebuf; } return( SUCCESS ) ; }
DWORD WINAPI CClientManager::ThreadWorker(LPVOID lp) { AUTO_LOG_FUNCTION; CClientManager* manager = reinterpret_cast<CClientManager*>(lp); timeval tv = { 0, 10 }; DWORD dwCount = 0; for (;;) { dwCount++; if (WAIT_OBJECT_0 == WaitForSingleObject(manager->m_hEventShutdown, 1)) break; if (manager->m_bShuttingDown) { break; } for (auto client_iter : manager->m_client_map) { if (WAIT_OBJECT_0 == WaitForSingleObject(manager->m_hEventShutdown, 0)) break; if (manager->m_bShuttingDown) { break; } auto client = client_iter.second; if (!client->IsConnectionEstablished()) { continue; } int nRet = 0; fd_set fdRead, fdWrite; FD_ZERO(&fdRead); FD_ZERO(&fdWrite); FD_SET(client->m_socket, &fdRead); FD_SET(client->m_socket, &fdWrite); nRet = select(client->m_socket + 1, &fdRead, &fdWrite, nullptr, &tv); if (WAIT_OBJECT_0 == WaitForSingleObject(manager->m_hEventShutdown, 0)) continue; BOOL bRead = FD_ISSET(client->m_socket, &fdRead); BOOL bWrite = FD_ISSET(client->m_socket, &fdWrite); if (bRead) { char* temp = client->m_buff.buff + client->m_buff.wpos; DWORD dwLenToRead = BUFF_SIZE - client->m_buff.wpos; nRet = recv(client->m_socket, temp, dwLenToRead, 0); if (nRet <= 0) { JLOG(_T("ThreadRecv::recv ret <= 0, ret %d"), nRet); manager->m_handler->OnConnectionLost(client); client->Disconnect(); continue; } else if (manager->m_handler) { client->m_buff.wpos += nRet; DWORD ret = RESULT_OK; ret = manager->m_handler->OnRecv(client); while (1) { unsigned int bytes_not_commited = client->m_buff.wpos - client->m_buff.rpos; if (bytes_not_commited == 0) { if (client->m_buff.wpos == BUFF_SIZE) { client->m_buff.Clear(); } break; } if (client->m_buff.wpos == BUFF_SIZE) { memmove_s(client->m_buff.buff, BUFF_SIZE, client->m_buff.buff + client->m_buff.rpos, bytes_not_commited); memset(client->m_buff.buff + bytes_not_commited, 0, BUFF_SIZE - bytes_not_commited); client->m_buff.wpos -= client->m_buff.rpos; client->m_buff.rpos = 0; ret = manager->m_handler->OnRecv(client); } else { ret = manager->m_handler->OnRecv(client); } if (ret == RESULT_NOT_ENOUGH) { break; } } client->last_recv_time_ = COleDateTime::GetTickCount(); } } if (bWrite) { // send link test if (manager->m_handler && client->m_bConnectionEstablished && ((COleDateTime::GetTickCount() - client->last_send_link_test_time_).GetTotalSeconds() * 1000 >= LINK_TEST_GAP)) { char buff[4096] = { 0 }; DWORD dwLen = client->GenerateLinkTestPackage(buff, sizeof(buff)); if (dwLen > 0 && dwLen <= sizeof(buff)) { int nLen = client->Send(buff, dwLen); if (nLen <= 0) { JLOG(_T("ThreadLinkTest::Send ret <= 0, ret %d"), nLen); client->Disconnect(); manager->m_handler->OnConnectionLost(client); continue; } CWinApp* app = AfxGetApp(); if (app) { CWnd* wnd = app->GetMainWnd(); if (wnd) { wnd->PostMessageW(WM_NETWORKSTARTUPOK, mp_snd_lnk_tst, client->get_acct_id()); } } JLOG(_T("Send link test to transmite server, len %d\n"), nLen); client->last_send_link_test_time_ = COleDateTime::GetTickCount(); } } // send data if (!client->buffer_.empty() && client->buffer_lock_.try_lock()) { std::lock_guard<std::mutex> lock(client->buffer_lock_, std::adopt_lock); auto buffer = client->buffer_.front(); client->Send(&buffer[0], buffer.size()); client->buffer_.pop_front(); } } // check timeup /*if (dwCount % 1000 == 0) { dwCount = 0; if ((COleDateTime::GetTickCount() - client->last_recv_time_).GetTotalSeconds() * 1000 > LINK_TEST_GAP * 3) { manager->m_handler->OnConnectionLost(client); client->Disconnect(); } }*/ } } return 0; }
void CZQCustomClient::ReadySendNextData(pBlock data, int buflen) { int iSendlen = 0; int iRemainLen = 0; EnterCriticalSection(&m_SendCS); m_IsSending = false; pClientSendData node = NULL; while (m_beginpSendData) { node = m_beginpSendData; iRemainLen = MAX_BUFFER_LEN - iSendlen; int iDatalen = node->buflen - node->iStartPosition; if (iDatalen > iRemainLen) { memmove_s(&data->MsgBuf[iSendlen], iRemainLen, &node->Buf[node->iStartPosition], node->buflen); iSendlen = MAX_BUFFER_LEN; node->iStartPosition += iRemainLen; break; } else { memmove_s(&data->MsgBuf[iSendlen], iDatalen, &node->Buf[iSendlen], node->buflen); iSendlen += iDatalen; m_beginpSendData = node->Next; if (m_beginpSendData == NULL) m_endSendData = NULL; free(node->Buf); delete (node); } } if (iSendlen > 0) { m_IsSending = true; //这里需要记录一下总的发送数量。 int ErrorCode = 0; DWORD Transfer = 0; DWORD flags = 0; data->OperatorType = ioWrite; data->buf.len = iSendlen; data->buf.buf = data->MsgBuf; memset(&data->overloapped, 0, sizeof(data->overloapped)); if ((m_socket == INVALID_SOCKET) || (WSASend(m_socket, &data->buf, 1, &Transfer, flags, &data->overloapped, NULL) == SOCKET_ERROR)) { ErrorCode = WSAGetLastError(); if (ErrorCode != ERROR_IO_PENDING) { //发送出错了 m_IsSending = false; Close(); } } m_IsSending = false; } LeaveCriticalSection(&m_SendCS); }
void TestMove_s( void ) { char buf[128]; char s2[] = "VALUE"; char str[] = "VALUE"; char src1[100] = "hello"; char src2[7] = {'g', 'o', 'o', 'd', 'b', 'y', 'e'}; char dst1[6], dst2[5], dst3[5]; char sc1[100] = "good"; char sc2[6] = "hello"; char sc3[6] = "hello"; char sc4[7] = "abc"; char sc5[1000] = "bye"; int violations = NumViolations; /* strtok_s */ static char str1[] = "?a???b,,,#c"; static char str2[] = "\t \t"; static char str3[] = "?a???b,,,#c"; char *t, *ptr1, *ptr2, *ptr3; rsize_t max1 = sizeof( str1 ); rsize_t max2 = sizeof( str2 ); rsize_t max3 = sizeof( str3 ); /***********************************************************************/ /* set constraint-handler */ /***********************************************************************/ set_constraint_handler_s( my_constraint_handler ); /***********************************************************************/ /* memcpy_s */ /***********************************************************************/ /* Test the "good" case */ VERIFY( memcpy_s( buf, sizeof( buf ), s2, 0 ) == 0 ); VERIFY( memcpy_s( buf, sizeof( buf ), s2, 1 + strlen( s2 ) ) == 0 ); VERIFY( memcpy_s( buf, strlen( s2 ) + 2, s2, 1 + strlen( s2 ) ) == 0 ); VERIFY( strlen( buf ) == strlen( "VALUE" ) ); VERIFY( strcmp( buf, "VALUE" ) == 0 ); VERIFY( NumViolations == violations ); /* Test various failing cases */ /* Test runtime-constraint violations */ VERIFY( memcpy_s( buf, 3, s2, strlen( s2 ) ) != 0 ); VERIFY( buf[0] == '\0' ); VERIFY( NumViolations == ++violations ); VERIFY( memcpy_s( NULL, sizeof( buf ), s2, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( memcpy_s( buf, sizeof( buf ), NULL, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( memcpy_s( buf, sizeof( buf ), s2, sizeof( buf ) + 1 ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( memcpy_s( buf, sizeof( buf ), buf + 1, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); #if RSIZE_MAX != SIZE_MAX VERIFY( memcpy_s( buf, sizeof( buf ), s2, ~0 ) != 0 ); VERIFY( NumViolations == ++violations ); #endif /***********************************************************************/ /* memmove_s */ /***********************************************************************/ /* Test the "good" cases */ VERIFY( memmove_s( buf, sizeof( buf ) , s2, 0 ) == 0 ); VERIFY( memmove_s( buf, sizeof( buf ) , s2, 1 + strlen( s2 ) ) == 0 ); VERIFY( memmove_s( buf, sizeof( buf ), buf + 1, 1 + strlen( s2 ) ) == 0 ); VERIFY( memmove_s( buf, 1 + strlen( s2 ), s2, 1 + strlen( s2 ) ) == 0 ); VERIFY( strlen( buf ) == strlen( "VALUE" ) ); VERIFY( strcmp( buf, "VALUE" ) == 0 ); VERIFY( NumViolations == violations ); /* Test various failing cases */ /* Test runtime-constraint violations */ VERIFY( memmove_s( buf, 3, s2, strlen( s2 ) ) != 0 ); VERIFY( buf[0] == '\0' ); VERIFY( NumViolations == ++violations ); VERIFY( memmove_s( NULL, sizeof( buf ), s2, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( memmove_s( buf, sizeof( buf ), NULL, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( memmove_s( buf, sizeof( buf ), s2, sizeof( buf ) + 1 ) != 0 ); VERIFY( NumViolations == ++violations ); #if RSIZE_MAX != SIZE_MAX VERIFY( memmove_s( buf, ~0, s2, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( memmove_s( buf, sizeof( buf ), s2, ~0 ) != 0 ); VERIFY( NumViolations == ++violations ); #endif /***********************************************************************/ /* strcpy_s */ /***********************************************************************/ /* Test the "good" cases */ VERIFY( strcpy_s( buf, sizeof( buf ), s2 ) == 0 ); VERIFY( strcpy_s( buf, sizeof( buf ), s2 ) == 0 ); VERIFY( strcpy_s( buf, strlen( s2 ) + 1, s2 ) == 0 ); VERIFY( strlen( buf ) == strlen( "VALUE" ) ); VERIFY( strcmp( buf, "VALUE" ) == 0 ); VERIFY( NumViolations == violations ); /* Test various failing cases */ /* Test runtime-constraint violations */ VERIFY( strcpy_s( buf, 3, s2 ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( buf[0] == '\0' ); VERIFY( strcpy_s( NULL, sizeof( buf ), s2 ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( strcpy_s( buf, sizeof( buf ), NULL ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( strcpy_s( buf, 5, s2 ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( strcpy_s( buf, sizeof( buf ), buf + 1 ) != 0 ); VERIFY( NumViolations == ++violations ); #if RSIZE_MAX != SIZE_MAX VERIFY( strcpy_s( buf, ~0, s2 ) != 0 ); VERIFY( NumViolations == ++violations ); #endif /***********************************************************************/ /* strcat_s */ /***********************************************************************/ strcpy( sc1, src1 ); VERIFY( strcat_s( sc1, 100, sc5 ) == 0 ); VERIFY( strcmp( sc1, "hellobye") == 0 ); VERIFY( strcat_s( sc2, 6, "" ) == 0 ); VERIFY( strcat_s( sc3, 6, "X" ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( sc3[0] == '\0'); VERIFY( strcat_s(sc4, 7, "defghijklmn") != 0); VERIFY( NumViolations == ++violations ); VERIFY( strcmp(sc4, "" ) == 0); /***********************************************************************/ /* strnlen_s */ /***********************************************************************/ /* Test the "good" case */ VERIFY( strnlen_s( str, sizeof( str ) ) == strlen( str ) ); VERIFY( strnlen_s( str, 4 ) == 4 ); VERIFY( strnlen_s( str, 0 ) == 0 ); VERIFY( strnlen_s( NULL, 1000 ) == 0 ); /* Test various failing cases */ /* No runtime-constraint violations to test */ VERIFY( NumViolations == violations ); /***********************************************************************/ /* strncpy_s */ /***********************************************************************/ /* Test the "good" case */ VERIFY( strncpy_s( buf, sizeof( buf ), s2, 0 ) == 0 ); VERIFY( strncpy_s( buf, sizeof( buf ), s2, strlen( s2 ) ) == 0 ); VERIFY( strncpy_s( buf, strlen( s2 ) + 1, s2, strlen( s2 ) ) == 0 ); VERIFY( strlen( buf ) == strlen( "VALUE" ) ); VERIFY( strcmp( buf, "VALUE" ) == 0 ); VERIFY( NumViolations == violations ); VERIFY( strncpy_s( dst1, 6, src1, 100 ) == 0 ); VERIFY( strcmp( dst1, src1 ) == 0 ); VERIFY( strncpy_s( dst3, 5, src2, 4 ) == 0 ); /* Test various failing cases */ /* Test runtime-constraint violations */ VERIFY( strncpy_s( buf, 3, s2, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( buf[0] == '\0' ); VERIFY( strncpy_s( NULL, sizeof( buf ), s2, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( strncpy_s( buf, sizeof( buf ), NULL, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( strncpy_s( buf, sizeof( buf ), buf + 1, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( strncpy_s( dst2, 5, src2, 7 ) != 0 ); VERIFY( NumViolations == ++violations ); #if RSIZE_MAX != SIZE_MAX VERIFY( strncpy_s( buf, ~0, s2, strlen( s2 ) ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( strncpy_s( buf, sizeof( buf ), s2, ~0 ) != 0 ); VERIFY( NumViolations == ++violations ); #endif /***********************************************************************/ /* strncat_s */ /***********************************************************************/ strcpy( sc1, "good" ); strcpy( sc2, "hello" ); strcpy( sc3, "hello" ); strcpy( sc4, "abc" ); VERIFY( strncat_s( sc1, 100, sc5, 1000 ) == 0); VERIFY( strcmp( sc1, "goodbye" ) == 0 ); VERIFY( strncat_s( sc2, 6, "", 1 ) == 0 ); VERIFY( strncat_s( sc4, 7, "defghijklmn", 3 ) == 0 ); VERIFY( strcmp( sc4, "abcdef" ) == 0 ); /* Test runtime-constraint violations */ VERIFY( strncat_s( sc3, 6, "XXX", 3 ) != 0 ); VERIFY( NumViolations == ++violations ); VERIFY( sc3[0] == '\0'); /***********************************************************************/ /* strtok_s */ /***********************************************************************/ VERIFY( (t = strtok_s( str1, &max1, "?", &ptr1 )) != NULL ); /* points to the token "a" */ VERIFY( strcmp( t, "a" ) == 0 ); VERIFY( (t = strtok_s( NULL, &max1, ",", &ptr1 )) != NULL ); /* points to the token "??b" */ VERIFY( strcmp( t, "??b" ) == 0 ); VERIFY( NULL == strtok_s( str2, &max2, " \t", &ptr2 ) ); /* null pointer */ VERIFY( NumViolations == violations ); VERIFY( (t = strtok_s( NULL, &max1, "#,", &ptr1 )) != NULL ); /* points to the token "c" */ VERIFY( strcmp( t, "c" ) == 0 ); VERIFY( ptr1 != NULL ); VERIFY( NumViolations == violations ); VERIFY( NULL == strtok_s( NULL, &max1, "#,", &ptr1 ) ); /* at the end */ strcpy( str1, str3 ); max1 = sizeof( str1 ); VERIFY( NULL == strtok_s( str1, &max1, str3, &ptr3 ) ); /* only delimiter chars */ /* Test runtime-constraint violations */ ptr1 = NULL; VERIFY( NULL == strtok_s( NULL, &max1, "?", &ptr1 ) ); /* null pointer */ VERIFY( NumViolations == ++violations ); VERIFY( NULL == strtok_s( str3, NULL, "?", &ptr1 ) ); VERIFY( NumViolations == ++violations ); VERIFY( NULL == strtok_s( str3, &max3, NULL, &ptr1 ) ); VERIFY( NumViolations == ++violations ); VERIFY( NULL == strtok_s( str3, &max3, "?", NULL ) ); VERIFY( NumViolations == ++violations ); ptr3 = NULL; VERIFY( NULL == strtok_s( NULL, &max3, "?", &ptr3 ) ); VERIFY( NumViolations == ++violations ); #if RSIZE_MAX != SIZE_MAX max1 = ~0; VERIFY( NULL == strtok_s( str3, &max1, "?", &ptr1 ) ); VERIFY( NumViolations == ++violations ); #endif }
//Transmission and reception of SOCKS protocol(UDP) size_t __fastcall SOCKSUDPRequest( const char *OriginalSend, const size_t SendSize, PSTR OriginalRecv, const size_t RecvSize) { //Initialization std::shared_ptr<char> SendBuffer(new char[LARGE_PACKET_MAXSIZE]()); std::shared_ptr<SOCKET_DATA> TCPSocketData, UDPSocketData(new SOCKET_DATA()), LocalSocketData; memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); memset(UDPSocketData.get(), 0, sizeof(SOCKET_DATA)); if (!Parameter.SOCKS_UDP_NoHandshake) { std::shared_ptr<SOCKET_DATA> TCPSocketDataTemp(new SOCKET_DATA()), LocalSocketDataTemp(new SOCKET_DATA()); TCPSocketDataTemp.swap(TCPSocketData); LocalSocketDataTemp.swap(LocalSocketData); memset(TCPSocketData.get(), 0, sizeof(SOCKET_DATA)); memset(LocalSocketData.get(), 0, sizeof(SOCKET_DATA)); } //Socket initialization if (Parameter.SOCKS_Address_IPv6.Storage.ss_family > 0 && //IPv6 (Parameter.SOCKS_Protocol_Network == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv6 || //Auto select Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV6 || //IPv6 Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV4 && Parameter.SOCKS_Address_IPv4.Storage.ss_family == 0)) //Non-IPv4 { if (!Parameter.SOCKS_UDP_NoHandshake) { //TCP process TCPSocketData->SockAddr.ss_family = AF_INET6; ((PSOCKADDR_IN6)&TCPSocketData->SockAddr)->sin6_addr = Parameter.SOCKS_Address_IPv6.IPv6.sin6_addr; ((PSOCKADDR_IN6)&TCPSocketData->SockAddr)->sin6_port = Parameter.SOCKS_Address_IPv6.IPv6.sin6_port; TCPSocketData->AddrLen = sizeof(sockaddr_in6); TCPSocketData->Socket = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); //Local process LocalSocketData->SockAddr.ss_family = AF_INET6; LocalSocketData->AddrLen = sizeof(sockaddr_in6); } //UDP process UDPSocketData->SockAddr.ss_family = AF_INET6; ((PSOCKADDR_IN6)&UDPSocketData->SockAddr)->sin6_addr = Parameter.SOCKS_Address_IPv6.IPv6.sin6_addr; if (Parameter.SOCKS_UDP_NoHandshake) ((PSOCKADDR_IN6)&UDPSocketData->SockAddr)->sin6_port = Parameter.SOCKS_Address_IPv6.IPv6.sin6_port; UDPSocketData->AddrLen = sizeof(sockaddr_in6); UDPSocketData->Socket = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); } else if (Parameter.SOCKS_Address_IPv4.Storage.ss_family > 0 && //IPv4 (Parameter.SOCKS_Protocol_Network == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv4 || //Auto select Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV4 || //IPv4 Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV6 && Parameter.SOCKS_Address_IPv6.Storage.ss_family == 0)) //Non-IPv6 { if (!Parameter.SOCKS_UDP_NoHandshake) { //TCP process TCPSocketData->SockAddr.ss_family = AF_INET; ((PSOCKADDR_IN)&TCPSocketData->SockAddr)->sin_addr = Parameter.SOCKS_Address_IPv4.IPv4.sin_addr; ((PSOCKADDR_IN)&TCPSocketData->SockAddr)->sin_port = Parameter.SOCKS_Address_IPv4.IPv4.sin_port; TCPSocketData->AddrLen = sizeof(sockaddr_in); TCPSocketData->Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //Local process LocalSocketData->SockAddr.ss_family = AF_INET; LocalSocketData->AddrLen = sizeof(sockaddr_in); } //UDP process UDPSocketData->SockAddr.ss_family = AF_INET; ((PSOCKADDR_IN)&UDPSocketData->SockAddr)->sin_addr = Parameter.SOCKS_Address_IPv4.IPv4.sin_addr; if (Parameter.SOCKS_UDP_NoHandshake) ((PSOCKADDR_IN)&UDPSocketData->SockAddr)->sin_port = Parameter.SOCKS_Address_IPv4.IPv4.sin_port; UDPSocketData->AddrLen = sizeof(sockaddr_in); UDPSocketData->Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); } else { return EXIT_FAILURE; } //Socket check if (!Parameter.SOCKS_UDP_NoHandshake && !SocketSetting(TCPSocketData->Socket, SOCKET_SETTING_INVALID_CHECK, nullptr) || !SocketSetting(UDPSocketData->Socket, SOCKET_SETTING_INVALID_CHECK, nullptr)) { closesocket(UDPSocketData->Socket); if (!Parameter.SOCKS_UDP_NoHandshake) closesocket(TCPSocketData->Socket); PrintError(LOG_ERROR_NETWORK, L"SOCKS socket initialization error", 0, nullptr, 0); return EXIT_FAILURE; } //Non-blocking mode setting if (!Parameter.SOCKS_UDP_NoHandshake && !SocketSetting(TCPSocketData->Socket, SOCKET_SETTING_NON_BLOCKING_MODE, nullptr) || !SocketSetting(UDPSocketData->Socket, SOCKET_SETTING_NON_BLOCKING_MODE, nullptr)) { closesocket(UDPSocketData->Socket); if (!Parameter.SOCKS_UDP_NoHandshake) closesocket(TCPSocketData->Socket); PrintError(LOG_ERROR_NETWORK, L"Socket non-blocking mode setting error", 0, nullptr, 0); return EXIT_FAILURE; } //Selecting structure setting std::shared_ptr<fd_set> ReadFDS(new fd_set()), WriteFDS(new fd_set()); std::shared_ptr<timeval> Timeout(new timeval()); memset(ReadFDS.get(), 0, sizeof(fd_set)); memset(WriteFDS.get(), 0, sizeof(fd_set)); memset(Timeout.get(), 0, sizeof(timeval)); //UDP transmission of standard SOCKS protocol must connect with TCP to server first. if (!Parameter.SOCKS_UDP_NoHandshake) { //Selection exchange process if (!SOCKSSelectionExchange(TCPSocketData.get(), ReadFDS.get(), WriteFDS.get(), Timeout.get(), SendBuffer.get(), OriginalRecv, RecvSize)) { shutdown(UDPSocketData->Socket, SD_BOTH); shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(UDPSocketData->Socket); closesocket(TCPSocketData->Socket); return EXIT_FAILURE; } else { memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); } //UDP connecting and get UDP socket infomation. if (SocketConnecting(IPPROTO_UDP, UDPSocketData->Socket, (PSOCKADDR)&UDPSocketData->SockAddr, UDPSocketData->AddrLen, nullptr, 0) == EXIT_FAILURE || getsockname(UDPSocketData->Socket, (PSOCKADDR)&LocalSocketData->SockAddr, &LocalSocketData->AddrLen) == SOCKET_ERROR) { shutdown(UDPSocketData->Socket, SD_BOTH); shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(UDPSocketData->Socket); closesocket(TCPSocketData->Socket); PrintError(LOG_ERROR_NETWORK, L"SOCKS connecting error", 0, nullptr, 0); return EXIT_FAILURE; } //Client command request process if (!SOCKSClientCommandRequest(IPPROTO_UDP, TCPSocketData->Socket, ReadFDS.get(), WriteFDS.get(), Timeout.get(), SendBuffer.get(), OriginalRecv, RecvSize, LocalSocketData.get())) { shutdown(UDPSocketData->Socket, SD_BOTH); shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(UDPSocketData->Socket); closesocket(TCPSocketData->Socket); return EXIT_FAILURE; } else { memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); //Copy network infomation from server message. if (UDPSocketData->SockAddr.ss_family == AF_INET6) ((PSOCKADDR_IN6)&UDPSocketData->SockAddr)->sin6_port = ((PSOCKADDR_IN6)&LocalSocketData->SockAddr)->sin6_port; else ((PSOCKADDR_IN)&UDPSocketData->SockAddr)->sin_port = ((PSOCKADDR_IN)&LocalSocketData->SockAddr)->sin_port; } } //UDP connecting again if (SocketConnecting(IPPROTO_UDP, UDPSocketData->Socket, (PSOCKADDR)&UDPSocketData->SockAddr, UDPSocketData->AddrLen, nullptr, 0) == EXIT_FAILURE) { if (!Parameter.SOCKS_UDP_NoHandshake) { shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(TCPSocketData->Socket); } PrintError(LOG_ERROR_NETWORK, L"SOCKS connecting error", 0, nullptr, 0); return EXIT_FAILURE; } //SOCKS UDP relay header SSIZE_T RecvLen = sizeof(socks_udp_relay_request); void *SOCKS_Pointer = SendBuffer.get(); if (Parameter.SOCKS_TargetServer.Storage.ss_family == AF_INET6) //IPv6 { ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type = SOCKS5_ADDRESS_IPV6; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(in6_addr); *(in6_addr *)SOCKS_Pointer = Parameter.SOCKS_TargetServer.IPv6.sin6_addr; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(uint16_t); *(PUINT16)SOCKS_Pointer = Parameter.SOCKS_TargetServer.IPv6.sin6_port; } else if (Parameter.SOCKS_TargetServer.Storage.ss_family == AF_INET) //IPv4 { ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type = SOCKS5_ADDRESS_IPV4; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(in_addr); *(in_addr *)SOCKS_Pointer = Parameter.SOCKS_TargetServer.IPv4.sin_addr; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(uint16_t); *(PUINT16)SOCKS_Pointer = Parameter.SOCKS_TargetServer.IPv4.sin_port; } else if (Parameter.SOCKS_TargetDomain != nullptr && Parameter.SOCKS_TargetDomain_Length > 0) //Damain { ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type = SOCKS5_ADDRESS_DOMAIN; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(uint8_t); *(PUINT8)SOCKS_Pointer = (uint8_t)Parameter.SOCKS_TargetDomain_Length; SOCKS_Pointer = SendBuffer.get() + RecvLen; memcpy_s(SOCKS_Pointer, (SSIZE_T)LARGE_PACKET_MAXSIZE - ((SSIZE_T)sizeof(socks_udp_relay_request) + RecvLen), Parameter.SOCKS_TargetDomain, Parameter.SOCKS_TargetDomain_Length); RecvLen += (SSIZE_T)Parameter.SOCKS_TargetDomain_Length; SOCKS_Pointer = SendBuffer.get() + RecvLen; *(PUINT16)SOCKS_Pointer = Parameter.SOCKS_TargetDomain_Port; RecvLen += (SSIZE_T)sizeof(uint16_t); } else { shutdown(UDPSocketData->Socket, SD_BOTH); closesocket(UDPSocketData->Socket); if (!Parameter.SOCKS_UDP_NoHandshake) { shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(TCPSocketData->Socket); } return EXIT_FAILURE; } memcpy_s(SendBuffer.get() + RecvLen, RecvSize, OriginalSend, SendSize); RecvLen += (SSIZE_T)SendSize; //Data exchange RecvLen = SOCKSSocketSelecting(UDPSocketData->Socket, ReadFDS.get(), WriteFDS.get(), Timeout.get(), SendBuffer.get(), RecvLen, OriginalRecv, RecvSize, sizeof(socks_udp_relay_request) + DNS_PACKET_MINSIZE); shutdown(UDPSocketData->Socket, SD_BOTH); closesocket(UDPSocketData->Socket); if (!Parameter.SOCKS_UDP_NoHandshake) { shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(TCPSocketData->Socket); } if (RecvLen >= (SSIZE_T)DNS_PACKET_MINSIZE) { //Remove SOCKS UDP relay header SOCKS_Pointer = OriginalRecv; if (Parameter.SOCKS_TargetServer.Storage.ss_family == AF_INET6 && //IPv6 ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_IPV6 && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t) + DNS_PACKET_MINSIZE) && memcmp((in6_addr *)(OriginalRecv + sizeof(socks_udp_relay_request)), &Parameter.SOCKS_TargetServer.IPv6.sin6_addr, sizeof(in6_addr)) == EXIT_SUCCESS && *(uint16_t *)(OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in6_addr)) == Parameter.SOCKS_TargetServer.IPv6.sin6_port) { memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t))); return RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t)); } else if (Parameter.SOCKS_TargetServer.Storage.ss_family == AF_INET && //IPv4 ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_IPV4 && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t) + DNS_PACKET_MINSIZE) && (*(in_addr *)(OriginalRecv + sizeof(socks_udp_relay_request))).S_un.S_addr == Parameter.SOCKS_TargetServer.IPv4.sin_addr.S_un.S_addr && *(uint16_t *)(OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in_addr)) == Parameter.SOCKS_TargetServer.IPv4.sin_port) { memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t))); return RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t)); } else if (Parameter.SOCKS_TargetDomain != nullptr && Parameter.SOCKS_TargetDomain_Length > 0) //Domain /* SOCKS server will reply IPv4/IPv6 address of domain. ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_DOMAIN && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain_Length + sizeof(uint16_t) + DNS_PACKET_MINSIZE) && *(uint8_t *)(OriginalRecv + sizeof(socks_udp_relay_request)) == Parameter.SOCKS_TargetDomain_Length && memcmp(OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(uint8_t), Parameter.SOCKS_TargetDomain, Parameter.SOCKS_TargetDomain_Length) == EXIT_SUCCESS && *(uint16_t *)(OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain_Length) == Parameter.SOCKS_TargetDomain_Port) */ { //IPv6 if (((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_IPV6 && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t) + DNS_PACKET_MINSIZE)) { memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t))); return RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t)); } //IPv4 else if (((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_IPV4 && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t) + DNS_PACKET_MINSIZE)) { memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t))); return RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t)); } // memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain_Length + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain_Length + sizeof(uint16_t))); // return RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain_Length + sizeof(uint16_t)); } } return EXIT_FAILURE; }
//Transmission and reception of SOCKS protocol(TCP) size_t __fastcall SOCKSTCPRequest( const char *OriginalSend, const size_t SendSize, PSTR OriginalRecv, const size_t RecvSize) { //Initialization std::shared_ptr<char> SendBuffer(new char[LARGE_PACKET_MAXSIZE]()); std::shared_ptr<SOCKET_DATA> TCPSocketData(new SOCKET_DATA()); memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); memset(TCPSocketData.get(), 0, sizeof(SOCKET_DATA)); //Socket initialization if (Parameter.SOCKS_Address_IPv6.Storage.ss_family > 0 && //IPv6 (Parameter.SOCKS_Protocol_Network == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv6 || //Auto select Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV6 || //IPv6 Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV4 && Parameter.SOCKS_Address_IPv4.Storage.ss_family == 0)) //Non-IPv4 { TCPSocketData->SockAddr.ss_family = AF_INET6; ((PSOCKADDR_IN6)&TCPSocketData->SockAddr)->sin6_addr = Parameter.SOCKS_Address_IPv6.IPv6.sin6_addr; ((PSOCKADDR_IN6)&TCPSocketData->SockAddr)->sin6_port = Parameter.SOCKS_Address_IPv6.IPv6.sin6_port; TCPSocketData->AddrLen = sizeof(sockaddr_in6); TCPSocketData->Socket = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); } else if (Parameter.SOCKS_Address_IPv4.Storage.ss_family > 0 && //IPv4 (Parameter.SOCKS_Protocol_Network == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv4 || //Auto select Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV4 || //IPv4 Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV6 && Parameter.SOCKS_Address_IPv6.Storage.ss_family == 0)) //Non-IPv6 { TCPSocketData->SockAddr.ss_family = AF_INET; ((PSOCKADDR_IN)&TCPSocketData->SockAddr)->sin_addr = Parameter.SOCKS_Address_IPv4.IPv4.sin_addr; ((PSOCKADDR_IN)&TCPSocketData->SockAddr)->sin_port = Parameter.SOCKS_Address_IPv4.IPv4.sin_port; TCPSocketData->AddrLen = sizeof(sockaddr_in); TCPSocketData->Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } else { return EXIT_FAILURE; } //Socket check if (!SocketSetting(TCPSocketData->Socket, SOCKET_SETTING_INVALID_CHECK, nullptr)) { PrintError(LOG_ERROR_NETWORK, L"SOCKS socket initialization error", 0, nullptr, 0); return EXIT_FAILURE; } //Non-blocking mode setting if (!SocketSetting(TCPSocketData->Socket, SOCKET_SETTING_NON_BLOCKING_MODE, nullptr)) { shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(TCPSocketData->Socket); PrintError(LOG_ERROR_NETWORK, L"Socket non-blocking mode setting error", 0, nullptr, 0); return EXIT_FAILURE; } //Selecting structure setting std::shared_ptr<fd_set> ReadFDS(new fd_set()), WriteFDS(new fd_set()); std::shared_ptr<timeval> Timeout(new timeval()); memset(ReadFDS.get(), 0, sizeof(fd_set)); memset(WriteFDS.get(), 0, sizeof(fd_set)); memset(Timeout.get(), 0, sizeof(timeval)); //Selection exchange process if (Parameter.SOCKS_Version == SOCKS_VERSION_5) { if (!SOCKSSelectionExchange(TCPSocketData.get(), ReadFDS.get(), WriteFDS.get(), Timeout.get(), SendBuffer.get(), OriginalRecv, RecvSize)) { shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(TCPSocketData->Socket); return EXIT_FAILURE; } else { memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); } } //Client command request process if (!SOCKSClientCommandRequest(IPPROTO_TCP, TCPSocketData->Socket, ReadFDS.get(), WriteFDS.get(), Timeout.get(), SendBuffer.get(), OriginalRecv, RecvSize, TCPSocketData.get())) { shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(TCPSocketData->Socket); return EXIT_FAILURE; } else { memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); } //Add length of request packet(It must be written in header when transpot with TCP protocol). memcpy_s(SendBuffer.get(), RecvSize, OriginalSend, SendSize); SSIZE_T RecvLen = AddLengthDataToHeader(SendBuffer.get(), SendSize, RecvSize); if (RecvLen < (SSIZE_T)DNS_PACKET_MINSIZE) { shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(TCPSocketData->Socket); return EXIT_FAILURE; } //Data exchange RecvLen = SOCKSSocketSelecting(TCPSocketData->Socket, ReadFDS.get(), WriteFDS.get(), Timeout.get(), SendBuffer.get(), RecvLen, OriginalRecv, RecvSize, DNS_PACKET_MINSIZE); shutdown(TCPSocketData->Socket, SD_BOTH); closesocket(TCPSocketData->Socket); if (RecvLen >= (SSIZE_T)DNS_PACKET_MINSIZE) { memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(uint16_t), RecvLen); return RecvLen; } return EXIT_FAILURE; }
void UDPTestReply(Host Session_SN, ushort Reply2ID, Host Tested) { uchar Request[0xFFF]; uchar Buffer[LOCATION_SZ] = {0}; ushort TransID; uchar *PRequest, *Mark; uint Size, SizeSz; ObjectDesc ObjLocation, ObjAddr; PRequest = Request; ZeroMemory(Request, 0xFFF); TransID = BytesRandomWord(); if (0xFFFF - TransID < 0x1000) TransID -= 0x1000; *(unsigned short *)PRequest = htons(TransID); PRequest += 2; Mark = PRequest; WriteValue(&PRequest, 0x2C); WriteValue(&PRequest, 0x1CB); *(unsigned short *)PRequest = htons(Reply2ID); PRequest += 2; *PRequest++ = RAW_PARAMS; WriteValue(&PRequest, 0x03); BuildLocationBlob(Session_Node, &Buffer[0]); ObjLocation.Family = OBJ_FAMILY_BLOB; ObjLocation.Id = 0x00; ObjLocation.Value.Memory.Memory = Buffer; ObjLocation.Value.Memory.MsZ = LOCATION_SZ; WriteObject(&PRequest, ObjLocation); struct in_addr PublicIP; PublicIP.S_un.S_addr = my_public_ip; ObjAddr.Family = OBJ_FAMILY_NETADDR; ObjAddr.Id = OBJ_ID_TESTED; strcpy_s(ObjAddr.Value.Addr.ip, MAX_IP_LEN + 1, inet_ntoa(PublicIP)); ObjAddr.Value.Addr.port = GetListeningPort(); WriteObject(&PRequest, ObjAddr); ObjAddr.Family = OBJ_FAMILY_NETADDR; ObjAddr.Id = OBJ_ID_TESTED; ObjAddr.Value.Addr = Tested; WriteObject(&PRequest, ObjAddr); Size = (uint)(PRequest - Request); SizeSz = GetWrittenSz(Size << 1); PRequest = Request; memmove_s(Request + SizeSz, 0xFF, Request, 0xFF - SizeSz); WriteValue(&PRequest , Size << 1); Size += SizeSz; CipherTCP(&(Keys.SendStream), Request, 3); CipherTCP(&(Keys.SendStream), Request + 3, Size - 3); printf("Sending UDPTest Response..\n"); NoWait = 1; SendPacketTCP(Session_SN.socket, Session_SN, Request, Size, HTTPS_PORT, &(Session_SN.Connected)); }
bool AudioBufferManager::processSrcData( const void** appSrcBuffer, CAUDIO_U32_t aSrcBufferLen, CAUDIO_U32_t aSrcDataSize, void** appOutBuffer, CAUDIO_U32_t aOutBufferLen) { if(!mIsInitSuccess) { AUDIO_PROCESSING_PRINTF("init AudioBufferManager failed"); return false; } if (NULL == appSrcBuffer) { AUDIO_PROCESSING_PRINTF("apSrcBuffer is NULL"); return false; } if(mMode != AUDIO_BUFFER_MANAGER_MODE_PROCESS) { AUDIO_PROCESSING_PRINTF("this API is only for process mode"); return false; } CAUDIO_U32_t srcDataLen = mLenOfSample * aSrcDataSize; // calculate processing rounds according to mFrameShiftLen CAUDIO_U32_t maxLoop = (srcDataLen + mpBufferCondition[0].mInDefBufferWritePtr) / mFrameShiftLen; for (CAUDIO_U32_t i = 0; i < maxLoop; i++) { if (!readFrameShiftDataFromSrcBuffer(appSrcBuffer, aSrcBufferLen, srcDataLen)) { return false; } // call callback function if (!mAudioProcessor.processData(mppProcessBufferPtrs, mProcessBufferLen, mInChannelNum, mOutChannelNum)) { AUDIO_PROCESSING_PRINTF("process data failed"); } // copy data to post processed buffer as much as what is processed if (!writeToPostProcessBuffer()) { return false; } } // copy data from post process buffer to out channel buffer for every out channel for (CAUDIO_U8_t channelIndex = 0; channelIndex < mOutChannelNum; channelIndex++) { void* pOutChannelBuf = *(appOutBuffer + channelIndex); memcpy_s(pOutChannelBuf, aOutBufferLen, (const CAUDIO_U8_t*)mpBufferCondition[channelIndex].mpPostProcessBuffer, srcDataLen); if (srcDataLen < mpBufferCondition[channelIndex].mPostProBufWrtPtr) { // move left data in post process buffer to the head of buffer memmove_s(mpBufferCondition[channelIndex].mpPostProcessBuffer, mPostProcessBufferLen, (const CAUDIO_U8_t*)mpBufferCondition[channelIndex].mpPostProcessBuffer + srcDataLen, mpBufferCondition[channelIndex].mPostProBufWrtPtr - srcDataLen); } mpBufferCondition[channelIndex].mPostProBufWrtPtr -= srcDataLen; } // copy left source data from in channel buffer to in deficiency buffer // these data would be processed at next calling for (CAUDIO_U8_t channelIndex = 0; channelIndex < mInChannelNum; channelIndex++) { CAUDIO_U32_t srcDataLeft = srcDataLen - mpBufferCondition[channelIndex].mSrcBufferReadPtr; if (0 < srcDataLeft) { const void* pSrcChannelBuf = *(appSrcBuffer + channelIndex); memcpy_s((CAUDIO_U8_t *)mpBufferCondition[channelIndex].mpInDeficiencyBuffer + mpBufferCondition[channelIndex].mInDefBufferWritePtr, mInDefBufferLen - mpBufferCondition[channelIndex].mInDefBufferWritePtr, (const CAUDIO_U8_t*)pSrcChannelBuf + mpBufferCondition[channelIndex].mSrcBufferReadPtr, srcDataLeft); mpBufferCondition[channelIndex].mInDefBufferWritePtr += srcDataLeft; } mpBufferCondition[channelIndex].mSrcBufferReadPtr = 0; } return true; }
//Transmission and reception of SOCKS protocol(TCP) size_t __fastcall SOCKSTCPRequest( const char *OriginalSend, const size_t SendSize, char *OriginalRecv, const size_t RecvSize) { //Initialization std::shared_ptr<char> SendBuffer(new char[LARGE_PACKET_MAXSIZE]()); memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); SOCKET_DATA TCPSocketData = {0}; memset(OriginalRecv, 0, RecvSize); //Socket initialization if (Parameter.SOCKS_Address_IPv6.Storage.ss_family > 0 && //IPv6 (Parameter.SOCKS_Protocol_Network == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv6 || //Auto select Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV6 || //IPv6 Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV4 && Parameter.SOCKS_Address_IPv4.Storage.ss_family == 0)) //Non-IPv4 { TCPSocketData.SockAddr.ss_family = AF_INET6; ((PSOCKADDR_IN6)&TCPSocketData.SockAddr)->sin6_addr = Parameter.SOCKS_Address_IPv6.IPv6.sin6_addr; ((PSOCKADDR_IN6)&TCPSocketData.SockAddr)->sin6_port = Parameter.SOCKS_Address_IPv6.IPv6.sin6_port; TCPSocketData.AddrLen = sizeof(sockaddr_in6); TCPSocketData.Socket = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); } else if (Parameter.SOCKS_Address_IPv4.Storage.ss_family > 0 && //IPv4 (Parameter.SOCKS_Protocol_Network == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv4 || //Auto select Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV4 || //IPv4 Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV6 && Parameter.SOCKS_Address_IPv6.Storage.ss_family == 0)) //Non-IPv6 { TCPSocketData.SockAddr.ss_family = AF_INET; ((PSOCKADDR_IN)&TCPSocketData.SockAddr)->sin_addr = Parameter.SOCKS_Address_IPv4.IPv4.sin_addr; ((PSOCKADDR_IN)&TCPSocketData.SockAddr)->sin_port = Parameter.SOCKS_Address_IPv4.IPv4.sin_port; TCPSocketData.AddrLen = sizeof(sockaddr_in); TCPSocketData.Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } else { return EXIT_FAILURE; } //Socket check if (!SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_INVALID_CHECK, false, nullptr)) { PrintError(LOG_LEVEL_2, LOG_ERROR_NETWORK, L"SOCKS socket initialization error", 0, nullptr, 0); return EXIT_FAILURE; } //Non-blocking mode setting and Hop Limits setting if (!SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_NON_BLOCKING_MODE, true, nullptr) || TCPSocketData.SockAddr.ss_family == AF_INET6 && !SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_HOP_LIMITS_IPV6, true, nullptr) || TCPSocketData.SockAddr.ss_family == AF_INET && (!SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_HOP_LIMITS_IPV4, true, nullptr) || !SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_DO_NOT_FRAGMENT, true, nullptr))) { shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(TCPSocketData.Socket); return EXIT_FAILURE; } //Selecting structure setting fd_set ReadFDS = {0}, WriteFDS = {0}; timeval Timeout = {0}; //Selection exchange process if (Parameter.SOCKS_Version == SOCKS_VERSION_5) { if (!SOCKSSelectionExchange(&TCPSocketData, &ReadFDS, &WriteFDS, &Timeout, SendBuffer.get(), OriginalRecv, RecvSize)) { shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(TCPSocketData.Socket); return EXIT_FAILURE; } else { memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); } } //Client command request process if (!SOCKSClientCommandRequest(IPPROTO_TCP, TCPSocketData.Socket, &ReadFDS, &WriteFDS, &Timeout, SendBuffer.get(), OriginalRecv, RecvSize, &TCPSocketData)) { shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(TCPSocketData.Socket); return EXIT_FAILURE; } else { memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); } //Add length of request packet(It must be written in header when transpot with TCP protocol). memcpy_s(SendBuffer.get(), RecvSize, OriginalSend, SendSize); SSIZE_T RecvLen = AddLengthDataToHeader(SendBuffer.get(), SendSize, RecvSize); if (RecvLen < (SSIZE_T)DNS_PACKET_MINSIZE) { shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(TCPSocketData.Socket); return EXIT_FAILURE; } //Socket timeout setting #if defined(PLATFORM_WIN) Timeout.tv_sec = Parameter.SOCKS_SocketTimeout_Reliable / SECOND_TO_MILLISECOND; Timeout.tv_usec = Parameter.SOCKS_SocketTimeout_Reliable % SECOND_TO_MILLISECOND * MICROSECOND_TO_MILLISECOND; #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) Timeout.tv_sec = Parameter.SOCKS_SocketTimeout_Reliable.tv_sec; Timeout.tv_usec = Parameter.SOCKS_SocketTimeout_Reliable.tv_usec; #endif //Data exchange RecvLen = ProxySocketSelecting(TCPSocketData.Socket, &ReadFDS, &WriteFDS, &Timeout, SendBuffer.get(), RecvLen, OriginalRecv, RecvSize, DNS_PACKET_MINSIZE, nullptr); shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(TCPSocketData.Socket); //Server response check if (RecvLen >= (SSIZE_T)DNS_PACKET_MINSIZE && ntohs(((uint16_t *)OriginalRecv)[0]) >= DNS_PACKET_MINSIZE && RecvLen >= ntohs(((uint16_t *)OriginalRecv)[0])) { RecvLen = ntohs(((uint16_t *)OriginalRecv)[0]); memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(uint16_t), RecvLen); //Responses check RecvLen = CheckResponseData( REQUEST_PROCESS_SOCKS, OriginalRecv, RecvLen, RecvSize, nullptr); if (RecvLen < (SSIZE_T)DNS_PACKET_MINSIZE) return EXIT_FAILURE; //Mark DNS cache. if (Parameter.CacheType > 0) MarkDomainCache(OriginalRecv, RecvLen); return RecvLen; } return EXIT_FAILURE; }
//Transmission and reception of SOCKS protocol(UDP) size_t __fastcall SOCKSUDPRequest( const char *OriginalSend, const size_t SendSize, char *OriginalRecv, const size_t RecvSize) { //Initialization std::shared_ptr<char> SendBuffer(new char[LARGE_PACKET_MAXSIZE]()); memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); SOCKET_DATA TCPSocketData = {0}, LocalSocketData = {0}, UDPSocketData = {0}; memset(OriginalRecv, 0, RecvSize); //Socket initialization if (Parameter.SOCKS_Address_IPv6.Storage.ss_family > 0 && //IPv6 (Parameter.SOCKS_Protocol_Network == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv6 || //Auto select Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV6 || //IPv6 Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV4 && Parameter.SOCKS_Address_IPv4.Storage.ss_family == 0)) //Non-IPv4 { if (!Parameter.SOCKS_UDP_NoHandshake) { //TCP process TCPSocketData.SockAddr.ss_family = AF_INET6; ((PSOCKADDR_IN6)&TCPSocketData.SockAddr)->sin6_addr = Parameter.SOCKS_Address_IPv6.IPv6.sin6_addr; ((PSOCKADDR_IN6)&TCPSocketData.SockAddr)->sin6_port = Parameter.SOCKS_Address_IPv6.IPv6.sin6_port; TCPSocketData.AddrLen = sizeof(sockaddr_in6); TCPSocketData.Socket = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); //Local process LocalSocketData.SockAddr.ss_family = AF_INET6; LocalSocketData.AddrLen = sizeof(sockaddr_in6); } //UDP process UDPSocketData.SockAddr.ss_family = AF_INET6; ((PSOCKADDR_IN6)&UDPSocketData.SockAddr)->sin6_addr = Parameter.SOCKS_Address_IPv6.IPv6.sin6_addr; if (Parameter.SOCKS_UDP_NoHandshake) ((PSOCKADDR_IN6)&UDPSocketData.SockAddr)->sin6_port = Parameter.SOCKS_Address_IPv6.IPv6.sin6_port; UDPSocketData.AddrLen = sizeof(sockaddr_in6); UDPSocketData.Socket = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); } else if (Parameter.SOCKS_Address_IPv4.Storage.ss_family > 0 && //IPv4 (Parameter.SOCKS_Protocol_Network == REQUEST_MODE_NETWORK_BOTH && GlobalRunningStatus.GatewayAvailable_IPv4 || //Auto select Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV4 || //IPv4 Parameter.SOCKS_Protocol_Network == REQUEST_MODE_IPV6 && Parameter.SOCKS_Address_IPv6.Storage.ss_family == 0)) //Non-IPv6 { if (!Parameter.SOCKS_UDP_NoHandshake) { //TCP process TCPSocketData.SockAddr.ss_family = AF_INET; ((PSOCKADDR_IN)&TCPSocketData.SockAddr)->sin_addr = Parameter.SOCKS_Address_IPv4.IPv4.sin_addr; ((PSOCKADDR_IN)&TCPSocketData.SockAddr)->sin_port = Parameter.SOCKS_Address_IPv4.IPv4.sin_port; TCPSocketData.AddrLen = sizeof(sockaddr_in); TCPSocketData.Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //Local process LocalSocketData.SockAddr.ss_family = AF_INET; LocalSocketData.AddrLen = sizeof(sockaddr_in); } //UDP process UDPSocketData.SockAddr.ss_family = AF_INET; ((PSOCKADDR_IN)&UDPSocketData.SockAddr)->sin_addr = Parameter.SOCKS_Address_IPv4.IPv4.sin_addr; if (Parameter.SOCKS_UDP_NoHandshake) ((PSOCKADDR_IN)&UDPSocketData.SockAddr)->sin_port = Parameter.SOCKS_Address_IPv4.IPv4.sin_port; UDPSocketData.AddrLen = sizeof(sockaddr_in); UDPSocketData.Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); } else { return EXIT_FAILURE; } //Socket check and Hop Limits setting if (!Parameter.SOCKS_UDP_NoHandshake && !SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_INVALID_CHECK, false, nullptr) || TCPSocketData.SockAddr.ss_family == AF_INET6 && !SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_HOP_LIMITS_IPV6, false, nullptr) || TCPSocketData.SockAddr.ss_family == AF_INET && (!SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_HOP_LIMITS_IPV4, false, nullptr) || !SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_DO_NOT_FRAGMENT, true, nullptr)) || !SocketSetting(UDPSocketData.Socket, SOCKET_SETTING_INVALID_CHECK, false, nullptr) || UDPSocketData.SockAddr.ss_family == AF_INET6 && !SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_HOP_LIMITS_IPV6, false, nullptr) || UDPSocketData.SockAddr.ss_family == AF_INET && (!SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_HOP_LIMITS_IPV4, false, nullptr) || !SocketSetting(UDPSocketData.Socket, SOCKET_SETTING_DO_NOT_FRAGMENT, true, nullptr))) { closesocket(UDPSocketData.Socket); if (!Parameter.SOCKS_UDP_NoHandshake) closesocket(TCPSocketData.Socket); PrintError(LOG_LEVEL_2, LOG_ERROR_NETWORK, L"SOCKS socket initialization error", 0, nullptr, 0); return EXIT_FAILURE; } //Non-blocking mode setting if (!Parameter.SOCKS_UDP_NoHandshake && !SocketSetting(TCPSocketData.Socket, SOCKET_SETTING_NON_BLOCKING_MODE, true, nullptr) || !SocketSetting(UDPSocketData.Socket, SOCKET_SETTING_NON_BLOCKING_MODE, true, nullptr)) { closesocket(UDPSocketData.Socket); if (!Parameter.SOCKS_UDP_NoHandshake) closesocket(TCPSocketData.Socket); return EXIT_FAILURE; } //Selecting structure setting fd_set ReadFDS = {0}, WriteFDS = {0}; timeval Timeout = {0}; //UDP transmission of standard SOCKS protocol must connect with TCP to server at first. if (!Parameter.SOCKS_UDP_NoHandshake) { //Selection exchange process if (!SOCKSSelectionExchange(&TCPSocketData, &ReadFDS, &WriteFDS, &Timeout, SendBuffer.get(), OriginalRecv, RecvSize)) { shutdown(UDPSocketData.Socket, SD_BOTH); shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(UDPSocketData.Socket); closesocket(TCPSocketData.Socket); return EXIT_FAILURE; } else { memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); } //UDP connecting and get UDP socket infomation. if (SocketConnecting(IPPROTO_UDP, UDPSocketData.Socket, (PSOCKADDR)&UDPSocketData.SockAddr, UDPSocketData.AddrLen, nullptr, 0) == EXIT_FAILURE || getsockname(UDPSocketData.Socket, (PSOCKADDR)&LocalSocketData.SockAddr, &LocalSocketData.AddrLen) == SOCKET_ERROR) { shutdown(UDPSocketData.Socket, SD_BOTH); shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(UDPSocketData.Socket); closesocket(TCPSocketData.Socket); PrintError(LOG_LEVEL_3, LOG_ERROR_NETWORK, L"SOCKS connecting error", 0, nullptr, 0); return EXIT_FAILURE; } //Client command request process if (!SOCKSClientCommandRequest(IPPROTO_UDP, TCPSocketData.Socket, &ReadFDS, &WriteFDS, &Timeout, SendBuffer.get(), OriginalRecv, RecvSize, &LocalSocketData)) { shutdown(UDPSocketData.Socket, SD_BOTH); shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(UDPSocketData.Socket); closesocket(TCPSocketData.Socket); return EXIT_FAILURE; } else { memset(SendBuffer.get(), 0, LARGE_PACKET_MAXSIZE); //Copy network infomation from server message. if (UDPSocketData.SockAddr.ss_family == AF_INET6) ((PSOCKADDR_IN6)&UDPSocketData.SockAddr)->sin6_port = ((PSOCKADDR_IN6)&LocalSocketData.SockAddr)->sin6_port; else ((PSOCKADDR_IN)&UDPSocketData.SockAddr)->sin_port = ((PSOCKADDR_IN)&LocalSocketData.SockAddr)->sin_port; } } //UDP connecting again if (SocketConnecting(IPPROTO_UDP, UDPSocketData.Socket, (PSOCKADDR)&UDPSocketData.SockAddr, UDPSocketData.AddrLen, nullptr, 0) == EXIT_FAILURE) { if (!Parameter.SOCKS_UDP_NoHandshake) { shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(TCPSocketData.Socket); } PrintError(LOG_LEVEL_3, LOG_ERROR_NETWORK, L"SOCKS connecting error", 0, nullptr, 0); return EXIT_FAILURE; } //SOCKS UDP relay header SSIZE_T RecvLen = sizeof(socks_udp_relay_request); void *SOCKS_Pointer = SendBuffer.get(); if (Parameter.SOCKS_TargetServer.Storage.ss_family == AF_INET6) //IPv6 { ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type = SOCKS5_ADDRESS_IPV6; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(in6_addr); *(in6_addr *)SOCKS_Pointer = Parameter.SOCKS_TargetServer.IPv6.sin6_addr; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(uint16_t); *(uint16_t *)SOCKS_Pointer = Parameter.SOCKS_TargetServer.IPv6.sin6_port; } else if (Parameter.SOCKS_TargetServer.Storage.ss_family == AF_INET) //IPv4 { ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type = SOCKS5_ADDRESS_IPV4; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(in_addr); *(in_addr *)SOCKS_Pointer = Parameter.SOCKS_TargetServer.IPv4.sin_addr; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(uint16_t); *(uint16_t *)SOCKS_Pointer = Parameter.SOCKS_TargetServer.IPv4.sin_port; } else if (Parameter.SOCKS_TargetDomain != nullptr && !Parameter.SOCKS_TargetDomain->empty()) //Damain { ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type = SOCKS5_ADDRESS_DOMAIN; SOCKS_Pointer = SendBuffer.get() + RecvLen; RecvLen += (SSIZE_T)sizeof(uint8_t); *(uint8_t *)SOCKS_Pointer = (uint8_t)Parameter.SOCKS_TargetDomain->length(); SOCKS_Pointer = SendBuffer.get() + RecvLen; memcpy_s(SOCKS_Pointer, (SSIZE_T)LARGE_PACKET_MAXSIZE - ((SSIZE_T)sizeof(socks_udp_relay_request) + RecvLen), Parameter.SOCKS_TargetDomain->c_str(), Parameter.SOCKS_TargetDomain->length()); RecvLen += (SSIZE_T)Parameter.SOCKS_TargetDomain->length(); SOCKS_Pointer = SendBuffer.get() + RecvLen; *(uint16_t *)SOCKS_Pointer = Parameter.SOCKS_TargetDomain_Port; RecvLen += (SSIZE_T)sizeof(uint16_t); } else { shutdown(UDPSocketData.Socket, SD_BOTH); closesocket(UDPSocketData.Socket); if (!Parameter.SOCKS_UDP_NoHandshake) { shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(TCPSocketData.Socket); } return EXIT_FAILURE; } memcpy_s(SendBuffer.get() + RecvLen, RecvSize, OriginalSend, SendSize); RecvLen += (SSIZE_T)SendSize; //Socket timeout setting #if defined(PLATFORM_WIN) Timeout.tv_sec = Parameter.SOCKS_SocketTimeout_Unreliable / SECOND_TO_MILLISECOND; Timeout.tv_usec = Parameter.SOCKS_SocketTimeout_Unreliable % SECOND_TO_MILLISECOND * MICROSECOND_TO_MILLISECOND; #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) Timeout.tv_sec = Parameter.SOCKS_SocketTimeout_Reliable.tv_sec; Timeout.tv_usec = Parameter.SOCKS_SocketTimeout_Reliable.tv_usec; #endif //Data exchange RecvLen = ProxySocketSelecting(UDPSocketData.Socket, &ReadFDS, &WriteFDS, &Timeout, SendBuffer.get(), RecvLen, OriginalRecv, RecvSize, sizeof(socks_udp_relay_request) + DNS_PACKET_MINSIZE, nullptr); shutdown(UDPSocketData.Socket, SD_BOTH); closesocket(UDPSocketData.Socket); if (!Parameter.SOCKS_UDP_NoHandshake) { shutdown(TCPSocketData.Socket, SD_BOTH); closesocket(TCPSocketData.Socket); } if (RecvLen >= (SSIZE_T)DNS_PACKET_MINSIZE) { SSIZE_T OriginalRecvLen = RecvLen; //Remove SOCKS UDP relay header SOCKS_Pointer = OriginalRecv; if (Parameter.SOCKS_TargetServer.Storage.ss_family == AF_INET6 && //IPv6 ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_IPV6 && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t) + DNS_PACKET_MINSIZE) && memcmp((in6_addr *)(OriginalRecv + sizeof(socks_udp_relay_request)), &Parameter.SOCKS_TargetServer.IPv6.sin6_addr, sizeof(in6_addr)) == 0 && *(uint16_t *)(OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in6_addr)) == Parameter.SOCKS_TargetServer.IPv6.sin6_port) { memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t))); RecvLen -= sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t); } else if (Parameter.SOCKS_TargetServer.Storage.ss_family == AF_INET && //IPv4 ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_IPV4 && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t) + DNS_PACKET_MINSIZE) && (*(in_addr *)(OriginalRecv + sizeof(socks_udp_relay_request))).s_addr == Parameter.SOCKS_TargetServer.IPv4.sin_addr.s_addr && *(uint16_t *)(OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in_addr)) == Parameter.SOCKS_TargetServer.IPv4.sin_port) { memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t))); RecvLen -= sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t); } else if (Parameter.SOCKS_TargetDomain != nullptr && !Parameter.SOCKS_TargetDomain->empty()) //Domain /* SOCKS server will reply IPv4/IPv6 address of domain. ((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_DOMAIN && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain->length() + sizeof(uint16_t) + DNS_PACKET_MINSIZE) && *(uint8_t *)(OriginalRecv + sizeof(socks_udp_relay_request)) == Parameter.SOCKS_TargetDomain->length() && memcmp(OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(uint8_t), Parameter.SOCKS_TargetDomain->c_str(), Parameter.SOCKS_TargetDomain->length()) == 0 && *(uint16_t *)(OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain->length()) == Parameter.SOCKS_TargetDomain_Port) */ { //IPv6 if (((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_IPV6 && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t) + DNS_PACKET_MINSIZE)) { memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t))); RecvLen -= sizeof(socks_udp_relay_request) + sizeof(in6_addr) + sizeof(uint16_t); } //IPv4 else if (((psocks_udp_relay_request)SOCKS_Pointer)->Address_Type == SOCKS5_ADDRESS_IPV4 && RecvLen >= (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t) + DNS_PACKET_MINSIZE)) { memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t))); RecvLen -= sizeof(socks_udp_relay_request) + sizeof(in_addr) + sizeof(uint16_t); } /* SOCKS server will reply IPv4/IPv6 address of domain. memmove_s(OriginalRecv, RecvSize, OriginalRecv + sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain->length() + sizeof(uint16_t), RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain->length() + sizeof(uint16_t))); return RecvLen - (SSIZE_T)(sizeof(socks_udp_relay_request) + sizeof(uint8_t) + Parameter.SOCKS_TargetDomain->length() + sizeof(uint16_t)); */ } //Server response check if (OriginalRecvLen != RecvLen) { //Responses check RecvLen = CheckResponseData( REQUEST_PROCESS_SOCKS, OriginalRecv, RecvLen, RecvSize, nullptr); if (RecvLen < (SSIZE_T)DNS_PACKET_MINSIZE) return EXIT_FAILURE; //Mark DNS cache. if (Parameter.CacheType > 0) MarkDomainCache(OriginalRecv, RecvLen); return RecvLen; } } return EXIT_FAILURE; }
long CSpiroView::GetWheelDistanceForFigure() const { ENSURE(m_pWheel != NULL && m_pAnchor != NULL); double dPerimWheel = m_pWheel->GetPerimeter(); double dPerimAnchor = m_pAnchor->GetPerimeter(); bool bInverted(false); // Anchor and wheel swapped to have anchor > wheel. if (dPerimAnchor < dPerimWheel) { bInverted = true; double d = dPerimAnchor; dPerimAnchor = dPerimWheel; dPerimWheel = d; } double dRemain = 0; long rgCycleOrder[200]; double rgdCycleLimits[2][200]; // first and last mark in every cycle double dCurrentPos = 0.0; int nTurnsThisCycle; int nTotalTurns = 0; int i; long nTolerance = m_pAnchor->GetCycleError(); // returns distance tolerance for one figure int iCycle; for (iCycle = 0;iCycle < 200;iCycle++) { nTurnsThisCycle = (long)((dPerimAnchor + dRemain) / dPerimWheel); rgdCycleLimits[0][iCycle] = dCurrentPos + dPerimWheel; while (rgdCycleLimits[0][iCycle] - dPerimAnchor >= 0.0) rgdCycleLimits[0][iCycle] -= dPerimAnchor; rgdCycleLimits[1][iCycle] = dCurrentPos + nTurnsThisCycle * dPerimWheel; while (rgdCycleLimits[1][iCycle] - dPerimAnchor >= 0.0) rgdCycleLimits[1][iCycle] -= dPerimAnchor; ASSERT(rgdCycleLimits[1][iCycle] >= 0.0 && rgdCycleLimits[1][iCycle] < dPerimAnchor); rgCycleOrder[iCycle] = iCycle; // rgCycleOrder says the order of the columns // sort the cycle order to find which columns go first for (i = 0; i < iCycle; i++) { // is new cycle being inserted at position i? if (rgdCycleLimits[0][rgCycleOrder[i]] > rgdCycleLimits[0][iCycle]) { //yes. Insert iCycle in this position in rgCycleOrder memmove_s((int*)rgCycleOrder + i + 1, (iCycle - i) * sizeof(int), (int*)rgCycleOrder + i, (iCycle - i) * sizeof(int)); rgCycleOrder[i] = iCycle; break; } } double dLastGap(0); // Initialize to avoid compiler warnings. double dThisGap; double dLastPos; double dThisPos; // check if the values are so close to the origin that the cycle is complete bool bFirstTurnCloses = rgdCycleLimits[0][iCycle] < (double)nTolerance; if (bFirstTurnCloses || // close to origin? check gaps dPerimAnchor - rgdCycleLimits[1][iCycle] < (double)nTolerance || rgdCycleLimits[1][iCycle] < 0.000000001) { dLastPos = rgdCycleLimits[0][rgCycleOrder[0]]; for (i = 1; i < iCycle; i++) { dThisGap = (dThisPos = rgdCycleLimits[0][rgCycleOrder[i]]) - dLastPos; if (i > 1 && abs((long)(dThisGap - dLastGap)) > nTolerance / 4) // there are gaps to be filled in break; dLastGap = dThisGap; dLastPos = dThisPos; } if (i == iCycle) { nTotalTurns += bFirstTurnCloses? 1 : nTurnsThisCycle; break; } } nTotalTurns += nTurnsThisCycle; dCurrentPos = rgdCycleLimits[1][iCycle]; dRemain = dPerimAnchor - dCurrentPos; } if (bInverted) // adjust the number of turns { double d = (double)nTotalTurns * dPerimWheel / dPerimAnchor; nTotalTurns = (long)d; if (d - (double)nTotalTurns > 0.9) nTotalTurns++; dPerimWheel = dPerimAnchor; } ASSERT(nTotalTurns < 200 && nTotalTurns > 0); return (long)(nTotalTurns * dPerimWheel); }