Exemplo n.º 1
0
/**********************************************************************************************************************
	NStringUtils::Convert_Raw - converts a wide string to a built-in value type

		source -- source wide string
		value -- output parameter to store conversion in

	Returns: conversion success/failure
**********************************************************************************************************************/
bool NStringUtils::Convert_Raw( const wchar_t *source, uint64 &value ) 
{
	wchar_t *end_ptr = nullptr;
	value = _wcstoui64( source, &end_ptr, 10 );

	return *end_ptr == 0;
}
Exemplo n.º 2
0
/*---------------------------------------------------------------------------*/
int t100::searchDevices()
{ 
  // Enumerate and print the HID devices on the system
  struct hid_device_info *devs, *cur_dev;

  t100_totalDevices = 0;
  
  devs = hid_enumerate(0x0, 0x0);
  cur_dev = devs; 
  while (cur_dev) 
  { 
    if((cur_dev->vendor_id == VID) && (cur_dev->product_id == PID))
    {     
      #if WIN
      t100_deviceSerials[t100_totalDevices] = _wcstoui64(cur_dev->serial_number,NULL,0);
      #else
      t100_deviceSerials[t100_totalDevices] = wcstoul(cur_dev->serial_number,NULL,0);
      #endif
      t100_totalDevices++;
    }   
    cur_dev = cur_dev->next;
  }
  hid_free_enumeration(devs);

  return t100_totalDevices;
}
Exemplo n.º 3
0
	vuint64_t wtou64_test(const WString& string, bool& success)
	{
		wchar_t* endptr = 0;
		vuint64_t result = _wcstoui64(string.Buffer(), &endptr, 10);
		success = endptr == string.Buffer() + string.Length() && u64tow(result) == string;
		return result;
	}
Exemplo n.º 4
0
VOID
ConditionSetValue(
	IN ConditionDataType Type,
	IN PWSTR StringValue,
	IN PCONDITION_ENTRY Entry
	)
{
	switch (Type) {

		case ConditionDataUlong:
			Entry->UlongValue = (ULONG)wcstol(StringValue, NULL, 16);
			break;

		case ConditionDataUlong64:
			Entry->Ulong64Value = (ULONG)_wcstoui64(StringValue, NULL, 16);
			break;

		case ConditionDataDouble:
		case ConditionDataString:
			StringCchCopy(Entry->StringValue, MAX_PATH, StringValue);
			break;

		default:
			StringCchCopy(Entry->StringValue, MAX_PATH, StringValue);
	}	
}
Exemplo n.º 5
0
extern "C" uintmax_t _CRTIMP __cdecl wcstoumax (
    const wchar_t *nptr,
    wchar_t **endptr,
    int ibase
    )
{
    return _wcstoui64(nptr, endptr, ibase);
}
Exemplo n.º 6
0
extern "C" unsigned long long _CRTIMP __cdecl wcstoull (
        const wchar_t *nptr,
        wchar_t **endptr,
        int ibase
        )
{
    return _wcstoui64(nptr, endptr, ibase);
}
Exemplo n.º 7
0
ulong StringParser::WStringTo(const WStringRef& inString, int base /*= 10*/)
{
#ifdef MEDUSA_WINDOWS
	return (ulong)_wcstoui64(inString.c_str(), nullptr, base);
#else
	return wcstoull(inString.c_str(), nullptr, base);
#endif

}
Exemplo n.º 8
0
 int64 ConvertStringToInt64(Var string, ScriptContext* scriptContext)
 {
     JavascriptString* str = JavascriptString::FromVar(string);
     charcount_t length = str->GetLength();
     const char16* buf = str->GetString();
     int radix = 10;
     if (length >= 2 && buf[0] == '0' && buf[1] == 'x')
     {
         radix = 16;
     }
     return (int64)_wcstoui64(buf, nullptr, radix);
 }
Exemplo n.º 9
0
void cmdCheck(int argc, wchar_t** argv)
{
	if (argc >= 1)
	{
		if (_wcsicmp(argv[0], L"heap") == 0 &&
			argc > 1)
		{
			tst_heapid hid = (tst_heapid)
				_wcstoui64(argv[1], NULL, 16);
			getTrackSystem()->CheckHeap(hid);
			return;
		}
	}
}
Exemplo n.º 10
0
bool ConfigurationHolder::readNumericFromConfigFile(Configuration & configObject, int nBase)
{
	WCHAR buf[21]; // UINT64_MAX in dec has 20 digits
	DWORD read = GetPrivateProfileString(CONFIG_FILE_SECTION_NAME, configObject.getName(), L"", buf, _countof(buf), configPath);

	if (read > 0 && wcslen(buf) > 0)
	{
#ifdef _WIN64
		configObject.setNumeric(_wcstoui64(buf, NULL, nBase));
#else
		configObject.setNumeric(wcstoul(buf, NULL, nBase));
#endif
		return true;
	}

	return false;
}
Exemplo n.º 11
0
uint64 StringParser::WStringTo(const WStringRef& inString, int base /*= 10*/)
{
#ifdef MEDUSA_WINDOWS
	return _wcstoui64(inString.c_str(), nullptr, base);
#endif
#ifdef MEDUSA_IOS
	return wcstoull(inString.c_str(), nullptr, base);
#endif

#ifdef MEDUSA_ANDROID
	std::wstringstream ss;
	ss << inString.c_str();
	uint64 r;
	ss >> r;
	return r;
#endif

}
Exemplo n.º 12
0
HRESULT STDMETHODCALLTYPE CNzbParser::startElement( 
	/* [in] */ const wchar_t *pwchNamespaceUri,
	/* [in] */ int cchNamespaceUri,
	/* [in] */ const wchar_t *pwchLocalName,
	/* [in] */ int cchLocalName,
	/* [in] */ const wchar_t *pwchRawName,
	/* [in] */ int cchRawName,
	/* [in] */ ISAXAttributes *pAttributes)
{
	CString localName(pwchLocalName, cchLocalName);
	if(localName == _T("nzb")) {
		ASSERT(theNzb);
		curNzb = theNzb;
	} else if(localName == _T("file")) {
		ASSERT(curNzb);
		curFile = new CNzbFile(curNzb);
		const wchar_t* pwchSubject;
		int cchSubject;
		VERIFY(SUCCEEDED(pAttributes->getValueFromName(L"", 0, L"subject", wcslen(L"subject"), &pwchSubject, &cchSubject)));
		curFile->subject = CString(pwchSubject, cchSubject);
		curNzb->files.Add(curFile);
	} else if(localName == _T("group")) {
		ASSERT(curFile);
		curGroup = true;
		curGroupString.Empty();
	} else if(localName == _T("segment")) {
		ASSERT(curFile);
		curSegment = new CNzbSegment(curFile);
		const wchar_t* pwchBytes;
		int cchBytes;
		VERIFY(SUCCEEDED(pAttributes->getValueFromName(L"", 0, L"bytes", wcslen(L"bytes"), &pwchBytes, &cchBytes)));
		CString bytes(pwchBytes, cchBytes);
		curSegment->bytes = _wcstoui64(bytes, NULL, 10);

		const wchar_t* pwchNumber;
		int cchNumber;
		VERIFY(SUCCEEDED(pAttributes->getValueFromName(L"", 0, L"number", wcslen(L"number"), &pwchNumber, &cchNumber)));
		CString number(pwchNumber, cchNumber);
		curSegment->number = wcstoul(number, NULL, 10);

		curFile->segments.Add(curSegment);
	}
	return S_OK;
}
Exemplo n.º 13
0
/**
 * Gets the switch port info from WMI (switch port friendly name, ifSpeed) 
 * and merges into the list of existing ports.
 */
void readWMISwitchPorts(HSP *sp)
{
	BSTR path = SysAllocString(WMI_VIRTUALIZATION_NS_V2);
	HRESULT hr = S_FALSE;
	IWbemServices *pNamespace = NULL;

	hr = connectToWMI(path, &pNamespace);
	if (FAILED(hr)) {
		//only try the v2 namespace since this will only be present
		//with the extensible switch that supports sampling.
	    //don't try to get counters if there is no sampling.
		SysFreeString(path);
		myLog(LOG_INFO, "readWMISwitchPorts: virtualization namespace v2 not found");
		return;
	} else {
		SysFreeString(path);
	}

	BSTR queryLang = SysAllocString(L"WQL");
	wchar_t *query = L"SELECT * FROM Msvm_EthernetSwitchPort";
	IEnumWbemClassObject *switchPortEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &switchPortEnum);
	SysFreeString(queryLang);
	if (FAILED(hr)) {
		myLog(LOG_ERR,"readWMISwitchPorts: ExecQuery() failed for query %S error=0x%x", query, hr);
		pNamespace->Release();
		return;
	}

	if (sp->vAdaptorList == NULL) {
		sp->vAdaptorList = adaptorListNew();
	}
	IWbemClassObject *switchPortObj = NULL;

	hr = WBEM_S_NO_ERROR;
	while (WBEM_S_NO_ERROR == hr) {
		SFLAdaptor *vAdaptor = NULL;
		ULONG uReturned = 1;
		hr = switchPortEnum->Next(WBEM_INFINITE, 1, &switchPortObj, &uReturned);
		if (0 == uReturned) {
			break;
		}
		wchar_t *guidString = stringFromWMIProperty(switchPortObj, PROP_NAME);
		if (guidString != NULL) {
			char portGuid[FORMATTED_GUID_LEN+1];
			guidToString(guidString, (UCHAR *)portGuid, FORMATTED_GUID_LEN);
			myLog(LOG_INFO, "readWMISwitchPorts: portGuid=%s", portGuid);
			my_free(guidString);
			vAdaptor = adaptorListGet(sp->vAdaptorList, portGuid);
		}
		if (vAdaptor != NULL) {
			HVSVPortInfo *portInfo = (HVSVPortInfo *)vAdaptor->userData;
			wchar_t *switchName = stringFromWMIProperty(switchPortObj, PROP_SYSTEM_NAME);
			if (switchName != NULL) {
				if (portInfo->switchName != NULL) {
					my_free(portInfo->switchName);
				}
				portInfo->switchName = switchName;
			}
			wchar_t *friendlyName = stringFromWMIProperty(switchPortObj, PROP_ELEMENT_NAME);
			if (friendlyName != NULL) {
				if (portInfo->portFriendlyName != NULL) {
					my_free(portInfo->portFriendlyName);
				}
				portInfo->portFriendlyName = friendlyName;
			}
			setPortCountersInstance(vAdaptor);
			wchar_t *speedString = stringFromWMIProperty(switchPortObj, PROP_SPEED);
			if (speedString != NULL) {
				ULONGLONG ifSpeed = _wcstoui64(speedString, NULL, 10);
				vAdaptor->ifSpeed = ifSpeed;
				my_free(speedString);
			}
			//could also get ifDirection but FullDuplex=True always

			//Get the MACs and VM system name when we enumerate the vms.
			myLog(LOG_INFO, 
				  "readWMISwitchPorts: updated switch port %s %S portId=%u ifIndex=%u ifSpeed=%llu counterName=%S", 
				  vAdaptor->deviceName, portInfo->portFriendlyName, portInfo->portId, vAdaptor->ifIndex, 
				  vAdaptor->ifSpeed, portInfo->portCountersInstance);
		} else {
			myLog(LOG_INFO, "readWMISwitchPorts: vAdapter not found");
		}
		switchPortObj->Release();
	}
	switchPortEnum->Release();
	pNamespace->Release();
}
Exemplo n.º 14
0
int main(int argc, char * argv[])
#endif // FOMENT_UNIX
{
    int_t pdx = 0;
    int adx = 1;
    while (adx < argc)
    {
        if (StringCompareS(argv[adx], "-A") == 0)
            adx += 2;
        else if (StringCompareS(argv[adx], "-I") == 0)
            adx += 2;
        else if (StringCompareS(argv[adx], "-X") == 0)
            adx += 2;
        else if (argv[adx][0] != '-')
        {
            pdx = adx;
            break;
        }
        else if (StringCompareS(argv[adx], "-no-inline-procedures") == 0)
        {
            InlineProcedures = 0;
            adx += 1;
        }
        else if (StringCompareS(argv[adx], "-no-inline-imports") == 0)
        {
            InlineImports = 0;
            adx += 1;
        }
        else if (StringCompareS(argv[adx], "--validate-heap") == 0)
        {
            ValidateHeap = 1;
            adx += 1;
        }
#ifdef FOMENT_WINDOWS
        else if (StringCompareS(argv[adx], "--section-table") == 0)
        {
            adx += 1;

            if (adx < argc)
            {
#ifdef FOMENT_32BIT
                SectionTableBase = (void *) wcstol(argv[adx], 0, 16);
#endif // FOMENT_32BIT
#ifdef FOMENT_64BIT
                SectionTableBase = (void *) _wcstoui64(argv[adx], 0, 16);
#endif // FOMENT_64BIT

                adx += 1;
            }
        }
#endif // FOMENT_WINDOWS
        else if (StringCompareS(argv[adx], "--random-seed") == 0)
        {
            adx += 1;

            if (adx < argc)
            {
                RandomSeed = StringToInt(argv[adx]);
                adx += 1;
            }
        }
        else
            break;
    }

    FThreadState ts;

    try
    {
        SetupFoment(&ts);

        if (pdx > 0)
        {
            AddToLibraryPath(argv[pdx]);
        }
    }
    catch (FObject obj)
    {
        printf("Unexpected exception: SetupFoment: %p\n", obj);
        WriteSimple(R.StandardOutput, obj, 0);

        if (ValidateHeap)
        {
            FailedGC();
            FailedExecute();
        }
        return(1);
    }

    FAssert(argc >= 1);

    try
    {
        int adx = 1;
        while (adx < argc)
        {
            if (StringCompareS(argv[adx], "-A") == 0)
            {
                adx += 1;

                if (adx == argc)
                    return(MissingArgument(argv[adx - 1]));

                FObject lp = R.LibraryPath;

                for (;;)
                {
                    FAssert(PairP(lp));

                    if (Rest(lp) == EmptyListObject)
                        break;
                    lp = Rest(lp);
                }

//                AsPair(lp)->Rest = MakePair(MakeStringS(argv[adx]), EmptyListObject);
                SetRest(lp, MakePair(MakeStringS(argv[adx]), EmptyListObject));

                adx += 1;
            }
            else if (StringCompareS(argv[adx], "-I") == 0)
            {
                adx += 1;

                if (adx == argc)
                    return(MissingArgument(argv[adx - 1]));

                R.LibraryPath = MakePair(MakeStringS(argv[adx]), R.LibraryPath);

                adx += 1;
            }
            else if (StringCompareS(argv[adx], "-X") == 0)
            {
                adx += 1;

                if (adx == argc)
                    return(MissingArgument(argv[adx - 1]));

                R.LibraryExtensions = MakePair(MakeStringS(argv[adx]), R.LibraryExtensions);

                adx += 1;
            }
            else if (StringCompareS(argv[adx], "-no-inline-procedures") == 0
                     || StringCompareS(argv[adx], "-no-inline-imports") == 0
                     || StringCompareS(argv[adx], "--validate-heap") == 0)
                adx += 1;
#ifdef FOMENT_WINDOWS
            else if (StringCompareS(argv[adx], "--section-table") == 0)
                adx += 2;
#endif // FOMENT_WINDOWS
            else if (StringCompareS(argv[adx], "--random-seed") == 0)
                adx += 2;
            else if (argv[adx][0] != '-')
                return(ProgramMode(adx, argc, argv));
            else
                break;
        }

        R.LibraryPath = ReverseListModify(MakePair(MakeStringC("."), R.LibraryPath));
        R.CommandLine = MakePair(MakeInvocation(adx, argv),
                                 MakeCommandLine(argc - adx, argv + adx));

        ExecuteThunk(R.InteractiveThunk);
        ExitFoment();
        return(0);
//        return(RunRepl(GetInteractionEnv()));
    }
    catch (FObject obj)
    {
        if (ExceptionP(obj) == 0)
            WriteStringC(R.StandardOutput, "exception: ");
        WriteSimple(R.StandardOutput, obj, 0);
        WriteCh(R.StandardOutput, '\n');

        if (ValidateHeap)
        {
            FailedGC();
            FailedExecute();
        }
        return(-1);
    }
}
Exemplo n.º 15
0
/**
 * Gets the switch port info from WMI (switch port friendly name, ifSpeed) 
 * and merges into the list of existing ports.
 */
void readWMISwitchPorts(HSP *sp)
{
	myLog(LOG_INFO, "entering readWMISwitchPorts");
	BSTR path = SysAllocString(WMI_VIRTUALIZATION_NS_V2);
	HRESULT hr = S_FALSE;
	IWbemServices *pNamespace = NULL;

	hr = connectToWMI(path, &pNamespace);
	if (FAILED(hr)) {
		//only try the v2 namespace since this will only be present
		//with the extensible switch that supports sampling.
	    //don't try to get counters if there is no sampling.
		SysFreeString(path);
		myLog(LOG_INFO, "readWMISwitchPorts: virtualization namespace v2 not found");
		return;
	} else {
		SysFreeString(path);
	}

	BSTR queryLang = SysAllocString(L"WQL");
	BSTR query = SysAllocString(L"SELECT * FROM Msvm_EthernetSwitchPort");
	IEnumWbemClassObject *switchPortEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &switchPortEnum);
	SysFreeString(queryLang);
	SysFreeString(query);
	if (FAILED(hr)) {
		myLog(LOG_ERR,"readWMISwitchPorts: ExecQuery() failed for query %S error=0x%x", query, hr);
		CoUninitialize();
		return;
	}

	if (sp->vAdaptorList == NULL) {
		sp->vAdaptorList = adaptorListNew();
	}
	IWbemClassObject *switchPortObj = NULL;

	BSTR propElementName = SysAllocString(L"ElementName");
	BSTR propSystemName = SysAllocString(L"SystemName");
	BSTR propName = SysAllocString(L"Name");
	BSTR propSpeed = SysAllocString(L"Speed");
	//could also get ifDirection but FullDuplex=True always
	VARIANT systemVal;
	VARIANT elementVal;
	VARIANT nameVal;
	VARIANT speedVal;

	hr = WBEM_S_NO_ERROR;
	while (WBEM_S_NO_ERROR == hr) {
		SFLAdaptor *vAdaptor = NULL;
		ULONG uReturned = 1;
		hr = switchPortEnum->Next(WBEM_INFINITE, 1, &switchPortObj, &uReturned);
		if (0 == uReturned) {
			break;
		}
		HRESULT portHr;
		portHr = switchPortObj->Get(propName, 0, &nameVal, 0, 0);
		char portGuid[FORMATTED_GUID_LEN+1];
		guidToString(nameVal.bstrVal, (UCHAR *)portGuid, FORMATTED_GUID_LEN);
		myLog(LOG_INFO, "readWMISwitchPorts: portGuid=%s", portGuid);
		VariantClear(&nameVal);
		vAdaptor = adaptorListGet(sp->vAdaptorList, portGuid);
		if (vAdaptor != NULL) {
			portHr = switchPortObj->Get(propSystemName, 0, &systemVal, 0, 0);
			portHr = switchPortObj->Get(propElementName, 0, &elementVal, 0, 0);
			portHr = switchPortObj->Get(propSpeed, 0, &speedVal, 0, 0);
			int length = SysStringLen(systemVal.bstrVal)+1; //include room for terminating null
			wchar_t *switchName = (wchar_t *)my_calloc(length*sizeof(wchar_t));
			wcscpy_s(switchName, length, systemVal.bstrVal);
			length = SysStringLen(elementVal.bstrVal)+1; 
			wchar_t *friendlyName = (wchar_t *)my_calloc(length*sizeof(wchar_t));
			wcscpy_s(friendlyName, length, elementVal.bstrVal);
			ULONGLONG ifSpeed = _wcstoui64(speedVal.bstrVal, NULL, 10);
			VariantClear(&systemVal);
			VariantClear(&elementVal);
			VariantClear(&speedVal);
			HVSVPortInfo *portInfo = (HVSVPortInfo *)vAdaptor->userData;
			if (portInfo->switchName != NULL) {
				my_free(portInfo->switchName);
			}
			portInfo->switchName = switchName;
			if (portInfo->portFriendlyName != NULL) {
				my_free(portInfo->portFriendlyName);
			}
			portInfo->portFriendlyName = friendlyName;
			setPortCountersInstance(vAdaptor);
			vAdaptor->ifSpeed = ifSpeed;
			//Get the MACs and VM system name when we enumerate the vms.
			myLog(LOG_INFO, 
				  "readWMISwitchPorts: updated switch port %s %S portId=%u ifIndex=%u ifSpeed=%llu counterName=%S", 
				  vAdaptor->deviceName, portInfo->portFriendlyName, portInfo->portId, vAdaptor->ifIndex, 
				  vAdaptor->ifSpeed, portInfo->portCountersInstance);
		} else {
			myLog(LOG_INFO, "readWMISwitchPorts: vAdapter not found");
		}
		switchPortObj->Release();
	}
	switchPortEnum->Release();
	pNamespace->Release();
	CoUninitialize();
	SysFreeString(propElementName);
	SysFreeString(propSystemName);
	SysFreeString(propName);
	SysFreeString(propSpeed);

	return;
}
Exemplo n.º 16
0
_Success_(return) BOOL WINSTD_API StringToGuidW(_In_z_ LPCWSTR lpszGuid, _Out_ LPGUID lpGuid, _Out_opt_ LPCWSTR *lpszGuidEnd)
{
    GUID g;
    LPWSTR lpszEnd;
    unsigned long ulTmp;
    unsigned long long ullTmp;

    if (!lpszGuid || !lpGuid || *lpszGuid != '{') return FALSE;
    lpszGuid++;

    g.Data1 = wcstoul(lpszGuid, &lpszEnd, 16);
    if (errno == ERANGE) return FALSE;
    lpszGuid = lpszEnd;

    if (*lpszGuid != '-') return FALSE;
    lpszGuid++;

    ulTmp = wcstoul(lpszGuid, &lpszEnd, 16);
    if (errno == ERANGE || ulTmp > 0xFFFF) return FALSE;
    g.Data2 = (unsigned short)ulTmp;
    lpszGuid = lpszEnd;

    if (*lpszGuid != '-') return FALSE;
    lpszGuid++;

    ulTmp = wcstoul(lpszGuid, &lpszEnd, 16);
    if (errno == ERANGE || ulTmp > 0xFFFF) return FALSE;
    g.Data3 = (unsigned short)ulTmp;
    lpszGuid = lpszEnd;

    if (*lpszGuid != '-') return FALSE;
    lpszGuid++;

    ulTmp = wcstoul(lpszGuid, &lpszEnd, 16);
    if (errno == ERANGE || ulTmp > 0xFFFF) return FALSE;
    g.Data4[0] = (unsigned char)((ulTmp >> 8) & 0xff);
    g.Data4[1] = (unsigned char)( ulTmp       & 0xff);
    lpszGuid = lpszEnd;

    if (*lpszGuid != '-') return FALSE;
    lpszGuid++;

    ullTmp = _wcstoui64(lpszGuid, &lpszEnd, 16);
    if (errno == ERANGE || ullTmp > 0xFFFFFFFFFFFF) return FALSE;
    g.Data4[2] = (unsigned char)((ullTmp >> 40) & 0xff);
    g.Data4[3] = (unsigned char)((ullTmp >> 32) & 0xff);
    g.Data4[4] = (unsigned char)((ullTmp >> 24) & 0xff);
    g.Data4[5] = (unsigned char)((ullTmp >> 16) & 0xff);
    g.Data4[6] = (unsigned char)((ullTmp >>  8) & 0xff);
    g.Data4[7] = (unsigned char)( ullTmp        & 0xff);
    lpszGuid = lpszEnd;

    if (*lpszGuid != '}') return FALSE;
    lpszGuid++;

    if (lpszGuidEnd)
        *lpszGuidEnd = lpszGuid;

    *lpGuid = g;
    return TRUE;
}
Exemplo n.º 17
0
void
O2Profile_SAX2Handler::
endElement(const XMLCh* const uri
		 , const XMLCh* const localname
		 , const XMLCh* const qname)
{
	switch (CurElm) {
		case PROF_XMLELM_ID:
			Profile->ID.assign(buf.c_str(), buf.size());
			break;
		case PROF_XMLELM_PRIVKEY:
			Profile->PrivKey.assign(buf.c_str(), buf.size());
			break;
		case PROF_XMLELM_PUBKEY:
			Profile->PubKey.assign(buf.c_str(), buf.size());
			break;
		case PROF_XMLELM_IP:
			Profile->IP = e2ip(buf.c_str(), buf.size());
			break;
		case PROF_XMLELM_P2PPORT:
			Profile->P2PPort = (ushort)wcstoul(buf.c_str(), NULL, 10);
			break;
		case PROF_XMLELM_PROXYPORT:
			Profile->ProxyPort = (ushort)wcstoul(buf.c_str(), NULL, 10);
			break;
		case PROF_XMLELM_ADMINPORT:
			Profile->AdminPort = (ushort)wcstoul(buf.c_str(), NULL, 10);
			break;
		case PROF_XMLELM_NAME:
			if (buf.size() <= O2_MAX_NAME_LEN) {
				Profile->SetNodeName(buf.c_str());
			}
			break;
		case PROF_XMLELM_COMMENT:
			if (buf.size() <= O2_MAX_COMMENT_LEN) {
				for (size_t i = 0; i < buf.size(); i++) {
					if (buf[i] == L'\n')
						Profile->Comment += L"\r\n";
					else
						Profile->Comment += buf[i];
				}
			}
			break;
		case PROF_XMLELM_DBDIR:
			Profile->SetDBDir(buf.c_str());
			break;
		case PROF_XMLELM_CACHEROOT:
			Profile->SetCacheRoot(buf.c_str());
			break;
		case PROF_XMLELM_ADMINROOT:
			Profile->SetAdminRoot(buf.c_str());
			break;
		case PROF_XMLELM_ADMIN_BROWSER_TYPE:
			Profile->AdminBrowserType = buf;
			break;
		case PROF_XMLELM_ADMIN_BROWSER_PATH:
			Profile->AdminBrowserPath = buf;
			break;
		case PROF_XMLELM_UPNP_ADAPTERNAME:
			unicode2ascii(buf, Profile->UPnPAdapterName);
			break;
		case PROF_XMLELM_UPNP_LOCATION:
			unicode2ascii(buf, Profile->UPnPLocation);
			break;
		case PROF_XMLELM_UPNP_SERVICEID:
			unicode2ascii(buf, Profile->UPnPServiceId);
			break;

		case PROF_XMLELM_LIMIT:
			if (plimit)
				*plimit = wcstoul(buf.c_str(), NULL, 10);
			break;
		case PROF_XMLELM_SIZE_T:
			if (puint64)
				*puint64 = _wcstoui64(buf.c_str(), NULL, 10);
			break;
		case PROF_XMLELM_BOOL:
			*pbool = buf[0] == '1' ? true : false;
			break;
	}

	buf = L"";

	CurElm = PROF_XMLELM_NONE;
	if (!MATCHLNAME(L"profile"))
		return;

	if (Profile->PrivKey.size() != RSA_PRIVKEY_SIZE
			|| Profile->PubKey.size() != RSA_PUBKEY_SIZE) {
		Profile->SetRSAKey(NULL, 0, NULL, 0);
	}
}
Exemplo n.º 18
0
BOOL CTortoiseProcApp::InitInstance()
{
	CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": InitInstance\n"));
	CheckUpgrade();
	CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
	CMFCButton::EnableWindowsTheming();
	CHistoryCombo::m_nGitIconIndex = SYS_IMAGE_LIST().AddIcon((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GITCONFIG), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE));

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL);

	//set the resource dll for the required language
	CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
	long langId = loc;
	{
		CString langStr;
		langStr.Format(_T("%ld"), langId);
		CCrashReport::Instance().AddUserInfoToReport(L"LanguageID", langStr);
	}
	CString langDll;
	CStringA langpath = CStringA(CPathUtils::GetAppParentDirectory());
	langpath += "Languages";
	do
	{
		langDll.Format(_T("%sLanguages\\TortoiseProc%ld.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId);

		CString sVer = _T(STRPRODUCTVER);
		CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
		if (sFileVer == sVer)
		{
			HINSTANCE hInst = LoadLibrary(langDll);
			if (hInst != NULL)
			{
				CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Load Language DLL %s\n"), langDll);
				AfxSetResourceHandle(hInst);
				break;
			}
		}
		{
			DWORD lid = SUBLANGID(langId);
			lid--;
			if (lid > 0)
			{
				langId = MAKELANGID(PRIMARYLANGID(langId), lid);
			}
			else
				langId = 0;
		}
	} while (langId != 0);
	TCHAR buf[6] = { 0 };
	_tcscpy_s(buf, _T("en"));
	langId = loc;
	// MFC uses a help file with the same name as the application by default,
	// which means we have to change that default to our language specific help files
	CString sHelppath = CPathUtils::GetAppDirectory() + _T("TortoiseGit_en.chm");
	free((void*)m_pszHelpFilePath);
	m_pszHelpFilePath=_tcsdup(sHelppath);
	sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseGit_en.chm");
	do
	{
		CString sLang = _T("_");
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf)))
		{
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf)))
		{
			sLang += _T("_");
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));

		DWORD lid = SUBLANGID(langId);
		lid--;
		if (lid > 0)
		{
			langId = MAKELANGID(PRIMARYLANGID(langId), lid);
		}
		else
			langId = 0;
	} while (langId);
	CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Set Help Filename %s\n"), m_pszHelpFilePath);
	setlocale(LC_ALL, "");

	if (!g_Git.CheckMsysGitDir())
	{
		UINT ret = CMessageBox::Show(NULL, IDS_PROC_NOMSYSGIT, IDS_APPNAME, 3, IDI_HAND, IDS_PROC_SETMSYSGITPATH, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON);
		if(ret == 2)
		{
			ShellExecute(NULL, NULL, _T("http://msysgit.github.io/"), NULL, NULL, SW_SHOW);
		}
		else if(ret == 1)
		{
			// open settings dialog
			CSinglePropSheetDlg(CString(MAKEINTRESOURCE(IDS_PROC_SETTINGS_TITLE)), new CSetMainPage(), this->GetMainWnd()).DoModal();
		}
		return FALSE;
	}
	if (CAppUtils::GetMsysgitVersion() < 0x01070a00)
	{
		int ret = CMessageBox::ShowCheck(NULL, IDS_PROC_OLDMSYSGIT, IDS_APPNAME, 1, IDI_EXCLAMATION, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON, IDS_IGNOREBUTTON, _T("OldMsysgitVersionWarning"), IDS_PROC_NOTSHOWAGAINIGNORE);
		if (ret == 1)
		{
			CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore"
			ShellExecute(NULL, NULL, _T("http://msysgit.github.io/"), NULL, NULL, SW_SHOW);
			return FALSE;
		}
		else if (ret == 2)
		{
			CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore"
			return FALSE;
		}
	}

	{
		CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Registering Crash Report ...\n"));
		CCrashReport::Instance().AddUserInfoToReport(L"msysGitDir", CGit::ms_LastMsysGitDir);
		CString versionString;
		versionString.Format(_T("%d"), CGit::ms_LastMsysGitVersion);
		CCrashReport::Instance().AddUserInfoToReport(L"msysGitVersion", versionString);
	}

	CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Initializing UI components ...\n"));
	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.

	INITCOMMONCONTROLSEX used = {
		sizeof(INITCOMMONCONTROLSEX),
			ICC_ANIMATE_CLASS | ICC_BAR_CLASSES | ICC_COOL_CLASSES | ICC_DATE_CLASSES |
			ICC_HOTKEY_CLASS | ICC_INTERNET_CLASSES | ICC_LISTVIEW_CLASSES |
			ICC_NATIVEFNTCTL_CLASS | ICC_PAGESCROLLER_CLASS | ICC_PROGRESS_CLASS |
			ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES | ICC_UPDOWN_CLASS |
			ICC_USEREX_CLASSES | ICC_WIN95_CLASSES
	};
	InitCommonControlsEx(&used);
	AfxOleInit();
	AfxEnableControlContainer();
	AfxInitRichEdit5();
	CWinAppEx::InitInstance();
	SetRegistryKey(_T("TortoiseGit"));
	AfxGetApp()->m_pszProfileName = _tcsdup(_T("TortoiseProc")); // w/o this ResizableLib will store data under TortoiseGitProc which is not compatible with older versions

	CCmdLineParser parser(AfxGetApp()->m_lpCmdLine);

	hWndExplorer = NULL;
	CString sVal = parser.GetVal(_T("hwnd"));
	if (!sVal.IsEmpty())
		hWndExplorer = (HWND)_wcstoui64(sVal, nullptr, 16);

	while (GetParent(hWndExplorer)!=NULL)
		hWndExplorer = GetParent(hWndExplorer);
	if (!IsWindow(hWndExplorer))
	{
		hWndExplorer = NULL;
	}

	// if HKCU\Software\TortoiseGit\Debug is not 0, show our command line
	// in a message box
	if (CRegDWORD(_T("Software\\TortoiseGit\\Debug"), FALSE)==TRUE)
		AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

	if (parser.HasKey(_T("urlhandler")))
	{
		CString url = parser.GetVal(_T("urlhandler"));
		if (url.Find(_T("tgit://clone/")) == 0)
		{
			url = url.Mid(13); // 21 = "tgit://clone/".GetLength()
		}
		else if (url.Find(_T("github-windows://openRepo/")) == 0)
		{
			url = url.Mid(26); // 26 = "github-windows://openRepo/".GetLength()
			int questioMark = url.Find('?');
			if (questioMark > 0)
				url = url.Left(questioMark);
		}
		else if (url.Find(_T("smartgit://cloneRepo/")) == 0)
		{
			url = url.Mid(21); // 21 = "smartgit://cloneRepo/".GetLength()
		}
		else
		{
			CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
			return FALSE;
		}
		CString newCmd;
		newCmd.Format(_T("/command:clone /url:\"%s\" /hasurlhandler"), url);
		parser = CCmdLineParser(newCmd);
	}

	if ( parser.HasKey(_T("path")) && parser.HasKey(_T("pathfile")))
	{
		CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
		return FALSE;
	}

	CTGitPath cmdLinePath;
	CTGitPathList pathList;
	if (g_sGroupingUUID.IsEmpty())
		g_sGroupingUUID = parser.GetVal(L"groupuuid");
	if ( parser.HasKey(_T("pathfile")) )
	{

		CString sPathfileArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("pathfile")));

		cmdLinePath.SetFromUnknown(sPathfileArgument);
		if (pathList.LoadFromFile(cmdLinePath)==false)
			return FALSE;		// no path specified!
		if ( parser.HasKey(_T("deletepathfile")) )
		{
			// We can delete the temporary path file, now that we've loaded it
			::DeleteFile(cmdLinePath.GetWinPath());
		}
		// This was a path to a temporary file - it's got no meaning now, and
		// anybody who uses it again is in for a problem...
		cmdLinePath.Reset();

	}
	else
	{

		CString sPathArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("path")));
		if (parser.HasKey(_T("expaths")))
		{
			// an /expaths param means we're started via the buttons in our Win7 library
			// and that means the value of /expaths is the current directory, and
			// the selected paths are then added as additional parameters but without a key, only a value

			// because of the "strange treatment of quotation marks and backslashes by CommandLineToArgvW"
			// we have to escape the backslashes first. Since we're only dealing with paths here, that's
			// a save bet.
			// Without this, a command line like:
			// /command:commit /expaths:"D:\" "D:\Utils"
			// would fail because the "D:\" is treated as the backslash being the escape char for the quotation
			// mark and we'd end up with:
			// argv[1] = /command:commit
			// argv[2] = /expaths:D:" D:\Utils
			// See here for more details: http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx
			CString cmdLine = GetCommandLineW();
			cmdLine.Replace(L"\\", L"\\\\");
			int nArgs = 0;
			LPWSTR *szArglist = CommandLineToArgvW(cmdLine, &nArgs);
			if (szArglist)
			{
				// argument 0 is the process path, so start with 1
				for (int i = 1; i < nArgs; ++i)
				{
					if (szArglist[i][0] != '/')
					{
						if (!sPathArgument.IsEmpty())
							sPathArgument += '*';
						sPathArgument += szArglist[i];
					}
				}
				sPathArgument.Replace(L"\\\\", L"\\");
			}
			LocalFree(szArglist);
		}
		if (sPathArgument.IsEmpty() && parser.HasKey(L"path"))
		{
			CMessageBox::Show(hWndExplorer, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
			return FALSE;
		}
		int asterisk = sPathArgument.Find('*');
		cmdLinePath.SetFromUnknown(asterisk >= 0 ? sPathArgument.Left(asterisk) : sPathArgument);
		pathList.LoadFromAsteriskSeparatedString(sPathArgument);
	}

	if (pathList.IsEmpty()) {
		pathList.AddPath(CTGitPath::CTGitPath(g_Git.m_CurrentDir));
	}

	// Set CWD to temporary dir, and restore it later
	{
		DWORD len = GetCurrentDirectory(0, NULL);
		if (len)
		{
			std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]);
			if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
			{
				sOrigCWD = originalCurrentDirectory.get();
				sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
			}
		}
		TCHAR pathbuf[MAX_PATH] = {0};
		GetTortoiseGitTempPath(MAX_PATH, pathbuf);
		SetCurrentDirectory(pathbuf);
	}

	CheckForNewerVersion();

	CAutoGeneralHandle TGitMutex = ::CreateMutex(NULL, FALSE, _T("TortoiseGitProc.exe"));
	if (!g_Git.SetCurrentDir(cmdLinePath.GetWinPathString(), parser.HasKey(_T("submodule")) == TRUE))
	{
		for (int i = 0; i < pathList.GetCount(); ++i)
			if(g_Git.SetCurrentDir(pathList[i].GetWinPath()))
				break;
	}

	if(!g_Git.m_CurrentDir.IsEmpty())
	{
		sOrigCWD = g_Git.m_CurrentDir;
		SetCurrentDirectory(g_Git.m_CurrentDir);
	}

	if (g_sGroupingUUID.IsEmpty())
	{
		CRegStdDWORD groupSetting = CRegStdDWORD(_T("Software\\TortoiseGit\\GroupTaskbarIconsPerRepo"), 3);
		switch (DWORD(groupSetting))
		{
		case 1:
		case 2:
			// implemented differently to TortoiseSVN atm
			break;
		case 3:
		case 4:
			{
				CString wcroot;
				if (g_GitAdminDir.HasAdminDir(g_Git.m_CurrentDir, true, &wcroot))
				{
					git_oid oid;
					CStringA wcRootA(wcroot + CPathUtils::GetAppDirectory());
					if (!git_odb_hash(&oid, wcRootA, wcRootA.GetLength(), GIT_OBJ_BLOB))
					{
						CStringA hash;
						git_oid_tostr(hash.GetBufferSetLength(GIT_OID_HEXSZ + 1), GIT_OID_HEXSZ + 1, &oid);
						hash.ReleaseBuffer();
						g_sGroupingUUID = hash;
					}
					ProjectProperties pp;
					pp.ReadProps();
					CString icon = pp.sIcon;
					icon.Replace('/', '\\');
					if (icon.IsEmpty())
						g_bGroupingRemoveIcon = true;
					g_sGroupingIcon = icon;
				}
			}
		}
	}

	CString sAppID = GetTaskIDPerUUID(g_sGroupingUUID).c_str();
	InitializeJumpList(sAppID);
	EnsureGitLibrary(false);

	{
		CString err;
		try
		{
			// requires CWD to be set
			CGit::m_LogEncode = CAppUtils::GetLogOutputEncode();

			// make sure all config files are read in order to check that none contains an error
			g_Git.GetConfigValue(_T("doesnot.exist"));
		}
		catch (char* msg)
		{
			err = CString(msg);
		}

		if (!err.IsEmpty())
		{
			UINT choice = CMessageBox::Show(hWndExplorer, err, _T("TortoiseGit"), 1, IDI_ERROR, CString(MAKEINTRESOURCE(IDS_PROC_EDITLOCALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_PROC_EDITGLOBALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON)));
			if (choice == 1)
			{
				// open the config file with alternative editor
				CAppUtils::LaunchAlternativeEditor(g_Git.GetGitLocalConfig());
			}
			else if (choice == 2)
			{
				// open the global config file with alternative editor
				CAppUtils::LaunchAlternativeEditor(g_Git.GetGitGlobalConfig());
			}
			return FALSE;
		}
	}

	// execute the requested command
	CommandServer server;
	Command * cmd = server.GetCommand(parser.GetVal(_T("command")));
	if (cmd)
	{
		cmd->SetExplorerHwnd(hWndExplorer);

		cmd->SetParser(parser);
		cmd->SetPaths(pathList, cmdLinePath);

		retSuccess = cmd->Execute();
		delete cmd;
	}

	// Look for temporary files left around by TortoiseSVN and
	// remove them. But only delete 'old' files because some
	// apps might still be needing the recent ones.
	{
		DWORD len = GetTortoiseGitTempPath(0, NULL);
		std::unique_ptr<TCHAR[]> path(new TCHAR[len + 100]);
		len = GetTortoiseGitTempPath (len + 100, path.get());
		if (len != 0)
		{
			CDirFileEnum finder(path.get());
			FILETIME systime_;
			::GetSystemTimeAsFileTime(&systime_);
			__int64 systime = (((_int64)systime_.dwHighDateTime)<<32) | ((__int64)systime_.dwLowDateTime);
			bool isDir;
			CString filepath;
			while (finder.NextFile(filepath, &isDir))
			{
				HANDLE hFile = ::CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, isDir ? FILE_FLAG_BACKUP_SEMANTICS : NULL, NULL);
				if (hFile != INVALID_HANDLE_VALUE)
				{
					FILETIME createtime_;
					if (::GetFileTime(hFile, &createtime_, NULL, NULL))
					{
						::CloseHandle(hFile);
						__int64 createtime = (((_int64)createtime_.dwHighDateTime)<<32) | ((__int64)createtime_.dwLowDateTime);
						if ((createtime + 864000000000) < systime)		//only delete files older than a day
						{
							::SetFileAttributes(filepath, FILE_ATTRIBUTE_NORMAL);
							if (isDir)
								::RemoveDirectory(filepath);
							else
								::DeleteFile(filepath);
						}
					}
					else
						::CloseHandle(hFile);
				}
			}
		}
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	// application, rather than start the application's message pump.
	return FALSE;
}
Exemplo n.º 19
0
/****
 * DumpEventInfo
 *
 * DESC:
 *     This function has two purposes depending on the mode. It will
 *     either (1) Print the contents of an event (if normal mode) or
 *     (2) return the latest record ID (if "last record" mode)
 *
 * ARGS:
 *     hRemote - Remote session context
 *     hResults - An open set of results
 *     outputFormat - 0 for JSON, otherwise XML
 *     mode - last record vs print results
 *     debug - set to 0 (none) 1 (basic) or 2 (verbose)
 *
 * REMARKS:
 */
DWORD64 DumpEventInfo(EVT_HANDLE hRemote, EVT_HANDLE hEvent, INT outputFormat, INT mode, INT debug)
{
    DWORD64 dwError = ERROR_SUCCESS;
    DWORD dwBufferSize = 0;
    DWORD dwBufferUsed = 0;
    DWORD dwPropertyCount = 0;
    LPWSTR pwsBuffer = NULL;
	rapidxml::xml_document<WCHAR> doc;

	if( debug >= DEBUG_L2 ) {
		wprintf(L"[DumpEventInfo]: Attempting to read event XML with no buffer\n" );
	}

    // Attempt to read the event as an XML string
	//
	// Note: We are expecting this call to fail, as we have NOT provided a buffer. Therefore
	// the purpose of this call is to fail, and have dwBufferUsed updated with required space	
    if (!EvtRender(NULL, hEvent, EvtRenderEventXml, dwBufferSize, pwsBuffer, &dwBufferUsed, &dwPropertyCount)) 
	{
		// Reading was NOT successful, as expected
		if( debug >= DEBUG_L2 ) {
			wprintf(L"[DumpEventInfo]: Required buffer space: %lu\n", dwBufferUsed );
		}

		// Get the error code
		dwError = GetLastError();

		if( debug >= DEBUG_L2 ) {
			wprintf(L"[DumpEventInfo]: Raw error code is: %lu\n", dwError );
		}

		// If call failed due to insufficient buffer (as we should expect)
        if (dwError == ERROR_INSUFFICIENT_BUFFER)
        {
			if( debug >= DEBUG_L2 ) {
				wprintf(L"[DumpEventInfo]: Last error code is insufficient buffer (as expecteted)\n" );
			}

			// Adjust the buffer size to the required amount as indicated by dwBufferUsed		
            dwBufferSize = dwBufferUsed;

			if( debug >= DEBUG_L2 ) {
				wprintf(L"[DumpEventInfo]: Attempting to reallocate buffer size: %lu\n", dwBufferSize );
			}

			// Re-allocate our buffer with the required size
            pwsBuffer = (LPWSTR)malloc(dwBufferSize);

			// If allocaton was successful
            if (pwsBuffer)
            {
				if( debug >= DEBUG_L2 ) {
					wprintf(L"[DumpEventInfo]: Allocation successful. Re-attempting to read event data\n" );
				}

				// Re-attempt to read event (as XML) now that we have appropriate buffer size
                if( EvtRender(NULL, hEvent, EvtRenderEventXml, dwBufferSize, pwsBuffer, &dwBufferUsed, &dwPropertyCount) ) 
				{
					if( debug >= DEBUG_L2 ) {
						wprintf(L"[DumpEventInfo]: Read successful. Last error code is: %lu\n", dwError );
					}

					// Reading was successful
					dwError = GetLastError();

					if( debug >= DEBUG_L2 ) {
						wprintf( L"[DumpEventInfo]: Raw XML: %s\n", pwsBuffer );
					}

					// Parse the XML string into our XML reader
					doc.parse<0>( pwsBuffer );

					if( debug >= DEBUG_L2 ) {
						wprintf( L"[DumpEventInfo]: XML parsing successful\n" );
					}

					// Retrieve the <Event> node
					rapidxml::xml_node<WCHAR> *nodeEvent = doc.first_node(L"Event");

					// Retrieve the <System> node
					rapidxml::xml_node<WCHAR> *nodeSystem = nodeEvent->first_node(L"System");
					// Children of the <System> node
					// You will recongize these as elements when viewing the event log in your viewer
					rapidxml::xml_node<WCHAR> *nodeEventID = nodeSystem->first_node(L"EventID");
					rapidxml::xml_node<WCHAR> *nodeChannel = nodeSystem->first_node(L"Channel");
					rapidxml::xml_node<WCHAR> *nodeEventRecordID = nodeSystem->first_node(L"EventRecordID");
					rapidxml::xml_node<WCHAR> *nodeProvider = nodeSystem->first_node(L"Provider");
					rapidxml::xml_node<WCHAR> *nodeComputer = nodeSystem->first_node(L"Computer");
					rapidxml::xml_node<WCHAR> *nodeTimeCreated = nodeSystem->first_node(L"TimeCreated");
					rapidxml::xml_node<WCHAR> *nodeTask = nodeSystem->first_node(L"Task");
					rapidxml::xml_node<WCHAR> *nodeLevel = nodeSystem->first_node(L"Level");

					if( debug >= DEBUG_L2 ) {
						wprintf( L"[DumpEventInfo]: Extracting XML elements successful\n" );
					}

					// Recall there are two modes. The default mode will parse the event log XML, and the "last record" mode
					// (called MODE_FETCH_LAST_RECORD) will fetch only the last record and exit afterwards. 
					if( mode == MODE_FETCH_LAST_RECORD ) {
						if( debug >= DEBUG_L2 ) {
							wprintf( L"[DumpEventInfo]: Record ID is '%s'\n", nodeEventRecordID->value() );
						}

						DWORD64 lastRecord = _wcstoui64( nodeEventRecordID->value(), NULL, 10 );

						if( debug >= DEBUG_L2 ) {
							wprintf( L"[DumpEventInfo]: Record ID converted to 64-bit number: %I64d\n", lastRecord );
						}

						return lastRecord;
					}

					// Extract the publisher name from the <Provider> node
					// We will need this to lookup the message string for this publisher
					LPWSTR pwszPublisherName = nodeProvider->first_attribute(L"Name")->value();

					if( debug >= DEBUG_L2 ) {
						wprintf( L"[DumpEventInfo] Publisher is: %s\n", pwszPublisherName );
					}

					// Setup an empty string to read the message string
					LPWSTR pwsMessage = NULL;

					// Get the handle to the provider's metadata that contains the message strings.
					EVT_HANDLE hProviderMetadata = EvtOpenPublisherMetadata(hRemote, pwszPublisherName, NULL, 0, 0);

					// If a provider handle was found
					if( hProviderMetadata != NULL ) 
					{
						if( debug >= DEBUG_L2 ) {
							wprintf( L"[DumpEventInfo] Publisher metadata found. Attempting to get message string\n");
						}

						// Get the message string associated with this event type
						pwsMessage = GetEventMessageDescription(hProviderMetadata, hEvent);

						// If a message was not found, default to an empty string
						if( pwsMessage == NULL ) {
							// Why are we setting to empty string?
							//pwsMessage = L"";

							if( debug >= DEBUG_L2 ) {
								wprintf( L"[DumpEventInfo] Message string not found. Assume empty\n");
							}
						}
					}
					else 
					{
						// Publisher/provider cannot be found. Do not display an error message. It occurs all too often when a 
						// publisher is not found, and skews the JSON results. when it prints itself to the main screen
						// printf("Error: EvtOpenPublisherMetadata for %s failed with %d\n", pwszPublisherName, GetLastError());						

						// Default the publisher to an empty string so we can continue
						pwszPublisherName = L"";

						if( debug >= DEBUG_L2 ) {
							wprintf( L"[DumpEventInfo] Publisher metadata not found. Assume empty\n");
						}
					}

					// We have all the results; print them to the screen
					if( outputFormat == OUTPUT_FORMAT_JSON ) 
					{
						wprintf(L"{\"record_id\":\"%s\",\"event_id\":\"%s\",\"logname\":\"%s\",\"source\":\"%s\",\"computer\":\"%s\",\"time_created\":\"%s\",\"task\":\"%s\",\"level\":\"%s\"", 
							nodeEventRecordID->value(), 
							nodeEventID->value(), 
							nodeChannel->value(), 
							nodeProvider->first_attribute(L"Name")->value(), 
							nodeComputer->value(), 
							nodeTimeCreated->first_attribute(L"SystemTime")->value(),
							nodeTask->value(),
							nodeLevel->value());
						
						// If a message string was found
						if( pwsMessage != NULL ) 
						{
							wprintf(L",\"message\":\"%s\"}", pwsMessage);

							if( debug >= DEBUG_L2 ) {
								wprintf( L"[DumpEventInfo] Attempting to free pwsMessage\n");
							}

							free(pwsMessage);

							if( debug >= DEBUG_L2 ) {
								wprintf( L"[DumpEventInfo] pwsMessage successfully freed\n");
							}
						} 
						else 
						{
							wprintf(L",\"message\":\"\"}");

							if( debug >= DEBUG_L2 ) {
								wprintf( L"[DumpEventInfo] No pwsMessage found to free\n");
							}
						}
					} 
					else 
					{
						// Note: A new line is not printed yet (see next steps)
						wprintf(L"%s||%s||%s||%s||%s||%s||%s||%s||", 
							nodeEventRecordID->value(), 
							nodeEventID->value(), 
							nodeChannel->value(), 
							nodeProvider->first_attribute(L"Name")->value(), 
							nodeComputer->value(), 
							nodeTimeCreated->first_attribute(L"SystemTime")->value(),
							nodeTask->value(),
							nodeLevel->value());

						// If a message string was found
						if( pwsMessage != NULL ) 
						{
							wprintf(L"%s\n", pwsMessage);
							free(pwsMessage);
						} 
						else 
						{
							wprintf(L"(no message provided)\n");
						}
					}
				} 
				else
				{
					// Reading was NOT successful

					// This time we were not expecting it to fail. Get the error code
					dwError = GetLastError();

					// Print error results to the screen
					fwprintf(stderr, L"[DumpEventInfo] Failed to render results with: %d\n", GetLastError());

					// Free up our allocation
					free(pwsBuffer);
				}				
            }
            else
            {
				// Allocation was unsuccessful
                fwprintf(stderr, L"[DumpEventInfo] malloc failed\n");
                dwError = ERROR_OUTOFMEMORY;
            }
        }
	}

	if( debug >= DEBUG_L2 ) {
		wprintf( L"[DumpEventInfo]: Data dump completed\n" );
	}

    return dwError;
}
Exemplo n.º 20
0
BOOL CTortoiseSIProcApp::ProcessCommandLine()
{
	CCmdLineParser parser(AfxGetApp()->m_lpCmdLine);

	CString sVal = parser.GetVal(_T("hwnd"));

	if (!sVal.IsEmpty()) {
		m_hWndExplorer = (HWND)_wcstoui64(sVal, nullptr, 16);
	}

	while (GetParent(m_hWndExplorer) != NULL) {
		m_hWndExplorer = GetParent(m_hWndExplorer);
	}

	if (!IsWindow(m_hWndExplorer))
	{
		m_hWndExplorer = NULL;
	}

#if _DEBUG
	if (CRegDWORD(_T("Software\\TortoiseSI\\Debug"), FALSE) == TRUE) {
		AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);
	}
#endif

	// The path and pathfile arguments are mutually exclusive
	if (parser.HasKey(_T("path")) && parser.HasKey(_T("pathfile")))
	{
		CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
		return FALSE;
	}

	CTGitPath cmdLinePath;
	CTGitPathList pathList;

	if (parser.HasKey(_T("pathfile")))
	{
		// Process /pathfile argument

		CString sPathFileArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("pathfile")));

		cmdLinePath.SetFromUnknown(sPathFileArgument);

		if (pathList.LoadFromFile(cmdLinePath) == false) {
			// no path specified!
			return FALSE;		
	    }

		if (parser.HasKey(_T("deletepathfile")))
		{
			// We can delete the temporary path file, now that we've loaded it
			::DeleteFile(cmdLinePath.GetWinPath());
		}

		// This was a path to a temporary file - it's got no meaning now, and
		// anybody who uses it again is in for a problem...
		cmdLinePath.Reset();

	} else {

		// Process /path and /expaths argument
		// Build-uo /path value as /path:<value>*<arg1>*<arg2>...
		// Where <arg1>, <arg2> etc are extracted from /expath arguments.
		// Since all arguments are passed in the form of /parameter:<argument>
		// We process only those arguments which are not preceded by a /parameter:
		// This only includes arguments specified following /expaths (See comments below)

		CString sPathArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("path")));

		if (parser.HasKey(_T("expaths")))
		{
			// An /expaths param means we are started via the buttons in our Win7 library
			// and that means the value of /expaths is the current directory and
			// the selected paths are then added as additional parameters but without a key, only a value
			//
			//     e.g. /expaths:"D:\" "D:\Utils"
			//
			// Because of the "strange treatment of quotation marks and backslashes by CommandLineToArgvW",
			// we have to escape the backslashes first.  Since we're only dealing with paths here, that's
			// a safe bet.  Without this, a command line like:
			//
			//     /command:commit /expaths:"D:\" "D:\Utils"
			// 
			// would fail because the "D:\" is treated as the backslash being the escape char for the quotation
			// mark and we'd end up with:
			//
			//     argv[1] = /command:commit
			//     argv[2] = /expaths:D:" D:\Utils
			//
			// See here for more details: http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx

			CString cmdLine = GetCommandLineW();

			// Escape backslashes
			cmdLine.Replace(L"\\", L"\\\\");

			int nArgs = 0;
			LPWSTR *szArgList = CommandLineToArgvW(cmdLine, &nArgs);

			if (szArgList)
			{
				// Argument 0 is the process path, so start with 1
				for (int i = 1; i < nArgs; i++)
				{
					if (szArgList[i][0] != '/')
					{
						if (!sPathArgument.IsEmpty()) {
							sPathArgument += '*';
						}
						sPathArgument += szArgList[i];
					}
				}

				sPathArgument.Replace(L"\\\\", L"\\");
			}

			LocalFree(szArgList);
		}

		if (sPathArgument.IsEmpty() && parser.HasKey(L"path"))
		{
			CMessageBox::Show(m_hWndExplorer, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
			return FALSE;
		}

		int asterisk = sPathArgument.Find('*');
		cmdLinePath.SetFromUnknown(asterisk >= 0 ? sPathArgument.Left(asterisk) : sPathArgument);
		pathList.LoadFromAsteriskSeparatedString(sPathArgument);
	}

	if (pathList.IsEmpty()) {
		pathList.AddPath(CTGitPath::CTGitPath(g_Git.m_CurrentDir));
	}

	// Set CWD to temporary dir, and restore it later
	{
		DWORD len = GetCurrentDirectory(0, NULL);

		if (len)
		{
			std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]);

			if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
			{
				m_sOrigCWD = originalCurrentDirectory.get();
				m_sOrigCWD = CPathUtils::GetLongPathname(m_sOrigCWD);
			}
		}

		TCHAR pathbuf[MAX_PATH] = { 0 };
		GetTortoiseGitTempPath(MAX_PATH, pathbuf);
		SetCurrentDirectory(pathbuf);
	}

	if (!g_Git.m_CurrentDir.IsEmpty())
	{
		m_sOrigCWD = g_Git.m_CurrentDir;
		SetCurrentDirectory(m_sOrigCWD);
	}

	// Execute the requested command
	CommandServer server;

	Command *cmd = server.GetCommand(parser.GetVal(_T("command")));

	if (cmd)
	{
		cmd->SetExplorerHwnd(m_hWndExplorer);
		cmd->SetParser(parser);
		cmd->SetPaths(pathList, cmdLinePath);
		m_bRetSuccess = cmd->Execute();
		delete cmd;
	}

	return TRUE;
}