const wchar_t * WcharMbcsConvertor::char2wchar(const char * mbcs2Convert, UINT codepage, int lenMbcs, int *pLenWc, int *pBytesNotProcessed) { // Do not process NULL pointer if (!mbcs2Convert) return NULL; // Do not process empty strings if (lenMbcs == 0 || lenMbcs == -1 && mbcs2Convert[0] == 0) { _wideCharStr.empty(); return _wideCharStr; } int bytesNotProcessed = 0; int lenWc = 0; // If length not specified, simply convert without checking if (lenMbcs == -1) { lenWc = MultiByteToWideChar(codepage, 0, mbcs2Convert, lenMbcs, NULL, 0); } // Otherwise, test if we are cutting a multi-byte character at end of buffer else if(lenMbcs != -1 && codepage == CP_UTF8) // For UTF-8, we know how to test it { int indexOfLastChar = Utf8::characterStart(mbcs2Convert, lenMbcs-1); // get index of last character if (indexOfLastChar != 0 && !Utf8::isValid(mbcs2Convert+indexOfLastChar, lenMbcs-indexOfLastChar)) // if it is not valid we do not process it right now (unless its the only character in string, to ensure that we always progress, e.g. that bytesNotProcessed < lenMbcs) { bytesNotProcessed = lenMbcs-indexOfLastChar; } lenWc = MultiByteToWideChar(codepage, 0, mbcs2Convert, lenMbcs-bytesNotProcessed, NULL, 0); } else // For other encodings, ask system if there are any invalid characters; note that it will not correctly know if last character is cut when there are invalid characters inside the text { lenWc = MultiByteToWideChar(codepage, (lenMbcs == -1) ? 0 : MB_ERR_INVALID_CHARS, mbcs2Convert, lenMbcs, NULL, 0); if (lenWc == 0 && GetLastError() == ERROR_NO_UNICODE_TRANSLATION) { // Test without last byte if (lenMbcs > 1) lenWc = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, mbcs2Convert, lenMbcs-1, NULL, 0); if (lenWc == 0) // don't have to check that the error is still ERROR_NO_UNICODE_TRANSLATION, since only the length parameter changed { // TODO: should warn user about incorrect loading due to invalid characters // We still load the file, but the system will either strip or replace invalid characters (including the last character, if cut in half) lenWc = MultiByteToWideChar(codepage, 0, mbcs2Convert, lenMbcs, NULL, 0); } else { // We found a valid text by removing one byte. bytesNotProcessed = 1; } } } if (lenWc > 0) { _wideCharStr.sizeTo(lenWc); MultiByteToWideChar(codepage, 0, mbcs2Convert, lenMbcs-bytesNotProcessed, _wideCharStr, lenWc); } else _wideCharStr.empty(); if(pLenWc) *pLenWc = lenWc; if(pBytesNotProcessed) *pBytesNotProcessed = bytesNotProcessed; return _wideCharStr; }
void* ILibFileDir_GetDirFirstFile(const char* directory, /*INOUT*/ char* filename, int filenamelength, /*INOUT*/ int* filesize) { #if defined(WIN32) || defined(_WIN32_WCE) WIN32_FIND_DATA FileData; HANDLE* hSearch; char* direx; #if defined(_WIN32_WCE) wchar_t *tempChar; int tempCharLength; #endif hSearch = malloc(sizeof(HANDLE)); direx = malloc(filenamelength + 5); if (directory[(int) strlen(directory) - 1] == '\\') { sprintf(direx,"%s*.*",directory); } else { sprintf(direx,"%s\\*.*",directory); } #if defined(_WIN32_WCE) tempCharLength = MultiByteToWideChar(CP_UTF8,0,direx,-1,NULL,0); tempChar = (wchar_t*)malloc(sizeof(wchar_t)*tempCharLength); MultiByteToWideChar(CP_UTF8,0,direx,-1,tempChar,tempCharLength); *hSearch = FindFirstFile(tempChar, &FileData); free(direx); free(tempChar); #else *hSearch = FindFirstFile(direx, &FileData); free(direx); #endif if (*hSearch == INVALID_HANDLE_VALUE) { free(hSearch); hSearch = NULL; } else { if (filename != NULL) { #if defined(UNICODE) WideCharToMultiByte(CP_UTF8,0,(LPCWSTR)FileData.cFileName,-1,filename,filenamelength,NULL,NULL); #else memcpy(filename,FileData.cFileName,1+(int)strlen(FileData.cFileName)); #endif } if (filesize != NULL) { *filesize = FileData.nFileSizeLow; } } return hSearch; #else DIR* dirObj; struct dirent* dirEntry; /* dirEntry is a pointer to static memory in the C runtime lib for readdir()*/ struct stat _si; char fullPath[1024]; dirObj = opendir(directory); if (dirObj != NULL) { dirEntry = readdir(dirObj); if ((dirEntry != NULL) && ((int) strlen(dirEntry->d_name) < filenamelength)) { if (filename != NULL) { strcpy(filename,dirEntry->d_name); sprintf(fullPath, "%s%s", directory, dirEntry->d_name); if (filesize != NULL) { if (stat(fullPath, &_si) != -1) { if ((_si.st_mode & S_IFDIR) == S_IFDIR) { *filesize = 0; } else { *filesize = _si.st_size; } } } } } } return dirObj; #endif }
bool wcePutFile(const char *host_file, const char *wce_file) { TCHAR tszSrcFile[MAX_PATH]; WCHAR wszDestFile[MAX_PATH]; BYTE buffer[5120]; WIN32_FIND_DATA wfd; HRESULT hr; DWORD dwAttr, dwNumRead, dwNumWritten; HANDLE hSrc, hDest, hFind; int nResult; #ifdef UNICODE nResult = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, host_file, strlen(host_file)+1, tszSrcFile, ARRAYSIZE(tszSrcFile)); if(0 == nResult) return false; #else hr = StringCchCopy(tszSrcFile, ARRAYSIZE(tszSrcFile), argv[1]); if(FAILED(hr)) return false; #endif nResult = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, wce_file, strlen(wce_file)+1, wszDestFile, ARRAYSIZE(wszDestFile)); if(0 == nResult) return false; hFind = FindFirstFile( tszSrcFile, &wfd); if (INVALID_HANDLE_VALUE == hFind) { _tprintf(TEXT("Host file does not exist\n")); return false; } FindClose( hFind); if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { _tprintf( TEXT("Host file specifies a directory\n")); return false; } if (wceConnect()) { dwAttr = CeGetFileAttributes( wszDestFile); if (dwAttr & FILE_ATTRIBUTE_DIRECTORY) { hr = StringCchCatW(wszDestFile, ARRAYSIZE(wszDestFile), L"\\"); if(FAILED(hr)) return false; #ifdef UNICODE hr = StringCchCatW(wszDestFile, ARRAYSIZE(wszDestFile), wfd.cFileName); if(FAILED(hr)) return false; #else nResult = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, wfd.cFileName, strlen(wfd.cFileName)+1, wszDestFile+wcslen(wszDestFile), ARRAYSIZE(wszDestFile)-wcslen(wszDestFile)); if(0 == nResult) { return 1; } #endif } hSrc = CreateFile(tszSrcFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hSrc) { _tprintf( TEXT("Unable to open host file\n")); return false; } hDest = CeCreateFile(wszDestFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hDest ) { _tprintf( TEXT("Unable to open target WinCE file\n")); return false; } //copy file do { if(ReadFile(hSrc, &buffer, sizeof(buffer), &dwNumRead, NULL)) { if (!CeWriteFile(hDest, &buffer, dwNumRead, &dwNumWritten, NULL)) { _tprintf( TEXT("Error !!! Writing WinCE file\n")); goto FatalError; } } else { _tprintf( TEXT("Error !!! Reading host file\n")); goto FatalError; } _tprintf( TEXT(".")); } while (dwNumRead); //_tprintf( TEXT("\n")); CeCloseHandle( hDest); CloseHandle (hSrc); } wceDisconnect(); return true; FatalError: CeCloseHandle( hDest); CloseHandle (hSrc); wceDisconnect(); return false; }
struct CListEvent* cli_AddEvent(CLISTEVENT *cle) { struct CListEvent* p = corecli.pfnAddEvent(cle); if (p == NULL) return NULL; if (p->cle.hContact != 0 && p->cle.hDbEvent != (HANDLE) 1 && !(p->cle.flags & CLEF_ONLYAFEW)) { MENUITEMINFO mii = { sizeof(mii) }; mii.fMask = MIIM_DATA | MIIM_BITMAP | MIIM_ID; if (p->cle.pszService && (!strncmp("SRMsg/ReadMessage", p->cle.pszService, SIZEOF("SRMsg/ReadMessage")) || !strncmp("GChat/DblClickEvent", p->cle.pszService, SIZEOF("GChat/DblClickEvent")))) { // dup check only for msg events for (int j = 0; j < GetMenuItemCount(g_CluiData.hMenuNotify); j++) { if (GetMenuItemInfo(g_CluiData.hMenuNotify, j, TRUE, &mii) != 0) { NotifyMenuItemExData *nmi = (struct NotifyMenuItemExData *) mii.dwItemData; if (nmi != 0 && (HANDLE) nmi->hContact == (HANDLE) p->cle.hContact && nmi->iIcon == p->imlIconIndex) return p; } } } char *szProto = GetContactProto(p->cle.hContact); TCHAR *szName = pcli->pfnGetContactDisplayName(p->cle.hContact, 0); if (szProto && szName) { NotifyMenuItemExData *nmi = (struct NotifyMenuItemExData *) malloc(sizeof(struct NotifyMenuItemExData)); if (nmi) { TCHAR szBuffer[128]; TCHAR* szStatus = pcli->pfnGetStatusModeDescription(db_get_w(p->cle.hContact, szProto, "Status", ID_STATUS_OFFLINE), 0); TCHAR szwProto[64]; MultiByteToWideChar(CP_ACP, 0, szProto, -1, szwProto, 64); szwProto[63] = 0; mir_sntprintf(szBuffer, SIZEOF(szBuffer), _T("%s: %s (%s)"), szwProto, szName, szStatus); szBuffer[127] = 0; AppendMenu(g_CluiData.hMenuNotify, MF_BYCOMMAND | MF_STRING, g_CluiData.wNextMenuID, szBuffer); mii.hbmpItem = HBMMENU_CALLBACK; nmi->hContact = p->cle.hContact; nmi->iIcon = p->imlIconIndex; nmi->hIcon = p->cle.hIcon; nmi->hDbEvent = p->cle.hDbEvent; mii.dwItemData = (ULONG_PTR) nmi; mii.wID = g_CluiData.wNextMenuID; SetMenuItemInfo(g_CluiData.hMenuNotify, g_CluiData.wNextMenuID, FALSE, &mii); p-> menuId = g_CluiData.wNextMenuID; g_CluiData.wNextMenuID++; if (g_CluiData.wNextMenuID > 0x7fff) g_CluiData.wNextMenuID = 1; g_CluiData.iIconNotify = p->imlIconIndex; } } } else if (p->cle.hContact != 0 && (p->cle.flags & CLEF_ONLYAFEW)) { g_CluiData.iIconNotify = p->imlIconIndex; g_CluiData.hUpdateContact = p->cle.hContact; } if (pcli->events.count > 0) { g_CluiData.bEventAreaEnabled = TRUE; if (g_CluiData.bNotifyActive == FALSE) { g_CluiData.bNotifyActive = TRUE; EventArea_HideShowNotifyFrame(); } } CLUI__cliInvalidateRect(g_CluiData.hwndEventFrame, NULL, FALSE); return p; }
// Dowmloadfile message handlers LRESULT Dowmloadfile::DownloadFileMessage(WPARAM wParam,LPARAM lParam) { //static bool insert_a_new_line = false; int ncommand = (int)wParam; if(ncommand == DOWNLOAD_CONNECT_SUCCESS) { //unsigned char IPAddress[4]; //((CIPAddressCtrl *)GetDlgItem(IDC_IPADDRESS_TEMCO_IP))->GetAddress(IPAddress[0],IPAddress[1],IPAddress[2],IPAddress[3]); CString retmessage; retmessage.Format(_T("Connect to Temco server success!")); //m_download_info.AddString(retmessage); m_download_info.InsertString(m_download_info.GetCount(),retmessage); m_download_info.SetTopIndex(m_download_info.GetCount()-1); if(Downloadfile_Thread == NULL) Downloadfile_Thread = CreateThread(NULL,NULL,DownLoadFileProcess,this,NULL, &download_threadid); } else if(ncommand == DOWNLOAD_DISCONNEC) { CString retmessage; retmessage.Format(_T("Disconnected with Temco server!")); //m_download_info.AddString(retmessage); m_download_info.InsertString(m_download_info.GetCount(),retmessage); m_download_info.SetTopIndex(m_download_info.GetCount()-1); GetDlgItem(IDC_BUTTON_START_DOWNLOAD)->EnableWindow(true); TCP_File_Socket.Close(); } else if(ncommand == DOWNLOAD_CONNECT_FAILED) { CString retmessage; retmessage.Format(_T("Connect to Temco server failed!Please try again!")); //m_download_info.AddString(retmessage); m_download_info.InsertString(m_download_info.GetCount(),retmessage); m_download_info.SetTopIndex(m_download_info.GetCount()-1); TCP_File_Socket.Close(); GetDlgItem(IDC_BUTTON_START_DOWNLOAD)->EnableWindow(true); } else if(ncommand == DOWNLOAD_CLOSE_SOCKET) { TCP_File_Socket.Close(); if(TCP_File_Socket.GetDownloadResults() == DOWNLOAD_RESULTS_FAILED) { GetDlgItem(IDC_BUTTON_START_DOWNLOAD)->EnableWindow(true); return 0; } CString ApplicationFolder; GetModuleFileName(NULL, ApplicationFolder.GetBuffer(MAX_PATH), MAX_PATH); PathRemoveFileSpec(ApplicationFolder.GetBuffer(MAX_PATH)); ApplicationFolder.ReleaseBuffer(); ISPtool_path = ApplicationFolder + _T("\\ISP.exe"); CString temp_isp_info; AutoFlashConfigPath = ApplicationFolder + _T("//AutoFlashFile.ini"); bool is_net_device = (bool)IsNetDevice(m_product_isp_auto_flash.product_class_id); WritePrivateProfileStringW(_T("Data"),_T("Command"),_T("1"),AutoFlashConfigPath); if(m_product_isp_auto_flash.BuildingInfo.strIp.IsEmpty())//串口 { WritePrivateProfileStringW(_T("Data"),_T("COM_OR_NET"),_T("COM"),AutoFlashConfigPath); CString cs_comport; cs_comport.Format(_T("COM%d"), m_product_isp_auto_flash.ncomport); WritePrivateProfileStringW(_T("Data"),_T("COMPORT"),cs_comport,AutoFlashConfigPath); WritePrivateProfileStringW(_T("Data"),_T("Baudrate"),_T("19200"),AutoFlashConfigPath); CString nflash_id; nflash_id.Format(_T("%d"),m_product_isp_auto_flash.product_id); WritePrivateProfileStringW(_T("Data"),_T("ID"),nflash_id,AutoFlashConfigPath); temp_isp_info.Format(_T("ISP via : ")); temp_isp_info = temp_isp_info + cs_comport; m_download_info.InsertString(m_download_info.GetCount(),temp_isp_info); temp_isp_info.Format(_T("ISP baudrate : 19200")); m_download_info.InsertString(m_download_info.GetCount(),temp_isp_info); temp_isp_info.Format(_T("Device ID :")); temp_isp_info = temp_isp_info + nflash_id; m_download_info.InsertString(m_download_info.GetCount(),temp_isp_info); } else { WritePrivateProfileStringW(_T("Data"),_T("COM_OR_NET"),_T("NET"),AutoFlashConfigPath); WritePrivateProfileStringW(_T("Data"),_T("IPAddress"),m_product_isp_auto_flash.BuildingInfo.strIp,AutoFlashConfigPath); if((m_product_isp_auto_flash.ncomport == 0) || (m_product_isp_auto_flash.ncomport == 47808)) { m_product_isp_auto_flash.ncomport = 10000; } temp_isp_info.Format(_T("ISP via : network")); m_download_info.InsertString(m_download_info.GetCount(),temp_isp_info); temp_isp_info.Format(_T("IP Address : ")); temp_isp_info = temp_isp_info + m_product_isp_auto_flash.BuildingInfo.strIp; m_download_info.InsertString(m_download_info.GetCount(),temp_isp_info); CString n_tcpport; n_tcpport.Format(_T("%d"),m_product_isp_auto_flash.ncomport); temp_isp_info.Format(_T("Port : ")); temp_isp_info = temp_isp_info + n_tcpport; m_download_info.InsertString(m_download_info.GetCount(),temp_isp_info); WritePrivateProfileStringW(_T("Data"),_T("IPPort"),n_tcpport,AutoFlashConfigPath); if(is_net_device == false) { WritePrivateProfileStringW(_T("Data"),_T("Subnote"),_T("1"),AutoFlashConfigPath); CString nsub_id; nsub_id.Format(_T("%d"),m_product_isp_auto_flash.product_id); WritePrivateProfileStringW(_T("Data"),_T("SubID"),nsub_id,AutoFlashConfigPath); temp_isp_info.Format(_T("Device is subnote.")); m_download_info.InsertString(m_download_info.GetCount(),temp_isp_info); } else { WritePrivateProfileStringW(_T("Data"),_T("Subnote"),_T("0"),AutoFlashConfigPath); temp_isp_info.Format(_T("Device is not a subnote.")); m_download_info.InsertString(m_download_info.GetCount(),temp_isp_info); } } CString exe_folder; GetModuleFileName(NULL, exe_folder.GetBuffer(MAX_PATH), MAX_PATH); PathRemoveFileSpec(exe_folder.GetBuffer(MAX_PATH)); exe_folder.ReleaseBuffer(); CString file_name; MultiByteToWideChar( CP_ACP, 0, download_filename, (int)strlen((char *)download_filename)+1, file_name.GetBuffer(MAX_PATH), MAX_PATH ); file_name.ReleaseBuffer(); CString mypath = exe_folder + _T("\\Database\\Firmware"); mypath = mypath + _T("\\") + file_name; WritePrivateProfileStringW(_T("Data"),_T("FirmwarePath"),mypath,AutoFlashConfigPath); temp_isp_info.Format(_T("FirmwarePath = ")); temp_isp_info = temp_isp_info + mypath; m_download_info.InsertString(m_download_info.GetCount(),temp_isp_info); m_download_info.SetTopIndex(m_download_info.GetCount()-1); //HANDLE Call_ISP_Application = NULL; //Call_ISP_Application =CreateThread(NULL,NULL,isp_thread,this,NULL, NULL); } else if(ncommand == DOWNLOAD_PERSENT) { int npersent = (int)lParam; CString persent_message; persent_message.Format(_T("File download finished %d%%"),npersent); //bool is_the_first = true; //if(!is_the_first) m_download_info.DeleteString(m_download_info.GetCount() - 1); //m_download_info.AddString(persent_message); m_download_info.InsertString(m_download_info.GetCount(),persent_message); m_download_info.SetTopIndex(m_download_info.GetCount()-1); } else if(ncommand == DOWNLOAD_FINISHED) { CString complete_message; complete_message.Format(_T("File download complete. ")); //m_download_info.AddString(complete_message); m_download_info.InsertString(m_download_info.GetCount(),complete_message); complete_message.Format(_T("Local file path : ")); complete_message = complete_message + Folder_Path; m_download_info.InsertString(m_download_info.GetCount(),complete_message); m_download_info.SetTopIndex(m_download_info.GetCount()-1); } else if(ncommand == DOWNLOAD_FILE_INFO) { CString nfile_name; CString nfile_size; MultiByteToWideChar( CP_ACP, 0, download_filename, (int)strlen((char *)download_filename)+1, nfile_name.GetBuffer(MAX_PATH), MAX_PATH ); nfile_name.ReleaseBuffer(); nfile_size.Format(_T("File size about %d Bytes "),malloc_download_memory_size); CString show_message; show_message = _T("File name ") + nfile_name + _T(" .") + nfile_size; m_download_info.InsertString(m_download_info.GetCount(),show_message); m_download_info.SetTopIndex(m_download_info.GetCount()-1); } else if(ncommand == DOWNLOAD_NOT_FIND_LOCAL) { CString complete_message; complete_message.Format(_T("Local Firmware folder doen't exsit the file we needed.we will download it from server.")); //m_download_info.AddString(complete_message); m_download_info.InsertString(m_download_info.GetCount(),complete_message); //m_download_info.SetTopIndex(m_download_info.GetCount()-1); complete_message.Format(_T("Check MD5 value over!")); //m_download_info.AddString(complete_message); m_download_info.InsertString(m_download_info.GetCount(),complete_message); m_download_info.SetTopIndex(m_download_info.GetCount()-1); } else if(ncommand == DOWNLOAD_LOCAL_EXSIT) { CString complete_message; complete_message.Format(_T("Local Firmware already exsit in the Firmware folder.The MD5 value is match ")); //m_download_info.AddString(complete_message); m_download_info.InsertString(m_download_info.GetCount(),complete_message); m_download_info.SetTopIndex(m_download_info.GetCount()-1); } else if(ncommand == DOWNLOAD_RESULTS/*DOWNLOAD_RESULTS*/) { GetDlgItem(IDC_BUTTON_START_DOWNLOAD)->EnableWindow(true); KillTimer(1); int ret_results = GetPrivateProfileInt(_T("Data"),_T("Command"),0,AutoFlashConfigPath); CString ret_message; switch(ret_results) { case NO_COMMAND: case START_AUTO_FLASH_COMMAND: case FAILED_NORESPONSED: ret_message.Format(_T("The device not response ,please try again!")); //m_download_info.AddString(complete_message); m_download_info.InsertString(m_download_info.GetCount(),ret_message); m_download_info.SetTopIndex(m_download_info.GetCount()-1); break; case FLASH_SUCCESS: { ret_message.Format(_T("ISP succeed!")); //m_download_info.AddString(complete_message); m_download_info.InsertString(m_download_info.GetCount(),ret_message); m_download_info.SetTopIndex(m_download_info.GetCount()-1); } break; case FAILED_UNKNOW_ERROR: { ret_message.Format(_T("Unknown error! More details please reference Log_info.txt !")); //m_download_info.AddString(complete_message); m_download_info.InsertString(m_download_info.GetCount(),ret_message); m_download_info.SetTopIndex(m_download_info.GetCount()-1); } break; } CFileFind configfind; if(configfind.FindFile(AutoFlashConfigPath)) { DeleteFile(AutoFlashConfigPath); } } else if(ncommand == RETURN_ERROR) { CString show_error_message; int file_error_type = (int)lParam; switch(file_error_type) { case NO_MD5_FILE_EXSIT: { show_error_message.Format(_T("TEMCO server doesn't contain the file you needed")); } break; case DOWNLOAD_FILE_ERROR: { show_error_message.Format(_T("Download file from server failed!")); } break; case HOST_BUSY: { show_error_message.Format(_T("Host busy,please try again later!")); } break; case DOWNLOAD_MD5_FAILED: { show_error_message.Format(_T("Check MD5 value failed!Please retry again!")); } break; case DOWNLOAD_MD5_CHECK_PASS: { string temp_md5 = MD5(ifstream( HEX_BIN_FILE_PATH )).toString(); CString MD5_value; MD5_value = temp_md5.c_str(); CString temp_show; temp_show.Format(_T("The File MD5 is :")); temp_show = temp_show + MD5_value; m_download_info.InsertString(m_download_info.GetCount(),temp_show); show_error_message.Format(_T("Check MD5 value with server Pass.")); } break; default: { show_error_message.Format(_T("Unknown error,please try again later!")); } break; } m_download_info.InsertString(m_download_info.GetCount(),show_error_message); m_download_info.SetTopIndex(m_download_info.GetCount()-1); } return 0; }
/********************************************************************* * _setmbcp (MSVCRT.@) * @implemented */ int CDECL _setmbcp(int cp) { int newcp; CPINFO cpi; BYTE *bytes; WORD chartypes[256]; WORD *curr_type; char bufA[256]; WCHAR bufW[256]; int charcount; int ret; int i; TRACE("_setmbcp %d\n",cp); switch (cp) { case _MB_CP_ANSI: newcp = GetACP(); break; case _MB_CP_OEM: newcp = GetOEMCP(); break; case _MB_CP_LOCALE: newcp = MSVCRT___lc_codepage; break; case _MB_CP_SBCS: newcp = 20127; /* ASCII */ break; default: newcp = cp; break; } if (!GetCPInfo(newcp, &cpi)) { ERR("Codepage %d not found\n", newcp); __set_errno(EINVAL); return -1; } /* setup the _mbctype */ memset(_mbctype, 0, sizeof(_mbctype)); bytes = cpi.LeadByte; while (bytes[0] || bytes[1]) { for (i = bytes[0]; i <= bytes[1]; i++) _mbctype[i + 1] |= _M1; bytes += 2; } if (cpi.MaxCharSize > 1) { /* trail bytes not available through kernel32 but stored in a structure in msvcrt */ struct cp_extra_info_t *cpextra = g_cpextrainfo; g_mbcp_is_multibyte = 1; while (TRUE) { if (cpextra->cp == 0 || cpextra->cp == newcp) { if (cpextra->cp == 0) ERR("trail bytes data not available for DBCS codepage %d - assuming all bytes\n", newcp); bytes = cpextra->TrailBytes; while (bytes[0] || bytes[1]) { for (i = bytes[0]; i <= bytes[1]; i++) _mbctype[i + 1] |= _M2; bytes += 2; } break; } cpextra++; } } else g_mbcp_is_multibyte = 0; /* we can't use GetStringTypeA directly because we don't have a locale - only a code page */ charcount = 0; for (i = 0; i < 256; i++) if (!(_mbctype[i + 1] & _M1)) bufA[charcount++] = i; ret = MultiByteToWideChar(newcp, 0, bufA, charcount, bufW, charcount); if (ret != charcount) ERR("MultiByteToWideChar of chars failed for cp %d, ret=%d (exp %d), error=%d\n", newcp, ret, charcount, GetLastError()); GetStringTypeW(CT_CTYPE1, bufW, charcount, chartypes); curr_type = chartypes; for (i = 0; i < 256; i++) if (!(_mbctype[i + 1] & _M1)) { if ((*curr_type) & C1_UPPER) _mbctype[i + 1] |= _SBUP; if ((*curr_type) & C1_LOWER) _mbctype[i + 1] |= _SBLOW; curr_type++; } if (newcp == 932) /* CP932 only - set _MP and _MS */ { /* On Windows it's possible to calculate the _MP and _MS from CT_CTYPE1 * and CT_CTYPE3. But as of Wine 0.9.43 we return wrong values what makes * it hard. As this is set only for codepage 932 we hardcode it what gives * also faster execution. */ for (i = 161; i <= 165; i++) _mbctype[i + 1] |= _MP; for (i = 166; i <= 223; i++) _mbctype[i + 1] |= _MS; } MSVCRT___lc_collate_cp = MSVCRT___lc_codepage = newcp; TRACE("(%d) -> %d\n", cp, MSVCRT___lc_codepage); return 0; }
LRESULT CBacnetAlarmLog::Fresh_Alarmlog_List(WPARAM wParam,LPARAM lParam) { bac_show_alarm_window = 0; for (int i=0;i<(int)m_alarmlog_data.size();i++) { bac_show_alarm_window = m_alarmlog_data.at(i).alarm || bac_show_alarm_window; } int Fresh_Item; int isFreshOne = (int)lParam; if(isFreshOne == REFRESH_ON_ITEM) { Fresh_Item = (int)wParam; } else { if(m_alarmlog_list.IsDataNewer((char *)&m_alarmlog_data.at(0),sizeof(Alarm_point) * BAC_ALARMLOG_COUNT)) { //避免list 刷新时闪烁;在没有数据变动的情况下不刷新List; m_alarmlog_list.SetListData((char *)&m_alarmlog_data.at(0),sizeof(Alarm_point) * BAC_ALARMLOG_COUNT); } //else //{ // return 0; //} } for (int i=0;i<(int)m_alarmlog_data.size();i++) { if(isFreshOne) { i = Fresh_Item; } CString temp_item; CString temp_message; CString temp_panel; CString temp_time; if(m_alarmlog_data.at(i).alarm == 1) { temp_item.Format(_T("%d"),i+1); temp_panel.Format(_T("%d"),(unsigned char)m_alarmlog_data.at(i).alarm_panel); MultiByteToWideChar( CP_ACP, 0, (char *)m_alarmlog_data.at(i).alarm_message, (int)strlen((char *)m_alarmlog_data.at(i).alarm_message)+1, temp_message.GetBuffer(MAX_PATH), MAX_PATH ); temp_message.ReleaseBuffer(); time_t tempalarm_time ; tempalarm_time = m_alarmlog_data.at(i).alarm_time; CTime time_alarmtime; time_alarmtime = tempalarm_time; temp_time = time_alarmtime.Format("%y/%m/%d %H:%M:%S"); } else { temp_time.Empty(); temp_panel.Empty(); temp_message.Empty(); temp_item.Empty(); m_alarmlog_list.SetItemText(i,ALARMLOG_DEL,_T("")); } m_alarmlog_list.SetItemText(i,ALARMLOG_NUM,temp_item); m_alarmlog_list.SetItemText(i,ALARMLOG_PANEL,temp_panel); m_alarmlog_list.SetItemText(i,ALARMLOG_MESSAGE,temp_message); m_alarmlog_list.SetItemText(i,ALARMLOG_TIME,temp_time); if(m_alarmlog_data.at(i).alarm == 1) { if(m_alarmlog_data.at(i).ddelete == 0) { m_alarmlog_list.SetItemText(i,ALARMLOG_DEL,Yes_No[0]); } else { m_alarmlog_list.SetItemText(i,ALARMLOG_DEL,Yes_No[1]); } } else { m_alarmlog_list.SetItemText(i,ALARMLOG_MESSAGE,_T("")); m_alarmlog_list.SetItemText(i,ALARMLOG_DEL,_T("")); } if(isFreshOne) { break; } } return 0; }
static void test_threadcp(void) { static const LCID ENGLISH = MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT); static const LCID HINDI = MAKELCID(MAKELANGID(LANG_HINDI, SUBLANG_HINDI_INDIA), SORT_DEFAULT); static const LCID GEORGIAN = MAKELCID(MAKELANGID(LANG_GEORGIAN, SUBLANG_GEORGIAN_GEORGIA), SORT_DEFAULT); static const LCID RUSSIAN = MAKELCID(MAKELANGID(LANG_RUSSIAN, SUBLANG_RUSSIAN_RUSSIA), SORT_DEFAULT); static const LCID JAPANESE = MAKELCID(MAKELANGID(LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN), SORT_DEFAULT); static const LCID CHINESE = MAKELCID(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED), SORT_DEFAULT); BOOL islead, islead_acp; CPINFOEXA cpi; UINT cp, acp; int i, num; LCID last; BOOL ret; struct test { LCID lcid; UINT threadcp; } lcids[] = { { HINDI, 0 }, { GEORGIAN, 0 }, { ENGLISH, 1252 }, { RUSSIAN, 1251 }, { JAPANESE, 932 }, { CHINESE, 936 } }; struct test_islead_nocp { LCID lcid; BYTE testchar; } isleads_nocp[] = { { HINDI, 0x00 }, { HINDI, 0x81 }, { HINDI, 0xa0 }, { HINDI, 0xe0 }, { GEORGIAN, 0x00 }, { GEORGIAN, 0x81 }, { GEORGIAN, 0xa0 }, { GEORGIAN, 0xe0 }, }; struct test_islead { LCID lcid; BYTE testchar; BOOL islead; } isleads[] = { { ENGLISH, 0x00, FALSE }, { ENGLISH, 0x81, FALSE }, { ENGLISH, 0xa0, FALSE }, { ENGLISH, 0xe0, FALSE }, { RUSSIAN, 0x00, FALSE }, { RUSSIAN, 0x81, FALSE }, { RUSSIAN, 0xa0, FALSE }, { RUSSIAN, 0xe0, FALSE }, { JAPANESE, 0x00, FALSE }, { JAPANESE, 0x81, TRUE }, { JAPANESE, 0xa0, FALSE }, { JAPANESE, 0xe0, TRUE }, { CHINESE, 0x00, FALSE }, { CHINESE, 0x81, TRUE }, { CHINESE, 0xa0, TRUE }, { CHINESE, 0xe0, TRUE }, }; last = GetThreadLocale(); acp = GetACP(); for (i = 0; i < sizeof(lcids)/sizeof(lcids[0]); i++) { SetThreadLocale(lcids[i].lcid); cp = 0xdeadbeef; GetLocaleInfoA(lcids[i].lcid, LOCALE_IDEFAULTANSICODEPAGE|LOCALE_RETURN_NUMBER, (LPSTR)&cp, sizeof(cp)); ok(cp == lcids[i].threadcp, "wrong codepage %u for lcid %04x, should be %u\n", cp, lcids[i].threadcp, cp); /* GetCPInfoEx/GetCPInfo - CP_ACP */ SetLastError(0xdeadbeef); memset(&cpi, 0, sizeof(cpi)); ret = GetCPInfoExA(CP_ACP, 0, &cpi); ok(ret, "GetCPInfoExA failed for lcid %04x, error %d\n", lcids[i].lcid, GetLastError()); ok(cpi.CodePage == acp, "wrong codepage %u for lcid %04x, should be %u\n", cpi.CodePage, lcids[i].lcid, acp); /* WideCharToMultiByte - CP_ACP */ num = WideCharToMultiByte(CP_ACP, 0, foobarW, -1, NULL, 0, NULL, NULL); ok(num == 7, "ret is %d (%04x)\n", num, lcids[i].lcid); /* MultiByteToWideChar - CP_ACP */ num = MultiByteToWideChar(CP_ACP, 0, "foobar", -1, NULL, 0); ok(num == 7, "ret is %d (%04x)\n", num, lcids[i].lcid); /* GetCPInfoEx/GetCPInfo - CP_THREAD_ACP */ SetLastError(0xdeadbeef); memset(&cpi, 0, sizeof(cpi)); ret = GetCPInfoExA(CP_THREAD_ACP, 0, &cpi); ok(ret, "GetCPInfoExA failed for lcid %04x, error %d\n", lcids[i].lcid, GetLastError()); if (lcids[i].threadcp) ok(cpi.CodePage == lcids[i].threadcp, "wrong codepage %u for lcid %04x, should be %u\n", cpi.CodePage, lcids[i].lcid, lcids[i].threadcp); else ok(cpi.CodePage == acp, "wrong codepage %u for lcid %04x, should be %u\n", cpi.CodePage, lcids[i].lcid, acp); /* WideCharToMultiByte - CP_THREAD_ACP */ num = WideCharToMultiByte(CP_THREAD_ACP, 0, foobarW, -1, NULL, 0, NULL, NULL); ok(num == 7, "ret is %d (%04x)\n", num, lcids[i].lcid); /* MultiByteToWideChar - CP_THREAD_ACP */ num = MultiByteToWideChar(CP_THREAD_ACP, 0, "foobar", -1, NULL, 0); ok(num == 7, "ret is %d (%04x)\n", num, lcids[i].lcid); } /* IsDBCSLeadByteEx - locales without codepage */ for (i = 0; i < sizeof(isleads_nocp)/sizeof(isleads_nocp[0]); i++) { SetThreadLocale(isleads_nocp[i].lcid); islead_acp = IsDBCSLeadByteEx(CP_ACP, isleads_nocp[i].testchar); islead = IsDBCSLeadByteEx(CP_THREAD_ACP, isleads_nocp[i].testchar); ok(islead == islead_acp, "wrong islead %i for test char %x in lcid %04x. should be %i\n", islead, isleads_nocp[i].testchar, isleads_nocp[i].lcid, islead_acp); } /* IsDBCSLeadByteEx - locales with codepage */ for (i = 0; i < sizeof(isleads)/sizeof(isleads[0]); i++) { SetThreadLocale(isleads[i].lcid); islead = IsDBCSLeadByteEx(CP_THREAD_ACP, isleads[i].testchar); ok(islead == isleads[i].islead, "wrong islead %i for test char %x in lcid %04x. should be %i\n", islead, isleads[i].testchar, isleads[i].lcid, isleads[i].islead); } SetThreadLocale(last); }
void StartServerProcess(char *cl, STARTUPINFOW* si, PROCESS_INFORMATION* pi) { void *address; WCHAR dllPath[MAX_PATH]; WCHAR WDFixed[MAX_PATH]; WCHAR wappendage[20]; WCHAR server_cast[14]; WCHAR cl_cast[300]; WCHAR kernel_cast[14]; char *appendage = "\\nwnx-module.dll"; char *server_name = "nwserver.exe"; char *kernel_name = "Kernel32.dll"; unsigned long numBytes, exitCode; HANDLE thandle; char debuggy[256]; GetCurrentDirectoryW(sizeof(WCHAR) * MAX_PATH, dllPath); GetCurrentDirectoryW(sizeof(WCHAR) * MAX_PATH, WDFixed); MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, appendage, -1, wappendage, strlen(appendage) + 1); wcscat(dllPath, wappendage ); MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, server_name, -1, server_cast, strlen(server_name) + 1); MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cl, -1, cl_cast, strlen(cl) + 1); MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, kernel_name, -1, kernel_cast, strlen(kernel_name) + 1); CreateProcessW(server_cast, cl_cast , NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_PRESERVE_CODE_AUTHZ_LEVEL, NULL, WDFixed, si, pi); // Get permission to write into the process's address space of a space about the length of the path/DLL name. address = VirtualAllocEx(pi->hProcess, NULL, sizeof(WCHAR)*wcsnlen(dllPath, MAX_PATH) + sizeof(WCHAR), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if(!address) { MessageBoxA(NULL, "Can't start server process; there was a memory access issue. Does NWNX2 have the permissions it needs to run?", "Error", MB_TASKMODAL | MB_TOPMOST | MB_ICONERROR | MB_OK); return; } // Write the DLL name into the process's address space if(!WriteProcessMemory(pi->hProcess, address, (const void *) dllPath, sizeof(WCHAR)*wcsnlen(dllPath, MAX_PATH) + sizeof(WCHAR), &numBytes)) { MessageBoxA(NULL, "Can't start server process; The write to memory failed.", "Error", MB_TASKMODAL | MB_TOPMOST | MB_ICONERROR | MB_OK); return; } // Force the process to load the DLL by creating a thread inside the process that calls LoadLibrary and exits. thandle = CreateRemoteThread(pi->hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) GetProcAddress(LoadLibraryW(kernel_cast), "LoadLibraryW"), address, 0, NULL); // Let's check if the thread ran ok- if(!GetExitCodeThread(thandle, &exitCode) || thandle == NULL) { MessageBoxA(NULL, "Can't start server process; The loading thread in nwserver failed to run.", "Error", MB_TASKMODAL | MB_TOPMOST | MB_ICONERROR | MB_OK); return; } // 259 is still running while(exitCode == 259) { GetExitCodeThread(thandle, &exitCode); } // Let's check how LoadLibrary() exited if(!exitCode) { exitCode = GetLastError(); // don't do this normally... sprintf(debuggy, "%d", exitCode); MessageBoxA(NULL, debuggy, "Error", MB_TASKMODAL | MB_TOPMOST | MB_ICONERROR | MB_OK); //MessageBoxA(NULL, "Can't start server process; nwnx-module.dll failed to load into nwserver.exe", "Error", MB_TASKMODAL | MB_TOPMOST | MB_ICONERROR | MB_OK); return; } // All good to go, let's kick the football- if(!ResumeThread(pi->hThread)) { MessageBoxA(NULL, "There was a threading problem, possibly a bad handle.", "Error", MB_TASKMODAL | MB_TOPMOST | MB_ICONERROR | MB_OK); } }
static void test_other_invalid_parameters(void) { char c_string[] = "Hello World"; size_t c_string_len = sizeof(c_string); WCHAR w_string[] = {'H','e','l','l','o',' ','W','o','r','l','d',0}; size_t w_string_len = sizeof(w_string) / sizeof(WCHAR); BOOL used; INT len; /* srclen=0 => ERROR_INVALID_PARAMETER */ SetLastError(0xdeadbeef); len = WideCharToMultiByte(CP_ACP, 0, w_string, 0, c_string, c_string_len, NULL, NULL); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); SetLastError(0xdeadbeef); len = MultiByteToWideChar(CP_ACP, 0, c_string, 0, w_string, w_string_len); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); /* dst=NULL but dstlen not 0 => ERROR_INVALID_PARAMETER */ SetLastError(0xdeadbeef); len = WideCharToMultiByte(CP_ACP, 0, w_string, w_string_len, NULL, c_string_len, NULL, NULL); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); SetLastError(0xdeadbeef); len = MultiByteToWideChar(CP_ACP, 0, c_string, c_string_len, NULL, w_string_len); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); /* CP_UTF7, CP_UTF8, or CP_SYMBOL and defchar not NULL => ERROR_INVALID_PARAMETER */ /* CP_SYMBOL's behavior here is undocumented */ SetLastError(0xdeadbeef); len = WideCharToMultiByte(CP_UTF7, 0, w_string, w_string_len, c_string, c_string_len, c_string, NULL); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); SetLastError(0xdeadbeef); len = WideCharToMultiByte(CP_UTF8, 0, w_string, w_string_len, c_string, c_string_len, c_string, NULL); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); SetLastError(0xdeadbeef); len = WideCharToMultiByte(CP_SYMBOL, 0, w_string, w_string_len, c_string, c_string_len, c_string, NULL); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); /* CP_UTF7, CP_UTF8, or CP_SYMBOL and used not NULL => ERROR_INVALID_PARAMETER */ /* CP_SYMBOL's behavior here is undocumented */ SetLastError(0xdeadbeef); len = WideCharToMultiByte(CP_UTF7, 0, w_string, w_string_len, c_string, c_string_len, NULL, &used); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); SetLastError(0xdeadbeef); len = WideCharToMultiByte(CP_UTF8, 0, w_string, w_string_len, c_string, c_string_len, NULL, &used); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); SetLastError(0xdeadbeef); len = WideCharToMultiByte(CP_SYMBOL, 0, w_string, w_string_len, c_string, c_string_len, NULL, &used); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); /* CP_UTF7, flags not 0 and used not NULL => ERROR_INVALID_PARAMETER */ /* (tests precedence of ERROR_INVALID_PARAMETER over ERROR_INVALID_FLAGS) */ /* The same test with CP_SYMBOL instead of CP_UTF7 gives ERROR_INVALID_FLAGS instead except on Windows NT4 */ SetLastError(0xdeadbeef); len = WideCharToMultiByte(CP_UTF7, 1, w_string, w_string_len, c_string, c_string_len, NULL, &used); ok(len == 0 && GetLastError() == ERROR_INVALID_PARAMETER, "len=%d error=%x\n", len, GetLastError()); }
static void test_utf7_decoding(void) { char input[32]; WCHAR output[32], expected[32]; int i, len, expected_len; static const signed char base64_decoding_table[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00-0x0F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10-0x1F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20-0x2F */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30-0x3F */ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40-0x4F */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50-0x5F */ -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60-0x6F */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70-0x7F */ }; struct { /* inputs */ char src[32]; int srclen; WCHAR *dst; int dstlen; /* expected outputs */ WCHAR expected_dst[32]; int chars_written; int len; } tests[] = { /* tests string conversion with srclen=-1 */ { "+T2BZfQ-", -1, output, sizeof(output) / sizeof(WCHAR) - 1, {0x4F60,0x597D,0}, 3, 3 }, /* tests string conversion with srclen=-2 */ { "+T2BZfQ-", -2, output, sizeof(output) / sizeof(WCHAR) - 1, {0x4F60,0x597D,0}, 3, 3 }, /* tests string conversion with dstlen=strlen(expected_dst) */ { "+T2BZfQ-", -1, output, 2, {0x4F60,0x597D}, 2, 0 }, /* tests string conversion with dstlen=strlen(expected_dst)+1 */ { "+T2BZfQ-", -1, output, 3, {0x4F60,0x597D,0}, 3, 3 }, /* tests string conversion with dstlen=strlen(expected_dst)+2 */ { "+T2BZfQ-", -1, output, 4, {0x4F60,0x597D,0}, 3, 3 }, /* tests dry run with dst=NULL and dstlen=0 */ { "+T2BZfQ-", -1, NULL, 0, {0}, 0, 3 }, /* tests dry run with dst!=NULL and dstlen=0 */ { "+T2BZfQ-", -1, output, 0, {0}, 0, 3 }, /* tests ill-formed UTF-7: 6 bits, not enough for a byte pair */ { "+T-+T-+T-hello", -1, output, sizeof(output) / sizeof(WCHAR) - 1, {'h','e','l','l','o',0}, 6, 6 }, /* tests ill-formed UTF-7: 12 bits, not enough for a byte pair */ { "+T2-+T2-+T2-hello", -1, output, sizeof(output) / sizeof(WCHAR) - 1, {'h','e','l','l','o',0}, 6, 6 }, /* tests ill-formed UTF-7: 18 bits, not a multiple of 16 and the last bit is a 1 */ { "+T2B-+T2B-+T2B-hello", -1, output, sizeof(output) / sizeof(WCHAR) - 1, {0x4F60,0x4F60,0x4F60,'h','e','l','l','o',0}, 9, 9 }, /* tests ill-formed UTF-7: 24 bits, a multiple of 8 but not a multiple of 16 */ { "+T2BZ-+T2BZ-+T2BZ-hello", -1, output, sizeof(output) / sizeof(WCHAR) - 1, {0x4F60,0x4F60,0x4F60,'h','e','l','l','o',0}, 9, 9 }, /* tests UTF-7 followed by characters that should be encoded but aren't */ { "+T2BZ-\x82\xFE", -1, output, sizeof(output) / sizeof(WCHAR) - 1, {0x4F60,0x0082,0x00FE,0}, 4, 4 }, /* tests srclen > strlen(src) */ { "a\0b", 4, output, sizeof(output) / sizeof(WCHAR) - 1, {'a',0,'b',0}, 4, 4 }, /* tests srclen < strlen(src) outside of a UTF-7 sequence */ { "hello", 2, output, sizeof(output) / sizeof(WCHAR) - 1, {'h','e'}, 2, 2 }, /* tests srclen < strlen(src) inside of a UTF-7 sequence */ { "+T2BZfQ-", 4, output, sizeof(output) / sizeof(WCHAR) - 1, {0x4F60}, 1, 1 }, /* tests srclen < strlen(src) right at the beginning of a UTF-7 sequence */ { "hi+T2A-", 3, output, sizeof(output) / sizeof(WCHAR) - 1, {'h','i'}, 2, 2 }, /* tests srclen < strlen(src) right at the end of a UTF-7 sequence */ { "+T2A-hi", 5, output, sizeof(output) / sizeof(WCHAR) - 1, {0x4F60}, 1, 1 }, /* tests srclen < strlen(src) at the beginning of an escaped + sign */ { "hi+-", 3, output, sizeof(output) / sizeof(WCHAR) - 1, {'h','i'}, 2, 2 }, /* tests srclen < strlen(src) at the end of an escaped + sign */ { "+-hi", 2, output, sizeof(output) / sizeof(WCHAR) - 1, {'+'}, 1, 1 }, /* tests len=0 but no error */ { "+", 1, output, sizeof(output) / sizeof(WCHAR) - 1, {0}, 0, 0 }, /* tests a single null char */ { "", -1, output, sizeof(output) / sizeof(WCHAR) - 1, {0}, 1, 1 }, /* tests a buffer that runs out while not decoding a UTF-7 sequence */ { "hello", -1, output, 2, {'h','e'}, 2, 0 }, /* tests a buffer that runs out in the middle of decoding a UTF-7 sequence */ { "+T2BZfQ-", -1, output, 1, {0x4F60}, 1, 0 } }; /* test which one-byte characters remove stray + signs */ for (i = 0; i < 256; i++) { sprintf(input, "+%c+AAA", i); memset(output, 0x23, sizeof(output) - sizeof(WCHAR)); output[sizeof(output) / sizeof(WCHAR) - 1] = 0; len = MultiByteToWideChar(CP_UTF7, 0, input, 7, output, sizeof(output) / sizeof(WCHAR) - 1); if (i == '-') { /* removes the - sign */ expected_len = 3; expected[0] = 0x002B; expected[1] = 0; expected[2] = 0; } else if (i <= 0x7F && base64_decoding_table[i] != -1) { /* absorbs the character into the base64 sequence */ expected_len = 2; expected[0] = (base64_decoding_table[i] << 10) | 0x03E0; expected[1] = 0; } else { /* removes the + sign */ expected_len = 3; expected[0] = i; expected[1] = 0; expected[2] = 0; } expected[expected_len] = 0x2323; ok(len == expected_len, "i=0x%02x: expected len=%i, got len=%i\n", i, expected_len, len); ok(memcmp(output, expected, (expected_len + 1) * sizeof(WCHAR)) == 0, "i=0x%02x: expected output=%s, got output=%s\n", i, wine_dbgstr_wn(expected, expected_len + 1), wine_dbgstr_wn(output, expected_len + 1)); } /* test which one-byte characters terminate a sequence * also test whether the unfinished byte pair is discarded or not */ for (i = 0; i < 256; i++) { sprintf(input, "+B%c+AAA", i); memset(output, 0x23, sizeof(output) - sizeof(WCHAR)); output[sizeof(output) / sizeof(WCHAR) - 1] = 0; len = MultiByteToWideChar(CP_UTF7, 0, input, 8, output, sizeof(output) / sizeof(WCHAR) - 1); if (i == '-') { /* explicitly terminates */ expected_len = 2; expected[0] = 0; expected[1] = 0; } else if (i <= 0x7F) { if (base64_decoding_table[i] != -1) { /* absorbs the character into the base64 sequence */ expected_len = 3; expected[0] = 0x0400 | (base64_decoding_table[i] << 4) | 0x000F; expected[1] = 0x8000; expected[2] = 0; } else { /* implicitly terminates and discards the unfinished byte pair */ expected_len = 3; expected[0] = i; expected[1] = 0; expected[2] = 0; } } else { /* implicitly terminates but does not the discard unfinished byte pair */ expected_len = 3; expected[0] = i; expected[1] = 0x0400; expected[2] = 0; } expected[expected_len] = 0x2323; ok(len == expected_len, "i=0x%02x: expected len=%i, got len=%i\n", i, expected_len, len); ok(memcmp(output, expected, (expected_len + 1) * sizeof(WCHAR)) == 0, "i=0x%02x: expected output=%s, got output=%s\n", i, wine_dbgstr_wn(expected, expected_len + 1), wine_dbgstr_wn(output, expected_len + 1)); } for (i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) { memset(output, 0x23, sizeof(output) - sizeof(WCHAR)); output[sizeof(output) / sizeof(WCHAR) - 1] = 0; SetLastError(0xdeadbeef); len = MultiByteToWideChar(CP_UTF7, 0, tests[i].src, tests[i].srclen, tests[i].dst, tests[i].dstlen); tests[i].expected_dst[tests[i].chars_written] = 0x2323; if (!tests[i].len && tests[i].chars_written) { ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "tests[%i]: expected error=0x%x, got error=0x%x\n", i, ERROR_INSUFFICIENT_BUFFER, GetLastError()); } ok(len == tests[i].len, "tests[%i]: expected len=%i, got len=%i\n", i, tests[i].len, len); if (tests[i].dst) { ok(memcmp(tests[i].dst, tests[i].expected_dst, (tests[i].chars_written + 1) * sizeof(WCHAR)) == 0, "tests[%i]: expected dst=%s, got dst=%s\n", i, wine_dbgstr_wn(tests[i].expected_dst, tests[i].chars_written + 1), wine_dbgstr_wn(tests[i].dst, tests[i].chars_written + 1)); } } }
int verify_trust(const char source[], int warn_unsigned=0) { int nchars = MultiByteToWideChar(CP_ACP, 0, source, -1, NULL, 0); wchar_t* wsource = new wchar_t[nchars]; if (wsource == NULL) { fprintf(stderr, "SECURITY FAILURE: out-of-memory allocating wsource\n"); return -2; } MultiByteToWideChar(CP_ACP, 0, source, -1, wsource, nchars); /* code adapted from * http://msdn.microsoft.com/en-us/library/windows/desktop/aa382384%28v=vs.85%29.aspx */ /* Initialize the WINTRUST_FILE_INFO structure. */ WINTRUST_FILE_INFO FileData; memset(&FileData, 0, sizeof(FileData)); FileData.cbStruct = sizeof(WINTRUST_FILE_INFO); FileData.pcwszFilePath = wsource; FileData.hFile = NULL; FileData.pgKnownSubject = NULL; GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2; WINTRUST_DATA WinTrustData; /* Initialize the WinVerifyTrust input data structure. */ memset(&WinTrustData, 0, sizeof(WinTrustData)); WinTrustData.cbStruct = sizeof(WinTrustData); WinTrustData.pPolicyCallbackData = NULL; WinTrustData.pSIPClientData = NULL; WinTrustData.dwUIChoice = WTD_UI_NONE; WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE; WinTrustData.dwUnionChoice = WTD_CHOICE_FILE; WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY; WinTrustData.hWVTStateData = NULL; WinTrustData.pwszURLReference = NULL; WinTrustData.dwUIContext = 0; WinTrustData.pFile = &FileData; int trusted = 0; LONG status = WinVerifyTrust( NULL, &WVTPolicyGUID, &WinTrustData); DWORD err; switch (status) { case ERROR_SUCCESS: trusted = 1; break; case TRUST_E_NOSIGNATURE: /* check the error details */ err = GetLastError(); if (TRUST_E_NOSIGNATURE == err || TRUST_E_SUBJECT_FORM_UNKNOWN == err || TRUST_E_PROVIDER_UNKNOWN == err) { if (warn_unsigned) fprintf(stderr, "SECURITY WARNING: '%s' not signed\n", source); trusted = -1; } else{ /* unknown error verifying signature */ fprintf(stderr, "SECURITY FAILURE: trying to verify '%s' " "status=0x%lx, error=0x$lx\n", source, status, err); trusted = -2; } break; case TRUST_E_EXPLICIT_DISTRUST: case CRYPT_E_SECURITY_SETTINGS: /* subject or publisher was invalidated by machine admin */ fprintf(stderr, "SECURITY VIOLATION: '%s' is blocked by local policy\n", source); trusted = 0; break; case TRUST_E_SUBJECT_NOT_TRUSTED: /* user clicked "No" when asked to install/run. */ fprintf(stderr, "SECURTIY VIOLATION: '%s' has untrusted signature\n", source); trusted = 0; break; case TRUST_E_BAD_DIGEST: /* tampered binary */ fprintf(stderr, "SECURITY VIOLATION: '%s' tampered binary\n", source); break; default: fprintf(stderr, "SECURITY FAILURE: verifying '%s' status=0x%lx\n", source, status); break; } /* cleanup */ WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE; WinVerifyTrust( NULL, &WVTPolicyGUID, &WinTrustData); delete [] wsource; return trusted; }
DWORD WINAPI ThreadProc(LPVOID p) // thread that will start & monitor makensis { TCHAR buf[1024]; char iobuf[1024]; //i/o buffer STARTUPINFO si={sizeof(si),}; SECURITY_ATTRIBUTES sa={sizeof(sa),}; SECURITY_DESCRIPTOR sd={0,}; //security information for pipes PROCESS_INFORMATION pi={0,}; HANDLE newstdout=0,read_stdout=0; //pipe handles OSVERSIONINFO osv={sizeof(osv)}; GetVersionEx(&osv); if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) //initialize security descriptor (Windows NT) { InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd, true, NULL, false); sa.lpSecurityDescriptor = &sd; } else sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = true; //allow inheritable handles if (!CreatePipe(&read_stdout,&newstdout,&sa,0)) //create stdout pipe { ErrorMessage(_T("CreatePipe")); PostMessage(g_hwnd,WM_USER+1203,0,1); return 1; } GetStartupInfo(&si); //set startupinfo for the spawned process /* The dwFlags member tells CreateProcess how to make the process. STARTF_USESTDHANDLES validates the hStd* members. STARTF_USESHOWWINDOW validates the wShowWindow member. */ si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdOutput = newstdout; si.hStdError = newstdout; //set the new handles for the child process // ******************************************************************* // If there is a command line in the config file, use it for create process //spawn the child process if (!CreateProcess(NULL,g_cmdline,NULL,NULL,TRUE,CREATE_NEW_CONSOLE, NULL,tempzip_path,&si,&pi)) { ErrorMessage(_T("CreateProcess")); wnd_printf(_T("\r\nPlease make sure the path to makensis.exe is correct.")); CloseHandle(newstdout); CloseHandle(read_stdout); PostMessage(g_hwnd,WM_USER+1203,0,1); return 1; } CloseHandle(newstdout); // close this handle (duplicated in subprocess) now so we get ERROR_BROKEN_PIPE DWORD dwLeft = 0, dwRead = 0; while (ReadFile(read_stdout, iobuf+dwLeft, sizeof(iobuf)-dwLeft-1, &dwRead, NULL)) //wait for buffer, or fails with ERROR_BROKEN_PIPE when subprocess exits { dwRead += dwLeft; iobuf[dwRead] = '\0'; #ifdef _UNICODE // this tweak is to prevent LogMessage from cutting in the middle of an UTF-8 sequence // we print only up to the latest \n of the buffer, and keep the remaining for the next loop char* lastLF = strrchr(iobuf,'\n'); if (lastLF == NULL) lastLF = iobuf+dwRead-1; char ch = *++lastLF; *lastLF = '\0'; MultiByteToWideChar(CP_UTF8,0,iobuf,lastLF+1-iobuf,buf,COUNTOF(buf)); wnd_printf(buf); *lastLF = ch; dwLeft = iobuf+dwRead-lastLF; memmove(iobuf, lastLF, dwLeft); #else wnd_printf(iobuf); #endif } #ifdef _UNICODE // because of UTF-8 tweak, in rare case there can be some data remaining dwRead += dwLeft; iobuf[dwRead] = 0; MultiByteToWideChar(CP_UTF8,0,iobuf,dwRead+1,buf,COUNTOF(buf)); wnd_printf(buf); #endif CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(read_stdout); wsprintf(buf,_T("(source ZIP size was %d bytes)\r\n"),g_zipfile_size); wnd_printf(buf); PostMessage(g_hwnd,WM_USER+1203,0,0); return 0; }
int tempzip_make(HWND hwndDlg, TCHAR *fn) { TCHAR buf[MAX_PATH]; GetTempPath(MAX_PATH,buf); GetTempFileName(buf,_T("z2e"),GetTickCount(),tempzip_path); if (!CreateDirectory(tempzip_path,NULL)) { GetTempPath(MAX_PATH,tempzip_path); _tcscat(tempzip_path,_T("\\nsi")); if (!CreateDirectory(tempzip_path,NULL)) { tempzip_path[0]=0; MessageBox(hwndDlg,_T("Error creating temporary directory"),g_errcaption,MB_OK|MB_ICONSTOP); return 1; } } FILE *fp=_tfopen(fn,_T("rb")); if (fp) { fseek(fp,0,SEEK_END); g_zipfile_size=ftell(fp); fclose(fp); } else g_zipfile_size=0; unzFile f; f = unzOpen(fn); if (!f || unzGoToFirstFile(f) != UNZ_OK) { if (f) unzClose(f); MessageBox(hwndDlg,_T("Error opening ZIP file"),g_errcaption,MB_OK|MB_ICONSTOP); return 1; } int nf=0, nkb=0; g_extracting=1; do { char filenameA[MAX_PATH]; unz_file_info info; // ZREAD uses byte size, not TCHAR length. unzGetCurrentFileInfo(f,&info,filenameA,sizeof(filenameA),NULL,0,NULL,0); // was zip created on MS-DOS/Windows? if ((info.version & 0xFF00) == 0) { OemToCharBuffA(filenameA, filenameA, strlen(filenameA)); } #ifdef _UNICODE TCHAR filename[MAX_PATH]; if (MultiByteToWideChar(CP_ACP, 0, filenameA, -1, filename, MAX_PATH) == 0) { if (f) unzClose(f); MessageBox(hwndDlg,_T("Error converting filename to Unicode"), g_errcaption, MB_OK|MB_ICONSTOP); return 1; } #else char* filename = filenameA; #endif if (filename[0] && filename[_tcslen(filename)-1] != _T('\\') && filename[_tcslen(filename)-1] != _T('/')) { TCHAR *pfn=filename; while (*pfn) { if (*pfn == _T('/')) *pfn=_T('\\'); pfn++; } pfn=filename; if (pfn[1] == _T(':') && pfn[2] == _T('\\')) pfn+=3; while (*pfn == _T('\\')) pfn++; TCHAR out_filename[1024]; lstrcpy(out_filename,tempzip_path); lstrcat(out_filename,_T("\\")); lstrcat(out_filename,pfn); if (_tcsstr(pfn,_T("\\"))) { TCHAR buf[1024]; lstrcpy(buf,out_filename); TCHAR *p=buf+_tcslen(buf); while (p > buf && *p != _T('\\')) p--; *p=0; if (buf[0]) doMKDir(buf); } if (unzOpenCurrentFile(f) == UNZ_OK) { SendDlgItemMessage(hwndDlg,IDC_ZIPINFO_FILES,LB_ADDSTRING,0,(LPARAM)pfn); FILE *fp; int l; fp = _tfopen(out_filename,_T("wb")); if (fp) { do { // Jim Park: Local buf, no need to TCHAR char buf[1024]; l=unzReadCurrentFile(f,buf,sizeof(buf)); if (l > 0) { if (fwrite(buf,1,l,fp) != (unsigned int)l) { unzClose(f); fclose(fp); MessageBox(hwndDlg,_T("Error writing output file(s)"),g_errcaption,MB_OK|MB_ICONSTOP); g_extracting=0; return 1; } nkb++; } } while (l > 0); fclose(fp); { // set file time HANDLE hf = CreateFile(out_filename, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0); if (hf != INVALID_HANDLE_VALUE) { FILETIME ft, lft; DosDateTimeToFileTime(HIWORD(info.dosDate), LOWORD(info.dosDate), &ft); LocalFileTimeToFileTime(&ft, &lft); SetFileTime(hf, 0, 0, &lft); CloseHandle(hf); } } } else { unzClose(f); MessageBox(hwndDlg,_T("Error opening output file(s)"),g_errcaption,MB_OK|MB_ICONSTOP); g_extracting=0; return 1; } nf++; wsprintf(buf,_T("Extracting: %d files, %dKB"),nf,nkb); SetDlgItemText(hwndDlg,IDC_ZIPINFO_SUMMARY,buf); MSG msg; int quit=0; while (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if (msg.message == WM_DESTROY && msg.hwnd == g_hwnd) { quit++; break; } TranslateMessage(&msg); DispatchMessage(&msg); } unzCloseCurrentFile(f); if (quit) break; } else { unzClose(f); MessageBox(hwndDlg,_T("Error extracting from ZIP file"),g_errcaption,MB_OK|MB_ICONSTOP); g_extracting=0; return 1; } } } while (unzGoToNextFile(f) == UNZ_OK); g_extracting=0; wsprintf(buf,_T("Extracted: %d files, %dKB"),nf,nkb); SetDlgItemText(hwndDlg,IDC_ZIPINFO_SUMMARY,buf); unzClose(f); return 0; }
extern int main(int argc, char *argv[]) { const char *filename_cstr = "test.aaf"; #ifndef _MSC_VER setlocale (LC_ALL, "en_US.UTF-8"); #endif if (argc >= 2) { filename_cstr = argv[1]; } // convert C str to wide string aafWChar filename[FILENAME_MAX]; size_t status = mbstowcs(filename, filename_cstr, sizeof(filename)); if (status == (size_t)-1) { fprintf(stderr, "mbstowcs failed for \"%s\"\n", filename_cstr); return 1; } remove(filename_cstr); IAAFFile *pFile = NULL; int mode = 0; aafProductIdentification_t productID; aafProductVersion_t TestVersion = {1, 1, 0, 0, kAAFVersionUnknown}; productID.companyName = (aafCharacter*)L"HSC"; productID.productName = (aafCharacter*)L"String Tester"; productID.productVersion = &TestVersion; productID.productVersionString = NULL; productID.productID = TestProductID; productID.platform = (aafCharacter*)L"Linux"; // Create new AAF file check(AAFFileOpenNewModify(filename, mode, &productID, &pFile)); // Create a simple Mob IAAFClassDef *classDef = NULL; IAAFMob *pMob = NULL; IAAFHeader *pHeader = NULL; IAAFDictionary *pDictionary = NULL; check(pFile->GetHeader(&pHeader)); check(pHeader->GetDictionary(&pDictionary)); check(pDictionary->LookupClassDef(AUID_AAFMasterMob, &classDef)); check(classDef->CreateInstance(IID_IAAFMob, (IUnknown **)&pMob)); classDef->Release(); check(pMob->SetMobID(TEST_MobID)); // UTF-8 for codepoint U+1D11E (musical G Clef): 0xf0,0x9d,0x84,0x9e // UTF-8 for codepoint U+1D122 (musical F Clef): 0xf0,0x9d,0x84,0xa2 // http://unicode.org/charts/PDF/U1D100.pdf // http://en.wikipedia.org/wiki/UTF-8 aafCharacter *mobname; const unsigned char inputStr[] = { 0xf0,0x9d,0x84,0x9e, // U+1D11E 0xf0,0x9d,0x84,0xa2, // U+1D122 0x4d, 0x6f, 0x62, // 'M' 'o' 'b' 0x0 }; // Convert UTF-8 inputStr to native wchar_t representation (UTF-32 Unix, UTF-16 Windows) int wlen = 0, n; #ifndef _MSC_VER int ret; char *p = (char *)inputStr; while ((ret = mblen(p, 4)) > 0) { ++wlen; p+=ret; } mobname = new aafCharacter[wlen+1]; n = mbstowcs(mobname, (const char *)inputStr, wlen+1); if (n == -1) { fprintf (stderr, "mbstowcs returned -1. Invalid multibyte string\n"); exit(1); } #else // Under Windows we must use MultiByteToWideChar() to get correct UTF-8 conversion to UTF-16 // since mbstowcs() is broken for UTF-8. wlen = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, (LPCSTR)inputStr, -1, NULL, 0); if (wlen == 0) { fprintf (stderr, "MultiByteToWideChar returned 0. Invalid multibyte string\n"); exit(1); } mobname = new aafCharacter[wlen]; n = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, (LPCSTR)inputStr, -1, mobname, wlen); if (n == 0) { fprintf (stderr, "MultiByteToWideChar returned 0. Invalid multibyte string\n"); exit(1); } #endif // SetName() calls OMSimpleProperty::set() which does a memcpy of the mobname string // to an OMByte* variable 'bits()' at OMProperty.cpp:399 // Found by setting an rwatch on mobname address. check(pMob->SetName(mobname)); aafUInt32 size_before = 0; check(pMob->GetNameBufLen(&size_before)); check(pHeader->AddMob(pMob)); pMob->Release(); pHeader->Release(); pDictionary->Release(); // All the work of storing to disk happens during Save() // The bits() variable is next read in OMType::contract() at OMType.cpp:137 // which is called by ImplAAFTypeDefCharacter::externalize() at ImplAAFTypeDefCharacter.cpp:307 // which is called by ImplAAFTypeDefString::externalize() at ImplAAFTypeDefString.cpp:584 // which is called by OMSSStoredObject::save() at OMSSStoredObject.cpp:382 check(pFile->Save()); check(pFile->Close()); pFile->Release(); // OMCharacterStringProperty<CharacterType>::stringLength() at OMVariableSizePropertyT.h:80 // calculates string length of AAF string properties // Read AAF file back in check(AAFFileOpenExistingRead(filename, mode, &pFile)); // Get the Mob check(pFile->GetHeader(&pHeader)); check(pHeader->LookupMob(TEST_MobID, &pMob)); aafUInt32 size_after = 0; check(pMob->GetNameBufLen(&size_after)); aafCharacter *mobname_after = new aafCharacter[size_after]; check(pMob->GetName(mobname_after, size_after)); // Compare Mob name before storing to disk with Mob name read back from disk int test_result = 0; if (size_before != size_after) { printf("size_before=%d != size_after=%d\n", size_before, size_after); test_result = 1; } else { if (memcmp(mobname, mobname_after, size_before) != 0) { printf("wchar_t* mobname and wchar_t* mobname_after differ:\n"); printf(" %s\n", hexDump(mobname, size_before)); printf(" %s\n", hexDump(mobname_after, size_after)); test_result = 1; } } // Check if the multibyte (UTF-8) versions of mobname and mobname_after match. char *outputStr; #ifndef _MSC_VER wlen = wcslen(mobname_after)*sizeof(aafCharacter) + 1; outputStr = new char [wlen]; n = wcstombs (outputStr, mobname_after, wlen); if (n == -1) { fprintf(stderr, "Could not convert mobname_after to multibyte str\n"); exit(1); } #else wlen = WideCharToMultiByte(CP_UTF8, 0, mobname_after, -1, NULL, 0, NULL, NULL); if (wlen == 0) { fprintf (stderr, "Failed to convert mobname_after to multibyte string\n"); exit(1); } outputStr = new char[wlen]; wlen = WideCharToMultiByte(CP_UTF8, 0, mobname_after, -1, outputStr, wlen, NULL, NULL); #endif if (strlen((char *)inputStr) != strlen(outputStr)) { fprintf(stderr, "UTF-8 version of string: input length(%d) != output length(%d)\n", (int)strlen((char *)inputStr), (int)strlen(outputStr)); test_result = 1; } if (strcmp((char *)inputStr, outputStr) != 0) { fprintf(stderr, "UTF-8 version of string: input and output strings differ\n"); printf(" %s\n", hexDump(inputStr, strlen((char *)inputStr))); printf(" %s\n", hexDump(outputStr, strlen(outputStr))); test_result = 1; } pMob->Release(); pHeader->Release(); check(pFile->Close()); pFile->Release(); delete [] mobname; delete [] mobname_after; return test_result; }
static void test_OleLoadPicturePath(void) { static WCHAR emptyW[] = {0}; IPicture *pic; HRESULT hres; int i; char temp_path[MAX_PATH]; char temp_file[MAX_PATH]; WCHAR temp_fileW[MAX_PATH + 5] = {'f','i','l','e',':','/','/','/'}; HANDLE file; DWORD size; WCHAR *ptr; const struct { LPOLESTR szURLorPath; REFIID riid; IPicture **pic; } invalid_parameters[] = { {NULL, NULL, NULL}, {NULL, NULL, &pic}, {NULL, &IID_IPicture, NULL}, {NULL, &IID_IPicture, &pic}, {emptyW, NULL, NULL}, {emptyW, &IID_IPicture, NULL}, }; for (i = 0; i < sizeof(invalid_parameters)/sizeof(invalid_parameters[0]); i++) { pic = (IPicture *)0xdeadbeef; hres = OleLoadPicturePath(invalid_parameters[i].szURLorPath, NULL, 0, 0, invalid_parameters[i].riid, (void **)invalid_parameters[i].pic); ok(hres == E_INVALIDARG, "[%d] Expected OleLoadPicturePath to return E_INVALIDARG, got 0x%08x\n", i, hres); ok(pic == (IPicture *)0xdeadbeef, "[%d] Expected output pointer to be 0xdeadbeef, got %p\n", i, pic); } pic = (IPicture *)0xdeadbeef; hres = OleLoadPicturePath(emptyW, NULL, 0, 0, NULL, (void **)&pic); todo_wine ok(hres == INET_E_UNKNOWN_PROTOCOL || /* XP/Vista+ */ broken(hres == E_UNEXPECTED) || /* NT4 */ broken(hres == E_OUTOFMEMORY), /* Win2k/Win2k3 */ "Expected OleLoadPicturePath to return INET_E_UNKNOWN_PROTOCOL, got 0x%08x\n", hres); ok(pic == NULL, "Expected the output interface pointer to be NULL, got %p\n", pic); pic = (IPicture *)0xdeadbeef; hres = OleLoadPicturePath(emptyW, NULL, 0, 0, &IID_IPicture, (void **)&pic); todo_wine ok(hres == INET_E_UNKNOWN_PROTOCOL || /* XP/Vista+ */ broken(hres == E_UNEXPECTED) || /* NT4 */ broken(hres == E_OUTOFMEMORY), /* Win2k/Win2k3 */ "Expected OleLoadPicturePath to return INET_E_UNKNOWN_PROTOCOL, got 0x%08x\n", hres); ok(pic == NULL, "Expected the output interface pointer to be NULL, got %p\n", pic); /* Create a local temporary image file for testing. */ GetTempPathA(sizeof(temp_path), temp_path); GetTempFileNameA(temp_path, "bmp", 0, temp_file); file = CreateFileA(temp_file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); WriteFile(file, bmpimage, sizeof(bmpimage), &size, NULL); CloseHandle(file); MultiByteToWideChar(CP_ACP, 0, temp_file, -1, temp_fileW + 8, sizeof(temp_fileW)/sizeof(WCHAR) - 8); /* Try a normal DOS path. */ hres = OleLoadPicturePath(temp_fileW + 8, NULL, 0, 0, &IID_IPicture, (void **)&pic); ok(hres == S_OK || broken(hres == E_UNEXPECTED), /* NT4 */ "Expected OleLoadPicturePath to return S_OK, got 0x%08x\n", hres); if (pic) IPicture_Release(pic); /* Try a DOS path with tacked on "file:". */ hres = OleLoadPicturePath(temp_fileW, NULL, 0, 0, &IID_IPicture, (void **)&pic); ok(hres == S_OK || broken(hres == E_UNEXPECTED), /* NT4 */ "Expected OleLoadPicturePath to return S_OK, got 0x%08x\n", hres); if (pic) IPicture_Release(pic); DeleteFileA(temp_file); /* Try with a nonexistent file. */ hres = OleLoadPicturePath(temp_fileW + 8, NULL, 0, 0, &IID_IPicture, (void **)&pic); ok(hres == INET_E_RESOURCE_NOT_FOUND || /* XP+ */ broken(hres == E_UNEXPECTED) || /* NT4 */ broken(hres == E_FAIL), /*Win2k */ "Expected OleLoadPicturePath to return INET_E_RESOURCE_NOT_FOUND, got 0x%08x\n", hres); hres = OleLoadPicturePath(temp_fileW, NULL, 0, 0, &IID_IPicture, (void **)&pic); ok(hres == INET_E_RESOURCE_NOT_FOUND || /* XP+ */ broken(hres == E_UNEXPECTED) || /* NT4 */ broken(hres == E_FAIL), /* Win2k */ "Expected OleLoadPicturePath to return INET_E_RESOURCE_NOT_FOUND, got 0x%08x\n", hres); file = CreateFileA(temp_file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); WriteFile(file, bmpimage, sizeof(bmpimage), &size, NULL); CloseHandle(file); /* Try a "file:" URL with slash separators. */ ptr = temp_fileW + 8; while (*ptr) { if (*ptr == '\\') *ptr = '/'; ptr++; } hres = OleLoadPicturePath(temp_fileW, NULL, 0, 0, &IID_IPicture, (void **)&pic); ok(hres == S_OK || broken(hres == E_UNEXPECTED), /* NT4 */ "Expected OleLoadPicturePath to return S_OK, got 0x%08x\n", hres); if (pic) IPicture_Release(pic); DeleteFileA(temp_file); /* Try with a nonexistent file. */ hres = OleLoadPicturePath(temp_fileW, NULL, 0, 0, &IID_IPicture, (void **)&pic); ok(hres == INET_E_RESOURCE_NOT_FOUND || /* XP+ */ broken(hres == E_UNEXPECTED) || /* NT4 */ broken(hres == E_FAIL), /* Win2k */ "Expected OleLoadPicturePath to return INET_E_RESOURCE_NOT_FOUND, got 0x%08x\n", hres); }
int main(int argc,char **argv) { HANDLE SCManager = 0; HANDLE service = 0; HANDLE device = 0; SERVICE_STATUS status; int i=1,j; char sysfilepath[256]; char devicepath[256]; char ret[1024]; WCHAR ToSend[512]; DWORD code, bytes; char DriveLetter; unsigned short port; unsigned long space; if( argc<2 ) { usage(argv[0]); return 0; } // get sysfile path GetCurrentDirectory(sizeof(sysfilepath), sysfilepath); strcat( sysfilepath, "\\\\" ); strcat( sysfilepath, SYSFILE ); if( !FileExists( sysfilepath ) && strcmp(argv[1],"-stop") && strcmp(argv[1],"-h") ) { printf("extracting .sys...\n"); if( !ExtractSysFile() ) { printf("cannot extract sys file...\n"); return 0; } } // MultiByteToWideChar(CP_ACP, 0, argv[4], -1, ToSend, sizeof(ToSend)); SCManager = OpenSCManager(NULL,NULL,SC_MANAGER_CREATE_SERVICE); if(SCManager) { service = CreateService(SCManager, SERVICENAME, SERVICENAME, SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START,SERVICE_ERROR_NORMAL, sysfilepath, NULL,NULL,NULL,NULL,NULL); if(!service) // if we cannot create it, maybe he is already existing service = OpenService(SCManager,SERVICENAME, SERVICE_ALL_ACCESS); if(service) StartService(service, 0, NULL); else printf("cannot create/open the service\n"); } else printf("cannot open the service manager\n"); sprintf(devicepath,"\\\\.\\Global\\%s\0",DEVICE); device = CreateFile(devicepath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL); if( !device || device==INVALID_HANDLE_VALUE ) { printf("cannot communicate with the driver.\n"); CloseServiceHandle(service); CloseServiceHandle(SCManager); return 0; } if( !strcmp(argv[1], "-stop")) { // stop & uninstall service // clean startup reg keys fix( NULL, FALSE ); // delete VOLUME.INI files DeleteAllSpaceFiles(); if( device ) CloseHandle( device ); if( service ) { ControlService(service, SERVICE_CONTROL_STOP,&status); DeleteService(service); CloseServiceHandle(service); } if( SCManager ) CloseServiceHandle(SCManager); return 0; } if( !strcmp(argv[1], "-h")) { printf("all options \"cumulables\" in a same command line\n"); printf("for exemple: agony -p process1.exe process2.exe will hide 2 process\n"); printf("we can accumulate different options on a same line:\n"); printf("%s -p process.exe process2.exe -s service1 -f process1.exe process2.exe\n",argv[0]); printf("we can also choose to launch our command one by one\n\n"); printf("for the -space option, the syntax is:\n"); printf("%s -space volume_letter:space_to_hide_in_MB\n",argv[0]); printf("we can cumulate for option -space, like other options:\n"); printf("%s -space C:5000 D:1000 F:5500\n",argv[0]); return 0; } code = NO_MSG; while( i < argc ) { if( !strcmp(argv[i],"-p") ) { code = PROCESS_CODE; i++; continue; } if( !strcmp(argv[i],"-f") ) { code = FILE_CODE; i++; continue; } if( !strcmp( argv[i], "-k" ) ) { code = REGKEY_CODE; i++; continue; } if( !strcmp( argv[i], "-v" ) ) { code = REGVALUE_CODE; i++; continue; } if( !strcmp( argv[i], "-s" ) ) { code = SERVICE_CODE; i++; continue; } if( !strcmp( argv[i], "-tcp" ) ) { code = TCP_PORT_CODE; i++; continue; } if( !strcmp( argv[i], "-udp" ) ) { code = UDP_PORT_CODE; i++; continue; } if( !strcmp( argv[i], "-space" ) ) { code = DISK_SPACE_CODE; i++; continue; } if( !strcmp( argv[i], "-r" ) ) { // we get the initial cmdline ret[0] = '\0'; for(j=1; j<argc; j++) { strcat(ret, " "); strcat(ret, argv[j]); } fix(ret, TRUE); i++; continue; } if( code == DISK_SPACE_CODE ) { DriveLetter = argv[i][0]; space = atoi( argv[i]+2 ); if(!CreateSpaceFile(DriveLetter,space)) printf("volume %c space will not be falsificated\n", DriveLetter); // we launch the hook and we hide the VOLUME.INI file DeviceIoControl(device, CODEMSG(DISK_SPACE_CODE), LSPACEFILENAME, sizeof(LSPACEFILENAME), &ret, sizeof(ret),&bytes,NULL); DeviceIoControl(device, CODEMSG(FILE_CODE), LSPACEFILENAME, sizeof(LSPACEFILENAME), &ret, sizeof(ret),&bytes,NULL); } else if( code == TCP_PORT_CODE || code == UDP_PORT_CODE ) { port = atoi( argv[i] ); DeviceIoControl(device, CODEMSG(code), &port, sizeof(port), &ret, sizeof(ret),&bytes,NULL); } else { // convert the arg to wide char before sending MultiByteToWideChar(CP_ACP, 0, argv[i], -1, ToSend, sizeof(ToSend)); DeviceIoControl(device, CODEMSG(code), ToSend, (wcslen(ToSend)+1)*2, &ret, sizeof(ret),&bytes,NULL); } i++; } CloseHandle( device ); if( service ) CloseServiceHandle(service); if( SCManager ) CloseServiceHandle(SCManager); return 0; }
int uv_chdir(const char* dir) { WCHAR utf16_buffer[MAX_PATH]; size_t utf16_len; WCHAR drive_letter, env_var[4]; if (dir == NULL) { return UV_EINVAL; } if (MultiByteToWideChar(CP_UTF8, 0, dir, -1, utf16_buffer, MAX_PATH) == 0) { DWORD error = GetLastError(); /* The maximum length of the current working directory is 260 chars, */ /* including terminating null. If it doesn't fit, the path name must be */ /* too long. */ if (error == ERROR_INSUFFICIENT_BUFFER) { return UV_ENAMETOOLONG; } else { return uv_translate_sys_error(error); } } if (!SetCurrentDirectoryW(utf16_buffer)) { return uv_translate_sys_error(GetLastError()); } /* Windows stores the drive-local path in an "hidden" environment variable, */ /* which has the form "=C:=C:\Windows". SetCurrentDirectory does not */ /* update this, so we'll have to do it. */ utf16_len = GetCurrentDirectoryW(MAX_PATH, utf16_buffer); if (utf16_len == 0) { return uv_translate_sys_error(GetLastError()); } else if (utf16_len > MAX_PATH) { return UV_EIO; } /* The returned directory should not have a trailing slash, unless it */ /* points at a drive root, like c:\. Remove it if needed. */ if (utf16_buffer[utf16_len - 1] == L'\\' && !(utf16_len == 3 && utf16_buffer[1] == L':')) { utf16_len--; utf16_buffer[utf16_len] = L'\0'; } if (utf16_len < 2 || utf16_buffer[1] != L':') { /* Doesn't look like a drive letter could be there - probably an UNC */ /* path. TODO: Need to handle win32 namespaces like \\?\C:\ ? */ drive_letter = 0; } else if (utf16_buffer[0] >= L'A' && utf16_buffer[0] <= L'Z') { drive_letter = utf16_buffer[0]; } else if (utf16_buffer[0] >= L'a' && utf16_buffer[0] <= L'z') { /* Convert to uppercase. */ drive_letter = utf16_buffer[0] - L'a' + L'A'; } else { /* Not valid. */ drive_letter = 0; } if (drive_letter != 0) { /* Construct the environment variable name and set it. */ env_var[0] = L'='; env_var[1] = drive_letter; env_var[2] = L':'; env_var[3] = L'\0'; if (!SetEnvironmentVariableW(env_var, utf16_buffer)) { return uv_translate_sys_error(GetLastError()); } } return 0; }
enum ILibFileDir_Type ILibFileDir_GetType(char* directory) { #if defined(WIN32) || defined(_WIN32_WCE) DWORD _si; int dirLen,dirSize; #if defined(_WIN32_WCE) wchar_t *tempChar; int tempCharLength; #endif dirLen = (int) strlen(directory); dirSize = dirLen+1; #if defined(_WIN32_WCE) tempCharLength = MultiByteToWideChar(CP_UTF8,0,directory,-1,NULL,0); tempChar = (wchar_t*)malloc(sizeof(wchar_t)*tempCharLength); MultiByteToWideChar(CP_UTF8,0,directory,-1,tempChar,tempCharLength); _si = GetFileAttributes(tempChar); #else _si = GetFileAttributes(directory); #endif if (_si == 0xFFFFFFFF) { return ILibFileDir_Type_NOT_FOUND_ERROR; } if ((_si & FILE_ATTRIBUTE_DIRECTORY) == 0) { return ILibFileDir_Type_FILE; } else { return ILibFileDir_Type_DIRECTORY; } #else struct stat _si; int dirLen,dirSize; char *fullpath; int pathExists; enum ILibFileDir_Type retVal = ILibFileDir_Type_NOT_FOUND_ERROR; dirLen = (int) strlen(directory); dirSize = dirLen+1; fullpath = (char*) malloc(dirSize); pathExists = stat (directory, &_si); if (pathExists != -1) { if ((_si.st_mode & S_IFDIR) == S_IFDIR) { retVal = ILibFileDir_Type_DIRECTORY; } else { retVal = ILibFileDir_Type_FILE; } } return retVal; #endif }
PLUGIN_EXPORT LPCWSTR GetString(void* data) { MeasureData* measure = (MeasureData*)data; static WCHAR sBuffer[256]; DWORD sBufferLen = _countof(sBuffer); BYTE tmpBuffer[7168]; ULONG tmpBufferLen = _countof(tmpBuffer); auto convertToWide = [&](LPCSTR str)->LPCWSTR { MultiByteToWideChar(CP_ACP, 0, str, -1, sBuffer, 256); return sBuffer; }; switch (measure->type) { case MEASURE_COMPUTER_NAME: GetComputerName(sBuffer, &sBufferLen); return sBuffer; case MEASURE_USER_NAME: GetUserName(sBuffer, &sBufferLen); return sBuffer; case MEASURE_WORK_AREA: wsprintf(sBuffer, L"%i x %i", GetSystemMetrics(SM_CXFULLSCREEN), GetSystemMetrics(SM_CYFULLSCREEN)); return sBuffer; case MEASURE_SCREEN_SIZE: wsprintf(sBuffer, L"%i x %i", GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); return sBuffer; case MEASURE_OS_VERSION: return GetPlatformName(); case MEASURE_ADAPTER_DESCRIPTION: if (ERROR_SUCCESS == GetAdaptersInfo((IP_ADAPTER_INFO*)tmpBuffer, &tmpBufferLen)) { PIP_ADAPTER_INFO info = (IP_ADAPTER_INFO*)tmpBuffer; int i = 0; while (info) { if (i == measure->data) { return convertToWide(info->Description); } info = info->Next; i++; } } break; case MEASURE_IP_ADDRESS: if (NO_ERROR == GetIpAddrTable((PMIB_IPADDRTABLE)tmpBuffer, &tmpBufferLen, FALSE)) { PMIB_IPADDRTABLE ipTable = (PMIB_IPADDRTABLE)tmpBuffer; if (measure->data >= 1000) { measure->data = measure->data - 999; for (UINT i = 0; i < ipTable->dwNumEntries; ++i) { if ((ipTable->table[i].wType) & MIB_IPADDR_DISCONNECTED) continue; --measure->data; if (measure->data == 0) { DWORD ip = ipTable->table[i].dwAddr; wsprintf(sBuffer, L"%i.%i.%i.%i", ip % 256, (ip >> 8) % 256, (ip >> 16) % 256, (ip >> 24) % 256); return sBuffer; } } }
static void test_inffilelist(void) { static const char inffile2[] = "test2.inf"; static const WCHAR inffile2W[] = {'t','e','s','t','2','.','i','n','f',0}; static const char invalid_inf[] = "invalid.inf"; static const WCHAR invalid_infW[] = {'i','n','v','a','l','i','d','.','i','n','f',0}; static const char *inf = "[Version]\n" "Signature=\"$Chicago$\""; static const char *inf2 = "[Version]\n" "Signature=\"$CHICAGO$\""; static const char *infNT = "[Version]\n" "Signature=\"$WINDOWS NT$\""; WCHAR *p, *ptr; char dirA[MAX_PATH]; WCHAR dir[MAX_PATH] = { 0 }; WCHAR buffer[MAX_PATH] = { 0 }; DWORD expected, outsize; BOOL ret; if(!pSetupGetInfFileListW) { win_skip("SetupGetInfFileListW not present\n"); return; } /* NULL means %windir%\\inf * get the value as reference */ expected = 0; SetLastError(0xdeadbeef); ret = pSetupGetInfFileListW(NULL, INF_STYLE_WIN4, NULL, 0, &expected); if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) { win_skip("SetupGetInfFileListW not implemented\n"); return; } ok(ret, "expected SetupGetInfFileListW to succeed! Error: %d\n", GetLastError()); ok(expected > 0, "expected required buffersize to be at least 1\n"); /* check if an empty string doesn't behaves like NULL */ outsize = 0; SetLastError(0xdeadbeef); ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, NULL, 0, &outsize); ok(!ret, "expected SetupGetInfFileListW to fail!\n"); /* create a private directory, the temp directory may contain some * inf files left over from old installations */ if (!GetTempFileNameA(CURR_DIR, "inftest", 1, dirA)) { win_skip("GetTempFileNameA failed with error %d\n", GetLastError()); return; } if (!CreateDirectoryA(dirA, NULL )) { win_skip("CreateDirectoryA(%s) failed with error %d\n", dirA, GetLastError()); return; } if (!SetCurrentDirectoryA(dirA)) { win_skip("SetCurrentDirectoryA failed with error %d\n", GetLastError()); RemoveDirectoryA(dirA); return; } MultiByteToWideChar(CP_ACP, 0, dirA, -1, dir, MAX_PATH); /* check a not existing directory */ ptr = dir + lstrlenW(dir); MultiByteToWideChar(CP_ACP, 0, "\\not_existent", -1, ptr, MAX_PATH - lstrlenW(dir)); outsize = 0xffffffff; SetLastError(0xdeadbeef); ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, NULL, 0, &outsize); ok(ret, "expected SetupGetInfFileListW to succeed!\n"); ok(outsize == 1, "expected required buffersize to be 1, got %d\n", outsize); ok(ERROR_PATH_NOT_FOUND == GetLastError(), "expected error ERROR_PATH_NOT_FOUND, got %d\n", GetLastError()); create_inf_file(inffile, inf); create_inf_file(inffile2, inf); create_inf_file(invalid_inf, "This content does not match the inf file format"); /* pass a filename instead of a directory */ *ptr = '\\'; MultiByteToWideChar(CP_ACP, 0, invalid_inf, -1, ptr+1, MAX_PATH - lstrlenW(dir)); outsize = 0xffffffff; SetLastError(0xdeadbeef); ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, NULL, 0, &outsize); ok(!ret, "expected SetupGetInfFileListW to fail!\n"); ok(ERROR_DIRECTORY == GetLastError(), "expected error ERROR_DIRECTORY, got %d\n", GetLastError()); /* make the filename look like directory */ dir[1 + lstrlenW(dir)] = 0; dir[lstrlenW(dir)] = '\\'; SetLastError(0xdeadbeef); ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, NULL, 0, &outsize); ok(!ret, "expected SetupGetInfFileListW to fail!\n"); ok(ERROR_DIRECTORY == GetLastError(), "expected error ERROR_DIRECTORY, got %d\n", GetLastError()); /* now check the buffer contents of a valid call */ *ptr = 0; expected = 3 + strlen(inffile) + strlen(inffile2); ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, buffer, MAX_PATH, &outsize); ok(ret, "expected SetupGetInfFileListW to succeed!\n"); ok(expected == outsize, "expected required buffersize to be %d, got %d\n", expected, outsize); for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1) ok(!lstrcmpW(p,inffile2W) || !lstrcmpW(p,inffileW), "unexpected filename %s\n",wine_dbgstr_w(p)); /* upper case value */ create_inf_file(inffile2, inf2); ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, buffer, MAX_PATH, &outsize); ok(ret, "expected SetupGetInfFileListW to succeed!\n"); ok(expected == outsize, "expected required buffersize to be %d, got %d\n", expected, outsize); for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1) ok(!lstrcmpW(p,inffile2W) || !lstrcmpW(p,inffileW), "unexpected filename %s\n",wine_dbgstr_w(p)); /* signature Windows NT is also inf style win4 */ create_inf_file(inffile2, infNT); expected = 3 + strlen(inffile) + strlen(inffile2); ret = pSetupGetInfFileListW(dir, INF_STYLE_WIN4, buffer, MAX_PATH, &outsize); ok(ret, "expected SetupGetInfFileListW to succeed!\n"); ok(expected == outsize, "expected required buffersize to be %d, got %d\n", expected, outsize); for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1) ok(!lstrcmpW(p,inffile2W) || !lstrcmpW(p,inffileW), "unexpected filename %s\n",wine_dbgstr_w(p)); /* old style */ expected = 2 + strlen(invalid_inf); ret = pSetupGetInfFileListW(dir, INF_STYLE_OLDNT, buffer, MAX_PATH, &outsize); ok(ret, "expected SetupGetInfFileListW to succeed!\n"); ok(expected == outsize, "expected required buffersize to be %d, got %d\n", expected, outsize); for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1) ok(!lstrcmpW(p,invalid_infW), "unexpected filename %s\n",wine_dbgstr_w(p)); /* mixed style */ expected = 4 + strlen(inffile) + strlen(inffile2) + strlen(invalid_inf); ret = pSetupGetInfFileListW(dir, INF_STYLE_OLDNT | INF_STYLE_WIN4, buffer, MAX_PATH, &outsize); ok(ret, "expected SetupGetInfFileListW to succeed!\n"); ok(expected == outsize, "expected required buffersize to be %d, got %d\n", expected, outsize); for(p = buffer; lstrlenW(p) && (outsize > (p - buffer)); p+=lstrlenW(p) + 1) ok(!lstrcmpW(p,inffile2W) || !lstrcmpW(p,inffileW) || !lstrcmpW(p,invalid_infW), "unexpected filename %s\n",wine_dbgstr_w(p)); DeleteFileA(inffile); DeleteFileA(inffile2); DeleteFileA(invalid_inf); SetCurrentDirectoryA(CURR_DIR); RemoveDirectoryA(dirA); }
bool GetAliases(wchar_t* asExeName, wchar_t** rsAliases, LPDWORD rnAliasesSize) { bool lbRc = false; DWORD nAliasRC, nAliasErr, nAliasAErr = 0, nSizeA = 0; _ASSERTE(asExeName && rsAliases && rnAliasesSize); _ASSERTE(*rsAliases == NULL); *rnAliasesSize = GetConsoleAliasesLength(asExeName); if (*rnAliasesSize == 0) { lbRc = true; } else { *rsAliases = (wchar_t*)calloc(*rnAliasesSize+2,1); nAliasRC = GetConsoleAliases(*rsAliases,*rnAliasesSize,asExeName); if (nAliasRC) { lbRc = true; } else { nAliasErr = GetLastError(); if (nAliasErr == ERROR_NOT_ENOUGH_MEMORY) { // Попробовать ANSI функции UINT nCP = CP_OEMCP; char szExeName[MAX_PATH+1]; char *pszAliases = NULL; WideCharToMultiByte(nCP,0,asExeName,-1,szExeName,MAX_PATH+1,0,0); nSizeA = GetConsoleAliasesLengthA(szExeName); if (nSizeA) { pszAliases = (char*)calloc(nSizeA+1,1); nAliasRC = GetConsoleAliasesA(pszAliases,nSizeA,szExeName); if (nAliasRC) { lbRc = true; MultiByteToWideChar(nCP,0,pszAliases,nSizeA,*rsAliases,((*rnAliasesSize)/2)+1); } else { nAliasAErr = GetLastError(); } free(pszAliases); } } if (!nAliasRC) { if ((*rnAliasesSize) < 255) { free(*rsAliases); *rsAliases = (wchar_t*)calloc(128,2); } _wsprintf(*rsAliases, SKIPLEN(127) L"\nConEmuC: GetConsoleAliases failed, ErrCode=0x%08X(0x%08X), AliasesLength=%i(%i)\n\n", nAliasErr, nAliasAErr, *rnAliasesSize, nSizeA); } } } return lbRc; }
//+--------------------------------------------------------------------------- // // Function: HrInstallNetComponent // // Purpose: Install the specified net component // // Arguments: // pnc [in] pointer to INetCfg object // szComponentId [in] component to install // pguidClass [in] class guid of the component // // Returns: S_OK or NETCFG_S_REBOOT on success, otherwise an error code // // Notes: // HRESULT HrInstallNetComponent(IN INetCfg* pnc, IN PCTSTR szComponentId, IN const GUID* pguidClass) { HRESULT hr=S_OK; OBO_TOKEN OboToken; INetCfgClassSetup* pncClassSetup; INetCfgComponent* pncc; WCHAR szComponentIdW[256] ; int cnt ; #ifdef _MBCS // @hootch@ // // size_t cchLen; StringCchLength(szComponentId, 256, &cchLen); cnt = MultiByteToWideChar( CP_ACP, // code page 0, // character-type options szComponentId, // string to map cchLen, // number of bytes in string szComponentIdW, // wide-character buffer 256 // size of buffer ); if(cnt == 0) { // error return S_FALSE ; } #endif // OBO_TOKEN specifies the entity on whose behalf this // component is being installed // set it to OBO_USER so that szComponentId will be installed // On-Behalf-Of "user" ZeroMemory (&OboToken, sizeof(OboToken)); OboToken.Type = OBO_USER; hr = pnc->QueryNetCfgClass (pguidClass, IID_INetCfgClassSetup, (void**)&pncClassSetup); if (SUCCEEDED(hr)) { #ifdef _MBCS hr = pncClassSetup->Install(szComponentIdW, &OboToken, NSF_POSTSYSINSTALL, 0, // <upgrade-from-build-num> NULL, // answerfile name NULL, // answerfile section name &pncc); #else hr = pncClassSetup->Install(szComponentId, &OboToken, NSF_POSTSYSINSTALL, 0, // <upgrade-from-build-num> NULL, // answerfile name NULL, // answerfile section name &pncc); #endif if (S_OK == hr) { // we dont want to use pncc (INetCfgComponent), release it ReleaseObj(pncc); } ReleaseObj(pncClassSetup); } return hr; }
int CDb3Base::WorkModuleChain(int firstTime) { DBModuleName moduleName, *newModName; if (firstTime) { cb->pfnAddLogMessage(STATUS_MESSAGE, TranslateT("Processing module name chain")); modChainCount = 0; last_mod = 0; free(modChain); modChain = (ModChainEntry*)malloc(sizeof(ModChainEntry)); phase = 0; ofsCurrent = m_dbHeader.ofsFirstModuleName; } switch (phase) { case 0: if (ofsCurrent == 0) { phase++; return ERROR_SUCCESS; } if (!SignatureValid(ofsCurrent, DBMODULENAME_SIGNATURE)) { cb->pfnAddLogMessage(STATUS_ERROR, TranslateT("Module chain corrupted, further entries ignored")); phase++; return ERROR_SUCCESS; } if (PeekSegment(ofsCurrent, &moduleName, offsetof(DBModuleName, name)) != ERROR_SUCCESS) { phase++; return ERROR_SUCCESS; } modChain = (ModChainEntry*)realloc(modChain, sizeof(ModChainEntry)*++modChainCount); modChain[modChainCount - 1].ofsOld = ofsCurrent; modChain[modChainCount - 1].size = offsetof(DBModuleName, name) + moduleName.cbName; modChain[modChainCount - 1].ofsNew = 0; if (moduleName.cbName) PeekSegment(ofsCurrent + offsetof(DBModuleName, name), &modChain[modChainCount - 1].name, moduleName.cbName); modChain[modChainCount - 1].name[moduleName.cbName] = 0; ofsCurrent = moduleName.ofsNext; break; case 1: ofsLast = 0; iCurrentModName = 0; m_dbHeader.ofsFirstModuleName = 0; phase++; case 2: if (iCurrentModName >= modChainCount) { DWORD dw = 0; if (ofsLast) WriteSegment(ofsLast + offsetof(DBModuleName, ofsNext), &dw, sizeof(DWORD)); return ERROR_NO_MORE_ITEMS; } if (modChain[iCurrentModName].ofsNew == 0) { newModName = (DBModuleName*)_alloca(modChain[iCurrentModName].size); if (ReadSegment(modChain[iCurrentModName].ofsOld, newModName, modChain[iCurrentModName].size) != ERROR_SUCCESS) return ERROR_NO_MORE_ITEMS; if ((modChain[iCurrentModName].ofsNew = WriteSegment(WSOFS_END, newModName, modChain[iCurrentModName].size)) == WS_ERROR) return ERROR_HANDLE_DISK_FULL; // check duplicated modulenames int i, n = 0; for (i = iCurrentModName + 1; i < modChainCount; i++) if (!strcmp(modChain[i].name, modChain[iCurrentModName].name)) { modChain[i].ofsNew = modChain[iCurrentModName].ofsNew; n++; } if (n) { TCHAR szModuleName[257]; MultiByteToWideChar(CP_ACP, 0, modChain[iCurrentModName].name, -1, szModuleName, SIZEOF(szModuleName)); TCHAR *pszModuleName = szModuleName; cb->pfnAddLogMessage(STATUS_WARNING, TranslateT("Module name '%s' is not unique: %d duplicates found"), pszModuleName, n); } if (iCurrentModName == 0) m_dbHeader.ofsFirstModuleName = modChain[iCurrentModName].ofsNew; else if (WriteSegment(ofsLast + offsetof(DBModuleName, ofsNext), &modChain[iCurrentModName].ofsNew, sizeof(DWORD)) == WS_ERROR) return ERROR_HANDLE_DISK_FULL; ofsLast = modChain[iCurrentModName].ofsNew; } iCurrentModName++; break; } return ERROR_SUCCESS; }
DWORD WINAPI Dowmloadfile::DownLoadFileProcess(LPVOID lpVoid) { Dowmloadfile *mparent = (Dowmloadfile *)lpVoid; int retry_time = 0; //int retry_send_ char sendbuffer[1000]; while(download_thread_flag) { switch(download_step) { case SEND_DOWNLOAD_COMMAND: { if(retry_time>10) { mparent->TCP_File_Socket.SetDownloadResults(DOWNLOAD_RESULTS_FAILED); download_step = THREAD_IDLE; continue; } retry_time ++; Download_Info temp_info; temp_info.HEAD_1 = 0x55; temp_info.HEAD_2 = 0xff; temp_info.length = sizeof(Download_Info) - 2; temp_info.commad = DOWNLOAD_FILE; temp_info.product_id = m_product_isp_auto_flash.product_class_id; temp_info.get_newest = 1; temp_info.file_type = 2; temp_info.softversion = 0; temp_info.CRC = 0xff; memset(sendbuffer,0,1000); memcpy(sendbuffer,&temp_info,sizeof(Download_Info)); sendbuffer[sizeof(Download_Info) - 1] = Add_CRC(sendbuffer,sizeof(Download_Info)); mparent->TCP_File_Socket.Send(sendbuffer,sizeof(Download_Info),0); for (int i=0;i<1000;i++) { if(download_step!= SEND_DOWNLOAD_COMMAND) { retry_time = 0; current_package = 1; break; } Sleep(1); } break; } case SEND_GET_MD5_VALUE: { if(retry_time>10) { mparent->TCP_File_Socket.SetDownloadResults(DOWNLOAD_RESULTS_FAILED); download_step = THREAD_IDLE; continue; } retry_time ++; Black_head_struct temp_info; temp_info.HEAD_1 = 0x55; temp_info.HEAD_2 = 0xff; temp_info.length = 4; temp_info.commad = GET_MD5_VALUE; memset(sendbuffer,0,1000); memcpy(sendbuffer,&temp_info,sizeof(temp_info)); sendbuffer[5] = Add_CRC(sendbuffer,5); mparent->TCP_File_Socket.Send(sendbuffer,6,0); for (int i=0;i<1000;i++) { if(download_step!= SEND_GET_MD5_VALUE) { current_package = 1; retry_time = 0; break; } Sleep(1); } } break; case CHECK_MD5_VALUE: { CString ApplicationFolder; CString temp_file_path; CString file_name; GetModuleFileName(NULL, ApplicationFolder.GetBuffer(MAX_PATH), MAX_PATH); PathRemoveFileSpec(ApplicationFolder.GetBuffer(MAX_PATH)); ApplicationFolder.ReleaseBuffer(); temp_file_path = ApplicationFolder + _T("\\Database\\Firmware"); MultiByteToWideChar( CP_ACP, 0, download_filename, (int)strlen((char *)download_filename)+1, file_name.GetBuffer(MAX_PATH), MAX_PATH ); file_name.ReleaseBuffer(); temp_file_path = temp_file_path + _T("\\") + file_name; CFileFind findfirmwarefile; if(!findfirmwarefile.FindFile(temp_file_path)) //没有发现文件 就要服务器传过来; { ::PostMessage(downloadfile_hwnd,WM_DOWNLOADFILE_MESSAGE,DOWNLOAD_NOT_FIND_LOCAL,NULL); download_step = START_SEND_WANT_PACKAGE; } else //发现有一样的了就要比对MD5是否一致; { //CString remote_md5; //CString local_md5; //MultiByteToWideChar( CP_ACP, 0, receive_md5, (int)strlen((char *)receive_md5)+1, remote_md5.GetBuffer(MAX_PATH), MAX_PATH ); //remote_md5.ReleaseBuffer(); char locoal_char_md5[20]; memcpy_s(locoal_char_md5,20, MD5(ifstream( temp_file_path )).digest(),20); int ret_value = memcmp(locoal_char_md5,receive_md5,16); //string local_string_md5 = MD5(ifstream( temp_file_path )).toString(); //local_md5 = local_string_md5.c_str(); if(ret_value == 0) //MD5值一样就不用下载 直接结束; { ::PostMessage(downloadfile_hwnd,WM_DOWNLOADFILE_MESSAGE,DOWNLOAD_LOCAL_EXSIT,NULL); //::PostMessage(downloadfile_hwnd,WM_DOWNLOADFILE_MESSAGE,DOWNLOAD_CLOSE_SOCKET,NULL); download_step = THREAD_IDLE; } else // 不一致就要再次下载; { ::PostMessage(downloadfile_hwnd,WM_DOWNLOADFILE_MESSAGE,DOWNLOAD_NOT_FIND_LOCAL,NULL); download_step = START_SEND_WANT_PACKAGE; } } } break; case START_SEND_WANT_PACKAGE: { if(retry_time>10) { mparent->TCP_File_Socket.SetDownloadResults(DOWNLOAD_RESULTS_FAILED); download_step = THREAD_IDLE; continue; } retry_time ++; File_Package_Struct temp_struct; temp_struct.HEAD_1 = 0x55; temp_struct.HEAD_2 = 0xff; temp_struct.length = sizeof(File_Package_Struct) - 2; temp_struct.commad = ACK_GET_FILE_PAGE; temp_struct.package_index = current_package; temp_struct.total_package = totalpackage; temp_struct.CRC = 0; memset(sendbuffer,0,1000); memcpy(sendbuffer,&temp_struct,sizeof(File_Package_Struct)); sendbuffer[sizeof(File_Package_Struct) - 1] = Add_CRC(sendbuffer,sizeof(File_Package_Struct)); mparent->TCP_File_Socket.Send(sendbuffer,sizeof(File_Package_Struct),0); for (int i=0;i<1000;i++) { if(download_step!= START_SEND_WANT_PACKAGE) { int npersent = (current_package * 100) / totalpackage; retry_time = 0; ::PostMessage(downloadfile_hwnd,WM_DOWNLOADFILE_MESSAGE,DOWNLOAD_PERSENT,npersent); break; } Sleep(1); } break; } case RECEIVE_WANTED_PACKAGE: { download_step = START_SEND_WANT_PACKAGE; break; } case RECEIVE_COMPLET: { CString file_name; MultiByteToWideChar( CP_ACP, 0, download_filename, (int)strlen((char *)download_filename)+1, file_name.GetBuffer(MAX_PATH), MAX_PATH ); file_name.ReleaseBuffer(); CString ApplicationFolder; download_thread_flag = true; GetModuleFileName(NULL, ApplicationFolder.GetBuffer(MAX_PATH), MAX_PATH); PathRemoveFileSpec(ApplicationFolder.GetBuffer(MAX_PATH)); ApplicationFolder.ReleaseBuffer(); Folder_Path = ApplicationFolder + _T("\\Database\\Firmware"); Folder_Path = Folder_Path + _T("\\") + file_name; HEX_BIN_FILE_PATH = Folder_Path; HANDLE hFile; hFile=CreateFile(Folder_Path,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); DWORD dWrites; WriteFile(hFile,receivefile_buffer,total_file_length,&dWrites,NULL); CloseHandle(hFile); if(receivefile_buffer) { delete receivefile_buffer; receivefile_buffer = NULL; total_file_length = 0; //开辟的内存空间大小; } download_step = THREAD_IDLE; char locoal_char_md5[20]; memcpy_s(locoal_char_md5,20, MD5(ifstream( HEX_BIN_FILE_PATH )).digest(),20); int ret_value = memcmp(locoal_char_md5,receive_md5,16); if(ret_value != 0) { ::PostMessage(downloadfile_hwnd,WM_DOWNLOADFILE_MESSAGE,RETURN_ERROR,DOWNLOAD_MD5_FAILED); mparent->TCP_File_Socket.SetDownloadResults(DOWNLOAD_RESULTS_FAILED); } else { ::PostMessage(downloadfile_hwnd,WM_DOWNLOADFILE_MESSAGE,RETURN_ERROR,DOWNLOAD_MD5_CHECK_PASS); mparent->TCP_File_Socket.SetDownloadResults(DOWNLOAD_RESULTS_PASS); } ::PostMessage(downloadfile_hwnd,WM_DOWNLOADFILE_MESSAGE,DOWNLOAD_FINISHED,NULL); break; } case THREAD_IDLE: { //mparent->TCP_File_Socket.ShutDown(); //mparent->TCP_File_Socket.Close(); ::PostMessage(downloadfile_hwnd,WM_DOWNLOADFILE_MESSAGE,DOWNLOAD_CLOSE_SOCKET,NULL); Downloadfile_Thread = NULL; retry_time = 0; Sleep(1000); return 0; } break; } Sleep(1); } return 0; }
// POST request to URL void WinHttpIO::post(HttpReq* req, const char* data, unsigned len) { LOG_debug << "POST target URL: " << req->posturl << " chunked: " << req->chunked; if (req->binary) { LOG_debug << "[sending " << (data ? len : req->out->size()) << " bytes of raw data]"; } else { LOG_debug << "Sending: " << *req->out; } WinHttpContext* httpctx; WCHAR szURL[8192]; WCHAR szHost[256]; URL_COMPONENTS urlComp = { sizeof urlComp }; urlComp.lpszHostName = szHost; urlComp.dwHostNameLength = sizeof szHost / sizeof *szHost; urlComp.dwUrlPathLength = (DWORD)-1; urlComp.dwSchemeLength = (DWORD)-1; httpctx = new WinHttpContext; httpctx->httpio = this; httpctx->req = req; httpctx->gzip = false; req->httpiohandle = (void*)httpctx; if (MultiByteToWideChar(CP_UTF8, 0, req->posturl.c_str(), -1, szURL, sizeof szURL / sizeof *szURL) && WinHttpCrackUrl(szURL, 0, 0, &urlComp)) { if ((httpctx->hConnect = WinHttpConnect(hSession, szHost, urlComp.nPort, 0))) { httpctx->hRequest = WinHttpOpenRequest(httpctx->hConnect, L"POST", urlComp.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, (urlComp.nScheme == INTERNET_SCHEME_HTTPS) ? WINHTTP_FLAG_SECURE : 0); if (httpctx->hRequest) { if (proxyUsername.size()) { LOG_verbose << "Setting proxy credentials"; WinHttpSetCredentials(httpctx->hRequest, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC, (LPWSTR)proxyUsername.data(), (LPWSTR)proxyPassword.data(), NULL); } WinHttpSetTimeouts(httpctx->hRequest, 58000, 58000, 0, 0); WinHttpSetStatusCallback(httpctx->hRequest, asynccallback, WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE | WINHTTP_CALLBACK_FLAG_READ_COMPLETE | WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE | WINHTTP_CALLBACK_FLAG_REQUEST_ERROR | WINHTTP_CALLBACK_FLAG_SECURE_FAILURE | WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE | WINHTTP_CALLBACK_FLAG_SEND_REQUEST | WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE | WINHTTP_CALLBACK_FLAG_HANDLES, 0); LPCWSTR pwszHeaders = req->type == REQ_JSON || !req->buf ? L"Content-Type: application/json\r\nAccept-Encoding: gzip" : L"Content-Type: application/octet-stream"; // data is sent in HTTP_POST_CHUNK_SIZE instalments to ensure // semi-smooth UI progress info if (req->chunkedout.size()) { req->outbuf.append(req->chunkedout); req->chunkedout.clear(); } req->chunked = 0; httpctx->postlen = data ? len : req->out->size(); httpctx->postdata = data ? data : req->out->data(); if (urlComp.nPort == 80) { LOG_verbose << "HTTP connection"; // HTTP connection: send a chunk of data immediately httpctx->postpos = (httpctx->postlen < HTTP_POST_CHUNK_SIZE) ? httpctx->postlen : HTTP_POST_CHUNK_SIZE; } else { LOG_verbose << "HTTPS connection"; // HTTPS connection: ignore certificate errors, send no data yet DWORD flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA; WinHttpSetOption(httpctx->hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &flags, sizeof flags); httpctx->postpos = 0; } if (WinHttpSendRequest(httpctx->hRequest, pwszHeaders, wcslen(pwszHeaders), (LPVOID)httpctx->postdata, httpctx->postpos, httpctx->postlen, (DWORD_PTR)httpctx)) { LOG_verbose << "Request sent"; req->status = REQ_INFLIGHT; return; } LOG_err << "Error sending request: " << req->posturl << " Code: " << GetLastError(); } else { LOG_err << "Error opening request: " << req->posturl << " Code: " << GetLastError(); } } else { LOG_err << "Error connecting to " << req->posturl << " Code: " << GetLastError(); httpctx->hRequest = NULL; } } else { LOG_err << "Error parsing POST URL: " << req->posturl << " Code: " << GetLastError(); httpctx->hRequest = NULL; httpctx->hConnect = NULL; } LOG_err << "Request failed"; req->status = REQ_FAILURE; }
static void textconv_cpmaps_init(void) { if(textconv_cpmaps_ok) return; textconv_cpmaps_ok=1; textconv_cpsource_map=textconv_select_mapping_by_name(textconv_codepage_sourcename); textconv_cptarget_map=textconv_select_mapping_by_name(textconv_codepage_targetname); #ifdef MPXPLAY_UTF8 if(!textconv_cpsource_map){ textconv_cpsource_map=textconv_select_mapping_by_id(GetACP()); if(!textconv_cpsource_map){ mpxp_uint16_t *mug; char asciistr[260]; mapping_unicode_generated=mug=(mpxp_uint16_t*)calloc(1,(256-32+8)*sizeof(mpxp_uint16_t)); if(mug){ unsigned int i; for(i=32;i<256;i++) asciistr[i]=i; asciistr[256]=0; for(i=32;i<256;){ unsigned int len=MultiByteToWideChar(CP_ACP,0,&asciistr[i],-1,mug,256+4-i); //fprintf(stdout,"%d len:%d ",i,len); if(len){ mug+=len; i+=len; }else{ *mug++=(mpxp_uint16_t)('_'); i++; } } //mug=mapping_unicode_generated; //for(i=32;i<256;i++,mug++) // fprintf(stdout,"| %3d %c %4.4X ",i,i,mug[0]); textconv_cpmap_generated.map=mapping_unicode_generated; textconv_cpmap_generated.begin=32; textconv_cpsource_map=&textconv_cpmap_generated; }else textconv_cpsource_map=&cp_maps[0]; } } if(textconv_cptarget_map) textscreen_console_codepage=textconv_cptarget_map->cp_id_num; #else if(!textconv_cpsource_map){ if(funcbit_test(id3textconv,ID3TEXTCONV_GET_WINCP)) textconv_cpsource_map=textconv_select_mapping_by_id(GetACP()); if(!textconv_cpsource_map) textconv_cpsource_map=&cp_maps[0]; } if(!textconv_cptarget_map){ if(funcbit_test(id3textconv,ID3TEXTCONV_GET_WINCP)) textconv_cptarget_map=textconv_select_mapping_by_id(GetOEMCP()); if(!textconv_cptarget_map) textconv_cptarget_map=&cp_maps[1]; } textscreen_console_codepage=textconv_cptarget_map->cp_id_num; if(funcbit_test(id3textconv,ID3TEXTCONV_CODEPAGE)) // at -8 textconv_cptarget_map=NULL; // WinChars/DosChars are used else if(textconv_cptarget_map==textconv_cpsource_map) textconv_cptarget_map=NULL; #endif }
WCHAR *WDL_UTF8ToWC(const char *buf, BOOL doublenull, int minsize, DWORD *sizeout) { if (doublenull) { int sz=1; const char *p = (const char *)buf; WCHAR *pout,*ret; while (*p) { int a=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,p,-1,NULL,0); int sp=strlen(p)+1; if (a < sp)a=sp; // in case it needs to be ansi mapped sz+=a; p+=sp; } if (sz < minsize) sz=minsize; pout = (WCHAR *) malloc(sizeof(WCHAR)*(sz+4)); ret=pout; p = (const char *)buf; while (*p) { int a; *pout=0; a = MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,p,-1,pout,sz-(pout-ret)); if (!a) { pout[0]=0; a=MultiByteToWideChar(CP_ACP,MB_ERR_INVALID_CHARS,p,-1,pout,sz-(pout-ret)); } pout += a; p+=strlen(p)+1; } *pout=0; pout[1]=0; if (sizeout) *sizeout=sz; return ret; } else { int srclen = strlen(buf)+1; int size=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,buf,srclen,NULL,0); if (size < srclen)size=srclen; // for ansi code page if (size<minsize)size=minsize; { WCHAR *outbuf = (WCHAR *)malloc(sizeof(WCHAR)*(size+128)); int a; *outbuf=0; if (srclen>1) { a=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,buf,srclen,outbuf, size); if (!a) { outbuf[0]=0; a=MultiByteToWideChar(CP_ACP,MB_ERR_INVALID_CHARS,buf,srclen,outbuf,size); } } if (sizeout) *sizeout = size; return outbuf; } } }
int TestFileFindNextFile(int argc, char* argv[]) { char* str; int length; BOOL status; HANDLE hFind; LPTSTR BasePath; WIN32_FIND_DATA FindData; TCHAR FilePath[PATHCCH_MAX_CCH]; str = argv[1]; #ifdef UNICODE length = MultiByteToWideChar(CP_UTF8, 0, str, strlen(str), NULL, 0); BasePath = (WCHAR*) calloc((length + 1), sizeof(WCHAR)); if (!BasePath) { _tprintf(_T("Unable to allocate memory")); return -1; } MultiByteToWideChar(CP_UTF8, 0, str, length, (LPWSTR) BasePath, length * sizeof(WCHAR)); BasePath[length] = 0; #else BasePath = _strdup(str); if (!BasePath) { printf("Unable to allocate memory"); return -1; } length = strlen(BasePath); #endif /* Simple filter matching all files inside current directory */ CopyMemory(FilePath, BasePath, length * sizeof(TCHAR)); FilePath[length] = 0; PathCchConvertStyle(BasePath, length, PATH_STYLE_WINDOWS); NativePathCchAppend(FilePath, PATHCCH_MAX_CCH, _T("TestDirectory2")); NativePathCchAppend(FilePath, PATHCCH_MAX_CCH, _T("TestDirectory2File*")); _tprintf(_T("Finding file: %s\n"), FilePath); hFind = FindFirstFile(FilePath, &FindData); if (hFind == INVALID_HANDLE_VALUE) { _tprintf(_T("FindFirstFile failure: %s\n"), FilePath); return -1; } _tprintf(_T("FindFirstFile: %s"), FindData.cFileName); /** * The current implementation does not enforce a particular order */ if ((_tcscmp(FindData.cFileName, testDirectory2File1) != 0) && (_tcscmp(FindData.cFileName, testDirectory2File2) != 0)) { _tprintf(_T("FindFirstFile failure: Expected: %s, Actual: %s\n"), testDirectory2File1, FindData.cFileName); return -1; } status = FindNextFile(hFind, &FindData); if (!status) { _tprintf(_T("FindNextFile failure: Expected: TRUE, Actual: %")_T(PRId32)_T("\n"), status); return -1; } if ((_tcscmp(FindData.cFileName, testDirectory2File1) != 0) && (_tcscmp(FindData.cFileName, testDirectory2File2) != 0)) { _tprintf(_T("FindNextFile failure: Expected: %s, Actual: %s\n"), testDirectory2File2, FindData.cFileName); return -1; } status = FindNextFile(hFind, &FindData); if (status) { _tprintf(_T("FindNextFile failure: Expected: FALSE, Actual: %")_T(PRId32)_T("\n"), status); return -1; } FindClose(hFind); return 0; }
/* {{{ mysql_local_infile_init */ static int mysql_local_infile_init(void **ptr, const char *filename, void *userdata) { MYSQL_INFILE_INFO *info; int CodePage= -1; #ifdef _WIN32 MYSQL *mysql= (MYSQL *)userdata; wchar_t *w_filename= NULL; int Length; #endif DBUG_ENTER("mysql_local_infile_init"); info = (MYSQL_INFILE_INFO *)my_malloc(sizeof(MYSQL_INFILE_INFO), MYF(MY_ZEROFILL)); if (!info) { DBUG_RETURN(1); } *ptr = info; info->filename = filename; #ifdef _WIN32 if (mysql) CodePage= madb_get_windows_cp(mysql->charset->csname); #endif if (CodePage == -1) { #ifdef _WIN32 info->fd= sopen(info->filename, _O_RDONLY | _O_BINARY, _SH_DENYNO , _S_IREAD | _S_IWRITE); #else info->fd = open(info->filename, O_RDONLY | O_BINARY, my_umask); #endif my_errno= errno; } #ifdef _WIN32 else { if ((Length= MultiByteToWideChar(CodePage, 0, info->filename, (int)strlen(info->filename), NULL, 0))) { if (!(w_filename= (wchar_t *)my_malloc((Length + 1) * sizeof(wchar_t), MYF(MY_ZEROFILL)))) { info->error_no= CR_OUT_OF_MEMORY; my_snprintf((char *)info->error_msg, sizeof(info->error_msg), ER(CR_OUT_OF_MEMORY)); DBUG_RETURN(1); } Length= MultiByteToWideChar(CodePage, 0, info->filename, (int)strlen(info->filename), w_filename, (int)Length); } if (Length == 0) { my_free(w_filename); info->error_no= CR_UNKNOWN_ERROR; my_snprintf((char *)info->error_msg, sizeof(info->error_msg), "Character conversion error: %d", GetLastError()); DBUG_RETURN(1); } info->fd= _wsopen(w_filename, _O_RDONLY | _O_BINARY, _SH_DENYNO , _S_IREAD | _S_IWRITE); my_errno= errno; my_free(w_filename); } #endif if (info->fd < 0) { info->error_no = my_errno; my_snprintf((char *)info->error_msg, sizeof(info->error_msg), EE(EE_FILENOTFOUND), filename, info->error_no); DBUG_RETURN(1); } DBUG_RETURN(0); }