string FileBrowser::mGetFileFTPLongDescription(string file) { string out = ""; struct stat statFileStatus; string fullFilePath = GetCurrentPath() + "\\" + file; stat(fullFilePath.c_str(),&statFileStatus); DWORD attr = GetFileAttributes(fullFilePath.c_str()); char execute = 'x'; char read = 'r'; char write = 'w'; char directory = '-'; if(attr&FILE_ATTRIBUTE_DIRECTORY) { directory = '-'; directory = 'd'; } if(attr&FILE_ATTRIBUTE_ARCHIVE ) { execute = '-'; } if(attr&FILE_ATTRIBUTE_READONLY ) { write = '-'; } if(attr&FILE_ATTRIBUTE_DEVICE ) { read = '-'; } char timeStr[ 100 ] = ""; struct tm locTime; int retval = localtime_s(&locTime, &statFileStatus.st_mtime); if(retval) { retval = localtime_s(&locTime, &statFileStatus.st_atime); } if(retval) { retval = localtime_s(&locTime, &statFileStatus.st_ctime); } if(retval) { time_t t; time(&t); retval = localtime_s(&locTime, &t); } /* SYSTEMTIME stCutoff; GetSystemTime(&stCutoff); stCutoff.wYear--; if (locTime.tm_year+1900 > stCutoff.wYear || (locTime.tm_year+1900 == stCutoff.wYear && locTime.tm_mon > stCutoff.wMonth) || (locTime.tm_year+1900 == stCutoff.wYear && locTime.tm_mon == stCutoff.wMonth && locTime.tm_mday > stCutoff.wDay)) { strftime(timeStr, 100, "%b %d %Y", &locTime); } else {*/ strftime(timeStr, 100, "%b %d %H:%M", &locTime); // } out= sprintfa("%c%c%c%c%c%c%c%c%c%c 1 root root %d %s %s\r\n",directory,read,write,execute,read,write,execute,read,write,execute,statFileStatus.st_size,timeStr,file.c_str()); return out; }
int sl_file_exists(sl_vm_t* vm, char* path) { DWORD dwAttrib = GetFileAttributes(sl_realpath(vm, path)); return (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); }
/* ======================================================================================================================= Map_SaveFile ======================================================================================================================= */ bool Map_SaveFile(const char *filename, bool use_region, bool autosave) { entity_t *e, *next; idStr temp; int count; brush_t *b; idStr status; int len = strlen(filename); WIN32_FIND_DATA FileData; if (FindFirstFile(filename, &FileData) != INVALID_HANDLE_VALUE) { // the file exists; if (len > 0 && GetFileAttributes(filename) & FILE_ATTRIBUTE_READONLY) { g_pParentWnd->MessageBox("File is read only", "Read Only", MB_OK); return false; } } if (filename == NULL || len == 0 || (filename && stricmp(filename, "unnamed.map") == 0)) { CFileDialog dlgSave(FALSE,"map",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"Map Files (*.map)|*.map||",AfxGetMainWnd()); if (dlgSave.DoModal() == IDOK) { filename = dlgSave.m_ofn.lpstrFile; strcpy(currentmap, filename); } else { return false; } } MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); if (statex.dwMemoryLoad > 95) { g_pParentWnd->MessageBox("Physical memory is over 95% utilized. Consider saving and restarting", "Memory"); } CWaitDlg dlg; Pointfile_Clear(); temp = filename; temp.BackSlashesToSlashes(); if (!use_region) { idStr backup; backup = temp; backup.StripFileExtension(); backup.SetFileExtension(".bak"); if (_unlink(backup) != 0 && errno != 2) { // errno 2 means the file doesn't exist, which we don't care about g_pParentWnd->MessageBox(va("Unable to delete %s: %s", backup.c_str(), strerror(errno)), "File Error"); } if (rename(filename, backup) != 0) { g_pParentWnd->MessageBox(va("Unable to rename %s to %s: %s", filename, backup.c_str(), strerror(errno)), "File Error"); } } common->Printf("Map_SaveFile: %s\n", filename); idStr mapFile; bool localFile = (strstr(filename, ":") != NULL); if (autosave || localFile) { mapFile = filename; } else { mapFile = fileSystem->OSPathToRelativePath(filename); } if (use_region) { AddRegionBrushes(); } idMapFile map; world_entity->origin.Zero(); idMapEntity *mapentity = EntityToMapEntity(world_entity, use_region, &dlg); dlg.SetText("Saving worldspawn..."); map.AddEntity(mapentity); if (use_region) { idStr buf; sprintf(buf, "{\n\"classname\" \"info_player_start\"\n\"origin\"\t \"%i %i %i\"\n\"angle\"\t \"%i\"\n}\n", (int)g_pParentWnd->GetCamera()->Camera().origin[0], (int)g_pParentWnd->GetCamera()->Camera().origin[1], (int)g_pParentWnd->GetCamera()->Camera().origin[2], (int)g_pParentWnd->GetCamera()->Camera().angles[YAW]); idLexer src(LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS | LEXFL_ALLOWPATHNAMES); src.LoadMemory(buf, buf.Length(), "regionbuf"); idMapEntity *playerstart = idMapEntity::Parse(src); map.AddEntity(playerstart); } count = -1; for (e = entities.next; e != &entities; e = next) { count++; next = e->next; if (e->brushes.onext == &e->brushes) { Entity_Free(e); // no brushes left, so remove it } else { if (use_region) { for (b = e->brushes.onext; b != &e->brushes; b = b->onext) { if (!Map_IsBrushFiltered(b)) { break; // got one } } if (b == &e->brushes) { continue; // nothing visible } } idVec3 origin; if (!GetVectorForKey(e, "origin", origin)) { idStr text; VectorSubtract(e->brushes.onext->mins, e->eclass->mins, origin); sprintf(text, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]); SetKeyValue(e, "origin", text); } if (use_region && !idStr::Icmp(ValueForKey(e, "classname"), "info_player_start")) { continue; } idStr classname = e->epairs.GetString("classname"); sprintf(status, "Saving entity %i (%s)...", count, classname.c_str()); dlg.SetText(status); map.AddEntity(EntityToMapEntity(e, use_region, &dlg)); count++; } } mapFile.StripFileExtension(); idStr mapExt = (use_region) ? ".reg" : ".map"; sprintf(status, "Writing file %s.%s...", mapFile.c_str(), mapExt.c_str()); dlg.SetText(status); map.Write(mapFile, mapExt, !(autosave || localFile)); mapModified = 0; if (use_region) { RemoveRegionBrushes(); } if (!strstr(temp, "autosave")) { Sys_SetTitle(temp); } Sys_Status("Saved.\n", 0); return true; }
int AddFile(wchar_t *fileName, wchar_t *path, int &index) { index = 0; if (!fileName || !fileName[0]) return -2; wchar_t *name2 = wcsdup(fileName); if (!name2) return -2; int l = (int)wcslen(name2); /*int pos = 0; while (fileName[pos]) { if (fileName[pos] == '/') fileName[pos] = '\\' l++; pos++; }//*/ if (fileName[0] == '<') { if (fileName[l-1] != '>') { return -2; } int l2 = 0; if (path) l2 = (int)wcslen(path); memcpy(name2, fileName+1, l * 2 - 4); name2[l-2] = 0; wchar_t *name = (wchar_t*) malloc(sizeof(wchar_t) * (l + 30)); if (name) { wsprintf(name, L"Override\\%s", name2); if (GetFileAttributes(name) == INVALID_FILE_ATTRIBUTES) { wsprintf(name, L"Include\\%s", name2); } free(name2); name2=name; l = (int)wcslen(name2); } //wchar_t *test = ResolvePath(path, name2); } else { if (fileName[0] == '\"') { if (l<=3 || fileName[l-1] != '\"') { free(name2); return -2; } l-=2; fileName++; memcpy(name2, fileName, l * 2); name2[l] = 0; } if (name2[1] != ':' && name2[0] != '\\') { wchar_t *w = wcsrchr(path, '\\'); int l2 = 1+(int)(w - path); if (!srealloc(name2, 2*(l2 + l + 2))) { free(name2); return -2; } memmove(name2 + l2, name2, 2*l+2); memcpy(name2, path, 2*l2); l+=l2+2; } } int q = GetFullPathName(name2, 0, 0, 0); wchar_t *nnew; if (q<=0 || !(nnew = (wchar_t*) malloc(q*sizeof(wchar_t)))) { free(name2); return -2; } int q2 = GetFullPathName(name2, q, nnew, 0); free(name2); if (q2 <= 0 || q2 >= q) { free(nnew); return -2; } name2 = nnew; q2 = GetLongPathName(nnew, 0, 0); if (q2 > 0 && (nnew = (wchar_t*)malloc(q2*sizeof(wchar_t)))) { if ((q = GetLongPathName(name2, nnew, q2)) >0 && q<q2) { free(name2); name2 = nnew; } else { free(nnew); } } /* //name2 = ResolvePathSteal(name2); if (name2[2] == '?') { l = (int) wcslen(name2); if (l < MAX_PATH+4) memmove(name2, name2 + 4, 2*(l - 3)); } int i = GetLongPathName(name2, 0, 0); if (i <= 0 || !(fileName = (wchar_t*) malloc(i*2+2))) { free(name2); return -2; } int w = i; i = GetLongPathName(name2, fileName, w); free(name2); if (i+1 != w) { free(fileName); return -2; } //*/ int i; for (i=0; i<numFiles; i++) { if (!wcsicmp(files[i].name, name2)) break; } if (i != numFiles) { free(name2); index = i; return files[i].loaded; } if (srealloc(files, sizeof(FileInfo)*(numFiles+1))) { index = numFiles; files[numFiles].name = name2; files[numFiles++].loaded = -1; return -1; } free(name2); return -2; }
/* IsDirectory * ---------------------------------------------------------------------------- */ static BOOL IsDirectory(CString lpszName) { DWORD dwRet; dwRet = GetFileAttributes(lpszName); return (dwRet != 0xFFFFFFFF) && (dwRet & FILE_ATTRIBUTE_DIRECTORY); }
/* * User pressed the install button. Make it go. */ void CBINDInstallDlg::OnInstall() { #if _MSC_VER >= 1400 char Vcredist_x86[MAX_PATH]; #endif BOOL success = FALSE; int oldlen; if (CheckBINDService()) StopBINDService(); InstallTags(); UpdateData(); if (!m_toolsOnly && m_accountName != LOCAL_SERVICE) { /* * Check that the Passwords entered match. */ if (m_accountPassword != m_accountPasswordConfirm) { MsgBox(IDS_ERR_PASSWORD); return; } /* * Check that there is not leading / trailing whitespace. * This is for compatibility with the standard password dialog. * Passwords really should be treated as opaque blobs. */ oldlen = m_accountPassword.GetLength(); m_accountPassword.TrimLeft(); m_accountPassword.TrimRight(); if (m_accountPassword.GetLength() != oldlen) { MsgBox(IDS_ERR_WHITESPACE); return; } /* * Check the entered account name. */ if (ValidateServiceAccount() == FALSE) return; /* * For Registration we need to know if account was changed. */ if (m_accountName != m_currentAccount) m_accountUsed = FALSE; if (m_accountUsed == FALSE && m_serviceExists == FALSE) { /* * Check that the Password is not null. */ if (m_accountPassword.GetLength() == 0) { MsgBox(IDS_ERR_NULLPASSWORD); return; } } } else if (m_accountName == LOCAL_SERVICE) { /* The LocalService always exists. */ m_accountExists = TRUE; if (m_accountName != m_currentAccount) m_accountUsed = FALSE; } /* Directories */ m_etcDir = m_targetDir + "\\etc"; m_binDir = m_targetDir + "\\bin"; if (m_defaultDir != m_targetDir) { if (GetFileAttributes(m_targetDir) != 0xFFFFFFFF) { int install = MsgBox(IDS_DIREXIST, MB_YESNO | MB_ICONQUESTION, m_targetDir); if (install == IDNO) return; } else { int createDir = MsgBox(IDS_CREATEDIR, MB_YESNO | MB_ICONQUESTION, m_targetDir); if (createDir == IDNO) return; } } if (!m_toolsOnly) { if (m_accountExists == FALSE) { success = CreateServiceAccount(m_accountName.GetBuffer(30), m_accountPassword.GetBuffer(30)); if (success == FALSE) { MsgBox(IDS_CREATEACCOUNT_FAILED); return; } m_accountExists = TRUE; } } ProgramGroup(FALSE); #if _MSC_VER >= 1400 /* * Install Visual Studio libraries. As per: * http://blogs.msdn.com/astebner/archive/2006/08/23/715755.aspx * * Vcredist_x86.exe /q:a /c:"msiexec /i vcredist.msi /qn /l*v %temp%\vcredist_x86.log" */ /*system(".\\Vcredist_x86.exe /q:a /c:\"msiexec /i vcredist.msi /qn /l*v %temp%\vcredist_x86.log\"");*/ /* * Enclose full path to Vcredist_x86.exe in quotes as * m_currentDir may contain spaces. */ sprintf(Vcredist_x86, "\"%s\\Vcredist_x86.exe\"", (LPCTSTR) m_currentDir); system(Vcredist_x86); #endif try { CreateDirs(); CopyFiles(); if (!m_toolsOnly) RegisterService(); RegisterMessages(); HKEY hKey; /* Create a new key for named */ SetCurrent(IDS_CREATE_KEY); if (RegCreateKey(HKEY_LOCAL_MACHINE, BIND_SUBKEY, &hKey) == ERROR_SUCCESS) { // Get the install directory RegSetValueEx(hKey, "InstallDir", 0, REG_SZ, (LPBYTE)(LPCTSTR)m_targetDir, m_targetDir.GetLength()); RegCloseKey(hKey); } SetCurrent(IDS_ADD_REMOVE); if (RegCreateKey(HKEY_LOCAL_MACHINE, BIND_UNINSTALL_SUBKEY, &hKey) == ERROR_SUCCESS) { CString buf(BIND_DISPLAY_NAME); RegSetValueEx(hKey, "DisplayName", 0, REG_SZ, (LPBYTE)(LPCTSTR)buf, buf.GetLength()); buf.Format("%s\\BINDInstall.exe", m_binDir); RegSetValueEx(hKey, "UninstallString", 0, REG_SZ, (LPBYTE)(LPCTSTR)buf, buf.GetLength()); RegCloseKey(hKey); } ProgramGroup(FALSE); if (m_startOnInstall) StartBINDService(); } catch(Exception e) { MessageBox(e.resString); SetCurrent(IDS_CLEANUP); FailedInstall(); MsgBox(IDS_FAIL); return; } catch(DWORD dw) { CString msg; msg.Format("A fatal error occured\n(%s)", GetErrMessage(dw)); MessageBox(msg); SetCurrent(IDS_CLEANUP); FailedInstall(); MsgBox(IDS_FAIL); return; } SetCurrent(IDS_INSTALL_DONE); MsgBox(IDS_SUCCESS); }
// Message handler for the Main dialog box LRESULT CALLBACK MainDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { RECT rt; HWND hCurrentRadioButton; wchar_t wdirname[MAX_PATH], msg[1024], *title; int ret, valid, ntxns, written; switch (message) { case WM_INITDIALOG: // maximize the dialog. GetClientRect(GetParent(hDlg), &rt); SetWindowPos(hDlg, HWND_TOP, 0, 0, rt.right, rt.bottom, SWP_SHOWWINDOW); CheckRadioButton(hDlg, IDC_MEDIUM_RADIO, IDC_SMALL_RADIO, IDC_SMALL_RADIO); SetDlgItemText(hDlg, IDC_HOME_EDIT, tpcb->getHomeDirW(wdirname, MAX_PATH)); SetDlgItemInt(hDlg, IDC_TXN_EDIT, 1000, 0); SetWindowText(hDlg, L"BDB TPCB Example app"); ShowWindow(hDlg, SW_SHOWNORMAL); return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDC_INIT_BUTTON || LOWORD(wParam) == IDC_RUN_BUTTON ) { hCurrentRadioButton = GetDlgItem(hDlg, IDC_SMALL_RADIO); if(BST_CHECKED == SendMessage(hCurrentRadioButton, BM_GETCHECK, NULL, NULL)) { tpcb->accounts = 500; tpcb->branches = 10; tpcb->tellers = 50; tpcb->history = 5000; } hCurrentRadioButton = GetDlgItem(hDlg, IDC_MEDIUM_RADIO); if(BST_CHECKED == SendMessage(hCurrentRadioButton, BM_GETCHECK, NULL, NULL)) { tpcb->accounts = 1000; tpcb->branches = 10; tpcb->tellers = 100; tpcb->history = 10000; } hCurrentRadioButton = GetDlgItem(hDlg, IDC_LARGE_RADIO); if(BST_CHECKED == SendMessage(hCurrentRadioButton, BM_GETCHECK, NULL, NULL)) { tpcb->accounts = 100000; tpcb->branches = 10; tpcb->tellers = 100; tpcb->history = 259200; } EnableWindow(GetDlgItem(hDlg, IDC_INIT_BUTTON), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_RUN_BUTTON), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_ADV_BUTTON), FALSE); } if (LOWORD(wParam) == IDC_ADV_BUTTON) { CreateDialog(hInst, MAKEINTRESOURCE(IDD_ADVANCEDDIALOG), hDlg, (DLGPROC)AdvancedDialog); } else if (LOWORD(wParam) == IDC_INIT_BUTTON) { // Close the environment first. // In case this is a re-initialization. tpcb->closeEnv(); GetHomeDirectory(hDlg, TRUE); tpcb->createEnv(0); ret = tpcb->populate(); } else if (LOWORD(wParam) == IDC_RUN_BUTTON) { GetHomeDirectory(hDlg, FALSE); if (GetFileAttributes( tpcb->getHomeDirW(wdirname, MAX_PATH)) != FILE_ATTRIBUTE_DIRECTORY) { _snwprintf(msg, 1024, L"Target directory: %s does not exist, or is not a directory.\nMake sure the " L"directory name is correct, and that you ran the initialization phase.", wdirname); MessageBox(hDlg, msg, L"Error", MB_OK); EnableWindow(GetDlgItem(hDlg, IDC_INIT_BUTTON), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_RUN_BUTTON), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_ADV_BUTTON), TRUE); return FALSE; } // TODO: Check for an empty directory? ntxns = GetDlgItemInt(hDlg, IDC_TXN_EDIT, &valid, FALSE); if (valid == FALSE) { MessageBox(hDlg, L"Invalid number in transaction field.", L"Error", MB_OK); EnableWindow(GetDlgItem(hDlg, IDC_INIT_BUTTON), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_RUN_BUTTON), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_ADV_BUTTON), TRUE); return FALSE; } tpcb->createEnv(0); ret = tpcb->run(ntxns); } else if (LOWORD(wParam) == IDC_EXIT_BUTTON) { tpcb->closeEnv(); EndDialog(hDlg, LOWORD(wParam)); DestroyWindow(hDlg); DestroyWindow(hWndFrame); return FALSE; } if (LOWORD(wParam) == IDC_INIT_BUTTON || LOWORD(wParam) == IDC_RUN_BUTTON ) { if (ret == 0) title = L"Results"; else title = L"Error message"; written = MultiByteToWideChar(CP_ACP, NULL, tpcb->msgString, strlen(tpcb->msgString), msg, sizeof(msg)/sizeof(msg[0])); msg[written] = L'\0'; MessageBox(hDlg, msg, title, MB_OK); EnableWindow(GetDlgItem(hDlg, IDC_INIT_BUTTON), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_RUN_BUTTON), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_ADV_BUTTON), TRUE); } break; case WM_DESTROY: // Same functionality as WM_COMMAND->IDC_EXIT_BUTTON tpcb->closeEnv(); EndDialog(hDlg, LOWORD(wParam)); DestroyWindow(hDlg); DestroyWindow(hWndFrame); return FALSE; default: return DefWindowProc(hDlg, message, wParam, lParam); } return TRUE; }
BOOL CFileAndFolder::IsFolder(const CString& sPath) { return ((GetFileAttributes(sPath) & FILE_ATTRIBUTE_DIRECTORY) != 0); }
/*makes the replace*/ INT replace(TCHAR source[MAX_PATH], TCHAR dest[MAX_PATH], DWORD dwFlags, BOOL *doMore) { TCHAR d[MAX_PATH]; TCHAR s[MAX_PATH]; HANDLE hFileSrc, hFileDest; DWORD dwAttrib, dwRead, dwWritten; LPBYTE buffer; BOOL bEof = FALSE; FILETIME srcCreationTime, destCreationTime, srcLastAccessTime, destLastAccessTime; FILETIME srcLastWriteTime, destLastWriteTime; GetPathCase(source, s); GetPathCase(dest, d); s[0] = (TCHAR)_totupper(s[0]); d[0] = (TCHAR)_totupper(d[0]); // ConOutPrintf(_T("old-src: %s\n"), s); // ConOutPrintf(_T("old-dest: %s\n"), d); // ConOutPrintf(_T("src: %s\n"), source); // ConOutPrintf(_T("dest: %s\n"), dest); /* Open up the sourcefile */ hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,NULL, OPEN_EXISTING, 0, NULL); if (hFileSrc == INVALID_HANDLE_VALUE) { ConOutResPrintf(STRING_COPY_ERROR1, source); return 0; } /* Get the time from source file to be used in the comparison with dest time if update switch is set */ GetFileTime (hFileSrc, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime); /* Retrieve the source attributes so that they later on can be inserted in to the destination */ dwAttrib = GetFileAttributes (source); if(IsExistingFile (dest)) { /* Resets the attributes to avoid probles with read only files, checks for read only has been made earlier */ SetFileAttributes(dest,FILE_ATTRIBUTE_NORMAL); /* Is the update flas set? The time has to be controled so that only older files are replaced */ if(dwFlags & REPLACE_UPDATE) { /* Read destination time */ hFileDest = CreateFile(dest, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFileSrc == INVALID_HANDLE_VALUE) { ConOutResPrintf(STRING_COPY_ERROR1, dest); return 0; } /* Compare time */ GetFileTime (hFileDest, &destCreationTime, &destLastAccessTime, &destLastWriteTime); if(!((srcLastWriteTime.dwHighDateTime > destLastWriteTime.dwHighDateTime) || ( srcLastWriteTime.dwHighDateTime == destLastWriteTime.dwHighDateTime && srcLastWriteTime.dwLowDateTime > destLastWriteTime.dwLowDateTime))) { CloseHandle (hFileSrc); CloseHandle (hFileDest); return 0; } CloseHandle (hFileDest); } /* Delete the old file */ DeleteFile (dest); } /* Check confirm flag, and take appropriate action */ if(dwFlags & REPLACE_CONFIRM) { /* Output depending on add flag */ if(dwFlags & REPLACE_ADD) ConOutResPrintf(STRING_REPLACE_HELP9, dest); else ConOutResPrintf(STRING_REPLACE_HELP10, dest); if( !FilePromptYNA (0)) return 0; } /* Output depending on add flag */ if(dwFlags & REPLACE_ADD) ConOutResPrintf(STRING_REPLACE_HELP11, dest); else ConOutResPrintf(STRING_REPLACE_HELP5, dest); /* Make sure source and destination is not the same */ if(!_tcscmp(s, d)) { ConOutResPaging(TRUE, STRING_REPLACE_ERROR7); CloseHandle (hFileSrc); *doMore = FALSE; return 0; } /* Open destination file to write to */ hFileDest = CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if (hFileDest == INVALID_HANDLE_VALUE) { CloseHandle (hFileSrc); ConOutResPaging(TRUE, STRING_REPLACE_ERROR7); *doMore = FALSE; return 0; } /* Get buffer for the copy process */ buffer = (LPBYTE)VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE); if (buffer == NULL) { CloseHandle (hFileDest); CloseHandle (hFileSrc); ConOutResPaging(TRUE, STRING_ERROR_OUT_OF_MEMORY); return 0; } /* Put attribute and time to the new destination file */ SetFileAttributes (dest, dwAttrib); SetFileTime (hFileDest, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime); do { /* Read data from source */ ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL); /* Done? */ if (dwRead == 0) break; /* Write to destination file */ WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL); /* Done! or ctrl break! */ if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT)) { ConOutResPuts(STRING_COPY_ERROR3); cmd_free (buffer); CloseHandle (hFileDest); CloseHandle (hFileSrc); nErrorLevel = 1; return 0; } } while (!bEof); /* Return memory and close files */ VirtualFree (buffer, 0, MEM_RELEASE); CloseHandle (hFileDest); CloseHandle (hFileSrc); /* Return one file replaced */ return 1; }
/* Function to iterate over source files and call replace for each of them */ INT recReplace(DWORD dwFlags, TCHAR szSrcPath[MAX_PATH], TCHAR szDestPath[MAX_PATH], BOOL *doMore) { TCHAR tmpDestPath[MAX_PATH], tmpSrcPath[MAX_PATH]; INT filesReplaced=0, i; DWORD dwAttrib = 0; HANDLE hFile; WIN32_FIND_DATA findBuffer; /* Get file handel to the sourcefile(s) */ hFile = FindFirstFile (szSrcPath, &findBuffer); /* Strip the paths back to the folder they are in, so that the diffrent filenames can be added if more than one */ for(i = (_tcslen(szSrcPath) - 1); i > -1; i--) if(szSrcPath[i] != _T('\\')) szSrcPath[i] = _T('\0'); else break; /* Go through all the soursfiles and copy/replace them */ do { if(CheckCtrlBreak(BREAK_INPUT)) { return filesReplaced; } /* Problem with file handler */ if(hFile == INVALID_HANDLE_VALUE) return filesReplaced; /* We do not want to replace any .. . ocr directory */ if(!_tcscmp (findBuffer.cFileName, _T(".")) || !_tcscmp (findBuffer.cFileName, _T(".."))|| findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; /* Add filename to destpath */ _tcscpy(tmpDestPath,szDestPath); _tcscat (tmpDestPath, findBuffer.cFileName); dwAttrib = GetFileAttributes(tmpDestPath); /* Check add flag */ if(dwFlags & REPLACE_ADD) { if(IsExistingFile(tmpDestPath)) continue; else dwAttrib = 0; } else { if(!IsExistingFile(tmpDestPath)) continue; } /* Check if file is read only, if so check if that should be ignored */ if(dwAttrib & FILE_ATTRIBUTE_READONLY) { if(!(dwFlags & REPLACE_READ_ONLY)) { ConOutResPrintf(STRING_REPLACE_ERROR5, tmpDestPath); *doMore = FALSE; break; } } /* Add filename to sourcepath, insted of wildcards */ _tcscpy(tmpSrcPath,szSrcPath); _tcscat (tmpSrcPath, findBuffer.cFileName); /* Make the replace */ if(replace(tmpSrcPath,tmpDestPath, dwFlags, doMore)) { filesReplaced++; } else if (!*doMore) { /* The file to be replaced was the same as the source */ filesReplaced = -1; break; } /* Take next sourcefile if any */ }while(FindNextFile (hFile, &findBuffer)); return filesReplaced; }
//暗号化ファイルの解析 CIPHER_RESULT PmCipher::ParseCipherFile(const char *cipher_path) { //戻り値・・・ステータス //第1引数・・・暗号化ファイルのパス //ファイルプロパティ文字列 char ch, str_size[10], *str_index, key_word[CIPHER_KEY_WORD_SIZE], cipher_key_word[CIPHER_KEY_WORD_SIZE]; //戻り値 CIPHER_RESULT cr = CIPHER_OK; //プロパティ一覧の解放(未解放時のための処理) SAFE_DELETE(m_property_list); //復号準備フラグOFF m_decrypt_init = false; //圧縮フラグOFF m_compress = false; //ファイルが存在しかつ、ディレクトリ属性ではない場合に処理開始 if(PathFileExists(cipher_path) && !(GetFileAttributes(cipher_path) & FILE_ATTRIBUTE_DIRECTORY)) { m_cipher_path = string(cipher_path); //暗号化ファイルのオープン m_fs_decrypt.open(cipher_path, ios::in|ios::binary); //キーワード読み込み m_fs_decrypt.read(cipher_key_word, CIPHER_KEY_WORD_SIZE); m_blow_fish.Decode((unsigned char *)cipher_key_word, (unsigned char *)key_word, CIPHER_KEY_WORD_SIZE); key_word[7] = '\0'; if(strcmp(key_word, CIPHER_KEY_WORD)) { DecryptEnd(); return CIPHER_ERR_INVALID_FILE; } m_fs_decrypt.get(ch); //圧縮フラグ読み込み if(ch == '0') { m_compress = false; } else { m_compress = true; } //プロパティ一覧ファイルの元サイズ読み込み m_fs_decrypt.read(str_size, 10); m_current_source_size = AlphaToLong(str_size, 10); //プロパティ一覧ファイルの圧縮サイズ読み込み m_fs_decrypt.read(str_size, 10); m_current_compress_size = AlphaToLong(str_size, 10); //プロパティ一覧ファイルの暗号化サイズ読み込み m_fs_decrypt.read(str_size, 10); m_cipher_index_size = AlphaToLong(str_size, 10); m_current_cipher_size = m_cipher_index_size; m_fs_decrypt.read(str_size, 10); //平文受け取りバッファ char *buf; //サイズ等 unsigned int size, buf_size, j; PmCipherProperty *cipher_property; m_total_buf_size = 0ul; m_total_decomp_buf_size = 0ul; m_decrypt_init = true; //ZLIBストリーム初期化 if(m_compress) { m_z.zalloc = Z_NULL; m_z.zfree = Z_NULL; m_z.opaque = Z_NULL; if (inflateInit(&m_z) != Z_OK) { DecryptEnd(); return CIPHER_ERR_INVALID_FILE; } m_z.avail_in = 0; m_z.avail_out = (unsigned int)(min(CIPHER_BUF_SIZE, m_current_source_size - m_total_buf_size)); m_z.next_out = m_output_buf; } CIPHER_RESULT dec_cr; buf_size = 0; str_index = new char[m_current_source_size]; //暗号化プロパティ一覧の復号完了までループ do { dec_cr = Decrypt(&buf, &size); memcpy(str_index + buf_size, buf, size); buf_size += size; } while(dec_cr == CIPHER_DEC_NEXT); char str_path[MAX_PATH]; //プロパティ一覧の生成 m_property_list = new PmCipherPropertyList(); buf_size = 0; //ルートパスの取得 j = 0; ZeroMemory(str_path, MAX_PATH); for(j = 0; buf_size + j < m_current_source_size && j < MAX_PATH; j++) { if(str_index[buf_size + j] == '\n') { memcpy(str_path, str_index + buf_size, j); m_root_path = string(str_path); buf_size += j + 1; break; } } //プロパティ一覧文字列の解析 while(dec_cr == CIPHER_DEC_FINISH && buf_size < m_current_source_size) { cipher_property = new PmCipherProperty(); //ファイル位置の取得 cipher_property->SetOffset(AlphaToLong(str_index + buf_size, 10)); buf_size += 10; //元ファイルサイズの取得 cipher_property->SetSourceSize(AlphaToLong(str_index + buf_size, 10)); buf_size += 10; //圧縮ファイルサイズの取得 cipher_property->SetCompressSize(AlphaToLong(str_index + buf_size, 10)); buf_size += 10; //暗号化ファイルサイズの取得 cipher_property->SetCipherSize(AlphaToLong(str_index + buf_size, 10)); buf_size += 10; //ファイルパスの取得 j = 0; ZeroMemory(str_path, MAX_PATH); for(j = 0; buf_size + j < m_current_source_size && j < MAX_PATH; j++) { if(str_index[buf_size + j] == '\n') { memcpy(str_path, str_index + buf_size, j); cipher_property->SetPath(string(str_path)); buf_size += j + 1; break; } } //プロパティをプロパティ一覧に追加 m_property_list->AddProperty(cipher_property); } //バッファメモリの解放 SAFE_DELETE_ARRAY(str_index); DecryptEnd(); } //ファイルが見つからないまたは、ディレクトリの場合エラー終了 else { cr = CIPHER_ERR_FILE_NOT_FOUND; } return cr; }
BOOL CTreeFileCtrl::IsFile(const CString& sPath) { return ((GetFileAttributes(sPath) & FILE_ATTRIBUTE_DIRECTORY) == 0); }
INT copy(TCHAR source[MAX_PATH], TCHAR dest[MAX_PATH], INT append, DWORD lpdwFlags, BOOL bTouch) { FILETIME srctime,NewFileTime; HANDLE hFileSrc; HANDLE hFileDest; LPBYTE buffer; DWORD dwAttrib; DWORD dwRead; DWORD dwWritten; BOOL bEof = FALSE; TCHAR TrueDest[MAX_PATH]; TCHAR TempSrc[MAX_PATH]; TCHAR * FileName; SYSTEMTIME CurrentTime; /* Check Breaker */ if (CheckCtrlBreak(BREAK_INPUT)) return 0; TRACE ("checking mode\n"); if (bTouch) { hFileSrc = CreateFile (source, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFileSrc == INVALID_HANDLE_VALUE) { ConOutResPrintf(STRING_COPY_ERROR1, source); nErrorLevel = 1; return 0; } GetSystemTime(&CurrentTime); SystemTimeToFileTime(&CurrentTime, &NewFileTime); if (SetFileTime(hFileSrc,(LPFILETIME) NULL, (LPFILETIME) NULL, &NewFileTime)) { CloseHandle(hFileSrc); nErrorLevel = 1; return 1; } else { CloseHandle(hFileSrc); return 0; } } dwAttrib = GetFileAttributes (source); hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFileSrc == INVALID_HANDLE_VALUE) { ConOutResPrintf(STRING_COPY_ERROR1, source); nErrorLevel = 1; return 0; } TRACE ("getting time\n"); GetFileTime (hFileSrc, &srctime, NULL, NULL); TRACE ("copy: flags has %s\n", lpdwFlags & COPY_ASCII ? "ASCII" : "BINARY"); /* Check to see if /D or /Z are true, if so we need a middle man to copy the file too to allow us to use CopyFileEx later */ if (lpdwFlags & COPY_DECRYPT) { GetEnvironmentVariable(_T("TEMP"),TempSrc,MAX_PATH); _tcscat(TempSrc,_T("\\")); FileName = _tcsrchr(source,_T('\\')); FileName++; _tcscat(TempSrc,FileName); /* This is needed to be on the end to prevent an error if the user did "copy /D /Z foo bar then it would be copied too %TEMP%\foo here and when %TEMP%\foo when it sets it up for COPY_RESTART, this would mean it is copying to itself which would error when it tried to open the handles for ReadFile and WriteFile */ _tcscat(TempSrc,_T(".decrypt")); if (!CopyFileEx(source, TempSrc, NULL, NULL, FALSE, COPY_FILE_ALLOW_DECRYPTED_DESTINATION)) { CloseHandle (hFileSrc); nErrorLevel = 1; return 0; } _tcscpy(source, TempSrc); } if (lpdwFlags & COPY_RESTART) { _tcscpy(TrueDest, dest); GetEnvironmentVariable(_T("TEMP"),dest,MAX_PATH); _tcscat(dest,_T("\\")); FileName = _tcsrchr(TrueDest,_T('\\')); FileName++; _tcscat(dest,FileName); } if (!IsExistingFile (dest)) { TRACE ("opening/creating\n"); hFileDest = CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); } else if (!append) { TRACE ("SetFileAttributes (%s, FILE_ATTRIBUTE_NORMAL);\n", debugstr_aw(dest)); SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL); TRACE ("DeleteFile (%s);\n", debugstr_aw(dest)); DeleteFile (dest); hFileDest = CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); } else { LONG lFilePosHigh = 0; if (!_tcscmp (dest, source)) { CloseHandle (hFileSrc); return 0; } TRACE ("opening/appending\n"); SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL); hFileDest = CreateFile (dest, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); /* Move to end of file to start writing */ SetFilePointer (hFileDest, 0, &lFilePosHigh,FILE_END); } if (hFileDest == INVALID_HANDLE_VALUE) { CloseHandle (hFileSrc); ConOutResPuts(STRING_ERROR_PATH_NOT_FOUND); nErrorLevel = 1; return 0; } /* A page-aligned buffer usually give more speed */ buffer = VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE); if (buffer == NULL) { CloseHandle (hFileDest); CloseHandle (hFileSrc); ConOutResPuts(STRING_ERROR_OUT_OF_MEMORY); nErrorLevel = 1; return 0; } do { ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL); if (lpdwFlags & COPY_ASCII) { LPBYTE pEof = memchr(buffer, 0x1A, dwRead); if (pEof != NULL) { bEof = TRUE; dwRead = pEof-buffer+1; break; } } if (dwRead == 0) break; WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL); if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT)) { ConOutResPuts(STRING_COPY_ERROR3); VirtualFree (buffer, 0, MEM_RELEASE); CloseHandle (hFileDest); CloseHandle (hFileSrc); nErrorLevel = 1; return 0; } } while (!bEof); TRACE ("setting time\n"); SetFileTime (hFileDest, &srctime, NULL, NULL); if ((lpdwFlags & COPY_ASCII) && !bEof) { /* we're dealing with ASCII files! */ buffer[0] = 0x1A; TRACE ("appending ^Z\n"); WriteFile (hFileDest, buffer, sizeof(CHAR), &dwWritten, NULL); } VirtualFree (buffer, 0, MEM_RELEASE); CloseHandle (hFileDest); CloseHandle (hFileSrc); TRACE ("setting mode\n"); SetFileAttributes (dest, dwAttrib); /* Now finish off the copy if needed with CopyFileEx */ if (lpdwFlags & COPY_RESTART) { if (!CopyFileEx(dest, TrueDest, NULL, NULL, FALSE, COPY_FILE_RESTARTABLE)) { nErrorLevel = 1; DeleteFile(dest); return 0; } /* Take care of file in the temp folder */ DeleteFile(dest); } if (lpdwFlags & COPY_DECRYPT) DeleteFile(TempSrc); return 1; }
bool DoesFileExist(const CString& name) { return (GetFileAttributes(name.GetString()) == 0xffffffff) ? false : true; }
// --------------------------------------------------------------------------- // CEnumCache::GetNextAssemblyDir // --------------------------------------------------------------------------- HRESULT CEnumCache::GetNextAssemblyDir(CTransCache* pOutRecord) { HRESULT hr = S_FALSE; DWORD dwCmpResult = 0; BOOL fIsMatch = FALSE; BOOL fFound = FALSE; WIN32_FIND_DATA FindFileData; WCHAR wzFullSearchPath[MAX_PATH+1]; DWORD dwAttr=0; WCHAR wzFullPath[MAX_PATH+1]; DWORD dwCacheType=0; if( !pOutRecord ) { hr = E_INVALIDARG; goto exit; } if(_fAllDone) { hr = S_FALSE; goto exit; } ASSERT(lstrlenW(_wzParentDir)); if(_hAsmDir == INVALID_HANDLE_VALUE) { if( (lstrlenW(_wzCachePath) + lstrlenW(_wzParentDir) + lstrlenW(g_szFindAllMask) + 4) >= MAX_PATH) { hr = HRESULT_FROM_WIN32(FUSION_E_INVALID_NAME); goto exit; } StrCpy(wzFullSearchPath, _wzCachePath); PathAddBackslash(wzFullSearchPath); StrCat(wzFullSearchPath, _wzParentDir); dwAttr = GetFileAttributes(wzFullSearchPath); if((dwAttr == (DWORD) -1) || !(dwAttr & FILE_ATTRIBUTE_DIRECTORY )) { hr = S_FALSE; goto exit; } StrCat(wzFullSearchPath, g_szFindAllMask); _hAsmDir = FindFirstFile(wzFullSearchPath, &FindFileData); if(_hAsmDir == INVALID_HANDLE_VALUE) { hr = FusionpHresultFromLastError(); goto exit; } fFound = TRUE; } else { if(FindNextFile(_hAsmDir, &FindFileData)) fFound = TRUE; } do { if(!fFound) break; if (!StrCmp(FindFileData.cFileName, L".")) continue; if (!StrCmp(FindFileData.cFileName, L"..")) continue; if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue; hr = ParseDirName ( pOutRecord, _wzParentDir, FindFileData.cFileName ); if(hr != S_OK) { pOutRecord->CleanInfo(pOutRecord->_pInfo, TRUE); continue; } if( (lstrlenW(_wzCachePath) + lstrlenW(_wzParentDir) + lstrlenW(FindFileData.cFileName) + 4) >= MAX_PATH) { hr = HRESULT_FROM_WIN32(FUSION_E_INVALID_NAME); goto exit; } StrCpy(wzFullPath, _wzCachePath); PathAddBackslash(wzFullPath); StrCat(wzFullPath, _wzParentDir); PathAddBackslash(wzFullPath); StrCat(wzFullPath, FindFileData.cFileName); dwCacheType = _pQry->GetCacheType(); hr = GetFusionInfo( pOutRecord, wzFullPath); if((hr != S_OK) && (dwCacheType != ASM_CACHE_GAC) && !_bShowAll) { pOutRecord->CleanInfo(pOutRecord->_pInfo, TRUE); continue; } PathAddBackslash(wzFullPath); DWORD dwLen = 0; if(dwCacheType & ASM_CACHE_DOWNLOAD) { if(!pOutRecord->_pInfo->pwzName) { if(_bShowAll) goto Done; else continue; } StrCatBuff(wzFullPath, pOutRecord->_pInfo->pwzName, MAX_PATH); } else { StrCatBuff(wzFullPath, _wzParentDir, MAX_PATH); } dwLen = lstrlenW(wzFullPath); StrCatBuff(wzFullPath, g_szDotDLL, MAX_PATH); if(((dwCacheType & ASM_CACHE_DOWNLOAD) || (dwCacheType & ASM_CACHE_ZAP) ) && (GetFileAttributes(wzFullPath) == (DWORD) -1) ) { // there is no AsmName.dll look for AsmName.exe if( (dwLen + lstrlenW(g_szDotEXE)) >= MAX_PATH) { hr = HRESULT_FROM_WIN32(FUSION_E_INVALID_NAME); goto exit; } StrCpy(wzFullPath+dwLen, g_szDotEXE); } if(!_bShowAll) { fIsMatch = _pQry->IsMatch(pOutRecord, _dwCmpMask, &dwCmpResult); if(!fIsMatch) { pOutRecord->CleanInfo(pOutRecord->_pInfo, TRUE); continue; } } Done : SAFEDELETEARRAY(pOutRecord->_pInfo->pwzPath); pOutRecord->_pInfo->pwzPath = WSTRDupDynamic(wzFullPath); hr = S_OK; goto exit; }while(FindNextFile(_hAsmDir, &FindFileData)); // while if( GetLastError() != ERROR_NO_MORE_FILES) { hr = FusionpHresultFromLastError(); goto exit; } hr = S_FALSE; FindClose(_hAsmDir); _hAsmDir = INVALID_HANDLE_VALUE; if(_hParentDir == INVALID_HANDLE_VALUE) _fAllDone = TRUE; exit : return hr; }
static BOOL InUn(int remove, char *drivername, char *dllname, char *dll2name, char *dsname) { char path[301], driver[300], attr[300], inst[400], inst2[400]; WORD pathmax = sizeof (path) - 1, pathlen; DWORD usecnt, mincnt; if (SQLInstallDriverManager(path, pathmax, &pathlen)) { char *p; sprintf(driver, "%s;Driver=%s;Setup=%s;", drivername, dllname, dllname); p = driver; while (*p) { if (*p == ';') { *p = '\0'; } ++p; } usecnt = 0; SQLInstallDriverEx(driver, NULL, path, pathmax, &pathlen, ODBC_INSTALL_INQUIRY, &usecnt); sprintf(driver, "%s;Driver=%s\\%s;Setup=%s\\%s;", drivername, path, dllname, path, dllname); p = driver; while (*p) { if (*p == ';') { *p = '\0'; } ++p; } sprintf(inst, "%s\\%s", path, dllname); if (dll2name) { sprintf(inst2, "%s\\%s", path, dll2name); } if (!remove && usecnt > 0) { /* first install try: copy over driver dll, keeping DSNs */ if (GetFileAttributes(dllname) != INVALID_FILE_ATTRIBUTES && CopyFile(dllname, inst, 0) && CopyOrDelModules(dllname, path, 0)) { if (dll2name != NULL) { CopyFile(dll2name, inst2, 0); } return TRUE; } } mincnt = remove ? 1 : 0; while (usecnt != mincnt) { if (!SQLRemoveDriver(driver, TRUE, &usecnt)) { break; } } if (remove) { if (!SQLRemoveDriver(driver, TRUE, &usecnt)) { ProcessErrorMessages("SQLRemoveDriver"); return FALSE; } if (!usecnt) { char buf[512]; DeleteFile(inst); /* but keep inst2 */ CopyOrDelModules(dllname, path, 1); if (!quiet) { sprintf(buf, "%s uninstalled.", drivername); MessageBox(NULL, buf, "Info", MB_ICONINFORMATION|MB_OK|MB_TASKMODAL| MB_SETFOREGROUND); } } if (nosys) { goto done; } sprintf(attr, "DSN=%s;", dsname); p = attr; while (*p) { if (*p == ';') { *p = '\0'; } ++p; } SQLConfigDataSource(NULL, ODBC_REMOVE_SYS_DSN, drivername, attr); goto done; } if (GetFileAttributes(dllname) == INVALID_FILE_ATTRIBUTES) { return FALSE; } if (!CopyFile(dllname, inst, 0)) { char buf[512]; sprintf(buf, "Copy %s to %s failed", dllname, inst); MessageBox(NULL, buf, "CopyFile", MB_ICONSTOP|MB_OK|MB_TASKMODAL|MB_SETFOREGROUND); return FALSE; } if (dll2name != NULL && !CopyFile(dll2name, inst2, 0)) { char buf[512]; sprintf(buf, "Copy %s to %s failed", dll2name, inst2); MessageBox(NULL, buf, "CopyFile", MB_ICONSTOP|MB_OK|MB_TASKMODAL|MB_SETFOREGROUND); /* but go on hoping that an SQLite engine is in place */ } if (!CopyOrDelModules(dllname, path, 0)) { return FALSE; } if (!SQLInstallDriverEx(driver, path, path, pathmax, &pathlen, ODBC_INSTALL_COMPLETE, &usecnt)) { ProcessErrorMessages("SQLInstallDriverEx"); return FALSE; } if (nosys) { goto done; } sprintf(attr, "DSN=%s;", dsname); p = attr; while (*p) { if (*p == ';') { *p = '\0'; } ++p; } SQLConfigDataSource(NULL, ODBC_REMOVE_SYS_DSN, drivername, attr); if (!SQLConfigDataSource(NULL, ODBC_ADD_SYS_DSN, drivername, attr)) { ProcessErrorMessages("SQLConfigDataSource"); return FALSE; } } else { ProcessErrorMessages("SQLInstallDriverManager"); return FALSE; } done: return TRUE; }
bool fexists(string f) { return (GetFileAttributes(f.c_str()) != 0xFFFFFFFF); }
static int TestplatformChmod( const char *nativePath, int pmode) { typedef DWORD (WINAPI *getSidLengthRequiredDef)(UCHAR); typedef BOOL (WINAPI *initializeSidDef)(PSID, PSID_IDENTIFIER_AUTHORITY, BYTE); typedef PDWORD (WINAPI *getSidSubAuthorityDef)(PSID, DWORD); typedef DWORD (WINAPI *setNamedSecurityInfoADef)(IN LPSTR, IN SE_OBJECT_TYPE, IN SECURITY_INFORMATION, IN PSID, IN PSID, IN PACL, IN PACL); typedef BOOL (WINAPI *getAceDef)(PACL, DWORD, LPVOID *); typedef BOOL (WINAPI *addAceDef)(PACL, DWORD, DWORD, LPVOID, DWORD); typedef BOOL (WINAPI *equalSidDef)(PSID, PSID); typedef BOOL (WINAPI *addAccessDeniedAceDef)(PACL, DWORD, DWORD, PSID); typedef BOOL (WINAPI *initializeAclDef)(PACL, DWORD, DWORD); typedef DWORD (WINAPI *getLengthSidDef)(PSID); typedef BOOL (WINAPI *getAclInformationDef)(PACL, LPVOID, DWORD, ACL_INFORMATION_CLASS); typedef BOOL (WINAPI *getSecurityDescriptorDaclDef)(PSECURITY_DESCRIPTOR, LPBOOL, PACL *, LPBOOL); typedef BOOL (WINAPI *lookupAccountNameADef)(LPCSTR, LPCSTR, PSID, PDWORD, LPSTR, LPDWORD, PSID_NAME_USE); typedef BOOL (WINAPI *getFileSecurityADef)(LPCSTR, SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, DWORD, LPDWORD); static const SECURITY_INFORMATION infoBits = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; static const DWORD readOnlyMask = FILE_DELETE_CHILD | FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY | FILE_WRITE_EA | FILE_APPEND_DATA | FILE_WRITE_DATA | DELETE; /* * References to security functions (only available on NT and later). */ static getSidLengthRequiredDef getSidLengthRequiredProc; static initializeSidDef initializeSidProc; static getSidSubAuthorityDef getSidSubAuthorityProc; static setNamedSecurityInfoADef setNamedSecurityInfoProc; static getAceDef getAceProc; static addAceDef addAceProc; static equalSidDef equalSidProc; static addAccessDeniedAceDef addAccessDeniedAceProc; static initializeAclDef initializeAclProc; static getLengthSidDef getLengthSidProc; static getAclInformationDef getAclInformationProc; static getSecurityDescriptorDaclDef getSecurityDescriptorDaclProc; static lookupAccountNameADef lookupAccountNameProc; static getFileSecurityADef getFileSecurityProc; static int initialized = 0; const BOOL set_readOnly = !(pmode & 0222); BOOL acl_readOnly_found = FALSE, curAclPresent, curAclDefaulted; SID_IDENTIFIER_AUTHORITY userSidAuthority = { SECURITY_WORLD_SID_AUTHORITY }; BYTE *secDesc = 0; DWORD secDescLen, attr, newAclSize; ACL_SIZE_INFORMATION ACLSize; PACL curAcl, newAcl = 0; WORD j; SID *userSid = 0; TCHAR *userDomain = 0; int res = 0; /* * One time initialization, dynamically load Windows NT features */ if (!initialized) { TCL_DECLARE_MUTEX(initializeMutex) Tcl_MutexLock(&initializeMutex); if (!initialized) { HINSTANCE hInstance = LoadLibrary("Advapi32"); if (hInstance != NULL) { setNamedSecurityInfoProc = (setNamedSecurityInfoADef) GetProcAddress(hInstance, "SetNamedSecurityInfoA"); getFileSecurityProc = (getFileSecurityADef) GetProcAddress(hInstance, "GetFileSecurityA"); getAceProc = (getAceDef) GetProcAddress(hInstance, "GetAce"); addAceProc = (addAceDef) GetProcAddress(hInstance, "AddAce"); equalSidProc = (equalSidDef) GetProcAddress(hInstance, "EqualSid"); addAccessDeniedAceProc = (addAccessDeniedAceDef) GetProcAddress(hInstance, "AddAccessDeniedAce"); initializeAclProc = (initializeAclDef) GetProcAddress(hInstance, "InitializeAcl"); getLengthSidProc = (getLengthSidDef) GetProcAddress(hInstance, "GetLengthSid"); getAclInformationProc = (getAclInformationDef) GetProcAddress(hInstance, "GetAclInformation"); getSecurityDescriptorDaclProc = (getSecurityDescriptorDaclDef) GetProcAddress(hInstance, "GetSecurityDescriptorDacl"); lookupAccountNameProc = (lookupAccountNameADef) GetProcAddress(hInstance, "LookupAccountNameA"); getSidLengthRequiredProc = (getSidLengthRequiredDef) GetProcAddress(hInstance, "GetSidLengthRequired"); initializeSidProc = (initializeSidDef) GetProcAddress(hInstance, "InitializeSid"); getSidSubAuthorityProc = (getSidSubAuthorityDef) GetProcAddress(hInstance, "GetSidSubAuthority"); if (setNamedSecurityInfoProc && getAceProc && addAceProc && equalSidProc && addAccessDeniedAceProc && initializeAclProc && getLengthSidProc && getAclInformationProc && getSecurityDescriptorDaclProc && lookupAccountNameProc && getFileSecurityProc && getSidLengthRequiredProc && initializeSidProc && getSidSubAuthorityProc) { initialized = 1; } } if (!initialized) { initialized = -1; } } Tcl_MutexUnlock(&initializeMutex); } /* * Process the chmod request. */ attr = GetFileAttributes(nativePath); /* * nativePath not found */ if (attr == 0xffffffff) { res = -1; goto done; } /* * If no ACL API is present or nativePath is not a directory, there is no * special handling. */ if (initialized < 0 || !(attr & FILE_ATTRIBUTE_DIRECTORY)) { goto done; } /* * Set the result to error, if the ACL change is successful it will be * reset to 0. */ res = -1; /* * Read the security descriptor for the directory. Note the first call * obtains the size of the security descriptor. */ if (!getFileSecurityProc(nativePath, infoBits, NULL, 0, &secDescLen)) { DWORD secDescLen2 = 0; if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { goto done; } secDesc = (BYTE *) ckalloc(secDescLen); if (!getFileSecurityProc(nativePath, infoBits, (PSECURITY_DESCRIPTOR) secDesc, secDescLen, &secDescLen2) || (secDescLen < secDescLen2)) { goto done; } } /* * Get the World SID. */ userSid = (SID *) ckalloc(getSidLengthRequiredProc((UCHAR) 1)); initializeSidProc(userSid, &userSidAuthority, (BYTE) 1); *(getSidSubAuthorityProc(userSid, 0)) = SECURITY_WORLD_RID; /* * If curAclPresent == false then curAcl and curAclDefaulted not valid. */ if (!getSecurityDescriptorDaclProc((PSECURITY_DESCRIPTOR) secDesc, &curAclPresent, &curAcl, &curAclDefaulted)) { goto done; } if (!curAclPresent || !curAcl) { ACLSize.AclBytesInUse = 0; ACLSize.AceCount = 0; } else if (!getAclInformationProc(curAcl, &ACLSize, sizeof(ACLSize), AclSizeInformation)) { goto done; } /* * Allocate memory for the new ACL. */ newAclSize = ACLSize.AclBytesInUse + sizeof(ACCESS_DENIED_ACE) + getLengthSidProc(userSid) - sizeof(DWORD); newAcl = (ACL *) ckalloc(newAclSize); /* * Initialize the new ACL. */ if (!initializeAclProc(newAcl, newAclSize, ACL_REVISION)) { goto done; } /* * Add denied to make readonly, this will be known as a "read-only tag". */ if (set_readOnly && !addAccessDeniedAceProc(newAcl, ACL_REVISION, readOnlyMask, userSid)) { goto done; } acl_readOnly_found = FALSE; for (j = 0; j < ACLSize.AceCount; j++) { LPVOID pACE2; ACE_HEADER *phACE2; if (!getAceProc(curAcl, j, &pACE2)) { goto done; } phACE2 = (ACE_HEADER *) pACE2; /* * Do NOT propagate inherited ACEs. */ if (phACE2->AceFlags & INHERITED_ACE) { continue; } /* * Skip the "read-only tag" restriction (either added above, or it is * being removed). */ if (phACE2->AceType == ACCESS_DENIED_ACE_TYPE) { ACCESS_DENIED_ACE *pACEd = (ACCESS_DENIED_ACE *) phACE2; if (pACEd->Mask == readOnlyMask && equalSidProc(userSid, (PSID) &pACEd->SidStart)) { acl_readOnly_found = TRUE; continue; } } /* * Copy the current ACE from the old to the new ACL. */ if (!addAceProc(newAcl, ACL_REVISION, MAXDWORD, (PACL *)pACE2, ((PACE_HEADER) pACE2)->AceSize)) { goto done; } } /* * Apply the new ACL. */ if (set_readOnly == acl_readOnly_found || setNamedSecurityInfoProc( (LPSTR) nativePath, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, newAcl, NULL) == ERROR_SUCCESS) { res = 0; } done: if (secDesc) { ckfree((char *) secDesc); } if (newAcl) { ckfree((char *) newAcl); } if (userSid) { ckfree((char *) userSid); } if (userDomain) { ckfree(userDomain); } if (res != 0) { return res; } /* * Run normal chmod command. */ return chmod(nativePath, pmode); }
string FileBrowser::mGetFolderFTPLongDescription(string folder) { string fullPath =""; if(m_CurrentFolder.size() ==0) { fullPath = folder + ":\\"; } else { fullPath= GetCurrentPath() + "\\" + folder; } if(FileExists(fullPath)) { DWORD attr = GetFileAttributes(fullPath.c_str()); char execute = 'x'; char read = 'r'; char write = 'w'; char directory = '-'; if(attr&FILE_ATTRIBUTE_DIRECTORY) { directory = 'd'; } if(attr&FILE_ATTRIBUTE_ARCHIVE ) { execute = '-'; } if(attr&FILE_ATTRIBUTE_READONLY ) { write = '-'; } if(attr&FILE_ATTRIBUTE_DEVICE ) { read = '-'; } struct stat statDirStatus; stat(fullPath.c_str(),&statDirStatus); char timeStr[ 100 ] = ""; struct tm locTime; int retval = localtime_s(&locTime, &statDirStatus.st_mtime); if(retval) { retval = localtime_s(&locTime, &statDirStatus.st_atime); } if(retval) { retval = localtime_s( &locTime, &statDirStatus.st_ctime); } if(retval) { time_t t; time(&t); retval = localtime_s(&locTime, &t); } strftime(timeStr, 100, "%b %d %Y", &locTime); return sprintfa("%c%c%c%c%c%c%c%c%c%c 1 root root %d %s %s\r\n",directory,read,write,execute,read,write,execute,read,write,execute,0,timeStr,folder.c_str()); } else { return sprintfa("%s\r\n",folder.c_str()); } }
void CBINDInstallDlg::ProgramGroup(BOOL create) { TCHAR path[MAX_PATH], commonPath[MAX_PATH], fileloc[MAX_PATH], linkpath[MAX_PATH]; HRESULT hres; IShellLink *psl = NULL; LPMALLOC pMalloc = NULL; ITEMIDLIST *itemList = NULL; HRESULT hr = SHGetMalloc(&pMalloc); if (hr != NOERROR) { MessageBox("Could not get a handle to Shell memory object"); return; } hr = SHGetSpecialFolderLocation(m_hWnd, CSIDL_COMMON_PROGRAMS, &itemList); if (hr != NOERROR) { MessageBox("Could not get a handle to the Common Programs folder"); if (itemList) { pMalloc->Free(itemList); } return; } hr = SHGetPathFromIDList(itemList, commonPath); pMalloc->Free(itemList); if (create) { sprintf(path, "%s\\ISC", commonPath); CreateDirectory(path, NULL); sprintf(path, "%s\\ISC\\BIND", commonPath); CreateDirectory(path, NULL); hres = CoInitialize(NULL); if (SUCCEEDED(hres)) { // Get a pointer to the IShellLink interface. hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl); if (SUCCEEDED(hres)) { IPersistFile* ppf; sprintf(linkpath, "%s\\BINDCtrl.lnk", path); sprintf(fileloc, "%s\\BINDCtrl.exe", m_binDir); psl->SetPath(fileloc); psl->SetDescription("BIND Control Panel"); hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf); if (SUCCEEDED(hres)) { WCHAR wsz[MAX_PATH]; MultiByteToWideChar(CP_ACP, 0, linkpath, -1, wsz, MAX_PATH); hres = ppf->Save(wsz, TRUE); ppf->Release(); } if (GetFileAttributes("readme.txt") != -1) { sprintf(fileloc, "%s\\Readme.txt", m_targetDir); sprintf(linkpath, "%s\\Readme.lnk", path); psl->SetPath(fileloc); psl->SetDescription("BIND Readme"); hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf); if (SUCCEEDED(hres)) { WCHAR wsz[MAX_PATH]; MultiByteToWideChar(CP_ACP, 0, linkpath, -1, wsz, MAX_PATH); hres = ppf->Save(wsz, TRUE); ppf->Release(); } psl->Release(); } } CoUninitialize(); } } else { TCHAR filename[MAX_PATH]; WIN32_FIND_DATA fd; sprintf(path, "%s\\ISC\\BIND", commonPath); sprintf(filename, "%s\\*.*", path); HANDLE hFind = FindFirstFile(filename, &fd); if (hFind != INVALID_HANDLE_VALUE) { do { if (strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..")) { sprintf(filename, "%s\\%s", path, fd.cFileName); DeleteFile(filename); } } while (FindNextFile(hFind, &fd)); FindClose(hFind); } RemoveDirectory(path); sprintf(path, "%s\\ISC", commonPath); RemoveDirectory(path); } }
/********************************************************************* * _searchenv_s (MSVCRT.@) */ int _tsearchenv_s(const _TCHAR* file, const _TCHAR* env, _TCHAR *buf, size_t count) { _TCHAR *envVal, *penv; _TCHAR curPath[MAX_PATH]; if (!MSVCRT_CHECK_PMT(file != NULL) || !MSVCRT_CHECK_PMT(buf != NULL) || !MSVCRT_CHECK_PMT(count > 0)) { *_errno() = EINVAL; return EINVAL; } *buf = '\0'; /* Try CWD first */ if (GetFileAttributes( file ) != INVALID_FILE_ATTRIBUTES) { GetFullPathName( file, MAX_PATH, buf, NULL ); _dosmaperr(GetLastError()); return 0; } /* Search given environment variable */ envVal = _tgetenv(env); if (!envVal) { _set_errno(ENOENT); return ENOENT; } penv = envVal; do { _TCHAR *end = penv; while(*end && *end != ';') end++; /* Find end of next path */ if (penv == end || !*penv) { _set_errno(ENOENT); return ENOENT; } memcpy(curPath, penv, (end - penv) * sizeof(_TCHAR)); if (curPath[end - penv] != '/' && curPath[end - penv] != '\\') { curPath[end - penv] = '\\'; curPath[end - penv + 1] = '\0'; } else curPath[end - penv] = '\0'; _tcscat(curPath, file); if (GetFileAttributes( curPath ) != INVALID_FILE_ATTRIBUTES) { if (_tcslen(curPath) + 1 > count) { MSVCRT_INVALID_PMT("buf[count] is too small", ERANGE); return ERANGE; } _tcscpy(buf, curPath); return 0; } penv = *end ? end + 1 : end; } while(1); }
FORCE_INLINE int NSISCALL ui_doinstall(void) { header *header = g_header; static WNDCLASS wc; // richedit subclassing and bgbg creation // detect default language // more information at: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/intl/nls_0xrn.asp LANGID (WINAPI *GUDUIL)(); static const char guduil[] = "GetUserDefaultUILanguage"; GUDUIL = myGetProcAddress("KERNEL32.dll", (char *) guduil); if (GUDUIL) { // Windows ME/2000+ myitoa(state_language, GUDUIL()); } else { *(DWORD*)state_language = CHAR4_TO_DWORD('0', 'x', 0, 0); { // Windows 9x static const char reg_9x_locale[] = "Control Panel\\Desktop\\ResourceLocale"; myRegGetStr(HKEY_CURRENT_USER, reg_9x_locale, NULL, g_tmp); } if (!g_tmp[0]) { // Windows NT // This key exists on 9x as well, so it's only read if ResourceLocale wasn't found static const char reg_nt_locale_key[] = ".DEFAULT\\Control Panel\\International"; static const char reg_nt_locale_val[] = "Locale"; myRegGetStr(HKEY_USERS, reg_nt_locale_key, reg_nt_locale_val, g_tmp); } mystrcat(state_language, g_tmp); } // set default language set_language(); // initialize auto close flag g_exec_flags.autoclose=g_flags&CH_FLAGS_AUTO_CLOSE; // read install directory from registry if (!is_valid_instpath(state_install_directory)) { if (header->install_reg_key_ptr) { myRegGetStr( (HKEY)header->install_reg_rootkey, GetNSISStringNP(header->install_reg_key_ptr), GetNSISStringNP(header->install_reg_value_ptr), ps_tmpbuf ); if (ps_tmpbuf[0]) { char *p=ps_tmpbuf; char *e; if (p[0]=='\"') { char *p2; p++; p2 = findchar(p, '"'); *p2 = 0; } // p is the path now, check for .exe extension e=p+mystrlen(p)-4; if (e > p) { // if filename ends in .exe, and is not a directory, remove the filename if (!lstrcmpi(e, ".exe")) // check extension { DWORD d; d=GetFileAttributes(p); if (d == INVALID_FILE_ATTRIBUTES || !(d&FILE_ATTRIBUTE_DIRECTORY)) { // if there is no back-slash, the string will become empty, but that's ok because // it would make an invalid instdir anyway trimslashtoend(p); } } } mystrcpy(state_install_directory,addtrailingslash(p)); } } } if (!is_valid_instpath(state_install_directory)) { GetNSISString(state_install_directory,header->install_directory_ptr); } #ifdef NSIS_CONFIG_LOG if (g_flags & CH_FLAGS_SILENT_LOG && !g_is_uninstaller) { #if !defined(NSIS_CONFIG_LOG_ODS) && !defined(NSIS_CONFIG_LOG_STDOUT) build_g_logfile(); #endif log_dolog=1; } #endif #ifdef NSIS_CONFIG_VISIBLE_SUPPORT g_hIcon=LoadImage(g_hInstance,MAKEINTRESOURCE(IDI_ICON2),IMAGE_ICON,0,0,LR_DEFAULTSIZE|LR_SHARED); #ifdef NSIS_SUPPORT_BGBG if (header->bg_color1 != -1) { DWORD cn = CHAR4_TO_DWORD('_', 'N', 'b', 0); RECT vp; extern LRESULT CALLBACK BG_WndProc(HWND, UINT, WPARAM, LPARAM); wc.lpfnWndProc = BG_WndProc; wc.hInstance = g_hInstance; wc.hIcon = g_hIcon; //wc.hCursor = LoadCursor(NULL,IDC_ARROW); wc.lpszClassName = (LPCSTR)&cn; if (!RegisterClass(&wc)) return 0; SystemParametersInfo(SPI_GETWORKAREA, 0, &vp, 0); m_bgwnd = CreateWindowEx(WS_EX_TOOLWINDOW,(LPCSTR)&cn,0,WS_POPUP, vp.left,vp.top,vp.right-vp.left,vp.bottom-vp.top,0,NULL,g_hInstance,NULL); } #endif//NSIS_SUPPORT_BGBG #endif//NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_SUPPORT_CODECALLBACKS // Select language if (ExecuteCallbackFunction(CB_ONINIT)) return 2; set_language(); #endif #ifdef NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_CONFIG_SILENT_SUPPORT if (!g_exec_flags.silent) #endif//NSIS_CONFIG_SILENT_SUPPORT { #ifdef NSIS_SUPPORT_BGBG ShowWindow(m_bgwnd, SW_SHOW); #endif//NSIS_SUPPORT_BGBG #ifdef NSIS_CONFIG_LICENSEPAGE { // load richedit DLL static char str1[]="RichEd20.dll"; static char str2[]="RichEdit20A"; if (!LoadLibrary(str1)) { *(WORD*)(str1+6) = CHAR2_TO_WORD('3','2'); LoadLibrary(str1); } // make richedit20a point to RICHEDIT if (!GetClassInfo(NULL,str2,&wc)) { str2[8]=0; GetClassInfo(NULL,str2,&wc); wc.lpszClassName = str2; str2[8]='2'; RegisterClass(&wc); } } #endif { int ret=DialogBox(g_hInstance,MAKEINTRESOURCE(IDD_INST+dlg_offset),0,DialogProc); #if defined(NSIS_SUPPORT_CODECALLBACKS) && defined(NSIS_CONFIG_ENHANCEDUI_SUPPORT) ExecuteCallbackFunction(CB_ONGUIEND); #endif return ret; } } #endif//NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_CONFIG_SILENT_SUPPORT #ifdef NSIS_CONFIG_VISIBLE_SUPPORT else #endif//NSIS_CONFIG_VISIBLE_SUPPORT { if (install_thread(NULL)) { #ifdef NSIS_SUPPORT_CODECALLBACKS if (!g_quit_flag) ExecuteCallbackFunction(CB_ONINSTFAILED); #endif//NSIS_SUPPORT_CODECALLBACKS return 2; } #ifdef NSIS_SUPPORT_CODECALLBACKS ExecuteCallbackFunction(CB_ONINSTSUCCESS); #endif//NSIS_SUPPORT_CODECALLBACKS return 0; } #endif//NSIS_CONFIG_SILENT_SUPPORT }
/* ======================================================================================================================= Map_LoadFile ======================================================================================================================= */ void Map_LoadFile(const char *filename) { entity_t *ent; CWaitDlg dlg; idStr fileStr, status; idMapFile mapfile; Sys_BeginWait(); Select_Deselect(); dlg.AllowCancel(true); idStr(filename).ExtractFileName(fileStr); sprintf(status, "Loading %s...", fileStr.c_str()); dlg.SetWindowText(status); sprintf(status, "Reading file %s...", fileStr.c_str()); dlg.SetText(status); // SetInspectorMode(W_CONSOLE); fileStr = filename; fileStr.BackSlashesToSlashes(); common->Printf("Map_LoadFile: %s\n", fileStr.c_str()); Map_Free(); g_qeglobals.d_parsed_brushes = 0; strcpy(currentmap, filename); if (mapfile.Parse(filename, true, true)) { g_qeglobals.bNeedConvert = false; g_qeglobals.bOldBrushes = false; g_qeglobals.bPrimitBrushes = false; g_qeglobals.mapVersion = 1.0; long lastUpdate = 0; int count = mapfile.GetNumEntities(); for (int i = 0; i < count; i++) { idMapEntity *mapent = mapfile.GetEntity(i); if (mapent) { idStr classname = mapent->epairs.GetString("classname"); // Update 20 times a second if ((GetTickCount() - lastUpdate) > 50) { lastUpdate = GetTickCount(); sprintf(status, "Loading entity %i (%s)...", i, classname.c_str()); dlg.SetText(status); } if (dlg.CancelPressed()) { Sys_Status("Map load cancelled.\n"); Map_New(); return; } if (classname == "worldspawn") { world_entity = EntityFromMapEntity(mapent, &dlg); Entity_PostParse(world_entity, &active_brushes); } else { ent = EntityFromMapEntity(mapent, &dlg); Entity_PostParse(ent, &active_brushes); Entity_Name(ent, true); // add the entity to the end of the entity list ent->next = &entities; ent->prev = entities.prev; entities.prev->next = ent; entities.prev = ent; g_qeglobals.d_num_entities++; } } } } if (!world_entity) { Sys_Status("No worldspawn in map.\n"); Map_New(); return; } common->Printf("--- LoadMapFile ---\n"); common->Printf("%s\n", fileStr.c_str()); common->Printf("%5i brushes\n", g_qeglobals.d_parsed_brushes); common->Printf("%5i entities\n", g_qeglobals.d_num_entities); dlg.SetText("Restoring Between"); Map_RestoreBetween(); dlg.SetText("Building Brush Data"); common->Printf("Map_BuildAllDisplayLists\n"); Map_BuildBrushData(); // // reset the "need conversion" flag conversion to the good format done in // Map_BuildBrushData // g_qeglobals.bNeedConvert = false; // move the view to a start position ent = AngledEntity(); g_pParentWnd->GetCamera()->Camera().angles[PITCH] = 0; if (ent) { GetVectorForKey(ent, "origin", g_pParentWnd->GetCamera()->Camera().origin); GetVectorForKey(ent, "origin", g_pParentWnd->GetXYWnd()->GetOrigin()); g_pParentWnd->GetCamera()->Camera().angles[YAW] = FloatForKey(ent, "angle"); } else { g_pParentWnd->GetCamera()->Camera().angles[YAW] = 0; VectorCopy(vec3_origin, g_pParentWnd->GetCamera()->Camera().origin); VectorCopy(vec3_origin, g_pParentWnd->GetXYWnd()->GetOrigin()); } Map_RegionOff(); mapModified = 0; if (GetFileAttributes(filename) & FILE_ATTRIBUTE_READONLY) { fileStr += " (read only) "; } Sys_SetTitle(fileStr); Texture_ShowInuse(); if (g_pParentWnd->GetCamera()->GetRenderMode()) { g_pParentWnd->GetCamera()->BuildRendererState(); } Sys_EndWait(); Sys_UpdateWindows(W_ALL); }
bool Ten18::Util::FileExists(const wchar_t *fileName) { return INVALID_FILE_ATTRIBUTES != GetFileAttributes(fileName); }
bool RecurseDeletePath(const char * a_path) { WIN32_FIND_DATA findData; char path[MAX_PATH] = ""; strcpy(path,a_path); // remove trailing '\' char int last = (int)strlen(path) - 1; if(path[last] == '\\') { path[last] = '\0'; } // is path valid HANDLE h = FindFirstFile(path,&findData); // path not could not be found OR path is a file, not a folder if((h == INVALID_HANDLE_VALUE) || (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))) { return false; } FindClose(h); h = NULL; // push current working directory char currDir[MAX_PATH + 1] = ""; GetCurrentDirectory(MAX_PATH,currDir); SetCurrentDirectory(path); // iterate over contents of folder h = FindFirstFile("*",&findData); if(h != INVALID_HANDLE_VALUE) { for(;;) { if(strcmp(findData.cFileName,".") != 0 && strcmp(findData.cFileName,"..") != 0) { if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { RecurseDeletePath(findData.cFileName); } else { DWORD attrs = GetFileAttributes(findData.cFileName); if(attrs & FILE_ATTRIBUTE_READONLY) { SetFileAttributes(findData.cFileName,attrs ^ FILE_ATTRIBUTE_READONLY); } if(DeleteFile(findData.cFileName) != TRUE) { DWORD res = GetLastError(); printf("\nDeleteFile() returned '%d'..\n",(int)res); } } } if(!FindNextFile(h,&findData)) break; } } // pop current working directory SetCurrentDirectory(currDir); FindClose(h); h = NULL; // remove this directory DWORD attrs = GetFileAttributes(path); if(attrs & FILE_ATTRIBUTE_READONLY) { SetFileAttributes(path,attrs ^ FILE_ATTRIBUTE_READONLY); } return RemoveDirectory(path) != 0; }
void Autoload(const char* fn) { String dir; if(fn) { dir=fn; int bs=dir.RIndex("\\"); dir.Delete(bs); } else { char buf[512]; GetCurrentDirectory(sizeof(buf),buf); dir=buf; } dir+="\\.tags-autoload"; dir.ToLower(); //DebugBreak(); StrList sl; int isenv=0; bool mainaload=false; for(;;) { if(GetFileAttributes(dir)!=0xFFFFFFFF) { sl.LoadFromFile(dir); for(int i=0;i<sl.Count();i++) { String fn=sl[i]; if(fn.Length()==0)continue; if(!(fn[0]=='\\' || fn[1]==':')) { int i=dir.RIndex("\\"); if(i!=-1) { fn.Insert(0,dir.Substr(0,i+1)); } } int z=dir.RIndex("\\"); if(z==-1)z=dir.RIndex(":"); Load(fn,isenv && z!=-1?"":dir.Substr(0,z+1),mainaload); } } if(!isenv) { int bs=dir.RIndex("\\"); if(bs!=-1) { dir.Delete(bs); bs=dir.RIndex("\\"); if(bs!=-1) { dir.Delete(bs+1); dir+=".tags-autoload"; }else { isenv=1; } }else { isenv=1; } if(isenv==1) { if(config.autoload.Length()!=0) { dir=config.autoload; mainaload=true; }else { break; } } }else { break; } } }
HRESULT CEnumCache::Initialize(CTransCache* pQry, DWORD dwCmpMask) { HRESULT hr = S_OK; WCHAR wzFullSearchPath[MAX_PATH+1]; _dwCmpMask = dwCmpMask; DWORD cchRequired=0; WIN32_FIND_DATA FindFileData; LPWSTR pwzCustomPath = lstrlenW(_wzCustomPath) ? _wzCustomPath : NULL; CMutex cCacheMutex(_bNeedMutex ? g_hCacheMutex : INVALID_HANDLE_VALUE); _pQry = pQry; _pQry->AddRef(); _dwCmpMask = dwCmpMask; // custom attribute is set by-default; un-set it if custom blob is not passed-in. if( (_dwCmpMask & ASM_CMPF_CUSTOM) && (!(_pQry->_pInfo->blobCustom.pBlobData) && pQry->GetCacheType() & ASM_CACHE_ZAP)) { _dwCmpMask &= (~ASM_CMPF_CUSTOM); } _dwColumns = _pQry->MapCacheMaskToQueryCols(_dwCmpMask); if( !_dwColumns ) { // _dwColumns == 0 means doing whole table scan _fAll = TRUE; } cchRequired = MAX_PATH; if(FAILED(hr = CreateAssemblyDirPath( pwzCustomPath, 0, _pQry->GetCacheType(), 0, _wzCachePath, &cchRequired))) goto exit; if(FAILED(hr = cCacheMutex.Lock())) goto exit; if(GetFileAttributes(_wzCachePath) == (DWORD) -1) { hr = DB_S_NOTFOUND; _fAllDone = TRUE; goto exit; } if(FAILED(hr = GetAssemblyParentDir( (CTransCache*) _pQry, _wzParentDir))) goto exit; cchRequired = lstrlenW(_wzCachePath) + lstrlenW(_wzParentDir) + lstrlenW(g_szFindAllMask) + 1; // extra chars for "\" etc if (cchRequired >= MAX_PATH) { hr = HRESULT_FROM_WIN32(FUSION_E_INVALID_NAME); goto exit; } StrCpy(wzFullSearchPath, _wzCachePath); if(_fAll) { StrCat(wzFullSearchPath, g_szFindAllMask); _hParentDir = FindFirstFile(wzFullSearchPath, &FindFileData); if(_hParentDir == INVALID_HANDLE_VALUE) { hr = FusionpHresultFromLastError(); goto exit; } StrCat(_wzParentDir, FindFileData.cFileName ); } else { if (!lstrlenW(_wzParentDir)) { hr = DB_S_NOTFOUND; _fAllDone = TRUE; goto exit; } PathAddBackslash(wzFullSearchPath); StrCat(wzFullSearchPath, _wzParentDir); if(GetFileAttributes(wzFullSearchPath) == (DWORD) -1) { hr = DB_S_NOTFOUND; _fAllDone = TRUE; goto exit; } _hParentDone = TRUE; } hr = S_OK; exit: if(FAILED(hr)) _fAllDone = TRUE; return hr; }
int main(int argc, char **argv) { int sending; int portnumber = -1; SOCKET *sklist; int skcount, sksize; int exitcode; int errors; int got_host = FALSE; int use_subsystem = 0; long now, next; sklist = NULL; skcount = sksize = 0; /* * Initialise port and protocol to sensible defaults. (These * will be overridden by more or less anything.) */ default_protocol = PROT_SSH; default_port = 22; flags = FLAG_STDERR; /* * Process the command line. */ do_defaults(NULL, &cfg); loaded_session = FALSE; default_protocol = cfg.protocol; default_port = cfg.port; errors = 0; { /* * Override the default protocol if PLINK_PROTOCOL is set. */ char *p = getenv("PLINK_PROTOCOL"); if (p) { const Backend *b = backend_from_name(p); if (b) { default_protocol = cfg.protocol = b->protocol; default_port = cfg.port = b->default_port; } } } if (argc > 2 && !strcmp(argv[1], "-ini") && *(argv[2]) != '\0') { char* dummy; DWORD attributes; GetFullPathName(argv[2], sizeof inifile, inifile, &dummy); attributes = GetFileAttributes(inifile); if (attributes != 0xFFFFFFFF && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { HANDLE handle = CreateFile(inifile, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle != INVALID_HANDLE_VALUE) { CloseHandle(handle); use_inifile = 1; argc -= 2; argv += 2; } } } while (--argc) { char *p = *++argv; if (*p == '-') { int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), 1, &cfg); if (ret == -2) { fprintf(stderr, "plink: option \"%s\" requires an argument\n", p); errors = 1; } else if (ret == 2) { --argc, ++argv; } else if (ret == 1) { continue; } else if (!strcmp(p, "-batch")) { console_batch_mode = 1; } else if (!strcmp(p, "-s")) { /* Save status to write to cfg later. */ use_subsystem = 1; } else if (!strcmp(p, "-V")) { version(); } else if (!strcmp(p, "-pgpfp")) { pgp_fingerprints(); exit(1); } else { fprintf(stderr, "plink: unknown option \"%s\"\n", p); errors = 1; } } else if (*p) { if (!cfg_launchable(&cfg) || !(got_host || loaded_session)) { char *q = p; /* * If the hostname starts with "telnet:", set the * protocol to Telnet and process the string as a * Telnet URL. */ if (!strncmp(q, "telnet:", 7)) { char c; q += 7; if (q[0] == '/' && q[1] == '/') q += 2; cfg.protocol = PROT_TELNET; p = q; while (*p && *p != ':' && *p != '/') p++; c = *p; if (*p) *p++ = '\0'; if (c == ':') cfg.port = atoi(p); else cfg.port = -1; strncpy(cfg.host, q, sizeof(cfg.host) - 1); cfg.host[sizeof(cfg.host) - 1] = '\0'; got_host = TRUE; } else { char *r, *user, *host; /* * Before we process the [user@]host string, we * first check for the presence of a protocol * prefix (a protocol name followed by ","). */ r = strchr(p, ','); if (r) { const Backend *b; *r = '\0'; b = backend_from_name(p); if (b) { default_protocol = cfg.protocol = b->protocol; portnumber = b->default_port; } p = r + 1; } /* * A nonzero length string followed by an @ is treated * as a username. (We discount an _initial_ @.) The * rest of the string (or the whole string if no @) * is treated as a session name and/or hostname. */ r = strrchr(p, '@'); if (r == p) p++, r = NULL; /* discount initial @ */ if (r) { *r++ = '\0'; user = p, host = r; } else { user = NULL, host = p; } /* * Now attempt to load a saved session with the * same name as the hostname. */ { Config cfg2; do_defaults(host, &cfg2); if (loaded_session || !cfg_launchable(&cfg2)) { /* No settings for this host; use defaults */ /* (or session was already loaded with -load) */ strncpy(cfg.host, host, sizeof(cfg.host) - 1); cfg.host[sizeof(cfg.host) - 1] = '\0'; cfg.port = default_port; got_host = TRUE; } else { cfg = cfg2; loaded_session = TRUE; } } if (user) { /* Patch in specified username. */ strncpy(cfg.username, user, sizeof(cfg.username) - 1); cfg.username[sizeof(cfg.username) - 1] = '\0'; } } } else { char *command; int cmdlen, cmdsize; cmdlen = cmdsize = 0; command = NULL; while (argc) { while (*p) { if (cmdlen >= cmdsize) { cmdsize = cmdlen + 512; command = sresize(command, cmdsize, char); } command[cmdlen++]=*p++; } if (cmdlen >= cmdsize) { cmdsize = cmdlen + 512; command = sresize(command, cmdsize, char); } command[cmdlen++]=' '; /* always add trailing space */ if (--argc) p = *++argv; } if (cmdlen) command[--cmdlen]='\0'; /* change trailing blank to NUL */ cfg.remote_cmd_ptr = command; cfg.remote_cmd_ptr2 = NULL; cfg.nopty = TRUE; /* command => no terminal */ break; /* done with cmdline */ } }
bool MachineInstaller::ShouldSilentInstall() { // Figure out the package name from our own EXE name wchar_t ourFile[MAX_PATH]; HMODULE hMod = GetModuleHandle(NULL); GetModuleFileName(hMod, ourFile, _countof(ourFile)); CString fullPath = CString(ourFile); CString pkgName = CString(ourFile + fullPath.ReverseFind(L'\\')); pkgName.Replace(L".exe", L""); wchar_t installFolder[MAX_PATH]; // C:\Users\Username\AppData\Local\$pkgName\packages SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder); wcscat(installFolder, L"\\"); wcscat(installFolder, pkgName); wcscat(installFolder, L"\\"); wcscat(installFolder, L"packages"); if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) { return false; } // C:\Users\Username\AppData\Local\$pkgName\.dead (was machine-installed but user uninstalled) SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder); wcscat(installFolder, L"\\"); wcscat(installFolder, pkgName); wcscat(installFolder, L"\\"); wcscat(installFolder, L".dead"); if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) { return false; } // C:\ProgramData\$pkgName\$username\packages wchar_t username[512]; DWORD unamesize = _countof(username); SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder); GetUserName(username, &unamesize); wcscat(installFolder, L"\\"); wcscat(installFolder, pkgName); wcscat(installFolder, L"\\"); wcscat(installFolder, username); wcscat(installFolder, L"\\"); wcscat(installFolder, L"packages"); if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) { return false; } // C:\ProgramData\$pkgName\$username\.dead SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder); wcscat(installFolder, L"\\"); wcscat(installFolder, pkgName); wcscat(installFolder, L"\\"); wcscat(installFolder, username); wcscat(installFolder, L"\\"); wcscat(installFolder, L".dead"); if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) { return false; } // None of these exist, we should install return true; }
//----------------------------------------------------------------------------- // Name: WindowProc() // Desc: The Main Window Procedure //----------------------------------------------------------------------------- long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; DWORD xPos, yPos; RECT draw_rect; POINT pt; int i; int demofile_idx; static int num_vectors = 0; static HDC hdc_mem_bkg, hdc_mem_exit_btn; static BITMAP bm_bkg, bm_exit_btn; TCHAR msg_filename_to_play[128]; switch (message) { case WM_CREATE: // Rendering Init mfc_render_init(hWnd); // Check the number of media files in specific folder // and fill the filename list array. num_vectors = find_media_files_fill_array(MEDIA_FILES_FOLDER); hdc_mem_bkg = CreateCompatibleDC(NULL); GetObject(hBmpBkg, sizeof(BITMAP), &bm_bkg); SelectObject(hdc_mem_bkg, (HGDIOBJ)hBmpBkg); hdc_mem_exit_btn = CreateCompatibleDC(NULL); GetObject(hBmpExitButton, sizeof(BITMAP), &bm_exit_btn); SelectObject(hdc_mem_exit_btn, (HGDIOBJ)hBmpExitButton); break; case WM_DESTROY: // Clean up and close the app // SelectObject(hdc_mem, (HGDIOBJ)hBitmapOld); DeleteDC(hdc_mem_bkg); if (hBmpBkg) DeleteObject(hBmpBkg); DeleteDC(hdc_mem_exit_btn); if (hBmpExitButton) DeleteObject(hBmpExitButton); mfc_render_final(); PostQuitMessage(0); return 0L; case WM_LBUTTONDOWN: xPos = LOWORD(lParam); yPos = HIWORD(lParam); pt.x = xPos; pt.y = yPos; // exit 버튼을 누르면 WM_DESTROY 메시지를 날려서 종료시킨다. draw_rect.left = 30+bm_bkg.bmWidth; draw_rect.top = 25; draw_rect.right = draw_rect.left + bm_exit_btn.bmWidth; draw_rect.bottom = draw_rect.top + bm_exit_btn.bmHeight; if (PtInRect(&draw_rect, pt) == TRUE) { SendMessage(hWnd, WM_DESTROY, 0, 0); break; } demofile_idx = GetDemofileIndex(xPos, yPos); mfc_demo_thread_control(hWnd, demofile_idx); break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // Background bitmap image BitBlt(hdc, 20, 20, bm_bkg.bmWidth, bm_bkg.bmHeight, hdc_mem_bkg, 0, 0, SRCCOPY); BitBlt(hdc, 30+bm_bkg.bmWidth, 25, bm_exit_btn.bmWidth, bm_exit_btn.bmHeight, hdc_mem_exit_btn, 0, 0, SRCCOPY); // Rectangle for the "DrawText" function below. draw_rect.left = DRAW_TEXT_X_POS; draw_rect.top = DRAW_TEXT_Y_POS - 60; draw_rect.right = draw_rect.left + DRAW_TEXT_X_LENG; draw_rect.bottom = draw_rect.top + DRAW_TEXT_Y_LENG; wsprintf(msg_filename_to_play, L"Press the file name to play.\n(In %s folder)", MEDIA_FILES_FOLDER); FillRect(hdc, &draw_rect, (HBRUSH) GetStockObject(WHITE_BRUSH)); DrawText(hdc, msg_filename_to_play, -1, &draw_rect, DT_CENTER); // Move the rectangle for the media filenames list draw_rect.left = DRAW_TEXT_X_POS; draw_rect.top = DRAW_TEXT_Y_POS; draw_rect.right = draw_rect.left + DRAW_TEXT_X_LENG; draw_rect.bottom = draw_rect.top + DRAW_TEXT_Y_LENG; for (i=0; i<num_vectors; i++) { if (GetFileAttributes(*(array_pszFileNames[i])) != 0xFFFFFFFF) DrawText(hdc, *(array_pszFileNames[i]), -1, &draw_rect, DT_LEFT); draw_rect.top += DRAW_TEXT_Y_LENG; draw_rect.bottom += DRAW_TEXT_Y_LENG; } EndPaint(hWnd, &ps); break; } return DefWindowProc(hWnd, message, wParam, lParam); }