Example #1
0
bool deleteFile(const char* path) {
	return DeleteFile(path)!=0;
}
Example #2
0
unsigned int __stdcall updateAll(void *parms)
{
	unsigned int ret = 0;
	OrangeFS_size fileSize;
	FileListHandler *syncList = FileListHandler::getInstance();
	MetadataHandler *metadataHandler = MetadataHandler::getInstance();
	wxString statusBarString = "Updated ";
	int numRetrieved = 0;
	int numCreated = 0;
	int numDeleted = 0;
	static int timesUpdated = 1;
	OrangeFS_ds_position ds_token;
	bool filesCreated = false;
	bool filesDeleted = false;
	bool syncFlag = false;

	mainFileListing = (char **) malloc(MAX_FILES * sizeof(char *));
	for (int i=0; i < MAX_FILES; i++)
	{	
		mainFileListing[i] = (char *) malloc(MAX_PATH);
		memset(mainFileListing[i], 0, MAX_PATH);
	}

	/* if the sync configuration has not been set, we'll wait for it and stay in the thread */
	do
	{
		if ( MAIN_APP->syncExists() )
		{
			syncFlag = true;
		}
		else
		{
			orangefs_debug_print("---- Unable to find sync configuration... Waiting 5 seconds ----\n");
#ifdef WIN32
			Sleep(5000);
#else
			sleep(5000);
#endif
			continue;
		}
	} while ( !syncFlag );

	/* register our local directory listener for changes to files locally */
	/* for now, we'll just monitor the root dir */
	MAIN_APP->setLocalSyncPath( MAIN_APP->getLocalSyncPath().substr(0, MAIN_APP->getLocalSyncPath().length()-1) );		/* set sync path without trailing '/' */

	orangefs_debug_print("Local sync path : %s\n", MAIN_APP->getLocalSyncPath().c_str());

	/* subscribe to changes on our local sync directory */
	changeHandler = new DirHandler();
	dirWatcher = new DirWatcher();
	dirWatcher->watchDirectory(MAIN_APP->getLocalSyncPath(), 
								FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE,
								changeHandler,
								false);

	/*****************************************/
	/*									     */
	/*		   MAIN SYNC UPDATE LOOP		 */
	/*										 */
	/*****************************************/
	do
	{
		ds_token = ORANGEFS_READDIR_START;
		filesCreated, filesDeleted = false;

		/* get a listing of all the files currently on the orangefs server at the subscribed directory/directories (for now, it's the root directory until we add different sync paths to the local config) */
		orangefs_find_files(&MAIN_APP->getMntentAt(0)->fs_id, MAIN_APP->getCred(), "/", &ds_token, MAX_FILES, &numRetrieved, mainFileListing, MAIN_APP->getAttr()); 

		/* set up the remote files runtime maps accessible by index or filename */
		for (int i=0; i < numRetrieved; i++)
		{
			wxString temp = mainFileListing[i];

			metadataHandler->addRemoteToRuntime(temp, i);
		}

		/* if the number of files changed, determine if file(s) was deleted or created */
		if (MAIN_APP->getNumFiles() != numRetrieved)
		{
			/* file(s) was deleted */
			if (numRetrieved < MAIN_APP->getNumFiles())
			{
				/* set a flag so we know the list control needs to be updated */
				filesDeleted = true;
				numDeleted = MAIN_APP->getNumFiles() - numRetrieved;
				orangefs_debug_print("NUM LOCAL : %d - NUM RETRIEVED : %d = NUM DELETED : %d\n", MAIN_APP->getNumFiles(), numRetrieved, numDeleted);
			}

			/* file(s) was created */
			if (numRetrieved > MAIN_APP->getNumFiles())
			{
				filesCreated = true;
				numCreated = numRetrieved - MAIN_APP->getNumFiles();
				orangefs_debug_print("NUM RETRIEVED: %d - NUM LOCAL : %d = NUM CREATED : %d\n", numRetrieved, MAIN_APP->getNumFiles(), numCreated);
			}
		}

		/**************************************************************************************/
		/* Here, we will check a few things to determine if things need to be updated locally */
		/*		-  compare the last modified times of the subscribed files on the server from */
		/*		   the last update to the current update, if they're different, something was */
		/*		   obviously changed and we'll do a low level scan and sync for the modified  */
		/*		   binary data																  */
		/**************************************************************************************/
		for (int i=0; i < numRetrieved; i++)
		{
			/* go through all the files saved locally */
			for (int j=0; j < metadataHandler->getNumFiles(); j++)
			{
				if ( !metadataHandler->getFileName(j).compare( metadataHandler->getRemoteFileName(i) ) )	/* we have found a file that is both on the server and locally stored */
				{
					if ( metadataHandler->getFileModTime( metadataHandler->getFileName(j) ) == MAIN_APP->getAttr()[i].mtime )
					{
						/* the mod times match, keep going until we find non-matching times */
						continue;
					}
					else
					{
						/* modified times don't match, update the modified time locally, and do low-level data copy */
						/* updateFileMetadata() not only adds the metadata to the application's data file, but updates all the hash maps that store the metadata during runtime */
						metadataHandler->updateFileMetadata(metadataHandler->getFileName(j), &MAIN_APP->getAttr()[i]);

						/****************************************************************************/
						/* FILES TO SYNC :															*/
						/*		local copy that needs updating : metadataHandler->getFileName(j)	*/
						/*		remote copy to sync data from  : mainFileListing[i]					*/
						/****************************************************************************/
						SyncType = SYNC_EXISTING;

						MAIN_APP->syncFile(metadataHandler->getFileName(j), MAIN_APP->getAttr()[i].size);	/* passing in size of remote file to sync */
						syncList->updateList(MAIN_APP->getFileName(i));
					}
				}
			}
		}

		/* find which files need to be created (if any) */
		if (filesCreated)
		{
			for (int i=0; i < numRetrieved; i++)
			{
				/* server file was not found locally, needs to be created/synced */
				if ( !metadataHandler->isServerOnLocal( metadataHandler->getRemoteFileName(i) ) )
				{
					SyncType = SYNC_NEW;

					orangefs_debug_print("FILE NAME : %s\n", metadataHandler->getRemoteFileName(i).c_str());

					/* sync the file/folder over, then add the file metadata to the data file and runtime maps */
					if ( MAIN_APP->getAttr()[i].objtype == OrangeFS_TYPE_DIRECTORY )
					{
						MAIN_APP->syncDir(metadataHandler->getRemoteFileName(i));
					}
					else 
					{
						MAIN_APP->syncFile(metadataHandler->getRemoteFileName(i), MAIN_APP->getAttr()[i].size);			
					}
					metadataHandler->addFileMetadata(metadataHandler->getRemoteFileName(i), &MAIN_APP->getAttr()[i]);
					syncList->updateList(metadataHandler->getRemoteFileName(i));
				}
			}
		}

		deleteIndexes.reserve(MAIN_APP->getNumFiles());		/* if all the files on the server were deleted, getNumFiles() would appropriately hold index for all of them */
		if (filesDeleted)
		{
			for (int i=0; i < MAIN_APP->getNumFiles(); i++)
			{
				/* the local file wasn't found on the server, delete locally */
				if ( !metadataHandler->isLocalOnServer( metadataHandler->getFileName(i) ) )
				{
					/* THIS ISN"T WORKING, GETS IN HERE EVERY TIME */

					orangefs_debug_print("---- ADDDED index : %d\n", i);
					deleteIndexes.push_back(i);
				}
			}

			orangefs_debug_print("NUM FILES FOR DELETE : %d\n", deleteIndexes.size());
			/* now we have the indexes of files stored locally to be deleted */
			for (int i=0; i < deleteIndexes.size(); i++)
			{
				/***********************************************************************************************/
				/* we will need to delete the actual file, and all of it's traces at the following locations : */
				/*																							   */
				/* 1) the physical file on the local hard disk												   */
				/* 2) the metadata entry from the metadata file												   */
				/* 3) the list control entry for the file													   */
				/* 4) the runtime maps																		   */
				/***********************************************************************************************/
				/* (1) */
				wxString fullPath = MAIN_APP->getLocalSyncPath();
				fullPath += metadataHandler->getFileName(i);
#ifdef WIN32
				DeleteFile(fullPath.c_str());
#elif
				remove(fullPath.c_str());
#endif
				/* (2) and (4) */
				metadataHandler->removeFile(metadataHandler->getFileName(i));

				/* (3) */
				MAIN_FRAME->fileHandler->removeListData(metadataHandler->getFileName(i));
			}
		}

#ifdef WIN32
		Sleep(5000);	/* Wait 5 seconds before checking for updates again */
#elif
		sleep(5000);	/* maybe in the future have the user set this value in the app configuration */
#endif

		stringstream ss;
		ss << timesUpdated;

		/* clear and refresh the status text */
		statusBarString.clear();
		statusBarString = "Updated ";

		statusBarString += ss.str();
		statusBarString += " times";
		MAIN_FRAME->setStatusbarText(statusBarString);
		timesUpdated++;
		
	}while(!MAIN_APP->stillUpdating());	/* keep checking for new files or existing file modifications on the subscribed dirs/files */


done_syncing:

	/* let the app know we're finished syncing */
	MAIN_APP->finishedSyncing(true);

	orangefs_debug_print("---- Syncing Completed ----\n");

	for (int i=0; i < MAX_FILES; i++)
	{	
		free(mainFileListing[i]);
	}
	free(mainFileListing);

	deleteIndexes.clear();

	LPDWORD exitCode;
	GetExitCodeThread(dirWatcher->getThreadHandle(), exitCode);
	TerminateThread(dirWatcher->getThreadHandle(), *exitCode);

	return ret;
}
Example #3
0
static BOOL
InUn(int remove, char *drivername, char *dllname, char *dll2name, char *dsname)
{
    char path[301], driver[300], attr[300], inst[400], inst2[400];
    WORD pathmax = sizeof (path) - 1, pathlen;
    DWORD usecnt, mincnt;

    if (SQLInstallDriverManager(path, pathmax, &pathlen)) {
	char *p;

	sprintf(driver, "%s;Driver=%s;Setup=%s;",
		drivername, dllname, dllname);
	p = driver;
	while (*p) {
	    if (*p == ';') {
		*p = '\0';
	    }
	    ++p;
	}
	usecnt = 0;
	SQLInstallDriverEx(driver, NULL, path, pathmax, &pathlen,
			   ODBC_INSTALL_INQUIRY, &usecnt);
	sprintf(driver, "%s;Driver=%s\\%s;Setup=%s\\%s;",
		drivername, path, dllname, path, dllname);
	p = driver;
	while (*p) {
	    if (*p == ';') {
		*p = '\0';
	    }
	    ++p;
	}
	sprintf(inst, "%s\\%s", path, dllname);
	if (dll2name) {
	    sprintf(inst2, "%s\\%s", path, dll2name);
	}
	if (!remove && usecnt > 0) {
	    /* first install try: copy over driver dll, keeping DSNs */
	    if (GetFileAttributes(dllname) != INVALID_FILE_ATTRIBUTES &&
		CopyFile(dllname, inst, 0) &&
		CopyOrDelModules(dllname, path, 0)) {
		if (dll2name != NULL) {
		    CopyFile(dll2name, inst2, 0);
		}
		return TRUE;
	    }
	}
	mincnt = remove ? 1 : 0;
	while (usecnt != mincnt) {
	    if (!SQLRemoveDriver(driver, TRUE, &usecnt)) {
		break;
	    }
	}
	if (remove) {
	    if (!SQLRemoveDriver(driver, TRUE, &usecnt)) {
		ProcessErrorMessages("SQLRemoveDriver");
		return FALSE;
	    }
	    if (!usecnt) {
		char buf[512];

		DeleteFile(inst);
		/* but keep inst2 */
		CopyOrDelModules(dllname, path, 1);
		if (!quiet) {
		    sprintf(buf, "%s uninstalled.", drivername);
		    MessageBox(NULL, buf, "Info",
			       MB_ICONINFORMATION|MB_OK|MB_TASKMODAL|
			       MB_SETFOREGROUND);
		}
	    }
	    if (nosys) {
		goto done;
	    }
	    sprintf(attr, "DSN=%s;", dsname);
	    p = attr;
	    while (*p) {
		if (*p == ';') {
		    *p = '\0';
		}
		++p;
	    }
	    SQLConfigDataSource(NULL, ODBC_REMOVE_SYS_DSN, drivername, attr);
	    goto done;
	}
	if (GetFileAttributes(dllname) == INVALID_FILE_ATTRIBUTES) {
	    return FALSE;
	}
	if (!CopyFile(dllname, inst, 0)) {
	    char buf[512];

	    sprintf(buf, "Copy %s to %s failed", dllname, inst);
	    MessageBox(NULL, buf, "CopyFile",
		       MB_ICONSTOP|MB_OK|MB_TASKMODAL|MB_SETFOREGROUND); 
	    return FALSE;
	}
	if (dll2name != NULL && !CopyFile(dll2name, inst2, 0)) {
	    char buf[512];

	    sprintf(buf, "Copy %s to %s failed", dll2name, inst2);
	    MessageBox(NULL, buf, "CopyFile",
		       MB_ICONSTOP|MB_OK|MB_TASKMODAL|MB_SETFOREGROUND); 
	    /* but go on hoping that an SQLite engine is in place */
	}
	if (!CopyOrDelModules(dllname, path, 0)) {
	    return FALSE;
	}
	if (!SQLInstallDriverEx(driver, path, path, pathmax, &pathlen,
				ODBC_INSTALL_COMPLETE, &usecnt)) {
	    ProcessErrorMessages("SQLInstallDriverEx");
	    return FALSE;
	}
	if (nosys) {
	    goto done;
	}
	sprintf(attr, "DSN=%s;", dsname);
	p = attr;
	while (*p) {
	    if (*p == ';') {
		*p = '\0';
	    }
	    ++p;
	}
	SQLConfigDataSource(NULL, ODBC_REMOVE_SYS_DSN, drivername, attr);
	if (!SQLConfigDataSource(NULL, ODBC_ADD_SYS_DSN, drivername, attr)) {
	    ProcessErrorMessages("SQLConfigDataSource");
	    return FALSE;
	}
    } else {
	ProcessErrorMessages("SQLInstallDriverManager");
	return FALSE;
    }
done:
    return TRUE;
}
Example #4
0
Application::Application(HINSTANCE _hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    MPQInit();
    instance = this;
    resources = NULL;
    imageLibrary = NULL;
    dotaLibrary = NULL;
    mainWindow = NULL;
    cache = NULL;
    hInstance = _hInstance;
    _loaded = false;

    root = String::getPath(getAppPath());
    cfg.read();

    warLoader = new MPQLoader("Custom_V1");
    warLoader->loadArchive(String::buildFullName(cfg.warPath, "war3.mpq"));
    warLoader->loadArchive(String::buildFullName(cfg.warPath, "war3x.mpq"));
    warLoader->loadArchive(String::buildFullName(cfg.warPath, "war3xlocal.mpq"));
    warLoader->loadArchive(String::buildFullName(cfg.warPath, "war3patch.mpq"));

    if (logCommand(lpCmdLine))
        return;

    ScriptType::initTypes();
    UpdateDialog::init(hInstance);

    INITCOMMONCONTROLSEX iccex;
    iccex.dwSize = sizeof iccex;
    iccex.dwICC = ICC_STANDARD_CLASSES | ICC_PROGRESS_CLASS |
                  ICC_BAR_CLASSES | ICC_TREEVIEW_CLASSES | ICC_LISTVIEW_CLASSES |
                  ICC_TAB_CLASSES | ICC_UPDOWN_CLASS | ICC_DATE_CLASSES;
    InitCommonControlsEx(&iccex);
    LoadLibrary("Riched20.dll");
    OleInitialize(NULL);

    String path = String::getPath(getAppPath());
    String resPath = String::buildFullName(path, "resources.mpq");
    String patchPath = String::buildFullName(path, "install.mpq");
    File* tOpen = File::open(resPath, File::READ);
    if (tOpen == NULL)
    {
        tOpen = File::open(patchPath, File::READ);
        if (tOpen)
        {
            delete tOpen;
            MoveFile(patchPath, resPath);
        }
    }
    else
        delete tOpen;
    resources = MPQArchive::open(resPath);
    MPQArchive* patch = MPQArchive::open(patchPath, File::READ);
    if (patch)
    {
        for (uint32 i = 0; i < patch->getHashSize(); i++)
        {
            char const* name = patch->getFileName(i);
            if (name)
            {
                MPQFile* source = patch->openFile(i, File::READ);
                if (source)
                {
                    MPQFile* dest = resources->openFile(name, File::REWRITE);
                    if (dest)
                    {
                        static uint8 buf[1024];
                        while (int length = source->read(buf, sizeof buf))
                            dest->write(buf, length);
                        delete dest;
                    }
                    delete source;
                }
            }
        }
        delete patch;
        DeleteFile(patchPath);
    }

    imageLibrary = new ImageLibrary(resources);

    cache = new CacheManager();
    dotaLibrary = new DotaLibrary();

#if 0
    File* dlog = File::open("diff.txt", File::REWRITE);
    for (int pt = 0; pt < 120; pt++)
    {
        String prev = "";
        bool different = false;
        for (int ver = 1; ver <= 80 && !different; ver++)
        {
            Dota* dota = dotaLibrary->getDota(makeVersion(6, ver));
            if (dota)
            {
                Dota::Hero* hero = dota->getHero(pt);
                if (hero)
                {
                    if (prev == "")
                        prev = hero->name;
                    else if (prev.icompare(hero->name))
                        different = true;
                }
            }
        }
        if (different)
        {
            dlog->printf("  Pt=%d\r\n", pt);
            prev = "";
            for (int ver = 1; ver <= 80; ver++)
            {
                Dota* dota = dotaLibrary->getDota(makeVersion(6, ver));
                if (dota)
                {
                    Dota::Hero* hero = dota->getHero(pt);
                    if (hero)
                    {
                        if (prev.icompare(hero->name))
                        {
                            dlog->printf("6.%02d = %s\r\n", ver, hero->name);
                            prev = hero->name;
                        }
                    }
                }
            }
        }
    }
    delete dlog;
#endif
#if 0
    dotaLibrary->getDota(parseVersion("6.79e"),
                         "K:\\Progs\\DotAReplay\\maps\\DotA v6.79e.w3x");
    WIN32_FIND_DATA data;
    String enumPath = "K:\\Progs\\DotAReplay\\maps";
    HANDLE hFind = FindFirstFile(String::buildFullName(enumPath, "*"), &data);
    BOOL success = (hFind != INVALID_HANDLE_VALUE);
    while (success)
    {
        String file(data.cFileName);
        if (String::getExtension(file).icompare(".w3x") == 0)
        {
            file.toLower();
            Array<String> sub;
            if (file.rfind("dota{{_| }allstars}?{_| }v(\\d)\\.(\\d\\d)([b-z]?)[^b-z]", 0, &sub) >= 0)
            {
                int major = sub[1].toInt();
                int minor = sub[2].toInt();
                int build = 0;
                if (!sub[3].isEmpty())
                    build = int(sub[3][0] - 'a');
                uint32 version = makeVersion(major, minor, build);

                dotaLibrary->getDota(version, String::buildFullName(enumPath, file));
            }
        }
        success = FindNextFile(hFind, &data);
    }
    FindClose(hFind);
#endif

    mainWindow = new MainWnd();

    mainWindow->postLoad();
    _loaded = true;

    if (lpCmdLine[0])
    {
        COPYDATASTRUCT cd;
        cd.dwData = MAINWND_OPEN_REPLAY;
        cd.cbData = strlen(lpCmdLine) + 1;
        cd.lpData = lpCmdLine;
        PostMessage(getMainWindow(), WM_COPYDATA_FAKE, NULL, (LPARAM) &cd);
    }
}
bool RecurseDeletePath(const char * a_path)
{
  WIN32_FIND_DATA findData;

  char path[MAX_PATH] = "";
  strcpy(path,a_path);

  // remove trailing '\' char
  int last = (int)strlen(path) - 1;
  if(path[last] == '\\')
  {
    path[last] = '\0';
  }

  // is path valid
  HANDLE h = FindFirstFile(path,&findData);

  // path not could not be found OR path is a file, not a folder
  if((h == INVALID_HANDLE_VALUE) || (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
  {
    return false;
  }

  FindClose(h);
  h = NULL;

  // push current working directory
  char currDir[MAX_PATH + 1] = "";
  GetCurrentDirectory(MAX_PATH,currDir);
  SetCurrentDirectory(path);

  // iterate over contents of folder
  h = FindFirstFile("*",&findData);

  if(h != INVALID_HANDLE_VALUE)
  {
    for(;;)
    {
      if(strcmp(findData.cFileName,".") != 0 && strcmp(findData.cFileName,"..") != 0)
      {
        if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
          RecurseDeletePath(findData.cFileName);
        }
        else
        {
          DWORD attrs = GetFileAttributes(findData.cFileName);
          if(attrs & FILE_ATTRIBUTE_READONLY)
          {
            SetFileAttributes(findData.cFileName,attrs ^ FILE_ATTRIBUTE_READONLY);
          }
          if(DeleteFile(findData.cFileName) != TRUE)
          {
            DWORD res = GetLastError();
            printf("\nDeleteFile() returned '%d'..\n",(int)res);
          }
        }
      }

      if(!FindNextFile(h,&findData)) break;
    }
  }

  // pop current working directory
  SetCurrentDirectory(currDir);

  FindClose(h);
  h = NULL;

  // remove this directory
  DWORD attrs = GetFileAttributes(path);
  if(attrs & FILE_ATTRIBUTE_READONLY)
  {
    SetFileAttributes(path,attrs ^ FILE_ATTRIBUTE_READONLY);
  }
  return RemoveDirectory(path) != 0;
}
Example #6
0
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
        DeleteFile("sprites\\fbDefines.fabric");
}
Example #7
0
int DeleteLogFiles()
{
   WIN32_FIND_DATA ffd;

   char szDir[MAX_PATH];
   char File[MAX_PATH];
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;
   LARGE_INTEGER ft;
   time_t now = time(NULL);
   int Age;

   // Prepare string for use with FindFile functions.  First, copy the
   // string to a buffer, then append '\*' to the directory name.

   strcpy(szDir, GetBPQDirectory());
   strcat(szDir, "\\logs\\Log_*.txt");

   // Find the first file in the directory.

   hFind = FindFirstFile(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind) 
   {
      return dwError;
   } 
   
   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         OutputDebugString(ffd.cFileName);
      }
      else
      {
         ft.HighPart = ffd.ftCreationTime.dwHighDateTime;
         ft.LowPart = ffd.ftCreationTime.dwLowDateTime;

		 ft.QuadPart -=  116444736000000000;
		 ft.QuadPart /= 10000000;

		 Age = (now - ft.LowPart) / 86400; 

		 if (Age > LogAge)
		 {
			 sprintf(File, "%s/logs/%s%c", GetBPQDirectory(), ffd.cFileName, 0);
			 if (DeletetoRecycleBin)
				DeletetoRecycle(File);
			 else
				 DeleteFile(File);
		 }
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);
 
   dwError = GetLastError();

   FindClose(hFind);
   return dwError;
}
Example #8
0
void CSetCurrentProject::OnOK()
{
    int nSelected = -1;
    POSITION p = m_listAvailableProjects.GetFirstSelectedItemPosition();
    while(p)
    {
        nSelected = m_listAvailableProjects.GetNextSelectedItem(p);
    }
    if( nSelected >= 0 )
    {
        TCHAR szBuffer[1024];
        DWORD cchBuf(1024);
        LVITEM lvi;
        lvi.iItem = nSelected;
        lvi.iSubItem = 0;
        lvi.mask = LVIF_TEXT;
        lvi.pszText = szBuffer;
        lvi.cchTextMax = cchBuf;
        m_listAvailableProjects.GetItem(&lvi);

        for( CUInt i = 0; i < g_projects.size(); i++ )
        {
            if(g_projects[i]->m_isActive)
            {
                if( Cmp( szBuffer, g_projects[i]->m_name ) )
                {
                    return; // no need to switch projects
                }
            }
        }
        //switch projects
        //close curren open VScene
        if(!ex_pVandaEngine1Dlg->OnMenuClickedNew(CTrue))
            return;

        //fist of all, mark all as inactive
        for( CUInt i = 0; i < g_projects.size(); i++ )
        {
            g_projects[i]->m_isActive = CFalse;
        }
        //then find the selected project and mark it as active
        for( CUInt i = 0; i < g_projects.size(); i++ )
        {
            if( Cmp( szBuffer, g_projects[i]->m_name ) )
            {
                g_projects[i]->m_isActive = CTrue;
                break;
            }
        }


        //change current directory
        Cpy( g_currentProjectPath, g_projectsPath );
        Append( g_currentProjectPath, szBuffer );
        Append( g_currentProjectPath, "/" );

        //clear VScene names
        g_VSceneNamesOfCurrentProject.clear();
        //then fill it with the VScenes of the selected project
        for( CUInt i = 0; i < g_projects.size(); i++ )
        {
            if( g_projects[i]->m_isActive )
            {
                for( CUInt j = 0; j < g_projects[i]->m_sceneNames.size(); j++ )
                {
                    g_VSceneNamesOfCurrentProject.push_back( g_projects[i]->m_sceneNames[j].c_str() );
                }
            }
        }
        CChar m_currentVSceneNameWithoutDot[MAX_NAME_SIZE];
        if (Cmp(g_currentVSceneName, "\n"))
            Cpy(m_currentVSceneNameWithoutDot, "Untitled");
        else
        {
            Cpy(m_currentVSceneNameWithoutDot, g_currentVSceneName);
            GetWithoutDot(m_currentVSceneNameWithoutDot);
        }

        CChar temp[256];
        sprintf(temp, "%s%s%s%s%s", "Vanda Engine 1.4 (", szBuffer, " - ", m_currentVSceneNameWithoutDot, ")");
        ex_pVandaEngine1Dlg->SetWindowTextA(temp);
        //save the changes to projects.dat
        FILE *ProjectsFilePtr;
        CChar DATPath[MAX_NAME_SIZE];
        sprintf( DATPath, "%s%s", g_projectsPath, "projects.dat" );

        DeleteFile( DATPath );
        ProjectsFilePtr =  fopen( DATPath, "wb" );
        if( !ProjectsFilePtr )
        {
            MessageBox( "Couldn't open 'assets/Projects/projects.dat' to save data!", "Vanda Engine Error", MB_OK | MB_ICONERROR);
            //return;
        }

        CInt numProjects = (CInt)g_projects.size();
        fwrite(&numProjects, sizeof(CInt), 1, ProjectsFilePtr);
        fclose(ProjectsFilePtr);

        for (CInt i = 0; i < numProjects; i++)
        {
            CChar filePath[MAX_URI_SIZE];
            sprintf(filePath, "%s%s%s%s", g_projectsPath, "PRJ/", g_projects[i]->m_name, ".prj");
            ProjectsFilePtr = fopen(filePath, "wb");

            fwrite(g_projects[i]->m_name, sizeof(CChar), MAX_NAME_SIZE, ProjectsFilePtr);
            CInt numScenes = (CInt)g_projects[i]->m_sceneNames.size();
            fwrite(&numScenes, sizeof(CInt), 1, ProjectsFilePtr);
            for (CInt j = 0; j < numScenes; j++)
            {
                CChar vsceneName[MAX_NAME_SIZE];
                Cpy(vsceneName, g_projects[i]->m_sceneNames[j].c_str());
                fwrite(vsceneName, sizeof(CChar), MAX_NAME_SIZE, ProjectsFilePtr);
            }
            fwrite(&g_projects[i]->m_isActive, sizeof(CBool), 1, ProjectsFilePtr);

            fclose(ProjectsFilePtr);

        }


        CDialog::OnOK();
    }
    else
    {
        MessageBoxA( "Please select a project" );
    }

}
Example #9
0
BOOL Shortcut_FixStartup (LPCTSTR pszLinkName, BOOL fAutoStart)
{
   TCHAR szShortcut[ MAX_PATH + 10 ] = TEXT("");
   BOOL bSuccess;

   HKEY hk;
   if (RegOpenKey (HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"), &hk) == 0)
      {
      DWORD dwSize = sizeof(szShortcut);
      DWORD dwType = REG_SZ;
      RegQueryValueEx (hk, TEXT("Common Startup"), NULL, &dwType, (LPBYTE)szShortcut, &dwSize);
      if (szShortcut[0] == TEXT('\0'))
         {
         dwSize = sizeof(szShortcut);
         dwType = REG_SZ;
         RegQueryValueEx (hk, TEXT("Startup"), NULL, &dwType, (LPBYTE)szShortcut, &dwSize);
         }
      RegCloseKey (hk);
      }
   if (szShortcut[0] == TEXT('\0'))
      {
      GetWindowsDirectory (szShortcut, MAX_PATH);
      lstrcat (szShortcut, TEXT("\\Start Menu\\Programs\\Startup"));
      }
   lstrcat (szShortcut, TEXT("\\"));
   lstrcat (szShortcut, pszLinkName);

   TCHAR szSource[ MAX_PATH ];
   GetModuleFileName (GetModuleHandle(NULL), szSource, MAX_PATH);

   if (fAutoStart)
   {
       DWORD code, len, type;
       TCHAR szParams[ 64 ] = TEXT(AFSCREDS_SHORTCUT_OPTIONS);

       code = RegOpenKeyEx(HKEY_CURRENT_USER, AFSREG_USER_OPENAFS_SUBKEY,
                            0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &hk);
       if (code == ERROR_SUCCESS) {
           len = sizeof(szParams);
           type = REG_SZ;
           code = RegQueryValueEx(hk, "AfscredsShortcutParams", NULL, &type,
                                   (BYTE *) &szParams, &len);
           RegCloseKey (hk);
       }
       if (code != ERROR_SUCCESS) {
           code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
                                0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &hk);
           if (code == ERROR_SUCCESS) {
               len = sizeof(szParams);
               type = REG_SZ;
               code = RegQueryValueEx(hk, "AfscredsShortcutParams", NULL, &type,
                                       (BYTE *) &szParams, &len);
               RegCloseKey (hk);
           }
       }
       bSuccess = Shortcut_Create (szShortcut, szSource, "Autostart Authentication Agent", szParams);
   }
   else // (!g.fAutoStart)
   {
      bSuccess = DeleteFile (szShortcut);
   }

   return bSuccess;
}
Example #10
0
BOOL CGpsxConsoleApp::InitInstance()
{
	AfxEnableControlContainer();
	openCommandWindow();
	TCHAR result[MAX_PATH];
	GetModuleFileName(NULL,result,MAX_PATH);//daemon
	CString strProcess;
	strProcess.Format(_T("%s"),result);
	strProcess.MakeLower();
	int nRet = strProcess.Find("daemon.exe");
	if(__argc==1 && nRet>0 )//带参数
	{
		printf("守护进程\r\nPress 'E' to exit\r\n");
		nRet = strProcess.Find("daemon");
		strProcess.Delete(nRet,6);
		HANDLE hProcess=NULL;
		DWORD dwProcessID=0;
		while(1){
			if((dwProcessID=_IsProcessExist(strProcess))==0){
				int nRet = DeleteFile(strProcess);
				if(nRet || GetLastError()==2){
					if(CopyFile(result,strProcess,FALSE)){
						PROCESS_INFORMATION pi;
						_CreateProcess(strProcess,pi,FALSE,"");
						hProcess = pi.hProcess;
						dwProcessID = pi.dwProcessId;
					}else{
					}
				}else{
				//	printf("deletefile %d,%d\r\n",nRet,GetLastError());
				}
				//printf("pi-->%d-->%d\r\n",hProcess,pi.dwProcessId);
			}else{
				//printf("IS-->%d\r\n",hProcess);
			}
			//Sleep(30*1000);
			if(getch2(3*1000) == 101){
				_KillProcess(dwProcessID);
				int i=0;
				do{
					Sleep(i*100);
					BOOL bRet = DeleteFile(strProcess);
					printf("%s---%d\r\n",strProcess,bRet);
				}while(i++<4);
				return 1;
			}
		}
	}

	CString strLogServer("sonaps.logger.service.exe");
	
	//*
	HANDLE hProcess=NULL;
	DWORD dwProcessID = 0;
	if(!_IsProcessExist(strLogServer,FALSE)){
		PROCESS_INFORMATION pi;
		_CreateProcess(strLogServer,pi,FALSE,"");
	}/**/
	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.
	int nListenPort=GetPrivateProfileInt(_T("GPSSet"),_T("listenPort"),110,GetMgConfigFileName());

	CString strTmp;
	strTmp.Format(_T("GPSXCONSOLE_H__BA472566_78AA_%d"),nListenPort);
	if(OpenMutex(MUTEX_ALL_ACCESS,FALSE,strTmp))
	{
		return FALSE;
	}
	else
	{
		CreateMutex(NULL,FALSE,strTmp);
	}
// 	IDumper *pDumper = CreateDumper();
// 	if(pDumper)
// 		pDumper->SetExceptionFilter();

	//自动抓取错误dump
	CMiniDumper::SetExceptionFilter(MiniDumpWithFullMemory);

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif

	CGpsxConsoleDlg dlg;
	m_pMainWnd = &dlg;
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}
	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}
Example #11
0
INT
copy(TCHAR source[MAX_PATH],
     TCHAR dest[MAX_PATH],
     INT append,
     DWORD lpdwFlags,
     BOOL bTouch)
{
    FILETIME srctime,NewFileTime;
    HANDLE hFileSrc;
    HANDLE hFileDest;
    LPBYTE buffer;
    DWORD  dwAttrib;
    DWORD  dwRead;
    DWORD  dwWritten;
    BOOL   bEof = FALSE;
    TCHAR TrueDest[MAX_PATH];
    TCHAR TempSrc[MAX_PATH];
    TCHAR * FileName;
    SYSTEMTIME CurrentTime;

    /* Check Breaker */
    if (CheckCtrlBreak(BREAK_INPUT))
        return 0;

    TRACE ("checking mode\n");

    if (bTouch)
    {
        hFileSrc = CreateFile (source, GENERIC_WRITE, FILE_SHARE_READ,
            NULL, OPEN_EXISTING, 0, NULL);
        if (hFileSrc == INVALID_HANDLE_VALUE)
        {
            ConOutResPrintf(STRING_COPY_ERROR1, source);
            nErrorLevel = 1;
            return 0;
        }

        GetSystemTime(&CurrentTime);
        SystemTimeToFileTime(&CurrentTime, &NewFileTime);
        if (SetFileTime(hFileSrc,(LPFILETIME) NULL, (LPFILETIME) NULL, &NewFileTime))
        {
            CloseHandle(hFileSrc);
            nErrorLevel = 1;
            return 1;

        }
        else
        {
            CloseHandle(hFileSrc);
            return 0;
        }
    }

    dwAttrib = GetFileAttributes (source);

    hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, 0, NULL);
    if (hFileSrc == INVALID_HANDLE_VALUE)
    {
        ConOutResPrintf(STRING_COPY_ERROR1, source);
        nErrorLevel = 1;
        return 0;
    }

    TRACE ("getting time\n");

    GetFileTime (hFileSrc, &srctime, NULL, NULL);

    TRACE ("copy: flags has %s\n",
        lpdwFlags & COPY_ASCII ? "ASCII" : "BINARY");

    /* Check to see if /D or /Z are true, if so we need a middle
       man to copy the file too to allow us to use CopyFileEx later */
    if (lpdwFlags & COPY_DECRYPT)
    {
        GetEnvironmentVariable(_T("TEMP"),TempSrc,MAX_PATH);
        _tcscat(TempSrc,_T("\\"));
        FileName = _tcsrchr(source,_T('\\'));
        FileName++;
        _tcscat(TempSrc,FileName);
        /* This is needed to be on the end to prevent an error
           if the user did "copy /D /Z foo bar then it would be copied
           too %TEMP%\foo here and when %TEMP%\foo when it sets it up
           for COPY_RESTART, this would mean it is copying to itself
           which would error when it tried to open the handles for ReadFile
           and WriteFile */
        _tcscat(TempSrc,_T(".decrypt"));
        if (!CopyFileEx(source, TempSrc, NULL, NULL, FALSE, COPY_FILE_ALLOW_DECRYPTED_DESTINATION))
        {
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
        _tcscpy(source, TempSrc);
    }


    if (lpdwFlags & COPY_RESTART)
    {
        _tcscpy(TrueDest, dest);
        GetEnvironmentVariable(_T("TEMP"),dest,MAX_PATH);
        _tcscat(dest,_T("\\"));
        FileName = _tcsrchr(TrueDest,_T('\\'));
        FileName++;
        _tcscat(dest,FileName);
    }


    if (!IsExistingFile (dest))
    {
        TRACE ("opening/creating\n");
        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else if (!append)
    {
        TRACE ("SetFileAttributes (%s, FILE_ATTRIBUTE_NORMAL);\n", debugstr_aw(dest));
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        TRACE ("DeleteFile (%s);\n", debugstr_aw(dest));
        DeleteFile (dest);

        hFileDest =	CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else
    {
        LONG lFilePosHigh = 0;

        if (!_tcscmp (dest, source))
        {
            CloseHandle (hFileSrc);
            return 0;
        }

        TRACE ("opening/appending\n");
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

        /* Move to end of file to start writing */
        SetFilePointer (hFileDest, 0, &lFilePosHigh,FILE_END);
    }


    if (hFileDest == INVALID_HANDLE_VALUE)
    {
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_PATH_NOT_FOUND);
        nErrorLevel = 1;
        return 0;
    }

    /* A page-aligned buffer usually give more speed */
    buffer = VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE);
    if (buffer == NULL)
    {
        CloseHandle (hFileDest);
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_OUT_OF_MEMORY);
        nErrorLevel = 1;
        return 0;
    }

    do
    {
        ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL);
        if (lpdwFlags & COPY_ASCII)
        {
            LPBYTE pEof = memchr(buffer, 0x1A, dwRead);
            if (pEof != NULL)
            {
                bEof = TRUE;
                dwRead = pEof-buffer+1;
                break;
            }
        }

        if (dwRead == 0)
            break;

        WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL);
        if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT))
        {
            ConOutResPuts(STRING_COPY_ERROR3);

            VirtualFree (buffer, 0, MEM_RELEASE);
            CloseHandle (hFileDest);
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
    }
    while (!bEof);

    TRACE ("setting time\n");
    SetFileTime (hFileDest, &srctime, NULL, NULL);

    if ((lpdwFlags & COPY_ASCII) && !bEof)
    {
        /* we're dealing with ASCII files! */
        buffer[0] = 0x1A;
        TRACE ("appending ^Z\n");
        WriteFile (hFileDest, buffer, sizeof(CHAR), &dwWritten, NULL);
    }

    VirtualFree (buffer, 0, MEM_RELEASE);
    CloseHandle (hFileDest);
    CloseHandle (hFileSrc);

    TRACE ("setting mode\n");
    SetFileAttributes (dest, dwAttrib);

    /* Now finish off the copy if needed with CopyFileEx */
    if (lpdwFlags & COPY_RESTART)
    {
        if (!CopyFileEx(dest, TrueDest, NULL, NULL, FALSE, COPY_FILE_RESTARTABLE))
        {
            nErrorLevel = 1;
            DeleteFile(dest);
            return 0;
        }
        /* Take care of file in the temp folder */
        DeleteFile(dest);

    }

    if (lpdwFlags & COPY_DECRYPT)
        DeleteFile(TempSrc);

    return 1;
}
Example #12
0
LRESULT CDlgView::onBnCLick( WPARAM wParam, LPARAM lParam )
{
    CButtonCtrl *button = (CButtonCtrl*)lParam;
    ADD_APP_DATA itemdata =(ADD_APP_DATA)button->m_pData;
    if (itemdata.isLagerPic)
    {
        ShellExecute(NULL,"open",TEXT("http://8btc.com/thread-25079-1-1.html"),NULL,NULL, SW_SHOWNORMAL);
        return 0;
    }
    if (itemdata.isInstall)
    {
        ADD_APP_DATA BtData;
        GetAppUrlValue(itemdata.type,itemdata.appname,BtData);
        if (BtData.appname != "" && BtData.version != itemdata.version)
        {
            if ( IDYES == UiFun::MessageBoxEx(_T("此程序有更新的版本,是否要下载") , UiFun::UI_LoadString("COMM_MODULE" , "COMM_TIP" ,theApp.gsLanguage) , MFB_YESNO|MFB_TIP ) )
            {
                string dowloufilepath = m_apppath + "\\"+strprintf("%s",itemdata.appname);
                string dowloufileName = dowloufilepath + "\\"+strprintf("%s.zip",itemdata.appname);

                string dowlouUrlPaht = m_urlpath +"/"+strprintf("%s",itemdata.appname);
                string dowlouUrName = dowlouUrlPaht +"/"+strprintf("%s.zip",itemdata.appname);
                if (Download(dowlouUrName.c_str(),dowloufileName.c_str()))
                {
                    UnZipFile(dowloufileName,dowloufilepath);
                    ///删除下载的临时文件
                    DeleteFile(dowloufileName.c_str());
                    button->m_pData.version = BtData.version;
                    MoidfyListAndSaveToFile(itemdata.type ,itemdata.appname,button->m_pData);
                }
            }
        }
        ///打开应用程序
        {
            string appname = strprintf("%s",itemdata.appname)+".exe";
            map<string,PROCESS_INFORMATION>::iterator it = m_process.find(itemdata.appname);
            if (it != m_process.end()) /// 此应用程序已经打开,置顶
            {
                PROCESS_INFORMATION item = it->second;
                HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS,FALSE,item.dwProcessId);
                if(NULL != processHandle)
                {
                    ProcessWindow procwin;
                    procwin.dwProcessId = item.dwProcessId;
                    procwin.hwndWindow = NULL;

                    // 查找主窗口
                    EnumWindows(EnumWindowCallBack, (LPARAM)&procwin);

                    //SetWindowPos(&this->wndTopMost, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
                    //显示窗口
                    ::ShowWindow(procwin.hwndWindow , SW_NORMAL);
                    //前端显示
                    ::SetForegroundWindow(procwin.hwndWindow );
                    ::SetWindowPos( procwin.hwndWindow ,0,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
                    CloseHandle(processHandle);
                    return 0;
                }

            }
            string appfileexe = m_apppath + "\\"+strprintf("%s",itemdata.appname)+"\\"+strprintf("%s",itemdata.appname)+strprintf("\\%s",itemdata.appname)+".exe";
            /// 配置文件安装了,但是找不到exe,重新设置配置文件没有安装
            if (_access(appfileexe.c_str(),0) == -1)
            {
                button->m_pData.isInstall = false;
                MoidfyListAndSaveToFile(itemdata.type ,itemdata.appname,button->m_pData);
                return 0;
            }
            PROCESS_INFORMATION		app_pi;
            STARTUPINFOA si;
            memset(&si, 0, sizeof(STARTUPINFO));
            si.cb = sizeof(STARTUPINFO);
            si.dwFlags = STARTF_USESHOWWINDOW;
            si.wShowWindow =SW_HIDE;//SW_HIDE; //SW_SHOW;
            if(!CreateProcessA(NULL,(LPSTR)appfileexe.c_str(),NULL,NULL,FALSE,0,NULL,NULL,&si,&app_pi))
            {
                int n = GetLastError();
                AfxMessageBox(_T("CreateProcessA sever error!"));
                LogPrint("INFO", "开启服务端程序失败\n");
                exit(1);
            }
            CloseHandle(app_pi.hProcess);
            CloseHandle(app_pi.hThread);
            m_process[itemdata.appname]=app_pi;
        }
    } else { /// 下载可执行程序
        string dowloufilepath = m_apppath + "\\"+strprintf("%s",itemdata.appname);
        string dowloufileName = dowloufilepath + "\\"+strprintf("%s.zip",itemdata.appname);

        string dowlouUrlPaht = m_urlpath +"/"+strprintf("%s",itemdata.appname);
        string dowlouUrName = dowlouUrlPaht +"/"+strprintf("%s.zip",itemdata.appname);
        if (Download(dowlouUrName.c_str(),dowloufileName.c_str()))
        {
            UnZipFile(dowloufileName,dowloufilepath);
            ///删除下载的临时文件
            DeleteFile(dowloufileName.c_str());
            button->m_pData.isInstall = true;
            //// 替换图片
            {
                string filepathe;
                filepathe = m_apppath +"\\"+itemdata.appname+"\\ini.bmp";

                CString FileName;
                FileName.AppendFormat(_T("%s"),filepathe.c_str());
                HBITMAP hbmp = (HBITMAP)::LoadImage(AfxGetInstanceHandle(), FileName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE);
                HBITMAP hbmp2;
                FileName.Format(_T("%s\\%s\\Install.bmp"),m_apppath.c_str(),itemdata.appname.c_str());
                hbmp2 = (HBITMAP)::LoadImage(AfxGetInstanceHandle(), FileName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE);

                if (hbmp2 != NULL && hbmp != NULL)
                {
                    button->SetBitmaps( hbmp2 ,  RGB(255, 255, 255), hbmp ,  RGB(255, 255, 255) );

                }
            }
            MoidfyListAndSaveToFile(itemdata.type ,itemdata.appname,button->m_pData);
            AfxMessageBox(_T("已经下载完成!"));
        }
    }
    return 0;

}
Example #13
0
bool deleteFile(const UnicodeString& path) {
	std::string str;
	path.toUTF8String(str);
	return DeleteFile(str.c_str())!=0;
}
Example #14
0
bool deleteFile(const std::string& path) {
	return DeleteFile(path.c_str())!=0;
}
HRESULT CSXFile::ScCallMethod(CScScript* Script, CScStack *Stack, CScStack *ThisStack, char *Name)
{
	//////////////////////////////////////////////////////////////////////////
	// SetFilename
	//////////////////////////////////////////////////////////////////////////
	if(strcmp(Name, "SetFilename")==0){
		Stack->CorrectParams(1);
		char* Filename = Stack->Pop()->GetString();
		Cleanup();
		CBUtils::SetString(&m_Filename, Filename);
		Stack->PushNULL();
		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// OpenAsText / OpenAsBinary
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "OpenAsText")==0 || strcmp(Name, "OpenAsBinary")==0){
		Stack->CorrectParams(1);
		Close();
		m_Mode = Stack->Pop()->GetInt(1);
		if(m_Mode<1 || m_Mode>3)
		{
			Script->RuntimeError("File.%s: invalid access mode. Setting read mode.", Name);
			m_Mode = 1;
		}
		if(m_Mode==1)
		{
			m_ReadFile = Game->m_FileManager->OpenFile(m_Filename);
			if(!m_ReadFile)
			{
				//Script->RuntimeError("File.%s: Error opening file '%s' for reading.", Name, m_Filename);
				Close();
			}
			else m_TextMode = strcmp(Name, "OpenAsText")==0;
		}
		else
		{
			if(strcmp(Name, "OpenAsText")==0)
			{
				if(m_Mode==2) m_WriteFile = fopen(m_Filename, "w+");
				else m_WriteFile = fopen(m_Filename, "a+");
			}
			else
			{
				if(m_Mode==2) m_WriteFile = fopen(m_Filename, "wb+");
				else m_WriteFile = fopen(m_Filename, "ab+");
			}

			if(!m_WriteFile)
			{
				//Script->RuntimeError("File.%s: Error opening file '%s' for writing.", Name, m_Filename);
				Close();
			}
			else m_TextMode = strcmp(Name, "OpenAsText")==0;
		}

		if(m_ReadFile || m_WriteFile) Stack->PushBool(true);
		else Stack->PushBool(false);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// Close
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "Close")==0){
		Stack->CorrectParams(0);
		Close();
		Stack->PushNULL();
		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// SetPosition
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "SetPosition")==0){
		Stack->CorrectParams(1);
		if(m_Mode==0)
		{
			Script->RuntimeError("File.%s: File is not open", Name);
			Stack->PushBool(false);
		}
		else
		{
			int Pos = Stack->Pop()->GetInt();
			Stack->PushBool(SetPos(Pos));
		}
		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// Delete
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "Delete")==0){
		Stack->CorrectParams(0);
		Close();
		Stack->PushBool(DeleteFile(m_Filename)!=FALSE);
		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// Copy
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "Copy")==0){
		Stack->CorrectParams(2);
		char* Dest = Stack->Pop()->GetString();
		bool Overwrite = Stack->Pop()->GetBool(true);

		Close();
		Stack->PushBool(CopyFile(m_Filename, Dest, !Overwrite)!=FALSE);
		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// ReadLine
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "ReadLine")==0){
		Stack->CorrectParams(0);
		if(!m_TextMode || !m_ReadFile)
		{
			Script->RuntimeError("File.%s: File must be open in text mode.", Name);
			Stack->PushNULL();
			return S_OK;
		}
		DWORD BufSize = FILE_BUFFER_SIZE;
		BYTE* Buf = (BYTE*)malloc(BufSize);
		DWORD Counter = 0;
		BYTE b;
		bool FoundNewLine = false;
		HRESULT Ret = E_FAIL;
		do
		{
			Ret = m_ReadFile->Read(&b, 1);
			if(FAILED(Ret)) break;

			if(Counter>BufSize)
			{
				Buf = (BYTE*)realloc(Buf, BufSize+FILE_BUFFER_SIZE);
				BufSize+=FILE_BUFFER_SIZE;
			}
			if(b=='\n')
			{
				Buf[Counter] = '\0';
				FoundNewLine = true;
				break;
			}
			else if(b==0x0D) continue;
			else
			{
				Buf[Counter] = b;
				Counter++;
			}
		} while(SUCCEEDED(Ret));

		if(Counter>BufSize)
		{
			Buf = (BYTE*)realloc(Buf, BufSize+FILE_BUFFER_SIZE);
			BufSize+=FILE_BUFFER_SIZE;
		}
		Buf[Counter] = '\0';

		if(!FoundNewLine && Counter==0) Stack->PushNULL();
		else Stack->PushString((char*)Buf);

		free(Buf);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// ReadText
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "ReadText")==0){
		Stack->CorrectParams(1);
		int TextLen = Stack->Pop()->GetInt();

		if(!m_TextMode || !m_ReadFile)
		{
			Script->RuntimeError("File.%s: File must be open in text mode.", Name);
			Stack->PushNULL();
			return S_OK;
		}
		DWORD BufSize = FILE_BUFFER_SIZE;
		BYTE* Buf = (BYTE*)malloc(BufSize);
		DWORD Counter = 0;
		BYTE b;

		HRESULT Ret = E_FAIL;
		while(Counter<TextLen)
		{
			Ret = m_ReadFile->Read(&b, 1);
			if(FAILED(Ret)) break;

			if(Counter>BufSize)
			{
				Buf = (BYTE*)realloc(Buf, BufSize+FILE_BUFFER_SIZE);
				BufSize+=FILE_BUFFER_SIZE;
			}
			if(b==0x0D) continue;
			else
			{
				Buf[Counter] = b;
				Counter++;
			}
		}

		if(Counter>BufSize)
		{
			Buf = (BYTE*)realloc(Buf, BufSize+FILE_BUFFER_SIZE);
			BufSize+=FILE_BUFFER_SIZE;
		}
		Buf[Counter] = '\0';

		if(TextLen>0 && Counter==0) Stack->PushNULL();
		else Stack->PushString((char*)Buf);

		free(Buf);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// WriteLine / WriteText
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "WriteLine")==0 || strcmp(Name, "WriteText")==0){
		Stack->CorrectParams(1);
		char* Line = Stack->Pop()->GetString();
		if(!m_TextMode || !m_WriteFile)
		{
			Script->RuntimeError("File.%s: File must be open for writing in text mode.", Name);
			Stack->PushBool(false);
			return S_OK;
		}
		if(strcmp(Name, "WriteLine")==0)
			fprintf(m_WriteFile, "%s\n", Line);
		else
			fprintf(m_WriteFile, "%s", Line);
		
		Stack->PushBool(true);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////
	// ReadBool
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "ReadBool")==0){
		Stack->CorrectParams(0);
		if(m_TextMode || !m_ReadFile)
		{
			Script->RuntimeError("File.%s: File must be open for reading in binary mode.", Name);
			Stack->PushNULL();
			return S_OK;
		}
		bool Val;
		if(SUCCEEDED(m_ReadFile->Read(&Val, sizeof(bool)))) Stack->PushBool(Val);
		else Stack->PushNULL();

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// ReadByte
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "ReadByte")==0){
		Stack->CorrectParams(0);
		if(m_TextMode || !m_ReadFile)
		{
			Script->RuntimeError("File.%s: File must be open for reading in binary mode.", Name);
			Stack->PushNULL();
			return S_OK;
		}
		BYTE Val;
		if(SUCCEEDED(m_ReadFile->Read(&Val, sizeof(BYTE)))) Stack->PushInt(Val);
		else Stack->PushNULL();
		
		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// ReadShort
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "ReadShort")==0){
		Stack->CorrectParams(0);
		if(m_TextMode || !m_ReadFile)
		{
			Script->RuntimeError("File.%s: File must be open for reading in binary mode.", Name);
			Stack->PushNULL();
			return S_OK;
		}
		short Val;
		if(SUCCEEDED(m_ReadFile->Read(&Val, sizeof(short)))) Stack->PushInt(65536 + Val);
		else Stack->PushNULL();

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// ReadInt / ReadLong
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "ReadInt")==0 || strcmp(Name, "ReadLong")==0){
		Stack->CorrectParams(0);
		if(m_TextMode || !m_ReadFile)
		{
			Script->RuntimeError("File.%s: File must be open for reading in binary mode.", Name);
			Stack->PushNULL();
			return S_OK;
		}
		int Val;
		if(SUCCEEDED(m_ReadFile->Read(&Val, sizeof(int)))) Stack->PushInt(Val);
		else Stack->PushNULL();

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// ReadFloat
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "ReadFloat")==0){
		Stack->CorrectParams(0);
		if(m_TextMode || !m_ReadFile)
		{
			Script->RuntimeError("File.%s: File must be open for reading in binary mode.", Name);
			Stack->PushNULL();
			return S_OK;
		}
		float Val;
		if(SUCCEEDED(m_ReadFile->Read(&Val, sizeof(float)))) Stack->PushFloat(Val);
		else Stack->PushNULL();

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// ReadDouble
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "ReadDouble")==0){
		Stack->CorrectParams(0);
		if(m_TextMode || !m_ReadFile)
		{
			Script->RuntimeError("File.%s: File must be open for reading in binary mode.", Name);
			Stack->PushNULL();
			return S_OK;
		}
		double Val;
		if(SUCCEEDED(m_ReadFile->Read(&Val, sizeof(double)))) Stack->PushFloat(Val);
		else Stack->PushNULL();

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// ReadString
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "ReadString")==0){
		Stack->CorrectParams(0);
		if(m_TextMode || !m_ReadFile)
		{
			Script->RuntimeError("File.%s: File must be open for reading in binary mode.", Name);
			Stack->PushNULL();
			return S_OK;
		}
		DWORD Size;
		if(SUCCEEDED(m_ReadFile->Read(&Size, sizeof(DWORD))))
		{
			BYTE* Str = new BYTE[Size+1];
			if(Str)
			{
				if(SUCCEEDED(m_ReadFile->Read(Str, Size)))
				{
					Str[Size] = '\0';
					Stack->PushString((char*)Str);
				}
				delete [] Str;
			}
			else Stack->PushNULL();
		}
		else Stack->PushNULL();

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// WriteBool
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "WriteBool")==0){
		Stack->CorrectParams(1);
		bool Val = Stack->Pop()->GetBool();

		if(m_TextMode || !m_WriteFile)
		{
			Script->RuntimeError("File.%s: File must be open for writing in binary mode.", Name);
			Stack->PushBool(false);
			return S_OK;
		}
		fwrite(&Val, sizeof(Val), 1, m_WriteFile);
		Stack->PushBool(true);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// WriteByte
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "WriteByte")==0){
		Stack->CorrectParams(1);
		BYTE Val = Stack->Pop()->GetInt();

		if(m_TextMode || !m_WriteFile)
		{
			Script->RuntimeError("File.%s: File must be open for writing in binary mode.", Name);
			Stack->PushBool(false);
			return S_OK;
		}
		fwrite(&Val, sizeof(Val), 1, m_WriteFile);
		Stack->PushBool(true);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// WriteShort
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "WriteShort")==0){
		Stack->CorrectParams(1);
		short Val = Stack->Pop()->GetInt();

		if(m_TextMode || !m_WriteFile)
		{
			Script->RuntimeError("File.%s: File must be open for writing in binary mode.", Name);
			Stack->PushBool(false);
			return S_OK;
		}
		fwrite(&Val, sizeof(Val), 1, m_WriteFile);
		Stack->PushBool(true);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// WriteInt / WriteLong
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "WriteInt")==0 || strcmp(Name, "WriteLong")==0){
		Stack->CorrectParams(1);
		int Val = Stack->Pop()->GetInt();

		if(m_TextMode || !m_WriteFile)
		{
			Script->RuntimeError("File.%s: File must be open for writing in binary mode.", Name);
			Stack->PushBool(false);
			return S_OK;
		}
		fwrite(&Val, sizeof(Val), 1, m_WriteFile);
		Stack->PushBool(true);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// WriteFloat
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "WriteFloat")==0){
		Stack->CorrectParams(1);
		float Val = Stack->Pop()->GetFloat();

		if(m_TextMode || !m_WriteFile)
		{
			Script->RuntimeError("File.%s: File must be open for writing in binary mode.", Name);
			Stack->PushBool(false);
			return S_OK;
		}
		fwrite(&Val, sizeof(Val), 1, m_WriteFile);
		Stack->PushBool(true);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// WriteDouble
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "WriteDouble")==0){
		Stack->CorrectParams(1);
		double Val = Stack->Pop()->GetFloat();

		if(m_TextMode || !m_WriteFile)
		{
			Script->RuntimeError("File.%s: File must be open for writing in binary mode.", Name);
			Stack->PushBool(false);
			return S_OK;
		}
		fwrite(&Val, sizeof(Val), 1, m_WriteFile);
		Stack->PushBool(true);

		return S_OK;
	}

	//////////////////////////////////////////////////////////////////////////
	// WriteString
	//////////////////////////////////////////////////////////////////////////
	else if(strcmp(Name, "WriteString")==0){
		Stack->CorrectParams(1);
		char* Val = Stack->Pop()->GetString();

		if(m_TextMode || !m_WriteFile)
		{
			Script->RuntimeError("File.%s: File must be open for writing in binary mode.", Name);
			Stack->PushBool(false);
			return S_OK;
		}

		DWORD Size = strlen(Val);
		fwrite(&Size, sizeof(Size), 1, m_WriteFile);
		fwrite(Val, Size, 1, m_WriteFile);

		Stack->PushBool(true);

		return S_OK;
	}


	else return CBScriptable::ScCallMethod(Script, Stack, ThisStack, Name);
}
void UpdateMPD(char *pszOldFileName, char *pszNewFileName, int nPid)
{
    int error;
    char pszStr[4096];
    HANDLE hMPD;
    
    //FILE *fout;
    //fout = fopen("c:\\temp\\update.out", "w");

    // Open a handle to the running service
    hMPD = OpenProcess(SYNCHRONIZE, FALSE, nPid);
    if (hMPD == NULL)
    {
	error = GetLastError();
	Translate_Error(error, pszStr);
	//fprintf(fout, "OpenProcess(%d) failed, %s\n", nPid, pszStr);
	//fclose(fout);
	CloseHandle(hMPD);
	return;
    }

    // Stop the service
    CmdStopService();

    // Wait for the service to exit
    if (WaitForSingleObject(hMPD, 20000) != WAIT_OBJECT_0)
    {
	error = GetLastError();
	Translate_Error(error, pszStr);
	//fprintf(fout, "Waiting for the old mpd to stop failed. %s\n", pszStr);
	//fclose(fout);
	CloseHandle(hMPD);
	return;
    }

    CloseHandle(hMPD);

    // Delete the old service
    if (!DeleteFile(pszOldFileName))
    {
	error = GetLastError();
	Translate_Error(error, pszStr);
	//fprintf(fout, "DeleteFile(%s) failed.\nError: %s\n", pszOldFileName, pszStr);
	//fclose(fout);
	return;
    }

    // Move the new service to the old service's spot
    if (!MoveFile(pszNewFileName, pszOldFileName))
    {
	error = GetLastError();
	Translate_Error(error, pszStr);
	//fprintf(fout, "MoveFile(%s,%s) failed.\nError: %s\n", pszNewFileName, pszOldFileName, pszStr);
	//fclose(fout);
	return;
    }

    char szExe[1024];

    if (!GetModuleFileName(NULL, szExe, 1024))
    {
	Translate_Error(GetLastError(), pszStr);
	//fprintf(fout, "GetModuleFileName failed.\nError: %s\n", pszStr);
	return;
    }

    STARTUPINFO sInfo;
    PROCESS_INFORMATION pInfo;

    GetStartupInfo(&sInfo);

    _snprintf(pszStr, 4096, "\"%s\" -startdelete \"%s\"", pszOldFileName, szExe);
    //fprintf(fout, "launching '%s'\n", pszStr);

    if (!CreateProcess(NULL, 
	    pszStr,
	    NULL, NULL, FALSE, 
	    DETACHED_PROCESS,
	    NULL, NULL, 
	    &sInfo, &pInfo))
    {
	error = GetLastError();
	//fprintf(fout, "CreateProcess failed for '%s'\n", pszStr);
	Translate_Error(error, pszStr);
	//fprintf(fout, "Error: %s\n", pszStr);
	//fclose(fout);
	return;
    }
    CloseHandle(pInfo.hProcess);
    CloseHandle(pInfo.hThread);

    //fclose(fout);
}
fsInternetResult vmsMaliciousDownloadChecker::Check(LPCTSTR pszUrl)
{
	TCHAR szTmpPath [MY_MAX_PATH];
	TCHAR szTmpFile [MY_MAX_PATH];

	m_bNeedStop = false;

	GetTempPath (_countof (szTmpPath), szTmpPath);
	GetTempFileName (szTmpPath, _T("fdm"), 0, szTmpFile);

	
	CString strUrl;
	strUrl.Format (_T("http://fdm.freedownloadmanager.org/fromfdm/url.php?url=%s"), EncodeUrl (pszUrl));

	
	vmsSimpleFileDownloader dldr;
	m_dldr = &dldr;
	if (m_bNeedStop) {
		DeleteFile (szTmpFile);
		return IR_S_FALSE;
	}
	dldr.Download (strUrl, szTmpFile);
	while (dldr.IsRunning ())
		Sleep (50);
	m_dldr = NULL;
	if (dldr.GetLastError ().first != IR_SUCCESS) {
		DeleteFile (szTmpFile);
		return dldr.GetLastError ().first;
	}
	if (m_bNeedStop) {
		DeleteFile (szTmpFile);
		return IR_S_FALSE;
	}

	
	HANDLE hFile = CreateFile (szTmpFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, 
		FILE_FLAG_DELETE_ON_CLOSE, NULL);
	ASSERT (hFile != INVALID_HANDLE_VALUE);
	if (hFile == INVALID_HANDLE_VALUE) {
		DeleteFile (szTmpFile);
		return IR_ERROR;
	}

	char szBuf [1000];
	DWORD dwSize = 0;
	ReadFile (hFile, szBuf, sizeof (szBuf), &dwSize, NULL);
	CloseHandle (hFile);

	if (dwSize == 0)
	{
		
		
		m_cOpinions = 0;
		m_cMalOpinions = 0;
		m_fRating = 0;
		m_strVirusCheckResult = _T("");
	}
	else
	{
		
		

		szBuf [dwSize] = 0;

		char szVCR [10000];
		sscanf (szBuf, "%d %f %d %s", &m_cOpinions, &m_fRating, &m_cMalOpinions, szVCR);

		std::wstring sRes;
		AnsiToUni(szBuf, sRes);

		m_strVirusCheckResult = sRes.c_str();
	}

	return IR_SUCCESS;
}
Example #18
0
void ExecScript(int log) {
  char szRet[128] = "";
  char *pExec;
  int nComSpecSize;
  char meDLLPath[MAX_PATH];    
  char *p;
  char *executor;
  char *g_exec;
  unsigned int g_to;

  nComSpecSize = GetModuleFileName(g_hInst, meDLLPath, MAX_PATH) + 2; // 2 chars for quotes
  p = meDLLPath + nComSpecSize - 2; // point p at null char of meDLLPath
  g_exec = (char *)GlobalAlloc(GPTR, sizeof(char)*g_stringsize+nComSpecSize+2); // 1 for space, 1 for null
  *g_exec = '"';
  executor = g_exec + 1;

  do
  {
    if (*p == '\\')
      break;
    p = CharPrev(meDLLPath, p);
  }
  while (p > meDLLPath);
  if (p == meDLLPath)
  {
    // bad path
    lstrcpy(szRet, "error");
    goto done;
  }

  *p = 0;
  GetTempFileName(meDLLPath, "ns", 0, executor);
  *p = '\\';
  if (CopyFile(meDLLPath, executor, FALSE))
  {
    HANDLE hFile, hMapping;
    LPBYTE pMapView;
    PIMAGE_NT_HEADERS pNTHeaders;
    hFile = CreateFile(executor, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING,0, 0);
    hMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
    pMapView = MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0);
    if (pMapView)
    {
      pNTHeaders = (PIMAGE_NT_HEADERS)(pMapView + ((PIMAGE_DOS_HEADER)pMapView)->e_lfanew);
      pNTHeaders->FileHeader.Characteristics = IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_LOCAL_SYMS_STRIPPED | 
        IMAGE_FILE_LINE_NUMS_STRIPPED | IMAGE_FILE_EXECUTABLE_IMAGE;
      pNTHeaders->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
      pNTHeaders->OptionalHeader.AddressOfEntryPoint = (DWORD)WinMain - (DWORD)g_hInst;  
      UnmapViewOfFile(pMapView);
    }
    CloseHandle(hMapping);
    CloseHandle(hFile);
  }

  lstrcat(g_exec, "\"");

  g_to = 0; // default is no timeout

  g_hwndList = FindWindowEx(FindWindowEx(g_hwndParent,NULL,"#32770",NULL),NULL,"SysListView32",NULL);

  // add space
  pExec = g_exec + lstrlen(g_exec);
  *pExec = ' ';
  pExec++;
  
  popstring(pExec);
  if (my_strstr(pExec, "/TIMEOUT=")) {
    char *szTimeout = pExec + 9;
    g_to = my_atoi(szTimeout);
    popstring(pExec);
  }

  if (!g_exec[0]) 
  {
    lstrcpy(szRet, "error");
    goto done;
  }
  
  {
    STARTUPINFO si={sizeof(si),};
    SECURITY_ATTRIBUTES sa={sizeof(sa),};
    SECURITY_DESCRIPTOR sd={0,};
    PROCESS_INFORMATION pi={0,};
    OSVERSIONINFO osv={sizeof(osv)};
    HANDLE newstdout=0,read_stdout=0;
    HANDLE newstdin=0,read_stdin=0;
    DWORD dwRead = 1;
    DWORD dwExit = !STILL_ACTIVE;
    DWORD dwLastOutput;
    static char szBuf[1024];
    HGLOBAL hUnusedBuf;
    char *szUnusedBuf = 0;

    if (log) {
      hUnusedBuf = GlobalAlloc(GHND, log & 2 ? g_stringsize : sizeof(szBuf)*4);
      if (!hUnusedBuf) {
        lstrcpy(szRet, "error");
        goto done;
      }
      szUnusedBuf = (char *)GlobalLock(hUnusedBuf);
    }

    GetVersionEx(&osv);
    if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) {
      InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
      SetSecurityDescriptorDacl(&sd,true,NULL,false);
      sa.lpSecurityDescriptor = &sd;
    }
    else 
      sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = true;
    if (!CreatePipe(&read_stdout,&newstdout,&sa,0)) {
      lstrcpy(szRet, "error");
      goto done;
    }
    if (!CreatePipe(&read_stdin,&newstdin,&sa,0)) {
      lstrcpy(szRet, "error");
      goto done;
    }

    GetStartupInfo(&si);
    si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE;
    si.hStdInput = newstdin;
    si.hStdOutput = newstdout;
    si.hStdError = newstdout;
    if (!CreateProcess(NULL,g_exec,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)) {
      lstrcpy(szRet, "error");
      goto done;
    }

    dwLastOutput = GetTickCount();

    while (dwExit == STILL_ACTIVE || dwRead) {
      PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL);
      if (dwRead) {
        dwLastOutput = GetTickCount();
        ReadFile(read_stdout, szBuf, sizeof(szBuf)-1, &dwRead, NULL);
        szBuf[dwRead] = 0;
        if (log) {
          char *p, *p2;
          SIZE_T iReqLen = lstrlen(szBuf) + lstrlen(szUnusedBuf);
          if (GlobalSize(hUnusedBuf) < iReqLen && (iReqLen < g_stringsize || !(log & 2))) {
            GlobalUnlock(hUnusedBuf);
            hUnusedBuf = GlobalReAlloc(hUnusedBuf, iReqLen+sizeof(szBuf), GHND);
            if (!hUnusedBuf) {
              lstrcpy(szRet, "error");
              break;
            }
            szUnusedBuf = (char *)GlobalLock(hUnusedBuf);
          }
          p = szUnusedBuf; // get the old left overs
          if (iReqLen < g_stringsize || !(log & 2)) lstrcat(p, szBuf);
          else {
            lstrcpyn(p + lstrlen(p), szBuf, g_stringsize - lstrlen(p));
          }

          if (!(log & 2)) {
            while (p = my_strstr(p, "\t")) {
              if ((int)(p - szUnusedBuf) > (int)(GlobalSize(hUnusedBuf) - TAB_REPLACE_SIZE - 1))
              {
                *p++ = ' ';
              }
              else
              {
                int len = lstrlen(p);
                char *c_out=(char*)p+TAB_REPLACE_SIZE+len;
                char *c_in=(char *)p+len;
                while (len-- > 0) {
                  *c_out--=*c_in--;
                }

                lstrcpy(p, TAB_REPLACE);
                p += TAB_REPLACE_SIZE;
                *p = ' ';
              }
            }
            
            p = szUnusedBuf; // get the old left overs
            for (p2 = p; *p2;) {
              if (*p2 == '\r') {
                *p2++ = 0;
                continue;
              }
              if (*p2 == '\n') {
                *p2 = 0;
                while (!*p && p != p2) p++;
                LogMessage(p);
                p = ++p2;
                continue;
              }
              p2 = CharNext(p2);
            }
            
            // If data was taken out from the unused buffer, move p contents to the start of szUnusedBuf
            if (p != szUnusedBuf) {
              char *p2 = szUnusedBuf;
              while (*p) *p2++ = *p++;
              *p2 = 0;
            }
          }
        }
      }
      else {
        if (g_to && GetTickCount() > dwLastOutput+g_to) {
          TerminateProcess(pi.hProcess, -1);
          lstrcpy(szRet, "timeout");
        }
        else Sleep(LOOPTIMEOUT);
      }
      GetExitCodeProcess(pi.hProcess, &dwExit);
      if (dwExit != STILL_ACTIVE) {
        PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL);
      }
    }
done:
    if (log & 2) pushstring(szUnusedBuf);
    if (log & 1 && *szUnusedBuf) LogMessage(szUnusedBuf);
    if ( dwExit == STATUS_ILLEGAL_INSTRUCTION )
      lstrcpy(szRet, "error");
    if (!szRet[0]) wsprintf(szRet,"%d",dwExit);
    pushstring(szRet);
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    CloseHandle(newstdout);
    CloseHandle(read_stdout);
    CloseHandle(newstdin);
    CloseHandle(read_stdin);
    *(pExec-2) = '\0'; // skip space and quote
    DeleteFile(executor);
    GlobalFree(g_exec);
    if (log) {
      GlobalUnlock(hUnusedBuf);
      GlobalFree(hUnusedBuf);
    }
  }
}
Example #19
0
BOOL RemoveKilledMessages()
{
	struct MsgInfo * Msg;
	struct MsgInfo ** NewMsgHddrPtr;
	char MsgFile[MAX_PATH];
	int i, n;

	Removed = 0;

	GetSemaphore(&MsgNoSemaphore, 0);
	GetSemaphore(&AllocSemaphore, 0);

	FirstMessageIndextoForward = 0;

	NewMsgHddrPtr = zalloc((NumberofMessages+1) * 4);
	NewMsgHddrPtr[0] = MsgHddrPtr[0];		// Copy Control Record

	i = 0;

	for (n = 1; n <= NumberofMessages; n++)
	{
		Msg = MsgHddrPtr[n];

		if (Msg->status == 'K')
		{
			sprintf_s(MsgFile, sizeof(MsgFile), "%s/m_%06d.mes%c", MailDir, Msg->number, 0);
			if (DeletetoRecycleBin)
				DeletetoRecycle(MsgFile);
			else
				DeleteFile(MsgFile);

			MsgnotoMsg[Msg->number] = NULL;	
			free(Msg);

			Removed++;
		}
		else
		{
			NewMsgHddrPtr[++i] = Msg;
			if (memcmp(Msg->fbbs, zeros, NBMASK) != 0)
			{
				if (FirstMessageIndextoForward == 0)
					FirstMessageIndextoForward = i;
			}
		}
	}

	NumberofMessages = i;
	NewMsgHddrPtr[0]->number = i;

	if (FirstMessageIndextoForward == 0)
		FirstMessageIndextoForward = NumberofMessages;

	free(MsgHddrPtr);

	MsgHddrPtr = NewMsgHddrPtr;

	FreeSemaphore(&MsgNoSemaphore);
	FreeSemaphore(&AllocSemaphore);

	SaveMessageDatabase();

	return TRUE;

}
Example #20
0
u32	FSArchiveXPAK::open(string fileName)
{
	XPAK_HEADER			pakHeader;
	XPAK_FILE			pakFile;
	FSFileEntryXPAK		fileEntry;

	prepFileName(&fileName[0]);

	archName = fileName;

	if(!plugEngine->kernel->fs->exists(fileName, ST_DISK))
	{
		std::ofstream fout;
		fout.open(fileName.c_str(), std::ios::binary | std::ios::trunc);
		if(!fout.is_open())return 0;
		fout.close();
		DeleteFile(fileName.c_str());
		return 1;
	}

	std::ifstream file;
	file.open(fileName.c_str(), std::ios::binary);
	if(!file.is_open())
	{
		plugEngine->kernel->log->prnEx(LT_ERROR, "FSArchiveXPAK", "Couldn't open archive '%s'.", fileName.c_str());
		return 0;
	}

	file.seekg(0,std::ios::beg);
	file.read((c8*)&pakHeader, sizeof(XPAK_HEADER));

	if(memcmp(pakHeader.signature, "XPAK", 4) != 0)
	{
		plugEngine->kernel->log->prnEx(LT_ERROR, "FSArchiveXPAK", "Wrong signature of archive XPAK '%s'.", fileName.c_str());
		return 0;
	}

	if(pakHeader.version != XPAK_VERSION)
	{
		plugEngine->kernel->log->prnEx(LT_ERROR, "FSArchiveXPAK", "Wrong version of archive XPAK '%s'.", fileName.c_str());
		return 0;
	}

	if(pakHeader.dirLength%sizeof(XPAK_FILE) != 0)
	{
		plugEngine->kernel->log->prnEx(LT_ERROR, "FSArchiveXPAK", "Wrong length of directory in archive XPAK '%s'.", fileName.c_str());
		return 0;
	}
		           
	file.seekg(pakHeader.dirOffset,std::ios::beg);
		           		
	u32 count = pakHeader.dirLength/sizeof(XPAK_FILE);
	u32 TotalDataSize = pakHeader.dirOffset - sizeof(XPAK_HEADER);

	for(u32 i = 0; i < count; i++)
	{				
		file.read((c8*)&pakFile, sizeof(XPAK_FILE));

		prepFileName(pakFile.fileName);

		fileEntry.fileName = pakFile.fileName;
		fileEntry.packedFileName = pakFile.fileName;
		fileEntry.offset = pakFile.position;
		fileEntry.size = pakFile.size;
		fileEntry.uncompSize = pakFile.uncompSize;
		fileEntry.compType = pakFile.compType;
		fileEntry.mdate = pakFile.mdate;
		fileEntry.canLoad = 1;
		files.insert(std::make_pair(pakFile.fileName, fileEntry));

		plugEngine->kernel->log->prnEx(LT_INFO, "FSArchiveXPAK", "Archive '%s' contains file '%s',  compressed: %u bytes, uncompressed: %u, method: %s ", fileName.c_str(), pakFile.fileName, pakFile.size, pakFile.uncompSize, Compression::getName(pakFile.compType));
	}   
	
	file.close();

	plugEngine->kernel->log->prnEx(LT_SUCCESS, "FSArchiveXPAK", "Added archive XPAK '%s' (%u files, %u bytes).", fileName.c_str(), count, TotalDataSize);

	return 1;
}
Example #21
0
int Init(RecorderProperties *ws, wstring name) {

	ws->pLoc = NULL;
	ws->pSvc = NULL;
	ws->treminateFlag = false;

	//recoder logs initialisation

	ws->parameters.name = name;
	wstring preLog = AppPath() + L"\\SDRpreinit_" + name + L"rec.log";
	OpenFileStream(ws->logStream, preLog);
	SetDefaultLog(ws->logStream);
	pugi::xml_document config;

	if (int initConfigResult = InitConfig(config) != status_ok) {
		return initConfigResult;
	}

	wstring recorderXpath = L"/sdr/recording/recorders/sdrd[@name='"
			+ ws->parameters.name + L"']";
	pugi::xml_node recorderConfigNode = config.select_single_node(
			recorderXpath.data()).node();

	if ((ws->parameters.interval =
			recorderConfigNode.attribute(L"interval").as_int()) == 0
			&& ws->parameters.interval <= 1) {
		ws->parameters.interval = 60;
	}

	if ((ws->parameters.countTotal =
			recorderConfigNode.attribute(L"count").as_int()) == 0
			&& ws->parameters.countTotal < -1) {
		ws->parameters.countTotal = -1;
	}

	//for archive testing
	if ((ws->parameters.archiveInterval = recorderConfigNode.attribute(
			L"archiveat").as_int()) == 0)
		ws->parameters.archiveInterval = -1;

	wstring apppath = AppPath();
	ws->parameters.rawCurrentPath =
			apppath
					+ config.select_single_node(L"/sdr/recording/logs/current").node().attribute(
							L"path").as_string();
	if (ws->parameters.rawCurrentPath.empty()) {
		WriteFileLogf(L"Failed to init configuration, code here:");
		return status_config_file_not_found;
	}

	ws->parameters.logDailyPath =
			apppath
					+ config.select_single_node(L"/sdr/recording/logs/daily").node().attribute(
							L"path").as_string();
	if (ws->parameters.logDailyPath.empty()) {
		WriteFileLogf(L"Failed to init configuration, code here:");
		return status_config_file_not_found;

	}

	ws->sysLogPath = ws->parameters.rawCurrentPath + ws->parameters.name
			+ L"rec.log";
	//ws->parameters.rawCurrentFile = ws->parameters.rawCurrentPath;
	ws->parameters.rawCurrentFile += ws->parameters.name + L"rec.sdrd";

	OpenFileStream(ws->rawStream,
			ws->parameters.rawCurrentPath + ws->parameters.rawCurrentFile);
	CloseFileStream(ws->logStream);

	DeleteFile(preLog.data());

	OpenFileStream(ws->logStream, ws->sysLogPath);
	SetDefaultLog(ws->logStream);
	WriteFileLogf(L"Starting recorder " + ws->parameters.name + L"rec.");
	return status_ok;
}
Example #22
0
/*makes the replace*/
INT replace(TCHAR source[MAX_PATH], TCHAR dest[MAX_PATH], DWORD dwFlags, BOOL *doMore)
{
	TCHAR d[MAX_PATH];
	TCHAR s[MAX_PATH];
	HANDLE hFileSrc, hFileDest;
	DWORD  dwAttrib, dwRead, dwWritten;
	LPBYTE buffer;
	BOOL   bEof = FALSE;
	FILETIME srcCreationTime, destCreationTime, srcLastAccessTime, destLastAccessTime;
	FILETIME srcLastWriteTime, destLastWriteTime;
	GetPathCase(source, s);
	GetPathCase(dest, d);
	s[0] = (TCHAR)_totupper(s[0]);
	d[0] = (TCHAR)_totupper(d[0]);
// 	ConOutPrintf(_T("old-src:  %s\n"), s);
// 	ConOutPrintf(_T("old-dest: %s\n"), d);
// 	ConOutPrintf(_T("src:  %s\n"), source);
// 	ConOutPrintf(_T("dest: %s\n"), dest);

	/* Open up the sourcefile */
	hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,NULL, OPEN_EXISTING, 0, NULL);
	if (hFileSrc == INVALID_HANDLE_VALUE)
	{
		ConOutResPrintf(STRING_COPY_ERROR1, source);
		return 0;
	}

	/* Get the time from source file to be used in the comparison with
	   dest time if update switch is set */
	GetFileTime (hFileSrc, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime);

	/* Retrieve the source attributes so that they later on can be
	   inserted in to the destination */
	dwAttrib = GetFileAttributes (source);

	if(IsExistingFile (dest))
	{
		/* Resets the attributes to avoid probles with read only files,
		   checks for read only has been made earlier */
		SetFileAttributes(dest,FILE_ATTRIBUTE_NORMAL);
		/* Is the update flas set? The time has to be controled so that
		   only older files are replaced */
		if(dwFlags & REPLACE_UPDATE)
		{
			/* Read destination time */
			hFileDest = CreateFile(dest, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
				0, NULL);

			if (hFileSrc == INVALID_HANDLE_VALUE)
			{
				ConOutResPrintf(STRING_COPY_ERROR1, dest);
				return 0;
			}

			/* Compare time */
			GetFileTime (hFileDest, &destCreationTime, &destLastAccessTime, &destLastWriteTime);
			if(!((srcLastWriteTime.dwHighDateTime > destLastWriteTime.dwHighDateTime) ||
					(	srcLastWriteTime.dwHighDateTime == destLastWriteTime.dwHighDateTime &&
						srcLastWriteTime.dwLowDateTime > destLastWriteTime.dwLowDateTime)))
			{
				CloseHandle (hFileSrc);
				CloseHandle (hFileDest);
				return 0;
			}
			CloseHandle (hFileDest);
		}
		/* Delete the old file */
		DeleteFile (dest);
	}

	/* Check confirm flag, and take appropriate action */
	if(dwFlags & REPLACE_CONFIRM)
	{
		/* Output depending on add flag */
		if(dwFlags & REPLACE_ADD)
			ConOutResPrintf(STRING_REPLACE_HELP9, dest);
		else
			ConOutResPrintf(STRING_REPLACE_HELP10, dest);
		if( !FilePromptYNA (0))
			return 0;
	}

	/* Output depending on add flag */
	if(dwFlags & REPLACE_ADD)
		ConOutResPrintf(STRING_REPLACE_HELP11, dest);
	else
		ConOutResPrintf(STRING_REPLACE_HELP5, dest);

	/* Make sure source and destination is not the same */
	if(!_tcscmp(s, d))
	{
		ConOutResPaging(TRUE, STRING_REPLACE_ERROR7);
		CloseHandle (hFileSrc);
		*doMore = FALSE;
		return 0;
	}

	/* Open destination file to write to */
	hFileDest = CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	if (hFileDest == INVALID_HANDLE_VALUE)
	{
		CloseHandle (hFileSrc);
		ConOutResPaging(TRUE, STRING_REPLACE_ERROR7);
		*doMore = FALSE;
		return 0;
	}

	/* Get buffer for the copy process */
	buffer = (LPBYTE)VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE);
	if (buffer == NULL)
	{
		CloseHandle (hFileDest);
		CloseHandle (hFileSrc);
		ConOutResPaging(TRUE, STRING_ERROR_OUT_OF_MEMORY);
		return 0;
	}

	/* Put attribute and time to the new destination file */
	SetFileAttributes (dest, dwAttrib);
	SetFileTime (hFileDest, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime);
	do
	{
		/* Read data from source */
		ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL);

		/* Done? */
		if (dwRead == 0)
			break;

		/* Write to destination file */
		WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL);

		/* Done! or ctrl break! */
		if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT))
		{
			ConOutResPuts(STRING_COPY_ERROR3);
			cmd_free (buffer);
			CloseHandle (hFileDest);
			CloseHandle (hFileSrc);
			nErrorLevel = 1;
			return 0;
		}
	}
	while (!bEof);

	/* Return memory and close files */
	VirtualFree (buffer, 0, MEM_RELEASE);
	CloseHandle (hFileDest);
	CloseHandle (hFileSrc);

	/* Return one file replaced */
	return 1;
}
void qtDLGAssembler::InsertNewInstructions()
{
	if(lineEdit->text().length() <= 0)
	{
		close();
		return;
	}

	QMap<quint64,DisAsDataRow>::const_iterator i = m_pCurrentDisassembler->SectionDisAs.constFind(m_instructionOffset);
	if(i == m_pCurrentDisassembler->SectionDisAs.constEnd()) 
	{
		close();
		return;
	}

	QString oldOpcodes = i.value().OpCodes;
	DWORD oldOpcodeLen = oldOpcodes.replace(" ", "").length() / 2,
		newOpcodeLen = NULL;
		
	QFile tempOutput("nanomite.asm");
	tempOutput.open(QIODevice::WriteOnly | QIODevice::Text);
	QTextStream out(&tempOutput);

	if(m_is64Bit)
		out << "BITS 64\n";
	else
		out << "BITS 32\n";

	out << "org 0x" << hex << i.value().Offset << "\r\n";
	out << lineEdit->text();
	tempOutput.close();

	QProcess nasm;
	nasm.setReadChannel(QProcess::StandardOutput);
    nasm.setProcessChannelMode(QProcess::MergedChannels);
    nasm.start("nasm.exe -o nanomite.bin nanomite.asm");
    if (!nasm.waitForStarted())
	{
		QMessageBox::critical(this, "Nanomite", "Unable to launch assembler!", QMessageBox::Ok, QMessageBox::Ok);
		close();
		return;
	}

	while(nasm.state() != QProcess::NotRunning)
	{
        nasm.waitForReadyRead();
		QString errorMessage = nasm.readAll();

		if(errorMessage.contains("nanomite.asm:3:"))
		{
			errorMessage.replace("nanomite.asm:3:","");
			QMessageBox::critical(this, "Nanomite", errorMessage, QMessageBox::Ok, QMessageBox::Ok);
			lineEdit->clear();
			return;
		}
    }
	DeleteFile(L"nanomite.asm");

	HANDLE hFile = CreateFileW(L"nanomite.bin",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,NULL,NULL);
	if(hFile == INVALID_HANDLE_VALUE)
	{
		lineEdit->clear();
		return;
	}

	int iLen = GetFileSize(hFile,NULL);
	LPVOID pFileBuffer = clsMemManager::CAlloc(iLen);
	DWORD BytesRead = NULL;	
	if(!ReadFile(hFile,pFileBuffer,iLen,&BytesRead,NULL))
	{
		CloseHandle(hFile);
		DeleteFile(L"nanomite.bin");
		clsMemManager::CFree(pFileBuffer);
		QMessageBox::critical(this,"Nanomite","no valid opcodes found!",QMessageBox::Ok,QMessageBox::Ok);
		lineEdit->clear();
		return;
	}
	CloseHandle(hFile);
	DeleteFile(L"nanomite.bin");


	if(BytesRead <= 0)
	{
		clsMemManager::CFree(pFileBuffer);
		QMessageBox::critical(this,"Nanomite","no valid opcodes found!",QMessageBox::Ok,QMessageBox::Ok);
		lineEdit->clear();
		return;
	}

	if(oldOpcodeLen >= BytesRead)
		newOpcodeLen = oldOpcodeLen;
	else if(oldOpcodeLen < BytesRead)
	{
		newOpcodeLen = oldOpcodeLen;
		while(newOpcodeLen < BytesRead)
		{
			++i;
			if(i == m_pCurrentDisassembler->SectionDisAs.constEnd()) return;
			oldOpcodes = i.value().OpCodes;
			newOpcodeLen += oldOpcodes.replace(" ", "").length() / 2;
		}
	}

	LPVOID pBuffer = clsMemManager::CAlloc(newOpcodeLen);
	memset(pBuffer,0x90,newOpcodeLen);
	memcpy(pBuffer,pFileBuffer,BytesRead);

	qtDLGPatchManager::AddNewPatch(GetProcessId(m_processHandle), m_processHandle, m_instructionOffset, newOpcodeLen, pBuffer);

	clsMemManager::CFree(pBuffer);
	clsMemManager::CFree(pFileBuffer);

	lineEdit->clear();
	close();
}
Example #24
0
FAR ULONG PASCAL MAPISendMail(
    LHANDLE lhSession,
    ULONG ulUIParam,
    lpMapiMessage lpMessage,
    FLAGS flFlags,
    ULONG ulReserved
)
{
#ifdef DEBUG_BOX
	MessageBox(NULL, "MAPISendMail", NULL, MB_OK);
#endif

	ostrstream out;
	bool q_mark = true;

	// Do basic mailto
	out << "mailto:";
	
	// Look for recipients
	for(int i = 0; i < lpMessage->nRecipCount; i++)
	{
		// Check on recip type and copy in header detail
		switch(lpMessage->lpRecips[i].ulRecipClass)
		{
		case MAPI_ORIG:
			continue;
		case MAPI_TO:
			out << (q_mark ? "?" : "&") << "to=";
			break;
		case MAPI_CC:
			out << (q_mark ? "?" : "&") << "cc=";
			break;
		case MAPI_BCC:
			out << (q_mark ? "?" : "&") << "bcc=";
			break;
		}
		q_mark = false;
		
		// copy in address detail
		const char* p = lpMessage->lpRecips[i].lpszAddress;
		if (!::strncmp(p, "SMTP:", 5))
			p += 5;
		char* encoded = EncodeURL(p);
		out << (encoded ? encoded : p);
		if (encoded)
			free(encoded);
	}

	// Look for subject
	if (lpMessage->lpszSubject && *lpMessage->lpszSubject)
	{
		char* encoded = EncodeURL(lpMessage->lpszSubject);
		out << (q_mark ? "?" : "&") << "subject=" << (encoded ? encoded : lpMessage->lpszSubject);
		q_mark = false;
		if (encoded)
			free(encoded);
	}

	// Look for body
	if (lpMessage->lpszNoteText && *lpMessage->lpszNoteText)
	{
		char* encoded = EncodeURL(lpMessage->lpszNoteText);
		out << (q_mark ? "?" : "&") << "body=" << (encoded ? encoded : lpMessage->lpszNoteText);
		q_mark = false;
		if (encoded)
			free(encoded);
	}

	// Look for files
	for(int i = 0; i < lpMessage->nFileCount; i++)
	{
		// Get name of attachment
		const char* fpath = lpMessage->lpFiles[i].lpszPathName;
		const char* fname = lpMessage->lpFiles[i].lpszFileName;
		
		if (!fname || !*fname || strrchr(fname, '\\'))
		{
			fname = strrchr(fpath, '\\');
			if (fname) fname++;
		}
		
		// Must duplicate this attachment into Temp
		char temp_path[MAX_PATH];
		char temp_path_[MAX_PATH];
		char temp_dir[MAX_PATH];
		if (GetTempPath(MAX_PATH, temp_dir))
		{
 			strcpy(temp_path, temp_dir);
 			strcpy(temp_path_, temp_dir);
 			strcat(temp_path_, "_");
 			strcat(temp_path, fname);
 			strcat(temp_path_, fname);
 		}
 		else
 		{
#ifdef DEBUG_BOX
			DWORD err = GetLastError();
			char temp_err[1024];
			snprintf(temp_err, 1024, "No temp directory, errno = %ld", err);
			MessageBox(NULL, temp_err, NULL, MB_OK);
#endif
 			// Fail if no temp directory
			return MAPI_E_FAILURE;
 		}

 		// If source file is in TEMP then we must copy it
 		if (!strncmp(temp_dir, fpath, strlen(temp_dir)))
 		{
	 		// Do copy to standard name
	 		if (!CopyFile(fpath, temp_path_, true))
	 		{
	 			DWORD last_err = GetLastError();

#ifdef DEBUG_BOX
 				char temp_err[1024];
 				snprintf(temp_err, 1024, "Orig. file: \"%s\"  Temp. file: \"%s\"  errno = %ld", fpath, temp_path_, last_err);
				MessageBox(NULL, temp_err, NULL, MB_OK);
#endif

 				if (last_err == ERROR_FILE_EXISTS)
 				{
					DeleteFile(temp_path_);
		 			if (!CopyFile(fpath, temp_path_, true))
		 			{
#ifdef DEBUG_BOX
		 				DWORD err = GetLastError();
		 				char temp_err[1024];
		 				snprintf(temp_err, 1024, "Unable to copy to temp directory after removal, errno = %ld", err);
						MessageBox(NULL, temp_err, NULL, MB_OK);
#endif
	 	 				return MAPI_E_FAILURE;
	 	 			}
	 			}
	 			else
	 			{
 	 				return MAPI_E_FAILURE;
 	 			}
	 		}
			strcpy(temp_path, temp_path_);
		}
		else
			strcpy(temp_path, fpath);
 
		// Encode attachment name and add to URL
		char* encoded = EncodeURL(temp_path);
		out << (q_mark ? "?" : "&") << "x-mulberry-file=" << (encoded ? encoded : temp_path);
		q_mark = false;
		if (encoded)
			free(encoded);
	}

	// NULL terminate the string
	out << ends;

#ifdef DEBUG_BOX
	MessageBox(NULL, out.str(), NULL, MB_OK);
	out.freeze(false);
#endif

	// Now do Shell open of mailto URL
	char dir[MAX_PATH];
	if (GetCurrentDirectory(MAX_PATH, dir))
	{
		ShellExecute((HWND) ulUIParam, "open", out.str(), 0L, dir, 0);
		out.freeze(false);
	}

	return SUCCESS_SUCCESS;
}
Example #25
0
File: mcdr.cpp Project: msdsgn/mcdr
/* ======================================================================= */
BOOL EncodeTrack(PWINDOWHANDLES H, DWORD Index, PCHAR BasePath, HANDLE CDHandle, PCDTRACK CDTrackData, PDWORD DiscCurrent, PDWORD DiscTotal, PDWORD TrackCount)
{
  Log(LOG_WRITE, "Encoding track %u/%u; Sector %u-%u/%u", Index+1, *TrackCount, CDTrackData[Index].Address, CDTrackData[Index].Address + CDTrackData[Index].Length - 1, CDTrackData[Index].Length);

  CHAR MP3FilePath[MAX_PATH];
  CHAR MP3FilePathFancy[MAX_PATH];

  HANDLE MP3FileHandle = INVALID_HANDLE_VALUE;
  static lame_global_flags *GFP = NULL;

  if(OneTrackOnly == 0)
  {
    _snprintf(MP3FilePath, MAX_PATH, "%s\\Track %u.mp3", BasePath, Index + 1);
    MakeFancyPath(MP3FilePath, MP3FilePathFancy, 35);
    SetLabel(H->WT, "Creating file %s...", MP3FilePath);
    MP3FileHandle = CreateFile(MP3FilePath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  }
  else
  {
    _snprintf(MP3FilePath, MAX_PATH, "%s\\Audio.mp3", BasePath, Index + 1);
    MakeFancyPath(MP3FilePath, MP3FilePathFancy, 35);
    switch(OneTrackOnly)
    {
      case 1:
        SetLabel(H->WT, "Creating solid file %s...", MP3FilePath);
        MP3FileHandle = CreateFile(MP3FilePath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        OneTrackOnly = 2;
        break;
      case 2:
        SetLabel(H->WT, "Re-opening file %s...", MP3FilePath);
        MP3FileHandle = CreateFile(MP3FilePath, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if(MP3FileHandle != INVALID_HANDLE_VALUE)
          SetFilePointer(MP3FileHandle, 0, NULL, FILE_END);
        break;
    }
  }

  BOOL Success = TRUE;
  INT EncoderReturnCode = 0;

  if(MP3FileHandle != INVALID_HANDLE_VALUE)
  {
    Log(LOG_WRITE, "Created file %s", MP3FilePath);

    DWORD DiscLastCurrent = *DiscCurrent;
    DWORD SectorTotal = CDTrackData[Index].Length/SECTORS_AT_READ;
    DWORD MP3BytesWritten;

    SendMessage(H->PO, PBM_SETRANGE32, 0, SectorTotal);
    SendMessage(H->PO, PBM_SETPOS, 0, 0);
    SendMessage(H->PA, PBM_SETRANGE32, 0, *DiscTotal);

    if(GFP == NULL)
    {
      GFP = lame_init();

      lame_set_preset(GFP, MP3Quality);
      lame_set_copyright(GFP, 1);
      lame_set_original(GFP, 1);
      lame_set_error_protection(GFP, 1);
      lame_set_extension(GFP, 1);
      lame_set_quality(GFP, Quality);

      EncoderReturnCode = lame_init_params(GFP);
    }

    if(EncoderReturnCode == 0)
    {
      DWORD dwWAVBufferSize=(1152 * lame_get_num_channels(GFP));
      DWORD dwMP3BufferSize=(DWORD)(1.25*(dwWAVBufferSize/lame_get_num_channels(GFP))+7200);
      PBYTE MP3Buffer = new BYTE[dwMP3BufferSize];
      PBYTE CDBuffer = new BYTE[SECTORS_AT_READ * RAW_SECTOR_SIZE];
      INT nOutputSamples;
      DWORD CDBytesWritten;
      RAW_READ_INFO Info;
      Info.TrackMode = CDDA;
      Info.SectorCount = SECTORS_AT_READ;
      DWORD SectorCurrent;
      TCHAR NumWritten[30];
      TCHAR NumWrittenKB[30];

      for(SectorCurrent = 0; SectorCurrent < SectorTotal; ++SectorCurrent, ++*DiscCurrent)
      {
        Info.DiskOffset.QuadPart = (CDTrackData[Index].Address + SectorCurrent*SECTORS_AT_READ) * CD_SECTOR_SIZE;
        MP3BytesWritten = SetFilePointer(MP3FileHandle, 0, NULL, FILE_CURRENT);
        Comma(MP3BytesWritten, NumWritten, sizeof(NumWritten));
        Comma(MP3BytesWritten / 1024, NumWrittenKB, sizeof(NumWrittenKB));
        SetLabel(H->WT, "Encoding track %u of %u and sector %u of %u\nTo %s\nWritten %s bytes (%s KB) to file", Index + 1, *TrackCount, SectorCurrent, SectorTotal - 1, MP3FilePathFancy, NumWritten, NumWrittenKB);
        if(DeviceIoControl(CDHandle, IOCTL_CDROM_RAW_READ, &Info, sizeof(Info), CDBuffer, SECTORS_AT_READ*RAW_SECTOR_SIZE, &CDBytesWritten, NULL) != 0)
        {
          if(EncodeAudioBuffer(CDBuffer, CDBytesWritten, dwWAVBufferSize, MP3FileHandle, MP3Buffer, GFP) == FALSE)
          {
            Log(LOG_WRITE, "Encoding of audio buffer failed");
            Success = FALSE;
            break;
          }
        }
        else
        {
          DWORD ErrorCode = GetLastError();
          if(ErrorCode == ERROR_INVALID_FUNCTION)
          {
            Log(LOG_WRITE, "Track %u is not a valid CDDA track", Index + 1);
            Success = FALSE;
            break;
          }
          else if(ErrorCode != ERROR_INVALID_PARAMETER)
          {
            Log(LOG_WRITE, "Error code %u reading track %u!", ErrorCode, Index + 1);
            Success = FALSE;
            break;
          }
        }
        SendMessage(H->PO, PBM_SETPOS, SectorCurrent, 0);
        SendMessage(H->PA, PBM_SETPOS, *DiscCurrent, 0);
        Percentage = (float)((float)*DiscCurrent / (float)*DiscTotal) * 100;
      }

      if(Success == FALSE)
      {
        *DiscTotal -= SectorTotal;
        SectorTotal = 0;
      }
      else if(OneTrackOnly == 0 || Index+1 == *TrackCount)
      {
        nOutputSamples = lame_encode_flush_nogap(GFP, MP3Buffer, LAME_MAXMP3BUFFER);

        if(nOutputSamples > 0)
        {
          if(WriteFile(MP3FileHandle, MP3Buffer, nOutputSamples, &MP3BytesWritten, NULL) == FALSE)
          {
            Log(LOG_WRITE, "Failed to write %u final bytes to file", nOutputSamples);
            Success = FALSE;
          }
          else if(nOutputSamples != (int)MP3BytesWritten)
          {
            Log(LOG_WRITE, "Written %u final bytes instead of %u bytes to file", MP3BytesWritten, nOutputSamples);
            Success = FALSE;
          }
        }
        else if(nOutputSamples < 0)
        {
          Log(LOG_WRITE, "Error code %d flushing encoded audio buffer", nOutputSamples);
          Success = FALSE;
        }
      }

      *DiscCurrent = DiscLastCurrent + SectorTotal;
      SendMessage(H->PO, PBM_SETPOS, *DiscCurrent, 0);
    }
    else
    {
      Log(LOG_WRITE, "Error code %d initialising audio encoder", EncoderReturnCode);
      Success = FALSE;
    }

    MP3BytesWritten = SetFilePointer(MP3FileHandle, 0, NULL, FILE_CURRENT);
    if(CloseHandle(MP3FileHandle) == FALSE)
    {
      Log(LOG_WRITE, "Error code %u closing file handle");
      Success = FALSE;
    }
    if(OneTrackOnly == 0 && (MP3BytesWritten == 0 || Success == FALSE))
    {
      if(DeleteFile(MP3FilePath) == FALSE)
        Log(LOG_WRITE, "Error code %u deleting file");
      else
        Log(LOG_WRITE, "Deleted the file due to error");
    }
    else Log(LOG_WRITE, "Written %u bytes to file", MP3BytesWritten);
  }
  else
  {
    Log(LOG_WRITE, "Error code %u creating %s", GetLastError(), MP3FilePath);
    Success = FALSE;
  }

  if(EncoderReturnCode == 0 && (OneTrackOnly == 0 || Index+1 == *TrackCount))
  {
    lame_close(GFP);
    GFP = NULL;
  }

  return Success;
}
Example #26
0
int CBiosDlg::UpdateBios(void)
{
	BOOL retval;
	PROCESS_INFORMATION pi={0};
	STARTUPINFOA si={0};
	SECURITY_ATTRIBUTES sa={0};
	HANDLE hReadPipe,hWritePipe;
	sa.bInheritHandle=TRUE;
	sa.nLength=sizeof SECURITY_ATTRIBUTES;
	sa.lpSecurityDescriptor=NULL;
	retval=CreatePipe(&hReadPipe,&hWritePipe,&sa,0);
	si.cb=sizeof STARTUPINFOA;
	si.wShowWindow=SW_HIDE;
	si.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
	si.hStdOutput=si.hStdError=hWritePipe;
	DWORD dwLen,dwRead,retCode1=-1,retCode2=-1,retDet=-1;
	UINT nActualBiosSize=0,nLock=0;
	char buff[256] = {0};
	TCHAR szErrMsg[256]={0};
	CFile fp;
	CFile fp1,fp2;
	DWORD fLen;
	BYTE* fBuff;
	CStringA cmd;
	CBytTool* t1=0;
	CChtTool86* t2=0;
	CChtTool64* t3=0;
	CHWToolDlg* pParent = (CHWToolDlg*)((CHWToolApp*)AfxGetApp())->m_pMainWnd;
	if (m_nType == 1)
	{
		t2 = new CChtTool86();
	}
	else if (m_nType == 2)
	{
		t1 = new CBytTool();
	}
	else if (m_nType == 3)
	{
		t3 = new CChtTool64();
	}
	SetCurrentDirectory(m_szTempDir);
	m_nSN = ((CButton*)GetDlgItem(IDC_SNCHECK))->GetCheck();
	retval=CreateProcessA(NULL,"cmd.exe /c fptw.exe -i",&sa,&sa,TRUE,0,NULL,NULL,&si,&pi);
	if(retval)
	{
		WaitForSingleObject(pi.hThread,INFINITE);//等待命令行执行完毕
		GetExitCodeProcess(pi.hProcess,&retDet);
		CloseHandle(pi.hThread);
		CloseHandle(pi.hProcess);
		if (retDet)
		{
			_tcscpy(szErrMsg,TEXT("不支持当前平台!"));
			goto end;
		}
		dwLen=GetFileSize(hReadPipe,NULL);
		char* szRegion = new char[dwLen];
		ReadFile(hReadPipe,szRegion,dwLen,&dwRead,NULL);
		if (dwRead)
		{
			char* szToken=strstr(szRegion,"BIOS       - Base: ");
			char szLen[9]={0};
			if (szToken)
			{
				strncpy(szLen,szToken+19,8);
				sscanf(szLen,"%x",&nActualBiosSize);
				nActualBiosSize = 0x800000 - nActualBiosSize;
			}
		}
		delete szRegion;
	}
	if (m_nBiosSize != nActualBiosSize)
	{
		wsprintf(szErrMsg,TEXT("当前BIOS分区大小与机器里的不一致, 机器中的大小为:0x%X, 文件中的大小为:0x%X!"),nActualBiosSize,m_nBiosSize);
		goto end;
	}

	retval=CreateProcessA(NULL,"cmd.exe /c fptw.exe -dumplock",&sa,&sa,TRUE,0,NULL,NULL,&si,&pi);
	if(retval)
	{
		WaitForSingleObject(pi.hThread,INFINITE);
		CloseHandle(pi.hThread);
		CloseHandle(pi.hProcess);
		dwLen=GetFileSize(hReadPipe,NULL);
		char* szRegion = new char[dwLen];
		ReadFile(hReadPipe,szRegion,dwLen,&dwRead,NULL);
		if (dwRead)
		{
			char* szToken=strstr(szRegion,"Host CPU master:    ");
			int a,b,c,d,nCPU=0,nTXE=0;
			if (szToken)
			{
				szToken += 20;
				if (4 == sscanf(szToken,"%x %x %x %x",&a,&b,&c,&d))
				{
					nCPU = (a<<24) + (b<<16) + (c<<8) + d;
				}
			}
			szToken=strstr(szRegion,"TXE region master:  ");
			if (szToken)
			{
				szToken += 20;
				if (4 == sscanf(szToken,"%x %x %x %x",&a,&b,&c,&d))
				{
					nTXE = (a<<24) + (b<<16) + (c<<8) + d;
				}
			}
			if (nCPU == 0x0B0A && nTXE == 0x0D0C)
			{
				nLock = 1;
			}
		}
		SetDlgItemText(IDC_STATUS,nLock?TEXT("TXE/ME 已锁定"):TEXT("TXE/ME 未锁定"));
		delete szRegion;
	}
	Sleep(2000);
	//////////////////////////////////////////////////////////////////////
	retval=CreateProcessA(NULL,"cmd.exe /c Check.exe",&sa,&sa,TRUE,0,NULL,NULL,&si,&pi);
	if(retval)
	{
		WaitForSingleObject(pi.hThread,INFINITE);
		GetExitCodeProcess(pi.hProcess,&retCode1);
		CloseHandle(pi.hThread);
		CloseHandle(pi.hProcess);
		if (retCode1 != 0)
		{
			m_bExistKey = FALSE;
			SetDlgItemText(IDC_STATUS,TEXT("未发现微软密钥"));
		}
		else
		{
			SetDlgItemText(IDC_STATUS,TEXT("发现微软密钥,保存中......"));
			dwLen=GetFileSize(hReadPipe,NULL);
			char *buff=new char [dwLen+1];
			char dpk[30]={0};
			char* vptr,*token="Product key:       ";
			memset(buff,0,dwLen+1);
			retval=ReadFile(hReadPipe,buff,dwLen,&dwRead,NULL);
			vptr=strstr(buff+700,token);
			if (vptr)
			{
				vptr +=strlen(token);
				strncpy(dpk,vptr,29);
				char szDPK[20]={0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
								0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
								0x1d,0x00,0x00,0x00};
				fp.Open(TEXT("key.bin"),CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
				fp.Write(szDPK,20);
				fp.Write(dpk,29);
				fp.Close();
				m_bExistKey = TRUE;
			}
			delete buff;
		}
	}

	if (!fp1.Open(m_szPath,CFile::modeRead|CFile::typeBinary))
	{
		_tcscpy(szErrMsg,TEXT("未发现BIOS文件,请确认其是否存在!"));
		goto end;
	}
	fLen=(DWORD)fp1.GetLength();
	fBuff = new BYTE[fLen];
	fp1.Read(fBuff,fLen);
	fp1.Close();
	if (!fp2.Open(TEXT("fw.bin"),CFile::modeCreate|CFile::modeReadWrite))
	{
		delete fBuff;
		_tcscpy(szErrMsg,TEXT("打开BIOS文件失败!"));
		goto end;
	}
	fp2.Write(fBuff,fLen);
	fp2.Close();
	delete fBuff;

	if (nLock == 0)
	{
		cmd="cmd.exe /c fptw.exe -f fw.bin";
	}
	else
	{
		cmd="cmd.exe /c fptw.exe -f fw.bin -bios";
	}
	Sleep(2000);
	SetDlgItemText(IDC_STATUS,TEXT("正在刷写BIOS......"));
	sa.bInheritHandle=0;
	si.wShowWindow=SW_SHOW;
	retval=CreateProcessA(NULL,(LPSTR)(LPCSTR)cmd,&sa,&sa,0,0,NULL,NULL,&si,&pi);
	WaitForSingleObject(pi.hThread,INFINITE);
	GetExitCodeProcess(pi.hProcess,&retCode1);
	CloseHandle(pi.hThread);
	CloseHandle(pi.hProcess);
	DeleteFile(TEXT("fw.bin"));
	if (retCode1 == 0)
	{
		SetDlgItemText(IDC_STATUS,TEXT("升级完成!"));
		Sleep(1000);
	}
	else
	{
		SetDlgItemText(IDC_STATUS,TEXT("升级失败!"));
		_tcscpy(szErrMsg,TEXT("BIOS升级失败!"));
		goto end;
	}

	si.wShowWindow=SW_HIDE;
	if (1)
	{
		CBiosInfo* pInfo = ((CHWToolApp*)AfxGetApp())->m_BiosInfo;
		strcpy(buff,"cmd.exe /c amidewin.exe /su \"");
		if (strncmp(pInfo->m_BiosInfoA.m_szSU,"00020003000400050006000700080009",32) == 0)
		{
			GUID guid;
			CoCreateGuid(&guid);
			memset(pInfo->m_BiosInfoA.m_szSU,0,sizeof(pInfo->m_BiosInfoA.m_szSU));
			sprintf(pInfo->m_BiosInfoA.m_szSU,"%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X",guid.Data1,guid.Data2,guid.Data3,guid.Data4[0],guid.Data4[1],guid.Data4[2],guid.Data4[3],guid.Data4[4],guid.Data4[5],guid.Data4[6],guid.Data4[7]);
			mbstowcs(pInfo->m_BiosInfoW.m_wszSU,pInfo->m_BiosInfoA.m_szSU,64);
			pParent->m_pDlg[1]->SetDlgItemText(IDC_UUID,pInfo->m_BiosInfoW.m_wszSU);
		}

		if (strlen(pInfo->m_BiosInfoA.m_szSU))
		{
			strcat(buff,pInfo->m_BiosInfoA.m_szSU);
			strcat(buff,"\"");
			retval=CreateProcessA(NULL,buff,&sa,&sa,0,0,NULL,NULL,&si,&pi);
			WaitForSingleObject(pi.hThread,INFINITE);
			CloseHandle(pi.hThread);
			CloseHandle(pi.hProcess);
		}
	}
	if (m_nSN == BST_CHECKED)
	{
		if (m_strSSN.GetLength())
		{
			Sleep(2000);
			SetDlgItemText(IDC_STATUS,TEXT("正在刷写保留的序列号......"));
			CBiosInfo* pInfo = ((CHWToolApp*)AfxGetApp())->m_BiosInfo;
			strcpy(buff,"cmd.exe /c amidewin.exe /ss \"");
			strcat(buff,pInfo->m_BiosInfoA.m_szSS);
			strcat(buff,"\"");
			retval=CreateProcessA(NULL,buff,&sa,&sa,0,0,NULL,NULL,&si,&pi);
			WaitForSingleObject(pi.hThread,INFINITE);
			CloseHandle(pi.hThread);
			CloseHandle(pi.hProcess);
		}
	}

	if (m_bExistKey)
	{
		if (fp.Open(TEXT("key.bin"),CFile::modeRead))
		{
			fp.Close();
			Sleep(2000);
			SetDlgItemText(IDC_STATUS,TEXT("正在重新写入机器中的微软密钥......"));
			CreateProcessA(NULL,"cmd.exe /c afuwin.exe /oad",&sa,&sa,0,0,NULL,NULL,&si,&pi);
			WaitForSingleObject(pi.hThread,INFINITE);
			CloseHandle(pi.hThread);
			CloseHandle(pi.hProcess);
			CreateProcessA(NULL,"cmd.exe /c afuwin.exe /akey.bin",&sa,&sa,0,0,NULL,NULL,&si,&pi);
			WaitForSingleObject(pi.hThread,INFINITE);
			GetExitCodeProcess(pi.hProcess,&retCode2);
			CloseHandle(pi.hThread);
			CloseHandle(pi.hProcess);
			if (retCode2 == 0)
			{
				SetDlgItemText(IDC_STATUS,TEXT("刷KEY成功!"));
			}
			else
			{
				SetDlgItemText(IDC_STATUS,TEXT("刷KEY失败!"));
			}
			DeleteFile(TEXT("key.bin"));
		}
	}
end:
	CloseHandle(hWritePipe);
	CloseHandle(hReadPipe);
	if (t1) delete t1;
	if (t2) delete t2;
	if (t3) delete t3;
	EnableMenuItem(::GetSystemMenu(GetParent()->m_hWnd,FALSE),SC_CLOSE,MF_BYCOMMAND|MF_ENABLED);
	GetParent()->GetDlgItem(IDC_TAB1)->EnableWindow();
	GetDlgItem(IDC_SNCHECK)->EnableWindow();
	GetDlgItem(IDC_UPDATE)->EnableWindow();
	GetDlgItem(IDC_BROWSE)->EnableWindow();
	if (retCode1 == 0)
	{
		HANDLE hToken;
		TOKEN_PRIVILEGES tkp;
		TCHAR szTmpDir[2048]={0};

		_tcscpy(szTmpDir,_tgetenv(TEXT("SystemRoot")));
		_tcscat(szTmpDir,TEXT("\\Temp"));
		SetCurrentDirectory(szTmpDir);
		DeleteFile(TEXT("Check.exe"));
		DeleteFile(TEXT("afuwin.exe"));
		DeleteFile(TEXT("amidewin.exe"));
		DeleteFile(TEXT("amifldrv32.sys"));
		DeleteFile(TEXT("amifldrv64.sys"));
		Sleep(1000);
		OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken);
		LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid);
		tkp.PrivilegeCount = 1;
		tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
		AdjustTokenPrivileges(hToken,FALSE,&tkp,sizeof(TOKEN_PRIVILEGES),NULL,0);
		ExitWindowsEx(EWX_FORCE|EWX_REBOOT,0);
		CloseHandle(hToken);
	}
	else
	{
		MessageBox(szErrMsg,TEXT("升级错误"),MB_ICONERROR);
	}

	return 0;
}
Example #27
0
void CDCAntivirusAlertDlg::OnDel()
{
	DeleteFile(m_sFilePath);
	CDialog::OnOK();
}
Example #28
0
/* Tar file extraction
 * gzFile in, handle of input tarball opened with gzopen
 * int cm, compressionMethod
 * int junkPaths, nonzero indicates to ignore stored path (don't create directories)
 * enum KeepMode keep, indicates to perform if file exists
 * int iCnt, char *iList[], argv style list of files to extract, {0,NULL} for all
 * int xCnt, char *xList[], argv style list of files NOT to extract, {0,NULL} for none
 * int failOnHardLinks, if nonzero then will treat failure to create a hard link same as
 *   failure to create a regular file, 0 prints a warning if fails - note that hardlinks
 *   will always fail on Windows prior to NT 5 (Win 2000) or later and non NTFS file systems.
 *
 * returns 0 (or positive value) on success
 * returns negative value on error, where
 *   -1 means error reading from tarball
 *   -2 means error extracting file from tarball
 *   -3 means error creating hard link
 */
int tgz_extract(gzFile in, int cm, int junkPaths, enum KeepMode keep, int iCnt, TCHAR *iList[], int xCnt, TCHAR *xList[], int failOnHardLinks)
{
  int           getheader = 1;    /* assume initial input has a tar header */
  HANDLE        outfile = INVALID_HANDLE_VALUE;

  union         tar_buffer buffer;
  unsigned long remaining;
  TCHAR          fname[BLOCKSIZE]; /* must be >= BLOCKSIZE bytes */
  time_t        tartime;

  /* do any prep work for extracting from compressed TAR file */
  if (cm_init(in, cm))
  {
    PrintMessage(_T("tgz_extract: unable to initialize decompression method."));
    cm_cleanup(cm);
    return -1;
  }
  
  while (1)
  {
    if (readBlock(cm, &buffer) < 0) return -1;
      
    /*
     * If we have to get a tar header
     */
    if (getheader >= 1)
    {
      /*
       * if we met the end of the tar
       * or the end-of-tar block,
       * we are done
       */
      if (/* (len == 0)  || */ (buffer.header.name[0]== 0)) break;

      /* compute and check header checksum, support signed or unsigned */
      if (!valid_checksum(&(buffer.header)))
      {
        PrintMessage(_T("tgz_extract: bad header checksum"));
        cm_cleanup(cm);
        return -1;
      }

      /* store time, so we can set the timestamp on files */
      tartime = (time_t)getoct(buffer.header.mtime,12);

      /* copy over filename chunk from header, avoiding overruns */
      if (getheader == 1) /* use normal (short or posix long) filename from header */
      {
        /* NOTE: prepends any prefix, including separator, and ensures terminated */
        memset(fname, 0, sizeof(fname));
		getFullName(&buffer, fname);
      }
      else /* use (GNU) long filename that preceeded this header */
      {
#if 0
        /* if (strncmp(fname,buffer.header.name,SHORTNAMESIZE-1) != 0) */
        char fs[SHORTNAMESIZE];   /* force strings to same max len, then compare */
        lstrcpyn(fs, fname, SHORTNAMESIZE);
        fs[SHORTNAMESIZE-1] = '\0';
        buffer.header.name[SHORTNAMESIZE-1] = '\0';
        if (lstrcmp(fs, buffer.header.name) != 0)
        {
          PrintMessage(_T("tgz_extract: mismatched long filename"));
          cm_cleanup(cm);
          return -1;
        }
#else
		PrintMessage(_T("tgz_extract: using GNU long filename [%s]"), fname);
#endif
      }
      /* LogMessage("buffer.header.name is:");  LogMessage(fname); */


      switch (buffer.header.typeflag)
      {
        case DIRTYPE:
		  dirEntry:
          if (!junkPaths)
          {
            safetyStrip(fname);
            makedir(fname);
          }
	      break;
		case LNKTYPE:   /* hard link */ 
		case CONTTYPE:  /* contiguous file, for compatibility treat as normal */
        case REGTYPE:
        case AREGTYPE:
	      /* Note: a file ending with a / may actually be a BSD tar directory entry */
	      if (fname[strlen(fname)-1] == '/')
	        goto dirEntry;

	      remaining = getoct(buffer.header.size,12);
	      if ( /* add (remaining > 0) && to ignore 0 zero byte files */
               ( (iList == NULL) || (matchname(fname, iCnt, iList, junkPaths)) ) &&
               (!matchname(fname, xCnt, xList, junkPaths))
             )
	      {
			  if (!junkPaths) /* if we want to use paths as stored */
			  {
	              /* try creating directory */
	              TCHAR *p = tstrrchr(fname, '/');
	              if (p != NULL) 
	              {
	                *p = '\0';
	                makedir(fname);
	                *p = '/';
	              }
			  }
			  else
			  {
	              /* try ignoring directory */
	              TCHAR *p = tstrrchr(fname, '/');
	              if (p != NULL) 
	              {
	                /* be sure terminating '\0' is copied and */
	                /* use ansi memcpy equivalent that handles overlapping regions */
	                MoveMemory(fname, p+1, (strlen(p+1) + 1) * sizeof(TCHAR) );
	              }
	          }
	          if (*fname) /* if after stripping path a fname still exists */
	          {
	            /* Attempt to open the output file and report action taken to user */
	            const TCHAR szERRMsg[] = _T("Error: Could not create file "),
	                        szSUCMsg[] = _T("Writing "),
	                        szSKPMsg[] = _T("Skipping ");
	            const TCHAR * szMsg = szSUCMsg;

	            safetyStrip(fname);

				if (buffer.header.typeflag == LNKTYPE)
				{
					outfile = INVALID_HANDLE_VALUE;
					/* create a hardlink if possible, else produce just a warning unless failOnHardLinks is true */
					if (!MakeHardLink(fname, buffer.header.linkname))
					{
						PrintMessage(_T("Warning: unable to create hard link %s [%d]"), fname, GetLastError());
						if (failOnHardLinks) 
						{
							cm_cleanup(cm);
							return -3;
						}
					}
					else
					{
						outfile = CreateFile(fname,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
						goto setTimeAndCloseFile;
					}
				} else 
				{
	            /* Open the file for writing mode, creating if doesn't exist and truncating if exists and overwrite mode */
	            outfile = CreateFile(fname,GENERIC_WRITE,FILE_SHARE_READ,NULL,(keep==OVERWRITE)?CREATE_ALWAYS:CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);

	            /* failed to open file, either valid error (like open) or it already exists and in a keep mode */
	            if (outfile == INVALID_HANDLE_VALUE)
	            {
	              /* if skip existing or only update existing and failed to open becauses exists */
	              if ((keep!=OVERWRITE) && (GetLastError()==ERROR_FILE_EXISTS))
	              {
	                /* assume skipping initially (mode==SKIP or ==UPDATE with existing file newer) */
	                szMsg = szSKPMsg; /* and update output message accordingly */

					/* if in update mode, check filetimes and reopen in overwrite mode */
	                if (keep == UPDATE)
	                {
	                  FILETIME ftm_a;
                      HANDLE h;
                      WIN32_FIND_DATA ffData;
 
	                  cnv_tar2win_time(tartime, &ftm_a); /* archive file time */
	                  h = FindFirstFile(fname, &ffData); /* existing file time */

                      if (h!=INVALID_HANDLE_VALUE)
                        FindClose(h);  /* cleanup search handle */
                      else
                        goto ERR_OPENING;

                      /* compare date+times, is one in tarball newer? */
                      if (*((LONGLONG *)&ftm_a) > *((LONGLONG *)&(ffData.ftLastWriteTime)))
                      {
                        outfile = CreateFile(fname,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
                        if (outfile == INVALID_HANDLE_VALUE) goto ERR_OPENING;
                        szMsg = szSUCMsg;
                      }
	                }
	              }
	              else /* in overwrite mode or failed for some other error than exists */
	              {
                    ERR_OPENING:
	                PrintMessage(_T("%s%s [%d]"), szERRMsg, fname, GetLastError());
	                cm_cleanup(cm);
	                return -2;
	              }
	            }

 	            /* Inform user of current extraction action (writing, skipping file XYZ) */
	            PrintMessage(_T("%s%s"), szMsg, fname);
				}
	          }
	      }
	      else
	          outfile = INVALID_HANDLE_VALUE;

	      /*
	       * could have no contents, in which case we close the file and set the times
	       */
	      if (remaining > 0)
	          getheader = 0;
		  else
	      {
	          setTimeAndCloseFile:
	          getheader = 1;
	          if (outfile != INVALID_HANDLE_VALUE)
	          {
	              FILETIME ftm;
 
	              cnv_tar2win_time(tartime, &ftm);
	              SetFileTime(outfile,&ftm,NULL,&ftm);
	              CloseHandle(outfile);
	              outfile = INVALID_HANDLE_VALUE;
	          }
		  }

	      break;
		case GNUTYPE_LONGLINK:
		case GNUTYPE_LONGNAME:
		{
	      remaining = getoct(buffer.header.size,12);
	      if (readBlock(cm, fname) < 0) return -1;
	      fname[BLOCKSIZE-1] = '\0';
	      if ((remaining >= BLOCKSIZE) || ((unsigned)strlen(fname) > remaining))
	      {
	          PrintMessage(_T("tgz_extract: invalid long name"));
	          cm_cleanup(cm);
	          return -1;
	      }
	      getheader = 2;
	      break;
		}
        default:
/*
	      if (action == TGZ_LIST)
	          printf(" %s     <---> %s\n",strtime(&tartime),fname);
*/
	      break;
      }
    }
    else  /* (getheader == 0) */
    {
      unsigned int bytes = (remaining > BLOCKSIZE) ? BLOCKSIZE : remaining;
	  unsigned long bwritten;

      if (outfile != INVALID_HANDLE_VALUE)
      {
          WriteFile(outfile,buffer.buffer,bytes,&bwritten,NULL);
		  if (bwritten != bytes)
          {
			  PrintMessage(_T("Error: write failed for %s"), fname);
              CloseHandle(outfile);
              DeleteFile(fname);

              cm_cleanup(cm);
              return -2;
          }
      }
      remaining -= bytes;
      if (remaining == 0) goto setTimeAndCloseFile;
    }
  } /* while(1) */
  
  cm_cleanup(cm);

  return 0;
}
Example #29
0
void SetInformationDirectory()
{
	strcpy(InformationDirectory,"d:\\");
	DeleteFile("d:\\log.inv");
}
Example #30
0
__declspec(dllexport) void download (HWND   parent,
              int    string_size,
              char   *variables,
              nsis_stack_t **stacktop)
{
  char buf[1024];
  char url[1024];
  char filename[1024];
  static char proxy[1024];
  BOOL bSuccess=FALSE;
  int timeout_ms=30000;
  int getieproxy=1;
  int manualproxy=0;
  int translation_version;

  char *error=NULL;

  // translation version 2 & 1
  static char szDownloading[1024]; // "Downloading %s"
  static char szConnecting[1024];  // "Connecting ..."
  static char szSecond[1024];      // " (1 second remaining)" for v2
                                   // "second" for v1
  static char szMinute[1024];      // " (1 minute remaining)" for v2
                                   // "minute" for v1
  static char szHour[1024];        // " (1 hour remaining)" for v2
                                   // "hour" for v1
  static char szProgress[1024];    // "%skB (%d%%) of %skB at %u.%01ukB/s" for v2
                                   // "%dkB (%d%%) of %dkB at %d.%01dkB/s" for v1

  // translation version 2 only
  static char szSeconds[1024];     // " (%u seconds remaining)"
  static char szMinutes[1024];     // " (%u minutes remaining)"
  static char szHours[1024];       // " (%u hours remaining)"

  // translation version 1 only
  static char szPlural[1024];      // "s";
  static char szRemaining[1024];   // " (%d %s%s remaining)";

  EXDLL_INIT();

  popstring(url);
  if (!lstrcmpi(url, "/TRANSLATE2")) {
    popstring(szDownloading);
    popstring(szConnecting);
    popstring(szSecond);
    popstring(szMinute);
    popstring(szHour);
    popstring(szSeconds);
    popstring(szMinutes);
    popstring(szHours);
    popstring(szProgress);
    popstring(url);
    translation_version=2;
  } else if (!lstrcmpi(url, "/TRANSLATE")) {
    popstring(szDownloading);
    popstring(szConnecting);
    popstring(szSecond);
    popstring(szMinute);
    popstring(szHour);
    popstring(szPlural);
    popstring(szProgress);
    popstring(szRemaining);
    popstring(url);
    translation_version=1;
  } else {
    lstrcpy(szDownloading, "Downloading %s");
    lstrcpy(szConnecting, "Connecting ...");
    lstrcpy(szSecond, " (1 second remaining)");
    lstrcpy(szMinute, " (1 minute remaining)");
    lstrcpy(szHour, " (1 hour remaining)");
    lstrcpy(szSeconds, " (%u seconds remaining)");
    lstrcpy(szMinutes, " (%u minutes remaining)");
    lstrcpy(szHours, " (%u hours remaining)");
    lstrcpy(szProgress, "%skB (%d%%) of %skB at %u.%01ukB/s");
    translation_version=2;
  }
  lstrcpyn(buf, url, 10);
  if (!lstrcmpi(buf, "/TIMEOUT=")) {
    timeout_ms=my_atoi(url+9);
    popstring(url);
  }
  if (!lstrcmpi(url, "/PROXY")) {
    getieproxy=0;
    manualproxy=1;
    popstring(proxy);
    popstring(url);
  }
  if (!lstrcmpi(url, "/NOIEPROXY")) {
    getieproxy=0;
    popstring(url);
  }
  popstring(filename);

  HANDLE hFile = CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,0,NULL);

  if (hFile == INVALID_HANDLE_VALUE)
  {
    wsprintf(buf, "Unable to open %s", filename);
    error = buf;
  }
  else
  {
    if (parent)
    {
      uMsgCreate = RegisterWindowMessage("nsisdl create");

      lpWndProcOld = (void *)SetWindowLong(parent,GWL_WNDPROC,(long)ParentWndProc);

      SendMessage(parent, uMsgCreate, TRUE, (LPARAM) parent);

      // set initial text
      char *p = filename;
      while (*p) p++;
      while (*p != '\\' && p != filename) p = CharPrev(filename, p);
      wsprintf(buf, szDownloading, p != filename ? p + 1 : p);
      SetDlgItemText(childwnd, 1006, buf);
      SetWindowText(g_hwndStatic, szConnecting);
    }
    {
      WSADATA wsaData;
      WSAStartup(MAKEWORD(1, 1), &wsaData);

      JNL_HTTPGet *get = 0;

      static char main_buf[8192];
      char *buf=main_buf;
      char *p=NULL;

      HKEY hKey;
      if (getieproxy && RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",0,KEY_READ,&hKey) == ERROR_SUCCESS)
      {
        DWORD l = 4;
        DWORD t;
        DWORD v;
        if (RegQueryValueEx(hKey,"ProxyEnable",NULL,&t,(unsigned char *)&v,&l) == ERROR_SUCCESS && t == REG_DWORD && v)
        {
          l=8192;
          if (RegQueryValueEx(hKey,"ProxyServer",NULL,&t,(unsigned char *)buf,&l ) == ERROR_SUCCESS && t == REG_SZ)
          {
            p=strstr(buf,"http=");
            if (!p) p=buf;
            else {
              p+=5;
            }
            char *tp=strstr(p,";");
            if (tp) *tp=0;
            char *p2=strstr(p,"=");
            if (p2) p=0; // we found the wrong proxy
          }
        }
        buf[8192-1]=0;
        RegCloseKey(hKey);
      }
      if (manualproxy == 1) {
        p = proxy;
      }

      DWORD start_time=GetTickCount();
      get=new JNL_HTTPGet(JNL_CONNECTION_AUTODNS,16384,(p&&p[0])?p:NULL);
      int         st;
      int         has_printed_headers = 0;
      __int64     cl = 0;
      int         len;
      __int64     sofar = 0;
      DWORD last_recv_time=start_time;

      get->addheader ("User-Agent: NSISDL/1.2 (Mozilla)");
      get->addheader ("Accept: */*");

      get->connect (url);

      while (1) {
        if (g_cancelled)
            error = "cancel";

        if (error)
        {
          if (parent)
          {
            SendMessage(parent, uMsgCreate, FALSE, (LPARAM) parent);
            SetWindowLong(parent, GWL_WNDPROC, (long)lpWndProcOld);
          }
          break;
        }

        st = get->run ();

        if (st == -1) {
          lstrcpyn(url, get->geterrorstr(), sizeof(url));
          error = url;
        } else if (st == 1) {
          if (sofar < cl || get->get_status () != 2)
            error="download incomplete";
          else
          {
            bSuccess=TRUE;
            error = "success";
          }
        } else {

          if (get->get_status () == 0) {
            // progressFunc ("Connecting ...", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on connecting.";
            else
              Sleep(10); // don't busy-loop while connecting

          } else if (get->get_status () == 1) {

            progress_callback("Reading headers", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on getting headers.";
            else
              Sleep(10); // don't busy-loop while reading headers

          } else if (get->get_status () == 2) {

            if (! has_printed_headers) {
              has_printed_headers = 1;
              last_recv_time=GetTickCount();

              cl = get->content_length ();
              if (cl == 0)
                error = "Server did not specify content length.";
              else if (g_hwndProgressBar) {
                SendMessage(g_hwndProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 30000));
                g_file_size = cl;
              }
            }

            int data_downloaded = 0;
            while ((len = get->bytes_available ()) > 0) {
              data_downloaded++;
              if (len > 8192)
                len = 8192;
              len = get->get_bytes (buf, len);
              if (len > 0) {
                last_recv_time=GetTickCount();
                DWORD dw;
                WriteFile(hFile,buf,len,&dw,NULL);
                sofar += len;
                int time_sofar=(GetTickCount()-start_time)/1000;
                int bps = (int)(sofar/(time_sofar?time_sofar:1));
                int remain = MulDiv64(time_sofar, cl, sofar) - time_sofar;

                if (translation_version == 2) {
                  char *rtext=remain==1?szSecond:szSeconds;;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=remain==1?szMinute:szMinutes;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=remain==1?szHour:szHours;
                    }
                  }

                  char sofar_str[128];
                  char cl_str[128];
                  myitoa64(sofar/1024, sofar_str);
                  myitoa64(cl/1024, cl_str);

                  wsprintf (buf,
                        szProgress, //%skB (%d%%) of %skB @ %u.%01ukB/s
                        sofar_str,
                        MulDiv64(100, sofar, cl),
                        cl_str,
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintf(buf+lstrlen(buf),rtext,
                        remain
                        );
                } else if (translation_version == 1) {
                  char *rtext=szSecond;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=szMinute;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=szHour;
                    }
                  }

                  wsprintf (buf,
                        szProgress, //%dkB (%d%%) of %dkB @ %d.%01dkB/s
                        int(sofar/1024),
                        MulDiv64(100, sofar, cl),
                        int(cl/1024),
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintf(buf+lstrlen(buf),szRemaining,
                        remain,
                        rtext,
                        remain==1?"":szPlural
                        );
                }
                progress_callback(buf, sofar);
              } else {
                if (sofar < cl)
                  error = "Server aborted.";
              }
            }
            if (GetTickCount() > last_recv_time+timeout_ms)
            {
              if (sofar != cl)
              {
                error = "Downloading timed out.";
              }
              else
              {
                // workaround for bug #1713562
                //   buggy servers that wait for the client to close the connection.
                //   another solution would be manually stopping when cl == sofar,
                //   but then buggy servers that return wrong content-length will fail.
                bSuccess = TRUE;
                error = "success";
              }
            }
            else if (!data_downloaded)
              Sleep(10);

          } else {
            error = "Bad response status.";
          }
        }

      }

      // Clean up the connection then release winsock
      if (get) delete get;
      WSACleanup();
    }

    CloseHandle(hFile);
  }

  if (g_cancelled || !bSuccess) {
    DeleteFile(filename);
  }

  pushstring(error);
}