HDC W32HandleDibDrv (PVPVOID vpbmi16) { HDC hdcMem = NULL; HBITMAP hbm = NULL; PVOID pvBits, pvIntelBits; STACKBMI32 bmi32; LPBITMAPINFO lpbmi32; DWORD dwClrUsed,nSize,nAlignmentSpace; PBITMAPINFOHEADER16 pbmi16; INT nbmiSize,nBytesWritten; HANDLE hfile=NULL,hsec=NULL; ULONG RetVal,OriginalSelLimit,SelectorLimit,OriginalFlags; PARM16 Parm16; CHAR pchTempFile[MAX_PATH]; BOOL bRet = FALSE; PVPVOID vpBase16 = (PVPVOID) ((ULONG) vpbmi16 & 0xffff0000); if ((hdcMem = W32FindAndLockDibInfo((USHORT)HIWORD(vpbmi16))) != (HDC)NULL) { return hdcMem; } // First create a memory device context compatible to // the app's current screen if ((hdcMem = CreateCompatibleDC (NULL)) == NULL) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv CreateCompatibleDC failed\n")); return NULL; } // Copy bmi16 to bmi32. DIB.DRV only supports DIB_RGB_COLORS lpbmi32 = CopyBMI16ToBMI32( vpbmi16, (LPBITMAPINFO)&bmi32, (WORD) DIB_RGB_COLORS); // this hack for Director 4.0 does essentially what WFW does // if this bitmap is 0 sized, just return an hDC for something simple if(bmi32.bmiHeader.biSizeImage == 0 && (CURRENTPTD()->dwWOWCompatFlagsEx & WOWCFEX_DIBDRVIMAGESIZEZERO)) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv:Zero biSizeImage, returning memory DC!\n")); return hdcMem; } try { // Copy the wholething into a temp file. First get a temp file name if ((nSize = GetTempPath (MAX_PATH, pchTempFile)) == 0 || nSize >= MAX_PATH) goto hdd_err; if (GetTempFileName (pchTempFile, "DIB", 0, pchTempFile) == 0) goto hdd_err; if ((hfile = CreateFile (pchTempFile, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, (FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE), NULL)) == INVALID_HANDLE_VALUE) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv CreateFile failed\n")); goto hdd_err; } // call back to get the size of the global object // associated with vpbmi16 Parm16.WndProc.wParam = HIWORD(vpbmi16); CallBack16(RET_GETDIBSIZE, &Parm16, 0, (PVPVOID)&SelectorLimit); Parm16.WndProc.wParam = HIWORD(vpbmi16); if (SelectorLimit == 0xffffffff || SelectorLimit == 0) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv Invalid Selector %x\n",HIWORD(vpbmi16))); goto hdd_err; } SelectorLimit++; OriginalSelLimit = SelectorLimit; CallBack16(RET_GETDIBFLAGS, &Parm16, 0, (PVPVOID)&OriginalFlags); if (OriginalFlags == 0x4) { //GA_DGROUP LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv GA_DGROUP Not Handled\n")); goto hdd_err; } GETVDMPTR(vpBase16, SelectorLimit, pbmi16); nbmiSize = GetBMI16Size(vpbmi16, (WORD) DIB_RGB_COLORS, &dwClrUsed); // Under NT CreateDIBSection will fail if the offset to the bits // is not dword aligned. So we may have to add some space at the top // of the section to get the offset correctly aligned. nAlignmentSpace = (nbmiSize+LOWORD(vpbmi16)) % 4; if (nAlignmentSpace) { if (WriteFile (hfile, pbmi16, nAlignmentSpace, &nBytesWritten, NULL) == FALSE || nBytesWritten != (INT) nAlignmentSpace) goto hdd_err; } // // detect a clinical case of bitedit screwing around dib.drv // // code below is using dib macros declared in wdib.h // namely: // DibNumColors - yields max number of colors in dib // DibColors - yields pointer to a dib color table // // Function W32CheckDibColorIndices checks to see if DIB color // table looks like a number (defined usually by biClrImportant) // of WORD indices in a sequential order (0, 1, 2, ...) // if this is the case, app is trying to use undocumented feature // of DIB.DRV that turns color matching off in this case. // Since we cannot enforce that rule, we approximate it by filling // color table by a number of known (and always same) entries // When blitting occurs, no color matching will be performed (when // both target and destination are of this very nature). // For no reason at all we fill color table with vga colors. // Sequential indices could have worked just as well. // // Modifications are made to memory pointed to by lpbmi32 if (W32CheckDibColorIndices((LPBITMAPINFOHEADER)lpbmi32)) { INT i, nColors; LPBITMAPINFOHEADER lpbmi = (LPBITMAPINFOHEADER)lpbmi32; LPRGBQUAD lprgbq = (LPRGBQUAD)DibColors(lpbmi); nColors = DibNumColors(lpbmi); lpbmi->biClrImportant = nColors; switch (lpbmi->biBitCount) { case 1: lprgbq[0] = rgbVGA[0]; lprgbq[1] = rgbVGA[0x0f]; break; case 4: RtlCopyMemory(lprgbq, rgbVGA, sizeof(rgbVGA)); break; case 8: RtlCopyMemory(lprgbq, rgbVGA, 8*sizeof(RGBQUAD)); RtlCopyMemory(lprgbq+248, rgbVGA+8, 8*sizeof(RGBQUAD)); RtlCopyMemory(lprgbq+8, rgb4, 2*sizeof(RGBQUAD)); RtlCopyMemory(lprgbq+246, rgb4+2, 2*sizeof(RGBQUAD)); for (i = 10; i < 246; ++i) { lprgbq[i].rgbBlue = i; lprgbq[i].rgbGreen= 0; lprgbq[i].rgbRed = 0; lprgbq[i].rgbReserved = 0; } break; default: // this should never happen break; } } if (WriteFile (hfile, pbmi16, SelectorLimit, &nBytesWritten, NULL) == FALSE || nBytesWritten != (INT) SelectorLimit) goto hdd_err; if (SelectorLimit < 64*1024) { if (SetFilePointer (hfile, 64*1024+nAlignmentSpace, NULL, FILE_BEGIN) == -1) goto hdd_err; if (SetEndOfFile (hfile) == FALSE) goto hdd_err; SelectorLimit = 64*1024; } if ((hsec = CreateFileMapping (hfile, NULL, PAGE_READWRITE | SEC_COMMIT, 0, SelectorLimit+nAlignmentSpace, NULL)) == NULL) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv CreateFileMapping Failed\n")); goto hdd_err; } // Now create the DIB section if ((hbm = CreateDIBSection (hdcMem, lpbmi32, DIB_RGB_COLORS, &pvBits, hsec, nAlignmentSpace + LOWORD(vpbmi16) + nbmiSize )) == NULL) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv CreateDibSection Failed\n")); goto hdd_err; } FREEVDMPTR(pbmi16); if((pvBits = MapViewOfFile(hsec, FILE_MAP_WRITE, 0, 0, SelectorLimit+nAlignmentSpace)) == NULL) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv MapViewOfFile Failed\n")); goto hdd_err; } pvBits = (PVOID) ((ULONG)pvBits + nAlignmentSpace); SelectObject (hdcMem, hbm); GdiSetBatchLimit(1); #ifndef i386 if (!NT_SUCCESS(VdmAddVirtualMemory((ULONG)pvBits, (ULONG)SelectorLimit, (PULONG)&pvIntelBits))) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv VdmAddVirtualMemory failed\n")); goto hdd_err; } // On risc platforms, the intel base + the intel linear address // of the DIB section is not equal to the DIB section's process // address. This is because of the VdmAddVirtualMemory call // above. So here we zap the correct address into the flataddress // array. if (!VdmAddDescriptorMapping(HIWORD(vpbmi16), (USHORT) ((SelectorLimit+65535)/65536), (ULONG) pvIntelBits, (ULONG) pvBits)) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv VdmAddDescriptorMapping failed\n")); goto hdd_err; } #else pvIntelBits = pvBits; #endif // Finally set the selectors to the new DIB Parm16.WndProc.wParam = HIWORD(vpbmi16); Parm16.WndProc.lParam = (LONG)pvIntelBits; Parm16.WndProc.wMsg = 0x10; // GA_NOCOMPACT Parm16.WndProc.hwnd = 1; // set so it's not randomly 0 CallBack16(RET_SETDIBSEL, &Parm16, 0, (PVPVOID)&RetVal); if (!RetVal) { LOGDEBUG(LOG_ALWAYS,("\nWOW::W32HandleDibDrv Callback set_sel_for_dib failed\n")); goto hdd_err; } // Store all the relevant information so that DeleteDC could // free all the resources later. if (W32AddDibInfo(hdcMem, hfile, hsec, nAlignmentSpace, pvBits, pvIntelBits, hbm, OriginalSelLimit, (USHORT)OriginalFlags, (USHORT)((HIWORD(vpbmi16)))) == FALSE) goto hdd_err; // Finally spit out the dump for debugging LOGDEBUG(6,("\t\tWOW::W32HandleDibDrv hdc=%04x nAlignment=%04x\n\t\tNewDib=%x OldDib=%04x:%04x DibSize=%x DibFlags=%x\n",hdcMem,nAlignmentSpace,pvBits,HIWORD(vpbmi16),LOWORD(vpbmi16),OriginalSelLimit,(USHORT)OriginalFlags)); bRet = TRUE; hdd_err:; } finally { if (!bRet) { if (hdcMem) { DeleteDC (hdcMem); hdcMem = NULL; } if (hfile) CloseHandle (hfile); if (hsec) CloseHandle (hsec); if (hbm) CloseHandle (hbm); } } return hdcMem; }
// Copy the pagefile to the current place in the output file. void WinPmem::write_page_file() { unsigned __int64 pagefile_offset = out_offset; TCHAR path[MAX_PATH + 1]; TCHAR filename[MAX_PATH + 1]; if (!GetTempPath(MAX_PATH, path)) { dprintf("[WINPMEM] Unable to determine temporary path."); goto error; } // filename is now the random path. GetTempFileName(path, L"fls", 0, filename); dprintf("[WINPMEM] Extracting fcat to %s", filename); if (extract_file_(WINPMEM_FCAT_EXECUTABLE, filename) < 0) { goto error; }; SECURITY_ATTRIBUTES saAttr; HANDLE stdout_rd = NULL; HANDLE stdout_wr = NULL; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if (!CreatePipe(&stdout_rd, &stdout_wr, &saAttr, 0)) { dprintf("[WINPMEM] StdoutRd CreatePipe"); goto error; }; // Ensure the read handle to the pipe for STDOUT is not inherited. SetHandleInformation(stdout_rd, HANDLE_FLAG_INHERIT, 0); WCHAR command_line[1000]; swprintf(command_line, 1000, L"%s %s \\\\.\\%s", filename, &pagefile_path_[3], pagefile_path_); CreateChildProcess(command_line, stdout_wr); dprintf("[WINPMEM] Preparing to read pagefile."); while (1) { DWORD bytes_read = buffer_size_; DWORD bytes_written = 0; if (!ReadFile(stdout_rd, buffer_, bytes_read, &bytes_read, NULL)) { break; }; if (!WriteFile(out_fd_, buffer_, bytes_read, &bytes_written, NULL) || bytes_written != bytes_read) { dprintf("[WINPMEM] Failed to write image file"); goto error; }; out_offset += bytes_written; }; error: // Write another metadata header. { char metadata[1000]; _snprintf_s(metadata, sizeof(metadata), _TRUNCATE, "# PMEM\n" "---\n" "PreviousHeader: %#llx\n" "PagefileOffset: %#llx\n" "PagefileSize: %#llx\n" "...\n", last_header_offset_, pagefile_offset, out_offset - pagefile_offset ); DWORD metadata_len = (DWORD)strlen(metadata); DWORD bytes_written = 0; if (!WriteFile(out_fd_, metadata, metadata_len, &bytes_written, NULL) || bytes_written != metadata_len) { dprintf("[WINPMEM] Failed to write image file"); }; out_offset += bytes_written; }; DeleteFile(filename); return; };
void ExecScript(int log) { char szRet[128] = ""; char *pExec; int nComSpecSize; char meDLLPath[MAX_PATH]; char *p; char *executor; char *g_exec; unsigned int g_to; nComSpecSize = GetModuleFileName(g_hInst, meDLLPath, MAX_PATH) + 2; // 2 chars for quotes p = meDLLPath + nComSpecSize - 2; // point p at null char of meDLLPath g_exec = (char *)GlobalAlloc(GPTR, sizeof(char)*g_stringsize+nComSpecSize+2); // 1 for space, 1 for null *g_exec = '"'; executor = g_exec + 1; do { if (*p == '\\') break; p = CharPrev(meDLLPath, p); } while (p > meDLLPath); if (p == meDLLPath) { // bad path lstrcpy(szRet, "error"); goto done; } *p = 0; GetTempFileName(meDLLPath, "ns", 0, executor); *p = '\\'; if (CopyFile(meDLLPath, executor, FALSE)) { HANDLE hFile, hMapping; LPBYTE pMapView; PIMAGE_NT_HEADERS pNTHeaders; hFile = CreateFile(executor, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING,0, 0); hMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL); pMapView = MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0); if (pMapView) { pNTHeaders = (PIMAGE_NT_HEADERS)(pMapView + ((PIMAGE_DOS_HEADER)pMapView)->e_lfanew); pNTHeaders->FileHeader.Characteristics = IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_LOCAL_SYMS_STRIPPED | IMAGE_FILE_LINE_NUMS_STRIPPED | IMAGE_FILE_EXECUTABLE_IMAGE; pNTHeaders->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; pNTHeaders->OptionalHeader.AddressOfEntryPoint = (DWORD)WinMain - (DWORD)g_hInst; UnmapViewOfFile(pMapView); } CloseHandle(hMapping); CloseHandle(hFile); } lstrcat(g_exec, "\""); g_to = 0; // default is no timeout g_hwndList = FindWindowEx(FindWindowEx(g_hwndParent,NULL,"#32770",NULL),NULL,"SysListView32",NULL); // add space pExec = g_exec + lstrlen(g_exec); *pExec = ' '; pExec++; popstring(pExec); if (my_strstr(pExec, "/TIMEOUT=")) { char *szTimeout = pExec + 9; g_to = my_atoi(szTimeout); popstring(pExec); } if (!g_exec[0]) { lstrcpy(szRet, "error"); goto done; } { STARTUPINFO si={sizeof(si),}; SECURITY_ATTRIBUTES sa={sizeof(sa),}; SECURITY_DESCRIPTOR sd={0,}; PROCESS_INFORMATION pi={0,}; OSVERSIONINFO osv={sizeof(osv)}; HANDLE newstdout=0,read_stdout=0; HANDLE newstdin=0,read_stdin=0; DWORD dwRead = 1; DWORD dwExit = !STILL_ACTIVE; DWORD dwLastOutput; static char szBuf[1024]; HGLOBAL hUnusedBuf; char *szUnusedBuf = 0; if (log) { hUnusedBuf = GlobalAlloc(GHND, log & 2 ? g_stringsize : sizeof(szBuf)*4); if (!hUnusedBuf) { lstrcpy(szRet, "error"); goto done; } szUnusedBuf = (char *)GlobalLock(hUnusedBuf); } GetVersionEx(&osv); if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) { InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd,true,NULL,false); sa.lpSecurityDescriptor = &sd; } else sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = true; if (!CreatePipe(&read_stdout,&newstdout,&sa,0)) { lstrcpy(szRet, "error"); goto done; } if (!CreatePipe(&read_stdin,&newstdin,&sa,0)) { lstrcpy(szRet, "error"); goto done; } GetStartupInfo(&si); si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdInput = newstdin; si.hStdOutput = newstdout; si.hStdError = newstdout; if (!CreateProcess(NULL,g_exec,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)) { lstrcpy(szRet, "error"); goto done; } dwLastOutput = GetTickCount(); while (dwExit == STILL_ACTIVE || dwRead) { PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL); if (dwRead) { dwLastOutput = GetTickCount(); ReadFile(read_stdout, szBuf, sizeof(szBuf)-1, &dwRead, NULL); szBuf[dwRead] = 0; if (log) { char *p, *p2; SIZE_T iReqLen = lstrlen(szBuf) + lstrlen(szUnusedBuf); if (GlobalSize(hUnusedBuf) < iReqLen && (iReqLen < g_stringsize || !(log & 2))) { GlobalUnlock(hUnusedBuf); hUnusedBuf = GlobalReAlloc(hUnusedBuf, iReqLen+sizeof(szBuf), GHND); if (!hUnusedBuf) { lstrcpy(szRet, "error"); break; } szUnusedBuf = (char *)GlobalLock(hUnusedBuf); } p = szUnusedBuf; // get the old left overs if (iReqLen < g_stringsize || !(log & 2)) lstrcat(p, szBuf); else { lstrcpyn(p + lstrlen(p), szBuf, g_stringsize - lstrlen(p)); } if (!(log & 2)) { while (p = my_strstr(p, "\t")) { if ((int)(p - szUnusedBuf) > (int)(GlobalSize(hUnusedBuf) - TAB_REPLACE_SIZE - 1)) { *p++ = ' '; } else { int len = lstrlen(p); char *c_out=(char*)p+TAB_REPLACE_SIZE+len; char *c_in=(char *)p+len; while (len-- > 0) { *c_out--=*c_in--; } lstrcpy(p, TAB_REPLACE); p += TAB_REPLACE_SIZE; *p = ' '; } } p = szUnusedBuf; // get the old left overs for (p2 = p; *p2;) { if (*p2 == '\r') { *p2++ = 0; continue; } if (*p2 == '\n') { *p2 = 0; while (!*p && p != p2) p++; LogMessage(p); p = ++p2; continue; } p2 = CharNext(p2); } // If data was taken out from the unused buffer, move p contents to the start of szUnusedBuf if (p != szUnusedBuf) { char *p2 = szUnusedBuf; while (*p) *p2++ = *p++; *p2 = 0; } } } } else { if (g_to && GetTickCount() > dwLastOutput+g_to) { TerminateProcess(pi.hProcess, -1); lstrcpy(szRet, "timeout"); } else Sleep(LOOPTIMEOUT); } GetExitCodeProcess(pi.hProcess, &dwExit); if (dwExit != STILL_ACTIVE) { PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL); } } done: if (log & 2) pushstring(szUnusedBuf); if (log & 1 && *szUnusedBuf) LogMessage(szUnusedBuf); if ( dwExit == STATUS_ILLEGAL_INSTRUCTION ) lstrcpy(szRet, "error"); if (!szRet[0]) wsprintf(szRet,"%d",dwExit); pushstring(szRet); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(newstdout); CloseHandle(read_stdout); CloseHandle(newstdin); CloseHandle(read_stdin); *(pExec-2) = '\0'; // skip space and quote DeleteFile(executor); GlobalFree(g_exec); if (log) { GlobalUnlock(hUnusedBuf); GlobalFree(hUnusedBuf); } } }
int TclpRenameFile( char *src, /* Pathname of file or dir to be renamed. */ char *dst) /* New pathname for file or directory. */ { DWORD srcAttr, dstAttr; /* * Would throw an exception under NT if one of the arguments is a * char block device. */ try { if (MoveFile(src, dst) != FALSE) { return TCL_OK; } } except (-1) {} TclWinConvertError(GetLastError()); srcAttr = GetFileAttributes(src); dstAttr = GetFileAttributes(dst); if (srcAttr == (DWORD) -1) { srcAttr = 0; } if (dstAttr == (DWORD) -1) { dstAttr = 0; } if (errno == EBADF) { errno = EACCES; return TCL_ERROR; } if ((errno == EACCES) && (TclWinGetPlatformId() == VER_PLATFORM_WIN32s)) { if ((srcAttr != 0) && (dstAttr != 0)) { /* * Win32s reports trying to overwrite an existing file or directory * as EACCES. */ errno = EEXIST; } } if (errno == EACCES) { decode: if (srcAttr & FILE_ATTRIBUTE_DIRECTORY) { char srcPath[MAX_PATH], dstPath[MAX_PATH]; int srcArgc, dstArgc; char **srcArgv, **dstArgv; char *srcRest, *dstRest; int size; size = GetFullPathName(src, sizeof(srcPath), srcPath, &srcRest); if ((size == 0) || (size > sizeof(srcPath))) { return TCL_ERROR; } size = GetFullPathName(dst, sizeof(dstPath), dstPath, &dstRest); if ((size == 0) || (size > sizeof(dstPath))) { return TCL_ERROR; } if (srcRest == NULL) { srcRest = srcPath + strlen(srcPath); } if (strnicmp(srcPath, dstPath, srcRest - srcPath) == 0) { /* * Trying to move a directory into itself. */ errno = EINVAL; return TCL_ERROR; } Tcl_SplitPath(srcPath, &srcArgc, &srcArgv); Tcl_SplitPath(dstPath, &dstArgc, &dstArgv); if (srcArgc == 1) { /* * They are trying to move a root directory. Whether * or not it is across filesystems, this cannot be * done. */ errno = EINVAL; } else if ((srcArgc > 0) && (dstArgc > 0) && (stricmp(srcArgv[0], dstArgv[0]) != 0)) { /* * If src is a directory and dst filesystem != src * filesystem, errno should be EXDEV. It is very * important to get this behavior, so that the caller * can respond to a cross filesystem rename by * simulating it with copy and delete. The MoveFile * system call already handles the case of moving a * file between filesystems. */ errno = EXDEV; } ckfree((char *) srcArgv); ckfree((char *) dstArgv); } /* * Other types of access failure is that dst is a read-only * filesystem, that an open file referred to src or dest, or that * src or dest specified the current working directory on the * current filesystem. EACCES is returned for those cases. */ } else if (errno == EEXIST) { /* * Reports EEXIST any time the target already exists. If it makes * sense, remove the old file and try renaming again. */ if (srcAttr & FILE_ATTRIBUTE_DIRECTORY) { if (dstAttr & FILE_ATTRIBUTE_DIRECTORY) { /* * Overwrite empty dst directory with src directory. The * following call will remove an empty directory. If it * fails, it's because it wasn't empty. */ if (TclpRemoveDirectory(dst, 0, NULL) == TCL_OK) { /* * Now that that empty directory is gone, we can try * renaming again. If that fails, we'll put this empty * directory back, for completeness. */ if (MoveFile(src, dst) != FALSE) { return TCL_OK; } /* * Some new error has occurred. Don't know what it * could be, but report this one. */ TclWinConvertError(GetLastError()); CreateDirectory(dst, NULL); SetFileAttributes(dst, dstAttr); if (errno == EACCES) { /* * Decode the EACCES to a more meaningful error. */ goto decode; } } } else { /* (dstAttr & FILE_ATTRIBUTE_DIRECTORY) == 0 */ errno = ENOTDIR; } } else { /* (srcAttr & FILE_ATTRIBUTE_DIRECTORY) == 0 */ if (dstAttr & FILE_ATTRIBUTE_DIRECTORY) { errno = EISDIR; } else { /* * Overwrite existing file by: * * 1. Rename existing file to temp name. * 2. Rename old file to new name. * 3. If success, delete temp file. If failure, * put temp file back to old name. */ char tempName[MAX_PATH]; int result, size; char *rest; size = GetFullPathName(dst, sizeof(tempName), tempName, &rest); if ((size == 0) || (size > sizeof(tempName)) || (rest == NULL)) { return TCL_ERROR; } *rest = '\0'; result = TCL_ERROR; if (GetTempFileName(tempName, "tclr", 0, tempName) != 0) { /* * Strictly speaking, need the following DeleteFile and * MoveFile to be joined as an atomic operation so no * other app comes along in the meantime and creates the * same temp file. */ DeleteFile(tempName); if (MoveFile(dst, tempName) != FALSE) { if (MoveFile(src, dst) != FALSE) { SetFileAttributes(tempName, FILE_ATTRIBUTE_NORMAL); DeleteFile(tempName); return TCL_OK; } else { DeleteFile(dst); MoveFile(tempName, dst); } } /* * Can't backup dst file or move src file. Return that * error. Could happen if an open file refers to dst. */ TclWinConvertError(GetLastError()); if (errno == EACCES) { /* * Decode the EACCES to a more meaningful error. */ goto decode; } } return result; } } } return TCL_ERROR; }
/* Write the actual file name at fname. */ FILE * gp_open_scratch_file(const char *prefix, char *fname, const char *mode) { UINT n; DWORD l; HANDLE hfile = INVALID_HANDLE_VALUE; int fd = -1; FILE *f = NULL; char sTempDir[_MAX_PATH]; char sTempFileName[_MAX_PATH]; memset(fname, 0, gp_file_name_sizeof); if (!gp_file_name_is_absolute(prefix, strlen(prefix))) { int plen = sizeof(sTempDir); if (gp_gettmpdir(sTempDir, &plen) != 0) l = GetTempPath(sizeof(sTempDir), sTempDir); else l = strlen(sTempDir); } else { strncpy(sTempDir, prefix, sizeof(sTempDir)); prefix = ""; l = strlen(sTempDir); } /* Fix the trailing terminator so GetTempFileName doesn't get confused */ if (sTempDir[l-1] == '/') sTempDir[l-1] = '\\'; /* What Windoze prefers */ if (l <= sizeof(sTempDir)) { n = GetTempFileName(sTempDir, prefix, 0, sTempFileName); if (n == 0) { /* If 'prefix' is not a directory, it is a path prefix. */ int l = strlen(sTempDir), i; for (i = l - 1; i > 0; i--) { uint slen = gs_file_name_check_separator(sTempDir + i, l, sTempDir + l); if (slen > 0) { sTempDir[i] = 0; i += slen; break; } } if (i > 0) n = GetTempFileName(sTempDir, sTempDir + i, 0, sTempFileName); } if (n != 0) { hfile = CreateFile(sTempFileName, GENERIC_READ | GENERIC_WRITE | DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL /* | FILE_FLAG_DELETE_ON_CLOSE */, NULL); /* * Can't apply FILE_FLAG_DELETE_ON_CLOSE due to * the logics of clist_fclose. Also note that * gdev_prn_render_pages requires multiple temporary files * to exist simultaneousely, so that keeping all them opened * may exceed available CRTL file handles. */ } } if (hfile != INVALID_HANDLE_VALUE) { /* Associate a C file handle with an OS file handle. */ fd = _open_osfhandle((long)hfile, 0); if (fd == -1) CloseHandle(hfile); else { /* Associate a C file stream with C file handle. */ f = fdopen(fd, mode); if (f == NULL) _close(fd); } } if (f != NULL) { if ((strlen(sTempFileName) < gp_file_name_sizeof)) strncpy(fname, sTempFileName, gp_file_name_sizeof - 1); else { /* The file name is too long. */ fclose(f); f = NULL; } } if (f == NULL) eprintf1("**** Could not open temporary file '%s'\n", fname); return f; }
void ribi::Rinside::Test() noexcept { { static bool is_tested{false}; if (is_tested) return; is_tested = true; } { ribi::fileio::FileIo(); } auto& r = Rinside().Get(); const auto f = ribi::fileio::FileIo(); //Read/write of integer { r["x"] = 42; const Rcpp::NumericVector v = r.parseEval("x"); assert(v.size() == 1); assert(v[0] == 42); } //Read/write of integer vector { const Rcpp::NumericVector v = {1,2,3}; r["v"] = v; const Rcpp::NumericVector w = r.parseEval("v"); assert(v == w); } //Read/write of plot with known name { if(f.IsRegularFile("tmp.png")) { f.DeleteFile("tmp.png"); } assert(!f.IsRegularFile("tmp.png")); r.parseEval("png(filename=\"tmp.png\")"); r.parseEval("plot(sin)"); r.parseEval("dev.off()"); assert(f.IsRegularFile("tmp.png")); f.DeleteFile("tmp.png"); } { const std::string newick{"((F:2,G:2):1,H:3);"}; if(f.IsRegularFile("tmp.png")) { f.DeleteFile("tmp.png"); } assert(!f.IsRegularFile("tmp.png")); r.parseEvalQ("library(ape)"); r.parseEvalQ("library(geiger)"); r["newick"] = newick; r.parseEvalQ("phylogeny <- read.tree(text = newick)"); r.parseEvalQ("png(filename=\"tmp.png\")"); r.parseEvalQ("plot(phylogeny)"); r.parseEvalQ("dev.off()"); assert(f.IsRegularFile("tmp.png")); f.DeleteFile("tmp.png"); } //Use any filename { const std::string filename = f.GetTempFileName(".png"); assert(!f.IsRegularFile(filename)); r.parseEval("png(filename=\""+filename+"\")"); r.parseEval("plot(sin)"); r.parseEval("dev.off()"); assert(f.IsRegularFile(filename)); f.DeleteFile(filename); } //Use any filename with a name in the R script { const std::string filename = f.GetTempFileName(".png"); assert(!f.IsRegularFile(filename)); r["png_filename"] = filename; r.parseEval("png(filename=png_filename)"); r.parseEval("plot(sin)"); r.parseEval("dev.off()"); assert(f.IsRegularFile(filename)); f.DeleteFile(filename); } //assert(1==2); }
static inline int sh(const char *script){ #ifdef _WIN32 g_logger.debug("sh('%s')", script); /* Running sh script on Windows 1) Write the command to run into temporary file 2) Run the temporary file with 'sh <temp_file_name>' */ char tmp_path[MAX_PATH]; if (GetTempPath(sizeof(tmp_path), tmp_path) == 0) { g_logger.error( "GetTempPath failed, error: %d", GetLastError()); return -1; } char tmp_file[MAX_PATH]; if (GetTempFileName(tmp_path, "sh_", 0, tmp_file) == 0) { g_logger.error( "GetTempFileName failed, error: %d", GetLastError()); return -1; } FILE* fp = fopen(tmp_file, "w"); if (fp == NULL) { g_logger.error( "Cannot open file '%s', error: %d", tmp_file, errno); return -1; } // cygwin'ify the script and write it to temp file { char* cygwin_script = replace_drive_letters(script); g_logger.debug(" - cygwin_script: '%s' ", cygwin_script); fprintf(fp, "%s", cygwin_script); free(cygwin_script); } fclose(fp); // Run the temp file with "sh" BaseString command; command.assfmt("sh %s", tmp_file); g_logger.debug(" - running '%s' ", command.c_str()); int ret = system(command.c_str()); if (ret == 0) g_logger.debug(" - OK!"); else g_logger.warning("Running the command '%s' as '%s' failed, ret: %d", script, command.c_str(), ret); // Remove the temp file unlink(tmp_file); return ret; #else return system(script); #endif }
void makeEXE(HWND hwndDlg) { TCHAR buf[2048]; GetTempPath(MAX_PATH,buf); GetTempFileName(buf,_T("zne"),0,nsifilename); #ifdef _UNICODE FILE *fp=_tfopen(nsifilename,_T("w, ccs=UNICODE")); // generate a Unicode .NSI file #else FILE *fp=_tfopen(nsifilename,_T("w")); #endif if (!fp) { MessageBox(hwndDlg,_T("Error writing .NSI file"),g_errcaption,MB_OK|MB_ICONSTOP); PostMessage(g_hwnd,WM_USER+1203,0,0); return; } GetDlgItemText(hwndDlg,IDC_INSTNAME,buf,sizeof(buf)); _ftprintf(fp,_T("!define ZIP2EXE_NAME `%s`\n"),buf); GetDlgItemText(hwndDlg,IDC_OUTFILE,buf,sizeof(buf)); _ftprintf(fp,_T("!define ZIP2EXE_OUTFILE `%s`\n"),buf); if (g_compressor == 1) _ftprintf(fp,_T("!define ZIP2EXE_COMPRESSOR_ZLIB\n")); if (g_compressor == 2) _ftprintf(fp,_T("!define ZIP2EXE_COMPRESSOR_BZIP2\n")); if (g_compressor == 3) _ftprintf(fp,_T("!define ZIP2EXE_COMPRESSOR_LZMA\n")); if (g_compressor_solid == 1) _ftprintf(fp,_T("!define ZIP2EXE_COMPRESSOR_SOLID\n")); GetDlgItemText(hwndDlg,IDC_INSTPATH,buf,sizeof(buf)); int iswinamp=0; LPCTSTR iswinampmode=NULL; if (!_tcscmp(buf,gp_poi)) lstrcpy(buf,_T("$EXEDIR")); if (!_tcscmp(buf,gp_winamp)) { iswinamp=1; } if (!_tcscmp(buf,gp_winamp_plugins)) { iswinamp=1; _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR_PLUGINS\n")); } if (!_tcscmp(buf,gp_winamp_vis)) { iswinamp=1; iswinampmode=_T("VisDir"); } if (!_tcscmp(buf,gp_winamp_dsp)) { iswinamp=1; iswinampmode=_T("DSPDir"); } if (!_tcscmp(buf,gp_winamp_skins)) { iswinamp=1; iswinampmode=_T("SkinDir"); _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR_SKINS\n")); } if (iswinamp) { _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR_WINAMP\n")); if (iswinampmode) { _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR_WINAMPMODE `%s`\n"),iswinampmode); } } else // set out path to $INSTDIR { _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR `%s`\n"),buf); } _ftprintf(fp,_T("!include `${NSISDIR}\\Contrib\\zip2exe\\Base.nsh`\n")); _ftprintf(fp,_T("!include `${NSISDIR}\\Contrib\\zip2exe\\%s.nsh`\n"),g_mui?_T("Modern"):_T("Classic")); _ftprintf(fp,_T("!insertmacro SECTION_BEGIN\n")); _ftprintf(fp,_T("File /r `%s\\*.*`\n"),tempzip_path); _ftprintf(fp,_T("!insertmacro SECTION_END\n")); fclose(fp); TCHAR g_makensis_path[MAX_PATH]; TCHAR *p=g_makensis_path; GetModuleFileName(g_hInstance,g_makensis_path,sizeof(g_makensis_path)); while (*p) p++; while (p >= g_makensis_path && *p != _T('\\')) p--; _tcscpy(p+1,_T("makensis.exe")); WIN32_FIND_DATA fd; HANDLE h=FindFirstFile(g_makensis_path,&fd); if (h==INVALID_HANDLE_VALUE) { if ((p-g_makensis_path>4)&&(_totlower(*(p-1))==_T('n'))&&(_totlower(*(p-2))==_T('i'))&&(_totlower(*(p-3))==_T('b'))&&(*(p-4)==_T('\\'))) { p -= 4; _tcscpy(p+1,_T("makensis.exe")); h=FindFirstFile(g_makensis_path,&fd); if (h==INVALID_HANDLE_VALUE) { MessageBox(hwndDlg,_T("Error finding makensis.exe."),g_errcaption,MB_OK|MB_ICONSTOP); PostMessage(g_hwnd,WM_USER+1203,0,0); return; } } } if (h!=INVALID_HANDLE_VALUE) FindClose(h); wsprintf(g_cmdline,_T("\"%s\" %s \"%s\""),g_makensis_path,g_options,nsifilename); DWORD id; g_hThread=CreateThread(NULL,0,ThreadProc,0,0,&id); }
LRESULT BlobMgmt::ShowImage() { #ifndef VC6 HDC hdc; RECT rectwin; wyInt32 renderwidth, renderheight; PAINTSTRUCT ps; LPSTREAM stream = NULL; HGLOBAL glbmem; void *glbbuffer; wyWChar tempfilename[MAX_PATH+1] = {0}, path[MAX_PATH + 1] = {0}; wyString tempstr; HANDLE hfile = INVALID_HANDLE_VALUE; DWORD byteswritten = 0; if(!m_piub->m_data || m_piub->m_datasize == 0) { VERIFY(hdc = BeginPaint(m_hwndimage, &ps)); VERIFY(EndPaint(m_hwndimage, &ps)); return 0; } /* allocate global memory and copy image data in it*/ VERIFY(glbmem = GlobalAlloc(GMEM_MOVEABLE | GMEM_NODISCARD, m_piub->m_datasize)); if(!glbmem) return 0; /* lock the global memory and get a pointer */ glbbuffer = GlobalLock(glbmem); /* copy the memory to buffer */ CopyMemory(glbbuffer, m_piub->m_data, m_piub->m_datasize); /* unlock it */ VERIFY(GlobalUnlock(glbmem)== NO_ERROR); /* create the stream */ VERIFY(CreateStreamOnHGlobal(glbmem, FALSE, &stream)== S_OK); /* prepare window for painting */ VERIFY(hdc = BeginPaint(m_hwndimage, &ps)); /* clear the window */ PrepareScreen(ps.hdc); if(pGlobals->m_configdirpath.GetLength() || SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, (LPWSTR)path))) { if(pGlobals->m_configdirpath.GetLength()) { //wcscpy(path, pGlobals->m_configdirpath.GetAsWideChar()); wcsncpy(path, pGlobals->m_configdirpath.GetAsWideChar(), MAX_PATH); path[MAX_PATH] = '\0'; } else { wcscat(path, L"\\"); wcscat(path, L"SQLyog"); } VERIFY(GetTempFileName(path, L"img", 0, tempfilename)); hfile = CreateFile(tempfilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, NULL, NULL); VERIFY(hfile != INVALID_HANDLE_VALUE); VERIFY(WriteFile(hfile, m_piub->m_data, m_piub->m_datasize, &byteswritten, NULL)); VERIFY(CloseHandle(hfile)); } tempstr.SetAs(tempfilename); WCHAR *wpath = GetWideString(tempstr.GetString()); Gdiplus::Graphics graphics(hdc); Gdiplus::Image *image = new Gdiplus::Image(wpath); HeapFree(GetProcessHeap(), 0, wpath); /* in win95 image will be null so we exit */ if(!image) goto ExitPara; /* the binary data might not be image so image.getlastatus will not return Ok */ if(image->GetLastStatus()!= Gdiplus::Ok) { delete image; goto ExitPara; } /* get the window width and calculate the correct render stats */ VERIFY(GetClientRect(m_hwndimage, &rectwin)); renderheight =(((LONG)image->GetHeight())> rectwin.bottom)?(rectwin.bottom):(image->GetHeight()); renderwidth =(((LONG)image->GetWidth())> rectwin.right)?(rectwin.right):(image->GetWidth()); graphics.DrawImage(image, 0, 0, renderwidth, renderheight); delete image; EndPaint(m_hwndimage, &ps); ExitPara: /* free up stuff */ VERIFY(DeleteFile(tempfilename)); if(stream) stream->Release(); VERIFY(GlobalFree(glbmem)== NULL); #endif return 0; }
/* * extract a previous version of the file to a temp file. Returns in tempfile * the name of a temp file containing the requested file version. The 'version' * parameter should contain a SLM file & version in the format file.c@vN. * eg * file.c@v1 is the first version * file.c@v-1 is the previous version * [email protected] is yesterdays version * * we use catsrc to create the previous version. */ BOOL SLM_GetVersion(SLMOBJECT pslm, LPSTR version, LPSTR tempfile) { #ifndef WIN32 // add WIN16 support sometime! return(FALSE); #else char currentdir[MAX_PATH]; char commandpath[MAX_PATH * 2]; HANDLE hfile; BOOL bOK; PROCESS_INFORMATION pi; STARTUPINFO si; SECURITY_ATTRIBUTES sa; GetTempPath(MAX_PATH, tempfile); GetTempFileName(tempfile, "slm", 0, tempfile); sa.nLength = sizeof(sa); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; hfile = CreateFile( tempfile, GENERIC_WRITE, FILE_SHARE_WRITE, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL); if (hfile == INVALID_HANDLE_VALUE) { return(FALSE); } // create a process to run catsrc wsprintf(commandpath, "catsrc %s", version); FillMemory(&si, sizeof(si), 0); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.hStdOutput = hfile; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); si.wShowWindow = SW_HIDE; GetCurrentDirectory(sizeof(currentdir), currentdir); SetCurrentDirectory(pslm->CurDir); bOK = CreateProcess( NULL, commandpath, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi); if (bOK) { WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { DeleteFile(tempfile); tempfile[0] = '\0'; } CloseHandle(hfile); SetCurrentDirectory(currentdir); return(bOK); #endif }
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; }
// // Invoke() // // invoke the GIB program and return the recommended play // int CGIB::Invoke(CPlayer* pPlayer, CHandHoldings* pHand, CHandHoldings* pDummyHand, CPlayerStatusDialog* pStatusDlg) { SECURITY_ATTRIBUTES saAttr; // // create the GIB monitor dialog // CGIBDialog gibDialog(pMAINFRAME); int nProcessingTime = theApp.GetValue(tnGIBAnalysisTime); gibDialog.m_nProcessTime = nProcessingTime; // gibDialog.m_hEventCancel = m_hEventCancel; // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // // create input and output pipes for the child process // // Create a pipe for the child process's STDOUT. if (!CreatePipe(&m_hChildStdoutRd, // returns the pipe's input handle &m_hChildStdoutWr, // returns the pipe's output handle &saAttr, 0)) { CString strError = "Stdout pipe creation failed\n"; TRACE(strError); pMAINFRAME->SetGIBMonitorText(strError); return ExitGracefully(-5); } // then create a pipe for the child process's STDIN. if (!CreatePipe(&m_hChildStdinRd, &m_hChildStdinWr, &saAttr, 0)) { CString strError = "Stdin pipe creation failed\n"; TRACE(strError); pMAINFRAME->SetGIBMonitorText(strError); return ExitGracefully(-5); } // // Now create the child process (GIB) // PROCESS_INFORMATION piProcInfo; if (!LaunchProgram(piProcInfo)) { TRACE("Create process failed"); return ExitGracefully(-1); } HANDLE hGIBProcess = piProcInfo.hProcess; DWORD nGIBProcessID = piProcInfo.dwProcessId; // now close the readable handle to the child's stdin SafeCloseHandle(m_hChildStdinRd); // and the writable handle to the child's stdout SafeCloseHandle(m_hChildStdoutWr); // //------------------------------------------------------------------ // // create the GIB input file // CFile file; CFileException fileException; CString strTempFile, strTempPath; GetTempPath(1024, strTempPath.GetBuffer(1024)); strTempPath.ReleaseBuffer(); GetTempFileName(strTempPath, "ezb", 0, strTempFile.GetBuffer(2048)); strTempFile.ReleaseBuffer(); // strTempFile.Format("%s\\%s", theApp.GetValueString(tszProgramDirectory), tszGIBTempFilename); /* LPTSTR szBuffer = strTempFile.GetBuffer(MAX_PATH); GetTempFileName(theApp.GetValueString(tszProgramDirectory), "ezb", 0, szBuffer); strTempFile.ReleaseBuffer(); */ // CString strInput; // strInput.Format("-T %d %s\n",theApp.GetValue(tnGIBAnalysisTime),strTempFile); int nCode = file.Open(strTempFile, CFile::modeWrite | CFile::modeCreate | CFile::shareDenyWrite, &fileException); if (nCode == 0) { CString strError = "Error opening temporary input file for GIB"; TRACE(strError); pMAINFRAME->SetGIBMonitorText(strError); return ExitGracefully(-2); } // CString strFileContents; CreateGIBInputFile(file, pPlayer, pHand, pDummyHand, strFileContents); file.Close(); // then send the parameters line CString strParameters, strShortParameters; strParameters.Format("-T %d %s\n",nProcessingTime,strTempFile); strShortParameters.Format("-T %d",nProcessingTime); DWORD dwWritten; int nErrCode; if (!WriteFile(m_hChildStdinWr, (LPCTSTR)strParameters, strParameters.GetLength(), &dwWritten, NULL)) { CString strError = "Error providing parameters to GIB"; TRACE(strError); pMAINFRAME->SetGIBMonitorText(strError); nErrCode = GetLastError(); return ExitGracefully(-3); } // // update the GIB monitor window // CString strGIBText = "========================================\n"; strGIBText += FormString("Launching %s %s\n", theApp.GetValueString(tszGIBPath), strShortParameters); // strGIBText += FormString("Input file contents:\n%s", strFileContents); strGIBText += "Awaiting Responses...\n"; strGIBText += "----------------------------------------\n"; // pMAINFRAME->SetGIBMonitorText(strGIBText); pMAINFRAME->AppendGIBMonitorText(strGIBText); // //------------------------------------------------------------ // // now set up the wait loop and the cancel dialog, // then sit and wait for the process to run or for a cancel message // /* // // create the "Cancel GIB" dialog thread // (this is a user interface thread) // CGIBMonitorThread* pMonitorThread = new CGIBMonitorThread(m_hEventFinished, m_hEventCancel, nProcessingTime); pMonitorThread->CreateThread(CREATE_SUSPENDED); pMonitorThread->SetThreadPriority(THREAD_PRIORITY_ABOVE_NORMAL); pMonitorThread->ResumeThread(); // wait for the monitor thread to initialize DWORD nCode0 = WaitForSingleObject(m_hEventFinished, INFINITE); */ // // create the wait thread // (this is a worker thread) // GIBStruct gibData; gibData.hReadHandle = m_hChildStdoutRd; gibData.pGIBDialog = &gibDialog; CWinThread* pWaitThread = AfxBeginThread(CGIB::ReadGIBOutput, &gibData, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED); // copy its handle se that we can check its exit code later HANDLE hWaitThread; BOOL bCode = ::DuplicateHandle(GetCurrentProcess(), pWaitThread->m_hThread, GetCurrentProcess(), &hWaitThread, 0, FALSE, DUPLICATE_SAME_ACCESS); // and launch the threads // MonitorThread->ResumeThread(); pWaitThread->ResumeThread(); // // Show the Wait/Cancel dialog // m_bGIBPending = TRUE; // mark dialog as active bCode = gibDialog.DoModal(); // see if the user cancelled if (!bCode) { /* // lock out the wait thread and cancel operations if (ClearGIBPending()) { */ // pMAINFRAME->SetStatusText("GIB cancelled."); // TerminateProcess(hGIBProcess, 0); TerminateThread(hWaitThread, 0); // wait for the read thread to end WaitForSingleObject(hWaitThread, INFINITE); // close the wait thread handle CloseHandle(hWaitThread); CloseHandle(hGIBProcess); // and delete the thread object delete pWaitThread; // close pipe handles SafeCloseHandle(m_hChildStdinWr); SafeCloseHandle(m_hChildStdoutRd); // and throw an exception throw CGIBException(); // } } /* // set up events HANDLE eventArray[2]; eventArray[0] = m_hEventCancel; eventArray[1] = pWaitThread->m_hThread; // // then sit back and wait for the thread(s) // for(;;) { // wait for the cancelled or finished messages DWORD nCode = WaitForMultipleObjects(2, // 2 events to wait for eventArray, // events array FALSE, // not all at once INFINITE); // wait 4-ever // if (nCode == WAIT_FAILED) { ASSERT(FALSE); break; } else if (nCode == WAIT_OBJECT_0) { // got the cancel message, so kill GIB & the wait thread // the following is very dangersous -- // so kids, don't try this at home TerminateThread(pWaitThread, 0); TerminateProcess(hGIBProcess, 0); return GIB_CANCEL; } else if (nCode == WAIT_OBJECT_0 + 1) { // GIB finished message // signal the GIB monitor that GIB has finished SetEvent(m_hEventFinished); break; } } */ // //------------------------------------------------------------ // // presumably, GIB has finished running // // wait for the GIB thread to exit, then get the card code DWORD nCardPlayed, nErrorCode; bCode = WaitForSingleObject(hWaitThread, INFINITE); bCode = GetExitCodeThread(hWaitThread, &nCardPlayed); if (!bCode) nErrorCode = GetLastError(); // close the wait thread handle CloseHandle(hWaitThread); // delete the temporary file DeleteFile(strTempFile); // and kill the child process // first send a Ctrl-C to the app // (this doesn't seem to do anything) CString strInput = "\03"; // Ctrl-C if (!WriteFile(m_hChildStdinWr, (LPCTSTR)strInput, strInput.GetLength(), &dwWritten, NULL)) { CString strError = "Error stopping GIB"; TRACE(strError); pMAINFRAME->SetGIBMonitorText(strError); nErrCode = GetLastError(); return ExitGracefully(-4); } // close the writable handle to the child's stdin SafeCloseHandle(m_hChildStdinWr); // then call terminateProcess TerminateProcess(hGIBProcess, 0); CloseHandle(hGIBProcess); // then close the readable handle to the child's stdout SafeCloseHandle(m_hChildStdoutRd); // // done // return nCardPlayed; }
void native_loop(const char *title, unsigned char *imageData, unsigned int imageDataLen) { HWND hWnd; HINSTANCE hInstance = GetModuleHandle(NULL); MSG msg; DWORD dwUnicodeLen = MultiByteToWideChar(CP_UTF8,0,title,-1,NULL,0); titleWide = (wchar_t*)calloc(strlen(title) + 1, sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8,0,title,-1,titleWide,dwUnicodeLen); //mbstowcs(titleWide, title, strlen(title)); wcscpy((wchar_t*)szTitle, titleWide); wcscpy((wchar_t*)szWindowClass, (wchar_t*)TEXT("MyClass")); MyRegisterClass(hInstance); hWnd = InitInstance(hInstance, FALSE); // Don't show window if (!hWnd) { return; } // Let's load up the tray icon HICON hIcon; { // This is really hacky, but LoadImage won't let me load an image from memory. // So we have to write out a temporary file, load it from there, then delete the file. // From http://msdn.microsoft.com/en-us/library/windows/desktop/aa363875.aspx TCHAR szTempFileName[MAX_PATH+1]; TCHAR lpTempPathBuffer[MAX_PATH+1]; int dwRetVal = GetTempPath(MAX_PATH+1, // length of the buffer lpTempPathBuffer); // buffer for path if (dwRetVal > MAX_PATH+1 || (dwRetVal == 0)) { return; // Failure } // Generates a temporary file name. int uRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files TEXT("_tmpicon"), // temp file name prefix 0, // create unique name szTempFileName); // buffer for name if (uRetVal == 0) { return; // Failure } // Dump the icon to the temp file FILE* fIcon = _wfopen(szTempFileName, TEXT("wb")); fwrite(imageData, 1, imageDataLen, fIcon); fclose(fIcon); fIcon = NULL; // Load the image from the file hIcon = LoadImage(NULL, szTempFileName, IMAGE_ICON, 64, 64, LR_LOADFROMFILE); // Delete the temp file _wremove(szTempFileName); } nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = hWnd; nid.uID = 100; nid.uCallbackMessage = WM_MYMESSAGE; nid.hIcon = hIcon; wcscpy((wchar_t*)nid.szTip, (wchar_t*)titleWide); // MinGW seems to use ANSI nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; Shell_NotifyIcon(NIM_ADD, &nid); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } }
int CUserPatcher::_Patch( LPCTSTR szfile, const T_UserPatchInfo &unpkinfo, const char *, CString &strLogfile ) { USES_CONVERSION; TCHAR szTempPath[MAX_PATH]; #if 1 TCHAR szTempName[MAX_PATH]; GetTempPath(MAX_PATH, szTempName); GetTempFileName(szTempName, _T("BK.UPK"), 0, szTempPath); DeleteFile( szTempPath ); #else strcpy(szTempPath, "c:\\office.unpack\\"); #endif INT err = KPATCHER_ERR_GENERAL; do { strings files; if(!m_objUpk->Extract(szfile, szTempPath, files)) { err = KPATCHER_ERR_EXTRACT; break; } typedef std::pair<std::string, std::string> stringPair; typedef std::vector< stringPair > stringPairs; stringPairs ps; for(int i=0; i<unpkinfo.files.GetSize(); ++i) { // const T_UserPatchInfo::PatchFileInfo &pi = unpkinfo.files[i]; std::string strfromfilename; _GetFilename( CT2CA(pi.strFilenameFrom), strfromfilename); for(strings::iterator it2=files.begin(); it2!=files.end(); ++it2) { std::string strfilename2; _GetFilename( it2->c_str(), strfilename2 ); if(stricmp(strfromfilename.c_str(), strfilename2.c_str())==0) { std::string sto = CT2CA(pi.strFilenameTo); ps.push_back( stringPair(*it2, sto) ); break; } } } if( ps.size()< unpkinfo.files.GetSize() ) { err = KPATCHER_ERR_FILENOTMATCH; break; } // 2. check file is not used BOOL bFileIsUsing = FALSE; for(unsigned int i=0; i<ps.size(); ++i) { CString strFilename = CA2CT(ps[i].second.c_str()); if( PathFileExists(strFilename) && IsFileUsing( strFilename ) ) { bFileIsUsing = TRUE; break; } } if(bFileIsUsing) { err = KPATCHER_ERR_FILEBUSY; break; } // 3. replace files struct T_ReplaceInfo { std::string strTo, strTmpBackup, strTmp; LARGE_INTEGER llfrom, llto; bool skipReplace; }; bool hasError = false; std::vector<T_ReplaceInfo> tmpfiles; // copy all files into target path for( unsigned int i=0; i<ps.size() && !hasError; ++i) { // BAKCUP in local DIR std::string strfrom, strto, strtmp, strbackup; strfrom = ps[i].first; strto = ps[i].second; strtmp = strto + "_TMP"; strbackup = ps[i].second + "_TMPBK"; T_ReplaceInfo r; r.strTo = strto; r.strTmpBackup = strbackup; r.strTmp = strtmp; if( GetFileVersion( CA2CT(strfrom.c_str()), r.llfrom) && GetFileVersion( CA2CT(strto.c_str()), r.llto) && r.llfrom.QuadPart==r.llto.QuadPart ) { r.skipReplace = true; } else { CreateDirs( strto.c_str() ); BOOL b1 = true, b2 = true; if( IsFileExist( CA2CT(strto.c_str()) ) ) b1 = MyMoveFileA( strto.c_str(), strbackup.c_str()); b2 = MyMoveFileA(strfrom.c_str(), strtmp.c_str()); if( !b1 || !b2 ) { #ifdef _DEBUG DWORD dwErr = GetLastError(); CStringA strA; strA.Format("MOVE FILE ERROR %d\r\n%d %s -> %s\r\n%d %s -> %s \r\n", dwErr, b1, strto.c_str(), strbackup.c_str(), b2, strfrom.c_str(), strtmp.c_str() ); MessageBoxA(NULL, strA, NULL, MB_OK); #endif hasError = true; } r.skipReplace = false; } tmpfiles.push_back( r ); } // 4. rollback or commit replace operation if( hasError ) { for( unsigned int i=0; i<tmpfiles.size(); ++i) { T_ReplaceInfo &r = tmpfiles[i]; if( r.skipReplace ) continue; MyMoveFileA( r.strTmpBackup.c_str(), r.strTo.c_str() ); } err = KPATCHER_ERR_REPLACE; } else { // Assume all move operation success CStringA slog; CStringA strProductKey = CT2CA(unpkinfo.strProductKey), strPatchKey = CT2CA(unpkinfo.strPatchKey); slog.AppendFormat("REG:%s\t%s\r\n", strProductKey, strPatchKey); for( unsigned int i=0; i<tmpfiles.size(); ++i) { T_ReplaceInfo &r = tmpfiles[i]; std::string strbackup = r.strTo + "_bk"; CString strVfrom, strVto; CStringA strVfromA, strVtoA; GenVersionStr( r.llfrom, strVfrom); GenVersionStr( r.llto, strVto); strVfromA = CT2CA( strVfrom ); strVtoA = CT2CA( strVto ); slog.AppendFormat("VER:%s\t%s\r\n", strVfromA, strVtoA); slog.AppendFormat("FILE:%d\t%s\t%s\r\n", r.skipReplace, strbackup.c_str(), r.strTo.c_str() ); if( r.skipReplace ) continue; // if( IsFileExist( CA2CT(r.strTmpBackup.c_str()) ) ) MyMoveFileA(r.strTmpBackup.c_str(), strbackup.c_str()); MyMoveFileA(r.strTmp.c_str(), r.strTo.c_str()); } std::string dir; _GetFileDir( ps[0].second.c_str(), dir ); char logfilename[MAX_PATH]; sprintf(logfilename, "$NTUninstKB%d$.log", unpkinfo.nKBID); dir += '\\'; dir += logfilename; strLogfile = CA2CT(dir.c_str()); file_put_contents( strLogfile, (BYTE*)(LPCSTR)slog, slog.GetLength()); err = KPATCHER_OK; } }while(FALSE); #ifndef _DEBUG { TCHAR szPath[MAX_PATH] = {0}; _tcscpy(szPath, szTempPath); SHFILEOPSTRUCT shfileopstruct = {0}; shfileopstruct.wFunc = FO_DELETE; shfileopstruct.pFrom = szPath; shfileopstruct.fFlags = FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_NOERRORUI; SHFileOperation(&shfileopstruct); } #endif return err; }
BOOL CJpegFile::DecryptJPEG(std::string csJpeg) { char szTempName[MAX_PATH] = ""; std::string szDstpath; HANDLE hSrc, hDst; BYTE *dst_data, *src_data; DWORD dst_len, src_len, src_hlen; DWORD result_len, i, j; int rfv = csJpeg.rfind('\\'); szDstpath = csJpeg; szDstpath.resize(rfv); if(szDstpath.size()== 2) szDstpath += '\\';//_T('\\'); if(GetTempFileName((LPCTSTR)szDstpath.c_str(), "ksc", 0, szTempName) == 0) { // AfxMessageBox("임시 파일을 생성할 수가 없습니다.", MB_ICONSTOP|MB_OK); return FALSE; } hSrc = CreateFile((LPCTSTR)csJpeg.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hSrc == INVALID_HANDLE_VALUE) { // AfxMessageBox("소스 파일이 존재하지 않습니다. 다른 파일을 선택해주세요.", MB_ICONSTOP|MB_OK); return FALSE; } hDst = CreateFile((LPCTSTR)szTempName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hDst == INVALID_HANDLE_VALUE) { CloseHandle(hSrc); return FALSE; } src_len = GetFileSize(hSrc, &src_hlen); if(src_hlen > 0) { CloseHandle(hSrc); CloseHandle(hDst); } dst_len = src_len - 8; src_data = new BYTE[src_len]; dst_data = new BYTE[dst_len]; ReadFile(hSrc, (LPVOID)src_data, src_len, &result_len, NULL); m_r = 1124; for(i = 0; i < 4; i++) { Decrypt(src_data[i]); } BYTE magic[4]; for(i = 4; i < 8; i++) { magic[i-4] = Decrypt(src_data[i]); } if(magic[0] == 'K' && magic[1] == 'S' && magic[2] == 'C' && magic[3] == 1) { //버전 1번 } else { CloseHandle(hSrc); CloseHandle(hDst); delete[] dst_data; delete[] src_data; return FALSE; } for(j = 0; i < src_len; i++, j++) { dst_data[j] = Decrypt(src_data[i]); } WriteFile(hDst, (LPCVOID)dst_data, dst_len, &result_len, NULL); CloseHandle(hSrc); CloseHandle(hDst); delete[] dst_data; delete[] src_data; LoadJpegFile(szTempName); DeleteFile((LPCTSTR)szTempName); return TRUE; }
static HB_BOOL hb_fsTempName( char * pszBuffer, const char * pszDir, const char * pszPrefix ) { HB_BOOL fResult; pszBuffer[ 0 ] = '\0'; hb_vmUnlock(); #if defined( HB_OS_WIN ) { LPCTSTR lpPrefix, lpDir; LPTSTR lpPrefixFree = NULL, lpDirFree = NULL; TCHAR lpBuffer[ HB_PATH_MAX ]; TCHAR lpTempDir[ HB_PATH_MAX ]; lpPrefix = pszPrefix ? HB_FSNAMECONV( pszPrefix, &lpPrefixFree ) : NULL; if( pszDir && pszDir[ 0 ] != '\0' ) lpDir = HB_FSNAMECONV( pszDir, &lpDirFree ); else { if( ! GetTempPath( HB_PATH_MAX, lpTempDir ) ) { hb_fsSetIOError( HB_FALSE, 0 ); return HB_FALSE; } lpTempDir[ HB_PATH_MAX - 1 ] = TEXT( '\0' ); lpDir = lpTempDir; } fResult = GetTempFileName( lpDir, lpPrefix ? lpPrefix : TEXT( "hb" ), 0, lpBuffer ); if( fResult ) HB_OSSTRDUP2( lpBuffer, pszBuffer, HB_PATH_MAX - 1 ); if( lpPrefixFree ) hb_xfree( lpPrefixFree ); if( lpDirFree ) hb_xfree( lpDirFree ); } #else { char * pTmpBuffer = ( char * ) hb_xgrab( L_tmpnam + 1 ); /* TODO: Implement these: */ HB_SYMBOL_UNUSED( pszDir ); HB_SYMBOL_UNUSED( pszPrefix ); pTmpBuffer[ 0 ] = '\0'; fResult = ( tmpnam( pszBuffer ) != NULL ); pTmpBuffer[ L_tmpnam ] = '\0'; if( fResult ) { # if defined( __DJGPP__ ) /* convert '/' to '\' */ char * pszDelim = pTmpBuffer; while( ( pszDelim = strchr( pszDelim, '/' ) ) != NULL ) *pszDelim = '\\'; # endif hb_osStrDecode2( pTmpBuffer, pszBuffer, HB_PATH_MAX - 1 ); } hb_xfree( pTmpBuffer ); } #endif hb_fsSetIOError( fResult, 0 ); hb_vmLock(); return fResult; }
void TestBasicEnvironment::SetUp() { char *tmp; CStdString xbmcTempPath; XFILE::CFile *f; /* NOTE: The below is done to fix memleak warning about unitialized variable * in xbmcutil::GlobalsSingleton<CAdvancedSettings>::getInstance(). */ g_advancedSettings.Initialize(); if (!CXBMCTestUtils::Instance().SetReferenceFileBasePath()) SetUpError(); CXBMCTestUtils::Instance().setTestFileFactoryWriteInputFile( XBMC_REF_FILE_PATH("xbmc/filesystem/test/reffile.txt") ); //for darwin set framework path - else we get assert //in guisettings init below #ifdef TARGET_DARWIN CStdString frameworksPath = CUtil::GetFrameworksPath(); CSpecialProtocol::SetXBMCFrameworksPath(frameworksPath); #endif /* TODO: Something should be done about all the asserts in GUISettings so * that the initialization of these components won't be needed. */ g_powerManager.Initialize(); CSettings::Get().Initialize(); /* Create a temporary directory and set it to be used throughout the * test suite run. */ #ifndef _LINUX TCHAR lpTempPathBuffer[MAX_PATH]; if (!GetTempPath(MAX_PATH, lpTempPathBuffer)) SetUpError(); xbmcTempPath = lpTempPathBuffer; if (!GetTempFileName(xbmcTempPath.c_str(), "xbmctempdir", 0, lpTempPathBuffer)) SetUpError(); DeleteFile(lpTempPathBuffer); if (!CreateDirectory(lpTempPathBuffer, NULL)) SetUpError(); CSpecialProtocol::SetTempPath(lpTempPathBuffer); #else char buf[MAX_PATH]; (void)xbmcTempPath; strcpy(buf, "/tmp/xbmctempdirXXXXXX"); if ((tmp = mkdtemp(buf)) == NULL) SetUpError(); CSpecialProtocol::SetTempPath(tmp); #endif /* Create and delete a tempfile to initialize the VFS (really to initialize * CLibcdio). This is done so that the initialization of the VFS does not * affect the performance results of the test cases. */ /* TODO: Make the initialization of the VFS here optional so it can be * testable in a test case. */ f = XBMC_CREATETEMPFILE(""); if (!f || !XBMC_DELETETEMPFILE(f)) { TearDown(); SetUpError(); } }
//**************************************************************************************** BOOL CBCGPMenuHash::SaveMenuBar (HMENU hMenu, CBCGPToolBar* pBar) { ASSERT_VALID (pBar); if (pBar->GetCount () == 0) { return FALSE; } HANDLE hFileOld = NULL; if (m_StoredMenues.Lookup (hMenu, hFileOld)) { //-------------------- // Free unused handle: //-------------------- ::CloseHandle (hFileOld); } //--------------------- // Get the temp path... //--------------------- CString strTempPath; GetTempPath (MAX_PATH, strTempPath.GetBuffer (MAX_PATH)); strTempPath.ReleaseBuffer(); //------------------------------------------- // Create a temporary file for the output.... //------------------------------------------- CString strTempName; GetTempFileName (strTempPath, _T("BCG"), 0, strTempName.GetBuffer (MAX_PATH)); strTempName.ReleaseBuffer (); HANDLE hFile = ::CreateFile (strTempName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL); if (hFile == INVALID_HANDLE_VALUE) { TRACE(_T("Can't create temporary file!\n")); return FALSE; } try { //--------------------------------- // Write a menubar context to file: //--------------------------------- #if _MSC_VER >= 1300 CFile file (hFile); #else CFile file ((HFILE) hFile); #endif CArchive ar (&file, CArchive::store); m_bIsActive = TRUE; pBar->Serialize (ar); ar.Flush (); m_bIsActive = FALSE; } catch (CArchiveException* pEx) { TRACE(_T("Archive exception in CBCGPMenuHash::SaveMenuBar ()!\n")); pEx->Delete (); ::CloseHandle(hFile); m_bIsActive = FALSE; return FALSE; } catch (CMemoryException* pEx) { TRACE(_T("Memory exception in CBCGPMenuHash::SaveMenuBar ()!\n")); pEx->Delete (); ::CloseHandle(hFile); m_bIsActive = FALSE; return FALSE; } catch (CFileException* pEx) { TRACE(_T("File exception in CBCGPMenuHash::SaveMenuBar ()!\n")); pEx->Delete (); ::CloseHandle(hFile); m_bIsActive = FALSE; return FALSE; } m_StoredMenues.SetAt (hMenu, hFile); return TRUE; }
// Function name : RunLocal // Description : // Return type : void // Argument : bool bDoSMP void RunLocal(bool bDoSMP) { DWORD size = 100; TCHAR pszHost[100], pszCmdLine[MAX_PATH], error_msg[256], pszEnv[256], pszExtra[MAX_PATH]; STARTUPINFO saInfo; PROCESS_INFORMATION psInfo; LPTSTR pEnv; int rootPort=0; HANDLE *hProcess = new HANDLE[g_nHosts]; GetComputerName(pszHost, &size); wsprintf(pszCmdLine, TEXT("%s %s"), g_pszExe, g_pszArgs); GetTempFileName(_T("."), _T("mpi"), 0, pszExtra); // This produces a name in the form: ".\XXXmpi.tmp" // \ is illegal in named objects so use &pszExtra[2] instead of pszExtra for the JobID if (bDoSMP) { wsprintf(pszEnv, _T("MPICH_JOBID=%s|MPICH_IPROC=0|MPICH_NPROC=%d|MPICH_ROOTHOST=%s|MPICH_ROOTPORT=%d|MPICH_EXTRA=%s|MPICH_COMNIC=%s|MPICH_SHM_LOW=0|MPICH_SHM_HIGH=%d"), &pszExtra[2], g_nHosts, pszHost, -1, pszExtra, pszHost, g_nHosts-1); } else { wsprintf(pszEnv, _T("MPICH_JOBID=%s|MPICH_IPROC=0|MPICH_NPROC=%d|MPICH_ROOTHOST=%s|MPICH_ROOTPORT=%d|MPICH_EXTRA=%s|MPICH_COMNIC=%s"), &pszExtra[2], g_nHosts, pszHost, -1, pszExtra, pszHost); } SetEnvironmentVariables(pszEnv); if (_tcslen(g_pszEnv) > 0) SetEnvironmentVariables(g_pszEnv); pEnv = GetEnvironmentStrings(); GetStartupInfo(&saInfo); // launch first process if (CreateProcess( NULL, pszCmdLine, NULL, NULL, FALSE, IDLE_PRIORITY_CLASS, pEnv, NULL, &saInfo, &psInfo)) { hProcess[0] = psInfo.hProcess; CloseHandle(psInfo.hThread); } else { int error = GetLastError(); Translate_Error(error, error_msg, TEXT("CreateProcess failed: ")); _tprintf(TEXT("Unable to launch '%s', error %d: %s"), pszCmdLine, error, error_msg); return; } RemoveEnvironmentVariables(pszEnv); FreeEnvironmentStrings(pEnv); if (g_bNoMPI) { rootPort = -1; } else { // Open the file and read the port number written by the first process HANDLE hFile = CreateFile(pszExtra, GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { Translate_Error(GetLastError(), error_msg, TEXT("CreateFile failed ")); _tprintf(error_msg); return; } DWORD num_read = 0; TCHAR pBuffer[100]; pBuffer[0] = '\0'; TCHAR *pChar = pBuffer; clock_t cStart = clock(); while (true) { num_read = 0; if (!ReadFile(hFile, pChar, 100, &num_read, NULL)) { Translate_Error(GetLastError(), error_msg, TEXT("ReadFile failed ")); _tprintf(error_msg); return; } if (num_read == 0) { if (clock() - cStart > 10 * CLOCKS_PER_SEC) { _tprintf(TEXT("Wait for process 0 to write port to temporary file timed out\n")); TerminateProcess(hProcess, 0); return; } Sleep(100); } else { for (int i=0; i<(int)num_read; i++) { if (*pChar == _T('\n')) break; pChar ++; } if (*pChar == _T('\n')) break; } } CloseHandle(hFile); rootPort = _ttoi(pBuffer); } DeleteFile(pszExtra); // launch all the rest of the processes for (int i=1; i<g_nHosts; i++) { if (bDoSMP) { wsprintf(pszEnv, _T("MPICH_JOBID=%s|MPICH_IPROC=%d|MPICH_NPROC=%d|MPICH_ROOTHOST=%s|MPICH_ROOTPORT=%d|MPICH_COMNIC=%s|MPICH_SHM_LOW=0|MPICH_SHM_HIGH=%d"), &pszExtra[2], i, g_nHosts, pszHost, rootPort, pszHost, g_nHosts-1); } else { wsprintf(pszEnv, _T("MPICH_JOBID=%s|MPICH_IPROC=%d|MPICH_NPROC=%d|MPICH_ROOTHOST=%s|MPICH_ROOTPORT=%d|MPICH_COMNIC=%s"), &pszExtra[2], i, g_nHosts, pszHost, rootPort, pszHost); } SetEnvironmentVariables(pszEnv); pEnv = GetEnvironmentStrings(); if (CreateProcess( NULL, pszCmdLine, NULL, NULL, FALSE, IDLE_PRIORITY_CLASS, pEnv, NULL, &saInfo, &psInfo)) { hProcess[i] = psInfo.hProcess; CloseHandle(psInfo.hThread); } else { int error = GetLastError(); Translate_Error(error, error_msg, TEXT("CreateProcess failed: ")); _tprintf(TEXT("Unable to launch '%s', error %d: %s"), pszCmdLine, error, error_msg); return; } RemoveEnvironmentVariables(pszEnv); FreeEnvironmentStrings(pEnv); } // Wait for all the processes to terminate WaitForLotsOfObjects(g_nHosts, hProcess); for (i=0; i<g_nHosts; i++) CloseHandle(hProcess[i]); delete hProcess; }
DWORD CHooks::RunScript(CString cmd, LPCTSTR currentDir, CString& error, bool bWait, bool bShow) { DWORD exitcode = 0; SECURITY_ATTRIBUTES sa = { 0 }; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; CAutoFile hOut ; CAutoFile hRedir; CAutoFile hErr; // clear the error string error.Empty(); // Create Temp File for redirection TCHAR szTempPath[MAX_PATH] = {0}; TCHAR szOutput[MAX_PATH] = {0}; TCHAR szErr[MAX_PATH] = {0}; GetTortoiseGitTempPath(_countof(szTempPath), szTempPath); GetTempFileName(szTempPath, L"git", 0, szErr); // setup redirection handles // output handle must be WRITE mode, share READ // redirect handle must be READ mode, share WRITE hErr = CreateFile(szErr, GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr); if (!hErr) { error = CFormatMessageWrapper(); return (DWORD)-1; } hRedir = CreateFile(szErr, GENERIC_READ, FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); if (!hRedir) { error = CFormatMessageWrapper(); return (DWORD)-1; } GetTempFileName(szTempPath, L"git", 0, szOutput); hOut = CreateFile(szOutput, GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr); if (!hOut) { error = CFormatMessageWrapper(); return (DWORD)-1; } // setup startup info, set std out/err handles // hide window STARTUPINFO si = { 0 }; si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.hStdOutput = hOut; si.hStdError = hErr; si.wShowWindow = bShow ? SW_SHOW : SW_HIDE; PROCESS_INFORMATION pi = { 0 }; if (!CreateProcess(nullptr, cmd.GetBuffer(), nullptr, nullptr, TRUE, CREATE_UNICODE_ENVIRONMENT, nullptr, currentDir, &si, &pi)) { const DWORD err = GetLastError(); // preserve the CreateProcess error error = CFormatMessageWrapper(err); SetLastError(err); cmd.ReleaseBuffer(); return (DWORD)-1; } cmd.ReleaseBuffer(); CloseHandle(pi.hThread); // wait for process to finish, capture redirection and // send it to the parent window/console if (bWait) { DWORD dw; char buf[256] = { 0 }; do { while (ReadFile(hRedir, &buf, sizeof(buf) - 1, &dw, nullptr)) { if (dw == 0) break; error += CString(CStringA(buf,dw)); } Sleep(150); } while (WaitForSingleObject(pi.hProcess, 0) != WAIT_OBJECT_0); // perform any final flushing while (ReadFile(hRedir, &buf, sizeof(buf) - 1, &dw, nullptr)) { if (dw == 0) break; error += CString(CStringA(buf, dw)); } WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &exitcode); } CloseHandle(pi.hProcess); DeleteFile(szOutput); DeleteFile(szErr); return exitcode; }
/*************** EXE create *******************************************************/ void GUI_manager::create_exe_file(HWND hwndDlg) { OPENFILENAME ofn; char strFilesName[MAX_PATH + 1]; char sendmap_exe[1000]; int exp_day=0; int exp_month=0; int exp_year=0; unsigned int gps_id = 0; char copyright_string[2048]; char licence_file[2048]; char expired_file[2048]; char temp_path[MAX_PATH]; char temp_file[MAX_PATH]; char temp[2000]; char temp_d[2000]; int result; strcpy(strFilesName,"MyMaps.exe"); ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.lpstrFile = strFilesName; //ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(strFilesName); ofn.lpstrFilter = "EXE files\0*.EXE\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; //ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT | OFN_EXPLORER; GetModuleFileName(NULL,sendmap_exe,1000); strcpy(copyright_string,sendmap_data.copyright_string); if (GetSaveFileName(&ofn)==TRUE) { memset(expired_file,0,400); memset(licence_file,0,400); #if FULL == 1 if( SendMessage(exe_expiry_check,BM_GETCHECK,0,0) == BST_CHECKED ) { GetWindowText(exe_expiry,temp,11); if( strlen(temp) == 10 ) { if( temp[2] == '/' && temp[5] == '/' ) { memset(temp_d,0,200); strncpy(temp_d,temp,2); exp_day = atoi(temp_d); strncpy(temp_d,&temp[3],2); exp_month = atoi(temp_d); strncpy(temp_d,&temp[6],4); exp_year = atoi(temp_d); } } if( !exp_day && !exp_month && !exp_year ) MessageBox(NULL,"Date format must be DD/MM/YYYY !","Creating EXE uploader",MB_ICONINFORMATION | MB_OK); } if( SendMessage(exe_lock_check,BM_GETCHECK,0,0) == BST_CHECKED ) { GetWindowText(exe_lock,temp,20); gps_id = strtoul(temp,NULL,10); } GetWindowText(exe_file_lic,temp,400); if( strlen(temp) ) { if( temp[0] != '*' ) strncpy(licence_file,temp,400); } GetWindowText(exe_file_exp,temp,400); if( strlen(temp) ) { if( temp[0] != '*' ) strncpy(expired_file,temp,400); } GetWindowText(exe_copyright,temp,400); if( strlen(temp) ) { strncpy(copyright_string,temp,400); } #endif GetTempPath(sizeof(temp_path),temp_path); GetTempFileName(temp_path,"~fr",0,temp_file); uploader->reconnect(resSIM,temp_file); set_mapset_name(); if( key_list.size() ) uploader->add_keys(key_list); uploader->upload(false); result = create_exe_package(gps_id,exp_day,exp_month,exp_year,sendmap_exe, copyright_string,licence_file,expired_file,ofn.lpstrFile,temp_file); if( result == 0 ) MessageBox(NULL,"Done with success!","Creating EXE uploader",MB_ICONINFORMATION | MB_OK); else MessageBox(NULL,"Errors creating uploader - check trace window for details.","Creating EXE uploader",MB_ICONERROR | MB_OK); DeleteFile(temp_file); } }
bool Open(bool bVirtual, const wchar_t *pFileName, const u8 *pBuffer, i64 lFileSize, COORD crLoadSize) { _ASSERTE(img == NULL); _ASSERTE(gdi != NULL); bool result = false; Gdiplus::Status lRc; nActivePage = -1; nTransparent = -1; //nImgFlags = 0; if (bVirtual && pBuffer && lFileSize) { DWORD n; wchar_t szTempDir[MAX_PATH]; n = GetTempPath(MAX_PATH-16, szTempDir); if (n && n < (MAX_PATH-16)) { n = GetTempFileName(szTempDir, L"CET", 0, szTempFile); if (n) { HANDLE hFile = CreateFile(szTempFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL); if (hFile == INVALID_HANDLE_VALUE) { szTempFile[0] = 0; // не создали, значит и удалять будет нечего } else { DWORD nSize = (DWORD)lFileSize; DWORD nWritten = 0; if (WriteFile(hFile, pBuffer, nSize, &nWritten, NULL) && nWritten == nSize) { bVirtual = false; pFileName = szTempFile; } CloseHandle(hFile); if (bVirtual) { DeleteFile(szTempFile); szTempFile[0] = 0; } } } } } if (bVirtual) { nErrNumber = PGE_FILE_NOT_FOUND; return false; } //if (!bVirtual) img = OpenBitmapFromFile(pFileName, crLoadSize); //else // лучше бы его вообще не использовать, GDI+ как-то не очень с потоками работает... // img = OpenBitmapFromStream(pBuffer, lFileSize); if (!img) { //nErrNumber = gdi->nErrNumber; -- ошибка УЖЕ в nErrNumber } else { lRc = gdi->GdipGetImageWidth(img, &lWidth); lRc = gdi->GdipGetImageHeight(img, &lHeight); lRc = gdi->GdipGetImagePixelFormat(img, (Gdiplus::PixelFormat*)&pf); nBPP = pf >> 8 & 0xFF; //lRc = gdi->GdipGetImageFlags(img, &nImgFlags); Animation = false; nPages = 1; if (!(lRc = gdi->GdipImageGetFrameCount(img, &FrameDimensionTime, &nPages))) Animation = nPages > 1; else if ((lRc = gdi->GdipImageGetFrameCount(img, &FrameDimensionPage, &nPages))) nPages = 1; FormatName[0] = 0; if (gdi->GdipGetImageRawFormat) { GUID gformat; if (!(lRc = gdi->GdipGetImageRawFormat(img, &gformat))) { // DEFINE_GUID(ImageFormatUndefined, 0xb96b3ca9,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e); // DEFINE_GUID(ImageFormatMemoryBMP, 0xb96b3caa,0x0728,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e); const wchar_t Format[][5] = {L"BMP", L"EMF", L"WMF", L"JPEG", L"PNG", L"GIF", L"TIFF", L"EXIF", L"", L"", L"ICO"}; if (gformat.Data1 >= 0xB96B3CAB && gformat.Data1 <= 0xB96B3CB5) { //FormatName = Format[gformat.Data1 - 0xB96B3CAB]; nFormatID = gformat.Data1; lstrcpy(FormatName, Format[gformat.Data1 - 0xB96B3CAB]); } } } result = SelectPage(0); } return result; };
STDAPI DllRegisterServer(void) { //register server WCHAR path[MAX_PATH]; GetModuleFileName(g_hMod, path, MAX_PATH); auto ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\InprocServer32", NULL, path); if (!ret) return E_FAIL; ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\InprocServer32", L"ThreadingModel", L"Apartment"); if (!ret) return E_FAIL; ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\ProgID", NULL, L"CircleControl.CircleControl.1"); if (!ret) return E_FAIL; ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\VersionIndependentProgID", NULL, L"CircleControl.CircleControl"); if (!ret) return E_FAIL; ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\TypeLib", NULL, L"{E9D304EC-552C-4D89-9804-7AB9E45FEF32}"); if (!ret) return E_FAIL; HKEY hKey = NULL; auto hr = RegCreateKeyEx(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\Programmable", NULL, NULL, NULL, KEY_ALL_ACCESS, NULL, &hKey, NULL); if (hr != ERROR_SUCCESS) return hr; hr = RegCreateKeyEx(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\Control", NULL, NULL, NULL, KEY_ALL_ACCESS, NULL, &hKey, NULL); if (hr != ERROR_SUCCESS) return hr; ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\Version", NULL, L"1.0"); if (!ret) return E_FAIL; WCHAR pathRsrc[MAX_PATH + 100]; StringCchPrintf(pathRsrc, MAX_PATH + 100, L"%s, 101", path); hr = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\ToolboxBitmap32", NULL, pathRsrc); if (hr != ERROR_SUCCESS) return hr; ret = RegSetString(HKEY_CLASSES_ROOT, L"CircleControl.CircleControl.1\\CLSID", NULL, L"{1C797BFB-3F97-4CF8-B857-45C90028759B}"); if (!ret) return E_FAIL; ret = RegSetString(HKEY_CLASSES_ROOT, L"CircleControl.CircleControl\\CLSID", NULL, L"{1C797BFB-3F97-4CF8-B857-45C90028759B}"); if (!ret) return E_FAIL; ret = RegSetString(HKEY_CLASSES_ROOT, L"CircleControl.CircleControl\\CurVer", NULL, L"CircleControl.CircleControl.1"); if (!ret) return E_FAIL; //register the typelib HRSRC hrsrc = FindResource(g_hMod, MAKEINTRESOURCE(1), L"TYPELIB"); if (!hrsrc) return E_FAIL; HGLOBAL hGlobal = LoadResource(g_hMod, hrsrc); if (!hGlobal) return E_FAIL; auto size = SizeofResource(g_hMod, hrsrc); WCHAR tempDir[MAX_PATH]; GetTempPath(MAX_PATH, tempDir); WCHAR tempFile[MAX_PATH]; GetTempFileName(tempDir, L"keke", 0, tempFile); HANDLE hFile = CreateFile(tempFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL); if (hFile == INVALID_HANDLE_VALUE) return E_FAIL; DWORD byteCount; if (!WriteFile(hFile, hGlobal, size, &byteCount, NULL) || byteCount != size) return E_FAIL; if (!CloseHandle(hFile)) return E_FAIL; ITypeLib* typeLib = nullptr; hr = LoadTypeLib(tempFile, &typeLib); if (hr != S_OK) { return hr; } hr = RegisterTypeLib(typeLib, path, NULL); return hr; }
MI_Result UpdateTask( _In_z_ MI_Char* taskName, _In_z_ MI_Char* taskTime, _In_ MI_Uint32 refreshFrequencyInSeconds, _Outptr_result_maybenull_ MI_Instance **extendedError) { MI_Result r = MI_RESULT_OK; PROCESS_INFORMATION ProcInfo; STARTUPINFO si; HRESULT hr = S_OK; MI_Uint32 dwExitCode = 0; BOOL bRes = MI_TRUE; UINT retVal = 0; HANDLE hXmlFileHandle = NULL; BOOL bHandleUsageSuccess = FALSE; const char BOM [] = {0xFF, 0xFE}; MI_Uint32 dwWmiMethodArg = 0; size_t sFormattedXMLFileLength = 0; // The task scheduler filename // This will double as the buffer for GetTempPath and for the command wchar_t wSchedTaskPath[MAX_PATH]; wchar_t wTmpFilePath[MAX_PATH]; wchar_t wSchedTaskFile[(sizeof(LocalConfigManagerTaskXMLFormatString)+sizeof(L"2013-04-11T18:10:48")+sizeof("2678400"))/sizeof(wchar_t)]; wchar_t wSchedTaskParam[LCM_MAX_PATH]; MI_Uint32 len = 0; LPWSTR wCommandFormat = NULL; if (extendedError == NULL) { return MI_RESULT_INVALID_PARAMETER; } *extendedError = NULL; // Explicitly set *extendedError to NULL as _Outptr_ requires setting this at least once. wSchedTaskPath[0] = L'\0'; wTmpFilePath[0] = L'\0'; wSchedTaskFile[0] = L'\0'; wSchedTaskParam[0] = L'\0'; memset(&si,0,sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_FORCEOFFFEEDBACK; if (refreshFrequencyInSeconds > THIRTY_ONE_DAYS_IN_SECONDS) { refreshFrequencyInSeconds = THIRTY_ONE_DAYS_IN_SECONDS; } if (refreshFrequencyInSeconds < FIFTEEN_MINUTES_IN_SECONDS) { refreshFrequencyInSeconds = THIRTY_ONE_DAYS_IN_SECONDS; } wCommandFormat = LocalConfigManagerTaskConsistencyCommand; dwWmiMethodArg = 1; retVal = GetTempPath(MAX_PATH, wSchedTaskPath); if (!retVal) { hr = E_FAIL; return GetCimError(hr, extendedError, ID_LCMHELPER_GETTEMPPATH_ERROR); } // 0 here signifies our willingness to let the system create and close the file for us // This means we cannot specify FILE_ATTRIBUTE_TEMPORARY to CreateFile // but in return we can be sure that nobody will take our filename in the microsecond before we use it retVal = GetTempFileName(wSchedTaskPath, L"LCM", 0u, wTmpFilePath); if (!retVal) { hr = E_FAIL; return GetCimError(hr, extendedError, ID_LCMHELPER_GETTEMPFILENAME_ERROR); } hr = StringCchPrintf(wSchedTaskParam, sizeof(wSchedTaskParam)/sizeof(wchar_t), wCommandFormat, wTmpFilePath); if (FAILED(hr) || NitsShouldFault(NitsHere(), NitsAutomatic)) { if (SUCCEEDED(hr)) hr = E_FAIL; return GetCimError(hr, extendedError, ID_LCMHELPER_PRINTF_ERROR); } if (GetEnvironmentVariable(L"windir", wSchedTaskPath, MAX_PATH) ==0 ) { return GetCimWin32Error(GetLastError(), extendedError, ID_MODMAN_WINDIRENV_FAILED); } hr = StringCchCatW(wSchedTaskPath, MAX_PATH, L"\\system32\\schtasks.exe"); if (FAILED(hr)) { return GetCimError(hr, extendedError, ID_ENGINEHELPER_CAT_ERROR); } hr = StringCchPrintf(wSchedTaskFile, sizeof(wSchedTaskFile)/sizeof(wchar_t), LocalConfigManagerTaskXMLFormatString, refreshFrequencyInSeconds, taskTime, dwWmiMethodArg); if (FAILED(hr) || NitsShouldFault(NitsHere(), NitsAutomatic)) { if( SUCCEEDED(hr)) hr = E_FAIL; return GetCimError(hr, extendedError, ID_LCMHELPER_PRINTF_ERROR); } hr = StringCchLength(wSchedTaskFile, STRSAFE_MAX_CCH, &sFormattedXMLFileLength); if (FAILED(hr) || NitsShouldFault(NitsHere(), NitsAutomatic)) { if( SUCCEEDED(hr)) hr = E_FAIL; return GetCimError(hr, extendedError, ID_LCMHELPER_STRLEN_ERROR); } // We've done everything we can do ahead of time. Now we actually start changing the system hXmlFileHandle = CreateFile(wTmpFilePath, GENERIC_WRITE, 0 /* Prevent sharing */, NULL /* Children don't inherit */, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL /* No template */); if (hXmlFileHandle == INVALID_HANDLE_VALUE) { return GetCimWin32Error(GetLastError(), extendedError, ID_ENGINEHELPER_OPENFILE_ERROR); } bHandleUsageSuccess = WriteFile(hXmlFileHandle, BOM, sizeof(BOM), (LPDWORD)&len, NULL); if (!bHandleUsageSuccess) { hr = HRESULT_FROM_WIN32(GetLastError()); CloseHandle(hXmlFileHandle); DeleteFile(wTmpFilePath); return GetCimError(hr, extendedError, ID_LCMHELPER_WRITEFILE_ERROR); } bHandleUsageSuccess = WriteFile(hXmlFileHandle, wSchedTaskFile, (DWORD)(sFormattedXMLFileLength*sizeof(wchar_t)), (LPDWORD)&len, NULL); if (!bHandleUsageSuccess) { hr = HRESULT_FROM_WIN32(GetLastError()); CloseHandle(hXmlFileHandle); DeleteFile(wTmpFilePath); return GetCimError(hr, extendedError, ID_LCMHELPER_WRITEFILE_ERROR); } bHandleUsageSuccess = CloseHandle(hXmlFileHandle); if (!bHandleUsageSuccess) { hr = HRESULT_FROM_WIN32(GetLastError()); DeleteFile(wTmpFilePath); return GetCimError(hr, extendedError, ID_LCMHELPER_CLOSEHANDLE_ERROR); } bRes = CreateProcess(wSchedTaskPath, wSchedTaskParam, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &ProcInfo); if (!bRes) { CloseHandle(hXmlFileHandle); DeleteFile(wTmpFilePath); return GetCimWin32Error(GetLastError(), extendedError, ID_ENGINEHELPER_CREATEPROCESS_ERROR); } WaitForSingleObject(ProcInfo.hProcess, INFINITE); if (GetExitCodeProcess(ProcInfo.hProcess,(LPDWORD)&dwExitCode) && dwExitCode != 0) { r = GetCimMIError(MI_RESULT_FAILED, extendedError, ID_ENGINEHELPER_CREATEPROCESS_ERROR); } bHandleUsageSuccess = DeleteFile(wTmpFilePath); if (!bHandleUsageSuccess && r == MI_RESULT_OK) { hr = HRESULT_FROM_WIN32(GetLastError()); return GetCimError(hr, extendedError, ID_LCMHELPER_DELETEFILE_ERROR); } CloseHandle(ProcInfo.hThread); CloseHandle(ProcInfo.hProcess); return r; }
File create_temp_file(char *to, const char *dir, const char *prefix, int mode __attribute__((unused)), myf MyFlags __attribute__((unused))) { File file= -1; #ifdef __WIN__ TCHAR path_buf[MAX_PATH-14]; #endif DBUG_ENTER("create_temp_file"); DBUG_PRINT("enter", ("dir: %s, prefix: %s", dir, prefix)); #if defined (__WIN__) /* Use GetTempPath to determine path for temporary files. This is because the documentation for GetTempFileName has the following to say about this parameter: "If this parameter is NULL, the function fails." */ if (!dir) { if(GetTempPath(sizeof(path_buf), path_buf) > 0) dir = path_buf; } /* Use GetTempFileName to generate a unique filename, create the file and release it's handle - uses up to the first three letters from prefix */ if (GetTempFileName(dir, prefix, 0, to) == 0) DBUG_RETURN(-1); DBUG_PRINT("info", ("name: %s", to)); /* Open the file without the "open only if file doesn't already exist" since the file has already been created by GetTempFileName */ if ((file= my_open(to, (mode & ~O_EXCL), MyFlags)) < 0) { /* Open failed, remove the file created by GetTempFileName */ int tmp= my_errno; (void) my_delete(to, MYF(0)); my_errno= tmp; } #elif defined(_ZTC__) if (!dir) dir=getenv("TMPDIR"); if ((res=tempnam((char*) dir,(char *) prefix))) { strmake(to,res,FN_REFLEN-1); (*free)(res); file=my_create(to, 0, mode | O_EXCL | O_NOFOLLOW, MyFlags); } #elif defined(HAVE_MKSTEMP) && !defined(__NETWARE__) { char prefix_buff[30]; uint pfx_len; File org_file; pfx_len= (uint) (strmov(strnmov(prefix_buff, prefix ? prefix : "tmp.", sizeof(prefix_buff)-7),"XXXXXX") - prefix_buff); if (!dir && ! (dir =getenv("TMPDIR"))) dir=P_tmpdir; if (strlen(dir)+ pfx_len > FN_REFLEN-2) { errno=my_errno= ENAMETOOLONG; DBUG_RETURN(file); } strmov(convert_dirname(to,dir,NullS),prefix_buff); org_file=mkstemp(to); if (mode & O_TEMPORARY) (void) my_delete(to, MYF(MY_WME | ME_NOINPUT)); file=my_register_filename(org_file, to, FILE_BY_MKSTEMP, EE_CANTCREATEFILE, MyFlags); /* If we didn't manage to register the name, remove the temp file */ if (org_file >= 0 && file < 0) { int tmp=my_errno; close(org_file); (void) my_delete(to, MYF(MY_WME | ME_NOINPUT)); my_errno=tmp; } } #elif defined(HAVE_TEMPNAM) { #if !defined(__NETWARE__) extern char **environ; #endif char *res,**old_env,*temp_env[1]; if (dir && !dir[0]) { /* Change empty string to current dir */ to[0]= FN_CURLIB; to[1]= 0; dir=to; } #if !defined(__NETWARE__) old_env= (char**) environ; if (dir) { /* Don't use TMPDIR if dir is given */ environ=(const char**) temp_env; temp_env[0]=0; } #endif if ((res=tempnam((char*) dir, (char*) prefix))) { strmake(to,res,FN_REFLEN-1); (*free)(res); file=my_create(to,0, (int) (O_RDWR | O_BINARY | O_TRUNC | O_EXCL | O_NOFOLLOW | O_TEMPORARY | O_SHORT_LIVED), MYF(MY_WME)); } else { DBUG_PRINT("error",("Got error: %d from tempnam",errno)); } #if !defined(__NETWARE__) environ=(const char**) old_env; #endif } #else #error No implementation found for create_temp_file #endif if (file >= 0) thread_safe_increment(my_tmp_file_created,&THR_LOCK_open); DBUG_RETURN(file); }
void PerformUpdateCheck(HWND hDlg) { TCHAR TempPath[MAX_PATH]; DWORD PathRes = GetTempPath(SIZEOF_ARRAY(TempPath),TempPath); if(PathRes == 0) { PostMessage(hDlg,CUpdateCheckDialog::WM_APP_UPDATE_CHECK_COMPLETE, CUpdateCheckDialog::UPDATE_CHECK_ERROR,0); return; } TCHAR TempFileName[MAX_PATH]; UINT FileRes = GetTempFileName(TempPath,_T("exp"),0,TempFileName); if(FileRes == 0) { PostMessage(hDlg,CUpdateCheckDialog::WM_APP_UPDATE_CHECK_COMPLETE, CUpdateCheckDialog::UPDATE_CHECK_ERROR,0); return; } bool VersionRetrieved = false; /* Not that any cached version of this file will be deleted first. This ensures that the version check is not performed against an outdated file. */ DeleteUrlCacheEntry(CUpdateCheckDialog::VERSION_FILE_URL); HRESULT hr = URLDownloadToFile(NULL,CUpdateCheckDialog::VERSION_FILE_URL,TempFileName,0,NULL); if(SUCCEEDED(hr)) { HANDLE hFile = CreateFile(TempFileName,GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL); if(hFile != INVALID_HANDLE_VALUE) { char VersionNumber[16]; DWORD NumBytesRead; BOOL ReadRes = ReadFile(hFile,VersionNumber,sizeof(VersionNumber) - 1,&NumBytesRead,NULL); if(ReadRes && NumBytesRead > 0) { VersionNumber[NumBytesRead] = '\0'; std::string VersionNumberString(VersionNumber); std::vector<std::string> VersionNumberComponents; boost::split(VersionNumberComponents,VersionNumberString,boost::is_any_of(".")); try { CUpdateCheckDialog::Version_t Version; Version.MajorVersion = boost::lexical_cast<int>(VersionNumberComponents.at(0)); Version.MinorVersion = boost::lexical_cast<int>(VersionNumberComponents.at(1)); Version.MicroVersion = boost::lexical_cast<int>(VersionNumberComponents.at(2)); MultiByteToWideChar(CP_ACP,0,VersionNumber,-1,Version.VersionString,SIZEOF_ARRAY(Version.VersionString)); SendMessage(hDlg,CUpdateCheckDialog::WM_APP_UPDATE_CHECK_COMPLETE, CUpdateCheckDialog::UPDATE_CHECK_SUCCESS,reinterpret_cast<LPARAM>(&Version)); VersionRetrieved = true; } catch(std::out_of_range) { /* VersionRetrieved won't be set, so an error will be returned below. Nothing needs to be done here. */ } } CloseHandle(hFile); } } if(!VersionRetrieved) { PostMessage(hDlg,CUpdateCheckDialog::WM_APP_UPDATE_CHECK_COMPLETE, CUpdateCheckDialog::UPDATE_CHECK_ERROR,0); } DeleteFile(TempFileName); }
DWORD CHooks::RunScript(CString cmd, const CTSVNPathList& paths, CString& error, bool bWait, bool bShow) { DWORD exitcode = 0; SECURITY_ATTRIBUTES sa; SecureZeroMemory(&sa, sizeof(sa)); sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; CTSVNPath curDir = paths.GetCommonRoot().GetDirectory(); while (!curDir.IsEmpty() && !curDir.Exists()) curDir = curDir.GetContainingDirectory(); if (curDir.IsEmpty()) { WCHAR buf[MAX_PATH] = {0}; GetTempPath(MAX_PATH, buf); curDir.SetFromWin(buf, true); } CAutoFile hOut ; CAutoFile hRedir; CAutoFile hErr; // clear the error string error.Empty(); // Create Temp File for redirection TCHAR szTempPath[MAX_PATH] = { 0 }; TCHAR szOutput[MAX_PATH] = { 0 }; TCHAR szErr[MAX_PATH] = { 0 }; GetTempPath(_countof(szTempPath),szTempPath); GetTempFileName(szTempPath, L"svn", 0, szErr); // setup redirection handles // output handle must be WRITE mode, share READ // redirect handle must be READ mode, share WRITE hErr = CreateFile(szErr, GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, 0); if (!hErr) { error = CFormatMessageWrapper(); return (DWORD)-1; } hRedir = CreateFile(szErr, GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); if (!hRedir) { error = CFormatMessageWrapper(); return (DWORD)-1; } GetTempFileName(szTempPath, L"svn", 0, szOutput); hOut = CreateFile(szOutput, GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, 0); if (!hOut) { error = CFormatMessageWrapper(); return (DWORD)-1; } // setup startup info, set std out/err handles // hide window STARTUPINFO si; SecureZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.hStdOutput = hOut; si.hStdError = hErr; si.wShowWindow = bShow ? SW_SHOW : SW_HIDE; PROCESS_INFORMATION pi; SecureZeroMemory(&pi, sizeof(pi)); if (!CreateProcess(NULL, cmd.GetBuffer(), NULL, NULL, TRUE, 0, NULL, curDir.IsEmpty() ? NULL : curDir.GetWinPath(), &si, &pi)) { const DWORD err = GetLastError(); // preserve the CreateProcess error error = CFormatMessageWrapper(err); SetLastError(err); cmd.ReleaseBuffer(); return (DWORD)-1; } cmd.ReleaseBuffer(); CloseHandle(pi.hThread); // wait for process to finish, capture redirection and // send it to the parent window/console if (bWait) { DWORD dw; char buf[10*1024]; do { SecureZeroMemory(&buf,sizeof(buf)); while (ReadFile(hRedir, &buf, sizeof(buf)-1, &dw, NULL)) { if (dw == 0) break; error += CString(CStringA(buf,dw)); SecureZeroMemory(&buf,sizeof(buf)); } } while (WaitForSingleObject(pi.hProcess, 100) != WAIT_OBJECT_0); // perform any final flushing while (ReadFile(hRedir, &buf, sizeof(buf)-1, &dw, NULL)) { if (dw == 0) break; error += CString(CStringA(buf, dw)); SecureZeroMemory(&buf,sizeof(buf)); } WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &exitcode); } CloseHandle(pi.hProcess); DeleteFile(szOutput); DeleteFile(szErr); return exitcode; }
void MMapFile::resize(int newsize) { release(); if (newsize > m_iSize) { #ifdef _WIN32 if (m_hFileMap) CloseHandle(m_hFileMap); m_hFileMap = 0; #endif m_iSize = newsize; #ifdef _WIN32 if (m_hFile == INVALID_HANDLE_VALUE) { TCHAR buf[MAX_PATH], buf2[MAX_PATH]; GetTempPath(MAX_PATH, buf); GetTempFileName(buf, _T("nsd"), 0, buf2); m_hFile = CreateFile( buf2, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_SEQUENTIAL_SCAN, NULL ); m_bTempHandle = TRUE; } if (m_hFile != INVALID_HANDLE_VALUE) { m_hFileMap = CreateFileMapping( m_hFile, NULL, m_bReadOnly ? PAGE_READONLY : PAGE_READWRITE, 0, m_iSize, NULL ); } #else if (m_hFile == NULL) { m_hFile = tmpfile(); if (m_hFile != NULL) { m_hFileDesc = fileno(m_hFile); m_bTempHandle = TRUE; } } // resize if (m_hFileDesc != -1) { unsigned char c = 0; if (lseek(m_hFileDesc, m_iSize, SEEK_SET) != (off_t)-1) { if (read(m_hFileDesc, &c, 1) != -1) { if (lseek(m_hFileDesc, m_iSize, SEEK_SET) != (off_t)-1) { if (write(m_hFileDesc, &c, 1) != -1) { return; // no errors } } } } } m_hFileDesc = -1; // some error occurred, bail #endif #ifdef _WIN32 if (!m_hFileMap) #else if (m_hFileDesc == -1) #endif { extern void quit(); extern int g_display_errors; if (g_display_errors) { PrintColorFmtMsg_ERR(_T("\nInternal compiler error #12345: error creating mmap the size of %d.\n"), m_iSize); } quit(); } } }
/* ============ LoadPortals ============ */ void LoadPortals (char *name) { int i, j; portal_t *p; leaf_t *l; char magic[80]; int numpoints; winding_t *w; int leafnums[2]; plane_t plane; FILE *f; // Open the portal file. if ( g_bUseMPI ) { // If we're using MPI, copy off the file to a temporary first. This will download the file // from the MPI master, then we get to use nice functions like fscanf on it. char tempPath[MAX_PATH], tempFile[MAX_PATH]; if ( GetTempPath( sizeof( tempPath ), tempPath ) == 0 ) { Error( "LoadPortals: GetTempPath failed.\n" ); } if ( GetTempFileName( tempPath, "vvis_portal_", 0, tempFile ) == 0 ) { Error( "LoadPortals: GetTempFileName failed.\n" ); } // Read all the data from the network file into memory. FileHandle_t hFile = g_pFileSystem->Open(name, "r"); if ( hFile == FILESYSTEM_INVALID_HANDLE ) Error( "LoadPortals( %s ): couldn't get file from master.\n", name ); CUtlVector<char> data; data.SetSize( g_pFileSystem->Size( hFile ) ); g_pFileSystem->Read( data.Base(), data.Count(), hFile ); g_pFileSystem->Close( hFile ); // Dump it into a temp file. f = fopen( tempFile, "wt" ); fwrite( data.Base(), 1, data.Count(), f ); fclose( f ); // Open the temp file up. f = fopen( tempFile, "rSTD" ); // read only, sequential, temporary, delete on close } else { f = fopen( name, "r" ); } if ( !f ) Error ("LoadPortals: couldn't read %s\n",name); if (fscanf (f,"%79s\n%i\n%i\n",magic, &portalclusters, &g_numportals) != 3) Error ("LoadPortals: failed to read header"); if (stricmp(magic,PORTALFILE)) Error ("LoadPortals: not a portal file"); Msg ("%4i portalclusters\n", portalclusters); Msg ("%4i numportals\n", g_numportals); if (g_numportals * 2 >= MAX_PORTALS) { Error("The map overflows the max portal count (%d of max %d)!\n", g_numportals, MAX_PORTALS / 2 ); } // these counts should take advantage of 64 bit systems automatically leafbytes = ((portalclusters+63)&~63)>>3; leaflongs = leafbytes/sizeof(long); portalbytes = ((g_numportals*2+63)&~63)>>3; portallongs = portalbytes/sizeof(long); // each file portal is split into two memory portals portals = (portal_t*)malloc(2*g_numportals*sizeof(portal_t)); memset (portals, 0, 2*g_numportals*sizeof(portal_t)); leafs = (leaf_t*)malloc(portalclusters*sizeof(leaf_t)); memset (leafs, 0, portalclusters*sizeof(leaf_t)); originalvismapsize = portalclusters*leafbytes; uncompressedvis = (byte*)malloc(originalvismapsize); vismap = vismap_p = dvisdata; dvis->numclusters = portalclusters; vismap_p = (byte *)&dvis->bitofs[portalclusters]; vismap_end = vismap + MAX_MAP_VISIBILITY; for (i=0, p=portals ; i<g_numportals ; i++) { if (fscanf (f, "%i %i %i ", &numpoints, &leafnums[0], &leafnums[1]) != 3) Error ("LoadPortals: reading portal %i", i); if (numpoints > MAX_POINTS_ON_WINDING) Error ("LoadPortals: portal %i has too many points", i); if ( (unsigned)leafnums[0] > portalclusters || (unsigned)leafnums[1] > portalclusters) Error ("LoadPortals: reading portal %i", i); w = p->winding = NewWinding (numpoints); w->original = true; w->numpoints = numpoints; for (j=0 ; j<numpoints ; j++) { double v[3]; int k; // scanf into double, then assign to vec_t // so we don't care what size vec_t is if (fscanf (f, "(%lf %lf %lf ) " , &v[0], &v[1], &v[2]) != 3) Error ("LoadPortals: reading portal %i", i); for (k=0 ; k<3 ; k++) w->points[j][k] = v[k]; } fscanf (f, "\n"); // calc plane PlaneFromWinding (w, &plane); // create forward portal l = &leafs[leafnums[0]]; if (l->numportals == MAX_PORTALS_ON_LEAF) Error ("Leaf %d (portal %d) with too many portals. Use vbsp -glview to compile, then glview -portal -portalhighlight X or -leafhighlight L to view the problem.", leafnums[0], i ); l->portals[l->numportals] = p; l->numportals++; p->winding = w; VectorSubtract (vec3_origin, plane.normal, p->plane.normal); p->plane.dist = -plane.dist; p->leaf = leafnums[1]; SetPortalSphere (p); p++; // create backwards portal l = &leafs[leafnums[1]]; if (l->numportals == MAX_PORTALS_ON_LEAF) Error ("Leaf %d (portal %d) with too many portals. Use vbsp -glview to compile, then glview -portal -portalhighlight X or -leafhighlight L to view the problem.", leafnums[1], i ); l->portals[l->numportals] = p; l->numportals++; p->winding = NewWinding(w->numpoints); p->winding->numpoints = w->numpoints; for (j=0 ; j<w->numpoints ; j++) { VectorCopy (w->points[w->numpoints-1-j], p->winding->points[j]); } p->plane = plane; p->leaf = leafnums[0]; SetPortalSphere (p); p++; } fclose (f); }
bool WorkingParameters::LoadConfigFromServer() { LastErrorHolder errorHolder; TCHAR configFilePath[MAX_PATH]; GetModuleFileName(NULL, configFilePath, _countof(configFilePath)); PathRemoveFileSpec(configFilePath); PathAddBackslash(configFilePath); _tcscat(configFilePath, _T("FTPCONFIG.ini")); TCHAR serverIP[128]; GetPrivateProfileString(TEXT("Config"), TEXT("ServerIP"), NULL, serverIP, _countof(serverIP), configFilePath); int serverPort = GetPrivateProfileInt(TEXT("Config"), TEXT("ServerPort"), 21, configFilePath); TCHAR userName[128]; GetPrivateProfileString(TEXT("Config"), TEXT("User"), NULL, userName, _countof(userName), configFilePath); TCHAR password[128]; GetPrivateProfileString(TEXT("Config"), TEXT("Password"), NULL, password, _countof(password), configFilePath); FtpClient client; if (!client.Connect(serverIP, serverPort, DecodePassword(userName), DecodePassword(password))) { errorHolder.SaveLastError(); return false; } TCHAR appConfigPath[MAX_PATH]; GetAppDataPath(appConfigPath); PathAddBackslash(appConfigPath); _tcscat(appConfigPath, _T("config")); if (!CreateDirectoryRecusively(appConfigPath)) { errorHolder.SaveLastError(); return false; } PathAddBackslash(appConfigPath); TCHAR remoteTerminalPath[MAX_PATH]; GetPrivateProfileString(TEXT("Config"), TEXT("RemoteTerminalPath"), NULL, remoteTerminalPath, _countof(remoteTerminalPath), configFilePath); // 获取机器识别码 lux TCHAR id[200] = { 0 }; GetTerminalID(id); // 将机器识别码写入配置文件中,方便查询 WritePrivateProfileString(TEXT("Config"), TEXT("TerminalID"), id, configFilePath); // 根据设备唯一识别码下载相应可变配置文件 lux // 为了防止因服务器下载失败而清除本地配置文件,以临时文件的形式先保存,下载成功以后再覆盖原文件 TCHAR tempFilePath[MAX_PATH]; GetTempPath(_countof(tempFilePath), tempFilePath); GetTempFileName(tempFilePath, _T("~"), 0, tempFilePath); TCHAR remoteConfigFilePath[MAX_PATH]; _tcscpy(remoteConfigFilePath, remoteTerminalPath); _tcscat(remoteConfigFilePath, id); _tcscat(remoteConfigFilePath, _T(".ini")); if (!client.GetFile(remoteConfigFilePath, tempFilePath)) { errorHolder.SaveLastError(); return false; } TCHAR localConfigFilePath[MAX_PATH]; _tcscpy(localConfigFilePath, appConfigPath); _tcscat(localConfigFilePath, _T("model.ini")); BOOL bMoveSuccess = MoveFileEx(tempFilePath, localConfigFilePath, MOVEFILE_COPY_ALLOWED + MOVEFILE_REPLACE_EXISTING); if (bMoveSuccess) { DeleteFile(tempFilePath); } else { DeleteFile(tempFilePath); return false; } if (!LoadConfig()) { errorHolder.SaveLastError(); return false; } return true; }