Example #1
0
File: fscache.c Project: guban/git
/*
 * Create an fsentry-based directory listing (similar to opendir / readdir).
 * Dir should not contain trailing '/'. Use an empty string for the current
 * directory (not "."!).
 */
static struct fsentry *fsentry_create_list(const struct fsentry *dir,
					   int *dir_not_found)
{
	wchar_t pattern[MAX_LONG_PATH + 2]; /* + 2 for "\*" */
	WIN32_FIND_DATAW fdata;
	HANDLE h;
	int wlen;
	struct fsentry *list, **phead;
	DWORD err;

	*dir_not_found = 0;

	/* convert name to UTF-16 and check length */
	if ((wlen = xutftowcs_path_ex(pattern, dir->name, MAX_LONG_PATH,
			dir->len, MAX_PATH - 2, core_long_paths)) < 0)
		return NULL;

	/*
	 * append optional '\' and wildcard '*'. Note: we need to use '\' as
	 * Windows doesn't translate '/' to '\' for "\\?\"-prefixed paths.
	 */
	if (wlen)
		pattern[wlen++] = '\\';
	pattern[wlen++] = '*';
	pattern[wlen] = 0;

	/* open find handle */
	h = FindFirstFileW(pattern, &fdata);
	if (h == INVALID_HANDLE_VALUE) {
		err = GetLastError();
		*dir_not_found = 1; /* or empty directory */
		errno = (err == ERROR_DIRECTORY) ? ENOTDIR : err_win_to_posix(err);
		trace_printf_key(&trace_fscache, "fscache: error(%d) '%.*s'\n",
						 errno, dir->len, dir->name);
		return NULL;
	}

	/* allocate object to hold directory listing */
	list = fsentry_alloc(NULL, dir->name, dir->len);
	list->st_mode = S_IFDIR;

	/* walk directory and build linked list of fsentry structures */
	phead = &list->next;
	do {
		*phead = fseentry_create_entry(list, &fdata);
		phead = &(*phead)->next;
	} while (FindNextFileW(h, &fdata));

	/* remember result of last FindNextFile, then close find handle */
	err = GetLastError();
	FindClose(h);

	/* return the list if we've got all the files */
	if (err == ERROR_NO_MORE_FILES)
		return list;

	/* otherwise free the list and return error */
	fsentry_release(list);
	errno = err_win_to_posix(err);
	return NULL;
}
Example #2
0
/**
   sys_read_dir : string -> string list
   <doc>Return the content of a directory</doc>
**/
Array<String> _hx_std_sys_read_dir( String p )
{
   Array<String> result = Array_obj<String>::__new();

#if defined(NEKO_WINDOWS)
   const wchar_t *path = p.__WCStr();
   size_t len = wcslen(path);
   if (len>MAX_PATH)
      return null();

   WIN32_FIND_DATAW d;
   HANDLE handle;
  #if defined(HX_WINRT) && !defined(_XBOX_ONE)
   std::wstring tempWStr(path);
   std::string searchPath(tempWStr.begin(), tempWStr.end());
  #else
   wchar_t searchPath[ MAX_PATH + 4 ];
   memcpy(searchPath,path, len*sizeof(wchar_t));
  #endif


   if( len && path[len-1] != '/' && path[len-1] != '\\' )
      searchPath[len++] = '/';
   searchPath[len++] = '*';
   searchPath[len++] = '.';
   searchPath[len++] = '*';
   searchPath[len] = '\0';

   hx::EnterGCFreeZone();
  #if defined(HX_WINRT) && !defined(_XBOX_ONE)
   handle = FindFirstFileEx(searchPath.c_str(), FindExInfoStandard, &d, FindExSearchNameMatch, NULL, 0);
  #else
   handle = FindFirstFileW(searchPath,&d);
  #endif
   if( handle == INVALID_HANDLE_VALUE )
   {
      hx::ExitGCFreeZone();
      return null();
   }
   while( true )
   {
      // skip magic dirs
      if( d.cFileName[0] != '.' || (d.cFileName[1] != 0 && (d.cFileName[1] != '.' || d.cFileName[2] != 0)) )
      {
         hx::ExitGCFreeZone();
         result->push(String(d.cFileName));
         hx::EnterGCFreeZone();
      }
      if( !FindNextFileW(handle,&d) )
         break;
   }
   FindClose(handle);
#elif !defined(EPPC)
   const char *name = p.__s;
   hx::EnterGCFreeZone();
   DIR *d = opendir(name);
   if( d == NULL )
   {
      hx::ExitGCFreeZone();
      hx::Throw(HX_CSTRING("Invalid directory"));
   }
   while( true )
   {
      struct dirent *e = readdir(d);
      if( e == NULL )
         break;
      // skip magic dirs
      if( e->d_name[0] == '.' && (e->d_name[1] == 0 || (e->d_name[1] == '.' && e->d_name[2] == 0)) )
         continue;
      hx::ExitGCFreeZone();
      result->push( String(e->d_name) );
      hx::ExitGCFreeZone();
   }
   closedir(d);
#endif
   hx::ExitGCFreeZone();

   return result;
}
Example #3
0
static DIRECTORY_STACK *WCMD_list_directory (DIRECTORY_STACK *inputparms, int level) {

  WCHAR string[1024], datestring[32], timestring[32];
  WCHAR real_path[MAX_PATH];
  WIN32_FIND_DATAW *fd;
  FILETIME ft;
  SYSTEMTIME st;
  HANDLE hff;
  int dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
  int numCols, numRows;
  int rows, cols;
  ULARGE_INTEGER byte_count, file_size;
  DIRECTORY_STACK *parms;
  int concurrentDirs = 0;
  BOOL done_header = FALSE;

  static const WCHAR fmtDir[]  = {'%','1','!','1','0','s','!',' ',' ','%','2','!','8','s','!',' ',' ',
                                  '<','D','I','R','>',' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
  static const WCHAR fmtFile[] = {'%','1','!','1','0','s','!',' ',' ','%','2','!','8','s','!',' ',' ',
                                  ' ',' ','%','3','!','1','0','s','!',' ',' ','\0'};
  static const WCHAR fmt2[]  = {'%','1','!','-','1','3','s','!','\0'};
  static const WCHAR fmt3[]  = {'%','1','!','-','2','3','s','!','\0'};
  static const WCHAR fmt4[]  = {'%','1','\0'};
  static const WCHAR fmt5[]  = {'%','1','%','2','\0'};

  dir_count = 0;
  file_count = 0;
  entry_count = 0;
  byte_count.QuadPart = 0;
  widest = 0;
  cur_width = 0;

  /* Loop merging all the files from consecutive parms which relate to the
     same directory. Note issuing a directory header with no contents
     mirrors what windows does                                            */
  parms = inputparms;
  fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATAW));
  while (parms && strcmpW(inputparms->dirName, parms->dirName) == 0) {
    concurrentDirs++;

    /* Work out the full path + filename */
    strcpyW(real_path, parms->dirName);
    strcatW(real_path, parms->fileName);

    /* Load all files into an in memory structure */
    WINE_TRACE("Looking for matches to '%s'\n", wine_dbgstr_w(real_path));
    hff = FindFirstFileW(real_path, (fd+entry_count));
    if (hff != INVALID_HANDLE_VALUE) {
      do {
        /* Skip any which are filtered out by attribute */
        if (((fd+entry_count)->dwFileAttributes & attrsbits) != showattrs) continue;

        entry_count++;

        /* Keep running track of longest filename for wide output */
        if (wide || orderByCol) {
           int tmpLen = strlenW((fd+(entry_count-1))->cFileName) + 3;
           if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
           if (tmpLen > widest) widest = tmpLen;
        }

        fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATAW));
        if (fd == NULL) {
          FindClose (hff);
          WINE_ERR("Out of memory\n");
          errorlevel = 1;
          return parms->next;
        }
      } while (FindNextFileW(hff, (fd+entry_count)) != 0);
      FindClose (hff);
    }

    /* Work out the actual current directory name without a trailing \ */
    strcpyW(real_path, parms->dirName);
    real_path[strlenW(parms->dirName)-1] = 0x00;

    /* Output the results */
    if (!bare) {
       if (level != 0 && (entry_count > 0)) WCMD_output_asis (newline);
       if (!recurse || ((entry_count > 0) && done_header==FALSE)) {
           static const WCHAR headerW[] = {'D','i','r','e','c','t','o','r','y',' ','o','f',
                                           ' ','%','1','\n','\n','\0'};
           WCMD_output (headerW, real_path);
           done_header = TRUE;
       }
    }

    /* Move to next parm */
    parms = parms->next;
  }

  /* Handle case where everything is filtered out */
  if (entry_count > 0) {

    /* Sort the list of files */
    qsort (fd, entry_count, sizeof(WIN32_FIND_DATAW), WCMD_dir_sort);

    /* Work out the number of columns */
    WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
    if (wide || orderByCol) {
      numCols = max(1, (int)max_width / widest);
      numRows = entry_count / numCols;
      if (entry_count % numCols) numRows++;
    } else {
      numCols = 1;
      numRows = entry_count;
    }
    WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);

    for (rows=0; rows<numRows; rows++) {
     BOOL addNewLine = TRUE;
     for (cols=0; cols<numCols; cols++) {
      WCHAR username[24];

      /* Work out the index of the entry being pointed to */
      if (orderByCol) {
        i = (cols * numRows) + rows;
        if (i >= entry_count) continue;
      } else {
        i = (rows * numCols) + cols;
        if (i >= entry_count) continue;
      }

      /* /L convers all names to lower case */
      if (lower) {
          WCHAR *p = (fd+i)->cFileName;
          while ( (*p = tolower(*p)) ) ++p;
      }

      /* /Q gets file ownership information */
      if (usernames) {
          strcpyW (string, inputparms->dirName);
          strcatW (string, (fd+i)->cFileName);
          WCMD_getfileowner(string, username, sizeof(username)/sizeof(WCHAR));
      }

      if (dirTime == Written) {
        FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
      } else if (dirTime == Access) {
        FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
      } else {
        FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
      }
      FileTimeToSystemTime (&ft, &st);
      GetDateFormatW(0, DATE_SHORTDATE, &st, NULL, datestring,
			sizeof(datestring)/sizeof(WCHAR));
      GetTimeFormatW(0, TIME_NOSECONDS, &st,
			NULL, timestring, sizeof(timestring)/sizeof(WCHAR));

      if (wide) {

        tmp_width = cur_width;
        if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
            static const WCHAR fmt[] = {'[','%','1',']','\0'};
            WCMD_output (fmt, (fd+i)->cFileName);
            dir_count++;
            tmp_width = tmp_width + strlenW((fd+i)->cFileName) + 2;
        } else {
            static const WCHAR fmt[] = {'%','1','\0'};
            WCMD_output (fmt, (fd+i)->cFileName);
            tmp_width = tmp_width + strlenW((fd+i)->cFileName) ;
            file_count++;
            file_size.u.LowPart = (fd+i)->nFileSizeLow;
            file_size.u.HighPart = (fd+i)->nFileSizeHigh;
        byte_count.QuadPart += file_size.QuadPart;
        }
        cur_width = cur_width + widest;

        if ((cur_width + widest) > max_width) {
            cur_width = 0;
        } else {
            static const WCHAR padfmt[] = {'%','1','!','*','s','!','\0'};
            WCMD_output(padfmt, cur_width - tmp_width, nullW);
        }

      } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        dir_count++;

        if (!bare) {
           WCMD_output (fmtDir, datestring, timestring);
           if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
           if (usernames) WCMD_output (fmt3, username);
           WCMD_output(fmt4,(fd+i)->cFileName);
        } else {
           if (!((strcmpW((fd+i)->cFileName, dotW) == 0) ||
                 (strcmpW((fd+i)->cFileName, dotdotW) == 0))) {
              WCMD_output (fmt5, recurse?inputparms->dirName:nullW, (fd+i)->cFileName);
           } else {
              addNewLine = FALSE;
           }
        }
      }
      else {
        file_count++;
        file_size.u.LowPart = (fd+i)->nFileSizeLow;
        file_size.u.HighPart = (fd+i)->nFileSizeHigh;
        byte_count.QuadPart += file_size.QuadPart;
        if (!bare) {
           WCMD_output (fmtFile, datestring, timestring,
                        WCMD_filesize64(file_size.QuadPart));
           if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
           if (usernames) WCMD_output (fmt3, username);
           WCMD_output(fmt4,(fd+i)->cFileName);
        } else {
           WCMD_output (fmt5, recurse?inputparms->dirName:nullW, (fd+i)->cFileName);
        }
      }
     }
     if (addNewLine) WCMD_output_asis (newline);
     cur_width = 0;
    }

    if (!bare) {
       if (file_count == 1) {
         static const WCHAR fmt[] = {' ',' ',' ',' ',' ',' ',' ','1',' ','f','i','l','e',' ',
                                     '%','1','!','2','5','s','!',' ','b','y','t','e','s','\n','\0'};
         WCMD_output (fmt, WCMD_filesize64 (byte_count.QuadPart));
       }
       else {
         static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','f','i','l','e','s',' ','%','2','!','2','4','s','!',
                                     ' ','b','y','t','e','s','\n','\0'};
         WCMD_output (fmt, file_count, WCMD_filesize64 (byte_count.QuadPart));
       }
    }
    byte_total = byte_total + byte_count.QuadPart;
    file_total = file_total + file_count;
    dir_total = dir_total + dir_count;

    if (!bare && !recurse) {
       if (dir_count == 1) {
           static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','y',
                                       ' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
           WCMD_output (fmt, 1);
       } else {
           static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','i',
                                       'e','s','\0'};
           WCMD_output (fmt, dir_count);
       }
    }
  }
  HeapFree(GetProcessHeap(),0,fd);

  /* When recursing, look in all subdirectories for matches */
  if (recurse) {
    DIRECTORY_STACK *dirStack = NULL;
    DIRECTORY_STACK *lastEntry = NULL;
    WIN32_FIND_DATAW finddata;

    /* Build path to search */
    strcpyW(string, inputparms->dirName);
    strcatW(string, starW);

    WINE_TRACE("Recursive, looking for '%s'\n", wine_dbgstr_w(string));
    hff = FindFirstFileW(string, &finddata);
    if (hff != INVALID_HANDLE_VALUE) {
      do {
        if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
            (strcmpW(finddata.cFileName, dotdotW) != 0) &&
            (strcmpW(finddata.cFileName, dotW) != 0)) {

          DIRECTORY_STACK *thisDir;
          int              dirsToCopy = concurrentDirs;

          /* Loop creating list of subdirs for all concurrent entries */
          parms = inputparms;
          while (dirsToCopy > 0) {
            dirsToCopy--;

            /* Work out search parameter in sub dir */
            strcpyW (string, inputparms->dirName);
            strcatW (string, finddata.cFileName);
            strcatW (string, slashW);
            WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(string));

            /* Allocate memory, add to list */
            thisDir = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
            if (dirStack == NULL) dirStack = thisDir;
            if (lastEntry != NULL) lastEntry->next = thisDir;
            lastEntry = thisDir;
            thisDir->next = NULL;
            thisDir->dirName = HeapAlloc(GetProcessHeap(),0,
                                         sizeof(WCHAR) * (strlenW(string)+1));
            strcpyW(thisDir->dirName, string);
            thisDir->fileName = HeapAlloc(GetProcessHeap(),0,
                                          sizeof(WCHAR) * (strlenW(parms->fileName)+1));
            strcpyW(thisDir->fileName, parms->fileName);
            parms = parms->next;
          }
        }
      } while (FindNextFileW(hff, &finddata) != 0);
      FindClose (hff);

      while (dirStack != NULL) {
        DIRECTORY_STACK *thisDir = dirStack;
        dirStack = WCMD_list_directory (thisDir, 1);
        while (thisDir != dirStack) {
          DIRECTORY_STACK *tempDir = thisDir->next;
          HeapFree(GetProcessHeap(),0,thisDir->dirName);
          HeapFree(GetProcessHeap(),0,thisDir->fileName);
          HeapFree(GetProcessHeap(),0,thisDir);
          thisDir = tempDir;
        }
      }
    }
  }

  /* Handle case where everything is filtered out */
  if ((file_total + dir_total == 0) && (level == 0)) {
    SetLastError (ERROR_FILE_NOT_FOUND);
    WCMD_print_error ();
    errorlevel = 1;
  }

  return parms;
}
Example #4
0
/* Recursively searches the directory dir for files that match the signature
 * sig, up to (depth + 1) levels deep.  That is, if depth is 0, it searches dir
 * (and only dir).  If depth is 1, searches dir and its immediate
 * subdirectories.
 * Assumes sig->File is not NULL.
 * Returns ERROR_SUCCESS on success (which may include non-critical errors),
 * something else on failures which should halt the install.
 */
static UINT ACTION_RecurseSearchDirectory(MSIPACKAGE *package, LPWSTR *appValue,
 MSISIGNATURE *sig, LPCWSTR dir, int depth)
{
    HANDLE hFind;
    WIN32_FIND_DATAW findData;
    UINT rc = ERROR_SUCCESS;
    size_t dirLen = lstrlenW(dir), fileLen = lstrlenW(sig->File);
    WCHAR subpath[MAX_PATH];
    WCHAR *buf;
    DWORD len;

    static const WCHAR starDotStarW[] = { '*','.','*',0 };

    TRACE("Searching directory %s for file %s, depth %d\n", debugstr_w(dir),
          debugstr_w(sig->File), depth);

    if (depth < 0)
        return ERROR_SUCCESS;

    *appValue = NULL;
    /* We need the buffer in both paths below, so go ahead and allocate it
     * here.  Add two because we might need to add a backslash if the dir name
     * isn't backslash-terminated.
     */
    len = dirLen + max(fileLen, strlenW(starDotStarW)) + 2;
    buf = msi_alloc(len * sizeof(WCHAR));
    if (!buf)
        return ERROR_OUTOFMEMORY;

    lstrcpyW(buf, dir);
    PathAddBackslashW(buf);
    lstrcatW(buf, sig->File);

    hFind = FindFirstFileW(buf, &findData);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
            BOOL matches;

            rc = ACTION_FileMatchesSig(sig, &findData, buf, &matches);
            if (rc == ERROR_SUCCESS && matches)
            {
                TRACE("found file, returning %s\n", debugstr_w(buf));
                *appValue = buf;
            }
        }
        FindClose(hFind);
    }

    if (rc == ERROR_SUCCESS && !*appValue)
    {
        lstrcpyW(buf, dir);
        PathAddBackslashW(buf);
        lstrcatW(buf, starDotStarW);

        hFind = FindFirstFileW(buf, &findData);
        if (hFind != INVALID_HANDLE_VALUE)
        {
            if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
                strcmpW( findData.cFileName, szDot ) &&
                strcmpW( findData.cFileName, szDotDot ))
            {
                lstrcpyW(subpath, dir);
                PathAppendW(subpath, findData.cFileName);
                rc = ACTION_RecurseSearchDirectory(package, appValue, sig,
                                                   subpath, depth - 1);
            }

            while (rc == ERROR_SUCCESS && !*appValue &&
                   FindNextFileW(hFind, &findData) != 0)
            {
                if (!strcmpW( findData.cFileName, szDot ) ||
                    !strcmpW( findData.cFileName, szDotDot ))
                    continue;

                lstrcpyW(subpath, dir);
                PathAppendW(subpath, findData.cFileName);
                if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                    rc = ACTION_RecurseSearchDirectory(package, appValue,
                                                       sig, subpath, depth - 1);
            }

            FindClose(hFind);
        }
    }

    if (*appValue != buf)
        msi_free(buf);

    return rc;
}
Example #5
0
/*
  Replace the last part of the path to long name.
  We try to avoid to call FindFirstFileW() since it takes long time.
*/
static inline size_t
replace_to_long_name(wchar_t **wfullpath, size_t size, int heap)
{
    WIN32_FIND_DATAW find_data;
    HANDLE find_handle;

    /*
      Skip long name conversion if the path is already long name.
      Short name is 8.3 format.
      http://en.wikipedia.org/wiki/8.3_filename
      This check can be skipped for directory components that have file
      extensions longer than 3 characters, or total lengths longer than
      12 characters.
      http://msdn.microsoft.com/en-us/library/windows/desktop/aa364980(v=vs.85).aspx
    */
    size_t const max_short_name_size = 8 + 1 + 3;
    size_t const max_extension_size = 3;
    size_t path_len = 1, extension_len = 0;
    wchar_t *pos = *wfullpath;

    if (size == 3 && pos[1] == L':' && pos[2] == L'\\' && pos[3] == L'\0') {
        /* root path doesn't need short name expansion */
        return size;
    }

    /* skip long name conversion if path contains wildcard characters */
    if (wcspbrk(pos, L"*?")) {
        return size;
    }

    pos = *wfullpath + size - 1;
    while (!IS_DIR_SEPARATOR_P(*pos) && pos != *wfullpath) {
        if (!extension_len && *pos == L'.') {
            extension_len = path_len - 1;
        }
        if (path_len > max_short_name_size || extension_len > max_extension_size) {
            return size;
        }
        path_len++;
        pos--;
    }

    find_handle = FindFirstFileW(*wfullpath, &find_data);
    if (find_handle != INVALID_HANDLE_VALUE) {
        size_t trail_pos = wcslen(*wfullpath);
        size_t file_len = wcslen(find_data.cFileName);

        FindClose(find_handle);
        while (trail_pos > 0) {
            if (IS_DIR_SEPARATOR_P((*wfullpath)[trail_pos]))
                break;
            trail_pos--;
        }
        size = trail_pos + 1 + file_len;
        if ((size + 1) > sizeof(*wfullpath) / sizeof((*wfullpath)[0])) {
            wchar_t *buf = (wchar_t *)xmalloc((size + 1) * sizeof(wchar_t));
            wcsncpy(buf, *wfullpath, trail_pos + 1);
            if (heap)
                xfree(*wfullpath);
            *wfullpath = buf;
        }
        wcsncpy(*wfullpath + trail_pos + 1, find_data.cFileName, file_len + 1);
    }
    return size;
}
Example #6
0
int
efile_rmdir(Efile_error* errInfo,	/* Where to return error codes. */
	    char* name)			/* Name of directory to delete. */
{
    OSVERSIONINFO os;
    DWORD attr;
    WCHAR *wname = (WCHAR *) name;

    if (RemoveDirectoryW(wname) != FALSE) {
	return 1;
    }
    errno = errno_map(GetLastError());
    if (errno == EACCES) {
	attr = GetFileAttributesW(wname);
	if (attr != (DWORD) -1) {
	    if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
		/* 
		 * Windows 95 reports calling RemoveDirectory on a file as an 
		 * EACCES, not an ENOTDIR.
		 */
		
		errno = ENOTDIR;
		goto end;
	    }

	    /* 
	     * Windows 95 reports removing a non-empty directory as
	     * an EACCES, not an EEXIST.  If the directory is not empty,
	     * change errno so caller knows what's going on.
	     */

	    os.dwOSVersionInfoSize = sizeof(os);
	    GetVersionEx(&os);
	    if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
		HANDLE handle;
		WIN32_FIND_DATAW data;
		WCHAR buffer[2*MAX_PATH];
		int len;

		len = wcslen(wname);
		wcscpy(buffer, wname);
		if (buffer[0] && buffer[len-1] != L'\\' && buffer[len-1] != L'/') {
		    wcscat(buffer, L"\\");
		}
		wcscat(buffer, L"*.*");
		handle = FindFirstFileW(buffer, &data);
		if (handle != INVALID_HANDLE_VALUE) {
		    while (1) {
			if ((wcscmp(data.cFileName, L".") != 0)
				&& (wcscmp(data.cFileName, L"..") != 0)) {
			    /*
			     * Found something in this directory.
			     */

			    errno = EEXIST;
			    break;
			}
			if (FindNextFileW(handle, &data) == FALSE) {
			    break;
			}
		    }
		    FindClose(handle);
		}
	    }
	}
    }

    if (errno == ENOTEMPTY) {
	/* 
	 * Posix allows both EEXIST or ENOTEMPTY, but we'll always
	 * return EEXIST to allow easy matching in Erlang code.
	 */

	errno = EEXIST;
    }

 end:
    return check_error(-1, errInfo);
}
Example #7
0
/*
 * __wt_win_directory_list --
 *	Get a list of files from a directory, MSVC version.
 */
int
__wt_win_directory_list(WT_FILE_SYSTEM *file_system,
    WT_SESSION *wt_session, const char *directory,
    const char *prefix, char ***dirlistp, uint32_t *countp)
{
	DWORD windows_error;
	HANDLE findhandle;
	WIN32_FIND_DATAW finddata;
	WT_DECL_ITEM(pathbuf);
	WT_DECL_ITEM(file_utf8);
	WT_DECL_ITEM(pathbuf_wide);
	WT_DECL_ITEM(prefix_wide);
	WT_DECL_RET;
	WT_SESSION_IMPL *session;
	size_t dirallocsz, pathlen, prefix_widelen;
	uint32_t count;
	char *dir_copy, **entries;

	session = (WT_SESSION_IMPL *)wt_session;

	*dirlistp = NULL;
	*countp = 0;

	findhandle = INVALID_HANDLE_VALUE;
	dirallocsz = 0;
	entries = NULL;

	WT_ERR(__wt_strdup(session, directory, &dir_copy));
	pathlen = strlen(dir_copy);
	if (dir_copy[pathlen - 1] == '\\')
		dir_copy[pathlen - 1] = '\0';
	WT_ERR(__wt_scr_alloc(session, pathlen + 3, &pathbuf));
	WT_ERR(__wt_buf_fmt(session, pathbuf, "%s\\*", dir_copy));

	WT_ERR(__wt_to_utf16_string(session, pathbuf->data, &pathbuf_wide));
	WT_ERR(__wt_to_utf16_string(session, prefix, &prefix_wide));
	prefix_widelen = wcslen(prefix_wide->data);

	findhandle = FindFirstFileW(pathbuf_wide->data, &finddata);
	if (findhandle == INVALID_HANDLE_VALUE) {
		windows_error = __wt_getlasterror();
		__wt_errx(session,
		    "%s: directory-list: FindFirstFile: %s",
		    pathbuf->data, __wt_formatmessage(session, windows_error));
		WT_ERR(__wt_map_windows_error(windows_error));
	}

	count = 0;
	do {
		/*
		 * Skip . and ..
		 */
		if (wcscmp(finddata.cFileName, L".") == 0 ||
		    wcscmp(finddata.cFileName, L"..") == 0)
			continue;

		/* The list of files is optionally filtered by a prefix. */
		if (prefix != NULL &&
		    wcsncmp(finddata.cFileName, prefix_wide->data,
			prefix_widelen) != 0)
			continue;

		WT_ERR(__wt_realloc_def(
		    session, &dirallocsz, count + 1, &entries));

		WT_ERR(__wt_to_utf8_string(
		    session, finddata.cFileName, &file_utf8));
		WT_ERR(__wt_strdup(session, file_utf8->data, &entries[count]));
		++count;
		__wt_scr_free(session, &file_utf8);
	} while (FindNextFileW(findhandle, &finddata) != 0);

	*dirlistp = entries;
	*countp = count;

err:	if (findhandle != INVALID_HANDLE_VALUE)
		if (FindClose(findhandle) == 0) {
			windows_error = __wt_getlasterror();
			__wt_errx(session,
			    "%s: directory-list: FindClose: %s",
			    pathbuf->data,
			    __wt_formatmessage(session, windows_error));
			if (ret == 0)
				ret = __wt_map_windows_error(windows_error);
		}

	__wt_free(session, dir_copy);
	__wt_scr_free(session, &pathbuf);
	__wt_scr_free(session, &file_utf8);
	__wt_scr_free(session, &pathbuf_wide);
	__wt_scr_free(session, &prefix_wide);

	if (ret == 0)
		return (0);

	WT_TRET(__wt_win_directory_list_free(
	    file_system, wt_session, entries, count));

	WT_RET_MSG(session, ret,
	    "%s: directory-list, prefix \"%s\"",
	    directory, prefix == NULL ? "" : prefix);
}
void FSDeleteFolderAndFiles(const unicode_t *dirName)
{
	if ( dirName == NULL ) return;
	if ( *dirName == 0 ) return;

#if defined(WIN32) || defined(_WIN32_WCE)

	UniString	findDir(dirName);

	if ( !findDir.EndWith(USTR("\\*.*")) )
	{
		if ( findDir.GetLastChar() == '\\' )
			findDir += L"*.*";
		else
			findDir += L"\\*.*";

		if ( findDir.GetCount() <= 6 ) return;
	}
	else
	{
		if ( findDir.GetCount() <= 6 ) return;
	}

	HANDLE hFind;

#if defined(_WIN32_WCE)
	WIN32_FIND_DATA findFileData;
	hFind = FindFirstFile(findDir.GetString(), &findFileData);
#else
	WIN32_FIND_DATAW findFileData;
	hFind = FindFirstFileW(findDir.GetString(), &findFileData);
#endif

	if (hFind != INVALID_HANDLE_VALUE) 
	{
		UniString	filePath;

		do
		{
			if ( wcscmp(findFileData.cFileName, L".") == 0 || wcscmp(findFileData.cFileName, L"..") == 0 )
				continue;

			filePath = dirName;
			filePath += L"\\";
			filePath += findFileData.cFileName;

			if ( findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
			{
				FSDeleteFolderAndFiles(filePath);
			}
			else
			{
				if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
					SetFileAttributesW(filePath.GetString(), FILE_ATTRIBUTE_NORMAL);

			#if defined(_WIN32_WCE)
				DeleteFile(filePath);
			#else
				DeleteFileW(filePath);
			#endif
			}
		}
	#if defined(_WIN32_WCE)
		while (FindNextFile(hFind, &findFileData) != 0);
	#else
		while (FindNextFileW(hFind, &findFileData) != 0);
	#endif

		FindClose(hFind);
	}

	RemoveDirectoryW(dirName);

#elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
	FSString	fsString(dirName);
	
	if ( fsString.GetCount() <= 1 ) return;

	_DeleteFolderAndFiles(fsString.GetString());
#else
	FSString	fsString(dirName);
	_DeleteFolderAndFiles(fsString.GetString());
#endif
}
Example #9
0
_MY_C_HEAD_
#include "LZMA/7zVersion.h"
#include "LZMA/Alloc.h"
#include "LZMA/Lzma86.h"
_MY_C_TAIL_

void __cdecl main2(int argc, wchar_t **argv)
{
    if (argc < 3)
    {
        printf("Too few parameters\n");
        return;
    }

    Byte  *outBuffer, FileType, bLZMA;
    SizeT  inSize, outSize, outMaxSize;
    WCHAR  szFileName[MAX_PATH];
    WCHAR  *szFileType[] = { L"UCA", L"UCI", L"AAC", L"M4A", L"Unknown" };
    PBYTE  pbFile;
    DWORD  dwFileNumber, dwErrorCount, dwMaxNumber, dwFileSize, dwRead;
    DWORD  dwBufferSize, dwMaxFileNumber, dwMethod[] = {'ACU', 'ICU', 'CAA', 'A4M', 'KNU'};
    HANDLE hFind, hHeap, hFile, hDestFile;
    WIN32_FIND_DATAW wfd;
    TSpiArchiveInfo *pSpiArcInfo;
    LARGE_INTEGER liFrequency, liStart, liStop;

    setlocale(LC_CTYPE, "");

    hDestFile = CreateFileW(argv[2],
                    GENERIC_READ|GENERIC_WRITE,
                    FILE_SHARE_READ|FILE_SHARE_WRITE,
                    NULL,
                    CREATE_ALWAYS,
                    FILE_ATTRIBUTE_NORMAL,
                    NULL);
    if (hDestFile == INVALID_HANDLE_VALUE)
    {
        wprintf(L"Can't create %s\n", argv[2]);
        return;
    }

    swprintf(szFileName, L"%s\\*.*", argv[1]);
    hFind = FindFirstFileW(szFileName, &wfd);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        wprintf(L"Can't find %s\n", szFileName);
        return;
    }

    outMaxSize   = 0;
    dwBufferSize = 0;
    dwErrorCount = 0;
    dwFileNumber = 0;
    dwMaxNumber  = 1000;
    hHeap = GetProcessHeap();
    pbFile = (PBYTE)HeapAlloc(hHeap, 0, 0);
    outBuffer = (Byte *)HeapAlloc(hHeap, 0, 0);
    pSpiArcInfo = (TSpiArchiveInfo *)HeapAlloc(hHeap,
                        HEAP_ZERO_MEMORY, dwMaxNumber * sizeof(*pSpiArcInfo));
    WriteFile(hDestFile, pSpiArcInfo, 0x10, &dwRead, NULL);

    bLZMA = argc >= 4 ? (Byte)wcstoul(argv[3], NULL, 10) : 1;
    dwMaxFileNumber = argc == 5 ? wcstoul(argv[4], NULL, 10) : -1;
    QueryPerformanceFrequency(&liFrequency);
    QueryPerformanceCounter(&liStart);

    do
    {
        if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            continue;

        swprintf(szFileName, L"%s\\%s", argv[1], wfd.cFileName);
        hFile = CreateFileW(szFileName,
                    GENERIC_READ,
                    FILE_SHARE_READ,
                    NULL,
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL,
                    NULL);
        if (hFile == INVALID_HANDLE_VALUE)
        {
            wprintf(L"Open %s failed.\n", szFileName);
            ++dwErrorCount;
            continue;
        }

        if (dwFileNumber >= dwMaxNumber)
        {
            dwMaxNumber = dwMaxNumber + (dwMaxNumber >> 1);
            pSpiArcInfo = (TSpiArchiveInfo *)HeapReAlloc(hHeap, HEAP_ZERO_MEMORY,
                pSpiArcInfo, dwMaxNumber * sizeof(*pSpiArcInfo));
        }

        dwFileSize = GetFileSize(hFile, NULL);
        if (dwFileSize > dwBufferSize)
        {
            dwBufferSize = dwFileSize;
            pbFile = (PBYTE)HeapReAlloc(hHeap, 0, pbFile, dwBufferSize);
        }

        ReadFile(hFile, pbFile, dwFileSize, &dwRead, NULL);
        CloseHandle(hFile);

        FileType = CheckFileType(pbFile);

        wprintf(L"Packing %s ... %s ", szFileName, szFileType[FileType]);
        pSpiArcInfo[dwFileNumber].position = SetFilePointer(hDestFile, 0, 0, FILE_CURRENT);
        if (dwFileSize > 300 && bLZMA && FileType != UCI && FileType != M4A && FileType != AAC)
        {
            outSize = dwFileSize / 20 * 21 + (1 << 16) + 4;
            if (outSize > outMaxSize)
            {
                outMaxSize = outSize;
                outBuffer = (Byte *)HeapReAlloc(hHeap, 0, outBuffer, outSize);
            }
            Lzma86_Encode(outBuffer, &outSize, (Byte *)pbFile, dwFileSize, 9, 1 << 27, 0);
            pSpiArcInfo[dwFileNumber].compsize = outSize;
            WriteFile(hDestFile, outBuffer, outSize, &dwRead, NULL);
            wprintf(L"@ compressed ... ");
        }
        else
        {
            if (FileType != UCI && FileType != UCA)
            {
                WriteFile(hDestFile, &dwFileSize, 4, &dwRead, NULL);
            }
            WriteFile(hDestFile, pbFile, dwFileSize, &dwRead, NULL);
            pSpiArcInfo[dwFileNumber].compsize = dwFileSize;
        }

		if (FileType != UNKNOWN)
        {
			*(LPDWORD)&pSpiArcInfo[dwFileNumber].method = dwMethod[FileType];
		}

        int w, h, b;
        CHAR *p;
        HSTREAM hStream;
        static BOOL bBassInit = FALSE;
        
        WideCharToMultiByte(936,
                    0,
                    wfd.cFileName,
                    -1,
                    pSpiArcInfo[dwFileNumber].filename,
                    sizeof(pSpiArcInfo[dwFileNumber].filename),
                    NULL, NULL);
		if (FileType == UNKNOWN)
		{
			CHAR *pExt = PathFindExtensionA(pSpiArcInfo[dwFileNumber].filename);
			if (pExt++)
			{
				lstrcpynA((LPSTR)pSpiArcInfo[dwFileNumber].method, pExt, sizeof(pSpiArcInfo->method));
			}
			else
			{
				*(LPDWORD)&pSpiArcInfo[dwFileNumber].method = 'KNU';
			}
		}
        
        p = PathFindExtensionA(pSpiArcInfo[dwFileNumber].filename);
        switch (FileType)
        {
        case UCA:
            UCADecode(pbFile, dwFileSize, NULL,(int *)&pSpiArcInfo[dwFileNumber].filesize);
            if (p)
            {
                lstrcpyA(p + 1, "wav");
            }
            printf("OK!");
            break;

        case UCI:
            UCIDecode(pbFile, dwFileSize, NULL, NULL, &w, &h, &b);
            pSpiArcInfo[dwFileNumber].filesize =
                (w * b / 8 + (b == 0x18 ? (w & 3) : 0)) * h + sizeof(TBitMapHeader);
            if (p)
            {
                lstrcpyA(p + 1, "bmp");
            }
            printf("OK!");
            break;

        case AAC:
        case M4A:
            if (bBassInit == FALSE)
            {
                bBassInit = TRUE;
                if (BASS_Init(0, 44100, 0, NULL, NULL) == FALSE)
                {
                    ++dwErrorCount;
                    printf("failed!");
                    break;
                }
            }

            hStream = FileType == AAC ? 
                BASS_AAC_StreamCreateFile(TRUE, pbFile, 0, dwFileSize, BASS_STREAM_DECODE) :
                BASS_MP4_StreamCreateFile(TRUE, pbFile, 0, dwFileSize, BASS_STREAM_DECODE);
            if (hStream)
            {
                pSpiArcInfo[dwFileNumber].filesize =
                    (DWORD)BASS_ChannelGetLength(hStream, BASS_POS_BYTE) +  + sizeof(TWaveHeader);

                BASS_StreamFree(hStream);

                if (p)
                {
                    lstrcpyA(p + 1, "wav");
                }

                printf("OK!");
            }
            else
            {
                ++dwErrorCount;
                printf("failed!");
            }
            break;

        default:
            pSpiArcInfo[dwFileNumber].filesize = dwFileSize;
            printf("OK!");
        }
        wprintf(L"\n");

        ++dwFileNumber;

    } while (dwFileNumber < dwMaxFileNumber && FindNextFileW(hFind, &wfd));
Example #10
0
BOOL
CFileDefExt::CountFolderAndFiles(HWND hwndDlg, LPWSTR pwszBuf, UINT cchBufMax, DWORD *ticks)
{
    /* Find filename position */
    UINT cchBuf = wcslen(pwszBuf);
    WCHAR *pwszFilename = pwszBuf + cchBuf;
    size_t cchFilenameMax = cchBufMax - cchBuf;
    if (!cchFilenameMax)
        return FALSE;
    *(pwszFilename++) = '\\';
    --cchFilenameMax;

    /* Find all files, FIXME: shouldn't be "*"? */
    StringCchCopyW(pwszFilename, cchFilenameMax, L"*");

    WIN32_FIND_DATAW wfd;
    HANDLE hFind = FindFirstFileW(pwszBuf, &wfd);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        ERR("FindFirstFileW %ls failed\n", pwszBuf);
        return FALSE;
    }

    BOOL root = FALSE;
    if (*ticks == 0) {
        *ticks = GetTickCount();
        root = TRUE;
    }

    do
    {
        if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            /* Don't process "." and ".." items */
            if (!wcscmp(wfd.cFileName, L".") || !wcscmp(wfd.cFileName, L".."))
                continue;

            ++m_cFolders;

            StringCchCopyW(pwszFilename, cchFilenameMax, wfd.cFileName);
            CountFolderAndFiles(hwndDlg, pwszBuf, cchBufMax, ticks);
        }
        else
        {
            m_cFiles++;

            ULARGE_INTEGER FileSize;
            FileSize.u.LowPart  = wfd.nFileSizeLow;
            FileSize.u.HighPart = wfd.nFileSizeHigh;
            m_DirSize.QuadPart += FileSize.QuadPart;
        }
        if (GetTickCount() - *ticks > (DWORD) 300)
        {
            /* FIXME Using IsWindow is generally ill advised */
            if (IsWindow(hwndDlg))
            {
                WCHAR wszBuf[MAX_PATH];

                if (SH_FormatFileSizeWithBytes(&m_DirSize, wszBuf, _countof(wszBuf)))
                    SetDlgItemTextW(hwndDlg, 14011, wszBuf);

                /* Display files and folders count */
                WCHAR wszFormat[256];
                LoadStringW(shell32_hInstance, IDS_FILE_FOLDER, wszFormat, _countof(wszFormat));
                StringCchPrintfW(wszBuf, _countof(wszBuf), wszFormat, m_cFiles, m_cFolders);
                SetDlgItemTextW(hwndDlg, 14027, wszBuf);
                *ticks = GetTickCount();
            }
            else
                break;
        }
    } while(FindNextFileW(hFind, &wfd));

    if (root && IsWindow(hwndDlg))
    {
        WCHAR wszBuf[MAX_PATH];

        if (SH_FormatFileSizeWithBytes(&m_DirSize, wszBuf, _countof(wszBuf)))
            SetDlgItemTextW(hwndDlg, 14011, wszBuf);

        /* Display files and folders count */
        WCHAR wszFormat[256];
        LoadStringW(shell32_hInstance, IDS_FILE_FOLDER, wszFormat, _countof(wszFormat));
        StringCchPrintfW(wszBuf, _countof(wszBuf), wszFormat, m_cFiles, m_cFolders);
        SetDlgItemTextW(hwndDlg, 14027, wszBuf);
    }

    FindClose(hFind);
    return TRUE;
}
Example #11
0
int hxc_find_first_file(char *folder, char *file, filefoundinfo* fileinfo)
{
#if defined (WIN32)

	HANDLE hfindfile;
	char *folderstr;
	WIN32_FIND_DATAW FindFileData;
	wchar_t	wpath[MAX_PATH+1];

	if(file)
	{
		folderstr=(char *) malloc(strlen(folder)+strlen(file)+2);
		sprintf((char *)folderstr,"%s\\%s",folder,file);
	}
	else
	{
		folderstr = (char *) malloc(strlen(folder)+1);
		sprintf((char *)folderstr,"%s",folder);
	}

	convertpath (folderstr, wpath);
	hfindfile = FindFirstFileW(wpath, &FindFileData);
	if(hfindfile!=INVALID_HANDLE_VALUE)
	{
		WideCharToMultiByte(CP_UTF8,0,FindFileData.cFileName,-1,fileinfo->filename,sizeof(fileinfo->filename),NULL,NULL);
		//sprintf(fileinfo->filename,"%s",FindFileData.cFileName);

		fileinfo->isdirectory = 0;

		if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			fileinfo->isdirectory = 1;
		}

		fileinfo->size = FindFileData.nFileSizeLow;
		free(folderstr);
		return (int)hfindfile;
	}
	else
	{
		free(folderstr);
		return -1;
	}

#else
	struct dirent *d;
	DIR * dir;
	struct stat fileStat;
	char * tmpstr;

	dir = opendir (folder);
	if(dir)
	{
		d = readdir (dir);
		if(d)
		{
			tmpstr = malloc (strlen(folder) + strlen(d->d_name) + 4 );
			if(tmpstr)
			{
				strcpy(tmpstr,folder);
				strcat(tmpstr,"/");
				strcat(tmpstr,d->d_name);

				memset(&fileStat,0,sizeof(struct stat));
				if(!lstat (tmpstr, &fileStat))
				{

					if ( S_ISDIR ( fileStat.st_mode ) )
						fileinfo->isdirectory=1;
					else
						fileinfo->isdirectory=0;

					fileinfo->size=fileStat.st_size;

					strncpy(fileinfo->filename,d->d_name,256);

					free(tmpstr);
					return (int)dir;
				}

				free(tmpstr);
			}

			closedir (dir);
			dir=(DIR *)-1;

		}

		closedir (dir);
		dir=(DIR *)-1;
	}
	else
	{
		dir=(DIR *)-1;
	}

	return (int)dir;

#endif

	return -1;
}
Example #12
0
static BOOL
AutoStartupApplications(INT nCSIDL_Folder)
{
    WCHAR szPath[MAX_PATH] = { 0 };
    HRESULT hResult;
    HANDLE hFind;
    WIN32_FIND_DATAW FoundData;
    size_t cchPathLen;

    TRACE("(%d)\n", nCSIDL_Folder);

    // Get the special folder path
    hResult = SHGetFolderPathW(NULL, nCSIDL_Folder, NULL, SHGFP_TYPE_CURRENT, szPath);
    cchPathLen = wcslen(szPath);
    if (!SUCCEEDED(hResult) || cchPathLen == 0)
    {
        WARN("SHGetFolderPath() failed with error %lu\n", GetLastError());
        return FALSE;
    }

    // Build a path with wildcard
    StringCbCatW(szPath, sizeof(szPath), L"\\*");

    // Start enumeration of files
    hFind = FindFirstFileW(szPath, &FoundData);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        WARN("FindFirstFile(%s) failed with error %lu\n", debugstr_w(szPath), GetLastError());
        return FALSE;
    }

    // Enumerate the files
    do
    {
        // Ignore "." and ".."
        if (wcscmp(FoundData.cFileName, L".") == 0 ||
            wcscmp(FoundData.cFileName, L"..") == 0)
        {
            continue;
        }

        // Don't run hidden files
        if (FoundData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
            continue;

        // Build the path
        szPath[cchPathLen + 1] = UNICODE_NULL;
        StringCbCatW(szPath, sizeof(szPath), FoundData.cFileName);

        TRACE("Executing %s in directory %s\n", debugstr_w(FoundData.cFileName), debugstr_w(szPath));

        DWORD dwType;
        if (GetBinaryTypeW(szPath, &dwType))
        {
            runCmd(szPath, NULL, TRUE, FALSE);
        }
        else
        {
            SHELLEXECUTEINFOW ExecInfo;
            ZeroMemory(&ExecInfo, sizeof(ExecInfo));
            ExecInfo.cbSize = sizeof(ExecInfo);
            ExecInfo.lpFile = szPath;
            ShellExecuteExW(&ExecInfo);
        }
    } while (FindNextFileW(hFind, &FoundData));

    FindClose(hFind);
    return TRUE;
}
Example #13
0
int fl_scandir(const char *dirname, struct dirent ***namelist,
	       int (*select)(struct dirent *),
	       int (*compar)(struct dirent **, struct dirent **)) {
  int len;
  char *findIn, *d, is_dir = 0;
  WIN32_FIND_DATAW findw;
  HANDLE h;
  int nDir = 0, NDir = 0;
  struct dirent **dir = 0, *selectDir;
  unsigned long ret;

  len    = strlen(dirname);
  findIn = (char *)malloc((size_t)(len+10));
  if (!findIn) return -1;
  strcpy(findIn, dirname);

  //#if defined(__GNUC__)
  //#warning FIXME This probably needs to be MORE UTF8 aware now
  //#endif /*__GNUC__*/
  for (d = findIn; *d; d++) if (*d=='/') *d='\\';
  if ((len==0)) { strcpy(findIn, ".\\*"); }
  if ((len==2)&&findIn[1]==':'&&isalpha(findIn[0])) { *d++ = '\\'; *d = 0; }
  if ((len==1)&& (d[-1]=='.')) { strcpy(findIn, ".\\*"); is_dir = 1; }
  if ((len>0) && (d[-1]=='\\')) { *d++ = '*'; *d = 0; is_dir = 1; }
  if ((len>1) && (d[-1]=='.') && (d[-2]=='\\')) { d[-1] = '*'; is_dir = 1; }
  if (!is_dir) { /* this file may still be a directory that we need to list */
    DWORD attr = GetFileAttributes(findIn);
    if (attr&FILE_ATTRIBUTE_DIRECTORY)
      strcpy(d, "\\*");
  }
  { /* Create a block to limit the scope while we find the initial "wide" filename */
//	unsigned short * wbuf = (unsigned short*)malloc(sizeof(short) *(len + 10));
//	wbuf[fl_utf2unicode(findIn, strlen(findIn), wbuf)] = 0;
	unsigned short *wbuf = NULL;
	unsigned wlen = fl_utf8toUtf16(findIn, strlen(findIn), NULL, 0); /* Pass NULL to query length */
	wlen++; /* add a little extra for termination etc. */
	wbuf = (unsigned short*)malloc(sizeof(unsigned short)*wlen);
	wlen = fl_utf8toUtf16(findIn, strlen(findIn), wbuf, wlen); /* actually convert the filename */
	wbuf[wlen] = 0; /* NULL terminate the resultant string */
	h = FindFirstFileW(wbuf, &findw); /* get a handle to the first filename in the search */
	free(wbuf); /* release the "wide" buffer before the pointer goes out of scope */
  }
  if (h==INVALID_HANDLE_VALUE) {
    free(findIn);
    ret = GetLastError();
    if (ret != ERROR_NO_MORE_FILES) {
      nDir = -1;
    }
    *namelist = dir;
    return nDir;
  }
  do {
	int l = wcslen(findw.cFileName);
	int dstlen = l * 5 + 1;
	selectDir=(struct dirent*)malloc(sizeof(struct dirent)+dstlen);

//	l = fl_unicode2utf(findw.cFileName, l, selectDir->d_name);
	l = fl_utf8fromwc(selectDir->d_name, dstlen, findw.cFileName, l);

	selectDir->d_name[l] = 0;
	if (findw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
		/* Append a trailing slash to directory names... */
		strcat(selectDir->d_name, "/");
	}
	if (!select || (*select)(selectDir)) {
		if (nDir==NDir) {
	struct dirent **tempDir = (struct dirent **)calloc(sizeof(struct dirent*), (size_t)(NDir+33));
	if (NDir) memcpy(tempDir, dir, sizeof(struct dirent*)*NDir);
	if (dir) free(dir);
	dir = tempDir;
	NDir += 32;
		}
		dir[nDir] = selectDir;
		nDir++;
		dir[nDir] = 0;
	} else {
		free(selectDir);
	}
   } while (FindNextFileW(h, &findw));
  ret = GetLastError();
  if (ret != ERROR_NO_MORE_FILES) {
    /* don't return an error code, because the dir list may still be valid
       up to this point */
  }
  FindClose(h);

  free (findIn);

  if (compar) qsort(dir, (size_t)nDir, sizeof(*dir),
		    (int(*)(const void*, const void*))compar);

  *namelist = dir;
  return nDir;
}
Example #14
0
RTR3DECL(int) RTPathQueryInfoEx(const char *pszPath, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs, uint32_t fFlags)
{
    /*
     * Validate input.
     */
    AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
    AssertReturn(*pszPath, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pObjInfo, VERR_INVALID_POINTER);
    AssertMsgReturn(    enmAdditionalAttribs >= RTFSOBJATTRADD_NOTHING
                    &&  enmAdditionalAttribs <= RTFSOBJATTRADD_LAST,
                    ("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs),
                    VERR_INVALID_PARAMETER);
    AssertMsgReturn(RTPATH_F_IS_VALID(fFlags, 0), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);

    /*
     * Query file info.
     */
    WIN32_FILE_ATTRIBUTE_DATA Data;
    PRTUTF16 pwszPath;
    int rc = RTStrToUtf16(pszPath, &pwszPath);
    if (RT_FAILURE(rc))
        return rc;
    if (!GetFileAttributesExW(pwszPath, GetFileExInfoStandard, &Data))
    {
        /* Fallback to FindFileFirst in case of sharing violation. */
        if (GetLastError() == ERROR_SHARING_VIOLATION)
        {
            WIN32_FIND_DATAW FindData;
            HANDLE hDir = FindFirstFileW(pwszPath, &FindData);
            if (hDir == INVALID_HANDLE_VALUE)
            {
                rc = RTErrConvertFromWin32(GetLastError());
                RTUtf16Free(pwszPath);
                return rc;
            }
            FindClose(hDir);

            Data.dwFileAttributes   = FindData.dwFileAttributes;
            Data.ftCreationTime     = FindData.ftCreationTime;
            Data.ftLastAccessTime   = FindData.ftLastAccessTime;
            Data.ftLastWriteTime    = FindData.ftLastWriteTime;
            Data.nFileSizeHigh      = FindData.nFileSizeHigh;
            Data.nFileSizeLow       = FindData.nFileSizeLow;
        }
        else
        {
            rc = RTErrConvertFromWin32(GetLastError());
            RTUtf16Free(pwszPath);
            return rc;
        }
    }

    /*
     * Getting the information for the link target is a bit annoying and
     * subject to the same access violation mess as above.. :/
     */
    /** @todo we're too lazy wrt to error paths here... */
    if (   (fFlags & RTPATH_F_FOLLOW_LINK)
        && (Data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
    {
        HANDLE hFinal = CreateFileW(pwszPath,
                                    GENERIC_READ,
                                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                    NULL,
                                    OPEN_EXISTING,
                                    FILE_FLAG_BACKUP_SEMANTICS,
                                    NULL);
        if (hFinal != INVALID_HANDLE_VALUE)
        {
            BY_HANDLE_FILE_INFORMATION FileData;
            if (GetFileInformationByHandle(hFinal, &FileData))
            {
                Data.dwFileAttributes   = FileData.dwFileAttributes;
                Data.ftCreationTime     = FileData.ftCreationTime;
                Data.ftLastAccessTime   = FileData.ftLastAccessTime;
                Data.ftLastWriteTime    = FileData.ftLastWriteTime;
                Data.nFileSizeHigh      = FileData.nFileSizeHigh;
                Data.nFileSizeLow       = FileData.nFileSizeLow;
            }
            CloseHandle(hFinal);
        }
        else if (GetLastError() != ERROR_SHARING_VIOLATION)
        {
            rc = RTErrConvertFromWin32(GetLastError());
            RTUtf16Free(pwszPath);
            return rc;
        }
    }

    RTUtf16Free(pwszPath);

    /*
     * Setup the returned data.
     */
    pObjInfo->cbObject    = ((uint64_t)Data.nFileSizeHigh << 32)
                          |  (uint64_t)Data.nFileSizeLow;
    pObjInfo->cbAllocated = pObjInfo->cbObject;

    Assert(sizeof(uint64_t) == sizeof(Data.ftCreationTime));
    RTTimeSpecSetNtTime(&pObjInfo->BirthTime,         *(uint64_t *)&Data.ftCreationTime);
    RTTimeSpecSetNtTime(&pObjInfo->AccessTime,        *(uint64_t *)&Data.ftLastAccessTime);
    RTTimeSpecSetNtTime(&pObjInfo->ModificationTime,  *(uint64_t *)&Data.ftLastWriteTime);
    pObjInfo->ChangeTime  = pObjInfo->ModificationTime;

    pObjInfo->Attr.fMode  = rtFsModeFromDos((Data.dwFileAttributes << RTFS_DOS_SHIFT) & RTFS_DOS_MASK_NT,
                                            pszPath, strlen(pszPath));

    /*
     * Requested attributes (we cannot provide anything actually).
     */
    switch (enmAdditionalAttribs)
    {
        case RTFSOBJATTRADD_NOTHING:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_NOTHING;
            break;

        case RTFSOBJATTRADD_UNIX:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_UNIX;
            pObjInfo->Attr.u.Unix.uid             = ~0U;
            pObjInfo->Attr.u.Unix.gid             = ~0U;
            pObjInfo->Attr.u.Unix.cHardlinks      = 1;
            pObjInfo->Attr.u.Unix.INodeIdDevice   = 0; /** @todo use volume serial number */
            pObjInfo->Attr.u.Unix.INodeId         = 0; /** @todo use fileid (see GetFileInformationByHandle). */
            pObjInfo->Attr.u.Unix.fFlags          = 0;
            pObjInfo->Attr.u.Unix.GenerationId    = 0;
            pObjInfo->Attr.u.Unix.Device          = 0;
            break;

        case RTFSOBJATTRADD_UNIX_OWNER:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_UNIX_OWNER;
            pObjInfo->Attr.u.UnixOwner.uid        = ~0U;
            pObjInfo->Attr.u.UnixOwner.szName[0]  = '\0'; /** @todo return something sensible here. */
            break;

        case RTFSOBJATTRADD_UNIX_GROUP:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_UNIX_GROUP;
            pObjInfo->Attr.u.UnixGroup.gid        = ~0U;
            pObjInfo->Attr.u.UnixGroup.szName[0]  = '\0';
            break;

        case RTFSOBJATTRADD_EASIZE:
            pObjInfo->Attr.enmAdditional          = RTFSOBJATTRADD_EASIZE;
            pObjInfo->Attr.u.EASize.cb            = 0;
            break;

        default:
            AssertMsgFailed(("Impossible!\n"));
            return VERR_INTERNAL_ERROR;
    }

    return VINF_SUCCESS;
}
Example #15
0
//
// Searches files by several patterns
//
VOID FilesScanExW(
	LPWSTR			path, 
	const LPWSTR*	fileMasks, 
	LONG			fileMasksCount, 
	DWORD			flags, 
	FINDFILEPROC	findFileProc, 
	PVOID			data, 
	HANDLE			stopEvent, 
	DWORD			subfolderDelay, 
	DWORD			foundedDelay
	)
{
	WCHAR curPath[MAX_PATH];
	WIN32_FIND_DATAW wfd;
	HANDLE hFind;
	BOOL fbExit = FALSE;
	int i;

	if(FilesPathCombineW(curPath, path, L"*") && (hFind = FindFirstFileW(curPath, &wfd)) != INVALID_HANDLE_VALUE)
	{
		do 
		{
			 // stop?
			if(stopEvent != NULL && WaitForSingleObject(stopEvent, 0) != WAIT_TIMEOUT){
				break;
			}

			if(!FilesIsDotsNameW(wfd.cFileName))
			{
				// check pattern
				if((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY && flags & FFFLAG_SEARCH_FOLDERS) ||
					(!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && flags & FFFLAG_SEARCH_FILES))
				{
					for( i = 0; i < fileMasksCount; i++)
					{
						if( PathMatchSpecW(wfd.cFileName, fileMasks[i]) != FALSE)
						{
							if(!findFileProc(path, &wfd, data)){
								fbExit = TRUE; // exit while loop
								break;
							}
							if(foundedDelay != 0) {
								Sleep(foundedDelay);
							}
							break;
						}
					}
				}

				// recursive scan
				if(!fbExit && ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (flags & FFFLAG_RECURSIVE)))
				{
					if(FilesPathCombineW(curPath, path, wfd.cFileName))
					{
						if(subfolderDelay != 0) {
							Sleep(subfolderDelay);
						}
						FilesScanExW(curPath, fileMasks, fileMasksCount, flags, findFileProc, data, stopEvent, subfolderDelay, foundedDelay);
					}
				}
			} // if(!FilesIsDotsNameW(wfd.cFileName))
		}while( !fbExit && (FindNextFileW(hFind, &wfd) != FALSE));

		FindClose(hFind);
	} // if(FilesPathCombineW(...
}
Example #16
0
/***********************************************************************
 *             CryptCATAdminEnumCatalogFromHash (WINTRUST.@)
 */
HCATINFO WINAPI CryptCATAdminEnumCatalogFromHash(HCATADMIN hCatAdmin, BYTE* pbHash,
                                                 DWORD cbHash, DWORD dwFlags,
                                                 HCATINFO* phPrevCatInfo )
{
    static const WCHAR slashW[] = {'\\',0};
    static const WCHAR globW[]  = {'\\','*','.','c','a','t',0};

    struct catadmin *ca = hCatAdmin;
    WIN32_FIND_DATAW data;
    HCATINFO prev = NULL;
    HCRYPTPROV prov;
    DWORD size;
    BOOL ret;

    TRACE("%p %p %d %x %p\n", hCatAdmin, pbHash, cbHash, dwFlags, phPrevCatInfo);

    if (!ca || ca->magic != CATADMIN_MAGIC || !pbHash || cbHash != 20 || dwFlags)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return NULL;
    }
    if (phPrevCatInfo) prev = *phPrevCatInfo;

    ret = CryptAcquireContextW(&prov, NULL, MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
    if (!ret) return NULL;

    if (!prev)
    {
        WCHAR *path;

        size = strlenW(ca->path) * sizeof(WCHAR) + sizeof(globW);
        if (!(path = HeapAlloc(GetProcessHeap(), 0, size)))
        {
            CryptReleaseContext(prov, 0);
            SetLastError(ERROR_OUTOFMEMORY);
            return NULL;
        }
        strcpyW(path, ca->path);
        strcatW(path, globW);

        FindClose(ca->find);
        ca->find = FindFirstFileW(path, &data);

        HeapFree(GetProcessHeap(), 0, path);
        if (ca->find == INVALID_HANDLE_VALUE)
        {
            CryptReleaseContext(prov, 0);
            return NULL;
        }
    }
    else if (!FindNextFileW(ca->find, &data))
    {
        CryptCATAdminReleaseCatalogContext(hCatAdmin, prev, 0);
        CryptReleaseContext(prov, 0);
        return NULL;
    }

    while (1)
    {
        WCHAR *filename;
        CRYPTCATMEMBER *member = NULL;
        struct catinfo *ci;
        HANDLE hcat;

        size = (strlenW(ca->path) + strlenW(data.cFileName) + 2) * sizeof(WCHAR);
        if (!(filename = HeapAlloc(GetProcessHeap(), 0, size)))
        {
            SetLastError(ERROR_OUTOFMEMORY);
            return NULL;
        }
        strcpyW(filename, ca->path);
        strcatW(filename, slashW);
        strcatW(filename, data.cFileName);

        hcat = CryptCATOpen(filename, CRYPTCAT_OPEN_EXISTING, prov, 0, 0);
        if (hcat == INVALID_HANDLE_VALUE)
        {
            WARN("couldn't open %s (%u)\n", debugstr_w(filename), GetLastError());
            continue;
        }
        while ((member = CryptCATEnumerateMember(hcat, member)))
        {
            if (member->pIndirectData->Digest.cbData != cbHash)
            {
                WARN("amount of hash bytes differs: %u/%u\n", member->pIndirectData->Digest.cbData, cbHash);
                continue;
            }
            if (!memcmp(member->pIndirectData->Digest.pbData, pbHash, cbHash))
            {
                TRACE("file %s matches\n", debugstr_w(data.cFileName));

                CryptCATClose(hcat);
                CryptReleaseContext(prov, 0);
                if (!phPrevCatInfo)
                {
                    FindClose(ca->find);
                    ca->find = INVALID_HANDLE_VALUE;
                }
                ci = create_catinfo(filename);
                HeapFree(GetProcessHeap(), 0, filename);
                return ci;
            }
        }
        CryptCATClose(hcat);
        HeapFree(GetProcessHeap(), 0, filename);

        if (!FindNextFileW(ca->find, &data))
        {
            FindClose(ca->find);
            ca->find = INVALID_HANDLE_VALUE;
            CryptReleaseContext(prov, 0);
            return NULL;
        }
    }
    return NULL;
}
Example #17
0
//
//	Copmpletely clears a specified directory removing all files (and subdirectories if ClearSubfolders flag set).
//
WINERROR FilesClearDirectoryW(
	LPWSTR	pPath,					// A full path to deirecroty to clear
	BOOL	bClearSubfolders,		// Clear subfolders recursively
	BOOL	bIgnoreErrors			// Ignore file delete errors (aka ERROR_SHARING_VIOLATION and so on)
	)
{
	WINERROR Status = ERROR_NOT_ENOUGH_MEMORY;
	PWIN32_FIND_DATAW	FindFileData = NULL;
	LPWSTR	pSearchPath = NULL, pFilePath = NULL;
	HANDLE	hFind;
	ULONG	DirPathLen, FilePathLen = MAX_PATH;					// chars

	do	// not a loop, used just to break out on error
	{
		DirPathLen	= (ULONG)lstrlenW(pPath);	// chars

		if (!(pFilePath = AppAlloc(FilePathLen * sizeof(WCHAR))))
		{
			ASSERT(Status == ERROR_NOT_ENOUGH_MEMORY);
			break;
		}

		if (!(pSearchPath = AppAlloc((DirPathLen + cstrlenW(wczFindAll) + 2) * sizeof(WCHAR))))
		{
			ASSERT(Status == ERROR_NOT_ENOUGH_MEMORY);
			break;
		}

		if (!(FindFileData = AppAlloc(sizeof(WIN32_FIND_DATAW))))
		{
			ASSERT(Status == ERROR_NOT_ENOUGH_MEMORY);
			break;
		}

		PathCombineW(pSearchPath, pPath, wczFindAll);

		hFind = FindFirstFileW(pSearchPath, FindFileData);
		if (hFind == INVALID_HANDLE_VALUE)
		{
			Status = ERROR_PATH_NOT_FOUND;
			break;
		}

		Status = NO_ERROR;

		do
		{
			ULONG NameLen;
			ULONG PathLen;

			// Skip "." and ".." names. 
			if (FindFileData->cFileName[0] == '.')
				continue;

			NameLen = lstrlenW(FindFileData->cFileName);
			PathLen = DirPathLen + NameLen + 2; // a char for "\" and one for 0

			if (FilePathLen < PathLen)
			{
				AppFree(pFilePath);
				if (!(pFilePath = AppAlloc(PathLen * sizeof(WCHAR))))
				{
					Status = ERROR_NOT_ENOUGH_MEMORY;
					break;
				}
				FilePathLen = PathLen;
			}

			PathCombineW(pFilePath, pPath, (LPWSTR)FindFileData->cFileName);

			if (FindFileData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				if (bClearSubfolders)
				{
					if ((Status = FilesClearDirectoryW(pFilePath, TRUE, bIgnoreErrors)) == NO_ERROR)
					{
						if (!RemoveDirectoryW(pFilePath) && !bIgnoreErrors)
						{
							Status = GetLastError();
							break;
						}
					}
					else
						break;
				}	// if (ClearSubfolders)
			}	// if (FindFileData->dwFileAttributes & 
			else
			{
				if (!DeleteFileW(pFilePath) && !bIgnoreErrors)
				{
					Status = GetLastError();
					break;
				}
			}

		} while(FindNextFileW(hFind, FindFileData));

	} while (FALSE);

	if (FindFileData)
		AppFree(FindFileData);

	if (pSearchPath)
		AppFree(pSearchPath);

	if (pFilePath)
		AppFree(pFilePath);

	return(Status);
}
Example #18
0
int FSSys::ReadDir( FSList* list, FSPath& _path, int* err, FSCInfo* info )
{
	list->Clear();
	FSPath path( _path );
	WIN32_FIND_DATAW ent;

	HANDLE handle = FindFirstFileW( FindPathStr( _drive, path.GetUnicode(), L"\\*" ).data(), &ent );

	if ( handle == INVALID_HANDLE_VALUE )
	{
		DWORD ret = GetLastError();

		if ( ret == ERROR_FILE_NOT_FOUND ) { return 0; }

		SetError( err, GetLastError() );
		return -1;
	}

	try
	{
		while ( true )
		{
			if ( info && info->Stopped() )
			{
				FindClose( handle );
				return -2;
			}

			//skip . and ..
			if ( !( ent.cFileName[0] == '.' && ( !ent.cFileName[1] || ( ent.cFileName[1] == '.' && !ent.cFileName[2] ) ) ) )
			{
				clPtr<FSNode> pNode = new FSNode();
				pNode->name.Set( CS_UNICODE, Utf16ToUnicode( ent.cFileName ).data() );

				pNode->st.dwFileAttributes = ent.dwFileAttributes;
				pNode->st.size = ( seek_t( ent.nFileSizeHigh ) << 32 ) + ent.nFileSizeLow;

				pNode->st.mtime = ent.ftLastWriteTime;

				if ( ent.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
				{
					pNode->st.mode = S_IFDIR;
				}
				else
				{
					pNode->st.mode = S_IFREG;
				}

				pNode->st.mode |= 0664;
				list->Append( pNode );
			}

			if ( !FindNextFileW( handle, &ent ) )
			{
				if ( GetLastError() == ERROR_NO_MORE_FILES ) { break; }

				SetError( err, GetLastError() );
				FindClose( handle );
				return -1;
			}
		};

		FindClose( handle );

		return 0;
	}
	catch ( ... )
	{
		FindClose( handle );
		throw;
	}

	SetError( err, 100 );
	return -1;
}
Example #19
0
int
efile_readdir(Efile_error* errInfo, /* Where to return error codes. */
	      char* name,           /* Name of directory to list */
	      EFILE_DIR_HANDLE* dir_handle, /* Handle of opened directory or NULL */
	      char* buffer,                 /* Buffer to put one filename in */ 
	      size_t *size)                 /* in-out size of buffer/size of filename excluding zero
					       termination in bytes*/
{
    HANDLE dir;			/* Handle to directory. */
    WCHAR wildcard[MAX_PATH];	/* Wildcard to search for. */
    WIN32_FIND_DATAW findData;	/* Data found by FindFirstFile() or FindNext(). */
    /* Alignment is not honored, this works on x86 because of alignment fixup by processor.
       Not perfect, but faster than alinging by hand (really) */
    WCHAR *wname = (WCHAR *) name;
    WCHAR *wbuffer = (WCHAR *) buffer;

    /*
     * First time we must setup everything.
     */

    if (*dir_handle == NULL) {
	int length = wcslen(wname);
	WCHAR* s;

	if (length+3 >= MAX_PATH) {
	    errno = ENAMETOOLONG;
	    return check_error(-1, errInfo);
	}

	wcscpy(wildcard, wname);
	s = wildcard+length-1;
	if (*s != L'/' && *s != L'\\')
	    *++s = L'\\';
	*++s = L'*';
	*++s = L'\0';
	DEBUGF(("Reading %ws\n", wildcard));
	dir = FindFirstFileW(wildcard, &findData);
	if (dir == INVALID_HANDLE_VALUE)
	    return set_error(errInfo);
	*dir_handle = (EFILE_DIR_HANDLE) dir;

	if (!IS_DOT_OR_DOTDOT(findData.cFileName)) {
	    wcscpy(wbuffer, findData.cFileName);
	    *size = wcslen(wbuffer)*2;
	    return 1;
	}
    }


    /*
     * Retrieve the name of the next file using the directory handle.
     */

    dir = (HANDLE) *dir_handle;

    for (;;) {
	if (FindNextFileW(dir, &findData)) {
	    if (IS_DOT_OR_DOTDOT(findData.cFileName))
		continue;
	    wcscpy(wbuffer, findData.cFileName);
	    *size = wcslen(wbuffer)*2;
	    return 1;
	}

	if (GetLastError() == ERROR_NO_MORE_FILES) {
	    FindClose(dir);
	    errInfo->posix_errno = errInfo->os_errno = 0;
	    return 0;
	}

	set_error(errInfo);
	FindClose(dir);
	return 0;
    }
}
Example #20
0
File: escript.c Project: HansN/otp
static char *
find_prog(char *origpath)
{
    wchar_t relpath[PMAX];
    wchar_t abspath[PMAX];

    if (strlen(origpath) >= PMAX)
        error("Path too long");

    MultiByteToWideChar(CP_UTF8, 0, origpath, -1, relpath, PMAX);

    if (wcsstr(relpath, LDIRSEPSTR) == NULL) {
        /* Just a base name */
	int sz;
        wchar_t *envpath;
	sz = GetEnvironmentVariableW(L"PATH", NULL, 0);
        if (sz) {	    
            /* Try to find the executable in the path */
            wchar_t dir[PMAX];
            wchar_t *beg;
            wchar_t *end;

	    HANDLE dir_handle;	        /* Handle to directory. */
	    wchar_t wildcard[PMAX];	/* Wildcard to search for. */
	    WIN32_FIND_DATAW find_data;	/* Data found by FindFirstFile() or FindNext(). */

            BOOL look_for_sep = TRUE;

	    envpath = (wchar_t *) emalloc(sz * sizeof(wchar_t*));
	    GetEnvironmentVariableW(L"PATH", envpath, sz);
	    beg = envpath;

            while (look_for_sep) {
                end = wcsstr(beg, LPATHSEPSTR);
                if (end != NULL) {
                    sz = end - beg;
                } else {
                    sz = wcslen(beg);
                    look_for_sep = FALSE;
                }
                if (sz >= PMAX) {
                    beg = end + 1;
                    continue;
                }
                wcsncpy(dir, beg, sz);
                dir[sz] = L'\0';
                beg = end + 1;

		swprintf(wildcard, PMAX, L"%s" LDIRSEPSTR L"%s",
			      dir, relpath /* basename */);
		dir_handle = FindFirstFileW(wildcard, &find_data);
		if (dir_handle == INVALID_HANDLE_VALUE) {
		    /* Try next directory in path */
		    continue;
		} else {
		    /* Wow we found the executable. */
		    wcscpy(relpath, wildcard);
		    FindClose(dir_handle);
		    look_for_sep = FALSE;
		    break;
		}
            }
	    efree(envpath);
        }
    }
    
    {
	DWORD size;
	wchar_t *absrest;
	size = GetFullPathNameW(relpath, PMAX, abspath, &absrest);
	if ((size == 0) || (size > PMAX)) {
	    /* Cannot determine absolute path to escript. Try the origin.  */
	    return strsave(origpath);
	} else {
	    char utf8abs[PMAX];
	    WideCharToMultiByte(CP_UTF8, 0, abspath, -1, utf8abs, PMAX, NULL, NULL);
	    return strsave(utf8abs);
	}
    }
}
/**
*           bIndex == 1     遍历指定文件夹并解压缩
*           数据升级Config因为包括黑白名单缓存,需特殊处理
*/
void CDownloadOperation::uncompressTraverse(IN LPWSTR path ,IN BYTE bIndex, IN OUT LPWSTR parentDirectory )
{
	USES_CONVERSION;
	WIN32_FIND_DATAW  fw;
	HANDLE hFind= FindFirstFileW(path,&fw);

	if(hFind == INVALID_HANDLE_VALUE)
		return ;

	WBRETURN bIsWBCab = NONE;

	do
	{
		if(wcscmp(fw.cFileName,L".") == 0 || wcscmp(fw.cFileName,L"..") == 0 || wcscmp(fw.cFileName,L".svn") == 0)
			continue;

		if(fw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if(bIndex == 1)
			{	

			}
		}
		else
		{
			if(bIndex == 1 && strstr(W2A(fw.cFileName),"cab") != NULL)
			{
				std::wstring newFile ;
				bool bIsSC = isSpecialCab(fw.cFileName);

				newFile = this->getAppDataPath();

				if( !bIsSC )
					newFile += BANKINFOPATHNOFIND;

				WBRETURN bWBCab = IsNewTBCacheFile(fw.cFileName);
				if( bWBCab != NONE)
					if( bWBCab != bIsWBCab && bIsWBCab != ALL )
					{
						if( bIsWBCab == NONE)
							bIsWBCab = bWBCab;
						else
							bIsWBCab = ALL;
					}
				

				std::wstring existingFile ;
				existingFile = getBankCachePath();
				existingFile += fw.cFileName;

				//没有通过验证的升级包不允许升级
				if( _UpdateMgr.isSafeFile((wchar_t *)existingFile.c_str() ) )
				{				
					moveFiles(fw.cFileName, true);	

					CCabExtract tt;
					if(tt.ExtractFile(existingFile.c_str(), newFile.c_str() ) )
						OutputDebugStringW(L"extractFile is OK!");
					else
					{
						moveFiles(fw.cFileName, false);
					}
				}
			}
		}
	}
	while( FindNextFile(hFind,&fw) );  

	this->UpdateWBFile(bIsWBCab);
	FindClose(hFind);
}
Example #22
0
static void create_snapshot(HWND hwnd, WCHAR* fn) {
    HANDLE h;
    NTSTATUS Status;
    IO_STATUS_BLOCK iosb;
    btrfs_get_file_ids bgfi;
    
    h = CreateFileW(fn, FILE_TRAVERSE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    
    if (h != INVALID_HANDLE_VALUE) {
        Status = NtFsControlFile(h, NULL, NULL, NULL, &iosb, FSCTL_BTRFS_GET_FILE_IDS, NULL, 0, &bgfi, sizeof(btrfs_get_file_ids));
            
        if (Status == STATUS_SUCCESS && bgfi.inode == 0x100 && !bgfi.top) {
            WCHAR parpath[MAX_PATH], subvolname[MAX_PATH], templ[MAX_PATH], name[MAX_PATH], searchpath[MAX_PATH];
            HANDLE h2, fff;
            btrfs_create_snapshot* bcs;
            ULONG namelen, pathend;
            WIN32_FIND_DATAW wfd;
            SYSTEMTIME time;
            
            StringCchCopyW(parpath, sizeof(parpath) / sizeof(WCHAR), fn);
            PathRemoveFileSpecW(parpath);
            
            StringCchCopyW(subvolname, sizeof(subvolname) / sizeof(WCHAR), fn);
            PathStripPathW(subvolname);
            
            h2 = CreateFileW(parpath, FILE_ADD_SUBDIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

            if (h2 == INVALID_HANDLE_VALUE) {
                ShowError(hwnd, GetLastError());
                CloseHandle(h);
                return;
            }
            
            if (!LoadStringW(module, IDS_SNAPSHOT_FILENAME, templ, MAX_PATH)) {
                ShowError(hwnd, GetLastError());
                CloseHandle(h);
                CloseHandle(h2);
                return;
            }
            
            GetLocalTime(&time);
            
            if (StringCchPrintfW(name, sizeof(name) / sizeof(WCHAR), templ, subvolname, time.wYear, time.wMonth, time.wDay) == STRSAFE_E_INSUFFICIENT_BUFFER) {
                MessageBoxW(hwnd, L"Filename too long.\n", L"Error", MB_ICONERROR);
                CloseHandle(h);
                CloseHandle(h2);
                return;
            }
            
            StringCchCopyW(searchpath, sizeof(searchpath) / sizeof(WCHAR), parpath);
            StringCchCatW(searchpath, sizeof(searchpath) / sizeof(WCHAR), L"\\");
            pathend = wcslen(searchpath);
            
            StringCchCatW(searchpath, sizeof(searchpath) / sizeof(WCHAR), name);
            
            fff = FindFirstFileW(searchpath, &wfd);
            
            if (fff != INVALID_HANDLE_VALUE) {
                ULONG i = wcslen(searchpath), num = 2;
                
                do {
                    FindClose(fff);
                    
                    searchpath[i] = 0;
                    if (StringCchPrintfW(searchpath, sizeof(searchpath) / sizeof(WCHAR), L"%s (%u)", searchpath, num) == STRSAFE_E_INSUFFICIENT_BUFFER) {
                        MessageBoxW(hwnd, L"Filename too long.\n", L"Error", MB_ICONERROR);
                        CloseHandle(h);
                        CloseHandle(h2);
                        return;
                    }

                    fff = FindFirstFileW(searchpath, &wfd);
                    num++;
                } while (fff != INVALID_HANDLE_VALUE);
            }
            
            namelen = wcslen(&searchpath[pathend]) * sizeof(WCHAR);
                        
            bcs = (btrfs_create_snapshot*)malloc(sizeof(btrfs_create_snapshot) - 1 + namelen);
            bcs->subvol = h;
            bcs->namelen = namelen;
            memcpy(bcs->name, &searchpath[pathend], namelen);
            
            Status = NtFsControlFile(h2, NULL, NULL, NULL, &iosb, FSCTL_BTRFS_CREATE_SNAPSHOT, NULL, 0, bcs, sizeof(btrfs_create_snapshot) - 1 + namelen);
        
            if (Status != STATUS_SUCCESS)
                ShowNtStatusError(hwnd, Status);
            
            CloseHandle(h2);
        }
        
        CloseHandle(h);
    } else
        ShowError(hwnd, GetLastError());
}
Example #23
0
static int Sys_EnumerateFiles2 (const char *match, int matchstart, int neststart, int (QDECL *func)(const char *fname, qofs_t fsize, time_t mtime, void *parm, searchpathfuncs_t *spath), void *parm, searchpathfuncs_t *spath)
{
	qboolean go;
	if (!WinNT)
	{
		HANDLE r;
		WIN32_FIND_DATAA fd;
		int nest = neststart;	//neststart refers to just after a /
		qboolean wild = false;

		while(match[nest] && match[nest] != '/')
		{
			if (match[nest] == '?' || match[nest] == '*')
				wild = true;
			nest++;
		}
		if (match[nest] == '/')
		{
			char submatch[MAX_OSPATH];
			char tmproot[MAX_OSPATH];
			char file[MAX_OSPATH];

			if (!wild)
				return Sys_EnumerateFiles2(match, matchstart, nest+1, func, parm, spath);

			if (nest-neststart+1> MAX_OSPATH)
				return 1;
			memcpy(submatch, match+neststart, nest - neststart);
			submatch[nest - neststart] = 0;
			nest++;

			if (neststart+4 > MAX_OSPATH)
				return 1;
			memcpy(tmproot, match, neststart);
			strcpy(tmproot+neststart, "*.*");

			r = FindFirstFile(tmproot, &fd);
			strcpy(tmproot+neststart, "");
			if (r==(HANDLE)-1)
				return 1;
			go = true;
			do
			{
				if (*fd.cFileName == '.');	//don't ever find files with a name starting with '.'
				else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)	//is a directory
				{
					if (wildcmp(submatch, fd.cFileName))
					{
						int newnest;
						if (strlen(tmproot) + strlen(fd.cFileName) + strlen(match+nest) + 2 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s/", tmproot, fd.cFileName);
							newnest = strlen(file);
							strcpy(file+newnest, match+nest);
							go = Sys_EnumerateFiles2(file, matchstart, newnest, func, parm, spath);
						}
					}
				}
			} while(FindNextFile(r, &fd) && go);
			FindClose(r);
		}
		else
		{
			const char *submatch = match + neststart;
			char tmproot[MAX_OSPATH];
			char file[MAX_OSPATH];

			if (neststart+4 > MAX_OSPATH)
				return 1;
			memcpy(tmproot, match, neststart);
			strcpy(tmproot+neststart, "*.*");

			r = FindFirstFile(tmproot, &fd);
			strcpy(tmproot+neststart, "");
			if (r==(HANDLE)-1)
				return 1;
			go = true;
			do
			{
				if (*fd.cFileName == '.')
					;	//don't ever find files with a name starting with '.' (includes .. and . directories, and unix hidden files)
				else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)	//is a directory
				{
					if (wildcmp(submatch, fd.cFileName))
					{
						if (strlen(tmproot+matchstart) + strlen(fd.cFileName) + 2 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s/", tmproot+matchstart, fd.cFileName);
							go = func(file, qofs_Make(fd.nFileSizeLow, fd.nFileSizeHigh), Sys_FileTimeToTime(fd.ftLastWriteTime), parm, spath);
						}
					}
				}
				else
				{
					if (wildcmp(submatch, fd.cFileName))
					{
						if (strlen(tmproot+matchstart) + strlen(fd.cFileName) + 1 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s", tmproot+matchstart, fd.cFileName);
							go = func(file, qofs_Make(fd.nFileSizeLow, fd.nFileSizeHigh), Sys_FileTimeToTime(fd.ftLastWriteTime), parm, spath);
						}
					}
				}
			} while(FindNextFile(r, &fd) && go);
			FindClose(r);
		}
	}
	else
	{
		HANDLE r;
		WIN32_FIND_DATAW fd;
		int nest = neststart;	//neststart refers to just after a /
		qboolean wild = false;

		while(match[nest] && match[nest] != '/')
		{
			if (match[nest] == '?' || match[nest] == '*')
				wild = true;
			nest++;
		}
		if (match[nest] == '/')
		{
			char submatch[MAX_OSPATH];
			char tmproot[MAX_OSPATH];

			if (!wild)
				return Sys_EnumerateFiles2(match, matchstart, nest+1, func, parm, spath);

			if (nest-neststart+1> MAX_OSPATH)
				return 1;
			memcpy(submatch, match+neststart, nest - neststart);
			submatch[nest - neststart] = 0;
			nest++;

			if (neststart+4 > MAX_OSPATH)
				return 1;
			memcpy(tmproot, match, neststart);
			strcpy(tmproot+neststart, "*.*");

			{
				wchar_t wroot[MAX_OSPATH];
				r = FindFirstFileW(widen(wroot, sizeof(wroot), tmproot), &fd);
			}
			strcpy(tmproot+neststart, "");
			if (r==(HANDLE)-1)
				return 1;
			go = true;
			do
			{
				char utf8[MAX_OSPATH];
				char file[MAX_OSPATH];
				narrowen(utf8, sizeof(utf8), fd.cFileName);
				if (*utf8 == '.');	//don't ever find files with a name starting with '.'
				else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)	//is a directory
				{
					if (wildcmp(submatch, utf8))
					{
						int newnest;
						if (strlen(tmproot) + strlen(utf8) + strlen(match+nest) + 2 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s/", tmproot, utf8);
							newnest = strlen(file);
							strcpy(file+newnest, match+nest);
							go = Sys_EnumerateFiles2(file, matchstart, newnest, func, parm, spath);
						}
					}
				}
			} while(FindNextFileW(r, &fd) && go);
			FindClose(r);
		}
		else
		{
			const char *submatch = match + neststart;
			char tmproot[MAX_OSPATH];

			if (neststart+4 > MAX_OSPATH)
				return 1;
			memcpy(tmproot, match, neststart);
			strcpy(tmproot+neststart, "*.*");

			{
				wchar_t wroot[MAX_OSPATH];
				r = FindFirstFileW(widen(wroot, sizeof(wroot), tmproot), &fd);
			}
			strcpy(tmproot+neststart, "");
			if (r==(HANDLE)-1)
				return 1;
			go = true;
			do
			{
				char utf8[MAX_OSPATH];
				char file[MAX_OSPATH];

				narrowen(utf8, sizeof(utf8), fd.cFileName);
				if (*utf8 == '.')
					;	//don't ever find files with a name starting with '.' (includes .. and . directories, and unix hidden files)
				else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)	//is a directory
				{
					if (wildcmp(submatch, utf8))
					{
						if (strlen(tmproot+matchstart) + strlen(utf8) + 2 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s/", tmproot+matchstart, utf8);
							go = func(file, qofs_Make(fd.nFileSizeLow, fd.nFileSizeHigh), Sys_FileTimeToTime(fd.ftLastWriteTime), parm, spath);
						}
					}
				}
				else
				{
					if (wildcmp(submatch, utf8))
					{
						if (strlen(tmproot+matchstart) + strlen(utf8) + 1 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s", tmproot+matchstart, utf8);
							go = func(file, qofs_Make(fd.nFileSizeLow, fd.nFileSizeHigh), Sys_FileTimeToTime(fd.ftLastWriteTime), parm, spath);
						}
					}
				}
			} while(FindNextFileW(r, &fd) && go);
			FindClose(r);
		}
	}
	return go;
}
Example #24
0
HRESULT __stdcall BtrfsContextMenu::InvokeCommand(LPCMINVOKECOMMANDINFO pici) {
    if (ignore)
        return E_INVALIDARG;
    
    if (!bg) {
        if ((IS_INTRESOURCE(pici->lpVerb) && pici->lpVerb == 0) || !strcmp(pici->lpVerb, SNAPSHOT_VERBA)) {
            UINT num_files, i;
            WCHAR fn[MAX_PATH];
            
            if (!stgm_set)
                return E_FAIL;
            
            num_files = DragQueryFileW((HDROP)stgm.hGlobal, 0xFFFFFFFF, NULL, 0);
            
            if (num_files == 0)
                return E_FAIL;
            
            for (i = 0; i < num_files; i++) {
                if (DragQueryFileW((HDROP)stgm.hGlobal, i, fn, sizeof(fn) / sizeof(MAX_PATH))) {
                    create_snapshot(pici->hwnd, fn);
                }
            }

            return S_OK;
        }
        
        return E_FAIL;
    }
    
    if ((IS_INTRESOURCE(pici->lpVerb) && pici->lpVerb == 0) || !strcmp(pici->lpVerb, NEW_SUBVOL_VERBA)) {
        HANDLE h;
        IO_STATUS_BLOCK iosb;
        NTSTATUS Status;
        ULONG pathlen, searchpathlen, pathend;
        WCHAR name[MAX_PATH], *searchpath;
        HANDLE fff;
        WIN32_FIND_DATAW wfd;
        
        if (!LoadStringW(module, IDS_NEW_SUBVOL_FILENAME, name, MAX_PATH)) {
            ShowError(pici->hwnd, GetLastError());
            return E_FAIL;
        }
        
        h = CreateFileW(path, FILE_ADD_SUBDIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    
        if (h == INVALID_HANDLE_VALUE) {
            ShowError(pici->hwnd, GetLastError());
            return E_FAIL;
        }
        
        pathlen = wcslen(path);
        
        searchpathlen = pathlen + wcslen(name) + 10;
        searchpath = (WCHAR*)malloc(searchpathlen * sizeof(WCHAR));
        
        StringCchCopyW(searchpath, searchpathlen, path);
        StringCchCatW(searchpath, searchpathlen, L"\\");
        pathend = wcslen(searchpath);
        
        StringCchCatW(searchpath, searchpathlen, name);
        
        fff = FindFirstFileW(searchpath, &wfd);
        
        if (fff != INVALID_HANDLE_VALUE) {
            ULONG i = wcslen(searchpath), num = 2;
            
            do {
                FindClose(fff);
                
                searchpath[i] = 0;
                if (StringCchPrintfW(searchpath, searchpathlen, L"%s (%u)", searchpath, num) == STRSAFE_E_INSUFFICIENT_BUFFER) {
                    MessageBoxW(pici->hwnd, L"Filename too long.\n", L"Error", MB_ICONERROR);
                    CloseHandle(h);
                    return E_FAIL;
                }

                fff = FindFirstFileW(searchpath, &wfd);
                num++;
            } while (fff != INVALID_HANDLE_VALUE);
        }
        
        Status = NtFsControlFile(h, NULL, NULL, NULL, &iosb, FSCTL_BTRFS_CREATE_SUBVOL, NULL, 0, &searchpath[pathend], wcslen(&searchpath[pathend]) * sizeof(WCHAR));
        
        free(searchpath);
        
        if (Status != STATUS_SUCCESS) {
            CloseHandle(h);
            ShowNtStatusError(pici->hwnd, Status);
            return E_FAIL;
        }
        
        CloseHandle(h);
        
        return S_OK;
    }
    
    return E_FAIL;
}
Example #25
0
/**
\brief Loads plugins from a specified directory.
\param pluginDir The directory to load plugins from.
*/
void pluginload(const char* pluginDir)
{
    //load new plugins
    wchar_t currentDir[deflen] = L"";
    GetCurrentDirectoryW(deflen, currentDir);
    SetCurrentDirectoryW(StringUtils::Utf8ToUtf16(pluginDir).c_str());
    char searchName[deflen] = "";
#ifdef _WIN64
    sprintf(searchName, "%s\\*.dp64", pluginDir);
#else
    sprintf(searchName, "%s\\*.dp32", pluginDir);
#endif // _WIN64
    WIN32_FIND_DATAW foundData;
    HANDLE hSearch = FindFirstFileW(StringUtils::Utf8ToUtf16(searchName).c_str(), &foundData);
    if(hSearch == INVALID_HANDLE_VALUE)
    {
        SetCurrentDirectoryW(currentDir);
        return;
    }
    PLUG_DATA pluginData;
    do
    {
        //set plugin data
        pluginData.initStruct.pluginHandle = curPluginHandle;
        char szPluginPath[MAX_PATH] = "";
        sprintf_s(szPluginPath, "%s\\%s", pluginDir, StringUtils::Utf16ToUtf8(foundData.cFileName).c_str());
        pluginData.hPlugin = LoadLibraryW(StringUtils::Utf8ToUtf16(szPluginPath).c_str()); //load the plugin library
        if(!pluginData.hPlugin)
        {
            dprintf("[PLUGIN] Failed to load plugin: %s\n", StringUtils::Utf16ToUtf8(foundData.cFileName).c_str());
            continue;
        }
        pluginData.pluginit = (PLUGINIT)GetProcAddress(pluginData.hPlugin, "pluginit");
        if(!pluginData.pluginit)
        {
            dprintf("[PLUGIN] Export \"pluginit\" not found in plugin: %s\n", StringUtils::Utf16ToUtf8(foundData.cFileName).c_str());
            FreeLibrary(pluginData.hPlugin);
            continue;
        }
        pluginData.plugstop = (PLUGSTOP)GetProcAddress(pluginData.hPlugin, "plugstop");
        pluginData.plugsetup = (PLUGSETUP)GetProcAddress(pluginData.hPlugin, "plugsetup");
        //auto-register callbacks for certain export names
        CBPLUGIN cbPlugin;
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBALLEVENTS");
        if(cbPlugin)
        {
            pluginregistercallback(curPluginHandle, CB_INITDEBUG, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_STOPDEBUG, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_CREATEPROCESS, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_EXITPROCESS, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_CREATETHREAD, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_EXITTHREAD, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_SYSTEMBREAKPOINT, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_LOADDLL, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_UNLOADDLL, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_OUTPUTDEBUGSTRING, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_EXCEPTION, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_BREAKPOINT, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_PAUSEDEBUG, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_RESUMEDEBUG, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_STEPPED, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_ATTACH, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_DETACH, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_DEBUGEVENT, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_MENUENTRY, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_WINEVENT, cbPlugin);
            pluginregistercallback(curPluginHandle, CB_WINEVENTGLOBAL, cbPlugin);
        }
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBINITDEBUG");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_INITDEBUG, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBSTOPDEBUG");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_STOPDEBUG, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBCREATEPROCESS");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_CREATEPROCESS, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBEXITPROCESS");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_EXITPROCESS, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBCREATETHREAD");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_CREATETHREAD, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBEXITTHREAD");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_EXITTHREAD, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBSYSTEMBREAKPOINT");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_SYSTEMBREAKPOINT, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBLOADDLL");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_LOADDLL, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBUNLOADDLL");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_UNLOADDLL, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBOUTPUTDEBUGSTRING");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_OUTPUTDEBUGSTRING, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBEXCEPTION");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_EXCEPTION, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBBREAKPOINT");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_BREAKPOINT, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBPAUSEDEBUG");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_PAUSEDEBUG, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBRESUMEDEBUG");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_RESUMEDEBUG, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBSTEPPED");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_STEPPED, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBATTACH");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_ATTACH, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBDETACH");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_DETACH, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBDEBUGEVENT");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_DEBUGEVENT, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBMENUENTRY");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_MENUENTRY, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBWINEVENT");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_WINEVENT, cbPlugin);
        cbPlugin = (CBPLUGIN)GetProcAddress(pluginData.hPlugin, "CBWINEVENTGLOBAL");
        if(cbPlugin)
            pluginregistercallback(curPluginHandle, CB_WINEVENTGLOBAL, cbPlugin);
        //init plugin
        //TODO: handle exceptions
        if(!pluginData.pluginit(&pluginData.initStruct))
        {
            dprintf("[PLUGIN] pluginit failed for plugin: %s\n", foundData.cFileName);
            FreeLibrary(pluginData.hPlugin);
            continue;
        }
        else if(pluginData.initStruct.sdkVersion < PLUG_SDKVERSION) //the plugin SDK is not compatible
        {
            dprintf("[PLUGIN] %s is incompatible with this SDK version\n", pluginData.initStruct.pluginName);
            FreeLibrary(pluginData.hPlugin);
            continue;
        }
        else
            dprintf("[PLUGIN] %s v%d Loaded!\n", pluginData.initStruct.pluginName, pluginData.initStruct.pluginVersion);
        //add plugin menu
        int hNewMenu = GuiMenuAdd(GUI_PLUGIN_MENU, pluginData.initStruct.pluginName);
        if(hNewMenu == -1)
        {
            dprintf("[PLUGIN] GuiMenuAdd(GUI_PLUGIN_MENU) failed for plugin: %s\n", pluginData.initStruct.pluginName);
            pluginData.hMenu = -1;
        }
        else
        {
            PLUG_MENU newMenu;
            newMenu.hEntryMenu = hNewMenu;
            newMenu.hEntryPlugin = -1;
            newMenu.pluginHandle = pluginData.initStruct.pluginHandle;
            pluginMenuList.push_back(newMenu);
            pluginData.hMenu = newMenu.hEntryMenu;
        }
        //add disasm plugin menu
        hNewMenu = GuiMenuAdd(GUI_DISASM_MENU, pluginData.initStruct.pluginName);
        if(hNewMenu == -1)
        {
            dprintf("[PLUGIN] GuiMenuAdd(GUI_DISASM_MENU) failed for plugin: %s\n", pluginData.initStruct.pluginName);
            pluginData.hMenu = -1;
        }
        else
        {
            PLUG_MENU newMenu;
            newMenu.hEntryMenu = hNewMenu;
            newMenu.hEntryPlugin = -1;
            newMenu.pluginHandle = pluginData.initStruct.pluginHandle;
            pluginMenuList.push_back(newMenu);
            pluginData.hMenuDisasm = newMenu.hEntryMenu;
        }
        //add dump plugin menu
        hNewMenu = GuiMenuAdd(GUI_DUMP_MENU, pluginData.initStruct.pluginName);
        if(hNewMenu == -1)
        {
            dprintf("[PLUGIN] GuiMenuAdd(GUI_DUMP_MENU) failed for plugin: %s\n", pluginData.initStruct.pluginName);
            pluginData.hMenu = -1;
        }
        else
        {
            PLUG_MENU newMenu;
            newMenu.hEntryMenu = hNewMenu;
            newMenu.hEntryPlugin = -1;
            newMenu.pluginHandle = pluginData.initStruct.pluginHandle;
            pluginMenuList.push_back(newMenu);
            pluginData.hMenuDump = newMenu.hEntryMenu;
        }
        //add stack plugin menu
        hNewMenu = GuiMenuAdd(GUI_STACK_MENU, pluginData.initStruct.pluginName);
        if(hNewMenu == -1)
        {
            dprintf("[PLUGIN] GuiMenuAdd(GUI_STACK_MENU) failed for plugin: %s\n", pluginData.initStruct.pluginName);
            pluginData.hMenu = -1;
        }
        else
        {
            PLUG_MENU newMenu;
            newMenu.hEntryMenu = hNewMenu;
            newMenu.hEntryPlugin = -1;
            newMenu.pluginHandle = pluginData.initStruct.pluginHandle;
            pluginMenuList.push_back(newMenu);
            pluginData.hMenuStack = newMenu.hEntryMenu;
        }
        pluginList.push_back(pluginData);
        //setup plugin
        if(pluginData.plugsetup)
        {
            PLUG_SETUPSTRUCT setupStruct;
            setupStruct.hwndDlg = GuiGetWindowHandle();
            setupStruct.hMenu = pluginData.hMenu;
            setupStruct.hMenuDisasm = pluginData.hMenuDisasm;
            setupStruct.hMenuDump = pluginData.hMenuDump;
            setupStruct.hMenuStack = pluginData.hMenuStack;
            pluginData.plugsetup(&setupStruct);
        }
        curPluginHandle++;
    }
    while(FindNextFileW(hSearch, &foundData));
    SetCurrentDirectoryW(currentDir);
}
Example #26
0
BOOL EnumFileList(LPCWSTR directory, LPCWSTR filter, std::vector<std::wstring> &file_list, BOOL include_dir, BOOL dir_front, ENUM_FILE_PROC proc, PVOID context)
{
    HANDLE find_handle;
    WIN32_FIND_DATAW data;
    std::wstring current_dir;
    std::wstring path;
    std::wstring temp_path;
    BOOL is_skip;
    BOOL is_stop;

    current_dir = directory;

    if (current_dir[current_dir.length() - 1] != L'\\') {
        current_dir += L"\\";
    }

    path = current_dir;
    current_dir += filter;

    find_handle = FindFirstFileW(current_dir.c_str(), &data);
    if (find_handle == INVALID_HANDLE_VALUE) {
        return TRUE;
    }

    AutoFindHandle auto_find_handle(find_handle);

    if (wcscmp(data.cFileName, L"..") != 0 && 
        wcscmp(data.cFileName, L".") != 0) {

            temp_path = path;
            temp_path += data.cFileName;

            if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {

                is_skip = FALSE;
                if (proc != NULL) {
                    is_stop = !proc(temp_path.c_str(), &is_skip, context);
                }

                if (!is_skip) {
                    file_list.push_back(temp_path);
                }

                if (is_stop) {
                    return FALSE;
                }

            }
            else {

                if (include_dir) {
                    if (dir_front) {
                        is_skip = FALSE;
                        is_stop = FALSE;
                        if (proc != NULL) {
                            is_stop = !proc(temp_path.c_str(), &is_skip, context);
                        }

                        if (!is_skip) {
                            file_list.push_back(temp_path);
                        }

                        if (is_stop) {
                            return FALSE;
                        }
                    }
                }

                if (!EnumFileList(temp_path.c_str(), filter, file_list, include_dir, dir_front, proc, context)) {
                    return FALSE;
                }

                if (include_dir) {
                    if (!dir_front) {
                        is_skip = FALSE;
                        is_stop = FALSE;
                        if (proc != NULL) {
                            is_stop = !proc(temp_path.c_str(), &is_skip, context);
                        }

                        if (!is_skip) {
                            file_list.push_back(temp_path);
                        }

                        if (is_stop) {
                            return FALSE;
                        }
                    }
                }

            }
    }

    while (FindNextFileW(find_handle, &data)) {

        if (wcscmp(data.cFileName, L"..") != 0 && 
            wcscmp(data.cFileName, L".") != 0 ){

                temp_path = path;
                temp_path += data.cFileName;

                if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {

                    is_skip = FALSE;
                    is_stop = FALSE;
                    if (proc != NULL) {
                        is_stop = !proc(temp_path.c_str(), &is_skip, context);
                    }

                    if (!is_skip) {
                        file_list.push_back(temp_path);
                    }

                    if (is_stop) {
                        return FALSE;
                    }
                }
                else {

                    if (include_dir) {
                        if (dir_front) {
                            is_skip = FALSE;
                            is_stop = FALSE;
                            if (proc != NULL) {
                                is_stop = !proc(temp_path.c_str(), &is_skip, context);
                            }

                            if (!is_skip) {
                                file_list.push_back(temp_path);
                            }

                            if (is_stop) {
                                return FALSE;
                            }
                        }
                    }

                    if (!EnumFileList(temp_path.c_str(), filter, file_list, include_dir, dir_front, proc, context)) {
                        return FALSE;
                    }

                    if (include_dir) {
                        if (!dir_front) {
                            is_skip = FALSE;
                            is_stop = FALSE;
                            if (proc != NULL) {
                                is_stop = !proc(temp_path.c_str(), &is_skip, context);
                            }

                            if (!is_skip) {
                                file_list.push_back(temp_path);
                            }

                            if (is_stop) {
                                return FALSE;
                            }
                        }
                    }
                }
        }
    }
    return TRUE;
}
Example #27
0
void __PHYSFS_platformEnumerateFiles(const char *dirname,
                                     int omitSymLinks,
                                     PHYSFS_EnumFilesCallback callback,
                                     const char *origdir,
                                     void *callbackdata)
{
    HANDLE dir = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATAW entw;
    size_t len = strlen(dirname);
    char *searchPath = NULL;
    WCHAR *wSearchPath = NULL;

    /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
    searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
    if (searchPath == NULL)
        return;

    /* Copy current dirname */
    strcpy(searchPath, dirname);

    /* if there's no '\\' at the end of the path, stick one in there. */
    if (searchPath[len - 1] != '\\')
    {
        searchPath[len++] = '\\';
        searchPath[len] = '\0';
    } /* if */

    /* Append the "*" to the end of the string */
    strcat(searchPath, "*");

    UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
    if (!wSearchPath)
        return;  /* oh well. */

    dir = FindFirstFileW(wSearchPath, &entw);

    __PHYSFS_smallFree(wSearchPath);
    __PHYSFS_smallFree(searchPath);
    if (dir == INVALID_HANDLE_VALUE)
        return;

    do
    {
        const DWORD attr = entw.dwFileAttributes;
        const DWORD tag = entw.dwReserved0;
        const WCHAR *fn = entw.cFileName;
        char *utf8;

        if ((fn[0] == '.') && (fn[1] == '\0'))
            continue;
        if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
            continue;
        if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
            continue;

        utf8 = unicodeToUtf8Heap(fn);
        if (utf8 != NULL)
        {
            callback(callbackdata, origdir, utf8);
            allocator.Free(utf8);
        } /* if */
    } while (FindNextFileW(dir, &entw) != 0);

    FindClose(dir);
} /* __PHYSFS_platformEnumerateFiles */
Example #28
0
//
//	Searches for files according to the specified Mask starting from the specified Path. 
//	For every file found allocates FILE_DESCW structure and links all theese structures into the FileListHead.
//	Returns number of files found.
//	Note: In the ANSI version of FindFirstFile the name is limited to MAX_PATH characters. So we have to use UNICODE version 
//		to completely scan all files.
//
ULONG	FilesScanW(
	PWCHAR				Path,			// directory to search in, should be ended with "\"
	PWCHAR				Mask,			// search mask
	PLIST_ENTRY			FilesList,		// the list where all FILE_DESCW structures will be linked
	PCRITICAL_SECTION	FilesListLock,	// file list locking object (OPTIONAL)
	ULONG				SearchPathLen,	// the length of the initial search path in chars, used to keep directory structure 
										//  relative to the search path
	ULONG				SearchFlags		// various flags
	)
{
	ULONG	Found = 0, PathLen, MaskLen, ScanLen = MAX_PATH;
	LPWIN32_FIND_DATAW	FindData;
	PWCHAR	ScanPath, ResolvedPath = NULL;

	if (FindData = AppAlloc(sizeof(WIN32_FIND_DATAW)))
	{
		if (ResolvedPath = FilesExpandEnvironmentVariablesW(Path))
			Path = ResolvedPath;

		PathLen = wcslen(Path);
		MaskLen = wcslen(Mask);

		if (SearchPathLen == 0)
			SearchPathLen = PathLen;

		while ((PathLen + MaskLen + 2) > ScanLen)		// 1 for "\\" and 1 for "\0"
			ScanLen += MAX_PATH;

		if (ScanPath = AppAlloc(ScanLen * sizeof(WCHAR)))
		{
			HANDLE hFind;
			PFILE_DESCW	fDesc;	

			memset(FindData, 0, sizeof(WIN32_FIND_DATA));
			PathCombineW(ScanPath, Path, Mask);

			// Searching for files within the current directory first
			if ((hFind = FindFirstFileW(ScanPath, FindData)) != INVALID_HANDLE_VALUE)
			{
				do
				{
					if ((FindData->nFileSizeHigh) || (FindData->nFileSizeLow > FILE_SIZE_MAX))
						continue;

					if (FindData->cFileName[0] == '.')
						continue;

					if (fDesc = FileDescAlloc(sizeof(FILE_DESCW) + (PathLen + wcslen(Mask) + wcslen(FindData->cFileName) + 2) * sizeof(WCHAR)))
					{
						LPWSTR	pDir, pPath;

						wcscpy((PWCHAR)&fDesc->Path, Path);
						if (pDir = StrRChrW(Mask, NULL, L'\\'))
						{
							PathCombineW((PWCHAR)&fDesc->Path, Path, Mask);
							*PathFindFileNameW((PWCHAR)&fDesc->Path) = 0;
							pPath = (PWCHAR)&fDesc->Path;
						}
						else
							pPath = Path;

						PathCombineW((PWCHAR)&fDesc->Path, pPath, FindData->cFileName);
		
						fDesc->SearchPathLen = SearchPathLen;
						fDesc->Flags = SearchFlags;

						if (FilesListLock)	EnterCriticalSection(FilesListLock);
						InsertTailList(FilesList, &fDesc->Entry);
						if (FilesListLock)	LeaveCriticalSection(FilesListLock);
					
						Found += 1;
					}
				} while(FindNextFileW(hFind, FindData) && WaitForSingleObject(g_AppShutdownEvent, 0) == WAIT_TIMEOUT);

				FindClose(hFind);
			}	// if ((hFind = FindFirstFileW(ScanPath, FindData)) != INVALID_HANDLE_VALUE)

			// Files are searched, looking for directories to scan them recursively
			PathCombineW(ScanPath, Path, L"*");
	
			if ((hFind = FindFirstFileW(ScanPath, FindData)) != INVALID_HANDLE_VALUE)
			{
				do
				{
					if (FindData->cFileName[0] != '.' && (FindData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
					{
						MaskLen = wcslen(FindData->cFileName);
						if ((PathLen + MaskLen + 2) > ScanLen)		// 1 for "\\" and 1 for "\0"
						{
							AppFree(ScanPath);
							do {
								ScanLen += MAX_PATH;
							} while ((PathLen + MaskLen + 2) > ScanLen);

							if (!(ScanPath = AppAlloc(ScanLen * sizeof(WCHAR))))
								break;	// not enough memory
						}	// if ((PathLen + MaskLen + 2) > ScanLen)

						PathCombineW(ScanPath, Path, FindData->cFileName);

						Found += FilesScanW(ScanPath, Mask, FilesList, FilesListLock, SearchPathLen, SearchFlags);
					}	// if (FindData->cFileName[0] != '.' &&
				} while(FindNextFileW(hFind, FindData) && WaitForSingleObject(g_AppShutdownEvent, 0) == WAIT_TIMEOUT);

				FindClose(hFind);
			}	// if (hFind = FindFirstFileW(ScanPath, FindData))

			if (ScanPath)
				AppFree(ScanPath);
		}	// if (ScanPath = 

		if (ResolvedPath)
			AppFree(ResolvedPath);

		AppFree(FindData);
	}	// if (FindData)
	return(Found);
}
Example #29
0
int x509_crt_parse_path( x509_crt *chain, const char *path )
{
    int ret = 0;
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
    int w_ret;
    WCHAR szDir[MAX_PATH];
    char filename[MAX_PATH];
	char *p;
    int len = (int) strlen( path );

	WIN32_FIND_DATAW file_data;
    HANDLE hFind;

    if( len > MAX_PATH - 3 )
        return( POLARSSL_ERR_X509_BAD_INPUT_DATA );

	memset( szDir, 0, sizeof(szDir) );
	memset( filename, 0, MAX_PATH );
	memcpy( filename, path, len );
	filename[len++] = '\\';
	p = filename + len;
    filename[len++] = '*';

	w_ret = MultiByteToWideChar( CP_ACP, 0, filename, len, szDir, MAX_PATH - 3 );

    hFind = FindFirstFileW( szDir, &file_data );
    if (hFind == INVALID_HANDLE_VALUE)
        return( POLARSSL_ERR_X509_FILE_IO_ERROR );

    len = MAX_PATH - len;
    do
    {
		memset( p, 0, len );

        if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            continue;

		w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
									 lstrlenW(file_data.cFileName),
									 p, len - 1,
									 NULL, NULL );

        w_ret = x509_crt_parse_file( chain, filename );
        if( w_ret < 0 )
            ret++;
        else
            ret += w_ret;
    }
    while( FindNextFileW( hFind, &file_data ) != 0 );

    if (GetLastError() != ERROR_NO_MORE_FILES)
        ret = POLARSSL_ERR_X509_FILE_IO_ERROR;

    FindClose( hFind );
#else /* _WIN32 */
    int t_ret;
    struct stat sb;
    struct dirent *entry;
    char entry_name[255];
    DIR *dir = opendir( path );

    if( dir == NULL)
        return( POLARSSL_ERR_X509_FILE_IO_ERROR );

#if defined(POLARSSL_THREADING_PTHREAD)
    if( ( ret = polarssl_mutex_lock( &readdir_mutex ) ) != 0 )
        return( ret );
#endif

    while( ( entry = readdir( dir ) ) != NULL )
    {
        snprintf( entry_name, sizeof entry_name, "%s/%s", path, entry->d_name );

        if( stat( entry_name, &sb ) == -1 )
        {
            closedir( dir );
            ret = POLARSSL_ERR_X509_FILE_IO_ERROR;
            goto cleanup;
        }

        if( !S_ISREG( sb.st_mode ) )
            continue;

        // Ignore parse errors
        //
        t_ret = x509_crt_parse_file( chain, entry_name );
        if( t_ret < 0 )
            ret++;
        else
            ret += t_ret;
    }
    closedir( dir );

cleanup:
#if defined(POLARSSL_THREADING_PTHREAD)
    if( polarssl_mutex_unlock( &readdir_mutex ) != 0 )
        ret = POLARSSL_ERR_THREADING_MUTEX_ERROR;
#endif

#endif /* _WIN32 */

    return( ret );
}
Example #30
0
/* =========================================================================
 * Handle the processing for a single directory, optionally recursing into
 *  subdirectories if needed.
 * Parameters:
 *  rootdir      [I]   The directory to search in
 *  filespec     [I]   The filespec to search for
 *  recurse      [I]   Whether to recurse (search subdirectories before
 *                          current directory)
 *  includedirs  [I]   Whether to set directory attributes as well
 *  attrib_set   [I]   Attributes to set
 *  attrib_clear [I]   Attributes to clear
 *
 * Returns TRUE if at least one file displayed / modified
 * ========================================================================= */
static BOOL ATTRIB_processdirectory(const WCHAR *rootdir, const WCHAR *filespec,
                                    BOOL recurse, BOOL includedirs,
                                    DWORD attrib_set, DWORD attrib_clear)
{
    BOOL found = FALSE;
    WCHAR buffer[MAX_PATH];
    HANDLE hff;
    WIN32_FIND_DATAW fd;
    WCHAR flags[] = {' ',' ',' ',' ',' ',' ',' ',' ','\0'};
    static const WCHAR slashW[] = {'\\','\0'};

    WINE_TRACE("Processing dir '%s', spec '%s', %d,%x,%x\n",
               wine_dbgstr_w(rootdir), wine_dbgstr_w(filespec),
               recurse, attrib_set, attrib_clear);

    if (recurse) {

      /* Build spec to search for */
      strcpyW(buffer, rootdir);
      strcatW(buffer, starW);

      /* Search for directories in the location and recurse if necessary */
      WINE_TRACE("Searching for directories with '%s'\n", wine_dbgstr_w(buffer));
      hff = FindFirstFileW(buffer, &fd);
      if (hff != INVALID_HANDLE_VALUE) {
          do {
              const WCHAR dot[] = {'.', 0};
              const WCHAR dotdot[] = {'.', '.', 0};

              /* Only interested in directories, and not . nor .. */
              if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
                  !strcmpW(fd.cFileName, dot) || !strcmpW(fd.cFileName, dotdot))
                  continue;

              /* Build new root dir to go searching in */
              strcpyW(buffer, rootdir);
              strcatW(buffer, fd.cFileName);
              strcatW(buffer, slashW);
              ATTRIB_processdirectory(buffer, filespec, recurse, includedirs,
                                      attrib_set, attrib_clear);

          } while (FindNextFileW(hff, &fd) != 0);
      }
      FindClose (hff);
    }

    /* Build spec to search for */
    strcpyW(buffer, rootdir);
    strcatW(buffer, filespec);
    WINE_TRACE("Searching for files as '%s'\n", wine_dbgstr_w(buffer));

    /* Search for files in the location with the filespec supplied */
    hff = FindFirstFileW(buffer, &fd);
    if (hff != INVALID_HANDLE_VALUE) {
        do {
            const WCHAR dot[] = {'.', 0};
            const WCHAR dotdot[] = {'.', '.', 0};
            DWORD count;
            WINE_TRACE("Found '%s'\n", wine_dbgstr_w(fd.cFileName));

            if (!strcmpW(fd.cFileName, dot) || !strcmpW(fd.cFileName, dotdot))
                continue;

            if (!includedirs && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
              continue;

            if (attrib_set || attrib_clear) {
                fd.dwFileAttributes &= ~attrib_clear;
                fd.dwFileAttributes |= attrib_set;
                if (!fd.dwFileAttributes)
                    fd.dwFileAttributes |= FILE_ATTRIBUTE_NORMAL;
                strcpyW(buffer, rootdir);
                strcatW(buffer, fd.cFileName);
                SetFileAttributesW(buffer, fd.dwFileAttributes);
                found = TRUE;
            } else {
                static const WCHAR fmt[] = {'%','1',' ',' ',' ',' ',' ','%','2','\n','\0'};
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
                    flags[4] = 'H';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
                    flags[1] = 'S';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
                    flags[0] = 'A';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
                    flags[5] = 'R';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
                    flags[6] = 'T';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
                    flags[7] = 'C';
                }
                strcpyW(buffer, rootdir);
                strcatW(buffer, fd.cFileName);
                ATTRIB_wprintf(fmt, flags, buffer);
                for (count = 0; count < (sizeof(flags)/sizeof(WCHAR) - 1); count++) flags[count] = ' ';
                found = TRUE;
            }
        } while (FindNextFileW(hff, &fd) != 0);
    }
    FindClose (hff);
    return found;
}