Exemplo n.º 1
0
CString FindIncludeFile( const TCHAR *pszIncludeFilename, const TCHAR *pszIncludePath )
{
	CString strEnvInclude;
	CStringList strrgPathList;
	
	if( FileExists( pszIncludeFilename ) )
		return CString(pszIncludeFilename);
	
	// add current directory to path list;
	strrgPathList.AddTail( ".\\" );
	
	// add path specified in the command line (/I option)
	if( pszIncludePath )
		AddPath( strrgPathList, pszIncludePath );
	
	// add path specified in the INCLUDE variable
	if( strEnvInclude.GetEnvironmentVariable( _T("INCLUDE") ) )
		AddPath( strrgPathList, strEnvInclude );
	
	POSITION pos = strrgPathList.GetHeadPosition();
	for (int i=0;i < strrgPathList.GetCount();i++)
	{
		CString strPath = strrgPathList.GetNext(pos);
		CString tmp = strPath.Right(1);
		if( tmp != ":" && tmp != "\\" )
			strPath += '\\';
		
		strPath += pszIncludeFilename;
		
		if( FileExists( strPath ) )
			return CString(strPath);
	}

	return CString("");
}
Exemplo n.º 2
0
HANDLE
RequestQueue::CreateHandle()
{
  if(m_handle)
  {
    return NULL;
  }
  CString tempFilename;
  tempFilename.GetEnvironmentVariable("WINDIR");
  tempFilename += "\\TEMP\\RequestQueue_";
  tempFilename += m_name;

  m_handle = CreateFile(tempFilename
                       ,GENERIC_READ|GENERIC_WRITE
                       ,FILE_SHARE_READ|FILE_SHARE_WRITE
                       ,NULL  // Security
                       ,OPEN_ALWAYS
                       ,FILE_ATTRIBUTE_NORMAL| FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_OVERLAPPED | FILE_FLAG_DELETE_ON_CLOSE
                       ,NULL);
  if(m_handle == INVALID_HANDLE_VALUE)
  {
    return NULL;
  }
  return m_handle;
}
Exemplo n.º 3
0
void init()
{
	HKEY hSetting = NULL;
	DWORD length = 0;
	CString path;
	int pos;

	// Adds iTunesMobileDevice.dll folder to the path, from the registry:
	if (::RegCreateKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Apple Inc.\\Apple Mobile Device Support\\Shared"), &hSetting) != ERROR_SUCCESS)
		throw "iTunesMobileDevice library not found";
	if (::RegQueryValueEx(hSetting, _T("iTunesMobileDeviceDLL"), NULL, NULL, NULL, &length) != ERROR_SUCCESS)
		throw "iTunesMobileDevice library not found";
	piTunesMobileDevicePath = new char[length+1];
	::RegQueryValueEx(hSetting, _T("iTunesMobileDeviceDLL"), NULL, NULL, (LPBYTE)piTunesMobileDevicePath, &length);

	// Adds the folder to the current system path:	
	path.GetEnvironmentVariable("PATH");
	path = (path + ";") + piTunesMobileDevicePath;
	pos = path.ReverseFind('\\');
	if (pos >= 0)
		path = path.Left(pos);
	SetEnvironmentVariable("PATH", path);

	// Loads the DLL routines
	iTunesDll = LoadLibrary(piTunesMobileDevicePath);
	//iTunesDll = LoadLibrary("C:\\Program Files\\Common Files\\Apple\\Mobile Device Support\\bin\\MobileDevice.dll");
	if (iTunesDll) {
		AMDeviceNotificationSubscribe = (tf_AMDeviceNotificationSubscribe)GetProcAddress(iTunesDll, "AMDeviceNotificationSubscribe");
		AMDeviceConnect = (tf_AMDeviceConnect)GetProcAddress(iTunesDll, "AMDeviceConnect");
		AMDeviceDisconnect = (tf_AMDeviceDisconnect)GetProcAddress(iTunesDll, "AMDeviceDisconnect");
		AMDeviceIsPaired = (tf_AMDeviceIsPaired)GetProcAddress(iTunesDll, "AMDeviceIsPaired");
		AMDeviceValidatePairing = (tf_AMDeviceValidatePairing)GetProcAddress(iTunesDll, "AMDeviceValidatePairing");
		AMDeviceStartSession = (tf_AMDeviceStartSession)GetProcAddress(iTunesDll, "AMDeviceStartSession");
		AMDeviceStartService = (tf_AMDeviceStartService)GetProcAddress(iTunesDll, "AMDeviceStartService");
		AMDeviceStopSession = (tf_AMDeviceStopSession)GetProcAddress(iTunesDll, "AMDeviceStopSession");
		AFCConnectionOpen = (tf_AFCConnectionOpen)GetProcAddress(iTunesDll, "AFCConnectionOpen");
		AFCDeviceInfoOpen = (tf_AFCDeviceInfoOpen)GetProcAddress(iTunesDll, "AFCDeviceInfoOpen");
		AFCDirectoryOpen = (tf_AFCDirectoryOpen)GetProcAddress(iTunesDll, "AFCDirectoryOpen");
		AFCDirectoryRead = (tf_AFCDirectoryRead)GetProcAddress(iTunesDll, "AFCDirectoryRead");
		AFCDirectoryClose = (tf_AFCDirectoryClose)GetProcAddress(iTunesDll, "AFCDirectoryClose");
		AFCFileInfoOpen = (tf_AFCFileInfoOpen)GetProcAddress(iTunesDll, "AFCFileInfoOpen");
		AFCKeyValueRead = (tf_AFCKeyValueRead)GetProcAddress(iTunesDll, "AFCKeyValueRead");
		AFCKeyValueClose = (tf_AFCKeyValueClose)GetProcAddress(iTunesDll, "AFCKeyValueClose");
		AFCFileRefOpen = (tf_AFCFileRefOpen)GetProcAddress(iTunesDll, "AFCFileRefOpen");
		AFCFileRefClose = (tf_AFCFileRefClose)GetProcAddress(iTunesDll, "AFCFileRefClose");
		AFCFileRefRead = (tf_AFCFileRefRead)GetProcAddress(iTunesDll, "AFCFileRefRead");
		AFCFileRefWrite = (tf_AFCFileRefWrite)GetProcAddress(iTunesDll, "AFCFileRefWrite");
		AFCRemovePath = (tf_AFCRemovePath)GetProcAddress(iTunesDll, "AFCRemovePath");
		AFCDirectoryCreate = (tf_AFCDirectoryCreate)GetProcAddress(iTunesDll, "AFCDirectoryCreate");
		AFCRenamePath = (tf_AFCRenamePath)GetProcAddress(iTunesDll, "AFCRenamePath");
		AFCGetFileInfo = (tf_AFCGetFileInfo)GetProcAddress(iTunesDll, "AFCGetFileInfo");
	} else
		throw "iTunesMobileDevice.dll could not be loaded";
}
Exemplo n.º 4
0
void
ServerSession::CreateLogfile()
{
  CString name = ("HTTP_Server");
  m_logfile = new Logfile(name);
  m_logfile->SetLogRotation(true);
  m_logfile->SetLogLevel(m_socketLogging = SOCK_LOGGING_FULLTRACE);

  CString filename;
  filename.GetEnvironmentVariable("WINDIR");
  filename += "\\TEMP\\HTTP_Server.txt";

  m_logfile->SetLogFilename(filename);
}
Exemplo n.º 5
0
// Attaches the API: loads the DLL
// Returns:
//		IPOD_ERR_OK				when successful
//		IPOD_ERR_DLL_NOT_FOUND	when the iTunesMobileDevice.dll could not be loaded
//
t_iPodError CiPoTApi::AttachDLL()
{
	HKEY hSetting = NULL;
	DWORD length = 0;
	CString path;
	int pos;
	t_MachError ret;
	t_AMDeviceNotification *notif; 

	if (m_iPodState == IPOD_STATE_NO_DLL) {
		if (m_pCoreFoundationPath == NULL) {
			if (::RegCreateKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Apple Inc.\\Apple Application Support"), &hSetting) != ERROR_SUCCESS)
			{
				::RegCloseKey(hSetting);
				return IPOD_ERR_DLL_NOT_FOUND;
			}
			if (::RegQueryValueEx(hSetting, _T("InstallDir"), NULL, NULL, NULL, &length) != ERROR_SUCCESS)
			{
				::RegCloseKey(hSetting);
				return IPOD_ERR_DLL_NOT_FOUND;
			}
			m_pCoreFoundationPath = new char[length+19+1]; // \CoreFoundation.dll = 19
			::RegQueryValueEx(hSetting, _T("InstallDir"), NULL, NULL, (LPBYTE)m_pCoreFoundationPath, &length);
			::RegCloseKey(hSetting);


			// Adds the folder to the current system path:	
			path.GetEnvironmentVariable("PATH");
			path = (path + ";") + m_pCoreFoundationPath;
			SetEnvironmentVariable("PATH", path);

			if (m_pCoreFoundationPath[lstrlen(m_pCoreFoundationPath)-1] != '\\')
				strcat(m_pCoreFoundationPath, "\\");
			strcat(m_pCoreFoundationPath, "CoreFoundation.dll");
		}
		
		if (m_piTunesMobileDevicePath == NULL) {
			// Adds iTunesMobileDevice.dll folder to the path, from the registry:
			if (::RegCreateKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Apple Inc.\\Apple Mobile Device Support\\Shared"), &hSetting) != ERROR_SUCCESS)
			{
				::RegCloseKey(hSetting);
				return IPOD_ERR_DLL_NOT_FOUND;
			}
			if (::RegQueryValueEx(hSetting, _T("iTunesMobileDeviceDLL"), NULL, NULL, NULL, &length) != ERROR_SUCCESS)
			{
				::RegCloseKey(hSetting);
				return IPOD_ERR_DLL_NOT_FOUND;
			}
			m_piTunesMobileDevicePath = new char[length+1];
			::RegQueryValueEx(hSetting, _T("iTunesMobileDeviceDLL"), NULL, NULL, (LPBYTE)m_piTunesMobileDevicePath, &length);
			::RegCloseKey(hSetting);

			// Adds the folder to the current system path:	
			path.GetEnvironmentVariable("PATH");
			path = (path + ";") + m_piTunesMobileDevicePath;
			pos = path.ReverseFind('\\');
			if (pos >= 0)
				path.Truncate(pos);
			SetEnvironmentVariable("PATH", path);
		}

		// Loads the iTunesMobileDevice DLL routines
		m_iTunesDll = LoadLibrary(m_piTunesMobileDevicePath);
		if (m_iTunesDll) {
			AMDeviceNotificationSubscribe = (tf_AMDeviceNotificationSubscribe)GetProcAddress(m_iTunesDll, "AMDeviceNotificationSubscribe");
			AMDeviceConnect = (tf_AMDeviceConnect)GetProcAddress(m_iTunesDll, "AMDeviceConnect");
			AMDeviceDisconnect = (tf_AMDeviceDisconnect)GetProcAddress(m_iTunesDll, "AMDeviceDisconnect");
			AMDeviceIsPaired = (tf_AMDeviceIsPaired)GetProcAddress(m_iTunesDll, "AMDeviceIsPaired");
			AMDeviceValidatePairing = (tf_AMDeviceValidatePairing)GetProcAddress(m_iTunesDll, "AMDeviceValidatePairing");
			AMDeviceStartSession = (tf_AMDeviceStartSession)GetProcAddress(m_iTunesDll, "AMDeviceStartSession");
			AMDeviceStartService = (tf_AMDeviceStartService)GetProcAddress(m_iTunesDll, "AMDeviceStartService");
			AMDeviceStopSession = (tf_AMDeviceStopSession)GetProcAddress(m_iTunesDll, "AMDeviceStopSession");
			AFCConnectionOpen = (tf_AFCConnectionOpen)GetProcAddress(m_iTunesDll, "AFCConnectionOpen");
			AFCDeviceInfoOpen = (tf_AFCDeviceInfoOpen)GetProcAddress(m_iTunesDll, "AFCDeviceInfoOpen");
			AFCDirectoryOpen = (tf_AFCDirectoryOpen)GetProcAddress(m_iTunesDll, "AFCDirectoryOpen");
			AFCDirectoryRead = (tf_AFCDirectoryRead)GetProcAddress(m_iTunesDll, "AFCDirectoryRead");
			AFCDirectoryClose = (tf_AFCDirectoryClose)GetProcAddress(m_iTunesDll, "AFCDirectoryClose");
			AFCFileInfoOpen = (tf_AFCFileInfoOpen)GetProcAddress(m_iTunesDll, "AFCFileInfoOpen");
			AFCKeyValueRead = (tf_AFCKeyValueRead)GetProcAddress(m_iTunesDll, "AFCKeyValueRead");
			AFCKeyValueClose = (tf_AFCKeyValueClose)GetProcAddress(m_iTunesDll, "AFCKeyValueClose");
			AFCFileRefOpen = (tf_AFCFileRefOpen)GetProcAddress(m_iTunesDll, "AFCFileRefOpen");
			AFCFileRefClose = (tf_AFCFileRefClose)GetProcAddress(m_iTunesDll, "AFCFileRefClose");
			AFCFileRefRead = (tf_AFCFileRefRead)GetProcAddress(m_iTunesDll, "AFCFileRefRead");
			AFCFileRefWrite = (tf_AFCFileRefWrite)GetProcAddress(m_iTunesDll, "AFCFileRefWrite");
			AFCRemovePath = (tf_AFCRemovePath)GetProcAddress(m_iTunesDll, "AFCRemovePath");
			AFCDirectoryCreate = (tf_AFCDirectoryCreate)GetProcAddress(m_iTunesDll, "AFCDirectoryCreate");
			AFCRenamePath = (tf_AFCRenamePath)GetProcAddress(m_iTunesDll, "AFCRenamePath");
		} else
			return IPOD_ERR_DLL_NOT_FOUND;

		// Loads the CoreFoundation DLL routines
		m_CoreFoundationDll = LoadLibrary(m_pCoreFoundationPath);
		if (m_CoreFoundationDll) {
					 _CFStringMakeConstantString = (tf_CFStringMakeConstantString) GetProcAddress(m_CoreFoundationDll, "__CFStringMakeConstantString");
					 CFWriteStreamCreateWithFile = (tf_CFWriteStreamCreateWithFile)GetProcAddress(m_CoreFoundationDll, "CFWriteStreamCreateWithFile");
           CFReadStreamCreateWithFile = (tf_CFReadStreamCreateWithFile)GetProcAddress(m_CoreFoundationDll, "CFReadStreamCreateWithFile");
           CFStringCreateWithCString = (tf_CFStringCreateWithCString)GetProcAddress(m_CoreFoundationDll, "CFStringCreateWithCString");
           CFURLCreateWithFileSystemPath = (tf_CFURLCreateWithFileSystemPath)GetProcAddress(m_CoreFoundationDll, "CFURLCreateWithFileSystemPath");
           CFReadStreamOpen = (tf_CFReadStreamOpen)GetProcAddress(m_CoreFoundationDll, "CFReadStreamOpen");
           CFWriteStreamOpen = (tf_CFWriteStreamOpen)GetProcAddress(m_CoreFoundationDll, "CFWriteStreamOpen");
           CFPropertyListCreateFromStream = (tf_CFPropertyListCreateFromStream)GetProcAddress(m_CoreFoundationDll, "CFPropertyListCreateFromStream");
           CFReadStreamClose = (tf_CFReadStreamClose)GetProcAddress(m_CoreFoundationDll, "CFReadStreamClose");
           CFPropertyListIsValid = (tf_CFPropertyListIsValid)GetProcAddress(m_CoreFoundationDll, "CFPropertyListIsValid");
           CFPropertyListWriteToStream = (tf_CFPropertyListWriteToStream)GetProcAddress(m_CoreFoundationDll, "CFPropertyListWriteToStream");
           CFWriteStreamClose = (tf_CFWriteStreamClose)GetProcAddress(m_CoreFoundationDll, "CFWriteStreamClose");
           CFRelease = (tf_CFRelease)GetProcAddress(m_CoreFoundationDll, "CFRelease");
           CFURLCreateDataAndPropertiesFromResource = (tf_CFURLCreateDataAndPropertiesFromResource)GetProcAddress(m_CoreFoundationDll, "CFURLCreateDataAndPropertiesFromResource");
           CFPropertyListCreateFromXMLData = (tf_CFPropertyListCreateFromXMLData)GetProcAddress(m_CoreFoundationDll, "CFPropertyListCreateFromXMLData");
           CFPropertyListCreateXMLData = (tf_CFPropertyListCreateXMLData)GetProcAddress(m_CoreFoundationDll, "CFPropertyListCreateXMLData");
           CFURLWriteDataAndPropertiesToResource = (tf_CFURLWriteDataAndPropertiesToResource)GetProcAddress(m_CoreFoundationDll, "CFURLWriteDataAndPropertiesToResource");
            bCanTranslatePLIST = true;
		} else
			return IPOD_ERR_DLL_NOT_FOUND;
		m_iPodState = IPOD_STATE_UNCONNECTED;
	}
	// Registers the static notification call-back method
	ret = AMDeviceNotificationSubscribe(&CiPoTApi::NotificationHandler, 0, 0, 0, &notif);
	return (ret == MDERR_OK) ? IPOD_ERR_OK : IPOD_IPOD_NOT_FOUND;
}
Exemplo n.º 6
0
int RunConverter( int argc, _TCHAR* * argv )
{
#ifdef _DEBUG
	// sleep a bit so we can have time to attach a debugger
	Tell(_T("Sleeping for %d seconds in debug mode."), startupTimeout / 1000);
	Sleep(startupTimeout);
#endif
	int ret = 0;
	wstring name;
	wstring title;
	HANDLE conversionHandle = NULL;

	po::options_description desc("Converts an MPEG-2 Program Stream to a DVR-MS, WMV, or WTV file.");
	po::positional_options_description pos;

	string input;
	string output;
	LONGLONG length;
	bool disableFileLogging;
	bool disableConsoleLogging;
	bool disableAllLogging;
	string interruptName;
	string interruptDirectory;
	string outputDirectory;
	string contentTitle;
	__int64 contentDuration = -1i64;

	desc.add_options()
		("help,?", "Display help message.")
		("input,i", po::value<string>(&input), "an MPEG2 input path. Can be a url.")
		("output,o", po::value<string>(&output), "output path.<type>. Where <type> can be one of \"dvr-ms\", \"wmv\", or \"wtv\"")
		("length,l", po::value<LONGLONG>(&length)->default_value(-1), "the length of the input content in bytes. Only required for a network path such as http." )
		("interrupt-name", po::value<string>(&interruptName), "the file name (without path or extension) of a file that will be created when conversion is to be interrupted.")
		("interrupt-directory", po::value<string>(&interruptDirectory), "the path for this app to look for an interrupt file. An interrupt file is the interrupt_file name with a .interrupt extension. The file itself can be empty.")
		("disable-file-logging", po::value<bool>(&disableFileLogging)->zero_tokens()->default_value(false), "indicates that logging to a file will be disabled.")
		("disable-console-logging", po::value<bool>(&disableConsoleLogging)->zero_tokens()->default_value(false), "indicates that logging to the console will be disabled.")
		("disable-all-logging", po::value<bool>(&disableAllLogging)->zero_tokens()->default_value(false), "indicates that all logging will be disabled.")
		("output-directory,d", po::value<string>(&outputDirectory), "the directory for this app to place conversion output. Only valid if output_path is omitted.")
		("content-title,t", po::value<string>(&contentTitle), "the Title that will be assigned to the output path.<type>.")
		("version,v", po::value<string>()->zero_tokens(), "prints the version of this app.")
		//("content-duration,d", po::value<__int64>(&contentDuration)->default_value(-1i64), "the duration of the input content in seconds." )
		;

	pos.add("input", 1);
	pos.add("output", 1);
	pos.add("length", 1);

	vector<string> args;

	for (int i = 1; i < argc; i++)
		args.push_back(WStringToString(argv[i]));

	po::variables_map variables;

	try
	{
		po::basic_parsed_options<char> oo = po::command_line_parser(args).
			options(desc).positional(pos).run();
		po::store(oo, variables);
		po::notify(variables);
	}
	catch (std::exception e)
	{
		Tell(_T("Invalid command line. Use --help to see options."));
		return -1;
	}

	if (!variables.count("input"))
	{
		bool display = false;
		wstring message;
		if (variables.count("version"))
		{
			message = _T("Version: ");
			message += MPEG2DVRMS_VERSION;
			display = true;
		}
		if (variables.count("help"))
		{
			message = _T("eh... help message not available yet. Hope you have the source!");
			display = true;
		}
		if (!display)
			message = _T("No input file was specified.");
		ret = 100;
		Tell(message);
	}
	else
	{
		try
		{
			//////////////////////////////////////////////////////////////////////////
			// command-line option handling

			LONGLONG contentLength = -1;

			if (variables.count("length"))
				contentLength = length;

			if (variables.count("interrupt-name"))
				name = StringToWString(interruptName);
			else
			{
				name = NewGuid();
				Tell(_T("Generated interrupt name is %s"), name.c_str());
			}

			if (variables.count("interrupt-directory"))
				_conversionFileStoragePath = StringToWString(interruptDirectory);

			if (variables.count("content-title"))
				title = StringToWString(contentTitle);
			else
				title = _T("");

#pragma region input output file handling
			wstring defaultExtension;

			if (IsVista())
				defaultExtension = _T(".dvr-ms");
			else
				defaultExtension = _T(".wtv");

			ATL_URL_SCHEME urlScheme;
			CUrl inputUrl;

			if (!inputUrl.CrackUrl(StringToWString(input).c_str()))
				urlScheme = ATL_URL_SCHEME_FILE;
			else
				urlScheme = inputUrl.GetScheme();

			if (urlScheme == -1)
				urlScheme = ATL_URL_SCHEME_FILE;

			wstring inputPath = StringToWString(input);
			CPath outputPath;

			if (urlScheme == ATL_URL_SCHEME_FILE)
			{
				CPath input = inputPath.c_str();

				if (input.IsFileSpec())
				{
					TCHAR szCurrentDirectory[MAX_PATH];
					if (!GetCurrentDirectory(MAX_PATH, szCurrentDirectory))
						throw CarverLab::Exception(GetLastError());
					wstring currentDirectory = (LPCTSTR)szCurrentDirectory;
					inputPath = currentDirectory + _T("\\") + inputPath.c_str();
					input = inputPath.c_str();
				}
				if (!input.FileExists())
					throw CarverLab::Exception(_T("MPEG2 input path does not exist."));

				if (!variables.count("output"))
					outputPath = inputPath.c_str();
				else
					outputPath = StringToWString(output).c_str();
			}
			else if (urlScheme == ATL_URL_SCHEME_HTTP ||
				urlScheme == ATL_URL_SCHEME_HTTPS)
			{
				if (!variables.count("output"))
				{
					wstring thefullpath;
					CString envString;
					envString.GetEnvironmentVariable(_T("PUBLIC"));
					thefullpath = envString;
					thefullpath += _T("\\Videos\\mpeg2dvrms-output");
					thefullpath += defaultExtension;
					outputPath = thefullpath.c_str();
				}
				else
					outputPath = StringToWString(output).c_str();
			}
			else
				throw CarverLab::Exception(_T("Only http or https URL schemes are supported."));

			bool isUrl = urlScheme != ATL_URL_SCHEME_FILE;

			CPath inPath = inputPath.c_str();

			if (outputPath.GetExtension().MakeLower() == inPath.GetExtension().MakeLower())
				outputPath.RenameExtension(defaultExtension.c_str());

			if (outputPath.GetExtension().MakeLower() == _T(".dvrms"))
			{
				outputPath.RemoveExtension();
				outputPath.AddExtension(_T(".dvr-ms"));
			}
#pragma endregion input output file handling

			//////////////////////////////////////////////////////////////////////////

			conversionHandle = CreateConversion(false, CComBSTR(name.c_str()));

			if (!conversionHandle)
				throw CarverLab::Exception();

			SetConsoleTitle(outputPath);

			Tell(_T("Press ENTER to interrupt and exit."));

			_done = false;
			HANDLE stdinput = GetStdHandle(STD_INPUT_HANDLE);

			std::auto_ptr<InternalThreadData> threadData(new InternalThreadData);
			threadData->activityCallback = ActivityCallback;
			threadData->contentLength = contentLength;
			threadData->conversionHandle = conversionHandle;
			threadData->inputPath = inPath;
			threadData->isUrl = isUrl;
			threadData->outputPath = outputPath;
			threadData->threadData = NULL;
			threadData->userData = NULL;
			threadData->contentTitle = StringToWString(contentTitle);
			threadData->contentDuration = contentDuration;

			_lastConvertedFilePath = outputPath;

			HANDLE thread = CreateThread(NULL, 0, BeginConversion, threadData.get(), 0, NULL);
			if (thread == NULL)
				throw CarverLab::Exception();

			bool shuttingDown = false;
			bool interruptSuccessful = false;	// will be true if the conversion is inactive after InterruptConversion is called

			while (!_done)
			{
				if (!shuttingDown && ((_kbhit() && _getch() == 13) || InterruptNow(name.c_str())))
				{
					shuttingDown = true;
					interruptSuccessful = InterruptConversion(conversionHandle, 30000);	// will wait 30 seconds for the conversion to die
				}

				Sleep(10);
			}

			if (!interruptSuccessful)
			{	// TODO: will need to kill this puppy in an unnice way... awwww
				Tell(_T("InterruptConversion was unsusccessful."));
			}
			// TODO: INFINITE? um... nope. this will need an intervention
			WaitForSingleObject(thread, INFINITE);

			CloseHandle(thread);
		}
		catch (CarverLab::Exception exception)
		{
			Tell(_T("*** Error: %s"), exception.GetErrorString());
			Tell(_T("Exiting..."));
			ret = exception.GetHRESULT();
		}
		catch (...)
		{
			DWORD errorCode = GetLastError();
			wstring error = Exception::GetLastErrorString(errorCode);
			Tell(_T("*** Unhandled Exception: %s"), error.c_str());
			Tell(_T("Exiting..."));
			ret = errorCode;
		}
		if (conversionHandle != NULL)
			CloseConversion(conversionHandle);
	}
#ifdef _DEBUG
	// sleep a bit so we can see any errors
	Tell(_T("Sleeping for %d seconds in debug mode."), sleepTimeout / 1000);
	Sleep(sleepTimeout);
#endif
	return ret;
}
Exemplo n.º 7
0
// Initialize our logfile/log event
void
LogAnalysis::Initialisation()
{
  // Still something to do?
  if(m_initialised || m_logLevel == HLL_NOLOG)
  {
    return;
  }

  // Read the config file (if any)
  ReadConfig();

  // We are now initialized
  // Must do this here, otherwise an endless loop will occur..
  m_initialised = true;

  // Try to register the MS-Windows event log  for writing
  if(m_doEvents)
  {
    // Use standard application event log
    m_eventLog = RegisterEventSource(NULL,m_name);
    if(m_eventLog == NULL)
    {
      m_doEvents = false;
    }
  }

  // Append date time to log's filename
  // And also clean up logfiles that are too old.
  if(m_rotate)
  {
    AppendDateTimeToFilename();
  }

  // Open the logfile
  m_file = CreateFile(m_logFileName
                     ,GENERIC_WRITE
                     ,FILE_SHARE_READ | FILE_SHARE_WRITE
                     ,NULL              // Security
                     ,CREATE_ALWAYS     // Always throw away old log
                     ,FILE_ATTRIBUTE_NORMAL
                     ,NULL);
  if(m_file ==  INVALID_HANDLE_VALUE)
  {
    CString file;
    if(file.GetEnvironmentVariable("TMP"))
    {
      if(file.Right(1) != "\\") file += "\\";
      file += "Analysis.log";

      // Open the logfile in shared writing mode
      // more applications can write to the file
      m_file = CreateFile(file
                         ,GENERIC_WRITE
                         ,FILE_SHARE_READ | FILE_SHARE_WRITE
                         ,NULL              // Security
                         ,CREATE_ALWAYS     // Always throw away old log
                         ,FILE_ATTRIBUTE_NORMAL
                         ,NULL);
      if(m_file == INVALID_HANDLE_VALUE)
      {
        // Give up. Cannot create a logfile
        m_file = NULL;
        m_logLevel = HLL_NOLOG;
        return;
      }
      else
      {
        // Alternative file created
        m_logFileName = file;
      }
    }
  }

  if(m_file)
  {
    // Write a BOM to the logfile, so we can read logged UTF-8 strings
    DWORD written = 0;		// Not optional for MS-Windows Server 2012!!
    CString bom = ConstructBOM();
    WriteFile(m_file,bom.GetString(),bom.GetLength(),&written,nullptr);

    // Starting the log writing thread
    RunLog();
  }
  // Tell that we are now running
  AnalysisLog("Logfile now running for:", LogType::LOG_INFO,false,m_name);
}