BOOL CConfigMsgLogDlg::OnInitDialog() { CDialog::OnInitDialog(); m_ChkbEnableLogOnConnect.SetCheck(m_bLogOnConnect == TRUE? BST_CHECKED : BST_UNCHECKED); m_odStartMsgID.vSetConfigData(IDC_EDIT_STARTMSGID); m_odStopMsgID.vSetConfigData(IDC_EDIT_STOPMSGID); m_odStartMsgID.vSetBase(BASE_HEXADECIMAL); m_odStopMsgID.vSetBase(BASE_HEXADECIMAL); m_odStartMsgID.vSetSigned(false); m_odStopMsgID.vSetSigned(false); vCreateFileList(); if(m_eCurrBus == CAN || m_eCurrBus == J1939) { //Load channel combo box m_omComboChannel.ResetContent(); if (NULL != GetICANDIL()) { LPARAM lParam = 0; if (S_OK == GetICANDIL()->DILC_GetControllerParams(lParam, NULL, NUMBER_HW)) { m_unChannelCount = (UINT)lParam; } } m_omComboChannel.InsertString(0, _("ALL")); for (UINT i = 1; i <= m_unChannelCount; i++) { CString omChannel; omChannel.Format("%d", i); m_omComboChannel.InsertString(i, omChannel.GetBuffer(MAX_PATH)); } m_omComboChannel.SetCurSel(0); } else if(m_eCurrBus == LIN) { //Load channel combo box m_omComboChannel.ResetContent(); if (NULL != GetILINDIL()) { LPARAM lParam = 0; if (S_OK == GetILINDIL()->DILL_GetControllerParams(lParam, NULL, NUMBER_HW)) { m_unChannelCount = (UINT)lParam; } } m_omComboChannel.InsertString(0, _("ALL")); for (UINT i = 1; i <= m_unChannelCount; i++) { CString omChannel; omChannel.Format("%d", i); m_omComboChannel.InsertString(i, omChannel.GetBuffer(MAX_PATH)); } m_omComboChannel.SetCurSel(0); } USHORT LogBlocks = GetLoggingBlockCount(); if (LogBlocks > 0) { for (USHORT i = 0; i < LogBlocks; i++) { SLOGINFO sLogObject; HANDLE hFind; WIN32_FIND_DATA FindData; CStdioFile omStdiofile; GetLoggingBlock(i, sLogObject); // check for valid log file CString strTempLog = sLogObject.m_sLogFileName; hFind = FindFirstFile(strTempLog, &FindData); if(hFind == INVALID_HANDLE_VALUE )//file not found { DWORD dError = GetLastError(); if(dError == ERROR_FILE_NOT_FOUND)//file not found { BOOL bFileOpen = omStdiofile.Open(strTempLog, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary); if(bFileOpen == TRUE)///file created, add in the list { omStdiofile.Close(); AddNewItem_GUI(sLogObject, i); } else //not a valid file { RemoveLoggingBlock(i--); //remove the old log data LogBlocks = GetLoggingBlockCount(); //refresh the log count } } else //not a valid filepath / file folder is removed { RemoveLoggingBlock(i--); //remove the old log data LogBlocks = GetLoggingBlockCount(); //refresh the log count } } else ///file found add in the list { AddNewItem_GUI(sLogObject, i); } } m_nLogIndexSel = 0; if(m_omListLogFiles.GetItemCount() > 0 )//check for log files exists { m_omListLogFiles.SetItemState(m_nLogIndexSel, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); } else { vEnableDisableControls(FALSE);//disable controls if no log files exists } } else { vEnableDisableControls(FALSE); } SetWindowText(m_strCurrWndText); if (m_bLogON) { vEnableDisableControls(FALSE); if(m_omListLogFiles.GetItemCount()>0) { vUpdate_GUI_From_Datastore(0); } GetDlgItem(IDC_CBTN_ADDLOG)->EnableWindow(FALSE); GetDlgItem(IDC_CHECK_RESET_TIMESTAMP)->EnableWindow(FALSE); GetWindowText(m_strCurrWndText); m_strCurrWndText+=_(" - Read Only as Logging is ON"); SetWindowText(m_strCurrWndText); // If Logging is on GetDlgItem(IDOK)->EnableWindow(FALSE); m_unDispUpdateTimerId = SetTimer(600, 600, NULL); } else { // PTV [1.6.4] // If Logging is on GetDlgItem(IDOK)->EnableWindow(TRUE); // PTV [1.6.4] } // Hide or show the Filters button in the dialog based on the protocol if (CAN == m_eCurrBus) { GetDlgItem(IDC_LOG_FILTER)->ShowWindow(1); } else if (J1939 == m_eCurrBus) { GetDlgItem(IDC_LOG_FILTER)->ShowWindow(0); } //Shashank else if(LIN == m_eCurrBus) { GetDlgItem(IDC_LOG_FILTER)->ShowWindow(0); } return TRUE; }
void TargetNode::Wildcards() { TargetNode *pTarget, *pTargetFile; if ( GetType() == TARGET_PROJECT ) { GetNodeC()->Wildcards(); GetNodeH()->Wildcards(); pTarget = GetFirstChildPRJ(); while ( pTarget ) { pTarget->Wildcards(); pTarget= pTarget->GetNext(); } } else if ( GetType() == NODE_FILE_C || GetType() == NODE_FILE_H ) { char szDrive [_MAX_DRIVE +1], szFoundDrive[_MAX_DRIVE +1]; char szDir [_MAX_DIR +1], szFoundDir [_MAX_DIR +1]; char szFname [_MAX_PATH +1], szFoundFname[_MAX_PATH +1]; char szExt [_MAX_EXT +1], szFoundExt [_MAX_EXT +1]; char szWildcardsPath [_MAX_PATH +1], szFoundFile [_MAX_DIR +1]; char szEmpty[] = ""; WIN32_FIND_DATA FileFindData; SetAllWorkFlagsToTrue(); while ( TRUE ) { pTargetFile = GetFirstChildTarget(); while ( pTargetFile ) { if ( pTargetFile-> GetWorkFlag() ) { _splitpath( pTargetFile->GetFileName(), szDrive, szDir, szFname, szExt ); if ( szFname[0] != '*' ) break; } pTargetFile= pTargetFile->GetNext(); } if ( pTargetFile == NULL ) break; pTargetFile->SetWorkFlagToFalse(); _splitpath( pTargetFile->GetFilePath(), szFoundDrive, szFoundDir, szFoundFname, szFoundExt ); strcpy( szFoundFname, "*" ); _makepath( szWildcardsPath, szFoundDrive, szFoundDir, szFoundFname, szFoundExt ); int nMatchedFiles=0, nNoMatchedFiles = 0; HANDLE hFindFile = FindFirstFile( szWildcardsPath, &FileFindData ); if ( hFindFile != INVALID_HANDLE_VALUE ) do { _makepath( szFoundFile, szFoundDrive, szFoundDir, FileFindData.cFileName, szEmpty ); pTarget = GetFirstChildTarget(); while ( pTarget ) { if ( stricmp( pTarget->GetFilePath(), szFoundFile ) == 0 ) break; pTarget= pTarget->GetNext(); } if ( pTarget ) { nMatchedFiles++; pTarget->SetWorkFlagToFalse(); } else nNoMatchedFiles++; } while ( FindNextFile( hFindFile, &FileFindData ) ); if ( nMatchedFiles && (nNoMatchedFiles==0 || (nNoMatchedFiles*100)/nMatchedFiles<=50) ) { hFindFile = FindFirstFile( szWildcardsPath, &FileFindData ); do { _makepath( szFoundFile, szFoundDrive, szFoundDir, FileFindData.cFileName, szEmpty ); pTarget = GetFirstChildTarget(); while ( pTarget ) { if ( stricmp( pTarget->GetFilePath(), szFoundFile ) == 0 ) break; pTarget= pTarget->GetNext(); } if ( pTarget ) pTarget->SetDeleteFlag(); else // szFoundFile is not matched to project's files, insert new one { char* pszPath = GetParentPRJ()->GetFilePath(); int nPathLen = strlen( pszPath ); pTargetFile = new TargetNode (szFoundFile, this, GetFirstChildTarget()->GetType()); if ( strstr( pTargetFile->GetFilePath(), pszPath) ) pTargetFile->SetFileName( pTargetFile->GetFilePath() + nPathLen); else pTargetFile->SetFileName( pTargetFile->GetFilePath() ); pTargetFile->SetExclusionFlag(); pTargetFile->SetWorkFlagToFalse(); } } while ( FindNextFile( hFindFile, &FileFindData ) ); // ----------------- delete matched files pTargetFile = GetFirstChildTarget(); BOOL bFirstFlag = TRUE; while ( pTargetFile ) { pTarget = pTargetFile->GetNext(); if ( pTargetFile-> GetDeleteFlag() ) { if ( bFirstFlag ) { _splitpath( pTargetFile->GetFileName(), szDrive, szDir, szFname, szExt ); strcpy( szFname, "*" ); _makepath( pTargetFile->GetFileName(), szDrive, szDir, szFname, szExt ); _splitpath( pTargetFile->GetFilePath(), szDrive, szDir, szFname, szExt ); strcpy( szFname, "*" ); _makepath( pTargetFile->GetFilePath(), szDrive, szDir, szFname, szExt ); bFirstFlag = FALSE; } else delete pTargetFile; } pTargetFile= pTarget; } } // if ( bFindAllFilesFlag ) } // while (TRUE ) } // else if ( GetType() == NODE_FILE_C || GetType() == NODE_FILE_H ) }
int pcap_findalldevs_ex(const char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf) { int type; char name[PCAP_BUF_SIZE], path[PCAP_BUF_SIZE], filename[PCAP_BUF_SIZE]; size_t pathlen; size_t stringlen; pcap_t *fp; char tmpstring[PCAP_BUF_SIZE + 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */ pcap_if_t *lastdev; /* Last device in the pcap_if_t list */ pcap_if_t *dev; /* Device we're adding to the pcap_if_t list */ /* List starts out empty. */ (*alldevs) = NULL; lastdev = NULL; if (strlen(source) > PCAP_BUF_SIZE) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The source string is too long. Cannot handle it correctly."); return -1; } /* * Determine the type of the source (file, local, remote) * There are some differences if pcap_findalldevs_ex() is called to list files and remote adapters. * In the first case, the name of the directory we have to look into must be present (therefore * the 'name' parameter of the pcap_parsesrcstr() is present). * In the second case, the name of the adapter is not required (we need just the host). So, we have * to use a first time this function to get the source type, and a second time to get the appropriate * info, which depends on the source type. */ if (pcap_parsesrcstr(source, &type, NULL, NULL, NULL, errbuf) == -1) return -1; switch (type) { case PCAP_SRC_IFLOCAL: if (pcap_parsesrcstr(source, &type, NULL, NULL, NULL, errbuf) == -1) return -1; /* Initialize temporary string */ tmpstring[PCAP_BUF_SIZE] = 0; /* The user wants to retrieve adapters from a local host */ if (pcap_findalldevs(alldevs, errbuf) == -1) return -1; if (*alldevs == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "No interfaces found! Make sure libpcap/Npcap is properly installed" " on the local machine."); return -1; } /* Scan all the interfaces and modify name and description */ /* This is a trick in order to avoid the re-implementation of the pcap_findalldevs here */ dev = *alldevs; while (dev) { char *localdesc, *desc; /* Create the new device identifier */ if (pcap_createsrcstr(tmpstring, PCAP_SRC_IFLOCAL, NULL, NULL, dev->name, errbuf) == -1) return -1; /* Delete the old pointer */ free(dev->name); /* Make a copy of the new device identifier */ dev->name = strdup(tmpstring); if (dev->name == NULL) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "malloc() failed"); pcap_freealldevs(*alldevs); return -1; } /* * Create the description. */ if ((dev->description == NULL) || (dev->description[0] == 0)) localdesc = dev->name; else localdesc = dev->description; if (pcap_asprintf(&desc, "%s '%s' %s", PCAP_TEXT_SOURCE_ADAPTER, localdesc, PCAP_TEXT_SOURCE_ON_LOCAL_HOST) == -1) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "malloc() failed"); pcap_freealldevs(*alldevs); return -1; } /* Now overwrite the description */ free(dev->description); dev->description = desc; dev = dev->next; } return 0; case PCAP_SRC_FILE: { #ifdef _WIN32 WIN32_FIND_DATA filedata; HANDLE filehandle; #else struct dirent *filedata; DIR *unixdir; #endif if (pcap_parsesrcstr(source, &type, NULL, NULL, name, errbuf) == -1) return -1; /* Check that the filename is correct */ stringlen = strlen(name); /* The directory must end with '\' in Win32 and '/' in UNIX */ #ifdef _WIN32 #define ENDING_CHAR '\\' #else #define ENDING_CHAR '/' #endif if (name[stringlen - 1] != ENDING_CHAR) { name[stringlen] = ENDING_CHAR; name[stringlen + 1] = 0; stringlen++; } /* Save the path for future reference */ pcap_snprintf(path, sizeof(path), "%s", name); pathlen = strlen(path); #ifdef _WIN32 /* To perform directory listing, Win32 must have an 'asterisk' as ending char */ if (name[stringlen - 1] != '*') { name[stringlen] = '*'; name[stringlen + 1] = 0; } filehandle = FindFirstFile(name, &filedata); if (filehandle == INVALID_HANDLE_VALUE) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error when listing files: does folder '%s' exist?", path); return -1; } #else /* opening the folder */ unixdir= opendir(path); /* get the first file into it */ filedata= readdir(unixdir); if (filedata == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error when listing files: does folder '%s' exist?", path); return -1; } #endif /* Add all files we find to the list. */ do { #ifdef _WIN32 /* Skip the file if the pathname won't fit in the buffer */ if (pathlen + strlen(filedata.cFileName) >= sizeof(filename)) continue; pcap_snprintf(filename, sizeof(filename), "%s%s", path, filedata.cFileName); #else if (pathlen + strlen(filedata->d_name) >= sizeof(filename)) continue; pcap_snprintf(filename, sizeof(filename), "%s%s", path, filedata->d_name); #endif fp = pcap_open_offline(filename, errbuf); if (fp) { /* allocate the main structure */ dev = (pcap_if_t *)malloc(sizeof(pcap_if_t)); if (dev == NULL) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "malloc() failed"); pcap_freealldevs(*alldevs); return -1; } /* Initialize the structure to 'zero' */ memset(dev, 0, sizeof(pcap_if_t)); /* Append it to the list. */ if (lastdev == NULL) { /* * List is empty, so it's also * the first device. */ *alldevs = dev; } else { /* * Append after the last device. */ lastdev->next = dev; } /* It's now the last device. */ lastdev = dev; /* Create the new source identifier */ if (pcap_createsrcstr(tmpstring, PCAP_SRC_FILE, NULL, NULL, filename, errbuf) == -1) { pcap_freealldevs(*alldevs); return -1; } dev->name = strdup(tmpstring); if (dev->name == NULL) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "malloc() failed"); pcap_freealldevs(*alldevs); return -1; } /* * Create the description. */ if (pcap_asprintf(&dev->description, "%s '%s' %s", PCAP_TEXT_SOURCE_FILE, filename, PCAP_TEXT_SOURCE_ON_LOCAL_HOST) == -1) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "malloc() failed"); pcap_freealldevs(*alldevs); return -1; } pcap_close(fp); } } #ifdef _WIN32 while (FindNextFile(filehandle, &filedata) != 0); #else while ( (filedata= readdir(unixdir)) != NULL); #endif #ifdef _WIN32 /* Close the search handle. */ FindClose(filehandle); #endif return 0; } case PCAP_SRC_IFREMOTE: return pcap_findalldevs_ex_remote(source, auth, alldevs, errbuf); default: pcap_strlcpy(errbuf, "Source type not supported", PCAP_ERRBUF_SIZE); return -1; } }
/** Finds the executable and parameter list associated with the provided extension. */ BOOL GetExecutableAndArgumentTemplateByExtention ( LPCSTR extension, LPSTR executable, LPSTR arguments ) { DWORD last_error = ERROR_SUCCESS; LONG result, length; CHAR value[MAX_PATH+1], key[MAX_PATH+1], name[MAX_PATH+1], uppercase[MAX_PATH+1], default_verb[] = "Open"; LPSTR verb = NULL; HANDLE found = INVALID_HANDLE_VALUE; WIN32_FIND_DATA find_data; LPSTR tmp, start = NULL; BOOL quoted = FALSE, expanded = FALSE, ok = FALSE; __try { /* make sure the output buffers not contain any misleading information, if we are to fail */ executable[0] = '\0'; if ( arguments ) { arguments[0] = '\0'; } /* using the extension, find the script type (or program ID) */ length = MAX_PATH; result = RegQueryValue ( HKEY_CLASSES_ROOT, extension, (LPSTR) value, &length ); if ( ERROR_SUCCESS != result ) { last_error = result; dprintf ( D_ALWAYS, "GetExecutableAndArgumentsByExtention: failed to find " "extension *%s in the registry (last-error = %d).\n", extension, last_error ); __leave; } /* Because some file types have /n/ verb handlers, there is no intelligent way we can choose which one to use. The verb 'Open' is the most common, but we allow the user define one if they want. */ strcpy ( uppercase, extension + 1 ); sprintf ( name, "OPEN_VERB_FOR_%s_FILES", strupr ( uppercase ) ); verb = param ( name ); sprintf ( key, "%s\\Shell\\%s\\Command", value, verb ? verb : default_verb ); if ( verb ) { free ( verb ); } length = MAX_PATH; result = RegQueryValue ( HKEY_CLASSES_ROOT, key, (LPSTR) value, &length ); if ( ERROR_SUCCESS != result ) { last_error = result; dprintf ( D_ALWAYS, "GetExecutableAndArgumentsByExtention: failed to " "find a suitable handler for files with extension " "'*%s'. (last-error = %d)\n", extension, last_error ); __leave; } /* we now have the command-line. First, let's trim all the leading whitespace. */ tmp = (LPSTR) value; /* strip leading spaces */ while ( *tmp && isspace ( *tmp ) ) { tmp++; } /* we are now at the start of the executable's path */ start = tmp; /* if the executable is surrounded by quotes, then we want to ignore all whitespace until we see another quote--after that we will stop. */ quoted = ( '"' == *start ); /* step through the executable's path until we reach either the closing quote, a whitespace character or NULL. */ if ( quoted ) { /* skip first quote because FindFirstFile() does not work if there are quotes surrounding a script name. */ start = ++tmp; while ( *tmp && ( '"' != *tmp ) ) { tmp++; } } else { start = tmp; while ( *tmp && !isspace ( *tmp ) ) { tmp++; } } /* null terminate at the closing quote, the first whitespace character or at the end of the buffer. */ *tmp = '\0'; /* validate the executable's existence */ found = FindFirstFile ( start, &find_data ); if ( INVALID_HANDLE_VALUE == found ) { last_error = GetLastError (); dprintf ( D_ALWAYS, "GetExecutableAndArgumentsByExtention: failed to " "locate the executable, %s, to handle files " "with extension '*%s'. (last-error = %d)\n", start, extension, last_error ); __leave; } /* clean-up after the script search */ FindClose ( found ); /* finally, copy the executable path */ strcpy ( executable, start ); /* if we have not already consumed the entire buffer, then copy the rest as the arguments to the executable */ start = ++tmp; if ( arguments && value - start < length - 1 ) { /* strip leading space until we are at the start of the executable's arguments */ while ( *start && isspace ( *start ) ) { start++; } /* make a copy of the arguments */ strcpy ( arguments, start ); } /* if we made it here, then we're all going to be ok */ ok = TRUE; } __finally { /* propagate the last error to our caller */ SetLastError ( ok ? ERROR_SUCCESS : last_error ); }; return ok; }
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); } }
VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv) { char exe_path[MAX_PATH]; char config_dir[MAX_PATH]; char ext_string[16]; char log_dir[MAX_PATH]; char priority_string[64]; char append_string[2]; DWORD priority; bool append; ResetError (); if (!ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 3000)) { MSG (M_ERR, "ReportStatusToSCMgr #1 failed"); goto finish; } /* * Create our exit event */ exit_event = create_event (EXIT_EVENT_NAME, false, false, true); if (!exit_event) { MSG (M_ERR, "CreateEvent failed"); goto finish; } /* * If exit event is already signaled, it means we were not * shut down properly. */ if (WaitForSingleObject (exit_event, 0) != WAIT_TIMEOUT) { MSG (M_ERR, "Exit event is already signaled -- we were not shut down properly"); goto finish; } if (!ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 3000)) { MSG (M_ERR, "ReportStatusToSCMgr #2 failed"); goto finish; } /* * Read info from registry in key HKLM\SOFTWARE\OpenVPN */ { HKEY openvpn_key; LONG status; DWORD len; DWORD type; static const char error_format_str[] = "Error querying registry key of type REG_SZ: HKLM\\" REG_KEY "\\%s"; static const char error_format_dword[] = "Error querying registry key of type REG_DWORD: HKLM\\" REG_KEY "\\%s"; status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, REG_KEY, 0, KEY_READ, &openvpn_key); if (status != ERROR_SUCCESS) { SetLastError (status); MSG (M_SYSERR, "Registry key HKLM\\" REG_KEY " not found"); goto finish; } /* get path to openvpn.exe */ QUERY_REG_STRING ("exe_path", exe_path); /* get path to configuration directory */ QUERY_REG_STRING ("config_dir", config_dir); /* get extension on configuration files */ QUERY_REG_STRING ("config_ext", ext_string); /* get path to log directory */ QUERY_REG_STRING ("log_dir", log_dir); /* get priority for spawned OpenVPN subprocesses */ QUERY_REG_STRING ("priority", priority_string); /* should we truncate or append to logfile? */ QUERY_REG_STRING ("log_append", append_string); RegCloseKey (openvpn_key); } /* set process priority */ priority = NORMAL_PRIORITY_CLASS; if (!_stricmp (priority_string, "IDLE_PRIORITY_CLASS")) priority = IDLE_PRIORITY_CLASS; else if (!_stricmp (priority_string, "BELOW_NORMAL_PRIORITY_CLASS")) priority = BELOW_NORMAL_PRIORITY_CLASS; else if (!_stricmp (priority_string, "NORMAL_PRIORITY_CLASS")) priority = NORMAL_PRIORITY_CLASS; else if (!_stricmp (priority_string, "ABOVE_NORMAL_PRIORITY_CLASS")) priority = ABOVE_NORMAL_PRIORITY_CLASS; else if (!_stricmp (priority_string, "HIGH_PRIORITY_CLASS")) priority = HIGH_PRIORITY_CLASS; else { MSG (M_ERR, "Unknown priority name: %s", priority_string); goto finish; } /* set log file append/truncate flag */ append = false; if (append_string[0] == '0') append = false; else if (append_string[0] == '1') append = true; else { MSG (M_ERR, "Log file append flag (given as '%s') must be '0' or '1'", append_string); goto finish; } /* * Instantiate an OpenVPN process for each configuration * file found. */ { WIN32_FIND_DATA find_obj; HANDLE find_handle; BOOL more_files; char find_string[MAX_PATH]; openvpn_snprintf (find_string, MAX_PATH, "%s\\*", config_dir); find_handle = FindFirstFile (find_string, &find_obj); if (find_handle == INVALID_HANDLE_VALUE) { MSG (M_ERR, "Cannot get configuration file list using: %s", find_string); goto finish; } /* * Loop over each config file */ do { HANDLE log_handle = NULL; STARTUPINFO start_info; PROCESS_INFORMATION proc_info; struct security_attributes sa; char log_file[MAX_PATH]; char log_path[MAX_PATH]; char command_line[256]; CLEAR (start_info); CLEAR (proc_info); CLEAR (sa); if (!ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 3000)) { MSG (M_ERR, "ReportStatusToSCMgr #3 failed"); FindClose (find_handle); goto finish; } /* does file have the correct type and extension? */ if (match (&find_obj, ext_string)) { /* get log file pathname */ if (!modext (log_file, sizeof (log_file), find_obj.cFileName, "log")) { MSG (M_ERR, "Cannot construct logfile name based on: %s", find_obj.cFileName); FindClose (find_handle); goto finish; } openvpn_snprintf (log_path, sizeof(log_path), "%s\\%s", log_dir, log_file); /* construct command line */ openvpn_snprintf (command_line, sizeof(command_line), PACKAGE " --service %s 1 --config \"%s\"", EXIT_EVENT_NAME, find_obj.cFileName); /* Make security attributes struct for logfile handle so it can be inherited. */ if (!init_security_attributes_allow_all (&sa)) { MSG (M_SYSERR, "InitializeSecurityDescriptor start_" PACKAGE " failed"); goto finish; } /* open logfile as stdout/stderr for soon-to-be-spawned subprocess */ log_handle = CreateFile (log_path, GENERIC_WRITE, FILE_SHARE_READ, &sa.sa, append ? OPEN_ALWAYS : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (log_handle == INVALID_HANDLE_VALUE) { MSG (M_SYSERR, "Cannot open logfile: %s", log_path); FindClose (find_handle); goto finish; } /* append to logfile? */ if (append) { if (SetFilePointer (log_handle, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER) { MSG (M_SYSERR, "Cannot seek to end of logfile: %s", log_path); FindClose (find_handle); goto finish; } } /* fill in STARTUPINFO struct */ GetStartupInfo(&start_info); start_info.cb = sizeof(start_info); start_info.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW; start_info.wShowWindow = SW_HIDE; start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE); start_info.hStdOutput = start_info.hStdError = log_handle; /* create an OpenVPN process for one config file */ if (!CreateProcess(exe_path, command_line, NULL, NULL, TRUE, priority | CREATE_NEW_CONSOLE, NULL, config_dir, &start_info, &proc_info)) { MSG (M_SYSERR, "CreateProcess failed, exe='%s' cmdline='%s' dir='%s'", exe_path, command_line, config_dir); FindClose (find_handle); CloseHandle (log_handle); goto finish; } /* close unneeded handles */ Sleep (1000); /* try to prevent race if we close logfile handle before child process DUPs it */ if (!CloseHandle (proc_info.hProcess) || !CloseHandle (proc_info.hThread) || !CloseHandle (log_handle)) { MSG (M_SYSERR, "CloseHandle failed"); goto finish; } } /* more files to process? */ more_files = FindNextFile (find_handle, &find_obj); } while (more_files); FindClose (find_handle); } /* we are now fully started */ if (!ReportStatusToSCMgr(SERVICE_RUNNING, NO_ERROR, 0)) { MSG (M_ERR, "ReportStatusToSCMgr SERVICE_RUNNING failed"); goto finish; } /* wait for our shutdown signal */ if (WaitForSingleObject (exit_event, INFINITE) != WAIT_OBJECT_0) { MSG (M_ERR, "wait for shutdown signal failed"); } finish: ServiceStop (); if (exit_event) CloseHandle (exit_event); }
void parseheader(char *path) { WIN32_FIND_DATA fd; HANDLE handle; int len = 0; char *listpath = (char*)calloc(strlen(path)+9,sizeof(char)); FILE *list = NULL; int listoffset = 0, listsize = 0; strncpy(listpath, path, strlen(path)-1); strcat(listpath,"list.txt\0"); list = fopen(listpath,"r"); free(listpath); if(!list) { printf("Could not open list.txt\n"); exit(-1); } while(!feof(list)) { char str[512]; fgets(str, 512, list); listfiles++; } rewind(list); offset = listfiles*8; handle = FindFirstFile(path,&fd); do { if(strcmp(fd.cFileName,".") != 0 && strcmp(fd.cFileName,"..") != 0 && strcmp(fd.cFileName,"list.txt") != 0&& !(fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) { FILE *infile = NULL; char *inpath = (char*)calloc(strlen(path)+strlen(fd.cFileName)+1,sizeof(char)); if((offset%PADDING)!=0) offset += PADDING - (offset%PADDING); strncpy(inpath, path, strlen(path)-1); strcat(inpath,fd.cFileName); infile = fopen(inpath, "rb"); if(!infile) { printf("Could not open %s\n",inpath); exit(1); } fseek(infile,0,SEEK_END); len = ftell(infile); fclose(infile); fscanf(list,"%08x %08x",&listoffset, &listsize); if(listsize == 0) { while(listsize == 0 && !feof(list)) { fwrite(&offset,1,4,outfile); fwrite(&listsize,1,4,outfile); fscanf(list,"%08x %08x",&listoffset, &listsize); } } fwrite(&offset,1,4,outfile); fwrite(&len,1,4,outfile); offset += len; len = 0; free(inpath); } } while(FindNextFile(handle,&fd) != 0); fscanf(list,"%08x %08x",&listoffset, &listsize); if(listsize == 0) { while(listsize == 0 && !feof(list)) { fwrite(&offset,1,4,outfile); fwrite(&listsize,1,4,outfile); fscanf(list,"%08x %08x",&listoffset, &listsize); } } if(!feof(list)) { printf("Probably didn't have all of the required files\n"); } fwrite(&offset,1,4,outfile); fwrite(&len,1,4,outfile); fclose(list); }
static void FillListBox() { WIN32_FIND_DATA wfd; HANDLE hSearch; TCHAR szFilePath[MAX_PATH]; TCHAR szFilePathSearch[MAX_PATH]; TCHAR szFileName[MAX_PATH]; TCHAR *PatchDesc = NULL; TCHAR PatchName[256]; int nHandlePos = 0; TV_INSERTSTRUCT TvItem; memset(&TvItem, 0, sizeof(TvItem)); TvItem.item.mask = TVIF_TEXT | TVIF_PARAM; TvItem.hInsertAfter = TVI_LAST; _stprintf(szFilePath, _T("%s%s\\"), szAppIpsPath, BurnDrvGetText(DRV_NAME)); _stprintf(szFilePathSearch, _T("%s*.dat"), szFilePath); hSearch = FindFirstFile(szFilePathSearch, &wfd); if (hSearch != INVALID_HANDLE_VALUE) { int Done = 0; while (!Done ) { memset(szFileName, '\0', MAX_PATH); _stprintf(szFileName, _T("%s%s"), szFilePath, wfd.cFileName); FILE *fp = _tfopen(szFileName, _T("r")); if (fp) { PatchDesc = NULL; memset(PatchName, '\0', 256); PatchDesc = GetPatchDescByLangcode(fp, nIpsSelectedLanguage); // If not available - try English first if (PatchDesc == NULL) PatchDesc = GetPatchDescByLangcode(fp, 0); // Simplified Chinese is the reference language (should always be available!!) if (PatchDesc == NULL) PatchDesc = GetPatchDescByLangcode(fp, 1); for (unsigned int i = 0; i < _tcslen(PatchDesc); i++) { if (PatchDesc[i] == '\r' || PatchDesc[i] == '\n') break; PatchName[i] = PatchDesc[i]; } // Check for categories TCHAR *Tokens; int nNumTokens = 0; int nNumNodes = 0; TCHAR szCategory[256]; unsigned int nPatchNameLength = _tcslen(PatchName); Tokens = _tcstok(PatchName, _T("/")); while (Tokens != NULL) { if (nNumTokens == 0) { int bAddItem = 1; // Check if item already exists nNumNodes = SendMessage(hIpsList, TVM_GETCOUNT, (WPARAM)0, (LPARAM)0); for (int i = 0; i < nNumNodes; i++) { TCHAR Temp[256]; TVITEM Tvi; memset(&Tvi, 0, sizeof(Tvi)); Tvi.hItem = hItemHandles[i]; Tvi.mask = TVIF_TEXT | TVIF_HANDLE; Tvi.pszText = Temp; Tvi.cchTextMax = 256; SendMessage(hIpsList, TVM_GETITEM, (WPARAM)0, (LPARAM)&Tvi); if (!_tcsicmp(Tvi.pszText, Tokens)) bAddItem = 0; } if (bAddItem) { TvItem.hParent = TVI_ROOT; TvItem.item.pszText = Tokens; hItemHandles[nHandlePos] = (HTREEITEM)SendMessage(hIpsList, TVM_INSERTITEM, 0, (LPARAM)&TvItem); nHandlePos++; } if (_tcslen(Tokens) == nPatchNameLength) { hPatchHandlesIndex[nPatchIndex] = hItemHandles[nHandlePos - 1]; _tcscpy(szPatchFileNames[nPatchIndex], szFileName); nPatchIndex++; } _tcscpy(szCategory, Tokens); } else { HTREEITEM hNode = TVI_ROOT; // See which category we should be in nNumNodes = SendMessage(hIpsList, TVM_GETCOUNT, (WPARAM)0, (LPARAM)0); for (int i = 0; i < nNumNodes; i++) { TCHAR Temp[256]; TVITEM Tvi; memset(&Tvi, 0, sizeof(Tvi)); Tvi.hItem = hItemHandles[i]; Tvi.mask = TVIF_TEXT | TVIF_HANDLE; Tvi.pszText = Temp; Tvi.cchTextMax = 256; SendMessage(hIpsList, TVM_GETITEM, (WPARAM)0, (LPARAM)&Tvi); if (!_tcsicmp(Tvi.pszText, szCategory)) hNode = Tvi.hItem; } TvItem.hParent = hNode; TvItem.item.pszText = Tokens; hItemHandles[nHandlePos] = (HTREEITEM)SendMessage(hIpsList, TVM_INSERTITEM, 0, (LPARAM)&TvItem); hPatchHandlesIndex[nPatchIndex] = hItemHandles[nHandlePos]; _tcscpy(szPatchFileNames[nPatchIndex], szFileName); nHandlePos++; nPatchIndex++; } Tokens = _tcstok(NULL, _T("/")); nNumTokens++; } fclose(fp); } Done = !FindNextFile(hSearch, &wfd); } FindClose(hSearch); } nNumPatches = nPatchIndex; // Expand all branches int nNumNodes = SendMessage(hIpsList, TVM_GETCOUNT, (WPARAM)0, (LPARAM)0);; for (int i = 0; i < nNumNodes; i++) { SendMessage(hIpsList, TVM_EXPAND, TVE_EXPAND, (LPARAM)hItemHandles[i]); } }
bool CSADirRead::GetSubDirs(CCOMList<CSADirEntry> &dir_array, const CCOMString &path) { CCOMString newPath; CCOMString searchString; searchString = path; searchString+= "\\*.*"; try { #ifndef USE_WIN32_FINDFILE struct _finddata_t c_file; long fhandle; if ((fhandle=_findfirst( searchString, &c_file ))!=-1) { // we only care about subdirs if ((c_file.attrib & _A_SUBDIR)==_A_SUBDIR) { // add c_file.name to the string array // we'll handle parents on our own if ((strcmp(c_file.name, ".")!=0) && (strcmp(c_file.name, "..")!=0)) { newPath = path; newPath+= "\\"; newPath+= c_file.name; GetSubDirs(dir_array, newPath); dir_array.push_back(newPath); } } // find the rest of them while(_findnext( fhandle, &c_file ) == 0 ) { if ((c_file.attrib & _A_SUBDIR)==_A_SUBDIR) { // we'll handle parents on our own if ((strcmp(c_file.name, ".")!=0) && (strcmp(c_file.name, "..")!=0)) { newPath = path; newPath+= "\\"; newPath+= c_file.name; GetSubDirs(dir_array, newPath); dir_array.push_back(newPath); } } } _findclose(fhandle); } #else WIN32_FIND_DATA FindFileData; HANDLE hFind; if ((hFind = FindFirstFile(searchString, &FindFileData))!=INVALID_HANDLE_VALUE) { // we only care about files, not subdirs if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY) { // we'll handle parents on our own if ((strcmp(FindFileData.cFileName, ".")!=0) && (strcmp(FindFileData.cFileName, "..")!=0)) { newPath = path; newPath+= "\\"; newPath+=FindFileData.cFileName; GetSubDirs(dir_array, newPath); dir_array.push_back(newPath); } } // find the rest of them while(FindNextFile( hFind, &FindFileData )) { // we only care about files, not subdirs if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY) { // we'll handle parents on our own if ((strcmp(FindFileData.cFileName, ".")!=0) && (strcmp(FindFileData.cFileName, "..")!=0)) { newPath = path; newPath+= "\\"; newPath+=FindFileData.cFileName; GetSubDirs(dir_array, newPath); dir_array.push_back(newPath); } } } } FindClose(hFind); #endif } catch (...) { return false; } return true; }
void CPlaylistItem::AutoLoadFiles() { if (m_fns.IsEmpty()) { return; } const CAppSettings& s = AfxGetAppSettings(); CString fn = m_fns.GetHead(); if (s.fAutoloadAudio && fn.Find(_T("://")) < 0) { int i = fn.ReverseFind('.'); if (i > 0) { const CMediaFormats& mf = s.m_Formats; CString ext = fn.Mid(i + 1).MakeLower(); if (!mf.FindExt(ext, true)) { CString path = fn; path.Replace('/', '\\'); path = path.Left(path.ReverseFind('\\') + 1); WIN32_FIND_DATA fd; ZeroMemory(&fd, sizeof(WIN32_FIND_DATA)); HANDLE hFind = FindFirstFile(fn.Left(i) + _T("*.*"), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } CString fullpath = path + fd.cFileName; CString ext2 = fullpath.Mid(fullpath.ReverseFind('.') + 1).MakeLower(); if (!FindFileInList(m_fns, fullpath) && ext != ext2 && mf.FindExt(ext2, true) && mf.IsUsingEngine(fullpath, DirectShow)) { m_fns.AddTail(fullpath); } } while (FindNextFile(hFind, &fd)); FindClose(hFind); } } } } if (s.IsISRAutoLoadEnabled()) { const CString& pathList = s.strSubtitlePaths; CAtlArray<CString> paths; int pos = 0; do { CString path = pathList.Tokenize(_T(";"), pos); if (!path.IsEmpty()) { paths.Add(path); } } while (pos != -1); CString dir = fn; dir.Replace('\\', '/'); int l = dir.ReverseFind('/') + 1; int l2 = dir.ReverseFind('.'); if (l2 < l) { // no extension, read to the end l2 = fn.GetLength(); } CString title = dir.Mid(l, l2 - l); paths.Add(title); CAtlArray<Subtitle::SubFile> ret; Subtitle::GetSubFileNames(fn, paths, ret); for (size_t i = 0; i < ret.GetCount(); i++) { if (!FindFileInList(m_subs, ret[i].fn)) { m_subs.AddTail(ret[i].fn); } } } }
int DeleteLogFiles() { WIN32_FIND_DATA ffd; char szDir[MAX_PATH]; char File[MAX_PATH]; HANDLE hFind = INVALID_HANDLE_VALUE; DWORD dwError=0; LARGE_INTEGER ft; time_t now = time(NULL); int Age; // Prepare string for use with FindFile functions. First, copy the // string to a buffer, then append '\*' to the directory name. strcpy(szDir, GetBPQDirectory()); strcat(szDir, "\\logs\\Log_*.txt"); // Find the first file in the directory. hFind = FindFirstFile(szDir, &ffd); if (INVALID_HANDLE_VALUE == hFind) { return dwError; } // List all the files in the directory with some info about them. do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { OutputDebugString(ffd.cFileName); } else { ft.HighPart = ffd.ftCreationTime.dwHighDateTime; ft.LowPart = ffd.ftCreationTime.dwLowDateTime; ft.QuadPart -= 116444736000000000; ft.QuadPart /= 10000000; Age = (now - ft.LowPart) / 86400; if (Age > LogAge) { sprintf(File, "%s/logs/%s%c", GetBPQDirectory(), ffd.cFileName, 0); if (DeletetoRecycleBin) DeletetoRecycle(File); else DeleteFile(File); } } } while (FindNextFile(hFind, &ffd) != 0); dwError = GetLastError(); FindClose(hFind); return dwError; }
//------------------------------------------------------------------------------ //format : http://www.forensicswiki.org/wiki/Windows_Prefetch_File_Format DWORD WINAPI Scan_prefetch(LPVOID lParam) { sqlite3 *db = (sqlite3 *)db_scan; unsigned int session_id = current_session_id; #ifdef CMD_LINE_ONLY_NO_DB printf("\"Prefetch\";\"file\";\"path\";\"create_time\";\"last_update\";\"last_access\";\"count\";\"exec\";\"session_id\";\"depend\";\r\n"); #endif //check if local or not :) HTREEITEM hitem = (HTREEITEM)SendMessage(htrv_files, TVM_GETNEXTITEM,(WPARAM)TVGN_CHILD, (LPARAM)TRV_HTREEITEM_CONF[FILES_TITLE_APPLI]); if (hitem!=NULL || !LOCAL_SCAN || WINE_OS) { if(!SQLITE_FULL_SPEED)sqlite3_exec(db,"BEGIN TRANSACTION;", NULL, NULL, NULL); char tmp_file_pref[MAX_PATH],ext[MAX_PATH]; while(hitem!=NULL) { tmp_file_pref[0] = 0; ext[0] = 0; GetTextFromTrv(hitem, tmp_file_pref, MAX_PATH); if (!strcmp("pf",extractExtFromFile(charToLowChar(tmp_file_pref), ext, MAX_PATH))) PfCheck(session_id, db, tmp_file_pref); hitem = (HTREEITEM)SendMessage(htrv_files, TVM_GETNEXTITEM,(WPARAM)TVGN_NEXT, (LPARAM)hitem); } if(!SQLITE_FULL_SPEED)sqlite3_exec(db,"END TRANSACTION;", NULL, NULL, NULL); h_thread_test[(unsigned int)lParam] = 0; check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan return 0; } //init if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"BEGIN TRANSACTION;", NULL, NULL, NULL); //get system path char path[MAX_PATH] ="%WINDIR%\\Prefetch\\*.pf"; ReplaceEnv("WINDIR",path,MAX_PATH); char path_f[MAX_PATH]; WIN32_FIND_DATA data; HANDLE hfic = FindFirstFile(path, &data); if (hfic != INVALID_HANDLE_VALUE) { do { if((data.cFileName[0] == '.' && (data.cFileName[1] == 0 || data.cFileName[1] == '.')) || (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){} else { strncpy(path_f,path,MAX_PATH); path_f[strlen(path_f)-4]=0; strncat(path_f,data.cFileName,MAX_PATH); strncat(path_f,"\0",MAX_PATH); PfCheck(session_id, db, path_f); } }while(FindNextFile (hfic,&data) && start_scan); FindClose(hfic); } if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"END TRANSACTION;", NULL, NULL, NULL); check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan h_thread_test[(unsigned int)lParam] = 0; return 0; }
/* ======================================================================================================================= 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; }
static void FindFiles(std::vector<std::string>& matches, const std::string& datadir, const std::string& dir, const boost::regex ®expattern, int flags) { #ifdef _WIN32 WIN32_FIND_DATA wfd; HANDLE hFind = FindFirstFile((datadir + dir + "\\*").c_str(), &wfd); if (hFind != INVALID_HANDLE_VALUE) { do { if(strcmp(wfd.cFileName,".") && strcmp(wfd.cFileName ,"..")) { if(!(wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) { if ((flags & FileSystem::ONLY_DIRS) == 0) { if (boost::regex_match(wfd.cFileName, regexpattern)) { matches.push_back(dir + wfd.cFileName); } } } else { if (flags & FileSystem::INCLUDE_DIRS) { if (boost::regex_match(wfd.cFileName, regexpattern)) { matches.push_back(dir + wfd.cFileName + "\\"); } } if (flags & FileSystem::RECURSE) { FindFiles(matches, datadir, dir + wfd.cFileName + "\\", regexpattern, flags); } } } } while (FindNextFile(hFind, &wfd)); FindClose(hFind); } #else DIR* dp; struct dirent* ep; if (!(dp = opendir((datadir + dir).c_str()))) { return; } while ((ep = readdir(dp))) { // exclude hidden files if (ep->d_name[0] != '.') { // is it a file? (we just treat sockets / pipes / fifos / character&block devices as files...) // (need to stat because d_type is DT_UNKNOWN on linux :-/) struct stat info; if (stat((datadir + dir + ep->d_name).c_str(), &info) == 0) { if (!S_ISDIR(info.st_mode)) { if ((flags & FileSystem::ONLY_DIRS) == 0) { if (boost::regex_match(ep->d_name, regexpattern)) { matches.push_back(dir + ep->d_name); } } } else { // or a directory? if (flags & FileSystem::INCLUDE_DIRS) { if (boost::regex_match(ep->d_name, regexpattern)) { matches.push_back(dir + ep->d_name + "/"); } } if (flags & FileSystem::RECURSE) { FindFiles(matches, datadir, dir + ep->d_name + "/", regexpattern, flags); } } } } } closedir(dp); #endif }
VOID CompleteFilename (LPTSTR strIN, BOOL bNext, LPTSTR strOut, UINT cusor) { /* Length of string before we complete it */ INT_PTR StartLength; /* Length of string after completed */ //INT EndLength; /* The number of chars added too it */ //static INT DiffLength = 0; /* Used to find and assemble the string that is returned */ TCHAR szBaseWord[MAX_PATH]; TCHAR szPrefix[MAX_PATH]; TCHAR szOrginal[MAX_PATH]; TCHAR szSearchPath[MAX_PATH]; /* Save the strings used last time, so if they hit tab again */ static TCHAR LastReturned[MAX_PATH]; static TCHAR LastSearch[MAX_PATH]; static TCHAR LastPrefix[MAX_PATH]; /* Used to search for files */ HANDLE hFile; WIN32_FIND_DATA file; /* List of all the files */ FileName * FileList = NULL; /* Number of files */ INT FileListSize = 0; /* Used for loops */ UINT i; /* Editable string of what was passed in */ TCHAR str[MAX_PATH]; /* Keeps track of what element was last selected */ static INT Sel; BOOL NeededQuote = FALSE; BOOL ShowAll = TRUE; TCHAR * line = strIN; strOut[0] = _T('\0'); while (_istspace (*line)) line++; if (!_tcsnicmp (line, _T("rd "), 3) || !_tcsnicmp (line, _T("cd "), 3)) ShowAll = FALSE; /* Copy the string, str can be edited and orginal should not be */ _tcscpy(str,strIN); _tcscpy(szOrginal,strIN); /* Look to see if the cusor is not at the end of the string */ if ((cusor + 1) < _tcslen(str)) str[cusor] = _T('\0'); /* Look to see if they hit tab again, if so cut off the diff length */ if (_tcscmp(str,LastReturned) || !_tcslen(str)) { /* We need to know how many chars we added from the start */ StartLength = _tcslen(str); /* no string, we need all files in that directory */ if (!StartLength) { _tcscat(str,_T("*")); } /* Zero it out first */ szBaseWord[0] = _T('\0'); szPrefix[0] = _T('\0'); /*What comes out of this needs to be: szBaseWord = path no quotes to the object szPrefix = what leads up to the filename no quote at the END of the full name */ FindPrefixAndSuffix(str,szPrefix,szBaseWord); /* Strip quotes */ for(i = 0; i < _tcslen(szBaseWord); ) { if (szBaseWord[i] == _T('\"')) memmove(&szBaseWord[i],&szBaseWord[i + 1], _tcslen(&szBaseWord[i]) * sizeof(TCHAR)); else i++; } /* clear it out */ memset(szSearchPath, 0, sizeof(szSearchPath)); /* Start the search for all the files */ GetFullPathName(szBaseWord, MAX_PATH, szSearchPath, NULL); /* Got a device path? Fallback to the the current dir plus the short path */ if (szSearchPath[0] == _T('\\') && szSearchPath[1] == _T('\\') && szSearchPath[2] == _T('.') && szSearchPath[3] == _T('\\')) { GetCurrentDirectory(MAX_PATH, szSearchPath); _tcscat(szSearchPath, _T("\\")); _tcscat(szSearchPath, szBaseWord); } if (StartLength > 0) { _tcscat(szSearchPath,_T("*")); } _tcscpy(LastSearch,szSearchPath); _tcscpy(LastPrefix,szPrefix); } else { _tcscpy(szSearchPath, LastSearch); _tcscpy(szPrefix, LastPrefix); StartLength = 0; } /* search for the files it might be */ hFile = FindFirstFile (szSearchPath, &file); if (hFile == INVALID_HANDLE_VALUE) { /* Assemble the orginal string and return */ _tcscpy(strOut,szOrginal); return; } /* aseemble a list of all files names */ do { FileName * oldFileList = FileList; if (!_tcscmp (file.cFileName, _T(".")) || !_tcscmp (file.cFileName, _T(".."))) continue; /* Don't show files when they are doing 'cd' or 'rd' */ if (!ShowAll && file.dwFileAttributes != 0xFFFFFFFF && !(file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { continue; } /* Add the file to the list of files */ FileList = cmd_realloc(FileList, ++FileListSize * sizeof(FileName)); if (FileList == NULL) { /* Don't leak old buffer */ cmd_free(oldFileList); /* Assemble the orginal string and return */ _tcscpy(strOut,szOrginal); FindClose(hFile); ConOutFormatMessage (GetLastError()); return; } /* Copies the file name into the struct */ _tcscpy(FileList[FileListSize-1].Name,file.cFileName); } while(FindNextFile(hFile,&file)); FindClose(hFile); /* Check the size of the list to see if we found any matches */ if (FileListSize == 0) { _tcscpy(strOut,szOrginal); if (FileList != NULL) cmd_free(FileList); return; } /* Sort the files */ qsort(FileList,FileListSize,sizeof(FileName), compare); /* Find the next/previous */ if (!_tcscmp(szOrginal,LastReturned)) { if (bNext) { if (FileListSize - 1 == Sel) Sel = 0; else Sel++; } else { if (!Sel) Sel = FileListSize - 1; else Sel--; } } else { Sel = 0; } /* nothing found that matched last time so return the first thing in the list */ strOut[0] = _T('\0'); /* Special character in the name */ if (FileNameContainsSpecialCharacters(FileList[Sel].Name)) { INT LastSpace; BOOL bInside; /* It needs a " at the end */ NeededQuote = TRUE; LastSpace = -1; bInside = FALSE; /* Find the place to put the " at the start */ for(i = 0; i < _tcslen(szPrefix); i++) { if (szPrefix[i] == _T('\"')) bInside = !bInside; if (szPrefix[i] == _T(' ') && !bInside) LastSpace = i; } /* insert the quotation and move things around */ if (szPrefix[LastSpace + 1] != _T('\"') && LastSpace != -1) { memmove ( &szPrefix[LastSpace+1], &szPrefix[LastSpace], (_tcslen(szPrefix)-LastSpace+1) * sizeof(TCHAR) ); if ((UINT)(LastSpace + 1) == _tcslen(szPrefix)) { _tcscat(szPrefix,_T("\"")); } szPrefix[LastSpace + 1] = _T('\"'); } else if (LastSpace == -1) { /* Add quotation only if none exists already */ if (szPrefix[0] != _T('\"')) { _tcscpy(szBaseWord,_T("\"")); _tcscat(szBaseWord,szPrefix); _tcscpy(szPrefix,szBaseWord); } } } _tcscpy(strOut,szPrefix); _tcscat(strOut,FileList[Sel].Name); /* check for odd number of quotes means we need to close them */ if (!NeededQuote) { for(i = 0; i < _tcslen(strOut); i++) { if (strOut[i] == _T('\"')) NeededQuote = !NeededQuote; } } if (szPrefix[_tcslen(szPrefix) - 1] == _T('\"') || NeededQuote) _tcscat(strOut,_T("\"")); _tcscpy(LastReturned,strOut); //EndLength = _tcslen(strOut); //DiffLength = EndLength - StartLength; if (FileList != NULL) cmd_free(FileList); }
UINT CSADirRead::FindFiles(const CCOMString & dir, const CCOMString & filter, bool bIncludeFilesInFileList, bool bIncludeFoldersInFileList) { // make sure the path ends in a single "\" CCOMString baseName = dir; FormatPath(baseName); baseName+='\\'; CCOMString fullPath = baseName; fullPath += filter; CCOMString fileName; // find first file in current directory #ifndef USE_WIN32_FINDFILE struct _finddata_t c_file; long fhandle; try { if ((fhandle=_findfirst( fullPath, &c_file ))!=-1) { bool bIsFolder = (c_file.attrib & _A_SUBDIR)==_A_SUBDIR; bool bAddThisOne = (bIsFolder && bIncludeFoldersInFileList) || (!bIsFolder && bIncludeFilesInFileList); // skip . and .. if (bIsFolder && (strcmp(c_file.name, ".")==0) || (strcmp(c_file.name, "..")==0)) { bAddThisOne = false; } if (bAddThisOne) { fileName = baseName; fileName += c_file.name; CSAFileEntry t; t.bIsFolder = bIsFolder; t.attrib = c_file.attrib; t.m_sName = fileName; t.time_write = c_file.time_write; t.time_create = c_file.time_create; t.size = c_file.size; m_files.push_back(t); } // find the rest of them while(_findnext( fhandle, &c_file ) == 0 ) { bool bIsFolder = (c_file.attrib & _A_SUBDIR)==_A_SUBDIR; bool bAddThisOne = (bIsFolder && bIncludeFoldersInFileList) || (!bIsFolder && bIncludeFilesInFileList); // skip . and .. if (bIsFolder && (strcmp(c_file.name, ".")==0) || (strcmp(c_file.name, "..")==0)) { bAddThisOne = false; } if (bAddThisOne) { fileName=baseName; fileName += c_file.name; CSAFileEntry t; t.bIsFolder = bIsFolder; t.attrib = c_file.attrib; t.m_sName = fileName; t.time_write = c_file.time_write; t.time_create = c_file.time_create; t.size = c_file.size; m_files.push_back(t); } } _findclose(fhandle); } } catch (...) { return false; } #else WIN32_FIND_DATA FindFileData; HANDLE hFind; try { if ((hFind = FindFirstFile(fullPath, &FindFileData))!=INVALID_HANDLE_VALUE) { bool bIsFolder = (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY; bool bAddThisOne = (bIsFolder && bIncludeFoldersInFileList) || ((!bIsFolder) && bIncludeFilesInFileList); // skip . and .. if (bIsFolder && (strcmp(FindFileData.cFileName, ".")==0) || (strcmp(FindFileData.cFileName, "..")==0)) { bAddThisOne = false; } if (bAddThisOne) { fileName = baseName; fileName += FindFileData.cFileName; CSAFileEntry t; t.m_sName = fileName; t.bIsFolder = bIsFolder; t.attrib = FindFileData.dwFileAttributes; memcpy(&t.time_write, &FindFileData.ftLastWriteTime, sizeof(_FILETIME)); memcpy(&t.time_create, &FindFileData.ftCreationTime, sizeof(_FILETIME)); t.size = ((unsigned __int64)FindFileData.nFileSizeHigh * ((unsigned __int64)MAXDWORD+1)) + (unsigned __int64)FindFileData.nFileSizeLow; m_files.push_back(t); } // find the rest of them while (FindNextFile(hFind, &FindFileData)) { bool bIsFolder = (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY; bool bAddThisOne = (bIsFolder && bIncludeFoldersInFileList) || ((!bIsFolder) && bIncludeFilesInFileList); // skip . and .. if (bIsFolder && (strcmp(FindFileData.cFileName, ".")==0) || (strcmp(FindFileData.cFileName, "..")==0)) { bAddThisOne = false; } if (bAddThisOne) { fileName = baseName; fileName += FindFileData.cFileName; CSAFileEntry t; t.m_sName = fileName; t.bIsFolder = bIsFolder; t.attrib = FindFileData.dwFileAttributes; memcpy(&t.time_write, &FindFileData.ftLastWriteTime, sizeof(_FILETIME)); memcpy(&t.time_create, &FindFileData.ftCreationTime, sizeof(_FILETIME)); t.size = ((unsigned __int64)FindFileData.nFileSizeHigh * ((unsigned __int64)MAXDWORD+1)) + (unsigned __int64)FindFileData.nFileSizeLow; m_files.push_back(t); } } FindClose(hFind); } } catch (...) { return false; } #endif return true; }
// Recursive version of `RemoveDirectory`. NOTE: unlike `rmdir`, this requires // Windows-formatted paths, and therefore should be in the `internal` namespace. inline Try<Nothing> recursive_remove_directory( const std::string& path, bool removeRoot, bool continueOnError) { // Appending a slash here if the path doesn't already have one simplifies // path join logic later, because (unlike Unix) Windows doesn't like double // slashes in paths. std::string current_path; if (!strings::endsWith(path, "\\")) { current_path = path + "\\"; } else { current_path = path; } // Get first file matching pattern `X:\path\to\wherever\*`. WIN32_FIND_DATA found; const std::string search_pattern = current_path + "*"; const SharedHandle search_handle( FindFirstFile(search_pattern.c_str(), &found), FindClose); if (search_handle.get() == INVALID_HANDLE_VALUE) { return WindowsError( "`os::internal::recursive_remove_directory` failed when searching " "for files with pattern '" + search_pattern + "'"); } do { // NOTE: do-while is appropriate here because folder is guaranteed to have // at least a file called `.` (and probably also one called `..`). const std::string current_file(found.cFileName); const bool is_current_directory = current_file.compare(".") == 0; const bool is_parent_directory = current_file.compare("..") == 0; // Don't try to delete `.` and `..` files in directory. if (is_current_directory || is_parent_directory) { continue; } // Path to remove. const std::string current_absolute_path = current_path + current_file; const bool is_directory = os::stat::isdir(current_absolute_path); // Delete current path, whether it's a directory, file, or symlink. if (is_directory) { Try<Nothing> removed = recursive_remove_directory( current_absolute_path, removeRoot, continueOnError); if (removed.isError()) { if (continueOnError) { LOG(WARNING) << "Failed to delete directory " << current_absolute_path << " with error " << removed.error(); } else { return Error(removed.error()); } } } else { // NOTE: this also handles symbolic links. if (::remove(current_absolute_path.c_str()) != 0) { if (continueOnError) { LOG(WARNING) << "`os::internal::recursive_remove_directory`" << " attempted to delete file '" << current_absolute_path << "', but failed"; } else { return WindowsError( "`os::internal::recursive_remove_directory` attempted to delete " "file '" + current_absolute_path + "', but failed"); } } } } while (FindNextFile(search_handle.get(), &found)); // Finally, remove current directory unless `removeRoot` is disabled. if (removeRoot && ::_rmdir(current_path.c_str()) == -1) { if (continueOnError) { LOG(WARNING) << "`os::internal::recursive_remove_directory`" << " attempted to delete directory '" << current_path << "', but failed"; return ErrnoError("rmdir failed in 'continueOnError' mode"); } else { return ErrnoError( "`os::internal::recursive_remove_directory` attempted to delete " "directory '" + current_path + "', but failed"); } } return Nothing(); }
Application::Application(HINSTANCE _hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MPQInit(); instance = this; resources = NULL; imageLibrary = NULL; dotaLibrary = NULL; mainWindow = NULL; cache = NULL; hInstance = _hInstance; _loaded = false; root = String::getPath(getAppPath()); cfg.read(); warLoader = new MPQLoader("Custom_V1"); warLoader->loadArchive(String::buildFullName(cfg.warPath, "war3.mpq")); warLoader->loadArchive(String::buildFullName(cfg.warPath, "war3x.mpq")); warLoader->loadArchive(String::buildFullName(cfg.warPath, "war3xlocal.mpq")); warLoader->loadArchive(String::buildFullName(cfg.warPath, "war3patch.mpq")); if (logCommand(lpCmdLine)) return; ScriptType::initTypes(); UpdateDialog::init(hInstance); INITCOMMONCONTROLSEX iccex; iccex.dwSize = sizeof iccex; iccex.dwICC = ICC_STANDARD_CLASSES | ICC_PROGRESS_CLASS | ICC_BAR_CLASSES | ICC_TREEVIEW_CLASSES | ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES | ICC_UPDOWN_CLASS | ICC_DATE_CLASSES; InitCommonControlsEx(&iccex); LoadLibrary("Riched20.dll"); OleInitialize(NULL); String path = String::getPath(getAppPath()); String resPath = String::buildFullName(path, "resources.mpq"); String patchPath = String::buildFullName(path, "install.mpq"); File* tOpen = File::open(resPath, File::READ); if (tOpen == NULL) { tOpen = File::open(patchPath, File::READ); if (tOpen) { delete tOpen; MoveFile(patchPath, resPath); } } else delete tOpen; resources = MPQArchive::open(resPath); MPQArchive* patch = MPQArchive::open(patchPath, File::READ); if (patch) { for (uint32 i = 0; i < patch->getHashSize(); i++) { char const* name = patch->getFileName(i); if (name) { MPQFile* source = patch->openFile(i, File::READ); if (source) { MPQFile* dest = resources->openFile(name, File::REWRITE); if (dest) { static uint8 buf[1024]; while (int length = source->read(buf, sizeof buf)) dest->write(buf, length); delete dest; } delete source; } } } delete patch; DeleteFile(patchPath); } imageLibrary = new ImageLibrary(resources); cache = new CacheManager(); dotaLibrary = new DotaLibrary(); #if 0 File* dlog = File::open("diff.txt", File::REWRITE); for (int pt = 0; pt < 120; pt++) { String prev = ""; bool different = false; for (int ver = 1; ver <= 80 && !different; ver++) { Dota* dota = dotaLibrary->getDota(makeVersion(6, ver)); if (dota) { Dota::Hero* hero = dota->getHero(pt); if (hero) { if (prev == "") prev = hero->name; else if (prev.icompare(hero->name)) different = true; } } } if (different) { dlog->printf(" Pt=%d\r\n", pt); prev = ""; for (int ver = 1; ver <= 80; ver++) { Dota* dota = dotaLibrary->getDota(makeVersion(6, ver)); if (dota) { Dota::Hero* hero = dota->getHero(pt); if (hero) { if (prev.icompare(hero->name)) { dlog->printf("6.%02d = %s\r\n", ver, hero->name); prev = hero->name; } } } } } } delete dlog; #endif #if 0 dotaLibrary->getDota(parseVersion("6.79e"), "K:\\Progs\\DotAReplay\\maps\\DotA v6.79e.w3x"); WIN32_FIND_DATA data; String enumPath = "K:\\Progs\\DotAReplay\\maps"; HANDLE hFind = FindFirstFile(String::buildFullName(enumPath, "*"), &data); BOOL success = (hFind != INVALID_HANDLE_VALUE); while (success) { String file(data.cFileName); if (String::getExtension(file).icompare(".w3x") == 0) { file.toLower(); Array<String> sub; if (file.rfind("dota{{_| }allstars}?{_| }v(\\d)\\.(\\d\\d)([b-z]?)[^b-z]", 0, &sub) >= 0) { int major = sub[1].toInt(); int minor = sub[2].toInt(); int build = 0; if (!sub[3].isEmpty()) build = int(sub[3][0] - 'a'); uint32 version = makeVersion(major, minor, build); dotaLibrary->getDota(version, String::buildFullName(enumPath, file)); } } success = FindNextFile(hFind, &data); } FindClose(hFind); #endif mainWindow = new MainWnd(); mainWindow->postLoad(); _loaded = true; if (lpCmdLine[0]) { COPYDATASTRUCT cd; cd.dwData = MAINWND_OPEN_REPLAY; cd.cbData = strlen(lpCmdLine) + 1; cd.lpData = lpCmdLine; PostMessage(getMainWindow(), WM_COPYDATA_FAKE, NULL, (LPARAM) &cd); } }
void parsedir(char *path) { WIN32_FIND_DATA fd; HANDLE handle; int curFile = 0, len = 0; handle = FindFirstFile(path,&fd); do { if(strcmp(fd.cFileName,".") != 0 && strcmp(fd.cFileName,"..") != 0 && strcmp(fd.cFileName,"list.txt") != 0&& !(fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) { FILE *infile = NULL; char *inpath = (char*)calloc(strlen(path)+strlen(fd.cFileName)+1,sizeof(char)); unsigned char *buffer = NULL; int padding = 0; if((offset%PADDING)!=0) { int i = 0, z = 0; padding = PADDING - (offset%PADDING); offset += PADDING - (offset%PADDING); //printf("%08x %08x\n",padding,offset); for(i=0; i<padding; i++) { fwrite(&z,1,1,outfile); } } strncpy(inpath, path, strlen(path)-1); strcat(inpath,fd.cFileName); infile = fopen(inpath, "rb"); if(!infile) { printf("Could not open %s\n",inpath); exit(1); } fseek(infile,0,SEEK_END); len = ftell(infile); rewind(infile); buffer = (unsigned char*)calloc(len,sizeof(unsigned char)); fread(buffer,1,len,infile); if(compressFile != 1) { unsigned char *lzlrbuff = NULL; lzlrbuff = CompressLZLR(buffer,len); len = lzlroutlen; fwrite(lzlrbuff,1,len,outfile); free(lzlrbuff); } else { fwrite(buffer,1,len,outfile); } fclose(outfile); outfile = fopen(outname,"rb+"); fseek(outfile,curFile*8,SEEK_SET); fwrite(&offset,1,4,outfile); fwrite(&len,1,4,outfile); fclose(outfile); outfile = fopen(outname,"ab+"); fseek(outfile,0,SEEK_END); fclose(infile); free(buffer); offset += len; curFile++; len = 0; } } while(FindNextFile(handle,&fd) != 0); fclose(outfile); outfile = fopen(outname,"rb+"); fseek(outfile,curFile*8,SEEK_SET); fwrite(&offset,1,4,outfile); fwrite(&len,1,4,outfile); fclose(outfile); outfile = fopen(outname,"ab+"); fseek(outfile,0,SEEK_END); }
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 ListPatches (HWND hW) { int i, tmpi, filesize, totalPatch=0, totalSize=0; char tmpStr[MAX_PATH], *fileData; WIN32_FIND_DATA FindData; HANDLE Find; FILE *fp; //clear listbox's SendDlgItemMessage(hW, IDC_PATCHCRCLIST, (UINT)LB_RESETCONTENT, (WPARAM)NULL, (LPARAM)NULL); SendDlgItemMessage(hW, IDC_PATCHNAMELIST, (UINT)LB_RESETCONTENT, (WPARAM)NULL, (LPARAM)NULL); //sprintf(tmpStr,"%s*.pnach", Config.PatchDir) sprintf(tmpStr, "patches\\*.pnach"); Find = FindFirstFile(tmpStr, &FindData); do { if (Find==INVALID_HANDLE_VALUE) break; sprintf(tmpStr,"%s", FindData.cFileName); //add file name to crc list SendDlgItemMessage(hW, IDC_PATCHCRCLIST, (UINT) LB_ADDSTRING, (WPARAM)NULL, (LPARAM)tmpStr); //sprintf(tmpStr,"%s%s", Config.PatchDir, FindData.cFileName) sprintf(tmpStr,"patches\\%s", FindData.cFileName); fp = fopen(tmpStr, "r"); if (fp == NULL) break; fseek(fp, 0, SEEK_END); filesize = ftell(fp); totalSize += filesize; fseek(fp, 0, SEEK_SET); fileData = (char *) malloc(filesize+1024); sprintf(fileData,""); //read file while((tmpi=fgetc(fp)) != EOF) sprintf(fileData,"%s%c",fileData,tmpi); //small hack :p for(i=0;i<filesize;i++) { if (fileData[i] == 'g' && fileData[i+1] == 'a' && fileData[i+2] == 'm' && fileData[i+3] == 'e' && fileData[i+4] == 't' && fileData[i+5] == 'i' && fileData[i+6] == 't' && fileData[i+7] == 'l' && fileData[i+8] == 'e' && fileData[i+9] == '=') { for(i=i+10,tmpi=0;i<filesize;i++,tmpi++) { if (fileData[i] == '\n') break; tmpStr[tmpi] = fileData[i]; } tmpStr[tmpi] = '\0'; break; } } //remove " in the string for (i=0,tmpi=0; tmpStr[i]!='\0'; i++) if (tmpStr[i] != '"') tmpStr[tmpi++] = tmpStr[i]; tmpStr[tmpi] = '\0'; //remove spaces at the left of the string sprintf(tmpStr,lTrim(tmpStr)); sprintf(tmpStr,"%s (%s)",tmpStr,FindData.cFileName); //add game name to patch name list SendDlgItemMessage(hW, IDC_PATCHNAMELIST, (UINT) LB_ADDSTRING, (WPARAM)NULL, (LPARAM)tmpStr); totalPatch++; sprintf(fileData,""); fclose(fp); } while (FindNextFile(Find,&FindData)); if (Find!=INVALID_HANDLE_VALUE) FindClose(Find); sprintf(tmpStr,"Patches Browser | Patches Found: %d | Total Filesize: %.2f KB", totalPatch,(float)totalSize/1024); SetWindowText(hW, tmpStr); }
int inline CShellBrowser::SetItemInformation(LPITEMIDLIST pidlDirectory, LPITEMIDLIST pidlRelative,TCHAR *szFileName) { LPITEMIDLIST pidlItem = NULL; HANDLE hFirstFile; TCHAR szPath[MAX_PATH]; int uItemId; m_nAwaitingAdd++; if((m_nTotalItems + m_nAwaitingAdd) > (m_iCurrentAllocation - 1)) { int PrevSize = m_iCurrentAllocation; if(m_iCurrentAllocation > MEM_ALLOCATION_LEVEL_MEDIUM) m_iCurrentAllocation += MEM_ALLOCATION_LEVEL_MEDIUM; else if(m_iCurrentAllocation > MEM_ALLOCATION_LEVEL_LOW) m_iCurrentAllocation += MEM_ALLOCATION_LEVEL_LOW; else m_iCurrentAllocation += DEFAULT_MEM_ALLOC; m_pwfdFiles = (WIN32_FIND_DATA *)realloc(m_pwfdFiles, m_iCurrentAllocation * (sizeof(WIN32_FIND_DATA))); m_pExtraItemInfo = (CItemObject *)realloc(m_pExtraItemInfo, m_iCurrentAllocation * sizeof(CItemObject)); m_pItemMap = (int *)realloc(m_pItemMap,m_iCurrentAllocation * sizeof(int)); InitializeItemMap(PrevSize,m_iCurrentAllocation); if(m_pwfdFiles == NULL || m_pExtraItemInfo == NULL) return E_OUTOFMEMORY; } uItemId = GenerateUniqueItemId(); m_pExtraItemInfo[uItemId].pridl = ILClone(pidlRelative); m_pExtraItemInfo[uItemId].bIconRetrieved = FALSE; m_pExtraItemInfo[uItemId].bThumbnailRetreived = FALSE; m_pExtraItemInfo[uItemId].bFolderSizeRetrieved = FALSE; StringCchCopy(m_pExtraItemInfo[uItemId].szDisplayName,MAX_PATH,szFileName); pidlItem = ILCombine(pidlDirectory,pidlRelative); SHGetPathFromIDList(pidlItem,szPath); CoTaskMemFree(pidlItem); /* DO NOT call FindFirstFile() on root drives (especially floppy drives). Doing so may cause a delay of up to a few seconds. */ if(!PathIsRoot(szPath)) { m_pExtraItemInfo[uItemId].bDrive = FALSE; hFirstFile = FindFirstFile(szPath,&m_pwfdFiles[uItemId]); } else { m_pExtraItemInfo[uItemId].bDrive = TRUE; StringCchCopy(m_pExtraItemInfo[uItemId].szDrive, SIZEOF_ARRAY(m_pExtraItemInfo[uItemId].szDrive), szPath); hFirstFile = INVALID_HANDLE_VALUE; } /* Need to use this, since may be in a virtual folder (such as the recycle bin), but items still exist. */ if(hFirstFile != INVALID_HANDLE_VALUE) { m_pExtraItemInfo[uItemId].bReal = TRUE; FindClose(hFirstFile); } else { StringCchCopy(m_pwfdFiles[uItemId].cFileName, sizeof(m_pwfdFiles[uItemId].cFileName)/sizeof(m_pwfdFiles[uItemId].cFileName[0]),szFileName); m_pwfdFiles[uItemId].nFileSizeLow = 0; m_pwfdFiles[uItemId].nFileSizeHigh = 0; m_pwfdFiles[uItemId].dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY; m_pExtraItemInfo[uItemId].bReal = FALSE; } return uItemId; }
void SPFS::AddFolder(LPCSTR lpszDir,LPCSTR lpszFMask) { if( !IsOpen() ) throw new SPFSException(_T("pack file isn't opened !"),SPFS_FILE_IS_NOT_OPENED); PACK_FSS_HEADER *fss = &_pHeader->fssHeader; DWORD fileCt = _pHeader->fileCt; // count of packed files. DWORD written = 0L; // written bytes count. DWORD readSz = 0L; // readed bytes count. void* lpSectionMem = malloc(_pHeader->fDataSecSz); // allocate heap memory for file data section. DWORD packOffset = 0L; // offset of pack file handle. size_t dirLength = strlen(lpszDir); // save directory length size. // store pointer to the file data section header. PACK_FS_HEADER* pFSHeader = (PACK_FS_HEADER*)lpSectionMem; // initialize find data structure. WIN32_FIND_DATA fData; ZeroMemory(&fData,sizeof(WIN32_FIND_DATA)); sprintf(fData.cFileName,"%s\\%s",lpszDir,lpszFMask); char szFilePath[_MAX_PATH]; sprintf(szFilePath,"%s\\",lpszDir); HANDLE hFind = FindFirstFile(fData.cFileName,&fData); HANDLE hFile = NULL; // set file pointer to the end of file data. if( hFind == (HANDLE)-1 || SetFilePointer(_hPackFile,0L,0L,FILE_BEGIN) == (DWORD)-1 ) throw new SPFSException(_T("can't find first SQL file !"),SPFS_FILE_NOT_FOUND); while( hFind != (HANDLE)-1 ) { // initialize full path of founded file. szFilePath[dirLength+1] = 0x00; strcat(szFilePath,fData.cFileName); // open founded file. if( m_procOpenFileToAdd ) hFile = (m_procOpenFileToAdd)(szFilePath); else hFile = CreateFile(szFilePath,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL); if( hFile != (HANDLE)-1 ) { // add file into pack file. DWORD offset = AddFile(_hPackFile, packOffset, hFile, _pHeader, lpSectionMem, written, m_procPreWriteFileSection); // add file into FSS. if( offset ) AddFileToFSS(fData.cFileName,offset,_pFNArray,_fnArrAlloc,_fnArrUsed, _pFOArray,_foArrAlloc,_pFNOArray,_fnoArrAlloc,fileCt); else { CloseHandle(hFile); throw new SPFSException(_T("can't add file to the pack file !"),SPFS_FILE_CANT_WRITE); } // close file handle. CloseHandle(hFile); } // find next file. if( !FindNextFile(hFind,&fData) ) { // file name offsets array size & file offsets array size. UINT arrSize = fileCt*sizeof(DWORD); // fill pack file header. {{ _pHeader->fssHeader.start = 0x68637273;// _T("srch") // current offset + file name array size + file offsets array size + name offsets array size. _pHeader->packSz = _pHeader->fssHeader.offsetFSS + _fnArrUsed + 2*arrSize; // set FSS section used bytes size. _pHeader->fssHeader.secUsedSz = _fnArrUsed + 2*arrSize; // set FSS section full bytes size. if( _pHeader->fssHeader.sectionSz < _pHeader->fssHeader.secUsedSz ) _pHeader->fssHeader.sectionSz = _pHeader->fssHeader.secUsedSz; // set file names array size. _pHeader->fssHeader.fnArraySz = _fnArrUsed; // set file offsets array size. _pHeader->fssHeader.foArraySz = arrSize; // set file name offsets array size. _pHeader->fssHeader.fnoArraySz = arrSize; // set offset of file names array. _pHeader->fssHeader.fnArray = _pHeader->fssHeader.offsetFSS; // set offset of file name offsets array. _pHeader->fssHeader.fnoArray = _pHeader->fssHeader.offsetFSS + _fnArrUsed; // set offset of file offsets array. _pHeader->fssHeader.foArray = _pHeader->fssHeader.offsetFSS + _fnArrUsed + arrSize; // }} // write pack header. if( !WritePackHeader(_hPackFile,_pHeader) ) throw new SPFSException(_T("can't write pack file header!"),SPFS_FILE_CANT_WRITE); // write pack FSS. if( !WritePackFSS(_hPackFile,_pHeader,_pFNArray,_fnArrUsed,_pFOArray,_pFNOArray,fileCt) ) throw new SPFSException(_T("can't write FSS(file search section) of pack file !"),SPFS_FILE_CANT_WRITE); FindClose(hFind); break; } } }
StringLinkedList getFilesRecursive(AllocatorPool* pool, String directory, Error* error) { if (directory.length == 0) { StringLinkedList nullResult = {}; return nullResult; } char* lastCharacter = &directory.data[directory.length - 1]; if (lastCharacter[0] == '/' || lastCharacter[0] == '\\') { // Trim trailing back-or-forward slash directory.length -= 1; } assert(directory.length < MAX_PATH); // Convert String to C-String char baseDir[MAX_PATH]; memcpy(baseDir, directory.data, directory.length); baseDir[directory.length] = '\0'; // Convert C-String to WChar-String wchar_t szBaseDir[MAX_PATH]; mbstowcs(szBaseDir, baseDir, MAX_PATH); const u32 directoryLimit = 100; wchar_t szDirectories[directoryLimit][MAX_PATH+10]; u32 directories = 0; u32 files = 0; StringCchCopy(szDirectories[directories++], MAX_PATH, szBaseDir); StringLinkedList list = {}; while (directories > 0) { --directories; wchar_t currentDirectory[MAX_PATH]; StringCchCopy(currentDirectory, MAX_PATH, szDirectories[directories]); wchar_t currentDirectoryWSearch[MAX_PATH]; StringCchCopy(currentDirectoryWSearch, MAX_PATH, currentDirectory); StringCchCat(currentDirectoryWSearch, MAX_PATH, TEXT("\\*")); WIN32_FIND_DATA ffd; HANDLE hFind = FindFirstFile(currentDirectoryWSearch, &ffd); DWORD dLastError = GetLastError(); if (hFind == INVALID_HANDLE_VALUE || dLastError == ERROR_FILE_NOT_FOUND) { if (error) { if (dLastError == ERROR_FILE_NOT_FOUND) { error->errorCode = DIRECTORY_NO_FILES; } else { error->errorCode = DIRECTORY_INVALID_DIR; } } StringLinkedList list_null = {}; return list_null; } do { if (wcscmp(ffd.cFileName, TEXT(".")) != 0 && wcscmp(ffd.cFileName, TEXT("..")) != 0) { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // Push this directory to be searched next iteration. StringCchCopy(szDirectories[directories], MAX_PATH, currentDirectory); StringCchCat(szDirectories[directories], MAX_PATH, TEXT("\\")); StringCchCat(szDirectories[directories], MAX_PATH, ffd.cFileName); ++directories; } else { wchar_t filepath[MAX_PATH]; StringCchCopy(filepath, ArrayCount(filepath), currentDirectory); StringCchCat(filepath, ArrayCount(filepath), TEXT("\\")); StringCchCat(filepath, ArrayCount(filepath), ffd.cFileName); String string = WcharToUTF8String(pool, filepath); list.add(string, pool); ++files; } } } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); } return list; }
/* The idea here is to read all the directory names into a string table * (separated by nulls) and when one of the other dir functions is called * return the pointer to the current file name. */ DIR * opendir(char *filename) { DIR *p; long len; long idx; char scannamespc[PATHLEN]; char *scanname = scannamespc; struct stat sbuf; WIN32_FIND_DATA FindData; HANDLE fh; /* check to see if filename is a directory */ if (stat(filename, &sbuf) < 0 || sbuf.st_mode & S_IFDIR == 0) { return NULL; } /* get the file system characteristics */ /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) { * if(dummy = strchr(root, '\\')) * *++dummy = '\0'; * if(GetVolumeInformation(root, volname, MAX_PATH, &serial, * &maxname, &flags, 0, 0)) { * downcase = !(flags & FS_CASE_IS_PRESERVED); * } * } * else { * downcase = TRUE; * } */ /* Create the search pattern */ strcpy(scanname, filename); if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL) strcat(scanname, "/*"); else strcat(scanname, "*"); /* do the FindFirstFile call */ fh = FindFirstFile(scanname, &FindData); if(fh == INVALID_HANDLE_VALUE) { return NULL; } /* Get us a DIR structure */ p = (DIR*)malloc(sizeof(DIR)); /* Newz(1303, p, 1, DIR); */ if(p == NULL) return NULL; /* now allocate the first part of the string table for * the filenames that we find. */ idx = strlen(FindData.cFileName)+1; p->start = (char*)malloc(idx * sizeof(char)); /* New(1304, p->start, idx, char);*/ if(p->start == NULL) { free(p); return NULL; } strcpy(p->start, FindData.cFileName); /* if(downcase) * strlwr(p->start); */ p->nfiles++; /* loop finding all the files that match the wildcard * (which should be all of them in this directory!). * the variable idx should point one past the null terminator * of the previous string found. */ while (FindNextFile(fh, &FindData)) { len = strlen(FindData.cFileName); /* bump the string table size by enough for the * new name and it's null terminator */ p->start = (char*)realloc((void*)p->start, idx+len+1 * sizeof(char)); /* Renew(p->start, idx+len+1, char);*/ if(p->start == NULL) { free(p); return NULL; } strcpy(&p->start[idx], FindData.cFileName); /* if (downcase) * strlwr(&p->start[idx]); */ p->nfiles++; idx += len+1; } FindClose(fh); p->size = idx; p->curr = p->start; return p; }
/* * returns 1 if at least one match, else returns 0 */ BOOL ShowCompletionMatches (LPTSTR str, INT charcount) { WIN32_FIND_DATA file; HANDLE hFile; BOOL found_dot = FALSE; INT curplace = 0; INT start; INT count; TCHAR path[MAX_PATH]; TCHAR fname[MAX_PATH]; TCHAR directory[MAX_PATH]; SHORT screenwidth; /* expand current file name */ count = charcount - 1; if (count < 0) count = 0; /* find front of word */ if (str[count] == _T('"')) { count--; while (count > 0 && str[count] != _T('"')) count--; } else { while (count > 0 && str[count] != _T(' ')) count--; } /* if not at beginning, go forward 1 */ if (str[count] == _T(' ')) count++; start = count; if (str[count] == _T('"')) count++; /* don't increment start */ /* extract directory from word */ _tcscpy (directory, &str[count]); curplace = _tcslen (directory) - 1; if (curplace >= 0 && directory[curplace] == _T('"')) directory[curplace--] = _T('\0'); _tcscpy (path, directory); while (curplace >= 0 && directory[curplace] != _T('\\') && directory[curplace] != _T(':')) { directory[curplace] = 0; curplace--; } /* look for a . in the filename */ for (count = _tcslen (directory); path[count] != _T('\0'); count++) { if (path[count] == _T('.')) { found_dot = TRUE; break; } } if (found_dot) _tcscat (path, _T("*")); else _tcscat (path, _T("*.*")); /* current fname */ curplace = 0; hFile = FindFirstFile (path, &file); if (hFile != INVALID_HANDLE_VALUE) { UINT longestfname = 0; /* Get the size of longest filename first. */ do { if (_tcslen(file.cFileName) > longestfname) { longestfname = _tcslen(file.cFileName); /* Directories get extra brackets around them. */ if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) longestfname += 2; } } while (FindNextFile (hFile, &file)); FindClose (hFile); hFile = FindFirstFile (path, &file); /* Count the highest number of columns */ GetScreenSize(&screenwidth, 0); /* For counting columns of output */ count = 0; /* Increase by the number of spaces behind file name */ longestfname += 3; /* find anything */ ConOutChar(_T('\n')); do { /* ignore . and .. */ if (!_tcscmp (file.cFileName, _T(".")) || !_tcscmp (file.cFileName, _T(".."))) continue; if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) _stprintf (fname, _T("[%s]"), file.cFileName); else _tcscpy (fname, file.cFileName); ConOutPrintf (_T("%*s"), - longestfname, fname); count++; /* output as much columns as fits on the screen */ if (count >= (screenwidth / longestfname)) { /* print the new line only if we aren't on the * last column, in this case it wraps anyway */ if (count * longestfname != (UINT)screenwidth) ConOutChar(_T('\n')); count = 0; } } while (FindNextFile (hFile, &file)); FindClose (hFile); if (count) ConOutChar(_T('\n')); } else { /* no match found */ MessageBeep (-1); return FALSE; } return TRUE; }
/** * This function attempts to remove a directory along with all the * files in it. If the recursive variable is non-zero, then it will * try to recursively remove all directories. If provided, the * callback function is executed prior to the directory or file being * removed. If the callback returns non-zero, then no removal is * done. */ int opal_os_dirpath_destroy(const char *path, bool recursive, opal_os_dirpath_destroy_callback_fn_t cbfunc) { int rc, exit_status = OPAL_SUCCESS; bool is_dir = false; #ifndef __WINDOWS__ DIR *dp; struct dirent *ep; char *filenm; #ifndef HAVE_STRUCT_DIRENT_D_TYPE struct stat buf; #endif if (NULL == path) { /* protect against error */ return OPAL_ERROR; } /* * Make sure we have access to the the base directory */ if( OPAL_SUCCESS != (rc = opal_os_dirpath_access(path, 0) ) ) { exit_status = rc; goto cleanup; } /* * Open up the directory */ dp = opendir(path); if (NULL == dp) { return OPAL_ERROR; } while (NULL != (ep = readdir(dp)) ) { /* skip: * - . and .. */ if ((0 == strcmp(ep->d_name, ".")) || (0 == strcmp(ep->d_name, "..")) ) { continue; } /* Check to see if it is a directory */ is_dir = false; /* Create a pathname. This is not always needed, but it makes * for cleaner code just to create it here. Note that we are * allocating memory here, so we need to free it later on. */ filenm = opal_os_path(false, path, ep->d_name, NULL); #ifdef HAVE_STRUCT_DIRENT_D_TYPE if (DT_DIR == ep->d_type) { is_dir = true; } #else /* have dirent.d_type */ rc = stat(filenm, &buf); if (rc < 0 || S_ISDIR(buf.st_mode)) { is_dir = true; } #endif /* have dirent.d_type */ /* * If not recursively decending, then if we find a directory then fail * since we were not told to remove it. */ if( is_dir && !recursive) { /* Set the error indicating that we found a directory, * but continue removing files */ exit_status = OPAL_ERROR; free(filenm); continue; } /* Will the caller allow us to remove this file/directory? */ if(NULL != cbfunc) { /* * Caller does not wish to remove this file/directory, * continue with the rest of the entries */ if( ! (cbfunc(path, ep->d_name)) ) { free(filenm); continue; } } /* Directories are recursively destroyed */ if(is_dir) { rc = opal_os_dirpath_destroy(filenm, recursive, cbfunc); free(filenm); if (OPAL_SUCCESS != rc) { exit_status = rc; goto cleanup; } } /* Files are removed right here */ else { if( 0 != (rc = unlink(filenm) ) ) { exit_status = OPAL_ERROR; } free(filenm); } } /* * Done with this directory */ closedir(dp); #else char search_path[MAX_PATH]; HANDLE file; WIN32_FIND_DATA file_data; TCHAR *file_name; if (NULL == path) { return OPAL_ERROR; } strncpy(search_path, path, strlen(path)+1); strncat (search_path, OPAL_PATH_SEP"*", 3); file = FindFirstFile(search_path, &file_data); if (INVALID_HANDLE_VALUE == file) { FindClose(file); return OPAL_ERROR; } do { /* * Skip * - . and .. */ if ((0 == strcmp(file_data.cFileName, ".")) || (0 == strcmp(file_data.cFileName, "..")) ) { continue; } is_dir = false; if(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { is_dir = true; } /* * If not recursively decending, then if we find a directory then fail * since we were not told to remove it. */ if( is_dir && !recursive) { /* Set the error indicating that we found a directory, * but continue removing files */ exit_status = OPAL_ERROR; continue; } /* Will the caller allow us to remove this file/directory */ if( NULL != cbfunc) { if( !cbfunc(path, file_data.cFileName) ) { continue; } } file_name = opal_os_path(false, path, file_data.cFileName, NULL); if( is_dir ) { if( OPAL_SUCCESS != (rc = opal_os_dirpath_destroy(file_name, recursive, cbfunc) ) ) { exit_status = rc; goto cleanup; } } else { DeleteFile(file_name); } } while( 0 != FindNextFile(file, &file_data) ); FindClose(file); #endif cleanup: /* * If the directory is empty, them remove it */ if(opal_os_dirpath_is_empty(path)) { rmdir(path); } return exit_status; }
VOID CompleteFilename (LPTSTR str, UINT charcount) { WIN32_FIND_DATA file; HANDLE hFile; INT curplace = 0; INT start; INT count; INT step; INT c = 0; BOOL found_dot = FALSE; BOOL perfectmatch = TRUE; TCHAR path[MAX_PATH]; TCHAR fname[MAX_PATH]; TCHAR maxmatch[MAX_PATH] = _T(""); TCHAR directory[MAX_PATH]; LPCOMMAND cmds_ptr; /* expand current file name */ count = charcount - 1; if (count < 0) count = 0; /* find how many '"'s there is typed already. */ step = count; while (step > 0) { if (str[step] == _T('"')) c++; step--; } /* if c is odd, then user typed " before name, else not. */ /* find front of word */ if (str[count] == _T('"') || (c % 2)) { count--; while (count > 0 && str[count] != _T('"')) count--; } else { while (count > 0 && str[count] != _T(' ')) count--; } /* if not at beginning, go forward 1 */ if (str[count] == _T(' ')) count++; start = count; if (str[count] == _T('"')) count++; /* don't increment start */ /* extract directory from word */ _tcscpy (directory, &str[count]); curplace = _tcslen (directory) - 1; if (curplace >= 0 && directory[curplace] == _T('"')) directory[curplace--] = _T('\0'); _tcscpy (path, directory); while (curplace >= 0 && directory[curplace] != _T('\\') && directory[curplace] != _T('/') && directory[curplace] != _T(':')) { directory[curplace] = 0; curplace--; } /* look for a '.' in the filename */ for (count = _tcslen (directory); path[count] != _T('\0'); count++) { if (path[count] == _T('.')) { found_dot = TRUE; break; } } if (found_dot) _tcscat (path, _T("*")); else _tcscat (path, _T("*.*")); /* current fname */ curplace = 0; hFile = FindFirstFile (path, &file); if (hFile != INVALID_HANDLE_VALUE) { /* find anything */ do { /* ignore "." and ".." */ if (!_tcscmp (file.cFileName, _T(".")) || !_tcscmp (file.cFileName, _T(".."))) continue; _tcscpy (fname, file.cFileName); if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) _tcscat (fname, _T("\\")); if (!maxmatch[0] && perfectmatch) { _tcscpy(maxmatch, fname); } else { for (count = 0; maxmatch[count] && fname[count]; count++) { if (tolower(maxmatch[count]) != tolower(fname[count])) { perfectmatch = FALSE; maxmatch[count] = 0; break; } } if (maxmatch[count] == _T('\0') && fname[count] != _T('\0')) perfectmatch = FALSE; } } while (FindNextFile (hFile, &file)); FindClose (hFile); /* only quote if the filename contains spaces */ if (_tcschr(directory, _T(' ')) || _tcschr(maxmatch, _T(' '))) { str[start] = _T('\"'); _tcscpy (&str[start+1], directory); _tcscat (&str[start], maxmatch); _tcscat (&str[start], _T("\"") ); } else { _tcscpy (&str[start], directory); _tcscat (&str[start], maxmatch); } if (!perfectmatch) { MessageBeep (-1); } } else { /* no match found - search for internal command */ for (cmds_ptr = cmds; cmds_ptr->name; cmds_ptr++) { if (!_tcsnicmp (&str[start], cmds_ptr->name, _tcslen (&str[start]))) { /* return the mach only if it is unique */ if (_tcsnicmp (&str[start], (cmds_ptr+1)->name, _tcslen (&str[start]))) _tcscpy (&str[start], cmds_ptr->name); break; } } MessageBeep (-1); } }
// Loads lua scripts from given directory void Eluna::LoadDirectory(char* Dirname, LoadedScripts* lscr) { #ifdef WIN32 HANDLE hFile; WIN32_FIND_DATA FindData; memset(&FindData, 0, sizeof(FindData)); char SearchName[MAX_PATH]; strcpy(SearchName, Dirname); strcat(SearchName, "\\*.*"); hFile = FindFirstFile(SearchName, &FindData); if (hFile == INVALID_HANDLE_VALUE) { sLog.outErrorEluna("[Eluna]: Error No `lua_scripts` directory found! Creating a 'lua_scripts' directory."); CreateDirectory("lua_scripts", NULL); return; } FindNextFile(hFile, &FindData); while (FindNextFile(hFile, &FindData)) { if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { strcpy(SearchName, Dirname); strcat(SearchName, "\\"); strcat(SearchName, FindData.cFileName); LoadDirectory(SearchName, lscr); } else { std::string fname = Dirname; fname += "\\"; fname += FindData.cFileName; size_t len = strlen(fname.c_str()); int i = 0; char ext[MAX_PATH]; while (len > 0) { ext[i++] = fname[--len]; if (fname[len] == '.') break; } ext[i++] = '\0'; if (!_stricmp(ext, "aul.")) { sLog.outDebug("[Eluna]: Load File: %s", fname.c_str()); lscr->insert(fname); } } } FindClose(hFile); #else char* dir = strrchr(Dirname, '/'); if (strcmp(Dirname, "..") == 0 || strcmp(Dirname, ".") == 0) return; if (dir && (strcmp(dir, "/..") == 0 || strcmp(dir, "/.") == 0 || strcmp(dir, "/.svn") == 0)) return; struct dirent** list; int fileCount = scandir(Dirname, &list, 0, 0); if (fileCount <= 0 || !list) return; struct stat attributes; bool error; while (fileCount--) { char _path[200]; sprintf(_path, "%s/%s", Dirname, list[fileCount]->d_name); if (stat(_path, &attributes) == -1) { error = true; sLog.outErrorEluna("[Eluna]: Error opening `%s`", _path); } else error = false; if (!error && S_ISDIR(attributes.st_mode)) LoadDirectory((char*)_path, lscr); else { char* ext = strrchr(list[fileCount]->d_name, '.'); if (ext && !strcmp(ext, ".lua")) lscr->insert(_path); } free(list[fileCount]); } free(list); #endif }
int SSL_CTX_load_verify_locations(SSL_CTX* ctx, const char* file, const char* path) { int ret = SSL_FAILURE; const int HALF_PATH = 128; if (file) ret = read_file(ctx, file, SSL_FILETYPE_PEM, CA); if (ret == SSL_SUCCESS && path) { // call read_file for each reqular file in path #ifdef _WIN32 WIN32_FIND_DATA FindFileData; HANDLE hFind; char name[MAX_PATH + 1]; // directory specification strncpy(name, path, MAX_PATH - 3); strncat(name, "\\*", 3); hFind = FindFirstFile(name, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) return SSL_BAD_PATH; do { if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY) { strncpy(name, path, MAX_PATH - 2 - HALF_PATH); strncat(name, "\\", 2); strncat(name, FindFileData.cFileName, HALF_PATH); ret = read_file(ctx, name, SSL_FILETYPE_PEM, CA); } } while (ret == SSL_SUCCESS && FindNextFile(hFind, &FindFileData)); FindClose(hFind); #else // _WIN32 const int MAX_PATH = 260; DIR* dir = opendir(path); if (!dir) return SSL_BAD_PATH; struct dirent* entry; struct stat buf; char name[MAX_PATH + 1]; while (ret == SSL_SUCCESS && (entry = readdir(dir))) { strncpy(name, path, MAX_PATH - 1 - HALF_PATH); strncat(name, "/", 1); strncat(name, entry->d_name, HALF_PATH); if (stat(name, &buf) < 0) return SSL_BAD_STAT; if (S_ISREG(buf.st_mode)) ret = read_file(ctx, name, SSL_FILETYPE_PEM, CA); } closedir(dir); #endif } return ret; }