Exemplo n.º 1
0
static HRESULT WINAPI InstallCallback_OnStopBinding(IBindStatusCallback *iface,
        HRESULT hresult, LPCWSTR szError)
{
    if(dwl_binding) {
        IBinding_Release(dwl_binding);
        dwl_binding = NULL;
    }

    if(FAILED(hresult)) {
        if(hresult == E_ABORT)
            TRACE("Binding aborted\n");
        else
            ERR("Binding failed %08x\n", hresult);
        return S_OK;
    }

    if(!msi_file) {
        ERR("No MSI file\n");
        return E_FAIL;
    }

    set_status(IDS_INSTALLING);
    EnableWindow(GetDlgItem(install_dialog, IDCANCEL), 0);

    if(sha_check(msi_file)) {
        WCHAR *cache_file_name;

        install_file(msi_file);

        cache_file_name = get_cache_file_name(TRUE);
        if(cache_file_name) {
            MoveFileW(msi_file, cache_file_name);
            heap_free(cache_file_name);
        }
    }else {
        WCHAR message[256];

        if(LoadStringW(hInst, IDS_INVALID_SHA, message, sizeof(message)/sizeof(WCHAR)))
            MessageBoxW(NULL, message, NULL, MB_ICONERROR);
    }

    DeleteFileW(msi_file);
    heap_free(msi_file);
    msi_file = NULL;

    EndDialog(install_dialog, 0);
    return S_OK;
}
Exemplo n.º 2
0
bool move(const Path& from, const Path& to)
{
    if( from.is_empty() || to.is_empty() )
    {
        LOGW("trying to move file with empty path.");
        return false;
    }

#ifdef PLATFORM_WIN32
    auto from_wstr = to_win32(from.c_str());
    auto to_wstr = to_win32(to.c_str());
    return MoveFileW(from_wstr.c_str(), to_wstr.c_str()) != 0;
#else
    return std::rename(from.c_str(), to.c_str()) == 0;
#endif
}
Exemplo n.º 3
0
bool RelocateFileOrDirectory(const char* from, const char* to)
{
    AWS_LOGSTREAM_INFO(FILE_SYSTEM_UTILS_LOG_TAG, "Moving file at " << from << " to " << to);

    if(MoveFileW(ToLongPath(Aws::Utils::StringUtils::ToWString(from)).c_str(), Aws::Utils::StringUtils::ToWString(to).c_str()))
    {
        AWS_LOGSTREAM_DEBUG(FILE_SYSTEM_UTILS_LOG_TAG,  "The moving operation of file at " << from << " to " << to << " Succeeded.");
        return true;
    }
    else
    {
        int errorCode = GetLastError();
        AWS_LOGSTREAM_DEBUG(FILE_SYSTEM_UTILS_LOG_TAG,  "The moving operation of file at " << from << " to " << to << " Returned error code of " << errorCode);
        return false;
    }
}
Exemplo n.º 4
0
sqInt sqFileRenameOldSizeNewSize(char* oldNameIndex, sqInt oldNameSize, char* newNameIndex, sqInt newNameSize)
{
  WCHAR *oldPath = NULL;
  WCHAR *newPath = NULL;

  /* convert the file names into a null-terminated C string */
  ALLOC_WIN32_PATH(oldPath, oldNameIndex, oldNameSize);
  ALLOC_WIN32_PATH(newPath, newNameIndex, newNameSize);

  if(hasCaseSensitiveDuplicate(oldPath))
    FAIL();
  if(!MoveFileW(oldPath, newPath))
    FAIL();
  
  return 1;
}
Exemplo n.º 5
0
int _rename(const char *oldname, const char *newname)
{
	wchar_t *wold, *wnew;
	BOOL rc;

	wold = wce_mbtowc(oldname);
	wnew = wce_mbtowc(newname);

	/* replace with MoveFile. */
	rc = MoveFileW(wold, wnew);

	free(wold);
	free(wnew);

	return rc==TRUE ? 0 : -1;
}
Exemplo n.º 6
0
bool fs::rename(const std::string& from, const std::string& to)
{
	g_tls_error = fse::ok;

#ifdef _WIN32
	if (!MoveFileW(to_wchar(from).get(), to_wchar(to).get()))
#else
	if (rename(from.c_str(), to.c_str()))
#endif
	{
		LOG_WARNING(GENERAL, "Error renaming '%s' to '%s': 0x%llx", from, to, GET_API_ERROR);
		return false;
	}

	return true;
}
Exemplo n.º 7
0
BOOL MoveFileEx(LPCSTR oldname, LPCSTR newname, DWORD dwFlags)
{
	LPWSTR woldname, wnewname;
	BOOL b;

	woldname = wce_mbtowc(oldname);
	wnewname = wce_mbtowc(newname);

	if( (dwFlags&MOVEFILE_REPLACE_EXISTING)!=0 )
		DeleteFileW( wnewname );

	b = MoveFileW( woldname, wnewname );

	free(woldname);
	free(wnewname);

	return b;
}
	void DeleteFltkPreference() {
		auto path = GetFltkPreferencePath();
		/*
#ifdef WIN32
		DeleteFileW(Utf8ToWString(path.c_str()).c_str());
#else
		unlink(path.c_str());
#endif
		*/
		
		// afraid of removing the pref file completely
		SPLog("Moving %s to %s", path.c_str(), (path + "-old").c_str());
#ifdef WIN32
		auto s = Utf8ToWString(path.c_str());
		MoveFileW(s.c_str(), (s + L"-old").c_str());
#else
		rename(path.c_str(), (path + "-old").c_str());
#endif
	}
Exemplo n.º 9
0
/**
 * The rename function updates the filename.
 */
int pcsl_file_rename(const pcsl_string * oldName, 
                     const pcsl_string * newName)
{
    int status = -1;
    const jchar * pszOldFilename = pcsl_string_get_utf16_data(oldName);
    const jchar * pszNewFilename = pcsl_string_get_utf16_data(newName);

    if ((NULL != pszOldFilename) && (NULL != pszNewFilename)) {
        status = MoveFileW(pszOldFilename, pszNewFilename) ? 0 : -1;
    }

    if (pszNewFilename)
        pcsl_string_release_utf16_data(pszNewFilename, newName);

    if (pszOldFilename)
        pcsl_string_release_utf16_data(pszOldFilename, oldName);

    return status;
}
Exemplo n.º 10
0
/*
 * __win_fs_rename --
 *	Rename a file.
 */
static int
__win_fs_rename(WT_FILE_SYSTEM *file_system,
    WT_SESSION *wt_session, const char *from, const char *to, uint32_t flags)
{
	DWORD windows_error;
	WT_DECL_RET;
	WT_DECL_ITEM(from_wide);
	WT_DECL_ITEM(to_wide);
	WT_SESSION_IMPL *session;

	WT_UNUSED(file_system);
	WT_UNUSED(flags);
	session = (WT_SESSION_IMPL *)wt_session;

	WT_ERR(__wt_to_utf16_string(session, from, &from_wide));
	WT_ERR(__wt_to_utf16_string(session, to, &to_wide));

	/*
	 * Check if file exists since Windows does not override the file if
	 * it exists.
	 */
	if (GetFileAttributesW(to_wide->data) != INVALID_FILE_ATTRIBUTES)
		if (DeleteFileW(to_wide->data) == FALSE) {
			windows_error = __wt_getlasterror();
			__wt_errx(session,
			    "%s: file-rename: DeleteFileW: %s",
			    to, __wt_formatmessage(session, windows_error));
			WT_ERR(__wt_map_windows_error(windows_error));
		}

	if (MoveFileW(from_wide->data, to_wide->data) == FALSE) {
		windows_error = __wt_getlasterror();
		__wt_errx(session,
		    "%s to %s: file-rename: MoveFileW: %s",
		    from, to, __wt_formatmessage(session, windows_error));
		WT_ERR(__wt_map_windows_error(windows_error));
	}

err:	__wt_scr_free(session, &from_wide);
	__wt_scr_free(session, &to_wide);
	return (ret);
}
Exemplo n.º 11
0
//---------------------------------------------------------------------------
bool File::Move(const Ztring &Source, const Ztring &Destination, bool OverWrite)
{
    if (OverWrite && Exists(Source))
        Delete(Destination);
    #ifdef ZENLIB_USEWX
        if (OverWrite && Exists(Destination))
            wxRemoveFile(Destination.c_str());
        return wxRenameFile(Source.c_str(), Destination.c_str());
    #else //ZENLIB_USEWX
        #ifdef ZENLIB_STANDARD
            return !std::rename(Source.To_Local().c_str(), Destination.To_Local().c_str());
        #elif defined WINDOWS
            #ifdef UNICODE
                return MoveFileW(Source.c_str(), Destination.c_str())!=0;
            #else
                return MoveFile(Source.c_str(), Destination.c_str())!=0;
            #endif //UNICODE
        #endif
    #endif //ZENLIB_USEWX
}
Exemplo n.º 12
0
int fs_move(const char *oldpath, const char *newpath)
{
	int rc = ERROR_SUCCESS;
	wchar_t *old_w = utf8_to_wchar(oldpath);
	wchar_t *new_w = utf8_to_wchar(newpath);

	if ((old_w == NULL) || (new_w == NULL)) {
		rc = GetLastError();
		goto out;
	}

	if (MoveFileW(old_w, new_w) == 0) {
		rc = GetLastError();
	}

out:
	free(old_w);
	free(new_w);
	return rc;
}
Exemplo n.º 13
0
BOOL MoveFileUTF8(LPCTSTR existfn, LPCTSTR newfn)
{
  if ((WDL_HasUTF8(existfn)||WDL_HasUTF8(newfn)) AND_IS_NOT_WIN9X)
  {
    MBTOWIDE(wbuf,existfn);
    if (wbuf_ok)
    {
      MBTOWIDE(wbuf2,newfn);
      if (wbuf2_ok)
      {
        int rv=MoveFileW(wbuf,wbuf2);
        MBTOWIDE_FREE(wbuf2);
        MBTOWIDE_FREE(wbuf);
        return rv;
      }
      MBTOWIDE_FREE(wbuf2);
    }
    MBTOWIDE_FREE(wbuf);
  }
  return MoveFileA(existfn,newfn);
}
Exemplo n.º 14
0
BOOL MoveFileUTF8(LPCTSTR existfn, LPCTSTR newfn)
{
  if ((WDL_HasUTF8(existfn)||WDL_HasUTF8(newfn)) && GetVersion()< 0x80000000)
  {
    MBTOWIDE(wbuf,existfn);
    if (wbuf_ok)
    {
      MBTOWIDE(wbuf2,newfn);
      if (wbuf2_ok)
      {
        int rv=MoveFileW(wbuf,wbuf2);
        MBTOWIDE_FREE(wbuf2);
        MBTOWIDE_FREE(wbuf);
        return rv;
      }
      MBTOWIDE_FREE(wbuf2);
    }
    MBTOWIDE_FREE(wbuf);
  }
  return MoveFileA(existfn,newfn);
}
Exemplo n.º 15
0
        FileSystem::status STDFileSystem::_renameFile(const char* src, const char* dest)
        {
            char buffSrc[512];
            _getFullPath(src, buffSrc);

            char buffDest[512];
            _getFullPath(dest, buffDest);

#if __S3E__
            return (s3eFileRename(buffSrc, buffDest) == S3E_RESULT_SUCCESS ? status_ok : status_error);
#elif OXYGINE_EDITOR
            return status_error;
#elif _WIN32
            std::wstring s = utf8tows(buffSrc);
            std::wstring d = utf8tows(buffDest);
            return MoveFileW(s.c_str(), d.c_str()) ? status_ok : status_error;
#else
            return (::rename(buffSrc, buffDest) != -1 ? status_ok : status_error);
#endif
            return status_error;
        }
Exemplo n.º 16
0
static LRESULT BrsFolder_Treeview_Rename(browse_info *info, NMTVDISPINFOW *pnmtv)
{
    LPTV_ITEMDATA item_data;
    WCHAR old_path[MAX_PATH], new_path[MAX_PATH], *p;
    NMTREEVIEWW nmtv;
    TVITEMW item;

    if(!pnmtv->item.pszText)
        return 0;

    item.mask = TVIF_HANDLE|TVIF_PARAM;
    item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_CARET, 0);
    SendMessageW(info->hwndTreeView, TVM_GETITEMW, 0, (LPARAM)&item);
    item_data = (LPTV_ITEMDATA)item.lParam;

    SHGetPathFromIDListW(item_data->lpifq, old_path);
    if(!(p = strrchrW(old_path, '\\')))
        return 0;
    p = new_path+(p-old_path+1);
    memcpy(new_path, old_path, (p-new_path)*sizeof(WCHAR));
    strcpyW(p, pnmtv->item.pszText);

    if(!MoveFileW(old_path, new_path))
        return 0;

    SHFree(item_data->lpifq);
    SHFree(item_data->lpi);
    item_data->lpifq = SHSimpleIDListFromPathW(new_path);
    IShellFolder_ParseDisplayName(item_data->lpsfParent, NULL, NULL,
            pnmtv->item.pszText, NULL, &item_data->lpi, NULL);

    item.mask = TVIF_HANDLE|TVIF_TEXT;
    item.pszText = pnmtv->item.pszText;
    SendMessageW(info->hwndTreeView, TVM_SETITEMW, 0, (LPARAM)&item);

    nmtv.itemNew.lParam = item.lParam;
    BrsFolder_Treeview_Changed(info, &nmtv);
    return 0;
}
Exemplo n.º 17
0
	void LFA_Rename ( const char * oldName, const char * newName )
	{
		std::string wideOldName, wideNewName;
		size_t utf8Len = strlen(oldName);
		if ( utf8Len < strlen(newName) ) utf8Len = strlen(newName);
		const size_t maxLen = 2 * (utf8Len+1);
		int wideLen;

		wideOldName.reserve ( maxLen );
		wideOldName.assign ( maxLen, ' ' );
		wideLen = MultiByteToWideChar ( CP_UTF8, 0, oldName, -1, (LPWSTR)wideOldName.data(), (int)maxLen );
		if ( wideLen == 0 ) LFA_Throw ( "LFA_Rename: MultiByteToWideChar failure", kLFAErr_ExternalFailure );

		wideNewName.reserve ( maxLen );
		wideNewName.assign ( maxLen, ' ' );
		wideLen = MultiByteToWideChar ( CP_UTF8, 0, newName, -1, (LPWSTR)wideNewName.data(), (int)maxLen );
		if ( wideLen == 0 ) LFA_Throw ( "LFA_Rename: MultiByteToWideChar failure", kLFAErr_ExternalFailure );

		BOOL ok = MoveFileW ( (LPCWSTR)wideOldName.data(), (LPCWSTR)wideNewName.data() );
		if ( ! ok ) LFA_Throw ( "LFA_Rename: MoveFileW failure", kLFAErr_ExternalFailure );

	}	// LFA_Rename
Exemplo n.º 18
0
/*
 * Arguments: existing_path (string), new_path (string)
 * Returns: [boolean]
 */
static int
sys_rename (lua_State *L)
{
  const char *old = luaL_checkstring(L, 1);
  const char *new = luaL_checkstring(L, 2);
  int res;

#ifndef _WIN32
  sys_vm_leave(L);
  res = rename(old, new);
  sys_vm_enter(L);
#else
  {
    void *os_old = utf8_to_filename(old);
    void *os_new = utf8_to_filename(new);
    if (!os_old || !os_new) {
      free(os_old);
      free(os_new);
      return sys_seterror(L, ERROR_NOT_ENOUGH_MEMORY);
    }

    sys_vm_leave(L);
    res = is_WinNT
     ? !MoveFileW(os_old, os_new)
     : !MoveFileA(os_old, os_new);

    free(os_old);
    free(os_new);
    sys_vm_enter(L);
  }
#endif

  if (!res) {
    lua_pushboolean(L, 1);
    return 1;
  }
  return sys_seterror(L, 0);
}
Exemplo n.º 19
0
void CreateConfigPath()
{
	PWSTR knownfolderpath = nullptr;

	ZeroMemory(pathconfigxml, sizeof(pathconfigxml));
	ZeroMemory(pathuserdic, sizeof(pathuserdic));
	ZeroMemory(pathuserbak, sizeof(pathuserbak));
	ZeroMemory(pathskkdic, sizeof(pathskkdic));
	ZeroMemory(pathinitlua, sizeof(pathinitlua));

	if(SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_DONT_VERIFY, nullptr, &knownfolderpath)))
	{
		WCHAR appdir[MAX_PATH];

		_snwprintf_s(appdir, _TRUNCATE, L"%s\\%s", knownfolderpath, TextServiceDesc);

		CoTaskMemFree(knownfolderpath);

		CreateDirectoryW(appdir, nullptr);
		SetCurrentDirectoryW(appdir);

		_snwprintf_s(pathconfigxml, _TRUNCATE, L"%s\\%s", appdir, fnconfigxml);
		_snwprintf_s(pathuserdic, _TRUNCATE, L"%s\\%s", appdir, fnuserdic);
		_snwprintf_s(pathuserbak, _TRUNCATE, L"%s\\%s", appdir, fnuserbak);
		_snwprintf_s(pathskkdic, _TRUNCATE, L"%s\\%s", appdir, fnskkdic);
		_snwprintf_s(pathinitlua, _TRUNCATE, L"%s\\%s", appdir, fninitlua);

		//for compatibility
		if(GetFileAttributesW(pathskkdic) == INVALID_FILE_ATTRIBUTES)
		{
			WCHAR skkdict[MAX_PATH];
			_snwprintf_s(skkdict, _TRUNCATE, L"%s\\%s", appdir, L"skkdict.dic");
			MoveFileW(skkdict, pathskkdic);
			_snwprintf_s(skkdict, _TRUNCATE, L"%s\\%s", appdir, L"skkdict.idx");
			DeleteFileW(skkdict);
		}
	}
}
Exemplo n.º 20
0
BOOL WINAPI MoveFileA(
  LPCSTR lpExistingFileName,
  LPCSTR lpNewFileName
)
{
	const int sLen1 = STRtoWSTR(lpExistingFileName, -1, NULL, 0);
	LPWSTR lpExistingFileNameW = alloca(sizeof (wchar_t)*sLen1);

	const int sLen2 = STRtoWSTR(lpNewFileName, -1, NULL, 0);
	LPWSTR lpNewFileNameW = alloca(sizeof (wchar_t)*sLen2);


	if (!lpExistingFileNameW  || !lpNewFileNameW)
	{
		SetLastError(ERROR_NOT_ENOUGH_MEMORY);
		return 0;
	}

	STRtoWSTR(lpExistingFileName, -1, lpExistingFileNameW, sLen1);
	STRtoWSTR(lpNewFileName, -1, lpNewFileNameW, sLen2);

	return MoveFileW(lpExistingFileNameW, lpNewFileNameW);
}
Exemplo n.º 21
0
bool fal_move( const String &filename, const String &dest, int32 &fsStatus )
{
   String fname1 = filename;
   Path::uriToWin( fname1 );
   String fname2 = dest;
   Path::uriToWin( fname2 );

   AutoWString wBuffer1( fname1 );
   AutoWString wBuffer2( fname2 );
   BOOL res = MoveFileW( wBuffer1.w_str(), wBuffer2.w_str() );

	if( ! res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
	{
      AutoCString cBuffer1( fname1 );
      AutoCString cBuffer2( fname2 );
      res = MoveFile( cBuffer1.c_str(), cBuffer2.c_str() );
	}

   if ( res == TRUE ) {
      return true;
   }
   fsStatus = GetLastError();
   return false;
}
Exemplo n.º 22
0
void FileSystemWidget::renameFile()
{
    QFileInfo info = contextFileInfo();
    if (!info.isFile()) {
        return;
    }
    QString fileName = QInputDialog::getText(m_liteApp->mainWindow(),
                                             tr("Rename File"),tr("File Name"),
                                             QLineEdit::Normal,info.fileName());
    if (!fileName.isEmpty() && fileName != info.fileName()) {
        QDir dir = contextDir();
#ifdef Q_OS_WIN
        if (!MoveFileW(info.filePath().toStdWString().c_str(),QFileInfo(dir,fileName).filePath().toStdWString().c_str())) {
            QMessageBox::information(m_liteApp->mainWindow(),tr("Rename File"),
                                     tr("Failed to rename the file!"));
        }
#else
        if (!QFile::rename(info.filePath(),QFileInfo(dir,fileName).filePath())) {
            QMessageBox::information(m_liteApp->mainWindow(),tr("Rename File"),
                                     tr("Failed to rename the file!"));
        }
#endif
    }
}
Exemplo n.º 23
0
T_bool blpp_fs_MoveFileBypassW(PT_wstr lpExistingFileName,PT_wstr lpNewFileName)
{
    filePathLinkW link1(lpExistingFileName),link2(lpNewFileName);
    return MoveFileW(link1.getLink().c_str(),link2.getLink().c_str());
}
Exemplo n.º 24
0
//------------------------------------------------------------------------------
bool move(const char* src_path, const char* dest_path)
{
    wstr<280> wsrc_path(src_path);
    wstr<280> wdest_path(dest_path);
    return (MoveFileW(wsrc_path.c_str(), wdest_path.c_str()) == TRUE);
}
Exemplo n.º 25
0
int main()
{
    LPWSTR *argv; int argc;

    argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    if(argv == NULL) {
        error("Error parsing commandline options!\n");
    }

    if(argc < 4) {
        error(
            "Usage: %S <options..>\n"
            "Options:\n"
            "  --crt                  CreateRemoteThread injection\n"
            "  --apc                  QueueUserAPC injection\n"
            "  --free                 Do not inject our monitor\n"
            "  --dll <dll>            DLL to inject\n"
            "  --app <app>            Path to application to start\n"
            "  --args <args>          Command-line arguments\n"
            "                         Excluding the application path!\n"
            "  --curdir <dirpath>     Current working directory\n"
            "  --maximize             Maximize the newly created GUI\n"
            "  --pid <pid>            Process identifier to inject\n"
            "  --process-name <name>  Process name to inject\n"
            "  --tid <tid>            Thread identifier to inject\n"
            "  --from <pid>           Inject from another process\n"
            "  --from-process <name>  "
            "Inject from another process, resolves pid\n"
            "  --only-start           "
            "Start the application and print pid/tid\n"
            "  --resume-thread        "
            "Resume the thread of the pid/tid target\n"
            "  --config <path>        "
            "Configuration file for the monitor\n"
            "  --dbg <path>           "
            "Attach debugger to target process\n"
            "  --dump <filepath>      "
            "Dump process memory with --pid to filepath\n"
            "  --verbose              Verbose switch\n",
            argv[0]
        );
    }

    const wchar_t *dll_path = NULL, *app_path = NULL, *arguments = L"";
    const wchar_t *config_file = NULL, *from_process = NULL, *dbg_path = NULL;
    const wchar_t *curdir = NULL, *process_name = NULL, *dump_path = NULL;
    uint32_t pid = 0, tid = 0, from = 0, inj_mode = INJECT_NONE;
    uint32_t show_window = SW_SHOWNORMAL, only_start = 0, resume_thread_ = 0;

    for (int idx = 1; idx < argc; idx++) {
        if(wcscmp(argv[idx], L"--crt") == 0) {
            inj_mode = INJECT_CRT;
            continue;
        }

        if(wcscmp(argv[idx], L"--apc") == 0) {
            inj_mode = INJECT_APC;
            continue;
        }

        if(wcscmp(argv[idx], L"--free") == 0) {
            inj_mode = INJECT_FREE;
            continue;
        }

        if(wcscmp(argv[idx], L"--dll") == 0) {
            dll_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--app") == 0) {
            app_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--args") == 0) {
            arguments = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--curdir") == 0) {
            curdir = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--maximize") == 0) {
            show_window = SW_MAXIMIZE;
            continue;
        }

        if(wcscmp(argv[idx], L"--pid") == 0) {
            pid = wcstol(argv[++idx], NULL, 10);
            continue;
        }

        if(wcscmp(argv[idx], L"--process-name") == 0) {
            process_name = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--tid") == 0) {
            tid = wcstol(argv[++idx], NULL, 10);
            continue;
        }

        if(wcscmp(argv[idx], L"--from") == 0) {
            from = wcstol(argv[++idx], NULL, 10);
            continue;
        }

        if(wcscmp(argv[idx], L"--from-process") == 0) {
            from_process = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--only-start") == 0) {
            only_start = 1;
            continue;
        }

        if(wcscmp(argv[idx], L"--resume-thread") == 0) {
            resume_thread_ = 1;
            continue;
        }

        if(wcscmp(argv[idx], L"--config") == 0) {
            config_file = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--dbg") == 0) {
            dbg_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--dump") == 0) {
            dump_path = argv[++idx];
            continue;
        }

        if(wcscmp(argv[idx], L"--verbose") == 0) {
            verbose = 1;
            continue;
        }

        error("[-] Found unsupported argument: %S\n", argv[idx]);
        return 1;
    }

    // Dump memory of a process.
    if(dump_path != NULL && pid != 0) {
        dump(pid, dump_path);
        return 0;
    }

    if(inj_mode == INJECT_NONE) {
        error("[-] No injection method has been provided!\n");
    }

    if(inj_mode == INJECT_CRT && pid == 0 && process_name == NULL &&
            app_path == NULL) {
        error("[-] No injection target has been provided!\n");
    }

    if(inj_mode == INJECT_APC && tid == 0 && process_name == NULL &&
            app_path == NULL) {
        error("[-] No injection target has been provided!\n");
    }

    if(inj_mode == INJECT_FREE && app_path == NULL) {
        error("[-] An app path is required when not injecting!\n");
    }

    if(pid != 0 && process_name != NULL) {
        error("[-] Both pid and process-name were set!\n");
    }

    static wchar_t dllpath[MAX_PATH_W];

    if(inj_mode == INJECT_FREE) {
        if(dll_path != NULL || tid != 0 || pid != 0) {
            error("[-] Unused --tid/--pid/--dll provided in --free mode!\n");
        }
    }

    if(inj_mode != INJECT_FREE) {
        if(PathFileExistsW(dll_path) == FALSE) {
            error("[-] Invalid DLL filepath has been provided\n");
        }

        if(GetFullPathNameW(dll_path, MAX_PATH_W, dllpath, NULL) == 0) {
            error("[-] Invalid DLL filepath has been provided\n");
        }

        if(GetLongPathNameW(dllpath, dllpath, MAX_PATH_W) == 0) {
            error("[-] Error obtaining the dll long path name\n");
        }
    }

    if(from != 0 && from_process != NULL) {
        error("[-] Both --from and --from-process are specified\n");
    }

    grant_debug_privileges(GetCurrentProcessId());

    if(app_path != NULL) {
        // If a process name has been provided as source process, then find
        // its process identifier (or first, if multiple).
        if(from_process != NULL) {
            from = pid_from_process_name(from_process);
        }

        // If no source process has been specified, then we use our
        // own process.
        if(from == 0) {
            from = GetCurrentProcessId();
        }

        if(PathFileExistsW(app_path) == FALSE) {
            error("[-] Invalid app filepath has been provided\n");
        }

        static wchar_t dirpath[MAX_PATH_W], filepath[MAX_PATH_W];

        // If a current working directory has been set then we use that
        // current working directory. Otherwise default to $TEMP.
        if(curdir != NULL) {
            // Allow the current working directory to be
            // specified as, e.g., %TEMP%.
            if(ExpandEnvironmentStringsW(curdir, dirpath, MAX_PATH_W) == 0) {
                error("[-] Error expanding environment variables\n");
            }

            curdir = dirpath;
        }
        else {
            // We don't want to be expanding the environment variable buffer
            // as that will probably corrupt the heap or so.
            curdir = wcscpy(dirpath, _wgetenv(L"TEMP"));
        }

        if(GetLongPathNameW(dirpath, dirpath, MAX_PATH_W) == 0) {
            error("[-] Error obtaining the curdir long path name\n");
        }

        if(GetFullPathNameW(app_path, MAX_PATH_W, filepath, NULL) == 0) {
            error("[-] Invalid app filepath has been provided\n");
        }

        if(GetLongPathNameW(filepath, filepath, MAX_PATH_W) == 0) {
            error("[-] Error obtaining the app long path name\n");
        }

        pid = start_app(from, filepath, arguments, curdir, &tid, show_window);
    }

    if(pid == 0 && process_name != NULL) {
        pid = pid_from_process_name(process_name);
    }

    // Drop the configuration file if available.
    if(config_file != NULL) {
        static wchar_t filepath[MAX_PATH_W];

        wsprintfW(filepath, L"C:\\cuckoo_%d.ini", pid);
        if(MoveFileW(config_file, filepath) == FALSE) {
            error("[-] Error dropping configuration file: %ld\n",
                GetLastError());
        }
    }

    // Do not do actual injection here, just have the application launched.
    if(only_start != 0) {
        printf("%d %d", pid, tid);
        return 0;
    }

    switch (inj_mode) {
    case INJECT_CRT:
        load_dll_crt(pid, dllpath);
        break;

    case INJECT_APC:
        load_dll_apc(pid, tid, dllpath);
        break;

    case INJECT_FREE:
        break;

    default:
        error("[-] Unhandled injection mode: %d\n", inj_mode);
    }

    if(dbg_path != NULL) {
        wchar_t buf[1024];
        wsprintfW(buf, L"\"%s\" -p %d", dbg_path, pid);

        start_app(GetCurrentProcessId(), dbg_path, buf,
            NULL, NULL, SW_SHOWNORMAL);

        Sleep(5000);
    }

    if((app_path != NULL || resume_thread_ != 0) && tid != 0) {
        resume_thread(tid);
    }

    // Report the process identifier.
    printf("%d", pid);
    return 0;
}
Exemplo n.º 26
0
VOID vProcessFontEntry(
    HKEY   hkey,
    WCHAR *pwcValueName,
    WCHAR *pwcFileName
)
{
    BOOL  bFot = FALSE;
    WCHAR awcTTF[MAX_PATH];
    WCHAR awcTmpBuf[MAX_PATH];
    WCHAR *pwcTTF;
    FLONG fl, fl2;
    FLONG flEmbed;
    DWORD dwPidTid;

    if (bCheckFontEntry(pwcValueName, EXT_TRUETYPE))
    {
    // This is a tt entry, either .fot or .ttf

        if (bFot = bCheckFontEntry(pwcFileName,EXT_FOT))
        {
        // this is an .fot entry, must find ttf pointed to by .fot,
        // but first must get the full path to the .fot file
        // for cGetTTFFromFOT routine expects it. We will also need
        // the full path to the .fot file so that we can delete it
        // eventually.

            if (bMakePathNameW(awcTmpBuf, pwcFileName,NULL, &fl2))
            {
                if (cGetTTFFromFOT(awcTmpBuf, MAX_PATH, awcTTF, &fl, &flEmbed, &dwPidTid) &&
                    !(fl & FONT_ISNOT_FOT))
                {
                // fix the entry to point to .ttf file. At this point
                // awcTTF points to the FULL path to the .ttf file.
                // However, we will only need a relative path to the
                // .ttf file, when the .ttf file is in the %windir%\system
                // or %windir%\fonts directories. In case the file is in the
                // %windir%\system directory we shall copy it to %windir%\fonts
                // directory and write the relative path to the registry.
                // In case it is in the %windir%\fonts directory we do not
                // touch the file and also just write the relative path to the
                // registry. In any other case we just write the full .ttf
                // path to the registry.

                // first delete the .fot file, it is no longer needed

                    if (bFot && !gbWin31Upgrade)
                    {
                        UserVerify(DeleteFileW(awcTmpBuf));
                    }

                    if ((fl & (FONT_IN_FONTS_DIR | FONT_IN_SYSTEM_DIR)) == 0)
                    {
                    // if ttf file is not in either the system or the fonts
                    // directories, just write the full path to the registry

                        pwcTTF = awcTTF;
                    }
                    else
                    {
                    // find the bare file part, this is what will be written
                    // in the registry

                        pwcTTF = &awcTTF[wcslen(awcTTF) - 1];
                        while ((pwcTTF >= awcTTF) && (*pwcTTF != L'\\') && (*pwcTTF != L':'))
                            pwcTTF--;
                        pwcTTF++;

                        if (fl & FONT_IN_SYSTEM_DIR)
                        {
                        // need to move the ttf to fonts dir, can reuse the
                        // buffer on the stack:

                            wcscpy(awcTmpBuf, gpwcFontsDir);
                            lstrcatW(awcTmpBuf, L"\\");
                            lstrcatW(awcTmpBuf, pwcTTF);

                        // note that MoveFile should succeed, for if there was
                        // a ttf file of the same file name in %windir%\fonts dir
                        // we would not have been in this code path.

                                RIPMSG2(RIP_VERBOSE, "Moving %ws to %ws", awcTTF, awcTmpBuf);
                                if (!gbWin31Upgrade)
                                {
                                    UserVerify(MoveFileW(awcTTF, awcTmpBuf));
                                }
                                else
                                {
                                // Boolean value TRUE means "do not copy if target exists"

                                    UserVerify(CopyFileW(awcTTF, awcTmpBuf, TRUE));
                                }
                        }
                    }

                    RIPMSG2(RIP_VERBOSE, "writing to the registry:\n    %ws=%ws", pwcValueName, pwcTTF);
                    UserVerify(ERROR_SUCCESS ==
                            RegSetValueExW(
                                hkey,          // here is the key
                                pwcValueName,
                                0,
                                REG_SZ,
                                (CONST BYTE*) pwcTTF,
                                (DWORD)((wcslen(pwcTTF)+1) * sizeof(WCHAR))));
                }
                #ifdef DEBUG
                else
                {
                    RIPMSG1(RIP_WARNING, "Could not locate ttf pointed to by %ws", awcTmpBuf);
                }
                #endif
            }
            #ifdef DEBUG
            else
            {
                RIPMSG1(RIP_WARNING, "Could not locate .fot:  %ws", pwcFileName);
            }
            #endif
        }
    }
    else
    {
    // not a true type case. little bit simpler,
    // we will use awcTTF buffer for the full path name, and pwcTTF
    // as local variable even though these TTF names are misnomer
    // for these are not tt fonts

        if (bMakePathNameW(awcTTF, pwcFileName,NULL, &fl))
        {
        // At this point
        // awcTTF points to the FULL path to the font file.

        // If the font is in the system subdirectory we will just move it
        // to the fonts subdirectory. If the path in the registry is relative
        // we will leave it alone. If it is an absolute path, we shall
        // fix the registry entry to only contain relative path, the
        // absolute path is redundant.

            if (fl & (FONT_IN_SYSTEM_DIR | FONT_IN_FONTS_DIR))
            {
            // find the bare file part, this is what will be written
            // in the registry

                pwcTTF = &awcTTF[wcslen(awcTTF) - 1];
                while ((pwcTTF >= awcTTF) && (*pwcTTF != L'\\') && (*pwcTTF != L':'))
                    pwcTTF--;
                pwcTTF++;

                if (fl & FONT_IN_SYSTEM_DIR)
                {
                // need to move the font to fonts dir, can reuse the
                // buffer on the stack to build the full destination path

                    wcscpy(awcTmpBuf, gpwcFontsDir);
                    lstrcatW(awcTmpBuf, L"\\");
                    lstrcatW(awcTmpBuf, pwcTTF);

                // note that MoveFile should succeed, for if there was
                // a font file of the same file name in %windir%\fonts dir
                // we would not have been in this code path. The only time
                // it could fail if the path in the registry is absolute.

                    RIPMSG2(RIP_VERBOSE, "Moving %ws to %ws", awcTTF, awcTmpBuf);
                    if (!gbWin31Upgrade)
                    {
                        UserVerify(MoveFileW(awcTTF, awcTmpBuf));
                    }
                    else
                    {
                    // Boolean value TRUE means "do not copy if target exists"

                        UserVerify(CopyFileW(awcTTF, awcTmpBuf, TRUE));
                    }
                }

            // check if the file path in the registry is absolute,
            // if so make it relative:

                if (!(fl & FONT_RELATIVE_PATH))
                {
                    RIPMSG2(RIP_VERBOSE, "writing to the registry:\n    %ws=%ws", pwcValueName, pwcTTF);
                    UserVerify(ERROR_SUCCESS ==
                            RegSetValueExW(
                                    hkey,          // here is the key
                                    pwcValueName,
                                    0,
                                    REG_SZ,
                                    (CONST BYTE*) pwcTTF,
                                    (DWORD)((wcslen(pwcTTF)+1) * sizeof(WCHAR))));
                }
            }
        }
    }
}
Exemplo n.º 27
0
VOID vMoveFileFromSystemToFontsDir(WCHAR *pwcFile)
{
    WCHAR awcTmpBuf[MAX_PATH];
    WCHAR awcTmp[MAX_PATH];
    FLONG fl;
    WCHAR *pwcTmp;

#if DBG
    BOOL  bOk;
#endif

    if (bMakePathNameW(awcTmp, pwcFile,NULL, &fl))
    {
    // If the font is in the system subdirectory we will just move it
    // to the fonts subdirectory. The path in the registry is relative
    // and we will leave it alone.

        if
        (
            (fl & (FONT_IN_SYSTEM_DIR | FONT_RELATIVE_PATH)) ==
            (FONT_IN_SYSTEM_DIR | FONT_RELATIVE_PATH)
        )
        {
        // find the bare file part, this is what will be written
        // in the registry

            pwcTmp = &awcTmp[wcslen(awcTmp) - 1];
            while ((pwcTmp >= awcTmp) && (*pwcTmp != L'\\') && (*pwcTmp != L':'))
                pwcTmp--;

            if (pwcTmp > awcTmp)
                pwcTmp++;

        // need to move the font to fonts dir, can reuse the
        // buffer on the stack to build the full destination path

            wcscpy(awcTmpBuf, gpwcFontsDir);
            lstrcatW(awcTmpBuf, L"\\");
            lstrcatW(awcTmpBuf, pwcTmp);

        // note that MoveFile should succeed, for if there was
        // a font file of the same file name in %windir%\fonts dir
        // we would not have been in this code path.

            #if DBG
                bOk =
            #endif
                MoveFileW(awcTmp, awcTmpBuf);

            RIPMSG3(RIP_VERBOSE,
                    "move %ws to %ws %s",
                    awcTmp,
                    awcTmpBuf,
                    (bOk) ? "succeeded" : "failed");
        }
        #if DBG
        else
        {
            RIPMSG2(RIP_WARNING,
                    "File %ws not in system directory, fl = 0x%lx\n",
                    awcTmp, fl);
        }
        #endif

    }
    #if DBG
    else
    {
        RIPMSG1(RIP_WARNING, "Could not locate %ws", pwcFile);
    }
    #endif
}
Exemplo n.º 28
0
posix_errno_t efile_rename(const efile_path_t *old_path, const efile_path_t *new_path) {
    BOOL old_is_directory, new_is_directory;
    DWORD move_flags, last_error;

    ASSERT_PATH_FORMAT(old_path);
    ASSERT_PATH_FORMAT(new_path);

    move_flags = MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH;

    if(MoveFileExW((WCHAR*)old_path->data, (WCHAR*)new_path->data, move_flags)) {
        return 0;
    }

    last_error = GetLastError();

    old_is_directory = has_file_attributes(old_path, FILE_ATTRIBUTE_DIRECTORY);
    new_is_directory = has_file_attributes(new_path, FILE_ATTRIBUTE_DIRECTORY);

    switch(last_error) {
    case ERROR_SHARING_VIOLATION:
    case ERROR_ACCESS_DENIED:
        if(old_is_directory) {
            BOOL moved_into_itself;

            moved_into_itself = (old_path->size <= new_path->size) &&
                !_wcsnicmp((WCHAR*)old_path->data, (WCHAR*)new_path->data,
                    PATH_LENGTH(old_path));

            if(moved_into_itself) {
                return EINVAL;
            } else if(is_path_root(old_path)) {
                return EINVAL;
            }

            /* Renaming a directory across volumes needs to be rewritten as
             * EXDEV so that the caller can respond by simulating it with
             * copy/delete operations.
             *
             * Files are handled through MOVEFILE_COPY_ALLOWED. */
            if(!has_same_mount_point(old_path, new_path)) {
                return EXDEV;
            }
        }
        break;
    case ERROR_PATH_NOT_FOUND:
    case ERROR_FILE_NOT_FOUND:
        return ENOENT;
    case ERROR_ALREADY_EXISTS:
    case ERROR_FILE_EXISTS:
        if(old_is_directory && !new_is_directory) {
            return ENOTDIR;
        } else if(!old_is_directory && new_is_directory) {
            return EISDIR;
        } else if(old_is_directory && new_is_directory) {
            /* This will fail if the destination isn't empty. */
            if(RemoveDirectoryW((WCHAR*)new_path->data)) {
                return efile_rename(old_path, new_path);
            }

            return EEXIST;
        } else if(!old_is_directory && !new_is_directory) {
            /* This is pretty iffy; the public documentation says that the
             * operation may EACCES on some systems when either file is open,
             * which gives us room to use MOVEFILE_REPLACE_EXISTING and be done
             * with it, but the old implementation simulated Unix semantics and
             * there's a lot of code that relies on that.
             *
             * The simulation renames the destination to a scratch name to get
             * around the fact that it's impossible to open (and by extension
             * rename) a file that's been deleted while open. It has a few
             * drawbacks though;
             *
             * 1) It's not atomic as there's a small window where there's no
             *    file at all on the destination path.
             * 2) It will confuse applications that subscribe to folder
             *    changes.
             * 3) It will fail if we lack general permission to write in the
             *    same folder. */

            WCHAR *swap_path = enif_alloc(new_path->size + sizeof(WCHAR) * 64);

            if(swap_path == NULL) {
                return ENOMEM;
            } else {
                static LONGLONG unique_counter = 0;
                WCHAR *swap_path_end;

                /* We swap in the same folder as the destination to be
                 * reasonably sure that it's on the same volume. Note that
                 * we're avoiding GetTempFileNameW as it will fail on long
                 * paths. */

                sys_memcpy(swap_path, (WCHAR*)new_path->data, new_path->size);
                swap_path_end = swap_path + PATH_LENGTH(new_path);

                while(!IS_SLASH(*swap_path_end)) {
                    ASSERT(swap_path_end > swap_path);
                    swap_path_end--;
                }

                StringCchPrintfW(&swap_path_end[1], 64, L"erl-%lx-%llx.tmp",
                    GetCurrentProcessId(), unique_counter);
                InterlockedIncrement64(&unique_counter);
            }

            if(MoveFileExW((WCHAR*)new_path->data, swap_path, MOVEFILE_REPLACE_EXISTING)) {
                if(MoveFileExW((WCHAR*)old_path->data, (WCHAR*)new_path->data, move_flags)) {
                    last_error = ERROR_SUCCESS;
                    DeleteFileW(swap_path);
                } else {
                    last_error = GetLastError();
                    MoveFileW(swap_path, (WCHAR*)new_path->data);
                }
            } else {
                last_error = GetLastError();
                DeleteFileW(swap_path);
            }

            enif_free(swap_path);

            return windows_to_posix_errno(last_error);
        }

        return EEXIST;
    }

    return windows_to_posix_errno(last_error);
}
Exemplo n.º 29
0
int __cdecl main(int argc, char *argv[])
{
    BOOL bRc = TRUE;
    BOOL bSuccess = TRUE;
    char results[40];
    FILE* resultsFile = NULL;
    int nCounter = 0;
    int i, j;
    WCHAR* wSource = NULL;
    WCHAR* wDest = NULL;
    WCHAR tempSource[] = {'t','e','m','p','k','.','t','m','p','\0'};
    WCHAR tempDest[] = {'t','e','m','p','2','.','t','m','p','\0'};
    HANDLE hFile;
    DWORD result;

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /* read in the expected results to compare with actual results */
    memset (results, 0, 20);
    resultsFile = fopen("expectedresults.txt", "r");
    if (resultsFile == NULL)
    {
        Fail("MoveFileW ERROR: Unable to open \"expectedresults.txt\"\n");
    }

    fgets(results, 20, resultsFile);
    fclose(resultsFile);

    /* clean the slate */
    removeAll();

    if (createExisting() != 0)
    {
        removeAll();
    }


    /* lpSource loop */
    for (i = 0; i < 4; i++)
    {
        /* lpDestination loop */
        for (j = 0; j < 4; j++)
        {

            wSource = convert(lpSource[i]);
            wDest = convert(lpDestination[j]);
            bRc = MoveFileW(wSource, wDest);
            free(wSource);
            free(wDest);
            if (!(
                        ((bRc == TRUE) && (results[nCounter] == '1'))
                        ||
                        ((bRc == FALSE ) && (results[nCounter] == '0'))                    )
               )
            {
                Trace("MoveFileW: FAILED: test[%d][%d]: \"%s\" -> \"%s\"\n",
                      i, j, lpSource[i], lpDestination[j]);
                bSuccess = FALSE;
            }

            /* undo the last move */
            removeAll();
            createExisting();

            nCounter++;
        }
    }

    removeAll();
    if (bSuccess == FALSE)
    {
        Fail("MoveFileW: Test Failed");
    }

    /* create the temp source file */
    hFile = CreateFileW(tempSource, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL, 0);

    if( hFile == INVALID_HANDLE_VALUE )
    {
        Fail("MoveFileW: CreateFile failed to "
             "create the file correctly.\n");
    }

    bRc = CloseHandle(hFile);
    if(!bRc)
    {
        Trace("MoveFileW: CloseHandle failed to close the "
              "handle correctly. ERROR:%u\n",GetLastError());

        /* delete the created file */
        bRc = DeleteFileW(tempSource);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                 "file correctly.\n");
        }
        Fail("");
    }

    /* set the file attributes to be readonly */
    bRc = SetFileAttributesW(tempSource, FILE_ATTRIBUTE_READONLY);
    if(!bRc)
    {
        Trace("MoveFileW: SetFileAttributes failed to set file "
              "attributes correctly. GetLastError returned %u\n",GetLastError());
        /* delete the created file */
        bRc = DeleteFileW(tempSource);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                 "file correctly.\n");
        }
        Fail("");
    }

    /* move the file to the new location */
    bRc = MoveFileW(tempSource, tempDest);
    if(!bRc)
    {
        /* delete the created file */
        bRc = DeleteFileW(tempSource);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                 "file correctly.\n");
        }

        Fail("MoveFileW(%S, %S): GetFileAttributes "
             "failed to get the file's attributes.\n",
             tempSource, tempDest);
    }

    /* check that the newly moved file has the same file attributes
    as the original */
    result = GetFileAttributesW(tempDest);
    if(result == 0)
    {
        /* delete the created file */
        bRc = DeleteFileW(tempDest);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                 "file correctly.\n");
        }

        Fail("MoveFileW: GetFileAttributes failed to get "
             "the file's attributes.\n");
    }

    if((result & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY)
    {
        /* delete the newly moved file */
        bRc = DeleteFileW(tempDest);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                 "file correctly.\n");
        }

        Fail("MoveFileW: GetFileAttributes failed to get "
             "the correct file attributes.\n");
    }

    /* set the file attributes back to normal, to be deleted */
    bRc = SetFileAttributesW(tempDest, FILE_ATTRIBUTE_NORMAL);
    if(!bRc)
    {
        /* delete the newly moved file */
        bRc = DeleteFileW(tempDest);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                 "file correctly.\n");
        }

        Fail("MoveFileW: SetFileAttributes failed to set "
             "file attributes correctly.\n");
    }

    /* delete the newly moved file */
    bRc = DeleteFileW(tempDest);
    if(!bRc)
    {
        Fail("MoveFileW: DeleteFileW failed to delete the"
             "file correctly.\n");
    }

    PAL_Terminate();

    return PASS;
}
Exemplo n.º 30
0
// If we find a file, which short name is equal to 'Name', we try to change
// its short name, while preserving the long name. It helps when unpacking
// an archived file, which long name is equal to short name of already
// existing file. Otherwise we would overwrite the already existing file,
// even though its long name does not match the name of unpacking file.
bool UpdateExistingShortName(wchar *Name)
{
  // 'Name' is the name of file which we want to create. Let's check
  // if file with such name is exist. If it does not, we return.
  FindData fd;
  if (!FindFile::FastFind(NULL,Name,&fd))
    return(false);

  // We continue only if file has a short name, which does not match its
  // long name, and this short name is equal to name of file which we need
  // to create.
  if (*fd.ShortName==0 || wcsicomp(PointToName(fd.NameW),fd.ShortName)==0 ||
      wcsicomp(PointToName(Name),fd.ShortName)!=0)
    return(false);

  // Generate the temporary new name for existing file.
  wchar NewName[NM];
  *NewName=0;
  for (int I=0;I<10000 && *NewName==0;I+=123)
  {
    // Here we copy the path part of file to create. We'll make the temporary
    // file in the same folder.
    wcsncpyz(NewName,Name,ASIZE(NewName));

    // Here we set the random name part.
    sprintfw(PointToName(NewName),ASIZE(NewName),L"rtmp%d",I);
    
    // If such file is already exist, try next random name.
    if (FileExist(NULL,NewName))
      *NewName=0;
  }

  // If we could not generate the name not used by any other file, we return.
  if (*NewName==0)
    return(false);
  
  // FastFind returns the name without path, but we need the fully qualified
  // name for renaming, so we use the path from file to create and long name
  // from existing file.
  wchar FullName[NM];
  wcsncpyz(FullName,Name,ASIZE(FullName));
  wcscpy(PointToName(FullName),PointToName(fd.NameW));
  
  // Rename the existing file to randomly generated name. Normally it changes
  // the short name too.
  if (!MoveFileW(FullName,NewName))
    return(false);

  // Now we need to create the temporary empty file with same name as
  // short name of our already existing file. We do it to occupy its previous
  // short name and not allow to use it again when renaming the file back to
  // its original long name.
  File KeepShortFile;
  bool Created=false;
  if (!FileExist(NULL,Name))
    Created=KeepShortFile.Create(NULL,Name);

  // Now we rename the existing file from temporary name to original long name.
  // Since its previous short name is occupied by another file, it should
  // get another short name.
  MoveFileW(NewName,FullName);

  if (Created)
  {
    // Delete the temporary zero length file occupying the short name,
    KeepShortFile.Close();
    KeepShortFile.Delete();
  }
  // We successfully changed the short name. Maybe sometimes we'll simplify
  // this function by use of SetFileShortName Windows API call.
  // But SetFileShortName is not available in older Windows.
  return(true);
}