void CDBManagePageFake::OnBnClickedButtonAddtolibFake()
{
	// TODO: 在此添加控件通知处理程序代码
	if(m_ary_SpecFileName.IsEmpty())
	{
		MessageBox(L"没有要入库的光谱数据,请添加光谱数据",L"光谱入库",MB_ICONERROR);
		return ;
	}
	if(m_ary_PicturesPath.IsEmpty())
	{
		MessageBox(L"缺少必要的图片,入库失败",L"光谱入库",MB_ICONERROR);
		return ;
	}

	CCompleteSpecAddToFakeLibInfoDlg CompleteSpecAddToFakeLibInfoDlg;
	CompleteSpecAddToFakeLibInfoDlg.m_WineName=m_WineName;
	CompleteSpecAddToFakeLibInfoDlg.m_Comfrom=m_Comfrom;
	CompleteSpecAddToFakeLibInfoDlg.m_SpecIDTitle=m_SpecIDTitle;
	CompleteSpecAddToFakeLibInfoDlg.m_Manager=m_Manager;
	

	if(IDOK == CompleteSpecAddToFakeLibInfoDlg.DoModal())
	{
		if(NULL!=m_pAddToLibDlg)
		{
			m_pAddToLibDlg->DestroyWindow();
			m_pAddToLibDlg=NULL;
		}
		m_Comfrom=CompleteSpecAddToFakeLibInfoDlg.m_Comfrom;
		m_SpecIDTitle=CompleteSpecAddToFakeLibInfoDlg.m_SpecIDTitle;
		m_Manager=CompleteSpecAddToFakeLibInfoDlg.m_Manager;
		m_WineName = CompleteSpecAddToFakeLibInfoDlg.m_WineName;

		//保存图片
		CWinePictures WinePictures;
		CTime tm=CTime::GetCurrentTime();
		CString Currenttime;
		Currenttime=tm.Format("%Y-%m-%d");
		if(!WinePictures.Open())
		{
			MessageBox(L"打开图片库失败!",L"导入图片",MB_ICONERROR);
			return;
		}

		CString m_strFolderPath=g_CurrentDir;
		m_strFolderPath+=L"\\Lib\\Pictures\\";
		m_strFolderPath+=m_SpecIDTitle;

		CreateDirectory(m_strFolderPath, NULL );
		for(int i=0;i<m_ary_PicturesPath.GetCount();i++)
		{
			//生成保存图片的文件夹
			CString newpicpath;
			newpicpath.Format(L"\\Lib\\Pictures\\%s\\%s",m_SpecIDTitle,m_ary_PicturesName[i]);
			CopyFile(m_ary_PicturesPath[i],g_CurrentDir+newpicpath,0);
			WinePictures.AddNew();
			WinePictures.m_WineName=m_WineName;
			WinePictures.m_ImportDate=Currenttime;
			WinePictures.m_Manager=m_Manager;
			WinePictures.m_PicturesDir=newpicpath;
			WinePictures.m_SpecIDTitle = m_SpecIDTitle;
			WinePictures.Update();

		}
		//开始导入光谱
		m_pAddToLibDlg=new CAddToLibDlg(m_ary_SpecFilePath.GetCount(),1);
		m_pAddToLibDlg->Create(IDD_DIALOG_ADDTOLIBPROGRESS,this);
		m_pAddToLibDlg->ShowWindow(SW_SHOW);
		pThreadAddSpecToLib=AfxBeginThread(ThreadAddSpecToFakeLib,this);
	}
}
void CTabSample::OnBnClickedButtotStartsample()
{
	// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
	// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
	BOOL bSelect = FALSE;
	CButton* pButton = NULL;

	UpdateData(TRUE);
	for (int i=0; i<InstrumentNum; i++)
	{
		ProcessMessages();
		pButton = (CButton*)GetDlgItem(m_iCheckIDInstrumentFDU[i]);
		m_iSelectObject[i] = pButton->GetCheck();
		m_Sec.Lock();
		m_oThreadManage.m_oADCDataRecThread.m_iSelectObject[i] = m_iSelectObject[i];
		m_Sec.Unlock();
		pButton = NULL;
		pButton = (CButton*)GetDlgItem(m_iCheckIDNoiseFDU[i]);
		m_iSelectObjectNoise[i] = pButton->GetCheck();
		m_Sec.Lock();
		m_oThreadManage.m_oADCDataRecThread.m_iSelectObjectNoise[i] = m_iSelectObjectNoise[i];
		m_Sec.Unlock();
		pButton = NULL;
	}

	for (int i=0; i<InstrumentNum; i++)
	{
		ProcessMessages();
		if (m_iSelectObject[i] == 1)
		{	
			bSelect = TRUE;	
			break;
		}
	}

	// 至少有一个仪器被选中
	if (bSelect == TRUE)
	{
		CString str = _T("");
		CString strTemp = _T("");
		SYSTEMTIME  sysTime;
		for (int i=0; i<InstrumentNum; i++)
		{
			m_dlgADCGraphShow[i].m_bStopSample = FALSE;
		}

		m_Sec.Lock();
		m_oThreadManage.m_oADCDataRecThread.OnReset();
		m_Sec.Unlock();

		m_oThreadManage.m_oSysTimeSocket.m_uiSysTimeCount = 0;
		// 创建本次ADC数据采集数据存储文件夹

		GetLocalTime(&sysTime);
		strTemp = m_csSaveFilePath;
		strTemp += _T("\\ADC数据备份");
		str.Format(_T("_%04d_%02d_%02d_%02d_%02d_%02d_%03d"), sysTime.wYear,sysTime.wMonth,sysTime.wDay,
			sysTime.wHour,sysTime.wMinute,sysTime.wSecond,sysTime.wMilliseconds);
		strTemp += str;
		// 按日期创建保存ADC采样数据的文件夹
		CreateDirectory(strTemp,NULL);
		GetDlgItem(IDC_EDIT_ADCSAVEFRAMENB)->GetWindowText(str);
		m_uiADCFileLength = atoi(str);
		m_oThreadManage.m_oADCDataSaveToFile.m_csSaveFilePath = strTemp;
		m_oThreadManage.m_oADCDataSaveToFile.m_uiADCFileLength = m_uiADCFileLength * ReceiveDataSize;
		for (int i=0; i<InstrumentNum; i++)
		{
			m_dlgADCGraphShow[i].m_csSaveFilePath = strTemp;
			m_dlgADCGraphShow[i].m_uiADCFileLength = m_uiADCFileLength * ReceiveDataSize;
		}

		// 先做零漂矫正
		m_oThreadManage.m_oADCSetSocket.OnADCZeroDrift();

		// 发送开始采样操作命令帧
		OnSendCmdFrame(m_iSelectObject);
		GetDlgItem(IDC_BUTTOT_STARTSAMPLE)->EnableWindow(FALSE);
		GetDlgItem(IDC_BUTTON_STOPSAMPLE)->EnableWindow(TRUE);
	}
}
Esempio n. 3
0
int create_directory(char *name)
{
    return CreateDirectory(name, NULL) != 0;
}
	BOOL FileSystemLayerImpl::createDirectory(const WindEngine::String& path)
	{
		return CreateDirectory(path.c_str(), NULL) != 0 || GetLastError() == ERROR_ALREADY_EXISTS;
	}
static LRESULT WINAPI swellFileSelectProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uMsg)
  {
    case WM_CREATE:
      if (lParam)  // swell-specific
      {
        SetWindowLong(hwnd,GWL_WNDPROC,(LPARAM)SwellDialogDefaultWindowProc);
        SetWindowLong(hwnd,DWL_DLGPROC,(LPARAM)swellFileSelectProc);
        SetWindowLongPtr(hwnd,GWLP_USERDATA,lParam);
        BrowseFile_State *parms = (BrowseFile_State *)lParam;
        if (parms->caption) SetWindowText(hwnd,parms->caption);

        SWELL_MakeSetCurParms(1,1,0,0,hwnd,false,false);

        SWELL_MakeButton(0,
              parms->mode == BrowseFile_State::OPENDIR ? "Choose directory" :
              parms->mode == BrowseFile_State::SAVE ? "Save" : "Open",
              IDOK,0,0,0,0, 0);

        SWELL_MakeButton(0, "Cancel", IDCANCEL,0,0,0,0, 0);
        HWND edit = SWELL_MakeEditField(0x100, 0,0,0,0,  0);
        if (edit)
        {
          if (parms->initialfile && *parms->initialfile) SetWindowText(edit,parms->initialfile);
          else if (parms->initialdir && *parms->initialdir) 
          {
            char buf[1024];
            lstrcpyn_safe(buf,parms->initialdir,sizeof(buf) - 1);
            if (parms->mode != BrowseFile_State::OPENDIR && buf[0] && buf[strlen(buf)-1]!='/') lstrcatn(buf,"/",sizeof(buf));
            SetWindowText(edit,buf);
          }
        }
        SWELL_MakeLabel(-1,parms->mode == BrowseFile_State::OPENDIR ? "Directory: " : "File:",0x101, 0,0,0,0, 0); 
        
        if (BFSF_Templ_dlgid && BFSF_Templ_dlgproc)
        {
          HWND dlg = SWELL_CreateDialog(BFSF_Templ_reshead, BFSF_Templ_dlgid, hwnd, BFSF_Templ_dlgproc, 0);
          if (dlg) SetWindowLong(dlg,GWL_ID,0x102);
          BFSF_Templ_dlgproc=0;
          BFSF_Templ_dlgid=0;
        }

        SWELL_MakeSetCurParms(1,1,0,0,NULL,false,false);
        SetWindowPos(hwnd,NULL,0,0,600, 400, SWP_NOACTIVATE|SWP_NOZORDER|SWP_NOMOVE);
      }
    break;
    case WM_GETMINMAXINFO:
      {
        LPMINMAXINFO p=(LPMINMAXINFO)lParam;
        p->ptMinTrackSize.x = 300;
        p->ptMinTrackSize.y = 300;
      }
    break;
    case WM_SIZE:
      {
        BrowseFile_State *parms = (BrowseFile_State *)GetWindowLongPtr(hwnd,GWLP_USERDATA);
        // reposition controls
        RECT r;
        GetClientRect(hwnd,&r);
        const int buth = 24, cancelbutw = 50, okbutw = parms->mode == BrowseFile_State::OPENDIR ? 120 : 50;
        const int xborder = 4, yborder=8;
        const int fnh = 20, fnlblw = parms->mode == BrowseFile_State::OPENDIR ? 70 : 50;

        int ypos = r.bottom - 4 - buth;
        int xpos = r.right;
        SetWindowPos(GetDlgItem(hwnd,IDCANCEL), NULL, xpos -= cancelbutw + xborder, ypos, cancelbutw,buth, SWP_NOZORDER|SWP_NOACTIVATE);
        SetWindowPos(GetDlgItem(hwnd,IDOK), NULL, xpos -= okbutw + xborder, ypos, okbutw,buth, SWP_NOZORDER|SWP_NOACTIVATE);

        HWND emb = GetDlgItem(hwnd,0x102);
        if (emb)
        {
          RECT sr;
          GetClientRect(emb,&sr);
          if (ypos > r.bottom-4-sr.bottom) ypos = r.bottom-4-sr.bottom;
          SetWindowPos(emb,NULL, xborder,ypos, xpos - xborder*2, sr.bottom, SWP_NOZORDER|SWP_NOACTIVATE);
          ShowWindow(emb,SW_SHOWNA);
        }
 

        SetWindowPos(GetDlgItem(hwnd,0x100), NULL, xborder*2 + fnlblw, ypos -= fnh + yborder, r.right-fnlblw-xborder*3, fnh, SWP_NOZORDER|SWP_NOACTIVATE);
        SetWindowPos(GetDlgItem(hwnd,0x101), NULL, xborder, ypos, fnlblw, fnh, SWP_NOZORDER|SWP_NOACTIVATE);
  
      }
    break;
    case WM_COMMAND:
      switch (LOWORD(wParam))
      {
        case IDCANCEL: EndDialog(hwnd,0); return 0;
        case IDOK: 
          {
            char buf[1024],msg[2048];
            GetDlgItemText(hwnd,0x100,buf,sizeof(buf));
            BrowseFile_State *parms = (BrowseFile_State *)GetWindowLongPtr(hwnd,GWLP_USERDATA);
            switch (parms->mode)
            {
              case BrowseFile_State::SAVE:
                 if (!buf[0]) 
                 {
                   MessageBox(hwnd,"No file specified","Error",MB_OK);
                   return 0;
                 }
                 else  
                 {
                   struct stat st={0,};
                   DIR *dir = opendir(buf);
                   if (dir)
                   {
                     closedir(dir);
                     snprintf(msg,sizeof(msg),"Path is a directory:\r\n\r\n%s",buf);
                     MessageBox(hwnd,msg,"Invalid file",MB_OK);
                     return 0;
                   }
                   if (!stat(buf,&st))
                   {
                     snprintf(msg,sizeof(msg),"File exists:\r\n\r\n%s\r\n\r\nOverwrite?",buf);
                     if (MessageBox(hwnd,msg,"Overwrite file?",MB_OKCANCEL)==IDCANCEL) return 0;
                   }
                 }
              break;
              case BrowseFile_State::OPENDIR:
                 if (!buf[0]) 
                 { 
                   MessageBox(hwnd,"No directory specified","Error",MB_OK);
                   return 0;
                 } 
                 else
                 {
                   DIR *dir = opendir(buf);
                   if (!dir) 
                   {
                     snprintf(msg,sizeof(msg),"Error opening directory:\r\n\r\n%s\r\n\r\nCreate?",buf);
                     if (MessageBox(hwnd,msg,"Create directory?",MB_OKCANCEL)==IDCANCEL) return 0;
                     CreateDirectory(buf,NULL);
                     dir=opendir(buf);
                     if (!dir) { MessageBox(hwnd,"Error creating directory","Error",MB_OK); return 0; }
                   }
                   if (dir) closedir(dir);
                 }
              break;
              default:
                 if (!buf[0]) 
                 {
                   MessageBox(hwnd,"No file specified","Error",MB_OK);
                   return 0;
                 }
                 else  
                 {
                   struct stat st={0,};
                   DIR *dir = opendir(buf);
                   if (dir)
                   {
                     closedir(dir);
                     snprintf(msg,sizeof(msg),"Path is a directory:\r\n\r\n%s",buf);
                     MessageBox(hwnd,msg,"Invalid file",MB_OK);
                     return 0;
                   }
                   if (stat(buf,&st))
                   {
                     snprintf(msg,sizeof(msg),"File does not exist:\r\n\r\n%s",buf);
                     MessageBox(hwnd,msg,"File not found",MB_OK);
                     return 0;
                   }
                 }
              break;
            }
            if (parms->fnout) 
            {
              lstrcpyn_safe(parms->fnout,buf,parms->fnout_sz);
            }
            else
            {
              size_t l = strlen(buf);
              parms->fnout = (char*)calloc(l+2,1);
              memcpy(parms->fnout,buf,l);
            }
          }
          EndDialog(hwnd,1);
        return 0;
      }
    break;
  }
  return 0;
}
Esempio n. 6
0
int CheckFolder(char *folderName, int bCreate)
{
#ifdef _WIN32
	//检查文件夹是否存在
	WIN32_FIND_DATA wfd;
	HANDLE m_hFile = NULL;
	
	if (NULL == folderName)		return -1;
	
	m_hFile = FindFirstFile(folderName, &wfd);
	if (INVALID_HANDLE_VALUE == m_hFile)	//不存在
	{
		if (bCreate==0x01)
		{
			if (! CreateDirectory(folderName, NULL))	//创建文件夹失败
			{
				//TRACE(szLog, "创建文件夹失败: %s\n", folderName);
				return -1;
			}
			return 0;
		}
		else
		{
			return -1;
		}
	}
	else
	{
		return 0;
	}
#else

	DIR *dir = opendir(folderName);
	if (NULL != dir)
	{
		closedir(dir);
		_TRACE("Path already exist.\n");
		return 0;
	}
	else
	{
		if (bCreate==0x01)
		{
			int err = mkdir(folderName, 0755);
			if (err == 0)
			{
				_TRACE("Path not exist. create success.\n");
			}
			else
			{
				_TRACE("Path not exist. create fail.%d\n", err);
				return -1;
			}
			return 0;
		}
		else
		{
			return -1;
		}
	}

	return 0;
#endif
	return -1;
}
Esempio n. 7
0
/**
 * Makes sure the path of the filename exists. If it doesn't, create the path.
 */
void Filename::verifyAndCreatePath(void) const
{
#if defined(WIN32)
	if (WindowsUnicode)
	{
		char *buffer = NULL;
		DWORD buflen;
		// get our current path
		buflen = GetFullPathName(".", 0, buffer, NULL);
		buffer = new char[buflen + 1];
		buflen = GetFullPathName(".", buflen + 1, buffer, NULL);
		Unicode::String srcPath = Unicode::narrowToWide(buffer);
		delete[] buffer;
		// get the destination path
		std::string correctPath(getDrive() + getPath());
		buflen = GetFullPathName(correctPath.c_str(), 0, buffer, NULL);
		buffer = new char[buflen + 1];
		buflen = GetFullPathName(correctPath.c_str(), buflen + 1, buffer, NULL);
		Unicode::String destPath = Unicode::narrowToWide(buffer);
		delete[] buffer;

		std::vector<Unicode::String> splitDestPath;
		splitPath(destPath, splitDestPath,
			static_cast<Unicode::unicode_char_t>(WIN32_PATH_SEPARATOR));

		Unicode::String prefix = L"\\\\?\\";
		destPath = prefix + splitDestPath[0];
		
		for (size_t i = 1; i < splitDestPath.size(); ++i)
		{
			destPath += WIN32_PATH_SEPARATOR;
			destPath += splitDestPath[i];
			if (SetCurrentDirectoryW((LPCWSTR)destPath.c_str()) == 0)
			{
				if (CreateDirectoryW((LPCWSTR)destPath.c_str(), NULL) == 0)
					return;
				if (SetCurrentDirectoryW((LPCWSTR)destPath.c_str()) == 0)
					return;
			}
		}

		// set the directory back to the working directory
		SetCurrentDirectoryW(srcPath.c_str());
	}
	else
	{
		char *buffer = NULL;
		DWORD buflen;
		// get our current path
		buflen = GetFullPathName(".", 0, buffer, NULL);
		buffer = new char[buflen + 1];
		buflen = GetFullPathName(".", buflen + 1, buffer, NULL);
		std::string srcPath = buffer;
		delete[] buffer;
		// get the destination path
		std::string correctPath(getDrive() + getPath());
		buflen = GetFullPathName(correctPath.c_str(), 0, buffer, NULL);
		buffer = new char[buflen + 1];
		buflen = GetFullPathName(correctPath.c_str(), buflen + 1, buffer, NULL);
		std::string destPath = buffer;
		delete[] buffer;

		// change to the destination path
		if (destPath.size() >= MAX_PATH)
			return;
		
		std::vector<std::string> splitDestPath;
		splitPath(destPath, splitDestPath, WIN32_PATH_SEPARATOR);

		destPath = splitDestPath[0];
		
		for (size_t i = 1; i < splitDestPath.size(); ++i)
		{
			destPath += WIN32_PATH_SEPARATOR;
			destPath += splitDestPath[i];
			if (SetCurrentDirectory(destPath.c_str()) == 0)
			{
				if (CreateDirectory(destPath.c_str(), NULL) == 0)
					return;
				if (SetCurrentDirectory(destPath.c_str()) == 0)
					return;
			}
		}

		// set the directory back to the working directory
		SetCurrentDirectory(srcPath.c_str());
	}
#elif defined(linux)
	// @todo: implement for linux
#endif
}	// Filename::verifyAndCreatePath
Esempio n. 8
0
	virtual BOOL InitInstance()
	{
		try{
			SetRegistryKey(G_softwarename());

			//boost process priority
			SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS);

			AfxInitRichEdit();
	//		AfxEnableControlContainer();
	//		AfxOleInit();

			{//create documents folder
				QString dir;
				GetDocumentsDir(dir);dir+=_qstr("\\");dir+=G_softwarename();
				CreateDirectory(dir,NULL);
			}


			CWinApp::InitInstance();

			//for 3D Connexion
			if (!AfxOleInit())
			{
				AfxMessageBox(L"OLE Init failed");
				return FALSE;
			}
			AfxEnableControlContainer();


			StrChar locstartupdir[600];
			GetCurrentDirectory(599,locstartupdir);
			startupdir=locstartupdir;
			datadir=startupdir+_qstr("/Data");
			{
				QString storeddatadir;
				QParamRead(PARAMLOCATION_REGISTRY,_qstr("DataDirectory"),storeddatadir);
				if (qstrlen(storeddatadir)>0)
					datadir=storeddatadir;
			}

			initlog();
			addlog(TFormatString(_text("Data directory: ^1"),datadir));

			scriptsdir=datadir;scriptsdir+=_qstr("\\Scripts");
			texturesdir=datadir;texturesdir+=_qstr("\\textures");

			addlog(_text("Fetching MAC address"));
			GetMACaddress(MACaddr);
			addlog(MACaddr);

			G_3DCosmos().LoadSettings();
			G_3DCosmos().init();


			loadstockcyclorbits();

			G_QXSys().startup();

			addlog(_text("Loading languages"),+1);
			QTranslate::Get().loadlanguages();
			addlog(_text("Loaded languages"),-1);

			addlog(_text("Creating source code window"),+1);
			mainwin= new Tmainwin();
			mainwin->createwindow(NULL,QString("Source code window"));
			addlog(_text("Source code window created"),-1);
			addlog(_text(""));
			addlog(_text(""));
			mainwin->ShowWindow(m_nCmdShow);
			m_pMainWnd=mainwin;

		}
		catch(QError &err)
		{
			reporterror(err.G_content());
		}

		return TRUE;
	}
Esempio n. 9
0
void log_file_rotate(LPLOGFILE logfile)
{
    struct tm	curr_tm;
    time_t	time_s;
    char	dir[128];
    char	system_cmd[128];

    time_s = time(0);
    curr_tm = *localtime(&time_s);

    if (curr_tm.tm_mday != logfile->last_day)
    {
	struct tm new_tm;
	new_tm = *tm_calc(&curr_tm, -3);

#ifndef _WIN32
	sprintf(system_cmd, "rm -rf %s/%04d%02d%02d", log_dir, new_tm.tm_year + 1900, new_tm.tm_mon + 1, new_tm.tm_mday);
#else
	sprintf(system_cmd, "del %s\\%04d%02d%02d", log_dir, new_tm.tm_year + 1900, new_tm.tm_mon + 1, new_tm.tm_mday);
#endif
	system(system_cmd);

	sys_log(0, "SYSTEM_CMD: %s", system_cmd);

	logfile->last_day = curr_tm.tm_mday;
    }

    if (curr_tm.tm_hour != logfile->last_hour)
    {
		struct stat	stat_buf;
		snprintf(dir, 128, "%s/%04d%02d%02d", log_dir, curr_tm.tm_year + 1900, curr_tm.tm_mon + 1, curr_tm.tm_mday);

		if (stat(dir, &stat_buf) != 0 || S_ISDIR(stat_buf.st_mode))
		{
#ifdef _WIN32
			CreateDirectory(dir, NULL);
#else
			mkdir(dir, S_IRWXU);
#endif
		}

		sys_log(0, "SYSTEM: LOG ROTATE (%04d-%02d-%02d %d)", 
				curr_tm.tm_year + 1900, curr_tm.tm_mon + 1, curr_tm.tm_mday, logfile->last_hour);

		// ·О±Ч ЖДАПА» ґЭ°н
		fclose(logfile->fp);

		// їЕ±дґЩ.
#ifndef _WIN32
		snprintf(system_cmd, 128, "mv %s %s/%s.%02d", logfile->filename, dir, logfile->filename, logfile->last_hour);
#else
		snprintf(system_cmd, 128, "move %s %s\\%s.%02d", logfile->filename, dir, logfile->filename, logfile->last_hour);
#endif
		system(system_cmd);

		// ё¶Бцё· АъАеЅГ°Ј АъАе
		logfile->last_hour = curr_tm.tm_hour;

		// ·О±Ч ЖДАПА» ґЩЅГ ї¬ґЩ.	
		logfile->fp = fopen(logfile->filename, "a+");
	}
}
Esempio n. 10
0
void CAtmoDynData::ReloadZoneDefinitionBitmaps()
{
  int i;
  // suchlogik fuer die Farbverlaufs Bitmaps ...
  // <WorkDir>\hardware\numchannels\zone..0..n.bmp
  // <WorkDir>\hardware\zone..0..n.bmp
  // <WorkDir>\zone..0..n.bmp
  // Automatik Berechnung...
  LockCriticalSection();
  if(!m_pAtmoConnection || !m_pAtmoConfig) {
      UnLockCriticalSection();
      return;
  }

  m_pAtmoConfig->UpdateZoneDefinitionCount();

  CalculateDefaultZones();


  char psz_filename[MAX_PATH];
  CAtmoZoneDefinition *zoneDef;

  sprintf(psz_filename,"%s%s",
                        m_WorkDir,
                        m_pAtmoConnection->getDevicePath()
                );
  CreateDirectory( psz_filename, NULL );

  sprintf(psz_filename,"%s%s\\%dx%dx%d",
                        m_WorkDir,
                        m_pAtmoConnection->getDevicePath(),
                        m_pAtmoConfig->getZonesTopCount(),
                        m_pAtmoConfig->getZonesLRCount(),
                        m_pAtmoConfig->getZonesBottomCount()

               );
  CreateDirectory(psz_filename, NULL );

  // try to load device depended zone definition bitmaps
  for(int zone=0; zone < m_pAtmoConfig->getZoneCount(); zone++)  {
      zoneDef = m_pAtmoConfig->getZoneDefinition(zone);
      if(!zoneDef) continue;

      sprintf(psz_filename,"%s%s\\%dx%dx%d\\zone_%d.bmp",
                        m_WorkDir,
                        m_pAtmoConnection->getDevicePath(),
                        m_pAtmoConfig->getZonesTopCount(),
                        m_pAtmoConfig->getZonesLRCount(),
                        m_pAtmoConfig->getZonesBottomCount(),
                        zone
                );
      i = zoneDef->LoadGradientFromBitmap( psz_filename );
      if(i == ATMO_LOAD_GRADIENT_OK) continue;
      if((i == ATMO_LOAD_GRADIENT_FAILED_SIZE) || (i == ATMO_LOAD_GRADIENT_FAILED_HEADER))
         MessageBox(0,psz_filename,"Failed to load, Check Format, Check Size.",MB_ICONERROR);

      sprintf(psz_filename,"%s%s\\zone_%d.bmp",
                        m_WorkDir,
                        m_pAtmoConnection->getDevicePath(),
                        zone
                );
      i = zoneDef->LoadGradientFromBitmap( psz_filename );
      if(i == ATMO_LOAD_GRADIENT_OK) continue;
      if((i == ATMO_LOAD_GRADIENT_FAILED_SIZE) || (i == ATMO_LOAD_GRADIENT_FAILED_HEADER))
         MessageBox(0,psz_filename,"Failed to load, Check Format, Check Size.",MB_ICONERROR);

      sprintf(psz_filename,"%szone_%d.bmp",
                        m_WorkDir,
                        zone
                );
      i = zoneDef->LoadGradientFromBitmap( psz_filename );
      if(i == ATMO_LOAD_GRADIENT_OK) continue;
      if((i == ATMO_LOAD_GRADIENT_FAILED_SIZE) || (i == ATMO_LOAD_GRADIENT_FAILED_HEADER))
         MessageBox(0,psz_filename,"Failed to load, Check Format, Check Size.",MB_ICONERROR);
  }

  UnLockCriticalSection();
}
Esempio n. 11
0
bool CreateReparsePoint(CommandData *Cmd,const wchar *Name,FileHeader *hd)
{
  static bool PrivSet=false;
  if (!PrivSet)
  {
    SetPrivilege(SE_RESTORE_NAME);
    // Not sure if we really need it, but let's request anyway.
    SetPrivilege(SE_CREATE_SYMBOLIC_LINK_NAME);
    PrivSet=true;
  }

  const DWORD BufSize=sizeof(REPARSE_DATA_BUFFER)+2*NM+1024;
  Array<byte> Buf(BufSize);
  REPARSE_DATA_BUFFER *rdb=(REPARSE_DATA_BUFFER *)&Buf[0];

  wchar SubstName[NM];
  wcsncpyz(SubstName,hd->RedirName,ASIZE(SubstName));
  size_t SubstLength=unrar_wcslen(SubstName);

  wchar PrintName[NM],*PrintNameSrc=SubstName,*PrintNameDst=PrintName;
  bool WinPrefix=unrar_wcsncmp(PrintNameSrc,L"\\??\\",4)==0;
  if (WinPrefix)
    PrintNameSrc+=4;
  if (WinPrefix && unrar_wcsncmp(PrintNameSrc,L"UNC\\",4)==0)
  {
    *(PrintNameDst++)='\\'; // Insert second \ in beginning of share name.
    PrintNameSrc+=3;
  }
  unrar_wcscpy(PrintNameDst,PrintNameSrc);

  size_t PrintLength=unrar_wcslen(PrintName);

  bool AbsPath=WinPrefix;
  // IsFullPath is not really needed here, AbsPath check is enough.
  // We added it just for extra safety, in case some Windows version would
  // allow to create absolute targets with SYMLINK_FLAG_RELATIVE.
  if (!Cmd->AbsoluteLinks && (AbsPath || IsFullPath(hd->RedirName) ||
      !IsRelativeSymlinkSafe(hd->FileName,hd->RedirName)))
    return false;

#ifndef NOFILECREATE
  CreatePath(Name,true);

  // 'DirTarget' check is important for Unix symlinks to directories.
  // Unix symlinks do not have their own 'directory' attribute.
  if (hd->Dir || hd->DirTarget)
  {
    if (!CreateDirectory(Name,NULL))
      return false;
  }
  else
  {
    HANDLE hFile=CreateFile(Name,GENERIC_WRITE,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);
    if (hFile == INVALID_HANDLE_VALUE)
      return false;
    CloseHandle(hFile);
  }
#endif

  if (hd->RedirType==FSREDIR_JUNCTION)
  {
    rdb->ReparseTag=IO_REPARSE_TAG_MOUNT_POINT;
    rdb->ReparseDataLength=USHORT(
      sizeof(rdb->MountPointReparseBuffer.SubstituteNameOffset)+
      sizeof(rdb->MountPointReparseBuffer.SubstituteNameLength)+
      sizeof(rdb->MountPointReparseBuffer.PrintNameOffset)+
      sizeof(rdb->MountPointReparseBuffer.PrintNameLength)+
      (SubstLength+1)*sizeof(WCHAR)+(PrintLength+1)*sizeof(WCHAR));
    rdb->Reserved=0;

    rdb->MountPointReparseBuffer.SubstituteNameOffset=0;
    rdb->MountPointReparseBuffer.SubstituteNameLength=USHORT(SubstLength*sizeof(WCHAR));
    unrar_wcscpy(rdb->MountPointReparseBuffer.PathBuffer,SubstName);

    rdb->MountPointReparseBuffer.PrintNameOffset=USHORT((SubstLength+1)*sizeof(WCHAR));
    rdb->MountPointReparseBuffer.PrintNameLength=USHORT(PrintLength*sizeof(WCHAR));
    unrar_wcscpy(rdb->MountPointReparseBuffer.PathBuffer+SubstLength+1,PrintName);
  }
  else
    if (hd->RedirType==FSREDIR_WINSYMLINK || hd->RedirType==FSREDIR_UNIXSYMLINK)
    {
      rdb->ReparseTag=IO_REPARSE_TAG_SYMLINK;
      rdb->ReparseDataLength=USHORT(
        sizeof(rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset)+
        sizeof(rdb->SymbolicLinkReparseBuffer.SubstituteNameLength)+
        sizeof(rdb->SymbolicLinkReparseBuffer.PrintNameOffset)+
        sizeof(rdb->SymbolicLinkReparseBuffer.PrintNameLength)+
        sizeof(rdb->SymbolicLinkReparseBuffer.Flags)+
        (SubstLength+1)*sizeof(WCHAR)+(PrintLength+1)*sizeof(WCHAR));
      rdb->Reserved=0;

      rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset=0;
      rdb->SymbolicLinkReparseBuffer.SubstituteNameLength=USHORT(SubstLength*sizeof(WCHAR));
      unrar_wcscpy(rdb->SymbolicLinkReparseBuffer.PathBuffer,SubstName);

      rdb->SymbolicLinkReparseBuffer.PrintNameOffset=USHORT((SubstLength+1)*sizeof(WCHAR));
      rdb->SymbolicLinkReparseBuffer.PrintNameLength=USHORT(PrintLength*sizeof(WCHAR));
      unrar_wcscpy(rdb->SymbolicLinkReparseBuffer.PathBuffer+SubstLength+1,PrintName);

      rdb->SymbolicLinkReparseBuffer.Flags=AbsPath ? 0:SYMLINK_FLAG_RELATIVE;
    }
    else
      return false;

  HANDLE hFile=CreateFile(Name,GENERIC_READ|GENERIC_WRITE,0,NULL,
               OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT| 
               FILE_FLAG_BACKUP_SEMANTICS,NULL);
  if (hFile==INVALID_HANDLE_VALUE)
    return false;

  DWORD Returned;
  if (!DeviceIoControl(hFile,FSCTL_SET_REPARSE_POINT,rdb, 
      FIELD_OFFSET(REPARSE_DATA_BUFFER,GenericReparseBuffer)+
      rdb->ReparseDataLength,NULL,0,&Returned,NULL))
  { 
    CloseHandle(hFile);
    uiMsg(UIERROR_SLINKCREATE,UINULL,Name);
    if (GetLastError()==ERROR_PRIVILEGE_NOT_HELD)
      uiMsg(UIERROR_NEEDADMIN);
    ErrHandler.SysErrMsg();
    ErrHandler.SetErrorCode(RARX_CREATE);

    if (hd->Dir)
      RemoveDirectory(Name);
    else
      DeleteFile(Name);
    return false;
  }
  File LinkFile;
  LinkFile.SetHandle(hFile);
  LinkFile.SetOpenFileTime(
    Cmd->xmtime==EXTTIME_NONE ? NULL:&hd->mtime,
    Cmd->xctime==EXTTIME_NONE ? NULL:&hd->ctime,
    Cmd->xatime==EXTTIME_NONE ? NULL:&hd->atime);
  LinkFile.Close();
#ifndef NOFILECREATE
  if (!Cmd->IgnoreGeneralAttr)
    SetFileAttr(Name,hd->FileAttr);
#endif
  return true;
}
Esempio n. 12
0
int PrepareHookModule(wchar_t (&szModule)[MAX_PATH+16])
{
	int iRc = -251;
	wchar_t szNewPath[MAX_PATH+16] = {}, szAddName[32] = {}, szVer[2] = {};
	INT_PTR nLen = 0;
	bool bAlreadyExists = false;

	// Copy szModule to CSIDL_LOCAL_APPDATA and return new path
	HRESULT hr = SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, szNewPath);
	if ((hr != S_OK) || !*szNewPath)
	{
		iRc = -251;
		goto wrap;
	}

	szVer[0] = MVV_4a[0];
	_wsprintf(szAddName, SKIPLEN(countof(szAddName))
		L"\\" CEDEFTERMDLLFORMAT /*L"ConEmuHk%s.%02u%02u%02u%s.dll"*/,
		WIN3264TEST(L"",L"64"), MVV_1, MVV_2, MVV_3, szVer);

	nLen = lstrlen(szNewPath);
	if (szNewPath[nLen-1] != L'\\')
	{
		szNewPath[nLen++] = L'\\'; szNewPath[nLen] = 0;
	}

	if ((nLen + lstrlen(szAddName) + 8) >= countof(szNewPath))
	{
		iRc = -252;
		goto wrap;
	}

	wcscat_c(szNewPath, L"ConEmu");
	if (!DirectoryExists(szNewPath))
	{
		if (!CreateDirectory(szNewPath, NULL))
		{
			iRc = -253;
			goto wrap;
		}
	}

	wcscat_c(szNewPath, szAddName);

	if ((bAlreadyExists = FileExists(szNewPath)) && FileCompare(szNewPath, szModule))
	{
		// OK, file exists and match the required
	}
	else
	{
		if (bAlreadyExists)
		{
			_ASSERTE(FALSE && "Continue to overwrite existing ConEmuHk in AppLocal");

			// Try to delete or rename old version
			if (!DeleteFile(szNewPath))
			{
				//SYSTEMTIME st; GetLocalTime(&st);
				wchar_t szBakPath[MAX_PATH+32]; wcscpy_c(szBakPath, szNewPath);
				wchar_t* pszExt = (wchar_t*)PointToExt(szBakPath);
				msprintf(pszExt, 16, L".%u.dll", GetTickCount());
				DeleteFile(szBakPath);
				MoveFile(szNewPath, szBakPath);
			}
		}

		if (!CopyFile(szModule, szNewPath, FALSE))
		{
			iRc = -254;
			goto wrap;
		}
	}

	wcscpy_c(szModule, szNewPath);
	iRc = 0;
wrap:
	return iRc;
}
Esempio n. 13
0
/**
 * Parse the update host and determine the updates directory
 * Then verify that the directory exists (creating if needed).
 */
void Client::initUpdatesDir()
{
    // If updatesHost is currently empty, fill it from config file
    if (mUpdateHost.empty())
        mUpdateHost = config.getStringValue("updatehost");

    // Exit on empty update host.
    if (mUpdateHost.empty())
        return;

    logger->log("Setting update host: %s", mUpdateHost.c_str());

    std::string updateHost = getHostNameFromURL(mUpdateHost);

    // Exit on a wrong update host.
    if (updateHost.length() < 2)
    {
        // Show the original updateHostname in the error message.
        errorMessage = strprintf(_("Invalid update host: %s"),
                                 mUpdateHost.c_str());
        mState = STATE_ERROR;
        return;
    }

    mUpdateHost = updateHost;
    mUpdatesDir = "updates/" + mUpdateHost;

    ResourceManager *resman = ResourceManager::getInstance();

    // Verify that the updates directory exists. Create if necessary.
    if (!resman->isDirectory("/" + mUpdatesDir))
    {
        if (!resman->mkdir("/" + mUpdatesDir))
        {
#if defined _WIN32
            std::string newDir = mLocalDataDir + "\\" + mUpdatesDir;
            std::string::size_type loc = newDir.find("/", 0);

            while (loc != std::string::npos)
            {
                newDir.replace(loc, 1, "\\");
                loc = newDir.find("/", loc);
            }

            if (!CreateDirectory(newDir.c_str(), 0) &&
                GetLastError() != ERROR_ALREADY_EXISTS)
            {
                logger->log("Error: %s can't be made, but doesn't exist!",
                            newDir.c_str());
                errorMessage =
                    strprintf(_("Error creating updates directory!\n(%s)"),
                                newDir.c_str());
                mState = STATE_ERROR;
            }
#else
            logger->log("Error: %s/%s can't be made, but doesn't exist!",
                        mLocalDataDir.c_str(), mUpdatesDir.c_str());
            errorMessage =
                strprintf(_("Error creating updates directory!\n(%s/%s)"),
                            mLocalDataDir.c_str(), mUpdatesDir.c_str());
            mState = STATE_ERROR;
#endif
        }
    }
}
Esempio n. 14
0
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
#endif
{
	hInst = hInstance;
	isWin64 = IsWindows64();
	
	GetVersionEx(&gOSVer);
	
	int nInstallVer = 0;
	
	wsprintf(gsTitle, L"ConEmu %s installer", CONEMUVERL);
	lstrcpyn(gsRunAsAdm, L"Run installer as administrator", countof(gsRunAsAdm));

	wchar_t szArg[MAX_PATH+1];
	LPCWSTR pszCmdToken = GetCommandLine();
	LPCWSTR pszCmdLineW = pszCmdToken;
	
	gsTempFolder[0] = 0;
	
	while (0 == NextArg(&pszCmdToken, szArg))
	{
		if (lstrcmp(szArg, L"/?") == 0 || lstrcmp(szArg, L"-?") == 0)
		{
			MessageBox(NULL, L"Usage:\nConEmuSetup [/e[:<extract path>]] [/p:x86 | /p:x64] [<msi args>]", gsTitle, MB_ICONINFORMATION);
			return 1;
		}
		
		if (*szArg == L'/')
		{
			if (szArg[1] == L'e' || szArg[1] == L'E')
			{
				gbExtractOnly = true;
				if (szArg[2] == L':' && szArg[3])
				{
					lstrcpyn(gsTempFolder, (szArg[3]==L'"') ? (szArg+4) : (szArg+3), countof(gsTempFolder));
				}
				continue;
			}
		
			if (lstrcmpi(szArg, L"/p:x86") == 0)
				nInstallVer = Ver86;
			else if (lstrcmpi(szArg, L"/p:x64") == 0)
				nInstallVer = Ver64;
			else
				pszCmdToken = pszCmdLineW;
			break;
		}
		else if (*szArg == L'-')
		{
			pszCmdToken = pszCmdLineW;
			break;
		}
			
		pszCmdLineW = pszCmdToken;
	}
	

	if (!gbExtractOnly)
	{
		wchar_t szInstallPath[MAX_PATH+32];
		bool bInstalled;
		HKEY hk;
	
		lstrcpyn(gsMessage, L"Choose version to install", countof(gsMessage));
		
			szInstallPath[0] = 0; bInstalled = false;
			struct {HKEY hk; LPCWSTR path; LPCWSTR name; bool our;}
				Keys[] = {
					{HKEY_LOCAL_MACHINE,L"SOFTWARE\\ConEmu",L"InstallDir",true},
					{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far Manager",L"InstallDir"},
					{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far2",L"InstallDir"},
					{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far",L"InstallDir"},
				};
			for (size_t s = 0; s < countof(Keys); s++)
			{
				if (!RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ, &hk)
					|| !RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ|KEY_WOW64_32KEY, &hk))
				{
					wchar_t szPath[MAX_PATH+1] = {}; DWORD cbSize = sizeof(szPath)-2;
					LONG lRc = RegQueryValueEx(hk, Keys[s].name, NULL, NULL, (LPBYTE)szPath, &cbSize);
					RegCloseKey(hk);
					if (!lRc && *szPath)
					{
						bInstalled = Keys[s].our;
						lstrcpy(szInstallPath, szPath);
						cbSize = lstrlen(szInstallPath);
						if (szInstallPath[cbSize-1] == L'\\') szInstallPath[cbSize-1] = 0;
						break;
					}
				}
			}
			if (szInstallPath[0] == 0)
			{
				GetEnvironmentVariable(L"ProgramFiles", szInstallPath, MAX_PATH);
				int nLen = lstrlen(szInstallPath);
				lstrcat(szInstallPath, (nLen > 0 && szInstallPath[nLen-1] != L'\\') ? L"\\ConEmu" : L"ConEmu");
			}
			wsprintf(gsVer86, L"%s x86\n%s installation folder is\n%s", CONEMUVERL, bInstalled ? L"Current" : L"Default", szInstallPath);

			
		if (isWin64)
		{
			
				szInstallPath[0] = 0; bInstalled = false;
				struct {HKEY hk; LPCWSTR path; LPCWSTR name; bool our;}
					Keys[] = {
						{HKEY_LOCAL_MACHINE,L"SOFTWARE\\ConEmu",L"InstallDir_x64",true},
						{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far Manager",L"InstallDir_x64"},
						{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far2",L"InstallDir_x64"},
						{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far",L"InstallDir_x64"},
					};
				for (size_t s = 0; s < countof(Keys); s++)
				{
					if (!RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ|KEY_WOW64_64KEY, &hk))
					{
						wchar_t szPath[MAX_PATH+1] = {}; DWORD cbSize = sizeof(szPath)-2;
						LONG lRc = RegQueryValueEx(hk, Keys[s].name, NULL, NULL, (LPBYTE)szPath, &cbSize);
						RegCloseKey(hk);
						if (!lRc && *szPath)
						{
							bInstalled = Keys[s].our;
							lstrcpy(szInstallPath, szPath);
							cbSize = lstrlen(szInstallPath);
							if (szInstallPath[cbSize-1] == L'\\') szInstallPath[cbSize-1] = 0;
							break;
						}
					}
				}
				if (szInstallPath[0] == 0)
				{
					GetEnvironmentVariable(L"ProgramW6432", szInstallPath, MAX_PATH);
					int nLen = lstrlen(szInstallPath);
					lstrcat(szInstallPath, (nLen > 0 && szInstallPath[nLen-1] != L'\\') ? L"\\ConEmu" : L"ConEmu");
				}
				wsprintf(gsVer64, L"%s x64\n%s installation folder is\n%s", CONEMUVERL, bInstalled ? L"Current" : L"Default", szInstallPath);

			wsprintf(gsFull, L"%s\n\nPress `Yes` to install x64 version\nPress `No` to install x86 version", gsMessage);
		}
		else
		{
			gsVer64[0] = 0;
		}
	}
	else
	{
		wchar_t szPath[MAX_PATH+1];
		if (*gsTempFolder)
		{
			lstrcpy(szPath, gsTempFolder);
		}
		else
		{
			GetTempPath(countof(szPath) - 14, szPath);
			wchar_t* pszSubDir = szPath+lstrlen(szPath);
			lstrcpy(pszSubDir, L"ConEmu");
			pszSubDir += 6;
			lstrcpy(pszSubDir, CONEMUVERL);
		}
		
		lstrcpyn(gsMessage, L"Choose version to extract", countof(gsMessage));
		wsprintf(gsVer86, L"%s x86\nExtract installation files to\n%s", CONEMUVERL, szPath);
		wsprintf(gsVer64, L"%s x64\nExtract installation files to\n%s", CONEMUVERL, szPath);
		wsprintf(gsFull, L"%s\n\nPress `Yes` to extract x64 version\nPress `No` to extract x86 version\n\n%s", gsMessage, szPath);
	}
	
	if (nInstallVer == 0)
		nInstallVer = ChooseVersion(); // IDCANCEL/Ver86/Ver64
		
	if (nInstallVer != Ver86 && nInstallVer != Ver64)
		return 1;
	
	if (gbExtractOnly && *gsTempFolder)
	{
		CreateDirectory(gsTempFolder, NULL);
	}
	else
	{
		GetTempPath(countof(gsTempFolder) - 14, gsTempFolder);
		
		wchar_t* pszSubDir = gsTempFolder+lstrlen(gsTempFolder);
		lstrcpy(pszSubDir, L"ConEmu");
		pszSubDir += 6;
		lstrcpy(pszSubDir, CONEMUVERL);
		pszSubDir += lstrlen(pszSubDir);
		if (!CreateDirectory(gsTempFolder, NULL))
		{
			bool lbCreated = false;
			SYSTEMTIME st = {}; GetLocalTime(&st);
			for (int i = 0; i < 100; i++)
			{
				wsprintf(pszSubDir, L"_%02i%02i%02i%i", st.wHour, st.wMinute, st.wSecond, i);
				if (CreateDirectory(gsTempFolder, NULL))
				{
					lbCreated = true;
					break;
				}
			}
			if (!lbCreated)
			{
				return ReportError(10, L"Can't create temp folder\n%s", gsTempFolder);
			}
		}
	}

	wsprintf(gsMsiFile, L"%s\\ConEmu.%s.%s.msi", gsTempFolder, CONEMUVERL, (nInstallVer == Ver86) ? L"x86" : L"x64");
	wsprintf(gsCabFile, L"%s\\ConEmu.cab", gsTempFolder);
	
	bool lbNeedExe = false;
	if (!gbExtractOnly && gOSVer.dwMajorVersion >= 6)
		lbNeedExe = true;

	if (!lbNeedExe)
		gsExeFile[0] = 0;
	else
		wsprintf(gsExeFile, L"%s\\ConEmuSetup.exe", gsTempFolder);
	
	int iExpMsi = ExportFile(nInstallVer, gsMsiFile);
	int iExpCab = (iExpMsi == 0) ? ExportFile(CABFILE, gsCabFile) : -1;
	int iExpExe = (!lbNeedExe) ? 0 : (iExpCab == 0) ? ExportFile(EXEFILE, gsExeFile) : -1;
	if (iExpMsi != 0 || iExpCab != 0 || iExpExe != 0)
	{
		DeleteFile(gsMsiFile);
		DeleteFile(gsCabFile);
		if (*gsExeFile)
			DeleteFile(gsExeFile);
		RemoveDirectory(gsTempFolder);
		return (iExpMsi != 0) ? iExpMsi : iExpCab;
	}
	
	if (gbExtractOnly)
	{
		wchar_t szMessage[MAX_PATH*2];
		wsprintf(szMessage, L"Installation files was extracted successfully\n%s", gsTempFolder);
		MessageBox(NULL, szMessage, gsTitle, MB_ICONINFORMATION);
		return 0;
	}

	int iInstRc = 0;
	SHELLEXECUTEINFO sei = {sizeof(sei)};
	wchar_t* pszParms = NULL;
	sei.fMask = SEE_MASK_NOCLOSEPROCESS|/*SEE_MASK_NOASYNC*/0x00000100; //|/*SEE_MASK_NOZONECHECKS*/0x00800000;
	sei.lpVerb = L"open";
	if (gOSVer.dwMajorVersion<=5 || !gbUseElevation)
	{
		sei.lpFile = gsMsiFile;
		sei.lpParameters = pszCmdToken;
	}
	else
	{
		sei.lpFile = gsExeFile;
		int nMaxLen = lstrlen(gsMsiFile) + (pszCmdToken ? lstrlen(pszCmdToken) : 0) + 64;
		pszParms = (wchar_t*)malloc(nMaxLen*sizeof(wchar_t));
		wsprintf(pszParms, L"/i \"%s\" %s", gsMsiFile, pszCmdToken ? pszCmdToken : L"");
		sei.lpParameters = pszParms;
	}
	sei.lpDirectory = gsTempFolder;
	sei.nShow = SW_SHOWNORMAL;
	
	BOOL lbExecute = ShellExecuteEx(&sei);
	
	#if 0
	if (!lbExecute && lbNeedExe)
	{
		DWORD nErr = GetLastError();
		if (nErr == 1223)
		{
			// Отмена пользователем UAC, или правов не хватило?
			sei.fMask = SEE_MASK_NOCLOSEPROCESS|/*SEE_MASK_NOASYNC*/0x00000100; //|/*SEE_MASK_NOZONECHECKS*/0x00800000;
			sei.lpVerb = L"open";
			sei.lpFile = gsMsiFile;
			sei.lpParameters = pszCmdToken;
			sei.lpDirectory = gsTempFolder;
			sei.nShow = SW_SHOWNORMAL;
			
			lbExecute = ShellExecuteEx(&sei);
		}
	}
	#endif
	
	if (!lbExecute)
	{
		iInstRc = ReportError(20, L"Installer failed\n%s", gsMsiFile);
	}
	else
	{
		if (!sei.hProcess)
		{
			iInstRc = ReportError(21, L"Installer failed\n%s", gsMsiFile);
		}
		else
		{
			WaitForSingleObject(sei.hProcess, INFINITE);
			DWORD nCode = 0;
			SetLastError(0);
			//1602 - это похоже "Отмена" пользователем
			if (!GetExitCodeProcess(sei.hProcess, &nCode) || (nCode != 0 && nCode != 1602))
			{
				wchar_t szFormat[128]; wsprintf(szFormat, L"Installer failed\n%%s\nExitCode=%u", nCode);
				iInstRc = ReportError(100+nCode, szFormat, gsMsiFile);
			}
		}
	}
	
	DeleteFile(gsMsiFile);
	DeleteFile(gsCabFile);
	if (*gsExeFile)
		DeleteFile(gsExeFile);
	RemoveDirectory(gsTempFolder);
	
	return iInstRc;
}
Esempio n. 15
0
void CCrashHandler::DumpMiniDump ( _EXCEPTION_POINTERS* pException, CExceptionInformation* pExceptionInformation )
{
    // Try to load the DLL in our directory
    HMODULE hDll = NULL;
    char szDbgHelpPath [MAX_PATH];
    if ( GetModuleFileNameA ( NULL, szDbgHelpPath, MAX_PATH ) )
    {
        char* pSlash = _tcsrchr ( szDbgHelpPath, '\\' );
        if ( pSlash )
        {
            _tcscpy ( pSlash + 1, "DBGHELP.DLL" );
            hDll = LoadLibrary ( szDbgHelpPath );
        }
    }

    // If we couldn't load the one in our dir, load any version available
    if ( !hDll )
    {
        hDll = LoadLibrary ( "DBGHELP.DLL" );
    }

    // We could load a dll?
    if ( hDll )
    {
        // Grab the MiniDumpWriteDump proc address
        MINIDUMPWRITEDUMP pDump = reinterpret_cast < MINIDUMPWRITEDUMP > ( GetProcAddress( hDll, "MiniDumpWriteDump" ) );
        if ( pDump )
        {
            // Grab the current time
            // Ask windows for the system time.
            SYSTEMTIME SystemTime;
            GetLocalTime ( &SystemTime );

            // Create the dump directory
            CreateDirectory ( ms_strDumpPath, 0 );
            CreateDirectory ( PathJoin( ms_strDumpPath, "private" ), 0 );

            SString strModuleName = pExceptionInformation->GetModuleBaseName ();
            strModuleName = strModuleName.ReplaceI ( ".dll", "" ).Replace ( ".exe", "" ).Replace ( "_", "" ).Replace ( ".", "" ).Replace ( "-", "" );
            if ( strModuleName.length () == 0 )
                strModuleName = "unknown";

            SString strFilename ( "server_%s_%s_%08x_%x_%04d%02d%02d_%02d%02d.dmp",
                                         MTA_DM_BUILDTAG_LONG,
                                         strModuleName.c_str (),
                                         pExceptionInformation->GetAddressModuleOffset (),
                                         pExceptionInformation->GetCode () & 0xffff,
                                         SystemTime.wYear,
                                         SystemTime.wMonth,
                                         SystemTime.wDay,
                                         SystemTime.wHour,
                                         SystemTime.wMinute
                                       );

            SString strFinalDumpPathFilename = PathJoin( ms_strDumpPath, "private", strFilename );

            // Create the file
            HANDLE hFile = CreateFile ( strFinalDumpPathFilename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
            if ( hFile != INVALID_HANDLE_VALUE )
            {
                // Create an exception information struct
                _MINIDUMP_EXCEPTION_INFORMATION ExInfo;
                ExInfo.ThreadId = GetCurrentThreadId ();
                ExInfo.ExceptionPointers = pException;
                ExInfo.ClientPointers = FALSE;

                // Write the dump
                pDump ( GetCurrentProcess(), GetCurrentProcessId(), hFile, (MINIDUMP_TYPE)( MiniDumpNormal | MiniDumpWithIndirectlyReferencedMemory ), &ExInfo, NULL, NULL );

                // Close the dumpfile
                CloseHandle ( hFile );

                FileSave( PathJoin( ms_strDumpPath, "server_pending_upload_filename" ), strFinalDumpPathFilename );
            }

            // Write a log with the generic exception information
            FILE* pFile = fopen ( PathJoin( ms_strDumpPath, "server_pending_upload.log" ), "a+" );
            if ( pFile )
            {
               // Header
                fprintf ( pFile, "%s", "** -- Unhandled exception -- **\n\n" );

                // Write the time
                time_t timeTemp;
                time ( &timeTemp );

                SString strMTAVersionFull = SString ( "%s", MTA_DM_BUILDTAG_LONG );

                SString strInfo;
                strInfo += SString ( "Version = %s\n", strMTAVersionFull.c_str () );
                strInfo += SString ( "Time = %s", ctime ( &timeTemp ) );

                strInfo += SString ( "Module = %s\n", pExceptionInformation->GetModulePathName () );

                // Write the basic exception information
                strInfo += SString ( "Code = 0x%08X\n", pExceptionInformation->GetCode () );
                strInfo += SString ( "Offset = 0x%08X\n\n", pExceptionInformation->GetAddressModuleOffset () );

                // Write the register info
                strInfo += SString ( "EAX=%08X  EBX=%08X  ECX=%08X  EDX=%08X  ESI=%08X\n" \
                                 "EDI=%08X  EBP=%08X  ESP=%08X  EIP=%08X  FLG=%08X\n" \
                                 "CS=%04X   DS=%04X  SS=%04X  ES=%04X   " \
                                 "FS=%04X  GS=%04X\n\n",
                                 pExceptionInformation->GetEAX (),
                                 pExceptionInformation->GetEBX (),
                                 pExceptionInformation->GetECX (),
                                 pExceptionInformation->GetEDX (),
                                 pExceptionInformation->GetESI (),
                                 pExceptionInformation->GetEDI (),
                                 pExceptionInformation->GetEBP (),
                                 pExceptionInformation->GetESP (),
                                 pExceptionInformation->GetEIP (),
                                 pExceptionInformation->GetEFlags (),
                                 pExceptionInformation->GetCS (),
                                 pExceptionInformation->GetDS (),
                                 pExceptionInformation->GetSS (),
                                 pExceptionInformation->GetES (),
                                 pExceptionInformation->GetFS (),
                                 pExceptionInformation->GetGS () );


                fprintf ( pFile, "%s", strInfo.c_str () );

                // End of unhandled exception
                fprintf ( pFile, "%s", "** -- End of unhandled exception -- **\n\n\n" );
        
                // Close the file
                fclose ( pFile );
            }
        }

        // Free the DLL again
        FreeLibrary ( hDll );
    }
}
Esempio n. 16
0
void Filesystem::createDirectory(std::string path)
{
	std::wstring sPath = std::wstring(path.begin(), path.end());
	CreateDirectory(sPath.c_str(), NULL);
}
DWORD WINAPI SocketThread_FileRecv(PVOID para)
{
	PSOCK_THREAD_PARA pPara = (PSOCK_THREAD_PARA)para;
	char* recvBuff = new char[1024];
	tstring filename = TEXT("unknown");
	tstring dirname = TEXT("unknown");
	tstring dirpath;
	char* filedata;
	int datalen = 0;
	bool first = true;
	FILE* ff = NULL;

	while(1)
	{
		memset(recvBuff, 0, 1024);
		int recv_size = recv(pPara->sock, recvBuff, 1024, 0);
		if (recv_size == 0 || recv_size == SOCKET_ERROR)
			break;

		if (first) // 应该包含文件名等信息
		{
			first = false;
			PFILEPACK fp = (PFILEPACK)recvBuff;
			if (fp->dirLen + sizeof(FILEPACK) > (uint32_t)recv_size)
			{
				glogger.error(TEXT("error file packet"));
				break;
			}

			filename = to_tstring(fp->time);
			if (fp->type == 'H')
				filename += TEXT(".html");
			else if (fp->type == 'L')
				filename += TEXT(".log");
			else
				filename += TEXT(".txt");

			dirname = gcommon::StringToTString(string(fp->data, fp->dirLen));			
			filedata = fp->data + fp->dirLen;
			datalen = recv_size - sizeof(FILEPACK) - fp->dirLen;

			// 信息
			// 获取崩溃位置作为目录名
			if (fp->type == 'H')
			{
				tstring remoteIP = inet_ltot(pPara->remoteIP);
				glogger.setDefaultColor(gcommon::PRINT_COLOR::BRIGHT_RED);
				glogger.insertCurrentTime(TEXT("   [yyyy-MM-dd HH:mm:ss] "));
				glogger.screen(TEXT("[") + remoteIP + TEXT("] ") + dirname + TEXT("\n"));
				glogger.logfile(TEXT("[") + remoteIP + TEXT("] ") + dirname + TEXT("\n"));
				glogger.setDefaultColor();
			}			
		}
		else
		{
			filedata = recvBuff;
			datalen = recv_size;
		}

		// 打开文件
		if (ff == NULL)
		{
			dirpath = pPara->para->outPath + inet_ltot(pPara->remoteIP) + TEXT("\\");
			CreateDirectory(dirpath.c_str(), NULL); 
			dirpath += dirname + TEXT("\\");
			CreateDirectory(dirpath.c_str(), NULL);
			_tfopen_s(&ff, (dirpath+filename).c_str(),TEXT("a"));
			if (ff == NULL)
			{
				glogger.error(TEXT("can not create file: %s"), filename.c_str());
				dirpath = pPara->para->outPath + inet_ltot(pPara->remoteIP) +
					TEXT("\\unknown\\");
				_tfopen_s(&ff, (dirpath + filename).c_str(), TEXT("a"));
				if(ff == NULL)
					break;
			}
		}

		// 写文件
		fwrite(filedata, 1, datalen, ff);
	}

	if (ff)fclose(ff);
	closesocket(pPara->sock);
	delete[] recvBuff;
	return 0;
}
Esempio n. 18
0
//this is the thread function which calls the subversion function
UINT CCacheDlg::WatchTestThread()
{
	CDirFileEnum direnum(m_sRootPath);
	m_filelist.RemoveAll();
	CString filepath;
	bool bIsDir = false;
	while (direnum.NextFile(filepath, &bIsDir))
		m_filelist.Add(filepath);

	CTime starttime = CTime::GetCurrentTime();
	GetDlgItem(IDC_STARTTIME)->SetWindowText(starttime.Format(_T("%H:%M:%S")));

	ULONGLONG startticks = GetTickCount64();

	CString sNumber;
	std::random_device rd;
	std::mt19937 mt(rd());
	std::uniform_int_distribution<INT_PTR> dist(0, max(0, m_filelist.GetCount() - 1));
	filepath = m_filelist.GetAt(dist(mt));
	GetStatusFromRemoteCache(CTGitPath(m_sRootPath), false);
	for (int i=0; i < 10000; ++i)
	{
		filepath = m_filelist.GetAt(dist(mt));
		GetDlgItem(IDC_FILEPATH)->SetWindowText(filepath);
		TouchFile(filepath);
		CopyRemoveCopy(filepath);
		sNumber.Format(_T("%d"), i);
		GetDlgItem(IDC_DONE)->SetWindowText(sNumber);
	}

	// create dummy directories and remove them again several times
	for (int outer = 0; outer<100; ++outer)
	{
		for (int i=0; i<10; ++i)
		{
			filepath.Format(_T("__MyDummyFolder%d"), i);
			CreateDirectory(m_sRootPath+_T("\\")+filepath, NULL);
			HANDLE hFile = CreateFile(m_sRootPath+_T("\\")+filepath+_T("\\file"), GENERIC_READ, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
			CloseHandle(hFile);
			SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, m_sRootPath+_T("\\")+filepath+_T("\\file"), NULL);
		}
		Sleep(500);
		for (int i=0; i<10; ++i)
		{
			filepath.Format(_T("__MyDummyFolder%d"), i);
			DeleteFile(m_sRootPath+_T("\\")+filepath+_T("\\file"));
			RemoveDirectory(m_sRootPath+_T("\\")+filepath);
		}
		sNumber.Format(_T("%d"), outer);
		GetDlgItem(IDC_DONE)->SetWindowText(sNumber);
	}

	CTime endtime = CTime::GetCurrentTime();
	CString sEnd = endtime.Format(_T("%H:%M:%S"));

	ULONGLONG endticks = GetTickCount64();

	CString sEndText;
	sEndText.Format(_T("%s  - %I64u ms"), sEnd, endticks - startticks);

	GetDlgItem(IDC_ENDTIME)->SetWindowText(sEndText);

	return 0;
}
bool CreateDirectory(const std::string& full_path)
{
	return CreateDirectory(full_path.c_str());
}
Esempio n. 20
0
        // This method creates minidump of the process
        void crash_handler::create_mini_dump(EXCEPTION_POINTERS* pExcPtrs)
        {   
            MINIDUMP_EXCEPTION_INFORMATION mei;
            MINIDUMP_CALLBACK_INFORMATION mci;

            // Load dbghelp.dll
            HMODULE hDbgHelp = LoadLibrary(_T("dbghelp.dll"));
            if(hDbgHelp == NULL)
            {
                // Error - couldn't load dbghelp.dll
                return;
            }

            // create folder if not existed
            if (!CreateDirectory((get_report_path() + std::wstring(L"\\")).c_str(), NULL) &&
                ERROR_ALREADY_EXISTS != GetLastError())
            {
                return;
            }

            create_log_file_for_hockey_app(pExcPtrs);

            // Create the minidump file
            HANDLE handleFile (CreateFile(
                get_report_mini_dump_path().c_str(),
                GENERIC_WRITE,
                0,
                NULL,
                CREATE_ALWAYS,
                FILE_ATTRIBUTE_NORMAL,
                NULL));

            // https://msdn.microsoft.com/ru-ru/library/windows/desktop/5fc6ft2t(v=vs.80).aspx
            if(handleFile==INVALID_HANDLE_VALUE)
            {
                return;
            }

            CHandle hFile(handleFile);

            // Write minidump to the file
            mei.ThreadId = GetCurrentThreadId();
            mei.ExceptionPointers = pExcPtrs;
            mei.ClientPointers = FALSE;
            mci.CallbackRoutine = NULL;
            mci.CallbackParam = NULL;

            typedef BOOL (WINAPI *LPMINIDUMPWRITEDUMP)(
                HANDLE hProcess, 
                DWORD ProcessId, 
                HANDLE hFile, 
                MINIDUMP_TYPE DumpType, 
                CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, 
                CONST PMINIDUMP_USER_STREAM_INFORMATION UserEncoderParam, 
                CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);

            LPMINIDUMPWRITEDUMP pfnMiniDumpWriteDump = 
                (LPMINIDUMPWRITEDUMP)GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
            if(!pfnMiniDumpWriteDump)
            {    
                // Bad MiniDumpWriteDump function
                return;
            }

            HANDLE hProcess = GetCurrentProcess();
            DWORD dwProcessId = GetCurrentProcessId();
            auto dump_type = (_MINIDUMP_TYPE)get_dump_type();
            if (dump_type == -1)
            {
                assert(!"dump_type must be positive");
                dump_type = MiniDumpNormal;
            }

            BOOL bWriteDump = pfnMiniDumpWriteDump(
                hProcess,
                dwProcessId,
                hFile,
                dump_type,
                &mei,
                NULL,
                &mci);

            if(!bWriteDump)
            {    
                // Error writing dump.
                return;
            }

            // Unload dbghelp.dll
            FreeLibrary(hDbgHelp);
        }
Esempio n. 21
0
bool DialogInstall::InstallPackage()
{
	if ((!m_MergeSkins && m_BackupSkins) || m_BackupPackage)
	{
		// Move skins into backup folder
		for (auto iter = m_PackageSkins.cbegin(); iter != m_PackageSkins.cend(); ++iter)
		{
			std::wstring from = g_Data.skinsPath + *iter;
			if (_waccess(from.c_str(), 0) == -1)
			{
				continue;
			}

			SHFILEOPSTRUCT fo =
			{
				nullptr,
				FO_DELETE,
				nullptr,
				nullptr,
				FOF_NO_UI | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
			};

			if (m_BackupPackage)
			{
				// Remove current skin
				from += L'\0';
				fo.pFrom = from.c_str();
				SHFileOperation(&fo);
			}
			else
			{
				std::wstring to = g_Data.skinsPath + L"@Backup\\";
				CreateDirectory(to.c_str(), nullptr);

				// Delete current backup
				to += *iter;
				to += L'\0';
				fo.pFrom = to.c_str();
				SHFileOperation(&fo);

				if (!CopyFiles(from, to, true))
				{
					m_ErrorMessage = L"Unable to move to:\n";
					m_ErrorMessage += to;
					return false;
				}
			}
		}
	}

	WCHAR buffer[MAX_PATH];

	// Helper to sets buffer with current file name
	auto getFileInfo = [&]()->bool
	{
		char cBuffer[MAX_PATH * 3];
		unz_file_info ufi;
		if (unzGetCurrentFileInfo(
				m_PackageUnzFile, &ufi, cBuffer, _countof(cBuffer), nullptr, 0, nullptr, 0) == UNZ_OK)
		{
			const uLong ZIP_UTF8_FLAG = 1 << 11;
			const DWORD codePage = (ufi.flag & ZIP_UTF8_FLAG) ? CP_UTF8 : CP_ACP;
			MultiByteToWideChar(codePage, 0, cBuffer, strlen(cBuffer) + 1, buffer, MAX_PATH);
			while (WCHAR* pos = wcschr(buffer, L'/')) *pos = L'\\';
			return true;
		}

		return false;
	};

	unzGoToFirstFile(m_PackageUnzFile);
	const WCHAR* root = m_PackageRoot.c_str();
	do
	{
		if (!getFileInfo())
		{
			m_ErrorMessage = L"Error retrieving file info.";
			return false;
		}

		if (wcsncmp(buffer, root, m_PackageRoot.length()) != 0)
		{
			// Ignore everything that isn't in the root directory
			continue;
		}

		WCHAR* component = buffer + m_PackageRoot.length();
		WCHAR* path = wcschr(component, L'\\');
		if (path)
		{
			*path = L'\0';
			++path;
		}
		else
		{
			continue;
		}

		bool error = false;
		std::wstring targetPath;

		WCHAR* pos = wcschr(path, L'\\');
		WCHAR* extension = PathFindExtension(pos ? pos : path);
		if (pos)
		{
			const std::wstring item(path, pos - path);

			if (_wcsicmp(component, L"Skins") == 0 &&
				m_PackageSkins.find(item) != m_PackageSkins.end())
			{
				targetPath = g_Data.skinsPath;
			}
			else if (_wcsicmp(component, L"Addons") == 0 &&
				m_PackageFormat == PackageFormat::Old &&
				m_PackageAddons.find(item) != m_PackageAddons.end())
			{
				targetPath = g_Data.settingsPath;
				targetPath += L"Addons\\";
			}
			else if (_wcsicmp(component, L"Plugins") == 0 &&
				_wcsnicmp(path, IsWin32Build() ? L"32bit" : L"64bit", pos - path) == 0 &&
				_wcsicmp(extension, L".dll") == 0 &&
				!wcschr(pos + 1, L'\\'))
			{
				const std::wstring plugin(pos + 1);
				if (m_PackagePlugins.find(plugin) != m_PackagePlugins.end())
				{
					path = pos + 1;
					targetPath = g_Data.settingsPath;
					targetPath += L"Plugins\\";
				}
			}

			if (!targetPath.empty())
			{
				targetPath += path;
				error = !ExtractCurrentFile(targetPath);
			}
			else if (_wcsicmp(component, m_PackageFormat == PackageFormat::New ? L"Layouts" : L"Themes") == 0 &&
				_wcsicmp(extension, m_PackageFormat == PackageFormat::New ? L".ini" : L".thm") == 0 &&
				m_PackageLayouts.find(item) != m_PackageLayouts.end())
			{
				if (m_PackageFormat == PackageFormat::Old)
				{
					wcscpy_s(extension, 5, L".ini");
				}

				targetPath = g_Data.settingsPath;
				targetPath += L"Layouts\\";
				targetPath += path;
				error = !ExtractCurrentFile(targetPath);
				if (!error)
				{
					CleanLayoutFile(targetPath.c_str());
				}
			}
		}
		else
		{
			if (_wcsicmp(component, L"Fonts") == 0 &&
				m_PackageFormat == PackageFormat::Old &&
				_wcsicmp(extension, L".ttf") == 0)
			{
				for (auto iter = m_PackageSkins.cbegin(); iter != m_PackageSkins.cend(); ++iter)
				{
					targetPath = g_Data.skinsPath;
					targetPath += *iter;
					targetPath += L"\\@Resources\\Fonts\\";
					targetPath += path;
					error = !ExtractCurrentFile(targetPath);
					if (error)
					{
						break;
					}
				}
			}
		}

		if (error)
		{
			m_ErrorMessage = L"Unable to create file:\n";
			m_ErrorMessage += targetPath;
			m_ErrorMessage += L"\n\nSkin Installer will now quit.";
			return false;
		}
	}
	while (unzGoToNextFile(m_PackageUnzFile) == UNZ_OK);

	if (!m_MergeSkins && m_BackupSkins)
	{
		KeepVariables();
	}

	return true;
}
Esempio n. 22
0
bool FileUtils::createDirectory(const std::string& path)
{
    CCASSERT(!path.empty(), "Invalid path");
    
    if (isDirectoryExist(path))
        return true;
    
    // Split the path
    size_t start = 0;
    size_t found = path.find_first_of("/\\", start);
    std::string subpath;
    std::vector<std::string> dirs;
    
    if (found != std::string::npos)
    {
        while (true)
        {
            subpath = path.substr(start, found - start + 1);
            if (!subpath.empty())
                dirs.push_back(subpath);
            start = found+1;
            found = path.find_first_of("/\\", start);
            if (found == std::string::npos)
            {
                if (start < path.length())
                {
                    dirs.push_back(path.substr(start));
                }
                break;
            }
        }
    }


#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
	WIN32_FILE_ATTRIBUTE_DATA wfad;
    std::wstring wpath(path.begin(), path.end());
    if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad)))
	{
		subpath = "";
		for(int i = 0 ; i < dirs.size() ; ++i)
		{
			subpath += dirs[i];
			if (i > 0 && !isDirectoryExist(subpath))
			{
                std::wstring wsubpath(subpath.begin(), subpath.end());
                BOOL ret = CreateDirectory(wsubpath.c_str(), NULL);
				if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
				{
					return false;
				}
			}
		}
	}
	return true;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    if ((GetFileAttributesA(path.c_str())) == INVALID_FILE_ATTRIBUTES)
    {
		subpath = "";
		for (int i = 0; i < dirs.size(); ++i)
		{
			subpath += dirs[i];
			if (!isDirectoryExist(subpath))
			{
				BOOL ret = CreateDirectoryA(subpath.c_str(), NULL);
				if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
				{
					return false;
				}
			}
		}
    }
    return true;
#else
    DIR *dir = NULL;

    // Create path recursively
    subpath = "";
    for (int i = 0; i < dirs.size(); ++i) {
        subpath += dirs[i];
        dir = opendir(subpath.c_str());
        if (!dir)
        {
            int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
            if (ret != 0 && (errno != EEXIST))
            {
                return false;
            }
        }
    }
    return true;
#endif
}
Esempio n. 23
0
/*
 *	pgsymlink - uses Win32 junction points
 *
 *	For reference:	http://www.codeproject.com/KB/winsdk/junctionpoints.aspx
 */
int
pgsymlink(const char *oldpath, const char *newpath)
{
	HANDLE		dirhandle;
	DWORD		len;
	char		buffer[MAX_PATH * sizeof(WCHAR) + offsetof(REPARSE_JUNCTION_DATA_BUFFER, PathBuffer)];
	char		nativeTarget[MAX_PATH];
	char	   *p = nativeTarget;
	REPARSE_JUNCTION_DATA_BUFFER *reparseBuf = (REPARSE_JUNCTION_DATA_BUFFER *) buffer;

	CreateDirectory(newpath, 0);
	dirhandle = CreateFile(newpath, GENERIC_READ | GENERIC_WRITE,
						   0, 0, OPEN_EXISTING,
			   FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, 0);

	if (dirhandle == INVALID_HANDLE_VALUE)
		return -1;

	/* make sure we have an unparsed native win32 path */
	if (memcmp("\\??\\", oldpath, 4) != 0)
		snprintf(nativeTarget, sizeof(nativeTarget), "\\??\\%s", oldpath);
	else
		strlcpy(nativeTarget, oldpath, sizeof(nativeTarget));

	while ((p = strchr(p, '/')) != NULL)
		*p++ = '\\';

	len = strlen(nativeTarget) * sizeof(WCHAR);
	reparseBuf->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
	reparseBuf->ReparseDataLength = len + 12;
	reparseBuf->Reserved = 0;
	reparseBuf->SubstituteNameOffset = 0;
	reparseBuf->SubstituteNameLength = len;
	reparseBuf->PrintNameOffset = len + sizeof(WCHAR);
	reparseBuf->PrintNameLength = 0;
	MultiByteToWideChar(CP_ACP, 0, nativeTarget, -1,
						reparseBuf->PathBuffer, MAX_PATH);

	/*
	 * FSCTL_SET_REPARSE_POINT is coded differently depending on SDK version;
	 * we use our own definition
	 */
	if (!DeviceIoControl(dirhandle,
	 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 41, METHOD_BUFFERED, FILE_ANY_ACCESS),
						 reparseBuf,
	reparseBuf->ReparseDataLength + REPARSE_JUNCTION_DATA_BUFFER_HEADER_SIZE,
						 0, 0, &len, 0))
	{
		LPSTR		msg;

		errno = 0;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
					  NULL, GetLastError(),
					  MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
					  (LPSTR) &msg, 0, NULL);
#ifndef FRONTEND
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not set junction for \"%s\": %s",
						nativeTarget, msg)));
#else
		fprintf(stderr, _("could not set junction for \"%s\": %s\n"),
				nativeTarget, msg);
#endif
		LocalFree(msg);

		CloseHandle(dirhandle);
		RemoveDirectory(newpath);
		return -1;
	}

	CloseHandle(dirhandle);

	return 0;
}
Esempio n. 24
0
 bool MakeDirectory( const char* path )
 {
     return CreateDirectory(path, NULL) == TRUE;
 }
Esempio n. 25
0
int _mkdir(const char *sDir)
{	
	USES_CONVERSION;
	return (CreateDirectory(A2T(sDir),NULL) ? 0 : -1);
}
Esempio n. 26
0
void TestBasicEnvironment::SetUp()
{
  char *tmp;
  CStdString xbmcTempPath;
  XFILE::CFile *f;

  /* NOTE: The below is done to fix memleak warning about unitialized variable
   * in xbmcutil::GlobalsSingleton<CAdvancedSettings>::getInstance().
   */
  g_advancedSettings.Initialize();

  if (!CXBMCTestUtils::Instance().SetReferenceFileBasePath())
    SetUpError();
  CXBMCTestUtils::Instance().setTestFileFactoryWriteInputFile(
    XBMC_REF_FILE_PATH("xbmc/filesystem/test/reffile.txt")
  );

//for darwin set framework path - else we get assert
//in guisettings init below
#ifdef TARGET_DARWIN
  CStdString frameworksPath = CUtil::GetFrameworksPath();
  CSpecialProtocol::SetXBMCFrameworksPath(frameworksPath);    
#endif
  /* TODO: Something should be done about all the asserts in GUISettings so
   * that the initialization of these components won't be needed.
   */
  g_powerManager.Initialize();
  g_guiSettings.Initialize();

  /* Create a temporary directory and set it to be used throughout the
   * test suite run.
   */
#ifndef _LINUX
  TCHAR lpTempPathBuffer[MAX_PATH];
  if (!GetTempPath(MAX_PATH, lpTempPathBuffer))
    SetUpError();
  xbmcTempPath = lpTempPathBuffer;
  if (!GetTempFileName(xbmcTempPath.c_str(), "xbmctempdir", 0, lpTempPathBuffer))
    SetUpError();
  DeleteFile(lpTempPathBuffer);
  if (!CreateDirectory(lpTempPathBuffer, NULL))
    SetUpError();
  CSpecialProtocol::SetTempPath(lpTempPathBuffer);
#else
  char buf[MAX_PATH];
  (void)xbmcTempPath;
  strcpy(buf, "/tmp/xbmctempdirXXXXXX");
  if ((tmp = mkdtemp(buf)) == NULL)
    SetUpError();
  CSpecialProtocol::SetTempPath(tmp);
#endif

  /* Create and delete a tempfile to initialize the VFS (really to initialize
   * CLibcdio). This is done so that the initialization of the VFS does not
   * affect the performance results of the test cases.
   */
  /* TODO: Make the initialization of the VFS here optional so it can be
   * testable in a test case.
   */
  f = XBMC_CREATETEMPFILE("");
  if (!f || !XBMC_DELETETEMPFILE(f))
  {
    TearDown();
    SetUpError();
  }
}
Esempio n. 27
0
void Sys_FS_MakeDirectory(const char* path) {
	CreateDirectory(path, nullptr);
}
Esempio n. 28
0
void MainMenu::update()
{

	if ( bDrawBackground || MPlayer || LogisticsData::instance->isSingleMission() )
	{
		getButton( MM_MSG_SAVE )->disable( true );
	}
	else
		getButton( MM_MSG_SAVE )->disable( false );

	getButton( MM_MSG_MULTIPLAYER )->disable( true );

	if ( introMovie )
	{
		userInput->mouseOff();

		if (userInput->getKeyDown(KEY_SPACE) || userInput->getKeyDown(KEY_ESCAPE) || userInput->getKeyDown(KEY_LMOUSE))
		{
			introMovie->stop();
		}

		bool result = introMovie->update();
		if (result)
		{
			
			//Movie's Over.
			//Whack it.
			delete introMovie;
			introMovie = NULL;
		}

		return;
	}

	if (!musicStarted)
	{
		musicStarted = true;
		soundSystem->setMusicVolume( prefs.MusicVolume );
		soundSystem->playDigitalMusic(tuneId);
	}

	if ( endAnim.isDone() )
	{
		status = endResult;
	}

	if ( bDrawMechlopedia )
	{
		mechlopedia->update();
		if ( mechlopedia->getStatus() == NEXT )
		{
			beginFadeIn( 0 );
			bDrawMechlopedia = 0;
			if ( !bDrawBackground )
				status = NEXT;
		}
		return;
	}

	if ( bOptions )
	{
		OptionsScreenWrapper::status_type result = optionsScreenWrapper->update();
		if (result == OptionsScreenWrapper::opt_DONE)
		{
			optionsScreenWrapper->end();
			bOptions = 0;
		}

		return;
	}

	if ( (bSave || bLoad || bLoadCampaign) && endAnim.isDone() )
	{
		LogisticsSaveDialog::instance()->update();

		if ( LogisticsSaveDialog::instance()->getStatus() == LogisticsScreen::YES 
			&& LogisticsSaveDialog::instance()->isDone() )
		{
			
			char name[1024];
			strcpy( name, savePath );
			strcat( name, LogisticsSaveDialog::instance()->getFileName() );
			int index = strlen( name ) - 4;
			if ( stricmp( &name[index], ".fit" ) !=0 ) 
				strcat( name, ".fit" );

			
			FitIniFile file;
			if ( bSave )
			{
				// make sure the save game directory exists, if not create it
				CreateDirectory( savePath, NULL );

				if ( NO_ERR != file.createWithCase( name ) )
				{
					char errorStr[1024];
					sprintf( errorStr, "couldn't open the file %s", name );
					Assert( 0, 0, errorStr );
				}
				else
				{
					LogisticsData::instance->save( file );
					LogisticsSaveDialog::instance()->end();
					file.close();
				}
				bSave = bLoad = 0;
				status = NEXT;
				

			}
			else if ( bLoadCampaign )
			{
				LogisticsData::instance->startNewCampaign( LogisticsSaveDialog::instance()->getFileName());
				status = endResult = RESTART;
//				background.beginFadeOut( 1.0f );
//				beginFadeOut( 1.0f );
				bLoadCampaign = 0;
			}
			else
			{
				if ( NO_ERR != file.open( name ) )
				{
					char errorStr[1024];
					sprintf( errorStr, "couldn't open the file %s", name );
					Assert( 0, 0, errorStr );
				}
				else
					LogisticsData::instance->load( file );
				LogisticsSaveDialog::instance()->end();
				bSave = bLoad = 0;
				status = RESTART;
				file.close();

			}
		}
		else if ( LogisticsSaveDialog::instance()->getStatus() == LogisticsScreen::NO &&
			LogisticsSaveDialog::instance()->isDone())
		{
			LogisticsSaveDialog::instance()->end();
			bSave = bLoad = bLoadCampaign = 0 ;
			if ( !bDrawBackground )
				status = NEXT;
			else
			{
				beginAnim.begin();
				endAnim.end();
			}
		}
		return;
	}
	else if ( bLoadSingle && endAnim.isDone())
	{
		singleLoadDlg.update();
		if ( singleLoadDlg.isDone() )
		{
			if ( singleLoadDlg.getStatus() == YES )
			{
				const char* pName = singleLoadDlg.getMapFileName();
				if (pName)
				{
					LogisticsData::instance->setSingleMission( pName );
					status = SKIPONENEXT;
				}
			}

			bLoadSingle = 0;
			beginAnim.begin();
			endAnim.end();
		}
	}

	else if ( promptToQuit )
	{
		LogisticsOKDialog::instance()->update();
		{
			if ( LogisticsOKDialog::instance()->getStatus() == LogisticsScreen::YES )
			{
				soundSystem->playDigitalSample( LOG_EXITGAME );
				gos_TerminateApplication();
				promptToQuit = 0;

			}
			else if ( LogisticsOKDialog::instance()->getStatus() == LogisticsScreen::NO)
			{
				if ( LogisticsOKDialog::instance()->isDone() )
					promptToQuit = 0;
			}

			

		}
	}
	else if ( bLegal )
	{
		LogisticsLegalDialog::instance()->update();
		if ( LogisticsLegalDialog::instance()->isDone() )
		{
			LogisticsLegalDialog::instance()->end();
			bLegal = 0;
		}
	}
	else if ( bHostLeftDlg )
	{
		LogisticsOneButtonDialog::instance()->update();
		if ( LogisticsOneButtonDialog::instance()->isDone() )
		{
			LogisticsOneButtonDialog::instance()->end();
			bHostLeftDlg = 0;
		}

		if ( MPlayer ) // has to be done, but can't be done when initialized
		{
			MPlayer->closeSession();
			delete MPlayer;
			MPlayer = NULL;
		}
	}
	else if ( promptToDisconnect )
	{
		LogisticsOKDialog::instance()->update();
		if ( LogisticsOKDialog::instance()->isDone() )
		{
			if ( YES == LogisticsOKDialog::instance()->getStatus() )
			{
				if ( MPlayer )
				{
					MPlayer->closeSession();
					delete MPlayer;
					MPlayer = NULL;
				}
				long oldRes = endResult;
				endResult = 0;

				handleMessage( oldRes, oldRes );

				setDrawBackground( true );
			}
			else
				handleMessage( NEXT, NEXT );
			
			promptToDisconnect = 0;
		}
	}
	else
	{
		if ( bDrawBackground  )
		{
			if ( !intro.animObjects[0].isDone() )
			{
				intro.update();
				background.update();
				if (userInput->getKeyDown(KEY_ESCAPE) || (Environment.Renderer == 3))
				{
					introOver = true;
					userInput->mouseOn();
					soundSystem->playDigitalSample( LOG_MAINMENUBUTTON );

				}
				else if ( !introOver )
					return;
			}
			else
			{
				background.update();
				if ( !introOver )
					soundSystem->playDigitalSample( LOG_MAINMENUBUTTON );

				introOver = true;
				userInput->mouseOn();

			}
		}

		beginAnim.update();
		endAnim.update();

		LogisticsScreen::update();
		if ( (!bLoadSingle) && userInput->isLeftClick() && !inside( userInput->getMouseX(), userInput->getMouseY() ) )
		{
			handleMessage( 0, MM_MSG_RETURN_TO_GAME );
		}
	}
}
BOOL vmsBuildPathToFile (LPCTSTR pszFileName)
{
	TCHAR szPath [MAX_PATH];
	
	vmsGetPath (pszFileName, szPath);
	
	int len = _tcslen (szPath);
	int start = 0;
	
	
	if (szPath [0] == '\\' && szPath [1] == '\\')
	{
		
		LPCTSTR psz = _tcschr (szPath + 2, '\\');
		
		if (psz)
			psz = _tcschr (psz+1, '\\');
		if (psz)
			psz++;
		if (psz == NULL)
		{
			
			SetLastError (ERROR_PATH_NOT_FOUND);
			return FALSE;
		}
		
		
		start = psz - szPath;
	}
	else
	{
		if (szPath [1] == ':')
			start = 3;
	}
	
	for (int i = start; i < len; i++)
	{
		if (szPath [i] == '\\' || szPath [i] == '/')
		{
			
			
			
			
			
			
			
			TCHAR szPath2 [MAX_PATH];
			
			CopyMemory (szPath2, szPath, i * sizeof (TCHAR));
			szPath2 [i] = 0;
			
			if (FALSE == CreateDirectory (szPath2, NULL))	
			{
				if (GetLastError () != ERROR_ALREADY_EXISTS)
					return FALSE;
			}
		}
	}
	
	return TRUE;
}
Esempio n. 30
0
codeINSTALL_EXIT Install_Exit(
    HWND    hwndParent,
    LPCTSTR pszInstallDir,
    WORD    cFailedDirs,
    WORD    cFailedFiles,
    WORD    cFailedRegKeys,
    WORD    cFailedRegVals,
    WORD    cFailedShortcuts)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	codeINSTALL_EXIT ret = codeINSTALL_EXIT_DONE;
	CString strCacheLocation;
//	CString strEnclosuresLocation;

	if (PreviouslyInstalled) {
/*		HKEY hApp;
		if (::RegOpenKeyEx(HKEY_CURRENT_USER, REG_KEY_APP, 0, 0, &hApp) == ERROR_SUCCESS) {
			// read the value from the registry
			strCacheLocation = RegReadString(hApp, szCacheLocation, _T(""));
			RegCloseKey(hApp);
		}
*/
	}
	else {
		CRegistry reg(HKEY_CURRENT_USER, REG_KEY_APP);
		reg.Write(szInstallDir, pszInstallDir);

		CRegistry regConf(HKEY_CURRENT_USER, REG_KEY_CONFIGURATION);
		strCacheLocation = regConf.Read(szCacheLocation, _T(""));

		if (strCacheLocation.IsEmpty()) {
			// create cache folder (try to reuse old value from the registry)
			strCacheLocation = CString(pszInstallDir) + _T("\\cache");
			CreateDirectory(strCacheLocation, NULL);
			regConf.Write(szCacheLocation, strCacheLocation);
		}

		// create cache structure
		CreateDirectory(strCacheLocation + _T("\\enclosures"), NULL);
		CreateDirectory(strCacheLocation + _T("\\favicons"), NULL);
		CreateDirectory(strCacheLocation + _T("\\feeds"), NULL);
		CreateDirectory(strCacheLocation + _T("\\html"), NULL);
	}

	//
	// Activate today plugin
	//
	if (TodayPluginEnabled == VALUE_NOT_SET) {
		CString sInstall;
		sInstall.LoadString(IDS_INSTALL_TITLE);
		CString sMsg;
		sMsg.LoadString(IDS_ACTIVATE_TODAY_PLUGIN);

		if (MessageBox(NULL, sMsg, sInstall, MB_YESNO | MB_SETFOREGROUND) == IDYES) {
			EnableTodayPlugin();
		}
	}
	else {
		// set the today plugin to the previous state
		EnableTodayPlugin(TodayPluginEnabled == 0 ? FALSE : TRUE);
	}

    return ret;
}