Exemplo n.º 1
0
static DWORD
DeleteFiles(LPTSTR FileName, DWORD* dwFlags, DWORD dwAttrFlags)
{
        TCHAR szFullPath[MAX_PATH];
        TCHAR szFileName[MAX_PATH];
        LPTSTR pFilePart;
        HANDLE hFile;
        WIN32_FIND_DATA f;
        BOOL bExclusion;
        INT res;
        DWORD dwFiles = 0;

        _tcscpy(szFileName, FileName);

        if(_tcschr (szFileName, _T('*')) == NULL &&
	   IsExistingDirectory (szFileName))
        {
	        /* If it doesnt have a \ at the end already then on needs to be added */
		if(szFileName[_tcslen(szFileName) -  1] != _T('\\'))
                        _tcscat (szFileName, _T("\\"));
                /* Add a wildcard after the \ */
                _tcscat (szFileName, _T("*"));
        }

	if(!_tcscmp (szFileName, _T("*")) ||
           !_tcscmp (szFileName, _T("*.*")) ||
           (szFileName[_tcslen(szFileName) -  2] == _T('\\') && szFileName[_tcslen(szFileName) -  1] == _T('*')))
        {
                /* well, the user wants to delete everything but if they didnt yes DEL_YES, DEL_QUIET, or DEL_PROMPT
	           then we are going to want to make sure that in fact they want to do that.  */

		if (!((*dwFlags & DEL_YES) || (*dwFlags & DEL_QUIET) || (*dwFlags & DEL_PROMPT)))
	        {
        	        res = FilePromptYNA (STRING_DEL_HELP2);
		        if ((res == PROMPT_NO) || (res == PROMPT_BREAK))
			        return 0x80000000;
		        if(res == PROMPT_ALL)
			        *dwFlags |= DEL_YES;
	        }
	}

        GetFullPathName (szFileName,
                         MAX_PATH,
                         szFullPath,
                         &pFilePart);

        hFile = FindFirstFile(szFullPath, &f);
        if (hFile != INVALID_HANDLE_VALUE)
        {
                do
                {
					bExclusion = FALSE;

					/*if it is going to be excluded by - no need to check attrs*/
					if(*dwFlags & DEL_ATTRIBUTES && !bExclusion)
					{

						/*save if file attr check if user doesnt care about that attr anyways*/
					 if(dwAttrFlags & ATTR_ARCHIVE && !(f.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE))
				        bExclusion = TRUE;
					 if(dwAttrFlags & ATTR_HIDDEN && !(f.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN))
				        bExclusion = TRUE;
					 if(dwAttrFlags & ATTR_SYSTEM && !(f.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM))
				        bExclusion = TRUE;
					 if(dwAttrFlags & ATTR_READ_ONLY && !(f.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
			            bExclusion = TRUE;
		             if(dwAttrFlags & ATTR_N_ARCHIVE && (f.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE))
			            bExclusion = TRUE;
		             if(dwAttrFlags & ATTR_N_HIDDEN && (f.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN))
			            bExclusion = TRUE;
		             if(dwAttrFlags & ATTR_N_SYSTEM && (f.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM))
			            bExclusion = TRUE;
		             if(dwAttrFlags & ATTR_N_READ_ONLY && (f.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
			            bExclusion = TRUE;
					}
					if(bExclusion)
						continue;

					/* ignore directories */
					if (f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		                continue;


					_tcscpy (pFilePart, f.cFileName);

					/* We cant delete ourselves */
					if(!_tcscmp (CMDPath,szFullPath))
						continue;


					TRACE("Full filename: %s\n", debugstr_aw(szFullPath));

					/* ask for deleting */
					if (*dwFlags & DEL_PROMPT)
					{
		                ConErrResPrintf(STRING_DEL_ERROR5, szFullPath);

		                res = FilePromptYN (STRING_DEL_ERROR6);

		                if ((res == PROMPT_NO) || (res == PROMPT_BREAK))
		                {
								 nErrorLevel = 0;
			                continue;
		                }
	                }

	                /*user cant ask it to be quiet and tell you what it did*/
	                if (!(*dwFlags & DEL_QUIET) && !(*dwFlags & DEL_TOTAL))
	                {
		                ConErrResPrintf(STRING_DEL_ERROR7, szFullPath);
	                }

	                /* delete the file */
	                if(*dwFlags & DEL_NOTHING)
		                continue;

	                if(RemoveFile (szFullPath, *dwFlags, &f))
		                dwFiles++;
					else
                        {
							ErrorMessage (GetLastError(), _T(""));
//                                FindClose(hFile);
//                                return -1;
						}
                }
                while (FindNextFile (hFile, &f));
				FindClose (hFile);
        } 
		else error_sfile_not_found(szFullPath);
        return dwFiles;
}
Exemplo n.º 2
0
InspIRCd::InspIRCd(int argc, char** argv) :
	 ConfigFileName(INSPIRCD_CONFIG_PATH "/inspircd.conf"),
	 PI(&DefaultProtocolInterface),

	 /* Functor pointer initialisation.
	  *
	  * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
	  * themselves within the class.
	  */
	 GenRandom(&DefaultGenRandom),
	 IsChannel(&DefaultIsChannel),
	 IsNick(&DefaultIsNick),
	 IsIdent(&DefaultIsIdent)
{
	ServerInstance = this;

	FailedPortList pl;
	// Flag variables passed to getopt_long() later
	int do_version = 0, do_nofork = 0, do_debug = 0,
	    do_nolog = 0, do_nopid = 0, do_root = 0;

	// Initialize so that if we exit before proper initialization they're not deleted
	this->Config = 0;
	this->XLines = 0;
	this->ConfigThread = NULL;
	this->FakeClient = NULL;

	UpdateTime();
	this->startup_time = TIME.tv_sec;

	SocketEngine::Init();

	this->Config = new ServerConfig;
	dynamic_reference_base::reset_all();
	this->XLines = new XLineManager;

	this->Config->cmdline.argv = argv;
	this->Config->cmdline.argc = argc;

#ifdef _WIN32
	srand(TIME.tv_nsec ^ TIME.tv_sec);

	// Initialize the console values
	g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_SCREEN_BUFFER_INFO bufinf;
	if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
	{
		g_wOriginalColors = bufinf.wAttributes & 0x00FF;
		g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
	}
	else
	{
		g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
		g_wBackgroundColor = 0;
	}
#else
	srandom(TIME.tv_nsec ^ TIME.tv_sec);
#endif

	{
		ServiceProvider* provs[] =
		{
			&rfcevents.numeric, &rfcevents.join, &rfcevents.part, &rfcevents.kick, &rfcevents.quit, &rfcevents.nick,
			&rfcevents.mode, &rfcevents.topic, &rfcevents.privmsg, &rfcevents.invite, &rfcevents.ping, &rfcevents.pong,
			&rfcevents.error
		};
		Modules.AddServices(provs, sizeof(provs)/sizeof(provs[0]));
	}

	struct option longopts[] =
	{
		{ "nofork",	no_argument,		&do_nofork,	1	},
		{ "config",	required_argument,	NULL,		'c'	},
		{ "debug",	no_argument,		&do_debug,	1	},
		{ "nolog",	no_argument,		&do_nolog,	1	},
		{ "nopid",	no_argument,		&do_nopid,	1	},
		{ "runasroot",	no_argument,		&do_root,	1	},
		{ "version",	no_argument,		&do_version,	1	},
#ifdef INSPIRCD_ENABLE_TESTSUITE
		{ "testsuite",	no_argument,		&do_testsuite,	1	},
#endif
		{ 0, 0, 0, 0 }
	};

	int c;
	int index;
	while ((c = getopt_long(argc, argv, ":c:", longopts, &index)) != -1)
	{
		switch (c)
		{
			case 'c':
				/* Config filename was set */
				ConfigFileName = optarg;
#ifdef _WIN32
				TCHAR configPath[MAX_PATH + 1];
				if (GetFullPathName(optarg, MAX_PATH, configPath, NULL) > 0)
					ConfigFileName = configPath;
#else
				char configPath[PATH_MAX + 1];
				if (realpath(optarg, configPath))
					ConfigFileName = configPath;
#endif
			break;
			case 0:
				/* getopt_long_only() set an int variable, just keep going */
			break;
			case '?':
				/* Unknown parameter */
			default:
				/* Fall through to handle other weird values too */
				std::cout << "Unknown parameter '" << argv[optind-1] << "'" << std::endl;
				std::cout << "Usage: " << argv[0] << " [--nofork] [--nolog] [--nopid] [--debug] [--config <config>]" << std::endl <<
					std::string(static_cast<size_t>(8+strlen(argv[0])), ' ') << "[--runasroot] [--version]" << std::endl;
				Exit(EXIT_STATUS_ARGV);
			break;
		}
	}

#ifdef INSPIRCD_ENABLE_TESTSUITE
	if (do_testsuite)
		do_nofork = do_debug = true;
#endif

	if (do_version)
	{
		std::cout << std::endl << INSPIRCD_VERSION << std::endl;
		Exit(EXIT_STATUS_NOERROR);
	}

#ifdef _WIN32
	// Set up winsock
	WSADATA wsadata;
	WSAStartup(MAKEWORD(2,2), &wsadata);
#endif

	/* Set the finished argument values */
	Config->cmdline.nofork = (do_nofork != 0);
	Config->cmdline.forcedebug = (do_debug != 0);
	Config->cmdline.writelog = !do_nolog;
	Config->cmdline.writepid = !do_nopid;

	if (do_debug)
	{
		FileWriter* fw = new FileWriter(stdout, 1);
		FileLogStream* fls = new FileLogStream(LOG_RAWIO, fw);
		Logs.AddLogTypes("*", fls, true);
	}

	if (!FileSystem::FileExists(ConfigFileName))
	{
#ifdef _WIN32
		/* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
		std::string txtconf = this->ConfigFileName;
		txtconf.append(".txt");

		if (FileSystem::FileExists(txtconf))
		{
			ConfigFileName = txtconf;
		}
		else
#endif
		{
			std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
			this->Logs.Log("STARTUP", LOG_DEFAULT, "Unable to open config file %s", ConfigFileName.c_str());
			Exit(EXIT_STATUS_CONFIG);
		}
	}

	std::cout << con_green << "InspIRCd - Internet Relay Chat Daemon" << con_reset << std::endl;
	std::cout << "For contributors & authors: " << con_green << "See /INFO Output" << con_reset << std::endl;

#ifndef _WIN32
	if (!do_root)
		this->CheckRoot();
	else
	{
		std::cout << "* WARNING * WARNING * WARNING * WARNING * WARNING *" << std::endl
		<< "YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED" << std::endl
		<< "AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED" << std::endl
		<< "OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR" << std::endl
		<< "SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN" << std::endl
		<< "TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART" << std::endl
		<< "THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!" << std::endl << std::endl
		<< "InspIRCd starting in 20 seconds, ctrl+c to abort..." << std::endl;
		sleep(20);
	}
#endif

	this->SetSignals();

	if (!Config->cmdline.nofork)
	{
		if (!this->DaemonSeed())
		{
			std::cout << "ERROR: could not go into daemon mode. Shutting down." << std::endl;
			Logs.Log("STARTUP", LOG_DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
			Exit(EXIT_STATUS_FORK);
		}
	}

	SocketEngine::RecoverFromFork();

	/* During startup we read the configuration now, not in
	 * a seperate thread
	 */
	this->Config->Read();
	this->Config->Apply(NULL, "");
	Logs.OpenFileLogs();

	// If we don't have a SID, generate one based on the server name and the server description
	if (Config->sid.empty())
		Config->sid = UIDGenerator::GenerateSID(Config->ServerName, Config->ServerDesc);

	// Initialize the UID generator with our sid
	this->UIDGen.init(Config->sid);

	// Create the server user for this server
	this->FakeClient = new FakeUser(Config->sid, Config->ServerName, Config->ServerDesc);

	// This is needed as all new XLines are marked pending until ApplyLines() is called
	this->XLines->ApplyLines();

	int bounditems = BindPorts(pl);

	std::cout << std::endl;

	this->Modules.LoadAll();

	// Build ISupport as ModuleManager::LoadAll() does not do it
	this->ISupport.Build();

	if (!pl.empty())
	{
		std::cout << std::endl << "WARNING: Not all your client ports could be bound -- " << std::endl << "starting anyway with " << bounditems
			<< " of " << bounditems + (int)pl.size() << " client ports bound." << std::endl << std::endl;
		std::cout << "The following port(s) failed to bind:" << std::endl << std::endl;
		int j = 1;
		for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
		{
			std::cout << j << ".\tAddress: " << i->first.str() << " \tReason: " << strerror(i->second) << std::endl;
		}

		std::cout << std::endl << "Hint: Try using a public IP instead of blank or *" << std::endl;
	}

	std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SocketEngine::GetMaxFds() << " max open sockets" << std::endl;

#ifndef _WIN32
	if (!Config->cmdline.nofork)
	{
		if (kill(getppid(), SIGTERM) == -1)
		{
			std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
			Logs.Log("STARTUP", LOG_DEFAULT, "Error killing parent process: %s",strerror(errno));
		}
	}

	/* Explicitly shut down stdio's stdin/stdout/stderr.
	 *
	 * The previous logic here was to only do this if stdio was connected to a controlling
	 * terminal.  However, we must do this always to avoid information leaks and other
	 * problems related to stdio.
	 *
	 * The only exception is if we are in debug mode.
	 *
	 *    -- nenolod
	 */
	if ((!do_nofork) && (!Config->cmdline.forcedebug))
	{
		int fd = open("/dev/null", O_RDWR);

		fclose(stdin);
		fclose(stderr);
		fclose(stdout);

		if (dup2(fd, STDIN_FILENO) < 0)
			Logs.Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdin.");
		if (dup2(fd, STDOUT_FILENO) < 0)
			Logs.Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdout.");
		if (dup2(fd, STDERR_FILENO) < 0)
			Logs.Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stderr.");
		close(fd);
	}
	else
	{
		Logs.Log("STARTUP", LOG_DEFAULT, "Keeping pseudo-tty open as we are running in the foreground.");
	}
#else
	/* Set win32 service as running, if we are running as a service */
	SetServiceRunning();

	// Handle forking
	if(!do_nofork)
	{
		FreeConsole();
	}

	QueryPerformanceFrequency(&stats.QPFrequency);
#endif

	Logs.Log("STARTUP", LOG_DEFAULT, "Startup complete as '%s'[%s], %lu max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SocketEngine::GetMaxFds());

#ifndef _WIN32
	ConfigTag* security = Config->ConfValue("security");

	const std::string SetGroup = security->getString("runasgroup");
	if (!SetGroup.empty())
	{
		errno = 0;
		if (setgroups(0, NULL) == -1)
		{
			this->Logs.Log("STARTUP", LOG_DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
			exit(EXIT_STATUS_CONFIG);
		}

		struct group* g = getgrnam(SetGroup.c_str());
		if (!g)
		{
			this->Logs.Log("STARTUP", LOG_DEFAULT, "getgrnam(%s) failed (wrong group?): %s", SetGroup.c_str(), strerror(errno));
			exit(EXIT_STATUS_CONFIG);
		}

		if (setgid(g->gr_gid) == -1)
		{
			this->Logs.Log("STARTUP", LOG_DEFAULT, "setgid(%d) failed (wrong group?): %s", g->gr_gid, strerror(errno));
			exit(EXIT_STATUS_CONFIG);
		}
	}

	const std::string SetUser = security->getString("runasuser");
	if (!SetUser.empty())
	{
		errno = 0;
		struct passwd* u = getpwnam(SetUser.c_str());
		if (!u)
		{
			this->Logs.Log("STARTUP", LOG_DEFAULT, "getpwnam(%s) failed (wrong user?): %s", SetUser.c_str(), strerror(errno));
			exit(EXIT_STATUS_CONFIG);
		}

		if (setuid(u->pw_uid) == -1)
		{
			this->Logs.Log("STARTUP", LOG_DEFAULT, "setuid(%d) failed (wrong user?): %s", u->pw_uid, strerror(errno));
			exit(EXIT_STATUS_CONFIG);
		}
	}

	this->WritePID(Config->PID);
#endif
}
Exemplo n.º 3
0
int find_file_helper(char *includepath, char *origin, char *includefolder, char *actualpath, char *cwd) {
    /*
     * Finds the file referenced in includepath in the includefolder. origin
     * describes the file in which the include is used (used for relative
     * includes). actualpath holds the return pointer. The 4th arg is used for
     * recursion on Windows and should be passed as NULL initially.
     *
     * Returns 0 on success, 1 on error and 2 if no file could be found.
     *
     * Please note that relative includes always return a path, even if that
     * file does not exist.
     */

    // relative include, this shit is easy
    if (includepath[0] != '\\') {
        strncpy(actualpath, origin, 2048);
        char *target = actualpath + strlen(actualpath) - 1;
        while (*target != PATHSEP)
            target--;
        strncpy(target + 1, includepath, 2046 - (target - actualpath));

#ifndef _WIN32
        int i;
        for (i = 0; i < strlen(actualpath); i++) {
            if (actualpath[i] == '\\')
                actualpath[i] = '/';
        }
#endif

        return 0;
    }

    char filename[2048];
    char *ptr = includepath + strlen(includepath);

    while (*ptr != '\\')
        ptr--;
    ptr++;

    strncpy(filename, ptr, 2048);

#ifdef _WIN32
    if (cwd == NULL)
        return find_file_helper(includepath, origin, includefolder, actualpath, includefolder);

    WIN32_FIND_DATA file;
    HANDLE handle = NULL;
    char mask[2048];

    GetFullPathName(includefolder, 2048, includefolder, NULL);

    GetFullPathName(cwd, 2048, mask, NULL);
    sprintf(mask, "%s\\*", mask);

    handle = FindFirstFile(mask, &file);
    if (handle == INVALID_HANDLE_VALUE)
        return 1;

    do {
        if (strcmp(file.cFileName, ".") == 0 || strcmp(file.cFileName, "..") == 0)
            continue;

        GetFullPathName(cwd, 2048, mask, NULL);
        sprintf(mask, "%s\\%s", mask, file.cFileName);
        if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
            if (!find_file_helper(includepath, origin, includefolder, actualpath, mask))
                return 0;
        } else {
            if (strcmp(filename, file.cFileName) == 0 && matches_includepath(mask, includepath, includefolder)) {
                strncpy(actualpath, mask, 2048);
                return 0;
            }
        }
    } while (FindNextFile(handle, &file));

    FindClose(handle);
#else
    FTS *tree;
    FTSENT *f;
    char *argv[] = { includefolder, NULL };

    tree = fts_open(argv, FTS_LOGICAL | FTS_NOSTAT, NULL);
    if (tree == NULL)
        return 1;

    while ((f = fts_read(tree))) {
        switch (f->fts_info) {
            case FTS_DNR:
            case FTS_ERR:
                fts_close(tree);
                return 2;
            case FTS_NS: continue;
            case FTS_DP: continue;
            case FTS_D: continue;
            case FTS_DC: continue;
        }

        if (strcmp(filename, f->fts_name) == 0 && matches_includepath(f->fts_path, includepath, includefolder)) {
            strncpy(actualpath, f->fts_path, 2048);
            fts_close(tree);
            return 0;
        }
    }

    fts_close(tree);
#endif

    // check for file without pboprefix
    strncpy(filename, includefolder, sizeof(filename));
    strncat(filename, includepath, sizeof(filename) - strlen(filename) - 1);
#ifndef _WIN32
    int i;
    for (i = 0; i < strlen(filename); i++) {
        if (filename[i] == '\\')
            filename[i] = '/';
    }
#endif
    if (access(filename, F_OK) != -1) {
        strcpy(actualpath, filename);
        return 0;
    }

    return 2;
}
Exemplo n.º 4
0
int _tmain(int argc, WCHAR* argv[])
{
	printf("PROJECT: Capture-HPC\n");
    printf("VERSION: 3.0\n");
    printf("DATE: October 19, 2009\n");
    printf("COPYRIGHT HOLDER: Victoria University of Wellington, NZ\n");
    printf("AUTHORS:\n");
    printf("\tChristian Seifert ([email protected])\n");
    printf("\tRamon Steenson([email protected])\n");
	printf("\tVan Lam Le ([email protected])\n");
	printf("\n");
    printf("Capture-HPC is free software; you can redistribute it and/or modify\n");
    printf("it under the terms of the GNU General Public License, V2 as published by\n");
    printf("the Free Software Foundation.\n");
    printf("\n");
    printf("Capture-HPC is distributed in the hope that it will be useful,\n");
    printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
    printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
    printf("GNU General Public License for more details.\n");
    printf("\n");
    printf("You should have received a copy of the GNU General Public License\n");
    printf("along with Capture-HPC; if not, write to the Free Software\n");
    printf("Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301,USA\n\n");

	/* Set the current directory to the where the CaptureClient.exe is found */
	/* This is a bug fix for the VIX library as the runProgramInGuest function
	   opens the client from within c:\windows\system32 so nothing will load
	   properly during execution */
	wchar_t* szFullPath = new wchar_t[4096];
	GetFullPathName(argv[0], 4096, szFullPath, NULL);
	std::wstring dir = szFullPath;
	dir = dir.substr(0, dir.find_last_of(L"\\")+1);
	SetCurrentDirectory(dir.c_str());
	GetCurrentDirectory(4096, szFullPath);

	LOG(INFO, "Capture: current directroy set - %ls", szFullPath);
	
	/* Delete the log directory */
	
	GetFullPathName(L"logs", 4096, szFullPath, NULL);
	SHFILEOPSTRUCT deleteLogDirectory;
	deleteLogDirectory.hwnd = NULL;
	deleteLogDirectory.pTo = NULL;
	deleteLogDirectory.lpszProgressTitle = NULL;
	deleteLogDirectory.wFunc = FO_DELETE;
	deleteLogDirectory.pFrom = szFullPath;
	deleteLogDirectory.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI;
	SHFileOperation(&deleteLogDirectory);

	delete [] szFullPath;
	
	//allows to do some custom testing
	if(argc>1) {
		std::wstring option = argv[1];
		if(option == L"-t") {
			PluginTest* test = new PluginTest();
			test->loadTest();
			exit(0);
		}
	}

	std::wstring serverIp = L"";
	std::wstring serverPort = L"7070";
	std::wstring vmServerId = L"";
	std::wstring vmId = L"";
	std::wstring logSystemEventsFile = L"";
	std::wstring collectModifiedFiles = L"false";
	std::wstring captureNetworkPackets = L"false";

	for(int i = 1; i < argc; i++)
	{
		std::wstring option = argv[i];
		if(option == L"--help" || option == L"-h") {
			printf("\nCapture client is a high interaction client honeypot which using event monitoring can monitor the state of the system it is being run on. ");
			printf("Capture can monitor processes, files, and the registry at the moment and classifies an event as being malicious by checking exclusion lists. ");
			printf("\nThese exclusion lists are regular expressions which can either allow or deny a particular event from a process in the system. Because of the fact ");
			printf("that it uses regular expressions, creating these list can be very simple but can also provide very fine grained exclusion if needed.\nThe client ");
			printf("can also copy all modified and deleted files to a temporary directory as well as capture all incoming and outgoing packets on the network adapters ");
			printf("on the system.\nThe client can be run in the following two modes:\n");
			printf("\n\nClient<->Server\n\n");
			printf("The client connects to a central Capture server where the client can be sent urls to visit. These urls can contain other information which tell ");
			printf("the client which program to use, for example www.google.com could be visited with either Internet Explorer or Mozilla Firefox and how long to visit the ");
			printf("url. While the url is being visited the state of the system is monitored and if anything malicious occurs during the visitation period the event ");
			printf("is passed back to the server. In this mode the client is run inside of a virtual machine so that when a malicious event occurs the server can revert ");
			printf("the virtual machine to a clean state\n\n");
			printf("To use this mode the options -s, -a, -b must be set so the client knows how to connect and authenticate with the server. To configure the ");
			printf("programs that are available to visit a url edit the clients.conf file. If -cn are set then the log directory will be sent to the server once ");
			printf("a malicious url is visited. For this to work tar.exe and gzip.exe must be included in the Capture Client folder.\n");
			printf("\n\nStandalone\n\n");
			printf("In this mode the client runs in the background of a system and monitors the state of it. Rather than being controlled by a remote server, in standalone mode ");
			printf("the user has control over the system. Malicious events can either be stored in a file or outputted to stdout.");
			printf("\n\nUsage: CaptureClient.exe [-chn] [-s server address -a vm server id -b vm id] [-l file]\n");
			printf("\n  -h\t\tPrint this help message");
			printf("\n  -s address\tAddress of the server the client connects up to. NOTE -a & -b\n\t\tmust be defined when using this option");
			printf("\n  -p port\tPort the server user the client connects up to. NOTE -a & -b\n\t\tmust be defined when using this option");
			printf("\n  -a server id\tUnique id of the virtual machine server that hosts the client");
			printf("\n  -b vm id\tUnique id of the virtual machine that this client is run on");
			printf("\n  -l file\tOutput system events to a file rather than stdout\n");
			printf("\n  -c\t\tCopy files into the log directory when they are modified or\n\t\tdeleted");
			printf("\n  -n\t\tCapture all incoming and outgoing network packets from the\n\t\tnetwork adapters on the system and store them in .pcap files in\n\t\tthe log directory");
			printf("\n\nIf -s is not set the client will operate in standalone mode");
			exit(1);
		} else if(option == L"-s") {
			if((i+1 < argc) && (argv[i+1][0] != '-')) {
				serverIp = argv[++i];
				LOG(INFO, "Capture: Connect to server ip: %ls", serverIp.c_str());
			}
		} else if(option == L"-p") {
			if((i+1 < argc) && (argv[i+1][0] != '-')) {
				serverPort = argv[++i];
				LOG(INFO, "Capture: Connect to server port: %ls", serverPort.c_str());
			}
		} else if(option == L"-a") {
			if((i+1 < argc) && (argv[i+1][0] != '-')) {
				vmServerId = argv[++i];
			}
		} else if(option == L"-b") {
			if((i+1 < argc) && (argv[i+1][0] != '-')) {
				vmId = argv[++i];
			}
		} else if(option == L"-l") {
			if((i+1 < argc) && (argv[i+1][0] != '-')) {			
				logSystemEventsFile = argv[++i];
				LOG(INFO, "Capture: Logging system events to %ls", logSystemEventsFile.c_str());
			}
		} else {
			if(argv[i][0] == '-')
			{
				for(UINT k = 1; k < option.length(); k++)
				{
					if(argv[i][k] == 'c') {
						LOG(INFO, "Capture: Collecting modified files");
						collectModifiedFiles = L"true";
					} else if(argv[i][k] == 'n') {
						HMODULE hModWinPcap = LoadLibrary(L"wpcap.dll");
						if(hModWinPcap == NULL)
						{
							LOG(ERR, "Capture: wpcap.dll not found. Check that winpcap is installed on this system\nCannot use -n option if winpcap is not installed ... exiting");
							exit(1);
						} else {
							LOG(INFO, "Capture: Capturing network packets");
							captureNetworkPackets = L"true";
							FreeLibrary(hModWinPcap);
						}
					}
				}
			}
		}
	}

	OptionsManager::getInstance()->addOption(L"server", serverIp);
	OptionsManager::getInstance()->addOption(L"port", serverPort);
	OptionsManager::getInstance()->addOption(L"vm-server-id", vmServerId);
	OptionsManager::getInstance()->addOption(L"vm-id", vmId);
	OptionsManager::getInstance()->addOption(L"log-system-events-file", logSystemEventsFile);
	OptionsManager::getInstance()->addOption(L"collect-modified-files", collectModifiedFiles);
	OptionsManager::getInstance()->addOption(L"capture-network-packets", captureNetworkPackets);
	OptionsManager::getInstance()->addOption(L"capture-network-packets-malicious", L"false");
	OptionsManager::getInstance()->addOption(L"capture-network-packets-benign", L"false");

	if(collectModifiedFiles == L"true")
	{
		if(serverIp != L"")
		{
			WIN32_FIND_DATA FindFileData;
			HANDLE hFind;

			hFind = FindFirstFile(L"7za.exe",&FindFileData);
			if(hFind == INVALID_HANDLE_VALUE)
			{
				LOG(ERR, "Could not find 7za.exe - Not collecting modified files\nCannot use -c option if 7za.exe is not in the current directory ... exiting");
				exit(1);
			}
		}
	}

	CaptureClient* cp = new CaptureClient();
	WaitForSingleObject(cp->hStopRunning, INFINITE);
	delete cp;
	return 0;
}
Exemplo n.º 5
0
BOOL InstallFile(char *szSource, char *szDestFormat, ...) {
	char szDest[MAX_PATH];
	char szDestPath[MAX_PATH];
	char szDestFile[MAX_PATH];
	char *lpszDestFile;
	char szCurInst[MAX_PATH];
	char szTempFile[MAX_PATH];
	DWORD dwFlags = VIFF_DONTDELETEOLD;
	DWORD dwRet;
	UINT uTmpLen;
	char szFailure[256];
	va_list val;

	va_start(val, szDestFormat);
	vsprintf(szDest, szDestFormat, val);
	va_end(val);

	if (!GetFullPathName(szDest, sizeof szDestPath, szDestPath, &lpszDestFile))
		return FALSE;

	strcpy(szDestFile, lpszDestFile);
	*lpszDestFile=0;

	do {
		szTempFile[0]=0;
		szCurInst[0]=0;
		uTmpLen = sizeof szTempFile;
		dwRet = VerInstallFile(dwFlags, szSource, szDestFile, g_szProgPath, szDestPath, szCurInst, szTempFile, &uTmpLen);

		if (dwRet & VIF_TEMPFILE) {
			DeleteFile(szTempFile);
			dwRet &= ~VIF_TEMPFILE;
		}

		szFailure[0]=0;

		if (dwRet & (VIF_MISMATCH | VIF_DIFFTYPE))
			sprintf(szFailure,	"The old %s doesn't look like a VirtualDub file.\n"
								"If it belongs to another application, installing the new file may cause "
								"the other app to stop functioning.\n"
								"Install the new file only if you are sure or have a backup."
								,szDestFile);
		else if (dwRet & VIF_SRCOLD)
			sprintf(szFailure,	"%s is older than the %s being installed over.\n"
								"You should install the older %s if you do not use other versions "
								"of VirtualDub, since the newer file may be incompatible."
								,szSource,szDestFile,szSource);
		else if (dwRet & VIF_WRITEPROT)
			sprintf(szFailure,	"The %s being installed over has been marked read-only.\n"
								"Override read-only attribute and install anyway?"
								,szDestFile);
		else if (dwRet & VIF_FILEINUSE)
			sprintf(szFailure,	"%s is in use.  It cannot be installed over right now.\n"
								"If you have any copies of VirtualDub or any programs that "
								"may be using VirtualDub's AVIFile handler, please close them "
								"and then click OK to retry the operation."
								,szDestFile);
		else if (dwRet & VIF_OUTOFSPACE)
			sprintf(szFailure,	"Doh! We're out of space trying to write:\n\t%s\n\nCan you clear some up?"
								,szDest);
		else if (dwRet & VIF_ACCESSVIOLATION)
			sprintf(szFailure,	"Access violation.  Check with your administrator to see if you have "
								"the appropriate permissions to write to \"%s\"."
								,szDest);
		else if (dwRet & VIF_SHARINGVIOLATION)
			sprintf(szFailure,	"Share violation; something else probably has %s open.  Try closing applications that "
								"have the file open, and check permissions on network drives."
								,szDestFile);
		else if (dwRet & VIF_CANNOTCREATE)
			sprintf(szFailure,	"Couldn't create temporary file %s.\nTry again?", szTempFile);
		else if (dwRet & VIF_CANNOTDELETE)
			sprintf(szFailure,	"Couldn't delete temporary file %s.\nTry installing again?", szTempFile);
		else if (dwRet & VIF_CANNOTDELETECUR)
			sprintf(szFailure,	"Couldn't delete existing file \"%s\".\nTry installing again?", szDest);
		else if (dwRet & VIF_CANNOTRENAME)
			sprintf(szFailure,	"Deleted old file %s, but couldn't move %s into its place.\n"
								"You should retry this operation.", szDestFile, szSource);
		else if (dwRet & VIF_CANNOTREADSRC)
			sprintf(szFailure,	"Couldn't read source file \"%s\".  Should I try again?"
								,szSource);
		else if (dwRet & VIF_CANNOTREADDST)
			sprintf(szFailure,	"Couldn't read destination file \"%s\".  I can try installing over it "
								"anyway, though."
								,szDest);
		else if (dwRet & VIF_OUTOFMEMORY)
			sprintf(szFailure,	"Ran out of memory!  Try freeing some up.");
		else if (dwRet)
			sprintf(szFailure,	"Unidentified error copying:\n\t%s\n\t\tto\n\t%s\n\nTry forcing install?"
								,szSource
								,szDest);

		if (szFailure[0])
			if (IDNO==MessageBox(NULL, szFailure, "Install error", MB_YESNO | MB_APPLMODAL))
				return FALSE;

		dwFlags |= VIFF_FORCEINSTALL;
	} while(dwRet);

	return TRUE;
}
Exemplo n.º 6
0
int Bcorrectfilename(char *filename, int removefn)
{
#ifdef _WIN32
	int r, trailslash=0;
#endif
	char path[256]="", fn[64]="", scratch[256], *ptr, *ptr2, ch;
	char cwd[256], *cwdp = cwd;
	char *tokarr[64];
	int ntok=0, i, j;

	int grpmode = 0;
	
	if (!Bstrncasecmp(filename,"GRP:",4)) {
		grpmode = 1;
		for (ptr=filename; *ptr; ptr++) if (*ptr == '\\') *ptr = '/';
	}
#ifdef _WIN32
	if (!grpmode) {
		// Windows uses backslashes so translate all unix-like forwardslashes
		for (ptr=filename; *ptr; ptr++) if (*ptr == '/') *ptr = '\\';
		if (*(ptr-1) == '\\') trailslash = 1;

		r = GetFullPathName(filename, 256, path, &ptr);
		if (r > 256) return -1;
		if (r == 0) return -1;
		if (!trailslash && removefn && ptr) *ptr=0;
		if (trailslash) {
			if (path[ strlen(path) - 1 ] != '\\')
				strcat(path, "\\");
		}

		for (ptr=path; *ptr; ptr++) if (*ptr == '\\') *ptr = '/';
	
		strcpy(filename,path);
	} else {
#endif
	
#ifndef _WIN32
		if (!grpmode) {
			Bgetcwd(cwd, 256);
			Bstrcat(cwd, "/");
		} else {
#endif
		cwd[0] = '/';
		cwd[1] = 0;
#ifndef _WIN32
		}
#endif

		ptr2 = filename;
		if (grpmode) {
			ptr2 += 3;
			if (ptr2[1] != '/')
				*ptr2 = '/';
			else ptr2++;
		}

		if (removefn) {
			ptr = Bstrrchr(ptr2, '/');
			if (ptr) ptr[1] = 0;
			else if (!grpmode) ptr2[0] = 0;
		}

		// now we have all the bits and pieces, clean it all up
		scratch[0] = 0;

		if (ptr2[0] != '/') {
			// relative path, which means prepend the current dir to the path
			Bstrcat(scratch, cwdp);
		}

		Bstrcat(scratch, ptr2);

		ptr2 = scratch;
		while ((ptr = Bstrtoken(ptr2==scratch?scratch:NULL,"/",&ptr2,1)) != NULL) {
			if (!Bstrcmp(ptr,".")) continue;
			else if (!Bstrcmp(ptr,"..")) {
				if (ntok>0) ntok--;
			} else {
				tokarr[ntok++] = ptr;
			}
		}

		ptr2 = filename;
		if (grpmode) {
			Bstrcpy(filename,"GRP:");
			ptr2 += 4;
		} else filename[0] = 0;
		*(ptr2++) = '/';
		for (i=0; i<ntok; i++) {
			ptr = tokarr[i];
			if (i>0) *(ptr2++) = '/';
			while (*ptr) *(ptr2++) = *(ptr++);
		}
		if (removefn) if (*(ptr2-1) != '/') *(ptr2++) = '/';
		*(ptr2) = 0;

#ifdef _WIN32
	}
#endif

	return 0;
}
Exemplo n.º 7
0
extern "C" int __stdcall WinMain(HINSTANCE hInst, HINSTANCE hPrevInst , __in LPSTR lpszCmdLine, int nCmdShow)
{

//-----------------------------------------------------------------------------------------------------------------
//  VARIABLES
//
//-----------------------------------------------------------------------------------------------------------------
    UINT    uiRet = ERROR_SUCCESS;
    HRESULT hr    = S_OK;

    char *szMsiFile          = 0;
    char *szBaseURL          = 0;
    char *szInstallPath      = 0;
    char *szMsiCacheFile     = 0;
    char *szOperation        = 0;
    char *szProductName      = 0;
    char *szMinimumMsi       = 0;
    char *szProperties       = 0;
    char *szInstProperties   = 0;
    char *szTempPath         = 0;
    char *szFilePart         = 0;
    char *szBase             = 0;
    char *szUpdate           = 0;

    char *szRegisteredMsiFolder = 0;
    char *szMsiDllLocation      = 0;

    char szAppTitle[MAX_STR_CAPTION]    = {0};
    char szError[MAX_STR_LENGTH]        = {0};
    char szText[MAX_STR_CAPTION]        = {0};
    char szBanner[MAX_STR_LENGTH]       = {0};
    char szAction[MAX_STR_LENGTH]       = {0};
    char szUserPrompt[MAX_STR_LENGTH]   = {0};
    char szProductCode[MAX_LENGTH_GUID] = {0};

    char szModuleFile[MAX_PATH]         = {0};
    DWORD dwModuleFileSize       = MAX_PATH;
    
    DWORD dwMsiFileSize          = 0;
    DWORD dwBaseURLSize          = 0;
    DWORD cchInstallPath         = 0;
    DWORD dwMsiCacheFileSize     = 0;
    DWORD dwOperationSize        = 0;
    DWORD dwProductNameSize      = 0;
    DWORD dwMinimumMsiSize       = 0;
    DWORD dwPropertiesSize       = 0;
    DWORD cchInstProperties      = 0;
    DWORD cchTempPath            = 0;
    DWORD dwLastError            = 0;
    DWORD cchReturn              = 0;
    DWORD dwBaseUpdateSize      = 0;
    DWORD dwUpdateSize          = 0;
    DWORD dwResult               = 0;
    DWORD dwType                 = 0;
    DWORD dwProductCodeSize      = MAX_LENGTH_GUID;

    DWORD dwRegisteredMsiFolderSize  = 0;
    DWORD dwMsiDllLocationSize       = 0;

    ULONG ulMsiMinVer        = 0;
    char *szStopScan         = NULL;

    bool        fDelayRebootReq    = false;
    bool        fPatch             = false;
    bool        fQFE               = false;
    bool        fOSSupported       = false;
    emEnum      emExecMode         = emPreset;

    HKEY hInstallerKey = 0;

    HMODULE hMsi = 0;
    PFnMsiSetInternalUI pfnMsiSetInternalUI = 0;
    PFnMsiInstallProduct pfnMsiInstallProduct = 0;
    PFnMsiApplyPatch pfnMsiApplyPatch = 0;
    PFnMsiReinstallProduct pfnMsiReinstallProduct = 0;
    PFnMsiQueryProductState pfnMsiQueryProductState = 0;
    PFnMsiOpenDatabase pfnMsiOpenDatabase = 0;
    PFnMsiDatabaseOpenView pfnMsiDatabaseOpenView = 0;
    PFnMsiViewExecute pfnMsiViewExecute = 0;
    PFnMsiViewFetch pfnMsiViewFetch = 0;
    PFnMsiRecordGetString pfnMsiRecordGetString = 0;
    PFnMsiCloseHandle pfnMsiCloseHandle = 0;

    MSIHANDLE hDatabase = 0;
    MSIHANDLE hView = 0;
    MSIHANDLE hRec = 0;

    INSTALLSTATE isProduct = INSTALLSTATE_UNKNOWN;
    
    const char * szAdminImagePath = 0;



//-----------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------
    // create our UI object
    CDownloadUI DownloadUI;

    // Load our AppTitle (caption)
    WIN::LoadString(hInst, IDS_APP_TITLE, szAppTitle, sizeof(szAppTitle)/sizeof(char));

    // Obtain path we are running from
    if (0 == WIN::GetModuleFileName(hInst, szModuleFile, dwModuleFileSize))
    {
        // No UI displayed. Silent failure.
        uiRet = GetLastError();
        goto CleanUp;
    }
    DebugMsg("[Info] we are running from --> %s\n", szModuleFile);

    // Figure out what we want to do
    emExecMode = GetExecutionMode (lpszCmdLine);
    
    if (emVerify == emExecMode)
    {
        //
        // We don't want any UI to be displayed in this case. The return value
        // from the exe is the result of the verification. Therefore, this
        // should be done before initializing the UI.
        //
        uiRet = VerifyFileSignature (szModuleFile, lpszCmdLine);
        if (ERROR_BAD_ARGUMENTS != uiRet)
            goto CleanUp;
    }
    
    if (ERROR_BAD_ARGUMENTS == uiRet || emHelp == emExecMode)
    {
        DisplayUsage(hInst, NULL, szAppTitle);
        goto CleanUp;
    }
    
    //
    // NOTE:
    // Delay handling admin. installs until we have determined if we are
    // patching an existing install or if we are doing a default install.
    //
 
    // initialize our UI object with desktop as parent
    DownloadUI.Initialize(hInst, /* hwndParent = */ 0, szAppTitle);

    // Check if we are installing on an OS that supports Windows Installer 3.0
    fOSSupported = IsOSSupported();
    if(!fOSSupported)
    {
        PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_OS_NOT_SUPPORTED);
        uiRet = ERROR_INSTALL_FAILURE;
        goto CleanUp;
    }
    HANDLE hMutex = 0;

    // only run one instance at a time
    if (AlreadyInProgress(hMutex))
    {
        // silently return - correct return code ?
		uiRet = ERROR_INSTALL_ALREADY_RUNNING;
		goto CleanUp;
    }
    
    // determine operation, default (if not present) is INSTALL
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_OPERATION, &szOperation, dwOperationSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    if (ERROR_SUCCESS != uiRet)
    {
        // set operation to default which is install
        if (szOperation)
            delete [] szOperation;
        szOperation = new char[lstrlen(szDefaultOperation) + 1];
        if (!szOperation)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        if (FAILED(StringCchCopy(szOperation, lstrlen(szDefaultOperation) + 1, szDefaultOperation)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }
    }

    // obtain name of product
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PRODUCTNAME, &szProductName, dwProductNameSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    if (ERROR_SUCCESS != uiRet)
    {
        // use default
        if (szProductName)
            delete [] szProductName;
        szProductName = new char[MAX_STR_CAPTION];
        if (!szProductName)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        WIN::LoadString(hInst, IDS_DEFAULT_PRODUCT, szProductName, MAX_STR_CAPTION);
    }

    // set banner text
    WIN::LoadString(hInst, IDS_BANNER_TEXT, szText, MAX_STR_CAPTION);
    StringCchPrintf(szBanner, sizeof(szBanner), szText, szProductName);
    if (irmCancel == DownloadUI.SetBannerText(szBanner))
    {
        ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        uiRet = ERROR_INSTALL_USEREXIT;
        goto CleanUp;
    }

    // Determine if this is a patch or a normal install.
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_DATABASE, &szMsiFile, dwMsiFileSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    else if (ERROR_SUCCESS != uiRet)
    {
        // look for patch
        if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PATCH, &szMsiFile, dwMsiFileSize)))
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        else if (ERROR_SUCCESS != uiRet)
        {
            PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_DATABASE);
            goto CleanUp;
        }

        fPatch = true;
    }
    
    //
    // If we are here, this is either an admin. install or a default install.
    // File signature verification, help and other invalid parameters have
    // already been taken care of above.
    //
    if (emAdminInstall == emExecMode)
    {
        uiRet = GetAdminInstallInfo (fPatch, lpszCmdLine, &szAdminImagePath);
        if (ERROR_BAD_ARGUMENTS == uiRet)
        {
            DisplayUsage(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
    }
    
    //
    // At this point, the validation of the commandline arguments is complete
    // and we have all the information we need.
    //

    // obtain minimum required MSI version
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_MINIMUM_MSI, &szMinimumMsi, dwMinimumMsiSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    else if (ERROR_SUCCESS != uiRet)
    {
        PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_MINIMUM_MSI);
        goto CleanUp;
    }

    // make sure required Msi version is a valid value -- must be >= 150
    ulMsiMinVer = strtoul(szMinimumMsi, &szStopScan, 10);
    if (!szStopScan || (szStopScan == szMinimumMsi) || (*szStopScan != 0) || ulMsiMinVer < MINIMUM_SUPPORTED_MSI_VERSION)
    {
        // invalid minimum version string
        PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_VER_STR, szMinimumMsi, MINIMUM_SUPPORTED_MSI_VERSION);
        uiRet = ERROR_INVALID_PARAMETER;
        goto CleanUp;
    }

    DebugMsg("[Resource] Minimum Msi Value = %d\n", ulMsiMinVer);

    // compare minimum required MSI version to that which is on the machine
    if (IsMsiUpgradeNecessary(ulMsiMinVer))
    {
        DebugMsg("[Info] Upgrade of Windows Installer is requested\n");

        // make sure this is admin -- must have admin priviledges to upgrade Windows Installer
        if (!IsAdmin())
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_REQUIRES_ADMIN_PRIV);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }

        // Ask the user if they want to upgrade the installer
        WIN::LoadString(hInst, IDS_ALLOW_MSI_UPDATE, szUserPrompt, MAX_STR_LENGTH);
        if (IDYES != WIN::MessageBox(DownloadUI.GetCurrentWindow(), szUserPrompt, szAppTitle, MB_YESNO|MB_ICONQUESTION))
        {
            // user decided to cancel
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }

        if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_UPDATE, &szUpdate, dwUpdateSize)))
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        else if (ERROR_SUCCESS != uiRet)
        {
            PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_UPDATE);
            goto CleanUp;
        }            
        
        // determine if we need to download the Windows Installer update package from the web -- based on presence of UPDATELOCATION property
        if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_UPDATELOCATION, &szBase, dwBaseUpdateSize)))
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        else if (ERROR_SUCCESS == uiRet)
        {
            // presence of UPDATELOCATION property indicates assumption of URL source
            if (ERROR_SUCCESS != (uiRet = DownloadAndUpgradeMsi(hInst, &DownloadUI, szAppTitle, szBase, szUpdate, szModuleFile, ulMsiMinVer)))
            {
                if (ERROR_SUCCESS_REBOOT_REQUIRED == uiRet)
                {
                    // successful, but must reboot at end
                    fDelayRebootReq = true;
                }
                else
                    goto CleanUp;
            }
        }
        else
        {
            // lack of UPDATELOCATION property indicates assumption of Media source
            if (ERROR_SUCCESS != (uiRet = UpgradeMsi(hInst, &DownloadUI, szAppTitle, szModuleFile, szUpdate, ulMsiMinVer)))
            {
                if (ERROR_SUCCESS_REBOOT_REQUIRED == uiRet)
                {
                    // successful, but must reboot at end
                    fDelayRebootReq = true;
                }
                else
                    goto CleanUp;
            }
        }
    }

    DebugMsg("[Info] Windows Installer has been upgraded, or was already correct version\n");

    // perform some extra authoring validation
    if (fPatch
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMinPatchOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMajPatchOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1))
    {
        // wrong operation
        DebugMsg("[Error] Operation %s is not valid for a patch\n", szOperation);
        PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_OPERATION, szOperation);
        uiRet = ERROR_INVALID_PARAMETER;
        goto CleanUp;
    }
    else if (!fPatch
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallUpdOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1))
    {
        // wrong operation
        DebugMsg("[Error] Operation %s is not valid for a package\n", szOperation);
        PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_OPERATION, szOperation);
        uiRet = ERROR_INVALID_PARAMETER;
        goto CleanUp;
    }

    // by now we either have a MSI or a MSP
    if (CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMinPatchOperation, -1)
        || CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallUpdOperation, -1)
        || (fPatch && CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1)))
        fQFE = true;

    // obtain base URL
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_BASEURL, &szBaseURL, dwBaseURLSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    else if (ERROR_SUCCESS == uiRet)
    {
        // presence of BASEURL property indicates assumption of URL source . . .

        // generate the path to the installation package == baseURL + msiFile
        //   note: msiFile is a relative path
        cchTempPath = lstrlen(szBaseURL) + lstrlen(szMsiFile) + 2; // 1 for slash, 1 for null
        szTempPath = new char[cchTempPath ];
        if (!szTempPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }
        if (FAILED(StringCchCopy(szTempPath, cchTempPath, szBaseURL)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }
        // check for trailing slash on szBaseURL
        char *pch = szBaseURL + lstrlen(szBaseURL) + 1; // put at null terminator
        pch = CharPrev(szBaseURL, pch);
        if (*pch != '/')
        {
            if (FAILED(StringCchCat(szTempPath, cchTempPath, szUrlPathSep)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }
        if (FAILED(StringCchCat(szTempPath, cchTempPath, szMsiFile)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }        

        // canocialize the URL path
        cchInstallPath = cchTempPath*2;
        szInstallPath = new char[cchInstallPath];
        if (!szInstallPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        dwLastError = 0; // success
        if (!InternetCanonicalizeUrl(szTempPath, szInstallPath, &cchInstallPath, 0))
        {
            dwLastError = GetLastError();
            if (ERROR_INSUFFICIENT_BUFFER == dwLastError)
            {
                // try again
                delete [] szInstallPath;
                szInstallPath = new char[cchInstallPath];
                if (!szInstallPath)
                {
                    ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
                    uiRet = ERROR_OUTOFMEMORY;
                    goto CleanUp;
                }
                dwLastError = 0; // reset to success for 2nd attempt
                if (!InternetCanonicalizeUrl(szTempPath, szInstallPath, &cchInstallPath, 0))
                    dwLastError = GetLastError();
            }
        }
        if (0 != dwLastError)
        {
            // error -- invalid path/Url
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath);
            uiRet = dwLastError;
            goto CleanUp;
        }

        // set action text for download
        WIN::LoadString(hInst, IDS_DOWNLOADING_PACKAGE, szText, MAX_STR_CAPTION);
        StringCchPrintf(szAction, sizeof(szAction), szText, szMsiFile);
        if (irmCancel == DownloadUI.SetActionText(szAction))
        {
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }

        // download the msi file so we can attempt a trust check -- must be local for WinVerifyTrust
        DebugMsg("[Info] Downloading msi file %s for WinVerifyTrust check\n", szInstallPath);

        szMsiCacheFile = new char[MAX_PATH];
        dwMsiCacheFileSize = MAX_PATH;
        if (!szMsiCacheFile)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        hr = WIN::URLDownloadToCacheFile(NULL, szInstallPath, szMsiCacheFile, dwMsiCacheFileSize, 0, /* IBindStatusCallback = */ &CDownloadBindStatusCallback(&DownloadUI));
        if (DownloadUI.HasUserCanceled())
        {
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }
        if (FAILED(hr))
        {
            // error during download -- probably because file not found (or lost connection)
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NOMSI, szInstallPath);
            uiRet = ERROR_FILE_NOT_FOUND;
            goto CleanUp;
        }

        DebugMsg("[Info] Msi file was cached to %s\n", szMsiCacheFile);

        // set action text for trust verification
        WIN::LoadString(hInst, IDS_VALIDATING_SIGNATURE, szText, MAX_STR_CAPTION);
        StringCchPrintf(szAction, sizeof(szAction), szText, szMsiFile);
        if (irmCancel == DownloadUI.SetActionText(szAction))
        {
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }

        // perform trust check 
        itvEnum itv = IsPackageTrusted(szModuleFile, szMsiCacheFile, DownloadUI.GetCurrentWindow());
        if (itvWintrustNotOnMachine == itv)
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NO_WINTRUST);
            uiRet = ERROR_CALL_NOT_IMPLEMENTED;
            goto CleanUp;
        }
        else if (itvUnTrusted == itv)
        {
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_UNTRUSTED, szInstallPath);
            uiRet = HRESULT_CODE(TRUST_E_SUBJECT_NOT_TRUSTED);
            goto CleanUp;
        }
    }
    else
    {
        // lack of BASEURL property indicates assumption of Media source

        // generate the path to the Msi file =  szModuleFile + msiFile
        //   note: msiFile is a relative path
        cchTempPath = lstrlen(szModuleFile) + lstrlen(szMsiFile) + 2; // 1 for null terminator, 1 for back slash
        szTempPath = new char[cchTempPath];
        if (!szTempPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        // find 'setup.exe' in the path so we can remove it
        if (0 == GetFullPathName(szModuleFile, cchTempPath, szTempPath, &szFilePart))
        {
            uiRet = GetLastError();
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath);
            goto CleanUp;
        }
        if (szFilePart)
            *szFilePart = '\0';

        if (FAILED(StringCchCat(szTempPath, cchTempPath, szMsiFile)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }
        
        cchInstallPath = 2*cchTempPath;
        szInstallPath = new char[cchInstallPath];
        if (!szInstallPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        // normalize the path
        cchReturn = GetFullPathName(szTempPath, cchInstallPath, szInstallPath, &szFilePart);
        if (cchReturn > cchInstallPath)
        {
            // try again, with larger buffer
            delete [] szInstallPath;
            cchInstallPath = cchReturn;
            szInstallPath = new char[cchInstallPath];
            if (!szInstallPath)
            {
                ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
                uiRet = ERROR_OUTOFMEMORY;
                goto CleanUp;
            }
            cchReturn = GetFullPathName(szTempPath, cchInstallPath, szInstallPath, &szFilePart);
        }
        if (0 == cchReturn)
        {
            // error -- invalid path
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath);
            uiRet = dwLastError;
            goto CleanUp;
        }

        // no download is necessary -- but we can check for the file's existence
        DWORD dwFileAttrib = GetFileAttributes(szInstallPath);
        if (0xFFFFFFFF == dwFileAttrib)
        {
            // package is missing
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NOMSI, szInstallPath);
            uiRet = ERROR_FILE_NOT_FOUND;
            goto CleanUp;
        }
    }

    //
    // good to go -- terminate our UI and let the Windows Installer take over
    //

    // retrieve the optional command line PROPERTY = VALUE strings if available
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PROPERTIES, &szProperties, dwPropertiesSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        uiRet = ERROR_OUTOFMEMORY;
        goto CleanUp;
    }
    else if (ERROR_SUCCESS != uiRet)
    {
        // PROPERTY=VALUE pairs not specified
        if (szProperties)
            delete [] szProperties;
        szProperties = NULL;
    }

    DownloadUI.Terminate();

    //
    // perform install 
    //

    hMsi = LoadLibrary(MSI_DLL);
    
    if (hMsi)
    {
        pfnMsiSetInternalUI = (PFnMsiSetInternalUI)GetProcAddress(hMsi, MSIAPI_MsiSetInternalUI);
        pfnMsiInstallProduct = (PFnMsiInstallProduct)GetProcAddress(hMsi, MSIAPI_MsiInstallProduct);
        pfnMsiApplyPatch = (PFnMsiApplyPatch)GetProcAddress(hMsi, MSIAPI_MsiApplyPatch);
        pfnMsiReinstallProduct = (PFnMsiReinstallProduct)GetProcAddress(hMsi, MSIAPI_MsiReinstallProduct);
        pfnMsiQueryProductState = (PFnMsiQueryProductState)GetProcAddress(hMsi, MSIAPI_MsiQueryProductState);
        pfnMsiOpenDatabase = (PFnMsiOpenDatabase)GetProcAddress(hMsi, MSIAPI_MsiOpenDatabase);
        pfnMsiDatabaseOpenView = (PFnMsiDatabaseOpenView)GetProcAddress(hMsi, MSIAPI_MsiDatabaseOpenView);
        pfnMsiViewExecute = (PFnMsiViewExecute)GetProcAddress(hMsi, MSIAPI_MsiViewExecute);
        pfnMsiViewFetch = (PFnMsiViewFetch)GetProcAddress(hMsi, MSIAPI_MsiViewFetch);
        pfnMsiRecordGetString = (PFnMsiRecordGetString)GetProcAddress(hMsi, MSIAPI_MsiRecordGetString);
        pfnMsiCloseHandle = (PFnMsiCloseHandle)GetProcAddress(hMsi, MSIAPI_MsiCloseHandle);
    }
    if (!hMsi || !pfnMsiSetInternalUI || !pfnMsiInstallProduct || !pfnMsiApplyPatch || !pfnMsiReinstallProduct || !pfnMsiQueryProductState
        || !pfnMsiDatabaseOpenView || !pfnMsiViewExecute || !pfnMsiViewFetch || !pfnMsiRecordGetString || !pfnMsiCloseHandle)
    {
        PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_FAILED_TO_UPGRADE_MSI);
        uiRet = ERROR_INSTALL_FAILURE;
        goto CleanUp;
    }

    DebugMsg("[Info] Setting Internal UI level to FULL...\n");
    pfnMsiSetInternalUI(INSTALLUILEVEL_FULL, 0);

    if (!fPatch)
    {
        // performing install or reinstall/recache
        DebugMsg("[Info] Calling MsiInstallProduct with szInstallPath = %s", szInstallPath); 
        DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}");

        // default operation for a package is INSTALL

        if (fQFE)
        {
            // check to see if this product is already installed
            if (ERROR_SUCCESS == pfnMsiOpenDatabase(szMsiCacheFile ? szMsiCacheFile : szInstallPath, MSIDBOPEN_READONLY, &hDatabase)
                && ERROR_SUCCESS == pfnMsiDatabaseOpenView(hDatabase, sqlProductCode, &hView)
                && ERROR_SUCCESS == pfnMsiViewExecute(hView, 0)
                && ERROR_SUCCESS == pfnMsiViewFetch(hView, &hRec)
                && ERROR_SUCCESS == pfnMsiRecordGetString(hRec, 1, szProductCode, &dwProductCodeSize))
            {
                isProduct = pfnMsiQueryProductState(szProductCode);
                DebugMsg("[Info] MsiQueryProductState returned %d\n", isProduct);
                if (INSTALLSTATE_ADVERTISED != isProduct && INSTALLSTATE_DEFAULT != isProduct)
                {
                    // product is unknown, so this will be a first time install
                    DebugMsg("[Info] The product code '%s' is unknown. Will use first time install logic...\n", szProductCode);
                    fQFE = false;
                }
                else
                {
                    // product is known, use QFE syntax
                    DebugMsg("[Info] The product code '%s' is known. Will use QFE recache and reinstall upgrade logic...\n", szProductCode);
                }
            }
            else
            {
                // some failure occurred when processing the product code, so treat as non-QFE
                DebugMsg("[Info] Unable to process product code. Will treat as first time install...\n");
                fQFE = false;
            }
            if (hDatabase)
                pfnMsiCloseHandle(hDatabase);
            if (hView)
                pfnMsiCloseHandle(hView);
            if (hRec)
                pfnMsiCloseHandle(hRec);
        }
        
        //
        // Set up the properties to be passed into MSIInstallProduct
        //
        if (fQFE && !szProperties)
            cchInstProperties = lstrlen (szDefaultInstallUpdCommandLine);
        else if (szProperties)
            cchInstProperties = lstrlen (szProperties);
        if (emAdminInstall == emExecMode)
            cchInstProperties += lstrlen (szAdminInstallProperty);
        
        szInstProperties = new char[cchInstProperties + 1];
        if (! szInstProperties)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }
        
        if (fQFE && !szProperties)
        {
            if (FAILED(StringCchCopy(szInstProperties, cchInstProperties + 1, szDefaultInstallUpdCommandLine)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }
        else if (szProperties)
        {
            if (FAILED(StringCchCopy(szInstProperties, cchInstProperties + 1, szProperties)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }
        else
            szInstProperties[0] = '\0';
        if (emAdminInstall == emExecMode)
        {
            if (FAILED(StringCchCat(szInstProperties, cchInstProperties + 1, szAdminInstallProperty)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }

        uiRet = pfnMsiInstallProduct(szInstallPath, szInstProperties);
        if (ERROR_SUCCESS != uiRet)
        {
            // attempt to display an error message stored in msi.dll
            PostMsiError(hInst, hMsi, DownloadUI.GetCurrentWindow(), szAppTitle, uiRet);
        }

        DebugMsg("[Info] MsiInstallProduct returned %d\n", uiRet);
    }
    else
    {
        // default Operation for a patch is MINPATCH

        // if szProperties is NULL, use our default value for QFE patches
        if (!szProperties && fQFE)
        {
            DebugMsg("[Info] Patch is a MINPATCH (small or minor update patch) so using default command line '%s'\n", szDefaultMinPatchCommandLine);

            szProperties = new char[lstrlen(szDefaultMinPatchCommandLine) + 1];
            if (!szProperties)
            {
                ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
                uiRet = ERROR_OUTOFMEMORY;
                goto CleanUp;
            }
            if (FAILED(StringCchCopy(szProperties, lstrlen(szDefaultMinPatchCommandLine) + 1, szDefaultMinPatchCommandLine)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }

        if (emAdminInstall == emExecMode)
        {
            // performing a patch
            DebugMsg("[Info] Calling MsiApplyPatch with szPatchPackage = %s", szMsiCacheFile);
            DebugMsg(" and szInstallPackage = %s and eInstallType = INSTALLTYPE_NETWORK_IMAGE", szAdminImagePath);
            DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}");

            uiRet = pfnMsiApplyPatch(szMsiCacheFile, szAdminImagePath, INSTALLTYPE_NETWORK_IMAGE, szProperties);
        }
        else
        {
            // performing a patch
            DebugMsg("[Info] Calling MsiApplyPatch with szPatchPackage = %s", szInstallPath);
            DebugMsg(" and szInstallPackage = {null} and eInstallType = INSTALLTYPE_DEFAULT");
            DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}");

            uiRet = pfnMsiApplyPatch(szInstallPath, NULL, INSTALLTYPE_DEFAULT, szProperties);
        }
        if (ERROR_SUCCESS != uiRet)
        {
            // attempt to display an error message stored in msi.dll
            PostMsiError(hInst, hMsi, DownloadUI.GetCurrentWindow(), szAppTitle, uiRet);
        }

        DebugMsg("[Info] MsiApplyPatch returned %d\n", uiRet);
    }

    
CleanUp:

    if (szMsiFile)
        delete [] szMsiFile;
    if (szBaseURL)
        delete [] szBaseURL;
    if (szInstallPath)
        delete [] szInstallPath;
    if (szMsiCacheFile)
    {
        WIN::DeleteUrlCacheEntry(szMsiCacheFile);
        delete [] szMsiCacheFile;
    }
    if (szProductName)
        delete [] szProductName;
    if (szMinimumMsi)
        delete [] szMinimumMsi;
    if (szProperties)
        delete [] szProperties;
    if (szTempPath)
        delete [] szTempPath;
    if (szBase)
        delete [] szBase;
    if (szUpdate)
        delete [] szUpdate;
    if (szRegisteredMsiFolder)
        delete [] szRegisteredMsiFolder;
    if (szMsiDllLocation)
        delete [] szMsiDllLocation;
    if (szOperation)
        delete [] szOperation;

    if(hMutex)
        CloseHandle(hMutex);

    if (hMsi)
        FreeLibrary(hMsi);

    DebugMsg("[Info] Setup exit code is %d\n", uiRet);

    if (fDelayRebootReq)
    {
        // need to reboot machine for updating Windows Installer
        WIN::LoadString(hInst, IDS_REBOOT_REQUIRED, szAction, MAX_STR_LENGTH);
        if (IDYES == MessageBox(NULL, szAction, szAppTitle, MB_YESNO|MB_ICONQUESTION))
        {
            // must first aquire system shutdown privileges on NT/Win2K
            AcquireShutdownPrivilege();
            // initiate system shutdown for reboot
            WIN::ExitWindowsEx(EWX_REBOOT, PCLEANUI | SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION);
        }
    }

    return uiRet;
}
Exemplo n.º 8
0
char *
lrealpath (const char *filename)
{
  /* Method 1: The system has a compile time upper bound on a filename
     path.  Use that and realpath() to canonicalize the name.  This is
     the most common case.  Note that, if there isn't a compile time
     upper bound, you want to avoid realpath() at all costs.  */
#if defined(REALPATH_LIMIT)
  {
    char buf[REALPATH_LIMIT];
    const char *rp = realpath (filename, buf);
    if (rp == NULL)
      rp = filename;
    return strdup (rp);
  }
#endif /* REALPATH_LIMIT */

  /* Method 2: The host system (i.e., GNU) has the function
     canonicalize_file_name() which malloc's a chunk of memory and
     returns that, use that.  */
#if defined(HAVE_CANONICALIZE_FILE_NAME)
  {
    char *rp = canonicalize_file_name (filename);
    if (rp == NULL)
      return strdup (filename);
    else
      return rp;
  }
#endif

  /* Method 3: Now we're getting desperate!  The system doesn't have a
     compile time buffer size and no alternative function.  Query the
     OS, using pathconf(), for the buffer limit.  Care is needed
     though, some systems do not limit PATH_MAX (return -1 for
     pathconf()) making it impossible to pass a correctly sized buffer
     to realpath() (it could always overflow).  On those systems, we
     skip this.  */
#if defined (HAVE_REALPATH) && defined (HAVE_UNISTD_H)
  {
    /* Find out the max path size.  */
    long path_max = pathconf ("/", _PC_PATH_MAX);
    if (path_max > 0)
      {
	/* PATH_MAX is bounded.  */
	char *buf, *rp, *ret;
	buf = (char *) malloc (path_max);
	if (buf == NULL)
	  return NULL;
	rp = realpath (filename, buf);
	ret = strdup (rp ? rp : filename);
	free (buf);
	return ret;
      }
  }
#endif

  /* The MS Windows method.  If we don't have realpath, we assume we
     don't have symlinks and just canonicalize to a Windows absolute
     path.  GetFullPath converts ../ and ./ in relative paths to
     absolute paths, filling in current drive if one is not given
     or using the current directory of a specified drive (eg, "E:foo").
     It also converts all forward slashes to back slashes.  */
#if defined (_WIN32)
  {
    char buf[MAX_PATH];
    char* basename;
    DWORD len = GetFullPathName (filename, MAX_PATH, buf, &basename);
    if (len == 0 || len > MAX_PATH - 1)
      return strdup (filename);
    else
      {
	/* The file system is case-preserving but case-insensitive,
	   Canonicalize to lowercase, using the codepage associated
	   with the process locale.  */
        CharLowerBuff (buf, len);
        return strdup (buf);
      }
  }
#endif

  /* This system is a lost cause, just duplicate the filename.  */
  return strdup (filename);
}
Exemplo n.º 9
0
static BOOL
CreateShortcut(
    LPCTSTR pszFolder,
    LPCTSTR pszName,
    LPCTSTR pszCommand,
    LPCTSTR pszDescription,
    INT iIconNr)
{
    TCHAR szPath[MAX_PATH];
    TCHAR szExeName[MAX_PATH];
    LPTSTR Ptr;
    TCHAR szWorkingDirBuf[MAX_PATH];
    LPTSTR pszWorkingDir = NULL;
    LPTSTR lpFilePart;
    DWORD dwLen;

    if (ExpandEnvironmentStrings(pszCommand,
                                 szPath,
                                 sizeof(szPath) / sizeof(szPath[0])) == 0)
    {
        _tcscpy(szPath, pszCommand);
    }

    if ((_taccess(szPath, 0 )) == -1)
        /* Expected error, don't return FALSE */
        return TRUE;

    dwLen = GetFullPathName(szPath,
                            sizeof(szWorkingDirBuf) / sizeof(szWorkingDirBuf[0]),
                            szWorkingDirBuf,
                            &lpFilePart);
    if (dwLen != 0 && dwLen <= sizeof(szWorkingDirBuf) / sizeof(szWorkingDirBuf[0]))
    {
        /* Since those should only be called with (.exe) files,
           lpFilePart has not to be NULL */
        ASSERT(lpFilePart != NULL);

        /* Save the file name */
        _tcscpy(szExeName, lpFilePart);

        /* We're only interested in the path. Cut the file name off.
           Also remove the trailing backslash unless the working directory
           is only going to be a drive, ie. C:\ */
        *(lpFilePart--) = _T('\0');
        if (!(lpFilePart - szWorkingDirBuf == 2 && szWorkingDirBuf[1] == _T(':') &&
              szWorkingDirBuf[2] == _T('\\')))
        {
            *lpFilePart = _T('\0');
        }

        pszWorkingDir = szWorkingDirBuf;
    }

    _tcscpy(szPath, pszFolder);

    Ptr = PathAddBackslash(szPath);

    _tcscpy(Ptr, pszName);

    // FIXME: we should pass 'command' straight in here, but shell32 doesn't expand it
    return SUCCEEDED(CreateShellLink(szPath, szExeName, _T(""), pszWorkingDir, szExeName, iIconNr, pszDescription));
}
Exemplo n.º 10
0
INT CommandAttrib (LPTSTR param)
{
    LPTSTR *arg;
    INT    argc, i;
    TCHAR  szPath[MAX_PATH];
    TCHAR  szFileName [MAX_PATH];
    BOOL   bRecurse = FALSE;
    BOOL   bDirectories = FALSE;
    DWORD  dwAttrib = 0;
    DWORD  dwMask = 0;

    /* initialize strings */
    szPath[0] = _T('\0');
    szFileName[0] = _T('\0');

    /* print help */
    if (!_tcsncmp (param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE,STRING_ATTRIB_HELP);
        return 0;
    }

    nErrorLevel = 0;

    /* build parameter array */
    arg = split (param, &argc, FALSE, FALSE);

    /* check for options */
    for (i = 0; i < argc; i++)
    {
        if (_tcsicmp (arg[i], _T("/s")) == 0)
            bRecurse = TRUE;
        else if (_tcsicmp (arg[i], _T("/d")) == 0)
            bDirectories = TRUE;
    }

    /* create attributes and mask */
    for (i = 0; i < argc; i++)
    {
        if (*arg[i] == _T('+'))
        {
            if (_tcslen (arg[i]) != 2)
            {
                error_invalid_parameter_format (arg[i]);
                freep (arg);
                return -1;
            }

            switch ((TCHAR)_totupper (arg[i][1]))
            {
                case _T('A'):
                    dwMask   |= FILE_ATTRIBUTE_ARCHIVE;
                    dwAttrib |= FILE_ATTRIBUTE_ARCHIVE;
                    break;

                case _T('H'):
                    dwMask   |= FILE_ATTRIBUTE_HIDDEN;
                    dwAttrib |= FILE_ATTRIBUTE_HIDDEN;
                    break;

                case _T('R'):
                    dwMask   |= FILE_ATTRIBUTE_READONLY;
                    dwAttrib |= FILE_ATTRIBUTE_READONLY;
                    break;

                case _T('S'):
                    dwMask   |= FILE_ATTRIBUTE_SYSTEM;
                    dwAttrib |= FILE_ATTRIBUTE_SYSTEM;
                    break;

                default:
                    error_invalid_parameter_format (arg[i]);
                    freep (arg);
                    return -1;
            }
        }
        else if (*arg[i] == _T('-'))
        {
            if (_tcslen (arg[i]) != 2)
            {
                error_invalid_parameter_format (arg[i]);
                freep (arg);
                return -1;
            }

            switch ((TCHAR)_totupper (arg[i][1]))
            {
                case _T('A'):
                    dwMask   |= FILE_ATTRIBUTE_ARCHIVE;
                    dwAttrib &= ~FILE_ATTRIBUTE_ARCHIVE;
                    break;

                case _T('H'):
                    dwMask   |= FILE_ATTRIBUTE_HIDDEN;
                    dwAttrib &= ~FILE_ATTRIBUTE_HIDDEN;
                    break;

                case _T('R'):
                    dwMask   |= FILE_ATTRIBUTE_READONLY;
                    dwAttrib &= ~FILE_ATTRIBUTE_READONLY;
                    break;

                case _T('S'):
                    dwMask   |= FILE_ATTRIBUTE_SYSTEM;
                    dwAttrib &= ~FILE_ATTRIBUTE_SYSTEM;
                    break;

                default:
                    error_invalid_parameter_format (arg[i]);
                    freep (arg);
                    return -1;
            }
        }
    }

    if (argc == 0)
    {
        DWORD len;

        len = GetCurrentDirectory (MAX_PATH, szPath);
        if (szPath[len-1] != _T('\\'))
        {
            szPath[len] = _T('\\');
            szPath[len + 1] = 0;
        }
        _tcscpy (szFileName, _T("*.*"));
        PrintAttribute (szPath, szFileName, bRecurse);
        freep (arg);
        return 0;
    }

    /* get full file name */
    for (i = 0; i < argc; i++)
    {
        if ((*arg[i] != _T('+')) && (*arg[i] != _T('-')) && (*arg[i] != _T('/')))
        {
            LPTSTR p;
            GetFullPathName (arg[i], MAX_PATH, szPath, NULL);
            p = _tcsrchr (szPath, _T('\\')) + 1;
            _tcscpy (szFileName, p);
            *p = _T('\0');

            if (dwMask == 0)
                PrintAttribute (szPath, szFileName, bRecurse);
            else
                ChangeAttribute (szPath, szFileName, dwMask,
                         dwAttrib, bRecurse, bDirectories);
        }
    }

    freep (arg);
    return 0;
}
Exemplo n.º 11
0
void InitMaps()
{
    hash_map<wstring,WORD> slots;

    // process boots map file
    hash_map<DWORD,wstring> mapFile;
    wstring mpath(getPesInfo()->gdbDir);
    mpath += L"GDB\\boots\\map.txt";
    if (!readMap(mpath.c_str(), mapFile))
    {
        LOG1S(L"Couldn't open boots map for reading: {%s}",mpath.c_str());
    }
    else
    {
        int slot = 0;
        for (hash_map<DWORD,wstring>::iterator it = mapFile.begin(); it != mapFile.end(); it++)
        {
            wstring boot(it->second);
            string_strip(boot);
            if (!boot.empty())
                string_strip_quotes(boot);

            if (!boot.empty())
            {
                // check that the file exists, so that we don't crash
                // later, when it's attempted to replace a boot.
                wstring filename(getPesInfo()->gdbDir);
                filename += L"GDB\\boots\\" + boot;
                HANDLE handle;
                DWORD size;
                if (OpenFileIfExists(filename.c_str(), handle, size))
                {
                    CloseHandle(handle);
                    if (slot >= MAX_BOOTS)
                    {
                        LOG2N(L"ERROR in bootserver map: Too many boots: %d (MAX supported = %d). Aborting map processing", slot, MAX_BOOTS);
                        break;
                    }

                    hash_map<wstring,WORD>::iterator wit = slots.find(boot);
                    if (wit != slots.end())
                    {
                        // boot already has an assigned slot
                        _boot_slots.insert(pair<DWORD,WORD>(
                                    it->first, wit->second));
                    }
                    else
                    {
                        _boot_slots.insert(pair<DWORD,WORD>(
                                    it->first, FIRST_EXTRA_BOOT_SLOT + slot));
                        slots.insert(pair<wstring,WORD>(
                                    boot, FIRST_EXTRA_BOOT_SLOT + slot));
                        slot++;
                    }
                }
                else
                    LOG1N1S(L"ERROR in bootserver map for ID = %d: FAILED to open boot BIN \"%s\". Skipping", it->first, boot.c_str());
            }
        }
    }

    if (_bootserv_config._random_boots)
    {
        // enumerate all boots and add them to the slots list
        wstring dir(getPesInfo()->gdbDir);
        dir += L"GDB\\boots\\";

        // normalize the path
        wchar_t fullpath[MAX_PATH];
        GetFullPathName(dir.c_str(), MAX_PATH, fullpath, 0);
        dir = fullpath;

        int count;
        LOG(L"Enumerating all boots in GDB...");
        EnumerateBoots(dir, count);
        _num_random_boots = count;
        LOG1N(L"_num_random_boots = %d", _num_random_boots);
    }

    // initialize fast bin lookup table
    for (hash_map<wstring,WORD>::iterator sit = slots.begin();
            sit != slots.end();
            sit++)
    {
        _fast_bin_table[sit->second - FIRST_EXTRA_BOOT_SLOT] = 
            new wstring(sit->first);
        if (k_bootserv.debug)
            LOG1N1S(L"slot %d <-- boot {%s}", sit->second, sit->first.c_str());
    }

    LOG1N(L"Total assigned GDB boots: %d", slots.size());
    LOG1N(L"Total random GDB boots: %d", _num_random_boots);

    if (slots.size() > 0)
        _num_slots = FIRST_EXTRA_BOOT_SLOT + slots.size();
    if (_num_random_boots > 0)
        _num_slots = FIRST_RANDOM_BOOT_SLOT + _num_random_boots;
    LOG1N(L"_num_slots = %d", _num_slots);
}
Exemplo n.º 12
0
ImageError_e Disk2InterfaceCard::InsertDisk(const int drive, LPCTSTR pszImageFilename, const bool bForceWriteProtected, const bool bCreateIfNecessary)
{
	FloppyDrive* pDrive = &m_floppyDrive[drive];
	FloppyDisk* pFloppy = &pDrive->m_disk;

	if (pFloppy->m_imagehandle)
		RemoveDisk(drive);

	// Reset the disk's attributes, but preserve the drive's attributes (GH#138/Platoon, GH#640)
	// . Changing the disk (in the drive) doesn't affect the drive's attributes.
	pFloppy->clear();

	const DWORD dwAttributes = GetFileAttributes(pszImageFilename);
	if(dwAttributes == INVALID_FILE_ATTRIBUTES)
		pFloppy->m_bWriteProtected = false;	// Assume this is a new file to create
	else
		pFloppy->m_bWriteProtected = bForceWriteProtected ? true : (dwAttributes & FILE_ATTRIBUTE_READONLY);

	// Check if image is being used by the other drive, and if so remove it in order so it can be swapped
	{
		const char* pszOtherPathname = DiskGetFullPathName(!drive);

		char szCurrentPathname[MAX_PATH]; 
		DWORD uNameLen = GetFullPathName(pszImageFilename, MAX_PATH, szCurrentPathname, NULL);
		if (uNameLen == 0 || uNameLen >= MAX_PATH)
			strcpy_s(szCurrentPathname, MAX_PATH, pszImageFilename);

 		if (!strcmp(pszOtherPathname, szCurrentPathname))
		{
			EjectDisk(!drive);
			FrameRefreshStatus(DRAW_LEDS | DRAW_BUTTON_DRIVES);
		}
	}

	ImageError_e Error = ImageOpen(pszImageFilename,
		&pFloppy->m_imagehandle,
		&pFloppy->m_bWriteProtected,
		bCreateIfNecessary,
		pFloppy->m_strFilenameInZip);

	if (Error == eIMAGE_ERROR_NONE && ImageIsMultiFileZip(pFloppy->m_imagehandle))
	{
		TCHAR szText[100+MAX_PATH];
		szText[sizeof(szText)-1] = 0;
		_snprintf(szText, sizeof(szText)-1, "Only the first file in a multi-file zip is supported\nUse disk image '%s' ?", pFloppy->m_strFilenameInZip.c_str());
		int nRes = MessageBox(g_hFrameWindow, szText, TEXT("Multi-Zip Warning"), MB_ICONWARNING | MB_YESNO | MB_SETFOREGROUND);
		if (nRes == IDNO)
		{
			RemoveDisk(drive);
			Error = eIMAGE_ERROR_REJECTED_MULTI_ZIP;
		}
	}

	if (Error == eIMAGE_ERROR_NONE)
	{
		GetImageTitle(pszImageFilename, pFloppy->m_imagename, pFloppy->m_fullname);
		Video_ResetScreenshotCounter(pFloppy->m_imagename);
	}
	else
	{
		Video_ResetScreenshotCounter(NULL);
	}

	SaveLastDiskImage(drive);
	
	return Error;
}
Exemplo n.º 13
0
Arquivo: du.c Projeto: mingpen/OpenNT
int _CRTAPI1 main (int c, char *v[])
{
    int         tenth, pct;
    int         bValidBuf;
    DWORDLONG   tmpTot, tmpFree;
    DWORD       cSecsPerClus, cBytesPerSec, cFreeClus, cTotalClus;
    USESTAT     useTot, useTmp;
    char        Buffer[MAX_PATH];
    char        *p;

    SHIFT (c, v);

    while (c && (**v == '/' || **v == '-'))
    {
        if (!strcmp (*v + 1, "s"))
            fNodeSummary = TRUE;
        else
        {
            puts ("Usage: DU [/s] [dirs]");
            exit (1);
        }
        SHIFT (c, v);
    }

    if (c == 0)
    {
        GetCurrentDirectory( MAX_PATH, (LPSTR)buf );

        root[0] = buf[0];
        if( bValidDrive = GetDiskFreeSpace( root,
                                            &cSecsPerClus,
                                            &cBytesPerSec,
                                            &cFreeClus,
                                            &cTotalClus ) == TRUE )
        {
            bytesPerAlloc = cBytesPerSec * cSecsPerClus;
            totFree       = (DWORDLONG)bytesPerAlloc * cFreeClus;
            totDisk       = (DWORDLONG)bytesPerAlloc * cTotalClus;
        }
        useTot = DoDu (buf);
        if (fNodeSummary)
            TotPrint (&useTot, buf);
    }
    else
    {
        CLEARUSE (useTot);

        while (c)
        {
            LPSTR FilePart;

            bValidBuf = GetFullPathName( *v, MAX_PATH, buf, &FilePart);

            if ( bValidBuf )
            {
                if ( buf[0] == '\\' ) {

                    fUnc        = TRUE;
                    bValidDrive = TRUE;
                    bytesPerAlloc = 1;
                } else {
                    root[0] = buf[0];
                    if( bValidDrive = GetDiskFreeSpace( root,
                                                        &cSecsPerClus,
                                                        &cBytesPerSec,
                                                        &cFreeClus,
                                                        &cTotalClus ) == TRUE)
                    {
                        bytesPerAlloc = cBytesPerSec * cSecsPerClus;
                        totFree       = (DWORDLONG)bytesPerAlloc * cFreeClus;
                        totDisk       = (DWORDLONG)bytesPerAlloc * cTotalClus;
                    } else
                        printf ("Invalid drive or directory %s\n", *v );
                }

                if( bValidDrive & (GetFileAttributes( buf ) & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
                {
                    useTmp = DoDu (buf);
                    if (fNodeSummary)
                        TotPrint (&useTmp, buf);
                    ADDUSE (useTot, useTmp);
                }
            }
            else
                printf ("Invalid drive or directory %s\n", *v );
            SHIFT (c, v);
        }
    }

    if (cDisp != 0)
    {
        if (cDisp > 1)
            TotPrint (&useTot, "Total");

        /* quick full-disk test */
        if ( !fUnc ) {
            if (totFree == 0)
                puts ("Disk is full");
            else
            {
                tmpTot = (totDisk + 1023) / 1024;
                tmpFree = (totFree + 1023) / 1024;
                pct = (DWORD)(1000 * (tmpTot - tmpFree) / tmpTot);
                tenth = pct % 10;
                pct /= 10;

                p = FormatDwordLong( totDisk-totFree, Buffer, sizeof(Buffer) );
                printf("%s/",p);
                p = FormatDwordLong( totDisk, Buffer, sizeof(Buffer) );
                printf("%s ",p);
                printf ("%d.%d%% of disk in use\n", pct, tenth);
            }
        }
    }
    return( 0 );
}
Exemplo n.º 14
0
static DWORD
ProcessDirectory(LPTSTR FileName, DWORD* dwFlags, DWORD dwAttrFlags)
{
        TCHAR szFullPath[MAX_PATH];
        LPTSTR pFilePart;
        LPTSTR pSearchPart;
        HANDLE hFile;
        WIN32_FIND_DATA f;
        DWORD dwFiles = 0;

        GetFullPathName (FileName,
                         MAX_PATH,
                         szFullPath,
                         &pFilePart);

        dwFiles = DeleteFiles(szFullPath, dwFlags, dwAttrFlags);
        if (dwFiles & 0x80000000)
                return dwFiles;

        if (*dwFlags & DEL_SUBDIR)
        {
	        /* Get just the file name */
	        pSearchPart = _tcsrchr(FileName,_T('\\'));
	        if(pSearchPart != NULL)
		        pSearchPart++;
	        else
		        pSearchPart = FileName;

	        /* Get the full path to the file */
	        GetFullPathName (FileName,MAX_PATH,szFullPath,NULL);

	        /* strip the filename off of it */
                pFilePart = _tcsrchr(szFullPath, _T('\\'));
                if (pFilePart == NULL)
                {
                        pFilePart = szFullPath;
                }
                else
                {
                        pFilePart++;
                }

                _tcscpy(pFilePart, _T("*"));

                hFile = FindFirstFile(szFullPath, &f);
                if (hFile != INVALID_HANDLE_VALUE)
                {
                        do
                        {
       		                if (!(f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
                                    !_tcscmp(f.cFileName, _T(".")) ||
                                    !_tcscmp(f.cFileName, _T("..")))
		                        continue;

                                _tcscpy(pFilePart, f.cFileName);
                                _tcscat(pFilePart, _T("\\"));
                                _tcscat(pFilePart, pSearchPart);

                                dwFiles +=ProcessDirectory(szFullPath, dwFlags, dwAttrFlags);
                                if (dwFiles & 0x80000000)
                                {
                                    break;
                                }
                        }
                        while (FindNextFile (hFile, &f));
	                FindClose (hFile);
                }
        }
        return dwFiles;
}
Exemplo n.º 15
0
int __cdecl	
_tmain( 
    int argc, 
    TCHAR* argv[] 
    )
{
    TCHAR DestPath[MAX_PATH];
    ULONG Size = MAX_PATH;
    TCHAR * InfPath = NULL;
	TCHAR DriverPackageInfPath[MAX_PATH];
    DWORD Ret;
    TCHAR Option;
    BOOL NeedRebootDev = FALSE;
    BOOL NeedRebootDrvPkg = FALSE;
    DWORD Flags = 0;  
    LPTSTR lpFilePart;
    int i;
    DWORD dw;
    Size = MAX_PATH;
    
    _tprintf( TEXT("Driver Installer Sample Program\n") ); 
    if( argc < 3 )
    {
        _tprintf( TEXT("USAGE: drvinst /i /c /r /g <inf-filename> [Flag(s)]\n") );
        _tprintf( TEXT("\nOptions:\n"));
        _tprintf( TEXT("/i : re-install driver package and devices if presented.\n") );
        _tprintf( TEXT("/u : uninstall devices and driver package.\n") );
        _tprintf( TEXT("/g : get installed driver package path.\n") );

        _tprintf( TEXT("\n<inf-filename> : path to the inf file.\n") );
        _tprintf( TEXT("\nFlags:\n"));
        _tprintf( TEXT("DRIVER_PACKAGE_REPAIR:                 0x00000001 ( 1)\n"));
        _tprintf( TEXT("DRIVER_PACKAGE_SILENT:                 0x00000002 ( 2)\n"));
        _tprintf( TEXT("DRIVER_PACKAGE_FORCE:                  0x00000004 ( 4)\n"));
        _tprintf( TEXT("DRIVER_PACKAGE_ONLY_IF_DEVICE_PRESENT: 0x00000008 ( 8)\n"));
        _tprintf( TEXT("DRIVER_PACKAGE_LEGACY:                 0x00000010 (16)\n"));
        _tprintf( TEXT("DRIVER_PACKAGE_DELETE_FILES:           0x00000020 (32)\n"));
        
        return 0;
    }

    //
    // Get command line choices
    //

    //
    // The code suppresses the warning 28193 for the call to _totlower.
    // This suppression is done because that function has a check return
    // annotation on it.  However, it doesn't return an error code
    // and the check return annotation is really being used to indicate
    // that the return value of the function should be looked at and/or 
    // assigned to a variable. The check return annotation means the return
    // value should always be checked in all code paths.  The return value is
    // assigned to a variable, but the return in the for loop could cause
    // this function to exit before Option is ever examined.  For that case,
    // the code doesn't need to check the value of Option so the warning
    // is being suppressed
    //
#pragma warning( suppress: 28193)
    Option = (TCHAR)_totlower(argv[1][1]);
	InfPath = argv[2];

    for ( i = 3; i<argc; i++ ){
        dw = _ttol( argv[i] );
        //
        // Either an error occurred during conversion of a flags parameter 
        // into a long or a flag of 0 was specified.  Either way,
        // this is invalid input.
        //
        if (0 == dw)
        {
            _tprintf( TEXT("An invalid flag was specified.") );
            
            return 0;
        }

        Flags |= dw;
    }


    GetFullPathName( InfPath, MAX_PATH, DriverPackageInfPath, &lpFilePart);  
    
    _tprintf( TEXT("INFO: Option \"/%c\"\n"), Option );    
    _tprintf( TEXT("INFO: Input file \"%s\"\n"), DriverPackageInfPath );
    _tprintf( TEXT("INFO: Flags 0x%X (%u)\n\n"), Flags, Flags );

    
    DIFXAPISetLogCallback( LogCallback, (PVOID)NULL );
    
    Ret = ERROR_SUCCESS;

    if ( TEXT('u') == Option )
    {
        _tprintf( TEXT("INFO: uninstalling devices.\n"));

        if ( TRUE == RemoveDevices( &NeedRebootDev ) ) {
            _tprintf( TEXT("SUCCESS: uninstalled devices.\n") );

        }
        else {
            _tprintf( TEXT("ERROR: failed.\n") );
            Ret = !ERROR_SUCCESS;
        }

        if ( ERROR_SUCCESS == Ret ) {
            _tprintf( TEXT("INFO: uninstalling driver package.\n"));    

            Ret = DriverPackageUninstall(  
                        DriverPackageInfPath,
                        Flags,
                        NULL,
                        &NeedRebootDrvPkg);

            if( ERROR_SUCCESS == Ret ){
                _tprintf( TEXT("SUCCESS: uninstalled driver package %s.\n"), DriverPackageInfPath );
            } else {
                _tprintf( TEXT("ERROR: failed with error code 0x%X\n"), Ret );
            }
        
            if ( NeedRebootDev || NeedRebootDrvPkg ) {
                _tprintf( TEXT("INFO: Machine will have to be rebooted to complete uninstall.") );
            }
        }
    }
    else if ( TEXT('i') == Option )
    {
        _tprintf( TEXT("DRVINST: installing drivers.\n"));
        
        /* http://msdn.microsoft.com/en-us/library/windows/hardware/ff552293(v=vs.85).aspx
           
        */
        
        // step1 - Checking for In-Progress Installations
        if ( WAIT_OBJECT_0 != CMP_WaitNoPendingInstallEvents ( 0 ) ) {
        	_tprintf( TEXT("ERROR: There are pending installation activities or some error happened when checking CMP_WaitNoPendingInstallEvents\n") );
					goto final_main;
        }
        
        /*
           step2 - Determine whether a device is plugged in.
           step3 - Preinstall driver packages
        	 If we use DIFx API, will save our time, otherwise we must follow the MSDN regarding step2 and step3
        	 
        */
        Ret = DriverPackageInstall( 
                    DriverPackageInfPath, 
                    Flags,
                    NULL,
                    &NeedRebootDrvPkg);

        if( ERROR_SUCCESS == Ret ){
            _tprintf( TEXT("SUCCESS: installed package %s.\n"), DriverPackageInfPath );
        } else if (ERROR_NO_MORE_ITEMS == Ret){
            _tprintf( TEXT("INFO: All devices found already have a better driver than what is contained in the specified inf file. To force an install, use the ForceIfNotBetter flag.\n"));
        } else if (ERROR_NO_SUCH_DEVINST == Ret){
            _tprintf( TEXT("INFO: There aren't any live devnodes with the DeviceId contained in the INF.\n"));
        }
        else{
            _tprintf( TEXT("ERROR: failed with error code 0x%X\n"), Ret );
        }

        if (NeedRebootDrvPkg){
            _tprintf( TEXT("INFO: Machine will have to be rebooted to complete install.") );
        }
    }
    else if ( TEXT('g') == Option )
    {  
        _tprintf( TEXT("TEST: getting driver package path.\n")); 
        Ret = DriverPackageGetPath( DriverPackageInfPath, DestPath, &Size );
        if ( ERROR_SUCCESS==Ret ){
            _tprintf( TEXT("INFO: INF path is %s\n"), DestPath );    
        } else {
            _tprintf( TEXT("ERROR: failed with error code 0x%X\n"), Ret );
        }
    } else {
        _tprintf( TEXT("ERROR: invalid command line option /%c.\n"), Option );
    }

final_main:
    DIFXAPISetLogCallback( NULL, (PVOID)NULL );
    
    return 1;
}
Exemplo n.º 16
0
BOOL APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	PCHAR pszDllPath = "Accelerator.dll";

	CHAR szDllPath[1024];
    PCHAR pszFilePart = NULL;

	if (!GetFullPathName(pszDllPath, ARRAYSIZE(szDllPath), szDllPath, &pszFilePart)) 
	{
        MessageBoxA(NULL, "GetFullPathName Failed\n", "Error", MB_OK);
        return false;
    }

	HMODULE hDll = LoadLibraryEx(pszDllPath, NULL, DONT_RESOLVE_DLL_REFERENCES);
    if (hDll == NULL) 
	{
		MessageBoxA(NULL, "Failed to load dll\n", "Error", MB_OK);
        return false;
    }

	ExportContext ec;
    ec.fHasOrdinal1 = FALSE;
    ec.nExports = 0;
    DetourEnumerateExports(hDll, &ec, ExportCallback);
    FreeLibrary(hDll);

	if (!ec.fHasOrdinal1) 
	{
		MessageBoxA(NULL, "This dll does not export ordinal #1.\n", "Error", MB_OK);
        return false;
    }
	//////////////////////////////////////////////////////////////////////////////////
	STARTUPINFO si;
    PROCESS_INFORMATION pi;
    CHAR szCommand[2048];
    CHAR szExe[1024];
    CHAR szFullExe[1024] = "\0";
    PCHAR pszFileExe = NULL;

    ZeroMemory(&si, sizeof(si));
    ZeroMemory(&pi, sizeof(pi));
    si.cb = sizeof(si);

    szCommand[0] = L'\0';
	strcpy(szExe, "LOVESICK_PUPPIES.exe");
	strcpy(szCommand, "LOVESICK_PUPPIES.exe");
	//////////////////////////////////////////////////////////////////////////////////
	DWORD dwFlags = CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED;

    SetLastError(0);
    SearchPath(NULL, szExe, ".exe", ARRAYSIZE(szFullExe), szFullExe, &pszFileExe);
    if (!DetourCreateProcessWithDllEx(szFullExe[0] ? szFullExe : NULL, szCommand,
                                      NULL, NULL, TRUE, dwFlags, NULL, NULL,
                                      &si, &pi, szDllPath, NULL)) 
	{
        DWORD dwError = GetLastError();
		MessageBoxA(NULL, "DetourCreateProcessWithDllEx failed\n", "Error", MB_OK);
        
        if (dwError == ERROR_INVALID_HANDLE)
		{
#if DETOURS_64BIT
			MessageBoxA(NULL, " Can't detour a 32-bit target process from a 64-bit parent process.\n", "Error", MB_OK);
            
#else
			MessageBoxA(NULL, " Can't detour a 64-bit target process from a 32-bit parent process.\n", "Error", MB_OK);
#endif
        }
        ExitProcess(9009);
    }

    ResumeThread(pi.hThread);

    WaitForSingleObject(pi.hProcess, INFINITE);

    DWORD dwResult = 0;
    if (!GetExitCodeProcess(pi.hProcess, &dwResult)) 
	{
		MessageBoxA(NULL, "GetExitCodeProcess failed\n", "Error", MB_OK);
        return false;
    }

    return true;
}
Exemplo n.º 17
0
INT cmd_rmdir (LPTSTR param)
{
    TCHAR ch;
    INT args;
    INT dirCount;
    LPTSTR *arg;
    INT i;
    BOOL RD_SUB = FALSE;
    BOOL RD_QUIET = FALSE;
    INT res;
    INT nError = 0;
    TCHAR szFullPath[MAX_PATH];

    if (!_tcsncmp (param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE,STRING_RMDIR_HELP);
        return 0;
    }

    arg = split (param, &args, FALSE, FALSE);
    dirCount = 0;

    /* check for options anywhere in command line */
    for (i = 0; i < args; i++)
    {
        if (*arg[i] == _T('/'))
        {
            /*found a command, but check to make sure it has something after it*/
            if (_tcslen (arg[i]) == 2)
            {
                ch = _totupper (arg[i][1]);

                if (ch == _T('S'))
                {
                    RD_SUB = TRUE;
                }
                else if (ch == _T('Q'))
                {
                    RD_QUIET = TRUE;
                }
            }
        }
        else
        {
            dirCount++;
        }
    }

    if (dirCount == 0)
    {
        /* No folder to remove */
        error_req_param_missing();
        freep(arg);
        return 1;
    }

    for (i = 0; i < args; i++)
    {
        if (*arg[i] == _T('/'))
            continue;

        if (RD_SUB)
        {
            /* ask if they want to delete evrything in the folder */
            if (!RD_QUIET)
            {
                res = FilePromptYNA (STRING_DEL_HELP2);
                if (res == PROMPT_NO || res == PROMPT_BREAK)
                {
                    nError = 1;
                    continue;
                }
                if (res == PROMPT_ALL)
                    RD_QUIET = TRUE;
            }
            /* get the folder name */
            GetFullPathName(arg[i],MAX_PATH,szFullPath,NULL);

            /* remove trailing \ if any, but ONLY if dir is not the root dir */
            if (_tcslen (szFullPath) >= 2 && szFullPath[_tcslen (szFullPath) - 1] == _T('\\'))
                szFullPath[_tcslen(szFullPath) - 1] = _T('\0');

            res = DeleteFolder(szFullPath);
        }
        else
        {
            res = RemoveDirectory(arg[i]);
        }

        if (!res)
        {
            /* Couldn't delete the folder, print out the error */
            nError = GetLastError();
            ErrorMessage(nError, _T("RD"));
        }
    }

    freep (arg);
    return nError;
}
Exemplo n.º 18
0
//-----------------------------------------------------------------------------
// Name: DXUtil_FindMediaFileCch()
// Desc: Returns a valid path to a DXSDK media file
//       cchDest is the size in TCHARs of strDestPath.  Be careful not to 
//       pass in sizeof(strDest) on UNICODE builds.
//-----------------------------------------------------------------------------
HRESULT DXUtil_FindMediaFileCch( TCHAR* strDestPath, int cchDest, TCHAR* strFilename )
{
    HRESULT hr;
    HANDLE file;
    TCHAR* strShortNameTmp = NULL;
    TCHAR strShortName[MAX_PATH];
    int cchPath;

    if( NULL==strFilename || NULL==strDestPath || cchDest < 1 )
        return E_INVALIDARG;

    lstrcpy( strDestPath, TEXT("") );
    lstrcpy( strShortName, TEXT("") );

    // Build full path name from strFileName (strShortName will be just the leaf filename)
    cchPath = GetFullPathName(strFilename, cchDest, strDestPath, &strShortNameTmp);
    if ((cchPath == 0) || (cchDest <= cchPath))
        return E_FAIL;
    if( strShortNameTmp )
        lstrcpyn( strShortName, strShortNameTmp, MAX_PATH );

    // first try to find the filename given a full path
    file = CreateFile( strDestPath, GENERIC_READ, FILE_SHARE_READ, NULL, 
                       OPEN_EXISTING, 0, NULL );
    if( INVALID_HANDLE_VALUE != file )
    {
        CloseHandle( file );
        return S_OK;
    }
    
    // next try to find the filename in the current working directory (path stripped)
    file = CreateFile( strShortName, GENERIC_READ, FILE_SHARE_READ, NULL, 
                       OPEN_EXISTING, 0, NULL );
    if( INVALID_HANDLE_VALUE != file )
    {
        _tcsncpy( strDestPath, strShortName, cchDest );
        strDestPath[cchDest-1] = 0; // _tcsncpy doesn't NULL term if it runs out of space
        CloseHandle( file );
        return S_OK;
    }
    
    // last, check if the file exists in the media directory
    if( FAILED( hr = DXUtil_GetDXSDKMediaPathCch( strDestPath, cchDest ) ) )
        return hr;

    if( lstrlen(strDestPath) + lstrlen(strShortName) < cchDest )
        lstrcat( strDestPath, strShortName );
    else
        return E_INVALIDARG;

    file = CreateFile( strDestPath, GENERIC_READ, FILE_SHARE_READ, NULL, 
                       OPEN_EXISTING, 0, NULL );
    if( INVALID_HANDLE_VALUE != file )
    {
        CloseHandle( file );
        return S_OK;
    }

    // On failure, just return the file as the path
    _tcsncpy( strDestPath, strFilename, cchDest );
    strDestPath[cchDest-1] = 0; // _tcsncpy doesn't NULL term if it runs out of space
    return HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND );
}
Exemplo n.º 19
0
void init_all(int argc, char **argv)
{
   cpu_info();

   char *config = 0, *bpx = 0, *labels = 0;

   char opt;
   while ((opt = getopt(argc, argv, "i:l:b:")) != EOF)
       switch (opt)
       {
       case 'i':
           config = optarg;
           break;
       case 'b':
           bpx = optarg;
           break;
       case 'l':
           labels = optarg;
       }

   temp.Minimized = false;

   init_z80tables();
   init_ie_help();
   load_config(config);
   //make_samples();
   #ifdef MOD_GS
   init_gs();
   #endif
   init_leds();
   init_tape();
   init_hdd_cd();
   start_dx();
   applyconfig();
   main_reset();
   autoload();
   init_bpx(bpx);
   init_labels(labels);
   temp.Gdiplus = GdiplusStartup();
   if (!temp.Gdiplus)
   {
       color(CONSCLR_WARNING);
       printf("warning: gdiplus.dll was not loaded, only SCR and BMP screenshots available\n");
   }

   load_errors = 0;
   trd_toload = 0;
   *(DWORD*)trd_loaded = 0; // clear loaded flags, don't see autoload'ed images

   for (; optind < argc; optind++)
   {
      char fname[0x200], *temp;
      GetFullPathName(argv[optind], sizeof fname, fname, &temp);

      trd_toload = DefaultDrive; // auto-select
      if (!loadsnap(fname)) errmsg("error loading <%s>", argv[optind]), load_errors = 1;
   }

   if (load_errors) {
      int code = MessageBox(wnd, "Some files, specified in\r\ncommand line, failed to load\r\n\r\nContinue emulation?", "File loading error", MB_YESNO | MB_ICONWARNING);
      if (code != IDYES) exit();
   }

   SetCurrentDirectory(conf.workdir);
//   timeBeginPeriod(1);
}
Exemplo n.º 20
0
int32_t main(int32_t argc, char** argv) {
  FILE* infile = NULL;
  char* outname = NULL;
  uintptr_t column_sep = 2;
  uint32_t flags = 0;
  int32_t retval = 0;
  uintptr_t* col_widths = NULL;
  unsigned char* spacebuf = NULL;
  unsigned char* rjustify_buf = NULL;
  uintptr_t col_ct = 0;
  uint32_t infile_param_idx = 0;
  char* param_ptr;
#ifndef _WIN32
  char* cptr;
#endif
  uint32_t param_idx;
  uint32_t uii;
  int32_t ii;
  char cc;
  if (argc == 1) {
    goto main_ret_HELP;
  }
  for (param_idx = 1; param_idx < (uint32_t)argc; param_idx++) {
    if ((!strcmp(argv[param_idx], "--help")) || (!strcmp(argv[param_idx], "-help")) || (!strcmp(argv[param_idx], "-?")) || (!strcmp(argv[param_idx], "-h"))) {
      goto main_ret_HELP;
    }
  }

  if (argc > 10) {
    fputs("Error: Too many parameters.\n\n", stderr);
    goto main_ret_INVALID_CMDLINE_2;
  }
  for (param_idx = 1; param_idx < (uint32_t)argc; param_idx++) {
    if (argv[param_idx][0] != '-') {
      if (!infile_param_idx) {
	infile_param_idx = param_idx;
      } else if (!outname) {
	if (flags & FLAG_INPLACE) {
	  goto main_ret_INVALID_CMDLINE_3;
	}
        outname = argv[param_idx];
      } else {
	fputs("Error: Invalid parameter sequence.\n\n", stderr);
	goto main_ret_INVALID_CMDLINE_2;
      }
      continue;
    }
    param_ptr = &(argv[param_idx][1]);
    if (*param_ptr == '-') {
      // allow both single- and double-dash
      param_ptr++;
    }
    if (!strcmp(param_ptr, "inplace")) {
      if (outname) {
	goto main_ret_INVALID_CMDLINE_3;
      }
      flags |= FLAG_INPLACE;
    } else if ((!strcmp(param_ptr, "spacing")) || (!strcmp(param_ptr, "s"))) {
      if (++param_idx == (uint32_t)argc) {
	fputs("Error: Missing --spacing parameter.\n", stderr);
	goto main_ret_INVALID_CMDLINE;
      }
      ii = atoi(argv[param_idx]);
      if (ii < 1) {
	fprintf(stderr, "Error: Invalid --spacing parameter '%s'.\n", argv[param_idx]);
	goto main_ret_INVALID_CMDLINE;
      }
      column_sep = (uint32_t)ii;
    } else if (!strcmp(param_ptr, "ralign")) {
      flags |= FLAG_RJUSTIFY;
    } else if (!strcmp(param_ptr, "leading")) {
      flags |= FLAG_SPACES_BEFORE_FIRST;
    } else if (!strcmp(param_ptr, "extend-short")) {
      flags |= FLAG_PAD;
    } else if (!strcmp(param_ptr, "trailing")) {
      flags |= FLAG_SPACES_AFTER_LAST;
    } else if (!strcmp(param_ptr, "force-eoln")) {
      flags |= FLAG_FINAL_EOLN;
    } else if (!strcmp(param_ptr, "noblank")) {
      flags |= FLAG_STRIP_BLANK;
    } else {
      if ((argv[param_idx][1] != '-') && argv[param_idx][1]) {
	// permit abbreviated style
	while (1) {
	  cc = *param_ptr++;
	  if (!cc) {
	    break;
	  }
	  switch (cc) {
	  case 'i':
	    if (outname) {
	      goto main_ret_INVALID_CMDLINE_3;
	    }
	    flags |= FLAG_INPLACE;
	    break;
	  case 'r':
	    flags |= FLAG_RJUSTIFY;
	    break;
	  case 'l':
	    flags |= FLAG_SPACES_BEFORE_FIRST;
	    break;
	  case 'e':
	    flags |= FLAG_PAD;
	    break;
	  case 't':
	    flags |= FLAG_SPACES_AFTER_LAST;
	    break;
	  case 'f':
	    flags |= FLAG_FINAL_EOLN;
	    break;
	  case 'n':
	    flags |= FLAG_STRIP_BLANK;
	    break;
	  default:
            fprintf(stderr, "Error: Invalid flag '%s'.\n\n", argv[param_idx]);
	    goto main_ret_INVALID_CMDLINE_2;
	  }
	}
      } else {
	fprintf(stderr, "Error: Invalid flag '%s'.\n\n", argv[param_idx]);
	goto main_ret_INVALID_CMDLINE_2;
      }
    }
  }
  if (!infile_param_idx) {
    fputs("Error: No input filename.\n\n", stderr);
    goto main_ret_INVALID_CMDLINE_2;
  }
  if (flags & FLAG_INPLACE) {
    uii = strlen(argv[infile_param_idx]);
    outname = (char*)malloc(uii + 11);
    if (!outname) {
      goto main_ret_NOMEM;
    }
    memcpy(outname, argv[infile_param_idx], uii);
    memcpy(&(outname[uii]), "-temporary", 11);
  } else if (outname) {
#ifdef _WIN32
    uii = GetFullPathName(argv[infile_param_idx], FNAMESIZE, pathbuf, NULL);
    if ((!uii) || (uii > FNAMESIZE))
#else
    if (!realpath(argv[infile_param_idx], pathbuf))
#endif
    {
      fprintf(stderr, "Error: Failed to open %s.\n", argv[infile_param_idx]);
      goto main_ret_OPEN_FAIL;
    }
#ifdef _WIN32
    uii = GetFullPathName(outname, FNAMESIZE, &(pathbuf[FNAMESIZE + 64]), NULL);
    if (uii && (uii <= FNAMESIZE) && (!strcmp(pathbuf, &(pathbuf[FNAMESIZE + 64]))))
#else
    cptr = realpath(outname, &(pathbuf[FNAMESIZE + 64]));
    if (cptr && (!strcmp(pathbuf, &(pathbuf[FNAMESIZE + 64]))))
#endif
    {
      fputs("Error: Input and output files match.  Use --inplace instead.\n", stderr);
      goto main_ret_INVALID_CMDLINE;
    }
  }
  if (fopen_checked(&infile, argv[infile_param_idx], "rb")) {
    goto main_ret_OPEN_FAIL;
  }
  retval = scan_column_widths(infile, column_sep, &col_widths, &col_ct, &spacebuf, (flags & FLAG_RJUSTIFY)? (&rjustify_buf) : NULL);
  if (retval) {
    goto main_ret_1;
  }
  retval = pretty_write(infile, outname, flags, column_sep, col_widths, col_ct, spacebuf, rjustify_buf);
  if (retval) {
    goto main_ret_1;
  }
  fclose_null(&infile);
  if (flags & FLAG_INPLACE) {
    unlink(argv[infile_param_idx]);
    if (rename(outname, argv[infile_param_idx])) {
      fprintf(stderr, "Error: File rename failed.  Output is in %s instead of %s.\n", outname, argv[infile_param_idx]);
      goto main_ret_OPEN_FAIL;
    }
  }
  while (0) {
  main_ret_HELP:
    fputs(
"prettify v1.04 (21 Feb 2014)   Christopher Chang ([email protected])\n\n"
"Takes a tab-and/or-space-delimited text table, and generates a space-delimited\n"
"pretty-printed version.  Multibyte character encodings are not currently\n"
"supported.\n\n"
, stdout);
    disp_usage(stdout);
    fputs(
"\nTo perform the simplest reverse conversion (multiple spaces to one tab), you\n"
"can use\n"
"  cat [input filename] | tr -s ' ' '\\t' > [output filename]\n"
"For one-to-one conversion between spaces and tabs instead, omit the \"-s\".  And\n"
"to strip leading and trailing tabs and spaces, try\n"
"  cat [in] | sed 's/^[[:space:]]*//g' | sed 's/[[:space:]]*$//g' > [out]\n"
, stdout);
    retval = RET_HELP;
    break;
  main_ret_NOMEM:
    retval = RET_NOMEM;
    break;
  main_ret_OPEN_FAIL:
    retval = RET_OPEN_FAIL;
    break;
  main_ret_INVALID_CMDLINE_3:
    fputs("Error: --inplace cannot be used with an output filename.\n", stderr);
    retval = RET_INVALID_CMDLINE;
    break;
  main_ret_INVALID_CMDLINE_2:
    disp_usage(stderr);
  main_ret_INVALID_CMDLINE:
    retval = RET_INVALID_CMDLINE;
    break;
  }
 main_ret_1:
  free_cond(col_widths);
  fclose_cond(infile);
  dispmsg(retval);
  return retval;
}
Exemplo n.º 21
0
static char *GetPythonImport (HINSTANCE hModule)
{
	unsigned char *dllbase, *import_data, *import_name;
	DWORD pe_offset, opt_offset;
	WORD opt_magic;
	int num_dict_off, import_off;

	/* Safety check input */
	if (hModule == NULL) {
		return NULL;
	}

	/* Module instance is also the base load address.  First portion of
	   memory is the MS-DOS loader, which holds the offset to the PE
	   header (from the load base) at 0x3C */
	dllbase = (unsigned char *)hModule;
	pe_offset = DWORD_AT(dllbase + 0x3C);

	/* The PE signature must be "PE\0\0" */
	if (memcmp(dllbase+pe_offset,"PE\0\0",4)) {
		return NULL;
	}

	/* Following the PE signature is the standard COFF header (20
	   bytes) and then the optional header.  The optional header starts
	   with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+
	   uses 64-bits for some fields).  It might also be 0x107 for a ROM
	   image, but we don't process that here.

	   The optional header ends with a data dictionary that directly
	   points to certain types of data, among them the import entries
	   (in the second table entry). Based on the header type, we
	   determine offsets for the data dictionary count and the entry
	   within the dictionary pointing to the imports. */

	opt_offset = pe_offset + 4 + 20;
	opt_magic = WORD_AT(dllbase+opt_offset);
	if (opt_magic == 0x10B) {
		/* PE32 */
		num_dict_off = 92;
		import_off   = 104;
	} else if (opt_magic == 0x20B) {
		/* PE32+ */
		num_dict_off = 108;
		import_off   = 120;
	} else {
		/* Unsupported */
		return NULL;
	}

	/* Now if an import table exists, offset to it and walk the list of
	   imports.  The import table is an array (ending when an entry has
	   empty values) of structures (20 bytes each), which contains (at
	   offset 12) a relative address (to the module base) at which a
	   string constant holding the import name is located. */

	if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) {
		/* We have at least 2 tables - the import table is the second
		   one.  But still it may be that the table size is zero */
		if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD)))
			return NULL;
		import_data = dllbase + DWORD_AT(dllbase +
						 opt_offset +
						 import_off);
		while (DWORD_AT(import_data)) {
			import_name = dllbase + DWORD_AT(import_data+12);
			if (strlen(import_name) >= 6 &&
			    !strncmp(import_name,"python",6)) {
				char *pch;

				/* Ensure python prefix is followed only
				   by numbers to the end of the basename */
				pch = import_name + 6;
#ifdef _DEBUG
				while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') {
#else
				while (*pch && *pch != '.') {
#endif
					if (*pch >= '0' && *pch <= '9') {
						pch++;
					} else {
						pch = NULL;
						break;
					}
				}
	    
				if (pch) {
					/* Found it - return the name */
					return import_name;
				}
			}
			import_data += 20;
		}
	}

	return NULL;
}


dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
				    const char *pathname, FILE *fp)
{
	dl_funcptr p;
	char funcname[258], *import_python;

	PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname);

	{
		HINSTANCE hDLL = NULL;
		char pathbuf[260];
		LPTSTR dummy;
		unsigned int old_mode;
		/* We use LoadLibraryEx so Windows looks for dependent DLLs 
		    in directory of pathname first.  However, Windows95
		    can sometimes not work correctly unless the absolute
		    path is used.  If GetFullPathName() fails, the LoadLibrary
		    will certainly fail too, so use its error code */

		/* Don't display a message box when Python can't load a DLL */
		old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);

		if (GetFullPathName(pathname,
				    sizeof(pathbuf),
				    pathbuf,
				    &dummy))
			/* XXX This call doesn't exist in Windows CE */
			hDLL = LoadLibraryEx(pathname, NULL,
					     LOAD_WITH_ALTERED_SEARCH_PATH);

		/* restore old error mode settings */
		SetErrorMode(old_mode);

		if (hDLL==NULL){
			PyObject *message;
			unsigned int errorCode;

			/* Get an error string from Win32 error code */
			wchar_t theInfo[256]; /* Pointer to error text
					      from system */
			int theLength; /* Length of error text */

			errorCode = GetLastError();

			theLength = FormatMessageW(
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */
				NULL, /* message source */
				errorCode, /* the message (error) ID */
				MAKELANGID(LANG_NEUTRAL,
					   SUBLANG_DEFAULT),
				           /* Default language */
				theInfo, /* the buffer */
				sizeof(theInfo), /* the buffer size */
				NULL); /* no additional format args. */

			/* Problem: could not get the error message.
			   This should not happen if called correctly. */
			if (theLength == 0) {
				message = PyUnicode_FromFormat(
					"DLL load failed with error code %d",
					errorCode);
			} else {
				/* For some reason a \r\n
				   is appended to the text */
				if (theLength >= 2 &&
				    theInfo[theLength-2] == '\r' &&
				    theInfo[theLength-1] == '\n') {
					theLength -= 2;
					theInfo[theLength] = '\0';
				}
				message = PyUnicode_FromString(
					"DLL load failed: ");

				PyUnicode_AppendAndDel(&message, 
					PyUnicode_FromUnicode(
						theInfo, 
						theLength));
			}
			PyErr_SetObject(PyExc_ImportError, message);
			Py_XDECREF(message);
			return NULL;
		} else {
			char buffer[256];

#ifdef _DEBUG
			PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll",
#else
			PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll",
#endif
				      PY_MAJOR_VERSION,PY_MINOR_VERSION);
			import_python = GetPythonImport(hDLL);

			if (import_python &&
			    strcasecmp(buffer,import_python)) {
				PyOS_snprintf(buffer, sizeof(buffer),
					      "Module use of %.150s conflicts "
					      "with this version of Python.",
					      import_python);
				PyErr_SetString(PyExc_ImportError,buffer);
				FreeLibrary(hDLL);
				return NULL;
			}
		}
		p = GetProcAddress(hDLL, funcname);
	}

	return p;
}
Exemplo n.º 22
0
VOID
__cdecl
main(
    IN ULONG argc,
    IN PCHAR argv[]
    )

{
    ULONG FileSpecIndex;
    CHAR DirectorySpec[256];
    PCHAR FileSpec;

    ULONG StartTick;
    ULONG StopTick;

    //
    //  Check for the statistics switch
    //

    if ((argc > 1) && (!strcmp(argv[1],"/s") || !strcmp(argv[1],"/S"))) {

        Statistics = TRUE;
        argc--;
        argv++;
    }

    //
    //  Check for the verbose switch
    //

    if ((argc > 1) && (!strcmp(argv[1],"/v") || !strcmp(argv[1],"/V"))) {

        Verbose = TRUE;
        argc--;
        argv++;
    }

    //
    //  Check for the compress or decompress switch.
    //

    if ((argc > 1) && (!strcmp(argv[1],"/c") || !strcmp(argv[1],"/C"))) {

        if (!strcmp(argv[1],"/c")) { WriteOutputFile = FALSE; } else { WriteOutputFile = TRUE;  }

        //
        //  Check for the minimum number of arguments for compression
        //

        if (argc < 4) { PrintSyntax(); }

        if (!strcmp(argv[2],"/LZOPT")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZOPT;
            StatisticsRoutine = StatisticsLZOPT;
            ResetStatistics   = ResetStatisticsLZOPT;
            strcpy( FileExtension, ".CLZOPT");

        } else if (!strcmp(argv[2],"/LZNT1")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZNT1;
            StatisticsRoutine = StatisticsLZNT1;
            ResetStatistics   = ResetStatisticsLZNT1;
            strcpy( FileExtension, ".CLZNT1");

        } else if (!strcmp(argv[2],"/LZDC1")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZDC;
            StatisticsRoutine = StatisticsLZDC1;
            ResetStatistics   = ResetStatisticsLZDC1;
            strcpy( FileExtension, ".CLZDC1");

            MatchFunction     = LZDC1FindMatch;

        } else if (!strcmp(argv[2],"/LZDC2")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZDC;
            StatisticsRoutine = StatisticsLZDC2;
            ResetStatistics   = ResetStatisticsLZDC2;
            strcpy( FileExtension, ".CLZDC2");

            MatchFunction     = LZDC2FindMatch;

        } else if (!strcmp(argv[2],"/LZRW1")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZRW;
            StatisticsRoutine = StatisticsLZRW1;
            ResetStatistics   = ResetStatisticsLZRW1;
            strcpy( FileExtension, ".CLZRW1");

            MatchFunction     = LZRW1FindMatch;

        } else if (!strcmp(argv[2],"/LZRW2")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZRW;
            StatisticsRoutine = StatisticsLZRW2;
            ResetStatistics   = ResetStatisticsLZRW2;
            strcpy( FileExtension, ".CLZRW2");

            MatchFunction     = LZRW2FindMatch;

        } else if (!strcmp(argv[2],"/DBLS")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressMRCF;
            StatisticsRoutine = StatisticsMRCF;
            ResetStatistics   = ResetStatisticsMRCF;
            strcpy( FileExtension, ".CDBLS");

            MatchFunction     = MrcfFindMatchStandard;

            UncompressedBufferSize = 512;

        } else if (!strcmp(argv[2],"/DBLSOPT")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressMRCF;
            StatisticsRoutine = StatisticsMRCF;
            ResetStatistics   = ResetStatisticsMRCF;
            strcpy( FileExtension, ".CDBLSOPT");

            MatchFunction     = MrcfFindOptimalMatch;

            UncompressedBufferSize = 512;

        } else if (!strcmp(argv[2],"/MRCF")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressMRCF;
            StatisticsRoutine = StatisticsMRCF;
            ResetStatistics   = ResetStatisticsMRCF;
            strcpy( FileExtension, ".CMRCF");

            MatchFunction     = MrcfFindMatchStandard;

        } else if (!strcmp(argv[2],"/MRCFOPT")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressMRCF;
            StatisticsRoutine = StatisticsMRCFOPT;
            ResetStatistics   = ResetStatisticsMRCFOPT;
            strcpy( FileExtension, ".CMRCFOPT");

            MatchFunction     = MrcfFindOptimalMatch;

        } else if (!strcmp(argv[2],"/JMS")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressJMS;
            StatisticsRoutine = StatisticsJMS;
            ResetStatistics   = ResetStatisticsJMS;
            strcpy( FileExtension, ".CJMS");

            MatchFunction     = JMSFindMatch;

        } else if (!strcmp(argv[2],"/JMSOPT")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressJMS;
            StatisticsRoutine = StatisticsJMSOPT;
            ResetStatistics   = ResetStatisticsJMSOPT;
            strcpy( FileExtension, ".CJMSOPT");

            MatchFunction     = JMSOPTFindMatch;

        } else if (!strcmp(argv[2],"/LZ115")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZ115;
            StatisticsRoutine = StatisticsLZ115;
            ResetStatistics   = ResetStatisticsLZ115;
            strcpy( FileExtension, ".CLZ115");

            MatchFunction     = LZ115FindMatch;

        } else if (!strcmp(argv[2],"/LZ115OPT")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZ115;
            StatisticsRoutine = StatisticsLZ115OPT;
            ResetStatistics   = ResetStatisticsLZ115OPT;
            strcpy( FileExtension, ".CLZ115OPT");

            MatchFunction     = LZ115OPTFindMatch;

        } else if (!strcmp(argv[2],"/LZ11HALF")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZ11HALF;
            StatisticsRoutine = StatisticsLZ11HALF;
            ResetStatistics   = ResetStatisticsLZ11HALF;
            strcpy( FileExtension, ".CLZ11HALF");

            MatchFunction     = LZ11HALFFindMatch;

        } else if (!strcmp(argv[2],"/LZ11HALFOPT")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZ11HALF;
            StatisticsRoutine = StatisticsLZ11HALFOPT;
            ResetStatistics   = ResetStatisticsLZ11HALFOPT;
            strcpy( FileExtension, ".CLZ11HALFOPT");

            MatchFunction     = LZ11HALFOPTFindMatch;

        } else if (!strcmp(argv[2],"/LZKM1")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZKM;
            StatisticsRoutine = StatisticsLZKM1;
            ResetStatistics   = ResetStatisticsLZKM1;
            strcpy( FileExtension, ".CLZKM1");

            MatchFunction     = LZKM1FindMatch;

        } else if (!strcmp(argv[2],"/LZKM2")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZKM;
            StatisticsRoutine = StatisticsLZKM2;
            ResetStatistics   = ResetStatisticsLZKM2;
            strcpy( FileExtension, ".CLZKM2");

            MatchFunction     = LZKM2FindMatch;

        } else if (!strcmp(argv[2],"/LZKMOPT")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZKM;
            StatisticsRoutine = StatisticsLZKMOPT;
            ResetStatistics   = ResetStatisticsLZKMOPT;
            strcpy( FileExtension, ".CLZKMOPT");

            MatchFunction     = LZKMOPTFindMatch;

        } else if (!strcmp(argv[2],"/LZKM1512")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZKM;
            StatisticsRoutine = StatisticsLZKM1;
            ResetStatistics   = ResetStatisticsLZKM1;
            strcpy( FileExtension, ".CLZKM1512");

            MatchFunction     = LZKM1FindMatch;

            UncompressedBufferSize = 512;

        } else if (!strcmp(argv[2],"/LZKM2512")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZKM;
            StatisticsRoutine = StatisticsLZKM2;
            ResetStatistics   = ResetStatisticsLZKM2;
            strcpy( FileExtension, ".CLZKM2512");

            MatchFunction     = LZKM2FindMatch;

            UncompressedBufferSize = 512;

        } else if (!strcmp(argv[2],"/LZKMOPT512")) {

            ActionRoutine     = CompressFile;
            CompressRoutine   = CompressLZKM;
            StatisticsRoutine = StatisticsLZKMOPT;
            ResetStatistics   = ResetStatisticsLZKMOPT;
            strcpy( FileExtension, ".CLZKMOPT512");

            MatchFunction     = LZKMOPTFindMatch;

            UncompressedBufferSize = 512;

        } else { PrintSyntax(); };

        //sscanf( argv[3], strncmp( argv[3], "0x", 2 ) ? "%ld" : "%lx", &UncompressedBufferSize );

        FileSpecIndex = 3;

    } else if ((argc > 1) && (!strcmp(argv[1],"/d") || !strcmp(argv[1],"/D"))) {

        if (!strcmp(argv[1],"/d")) { WriteOutputFile = FALSE; } else { WriteOutputFile = TRUE;  }

        //
        //  Check for the minimum number of arguments for decompression
        //

        if (argc < 4) { PrintSyntax(); }

        if (!strcmp(argv[2],"/12.4")) {

            ActionRoutine     = DecompressFile;
            DecompressRoutine = DecompressLZRW;
            StatisticsRoutine = StatisticsLZRW1;
            ResetStatistics   = ResetStatisticsLZRW1;
            strcpy( FileExtension, ".D12.4");

        } else if (!strcmp(argv[2],"/11.5")) {

            ActionRoutine     = DecompressFile;
            DecompressRoutine = DecompressLZ115;
            StatisticsRoutine = StatisticsLZ115;
            ResetStatistics   = ResetStatisticsLZ115;
            strcpy( FileExtension, ".D11.5");

        } else if (!strcmp(argv[2],"/11HALF")) {

            ActionRoutine     = DecompressFile;
            DecompressRoutine = DecompressLZ11HALF;
            StatisticsRoutine = StatisticsLZ11HALF;
            ResetStatistics   = ResetStatisticsLZ11HALF;
            strcpy( FileExtension, ".D11HALF");

        } else if (!strcmp(argv[2],"/LZKM")) {

            ActionRoutine     = DecompressFile;
            DecompressRoutine = DecompressLZKM;
            StatisticsRoutine = StatisticsLZKM1;
            ResetStatistics   = ResetStatisticsLZKM1;
            strcpy( FileExtension, ".DLZKM");

        } else if (!strcmp(argv[2],"/MRCF")) {

            ActionRoutine     = DecompressFile;
            DecompressRoutine = DecompressMRCF;
            StatisticsRoutine = StatisticsMRCF;
            strcpy( FileExtension, ".DMRCF");

        } else if (!strcmp(argv[2],"/JMS")) {

            ActionRoutine     = DecompressFile;
            DecompressRoutine = DecompressJMS;
            StatisticsRoutine = StatisticsJMS;
            strcpy( FileExtension, ".DJMS");

        } else { PrintSyntax(); };

        FileSpecIndex = 3;

    } else {

        PrintSyntax();
    }

    if (Statistics) { ResetStatistics(); }

    //
    //  Now do the action routine for each file spec
    //

    StartTick = GetTickCount();

    for (FileSpecIndex; FileSpecIndex < argc; FileSpecIndex += 1) {

        (VOID)GetFullPathName( argv[FileSpecIndex], 256, DirectorySpec, &FileSpec );

        DoAction( DirectorySpec, FileSpec );
    }

    StopTick = GetTickCount();

    //
    //  Now print the final statistics
    //

    if (Statistics) { StatisticsRoutine(); }

    {
        LONGLONG Percent = 100;
        ULONG TotalTicks;

        if (TotalUncompressedSize != 0) {

            Percent = TotalCompressedSize * 100 / TotalUncompressedSize;
        }

        TotalTicks = StopTick - StartTick;

        printf("\n");
        printf("Total File Count        = %8ld\n", (ULONG)TotalFileCount);
        printf("      Compressed Size   = %8ld\n", (ULONG)TotalCompressedSize);
        printf("      Uncompressed Size = %8ld\n", (ULONG)TotalUncompressedSize);
        printf("                        = %8ld%%\n", (ULONG)Percent);
        printf("                        = %8ld ms\n", TotalTicks);
    }

    return;
}
Exemplo n.º 23
0
BOOL 
ProcessPlugIn(
	NDAS_LOGICALUNIT_ADDRESS Address,
	int argc, 
	TCHAR** argv)
{
	if (argc < 1)
	{
		usage();
		return FALSE;
	}

	PNDAS_LOGICALUNIT_DESCRIPTOR logicalUnitDescriptor = NULL;

	if (0 == lstrcmpi(_T("filedisk"), argv[0]))
	{
		if (argc != 4 )
		{
			usage();
			return FALSE;
		}

		LPCTSTR filePath = argv[1];
		// const WCHAR FileNamePrefix[] = L"\\\\?\\";
		const WCHAR FileNamePrefix[] = L"\\??\\";

#ifdef UNICODE

		DWORD fileFullPathLength = GetFullPathName(filePath, 0, NULL, NULL);
		if (0 == fileFullPathLength)
		{
			_tprintf(_T("Error: GetFullPathName failed!\n"));
			return FALSE;
		}

		fileFullPathLength += RTL_NUMBER_OF(FileNamePrefix);

		LPWSTR fileFullPathBuffer = static_cast<LPWSTR>(HeapAlloc(
			GetProcessHeap(),
			HEAP_ZERO_MEMORY,
			fileFullPathLength * sizeof(WCHAR)));

		if (!fileFullPathBuffer)
		{
			_tprintf(_T("Error: Out of memory!\n"));
			SetLastError(ERROR_OUTOFMEMORY);
			return FALSE;
		}

		LPWSTR fileFullPath = NULL;

		size_t remainingLength = 0;

		StringCchCopyExW(
			fileFullPathBuffer,
			fileFullPathLength,
			FileNamePrefix,
			&fileFullPath,
			&remainingLength,
			STRSAFE_IGNORE_NULLS);

		GetFullPathName(
			filePath, 
			static_cast<DWORD>(remainingLength), 
			fileFullPath,
			NULL);

#else
		C_ASSERT(FALSE && "not implemented");
#endif
		_tprintf(_T("File Name=%s\n"), fileFullPathBuffer);
		_tprintf(_T("Length=%d bytes\n"), fileFullPathLength * sizeof(WCHAR));

		DWORD descriptorLength = 
			FIELD_OFFSET(FILEDISK_DESCRIPTOR, FilePath) +
			fileFullPathLength * sizeof(WCHAR);

		PFILEDISK_DESCRIPTOR descriptor = 
			static_cast<PFILEDISK_DESCRIPTOR>(
				HeapAlloc(
					GetProcessHeap(),
					HEAP_ZERO_MEMORY,
					descriptorLength));

		if (NULL == descriptor)
		{
			_tprintf(_T("Error: Out of memory!\n"));
			HeapFree(GetProcessHeap(), 0, fileFullPathBuffer);
			SetLastError(ERROR_OUTOFMEMORY);
			return FALSE;
		}

		descriptor->Header.Version = sizeof(NDAS_LOGICALUNIT_DESCRIPTOR);
		descriptor->Header.Size = descriptorLength;
		descriptor->Header.Address = Address;
		descriptor->Header.Type = NdasExternalType;
		descriptor->Header.ExternalTypeGuid = NDASPORT_FILEDISK_TYPE_GUID;

		descriptor->LogicalBlockAddress.QuadPart = 750LL * 1024LL * 1024LL * 1024LL / 512LL;
		descriptor->BytesPerBlock = 512;
		descriptor->FileDiskFlags = FILEDISK_FLAG_USE_SPARSE_FILE;

		CopyMemory(
			descriptor->FilePath,
			fileFullPathBuffer,
			fileFullPathLength * sizeof(WCHAR));

		HeapFree(GetProcessHeap(), 0, fileFullPathBuffer);

		logicalUnitDescriptor = 
			reinterpret_cast<PNDAS_LOGICALUNIT_DESCRIPTOR>(
				static_cast<PFILEDISK_DESCRIPTOR>(descriptor));
	}
	else if (0 == lstrcmpi(_T("ramdisk"), argv[0]))
	{
		return TRUE;
	}
	else if (0 == lstrcmpi(_T("ndasdlu"), argv[0]))
	{
		logicalUnitDescriptor = ProcessPlugIn_Dlu(Address, argc - 1, argv + 1);

		if (NULL == logicalUnitDescriptor)
		{
			return FALSE;
		}
	}
	else
	{
		//
		// Reserve 2MB from the end
		//
		LARGE_INTEGER logicalBlockAddress;
		logicalBlockAddress.QuadPart = -2 * 1024 * 1024 / 512;

		NDAS_DEVICE_IDENTIFIER ndasDeviceIdentifier;
		BOOL success = ParseNdasDeviceId(argv[0], &ndasDeviceIdentifier);

		if (!success)
		{
			_tprintf(_T("Error: NDAS Device Identifier is invalid.\n\n"));
			usage();
			return FALSE;
		}

		ACCESS_MASK accessMode;
		if (0 == lstrcmpi(_T("ro"), argv[1]))
		{
			accessMode = GENERIC_READ;
		}
		else if (0 == lstrcmpi(_T("rw"), argv[1]))
		{
			accessMode = GENERIC_READ | GENERIC_WRITE;
		}
		else
		{
			_tprintf(_T("Error: Access mode is invalid or not specified.\n\n"));
			usage();
			return FALSE;
		}

		if (argc > 2 && 0 == lstrcmpi(_T("noreserve"), argv[2]))
		{
			logicalBlockAddress.QuadPart = 0;
			_tprintf(_T("No reserve mode\n"));
		}

#ifdef _DEBUG
		_tprintf(_T("(%d,%d,%d) %02X-%02X-%02X-%02X-%02X-%02X %d\n"),
				 Address.PathId,
				 Address.TargetId,
				 Address.Lun,			
				 ndasDeviceIdentifier.Identifier[0],
				 ndasDeviceIdentifier.Identifier[1],
				 ndasDeviceIdentifier.Identifier[2],
				 ndasDeviceIdentifier.Identifier[3],
				 ndasDeviceIdentifier.Identifier[4],
				 ndasDeviceIdentifier.Identifier[5],
				 ndasDeviceIdentifier.UnitNumber);
#endif

		logicalUnitDescriptor = NdasPortCtlBuildNdasAtaDeviceDescriptor(
			Address,
			0,
			&ndasDeviceIdentifier,
			0, 
			0,
			accessMode,
			0,
			&logicalBlockAddress);

		if (NULL == logicalUnitDescriptor)
		{
			_tprintf(_T("Error: Out of memory!\n"));
			return FALSE;
		}
	}
	
	_ASSERT(NULL != logicalUnitDescriptor);

	XTL::AutoProcessHeap logicalUnitDescriptorPtr = logicalUnitDescriptor;

	XTL::AutoFileHandle handle = NdasPortCtlCreateControlDevice(GENERIC_READ | GENERIC_WRITE);
	if (handle.IsInvalid())
	{
		ErrorHolder lastError;
		
		_tprintf(_T("Opening NDAS Port device file failed.\n"));
		_tprintf(_T("Error %u (0x%X): %hs\n"), 
			lastError.GetCode(), 
			lastError.GetCode(), 
			lastError.GetDescriptionA());

		return FALSE;
	}

	BOOL success = NdasPortCtlGetPortNumber(
		handle, 
		&logicalUnitDescriptor->Address.PortNumber);

	if (!success)
	{
		ErrorHolder lastError;

		_tprintf(_T("Getting the port number failed.\n"));
		_tprintf(_T("Error %u (0x%X): %hs\n"), 
			lastError.GetCode(), 
			lastError.GetCode(), 
			lastError.GetDescriptionA());
		return FALSE;
	}

	success = NdasPortCtlPlugInLogicalUnit(
		handle,
		logicalUnitDescriptor);

	if (!success)
	{
		ErrorHolder lastError;

		_tprintf(_T("PlugIn failed.\n"));
		_tprintf(_T("Error %u (0x%X): %hs\n"), 
			lastError.GetCode(), 
			lastError.GetCode(), 
			lastError.GetDescriptionA());
		return FALSE;
	}

	return TRUE;
}
Exemplo n.º 24
0
int CTabBarClass::PrepareTab(CTab& pTab, CVirtualConsole *apVCon)
{
	int iTabIcon = -1;

	#ifdef _DEBUG
	if (this != gpConEmu->mp_TabBar)
	{
		_ASSERTE(this == gpConEmu->mp_TabBar);
	}
	#endif

	MCHKHEAP
	// get file name
	TCHAR dummy[MAX_PATH*2];
	TCHAR fileName[MAX_PATH+4]; fileName[0] = 0;
	TCHAR szFormat[32];
	TCHAR szEllip[MAX_PATH+1];
	//wchar_t /**tFileName=NULL,*/ *pszNo=NULL, *pszTitle=NULL;
	int nSplit = 0;
	int nMaxLen = 0; //gpSet->nTabLenMax - _tcslen(szFormat) + 2/* %s */;
	int origLength = 0; //_tcslen(tFileName);

	CRealConsole* pRCon = apVCon ? apVCon->RCon() : NULL;
	bool bIsFar = pRCon ? pRCon->isFar() : false;

	// Far 4040 - new "Desktop" window type has "0" index
	if (apVCon && (pTab->Info.nFarWindowID == 0 || pTab->Type() == fwt_Panels))
	{
		iTabIcon = apVCon->RCon()->GetRootProcessIcon();
	}

	LPCWSTR pszTabName = pRCon->GetTabTitle(pTab);

	// That will be Far Manager panels or simple consoles (cmd, posh, bash, etc.)
	if (pTab->Name.Empty() || (pTab->Type() == fwt_Panels))
	{
		//_tcscpy(szFormat, _T("%s"));
		lstrcpyn(szFormat,
			bIsFar ? gpSet->szTabPanels
			: gpSet->szTabConsole,
			countof(szFormat));
		// Modified console contents - tab suffix
		// Not only Far manager windows but simple consoles also
		if (gpSet->szTabModifiedSuffix[0] && (pTab->Flags() & fwt_ModifiedFarWnd))
		{
			if ((_tcslen(szFormat) + _tcslen(gpSet->szTabModifiedSuffix)) < countof(szFormat))
			{
				wcscat_c(szFormat, gpSet->szTabModifiedSuffix);
			}
		}
		nMaxLen = gpSet->nTabLenMax - _tcslen(szFormat) + 2/* %s */;

		lstrcpyn(fileName, pszTabName, countof(fileName));

		if (gpSet->pszTabSkipWords && *gpSet->pszTabSkipWords)
		{
			StripWords(fileName, gpSet->pszTabSkipWords);
		}
		origLength = _tcslen(fileName);
		//if (origLength>6) {
		//    // Чтобы в заголовке было что-то вроде "{C:\Program Fil...- Far"
		//    //                              вместо "{C:\Program F...} - Far"
		//	После добавления суффиков к заголовку фара - оно уже влезать не будет в любом случае... Так что если панели - '...' строго ставить в конце
		//    if (lstrcmp(tFileName + origLength - 6, L" - Far") == 0)
		//        nSplit = nMaxLen - 6;
		//}
	}
	else
	{

		LPTSTR tFileName = NULL;
		if (GetFullPathName(pszTabName, countof(dummy), dummy, &tFileName) && tFileName && *tFileName)
			lstrcpyn(fileName, tFileName, countof(fileName));
		else
			lstrcpyn(fileName, pszTabName, countof(fileName));

		if (pTab->Type() == fwt_Editor)
		{
			if (pTab->Flags() & fwt_ModifiedFarWnd)
				lstrcpyn(szFormat, gpSet->szTabEditorModified, countof(szFormat));
			else
				lstrcpyn(szFormat, gpSet->szTabEditor, countof(szFormat));
		}
		else if (pTab->Type() == fwt_Viewer)
		{
			lstrcpyn(szFormat, gpSet->szTabViewer, countof(szFormat));
		}
		else
		{
			_ASSERTE(FALSE && "Must be processed in previous branch");
			lstrcpyn(szFormat, bIsFar ? gpSet->szTabPanels : gpSet->szTabConsole, countof(szFormat));
		}
	}

	// restrict length
	if (!nMaxLen)
		nMaxLen = gpSet->nTabLenMax - _tcslen(szFormat) + 2/* %s */;

	if (!origLength)
		origLength = _tcslen(fileName);
	if (nMaxLen<15) nMaxLen=15; else if (nMaxLen>=MAX_PATH) nMaxLen=MAX_PATH-1;

	if (origLength > nMaxLen)
	{
		/*_tcsnset(fileName, _T('\0'), MAX_PATH);
		_tcsncat(fileName, tFileName, 10);
		_tcsncat(fileName, _T("..."), 3);
		_tcsncat(fileName, tFileName + origLength - 10, 10);*/
		//if (!nSplit)
		//    nSplit = nMaxLen*2/3;
		//// 2009-09-20 Если в заголовке нет расширения (отсутствует точка)
		//const wchar_t* pszAdmin = gpSet->szAdminTitleSuffix;
		//const wchar_t* pszFrom = tFileName + origLength - (nMaxLen - nSplit);
		//if (!wcschr(pszFrom, L'.') && (*pszAdmin && !wcsstr(tFileName, pszAdmin)))
		//{
		//	// то троеточие ставить в конец, а не середину
		//	nSplit = nMaxLen;
		//}
		// "{C:\Program Files} - Far 2.1283 Administrator x64"
		// После добавления суффиков к заголовку фара - оно уже влезать не будет в любом случае... Так что если панели - '...' строго ставить в конце
		nSplit = nMaxLen;
		_tcsncpy(szEllip, fileName, nSplit); szEllip[nSplit]=0;
		szEllip[nSplit] = L'\x2026' /*"…"*/;
		szEllip[nSplit+1] = 0;
		//_tcscat(szEllip, L"\x2026" /*"…"*/);
		//_tcscat(szEllip, tFileName + origLength - (nMaxLen - nSplit));
		//tFileName = szEllip;
		lstrcpyn(fileName, szEllip, countof(fileName));
	}

	// szFormat различается для Panel/Viewer(*)/Editor(*)
	// Пример: "%i-[%s] *"
	////pszNo = wcsstr(szFormat, L"%i");
	////pszTitle = wcsstr(szFormat, L"%s");
	////if (pszNo == NULL)
	////	_wsprintf(fileName, SKIPLEN(countof(fileName)) szFormat, tFileName);
	////else if (pszNo < pszTitle || pszTitle == NULL)
	////	_wsprintf(fileName, SKIPLEN(countof(fileName)) szFormat, pTab->Pos, tFileName);
	////else
	////	_wsprintf(fileName, SKIPLEN(countof(fileName)) szFormat, tFileName, pTab->Pos);
	//wcscpy(pTab->Name, fileName);
	const TCHAR* pszFmt = szFormat;
	TCHAR* pszDst = dummy;
	TCHAR* pszStart = pszDst;
	TCHAR* pszEnd = dummy + countof(dummy) - 1; // в конце еще нужно зарезервировать место для '\0'

	if (!pszFmt || !*pszFmt)
	{
		pszFmt = _T("%s");
	}
	*pszDst = 0;

	bool bRenamedTab = false;
	if (pTab->Flags() & fwt_Renamed)
	{
		if (wcsstr(pszFmt, L"%s") == NULL)
		{
			if (wcsstr(pszFmt, L"%n") != NULL)
				bRenamedTab = true;
			else
				pszFmt = _T("%s");
		}
	}

	TCHAR szTmp[64];
	CmdArg szArg;
	bool  bAppendAdmin = gpSet->isAdminSuffix() && (pTab->Flags() & fwt_Elevated);

	while (*pszFmt && pszDst < pszEnd)
	{
		if (*pszFmt == _T('%'))
		{
			pszFmt++;
			LPCTSTR pszText = NULL;
			switch (*pszFmt)
			{
				case _T('s'): case _T('S'):
					pszText = fileName;
					break;
				case _T('i'): case _T('I'):
					_wsprintf(szTmp, SKIPLEN(countof(szTmp)) _T("%i"), pTab->Info.nIndex);
					pszText = szTmp;
					break;
				case _T('p'): case _T('P'):
					if (!apVCon || !apVCon->RCon())
					{
						wcscpy_c(szTmp, _T("?"));
					}
					else
					{
						_wsprintf(szTmp, SKIPLEN(countof(szTmp)) _T("%u"), apVCon->RCon()->GetActivePID());
					}
					pszText = szTmp;
					break;
				case _T('c'): case _T('C'):
					{
						int iCon = gpConEmu->isVConValid(apVCon);
						if (iCon > 0)
							_wsprintf(szTmp, SKIPLEN(countof(szTmp)) _T("%u"), iCon);
						else
							wcscpy_c(szTmp, _T("?"));
						pszText = szTmp;
					}
					break;
				case _T('n'): case _T('N'):
					{
						pszText = bRenamedTab ? fileName : pRCon ? pRCon->GetActiveProcessName() : NULL;
						wcscpy_c(szTmp, (pszText && *pszText) ? pszText : L"?");
						pszText = szTmp;
					}
					break;
				case _T('d'): case _T('D'):
					{
						pszText = pRCon ? pRCon->GetConsoleCurDir(szArg) : NULL;
						if (!pszText || !*pszText)
							pszText = L"?";
					}
					break;
				case _T('a'): case _T('A'):
					pszText = bAppendAdmin ? gpSet->szAdminTitleSuffix : NULL;
					bAppendAdmin = false;
					break;
				case _T('%'):
					pszText = L"%";
					break;
				case 0:
					pszFmt--;
					break;
			}
			pszFmt++;
			if (pszText)
			{
				if ((*(pszDst-1) == L' ') && (*pszText == L' '))
					pszText = SkipNonPrintable(pszText);
				while (*pszText && pszDst < pszEnd)
				{
					*(pszDst++) = *(pszText++);
				}
			}
		}
		else if ((pszDst > pszStart) && (*(pszDst-1) == L' ') && (*pszFmt == L' '))
		{
			pszFmt++; // Avoid adding sequential spaces (e.g. if some macros was empty)
		}
		else
		{
			*(pszDst++) = *(pszFmt++);
		}
	}

	// Fin. Append smth else?
	if (bAppendAdmin)
	{
		LPCTSTR pszText = gpSet->szAdminTitleSuffix;
		if (pszText)
		{
			while (*pszText && pszDst < pszEnd)
			{
				*(pszDst++) = *(pszText++);
			}
		}
	}

	*pszDst = 0;

	#ifdef _DEBUG
	if (dummy[0] && *(pszDst-1) == L' ')
		*pszDst = 0;
	#endif

	pTab->SetLabel(dummy);

	MCHKHEAP;

	return iTabIcon;
}
Exemplo n.º 25
0
PUBLIC BOOL
CmdLine_Parse(s_CLONEPARMS *parm)
{
   BOOL gotSrcFn=FALSE,gotDstFn=FALSE;
   PSTR pszArg;
   UINT argc = Env_ParamCount();
   UINT iArg = 1;

   ZeroMemory(parm,sizeof(s_CLONEPARMS));
   parm->flags = PARM_FLAG_CLIMODE;

   while (iArg <= argc) {
      pszArg = Env_ParamStr(iArg);
      if (!pszArg) break; // can't happen.
      
      iArg++;
      if (pszArg[0]=='-') { // if option
         if (pszArg[1]=='-') {
            // verbose options
            char szItem[32];
            pszArg+=2;
            for (;;) {
               pszArg = VerboseSubOption(szItem,32,pszArg);
               if (szItem[0]==0) break;
               if (String_Compare(szItem,pszVOPTHELP)==0) {
                  return Usage(TRUE);
               } else if  (String_Compare(szItem,pszVOPTOUTPUT)==0) {
                  iArg = GetOutputOption(parm,iArg,gotDstFn);
                  if (iArg==0) return FALSE;
                  gotDstFn = TRUE;
               } else if  (String_Compare(szItem,pszVOPTKEEPUUID)==0) {
                  if (!GetOption(parm,iArg,PARM_FLAG_KEEPUUID,pszVOPTKEEPUUID)) return FALSE;
               } else if  (String_Compare(szItem,pszVOPTCOMPACT)==0) {
                  if (!GetOption(parm,iArg,PARM_FLAG_COMPACT,pszVOPTCOMPACT)) return FALSE;
               } else if  (String_Compare(szItem,pszVOPTNOMERGE)==0) {
                  if (!GetOption(parm,iArg,PARM_FLAG_NOMERGE,pszVOPTNOMERGE)) return FALSE;
               } else if  (String_Compare(szItem,pszVOPTREPART)==0) {
                  if (!GetOption(parm,iArg,PARM_FLAG_REPART,pszVOPTREPART)) return FALSE;
               } else if  (String_Compare(szItem,pszVOPTENLARGE)==0) {
                  iArg = GetEnlargeOption(parm,iArg);
                  if (iArg==0) return FALSE;
               } else {
                  return ArgError(RSTR(UNKOPT),iArg-1);
               }
            }
         } else {
            // single char options.
            CHAR c;
            pszArg++;
            c = *pszArg++;
            if (!c) return ArgError(RSTR(INVOPT),iArg-1);
            while (c) {
               if (c==pszCHAROPT[4]) { // 'h'
                  return Usage(TRUE);
               } else if (c==pszCHAROPT[0]) { // 'o'
                  iArg = GetOutputOption(parm,iArg,gotDstFn);
                  if (iArg==0) return FALSE;
                  gotDstFn = TRUE;
               } else if (c==pszCHAROPT[1]) { // 'k'
                  if (!GetOption(parm,iArg,PARM_FLAG_KEEPUUID,pszVOPTKEEPUUID)) return FALSE;
               } else if (c==pszCHAROPT[3]) { // 'c'
                  if (!GetOption(parm,iArg,PARM_FLAG_COMPACT,pszVOPTCOMPACT)) return FALSE;
               } else if (c==pszCHAROPT[5]) { // 'r'
                  if (!GetOption(parm,iArg,PARM_FLAG_REPART,pszVOPTREPART)) return FALSE;
               } else if (c==pszCHAROPT[2]) { // 'e'
                  iArg = GetEnlargeOption(parm,iArg);
                  if (iArg==0) return FALSE;
               } else {
                  return ArgError(RSTR(UNKOPT),iArg-1);
               }
               c = *pszArg++;
            }
         }
      } else if (gotSrcFn) {
         return ArgError(RSTR(SRCTWICE),iArg-1);
      } else {
         GetFullPathName(pszArg,1024,parm->srcfn,0);
         gotSrcFn = TRUE;
      }
   }
   if (!gotSrcFn) {
      return ArgError(RSTR(NEEDSRC),iArg-1);
   }
   if (!gotDstFn) {
      Env_GenerateCloneName(parm->dstfn,parm->srcfn);
   }
   GetFullPathName(parm->dstfn,1024,tmpfn,0);
   String_Copy(parm->dstfn, tmpfn, 1024);

   if (!(parm->flags & PARM_FLAG_ENLARGE)) parm->flags &= ~PARM_FLAG_REPART;

   return TRUE;
}
Exemplo n.º 26
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);
}
Exemplo n.º 27
0
/*
 * AccLoadProg - create a new process for debugging
 */
trap_retval ReqProg_load( void )
{
    char            *parm;
    char            *src;
    char            *dst;
    char            *endsrc;
    char            exe_name[PATH_MAX];
    char            ch;
    BOOL            rc;
    int             len;
    MYCONTEXT       con;
    thread_info     *ti;
    HANDLE          handle;
    prog_load_req   *acc;
    prog_load_ret   *ret;
    header_info     hi;
    WORD            stack;
    WORD            version;
    DWORD           pid;
    DWORD           pid_started;
    DWORD           cr_flags;
    char            *buff;
    size_t          nBuffRequired;
    char            *dll_name;
    char            *service_name;
    char            *dll_destination;
    char            *service_parm;

    acc = GetInPtr( 0 );
    ret = GetOutPtr( 0 );
    parm = GetInPtr( sizeof( *acc ) );

    /*
     * reset status variables
     */
    LastExceptionCode = -1;
    DebugString = NULL;
    DebugeeEnded = FALSE;
    RemoveAllThreads();
    FreeLibList();
    DidWaitForDebugEvent = FALSE;
    DebugeePid = 0;
    DebugeeTid = 0;
    SupportingExactBreakpoints = 0;

    /*
     * check if pid is specified
     */
    ParseServiceStuff( parm, &dll_name, &service_name, &dll_destination, &service_parm );
    pid = 0;
    src = parm;

    /*
    //  Just to be really safe!
    */
    nBuffRequired = GetTotalSize() + PATH_MAX + 16;
    buff = LocalAlloc( LMEM_FIXED, nBuffRequired );
    if( buff == NULL ) {
        ret->err = ERROR_NOT_ENOUGH_MEMORY;
        return( sizeof( *ret ) );
    }

    if( *src == '#' ) {
        src++;
        pid = strtoul( src, &endsrc, 16 );
        if( pid == 0 ) {
            pid = -1;
        }
        strcpy( buff, endsrc );
    } else {
        while( isdigit( *src ) ) {
            src++;
        }
        if( *src == 0 && src != parm ) {
            pid = atoi( parm );
        }
    }

    /*
     * get program to debug.  If the user has specified a pid, then
     * skip directly to doing a DebugActiveProcess
     */
    IsWOW = FALSE;
#if !defined( MD_x64 )
    IsDOS = FALSE;
#endif
    if( pid == 0 ) {
        ret->err = FindProgFile( parm, exe_name, NtExtList );
        if( ret->err != 0 ) {
            goto error_exit;
        }

        /*
         * Get type of application
         */
        handle = CreateFile( (LPTSTR)exe_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
        if( handle == INVALID_HANDLE_VALUE ) {
            ret->err = GetLastError();
            goto error_exit;
        }
        GetFullPathName( exe_name, MAX_PATH, CurrEXEName, NULL );

        /*
         * get the parm list
         */
        if( strchr( CurrEXEName, ' ' ) != NULL ) {
            strcpy( buff, "\"" );
            strcat( buff, CurrEXEName );
            strcat( buff, "\"" );
        } else {
            strcpy( buff, CurrEXEName );
        }
        dst = &buff[strlen( buff )];
        src = parm;
        while( *src != 0 ) {
            ++src;
        }
        // parm layout
        // <--parameters-->0<--program_name-->0<--arguments-->0
        //
        for( len = GetTotalSize() - sizeof( *acc ) - (src - parm) - 1; len > 0; --len ) {
            ch = *src;
            if( ch == 0 ) {
                ch = ' ';
            }
            *dst = ch;
            ++dst;
            ++src;
        }
        *dst = 0;

        cr_flags = DEBUG_ONLY_THIS_PROCESS;

        if( !GetEXEHeader( handle, &hi, &stack ) ) {
            ret->err = GetLastError();
            CloseHandle( handle );
            goto error_exit;
        }
        if( hi.sig == EXE_PE ) {
            if( IS_PE64( hi.u.peh ) ) {
                DebugeeSubsystem = PE64( hi.u.peh ).subsystem;
            } else {
                DebugeeSubsystem = PE32( hi.u.peh ).subsystem;
#if defined( MD_x64 )
                IsWOW = TRUE;
#endif
            }
            if( DebugeeSubsystem == SS_WINDOWS_CHAR ) {
                cr_flags |= CREATE_NEW_CONSOLE;
            }
#if !defined( MD_x64 )
        } else if( hi.sig == EXE_NE ) {
            IsWOW = TRUE;
            /*
             * find out the pid of WOW, if it is already running.
             */
            pVDMEnumProcessWOW( EnumWOWProcessFunc, (LPARAM)&pid );
            if( pid != 0 ) {
                version = LOWORD( GetVersion() );
                if( LOBYTE( version ) == 3 && HIBYTE( version ) < 50 ) {
                    int kill = MessageBox( NULL, TRP_NT_wow_warning, TRP_The_WATCOM_Debugger, MB_APPLMODAL + MB_YESNO );
                    if( kill == IDYES ) {
                        DWORD axs = PROCESS_TERMINATE+STANDARD_RIGHTS_REQUIRED;
                        HANDLE hprocess = OpenProcess( axs, FALSE, pid );

                        if( hprocess != 0 && TerminateProcess( hprocess, 0 ) ) {
                            CloseHandle( hprocess );
                            pid = 0;
                        }
                    }
                } else {
                    cr_flags |= CREATE_SEPARATE_WOW_VDM;
                    pid = 0; // always start a new VDM.
                }
            }
            if( pid != 0 ) {
                ret->err = GetLastError();
                CloseHandle( handle );
                goto error_exit;
            }
        } else {
            IsDOS = TRUE;
#endif
        }
        CloseHandle( handle );
    }

    /*
     * start the debugee
     */
    pid_started = pid;
    if( *dll_name ) {
        strcat( buff, LOAD_PROG_STR_DELIM );
        strcat( buff, LOAD_PROG_STR_DLLNAME );
        strcat( buff, dll_name );
    }
    if( *service_name ) {
        strcat( buff, LOAD_PROG_STR_DELIM );
        strcat( buff, LOAD_PROG_STR_SERVICE );
        strcat( buff, service_name );
    }
    if( *dll_destination ) {
        strcat( buff, LOAD_PROG_STR_DELIM );
        strcat( buff, LOAD_PROG_STR_COPYDIR );
        strcat( buff, dll_destination );
    }
    if( *service_parm ) {
        strcat( buff, LOAD_PROG_STR_DELIM );
        strcat( buff, LOAD_PROG_STR_SERVICEPARM );
        strcat( buff, service_parm );
    }
    ret->err = StartControlThread( buff, &pid_started, cr_flags );
    if( ret->err != 0 ) {
        goto error_exit;
    }
    /*
     * CREATE_PROCESS_DEBUG_EVENT will always be the first debug event.
     * If it is not, then something is horribly wrong.
     */
    rc = MyWaitForDebugEvent();
    if( !rc || ( DebugEvent.dwDebugEventCode != CREATE_PROCESS_DEBUG_EVENT ) || ( DebugEvent.dwProcessId != pid_started ) ) {
        ret->err = GetLastError();
        goto error_exit;
    }
    ProcessInfo.pid = DebugEvent.dwProcessId;
    ProcessInfo.process_handle = DebugEvent.u.CreateProcessInfo.hProcess;
    ProcessInfo.base_addr = DebugEvent.u.CreateProcessInfo.lpBaseOfImage;
    AddProcess( &hi );
    AddThread( DebugEvent.dwThreadId, DebugEvent.u.CreateProcessInfo.hThread, DebugEvent.u.CreateProcessInfo.lpStartAddress );
    DebugeePid = DebugEvent.dwProcessId;
    DebugeeTid = DebugEvent.dwThreadId;
    LastDebugEventTid = DebugEvent.dwThreadId;

#if defined( MD_x86 )
#ifdef WOW
    if( IsWOW ) {
        ret->flags = LD_FLAG_IS_PROT;
        ret->err = 0;
        ret->task_id = DebugeePid;
        /*
         * we use our own CS and DS as the Flat CS and DS, for lack
         * of anything better
         */
        FlatDS = GetDS();
        FlatCS = GetCS();
        if( !executeUntilVDMStart() ) {
            ret->err = GetLastError();
            goto error_exit;
        }
        if( pid ) {
            addAllWOWModules();
        } else {
            addKERNEL();
        }
        /*
         * we save the starting CS:IP of the WOW app, since we will use
         * it to force execution of code later
         */
        ti = FindThread( DebugeeTid );
        MyGetThreadContext( ti, &con );
        WOWAppInfo.segment = ( WORD ) con.SegCs;
        WOWAppInfo.offset = ( WORD ) con.Eip;
        con.SegSs = con.SegDs; // Wow lies about the stack segment.  Reset it
        con.Esp = stack;
        MySetThreadContext( ti, &con );
    } else if( IsDOS ) {
        // TODO! Clean up this code
        ret->flags = 0; //LD_FLAG_IS_PROT;
        ret->err = 0;
        ret->task_id = DebugeePid;
        /*
         * we use our own CS and DS as the Flat CS and DS, for lack
         * of anything better
         */
        FlatDS = GetDS();
        FlatCS = GetCS();
        if( !executeUntilVDMStart() ) {
            ret->err = GetLastError();
            goto error_exit;
        }
#if 0
        if( pid ) {
            addAllWOWModules();
        } else {
            addKERNEL();
        }
#endif
        /*
         * we save the starting CS:IP of the WOW app, since we will use
         * it to force execution of code later
         */
        ti = FindThread( DebugeeTid );
        MyGetThreadContext( ti, &con );
        WOWAppInfo.segment = ( WORD )con.SegCs;
        WOWAppInfo.offset = ( WORD )con.Eip;
        con.SegSs = con.SegDs; // Wow lies about the stack segment.  Reset it
        con.Esp = stack;
        MySetThreadContext( ti, &con );
    } else {
#else
    {
#endif
#else
    {
#endif
        LPVOID base;

        if( pid == 0 ) {
            base = (LPVOID)DebugEvent.u.CreateProcessInfo.lpStartAddress;
        } else {
            base = 0;
        }

        ret->flags = LD_FLAG_IS_PROT;
        ret->err = 0;
        ret->task_id = DebugeePid;
        if( executeUntilStart( pid != 0 ) ) {
            LPVOID old;
            /*
             * make the application load our DLL, so that we can have it
             * run code out of it.  One small note: this will not work right
             * if the app does not load our DLL at the same address the
             * debugger loaded it at!!!
             */

            ti = FindThread( DebugeeTid );
            MyGetThreadContext( ti, &con );
            old = (LPVOID)AdjustIP( &con, 0 );
            if( base != 0 ) {
                SetIP( &con, base );
            }
            MySetThreadContext( ti, &con );
            SetIP( &con, old );
            MySetThreadContext( ti, &con );
        }
        ti = FindThread( DebugeeTid );
        MyGetThreadContext( ti, &con );
#if defined( MD_x86 )
        FlatCS = con.SegCs;
        FlatDS = con.SegDs;
#endif
        ret->flags |= LD_FLAG_IS_BIG;
    }
    ret->flags |= LD_FLAG_HAVE_RUNTIME_DLLS;
    if( pid != 0 ) {
        ret->flags |= LD_FLAG_IS_STARTED;
    }
    ret->mod_handle = 0;

error_exit:
    if( buff != NULL ) {
        LocalFree( buff );
    }
    return( sizeof( *ret ) );

}

trap_retval ReqProg_kill( void )
{
    prog_kill_ret   *ret;

    ret = GetOutPtr( 0 );
    ret->err = 0;
    DelProcess( TRUE );
    StopControlThread();
    return( sizeof( *ret ) );
}
Exemplo n.º 28
0
API_EXPORT(void) ap_add_cgi_vars(request_rec *r)
{
    table *e = r->subprocess_env;

    ap_table_setn(e, "GATEWAY_INTERFACE", "CGI/1.1");
    ap_table_setn(e, "SERVER_PROTOCOL", r->protocol);
    ap_table_setn(e, "REQUEST_METHOD", r->method);
    ap_table_setn(e, "QUERY_STRING", r->args ? r->args : "");
    ap_table_setn(e, "REQUEST_URI", original_uri(r));

    /* Note that the code below special-cases scripts run from includes,
     * because it "knows" that the sub_request has been hacked to have the
     * args and path_info of the original request, and not any that may have
     * come with the script URI in the include command.  Ugh.
     */

    if (!strcmp(r->protocol, "INCLUDED")) {
	ap_table_setn(e, "SCRIPT_NAME", r->uri);
	if (r->path_info && *r->path_info) {
	    ap_table_setn(e, "PATH_INFO", r->path_info);
	}
    }
    else if (!r->path_info || !*r->path_info) {
	ap_table_setn(e, "SCRIPT_NAME", r->uri);
    }
    else {
	int path_info_start = ap_find_path_info(r->uri, r->path_info);

	ap_table_setn(e, "SCRIPT_NAME",
		      ap_pstrndup(r->pool, r->uri, path_info_start));

	ap_table_setn(e, "PATH_INFO", r->path_info);
    }

    if (r->path_info && r->path_info[0]) {
	/*
	 * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
	 * Need to re-escape it for this, since the entire URI was
	 * un-escaped before we determined where the PATH_INFO began.
	 */
	request_rec *pa_req;

	pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r);

	if (pa_req->filename) {
#ifdef WIN32
	    char buffer[HUGE_STRING_LEN];
#endif
	    char *pt = ap_pstrcat(r->pool, pa_req->filename, pa_req->path_info,
				  NULL);
#ifdef WIN32
	    /* We need to make this a real Windows path name */
	    GetFullPathName(pt, HUGE_STRING_LEN, buffer, NULL);
	    ap_table_setn(e, "PATH_TRANSLATED", ap_pstrdup(r->pool, buffer));
#else
	    ap_table_setn(e, "PATH_TRANSLATED", pt);
#endif
	}
	ap_destroy_sub_req(pa_req);
    }
}
Exemplo n.º 29
0
void
Analyzer::stop()
{
    LOG(INFO, "Analyzer: stopping");

    onProcessEventConnection.disconnect();
    onRegistryEventConnection.disconnect();
    onFileEventConnection.disconnect();
    onNetworkEventConnection.disconnect();

    if(captureNetworkPackets)
    {
        LOG(INFO, "Analyzer: stopping network dumper");
        networkPacketDumper->stop();
    }

    if(collectModifiedFiles)
    {
        LOG(INFO, "Analyzer: copying modified files");
        fileMonitor->setMonitorModifiedFiles(false);
        fileMonitor->copyCreatedFiles();
    }

    if(OptionsManager::getInstance()->getOption(L"server") != L"") { //only when connected to server
        if(collectModifiedFiles || captureNetworkPackets) //then we zip what we have and send to server
        {
            //if malicious && capture malicious set to false, then delete pcap
            if(malicious && (OptionsManager::getInstance()->getOption(L"capture-network-packets-malicious") == L"false")) {
                if(networkPacketDumper)
                    networkPacketDumper->deleteAdapterFiles();
            }
            //if benign && capture benign set to false, then delete pcap
            if(!malicious && (OptionsManager::getInstance()->getOption(L"capture-network-packets-benign") == L"false")) {
                if(networkPacketDumper)
                    networkPacketDumper->deleteAdapterFiles();
            }

            if(!malicious) {
                LOG(INFO, "Analyzer: deleting modified files");
                wchar_t* szFullPathDF = new wchar_t[1024];
                GetFullPathName(L"logs\\deleted_files", 1024, szFullPathDF, NULL);
                SHFILEOPSTRUCT deleteDeletedFilesDirectory;
                deleteDeletedFilesDirectory.hwnd = NULL;
                deleteDeletedFilesDirectory.pTo = NULL;
                deleteDeletedFilesDirectory.lpszProgressTitle = NULL;
                deleteDeletedFilesDirectory.wFunc = FO_DELETE;
                deleteDeletedFilesDirectory.pFrom = szFullPathDF;
                deleteDeletedFilesDirectory.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI;
                SHFileOperation(&deleteDeletedFilesDirectory);
                delete [] szFullPathDF;

                wchar_t* szFullPathMF = new wchar_t[1024];
                GetFullPathName(L"logs\\modified_files", 1024, szFullPathMF, NULL);
                SHFILEOPSTRUCT deleteModifiedFilesDirectory;
                deleteModifiedFilesDirectory.hwnd = NULL;
                deleteModifiedFilesDirectory.pTo = NULL;
                deleteModifiedFilesDirectory.lpszProgressTitle = NULL;
                deleteModifiedFilesDirectory.wFunc = FO_DELETE;
                deleteModifiedFilesDirectory.pFrom = szFullPathMF;
                deleteModifiedFilesDirectory.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI;
                SHFileOperation(&deleteModifiedFilesDirectory);
                delete [] szFullPathMF;
            }

            SYSTEMTIME st;
            GetLocalTime(&st);


            if((malicious && collectModifiedFiles) || (!malicious && (OptionsManager::getInstance()->getOption(L"capture-network-packets-benign") == L"true")) ||
                    (malicious && (OptionsManager::getInstance()->getOption(L"capture-network-packets-malicious") == L"true")))
            {

                wchar_t* szLogFileName = new wchar_t[1024];

                std::wstring log = L"capture_";
                log += boost::lexical_cast<std::wstring>(st.wDay);
                log += boost::lexical_cast<std::wstring>(st.wMonth);
                log += boost::lexical_cast<std::wstring>(st.wYear);
                log += L"_";
                log += boost::lexical_cast<std::wstring>(st.wHour);
                log += boost::lexical_cast<std::wstring>(st.wMinute);
                log += L".zip";
                GetFullPathName(log.c_str(), 1024, szLogFileName, NULL);

                bool compressed = compressLogDirectory(szLogFileName);
                if(server.isConnected() && compressed)
                {
                    LOG(INFO, "Analyzer: sending log file to server");
                    FileUploader uploader(server);
                    uploader.sendFile(szLogFileName);

                }
                if(compressed)
                {
                    DeleteFile(szLogFileName);
                }
                delete [] szLogFileName;
            }
        }

        /* Delete the log directory */
        LOG(INFO, "Analyzer: deleting logs");
        wchar_t* szFullPath = new wchar_t[1024];
        GetFullPathName(L"logs", 1024, szFullPath, NULL);
        SHFILEOPSTRUCT deleteLogDirectory;
        deleteLogDirectory.hwnd = NULL;
        deleteLogDirectory.pTo = NULL;
        deleteLogDirectory.lpszProgressTitle = NULL;
        deleteLogDirectory.wFunc = FO_DELETE;
        deleteLogDirectory.pFrom = szFullPath;
        deleteLogDirectory.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI;
        SHFileOperation(&deleteLogDirectory);
        delete [] szFullPath;
    }
    LOG(INFO, "Analyzer: stopped");
}
Exemplo n.º 30
0
int Language::Load()
{
    WIN32_FIND_DATA stFindFile;
    HANDLE hFindFile;
    HMODULE hPlugin;

    TCHAR szCurrentExe[MAX_PATH];
    TCHAR szCurrentDir[MAX_PATH];
    TCHAR szPluginDir[MAX_PATH];
    TCHAR szPluginTemplate[MAX_PATH];
    TCHAR szFullName[MAX_PATH];
    TCHAR *pFilePart;

    TCHAR szResString[MAX_PATH];

    // Get full path name of Netmon.exe
    GetModuleFileName(0, szCurrentExe, MAX_PATH);

    // Get base directory
    GetFullPathName(szCurrentExe, MAX_PATH, szCurrentDir, &pFilePart);
    *pFilePart = TEXT('\0');

    // Get plugin directory
    _tcscpy_s(szPluginDir, MAX_PATH, szCurrentDir);
    _tcscat_s(szPluginDir, MAX_PATH, TEXT("Lang\\"));

    // Get plugin template
    _tcscpy_s(szPluginTemplate, MAX_PATH, szPluginDir);
    _tcscat_s(szPluginTemplate, MAX_PATH, TEXT("*.dll"));

    // Find files
    hFindFile = FindFirstFile(szPluginTemplate, &stFindFile); // Fix when release

    if (hFindFile != INVALID_HANDLE_VALUE )
    {
        do
        {
            if (!(stFindFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) // If it's not a folder
            {
                _tcscpy_s(szFullName, MAX_PATH, szPluginDir);
                _tcscat_s(szFullName, MAX_PATH, stFindFile.cFileName);

                if ((hPlugin = LoadLibrary(szFullName)) != NULL )
                {
                    BOOL bValid = TRUE;
                    StringTable st;

                    // Read string table
                    for(int i = STRING_TABLE_MIN; i <= STRING_TABLE_MAX; i++)
                    {
                        if (LoadString(hPlugin, i, szResString, MAX_PATH) == 0 ) // String not exist
                        {
                            bValid = FALSE;
                            break;
                        }
                        else
                        {
                            st.Set(i, szResString);
                        }
                    }

                    if (bValid ) // All strings for this language are successfully loaded
                    {
                        _tables.push_back(st);
                    }

                    FreeLibrary(hPlugin);
                }
            }
        } while( FindNextFile(hFindFile, &stFindFile) != FALSE );

        FindClose(hFindFile);
    }

    return _tables.size();
}