Exemple #1
0
WCHAR *WindowsRetrieveDosName(const WCHAR *aLongName)
{
	// Convert to a short DOS file name. File MUST already exist!
	// len will be space required for string and terminator
	DWORD len = GetShortPathNameW((WCHAR *)aLongName, 0, 0);
	if( len <= 0 )
		{
		prog << Log::Indent() << "Failed to find existing file and retrieve short name" << Log::Endl();
		return 0;
		}
	
	//prog << Log::Indent() << "space required for short name is " << len << Log::Endl();
	WCHAR *shortName = new WCHAR[len];
	(void) GetShortPathNameW(aLongName, shortName, len);
	return shortName;
}
SString SharedUtil::GetSystemShortPathName( const SString& strPath )
{
    wchar_t szBuffer[32000];
    szBuffer[0] = 0;
    GetShortPathNameW( FromUTF8( strPath ), szBuffer, NUMELMS( szBuffer ) - 1 );
    return ToUTF8( szBuffer );
}
Exemple #3
0
char *Sys_GetHomeDir(void)
{
  char *cur;
  char *old;
  char profile[MAX_PATH];
  int len;
  static char gdir[MAX_OSPATH];
  WCHAR sprofile[MAX_PATH];
  WCHAR uprofile[MAX_PATH];

  /* The following lines implement a horrible
     hack to connect the UTF-16 WinAPI to the
     ASCII Quake II. While this should work in
     most cases, it'll fail if the "Windows to
     DOS filename translation" is switched off.
     In that case the function will return NULL
     and no homedir is used. */

  /* Get the path to "My Documents" directory */
  SHGetFolderPathW(NULL, CSIDL_PERSONAL, NULL, 0, uprofile);

  /* Create a UTF-16 DOS path */
  len = GetShortPathNameW(uprofile, sprofile, sizeof(sprofile));

  if (len == 0) {
    return NULL;
  }

  /* Since the DOS path contains no UTF-16 characters, just convert it to ASCII
   */
  WideCharToMultiByte(CP_ACP, 0, sprofile, -1, profile, sizeof(profile), NULL, NULL);

  if (len == 0) {
    return NULL;
  }

  /* Check if path is too long */
  if ((len + strlen(CFGDIR) + 3) >= 256) {
    return NULL;
  }

  /* Replace backslashes by slashes */
  cur = old = profile;

  if (strstr(cur, "\\") != NULL) {
    while (cur != NULL) {
      if ((cur - old) > 1) {
        *cur = '/';
      }

      old = cur;
      cur = strchr(old + 1, '\\');
    }
  }

  snprintf(gdir, sizeof(gdir), "%s/%s/", profile, CFGDIR);

  return gdir;
}
Exemple #4
0
///////////////////////////////////////////////////////////////////////////////
// load lua code
///////////////////////////////////////////////////////////////////////////////
bool widePathToShortAsciiPath(const wchar_t* wPath, char* cPath)
{
	wchar_t transformString[MAX_PATH];
	ZeroMemory(transformString, MAX_PATH * sizeof(wchar_t));
	ZeroMemory(cPath, MAX_PATH);

	do
	{
		if (GetShortPathNameW(wPath, NULL, 0) == 0) break;
		if (GetShortPathNameW(wPath, transformString, MAX_PATH) == 0) break;
		for (int i = 0; i < MAX_PATH; i++)
			cPath[i] = ((char*)&transformString[0])[i*2];
		return true;
	} while (0);

	return false;
}
Exemple #5
0
/***********************************************************************
 *           start_dosbox
 */
static void start_dosbox( const char *appname, const char *args )
{
    static const WCHAR cfgW[] = {'c','f','g',0};
    const char *config_dir = wine_get_config_dir();
    WCHAR path[MAX_PATH], config[MAX_PATH];
    HANDLE file;
    char *p, *buffer, app[MAX_PATH];
    int i;
    int ret = 1;
    DWORD written, drives = GetLogicalDrives();
    char *dosbox = find_dosbox();

    if (!dosbox) return;
    if (!GetTempPathW( MAX_PATH, path )) return;
    if (!GetTempFileNameW( path, cfgW, 0, config )) return;
    if (!GetCurrentDirectoryW( MAX_PATH, path )) return;
    if (!GetShortPathNameA( appname, app, MAX_PATH )) return;
    GetShortPathNameW( path, path, MAX_PATH );
    file = CreateFileW( config, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 );
    if (file == INVALID_HANDLE_VALUE) return;

    buffer = HeapAlloc( GetProcessHeap(), 0, sizeof("[autoexec]") +
                        sizeof("mount -z c") + sizeof("config -securemode") +
                        25 * (strlen(config_dir) + sizeof("mount c /dosdevices/c:")) +
                        4 * strlenW( path ) +
                        6 + strlen( app ) + strlen( args ) + 20 );
    p = buffer;
    p += sprintf( p, "[autoexec]\n" );
    for (i = 25; i >= 0; i--)
        if (!(drives & (1 << i)))
        {
            p += sprintf( p, "mount -z %c\n", 'a' + i );
            break;
        }
    for (i = 0; i <= 25; i++)
        if (drives & (1 << i))
            p += sprintf( p, "mount %c %s/dosdevices/%c:\n", 'a' + i, config_dir, 'a' + i );
    p += sprintf( p, "%c:\ncd ", path[0] );
    p += WideCharToMultiByte( CP_UNIXCP, 0, path + 2, -1, p, 4 * strlenW(path), NULL, NULL ) - 1;
    p += sprintf( p, "\nconfig -securemode\n" );
    p += sprintf( p, "%s %s\n", app, args );
    p += sprintf( p, "exit\n" );
    if (WriteFile( file, buffer, strlen(buffer), &written, NULL ) && written == strlen(buffer))
    {
        const char *args[5];
        char *config_file = wine_get_unix_file_name( config );
        args[0] = dosbox;
        args[1] = "-userconf";
        args[2] = "-conf";
        args[3] = config_file;
        args[4] = NULL;
        ret = _spawnvp( _P_WAIT, args[0], args );
    }
    CloseHandle( file );
    DeleteFileW( config );
    HeapFree( GetProcessHeap(), 0, buffer );
    ExitProcess( ret );
}
Exemple #6
0
StString StFileNode::getCompatibleName(const StString& theFileName) {
#ifdef _WIN32
    stUtfWide_t aShortNameWide[MAX_PATH];
    GetShortPathNameW(theFileName.toUtfWide().toCString(), aShortNameWide, MAX_PATH);
    return *aShortNameWide != L'\0' ? StString(aShortNameWide) : theFileName;
#else
    return theFileName;
#endif
}
Exemple #7
0
// Case-Normalize file name via GetShortPathNameW()/GetLongPathNameW()
QString normalizeFileName(const QString &name)
{
    wchar_t shortBuffer[MAX_PATH];
    const QString nativeFileName = QDir::toNativeSeparators(name);
    if (!GetShortPathNameW((wchar_t *)nativeFileName.utf16(), shortBuffer, MAX_PATH))
        return name;
    wchar_t result[MAX_PATH];
    if (!GetLongPathNameW(shortBuffer, result, MAX_PATH))
        return name;
    return QDir::fromNativeSeparators(QString::fromWCharArray(result));
}
Exemple #8
0
/*
 * Convert long path to short path
 */
QString AbstractTool::pathToShort(const QString &longPath)
{
    QString shortPath;
    DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);

    if(buffSize > 0)
    {
        wchar_t *buffer = new wchar_t[buffSize];
        DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);

        if(result > 0 && result < buffSize)
        {
            shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
        }

        delete[] buffer;
    }

    return (shortPath.isEmpty() ? longPath : shortPath);
}
BOOL CHistoryManager::PrepareTempDirs()
{
	for (int i = 0; i < TEMP_KEY_COUNT; i++)
	{
		HKEY key;
		if (RegOpenKeyExA(HKEY_CURRENT_USER, REG_TEMP_FOLDER, 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
			continue;

		g_TempPaths[i].strRegKey = g_TempKey[i];

		WCHAR szPath[1024];
		DWORD Size = 1024;
		if (RegQueryValueExW(key, g_TempPaths[i].strRegKey.c_str(), NULL, NULL, (LPBYTE)szPath, &Size) != ERROR_SUCCESS)
		{
			RegCloseKey(key);
			continue;
		}

		CStringW strPath = szPath;
		strPath.Replace(L'/', L'\\');
		if (strPath[strPath.GetLength() - 1] != L'\\')
			strPath += L'\\';

		//////////////////////////////////////////////////////////////////////////
		// Create Redirect Directory

		CStringW strTemp = m_strRedirectPath + CStringW(g_TempPaths[i].strRegKey.c_str());
		if (!CreateDirectoryW(strTemp, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
			continue;
		SetFileAttributesW(strTemp, FILE_ATTRIBUTE_HIDDEN);
		
		//////////////////////////////////////////////////////////////////////////
		// 

 		WCHAR szDir[1024], szShort[1024], szLong[1024];
 		ExpandEnvironmentStringsW((LPWSTR)(LPCWSTR)strPath, (LPWSTR)szDir, _countof(szDir));
 		GetShortPathNameW(szDir, szShort, _countof(szShort));
		GetLongPathNameW(szDir, szLong, _countof(szLong));
		
		_wcslwr_s(szShort);
		_wcslwr_s(szLong);

		g_TempPaths[i].strShortTempDir = szShort;
		g_TempPaths[i].strLongTempDir = szLong;

		SplitPath(g_TempPaths[i].strShortTempDir, g_TempPaths[i].vecShortParts);
		SplitPath(g_TempPaths[i].strLongTempDir, g_TempPaths[i].vecLongParts);

		RegCloseKey(key);
	}

	return true;
}
/*--------------------------------------------------------------------------*/
wchar_t *createtempfilenameW(const wchar_t *wcprefix, BOOL bShortFormat)
{
    wchar_t *wcReturnedTempFilename = NULL;

#ifdef _MSC_VER
    wchar_t *wcTmpDir = getTMPDIRW();
    if (wcTmpDir)
    {
        unsigned int uRetVal = 0;
        wchar_t wcTempFileName[MAX_PATH];
        uRetVal = GetTempFileNameW(wcTmpDir, wcprefix, 0, wcTempFileName);
        if (uRetVal != 0)
        {
            size_t len = wcslen(wcTempFileName) + 1;
            wchar_t* shortTempFilename = (wchar_t *)MALLOC(len * sizeof(wchar_t));
            if (shortTempFilename)
            {
                if (bShortFormat)
                {
                    GetShortPathNameW(wcTempFileName, shortTempFilename, (DWORD)len);
                }
                wcReturnedTempFilename = shortTempFilename;
            }
        }

        FREE(wcTmpDir);
    }
#else
    char *prefix = wide_string_to_UTF8(wcprefix);
    char *result = createtempfilename(prefix, bShortFormat);

    wcReturnedTempFilename = to_wide_string(result);

    if (result)
    {
        FREE(result);
        result = NULL;
    }
    if (prefix)
    {
        FREE(prefix);
        prefix = NULL;
    }
    if (result)
    {
        FREE(result);
        result = NULL;
    }
#endif
    return wcReturnedTempFilename;
}
char * pyi_win32_wcs_to_mbs_sfn(const wchar_t *wstr) {
    DWORD wsfnlen;
    wchar_t * wstr_sfn = NULL;
    char * str = NULL;
    DWORD ret;

    wsfnlen = GetShortPathNameW(wstr, NULL, 0);
    if(wsfnlen) {
        wstr_sfn = (wchar_t *)malloc(sizeof(wchar_t) * wsfnlen + 1);
        ret = GetShortPathNameW(wstr, wstr_sfn, wsfnlen);
        if(ret) {
            str = pyi_win32_wcs_to_mbs(wstr_sfn);
        }
        free(wstr_sfn);
    }
    if(!str){
        VS("Failed to get short path name for filename. GetShortPathNameW: \n%s",
                   GetWinErrorString()
                   );
        str = pyi_win32_wcs_to_mbs(wstr);
    }
    return str;
}
Exemple #12
0
void BLI_get_short_name(char short_name[256], const char *filename)
{
	wchar_t short_name_16[256];
	int i = 0;

	UTF16_ENCODE(filename);

	GetShortPathNameW(filename_16, short_name_16, 256);

	for (i = 0; i < 256; i++) {
		short_name[i] = (char)short_name_16[i];
	}

	UTF16_UN_ENCODE(filename);
}
Exemple #13
0
char *path_utf8_to_ansi(const char *psz_filename_utf8, int b_create)
{
	char *short_path = NULL;
	wchar_t *psz_filename_utf16 = NULL;

	if(!psz_filename_utf8)
	{
		return NULL;
	}
	
	psz_filename_utf16 = utf8_to_utf16(psz_filename_utf8);
	if(psz_filename_utf16)
	{
		char *psz_filename_ansi = NULL;
		if(b_create)
		{
			FILE *fh = _wfopen(psz_filename_utf16, L"a+");
			if(fh) fclose(fh);
		}
		psz_filename_ansi = utf16_to_ansi(psz_filename_utf16);
		if(psz_filename_ansi)
		{
			if(strcmp(psz_filename_ansi, psz_filename_utf8))
			{
				wchar_t short_name_utf16[MAX_PATH];
				DWORD result = GetShortPathNameW(psz_filename_utf16, short_name_utf16, MAX_PATH);
				if((result > 0) && (result < MAX_PATH))
				{
					short_path = utf16_to_ansi(short_name_utf16);
					free(psz_filename_ansi);
				}
				else
				{
					short_path = psz_filename_ansi; /*if GetShortPathName() failed, use the ANSI version*/
				}
			}
			else
			{
				short_path = psz_filename_ansi; /*don't convert plain ASCII filenames to "short" path*/
			}
		}
		free(psz_filename_utf16);
	}

	return short_path;
}
Exemple #14
0
// This function has been copied (and modified a little bit) from Scribus (program under GPL license):
// http://docs.scribus.net/devel/util_8cpp-source.html#l00112
QString fileFilters::shortPathName(QString long_path) {
    if ((QSysInfo::WindowsVersion >= QSysInfo::WV_NT) && (QFile::exists(long_path))) {
                QString short_path = long_path;

                const int max_path = 4096;
                WCHAR shortName[max_path];

                QString nativePath = QDir::convertSeparators(long_path);
                int ret = GetShortPathNameW((LPCWSTR) nativePath.utf16(), shortName, max_path);
                if (ret != ERROR_INVALID_PARAMETER && ret < MAX_PATH)
                        short_path = QString::fromUtf16((const ushort*) shortName);

                return short_path;
        } else {
                return long_path;
        }
}
Exemple #15
0
// TODO rename fuction and revisit
int pyi_get_temp_path(char *buffer)
{
    int i;
    char *ret;
    char prefix[16];
    stb__wchar wchar_buffer[PATH_MAX];
    stb__wchar wchar_dos83_buffer[PATH_MAX];

    // TODO later when moving to full unicode support - use 83 filename only where really necessary.
    /*
     * Get path to Windows temporary directory.
     *
     * Usually on Windows it points to a user-specific path.
     * When the username contains foreign characters then
     * the path to temp dir contains them too and the frozen
     * app fails to run.
     *
     * Converting temppath to 8.3 filename should fix this
     * when running in --onefile mode.
     */
    GetTempPathW(PATH_MAX, wchar_buffer);
    GetShortPathNameW(wchar_buffer, wchar_dos83_buffer, PATH_MAX);
    /* Convert wchar_t to utf8 just use char as usual. */
    stb_to_utf8(buffer, wchar_dos83_buffer, PATH_MAX);

    sprintf(prefix, "_MEI%d", getpid());

    /*
     * Windows does not have a race-free function to create a temporary
     * directory. Thus, we rely on _tempnam, and simply try several times
     * to avoid stupid race conditions.
     */
    for (i=0;i<5;i++) {
        // TODO use race-free fuction - if any exists?
        ret = _tempnam(buffer, prefix);
        if (mkdir(ret) == 0) {
            strcpy(buffer, ret);
            free(ret);
            return 1;
        }
        free(ret);
    }
    return 0;
}
Exemple #16
0
static int WPath2A(char *dst, size_t size, const WCHAR *src) {
	int len;
	BOOL default_char = FALSE;

	// test if we can convert lossless
	len = WideCharToMultiByte(CP_ACP, 0, src, -1, dst, size, NULL, &default_char);

	if (default_char) {
		/* The following lines implement a horrible
		   hack to connect the UTF-16 WinAPI to the
		   ASCII doom3 strings. While this should work in
		   most cases, it'll fail if the "Windows to
		   DOS filename translation" is switched off.
		   In that case the function will return NULL
		   and no homedir is used. */
		WCHAR w[MAX_OSPATH];
		len = GetShortPathNameW(src, w, sizeof(w));

		if (len == 0)
			return 0;

		/* Since the DOS path contains no UTF-16 characters, convert it to the system's default code page */
		len = WideCharToMultiByte(CP_ACP, 0, w, len, dst, size - 1, NULL, NULL);
	}

	if (len == 0)
		return 0;

	dst[len] = 0;
	/* Replace backslashes by slashes */
	for (int i = 0; i < len; ++i)
		if (dst[i] == '\\')
			dst[i] = '/';

	// cut trailing slash
	if (dst[len - 1] == '/') {
		dst[len - 1] = 0;
		len--;
	}

	return len;
}
Exemple #17
0
/**
 * Get the short DOS 8.3 format for paths.
 * FreeType doesn't support Unicode filenames and Windows' fopen (as used
 * by FreeType) doesn't support UTF-8 filenames. So we have to convert the
 * filename into something that isn't UTF-8 but represents the Unicode file
 * name. This is the short DOS 8.3 format. This does not contain any
 * characters that fopen doesn't support.
 * @param long_path the path in UTF-8.
 * @return the short path in ANSI (ASCII).
 */
char *GetShortPath(const char *long_path)
{
	static char short_path[MAX_PATH];
#ifdef UNICODE
	/* The non-unicode GetShortPath doesn't support UTF-8...,
	 * so convert the path to wide chars, then get the short
	 * path and convert it back again. */
	wchar_t long_path_w[MAX_PATH];
	MultiByteToWideChar(CP_UTF8, 0, long_path, -1, long_path_w, MAX_PATH);

	wchar_t short_path_w[MAX_PATH];
	GetShortPathNameW(long_path_w, short_path_w, MAX_PATH);

	WideCharToMultiByte(CP_ACP, 0, short_path_w, -1, short_path, MAX_PATH, NULL, NULL);
#else
	/* Technically not needed, but do it for consistency. */
	GetShortPathNameA(long_path, short_path, MAX_PATH);
#endif
	return short_path;
}
Exemple #18
0
void CYahooProto::SendAvatar(const TCHAR *szFile)
{
	struct _stat statbuf;
	if (_tstat(szFile, &statbuf) != 0) {
		LOG(("[YAHOO_SendAvatar] Error reading File information?!"));
		return;
	}

	yahoo_file_info *sf = y_new(struct yahoo_file_info, 1);
	sf->filesize = statbuf.st_size;

	wchar_t tszFilename[MAX_PATH];
	wcsncpy(tszFilename, szFile, _countof(tszFilename) - 1);
	GetShortPathNameW(szFile, tszFilename, _countof(tszFilename));
	char szFilename[MAX_PATH];
	WideCharToMultiByte(CP_ACP, 0, tszFilename, -1, szFilename, MAX_PATH, 0, 0);
	sf->filename = strdup(szFilename);

	debugLogA("[Uploading avatar] filename: %s size: %ld", sf->filename, sf->filesize);

	ForkThread(&CYahooProto::send_avt_thread, sf);
}
void SettingsManagerHelpers::GetAsciiFilename(const wchar_t* wfilename, CCharBuffer buffer)
{
	if (buffer.getSizeInElements() <= 0)
	{
		return;
	}

	if (wfilename[0] == 0)
	{
		buffer[0] = 0;
		return;
	}

	if (Utf16ContainsAsciiOnly(wfilename))
	{
		ConvertUtf16ToUtf8(wfilename, buffer);
		return;
	}

	// The path is non-ASCII unicode, so let's resort to short filenames (they are always ASCII-only, I hope)
	wchar_t shortW[MAX_PATH];
	const int bufferCharCount = sizeof(shortW) / sizeof(shortW[0]);
	const int charCount = GetShortPathNameW(wfilename, shortW, bufferCharCount);
	if (charCount <= 0 || charCount >= bufferCharCount)
	{
		buffer[0] = 0;
		return;
	}

	shortW[charCount] = 0;
	if (!Utf16ContainsAsciiOnly(shortW))
	{
		buffer[0] = 0;
		return;
	}

	ConvertUtf16ToUtf8(shortW, buffer);
}
Exemple #20
0
/* utils::shortPathName */
SEXP in_shortpath(SEXP paths)
{
    SEXP ans, el;
    int i, n = LENGTH(paths);
    char tmp[MAX_PATH];
    wchar_t wtmp[32768];
    DWORD res;
    const void *vmax = vmaxget();

    if(!isString(paths)) error(_("'path' must be a character vector"));

    PROTECT(ans = allocVector(STRSXP, n));
    for (i = 0; i < n; i++) {
	el = STRING_ELT(paths, i);
	if(getCharCE(el) == CE_UTF8) {
	    res = GetShortPathNameW(filenameToWchar(el, FALSE), wtmp, 32768);
	    if (res && res <= 32768)
		wcstoutf8(tmp, wtmp, wcslen(wtmp)+1);
	    else
		strcpy(tmp, translateChar(el));
	    /* documented to return paths using \, which the API call does
	       not necessarily do */
	    R_fixbackslash(tmp);
	    SET_STRING_ELT(ans, i, mkCharCE(tmp, CE_UTF8));
	} else {
	    res = GetShortPathName(translateChar(el), tmp, MAX_PATH);
	    if (res == 0 || res > MAX_PATH) strcpy(tmp, translateChar(el));
	    /* documented to return paths using \, which the API call does
	       not necessarily do */
	    R_fixbackslash(tmp);
	    SET_STRING_ELT(ans, i, mkChar(tmp));
	}
    }
    UNPROTECT(1);
    vmaxset(vmax);
    return ans;
}
CHistoryManagerXP::CHistoryManagerXP(void)
{
	LPWSTR lpszTempPath = new WCHAR[MAX_PATH + 1];
	int nLength = GetTempPathW(MAX_PATH, lpszTempPath);
	if (nLength > MAX_PATH)
	{
		delete[] lpszTempPath;
		lpszTempPath = new WCHAR[nLength + 1];
		GetTempPathW(nLength, lpszTempPath);
	}

	lpszTempPath[nLength] = '\0';
	CStringW strTempPath = lpszTempPath;	
	delete[] lpszTempPath;

	strTempPath.Replace(L'/', L'\\');
	if (strTempPath[strTempPath.GetLength() - 1] != '\\')
		strTempPath += L"\\";

	m_strWinTemp = strTempPath;

	strTempPath += L"BankTemp";
	if (!CreateDirectoryW(strTempPath, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
		return;

	SetFileAttributesW(strTempPath, FILE_ATTRIBUTE_HIDDEN);

	LPWSTR pBuf = NULL;

	// short path
	pBuf = m_strRedirectPath.GetBuffer(1024);
	GetShortPathNameW(strTempPath, pBuf, 1024);
	m_strRedirectPath.ReleaseBuffer();
	m_strRedirectPath += L"\\";
	m_strRedirectPath.MakeLower();
}
char *
CodeSet_GetAltPathName(const utf16_t *pathW) // IN
{
   char *path = NULL;
#if defined(_WIN32)
   utf16_t shortPathW[_MAX_PATH];

   ASSERT(pathW);

   if (GetShortPathNameW(pathW, shortPathW, ARRAYSIZE(shortPathW)) == 0) {
      goto exit;
   }

   if (!CodeSetOld_Utf16leToCurrent((const char *)shortPathW,
                                    wcslen(shortPathW) * sizeof *shortPathW,
                                    &path, NULL)) {
      goto exit;
   }

  exit:
#endif // _WIN32

   return path;
}
Exemple #23
0
/****************************************************************************
 * WCMD_HandleTildaModifiers
 *
 * Handle the ~ modifiers when expanding %0-9 or (%a-z/A-Z in for command)
 *    %~xxxxxV  (V=0-9 or A-Z, a-z)
 * Where xxxx is any combination of:
 *    ~ - Removes quotes
 *    f - Fully qualified path (assumes current dir if not drive\dir)
 *    d - drive letter
 *    p - path
 *    n - filename
 *    x - file extension
 *    s - path with shortnames
 *    a - attributes
 *    t - date/time
 *    z - size
 *    $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
 *                   qualified path
 *
 *  To work out the length of the modifier:
 *
 *  Note: In the case of %0-9 knowing the end of the modifier is easy,
 *    but in a for loop, the for end WCHARacter may also be a modifier
 *    eg. for %a in (c:\a.a) do echo XXX
 *             where XXX = %~a    (just ~)
 *                         %~aa   (~ and attributes)
 *                         %~aaxa (~, attributes and extension)
 *                   BUT   %~aax  (~ and attributes followed by 'x')
 *
 *  Hence search forwards until find an invalid modifier, and then
 *  backwards until find for variable or 0-9
 */
void WCMD_HandleTildaModifiers(WCHAR **start, BOOL atExecute)
{

#define NUMMODIFIERS 11
  static const WCHAR validmodifiers[NUMMODIFIERS] = {
        '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
  };

  WIN32_FILE_ATTRIBUTE_DATA fileInfo;
  WCHAR  outputparam[MAX_PATH];
  WCHAR  finaloutput[MAX_PATH];
  WCHAR  fullfilename[MAX_PATH];
  WCHAR  thisoutput[MAX_PATH];
  WCHAR  *pos            = *start+1;
  WCHAR  *firstModifier  = pos;
  WCHAR  *lastModifier   = NULL;
  int   modifierLen     = 0;
  BOOL  finished        = FALSE;
  int   i               = 0;
  BOOL  exists          = TRUE;
  BOOL  skipFileParsing = FALSE;
  BOOL  doneModifier    = FALSE;

  /* Search forwards until find invalid character modifier */
  while (!finished) {

    /* Work on the previous character */
    if (lastModifier != NULL) {

      for (i=0; i<NUMMODIFIERS; i++) {
        if (validmodifiers[i] == *lastModifier) {

          /* Special case '$' to skip until : found */
          if (*lastModifier == '$') {
            while (*pos != ':' && *pos) pos++;
            if (*pos == 0x00) return; /* Invalid syntax */
            pos++;                    /* Skip ':'       */
          }
          break;
        }
      }

      if (i==NUMMODIFIERS) {
        finished = TRUE;
      }
    }

    /* Save this one away */
    if (!finished) {
      lastModifier = pos;
      pos++;
    }
  }

  while (lastModifier > firstModifier) {
    WINE_TRACE("Looking backwards for parameter id: %s\n",
               wine_dbgstr_w(lastModifier));

    if (!atExecute && context && (*lastModifier >= '0' && *lastModifier <= '9')) {
      /* Its a valid parameter identifier - OK */
      break;

    } else {
      int foridx = FOR_VAR_IDX(*lastModifier);
      /* Its a valid parameter identifier - OK */
      if ((foridx >= 0) && (forloopcontext.variable[foridx] != NULL)) break;

      /* Its not a valid parameter identifier - step backwards */
      lastModifier--;
    }
  }
  if (lastModifier == firstModifier) return; /* Invalid syntax */

  /* Extract the parameter to play with */
  if (*lastModifier == '0') {
    strcpyW(outputparam, context->batchfileW);
  } else if ((*lastModifier >= '1' && *lastModifier <= '9')) {
    strcpyW(outputparam,
            WCMD_parameter (context -> command,
                            *lastModifier-'0' + context -> shift_count[*lastModifier-'0'],
                            NULL, FALSE, TRUE));
  } else {
    int foridx = FOR_VAR_IDX(*lastModifier);
    strcpyW(outputparam, forloopcontext.variable[foridx]);
  }

  /* So now, firstModifier points to beginning of modifiers, lastModifier
     points to the variable just after the modifiers. Process modifiers
     in a specific order, remembering there could be duplicates           */
  modifierLen = lastModifier - firstModifier;
  finaloutput[0] = 0x00;

  /* 1. Handle '~' : Strip surrounding quotes */
  if (outputparam[0]=='"' &&
      memchrW(firstModifier, '~', modifierLen) != NULL) {
    int len = strlenW(outputparam);
    if (outputparam[len-1] == '"') {
        outputparam[len-1]=0x00;
        len = len - 1;
    }
    memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1);
  }

  /* 2. Handle the special case of a $ */
  if (memchrW(firstModifier, '$', modifierLen) != NULL) {
    /* Special Case: Search envar specified in $[envvar] for outputparam
       Note both $ and : are guaranteed otherwise check above would fail */
    WCHAR *begin = strchrW(firstModifier, '$') + 1;
    WCHAR *end   = strchrW(firstModifier, ':');
    WCHAR env[MAX_PATH];
    DWORD size;

    /* Extract the env var */
    memcpy(env, begin, (end-begin) * sizeof(WCHAR));
    env[(end-begin)] = 0x00;

    size = GetEnvironmentVariableW(env, NULL, 0);
    if (size > 0) {
      WCHAR *fullpath = heap_alloc(size * sizeof(WCHAR));
      if (!fullpath || (GetEnvironmentVariableW(env, fullpath, size) == 0) ||
          (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0))
          size = 0;
      heap_free(fullpath);
    }

    if (!size) {
      /* If env var not found, return empty string */
      finaloutput[0] = 0x00;
      outputparam[0] = 0x00;
      skipFileParsing = TRUE;
    }
  }

  /* After this, we need full information on the file,
    which is valid not to exist.  */
  if (!skipFileParsing) {
    if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0) {
      exists = FALSE;
      fullfilename[0] = 0x00;
    } else {
      exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
                                    &fileInfo);
    }

    /* 2. Handle 'a' : Output attributes (File doesn't have to exist) */
    if (memchrW(firstModifier, 'a', modifierLen) != NULL) {

      WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
      doneModifier = TRUE;

      if (exists) {
        strcpyW(thisoutput, defaults);
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
          thisoutput[0]='d';
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
          thisoutput[1]='r';
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
          thisoutput[2]='a';
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
          thisoutput[3]='h';
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
          thisoutput[4]='s';
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
          thisoutput[5]='c';
        /* FIXME: What are 6 and 7? */
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
          thisoutput[8]='l';
        strcatW(finaloutput, thisoutput);
      }
    }

    /* 3. Handle 't' : Date+time (File doesn't have to exist) */
    if (memchrW(firstModifier, 't', modifierLen) != NULL) {

      SYSTEMTIME systime;
      int datelen;

      doneModifier = TRUE;

      if (exists) {
        if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);

        /* Format the time */
        FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
        GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
                          NULL, thisoutput, MAX_PATH);
        strcatW(thisoutput, spaceW);
        datelen = strlenW(thisoutput);
        GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
                          NULL, (thisoutput+datelen), MAX_PATH-datelen);
        strcatW(finaloutput, thisoutput);
      }
    }

    /* 4. Handle 'z' : File length (File doesn't have to exist) */
    if (memchrW(firstModifier, 'z', modifierLen) != NULL) {
      /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
      ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/
                                  fileInfo.nFileSizeLow;
      static const WCHAR fmt[] = {'%','u','\0'};

      doneModifier = TRUE;
      if (exists) {
        if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
        wsprintfW(thisoutput, fmt, fullsize);
        strcatW(finaloutput, thisoutput);
      }
    }

    /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
    if (memchrW(firstModifier, 's', modifierLen) != NULL) {
      if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
      /* Don't flag as doneModifier - %~s on its own is processed later */
      GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0]));
    }

    /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
    /*      Note this overrides d,p,n,x                                 */
    if (memchrW(firstModifier, 'f', modifierLen) != NULL) {
      doneModifier = TRUE;
      if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
      strcatW(finaloutput, fullfilename);
    } else {

      WCHAR drive[10];
      WCHAR dir[MAX_PATH];
      WCHAR fname[MAX_PATH];
      WCHAR ext[MAX_PATH];
      BOOL doneFileModifier = FALSE;
      BOOL addSpace = (finaloutput[0] != 0x00);

      /* Split into components */
      WCMD_splitpath(fullfilename, drive, dir, fname, ext);

      /* 5. Handle 'd' : Drive Letter */
      if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
        if (addSpace) {
          strcatW(finaloutput, spaceW);
          addSpace = FALSE;
        }

        strcatW(finaloutput, drive);
        doneModifier = TRUE;
        doneFileModifier = TRUE;
      }

      /* 6. Handle 'p' : Path */
      if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
        if (addSpace) {
          strcatW(finaloutput, spaceW);
          addSpace = FALSE;
        }

        strcatW(finaloutput, dir);
        doneModifier = TRUE;
        doneFileModifier = TRUE;
      }

      /* 7. Handle 'n' : Name */
      if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
        if (addSpace) {
          strcatW(finaloutput, spaceW);
          addSpace = FALSE;
        }

        strcatW(finaloutput, fname);
        doneModifier = TRUE;
        doneFileModifier = TRUE;
      }

      /* 8. Handle 'x' : Ext */
      if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
        if (addSpace) {
          strcatW(finaloutput, spaceW);
          addSpace = FALSE;
        }

        strcatW(finaloutput, ext);
        doneModifier = TRUE;
        doneFileModifier = TRUE;
      }

      /* If 's' but no other parameter, dump the whole thing */
      if (!doneFileModifier &&
          memchrW(firstModifier, 's', modifierLen) != NULL) {
        doneModifier = TRUE;
        if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
        strcatW(finaloutput, outputparam);
      }
    }
  }

  /* If No other modifier processed,  just add in parameter */
  if (!doneModifier) strcpyW(finaloutput, outputparam);

  /* Finish by inserting the replacement into the string */
  WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1);
}
Exemple #24
0
/*
 * Main function
 */
int wmain(int argc, WCHAR *argv[])
{
    LPSTR (*CDECL wine_get_unix_file_name_ptr)(LPCWSTR) = NULL;
    LPWSTR (*CDECL wine_get_dos_file_name_ptr)(LPCSTR) = NULL;
    WCHAR dos_pathW[MAX_PATH];
    char path[MAX_PATH];
    int outputformats;
    int i;

    outputformats = parse_options(argv);
    if (outputformats == 0)
        outputformats = UNIXFORMAT;

    if (outputformats & UNIXFORMAT) {
        wine_get_unix_file_name_ptr = (void*)
            GetProcAddress(GetModuleHandleA("KERNEL32"),
                           "wine_get_unix_file_name");
        if (wine_get_unix_file_name_ptr == NULL) {
            fprintf(stderr, "%s: cannot get the address of "
                            "'wine_get_unix_file_name'\n", progname);
            exit(3);
        }
    }

    if (outputformats & WINDOWSFORMAT) {
        wine_get_dos_file_name_ptr = (void*)
            GetProcAddress(GetModuleHandleA("KERNEL32"),
                           "wine_get_dos_file_name");
        if (wine_get_dos_file_name_ptr == NULL) {
            fprintf(stderr, "%s: cannot get the address of "
                            "'wine_get_dos_file_name'\n", progname);
            exit(3);
        }
    }

    for (i = 1; argv[i]; i++)
    {
        *path='\0';
        if (outputformats & LONGFORMAT) {
            if (GetLongPathNameW(argv[i], dos_pathW, MAX_PATH))
                WideCharToMultiByte(CP_UNIXCP, 0, dos_pathW, -1, path, MAX_PATH, NULL, NULL);
            printf("%s\n", path);
        }
        if (outputformats & SHORTFORMAT) {
            if (GetShortPathNameW(argv[i], dos_pathW, MAX_PATH))
                WideCharToMultiByte(CP_UNIXCP, 0, dos_pathW, -1, path, MAX_PATH, NULL, NULL);
            printf("%s\n", path);
        }
        if (outputformats & UNIXFORMAT) {
            WCHAR *ntpath, *tail;
            int ntpathlen=lstrlenW(argv[i]);
            ntpath=HeapAlloc(GetProcessHeap(), 0, sizeof(*ntpath)*(ntpathlen+1));
            lstrcpyW(ntpath, argv[i]);
            tail=NULL;
            while (1)
            {
                char *unix_name;
                WCHAR *slash, *c;

                unix_name = wine_get_unix_file_name_ptr(ntpath);
                if (unix_name)
                {
                    if (tail)
                    {
                        WideCharToMultiByte(CP_UNIXCP, 0, tail+1, -1, path, MAX_PATH, NULL, NULL);
                        printf("%s/%s\n", unix_name, path);
                    }
                    else
                    {
                        printf("%s\n", unix_name);
                    }
                    HeapFree( GetProcessHeap(), 0, unix_name );
                    break;
                }

                slash=(tail ? tail : ntpath+ntpathlen);
                while (slash != ntpath && *slash != '/' && *slash != '\\')
                    slash--;
                if (slash == ntpath)
                {
                    /* This is a complete path conversion failure.
                     * It would typically happen if ntpath == "".
                     */
                    printf("\n");
                    break;
                }
                c=slash+1;
                while (*c != '\0' && *c != '*' && *c != '?' &&
                       *c != '<' && *c != '>' && *c != '|' && *c != '"')
                    c++;
                if (*c != '\0')
                {
                    /* If this is not a valid NT path to start with,
                     * then obviously we cannot convert it.
                     */
                    printf("\n");
                    break;
                }
                if (tail)
                    *tail='/';
                tail=slash;
                *tail='\0';
            }
            HeapFree(GetProcessHeap(), 0, ntpath);
        }
        if (outputformats & WINDOWSFORMAT) {
            WCHAR* windows_name;
            char* unix_name;
            DWORD size;

            size=WideCharToMultiByte(CP_UNIXCP, 0, argv[i], -1, NULL, 0, NULL, NULL);
            unix_name=HeapAlloc(GetProcessHeap(), 0, size);
            WideCharToMultiByte(CP_UNIXCP, 0, argv[i], -1, unix_name, size, NULL, NULL);

            if ((windows_name = wine_get_dos_file_name_ptr(unix_name)))
            {
                WideCharToMultiByte(CP_UNIXCP, 0, windows_name, -1, path, MAX_PATH, NULL, NULL);
                printf("%s\n", path);
                HeapFree( GetProcessHeap(), 0, windows_name );
            }
            else printf( "\n" );
            HeapFree( GetProcessHeap(), 0, unix_name );
        }
    }

    exit(0);
}
int uv_fs_event_start(uv_fs_event_t* handle,
                      uv_fs_event_cb cb,
                      const char* path,
                      unsigned int flags) {
  int name_size, is_path_dir;
  DWORD attr, last_error;
  WCHAR* dir = NULL, *dir_to_watch, *pathw = NULL;
  WCHAR short_path[MAX_PATH];

  if (uv__is_active(handle))
    return UV_EINVAL;

  handle->cb = cb;
  handle->path = uv__strdup(path);
  if (!handle->path) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
  }

  uv__handle_start(handle);

  /* Convert name to UTF16. */
  name_size = uv_utf8_to_utf16(path, NULL, 0) * sizeof(WCHAR);
  pathw = (WCHAR*)uv__malloc(name_size);
  if (!pathw) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
  }

  if (!uv_utf8_to_utf16(path, pathw,
      name_size / sizeof(WCHAR))) {
    return uv_translate_sys_error(GetLastError());
  }

  /* Determine whether path is a file or a directory. */
  attr = GetFileAttributesW(pathw);
  if (attr == INVALID_FILE_ATTRIBUTES) {
    last_error = GetLastError();
    goto error;
  }

  is_path_dir = (attr & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0;

  if (is_path_dir) {
     /* path is a directory, so that's the directory that we will watch. */
    handle->dirw = pathw;
    dir_to_watch = pathw;
  } else {
    /*
     * path is a file.  So we split path into dir & file parts, and
     * watch the dir directory.
     */

    /* Convert to short path. */
    if (!GetShortPathNameW(pathw, short_path, ARRAY_SIZE(short_path))) {
      last_error = GetLastError();
      goto error;
    }

    if (uv_split_path(pathw, &dir, &handle->filew) != 0) {
      last_error = GetLastError();
      goto error;
    }

    if (uv_split_path(short_path, NULL, &handle->short_filew) != 0) {
      last_error = GetLastError();
      goto error;
    }

    dir_to_watch = dir;
    uv__free(pathw);
    pathw = NULL;
  }

  handle->dir_handle = CreateFileW(dir_to_watch,
                                   FILE_LIST_DIRECTORY,
                                   FILE_SHARE_READ | FILE_SHARE_DELETE |
                                     FILE_SHARE_WRITE,
                                   NULL,
                                   OPEN_EXISTING,
                                   FILE_FLAG_BACKUP_SEMANTICS |
                                     FILE_FLAG_OVERLAPPED,
                                   NULL);

  if (dir) {
    uv__free(dir);
    dir = NULL;
  }

  if (handle->dir_handle == INVALID_HANDLE_VALUE) {
    last_error = GetLastError();
    goto error;
  }

  if (CreateIoCompletionPort(handle->dir_handle,
                             handle->loop->iocp,
                             (ULONG_PTR)handle,
                             0) == NULL) {
    last_error = GetLastError();
    goto error;
  }

  if (!handle->buffer) {
    handle->buffer = (char*)uv__malloc(uv_directory_watcher_buffer_size);
  }
  if (!handle->buffer) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "uv__malloc");
  }

  memset(&(handle->req.u.io.overlapped), 0,
         sizeof(handle->req.u.io.overlapped));

  if (!ReadDirectoryChangesW(handle->dir_handle,
                             handle->buffer,
                             uv_directory_watcher_buffer_size,
                             (flags & UV_FS_EVENT_RECURSIVE) ? TRUE : FALSE,
                             FILE_NOTIFY_CHANGE_FILE_NAME      |
                               FILE_NOTIFY_CHANGE_DIR_NAME     |
                               FILE_NOTIFY_CHANGE_ATTRIBUTES   |
                               FILE_NOTIFY_CHANGE_SIZE         |
                               FILE_NOTIFY_CHANGE_LAST_WRITE   |
                               FILE_NOTIFY_CHANGE_LAST_ACCESS  |
                               FILE_NOTIFY_CHANGE_CREATION     |
                               FILE_NOTIFY_CHANGE_SECURITY,
                             NULL,
                             &handle->req.u.io.overlapped,
                             NULL)) {
    last_error = GetLastError();
    goto error;
  }

  handle->req_pending = 1;
  return 0;

error:
  if (handle->path) {
    uv__free(handle->path);
    handle->path = NULL;
  }

  if (handle->filew) {
    uv__free(handle->filew);
    handle->filew = NULL;
  }

  if (handle->short_filew) {
    uv__free(handle->short_filew);
    handle->short_filew = NULL;
  }

  uv__free(pathw);

  if (handle->dir_handle != INVALID_HANDLE_VALUE) {
    CloseHandle(handle->dir_handle);
    handle->dir_handle = INVALID_HANDLE_VALUE;
  }

  if (handle->buffer) {
    uv__free(handle->buffer);
    handle->buffer = NULL;
  }

  return uv_translate_sys_error(last_error);
}
Exemple #26
0
static gchar *
get_session_address_dbus_launch (GError **error)
{
  HANDLE autolaunch_mutex, init_mutex;
  char *address = NULL;
  wchar_t gio_path[MAX_PATH+1+200];

  autolaunch_mutex = acquire_mutex (DBUS_AUTOLAUNCH_MUTEX);

  init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);

  if (is_mutex_owned (DBUS_DAEMON_MUTEX))
    address = read_shm (DBUS_DAEMON_ADDRESS_INFO);

  release_mutex (init_mutex);

  if (address == NULL)
    {
      gio_path[MAX_PATH] = 0;
      if (GetModuleFileNameW (_g_io_win32_get_module (), gio_path, MAX_PATH))
	{
	  PROCESS_INFORMATION pi = { 0 };
	  STARTUPINFOW si = { 0 };
	  BOOL res;
	  wchar_t gio_path_short[MAX_PATH];
	  wchar_t rundll_path[MAX_PATH*2];
	  wchar_t args[MAX_PATH*4];

	  GetShortPathNameW (gio_path, gio_path_short, MAX_PATH);

	  GetWindowsDirectoryW (rundll_path, MAX_PATH);
	  wcscat (rundll_path, L"\\rundll32.exe");
	  if (GetFileAttributesW (rundll_path) == INVALID_FILE_ATTRIBUTES)
	    {
	      GetSystemDirectoryW (rundll_path, MAX_PATH);
	      wcscat (rundll_path, L"\\rundll32.exe");
	    }

	  wcscpy (args, L"\"");
	  wcscat (args, rundll_path);
	  wcscat (args, L"\" ");
	  wcscat (args, gio_path_short);
#if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)
	  wcscat (args, L",g_win32_run_session_bus");
#elif defined (_MSC_VER)
	  wcscat (args, L",_g_win32_run_session_bus@16");
#else
	  wcscat (args, L",g_win32_run_session_bus@16");
#endif

	  res = CreateProcessW (rundll_path, args,
				0, 0, FALSE,
				NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | DETACHED_PROCESS,
				0, NULL /* TODO: Should be root */,
				&si, &pi);
	  if (res)
	    address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
	}
    }

  release_mutex (autolaunch_mutex);

  if (address == NULL)
    g_set_error (error,
		 G_IO_ERROR,
		 G_IO_ERROR_FAILED,
		 _("Session dbus not running, and autolaunch failed"));

  return address;
}
Exemple #27
0
Boolean FskSSLCheckServerCert(SSL *ssl, char *hostname) {
	long err;
	X509 *peer;
	char peer_CN[256];
	err = SSL_get_verify_result(ssl);
#if 0
	if ((err != X509_V_OK)
		&& (err != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
		&& (err != X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)) {
		ERR_print_errors_fp(stderr);
fprintf(stderr, "[%s] cert for %s didn't verify %d %s\n", threadTag(FskThreadGetCurrent()), hostname, err, X509_verify_cert_error_string(err));
#else
	if (err != X509_V_OK) {
		if ((NULL != FskStrStr(hostname, "google.com")) 
			|| (NULL != FskStrStr(hostname, "googleapis.com")) 
			|| (NULL != FskStrStr(hostname, "twitter.com"))
			|| (NULL != FskStrStr(hostname, "yammer.com"))
			|| (NULL != FskStrStr(hostname, "facebook.com"))
			|| (NULL != FskStrStr(hostname, "foursquare.com"))
			|| (NULL != FskStrStr(hostname, "akamaihd.net"))
			|| (NULL != FskStrStr(hostname, "fbcdn.net"))
			|| (NULL != FskStrStr(hostname, "radiotime.com"))
			|| (NULL != FskStrStr(hostname, "s3.amazonaws.com"))
			|| (NULL != FskStrStr(hostname, "orb.com"))) {
			if ((err != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
				&& (err != X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)) {
				return false;
			}
			myprintf((stderr, "b) cert didn't verify because %d %s\n", err, X509_verify_cert_error_string(err)));
			myprintf((stderr, " but since it's %s we'll let it through\n", hostname));
		}
		else {
#endif
			return false;
		}
	}

	peer = SSL_get_peer_certificate(ssl);
	X509_NAME_get_text_by_NID(X509_get_subject_name(peer), NID_commonName,
						peer_CN, 256);
//fprintf(stderr, "comparing peer_CN %s with hostname %s\n", peer_CN, hostname);
	if (FskStrCompareCaseInsensitive(peer_CN, hostname)) {
		int pos, L, subL;
		char *match = peer_CN + 1;

		subL = FskStrLen(match);
		L = FskStrLen(hostname);
		if (peer_CN[0] == '*') {
			pos = L - subL;
			if (0 == FskStrCompareCaseInsensitive(match, hostname + pos)) {
//fprintf(stderr, "Matched wildcard %s and %s\n", match, hostname + pos);
				return true;
			}
		}

		if (	(FskStrEndsWith(match, "akamaihd.net")
				&& FskStrEndsWith(hostname, "akamai.net")) 
			||	(FskStrEndsWith(match, "akamai.net")
				&& FskStrEndsWith(hostname, "akamaihd.net")) ) {
			return true;
		}
			
	

		myprintf((stderr, "cert common name %s and host %s don't match\n", peer_CN, hostname));
		return false;
	}

	return true;
}

//SSL_CTX *FskSSLInitialize(char *keyfile, char *password)
static SSL_CTX *FskOpenSSLInitialize(const char *calistpath)
{
	SSL_METHOD	*method;
	SSL_CTX		*context;

	if (gSSLContext) {
		return gSSLContext;
	}
	else {
		SSL_library_init();
		SSL_load_error_strings();			// not necessary, but useful
	}

	method = SSLv23_method();
	context = SSL_CTX_new(method);

#if 0
	if (FskStrLen(keyfile) > 0) {
		keyfile = FskEnvironmentDoApply(FskStrDoCopy(keyfile));
		if (!SSL_CTX_use_certificate_chain_file(context, keyfile))
			doSSLError("Can't read certificate file");
		fprintf(stderr, "keyfile is %s\n", keyfile);

		if (FskStrLen(password) > 0) {
			gSSLPassword = FskStrDoCopy(password);
			SSL_CTX_set_default_passwd_cb(context, passwordCallback);
			if (!SSL_CTX_use_PrivateKey_file(context, keyfile, SSL_FILETYPE_PEM))
				doSSLError( "Can't read private keyfile");
		}

		FskMemPtrDispose(keyfile);
	}
#endif

#if TARGET_OS_WIN32
	{
	// try to make the path 8.3 safe to avoid nightmares with multibyte character paths, etc.
	UInt16 *nativePath;

	if (kFskErrNone == FskFilePathToNative(calistpath, (char **)&nativePath)) {
		DWORD shortLen;

		shortLen = GetShortPathNameW(nativePath, NULL, 0);
		if (0 != shortLen) {
			UInt16 *eightDotThree;

			if (kFskErrNone == FskMemPtrNewClear(shortLen * 2, (FskMemPtr *)&eightDotThree)) {
				if (0 != GetShortPathNameW(nativePath, eightDotThree, shortLen)) {
					char *utf8;
					UInt32 utf8Len;

					if (kFskErrNone == FskTextUnicode16LEToUTF8(eightDotThree, shortLen * 2, &utf8, &utf8Len)) {
						char *enc;

						if (kFskErrNone == FskTextToPlatform(utf8, utf8Len, &enc, NULL)) {
							FskMemPtrDispose(calistpath);
							calistpath = enc;
						}
						FskMemPtrDispose(utf8);
					}
				}
				FskMemPtrDispose(eightDotThree);
			}
		}
		FskMemPtrDispose(nativePath);
	}
	}
#endif

	if (!(SSL_CTX_load_verify_locations(context, calistpath, 0))) {
		doSSLError("Can't read default CA list");
	}

	SSL_CTX_set_verify_depth(context, 0);

//	SSL_CTX_set_verify(context, SSL_VERIFY_PEER, 0);

	gSSLContext = context;

	return context;
}
Exemple #28
0
static void
setup (void)
{
  char *full_prefix = NULL;
  char *cp_prefix; 

  wchar_t wcbfr[1000];
  
  G_LOCK (mutex);
  if (locale_dir != NULL)
    {
      G_UNLOCK (mutex);
      return;
    }

  if (GetModuleFileNameW (hmodule, wcbfr, G_N_ELEMENTS (wcbfr)))
    {
      full_prefix = g_utf16_to_utf8 (wcbfr, -1, NULL, NULL, NULL);
      if (GetShortPathNameW (wcbfr, wcbfr, G_N_ELEMENTS (wcbfr)))
	cp_prefix = g_utf16_to_utf8 (wcbfr, -1, NULL, NULL, NULL);
      else if (full_prefix)
	cp_prefix = g_locale_from_utf8 (full_prefix, -1, NULL, NULL, NULL);
    }

  if (full_prefix != NULL)
    {
      gchar *p = strrchr (full_prefix, '\\');
      if (p != NULL)
	*p = '\0';

      p = strrchr (full_prefix, '\\');
      if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
	*p = '\0';
		  
      /* Replace backslashes with forward slashes to avoid
       * problems for instance in makefiles that use
       * gconftool-2 --get-default-source.
       */
      while ((p = strchr (full_prefix, '\\')) != NULL)
	*p = '/';

      runtime_prefix = full_prefix;
    }
  else
    {
      runtime_prefix = g_strdup ("");
    }

  if (cp_prefix != NULL)
    {
      gchar *p = _mbsrchr (cp_prefix, '\\');
      if (p != NULL)
	*p = '\0';
      
      p = _mbsrchr (cp_prefix, '\\');
      if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
	*p = '\0';
    }
  else
    {
      cp_prefix = g_strdup ("");
    }

  locale_dir = g_strconcat (cp_prefix, GCONF_LOCALE_DIR + strlen (PREFIX), NULL);

  confdir = _gconf_win32_replace_prefix (GCONF_CONFDIR);
  etcdir = _gconf_win32_replace_prefix (GCONF_ETCDIR);
  serverdir = _gconf_win32_replace_prefix (GCONF_SERVERDIR);
  backend_dir = _gconf_win32_replace_prefix (GCONF_BACKEND_DIR);

  G_UNLOCK (mutex);
}
Exemple #29
0
/*
 * Return full path to the current executable.
 * Executable is the .exe created by pyinstaller: path/myappname.exe
 *
 * execfile - buffer where to put path to executable.
 * appname - usually the item argv[0].
 */
int pyi_path_executable(char *execfile, const char *appname)
{
    char buffer[PATH_MAX];

#ifdef WIN32
    char dos83_buffer[PATH_MAX];
    stb__wchar wchar_buffer[PATH_MAX];
    stb__wchar wchar_dos83_buffer[PATH_MAX];
    char basename[PATH_MAX];
    char dirname[PATH_MAX];

    /* Windows has special function to obtain path to executable.
     * We EXPLICTLY use wide-string API in the bootloader because
     * otherwise it is impossible to represent non-ASCII character
     * from a different character set. For instance, let's say I have
     * a Latin-1 (Europe Windows), and I want to run a PyInstaller
     * program in a path with japanese character; there is no way to
     * represent that path with ANSI API in Windows, because ANSI API
     * would only support the local charset (Latin-1).
     */
	if (!GetModuleFileNameW(NULL, wchar_buffer, PATH_MAX)) {
		FATALERROR("System error - unable to load!");
		return -1;
	}
    /* Convert wchar_t to utf8. Just use type char as usual. */
    stb_to_utf8(buffer, wchar_buffer, PATH_MAX);

    /*
     * Use 8.3 filename (dos 8.3 or short filename)
     * to overcome the Python and PyInstaller limitation
     * to run with foreign characters in directory names.
     *
     * If 8.3 filename does not exist, original vaule is just copied
     * to the supplied buffer. 8.3 filename might not be available
     * for some networking file systems.
     *
     * This is workaround for <http://www.pyinstaller.org/ticket/298>.
     */
    GetShortPathNameW(wchar_buffer, wchar_dos83_buffer, PATH_MAX);
    /* Convert wchar_t to utf8 just use char as usual. */
    stb_to_utf8(dos83_buffer, wchar_dos83_buffer, PATH_MAX);

    /*
     * Construct proper execfile -  83_DIRNAME + full_basename.
     * GetShortPathName() makes also the basename (appname.exe) shorter.
     *
     * However, bootloader code depends on unmodified basename.
     * Using basename from original path should fix this.
     * It is supposed that basename does not contain any foreign characters.
     *
     * Reuse 'buffer' variable.
     */
    pyi_path_basename(basename, buffer);
    pyi_path_dirname(dirname, dos83_buffer);
    pyi_path_join(buffer, dirname, basename);

#elif __APPLE__
    uint32_t length = sizeof(buffer);

    /* Mac OS X has special function to obtain path to executable. */
    if (_NSGetExecutablePath(buffer, &length) != 0) {
        FATALERROR("System error - unable to load!");
		return -1;
    }
#else
    /* Fill in thisfile. */
    #ifdef __CYGWIN__
    if (strncasecmp(&appname[strlen(appname)-4], ".exe", 4)) {
        strcpy(execfile, appname);
        strcat(execfile, ".exe");
        PI_SetProgramName(execfile);
    }
    else
    #endif /* __CYGWIN__ */
    PI_SetProgramName(appname);
    strcpy(buffer, PI_GetProgramFullPath());
#endif
    /*
     * Ensure path to executable is absolute.
     * 'execfile' starting with ./ might break some modules when changing
     * the CWD.From 'execfile' is constructed 'homepath' and homepath is used
     * for LD_LIBRARY_PATH variavle. Relative LD_LIBRARY_PATH is a security
     * problem.
     */
    if(stb_fullpath(execfile, PATH_MAX, buffer) == false) {
        VS("LOADER: executable is %s\n", execfile);
        return -1;
    }
 
    VS("LOADER: executable is %s\n", execfile);

	return 0;
}
Exemple #30
0
int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle,
    const char* filename, uv_fs_event_cb cb) {
  int name_size;
  DWORD attr, last_error;
  wchar_t* dir = NULL, *dir_to_watch, *filenamew;
  wchar_t short_path[MAX_PATH];

  uv_fs_event_init_handle(loop, handle, filename, cb);

  /* Convert name to UTF16. */
  name_size = uv_utf8_to_utf16(filename, NULL, 0) * sizeof(wchar_t);
  filenamew = (wchar_t*)malloc(name_size);
  if (!filenamew) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
  }

  if (!uv_utf8_to_utf16(filename, filenamew, 
      name_size / sizeof(wchar_t))) {
    uv__set_sys_error(loop, GetLastError());
    return -1;
  }

  /* Determine whether filename is a file or a directory. */
  attr = GetFileAttributesW(filenamew);
  if (attr == INVALID_FILE_ATTRIBUTES) {
    last_error = GetLastError();
    goto error;
  }

  handle->is_path_dir = (attr & FILE_ATTRIBUTE_DIRECTORY) ? 1 : 0;

  if (handle->is_path_dir) {
     /* filename is a directory, so that's the directory that we will watch. */
    dir_to_watch = filenamew;
  } else {
    /* 
     * filename is a file.  So we split filename into dir & file parts, and
     * watch the dir directory.
     */
    
    /* Convert to short path. */
    if (!GetShortPathNameW(filenamew, short_path, COUNTOF(short_path))) {
      last_error = GetLastError();
      goto error;
    }

    if (uv_split_path(filenamew, &dir, &handle->filew) != 0) {
      last_error = GetLastError();
      goto error;
    }

    if (uv_split_path(short_path, NULL, &handle->short_filew) != 0) {
      last_error = GetLastError();
      goto error;
    }

    dir_to_watch = dir;
  }

  handle->dir_handle = CreateFileW(dir_to_watch,
                                   FILE_LIST_DIRECTORY,
                                   FILE_SHARE_READ | FILE_SHARE_DELETE |
                                     FILE_SHARE_WRITE,
                                   NULL,
                                   OPEN_EXISTING,
                                   FILE_FLAG_BACKUP_SEMANTICS |
                                     FILE_FLAG_OVERLAPPED,
                                   NULL);

  if (dir) {
    free(dir);
    dir = NULL;
  }

  if (handle->dir_handle == INVALID_HANDLE_VALUE) {
    last_error = GetLastError();
    goto error;
  }

  if (CreateIoCompletionPort(handle->dir_handle,
                             loop->iocp,
                             (ULONG_PTR)handle,
                             0) == NULL) {
    last_error = GetLastError();
    goto error;
  }

  handle->buffer = (char*)_aligned_malloc(uv_directory_watcher_buffer_size, 
    sizeof(DWORD));
  if (!handle->buffer) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
  }

  memset(&(handle->req.overlapped), 0, sizeof(handle->req.overlapped));

  if (!ReadDirectoryChangesW(handle->dir_handle,
                             handle->buffer,
                             uv_directory_watcher_buffer_size,
                             FALSE,
                             FILE_NOTIFY_CHANGE_FILE_NAME      |
                               FILE_NOTIFY_CHANGE_DIR_NAME     |
                               FILE_NOTIFY_CHANGE_ATTRIBUTES   |
                               FILE_NOTIFY_CHANGE_SIZE         |
                               FILE_NOTIFY_CHANGE_LAST_WRITE   |
                               FILE_NOTIFY_CHANGE_LAST_ACCESS  |
                               FILE_NOTIFY_CHANGE_CREATION     |
                               FILE_NOTIFY_CHANGE_SECURITY,
                             NULL,
                             &handle->req.overlapped,
                             NULL)) {
    last_error = GetLastError();
    goto error;
  }

  handle->req_pending = 1;
  return 0;

error:
  if (handle->filename) {
    free(handle->filename);
    handle->filename = NULL;
  }

  if (handle->filew) {
    free(handle->filew);
    handle->filew = NULL;
  }

  if (handle->short_filew) {
    free(handle->short_filew);
    handle->short_filew = NULL;
  }

  if (handle->dir_handle != INVALID_HANDLE_VALUE) {
    CloseHandle(handle->dir_handle);
    handle->dir_handle = INVALID_HANDLE_VALUE;
  }

  if (handle->buffer) {
    _aligned_free(handle->buffer);
    handle->buffer = NULL;
  }

  uv__set_sys_error(loop, last_error);
  return -1;
}