ERRORCODE NodeSimCodeGenerator::GenerateMakeFile(IBMNetWorkGetService* pBmNetWork, ETYPE_BUS eBus, std::string strForCppFile)
{
    std::string strMakeFilePath;
    std::string strLibFolder;
    std::string strSimIncludeFolder;
    GetBusmasterNodeSimualtionFolder(NS_MAKEFILE_FOLDER, strMakeFilePath);
    GetBusmasterNodeSimualtionFolder(NS_LIB_FOLDER, strLibFolder);
    GetBusmasterNodeSimualtionFolder(NS_INCLUDE_FOLDER, strSimIncludeFolder);
    CStdioFile omStdiofile;
    CStdioFile omStdioMakefile;
    CFileException omException ;
    DWORD dwSize                 = 0;
    DWORD dwRead                 = 0;
    BOOL bFileOpen               = FALSE;
    CString omStrFile            = "";


    char drive[_MAX_DRIVE];
    char dir[_MAX_DIR];
    char fname[_MAX_FNAME];
    char ext[_MAX_EXT];

    _splitpath( strForCppFile.c_str(), drive, dir, fname, ext );
    char chAbsPath[MAX_PATH] = {'\0'};
    PathCombine(chAbsPath, strMakeFilePath.c_str(), "GCCDLLMakeTemplate");
    strMakeFilePath = std::string(chAbsPath);

    bFileOpen = omStdiofile.Open(strMakeFilePath.c_str(), CFile::modeRead | CFile::typeText, &omException);
    if(bFileOpen!=FALSE)
    {
        CHAR* pcBuff   = nullptr;
        CString omTemp = "";
        // Get the size of file
        dwSize = (DWORD)omStdiofile.GetLength();
        //pcBuff = (char*) new char[dwSize];
        pcBuff = (char*) new char[dwSize+1];

        if(pcBuff!=nullptr)
        {
            memset(pcBuff, 0, dwSize);
            // Read the whole file and put the content to pcBuff;
            dwRead = omStdiofile.Read(pcBuff,dwSize);
            // Add end of string;
            *(pcBuff+dwRead) = '\0';
            // copy the content to CString object;
            omStrFile = pcBuff;
            // Delete the buffer and initialise it to nullptr
            delete []pcBuff;
            pcBuff = nullptr;
        }

        //1. NS_LIB Folder
        omStrFile.Replace("<BUSMASTER_NS_LIB_FOLDER>", strLibFolder.c_str());

        //2. Protocol Lib
        omStrFile.Replace("<PROTOCOL_HELPER_LIB>", GetProtocolLib(eBus).c_str());

        //3. DB Object
        std::string strCheckSum;
        std::string strDbCachePath;
        std::string strGccVer;
        std::string strObjPath ="";
        std::string strIncPath ="";
        GetCurrentGccVersion(strGccVer);
        GetBusMasterDBCachePath(strDbCachePath);
        int nChannels = 0;
        pBmNetWork->GetChannelCount(eBus, nChannels);
        ICluster* pCluster = nullptr;
        for ( int i = 0; i < nChannels; i++ )
        {
            int nDBCount = 0;
            pBmNetWork->GetDBServiceCount(eBus, i, nDBCount);

            for (int nDbIndex = 0; nDbIndex < nDBCount; nDbIndex++)
            {
                pBmNetWork->GetDBService(eBus, i, nDbIndex, &pCluster);
                strObjPath += "\"";
                strObjPath += strDbCachePath + "\\";

                strIncPath += "-include\"";
                strIncPath += strDbCachePath + "\\";

                if (pCluster != nullptr)
                {
                    pCluster->GetDBFileChecksum(strCheckSum);
                    strObjPath += strCheckSum + "_gcc";
                    strObjPath += strGccVer + ".obj";

                    strIncPath += strCheckSum + ".h";
                }
                strObjPath += "\" ";
                strIncPath += "\" ";
            }
        }
        omStrFile.Replace("<DB_OBJFILES>", strObjPath.c_str());

        //4. DB Include
        omStrFile.Replace("<DB_INCLUDES>", strIncPath.c_str());
        //5. FileName
        omStrFile.Replace("<FILENAME>", fname);

        //6. BM Includes
        omStrFile.Replace("<BM_INCLUDES>", strSimIncludeFolder.c_str());

        //7. file path
        char chShortPath[1024];
        GetShortPathName(strForCppFile.c_str(), chShortPath, 1024);
        CString strTemp = chShortPath;
        strTemp.Replace("\\", "/");
        omStrFile.Replace("<FILEPATH>", strTemp);

        std::strcat(fname, "make");
        PathCombine(chAbsPath, drive, dir);
        char chFullPath[BM_MAX_PATH] = { '\0' };
        PathCombine(chFullPath, chAbsPath, fname);
        std::string strMakeFileName = std::string(chFullPath);
        bFileOpen = omStdioMakefile.Open(strMakeFileName.c_str(), CFile::modeWrite | CFile::typeText | CFile::modeCreate, &omException);

        if(bFileOpen!=FALSE)
        {
            omStdioMakefile.WriteString(omStrFile);
        }
    }
    return S_OK;
}
Example #2
0
bool WNInstall_MoveFileOnReboot(const char * pszExisting, const char * pszNew)
{	
  bool fOk = 0;
#if !JDK_IS_WINE   
  HMODULE hLib=LoadLibrary("kernel32.dll");
  if (hLib)
  {
    typedef BOOL (WINAPI *mfea_t)(LPCSTR lpExistingFileName,LPCSTR lpNewFileName,DWORD dwFlags);
    mfea_t mfea;
    mfea=(mfea_t) GetProcAddress(hLib,"MoveFileExA");
    if (mfea)
    {
      fOk=(mfea(pszExisting, NULL, MOVEFILE_DELAY_UNTIL_REBOOT)!=0);
    }
    FreeLibrary(hLib);
  }

  if (!fOk)
  {
    static char szRenameLine[1024];
    int cchRenameLine;
    char *szRenameSec = "[Rename]\r\n";
    HANDLE hfile, hfilemap;
    DWORD dwFileSize, dwRenameLinePos=0;
    static char wininit[1024];
    static char tmpbuf[1024];
    static char nulint[4]="NUL";

    if (pszNew) GetShortPathName(pszNew,tmpbuf,1024);
    else *((int *)tmpbuf) = *((int *)nulint);
    // wininit is used as a temporary here
    GetShortPathName(pszExisting,wininit,1024);
    pszExisting=wininit;
    cchRenameLine = wsprintf(szRenameLine,"%s=%s\r\n",tmpbuf,pszExisting);

    GetWindowsDirectory(wininit, 1024-16);
    lstrcat(wininit, "\\wininit.ini");
    hfile = CreateFile(wininit,
        GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);

    if (hfile != INVALID_HANDLE_VALUE) 
    {
      dwFileSize = GetFileSize(hfile, NULL);
      hfilemap = CreateFileMapping(hfile, NULL, PAGE_READWRITE, 0, dwFileSize + cchRenameLine + 10, NULL);

      if (hfilemap != NULL) 
      {
        LPSTR pszWinInit = (LPSTR) MapViewOfFile(hfilemap, FILE_MAP_WRITE, 0, 0, 0);

        if (pszWinInit != NULL) 
        {
          int do_write=0;
          LPSTR pszRenameSecInFile = strstr(pszWinInit, szRenameSec);
          if (pszRenameSecInFile == NULL) 
          {
            lstrcpy(pszWinInit+dwFileSize, szRenameSec);
            dwFileSize += 10;
            dwRenameLinePos = dwFileSize;
            do_write++;
          } 
          else
          {
            char *pszFirstRenameLine = strstr(pszRenameSecInFile, "\n")+1;
            int l=pszWinInit + dwFileSize-pszFirstRenameLine;
            if (!wninstall_findinmem(pszFirstRenameLine,szRenameLine,l))
            {
              memmove(pszFirstRenameLine + cchRenameLine, pszFirstRenameLine, l);
              dwRenameLinePos = pszFirstRenameLine - pszWinInit;
              do_write++;
            }
          }

          if (do_write)
          {
            memcpy(&pszWinInit[dwRenameLinePos], szRenameLine,cchRenameLine);
            dwFileSize += cchRenameLine;
          }

          UnmapViewOfFile(pszWinInit);

          fOk++;
        }
        CloseHandle(hfilemap);
      }
      SetFilePointer(hfile, dwFileSize, NULL, FILE_BEGIN);
      SetEndOfFile(hfile);
      CloseHandle(hfile);
    }
  }
#endif
  return fOk;
	
}
Example #3
0
bool ecUtils::Launch(const ecFileName &strFileName, const ecFileName &strViewer)
{
	bool rc=false;

	if(!strViewer.IsEmpty())//use custom editor
	{
		wxString strCmdline(strViewer);
		
		PTCHAR pszCmdLine=strCmdline.GetBuffer(strCmdline.GetLength());
		GetShortPathName(pszCmdLine,pszCmdLine,strCmdline.GetLength());
		strCmdline.ReleaseBuffer();

		strCmdline+=_TCHAR(' ');
		strCmdline+=strFileName;
		PROCESS_INFORMATION pi;
		STARTUPINFO si;

		si.cb = sizeof(STARTUPINFO); 
		si.lpReserved = NULL; 
		si.lpReserved2 = NULL; 
		si.cbReserved2 = 0; 
		si.lpDesktop = NULL; 
		si.dwFlags = 0; 
		si.lpTitle=NULL;

		if(CreateProcess(
			NULL, // app name
			//strCmdline.GetBuffer(strCmdline.GetLength()),    // command line
			strCmdline.GetBuffer(strCmdline.GetLength()),    // command line
			NULL, // process security
			NULL, // thread security
			TRUE, // inherit handles
			0,
			NULL, // environment
			NULL, // current dir
			&si, // startup info
			&pi)){
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
			rc=true;
		} else {
			MessageBoxF(wxT("Failed to invoke %s.\n"),strCmdline);
		}
		strCmdline.ReleaseBuffer();
	} else {// Use association
		TCHAR szExe[MAX_PATH];
		HINSTANCE h=FindExecutable(strFileName,wxT("."),szExe);
		if(int(h)<=32){
			wxString str;
			switch(int(h)){
				case 0:  str=wxT("The system is out of memory or resources.");break;
				case 31: str=wxT("There is no association for the specified file type.");break;
				case ERROR_FILE_NOT_FOUND: str=wxT("The specified file was not found.");break;
				case ERROR_PATH_NOT_FOUND: str=wxT("The specified path was not found.");break;
				case ERROR_BAD_FORMAT:     str=wxT("The .EXE file is invalid (non-Win32 .EXE or error in .EXE image).");break;
				default: break;
			}
			MessageBoxF(wxT("Failed to open document %s.\r\n%s"),strFileName,str);
		} else {

			SHELLEXECUTEINFO sei = {sizeof(sei), 0, AfxGetMainWnd()->GetSafeHwnd(), wxT("open"),
					strFileName, NULL, NULL, SW_SHOWNORMAL, AfxGetInstanceHandle( )};

			sei.hInstApp=0;
			HINSTANCE hInst=ShellExecute(AfxGetMainWnd()->GetSafeHwnd(),wxT("open"), strFileName, NULL, wxT("."), 0)/*ShellExecuteEx(&sei)*/;
			if(int(hInst)<=32/*sei.hInstApp==0*/)
			{
				wxString str;
				switch(int(hInst))
				{
					case 0 : str=wxT("The operating system is out of memory or resources. ");break;
					case ERROR_FILE_NOT_FOUND : str=wxT("The specified file was not found. ");break;
					case ERROR_PATH_NOT_FOUND : str=wxT("The specified path was not found. ");break;
					case ERROR_BAD_FORMAT : str=wxT("The .EXE file is invalid (non-Win32 .EXE or error in .EXE image). ");break;
					case SE_ERR_ACCESSDENIED : str=wxT("The operating system denied access to the specified file. ");break;
					case SE_ERR_ASSOCINCOMPLETE : str=wxT("The filename association is incomplete or invalid. ");break;
					case SE_ERR_DDEBUSY : str=wxT("The DDE transaction could not be completed because other DDE transactions were being processed. ");break;
					case SE_ERR_DDEFAIL : str=wxT("The DDE transaction failed. ");break;
					case SE_ERR_DDETIMEOUT : str=wxT("The DDE transaction could not be completed because the request timed out. ");break;
					case SE_ERR_DLLNOTFOUND : str=wxT("The specified dynamic-link library was not found. ");break;
					//case SE_ERR_FNF : str=wxT("The specified file was not found. ");break;
					case SE_ERR_NOASSOC : str=wxT("There is no application associated with the given filename extension. ");break;
					case SE_ERR_OOM : str=wxT("There was not enough memory to complete the operation. ");break;
					//case SE_ERR_PNF : str=wxT("The specified path was not found. ");break;
					case SE_ERR_SHARE : str=wxT("A sharing violation occurred. ");break;
					default: str=wxT("An unexpected error occurred");break;
				}
				MessageBoxF(wxT("Failed to open document %s using %s.\r\n%s"),strFileName,szExe,str);
			} else {
				rc=true;
			}
		}
	}
	return rc;
}
static QString getShortPath( const QString &path )
{
  TCHAR buf[MAX_PATH];
  GetShortPathName( path.toAscii(), buf, MAX_PATH );
  return buf;
}
Example #5
0
/*--------------------------------------------------------------------------*/
BOOL SetTclTkEnvironment(char *DefaultPath)
{
#define TCL_LIBRARY "TCL_LIBRARY"
#define TCL_LIBRARY_FORMAT "%s/modules/tclsci/tcl/tcl%d.%d"

#define TK_LIBRARY "TK_LIBRARY"
#define TK_LIBRARY_FORMAT "%s/modules/tclsci/tcl/tk%d.%d"

#define TCL_DEFAULT_ENCODING_DIR_FORMAT "%s/modules/tclsci/tcl/tcl%d.%d/encoding"

    int tcl_major = 8;
    int tcl_minor = 4; /* default */
    int tcl_patchLevel = 0;
    int tcl_type = 0;

    BOOL bOK = TRUE;

    char TCL_LIBRARY_PATH[PATH_MAX];
    char TK_LIBRARY_PATH[PATH_MAX];
    char TCL_DEFAULT_ENCODING_DIR[PATH_MAX];

    Tcl_DString encodingName;

    char ShortPath[PATH_MAX];
    char *CopyOfDefaultPath = NULL;

    Tcl_Obj *pathPtr = NULL;
    Tcl_Obj *objPtr = NULL;

    CopyOfDefaultPath = MALLOC(((int)strlen(DefaultPath) + 1) * sizeof(char));
    if (CopyOfDefaultPath == NULL)
    {
        return FALSE;
    }

    if (getScilabMode() == SCILAB_STD)
    {
        /* redirect stdout, stderr in console */
        freopen("CONOUT$", "wb", stdout); /* redirect stdout --> CONOUT$*/
        freopen("CONOUT$", "wb", stderr); /* redirect stderr --> CONOUT$*/
    }

    Tcl_GetVersion(&tcl_major, &tcl_minor, &tcl_patchLevel, &tcl_type);

    GetShortPathName(DefaultPath, ShortPath, PATH_MAX);
    AntislashToSlash(ShortPath, CopyOfDefaultPath);
    sprintf (TCL_LIBRARY_PATH, TCL_LIBRARY_FORMAT, CopyOfDefaultPath, tcl_major, tcl_minor);
    sprintf (TK_LIBRARY_PATH, TK_LIBRARY_FORMAT, CopyOfDefaultPath, tcl_major, tcl_minor);
    sprintf (TCL_DEFAULT_ENCODING_DIR,
             TCL_DEFAULT_ENCODING_DIR_FORMAT,
             CopyOfDefaultPath,
             tcl_major,
             tcl_minor);

    if (CopyOfDefaultPath)
    {
        FREE(CopyOfDefaultPath);
        CopyOfDefaultPath = NULL;
    }

    /* TCL_LIBRARY initialization */
    SetEnvironmentVariable(TCL_LIBRARY, TCL_LIBRARY_PATH);
    setenvtcl(TCL_LIBRARY, TCL_LIBRARY_PATH);
    if (Tcl_SetVar(getTclInterp(), "tcl_library", TCL_LIBRARY_PATH, TCL_GLOBAL_ONLY) == NULL)
    {
        releaseTclInterp();
        fprintf(stderr, _("%s: An error occurred: %s\n"), "tcl_library",
                _("Impossible to set environment variable."));
        bOK = FALSE;
    }
    releaseTclInterp();

    if (Tcl_SetVar(getTclInterp(), "tclDefaultLibrary", TCL_LIBRARY_PATH, TCL_GLOBAL_ONLY) == NULL)
    {
        releaseTclInterp();
        fprintf(stderr, _("%s: An error occurred: %s\n"), "tclDefaultLibrary",
                _("Impossible to set environment variable."));
        bOK = FALSE;
    }
    releaseTclInterp();

    if (Tcl_SetVar(getTclInterp(), "tcl_pkgPath", TCL_LIBRARY_PATH, TCL_GLOBAL_ONLY) == NULL)
    {
        releaseTclInterp();
        fprintf(stderr, _("%s: An error occurred: %s\n"), "tcl_pkgPath",
                _("Impossible to set environment variable."));
        bOK = FALSE;
    }
    releaseTclInterp();

    pathPtr = Tcl_NewStringObj(TCL_LIBRARY_PATH, -1);

    /* TK_LIBRARY initialization */
    SetEnvironmentVariable(TK_LIBRARY, TK_LIBRARY_PATH);
    setenvtcl(TK_LIBRARY, TK_LIBRARY_PATH);
    if (Tcl_SetVar(getTclInterp(), "tk_library", TK_LIBRARY_PATH, TCL_GLOBAL_ONLY) == NULL)
    {
        releaseTclInterp();
        fprintf(stderr, _("%s: An error occurred: %s\n"), "tk_library",
                _("Impossible to set environment variable."));
        bOK = FALSE;
    }
    releaseTclInterp();

    objPtr = Tcl_NewStringObj(TK_LIBRARY_PATH, -1);
    Tcl_ListObjAppendElement(NULL, pathPtr, objPtr);
    TclSetLibraryPath(pathPtr);

    /* encoding initialization */
    Tcl_SetDefaultEncodingDir(TCL_DEFAULT_ENCODING_DIR);
    if ( Tcl_SetSystemEncoding(NULL, Tcl_GetEncodingNameFromEnvironment(&encodingName)) == TCL_ERROR )
    {
        fprintf(stderr, _("%s: An error occurred: %s\n"), "Tcl_SetSystemEncoding",
                _("Impossible to set system encoding."));
        bOK = FALSE;
    }
    Tcl_DStringFree(&encodingName);

    return bOK ;
}
Example #6
0
void attribute_hidden InitTempDir()
{
    char *tmp, *tm, tmp1[PATH_MAX+11], *p;
#ifdef Win32
    char tmp2[PATH_MAX];
    int hasspace = 0;
#endif

    if(R_TempDir) return; /* someone else set it */
    tmp = NULL; /* getenv("R_SESSION_TMPDIR");   no longer set in R.sh */
    if (!tmp) {
	tm = getenv("TMPDIR");
	if (!isDir(tm)) {
	    tm = getenv("TMP");
	    if (!isDir(tm)) {
		tm = getenv("TEMP");
		if (!isDir(tm))
#ifdef Win32
		    tm = getenv("R_USER"); /* this one will succeed */
#else
		    tm = "/tmp";
#endif
	    }
	}
#ifdef Win32
	/* make sure no spaces in path */
	for (p = tm; *p; p++)
	    if (isspace(*p)) { hasspace = 1; break; }
	if (hasspace) {
	    GetShortPathName(tm, tmp2, MAX_PATH);
	    tm = tmp2;
	}
	snprintf(tmp1, PATH_MAX+11, "%s\\RtmpXXXXXX", tm);
#else
	snprintf(tmp1, PATH_MAX+11, "%s/RtmpXXXXXX", tm);
#endif
	tmp = mkdtemp(tmp1);
	if(!tmp) R_Suicide(_("cannot create 'R_TempDir'"));
#ifndef Win32
# ifdef HAVE_SETENV
	if(setenv("R_SESSION_TMPDIR", tmp, 1))
	    errorcall(R_NilValue, _("unable to set R_SESSION_TMPDIR"));
# elif defined(HAVE_PUTENV)
	{
	    size_t len = strlen(tmp) + 20;
	    char * buf = (char *) malloc((len) * sizeof(char));
	    if(buf) {
		snprintf(buf, len, "R_SESSION_TMPDIR=%s", tmp);
		if(putenv(buf))
		    errorcall(R_NilValue, _("unable to set R_SESSION_TMPDIR"));
		/* no free here: storage remains in use */
	    } else
		errorcall(R_NilValue, _("unable to set R_SESSION_TMPDIR"));
	}
# endif
#endif
    }

    size_t len = strlen(tmp) + 1;
    p = (char *) malloc(len);
    if(!p)
	R_Suicide(_("cannot allocate 'R_TempDir'"));
    else {
	R_TempDir = p;
	strcpy(R_TempDir, tmp);
	Sys_TempDir = R_TempDir;
    }
}
Example #7
0
static wchar_t *makeCmdLine
(
	bool			ask,
	wchar_t			*buffer,
	const wchar_t	*mask,
	const wchar_t	*dir,
	const wchar_t	*fn,
	const wchar_t	*title = nullptr,
	const wchar_t	macro = L'='
)
{
	static wchar_t tmp[NM];
	static wchar_t n1[NM], drv1[NM], dir1[NM], fil1[NM], ext1[NM];
	static wchar_t n2[NM], drv2[NM], dir2[NM], fil2[NM], ext2[NM];
	wchar_t				*i, *j, *e1 = ext1, *e2 = ext2, *smartQuote = nullptr;
	fExpand (wcscpy (tmp, fn), dir);
	GetFullPathName (tmp, _countof(n1), n1, &j);
	fnSplit (n1, drv1, dir1, fil1, ext1);
	GetShortPathName (tmp, n2, _countof(n2));
	fnSplit (n2, drv2, dir2, fil2, ext2);
	wcscat (wcscat (wcscat (wcscpy (n1, drv1), dir1), fil1), ext1);
	wcscat (wcscat (wcscat (wcscpy (n2, drv2), dir2), fil2), ext2);
	if (*e1 == L'.') e1++;
	if (*e2 == L'.') e2++;
	i = (wchar_t *) mask;
	if (ask)
	{
		nullUserStrings ();
		if (!scanUserInput (false, L'=', mask, title)) return (nullptr);
	}

	*tmp = 0;
	*(j = buffer) = 0;
	while (*i)
	{
		int		dosName = 0, noDrive = 0, noBackslash = 0, doQuote = 1;
		wchar_t	*m = wcschr (i, macro);
		if (m)
		{
			*m = 0;
			wcscat (j, i);
			j = wcschr (j, 0);
			*m = macro;
			if (*++m == macro)
			{
				j[0] = macro;
				j[1] = 0;
				j = wcschr (j, 0);
				i = m + 1;
			}
			else if (ask && wcschr (L"0123456789?", *m))
			{
				if (*m != L'?') wcscpy (j, userString[*m - L'0']);
				j = wcschr (j, 0);
				if (*m == L'?')
				{
					m++;
					while (*m)
					{
						if ((m[0] == L'\\') && ((m[1] == L'\\') || (m[1] == L'\'') || (m[1] == L'?')))
						{
							m++;
							m++;
						}
						else
						{
							if (*m == L'?')
								break;
							else
								m++;
						}
					}
				}

				i = m + 1;
			}
			else
			{
				int modifyer = 1;
				while (modifyer)
				{
					switch (*m)
					{
					case L'd':
						dosName = 1;
						break;
					case L'm':
						noDrive = 1;
						break;
					case L't':
						noBackslash = 1;
						break;
					case L'o':
						doQuote = 0;
						break;
					default:
						m--;
						modifyer = 0;
						break;
					}

					m++;
				}

				switch (*m)
				{
				case L'M':
					wcscat (j, drv1);
					break;
				case L'N':
					wcscat (j, quote (doQuote, wcscpy (tmp, dosName ? fil2 : fil1)));
					break;
				case L'E':
					if (*(m + 1) == L's')
					{
						EditorGetStringEx egs;
						EditorGetStr (&egs);
						wcsncpy (j + wcslen (j), egs.StringText, egs.StringLength + 1);
						m++;
					}
					else if (*(m + 1) == L'p')
					{
						TEditorPos	pos = EditorGetPos ();
						FSF.itoa64 (pos.Row + 1, tmp, 10);
						wcscat (j, tmp);
						m++;
					}
					else if (*(m + 1) == L'c')
					{
						TEditorPos	pos = EditorGetPos ();
						FSF.itoa64 (pos.Col + 1, tmp, 10);
						wcscat (j, tmp);
						m++;
					}
					else
						wcscat (j, quote (doQuote, wcscpy (tmp, dosName ? e2 : e1)));
					break;
				case L'F':
					wcscpy (tmp, dosName ? fil2 : fil1);
					if (*(dosName ? e2 : e1)) wcscat (wcscat (tmp, L"."), dosName ? e2 : e1);
					wcscat (j, quote (doQuote, tmp));
					break;
				case L'D':
					if (noDrive)
						*tmp = 0;
					else
						wcscpy (tmp, drv1);
					wcscat (tmp, dosName ? dir2 : dir1);
					if (noBackslash) delBackslash (tmp);
					wcscat (j, quote (doQuote, tmp));
					break;
				case L'P':
					if (noDrive)
					{
						wcscpy (tmp, dosName ? dir2 : dir1);
						wcscat (tmp, dosName ? fil2 : fil1);
						if (*(dosName ? e2 : e1)) wcscat (wcscat (tmp, L"."), dosName ? e2 : e1);
						wcscat (j, quote (doQuote, tmp));
					}
					else
						wcscat (j, quote (doQuote, wcscat (tmp, dosName ? n2 : n1)));
					break;
				case L'\'':
					if (smartQuote)
					{
						for (wchar_t *p = smartQuote; *p; p++)
							if (*p == L'\"') *p = L'\'';
						quote (1, smartQuote);
						smartQuote = nullptr;
					}
					else
						smartQuote = wcschr (j, 0);
					break;
				}

				i = m + 1;
				j = wcschr (j, 0);
			}
		}
		else
			break;
	}

	wcscat (j, i);
	return (buffer);
}
Example #8
0
//----------------------------------------------------------------------------
// Fetch the user's default browser.
//----------------------------------------------------------------------------
bool GetBrowserCommandLineFromRegistry(std::string& sBrowser)
{
	LONG  nLong;
	HKEY  hKey;
	TCHAR sValue[MAX_PATH];
	DWORD nValueLength = sizeof(sValue);
	TCHAR sShortPath[MAX_PATH];

	sBrowser = TEXT("");

	// Find out what the preferred browser is by looking to see if .html is 
	// associated with NetscapeMarkup or htmlfile.
	if (RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT(".html"), 0, KEY_QUERY_VALUE, &hKey)  != ERROR_SUCCESS)
		return false;

	nLong = RegQueryValueEx(hKey, TEXT(""), NULL, NULL, (LPBYTE) sValue, &nValueLength);
	RegCloseKey(hKey);
	if (nLong != ERROR_SUCCESS)
		return false;

	string sTemp = sValue;
	sTemp += TEXT("\\shell\\open\\command");
	if (RegOpenKeyEx(HKEY_CLASSES_ROOT, sTemp.c_str(), 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
		return false;

	nValueLength = sizeof(sValue);
	nLong = RegQueryValueEx(hKey, "", NULL, NULL, (LPBYTE)sValue, &nValueLength);
	RegCloseKey(hKey);
	if (nLong != ERROR_SUCCESS)
		return false;

	sTemp = sValue;
	int nLocation = (int)(sTemp.find('\"'));
	if (nLocation == 0)
	{
		sTemp.erase(0, 1); // Remove the leading quote.
		nLocation = (int)(sTemp.find('\"', 1));
		if (nLocation != -1)
			sTemp.erase(nLocation, sTemp.length() - nLocation); // Remove the traling quote (and anything following it).

		DWORD nRetValue = GetShortPathName(sTemp.c_str(), sShortPath, MAX_PATH);
		if (nRetValue == 0 || nRetValue >= MAX_PATH)
			return false;
		else
			sBrowser = sShortPath;
	}
	else if (nLocation != -1)
	{
		sBrowser = sTemp;
		sBrowser.erase(0, nLocation);

		UINT nLen = sBrowser.length();
		while (nLen > 0 && (sBrowser[nLen - 1] == ' ' || 
			sBrowser[nLen - 1] == '\t' || sBrowser[nLen - 1] == '\n'))
		{
			sBrowser.erase(nLen - 1);
			nLen = sBrowser.length();
		}
	}

	return sBrowser.length() > 0;
}
Example #9
0
/* Extracts the executable or script name from the first string in 
   cmdline.
  
   If the name contains blanks then it must be quoted with double quotes,
   otherwise quotes are optional.  If the name contains blanks then it 
   will be converted to a short name.
  
   The optional quotes will be removed.  The result is copied to a malloc'ed
   buffer and returned through the pexe argument.  The pargs parameter is set
   to the address of the character in cmdline located after the name.
  
   The malloc'ed buffer returned in *pexe must be freed by the caller.  */
bool GetApplicationName(const char *cmdline, char **pexe, const char **pargs)
{
	// Start of executable name in cmdline.
	const char *pExeStart=NULL;
	// Character after executable name (separator).
	const char *pExeEnd=NULL;

	// Character after last path separator.
	const char *pBasename=NULL;
	// Period at start of extension.
	const char *pExtension=NULL;

	const char *current=cmdline;

	bool bQuoted=false;

	// Skip initial whitespace.
	while(*current==' ' || *current=='\t') current++;

	// Calculate start of name and determine if quoted.

	if(*current=='"')
	{
		pExeStart=++current;
		bQuoted=true;
	}
	else
	{
		pExeStart=current;
		bQuoted=false;
	}

	*pargs=NULL;
	*pexe=NULL;

	/* Scan command line looking for path separators (/ and \\) and the 
	   terminator, either a quote or a blank.  The location of the 
	   extension is also noted.  */
	for( ; *current!='\0'; current++)
	{
		if(*current=='.')
			pExtension=current;
		else if(IsPathSeparator(*current) && current[1]!='\0')
		{
			pBasename=&current[1];
			pExtension=NULL;
		}

		// Check for terminator, either quote or blank.
		if(bQuoted)
		{
			if(*current!='"') continue;
		}
		else
		{
			if(*current!=' ') continue;
		}

		/* Hit terminator, remember end of name (address of terminator) 
		   and start of arguments. */
		pExeEnd=current;

		if(bQuoted && *current=='"')
			*pargs=&current[1];
		else
			*pargs=current;
		break;
	}

	if(!pBasename) pBasename=pExeStart;

	if(!pExeEnd) pExeEnd=current;

	if(!*pargs) *pargs=current;

	bool bHasPathSeparators=pExeStart!=pBasename;

	// We have pointers to all the useful parts of the name.

	// Default extensions in the order cmd.exe uses to search.

	static const char ExtensionList[][5]={".com", ".exe", ".bat", ".cmd"};
	DWORD dwBasePathLength=pExeEnd-pExeStart;

	DWORD dwAltNameLength=0;
	char *pPathname=(char *)alloca(MAX_PATHLENGTH+1);
	char *pAltPathname=(char *)alloca(MAX_PATHLENGTH+1);

	pPathname[MAX_PATHLENGTH]='\0';
	pAltPathname[MAX_PATHLENGTH]='\0';

	memcpy(pPathname, pExeStart, dwBasePathLength);
	pPathname[dwBasePathLength]='\0';

	if(!pExtension)
	{
		// Try appending extensions.
		for(int index=0;
		  index<(int)(sizeof(ExtensionList)/sizeof(ExtensionList[0]));
		  index++)
		{
			if(!bHasPathSeparators)
			{
				// There are no path separators, search in the
				// standard locations
				dwAltNameLength=SearchPath(NULL, pPathname,
				  ExtensionList[index], MAX_PATHLENGTH,
				  pAltPathname, NULL);
				if(dwAltNameLength_ok(dwAltNameLength))
				{
					memcpy(pPathname, pAltPathname,
						dwAltNameLength);
					pPathname[dwAltNameLength]='\0';
					break;
				}
			}
			else
			{
				snprintf(&pPathname[dwBasePathLength],
					MAX_PATHLENGTH-dwBasePathLength,
					"%s", ExtensionList[index]);
				if(GetFileAttributes(pPathname)
				  !=INVALID_FILE_ATTRIBUTES)
					break;
				pPathname[dwBasePathLength]='\0';
			}
		}
	}
	else if(!bHasPathSeparators)
	{
		// There are no path separators, search in the standard
		// locations.
		dwAltNameLength=SearchPath(NULL, pPathname,
			NULL, MAX_PATHLENGTH, pAltPathname, NULL);
		if(dwAltNameLength_ok(dwAltNameLength))
		{
			memcpy(pPathname, pAltPathname, dwAltNameLength);
			pPathname[dwAltNameLength] = '\0';
		}
	}

	if(strchr(pPathname, ' '))
	{
		dwAltNameLength=GetShortPathName(pPathname,
			pAltPathname, MAX_PATHLENGTH);

		if(dwAltNameLength_ok(dwAltNameLength))
		{
			*pexe=(char *)malloc(dwAltNameLength+1);
			if(!*pexe) return false;
			memcpy(*pexe, pAltPathname, dwAltNameLength+1);
		}
	}

	if(!*pexe)
	{
		DWORD dwPathnameLength=strlen(pPathname);
		*pexe=(char *)malloc(dwPathnameLength+1);
		if(!*pexe) return false;
		memcpy(*pexe, pPathname, dwPathnameLength+1);
	}

	return true;
}
Example #10
0
/*!
\param shorten will try to match against the short version
recent switch back to short path names in project settings has broken some stuff
with shorten == true, we will convert in to short version before looking for root
FIXME WAAA .. the stuff below is much more simple on linux .. add appropriate #ifdef
*/
char* vfsExtractRelativePath_short(const char *in, bool shorten)
{
  int i;
  char l_in[PATH_MAX];
  char check[PATH_MAX];
  static char out[PATH_MAX];
  out[0] = 0;

#ifdef DBG_RLTPATH
  Sys_Printf("vfsExtractRelativePath: %s\n", in);
#endif

#ifdef _WIN32
  if (shorten)
  {
    // make it short
    if (GetShortPathName(in, l_in, PATH_MAX) == 0)
    {
#ifdef DBG_RLTPATH
      Sys_Printf("GetShortPathName failed\n");
#endif
      return NULL;
    }
  }
  else
  {
    strcpy(l_in,in);
  }
  vfsCleanFileName(l_in);
#else
  strcpy(l_in, in);
  vfsCleanFileName(l_in);
#endif // ifdef WIN32


#ifdef DBG_RLTPATH
  Sys_Printf("cleaned path: %s\n", l_in);
#endif

  for (i = 0; i < g_numDirs; i++)
  {
    strcpy(check,g_strDirs[i]);
    vfsCleanFileName(check);
#ifdef DBG_RLTPATH
    Sys_Printf("Matching against %s\n", check);
#endif

    // try to find a match
    if (strstr(l_in, check))
    {
      strcpy(out,l_in+strlen(check)+1);
      break;
    }

  }
  if (out[0]!=0)
  {
#ifdef DBG_RLTPATH
    Sys_Printf("vfsExtractRelativePath: success\n");
#endif
    return out;
  }
#ifdef DBG_RLTPATH
  Sys_Printf("vfsExtractRelativePath: failed\n");
#endif
  return NULL;
}
Example #11
0
static BOOL
RunInstaller()
{
  PROCESS_INFORMATION pi;
  STARTUPINFO         sti;
  char                szCmdLine[MAX_BUF];
  char                szSetupFile[MAX_BUF];
  char                szUninstallFile[MAX_BUF];
  char                szArcLstFile[MAX_BUF];
  BOOL                bRet;
  char                szText[256];
  char                szTempPath[MAX_BUF];
  char                szTmp[MAX_PATH];
  char                xpiDir[MAX_PATH];
  char                szFilename[MAX_BUF];
  char                szBuf[MAX_BUF];

  if(gbUncompressOnly == TRUE)
    return(TRUE);

  // Update UI
  UpdateProgressBar(100);
  LoadString(hInst, IDS_STATUS_LAUNCHING_SETUP, szText, sizeof(szText));
  SetStatusLine(szText);

  memset(&sti,0,sizeof(sti));
  sti.cb = sizeof(STARTUPINFO);

  // Setup program is in the directory specified for temporary files
  GetFullTempPathName("", MAX_BUF, szTempPath);
	GetFullTempPathName("Archive.lst",   sizeof(szArcLstFile),    szArcLstFile);
  GetFullTempPathName("SETUP.EXE",     sizeof(szSetupFile),     szSetupFile);
  GetFullTempPathName("uninstall.exe", sizeof(szUninstallFile), szUninstallFile);

  GetPrivateProfileString("Archives", "uninstall.exe", "", szBuf, sizeof(szBuf), szArcLstFile);
  if((FileExists(szUninstallFile) != FALSE) && (*szBuf != '\0'))
  {
    lstrcpy(szCmdLine, szUninstallFile);
  }
  else
  {
    lstrcpy(szCmdLine, szSetupFile);
    GetModuleFileName(NULL, szFilename, sizeof(szFilename));
    ParsePath(szFilename, xpiDir, sizeof(xpiDir), PP_PATH_ONLY);
    AppendBackSlash(xpiDir, sizeof(xpiDir));
    lstrcat(xpiDir, "xpi");
    if(FileExists(xpiDir))
    {
      GetShortPathName(xpiDir, szBuf, sizeof(szBuf));
      lstrcat(szCmdLine, " -a ");
      lstrcat(szCmdLine, szBuf);
    }
    lstrcat(szCmdLine, " -n ");
    lstrcat(szCmdLine, szFilename);
  }

  if(szCmdLine != NULL)
    lstrcat(szCmdLine, szCmdLineToSetup);

  // Launch the installer
  bRet = CreateProcess(NULL, szCmdLine, NULL, NULL, FALSE, 0, NULL, szTempPath, &sti, &pi);

  if (!bRet)
    return FALSE;

  CloseHandle(pi.hThread);

  // Wait for the InstallShield UI to appear before taking down the dialog box
  WaitForInputIdle(pi.hProcess, 3000);  // wait up to 3 seconds
  if(dwMode != SILENT)
  {
    DestroyWindow(dlgInfo.hWndDlg);
  }

  // Wait for the installer to complete
  WaitForSingleObject(pi.hProcess, INFINITE);
  CloseHandle(pi.hProcess);


  // Delete the files from the temp directory
  EnumResourceNames(NULL, "FILE", (ENUMRESNAMEPROC)DeleteTempFilesProc, 0);

  // delete archive.lst file in the temp directory
  GetFullTempPathName("Archive.lst", sizeof(szTmp), szTmp);
  DeleteFile(szTmp);
  GetFullTempPathName("xpcom.ns", sizeof(szTmp), szTmp);
  DirectoryRemove(szTmp, TRUE);
  DirectoryRemove(szTempPath, FALSE);
  return TRUE;
}
Example #12
0
/* ======================================================================== */
int SetAsShell (TCHAR * shellpath)
{
    dbg_printf(TEXT("Setting as shell..."));
    TCHAR temp[2000];
    int f = 0;
    /* okay, now really set it */
    if (_tcscmp(shellpath, TEXT("explorer.exe"))) {
        if (0 == shellpath[0]
            || 0 == SearchPath(NULL, shellpath, TEXT(".exe"), MAX_PATH, temp, NULL)) {
            error(MB_OK, TEXT("Error: File does not exist: '%s'"), shellpath);
            return 1;
        }
        _tcscpy(shellpath, temp);
    }
    dbg_printf(TEXT("shellpath=%s"), shellpath);

    if (0 == is_usingNT)
    {
        /* win9x/me */
        GetShortPathName(temp, shellpath, MAX_PATH);
        f = rw_ini(A_WR, temp);
    }
    else
    {
        if (is_admin)
        {
            dbg_printf(TEXT("set NT/admin/user/bootopt"));
            /* set the boot option that indicates whether to look
               for the shell in HKCU or HKLM */
            if (is_per_user)
                f = rw_reg(A_WR | A_SZ, HKEY_LOCAL_MACHINE, inimapstr, TEXT("Shell"), usr_bootOption);
            else
                f = rw_reg(A_WR | A_SZ, HKEY_LOCAL_MACHINE, inimapstr, TEXT("Shell"), sys_bootOption);

            dbg_printf(TEXT("set NT/admin/user/bootopt: ret=%d"), f);

            if (f) {
                /* flush the IniFileMapping cache (NT based systems) */
                WritePrivateProfileStringW(NULL, NULL, NULL, TEXT("system.ini"));
            } else {
                error(MB_OK, TEXT("Error: Could not set Boot Option."));
                return 1;
            }
        }

        dbg_printf(TEXT("set NT/user/shell_hkcu"));
        if (is_per_user)
        {
            /* set shell in HKCU */
            f = rw_reg(A_WR | A_SZ, HKEY_CURRENT_USER, logonstr, TEXT("Shell"), shellpath);
        }
        else
        {
            /* remove shell from HKCU */
            f = rw_reg(A_DEL, HKEY_CURRENT_USER, logonstr, TEXT("Shell"), NULL);
        }
        dbg_printf(TEXT("set NT/user/shell_hkcu: ret=%d"), f);

        if (is_admin)
        {
            dbg_printf(TEXT("set NT/user/shell_hklm"));
            if (is_per_user)
                /* set explorer as default for all users */
                f = rw_reg(A_WR | A_SZ, HKEY_LOCAL_MACHINE, logonstr, TEXT("Shell"), szExplorer);
            else
                /* set our shell for all users */
                f = rw_reg(A_WR | A_SZ, HKEY_LOCAL_MACHINE, logonstr, TEXT("Shell"), shellpath);
            dbg_printf(TEXT("set NT/user/shell_hklm: ret=%d"), f);
        }
    }

    if (0 == f)
    {
        error(MB_OK, TEXT("Error: Could not set '%s' as shell."), shellpath);
        return 1;
    }

    dbg_printf(TEXT("Setting as shell... done."));
    return 0;
}
Example #13
0
int RunSession( HWND hwnd, const char * folder_in, char * session_in ) {
	char buffer[4096]="", shortname[1024]="" ;
	char *session=NULL ;
	int return_code=0 ;
	
	if( session_in==NULL ) return 0 ;
	if( strlen(session_in) <= 0 ) return 0 ;
		
	if( !GetModuleFileName( NULL, (LPTSTR)buffer, 1023 ) ) return 0 ;
	if( !GetShortPathName( buffer, shortname, 1023 ) ) return 0 ;

	session = (char*)malloc(strlen(session_in)+100) ;
	
	if( (IniFileFlag==SAVEMODE_REG)||(IniFileFlag==SAVEMODE_FILE) ) {
		mungestr(session_in, session) ;
		sprintf( buffer, "%s\\Sessions\\%s", TEXT(PUTTY_REG_POS), session ) ;
		if( RegTestKey(HKEY_CURRENT_USER, buffer) ) {
			strcpy( session, session_in ) ;
			if( session[strlen(session)-1] == '&' ) {
				session[strlen(session)-1]='\0' ;
				while( (session[strlen(session)-1]==' ')||(session[strlen(session)-1]=='\t') ) session[strlen(session)-1]='\0' ;
				if( PuttyFlag )	sprintf( buffer, "%s -putty -load \"%s\" -send-to-tray", shortname, session ) ;
				else sprintf( buffer, "%s -load \"%s\" -send-to-tray", shortname, session ) ;
				}
			else {
				if( PuttyFlag )	sprintf( buffer, "%s -putty -load \"%s\"", shortname, session ) ;
				else sprintf( buffer, "%s -load \"%s\"", shortname, session ) ;
				}
			RunCommand( hwnd, buffer ) ;
			return_code = 1 ;
			}
		else { RunCommand( hwnd, session_in ) ; }
		}
	else if( IniFileFlag==SAVEMODE_DIR ) {
		if( DirectoryBrowseFlag ) {
			if( strcmp(folder_in,"")&&strcmp(folder_in,"Default") ) {
				strcat( shortname, " -folder \"" ) ;
				strcat( shortname, folder_in ) ;
				strcat( shortname, "\"" ) ;
				}
			}

		strcpy( session, session_in ) ;
		if( session[strlen(session)-1] == '&' ) {
			session[strlen(session)-1]='\0' ;
			while( (session[strlen(session)-1]==' ')||(session[strlen(session)-1]=='\t') ) session[strlen(session)-1]='\0' ;
			if( PuttyFlag )	sprintf( buffer, "%s -putty -load \"%s\" -send-to-tray", shortname, session ) ;
			else sprintf( buffer, "%s -load \"%s\" -send-to-tray", shortname, session ) ;
			}
		else {
			if( PuttyFlag )	sprintf( buffer, "%s -putty -load \"%s\"", shortname, session ) ;
			else sprintf( buffer, "%s -load \"%s\"", shortname, session ) ;
			//else sprintf( buffer, "%s @%s", shortname, session ) ;
			}
/*		if( DirectoryBrowseFlag ) {
			if( strcmp(folder_in,"")&&strcmp(folder_in,"Default") ) {
				strcat( buffer, " -folder \"" ) ;
				strcat( buffer, folder_in ) ;
				strcat( buffer, "\"" ) ;
				}
			}*/
//MessageBox( hwnd, buffer, "Info", MB_OK ) ;
		RunCommand( hwnd, buffer ) ;
		return_code = 1 ;
		}

	free( session ) ;
	return return_code ;
	}
Example #14
0
char *fb_hGetShortPath( char *src, char *dst, int maxlen )
{
#if defined( HOST_DOS )
	if( strchr( src, 32 ) == NULL ) {
		strcpy( dst, src );
    } else {
        /* FIXME: SPC is only allowed when using LFNs provided by a Windows
         * environment. So I guess that we have to use the following INT
         * function:
         *
         * IN:
         *
         * AX = 0x7160
         * CL = 0x01
         * CH = SUBST expansion flag, 0x00 = true path for SUBSTed drive letter
         *                            0x80 = SUBSTed drive letter
         * DS:SI = ASCIZ FLN
         * ES:DI = buffer for SFN ( max size = 67 or 128 ??? )
         *
         * OUT:
         *
         * CF = 1 on error
         *      AX = error code
         *
         */
        strncpy( dst, src, maxlen-1 );
        dst[maxlen-1] = 0;
	}

	return dst;

#elif defined( HOST_UNIX )
	if( strchr( src, 32 ) == NULL ) {
		strcpy( dst, src );
	} else {
		int i = 0;
		char *old_dst = dst;

		while ((*src) && (i < maxlen - 1)) {
			if (*src == ' ') {
				*dst++ = '\\';
				i++;
			}
			if (i == maxlen - 1)
				break;
			*dst++ = *src++;
			i++;
		}
		dst = old_dst;
		dst[maxlen - 1] = '\0';
	}

	return dst;

#elif defined( HOST_WIN32 )
	if( strchr( src, 32 ) == NULL ) {
		strcpy( dst, src );
	} else {
	 	GetShortPathName( src, dst, maxlen );
	}
	return dst;

#else
	/* !!!WRITEME!!! */
	strncpy(dst, src, maxlen);
	return dst;
#endif
}
Example #15
0
void COwnedLostItem::GiveControlToNetscape()
{	
	char buffer[_MAX_PATH];
	::GetModuleFileName(theApp.m_hInstance, buffer, _MAX_PATH);
	
	// Get the app's directory into a short file name
	char shortBuffer[_MAX_PATH];
	GetShortPathName(buffer, shortBuffer, _MAX_PATH);

	CString directoryName(shortBuffer);
	directoryName.MakeUpper();  // This is what we'll write to the registry

	CString strValueName, strCmdPath;

	// Special Internet Shortcut check
	if (IsInternetShortcut())
	{
		CInternetShortcut internetShortcut;
		if (internetShortcut.ShellSupport())
		{
			// Need to take over lots of stuff
			CString strType = GetInternetShortcutFileClass();
			
			// Set the open command path
			strValueName.Format(strOPEN_CMD_FMT, (const char *)strType);
			strCmdPath = directoryName + " -h \"%1\"";
			FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strCmdPath);
		
			// Set the DDE exec value
			strValueName.Format(strDDE_EXEC_FMT, (const char *)strType);
			FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strDDE_EXEC_VALUE);

			// Set the DDE app name
			strValueName.Format(strDDE_APP_FMT, (const char *)strType);
			FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strDDE_APP_NAME);
							
			// Set the DDE topic
			strValueName.Format(strDDE_TOPIC_FMT, (const char *)strType);
			CString strDDETopic;
			strDDETopic.LoadString(IDS_DDE_OPENURL);
			FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strDDETopic);

			// Set the Default Icon
			CString strIconPath;
			if ((strType == "news") || (strType == "snews"))
			{
				// Use the news icon from URL.DLL
				::GetSystemDirectory(buffer, _MAX_PATH);
				strIconPath = CString(buffer) + "\\URL.DLL,1";
			}  
			else
			{
				// Use the document icon
				strIconPath = CString(buffer) + ",1";
			}  
			strValueName.Format(strDEF_ICON_FMT, (const char *)strType);
			FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strIconPath);
			
			// Take over printing (applies to ALL Internet Shortcuts.  If we own one, we'll take
			// over printing for ALL of them).
			CString csMunge = directoryName + " /print(\"%1\")";
			FEU_RegistryWizard(HKEY_CLASSES_ROOT, "InternetShortcut\\shell\\print\\command", csMunge);
            FEU_RegistryWizard(HKEY_CLASSES_ROOT, "InternetShortcut\\shell\\print\\ddeexec", "[print(\"%1\")]");
            FEU_RegistryWizard(HKEY_CLASSES_ROOT, "InternetShortcut\\shell\\print\\ddeexec\\Application", strDDE_APP_NAME);

			//  The PrintTo Command.
            csMunge = directoryName + " /printto(\"%1\",\"%2\",\"%3\",\"%4\")";
            FEU_RegistryWizard(HKEY_CLASSES_ROOT, "InternetShortcut\\shell\\PrintTo\\command", csMunge);
            FEU_RegistryWizard(HKEY_CLASSES_ROOT, "InternetShortcut\\shell\\PrintTo\\ddeexec", "[printto(\"%1\",\"%2\",\"%3\",\"%4\")]");
            FEU_RegistryWizard(HKEY_CLASSES_ROOT, "InternetShortcut\\shell\\PrintTo\\ddeexec\\Application", strDDE_APP_NAME);
		}

		return;
	}

	CPtrList* allHelpers = &(CHelperApp::m_cplHelpers);

	for (POSITION pos = allHelpers->GetHeadPosition(); pos != NULL;)
	{
		CHelperApp* app = (CHelperApp*)allHelpers->GetNext(pos);
		CString helperMime(app->cd_item->ci.type);

		if (helperMime == m_csMimeType)
		{
			// Found the helper app.  Get the file class.
			CString fileClass(app->strFileClass);
			if (fileClass != "")
			{
				// We have some registry work to do.
				// In the case where this is text/html, we point .htm and .html to
				// NetscapeMarkup.
				HKEY hKey;
				DWORD dwDisp;

				if (m_csMimeType == "text/html")
				{
					::RegCreateKeyEx(HKEY_CLASSES_ROOT,
						".htm", 0L, NULL,
						REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,
						&hKey, &dwDisp);
					::RegSetValueEx(hKey, NULL, 0L, REG_SZ,
						(const BYTE *)((const char *)strMARKUP_KEY),
						strMARKUP_KEY.GetLength() + 1);
					::RegCloseKey(hKey);
					
					::RegCreateKeyEx(HKEY_CLASSES_ROOT,
						".html", 0L, NULL,
						REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,
						&hKey, &dwDisp);
					::RegSetValueEx(hKey, NULL, 0L, REG_SZ,
						(const BYTE *)((const char *)strMARKUP_KEY),
						strMARKUP_KEY.GetLength() + 1);
					::RegCloseKey(hKey);	
				}

				// In the case where this is application/x-unknown-content-type-NetscapeMarkup, 
				// we point .shtml to NetscapeMarkup.
				else if (m_csMimeType == "application/x-unknown-content-type-NetscapeMarkup")
				{
					::RegCreateKeyEx(HKEY_CLASSES_ROOT,
						".shtml", 0L, NULL,
						REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,
						&hKey, &dwDisp);
					::RegSetValueEx(hKey, NULL, 0L, REG_SZ,
						(const BYTE *)((const char *)strMARKUP_KEY),
						strMARKUP_KEY.GetLength() + 1);
					::RegCloseKey(hKey);
					
				}

				// In all other cases, we should use the existing file class
				else
				{
					// Need to take over lots of stuff
					CString strType = fileClass;
					if (strType == "NetscapeMarkup")
					  return; // Don't let ANYTHING mess with NetscapeMarkup.
							  // Someone might point something to it later, and
							  // we don't want this code changing the stuff that's already there.

					// Set the open command path
					strValueName.Format(strOPEN_CMD_FMT, (const char *)strType);
					strCmdPath = directoryName + " \"%1\"";
					FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strCmdPath);
		
					// Set the DDE exec value
					strValueName.Format(strDDE_EXEC_FMT, (const char *)strType);
					FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strDDE_EXEC_VALUE);

					// Set the DDE app name
					strValueName.Format(strDDE_APP_FMT, (const char *)strType);
					FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strDDE_APP_NAME);
							
					// Set the DDE topic
					strValueName.Format(strDDE_TOPIC_FMT, (const char *)strType);
					CString strDDETopic;
					strDDETopic.LoadString(IDS_DDE_OPENURL);
					FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strDDETopic);

					// Set the Default Icon
					CString strIconPath;
					CString iconString = ",1";
					if (m_csMimeType == "text/x-javascript" || m_csMimeType == "application/x-javascript")
						iconString = ",7";
					else if (m_csMimeType.Left(5) == "image")
						iconString = ",6";

					strIconPath = CString(buffer) + iconString;
					  
					strValueName.Format(strDEF_ICON_FMT, (const char *)strType);
					FEU_RegistryWizard(HKEY_CLASSES_ROOT, strValueName, strIconPath);
				}
			}

			return;
		}
	}

}
// Falta obtener el tiempo del audio
TMedio *InformacionArchivoEx::ObtenerInfo(const TCHAR *Path, TipoArchivo &TiposArchivo, Unidades_Disco &Unidades, std::vector<DatosPathBuscar> &Buscar_Paths, libvlc_instance_t *InstanciaVLC, FMOD::System *InstanciaFMOD) {
    // Lo primero es determinar si es un archivo de audio o de video
	DWL::DWLString	PathStr = Path;
	UINT64			Tiempo  = 0;
	UINT			Ancho   = 0;
	UINT			Alto    = 0;
	bool            EsVideo = false;
	DWL::DWLString  Tmp;

	// Comprobamos que exista la ruta del archivo
	TCHAR PathCorto[MAX_PATH + 1];
	ZeroMemory(PathCorto, MAX_PATH + 1);
	GetShortPathName(Path, PathCorto, MAX_PATH + 1);
	if (PathCorto[0] == 0) return NULL;


	Tipo_Medio TipoMedio = _TipoMedio(PathStr, TiposArchivo); 
	// Si es del tipo video, puede ser que dicho contenedor de video solo tenga audio dentro, por lo que se considerara dicho medio como audio a pesar de su extensión.
	if (TipoMedio == Tipo_Medio_Video || TipoMedio == Tipo_Medio_INDEFINIDO) {
		EsVideo = true;
		TipoArchivo_Datos *nDatos = TiposArchivo.BuscarTipoArchivo(Path);
		if (nDatos != NULL) {
			if (nDatos->ID == EXT_ASF || nDatos->ID == EXT_MP4 || nDatos->ID == EXT_OGG) {
				EsVideo = _AnalisisVLC(Path, Tiempo, Ancho, Alto, InstanciaVLC);
			}
		}

		if (EsVideo == false && TipoMedio != Tipo_Medio_INDEFINIDO) TipoMedio = Tipo_Medio_Audio;
	}
	if (TipoMedio == Tipo_Medio_INDEFINIDO && EsVideo == true) TipoMedio = Tipo_Medio_Video;

	//	else												EsVideo = false;

	Unidad_Disco *UD = Unidades.Buscar_Letra(Path[0]);	
	OrdenEstructuraDirectorios TipoOrden = Indefinido;
	bool                       PathAntesQueTag = false;
	_AnalizarPath(PathStr, TipoMedio, Buscar_Paths);
	switch (TipoMedio) {
		case Tipo_Medio_Subtitulos :
			TMedioSubtitulos *InfoSubtitulos;
			InfoSubtitulos = new TMedioSubtitulos;
			InfoSubtitulos->Path = PathStr;
			return InfoSubtitulos;
		case Tipo_Medio_Audio :
			// Buscamos los datos de su path buscar (si es que existen)
			for (size_t n = 0; n < Buscar_Paths.size(); n++) {
				if (Buscar_Paths[n].Path == PathStr.SubStr(0, Buscar_Paths[n].Path.Tam())) {
					TipoOrden = Buscar_Paths[n].TipoOrden;
					PathAntesQueTag = Buscar_Paths[n].PathAntesQueTag;
				}
			}
				
			TMedioPreAudio *InfoAudio;
			InfoAudio = new TMedioPreAudio;
			// Examinamos los tags y de paso obtenemos la longitud del archivo
			InfoAudio->Longitud = ObtenerMetaDatosAudio(Path, TiposArchivo); 

			// Obtengo los mejores valores posibles necesarios
			MetaDato *InfoNombre;
			InfoNombre = _BuscarNombre();
			MetaDato *InfoGenero;
			InfoGenero = _BuscarGenero();
			MetaDato *InfoGrupo;
			InfoGrupo = _BuscarGrupo();
			MetaDato *InfoDisco;
			InfoDisco = _BuscarDisco();
			MetaDato *InfoPista;
			InfoPista = _BuscarPista();

			InfoAudio->Path			= PathStr;
			InfoAudio->NombreTipo	= InfoPath.Tipo();
		
			if (PathAntesQueTag == false) { // Primero el tag
				// [Nombre] por cojones como minimo hay el nombre en el archivo por lo que nunca sera desconocido
				if (InfoNombre == NULL) {
					_Filtro(InfoPath.Nombre(), &InfoAudio->Nombre);
				}
				else {
					if (InfoNombre->Datos.Tam() > 0)	_Filtro(InfoNombre->Datos(), &InfoAudio->Nombre);
					if (InfoAudio->Nombre.Tam() == 0)	_Filtro(InfoPath.Nombre(), &InfoAudio->Nombre);
				}
		
				// [Genero]
				if (InfoGenero != NULL) _Filtro(InfoGenero->Datos(), &InfoAudio->NombreGenero);
				else					_Filtro(InfoPath.Genero(), &InfoAudio->NombreGenero);
				// - Un filtro de un string que contiene solo espacios puede retornar un nombre vacio
				if (InfoAudio->NombreGenero.Tam() == 0) InfoAudio->NombreGenero = TEXT("1024"); // El genero numerico 1024 no existe y retornara Genero desconocido

				// [Grupo]
				if (InfoGrupo == NULL) {
					if (InfoPath.Grupo.Tam() > 0)			_Filtro(InfoPath.Grupo(), &InfoAudio->NombreGrupo);
				}
				else {
					if (InfoGrupo->Datos.Tam() > 0)			_Filtro(InfoGrupo->Datos(), &InfoAudio->NombreGrupo); 
					if (InfoAudio->NombreGrupo.Tam() == 0)	_Filtro(InfoPath.Grupo(), &InfoAudio->NombreGrupo);
				}
				// - Un filtro de un string que contiene solo espacios puede retornar un nombre vacio
				if (InfoAudio->NombreGrupo.Tam() == 0)	
					InfoAudio->NombreGrupo = TEXT("?");
		
				// [Disco]
				if (InfoDisco == NULL) {
					if (InfoPath.Disco.Tam() > 0)			_Filtro(InfoPath.Disco(), &InfoAudio->NombreDisco);
				}
				else {
					if (InfoDisco->Datos.Tam() > 0)			_Filtro(InfoDisco->Datos(), &InfoAudio->NombreDisco);
					if (InfoAudio->NombreDisco.Tam() == 0)	_Filtro(InfoPath.Disco(), &InfoAudio->NombreDisco);
				}
				// - Un filtro de un string que contiene solo espacios puede retornar un nombre vacio
				if (InfoAudio->NombreDisco.Tam() == 0)	
					InfoAudio->NombreDisco = TEXT("?");

				// [Pista]
				if (InfoPista == NULL)  InfoAudio->Pista = InfoPath.Pista;
				else { // No tienen porque venir los datos de la pista solo con un valor
					DWL::DWLString PistaFinal;
					bool EsNum = true;
					for (size_t n = 0; (n < InfoPista->Datos.Tam() && EsNum == true); n++) {
						EsNum = _EsNumero(InfoPista->Datos[n]);
						if (EsNum == true) PistaFinal += InfoPista->Datos[n];
					}
					if (PistaFinal.Tam() > 0)	InfoAudio->Pista = _wtoi(PistaFinal());
					else						InfoAudio->Pista = InfoPath.Pista;
					// Si en el tag trae pista 0 o algo raro metemos la del path
					if (InfoAudio->Pista < 1)	InfoAudio->Pista = InfoPath.Pista;
				}
			}
			else { // Primero el path
				// [Nombre] por cojones como minimo hay el nombre en el archivo por lo que nunca sera desconocido
				_Filtro(InfoPath.Nombre(), &InfoAudio->Nombre);
				// [Genero]
				if (InfoPath.Genero.Tam() != 0) _Filtro(InfoPath.Genero(), &InfoAudio->NombreGenero);
				else {
					if (InfoGenero != NULL) {
						if (InfoGenero->Datos.Tam() != 0) _Filtro(InfoGenero->Datos(), &InfoAudio->NombreGenero);
					}
				}
				// - Un filtro de un string que contiene solo espacios puede retornar un nombre vacio
				if (InfoAudio->NombreGenero.Tam() == 0) InfoAudio->NombreGenero = TEXT("1024"); // El genero numerico 1024 no existe y retornara Genero desconocido
				// [Grupo]
				if (InfoPath.Grupo.Tam() != 0) {
					_Filtro(InfoPath.Grupo(), &InfoAudio->NombreGrupo);
					if (InfoAudio->NombreGrupo.Tam() == 0 && InfoGrupo->Datos.Tam() > 0) _Filtro(InfoGrupo->Datos(), &InfoAudio->NombreGrupo);
				}
				else {
					if (InfoGrupo != NULL) {
						if (InfoGrupo->Datos.Tam() > 0)	_Filtro(InfoGrupo->Datos(), &InfoAudio->NombreGrupo); 
					}
				}
				// - Un filtro de un string que contiene solo espacios puede retornar un nombre vacio
				if (InfoAudio->NombreGrupo.Tam() == 0)	
					InfoAudio->NombreGrupo = TEXT("?");
				// [Disco]
				if (InfoPath.Disco.Tam() != 0) {
					_Filtro(InfoPath.Disco(), &InfoAudio->NombreDisco);
					if (InfoAudio->NombreDisco.Tam() == 0 && InfoDisco->Datos.Tam() > 0) _Filtro(InfoDisco->Datos(), &InfoAudio->NombreDisco);
				}
				else {
					if (InfoDisco != NULL) {
						if (InfoDisco->Datos.Tam() > 0)	_Filtro(InfoDisco->Datos(), &InfoAudio->NombreDisco);
					}
				}
				// - Un filtro de un string que contiene solo espacios puede retornar un nombre vacio
				if (InfoAudio->NombreDisco.Tam() == 0)	
					InfoAudio->NombreDisco = TEXT("?");
				// [Pista]
				if (InfoPath.Pista > 0)  InfoAudio->Pista = InfoPath.Pista;
				else { // No tienen porque venir los datos de la pista solo con un valor
					DWL::DWLString PistaFinal;
					bool EsNum = true;
					if (InfoPista != NULL) {
						for (size_t n = 0; (n < InfoPista->Datos.Tam() && EsNum == true); n++) {
							EsNum = _EsNumero(InfoPista->Datos[n]);
							if (EsNum == true) PistaFinal += InfoPista->Datos[n];
						}
						if (PistaFinal.Tam() > 0)	InfoAudio->Pista = _wtoi(PistaFinal());
						else						InfoAudio->Pista = 0;
					}
					else {
						InfoAudio->Pista = 0;
					}
				}


			}
			InfoAudio->Reproducido	= 0;
			InfoAudio->Tiempo		= _ObtenerTiempoCancion(Path, InstanciaFMOD);
	//		InfoAudio->Longitud		= _ObtenerLongitud(PathStr()); // la estamos obteniendo desde ObtenerMetaDatosAudio que tambien abre el archivo
			if (UD == NULL) InfoAudio->ID_Disco		= 0; // es una unidad de red
			else			InfoAudio->ID_Disco		= UD->Numero_Serie();
			InfoAudio->Nota			= 2;
			InfoAudio->Item			= NULL;
			InfoAudio->Nodo			= NULL;
			InfoAudio->TipoMedio    = Tipo_Medio_PreAudio; // falta por analizar sus raices (generos, grupos, discos, anomalias)
			return InfoAudio;
		case Tipo_Medio_Video :
			TMedioVideo *InfoVideo;
			InfoVideo = new TMedioVideo;
			InfoVideo->Path			= PathStr;
			_Filtro(InfoPath.Nombre(), &InfoVideo->Nombre);
			InfoVideo->Reproducido	= 0;
			InfoVideo->Tiempo		= Tiempo;
			InfoVideo->Longitud		= _ObtenerLongitud(PathStr());
			if (UD == NULL) InfoVideo->ID_Disco		= 0; // es una unidad de red
			else			InfoVideo->ID_Disco		= UD->Numero_Serie();
			InfoVideo->Nota			= 2;
			InfoVideo->Item			= NULL;
			InfoVideo->Nodo			= NULL;
			InfoVideo->Pista		= InfoPath.Pista;
			InfoVideo->Alto			= Alto;
			InfoVideo->Ancho		= Ancho;
			InfoVideo->TipoMedio    = Tipo_Medio_Video;
			return InfoVideo;
		case Tipo_Medio_Lista :
			TMedioListaM3u *InfoLista;
			InfoLista = new TMedioListaM3u;
			InfoLista->Path			= PathStr;
			_Filtro(InfoPath.Nombre(), &InfoLista->Nombre);
			InfoLista->Reproducido	= 0;
			InfoLista->Tiempo		= 0;
			InfoLista->Longitud		= _ObtenerLongitud(PathStr());
			if (UD == NULL) InfoLista->ID_Disco		= 0; // es una unidad de red
			else			InfoLista->ID_Disco		= UD->Numero_Serie();
			InfoLista->Nota			= 2;
			InfoLista->Item			= NULL;
			InfoLista->Nodo			= NULL;
			InfoLista->TipoMedio    = Tipo_Medio_Lista;
			return InfoLista;
		case Tipo_Medio_CDAudio :
//			_AnalizarPathPistaAudio(PathStr);
			TMedioCDAudio *InfoCDAudio;
			InfoCDAudio = new TMedioCDAudio;
			InfoCDAudio->Path		 = PathStr;
			_Filtro(InfoPath.Nombre(), &InfoCDAudio->Nombre);
			InfoCDAudio->Reproducido = 0;
			InfoCDAudio->Tiempo		 = _ObtenerTiempoCancionCDAudio(Path, InstanciaFMOD);
			InfoCDAudio->Longitud	 = _ObtenerLongitud(PathStr());
			if (UD == NULL) InfoCDAudio->ID_Disco		= 0; // es una unidad de red
			else			InfoCDAudio->ID_Disco		= UD->Numero_Serie();
			InfoCDAudio->Nota		 = 2;
			InfoCDAudio->Item		 = NULL;
			InfoCDAudio->Nodo		 = NULL;
			InfoCDAudio->TipoMedio   = Tipo_Medio_CDAudio;
			InfoCDAudio->Pista       = InfoPath.Pista;
			return InfoCDAudio;
	}


	return NULL;
}
Example #17
0
/* This might be given a command line (whole = 0) or just the
   executable (whole = 1).  In the later case the path may or may not
   be quoted */
static char *expandcmd(const char *cmd, int whole)
{
    char c = '\0';
    char *s, *p, *q = NULL, *f, *dest, *src;
    int   d, ext, len = strlen(cmd)+1;
    char buf[len], fl[len], fn[MAX_PATH];

    /* make a copy as we manipulate in place */
    strcpy(buf, cmd);

    // This is the return value.
    if (!(s = (char *) malloc(MAX_PATH + strlen(cmd)))) {
	strcpy(RunError, "Insufficient memory (expandcmd)");
	return NULL;
    }
    /* skip leading spaces */
    for (p = buf; *p && isspace(*p); p++);
    /* find the command itself, possibly double-quoted */
    if (whole) {
	d = 0;
    } else { // command line
	for (q = p, d = 0; *q && ( d || !isspace(*q) ); q++)
	    if (*q == '\"') d = d ? 0 : 1;
	if (d) {
	    strcpy(RunError, "A \" is missing (expandcmd)");
	    return NULL;
	}
	c = *q; /* character after the command, normally a space */
	*q = '\0';
    }

    /*
     * Guido resorted to this since SearchPath returned FOUND also
     * for file name without extension -> explicitly set
     *  extension
     */
    for (f = p, ext = 0 ; *f ; f++) {
	if ((*f == '\\') || (*f == '/')) ext = 0;
	else if (*f == '.') ext = 1;
    }
    /* SearchPath doesn't like ", so strip out quotes */
    for (dest = fl , src = p; *src ; src++)
	if (*src != '"') *dest++ = *src;
    *dest = '\0';
    if (ext) {
	/*
	 * user set extension; we don't check that it is executable;
	 * it might get an error after; but maybe sometimes
	 * in the future every extension will be executable
	 */
	d = SearchPath(NULL, fl, NULL, MAX_PATH, fn, &f);
    } else {
	int iexts = 0;
	const char *exts[] = { ".exe" , ".com" , ".cmd" , ".bat" , NULL };
	while (exts[iexts]) {
	    strcpy(dest, exts[iexts]);
	    if ((d = SearchPath(NULL, fl, NULL, MAX_PATH, fn, &f))) break;
	    iexts++ ;
	}
    }
    if (!d) {
	free(s);
	snprintf(RunError, 500, "'%s' not found", p);
	if(!whole) *q = c;
	return NULL;
    }
    /*
      NB: as of Windows 7 SearchPath does not return short names any more.

      Paranoia : on my system switching to short names is not needed
      since SearchPath already returns 'short names'. However,
      this is not documented so I prefer to be explicit.
    */
    GetShortPathName(fn, s, MAX_PATH);
    if (!whole) {
	*q = c;
	strcat(s, q);
    }
    return s;
}
bool RunCommands(CCommandArray& Commands, LPCTSTR pszOrigDocName)
{
	s_bRunsCommands = true;

	char szCurDir[MAX_PATH];
	_getcwd(szCurDir, MAX_PATH);

	procWnd.GetReady();

	// cut up document name into file and extension components.
	//  create two sets of buffers - one set with the long filename
	//  and one set with the 8.3 format.

	char szDocLongPath[MAX_PATH] = {0}, szDocLongName[MAX_PATH] = {0}, 
		szDocLongExt[MAX_PATH] = {0};
	char szDocShortPath[MAX_PATH] = {0}, szDocShortName[MAX_PATH] = {0}, 
		szDocShortExt[MAX_PATH] = {0};

	GetFullPathName(pszOrigDocName, MAX_PATH, szDocLongPath, NULL);
	GetShortPathName(pszOrigDocName, szDocShortPath, MAX_PATH);

	// split them up
	char *p = strrchr(szDocLongPath, '.');
	if(p && strrchr(szDocLongPath, '\\') < p && strrchr(szDocLongPath, '/') < p)
	{
		// got the extension
		strcpy(szDocLongExt, p+1);
		p[0] = 0;
	}

	p = strrchr(szDocLongPath, '\\');
	if(!p)
		p = strrchr(szDocLongPath, '/');
	if(p)
	{
		// got the filepart
		strcpy(szDocLongName, p+1);
		p[0] = 0;
	}

	// split the short part up
	p = strrchr(szDocShortPath, '.');
	if(p && strrchr(szDocShortPath, '\\') < p && strrchr(szDocShortPath, '/') < p)
	{
		// got the extension
		strcpy(szDocShortExt, p+1);
		p[0] = 0;
	}

	p = strrchr(szDocShortPath, '\\');
	if(!p)
		p = strrchr(szDocShortPath, '/');
	if(p)
	{
		// got the filepart
		strcpy(szDocShortName, p+1);
		p[0] = 0;
	}

	int iSize = Commands.GetSize(), i = 0;
	char *ppParms[32];
	while(iSize--)
	{
		CCOMMAND &cmd = Commands[i++];

		// anything there?
		if((!cmd.szRun[0] && !cmd.iSpecialCmd) || !cmd.bEnable)
			continue;

		// set name pointers for long filenames
		pszDocExt = szDocLongExt;
		pszDocName = szDocLongName;
		pszDocPath = szDocLongPath;
		
		char szNewParms[MAX_PATH*5], szNewRun[MAX_PATH*5];

		// HACK: force the spawnv call for launching the game
		if (!Q_stricmp(cmd.szRun, "$game_exe"))
		{
			cmd.bUseProcessWnd = FALSE;
		}

		FixGameVars(cmd.szRun, szNewRun, TRUE);
		FixGameVars(cmd.szParms, szNewParms, TRUE);

		CString strTmp;
		strTmp.Format("\r\n"
			"** Executing...\r\n"
			"** Command: %s\r\n"
			"** Parameters: %s\r\n\r\n", szNewRun, szNewParms);
		procWnd.Append(strTmp);
		
		// create a parameter list (not always required)
		if(!cmd.bUseProcessWnd || cmd.iSpecialCmd)
		{
			char *p = szNewParms;
			ppParms[0] = szNewRun;
			int iArg = 1;
			BOOL bDone = FALSE;
			while(p[0])
			{
				ppParms[iArg++] = p;
				while(p[0])
				{
					if(p[0] == ' ')
					{
						// found a space-separator
						p[0] = 0;

						p++;

						// skip remaining white space
						while (*p == ' ')
							p++;

						break;
					}

					// found the beginning of a quoted parameters
					if(p[0] == '\"')
					{
						while(1)
						{
							p++;
							if(p[0] == '\"')
							{
								// found the end
								if(p[1] == 0)
									bDone = TRUE;
								p[1] = 0;	// kick its ass
								p += 2;

								// skip remaining white space
								while (*p == ' ')
									p++;

								break;
							}
						}
						break;
					}

					// else advance p
					++p;
				}

				if(!p[0] || bDone)
					break;	// done.
			}

			ppParms[iArg] = NULL;

			if(cmd.iSpecialCmd)
			{
				BOOL bError = FALSE;
				LPCTSTR pszError = "";

				if(cmd.iSpecialCmd == CCCopyFile && iArg == 3)
				{
					RemoveQuotes(ppParms[1]);
					RemoveQuotes(ppParms[2]);
					
					// don't copy if we're already there
					if (stricmp(ppParms[1], ppParms[2]) && 					
							(!CopyFile(ppParms[1], ppParms[2], FALSE)))
					{
						bError = TRUE;
						pszError = GetErrorString();
					}
				}
				else if(cmd.iSpecialCmd == CCDelFile && iArg == 2)
				{
					RemoveQuotes(ppParms[1]);
					if(!DeleteFile(ppParms[1]))
					{
						bError = TRUE;
						pszError = GetErrorString();
					}
				}
				else if(cmd.iSpecialCmd == CCRenameFile && iArg == 3)
				{
					RemoveQuotes(ppParms[1]);
					RemoveQuotes(ppParms[2]);
					if(rename(ppParms[1], ppParms[2]))
					{
						bError = TRUE;
						pszError = strerror(errno);
					}
				}
				else if(cmd.iSpecialCmd == CCChangeDir && iArg == 2)
				{
					RemoveQuotes(ppParms[1]);
					if(mychdir(ppParms[1]) == -1)
					{
						bError = TRUE;
						pszError = strerror(errno);
					}
				}

				if(bError)
				{
					CString str;
					str.Format("The command failed. Windows reported the error:\r\n"
						"  \"%s\"\r\n", pszError);
					procWnd.Append(str);
					procWnd.SetForegroundWindow();
					str += "\r\nDo you want to continue?";
					if(AfxMessageBox(str, MB_YESNO) == IDNO)
						break;
				}
			}
			else
			{
				// Change to the game exe folder before spawning the engine.
				// This is necessary for Steam to find the correct Steam DLL (it
				// uses the current working directory to search).
				char szDir[MAX_PATH];
				Q_strncpy(szDir, szNewRun, sizeof(szDir));
				Q_StripFilename(szDir);

				mychdir(szDir);

				// YWB Force asynchronous operation so that engine doesn't hang on
				//  exit???  Seems to work.
				// spawnv doesn't like quotes
				RemoveQuotes(szNewRun);
				_spawnv(/*cmd.bNoWait ?*/ _P_NOWAIT /*: P_WAIT*/, szNewRun, 
					(const char *const *)ppParms);
			}
		}
		else
		{
			procWnd.Execute(szNewRun, szNewParms);
		}

		// check for existence?
		if(cmd.bEnsureCheck)
		{
			char szFile[MAX_PATH];
			FixGameVars(cmd.szEnsureFn, szFile, FALSE);
			if(GetFileAttributes(szFile) == 0xFFFFFFFF)
			{
				// not there!
				CString str;
				str.Format("The file '%s' was not built.\n"
					"Do you want to continue?", szFile);
				procWnd.SetForegroundWindow();
				if(AfxMessageBox(str, MB_YESNO) == IDNO)
					break;	// outta here
			}
		}
	}

	mychdir(szCurDir);

	s_bRunsCommands = false;

	return TRUE;
}
Example #19
0
/* initDirPathArray() -- Initializes the afs dir paths for the 
 *     server and client installations.
 *
 *     For NT these are determined dynamically; for Unix they are static.
 *
 *     NT NOTE: If a particular component (client/server) is not installed
 *              then we may not be able to initialize the paths to anything
 *              meaningful.  In this case the paths are set to the local
 *              temp directory to avoid later reference to an uninitialized
 *              variable.  The initStatus flag is set to indicate which
 *              paths (client/server) initialized properly for callers of
 *              initAFSDirPath() who would like to know this information.
 */
static void
initDirPathArray(void)
{
    char *pathp;
    const char *clientPrefix = "";
    const char *serverPrefix = "";

#ifdef AFS_NT40_ENV
    char *buf;
    int status;

    /* get the afs server software installation dir from the registry */
    if (afssw_GetServerInstallDir(&buf)) {
	/* failed; server not installed; use temp directory */
	strcpy(ntServerInstallDirLong, gettmpdir());
    } else {
	strcpy(ntServerInstallDirLong, buf);
	free(buf);
	initStatus |= AFSDIR_SERVER_PATHS_OK;
    }
    FilepathNormalize(ntServerInstallDirLong);
    status =
	GetShortPathName(ntServerInstallDirLong, ntServerInstallDirShort,
			 AFSDIR_PATH_MAX);
    if (status == 0 || status > AFSDIR_PATH_MAX) {
	/* can't convert path to short version; just use long version */
	strcpy(ntServerInstallDirShort, ntServerInstallDirLong);
    }
    FilepathNormalize(ntServerInstallDirShort);

    /* get the afs client configuration directory (/usr/vice/etc equivalent) */
    if (afssw_GetClientCellServDBDir(&buf)) {
        /* failed */
        status = GetWindowsDirectory(ntClientConfigDirLong, AFSDIR_PATH_MAX);
        if (status == 0 || status > AFSDIR_PATH_MAX) {
            /* failed to get canonical Windows directory; use temp directory */
            strcpy(ntClientConfigDirLong, gettmpdir());
        } else {
            initStatus |= AFSDIR_CLIENT_PATHS_OK;
        }
    } else {
        strcpy(ntClientConfigDirLong, buf);
        free(buf);
        initStatus |= AFSDIR_CLIENT_PATHS_OK;
    }
    FilepathNormalize(ntClientConfigDirLong);

    status =
	GetShortPathName(ntClientConfigDirLong, ntClientConfigDirShort,
			 AFSDIR_PATH_MAX);
    if (status == 0 || status > AFSDIR_PATH_MAX) {
	/* can't convert path to short version; just use long version */
	strcpy(ntClientConfigDirShort, ntClientConfigDirLong);
    }
    FilepathNormalize(ntClientConfigDirShort);
    clientPrefix = ntClientConfigDirShort;

    /* setup the root server directory path (/usr/afs equivalent) */
    strcpy(afsSrvDirPath, ntServerInstallDirShort);
    strcat(afsSrvDirPath, AFSDIR_CANONICAL_SERVER_AFS_DIRPATH);

    /* there is no root client directory path (/usr/vice equivalent) */
    afsClntDirPath[0] = '\0';

    /* setup top level dirpath (/usr equivalent); valid for server ONLY */
    strcpy(dirPathArray[AFSDIR_USR_DIRPATH_ID], ntServerInstallDirShort);
    serverPrefix = ntServerInstallDirShort;
    strcat(dirPathArray[AFSDIR_USR_DIRPATH_ID], AFSDIR_CANONICAL_USR_DIRPATH);

#else /* AFS_NT40_ENV */
    /* setup the root server directory path */
    strcpy(afsSrvDirPath, AFSDIR_CANONICAL_SERVER_AFS_DIRPATH);

    /* setup the root client directory path */
#ifdef AFS_DARWIN_ENV
    if (access(AFSDIR_ALTERNATE_CLIENT_VICE_DIRPATH, F_OK) == 0)
	strcpy(afsClntDirPath, AFSDIR_ALTERNATE_CLIENT_VICE_DIRPATH);
    else
#endif
	strcpy(afsClntDirPath, AFSDIR_CANONICAL_CLIENT_VICE_DIRPATH);

    /* setup top level dirpath; valid for both server and client */
    strcpy(dirPathArray[AFSDIR_USR_DIRPATH_ID], AFSDIR_CANONICAL_USR_DIRPATH);

    initStatus |= (AFSDIR_CLIENT_PATHS_OK | AFSDIR_SERVER_PATHS_OK);
#endif /* AFS_NT40_ENV */

    /* now initialize various dir and file paths exported by dirpath module */

    /* server dir paths */
    strcpy(dirPathArray[AFSDIR_SERVER_AFS_DIRPATH_ID], afsSrvDirPath);

    pathp = dirPathArray[AFSDIR_SERVER_ETC_DIRPATH_ID];
    AFSDIR_SERVER_DIRPATH(pathp, AFSDIR_SERVER_ETC_DIR);

    pathp = dirPathArray[AFSDIR_SERVER_BIN_DIRPATH_ID];
    AFSDIR_SERVER_DIRPATH(pathp, AFSDIR_SERVER_BIN_DIR);

    pathp = dirPathArray[AFSDIR_SERVER_CORES_DIRPATH_ID];
    AFSDIR_SERVER_DIRPATH(pathp, AFSDIR_CORES_DIR);

    pathp = dirPathArray[AFSDIR_SERVER_DB_DIRPATH_ID];
    AFSDIR_SERVER_DIRPATH(pathp, AFSDIR_DB_DIR);

    pathp = dirPathArray[AFSDIR_SERVER_LOGS_DIRPATH_ID];
    AFSDIR_SERVER_DIRPATH(pathp, AFSDIR_LOGS_DIR);

    pathp = dirPathArray[AFSDIR_SERVER_LOCAL_DIRPATH_ID];
    AFSDIR_SERVER_DIRPATH(pathp, AFSDIR_LOCAL_DIR);

    pathp = dirPathArray[AFSDIR_SERVER_BACKUP_DIRPATH_ID];
    AFSDIR_SERVER_DIRPATH(pathp, AFSDIR_BACKUP_DIR);

    pathp = dirPathArray[AFSDIR_SERVER_MIGRATE_DIRPATH_ID];
    AFSDIR_SERVER_DIRPATH(pathp, AFSDIR_MIGR_DIR);

    pathp = dirPathArray[AFSDIR_SERVER_BIN_FILE_DIRPATH_ID];
    AFSDIR_SERVER_DIRPATH(pathp, AFSDIR_BIN_FILE_DIR);

    /* client dir path */
#ifdef AFS_NT40_ENV
    strcpy(dirPathArray[AFSDIR_CLIENT_VICE_DIRPATH_ID],
	   "/NoUsrViceDirectoryOnWindows");
    strcpy(dirPathArray[AFSDIR_CLIENT_ETC_DIRPATH_ID],
	   ntClientConfigDirShort);
#else
    strcpy(dirPathArray[AFSDIR_CLIENT_VICE_DIRPATH_ID], afsClntDirPath);

    pathp = dirPathArray[AFSDIR_CLIENT_ETC_DIRPATH_ID];
#ifdef AFS_DARWIN_ENV
    if (access(AFSDIR_ALTERNATE_CLIENT_ETC_DIR, F_OK) == 0)
	AFSDIR_CLIENT_DIRPATH(pathp, AFSDIR_ALTERNATE_CLIENT_ETC_DIR);
    else
#endif
	AFSDIR_CLIENT_DIRPATH(pathp, AFSDIR_CLIENT_ETC_DIR);
#endif /* AFS_NT40_ENV */

#ifndef AFS_NT40_ENV
    pathp = dirPathArray[AFSDIR_CLIENT_DATA_DIRPATH_ID];
#ifdef AFS_DARWIN_ENV
    if (access(AFSDIR_ALTERNATE_CLIENT_DATA_DIR, F_OK) == 0)
	AFSDIR_CLIENT_DIRPATH(pathp, AFSDIR_ALTERNATE_CLIENT_DATA_DIR);
    else
#endif
	AFSDIR_CLIENT_DIRPATH(pathp, AFSDIR_DATA_DIR);
#endif

    /* server file paths */
    pathp = dirPathArray[AFSDIR_SERVER_THISCELL_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_ETC_DIR,
			   AFSDIR_THISCELL_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_RXKAD_KEYTAB_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_ETC_DIR, AFSDIR_RXKAD_KEYTAB_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_CELLSERVDB_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_ETC_DIR,
			   AFSDIR_CELLSERVDB_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_NOAUTH_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_NOAUTH_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_BUDBLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_BUDBLOG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_TAPECONFIG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_BACKUP_DIR, AFSDIR_TAPECONFIG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_KALOGDB_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_KALOGDB_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_KALOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_KALOG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_KADB_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_DB_DIR, AFSDIR_KADB_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_NTPD_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_BIN_DIR, AFSDIR_NTPD_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_PRDB_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_DB_DIR, AFSDIR_PRDB_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_PTLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_PTLOG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_KCONF_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_ETC_DIR, AFSDIR_KCONF_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_VLDB_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_DB_DIR, AFSDIR_VLDB_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_VLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_VLOG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_CORELOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_CORE_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_SLVGLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_SLVGLOG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_SALSRVLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_SALSRVLOG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_SALVAGER_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_BIN_DIR,
			   AFSDIR_SALVAGER_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_SALSRV_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_BIN_DIR,
			   AFSDIR_SALSRV_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_SLVGLOCK_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_SLVGLOCK_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_KEY_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_ETC_DIR, AFSDIR_KEY_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_ULIST_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_ETC_DIR, AFSDIR_ULIST_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_BOZCONF_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_BOSCONFIG_DIR, AFSDIR_BOZCONF_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_BOZCONFNEW_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_BOSCONFIG_DIR,
			   AFSDIR_BOZCONFNEW_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_BOZLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_BOZLOG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_BOZINIT_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_BOSCONFIG_DIR, AFSDIR_BOZINIT_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_BOZRXBIND_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_BOSCONFIG_DIR, AFSDIR_BOZRXBIND_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_BOSVR_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_BOSSERVER_DIR, AFSDIR_BOSVR_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_VOLSERLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_VOLSERLOG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_ROOTVOL_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_ETC_DIR, AFSDIR_ROOTVOL_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_HOSTDUMP_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_HOSTDUMP_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_CLNTDUMP_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_CLNTDUMP_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_CBKDUMP_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_CBKDUMP_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_OLDSYSID_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_OLDSYSID_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_SYSID_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_SYSID_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_FILELOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_FILELOG_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_AUDIT_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_AUDIT_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_NETINFO_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_NETINFO_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_NETRESTRICT_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_NETRESTRICT_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_KRB_EXCL_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_ETC_DIR, AFSDIR_KRB_EXCL_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_FSSTATE_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_FSSTATE_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_OSDDB_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_DB_DIR, AFSDIR_OSDDB_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_OSDDBLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_OSDDB_LOGNAME);

    pathp = dirPathArray[AFSDIR_SERVER_RXOSDLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_RXOSD_LOGNAME);

    pathp = dirPathArray[AFSDIR_SERVER_RXOSD_FETCHQ_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOCAL_DIR, AFSDIR_RXOSD_FETCHQ_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_RECALL_MIGRATED_FILE_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_SERVER_BIN_DIR, AFSDIR_RECALL_MIGRATED_FILE_FILE);

    pathp = dirPathArray[AFSDIR_SERVER_RECALLLOG_FILEPATH_ID];
    AFSDIR_SERVER_FILEPATH(pathp, AFSDIR_LOGS_DIR, AFSDIR_RECALL_LOGNAME);

    /* client file paths */
#ifdef AFS_NT40_ENV
    strcpy(dirPathArray[AFSDIR_CLIENT_THISCELL_FILEPATH_ID],
	   "/NoUsrViceEtcThisCellFileOnWindows");
    sprintf(dirPathArray[AFSDIR_CLIENT_CELLSERVDB_FILEPATH_ID], "%s/%s",
	    ntClientConfigDirShort, AFSDIR_CELLSERVDB_FILE_NTCLIENT);
    strcpy(dirPathArray[AFSDIR_CLIENT_CELLALIAS_FILEPATH_ID],
	   "/NoCellAliasOnWindows");
#else
    pathp = dirPathArray[AFSDIR_CLIENT_THISCELL_FILEPATH_ID];
    AFSDIR_CLIENT_FILEPATH(pathp, AFSDIR_CLIENT_ETC_DIR,
			   AFSDIR_THISCELL_FILE);

    pathp = dirPathArray[AFSDIR_CLIENT_CELLSERVDB_FILEPATH_ID];
    AFSDIR_CLIENT_FILEPATH(pathp, AFSDIR_CLIENT_ETC_DIR,
			   AFSDIR_CELLSERVDB_FILE);

    pathp = dirPathArray[AFSDIR_CLIENT_CELLALIAS_FILEPATH_ID];
    AFSDIR_CLIENT_FILEPATH(pathp, AFSDIR_CLIENT_ETC_DIR,
			   AFSDIR_CELLALIAS_FILE);
#endif /* AFS_NT40_ENV */

    pathp = dirPathArray[AFSDIR_CLIENT_NETINFO_FILEPATH_ID];
    AFSDIR_CLIENT_FILEPATH(pathp, AFSDIR_CLIENT_ETC_DIR, AFSDIR_NETINFO_FILE);

    pathp = dirPathArray[AFSDIR_CLIENT_NETRESTRICT_FILEPATH_ID];
    AFSDIR_CLIENT_FILEPATH(pathp, AFSDIR_CLIENT_ETC_DIR,
			   AFSDIR_NETRESTRICT_FILE);

    initFlag = 1;		/* finished dirpath initialization */
    return;
}
Example #20
0
/** Modifies the wininit.ini file to rename / delete a file.
 *
 * @param prevName The previous / current name of the file.
 * @param newName The new name to move the file to.  If NULL, the current file
 * will be deleted.
 */
void RenameViaWininit(const TCHAR* prevName, const TCHAR* newName)
{
  static char szRenameLine[1024];
  static TCHAR wininit[1024];
  static TCHAR tmpbuf[1024];

  int cchRenameLine;
  LPCSTR szRenameSec = "[Rename]\r\n"; // rename section marker
  HANDLE hfile;
  DWORD dwFileSize;
  SIZE_T dwBytes;
  DWORD dwRenameLinePos;
  char *pszWinInit;   // Contains the file contents of wininit.ini

  int spn;   // length of the short path name in TCHARs.

  lstrcpy(tmpbuf, _T("NUL"));

  if (newName) {
    // create the file if it's not already there to prevent GetShortPathName from failing
    CloseHandle(myOpenFile(newName,0,CREATE_NEW));
    spn = GetShortPathName(newName,tmpbuf,1024);
    if (!spn || spn > 1024)
      return;
  }
  // wininit is used as a temporary here
  spn = GetShortPathName(prevName,wininit,1024);
  if (!spn || spn > 1024)
    return;
#ifdef _UNICODE
  cchRenameLine = wsprintfA(szRenameLine, "%ls=l%s\r\n", tmpbuf, wininit);
#else
  cchRenameLine = wsprintfA(szRenameLine, "%s=%s\r\n", tmpbuf, wininit);
#endif
  // Get the path to the wininit.ini file.
  GetWindowsDirectory(wininit, 1024-16);
  lstrcat(wininit, _T("\\wininit.ini"));

  hfile = myOpenFile(wininit, GENERIC_READ | GENERIC_WRITE, OPEN_ALWAYS);

  if (hfile != INVALID_HANDLE_VALUE)
  {
    // We are now working on the Windows wininit file
    dwFileSize = GetFileSize(hfile, NULL);
    pszWinInit = (char*) GlobalAlloc(GPTR, dwFileSize + cchRenameLine + 10);

    if (pszWinInit != NULL)
    {
      if (ReadFile(hfile, pszWinInit, dwFileSize, &dwBytes, NULL) && dwFileSize == dwBytes)
      {
        // Look for the rename section in the current file.
        LPSTR pszRenameSecInFile = mystrstriA(pszWinInit, szRenameSec);
        if (pszRenameSecInFile == NULL)
        {
          // No rename section.  So we add it to the end of file.
          lstrcpyA(pszWinInit+dwFileSize, szRenameSec);
          dwFileSize += 10;
          dwRenameLinePos = dwFileSize;
        }
        else
        {
          // There is a rename section, but is there another section after it?
          char *pszFirstRenameLine = pszRenameSecInFile+10;
          char *pszNextSec = mystrstriA(pszFirstRenameLine,"\n[");
          if (pszNextSec)
          {
            char *p = pszWinInit + dwFileSize;
            char *pEnd = pszWinInit + dwFileSize + cchRenameLine;

            while (p > pszNextSec)
            {
              *pEnd-- = *p--;
            }

            dwRenameLinePos = pszNextSec - pszWinInit + 1; // +1 for the \n
          }
          // rename section is last, stick item at end of file
          else dwRenameLinePos = dwFileSize;
        }

        mini_memcpy(&pszWinInit[dwRenameLinePos], szRenameLine, cchRenameLine);
        dwFileSize += cchRenameLine;

        SetFilePointer(hfile, 0, NULL, FILE_BEGIN);
        WriteFile(hfile, pszWinInit, dwFileSize, &dwBytes, NULL);

        GlobalFree(pszWinInit);
      }
    }
    
    CloseHandle(hfile);
  }
}
Example #21
0
// Downloads file from the net
unsigned __stdcall NetworkDownloadThreadProc(void* pParam)
{
	MeasureData* measure = (MeasureData*)pParam;
	const bool download = !measure->downloadFile.empty();
	bool ready = false;

	std::wstring url;

	if (measure->regExp.empty() && measure->resultString.empty())
	{
		if (!measure->url.empty() && measure->url[0] != L'[')
		{
			url = measure->url;
		}
	}
	else
	{
		EnterCriticalSection(&g_CriticalSection);
		url = measure->resultString;
		LeaveCriticalSection(&g_CriticalSection);

		std::wstring::size_type pos = url.find(L':');
		if (pos == std::wstring::npos && !url.empty())	// No protocol
		{
			// Add the base url to the string
			if (url[0] == L'/')
			{
				// Absolute path
				pos = measure->url.find(L'/', 7);	// Assume "http://" (=7)
				if (pos != std::wstring::npos)
				{
					std::wstring path(measure->url.substr(0, pos));
					url = path + url;
				}
			}
			else
			{
				// Relative path

				pos = measure->url.rfind(L'/');
				if (pos != std::wstring::npos)
				{
					std::wstring path(measure->url.substr(0, pos + 1));
					url = path + url;
				}
			}
		}
	}

	if (!url.empty())
	{
		// Create the filename
		WCHAR buffer[MAX_PATH] = {0};
		std::wstring fullpath, directory;

		if (download)  // download mode
		{
			PathCanonicalize(buffer, measure->downloadFile.c_str());

			std::wstring path = buffer;
			std::wstring::size_type pos = path.find_first_not_of(L'\\');
			if (pos != std::wstring::npos)
			{
				path.erase(0, pos);
			}

			PathCanonicalize(buffer, measure->downloadFolder.c_str());
			CreateDirectory(buffer, nullptr);	// Make sure that the folder exists

			wcscat(buffer, path.c_str());

			if (buffer[wcslen(buffer)-1] != L'\\')  // path is a file
			{
				fullpath = buffer;
				PathRemoveFileSpec(buffer);
			}
			PathAddBackslash(buffer);
		}
		else  // cache mode
		{
			GetTempPath(MAX_PATH, buffer);
			wcscat(buffer, L"Rainmeter-Cache\\");  // "%TEMP%\Rainmeter-Cache\"
		}
		CreateDirectory(buffer, nullptr);	// Make sure that the folder exists
		directory = buffer;

		if (fullpath.empty())
		{
			fullpath = directory;

			std::wstring::size_type pos2 = url.find_first_of(L"?#");
			std::wstring::size_type pos1 = url.find_last_of(L'/', pos2);
			pos1 = (pos1 != std::wstring::npos) ? pos1 + 1 : 0;

			std::wstring name;
			if (pos2 != std::wstring::npos)
			{
				name.assign(url, pos1, pos2 - pos1);
			}
			else
			{
				name.assign(url, pos1, url.length() - pos1);
			}

			if (!name.empty())
			{
				// Replace reserved characters to "_"
				pos1 = 0;
				while ((pos1 = name.find_first_of(L"\\/:*?\"<>|", pos1)) != std::wstring::npos)
				{
					name[pos1] = L'_';
				}
				fullpath += name;
			}
			else
			{
				fullpath += L"index";
			}
		}

		ready = true;

		if (download)  // download mode
		{
			if (!PathFileExists(directory.c_str()) || !PathIsDirectory(directory.c_str()))
			{
				ready = false;
				RmLogF(
					measure->rm, LOG_ERROR,
					L"WebParser: Directory does not exist: %s", directory.c_str());
			}
			else if (PathIsDirectory(fullpath.c_str()))
			{
				ready = false;
				RmLogF(
					measure->rm, LOG_ERROR,
					L"WebParser: Path is a directory, not a file: %s", fullpath.c_str());
			}
			else if (PathFileExists(fullpath.c_str()))
			{
				DWORD attr = GetFileAttributes(fullpath.c_str());
				if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_READONLY))
				{
					ready = false;
					RmLogF(
						measure->rm, LOG_ERROR,
						L"WebParser: File is read-only: %s", fullpath.c_str());
				}
			}
		}
		else  // cache mode
		{
			EnterCriticalSection(&g_CriticalSection);

			if (PathFileExists(fullpath.c_str()))
			{
				std::wstring::size_type pos = fullpath.find_last_of(L'.');

				std::wstring path, ext;
				if (pos != std::wstring::npos)
				{
					path.assign(fullpath, 0, pos);
					ext.assign(fullpath, pos, fullpath.length() - pos);
				}
				else
				{
					path = fullpath;
				}

				// Assign a serial number
				int i = 1;
				do
				{
					wsprintf(buffer, L"_%i", i++);

					fullpath = path;
					fullpath += buffer;
					if (!ext.empty())
					{
						fullpath += ext;
					}
				} while (PathFileExists(fullpath.c_str()));
			}

			// Create empty file
			HANDLE hFile = CreateFile(fullpath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
			if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile);

			LeaveCriticalSection(&g_CriticalSection);
		}

		if (ready)
		{
			// Delete IE cache before download if "SyncMode5" is not 3 (every visit to the page)
			{
				// Check "Temporary Internet Files" sync mode (SyncMode5)
				// Values:
				//   Every visit to the page                 3
				//   Every time you start Internet Explorer  2
				//   Automatically (default)                 4
				//   Never                                   0
				// http://support.microsoft.com/kb/263070/en

				HKEY hKey;
				LONG ret;
				DWORD mode;

				ret = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", 0, KEY_QUERY_VALUE, &hKey);
				if (ret == ERROR_SUCCESS)
				{
					DWORD size = sizeof(mode);
					ret = RegQueryValueEx(hKey, L"SyncMode5", nullptr, nullptr, (LPBYTE)&mode, &size);
					RegCloseKey(hKey);
				}

				if (ret != ERROR_SUCCESS || mode != 3)
				{
					std::wstring::size_type pos = url.find_first_of(L'#');

					if (pos != std::wstring::npos)
					{
						DeleteUrlCacheEntry(url.substr(0, pos).c_str());
					}
					else
					{
						DeleteUrlCacheEntry(url.c_str());
					}
				}
			}

			RmLogF(
				measure->rm, LOG_DEBUG,
				L"WebParser: Downloading url '%s' to: %s", url.c_str(), fullpath.c_str());

			HRESULT resultCoInitialize = CoInitialize(nullptr);  // requires before calling URLDownloadToFile function

			// Download the file
			HRESULT result = URLDownloadToFile(nullptr, url.c_str(), fullpath.c_str(), 0, nullptr);
			if (result == S_OK)
			{
				EnterCriticalSection(&g_CriticalSection);

				if (!download)  // cache mode
				{
					if (!measure->downloadedFile.empty())
					{
						// Delete old downloaded file
						DeleteFile(measure->downloadedFile.c_str());
					}
				}

				// Convert LFN to 8.3 filename if the path contains blank character
				if (fullpath.find_first_of(L' ') != std::wstring::npos)
				{
					DWORD size = GetShortPathName(fullpath.c_str(), buffer, MAX_PATH);
					if (size > 0 && size <= MAX_PATH)
					{
						fullpath = buffer;
					}
				}
				measure->downloadedFile = fullpath;

				LeaveCriticalSection(&g_CriticalSection);

				if (!measure->finishAction.empty())
				{
					RmExecute(measure->skin, measure->finishAction.c_str());
				}
			}
			else
			{
				ready = false;

				if (!download)  // cache mode
				{
					// Delete empty file
					DeleteFile(fullpath.c_str());
				}

				RmLogF(
					measure->rm, LOG_ERROR,
					L"WebParser: Download failed (res=0x%08X, COM=0x%08X): %s",
					result, resultCoInitialize, url.c_str());

				if (!measure->onDownloadErrAction.empty())
				{
					RmExecute(measure->skin, measure->onDownloadErrAction.c_str());
				}
			}

			if (SUCCEEDED(resultCoInitialize))
			{
				CoUninitialize();
			}
		}
		else
		{
			RmLogF(measure->rm, LOG_ERROR, L"WebParser: Download failed: %s", url.c_str());

			if (!measure->onDownloadErrAction.empty())
			{
				RmExecute(measure->skin, measure->onDownloadErrAction.c_str());
			}
		}
	}
	else
	{
		RmLog(measure->rm, LOG_ERROR, L"WebParser: Url is empty");
	}

	if (!ready) // download failed
	{
		EnterCriticalSection(&g_CriticalSection);

		if (!download) // cache mode
		{
			if (!measure->downloadedFile.empty())
			{
				// Delete old downloaded file
				DeleteFile(measure->downloadedFile.c_str());
			}
		}

		// Clear old downloaded filename
		measure->downloadedFile.clear();

		LeaveCriticalSection(&g_CriticalSection);
	}

	EnterCriticalSection(&g_CriticalSection);
	CloseHandle(measure->dlThreadHandle);
	measure->dlThreadHandle = 0;
	LeaveCriticalSection(&g_CriticalSection);

	return 0;   // thread completed successfully
}
BOOL He4HookDriverHide::DelShortName(PW32_FILEINFOSET lpFileInfoSetW32)
{
  if (!lpFileInfoSetW32)
    return FALSE;

  USER_COMMAND    UserCommand;
  W32_FILEINFOSET FileInfoSet;
  W32_FILEINFO    FileInfo;
  char           *lpszShortName = 0;
  char           *lpwszShortChangedName = 0;
  DWORD           dwRes;

  FileInfoSet.dwSize = 1;
  FileInfoSet.lpFileInfo = &FileInfo;

  //UserCommand.m_dwCommand = HE4_DEL_FROM_SAVE_LIST;
  //UserCommand.m_lpInBuffer = &FileInfoSet;
  //UserCommand.m_dwInBufferSize = sizeof(FILEINFOSET);

  for (int i=0; i<(int)lpFileInfoSetW32->dwSize; i++)
  {
    if (!lpFileInfoSetW32->lpFileInfo[i].lpszName)
      continue;
    if ((lpFileInfoSetW32->lpFileInfo[i].dwAccessType & FILE_ACC_TYPE_EXCHANGE) && (!lpFileInfoSetW32->lpFileInfo[i].lpszChangedName))
      continue;

    lpszShortName = new char[lstrlen(lpFileInfoSetW32->lpFileInfo[i].lpszName)+sizeof(char)];
    if (!lpszShortName)
      continue;
//    lstrcpy(&lpszShortName[1], lpFileInfoSetW32->lpFileInfo[i].lpszName);
//    lpszShortName[0] = 'c';
    dwRes = GetShortPathName(lpFileInfoSetW32->lpFileInfo[i].lpszName, lpszShortName, lstrlen(lpFileInfoSetW32->lpFileInfo[i].lpszName)+sizeof(char));
    if (!dwRes)
    {
      delete[] lpszShortName;
      lpszShortName = 0; 
      continue;
    }
//    memcpy(&lpszShortName[0], &lpszShortName[1], lstrlen(lpszShortName));
    if (lstrlen(lpszShortName) == lstrlen(lpFileInfoSetW32->lpFileInfo[i].lpszName))
    {
      delete[] lpszShortName;
      lpszShortName = 0; 
      continue;
    }
    if (lpFileInfoSetW32->lpFileInfo[i].dwAccessType & FILE_ACC_TYPE_EXCHANGE)
    {
      lpwszShortChangedName = new char[lstrlen(lpFileInfoSetW32->lpFileInfo[i].lpszChangedName)+sizeof(char)];
      if (!lpwszShortChangedName)
      {
        delete[] lpszShortName;
        lpszShortName = 0; 
        continue;
      }
      dwRes = GetShortPathName((char*)lpFileInfoSetW32->lpFileInfo[i].lpszChangedName, lpwszShortChangedName, lstrlen(lpFileInfoSetW32->lpFileInfo[i].lpszChangedName)+sizeof(char));
      if (!dwRes)
      {
        delete[] lpszShortName;
        lpszShortName = 0; 
        delete[] lpwszShortChangedName;
        lpwszShortChangedName = 0; 
        continue;
       }
    }
    
    FileInfo.lpszName = lpszShortName;         
    FileInfo.lpszChangedName = lpwszShortChangedName; 
    FileInfo.dwAccessType = lpFileInfoSetW32->lpFileInfo[i].dwAccessType;

    PFILEINFOSET pFileInfo = CreateFileInfoSet(&FileInfoSet);
    if (pFileInfo)
    {
      UserCommand.m_dwCommand = HE4_DEL_FROM_SAVE_LIST;
      UserCommand.m_lpInBuffer = pFileInfo;
      UserCommand.m_dwInBufferSize = pFileInfo->dwSize;
      UserCommand.m_dwBytesReturned = 0;
      SendCommand(&UserCommand);
      delete[] (char*)pFileInfo;
    }
    
    delete[] lpszShortName;
    lpszShortName = 0; 
    delete[] lpwszShortChangedName;
    lpwszShortChangedName = 0; 
  }

  return TRUE;
}
Example #23
0
int
main (int argc, char ** argv)
{
  int rc;
  int need_shell;
  char * cmdline;
  char * progname;
  int envsize;
  char **pass_through_args;
  int num_pass_through_args;
  char modname[MAX_PATH];
  char path[MAX_PATH];
  char dir[MAX_PATH];
  int status;

  interactive = TRUE;

  SetConsoleCtrlHandler ((PHANDLER_ROUTINE) console_event_handler, TRUE);

  if (!GetCurrentDirectory (sizeof (dir), dir))
    fail ("error: GetCurrentDirectory failed\n");

  /* We serve double duty: we can be called either as a proxy for the
     real shell (that is, because we are defined to be the user shell),
     or in our role as a helper application for running DOS programs.
     In the former case, we interpret the command line options as if we
     were a Unix shell, but in the latter case we simply pass our
     command line to CreateProcess.  We know which case we are dealing
     with by whether argv[0] refers to ourself or to some other program.
     (This relies on an arcane feature of CreateProcess, where we can
     specify cmdproxy as the module to run, but specify a different
     program in the command line - the MSVC startup code sets argv[0]
     from the command line.)  */

  if (!GetModuleFileName (NULL, modname, sizeof (modname)))
    fail ("error: GetModuleFileName failed\n");

  /* Change directory to location of .exe so startup directory can be
     deleted.  */
  progname = strrchr (modname, '\\');
  *progname = '\0';
  SetCurrentDirectory (modname);
  *progname = '\\';

  /* Due to problems with interaction between API functions that use "OEM"
     codepage vs API functions that use the "ANSI" codepage, we need to
     make things consistent by choosing one and sticking with it.  */
  SetConsoleCP (GetACP ());
  SetConsoleOutputCP (GetACP ());

  /* Although Emacs always sets argv[0] to an absolute pathname, we
     might get run in other ways as well, so convert argv[0] to an
     absolute name before comparing to the module name.  */
  path[0] = '\0';
  /* The call to SearchPath will find argv[0] in the current
     directory, append ".exe" to it if needed, and also canonicalize
     it, to resolve references to ".", "..", etc.  */
  status = SearchPath (NULL, argv[0], ".exe", sizeof (path), path,
				  &progname);
  if (!(status > 0 && stricmp (modname, path) == 0))
    {
      if (status <= 0)
	{
	  char *s;

	  /* Make sure we have argv[0] in path[], as the failed
	     SearchPath might not have copied it there.  */
	  strcpy (path, argv[0]);
	  /* argv[0] could include forward slashes; convert them all
	     to backslashes, for strrchr calls below to DTRT.  */
	  for (s = path; *s; s++)
	    if (*s == '/')
	      *s = '\\';
	}
      /* Perhaps MODNAME and PATH use mixed short and long file names.  */
      if (!(GetShortPathName (modname, modname, sizeof (modname))
	    && GetShortPathName (path, path, sizeof (path))
	    && stricmp (modname, path) == 0))
	{
	  /* Sometimes GetShortPathName fails because one or more
	     directories leading to argv[0] have issues with access
	     rights.  In that case, at least we can compare the
	     basenames.  Note: this disregards the improbable case of
	     invoking a program of the same name from another
	     directory, since the chances of that other executable to
	     be both our namesake and a 16-bit DOS application are nil.  */
	  char *p = strrchr (path, '\\');
	  char *q = strrchr (modname, '\\');
	  char *pdot, *qdot;

	  if (!p)
	    p = strchr (path, ':');
	  if (!p)
	    p = path;
	  else
	    p++;
	  if (!q)
	    q = strchr (modname, ':');
	  if (!q)
	    q = modname;
	  else
	    q++;

	  pdot = strrchr (p, '.');
	  if (!pdot || stricmp (pdot, ".exe") != 0)
	    pdot = p + strlen (p);
	  qdot = strrchr (q, '.');
	  if (!qdot || stricmp (qdot, ".exe") != 0)
	    qdot = q + strlen (q);
	  if (pdot - p != qdot - q || strnicmp (p, q, pdot - p) != 0)
	    {
	      /* We are being used as a helper to run a DOS app; just
		 pass command line to DOS app without change.  */
	      /* TODO: fill in progname.  */
	      if (spawn (NULL, GetCommandLine (), dir, &rc))
		return rc;
	      fail ("Could not run %s\n", GetCommandLine ());
	    }
	}
    }

  /* Process command line.  If running interactively (-c or /c not
     specified) then spawn a real command shell, passing it the command
     line arguments.

     If not running interactively, then attempt to execute the specified
     command directly.  If necessary, spawn a real shell to execute the
     command.

  */

  progname = NULL;
  cmdline = NULL;
  /* If no args, spawn real shell for interactive use.  */
  need_shell = TRUE;
  interactive = TRUE;
  /* Ask command.com to create an environment block with a reasonable
     amount of free space.  */
  envsize = get_env_size () + 300;
  pass_through_args = (char **) alloca (argc * sizeof (char *));
  num_pass_through_args = 0;

  while (--argc > 0)
    {
      ++argv;
      /* Act on switches we recognize (mostly single letter switches,
	 except for -e); all unrecognized switches and extra args are
	 passed on to real shell if used (only really of benefit for
	 interactive use, but allow for batch use as well).  Accept / as
	 switch char for compatibility with cmd.exe.  */
      if (((*argv)[0] == '-' || (*argv)[0] == '/') && (*argv)[1] != '\0')
	{
	  if (((*argv)[1] == 'c' || (*argv)[1] == 'C') && ((*argv)[2] == '\0'))
	    {
	      if (--argc == 0)
		fail ("error: expecting arg for %s\n", *argv);
	      cmdline = *(++argv);
	      interactive = FALSE;
	    }
	  else if (((*argv)[1] == 'i' || (*argv)[1] == 'I') && ((*argv)[2] == '\0'))
	    {
	      if (cmdline)
		warn ("warning: %s ignored because of -c\n", *argv);
	    }
	  else if (((*argv)[1] == 'e' || (*argv)[1] == 'E') && ((*argv)[2] == ':'))
	    {
	      int requested_envsize = atoi (*argv + 3);
	      /* Enforce a reasonable minimum size, as above.  */
	      if (requested_envsize > envsize)
		envsize = requested_envsize;
	      /* For sanity, enforce a reasonable maximum.  */
	      if (envsize > 32768)
		envsize = 32768;
	    }
	  else
	    {
	      /* warn ("warning: unknown option %s ignored", *argv); */
	      pass_through_args[num_pass_through_args++] = *argv;
	    }
	}
      else
	break;
    }

#if 0
  /* I think this is probably not useful - cmd.exe ignores extra
     (non-switch) args in interactive mode, and they cannot be passed on
     when -c was given.  */

  /* Collect any remaining args after (initial) switches.  */
  while (argc-- > 0)
    {
      pass_through_args[num_pass_through_args++] = *argv++;
    }
#else
  /* Probably a mistake for there to be extra args; not fatal.  */
  if (argc > 0)
    warn ("warning: extra args ignored after '%s'\n", argv[-1]);
#endif

  pass_through_args[num_pass_through_args] = NULL;

  /* If -c option, determine if we must spawn a real shell, or if we can
     execute the command directly ourself.  */
  if (cmdline)
    {
      const char *args;

      /* The program name is the first token of cmdline.  Since
         filenames cannot legally contain embedded quotes, the value
         of escape_char doesn't matter.  */
      args = cmdline;
      if (!get_next_token (path, &args))
        fail ("error: no program name specified.\n");

      canon_filename (path);
      progname = make_absolute (path);

      /* If we found the program and the rest of the command line does
         not contain unquoted shell metacharacters, run the program
         directly (if not found it might be an internal shell command,
         so don't fail).  */
      if (progname != NULL && try_dequote_cmdline (cmdline))
        need_shell = FALSE;
      else
        progname = NULL;
    }

 pass_to_shell:
  if (need_shell)
    {
      char * p;
      int    extra_arg_space = 0;
      int    maxlen, remlen;
      int    run_command_dot_com;

      progname = getenv ("COMSPEC");
      if (!progname)
	fail ("error: COMSPEC is not set\n");

      canon_filename (progname);
      progname = make_absolute (progname);

      if (progname == NULL || strchr (progname, '\\') == NULL)
	fail ("error: the program %s could not be found.\n", getenv ("COMSPEC"));

      /* Need to set environment size when running command.com.  */
      run_command_dot_com =
	(stricmp (strrchr (progname, '\\'), "command.com") == 0);

      /* Work out how much extra space is required for
         pass_through_args.  */
      for (argv = pass_through_args; *argv != NULL; ++argv)
	/* We don't expect to have to quote switches.  */
	extra_arg_space += strlen (*argv) + 2;

      if (cmdline)
	{
	  char * buf;

	  /* Convert to syntax expected by cmd.exe/command.com for
	     running non-interactively.  Always quote program name in
	     case path contains spaces (fortunately it can't contain
	     quotes, since they are illegal in path names).  */

	  remlen = maxlen =
	    strlen (progname) + extra_arg_space + strlen (cmdline) + 16 + 2;
	  buf = p = alloca (maxlen + 1);

	  /* Quote progname in case it contains spaces.  */
	  p += _snprintf (p, remlen, "\"%s\"", progname);
	  remlen = maxlen - (p - buf);

	  /* Include pass_through_args verbatim; these are just switches
             so should not need quoting.  */
	  for (argv = pass_through_args; *argv != NULL; ++argv)
	    {
	      p += _snprintf (p, remlen, " %s", *argv);
	      remlen = maxlen - (p - buf);
	    }

	  /* Now that we know we will be invoking the shell, quote the
	     command line after the "/c" switch as the shell expects:
	     a single pair of quotes enclosing the entire command
	     tail, no matter whether quotes are used in the command
	     line, and how many of them are there.  See the output of
	     "cmd /?" for how cmd.exe treats quotes.  */
	  if (run_command_dot_com)
	    _snprintf (p, remlen, " /e:%d /c \"%s\"", envsize, cmdline);
	  else
	    _snprintf (p, remlen, " /c \"%s\"", cmdline);
	  cmdline = buf;
	}
      else
	{
	  if (run_command_dot_com)
	    {
	      /* Provide dir arg expected by command.com when first
		 started interactively (the "command search path").  To
		 avoid potential problems with spaces in command dir
		 (which cannot be quoted - command.com doesn't like it),
		 we always use the 8.3 form.  */
	      GetShortPathName (progname, path, sizeof (path));
	      p = strrchr (path, '\\');
	      /* Trailing slash is acceptable, so always leave it.  */
	      *(++p) = '\0';
	    }
	  else
	    path[0] = '\0';

	  remlen = maxlen =
	    strlen (progname) + extra_arg_space + strlen (path) + 13;
	  cmdline = p = alloca (maxlen + 1);

	  /* Quote progname in case it contains spaces.  */
	  p += _snprintf (p, remlen, "\"%s\" %s", progname, path);
	  remlen = maxlen - (p - cmdline);

	  /* Include pass_through_args verbatim; these are just switches
             so should not need quoting.  */
	  for (argv = pass_through_args; *argv != NULL; ++argv)
	    {
	      p += _snprintf (p, remlen, " %s", *argv);
	      remlen = maxlen - (p - cmdline);
	    }

	  if (run_command_dot_com)
	    _snprintf (p, remlen, " /e:%d", envsize);
	}
    }

  if (!progname)
    fail ("Internal error: program name not defined\n");

  if (!cmdline)
    cmdline = progname;

  if (spawn (progname, cmdline, dir, &rc))
    return rc;

  if (!need_shell)
    {
      need_shell = TRUE;
      goto pass_to_shell;
    }

  fail ("Could not run %s\n", progname);

  return 0;
}
Example #24
0
void DeleteFileOnReboot(char *pszFile)
{
    BOOL fOk = 0;
    HMODULE hLib=GetModuleHandle("KERNEL32.dll");
    if (hLib)
    {
        typedef BOOL (WINAPI *mfea_t)(LPCSTR lpExistingFileName,LPCSTR lpNewFileName,DWORD dwFlags);
        mfea_t mfea;
        mfea=(mfea_t) GetProcAddress(hLib,"MoveFileExA");
        if (mfea)
        {
            fOk=mfea(pszFile, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
        }
    }

    if (!fOk)
    {
        static char szRenameLine[1024];
        static char wininit[1024];
        int cchRenameLine;
        char *szRenameSec = "[Rename]\r\n";
        HANDLE hfile, hfilemap;
        DWORD dwFileSize, dwRenameLinePos;

        int spn;

        // wininit is used as a temporary here
        spn = GetShortPathName(pszFile,wininit,1024);
        if (!spn || spn > 1024)
            return;
        cchRenameLine = wsprintf(szRenameLine,"NUL=%s\r\n",wininit);

        GetWindowsDirectory(wininit, 1024-16);
        lstrcat(wininit, "\\wininit.ini");
        hfile = CreateFile(wininit,
                           GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
                           FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);

        if (hfile != INVALID_HANDLE_VALUE)
        {
            dwFileSize = GetFileSize(hfile, NULL);
            hfilemap = CreateFileMapping(hfile, NULL, PAGE_READWRITE, 0, dwFileSize + cchRenameLine + 10, NULL);

            if (hfilemap != NULL)
            {
                LPSTR pszWinInit = (LPSTR) MapViewOfFile(hfilemap, FILE_MAP_WRITE, 0, 0, 0);

                if (pszWinInit != NULL)
                {
                    LPSTR pszRenameSecInFile = mystrstri(pszWinInit, szRenameSec);
                    if (pszRenameSecInFile == NULL)
                    {
                        lstrcpy(pszWinInit+dwFileSize, szRenameSec);
                        dwFileSize += 10;
                        dwRenameLinePos = dwFileSize;
                    }
                    else
                    {
                        char *pszFirstRenameLine = pszRenameSecInFile+10;
                        char *pszNextSec = mystrstri(pszFirstRenameLine,"\n[");
                        if (pszNextSec)
                        {
                            char *p = ++pszNextSec;
                            while (p < pszWinInit + dwFileSize) {
                                p[cchRenameLine] = *p;
                                p++;
                            }

                            dwRenameLinePos = pszNextSec - pszWinInit;
                        }
                        // rename section is last, stick item at end of file
                        else dwRenameLinePos = dwFileSize;
                    }

                    mini_memcpy(&pszWinInit[dwRenameLinePos], szRenameLine, cchRenameLine);
                    dwFileSize += cchRenameLine;

                    UnmapViewOfFile(pszWinInit);
                }
                CloseHandle(hfilemap);
            }
            SetFilePointer(hfile, dwFileSize, NULL, FILE_BEGIN);
            SetEndOfFile(hfile);
            CloseHandle(hfile);
        }
    }
}
Example #25
0
__declspec(dllexport) DWORD __stdcall Load( const char *exe, const char *dll, const char *func, const void *dllData, int dataLen, DWORD *pid )
{
	SIZE_T Num;
	char buff[MAX_PATH];
	LPVOID Entry;
	STARTUPINFO StartInfo;
	PROCESS_INFORMATION ProcInfo;
	IMAGE_DOS_HEADER idh;
	IMAGE_OPTIONAL_HEADER32 ioh;

	FILE *pExe = fopen( exe, "rb" );
	if ( !pExe )
	{
		buff[0] = 0;
		if ( GetShortPathName( exe, buff, MAX_PATH ) >= MAX_PATH )
			buff[0] = 0;

		pExe = fopen( buff, "rb" );
		if ( !pExe )
			return NO_OPEN_EXE;
	}

	if ( fread( &idh, 1, sizeof(IMAGE_DOS_HEADER), pExe ) != sizeof(IMAGE_DOS_HEADER) )
	{
		fclose( pExe );
		return NO_READ_EXE_DATA;
	}

	fseek( pExe, idh.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER), SEEK_SET );
	if ( fread( &ioh, 1, sizeof(IMAGE_OPTIONAL_HEADER32), pExe ) != sizeof(IMAGE_OPTIONAL_HEADER32) )
	{
		fclose( pExe );
		return NO_READ_EXE_DATA;
	}

	Entry = (LPVOID)(ioh.ImageBase + ioh.AddressOfEntryPoint);
	
	//sprintf( buff, "magic: %X\nlfanew: %X\nimg_base: %X\naoep: %X\nmagic2: %X", idh.e_magic, idh.e_lfanew, ioh.ImageBase, ioh.AddressOfEntryPoint, ioh.Magic );
	//MessageBox( NULL, buff, "Error", MB_OK );

	fclose( pExe );

	// find the exe's working directory
	strcpy( buff, exe );

	int i=(int)strlen(buff);
	while ( buff[i] != '\\' && buff[i] != '/' && i > 0 )
		i--;
	buff[i] = 0;

	//GetStartupInfo( &StartInfo );
	memset( &StartInfo, 0, sizeof(STARTUPINFO) );
	StartInfo.cb = sizeof(STARTUPINFO);

	// launch the exe
	if ( !CreateProcess( exe, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, buff, &StartInfo, &ProcInfo ) )
		return NO_RUN_EXE;

	*pid = ProcInfo.dwProcessId;

	int dllNameLen = (int)strlen(dll)+1;
	int funcNameLen = (int)strlen(func)+1;
	const int LoadAsmSize = 60;
	SIZE_T allocSize = dllNameLen + funcNameLen + dataLen + LoadAsmSize;

	// allocate some space in the exe for our memory
	DWORD ProcMem = 0;
	
	ProcMem = (DWORD)VirtualAllocEx( ProcInfo.hProcess, NULL, allocSize, MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE );
	if ( !ProcMem )
	{
		ProcMem = 0x00700000;
		if ( !VirtualProtectEx( ProcInfo.hProcess, (LPVOID)ProcMem, allocSize, PAGE_EXECUTE_READWRITE, (PDWORD)&Num ) )
		{
			TerminateProcess( ProcInfo.hProcess, 0 );
			return NO_ALLOC_MEM;
		}
	}

	char *toWrite = new char[allocSize];
	if ( !toWrite )
	{
		TerminateProcess( ProcInfo.hProcess, 0 );
		return NO_ALLOC_MEM;
	}

	// change protection to allow us to read/write the entry point (note: the old protection is not restored (so that we can change this space again later...)
	if ( !VirtualProtectEx( ProcInfo.hProcess, Entry, 8, PAGE_EXECUTE_READWRITE, (PDWORD)&Num ) )
	{
		TerminateProcess( ProcInfo.hProcess, 0 );
		return NO_VPROTECT;
	}
	
	// read the old code at the entry point
	if ( !ReadProcessMemory( ProcInfo.hProcess, Entry, buff, 8, &Num ) || Num != 8 )
	{
		TerminateProcess( ProcInfo.hProcess, 0 );
		return NO_READ;
	}

	// note if you change this size you must rewrite the LoadAsm to copy back the original code properly
	unsigned char EntryAsm[] = {
		0xE9, 0,0,0,0,			// jmp (offset)
		0x90,0x90,0x90,			// nop (for 4 byte alignment)
	};

	*((DWORD*)&EntryAsm[1]) = ProcMem - ((DWORD)Entry + 5);

	// write the new code at the entry point
	if ( !WriteProcessMemory( ProcInfo.hProcess, Entry, EntryAsm, 8, &Num ) || Num != 8 )
	{
		TerminateProcess( ProcInfo.hProcess, 0 );
		return NO_WRITE;
	}

	// this asm section does everything
	unsigned char LoadAsm[LoadAsmSize] = {
		// restore the original entry point bytes
		0xB8, 0,0,0,0,			// mov     eax, (number)
		0xC7, 0x00, 0,0,0,0,	// mov     dword ptr [eax], (num)
		0xC7, 0x40, 4, 0,0,0,0, // mov     dword ptr [eax+4], (num)

		// LoadLibrary( name )
		0x68, 0,0,0,0,			// push (num)
		0xE8, 0,0,0,0,			// call (offset)

		// GetProcAddress( lib, name )
		0x68, 0,0,0,0,			// push (num)
		0x50,					// push eax
		0xE8, 0,0,0,0,			// call (offset)

		// name( data, dataLen )
		0x68, 0,0,0,0,			// push (num)
		0x68, 0,0,0,0,			// push (num)
		0xFF, 0xD0,				// call eax

		// go back to the original entry point
		0xE9, 0,0,0,0,			// jmp  (offset)
		
		0x90, 0x90, 0x90, 0x90,	// nop (padding)
	};

	*((DWORD*)(LoadAsm+ 1)) = (DWORD)Entry; // data dest
	*((DWORD*)(LoadAsm+ 7)) = *((DWORD*)&buff[0]); // 1st data 
	*((DWORD*)(LoadAsm+14)) = *((DWORD*)&buff[4]); // 2nd data

	HMODULE hKernel = LoadLibrary( "Kernel32" );

	*((DWORD*)(LoadAsm+19)) = (ProcMem + LoadAsmSize); // begining of dll name
	*((DWORD*)(LoadAsm+24)) = ((DWORD)GetProcAddress( hKernel, "LoadLibraryA" )) - (ProcMem + 28); // offset to LoadLibraryA
	
	*((DWORD*)(LoadAsm+29)) = (ProcMem + LoadAsmSize + dllNameLen); // begining of function name
	*((DWORD*)(LoadAsm+35)) = ((DWORD)GetProcAddress( hKernel, "GetProcAddress" )) - (ProcMem + 39); // offset to GetProcAddress

	FreeLibrary( hKernel );

	*((DWORD*)(LoadAsm+40)) = dataLen; // user data Length
	*((DWORD*)(LoadAsm+45)) = ProcMem + LoadAsmSize + dllNameLen + funcNameLen; // begining of user data
	*((DWORD*)(LoadAsm+52)) = (DWORD)Entry - (ProcMem + 56); // entry points

	memcpy( toWrite, LoadAsm, LoadAsmSize );
	memcpy( &toWrite[LoadAsmSize], dll, dllNameLen );
	memcpy( &toWrite[LoadAsmSize+dllNameLen], func, funcNameLen );

	if ( dataLen > 0 )
		memcpy( &toWrite[LoadAsmSize+dllNameLen+funcNameLen], dllData, dataLen );

	if ( !WriteProcessMemory( ProcInfo.hProcess, (void*)ProcMem, toWrite, allocSize, &Num ) || Num != allocSize )
	{
		TerminateProcess( ProcInfo.hProcess, 0 );
		return NO_WRITE;
	}

	delete[] toWrite;

	*pid = ProcInfo.dwProcessId;

	ResumeThread( ProcInfo.hThread );

	CloseHandle( ProcInfo.hProcess );
	CloseHandle( ProcInfo.hThread );

	return SUCCESS;
}
Example #26
0
int _tmain(int argc, _TCHAR* argv[])
{
    // we have three parameters
    const TCHAR * src = NULL;
    const TCHAR * dst = NULL;
    const TCHAR * wc = NULL;
    BOOL bErrOnMods = FALSE;
    BOOL bErrOnUnversioned = FALSE;
    BOOL bErrOnMixed = FALSE;
    BOOL bQuiet = FALSE;
    BOOL bUseSubWCRevIgnore = TRUE;
    SubWCRev_t SubStat;

    SetDllDirectory(L"");
    CCrashReportTSVN crasher(L"SubWCRev " _T(APP_X64_STRING));

    if (argc >= 2 && argc <= 5)
    {
        // WC path is always first argument.
        wc = argv[1];
    }
    if (argc == 4 || argc == 5)
    {
        // SubWCRev Path Tmpl.in Tmpl.out [-params]
        src = argv[2];
        dst = argv[3];
        if (!PathFileExists(src))
        {
            _tprintf(L"File '%s' does not exist\n", src);
            return ERR_FNF;     // file does not exist
        }
    }
    if (argc == 3 || argc == 5)
    {
        // SubWCRev Path -params
        // SubWCRev Path Tmpl.in Tmpl.out -params
        const TCHAR * Params = argv[argc-1];
        if (Params[0] == '-')
        {
            if (wcschr(Params, 'q') != 0)
                bQuiet = TRUE;
            if (wcschr(Params, 'n') != 0)
                bErrOnMods = TRUE;
            if (wcschr(Params, 'N') != 0)
                bErrOnUnversioned = TRUE;
            if (wcschr(Params, 'm') != 0)
                bErrOnMixed = TRUE;
            if (wcschr(Params, 'd') != 0)
            {
                if ((dst != NULL) && PathFileExists(dst))
                {
                    _tprintf(L"File '%s' already exists\n", dst);
                    return ERR_OUT_EXISTS;
                }
            }
            // the 'f' option is useful to keep the revision which is inserted in
            // the file constant, even if there are commits on other branches.
            // For example, if you tag your working copy, then half a year later
            // do a fresh checkout of that tag, the folder in your working copy of
            // that tag will get the HEAD revision of the time you check out (or
            // do an update). The files alone however won't have their last-committed
            // revision changed at all.
            if (wcschr(Params, 'f') != 0)
                SubStat.bFolders = TRUE;
            if (wcschr(Params, 'e') != 0)
                SubStat.bExternals = TRUE;
            if (wcschr(Params, 'E') != 0)
                SubStat.bExternalsNoMixedRevision = TRUE;
            if (wcschr(Params, 'x') != 0)
                SubStat.bHexPlain = TRUE;
            if (wcschr(Params, 'X') != 0)
                SubStat.bHexX = TRUE;
            if (wcschr(Params, 'F') != 0)
                bUseSubWCRevIgnore = FALSE;
        }
        else
        {
            // Bad params - abort and display help.
            wc = NULL;
        }
    }

    if (wc == NULL)
    {
        _tprintf(L"SubWCRev %d.%d.%d, Build %d - %s\n\n",
            TSVN_VERMAJOR, TSVN_VERMINOR,
            TSVN_VERMICRO, TSVN_VERBUILD,
            _T(TSVN_PLATFORM));
        _putts(_T(HelpText1));
        _putts(_T(HelpText2));
        _putts(_T(HelpText3));
        _putts(_T(HelpText4));
        _putts(_T(HelpText5));
        return ERR_SYNTAX;
    }

    DWORD reqLen = GetFullPathName(wc, 0, NULL, NULL);
    auto wcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
    GetFullPathName(wc, reqLen, wcfullPath.get(), NULL);
    // GetFullPathName() sometimes returns the full path with the wrong
    // case. This is not a problem on Windows since its filesystem is
    // case-insensitive. But for SVN that's a problem if the wrong case
    // is inside a working copy: the svn wc database is case sensitive.
    // To fix the casing of the path, we use a trick:
    // convert the path to its short form, then back to its long form.
    // That will fix the wrong casing of the path.
    int shortlen = GetShortPathName(wcfullPath.get(), NULL, 0);
    if (shortlen)
    {
        auto shortPath = std::make_unique<TCHAR[]>(shortlen + 1);
        if (GetShortPathName(wcfullPath.get(), shortPath.get(), shortlen + 1))
        {
            reqLen = GetLongPathName(shortPath.get(), NULL, 0);
            wcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
            GetLongPathName(shortPath.get(), wcfullPath.get(), reqLen);
        }
    }
    wc = wcfullPath.get();
    std::unique_ptr<TCHAR[]> dstfullPath = nullptr;
    if (dst)
    {
        reqLen = GetFullPathName(dst, 0, NULL, NULL);
        dstfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
        GetFullPathName(dst, reqLen, dstfullPath.get(), NULL);
        shortlen = GetShortPathName(dstfullPath.get(), NULL, 0);
        if (shortlen)
        {
            auto shortPath = std::make_unique<TCHAR[]>(shortlen + 1);
            if (GetShortPathName(dstfullPath.get(), shortPath.get(), shortlen+1))
            {
                reqLen = GetLongPathName(shortPath.get(), NULL, 0);
                dstfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
                GetLongPathName(shortPath.get(), dstfullPath.get(), reqLen);
            }
        }
        dst = dstfullPath.get();
    }
    std::unique_ptr<TCHAR[]> srcfullPath = nullptr;
    if (src)
    {
        reqLen = GetFullPathName(src, 0, NULL, NULL);
        srcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
        GetFullPathName(src, reqLen, srcfullPath.get(), NULL);
        shortlen = GetShortPathName(srcfullPath.get(), NULL, 0);
        if (shortlen)
        {
            auto shortPath = std::make_unique<TCHAR[]>(shortlen + 1);
            if (GetShortPathName(srcfullPath.get(), shortPath.get(), shortlen+1))
            {
                reqLen = GetLongPathName(shortPath.get(), NULL, 0);
                srcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
                GetLongPathName(shortPath.get(), srcfullPath.get(), reqLen);
            }
        }
        src = srcfullPath.get();
    }

    if (!PathFileExists(wc))
    {
        _tprintf(L"Directory or file '%s' does not exist\n", wc);
        if (wcschr(wc, '\"') != NULL) // dir contains a quotation mark
        {
            _tprintf(L"The WorkingCopyPath contains a quotation mark.\n");
            _tprintf(L"this indicates a problem when calling SubWCRev from an interpreter which treats\n");
            _tprintf(L"a backslash char specially.\n");
            _tprintf(L"Try using double backslashes or insert a dot after the last backslash when\n");
            _tprintf(L"calling SubWCRev\n");
            _tprintf(L"Examples:\n");
            _tprintf(L"SubWCRev \"path to wc\\\\\"\n");
            _tprintf(L"SubWCRev \"path to wc\\.\"\n");
        }
        return ERR_FNF;         // dir does not exist
    }
    std::unique_ptr<char[]> pBuf = nullptr;
    DWORD readlength = 0;
    size_t filelength = 0;
    size_t maxlength  = 0;
    if (dst != NULL)
    {
        // open the file and read the contents
        CAutoFile hFile = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
        if (!hFile)
        {
            _tprintf(L"Unable to open input file '%s'\n", src);
            return ERR_OPEN;        // error opening file
        }
        filelength = GetFileSize(hFile, NULL);
        if (filelength == INVALID_FILE_SIZE)
        {
            _tprintf(L"Could not determine file size of '%s'\n", src);
            return ERR_READ;
        }
        maxlength = filelength+4096;    // We might be increasing file size.
        pBuf = std::make_unique<char[]>(maxlength);
        if (pBuf == NULL)
        {
            _tprintf(L"Could not allocate enough memory!\n");
            return ERR_ALLOC;
        }
        if (!ReadFile(hFile, pBuf.get(), (DWORD)filelength, &readlength, NULL))
        {
            _tprintf(L"Could not read the file '%s'\n", src);
            return ERR_READ;
        }
        if (readlength != filelength)
        {
            _tprintf(L"Could not read the file '%s' to the end!\n", src);
            return ERR_READ;
        }
    }
    // Now check the status of every file in the working copy
    // and gather revision status information in SubStat.

    apr_pool_t * pool;
    svn_error_t * svnerr = NULL;
    svn_client_ctx_t * ctx;
    const char * internalpath;

    apr_initialize();
    svn_dso_initialize2();
    apr_pool_create_ex (&pool, NULL, abort_on_pool_failure, NULL);
    svn_client_create_context2(&ctx, NULL, pool);

    size_t ret = 0;
    getenv_s(&ret, NULL, 0, "SVN_ASP_DOT_NET_HACK");
    if (ret)
    {
        svn_wc_set_adm_dir("_svn", pool);
    }

    char *wc_utf8 = Utf16ToUtf8(wc, pool);
    internalpath = svn_dirent_internal_style (wc_utf8, pool);
    if (bUseSubWCRevIgnore)
    {
        const char *wcroot;
        svnerr = svn_client_get_wc_root(&wcroot, internalpath, ctx, pool, pool);
        if ((svnerr == SVN_NO_ERROR) && wcroot)
            LoadIgnorePatterns(wcroot, &SubStat);
        svn_error_clear(svnerr);
        LoadIgnorePatterns(internalpath, &SubStat);
    }

    svnerr = svn_status(    internalpath,   //path
                            &SubStat,       //status_baton
                            TRUE,           //noignore
                            ctx,
                            pool);

    if (svnerr)
    {
        svn_handle_error2(svnerr, stdout, FALSE, "SubWCRev : ");
    }
    TCHAR wcfullpath[MAX_PATH] = { 0 };
    LPTSTR dummy;
    GetFullPathName(wc, MAX_PATH, wcfullpath, &dummy);
    apr_status_t e = 0;
    if (svnerr)
    {
        e = svnerr->apr_err;
        svn_error_clear(svnerr);
    }
    apr_terminate2();
    if (svnerr)
    {
        if (e == SVN_ERR_WC_NOT_DIRECTORY)
            return ERR_NOWC;
        return ERR_SVN_ERR;
    }

    char wcfull_oem[MAX_PATH] = { 0 };
    CharToOem(wcfullpath, wcfull_oem);
    _tprintf(L"SubWCRev: '%hs'\n", wcfull_oem);


    if (bErrOnMods && SubStat.HasMods)
    {
        _tprintf(L"Working copy has local modifications!\n");
        return ERR_SVN_MODS;
    }
    if (bErrOnUnversioned && SubStat.HasUnversioned)
    {
        _tprintf(L"Working copy has unversioned items!\n");
        return ERR_SVN_UNVER;
    }

    if (bErrOnMixed && (SubStat.MinRev != SubStat.MaxRev))
    {
        if (SubStat.bHexPlain)
            _tprintf(L"Working copy contains mixed revisions %lX:%lX!\n", SubStat.MinRev, SubStat.MaxRev);
        else if (SubStat.bHexX)
            _tprintf(L"Working copy contains mixed revisions %#lX:%#lX!\n", SubStat.MinRev, SubStat.MaxRev);
        else
            _tprintf(L"Working copy contains mixed revisions %ld:%ld!\n", SubStat.MinRev, SubStat.MaxRev);
        return ERR_SVN_MIXED;
    }

    if (!bQuiet)
    {
        if (SubStat.bHexPlain)
            _tprintf(L"Last committed at revision %lX\n", SubStat.CmtRev);
        else if (SubStat.bHexX)
            _tprintf(L"Last committed at revision %#lX\n", SubStat.CmtRev);
        else
            _tprintf(L"Last committed at revision %ld\n", SubStat.CmtRev);

        if (SubStat.MinRev != SubStat.MaxRev)
        {
            if (SubStat.bHexPlain)
                _tprintf(L"Mixed revision range %lX:%lX\n", SubStat.MinRev, SubStat.MaxRev);
            else if (SubStat.bHexX)
                _tprintf(L"Mixed revision range %#lX:%#lX\n", SubStat.MinRev, SubStat.MaxRev);
            else
                _tprintf(L"Mixed revision range %ld:%ld\n", SubStat.MinRev, SubStat.MaxRev);
        }
        else
        {
            if (SubStat.bHexPlain)
                _tprintf(L"Updated to revision %lX\n", SubStat.MaxRev);
            else if (SubStat.bHexX)
                _tprintf(L"Updated to revision %#lX\n", SubStat.MaxRev);
            else
                _tprintf(L"Updated to revision %ld\n", SubStat.MaxRev);
        }

        if (SubStat.HasMods)
        {
            _tprintf(L"Local modifications found\n");
        }

        if (SubStat.HasUnversioned)
        {
            _tprintf(L"Unversioned items found\n");
        }
    }

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

    // now parse the file contents for version defines.

    size_t index = 0;

    while (InsertRevision(VERDEF, pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(VERDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));

    index = 0;
    while (InsertRevision(VERDEFAND, pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(VERDEFAND), (wchar_t*)pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));

    index = 0;
    while (InsertRevision(VERDEFOFFSET1, pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(VERDEFOFFSET1), (wchar_t*)pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));

    index = 0;
    while (InsertRevision(VERDEFOFFSET2, pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(VERDEFOFFSET2), (wchar_t*)pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));

    index = 0;
    while (InsertRevision(RANGEDEF, pBuf.get(), index, filelength, maxlength, SubStat.MinRev, SubStat.MaxRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(RANGEDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.MinRev, SubStat.MaxRev, &SubStat));

    index = 0;
    while (InsertDate(DATEDEF, pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDateW(TEXT(DATEDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));

    index = 0;
    while (InsertDate(DATEDEFUTC, pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDateW(TEXT(DATEDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));

    index = 0;
    while (InsertDate(DATEWFMTDEF, pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDateW(TEXT(DATEWFMTDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDate(DATEWFMTDEFUTC, pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDateW(TEXT(DATEWFMTDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));

    index = 0;
    while (InsertDate(NOWDEF, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
    index = 0;
    while (InsertDateW(TEXT(NOWDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

    index = 0;
    while (InsertDate(NOWDEFUTC, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
    index = 0;
    while (InsertDateW(TEXT(NOWDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

    index = 0;
    while (InsertDate(NOWWFMTDEF, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
    index = 0;
    while (InsertDateW(TEXT(NOWWFMTDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

    index = 0;
    while (InsertDate(NOWWFMTDEFUTC, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
    index = 0;
    while (InsertDateW(TEXT(NOWWFMTDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

    index = 0;
    while (InsertBoolean(MODDEF, pBuf.get(), index, filelength, SubStat.HasMods));
    index = 0;
    while (InsertBooleanW(TEXT(MODDEF), (wchar_t*)pBuf.get(), index, filelength, SubStat.HasMods));

    index = 0;
    while (InsertBoolean(UNVERDEF, pBuf.get(), index, filelength, SubStat.HasUnversioned));
    index = 0;
    while (InsertBooleanW(TEXT(UNVERDEF), (wchar_t*)pBuf.get(), index, filelength, SubStat.HasUnversioned));

    index = 0;
    while (InsertBoolean(MIXEDDEF, pBuf.get(), index, filelength, (SubStat.MinRev != SubStat.MaxRev) || SubStat.bIsExternalMixed));
    index = 0;
    while (InsertBooleanW(TEXT(MIXEDDEF), (wchar_t*)pBuf.get(), index, filelength, (SubStat.MinRev != SubStat.MaxRev) || SubStat.bIsExternalMixed));

    index = 0;
    while (InsertBoolean(EXTALLFIXED, pBuf.get(), index, filelength, !SubStat.bIsExternalsNotFixed));
    index = 0;
    while (InsertBooleanW(TEXT(EXTALLFIXED), (wchar_t*)pBuf.get(), index, filelength, !SubStat.bIsExternalsNotFixed));

    index = 0;
    while (InsertBoolean(ISTAGGED, pBuf.get(), index, filelength, SubStat.bIsTagged));
    index = 0;
    while (InsertBooleanW(TEXT(ISTAGGED), (wchar_t*)pBuf.get(), index, filelength, SubStat.bIsTagged));

    index = 0;
    while (InsertUrl(URLDEF, pBuf.get(), index, filelength, maxlength, SubStat.Url));
    index = 0;
    while (InsertUrlW(TEXT(URLDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, Utf8ToWide(SubStat.Url).c_str()));

    index = 0;
    while (InsertBoolean(ISINSVN, pBuf.get(), index, filelength, SubStat.bIsSvnItem));
    index = 0;
    while (InsertBooleanW(TEXT(ISINSVN), (wchar_t*)pBuf.get(), index, filelength, SubStat.bIsSvnItem));

    index = 0;
    while (InsertBoolean(NEEDSLOCK, pBuf.get(), index, filelength, SubStat.LockData.NeedsLocks));
    index = 0;
    while (InsertBooleanW(TEXT(NEEDSLOCK), (wchar_t*)pBuf.get(), index, filelength, SubStat.LockData.NeedsLocks));

    index = 0;
    while (InsertBoolean(ISLOCKED, pBuf.get(), index, filelength, SubStat.LockData.IsLocked));
    index = 0;
    while (InsertBooleanW(TEXT(ISLOCKED), (wchar_t*)pBuf.get(), index, filelength, SubStat.LockData.IsLocked));

    index = 0;
    while (InsertDate(LOCKDATE, pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));
    index = 0;
    while (InsertDateW(TEXT(LOCKDATE), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));

    index = 0;
    while (InsertDate(LOCKDATEUTC, pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));
    index = 0;
    while (InsertDateW(TEXT(LOCKDATEUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));

    index = 0;
    while (InsertDate(LOCKWFMTDEF, pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));
    index = 0;
    while (InsertDateW(TEXT(LOCKWFMTDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));

    index = 0;
    while (InsertDate(LOCKWFMTDEFUTC, pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));
    index = 0;
    while (InsertDateW(TEXT(LOCKWFMTDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));

    index = 0;
    while (InsertUrl(LOCKOWNER, pBuf.get(), index, filelength, maxlength, SubStat.LockData.Owner));
    index = 0;
    while (InsertUrlW(TEXT(LOCKOWNER), (wchar_t*)pBuf.get(), index, filelength, maxlength, Utf8ToWide(SubStat.LockData.Owner).c_str()));

    index = 0;
    while (InsertUrl(LOCKCOMMENT, pBuf.get(), index, filelength, maxlength, SubStat.LockData.Comment));
    index = 0;
    while (InsertUrlW(TEXT(LOCKCOMMENT), (wchar_t*)pBuf.get(), index, filelength, maxlength, Utf8ToWide(SubStat.LockData.Comment).c_str()));

    CAutoFile hFile = CreateFile(dst, GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, NULL, NULL);
    if (!hFile)
    {
        _tprintf(L"Unable to open output file '%s' for writing\n", dst);
        return ERR_OPEN;
    }

    size_t filelengthExisting = GetFileSize(hFile, NULL);
    BOOL sameFileContent = FALSE;
    if (filelength == filelengthExisting)
    {
        DWORD readlengthExisting = 0;
        auto pBufExisting = std::make_unique<char[]>(filelength);
        if (!ReadFile(hFile, pBufExisting.get(), (DWORD)filelengthExisting, &readlengthExisting, NULL))
        {
            _tprintf(L"Could not read the file '%s'\n", dst);
            return ERR_READ;
        }
        if (readlengthExisting != filelengthExisting)
        {
            _tprintf(L"Could not read the file '%s' to the end!\n", dst);
            return ERR_READ;
        }
        sameFileContent = (memcmp(pBuf.get(), pBufExisting.get(), filelength) == 0);
    }

    // The file is only written if its contents would change.
    // this object prevents the timestamp from changing.
    if (!sameFileContent)
    {
        SetFilePointer(hFile, 0, NULL, FILE_BEGIN);

        WriteFile(hFile, pBuf.get(), (DWORD)filelength, &readlength, NULL);
        if (readlength != filelength)
        {
            _tprintf(L"Could not write the file '%s' to the end!\n", dst);
            return ERR_READ;
        }

        if (!SetEndOfFile(hFile))
        {
            _tprintf(L"Could not truncate the file '%s' to the end!\n", dst);
            return ERR_READ;
        }
    }

    return 0;
}
Example #27
0
// Creates a shortcut in the startup folder.
void SetStartupOptions() {
	// Required for Win95
	CoInitialize(NULL);
	
	// Create the COM server
	IShellLink *pShellLink = NULL;
	HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL,
			CLSCTX_INPROC_SERVER, IID_IShellLink,
			reinterpret_cast<LPVOID*>(&pShellLink));
	if (FAILED(hr))
		return;
	
	TCHAR szPath[MAX_PATH] = {0};
	GetModuleFileName(NULL, szPath, sizeof(szPath));
	GetShortPathName(szPath, szPath, sizeof(szPath));
	
	// Set attributes
	pShellLink->SetPath(szPath);
	pShellLink->SetDescription(SZ_APPNAME);
	pShellLink->SetHotkey(0);
	pShellLink->SetIconLocation(szPath, 0);
	
	// Get the IPersistFile interface to save
	IPersistFile *pPF = NULL;
	hr = pShellLink->QueryInterface(IID_IPersistFile, reinterpret_cast<LPVOID*>(&pPF));
	
	if (FAILED(hr)) {
		pShellLink->Release();
		return;
	}
	
	LPMALLOC pMalloc;
	if (SUCCEEDED(SHGetMalloc(&pMalloc))) {
		LPITEMIDLIST pidl;
		SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidl);
		SHGetPathFromIDList(pidl, szPath);
		pMalloc->Free(pidl);
		pMalloc->Release();
	}
	
	// Create a .lnk file
	TCHAR szLinkFile[MAX_PATH] = {0};
	wsprintf(szLinkFile, "%s.lnk", SZ_APPNAME);
	
	if (szPath[lstrlen(szPath) - 1] != '\\')
		lstrcat(szPath, "\\");
	lstrcat(szPath, szLinkFile);
	
	if (g_bStartWithWindows) {
		// Save Unicode LNK file
		WCHAR wszLinkFile[MAX_PATH] = {0};
		MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szPath, -1, wszLinkFile, MAX_PATH);
		hr = pPF->Save(wszLinkFile, TRUE);
		if (FAILED(hr))
			ShowError(IDS_STARTUP_ERR, MB_ICONHAND);
	} else {
		DeleteFile(szPath);
	}
	
	// Clean up
	pPF->Release();
	pShellLink->Release();
	CoUninitialize();
}
Example #28
0
BOOL CDynamoRIOApp::InitInstance()
{
#ifndef DRSTATS_DEMO
    TCHAR msg[MAX_PATH*2];
#endif
    BOOL windows_NT;

    // Standard initialization
    // If you are not using these features and wish to reduce the size
    //  of your final executable, you should remove from the following
    //  the specific initialization routines you do not need.

    if (!CheckWindowsVersion(windows_NT)) {
        // abort
        return FALSE;
    }

#if 0 // warning C4996: 'CWinApp::Enable3dControlsStatic': CWinApp::Enable3dControlsStatic is no longer needed. You should remove this call.
#ifdef _AFXDLL
    Enable3dControls();                     // Call this when using MFC in a shared DLL
#else
    Enable3dControlsStatic();       // Call this when linking to MFC statically
#endif
#endif

#ifndef DRSTATS_DEMO
    // Change the registry key under which our settings are stored,
    // including MRU
    SetRegistryKey(L_DYNAMORIO_REGISTRY_KEY);

    LoadStdProfileSettings(12);  // Load standard INI file options (including MRU)
#endif

    // Register the application's document templates.  Document templates
    //  serve as the connection between documents, frame windows and views.

    CSingleDocTemplate* pDocTemplate;
    pDocTemplate = new CSingleDocTemplate(
#ifdef DRSTATS_DEMO
                                          IDR_MAINFRAME_DEMO,
#else
                                          IDR_MAINFRAME,
#endif
                                          RUNTIME_CLASS(CDynamoRIODoc),
                                          RUNTIME_CLASS(CMainFrame),       // main SDI frame window
                                          RUNTIME_CLASS(CDynamoRIOView));
    AddDocTemplate(pDocTemplate);

    // Parse command line for standard shell commands, DDE, file open
    CCommandLineInfo cmdInfo;
    ParseCommandLine(cmdInfo);

    // Dispatch commands specified on the command line
    if (!ProcessShellCommand(cmdInfo))
        return FALSE;

    // enable file manager drag/drop and DDE Execute open
    m_pMainWnd->DragAcceptFiles();

    // The one and only window has been initialized, so show and update it.
    m_pMainWnd->ShowWindow(SW_SHOW);
    m_pMainWnd->UpdateWindow();

    // I can't find any other way to access the main frame
    m_pMainFrame = (CMainFrame *) m_pMainWnd;

    // I can't figure out how to disable a menu item that has a command
    // handler when this var is set, so I disable it:
    m_pMainFrame->m_bAutoMenuEnable = FALSE;        

#ifndef DRSTATS_DEMO
    m_bSystemwideAllowed = TRUE;

    // set the string we'll put into the registry key to inject system-wide
    TCHAR data[1024];
    int len = GetEnvironmentVariable(_T("DYNAMORIO_HOME"), m_dynamorio_home, _MAX_DIR);
#if 1 //NOCHECKIN
    if (len == 0)
        m_dynamorio_home[0] = _T('\0');
#else
    if (len == 0) {
        int res = MessageBox(NULL, 
                             _T("DYNAMORIO_HOME environment variable not found.\n")
                             _T("Set all the DynamoRIO environment variables to their default values?\n")
                             _T("(Otherwise this GUI cannot operate and must exit.)"),
                             _T("DynamoRIO Not Configured for Current User"), MB_YESNO | MYMBFLAGS);
        if (res == IDYES) {
            if (!ConfigureForNewUser())
                return FALSE;
        } else {
            // abort
            return FALSE;
        }
    }
#endif

    if (windows_NT) {
        // we don't support systemwide on NT
        // hack: use "confirm systemwide" setting to decide whether to notify user
        if (GetProfileInt(_T("Settings"), _T("Confirm Systemwide"), 1) == 1) {
            MessageBox(NULL, _T("Run All is not supported on Windows NT, it will be disabled"),
                       _T("Notice"), MB_OK | MYMBFLAGS);
            // but then how does user turn off, if can't do Run All?
            // just turn it off now:
            SetSystemwideSetting(0);
        }
        m_bSystemwideAllowed = FALSE; // so key won't be cleared
        DisableSystemwideInject();
    } else {
        //NOCHECKIN assert(len > 0 && len < _MAX_DIR && len + _tcslen(L_INJECT_ALL_DLL_SUBPATH) < MAX_PATH);
        _stprintf(data, _T("%s%s"), m_dynamorio_home, L_INJECT_ALL_DLL_SUBPATH);

        // make sure it exists
        CFile check;
        if (!check.Open(data, CFile::modeRead|CFile::shareDenyNone)) {
#if 0 // I'm disabling this dialog until we decide to support running apps
            _stprintf(msg, _T("Library %s does not exist"), data);
            MessageBox(NULL, msg, _T("Error"), MB_OK | MYMBFLAGS);
#endif
            m_bSystemwideAllowed = FALSE; // so key won't be cleared
            DisableSystemwideInject();
        } else {
            if (_tcschr(data, _T(' ')) != NULL) {
                // registry key cannot handle spaces in names!
                // must get 8.3 alias -- and some volumes do not support such an alias!
                len = GetShortPathName(data, m_inject_all_value, MAX_PATH);
                if (len == 0) {
                    _stprintf(msg, _T("Cannot find 8.3 alias for space-containing path \"%s\"!\nDisabling Run All"),
                              data);
                    MessageBox(NULL, msg, _T("Error"), MB_OK | MYMBFLAGS);
                    m_bSystemwideAllowed = FALSE; // so key won't be cleared
                    DisableSystemwideInject();
                }
            } else {
                _tcscpy(m_inject_all_value, data);
            }
            check.Close();
        }
    }

    // find current status of system-wide injection
    if (m_bSystemwideAllowed) {
        HKEY hk;
        unsigned long size = 1024;
        int     res = RegOpenKeyEx(INJECT_ALL_HIVE, INJECT_ALL_KEY_L, 0, KEY_READ, &hk);
        assert(res == ERROR_SUCCESS);
        res = RegQueryValueEx(hk, INJECT_ALL_SUBKEY_L, 0, NULL, (LPBYTE) data, &size);
        assert(res == ERROR_SUCCESS);
        RegCloseKey(hk);

        // WARNING: do not use Unicode build!
        // if ever get size==2, it's b/c of Unicode build!
        // Plus, stats viewing doesn't work w/ Unicode build
        if (size > sizeof(TCHAR)) {
            // make sure we're the ones who set this value
            if (_tcscmp(m_inject_all_value, data) != 0) {
                // FIXME: have user notify us of conflict?
                int res = MessageBox(NULL, 
                                     _T("DynamoRIO's RunAll system-wide injection method is ")
                                     _T("being used by some other program.\n")
                                     _T("DynamoRIO can attempt to override the other program.\n")
                                     _T("Otherwise, system-wide injection will be disabled.\n")
                                     _T("Override?"),
                                     _T("DynamoRIO Conflict"),
                                     MB_YESNO | MYMBFLAGS);
                if (res == IDYES) {
                    // now clear the registry key
                    SetSystemwideInject(_T(""));
                    // if the call fails, callee calls Disable for us
                } else {
                    m_bSystemwideAllowed = FALSE; // so key won't be cleared
                    DisableSystemwideInject();
                }
            } else {
                m_bInjectAll = TRUE;
            }
        } else {
            // empty value: no injection
            m_bInjectAll = FALSE;
        }
    }
    if (m_bSystemwideAllowed) {
        m_pMainWnd->GetMenu()->CheckMenuItem(ID_FILE_SYSTEMWIDE, 
                                             MF_BYCOMMAND | ((m_bInjectAll) ? MF_CHECKED : MF_UNCHECKED));
    }

    // make sure preinject dll exists
    if (m_bSystemwideAllowed) {
        CFile check;
        if (!check.Open(m_inject_all_value, CFile::modeRead|CFile::shareDenyNone)) {
#if 0 // I'm disabling this dialog until we decide to support running apps
            _stprintf(msg, _T("Library %s does not exist!\nDisabling Run All"), m_inject_all_value);
            MessageBox(NULL, msg, _T("DynamoRIO Configuration Error"), MB_OK | MYMBFLAGS);
#endif
            DisableSystemwideInject();
        } else
            check.Close();
    }

    m_dll_path[0] = _T('\0');

    DisableMissingLibraries(TRUE);

    // now select the previously checked library
    int lib = GetProfileInt(_T("Settings"), _T("Library"), 1);
    int tried = 0;
    while (tried < 3) {
        if (lib == 0 && SwitchLibraries(L_DLLPATH_RELEASE, FALSE)) {
            OnLibraryRelease();
            break;
        } else if (lib == 1 && SwitchLibraries(L_DLLPATH_DEBUG, FALSE)) {
            OnLibraryDebug();
            break;
        } else if (lib == 2 && SwitchLibraries(L_DLLPATH_PROFILE, FALSE)) {
            OnLibraryProfile();
            break;
        } 
        lib = (lib + 1) % 3;
        tried++;
    }
    if (tried == 3) {
#if 0 // Disabling
        MessageBox(NULL, _T("Cannot find any DynamoRIO libraries!\n")
                   _T("Running of applications will be disabled."), _T("Error"), MB_OK | MYMBFLAGS);
#endif
        // disable Run and libraries
        m_pMainWnd->GetMenu()->EnableMenuItem(ID_FILE_RUN, MF_BYCOMMAND|MF_GRAYED);
        DisableSystemwideInject();
        m_pMainWnd->GetMenu()->EnableMenuItem(ID_LIBRARY_RELEASE, MF_BYCOMMAND|MF_GRAYED);
        m_pMainWnd->GetMenu()->EnableMenuItem(ID_LIBRARY_DEBUG, MF_BYCOMMAND|MF_GRAYED);
        m_pMainWnd->GetMenu()->EnableMenuItem(ID_LIBRARY_PROFILE, MF_BYCOMMAND|MF_GRAYED);
        m_pMainWnd->GetMenu()->CheckMenuItem(ID_LIBRARY_RELEASE, MF_BYCOMMAND|MF_UNCHECKED);
        m_pMainWnd->GetMenu()->CheckMenuItem(ID_LIBRARY_DEBUG,   MF_BYCOMMAND|MF_UNCHECKED);
        m_pMainWnd->GetMenu()->CheckMenuItem(ID_LIBRARY_PROFILE, MF_BYCOMMAND|MF_UNCHECKED);
    }

    if (m_bInjectAll) {
        MessageBox(NULL, _T("Run All is already set!"),
                   _T("Warning"), MB_OK | MYMBFLAGS);

        // FIXME: share this code with OnFileSystemwide
        SetEnvVarPermanently(_T("DYNAMORIO_SYSTEMWIDE"), m_dll_path);

        // disable changing the library
        m_pMainWnd->GetMenu()->EnableMenuItem(ID_LIBRARY_RELEASE, MF_BYCOMMAND|MF_GRAYED);
        m_pMainWnd->GetMenu()->EnableMenuItem(ID_LIBRARY_DEBUG, MF_BYCOMMAND|MF_GRAYED);
        m_pMainWnd->GetMenu()->EnableMenuItem(ID_LIBRARY_PROFILE, MF_BYCOMMAND|MF_GRAYED);
    }
#endif /*! DRSTATS_DEMO */

    return TRUE;
}
Example #29
0
int main(int argc, char** argv)
{
	SETTINGS settings;
	int      option_index = 1,
	         ret,
	         i,
	         bits;

#ifdef _WIN32
 	char     CmdDir[MAX_PATH];
 	char     *p;
#endif

	memset(&settings, 0, sizeof(settings));
	settings.first_file = 1;
	settings.radio = 1;
	settings.clip_prev = 1;
	settings.outbitwidth = 16;
	settings.format = WAV_NO_FMT;

#ifdef _WIN32
	/* Is this good enough? Or do we need to consider multi-byte codepages as 
	* well? 
	*/
	SetConsoleOutputCP(GetACP());

	GetModuleFileName(NULL, CmdDir, MAX_PATH);
	p = strrchr(CmdDir, '\\') + 1;
	p[0] = '\0';
#endif

	while ((ret = getopt_long(argc, argv, ARG_STRING, long_options, &option_index)) != -1) {
		switch(ret) {
			case 0:
				if (!strcmp(long_options[option_index].name, "force")) {
					settings.force = 1;
				}
				else if (!strcmp(long_options[option_index].name, "undo-gain")) {
					settings.undo = 1;
				}
				else {
					fprintf(stderr, "Internal error parsing command line options\n");
					exit(1);
				}
				break;
			case 'h':
				usage();
				exit(0);
				break;
			case 'a':
				settings.audiophile = 1;
				break;
			case 'r':
				settings.radio = 1;
				break;
			case 'q':
				settings.adc = 1;
				break;
			case 'p':
				settings.no_offset = 1;
				break;
			case 'c':
				settings.apply_gain = 0;
				break;
			case 'x':
				settings.scale = 1;
				break;
			case 'y':
				settings.apply_gain = 1;
				settings.scale = 0;
				break;
			case 'w':
				settings.write_chunk = 1;
				break;
			case 's':
				settings.fast = 1;
				break;
			case 'o':
				settings.std_out = 1;
				break;
#ifdef ENABLE_RECURSIVE
			case 'z':
				settings.recursive = 1;
				break;
#endif
			case 'l':
				write_to_log = 1;
#ifdef _WIN32
				strcpy(log_file_name, CmdDir);
				strcat(log_file_name, LOG_NAME);
#else
				strcpy(log_file_name, LOG_NAME);
#endif
				break;
			case 'f':
				write_to_log = 1;
				strcpy(log_file_name, optarg);
				break;
			case 'n':
				settings.clip_prev = 0;
				break;
			case 'd':
				settings.need_to_process = 1;
				settings.dithering = 1;
   				if(sscanf(optarg, "%d", &settings.shapingtype) != 1) {
	    				fprintf(stderr, "Warning: dither type %s not recognised, using default\n", optarg);
		    			break;
				}
				if (settings.shapingtype == 0)
					settings.dithering = 0;
				else if (settings.shapingtype == 1)
					settings.shapingtype = 0;
				else if (settings.shapingtype == 2)
					settings.shapingtype = 1;
				else if (settings.shapingtype == 3)
					settings.shapingtype = 2;
				else if (settings.shapingtype == 4)
					settings.shapingtype = 3;
				break;
			case 't':
				settings.limiter = 1;
				break;
			case 'g':
   				if(sscanf(optarg, "%lf", &settings.man_gain) != 1) {
	    				fprintf(stderr, "Warning: manual gain %s not recognised, ignoring\n", optarg);
					break;
				}
				if(settings.man_gain < -20.0) {
	    				fprintf(stderr, "Warning: manual gain %s is out of range, "
					                 "applying gain of -20.0dB\n", optarg);
					settings.man_gain = -20.0;
				}
				else if(settings.man_gain > 12.0) {
	    				fprintf(stderr, "Warning: manual gain %s is out of range, "
					                 "applying gain of +12.0dB\n", optarg);
					settings.man_gain = 12.0;
				}
				break;
			case 'b':
				settings.need_to_process = 1;
   				if(sscanf(optarg, "%d", &bits) != 1) {
	    				fprintf(stderr, "Warning: output format %s not recognised, using default\n", optarg);
		    			break;
				}
				if (bits == 1) {
					settings.outbitwidth = 8;
					settings.format = WAV_FMT_8BIT;
		    			break;
				}
				else if (bits == 2) {
					settings.outbitwidth = 16;
					settings.format = WAV_FMT_16BIT;
		    			break;
				}
				else if (bits == 3) {
					settings.outbitwidth = 24;
					settings.format = WAV_FMT_24BIT;
		    			break;
				}
				else if (bits == 4) {
					settings.outbitwidth = 32;
					settings.format = WAV_FMT_32BIT;
		    			break;
				}
				else if (bits == 5) {
					settings.outbitwidth = 32;
					settings.format = WAV_FMT_FLOAT;
		    			break;
				}
				else if (bits == 6) {
					settings.outbitwidth = 16;
					settings.format = WAV_FMT_AIFF;
		    			break;
				}
				else {
	    				fprintf(stderr, "Warning: output format %s not recognised, using default\n", optarg);
					break;
				}
				break;
#ifdef _WIN32
			case 'e': {
				char *p;
				int k;
				char * lpPart[MAX_PATH]={NULL};

				settings.cmd = (char *) malloc(1024*8); /* 8Kb is XP's limit */
				if (settings.cmd == NULL) {
					fprintf(stderr, "Failed to allocate memory for cmd...\n");
					return 1;
				}

				p = settings.cmd;

				k = GetFullPathName(argv[optind - 1], 1024*8, p, lpPart);
				k = GetShortPathName(p, p, MAX_PATH);
				if (k == 0) {
					p += sprintf (p, "%s", argv[optind - 1]);
				} else {
					p += k;
				}

				for (k = optind; k < argc; ++k) {
					p += sprintf(p, " \"%s\"", argv[k]);
				}

				argc = optind;
				break;
			}
#endif
		}
	}
	if (settings.undo == 1) {
		settings.write_chunk = 0;
		settings.no_offset = 1;
	}

	if (optind >= argc) {
		fprintf(stderr, _("No files specified.\n"));
		usage();
		return EXIT_SUCCESS;
	}

	if (write_to_log) {
		write_log("Command line:\n\t");
		for(i = 0; i < argc; i++)
			write_log("%s ",  argv[i]);
		write_log("\n");
	}

	if (!strcmp(argv[optind], "-")) {
		double track_peak, track_gain;
		double dc_offset;
		double offset;
		if (!get_gain("-", &track_peak, &track_gain,
		              &dc_offset, &offset, &settings))
			return -1;
	}
	else {
		for (i = optind; i < argc; ++i) {
#ifdef ENABLE_RECURSIVE
			if (process_argument(argv[i], &settings) < 0) {
				free_list(settings.file_list);
				return EXIT_FAILURE;
			}
#else
			if (add_to_list(&settings.file_list, argv[i]) < 0)
				return EXIT_FAILURE;
#endif
		}

		/* Process files (perhaps remaining) in list */
		ret = process_files(settings.file_list, &settings, ".");
		free_list(settings.file_list);
		settings.file_list = NULL;
		if (settings.cmd) free(settings.cmd);
		settings.cmd = NULL;
	}

	return (ret < 0) ? EXIT_FAILURE : EXIT_SUCCESS;
}
Example #30
0
bool CCommonAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
{
	OPENFILENAME ofn = {0};				// common dialog box structure
	TCHAR szFile[MAX_PATH] = {0};		// buffer for file name. Explorer can't handle paths longer than MAX_PATH.
	ofn.lStructSize = sizeof(OPENFILENAME);
	ofn.hwndOwner = hwndOwner;
	if (path.GetLength() >= MAX_PATH)
	{
		CString dir = path;
		while (true)
		{
			int index = dir.ReverseFind(_T('\\'));
			if (index < 0)
				break;
			dir = dir.Left(index);
			if (PathFileExists(dir))
				break;
		}
		GetShortPathName(dir, szFile, MAX_PATH);
		CString remain = path.Right(path.GetLength() - dir.GetLength());
		_tcscat_s(szFile, MAX_PATH, remain);
	}
	else
		_tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
	ofn.lpstrFile = szFile;
	ofn.nMaxFile = _countof(szFile);

	CSelectFileFilter fileFilter;
	if (filter)
	{
		fileFilter.Load(filter);
		ofn.lpstrFilter = fileFilter;
	}
	ofn.nFilterIndex = 1;

	ofn.lpstrFileTitle = NULL;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = NULL;
	CString temp;
	if (title)
	{
		temp.LoadString(title);
		CStringUtils::RemoveAccelerators(temp);
	}
	ofn.lpstrTitle = temp;
	if (bOpen)
		ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
	else
		ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;


	// Display the Open dialog box.
	bool bRet = false;
	if (bOpen)
	{
		bRet = !!GetOpenFileName(&ofn);
	}
	else
	{
		bRet = !!GetSaveFileName(&ofn);
	}
	SetCurrentDirectory(sOrigCWD.GetBuffer());
	sOrigCWD.ReleaseBuffer();
	if (bRet)
	{
		path = CString(ofn.lpstrFile);
		if (filterindex)
			*filterindex = ofn.nFilterIndex;
		return true;
	}
	return false;
}