コード例 #1
0
ファイル: unicode.c プロジェクト: JunaidLoonat/FreeRDP
void ByteSwapUnicode(WCHAR* wstr, int length)
{
	WCHAR* end = &wstr[length];

	while (wstr < end)
	{
		*wstr = _byteswap_ushort(*wstr);
		wstr++;
	}
}
コード例 #2
0
ファイル: LzopStreamReader.cpp プロジェクト: zukisoft/vm
static intptr_t ReadBE16(intptr_t base, size_t* length, uint16_t* value)
{
	if((!length) | (!value)) throw Exception(E_POINTER);
	if(*length < sizeof(uint16_t)) throw Exception(E_DECOMPRESS_TRUNCATED, COMPRESSION_METHOD);

	*value = _byteswap_ushort(*reinterpret_cast<uint16_t*>(base));

	*length -= sizeof(uint16_t);
	return base + sizeof(uint16_t);
}
コード例 #3
0
/// SwapByteOrder_16 - This function returns a byte-swapped representation of
/// the 16-bit argument.
inline uint16_t SwapByteOrder_16(uint16_t value) {
#if defined(_MSC_VER) && !defined(_DEBUG)
    // The DLL version of the runtime lacks these functions (bug!?), but in a
    // release build they're replaced with BSWAP instructions anyway.
    return _byteswap_ushort(value);
#else
    uint16_t Hi = value << 8;
    uint16_t Lo = value >> 8;
    return Hi | Lo;
#endif
}
コード例 #4
0
ファイル: main.cpp プロジェクト: xmoeproject/X-moe
	/**
	 * 名前の取得
	 * @param name 名前文字列(ユニコード)
	 * @len 長さ
	 */
	ttstr layname(psd_layer_record *lay) {
		ttstr ret;
		if (lay->unicode_name_length > 0) {
			psd_ushort *name = lay->unicode_name;
			for (int i=0;i<lay->unicode_name_length;i++) {
				ret += (tjs_char)_byteswap_ushort(*name++);
			}
		} else {
			ret = ttstr((char*)lay->layer_name);
		}
		return ret;
	}
コード例 #5
0
ファイル: main.cpp プロジェクト: xmoeproject/X-moe
	/**
	 * 文字リソースの取得
	 * @param id 文字列ID
	 * @return 文字列リソース
	 */
	ttstr getStringResource(int id) {
		ttstr ret;
		if (!context) TVPThrowExceptionMessage(L"no data");
		if (id < 0 || id >= context->number_of_unicode_strings)
			TVPThrowExceptionMessage(L"no such string resouce");

		psd_unicode_strings * str = context->unicode_strings + id;
		psd_ushort *name = str->name;
		if (str->name_length > 0) {
			for (int i = 0; i < str->name_length; i++) {
				ret += (tjs_char)_byteswap_ushort(*name++);
			}
		}
		return ret;
	}
コード例 #6
0
void retFromKadmin(_octet1 * data)
{
	WORD code;
	if(data->length >= 2)
	{
		if(code = _byteswap_ushort(*(PWORD) data->value))
			kprintf("%s (%u)", kull_m_kadmin_passwd_err_to_string(code), code);
		else kprintf("OK");
		if(data->length > 2)
		{
			kprintf(" - {");
			kull_m_string_printf_hex(data->value + 2, data->length - 2, 0);
			kprintf("}");
		}
		printf("\n");
	}
	else PRINT_ERROR("Size\n");
}
コード例 #7
0
ファイル: BufferUtils.cpp プロジェクト: Wimmie/rpcs3
void uploadVertexData(const VertexBufferFormat &vbf, const RSXVertexData *vertexData, size_t baseOffset, void* bufferMap)
{
	for (int vertex = 0; vertex < vbf.elementCount; vertex++)
	{
		for (size_t attributeId : vbf.attributeId)
		{
			if (!vertexData[attributeId].addr)
			{
				memcpy(bufferMap, vertexData[attributeId].data.data(), vertexData[attributeId].data.size());
				continue;
			}
			size_t offset = (size_t)vertexData[attributeId].addr + baseOffset - vbf.range.first;
			size_t tsize = vertexData[attributeId].GetTypeSize();
			size_t size = vertexData[attributeId].size;
			auto src = vm::get_ptr<const u8>(vertexData[attributeId].addr + (u32)baseOffset + (u32)vbf.stride * vertex);
			char* dst = (char*)bufferMap + offset + vbf.stride * vertex;

			switch (tsize)
			{
			case 1:
			{
				memcpy(dst, src, size);
				break;
			}

			case 2:
			{
				const u16* c_src = (const u16*)src;
				u16* c_dst = (u16*)dst;
				for (u32 j = 0; j < size; ++j) *c_dst++ = _byteswap_ushort(*c_src++);
				break;
			}

			case 4:
			{
				const u32* c_src = (const u32*)src;
				u32* c_dst = (u32*)dst;
				for (u32 j = 0; j < size; ++j) *c_dst++ = _byteswap_ulong(*c_src++);
				break;
			}
			}
		}
	}
}
コード例 #8
0
ファイル: MidiParser.cpp プロジェクト: CalculatorSP/xbot2014
uint32_t MidiParser::_parseHeader(FILE* fp)
{
    // Get ticksPerQuarterNote from Midi Header
    uint16_t ticksPerQuarterNote;
    fseek(fp, 12, SEEK_CUR);
    fread_s(&ticksPerQuarterNote, 2, 2, 1, fp);
    ticksPerQuarterNote = _byteswap_ushort(ticksPerQuarterNote);

    // Get length of header track
    uint32_t trackLen;
    fseek(fp, 4, SEEK_CUR);
    fread_s(&trackLen, 4, 4, 1, fp);
    trackLen = _byteswap_ulong(trackLen);

    // Parse header track to get tempo
    uint32_t microsPerQuarterNote;
    long endPos = ftell(fp) + trackLen;
    while (ftell(fp) < endPos)
    {
        // Skip "00 FF"
        fseek(fp, 2, SEEK_CUR);

        // Get header command byte
        uint8_t cmd;
        fread_s(&cmd, 1, 1, 1, fp);
        uint32_t len = _readVariableLen(fp);

        if (cmd == 0x51)
        {
            // Tempo
            uint8_t tmp[4] = { 0, 0, 0, 0 };
            fread_s(&tmp[1], 3, 3, 1, fp);
            microsPerQuarterNote = _byteswap_ulong(*(uint32_t *)tmp);
        }
        else // Skip any other commands
            fseek(fp, len, SEEK_CUR);
    }

    return microsPerQuarterNote / ticksPerQuarterNote;
}
コード例 #9
0
ファイル: PGSSub.cpp プロジェクト: Grimace1975/mpc-hc
bool CPGSSubFile::Open(CString fn, CString name /*= _T("")*/, CString videoName /*= _T("")*/)
{
    bool bOpened = false;

    if (name.IsEmpty()) {
        m_name = Subtitle::GuessSubtitleName(fn, videoName);
    } else {
        m_name = name;
    }

    CFile f;
    if (f.Open(fn, CFile::modeRead | CFile::shareDenyWrite)) {
        WORD wSyncCode = 0;
        f.Read(&wSyncCode, sizeof(wSyncCode));
        wSyncCode = _byteswap_ushort(wSyncCode);
        if (wSyncCode == PGS_SYNC_CODE) {
            m_parsingThread = std::thread([this, fn] { ParseFile(fn); });
            bOpened = true;
        }
    }

    return bOpened;
}
コード例 #10
0
PDIRTY_ASN1_SEQUENCE_EASY kuhl_m_kerberos_ticket_createAppEncTicketPart(PKIWI_KERBEROS_TICKET ticket, LPCVOID PacAuthData, DWORD PacAuthDataSize)
{
	PDIRTY_ASN1_SEQUENCE_EASY App_EncTicketPart, Seq_EncTicketPart, Ctx_EncTicketPart, Ctx_Root, Seq_1, Seq_2, Seq_3, Seq_4, OctetString;
	UCHAR integer1;	USHORT integer2;

	if(App_EncTicketPart = KULL_M_ASN1_CREATE_APP(ID_APP_ENCTICKETPART))
	{
		if(Seq_EncTicketPart = KULL_M_ASN1_CREATE_SEQ())
		{
			kull_m_asn1_append_ctx_and_data_to_seq(&Seq_EncTicketPart, ID_CTX_ENCTICKETPART_FLAGS, kull_m_asn1_BitStringFromULONG(ticket->TicketFlags));
			kull_m_asn1_append_ctx_and_data_to_seq(&Seq_EncTicketPart, ID_CTX_ENCTICKETPART_KEY, kuhl_m_kerberos_ticket_createSequenceEncryptionKey((UCHAR) ticket->KeyType, ticket->Key.Value, ticket->Key.Length));
			kull_m_asn1_append_ctx_and_data_to_seq(&Seq_EncTicketPart, ID_CTX_ENCTICKETPART_CREALM, kull_m_asn1_GenString(&ticket->AltTargetDomainName));
			kull_m_asn1_append_ctx_and_data_to_seq(&Seq_EncTicketPart, ID_CTX_ENCTICKETPART_CNAME, kuhl_m_kerberos_ticket_createSequencePrimaryName(ticket->ClientName));
			if(Ctx_EncTicketPart = KULL_M_ASN1_CREATE_CTX(ID_CTX_ENCTICKETPART_TRANSITED))
			{
				if(Seq_1 = KULL_M_ASN1_CREATE_SEQ())
				{
					integer1 = 0;
					kull_m_asn1_append_ctx_and_data_to_seq(&Seq_1, ID_CTX_TRANSITEDENCODING_TR_TYPE, kull_m_asn1_create(DIRTY_ASN1_ID_INTEGER, &integer1, sizeof(UCHAR), NULL));
					kull_m_asn1_append_ctx_and_data_to_seq(&Seq_1, ID_CTX_TRANSITEDENCODING_CONTENTS, kull_m_asn1_create(DIRTY_ASN1_ID_OCTET_STRING, NULL, 0, NULL));
					kull_m_asn1_append(&Ctx_EncTicketPart, Seq_1);
				}
				kull_m_asn1_append(&Seq_EncTicketPart, Ctx_EncTicketPart);
			}
			kull_m_asn1_append_ctx_and_data_to_seq(&Seq_EncTicketPart, ID_CTX_ENCTICKETPART_AUTHTIME, kull_m_asn1_GenTime(&ticket->StartTime));
			kull_m_asn1_append_ctx_and_data_to_seq(&Seq_EncTicketPart, ID_CTX_ENCTICKETPART_STARTTIME, kull_m_asn1_GenTime(&ticket->StartTime));
			kull_m_asn1_append_ctx_and_data_to_seq(&Seq_EncTicketPart, ID_CTX_ENCTICKETPART_ENDTIME, kull_m_asn1_GenTime(&ticket->EndTime));
			kull_m_asn1_append_ctx_and_data_to_seq(&Seq_EncTicketPart, ID_CTX_ENCTICKETPART_RENEW_TILL, kull_m_asn1_GenTime(&ticket->RenewUntil));
			/* ID_CTX_ENCTICKETPART_CADDR not present */
			if(Ctx_EncTicketPart = KULL_M_ASN1_CREATE_CTX(ID_CTX_ENCTICKETPART_AUTHORIZATION_DATA))
			{
				if(Seq_1 = KULL_M_ASN1_CREATE_SEQ())
				{
					if(Seq_2 = KULL_M_ASN1_CREATE_SEQ())
					{
						integer1 = ID_AUTHDATA_AD_IF_RELEVANT;
						kull_m_asn1_append_ctx_and_data_to_seq(&Seq_2, ID_CTX_AUTHORIZATIONDATA_AD_TYPE, kull_m_asn1_create(DIRTY_ASN1_ID_INTEGER, &integer1, sizeof(UCHAR), NULL));
						if(Ctx_Root = KULL_M_ASN1_CREATE_CTX(ID_CTX_AUTHORIZATIONDATA_AD_DATA))
						{
							if(OctetString = kull_m_asn1_create(DIRTY_ASN1_ID_OCTET_STRING, NULL, 0, NULL))
							{
								if(Seq_3 = KULL_M_ASN1_CREATE_SEQ())
								{
									if(Seq_4 = KULL_M_ASN1_CREATE_SEQ())
									{
										integer2 = _byteswap_ushort(ID_AUTHDATA_AD_WIN2K_PAC);
										kull_m_asn1_append_ctx_and_data_to_seq(&Seq_4, ID_AUTHDATA_AD_WIN2K_PAC, kull_m_asn1_create(DIRTY_ASN1_ID_INTEGER, &integer2, sizeof(USHORT), NULL));
										kull_m_asn1_append_ctx_and_data_to_seq(&Seq_4, ID_CTX_AUTHORIZATIONDATA_AD_DATA, kull_m_asn1_create(DIRTY_ASN1_ID_OCTET_STRING, PacAuthData, PacAuthDataSize, NULL));
										kull_m_asn1_append(&Seq_3, Seq_4);
									}
									kull_m_asn1_append(&OctetString, Seq_3);
								}
								kull_m_asn1_append(&Ctx_Root, OctetString);
							}
							kull_m_asn1_append(&Seq_2, Ctx_Root);
						}
						kull_m_asn1_append(&Seq_1, Seq_2);
					}
					kull_m_asn1_append(&Ctx_EncTicketPart, Seq_1);
				}
				kull_m_asn1_append(&Seq_EncTicketPart, Ctx_EncTicketPart);
			}
			kull_m_asn1_append(&App_EncTicketPart, Seq_EncTicketPart);
		}
	}
	return App_EncTicketPart;
}
コード例 #11
0
ファイル: ping.c プロジェクト: glenrgordon/processhacker2
NTSTATUS NetworkPingThreadStart(
    _In_ PVOID Parameter
    )
{
    HANDLE icmpHandle = INVALID_HANDLE_VALUE;
    ULONG icmpCurrentPingMs = 0;
    ULONG icmpReplyCount = 0;
    ULONG icmpReplyLength = 0;
    PVOID icmpReplyBuffer = NULL;
    PPH_BYTES icmpEchoBuffer = NULL;
    IP_OPTION_INFORMATION pingOptions =
    {
        255,         // Time To Live
        0,           // Type Of Service
        IP_FLAG_DF,  // IP header flags
        0            // Size of options data
    };

    PNETWORK_OUTPUT_CONTEXT context = (PNETWORK_OUTPUT_CONTEXT)Parameter;

    __try
    {
        // Create ICMP echo buffer.
        if (context->PingSize > 0 && context->PingSize != 32)
        {
            PPH_STRING randString;

            randString = PhCreateStringEx(NULL, context->PingSize * 2 + 2);

            // Create a random string to fill the buffer.
            PhGenerateRandomAlphaString(randString->Buffer, (ULONG)randString->Length / sizeof(WCHAR));

            icmpEchoBuffer = PhConvertUtf16ToMultiByte(randString->Buffer);
            PhDereferenceObject(randString);
        }
        else
        {
            PPH_STRING version;

            // We're using a default length, query the PH version and use the previous buffer format.
            version = PhGetPhVersion();

            if (version)
            {
                icmpEchoBuffer = FormatAnsiString("processhacker_%S_0x0D06F00D_x1", version->Buffer);
                PhDereferenceObject(version);
            }
        }

        if (context->IpAddress.Type == PH_IPV6_NETWORK_TYPE)
        {
            SOCKADDR_IN6 icmp6LocalAddr = { 0 };
            SOCKADDR_IN6 icmp6RemoteAddr = { 0 };
            PICMPV6_ECHO_REPLY2 icmp6ReplyStruct = NULL;

            // Create ICMPv6 handle.
            if ((icmpHandle = Icmp6CreateFile()) == INVALID_HANDLE_VALUE)
                __leave;

            // Set Local IPv6-ANY address.
            icmp6LocalAddr.sin6_addr = in6addr_any;
            icmp6LocalAddr.sin6_family = AF_INET6;

            // Set Remote IPv6 address.
            icmp6RemoteAddr.sin6_addr = context->IpAddress.In6Addr;
            icmp6RemoteAddr.sin6_port = _byteswap_ushort((USHORT)context->NetworkItem->RemoteEndpoint.Port);

            // Allocate ICMPv6 message.
            icmpReplyLength = ICMP_BUFFER_SIZE(sizeof(ICMPV6_ECHO_REPLY), icmpEchoBuffer);
            icmpReplyBuffer = PhAllocate(icmpReplyLength);
            memset(icmpReplyBuffer, 0, icmpReplyLength);

            InterlockedIncrement(&context->PingSentCount);

            // Send ICMPv6 ping...
            icmpReplyCount = Icmp6SendEcho2(
                icmpHandle,
                NULL,
                NULL,
                NULL,
                &icmp6LocalAddr,
                &icmp6RemoteAddr,
                icmpEchoBuffer->Buffer,
                (USHORT)icmpEchoBuffer->Length,
                &pingOptions,
                icmpReplyBuffer,
                icmpReplyLength,
                context->MaxPingTimeout
                );

            icmp6ReplyStruct = (PICMPV6_ECHO_REPLY2)icmpReplyBuffer;
            if (icmpReplyCount > 0 && icmp6ReplyStruct)
            {
                BOOLEAN icmpPacketSignature = FALSE;

                if (icmp6ReplyStruct->Status != IP_SUCCESS)
                {
                    InterlockedIncrement(&context->PingLossCount);
                }

                if (_memicmp(
                    icmp6ReplyStruct->Address.sin6_addr,
                    context->IpAddress.In6Addr.u.Word,
                    sizeof(icmp6ReplyStruct->Address.sin6_addr)
                    ) != 0)
                {
                    InterlockedIncrement(&context->UnknownAddrCount);
                }

                icmpPacketSignature = _memicmp(
                    icmpEchoBuffer->Buffer,
                    icmp6ReplyStruct->Data,
                    icmpEchoBuffer->Length
                    ) == 0;

                if (!icmpPacketSignature)
                {
                    InterlockedIncrement(&context->HashFailCount);
                }

                icmpCurrentPingMs = icmp6ReplyStruct->RoundTripTime;
            }
            else
            {
                InterlockedIncrement(&context->PingLossCount);
            }
        }
        else
        {
            IPAddr icmpLocalAddr = 0;
            IPAddr icmpRemoteAddr = 0;
            PICMP_ECHO_REPLY icmpReplyStruct = NULL;

            // Create ICMPv4 handle.
            if ((icmpHandle = IcmpCreateFile()) == INVALID_HANDLE_VALUE)
                __leave;

            // Set Local IPv4-ANY address.
            icmpLocalAddr = in4addr_any.s_addr;

            // Set Remote IPv4 address.
            icmpRemoteAddr = context->IpAddress.InAddr.s_addr;

            // Allocate ICMPv4 message.
            icmpReplyLength = ICMP_BUFFER_SIZE(sizeof(ICMP_ECHO_REPLY), icmpEchoBuffer);
            icmpReplyBuffer = PhAllocate(icmpReplyLength);
            memset(icmpReplyBuffer, 0, icmpReplyLength);

            InterlockedIncrement(&context->PingSentCount);

            // Send ICMPv4 ping...
            icmpReplyCount = IcmpSendEcho2Ex(
                icmpHandle,
                NULL,
                NULL,
                NULL,
                icmpLocalAddr,
                icmpRemoteAddr,
                icmpEchoBuffer->Buffer,
                (USHORT)icmpEchoBuffer->Length,
                &pingOptions,
                icmpReplyBuffer,
                icmpReplyLength,
                context->MaxPingTimeout
                );

            icmpReplyStruct = (PICMP_ECHO_REPLY)icmpReplyBuffer;

            if (icmpReplyStruct && icmpReplyCount > 0)
            {
                BOOLEAN icmpPacketSignature = FALSE;

                if (icmpReplyStruct->Status != IP_SUCCESS)
                {
                    InterlockedIncrement(&context->PingLossCount);
                }

                if (icmpReplyStruct->Address != context->IpAddress.InAddr.s_addr)
                {
                    InterlockedIncrement(&context->UnknownAddrCount);
                }

                if (icmpReplyStruct->DataSize == icmpEchoBuffer->Length)
                {
                    icmpPacketSignature = _memicmp(
                        icmpEchoBuffer->Buffer,
                        icmpReplyStruct->Data,
                        icmpReplyStruct->DataSize
                        ) == 0;
                }

                icmpCurrentPingMs = icmpReplyStruct->RoundTripTime;

                if (!icmpPacketSignature)
                {
                    InterlockedIncrement(&context->HashFailCount);
                }
            }
            else
            {
                InterlockedIncrement(&context->PingLossCount);
            }
        }

        InterlockedIncrement(&context->PingRecvCount);

        if (context->PingMinMs == 0 || icmpCurrentPingMs < context->PingMinMs)
            context->PingMinMs = icmpCurrentPingMs;
        if (icmpCurrentPingMs > context->PingMaxMs)
            context->PingMaxMs = icmpCurrentPingMs;

        context->CurrentPingMs = icmpCurrentPingMs;

        PhAddItemCircularBuffer_ULONG(&context->PingHistory, icmpCurrentPingMs);
    }
    __finally
    {
        if (icmpEchoBuffer)
        {
            PhDereferenceObject(icmpEchoBuffer);
        }

        if (icmpHandle != INVALID_HANDLE_VALUE)
        {
            IcmpCloseHandle(icmpHandle);
        }

        if (icmpReplyBuffer)
        {
            PhFree(icmpReplyBuffer);
        }
    }

    PostMessage(context->WindowHandle, WM_PING_UPDATE, 0, 0);

    return STATUS_SUCCESS;
}
コード例 #12
0
ファイル: BinaryReaderBE.cpp プロジェクト: Refection/x360emu
s16 BinaryReaderBE::ReadInt16()
{
	return (s16) _byteswap_ushort((u16) BinaryReader::ReadInt16());
}
コード例 #13
0
ファイル: DualshockPad.cpp プロジェクト: AxioDL/boo
static inline uint16_t bswap16(uint16_t val) { return _byteswap_ushort(val); }
コード例 #14
0
NTSTATUS kuhl_m_kerberos_ccache_enum(int argc, wchar_t * argv[], BOOL isInject, BOOL isSave)
{
	PBYTE file, data;
	DWORD length, i;
	USHORT version;

	PKERB_EXTERNAL_NAME principalName; UNICODE_STRING principalRealm;
	PKIWI_KERBEROS_TICKET ticket;
	PDIRTY_ASN1_SEQUENCE_EASY App_KrbCred;
	DWORD App_KrbCred_Size;
	wchar_t * saveFilename;

	if(argc)
	{
		if(kull_m_file_readData(argv[0], &file, &length))
		{
			data = file;	
			version = _byteswap_ushort(*(PUSHORT) data); data += sizeof(USHORT);
			if(version == 0x0504)
			{
				data += sizeof(USHORT) + _byteswap_ushort(*(PUSHORT) data);
				kuhl_m_kerberos_ccache_externalname(&data, &principalName, &principalRealm);
				if(principalName)
				{
					kuhl_m_kerberos_ticket_displayExternalName(L"\nPrincipal : ", principalName, &principalRealm);
					for(i = 0; data < (file + length); i++)
					{
						kprintf(L"\n\nData %u", i);
						if(ticket = (PKIWI_KERBEROS_TICKET) LocalAlloc(LPTR, sizeof(KIWI_KERBEROS_TICKET)))
						{
							kuhl_m_kerberos_ccache_externalname(&data, &ticket->ClientName, &ticket->AltTargetDomainName);
							kuhl_m_kerberos_ccache_externalname(&data, &ticket->ServiceName, &ticket->DomainName);

							ticket->TargetName = kuhl_m_kerberos_ticket_copyExternalName(ticket->ServiceName);
							kull_m_string_copyUnicodeStringBuffer(&ticket->DomainName, &ticket->TargetDomainName);

							ticket->KeyType = _byteswap_ushort(*(PUSHORT) data); data += sizeof(USHORT);
							ticket->TicketEncType = _byteswap_ushort(*(PUSHORT) data); data += sizeof(USHORT);
							ticket->Key.Length = _byteswap_ushort(*(PUSHORT) data); data += sizeof(USHORT);
							if(ticket->Key.Length)
								if(ticket->Key.Value = (PUCHAR) LocalAlloc(LPTR, ticket->Key.Length))
									RtlCopyMemory(ticket->Key.Value, data, ticket->Key.Length);
							data += ticket->Key.Length + sizeof(DWORD); // authtime;

							kuhl_m_kerberos_ccache_UnixTimeToFileTime(_byteswap_ulong(*(PDWORD) data), &ticket->StartTime); data += sizeof(DWORD); // local ?
							kuhl_m_kerberos_ccache_UnixTimeToFileTime(_byteswap_ulong(*(PDWORD) data), &ticket->EndTime); data += sizeof(DWORD);
							kuhl_m_kerberos_ccache_UnixTimeToFileTime(_byteswap_ulong(*(PDWORD) data), &ticket->RenewUntil); data += sizeof(DWORD) + sizeof(UCHAR); // skey

							ticket->TicketFlags = _byteswap_ulong(*(PDWORD) data); data += sizeof(DWORD);
							kuhl_m_kerberos_ccache_skip_struct_with_buffer(&data); // address
							kuhl_m_kerberos_ccache_skip_struct_with_buffer(&data); // authdata
							
							ticket->Ticket.Length = _byteswap_ulong(*(PDWORD) data); data += sizeof(DWORD);
							ticket->TicketKvno = 2;
							if(ticket->Ticket.Length)
								if(ticket->Ticket.Value = (PUCHAR) LocalAlloc(LPTR, ticket->Ticket.Length))
									RtlCopyMemory(ticket->Ticket.Value, data, ticket->Ticket.Length);
							data += ticket->Ticket.Length;
							kuhl_m_kerberos_ccache_skip_buffer(&data);

							if(!RtlEqualUnicodeString(&usXCACHECONF, &ticket->TargetDomainName, TRUE))
							{
								kuhl_m_kerberos_ticket_display(ticket, FALSE);
								if(isSave || isInject)
								{
									if(App_KrbCred = kuhl_m_kerberos_ticket_createAppKrbCred(ticket, TRUE))
									{
										App_KrbCred_Size = kull_m_asn1_getSize(App_KrbCred);
										if(isInject)
										{
											kprintf(L"\n\t   * Injecting ticket : ");
											if(NT_SUCCESS(kuhl_m_kerberos_ptt_data(App_KrbCred, App_KrbCred_Size)))
												kprintf(L"OK\n");
										}
										else
										{
											if(saveFilename = kuhl_m_kerberos_ccache_generateFileName(i, ticket, MIMIKATZ_KERBEROS_EXT))
											{
												if(kull_m_file_writeData(saveFilename, App_KrbCred, App_KrbCred_Size))
													kprintf(L"\n\t   * Saved to file %s !", saveFilename);
												else PRINT_ERROR_AUTO(L"kull_m_file_writeData");

												LocalFree(saveFilename);
											}
										}
										LocalFree(App_KrbCred);
									}
								}
							}
							else kprintf(L"\n\t* %wZ entry? *", &usXCACHECONF);
							kuhl_m_kerberos_ticket_freeTicket(ticket);
						}
					}
					kuhl_m_kerberos_ticket_freeExternalName(principalName);
				}
			}
			else PRINT_ERROR(L"ccache version != 0x0504\n");
			LocalFree(file);
		}
		else PRINT_ERROR_AUTO(L"kull_m_file_readData");
	}
	else PRINT_ERROR(L"At least one filename is needed\n");
	return STATUS_SUCCESS;
}
コード例 #15
0
///////////////////////////////////////////////////////////////////////////
//	Name:	ReadHeader
//
//	Description:
//	Read header from GRAND raw data file (.BID).  See GRAND Collect Users 
//	Manual or MIC Users Manual for detailed definition of header format.
//
//	Declaration:
//	bool CGrandDataFile::ReadHeader(const CString &strNameWithPath, CString *pstrErrorMsg)
//
//	Input:	
//			strNameWithPath		filename with full path that is to be opened
//			
//	Output:	pstrErrorMsg	error, if any
//
//			mdVersionNumber		version number read from header
//			msStaNum			station number read from header
//			miYr				year read from header
//			miMon				month read from header
//			miDay				day read from header
//			mdTimestampOfFirstRecordInFile	time of first record in the file in DATE
//
//			
//			
//
//	Return:	true (header read) / false (some kind of error, see pstrErroMsg)
//	
//  date    /	author	revision
//  -----------------	--------
//	10-Dec-2001	SFK		Created from ReadBIDHeader in DbImport.cpp
//////////////////////////////////////////////////////////////////
bool CGrandDataFile::ReadHeader(const CString &strNameWithPath, CString *pstrErrorMsg) // Joe start here, identify by suffix, then branch at end of header read using code in RAD V6 side as guide, then move on to data read and trasnlation
{
    int iHdrSize;
    char str[54];
	struct GRAND_DATA_PT GrandPt;
	fpos_t pos = fpos_t(m_lFileOffset);
	
	miErrorNum = 0;		// 13-Jan-2005 Added setting error num to 0.

   /* ------------------------------------------------------------------
    *	Open the file
    * ----------------------------------------------------------------*/
	if (!OpenDataFile(strNameWithPath, pstrErrorMsg)) 
		return(false);

	// generate an error message in case we get an error in any of the reads,
	// will clear at end of function if all okay
	if (pstrErrorMsg && !(pstrErrorMsg->IsEmpty())) 
	{
		miErrorNum = iFILE_READ_ERR;
		pstrErrorMsg->Format("\nError: Unexpected error during read of %s", strNameWithPath);
	}
	
	if (strNameWithPath.Right(4).CompareNoCase(".BI0") == 0)
		BI0 = true;
   /* ------------------------------------------------------------------
    *	Read the first 4 bytes to get the number of bytes in header.
    *	Based on the location of the number, determine whether the data
    *	file is from CDMPC or LANL GRAND Collect.  The CDMPC number
    *	must be decremented by 1.
    * ----------------------------------------------------------------*/

	//skip over the SnF header if there is one
	int itemp = fsetpos(mpFile, &pos); //SCR00227

    if (fread(str, 4, 1, mpFile) != 1) return(false);
	m_lUsableBytesReadIn += 4; //SCR00227

    str[4] = '\0';    
    iHdrSize = atoi(str);
    if (str[3] == ' ') iHdrSize = iHdrSize - 1; // this file formed by CDMPC
	if (iHdrSize <= 22) return(false);
   /* ------------------------------------------------------------------
    *	The next 5 bytes no longer contain useful information,	just
    *	skip by them.
    * ----------------------------------------------------------------*/
    if (fread(str, 5, 1, mpFile) != 1) return(false);
	m_lUsableBytesReadIn += 5; //SCR00227
       
   /* ------------------------------------------------------------------
    *	Read past the version number in the next 5 bytes.
    * ----------------------------------------------------------------*/
    if (fread(str, 5, 1, mpFile) != 1) return(false);
	m_lUsableBytesReadIn += 5; //SCR00227
	str[5] = '\0';
	mdVersionNumber = atof(str);

   /* ------------------------------------------------------------------
    *  Read station number
    * ----------------------------------------------------------------*/
    if (fread(str, 3, 1, mpFile) != 1) return(false);
	m_lUsableBytesReadIn += 3; //SCR00227
    str[3] = '\0';
    msStaNum = atoi(str);

   /* ------------------------------------------------------------------
    *	Read year
    * ----------------------------------------------------------------*/
    if (fread(str, 3, 1, mpFile) != 1) return(false);
	m_lUsableBytesReadIn += 3; //SCR00227
    str[3] = '\0';
    miYr = atoi(str);
	//3-aug-2005 hn Added a four digit year.
	if (miYr < 86)
	{
		miYr4 = miYr + 2000;
	}
	else
	{
		miYr4 = miYr + 1900;
	}

   /* ------------------------------------------------------------------
    *	Read month
    * ----------------------------------------------------------------*/
    if (fread(str, 3, 1, mpFile) != 1) 
		return(false);

	m_lUsableBytesReadIn += 3; //SCR00227
    str[3] = '\0';
    miMon = atoi(str);

	if ((miMon < 1) || (miMon >12)) 
		return(false);

   /* ------------------------------------------------------------------
    *	Read day.
    * ----------------------------------------------------------------*/
    if (fread(str, 3, 1, mpFile) != 1) 
		return(false);

	m_lUsableBytesReadIn += 3; //SCR00227
    str[3] = '\0';
    miDay = atoi(str);

	if ((miDay < 1) || (miDay >31)) 
		return(false);

   /* ------------------------------------------------------------------
    *	Read past the expansion space in the header so the file pointer
    *	is positioned at the beginning of the first data point at exit.
    * ----------------------------------------------------------------*/
    if (fread(str, (iHdrSize - 22), 1, mpFile)!= 1) 
		return(false);

	m_lUsableBytesReadIn += iHdrSize - 22; //SCR00227
    
   /* ------------------------------------------------------------------
    *	Save the position of the file pointer.
	*	Read the first record in the file to get the time of it.
    *	Restore file pointer to just at the first record.
    * ----------------------------------------------------------------*/
	if(fgetpos(mpFile, &pos ) != 0) 
		return(false);

	if (BI0)   // todo: jfl skip first 5 a la Bob?
	{
		struct DMGGRAND_DATA_PT_HDR DGrandPt;
		// read 4 bytes at a time looking for the first data record (0xffffffff)
		unsigned int tag;
		while (fread(&tag, sizeof(unsigned int),1, mpFile))
		{
			if (tag ^ 0xFFFFFFFF) // ^ anything but the data mask shown here
				OutputDebugString("skipping non-data record\r\n");
			else
				break;
		}
		if (fread(&DGrandPt, sizeof(struct DMGGRAND_DATA_PT_HDR), 1, mpFile) == 0) return(false);
		DGrandPt.ulJulianTime = _byteswap_ulong(DGrandPt.ulJulianTime);
		DGrandPt.usJSCS = _byteswap_ushort(DGrandPt.usJSCS);
		if (checksum_ulong(&(DGrandPt.ulJulianTime)) != DGrandPt.usJSCS)
			OutputDebugString("skip this record\r\n"); // todo: jfl return false?
		mdTimestampOfFirstRecordInFile = m_MyDateTime.MyTimestampToDATETimestamp((double)DGrandPt.ulJulianTime);
	}
	else
	{
		if (fread(&GrandPt, sizeof(struct GRAND_DATA_PT), 1, mpFile) == 0) 
			return(false);
		mdTimestampOfFirstRecordInFile = m_MyDateTime.MyTimestampToDATETimestamp((double)GrandPt.ulJulianTime);
	}
	if(fsetpos(mpFile, &pos ) != 0) 
		return(false);
               
	if (pstrErrorMsg) // wtf?
		pstrErrorMsg->Empty();

	miErrorNum = 0;	// no error
    return(true);
}
コード例 #16
0
void g() {
  (void)_byteswap_ushort(42);
  (void)_byteswap_uint64(42LL);
}
コード例 #17
0
ファイル: etwmon.c プロジェクト: Azarien/processhacker2
VOID NTAPI EtpEtwEventCallback(
    _In_ PEVENT_RECORD EventRecord
    )
{
    if (memcmp(&EventRecord->EventHeader.ProviderId, &DiskIoGuid_I, sizeof(GUID)) == 0)
    {
        // DiskIo

        ET_ETW_DISK_EVENT diskEvent;

        memset(&diskEvent, 0, sizeof(ET_ETW_DISK_EVENT));
        diskEvent.Type = -1;

        switch (EventRecord->EventHeader.EventDescriptor.Opcode)
        {
        case EVENT_TRACE_TYPE_IO_READ:
            diskEvent.Type = EtEtwDiskReadType;
            break;
        case EVENT_TRACE_TYPE_IO_WRITE:
            diskEvent.Type = EtEtwDiskWriteType;
            break;
        default:
            break;
        }

        if (diskEvent.Type != -1)
        {
            DiskIo_TypeGroup1 *data = EventRecord->UserData;

            if (WindowsVersion >= WINDOWS_8)
            {
                diskEvent.ClientId.UniqueThread = UlongToHandle(data->IssuingThreadId);
                diskEvent.ClientId.UniqueProcess = EtThreadIdToProcessId(diskEvent.ClientId.UniqueThread);
            }
            else
            {
                if (EventRecord->EventHeader.ProcessId != -1)
                {
                    diskEvent.ClientId.UniqueProcess = UlongToHandle(EventRecord->EventHeader.ProcessId);
                    diskEvent.ClientId.UniqueThread = UlongToHandle(EventRecord->EventHeader.ThreadId);
                }
            }

            diskEvent.IrpFlags = data->IrpFlags;
            diskEvent.TransferSize = data->TransferSize;
            diskEvent.FileObject = (PVOID)data->FileObject;
            diskEvent.HighResResponseTime = data->HighResResponseTime;

            EtProcessDiskEvent(&diskEvent);
            EtDiskProcessDiskEvent(&diskEvent);
        }
    }
    else if (memcmp(&EventRecord->EventHeader.ProviderId, &FileIoGuid_I, sizeof(GUID)) == 0)
    {
        // FileIo

        ET_ETW_FILE_EVENT fileEvent;

        memset(&fileEvent, 0, sizeof(ET_ETW_FILE_EVENT));
        fileEvent.Type = -1;

        switch (EventRecord->EventHeader.EventDescriptor.Opcode)
        {
        case 0: // Name
            fileEvent.Type = EtEtwFileNameType;
            break;
        case 32: // FileCreate
            fileEvent.Type = EtEtwFileCreateType;
            break;
        case 35: // FileDelete
            fileEvent.Type = EtEtwFileDeleteType;
            break;
        default:
            break;
        }

        if (fileEvent.Type != -1)
        {
            FileIo_Name *data = EventRecord->UserData;

            fileEvent.FileObject = (PVOID)data->FileObject;
            PhInitializeStringRef(&fileEvent.FileName, data->FileName);

            EtDiskProcessFileEvent(&fileEvent);
        }
    }
    else if (
        memcmp(&EventRecord->EventHeader.ProviderId, &TcpIpGuid_I, sizeof(GUID)) == 0 ||
        memcmp(&EventRecord->EventHeader.ProviderId, &UdpIpGuid_I, sizeof(GUID)) == 0
        )
    {
        // TcpIp/UdpIp

        ET_ETW_NETWORK_EVENT networkEvent;

        memset(&networkEvent, 0, sizeof(ET_ETW_NETWORK_EVENT));
        networkEvent.Type = -1;

        switch (EventRecord->EventHeader.EventDescriptor.Opcode)
        {
        case EVENT_TRACE_TYPE_SEND: // send
            networkEvent.Type = EtEtwNetworkSendType;
            networkEvent.ProtocolType = PH_IPV4_NETWORK_TYPE;
            break;
        case EVENT_TRACE_TYPE_RECEIVE: // receive
            networkEvent.Type = EtEtwNetworkReceiveType;
            networkEvent.ProtocolType = PH_IPV4_NETWORK_TYPE;
            break;
        case EVENT_TRACE_TYPE_SEND + 16: // send ipv6
            networkEvent.Type = EtEtwNetworkSendType;
            networkEvent.ProtocolType = PH_IPV6_NETWORK_TYPE;
            break;
        case EVENT_TRACE_TYPE_RECEIVE + 16: // receive ipv6
            networkEvent.Type = EtEtwNetworkReceiveType;
            networkEvent.ProtocolType = PH_IPV6_NETWORK_TYPE;
            break;
        }

        if (memcmp(&EventRecord->EventHeader.ProviderId, &TcpIpGuid_I, sizeof(GUID)) == 0)
            networkEvent.ProtocolType |= PH_TCP_PROTOCOL_TYPE;
        else
            networkEvent.ProtocolType |= PH_UDP_PROTOCOL_TYPE;

        if (networkEvent.Type != -1)
        {
            PH_IP_ENDPOINT source;
            PH_IP_ENDPOINT destination;

            if (networkEvent.ProtocolType & PH_IPV4_NETWORK_TYPE)
            {
                TcpIpOrUdpIp_IPV4_Header *data = EventRecord->UserData;

                networkEvent.ClientId.UniqueProcess = UlongToHandle(data->PID);
                networkEvent.TransferSize = data->size;

                source.Address.Type = PH_IPV4_NETWORK_TYPE;
                source.Address.Ipv4 = data->saddr;
                source.Port = _byteswap_ushort(data->sport);
                destination.Address.Type = PH_IPV4_NETWORK_TYPE;
                destination.Address.Ipv4 = data->daddr;
                destination.Port = _byteswap_ushort(data->dport);
            }
            else if (networkEvent.ProtocolType & PH_IPV6_NETWORK_TYPE)
            {
                TcpIpOrUdpIp_IPV6_Header *data = EventRecord->UserData;

                networkEvent.ClientId.UniqueProcess = UlongToHandle(data->PID);
                networkEvent.TransferSize = data->size;

                source.Address.Type = PH_IPV6_NETWORK_TYPE;
                source.Address.In6Addr = data->saddr;
                source.Port = _byteswap_ushort(data->sport);
                destination.Address.Type = PH_IPV6_NETWORK_TYPE;
                destination.Address.In6Addr = data->daddr;
                destination.Port = _byteswap_ushort(data->dport);
            }

            networkEvent.LocalEndpoint = source;

            if (networkEvent.ProtocolType & PH_TCP_PROTOCOL_TYPE)
                networkEvent.RemoteEndpoint = destination;

            EtProcessNetworkEvent(&networkEvent);
        }
    }
}
コード例 #18
0
ファイル: Endian.hpp プロジェクト: DEC05EBA/desone
static uint16 byteswap(uint16 value)
{
	return _byteswap_ushort(value);
}
unsigned long	readExplicitFile( ifstream& input, unsigned long offset , bool bigEndian , unsigned short target , DicomFileImage& fileInfo )
{
	unsigned long	currentOffset;
	unsigned long	size;
	unsigned short	group;
	unsigned short	element;
	char			type[3];
	unsigned short	lengthShort;
	char*			value;
	bool			found;



	try
	{
		currentOffset = offset;
		found = false;
		type[2] = '\0';
		value = NULL;
		input.seekg(0,ifstream::end);
		size = input.tellg();
		input.seekg(offset,ifstream::beg);
		while( !input.eof()  &&  ( currentOffset = input.tellg() ) < size )
		{
			input.read((char*)&group,2);	// read group code
			input.read((char*)&element,2);	// read element code
			input.read(type,2);	// read value representation
			input.read((char*)&lengthShort,2);	// for "OB","OW",“OF”,“SQ”,“UT”,"UN" unused , else read Value Length

			// if the transfer syntax is Big Endian perform a byte swap
			if ( bigEndian )
			{
				group = _byteswap_ushort(group);
				element = _byteswap_ushort(element);
				lengthShort = _byteswap_ulong(lengthShort);
			}

			if ( group == target  &&  !found )	found = true;
			else if ( group != target  &&  found )	break;
		

			// if the value representation is one of the following
			if ( strcmp(type,"OB") == 0  ||  strcmp(type,"OW") == 0  ||  
				 strcmp(type,"OF") == 0  ||  strcmp(type,"SQ") == 0  ||  
				 strcmp(type,"UN") == 0  ||  strcmp(type,"UT") == 0 )
			{
				int	valueSize;


				// read unlimited text
				value = readUnlimitedText(input,type,false,bigEndian,&valueSize);
				saveInformation(group,element,valueSize,value,fileInfo);
				delete[] value;
				value = NULL;
			}
			else
			{
				if ( lengthShort > 0 )
				{
					// read data equal to the defined length
					value = new char[lengthShort];
					input.read(value,lengthShort);
					saveInformation(group,element,sizeof(unsigned short),value,fileInfo);
					delete[] value;
					value = NULL;
				}
			}
		}
	}
	catch( exception& e )
	{
		if ( value != NULL )
			delete[] value;

		throw e;
	}



	return currentOffset;
};
コード例 #20
0
BOOL kiwi_krbcred_valid_header(OssBuf *input)
{
	return ((input->length > 4) && (_byteswap_ushort(*(PUSHORT) input->value) == 0x7682));
}
コード例 #21
0
void mtsOptoforce3D::Run(void)
{
    struct optopacket {
        unsigned char header[4];
        unsigned short count;
        unsigned short status;
        short fx;
        short fy;
        short fz;
        unsigned short checksum;
    };

    union PacketDataType {
        unsigned char bytes[16];
        optopacket packet;
    };

    PacketDataType buffer;
    ProcessQueuedCommands();

    if (connected) {
        bool found = false;
        unsigned short recvChecksum;
#if (CISST_OS == CISST_WINDOWS)
        // On Windows, serialPort.Read seems to always return the requested number
        // of characters, which is sizeof(buffer).
        // Thus, we have to check whether part of the expected packet has been combined
        // with another packet, such as the 7 byte response to the command sent to the sensor.
            int n = serialPort.Read((char *)&buffer, sizeof(buffer));

            while (!found) {
                for (int i = 0; i < n - 3; i++) {
                    if ((buffer.bytes[i] == 170) && (buffer.bytes[i + 1] == 7)
                        && (buffer.bytes[i + 2] == 8) && (buffer.bytes[i + 3] == 10)) {
                        if (i != 0) {                               // If pattern not found at beginning of buffer
                            memmove(buffer.bytes, buffer.bytes + i, n - i);    //    shift so that 170 is in buffer[0]
                            serialPort.Read(buffer.bytes + n - i, i);          //    fill the rest of the buffer
                        }
                        found = true;
                        break;
                    }
                }
                if (!found) {                                       // If pattern not yet found
                    memmove(buffer.bytes, buffer.bytes + n - 4, 4);               //    move last 4 characters to beginning of buffer
                    serialPort.Read(buffer.bytes + 4, sizeof(buffer.bytes) - 4);  //    get another 12 characters
                }
            }
            // Now, process the data
            RawSensor.X() = (double)static_cast<short>(_byteswap_ushort(buffer.packet.fx)) * scale.X();
            RawSensor.Y() = (double)static_cast<short>(_byteswap_ushort(buffer.packet.fy)) * scale.Y();
            RawSensor.Z() = (double)static_cast<short>(_byteswap_ushort(buffer.packet.fz)) * scale.Z();
            Count = _byteswap_ushort(buffer.packet.count);
            Status = _byteswap_ushort(buffer.packet.status);
            recvChecksum = _byteswap_ushort(buffer.packet.checksum);
#else
        // On Linux, serialPort.Read seems to return a complete packet, even if it is less than the
        // requested size.
        // Thus, we can discard packets that are not the correct size.
        while (!found) {
            if (serialPort.Read((char *)&buffer, sizeof(buffer)) == sizeof(buffer)) {
                // Check for expected 4 byte packet header
                found = ((buffer.bytes[0] == 170) && (buffer.bytes[1] == 7)
                    && (buffer.bytes[2] == 8) && (buffer.bytes[3] == 10));
            }
        }
        // Now, process the data
        RawSensor.X() = (double)static_cast<short>(bswap_16(buffer.packet.fx)) * scale.X();
        RawSensor.Y() = (double)static_cast<short>(bswap_16(buffer.packet.fy)) * scale.Y();
        RawSensor.Z() = (double)static_cast<short>(bswap_16(buffer.packet.fz)) * scale.Z();
        Count = bswap_16(buffer.packet.count);
        Status = bswap_16(buffer.packet.status);
        recvChecksum = bswap_16(buffer.packet.checksum);
#endif
        // Verify the checksum (last 2 bytes).
        unsigned short checksum = buffer.bytes[0];
        for (size_t i = 1; i < sizeof(buffer) - 2; i++)
            checksum += buffer.bytes[i];
        // (Status == 0) means no errors or overload warnings.
        // For now, we check ((Status&0xFC00) == 0), which ignores overload warnings.
        bool valid = (checksum == recvChecksum) && ((Status & 0xFC00) == 0);
        ForceTorque.SetValid(valid);

        if (valid) {
            if (calib_valid) {
                Force = RawSensor;
            }
            else if (matrix_a_valid) {
                // Obtain forces by applying the calibration matrix, which depends on sensor-specific calibration
                // values (A) and the assumed length to where the forces are applied (Length), which determines matrix_l (L).
                // The calibration matrix, matrix_cal, is equal to inv(A*L)

                Force = matrix_cal*RawSensor - bias;  // F = inv(A*L)*S - bias

                // Stablize the sensor readings
                ForceCurrent.Assign(Force);

                for (int i=0; i<3; i++) {
                    if(fabs(ForceCurrent.Element(i)) < 0.2)
                        ForceCurrent.Element(i) = 0.0;
            }
                
                Force.Assign(ForceCurrent);

                for (int i=0; i<3; i++)
                    Force.Element(i) = 0.5*ForceCurrent.Element(i) + 
                                        0.5*ForcePrevious.Element(i);
                ForcePrevious.Assign(Force);
            }
            else {
                Force = RawSensor - bias;
            }
            
            ForceTorque.SetForce(vctDouble6(Force.X(), Force.Y(), Force.Z(), 0.0, 0.0, 0.0));
        }
    }
    else {
        ForceTorque.SetValid(false);
        osaSleep(0.1);  // If not connected, wait
    }
}
コード例 #22
0
bool CGrandDataFile::ReadDataFile(CDbVista* pDb, const CString &strNameWithPath, CString *pstrMsg)
{

	static float fLastGoodGamma1 = 0.0;	// 11-Aug-2005 SFK best guess to substitute
	static float fLastGoodGamma2 = 0.0;	// 11-Aug-2005 SFK best guess to substitute
	static float fLastGoodGamma1Unc = 0.0;	// 11-Aug-2005 SFK best guess to substitute
	static float fLastGoodGamma2Unc = 0.0;	// 11-Aug-2005 SFK best guess to substitute

    struct db_float_data_rec	dbFloatData;  /* database record structure */
	struct db_day_rec	dbDay;   /* database record structure */ 
    struct GRAND_DATA_PT GrandPt;

    int i;
    DATE dFirstTimeInDay, dLastTimeInDay, dFirstTimeInFile;
    unsigned long ulPtsInDaySoFar; /* how many data pts in day so far */
    unsigned long ulPtsInDay;	    /* how many data pts in entire day */
    DATE dPrevTime;
    int iInvalidData;	    		/* number of records not belonging in the day */
    int iOutOfOrder;
    int iGamAdjust;
    char szDateStr[MAX_DT_LEN+1], szFirst[MAX_DT_LEN+1], szLast[MAX_DT_LEN+1];
	char szTempDate[MAX_DT_LEN+1], szTempTime[MAX_DT_LEN+1];
	bool bFirstPoint = true;
	bool bDayAlreadyExists = false;
	bool bOverwrote = false;
	CString TempStr;	
	DATE  dCurrentPtJulianTime = -1;
	//CMyDateTime DateCvt;
	double dMilliSecs;

	//SCR00227
	//Use CheckSignatureEx() because the return is testable.
	m_lFileOffset = 0;
	m_lUsableFileLength = 0;
	m_bIsSignedFile = false;
	m_lUsableBytesReadIn = 0;

	unsigned char *publicKey, *signatureTimestamp; //not used
	const char *inputFileName = LPCTSTR(strNameWithPath);

	int iRetval = CheckSignatureEx (inputFileName, &m_lFileOffset, &m_lUsableFileLength,  
				&publicKey, &signatureTimestamp );

	/*char* temp = new char[100];
	sprintf (temp,"check signature returns offset of %i from check signature",m_lFileOffset);
	MessageBox (NULL, temp, "heather's debug message", MB_OK|MB_ICONWARNING);
	delete [] temp;*/
	// iRetval interpretation (From Cesare's InLineVerifier.c file)
	//0 = Successfully verified
	//1 = File is CORRUPTED - signature is invalid
	//3 = Verified OK, but CA authority is unknown
	//-14 = Input file has no S/MIME format
	// All others are failures.
	switch(iRetval)
	{
	case 0:
		{
			//Signature is valid
			m_bIsSignedFile = true;
			break;
		}
	case 3:
		{
			//Signature CA unknown
			if (pstrMsg)
			{
				pstrMsg->Format("\nCode %d Warning: Signed file %s has an unknown CA.",
					iRetval,
					m_Dir.StripPathFromFilename(strNameWithPath));
			}
			m_bIsSignedFile = true;
			break;
		}
	case -1:
		{
			if (pstrMsg)
			{
				pstrMsg->Format("\nCode %d Warning: CheckSignature library returned out of memory error for file %s.",
					iRetval,
					m_Dir.StripPathFromFilename(strNameWithPath));
			}
			//Library out of memory error, try to continue
			m_bIsSignedFile = true;
			break;
		}
	case 1:
		{
			//Invalid signature, try anyway.
			if (pstrMsg)
			{
				pstrMsg->Format("\nCode %d Warning: Signed file %s has invalid signature.",
					iRetval,
					m_Dir.StripPathFromFilename(strNameWithPath));
			}

			m_bIsSignedFile = true;
			break;
		}
	case -10:
		{
			//Input file does not exist
			if (pstrMsg)
			{
				pstrMsg->Format("\nCode %d Error: File %s does not exist.",
					iRetval,
					m_Dir.StripPathFromFilename(strNameWithPath));
			}
			m_bIsSignedFile = false;
			return false;
		}
	case -11:
		{
			//Input file empty
			if (pstrMsg)
			{
				pstrMsg->Format("\nCode %d Error: File %s is empty.",
					iRetval,
					m_Dir.StripPathFromFilename(strNameWithPath));
			}
			m_bIsSignedFile = false;
			return false;
		}
	case -12:
		{
			//IO Error
			if (pstrMsg)
			{
				pstrMsg->Format("\nCode %d Error: IO error reading file %s.",
					iRetval,
					m_Dir.StripPathFromFilename(strNameWithPath));
			}
			m_bIsSignedFile = false;
			return false;
		}
	case -14:
		{
			//There is no signature on this file
			//Treat as normal
			m_bIsSignedFile = false;
			break;
		}
	default:
		{
			//This file is no good...and we don't know why.
			if (pstrMsg)
			{
				pstrMsg->Format("\nCode %d Error: Signed file %s failed signature check.",
					iRetval,
					m_Dir.StripPathFromFilename(strNameWithPath));
			}
			return false;
		}
	}

   /* ------------------------------------------------------------------
    *	Read header information
    * ----------------------------------------------------------------*/
	if (!ReadHeader(strNameWithPath, pstrMsg)) 
	{
		//MessageBox (NULL, "could not read header", "heather's debug message", MB_OK|MB_ICONWARNING);
		if (mpFile) 
			CloseDataFile();

		return(false);
	}

   /* ------------------------------------------------------------------
    *	During read of header, got the station number.  Verify from the
	*	Facility Configuration Com that this is a valid station number and
	*	is a GRAND type.
	*	First verify that a database framework exists for this facility
    * ----------------------------------------------------------------*/
	if (pDb->mbDatabaseCleared) 	// no framework yet
	{
		pDb->BuildDatabaseFramework(pDb->msFacNum);
		pDb->mbDatabaseCleared = false;
	}

	struct db_sta_rec dbSta;
	bool bExists = m_pFacCfg->GetStationRecord(pDb->msFacNum, msStaNum, &dbSta);
	if (!bExists) 
	{
		if (pstrMsg) pstrMsg->Format("\nError: Skipping file %s with unknown station",m_Dir.StripPathFromFilename(strNameWithPath));
		return(false);
	}
	if (dbSta.s_sta_type != GRAND_TYPE) 
	{
		if (pstrMsg) pstrMsg->Format("\nError: Skipping file %s with unexpected station type %d",m_Dir.StripPathFromFilename(strNameWithPath), dbSta.s_sta_type);
		return(false);
	}
	CString strStationName = dbSta.sz_sta_name;
	CGrandData GInst(pDb, msStaNum, false, m_bQuietMode);

	// 02-Mar-2005 SFK Make sure this station is in the database framework		
	pDb->AddStationToDatabaseFramework(pDb->msFacNum, msStaNum);
	//MessageBox (NULL, "added station in db", "heather's debug message", MB_OK|MB_ICONWARNING);
	// By the time get here, know we have GRAND data and a valid station number
   /* ------------------------------------------------------------------
    *	This routine tries to eliminate bad data from the GRAND from
    *	getting into the database and corrupting it.  If the GRAND
    *	problem is ever found and fixed this can be removed.
    *	Check the size of the file, if it is 109 bytes long, it is
    *	probably a bad data file and should not be imported.  If the
    *	user responds within a certain time, allow him to decide whether
    *	or not to import the data.  The default is to end the import
    *	process for this file.
    
    *	FIX for timeouts***************************************
    * ----------------------------------------------------------------*/
	m_lFileLength = _filelength(fileno(mpFile));  //SCR00227

    if (m_lFileLength == 109) 
	{
		if (pstrMsg) 
		{
			pstrMsg->Format("Error: \nSkipping file %s (date=%02d.%02d.%02d): bad data size of 109", 
				mstrFilenameWithPath, miYr, miMon, miDay);
		}
		if (mpFile) 
			CloseDataFile();

		miErrorNum = iSKIP_FILE;
		return(false);
	}    

   /* ------------------------------------------------------------------
    *	Determine the limits of julian times that belong in this day
    * ----------------------------------------------------------------*/
    sprintf(szDateStr,"%02d.%02d.%02d", miYr, miMon, miDay); 
	DATE dDayStart = m_MyDateTime.DateTimeStrsToDATETimestamp(szDateStr, "00:00:00");
	DATE dFirstTimeInNextDay = dDayStart + 1;
       
   /* ------------------------------------------------------------------
    *	Check if record for this day already exists in database
    * -----------------------------------------------------------------*/
	DB_D_INTERVAL DayInFile;
	ulPtsInDaySoFar = 0;
	bOverwrote = false;

	int iStatus = GInst.DayExists(dDayStart, &ulPtsInDaySoFar, &DayInFile);

	if (iStatus == iDB_BAD) 
	{
		miErrorNum = iStatus;
		if (mpFile) CloseDataFile();
		return(false);
	}
	dbDay.d_day_beg_time_key = DayInFile.dStart;
	dbDay.d_day_end_time = 0;
                                                          
   /* ------------------------------------------------------------------
    *	If data already in database, either automatically overwrite the 
    *	data or ask the user if they want to overwrite.
    * ----------------------------------------------------------------*/
    if (iStatus == iDAY_IN_DB)   // day exists in db
	{
		// check to see if can just add to the existing day; this is allowed

		if (mdTimestampOfFirstRecordInFile > DayInFile.dEnd)  // will add to end of day
		{
			bDayAlreadyExists = true;
		}
		else
		{
			//Determine if we are going to overwrite the existing day's data or not.  
			//If not, say so and exit.
			//If so, do it.

			//The only time we have to ask 
			//the user if he really wants to overwrite the existing data
			//is when the quiet mode is OFF (i.e. we are allowed to ask) and the
			//input command says to overwrite (mbOverwrite is true).

			//Otherwise, we just do what the input command says.  Therefore, initialize the
			//local boolean to do waht the input command says.
			bool local_overwrite_flag = mbOverwrite;

			//Was "NOT FOR NDAR".  REINSERTED 11/26/2007 PJM
			//Now determine if we need to ask
			if (!m_bQuietMode && mbOverwrite)  //this is the only case in which we need to ask
			{
				//..so ask using a message box
        		TempStr.Format(
					"File %s contains data from %s which already exists in database.  Do you want to overwrite the day?",
					mstrFilenameWithPath, szDateStr);

				if (MessageBox(NULL, TempStr, "GrandCom: Day Already In Database", MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) 
					local_overwrite_flag = false;
				else
					local_overwrite_flag = true;
			}
			
			if (!local_overwrite_flag)  //Don't overwrite. Just say we are not, clean up, and bail.
			{
				if (pstrMsg)
				{
					pstrMsg->Format("\nSkipping file %s (date=%02d.%02d.%02d): day's data already in database", 
							mstrFilenameWithPath, miYr, miMon, miDay);
				}

				if (mpFile) 
					CloseDataFile();

				miErrorNum = iSKIP_FILE;

				return true;
			}

   			iStatus = GInst.DeleteDay(dDayStart);

			if (iStatus != iDAY_IN_DB) 
			{
				miErrorNum = iStatus;
				if (mpFile) CloseDataFile();
				return false;	
			}

   			bOverwrote = true;
		}
	}	
	


   /* ------------------------------------------------------------------
    *	If day is not already in db, create a new day record with all db linkages needed.
	*	If day is in db, then add to the existing record.
    * ----------------------------------------------------------------*/
	if (!bDayAlreadyExists) 
	{
		if (!GInst.CreateDay(dDayStart)) 
		{
			miErrorNum = GInst.miErrorNum;
			if (mpFile) CloseDataFile();
			return(false);
		}
		i = 0;
		dPrevTime = 0.0;
		dLastTimeInDay = 0.0;        
		ulPtsInDaySoFar = 0;
		bFirstPoint = true;
		GInst.mbFillingExistingRec = false;
	}
	else 
	{ // data exists, adding to day
	
		if (!GInst.GetMultipleDbRecord(DayInFile.dEnd, &i, &dbFloatData, BEFORE)) 
		{
			miErrorNum = GInst.miErrorNum;
			if (mpFile) CloseDataFile();
			return false;
		}
			
		if (i == (NUM_RAW_DATA_PTS_IN_MULTIPLE_DB_RECORD-1)) 
		{
			i = 0;
			GInst.mbFillingExistingRec = false;
		}
		else 
		{
			i++;
			GInst.mbFillingExistingRec = true;
			ulPtsInDaySoFar = ulPtsInDaySoFar - i;
		}
		dPrevTime = dbDay.d_day_end_time;
		dLastTimeInDay = DayInFile.dEnd;//	dbDay.ul_day_end_time;
		dFirstTimeInFile = mdTimestampOfFirstRecordInFile;
		dFirstTimeInDay = DayInFile.dStart;	//dbDay.ul_day_beg_time;
		bFirstPoint = false;
	}

	iInvalidData = 0;
	iOutOfOrder = 0;
	iGamAdjust = 0; 
	
   /* ------------------------------------------------------------------
    *	Read records from the raw data file one at a time until all read.
    *	A group of individual records are combined into a single multiple
    *	record in the database.  As each record becomes full, write it
    *	to the database.
    * ----------------------------------------------------------------*/
	size_t items = 1;									//SCR00227
	size_t itemsize = sizeof(struct GRAND_DATA_PT);	//SCR00227  (36)
	int numitemstoreadeachtime = 1;
	int numitemsreadsofar = 0;

	unsigned int  ValidRecords = 0, SkippedRecords = 0, NonAcqRecords = 0; // BI0 counters

	while (items != 0)
	{
		if (BI0)
		{
			itemsize = sizeof(struct DMGGRAND_DATA_PT_HDR) + sizeof(struct DMGGRAND_DATA_PT_BDY);
			struct DMGGRAND_DATA_PT_HDR biorh;
			char  biff[512];

			unsigned int tag;
			while (fread(&tag,sizeof(unsigned int),1,mpFile)) // scan to next data record
			{
				if (tag ^ 0xFFFFFFFF) // anything but the mask
				{
					sprintf(biff,"0x%08x; skipping\n",tag);
					OutputDebugString(biff);
				}
				else
					break;
			}
			// hdr and data reads go here
			if (items = fread(&biorh,sizeof(struct DMGGRAND_DATA_PT_HDR),1,mpFile)) // got a data record header
			{
				unsigned short DCSv = 0, JSCSv = 0; 

				// doin that endian boogie thang
				biorh.ulJulianTime = _byteswap_ulong(biorh.ulJulianTime);
				biorh.usJSCS = _byteswap_ushort(biorh.usJSCS);
				byte* time = (byte*)(&biorh);	
				for (int i = 0; i < 4; i++)	JSCSv += time[i];
				bool timebad, databad;
				timebad = (JSCSv != biorh.usJSCS);

				if (biorh.OpCode != 0x15)  // not an acquire record, read through it
				{
					byte dross[1024];
					if (items = fread(dross,biorh.Len - 4,1,mpFile)) // data starts after the opcode, len was data len + 2 opcode + 2 data cs, so read len-4 to get to end of data, 2 more for data cs
					{
						unsigned short datacs;
						items = fread(&datacs,2,1,mpFile);
						for (int i = 0; i < (biorh.Len - 4); i++) DCSv += dross[i];	
						datacs= _byteswap_ushort(datacs);
						databad = (DCSv != datacs);
					}
				}
				else if (biorh.OpCode == 0x15)  // acquire record
				{ 
					struct DMGGRAND_DATA_PT_BDY bior;
					if (items = fread(&bior,sizeof(struct DMGGRAND_DATA_PT_BDY),1,mpFile))
					{
						numitemsreadsofar += items; // jfl todo not skipping records based on bad checksums just yet

						bior.usDCS = _byteswap_ushort(bior.usDCS);
						bior.usGrandStatus  = _byteswap_ushort(bior.usGrandStatus);
						bior.A.ul = _byteswap_ulong(bior.A.ul);
						bior.B.ul = _byteswap_ulong(bior.B.ul);
						bior.C.ul = _byteswap_ulong(bior.C.ul);
						bior.G1.ul = _byteswap_ulong(bior.G1.ul);
						bior.G1u.ul = _byteswap_ulong(bior.G1u.ul);
						bior.G2.ul = _byteswap_ulong(bior.G2.ul);
						bior.G2u.ul = _byteswap_ulong(bior.G2u.ul);
						bior.usElapsedTime  = _byteswap_ulong(bior.usElapsedTime);

						byte* data = (byte*)(&bior);
						for (int i = 0; i < (biorh.Len - 4); i++) DCSv += data[i];	
						databad = (DCSv != bior.usDCS);

						GrandPt.ulJulianTime = biorh.ulJulianTime;
						GrandPt.usElapsedTime = bior.usElapsedTime;
						GrandPt.usGrandStatus = bior.usGrandStatus;
						GrandPt.fA = bior.A.f;
						GrandPt.fB = bior.B.f;
						GrandPt.fC = bior.C.f;
						GrandPt.fG1 = bior.G1.f;
						GrandPt.fG1u = bior.G1u.f;
						GrandPt.fG2 = bior.G2.f;
						GrandPt.fG2u = bior.G2u.f;
					}
				}
			}
		}
		else
		{
			items = fread(&GrandPt, itemsize, numitemstoreadeachtime, mpFile);
			if (items == 0)
				break;
			//for a signed file, if we read beyond the "real" data and into
			//the footer, then we are finished reading.
			m_lUsableBytesReadIn += numitemstoreadeachtime * itemsize;
			numitemsreadsofar += items;

			if (m_bIsSignedFile && (m_lUsableBytesReadIn > m_lUsableFileLength))
			{
				//MessageBox (NULL, "rad thinks it is signed", "heather's debug message", MB_OK|MB_ICONWARNING);
				break;
			}
		}
		dCurrentPtJulianTime = m_MyDateTime.MyTimestampToDATETimestamp((double)GrandPt.ulJulianTime);

	   /* ------------------------------------------------------------------
		*   If the point's julian time is not in this day, note it and skip this point.
		* ----------------------------------------------------------------*/
		if ((dCurrentPtJulianTime < dDayStart) || (dCurrentPtJulianTime >= dFirstTimeInNextDay)) 
		{
			iInvalidData++;

			if (iInvalidData < 100) 	// print only the first 100 invalid data points
			{
				m_MyDateTime.DATETimestampToDateTimeStrs(dCurrentPtJulianTime, szTempDate, szTempTime, GEN_DTF_IAEA, GEN_DTF_HMSM);
				TempStr.Format("\nInvalid record time in file %s: %10ld %s %s",m_Dir.StripPathFromFilename(strNameWithPath), GrandPt.ulJulianTime, szTempDate, szTempTime);
				*pstrMsg += TempStr;
			}
			else 
			{	// 21-Jan-2005 SFK Don't print everything with big bad file
				if (iInvalidData == 100) 
				{
					TempStr.Format("\nToo many invalid data records in file %s to list details for each record.", m_Dir.StripPathFromFilename(strNameWithPath));
					*pstrMsg += TempStr;
				}
			}
			continue;
		}
		
	   /* ------------------------------------------------------------------
		*   If the point is out of order count it.  
		*	If the points are in order then set a new prev point
		* ----------------------------------------------------------------*/
		if (bFirstPoint) 
			dPrevTime = dCurrentPtJulianTime;

		if ((dCurrentPtJulianTime < dPrevTime) && (!bFirstPoint)) 
		{
			iOutOfOrder++;
			if (mbSkipOutOfOrder == true) continue;
		}
		else
		{
			dPrevTime = dCurrentPtJulianTime; 
		}

	   /* ------------------------------------------------------------------
		*   The largest point in the day is the last point and the smallest
		*	point in the day is the first point.
		* ----------------------------------------------------------------*/
		if (dCurrentPtJulianTime > dLastTimeInDay)
		{
			dLastTimeInDay = dCurrentPtJulianTime;
		}
		if (bFirstPoint) 
		{
			dFirstTimeInDay = dCurrentPtJulianTime;
			dFirstTimeInFile = dFirstTimeInDay;
			bFirstPoint = false;
		}	
		else 
		{
			if (dCurrentPtJulianTime < dFirstTimeInDay) 
			{
				dFirstTimeInDay = dCurrentPtJulianTime;
				dFirstTimeInFile = dFirstTimeInDay;
			}
		}

	   /* ------------------------------------------------------------------
		*   If this is the first record of a multiple record (index = 0),
		*   fill in the julian time of the 1st record and the number of
		*	pts in the day so far.
		* ----------------------------------------------------------------*/
		if (i == 0) 
		{	   
			dbFloatData.d_fdata_beg_time_key = dCurrentPtJulianTime;
			dbFloatData.ul_fdata_pts_so_far = ulPtsInDaySoFar;
		}

	   /* ------------------------------------------------------------------
		*   Fill the database record.
		*	Reverse the polarity of the authentication status bit
		* ----------------------------------------------------------------*/
		dbFloatData.d_fdata_time[i]  = dCurrentPtJulianTime;
		dbFloatData.ul_fdata_status[i] = (unsigned long)(GrandPt.usGrandStatus ^ 0x0002);
		dbFloatData.d_fdata_etime[i] = (double)GrandPt.usElapsedTime;
		dbFloatData.f_data_chan1[i]	 = GrandPt.fA;
		dbFloatData.f_data_chan2[i]	 = GrandPt.fB;
		dbFloatData.f_data_chan3[i]	 = GrandPt.fC;
		dbFloatData.f_data_chan4[i]	 = GrandPt.fG1;
		dbFloatData.f_data_chan5[i]	 = GrandPt.fG2;
		dbFloatData.f_data_chan6[i]	 = GrandPt.fG1u;
		dbFloatData.f_data_chan7[i]	 = GrandPt.fG2u;
		//if (GrandPt.fA > 1000.) {
		//	i=i;  //debug hit point
		//}

	   /* ------------------------------------------------------------------
		*   Alter IC data points with readings greater than 900000
		*   (when IC couldn't get good data).  Either put in value of previous
		*   point or set value to 0.
		*   point.
		* ----------------------------------------------------------------*/
		// 11-Aug-2005 SFK  Reworked the following section to handle the various gamma conditions
		//					and setting different status bits for the different conditions.
		if ((dbFloatData.f_data_chan4[i] >= SATURATED_G-1.0)  || (dbFloatData.f_data_chan5[i] >= SATURATED_G-1.0)) {
			iGamAdjust++;	
			
			// is this because  gamma 1 signal is saturated?
			if ((dbFloatData.f_data_chan4[i] >= SATURATED_G) && (dbFloatData.f_data_chan4[i] < INVALID_G)) {
				dbFloatData.f_data_chan4[i] = fLastGoodGamma1;								// replace with last good gamma point
				dbFloatData.ul_fdata_status[i] = dbFloatData.ul_fdata_status[i] | SATURATED_BIT;	
			}
			// is this because the gamma 1 signal is invalid (didn't get any readings in the time period)
			if ((dbFloatData.f_data_chan4[i] >= INVALID_G) && (dbFloatData.f_data_chan4[i] < OFFSET_G)) {
				dbFloatData.f_data_chan4[i] = fLastGoodGamma1;								// replace with last good gamma point
				dbFloatData.ul_fdata_status[i] = dbFloatData.ul_fdata_status[i] | INVALID_G_BIT;
			}
			// is this because offsets were being taken on gamma 1
			if (dbFloatData.f_data_chan4[i] >= OFFSET_G) {
				dbFloatData.f_data_chan4[i] = fLastGoodGamma1;									// replace with last good gamma point
				dbFloatData.ul_fdata_status[i] = dbFloatData.ul_fdata_status[i] | OFFSET_BIT;	// 28-Jun-2005 SFK Added an offset bit
			}

			// is this because  gamma 2 signal is saturated?
			if ((dbFloatData.f_data_chan5[i] >= SATURATED_G) && (dbFloatData.f_data_chan5[i] < INVALID_G)) {
				dbFloatData.f_data_chan5[i] = fLastGoodGamma2;								// replace with last good gamma point
				dbFloatData.ul_fdata_status[i] = dbFloatData.ul_fdata_status[i] | SATURATED_BIT;	
			}
			// is this because the gamma 2 signal is invalid (didn't get any readings in the time period)
			if ((dbFloatData.f_data_chan5[i] >= INVALID_G) && (dbFloatData.f_data_chan5[i] < OFFSET_G)) {
				dbFloatData.f_data_chan5[i] = fLastGoodGamma2;								// replace with last good gamma point
				dbFloatData.ul_fdata_status[i] = dbFloatData.ul_fdata_status[i] | INVALID_G_BIT;
			}
			// is this because offsets were being taken on gamma 2
			if (dbFloatData.f_data_chan5[i] >= OFFSET_G) {
				dbFloatData.f_data_chan5[i] = fLastGoodGamma2;								// replace with last good gamma point
				dbFloatData.ul_fdata_status[i] = dbFloatData.ul_fdata_status[i] | OFFSET_BIT;	// 28-Jun-2005 SFK Added an offset bit
			}
		}	
		else {	// if the gammas were within range, remember their last good reading to substitute above
			if (dbFloatData.f_data_chan4[i] < SATURATED_G) fLastGoodGamma1 =  dbFloatData.f_data_chan4[i];
			if (dbFloatData.f_data_chan5[i] < SATURATED_G) fLastGoodGamma2 =  dbFloatData.f_data_chan5[i];
		}
		
		// 29-Jun-2005 SFK Now check if the uncertainty values are > 9000 and < 10000 which indicates either
		// offsets or not enough readings to be really "good" measurement or ADC at full scale 
		// which indicates signal changing very fast
		// 11-Aug-2005 SFK  The status bits are set when reading the actual gamma channels.  Here just
		//					decide whether to replace the present reading with the last good reading.
		if (dbFloatData.f_data_chan6[i] >= SATURATED_U) {
			dbFloatData.f_data_chan6[i] = fLastGoodGamma1Unc;
		}
		else {
			fLastGoodGamma1Unc = dbFloatData.f_data_chan6[i];		// remember last good reading to substitute above
		}
		if (dbFloatData.f_data_chan7[i] >= SATURATED_U) {
			dbFloatData.f_data_chan7[i] = fLastGoodGamma2Unc;
		}
		else {
			fLastGoodGamma2Unc = dbFloatData.f_data_chan7[i];		// remeber last good reading to substitute above
		}

		// 09-Feb-2005 SFK Check to see if ms are in the Gamma 2 (xxx ms are encoded as 8xxx00)
		if ((dbFloatData.f_data_chan5[i] >= GAMMA2_IS_MS) && (dbFloatData.f_data_chan5[i] < SATURATED_G)) {
			dMilliSecs = dbFloatData.f_data_chan5[i] - GAMMA2_IS_MS;
			dMilliSecs = dMilliSecs/100;
			// convert to DATE
			dMilliSecs = dMilliSecs/dMILLISEC_PER_DAY;
			// add ms to original elapsed time and the timestamp
			dbFloatData.d_fdata_time[i] += dMilliSecs;
			dbFloatData.d_fdata_etime[i] = dbFloatData.d_fdata_etime[i]/10;  // Elapsed time is in tenths of sec
		}


		i++;	// count the point just processed

		if (i == NUM_RAW_DATA_PTS_IN_MULTIPLE_DB_RECORD) {  //78

			// about to grow database, check size limit and recover here, see BMEND-8
			// TBD note: this technique should be extened to all other datatypes, not just grand
			bool toobig = false;
			ULONG cursize, maxsize;
			double maxpercentsize = 0.95;	// TBD note: this should be externally configured
			pDb->CheckDatabaseSize(maxpercentsize, cursize, maxsize, toobig);
			if (toobig)
			{
				if (pstrMsg) 
					pstrMsg->Format("\nSkipping file %s. The database size %ul bytes is more than %3.0f%% (%ul) of max %ul bytes.", 
					strNameWithPath, cursize, (maxpercentsize * 100), ULONG(maxpercentsize * maxsize), maxsize);
				miErrorNum = iFILE_READ_ERR;
				if (mpFile) CloseDataFile();
				return(false);
			}

		   /* ------------------------------------------------------------------
			*	When have enough data to fill multiple record, create the new
			*	record, fill it and attach to database.
			* ----------------------------------------------------------------*/
			GInst.mdbFloatDataRec = dbFloatData;
			if (!GInst.AddData(pstrMsg)) 
			{
				miErrorNum = GInst.miErrorNum;
				if (mpFile) CloseDataFile();
				return(false);
			}
			ulPtsInDaySoFar += i;	// accumulate points read so far
			//MessageBox (NULL, "wrote multiple points to db", "heather's debug message", MB_OK|MB_ICONWARNING);
			i = 0;
		}
	}

   /* ------------------------------------------------------------------
	*	Got an error reading the data file.  Are expecting an EOF
	*	error.	If it's anything else, then abort and delete partial
	*	data already in the db.  If it's EOF, close	the raw data file
	*	and continue.
	* ----------------------------------------------------------------*/
	int dum = feof(mpFile);
	if (!m_bIsSignedFile && (feof(mpFile) == 0)) 
	{
		if (pstrMsg) pstrMsg->Format("\nImport Error Reading File %s.  File Error = %s", mstrFilenameWithPath, strerror(errno));
		if (mpFile) CloseDataFile();
		GInst.DeleteDay(dDayStart);
		miErrorNum = iFILE_READ_ERR;
		if (mpFile) CloseDataFile();
		//MessageBox (NULL, "import error", "heather's debug message", MB_OK|MB_ICONWARNING);
		return(false);
	}
	if (mpFile) CloseDataFile();

   /* ------------------------------------------------------------------
	*	Are at the end of the raw data file.  Fill the julian times
	*	of the unfilled records with 0 and write the partially filled
	*	record to the data base.
	* ----------------------------------------------------------------*/
	ulPtsInDay = ulPtsInDaySoFar + i;

	if (i > 0) 
	{
		while (i < NUM_RAW_DATA_PTS_IN_MULTIPLE_DB_RECORD) 
		{
			dbFloatData.d_fdata_time[i] = 0;
			i++;
		}
		GInst.mdbFloatDataRec = dbFloatData;
		if (!GInst.AddData(pstrMsg)) 
		{
			miErrorNum = GInst.miErrorNum;
			return(false);
		}

	}
   /* ------------------------------------------------------------------
    *	If there was no data for this day, delete the record you added
    *	at the start of reading the raw data file.  Print out some hints for the
	*	user as to why no data points are in the day.
    * ----------------------------------------------------------------*/
    if (ulPtsInDay == 0) 
	{
		GInst.DeleteDay(dDayStart);
		DB_D_INTERVAL DumDayInFile;
		unsigned long ulDumPtsInDaySoFar;
		int iStatus = GInst.DayExists(dDayStart, &ulDumPtsInDaySoFar, &DumDayInFile);

		if (pstrMsg) 
		{ 
			if (dCurrentPtJulianTime == 0) 
			{
				pstrMsg->Format("No data points in this file.");
			}
			else 
			{
				m_MyDateTime.DATETimestampToDateTimeStrs(dCurrentPtJulianTime, szTempDate, szTempTime, GEN_DTF_IAEA, GEN_DTF_HMSM);

    			pstrMsg->Format("\nHeader from file %s indicates data from %s, file data from %s\n", 
					mstrFilenameWithPath, szDateStr, szTempDate);

   				if (iOutOfOrder > 0)
				{
					TempStr.Format("  %5d pts out of order.", iOutOfOrder);
					*pstrMsg += TempStr;
				}

				if (iInvalidData > 0)
				{
					TempStr.Format("  %5d rec(s) with invalid times.",iInvalidData);
					*pstrMsg += TempStr;
				}
			}
		}    
		return true;
    }

   /* ------------------------------------------------------------------
    *	Some data from this day in database - now update the day record
    *	describing this day.
    *	First, find the day record.  Then read it, update the pts field
    *	and then write it back to the database.
    * ----------------------------------------------------------------*/
	iStatus = GInst.GetDayData(dDayStart, &dbDay);
	if (iStatus != iDAY_IN_DB) 
	{
		miErrorNum = iStatus;
		return (false);
	}
    dbDay.ul_day_total_pts = ulPtsInDay;
    dbDay.d_day_end_time = dLastTimeInDay;
	dbDay.d_day_beg_time = dFirstTimeInDay;
	iStatus = GInst.AddDayData(&dbDay);
	//MessageBox (NULL, "updated day record", "heather's debug message", MB_OK|MB_ICONWARNING);

   /* ------------------------------------------------------------------
    *	Log which file was just imported successfully.  Include date, station
    *	name, file name and first/last time in the file.
    *	Also log if the day's data was overwritten and if there were
    *	any points out of order or data with invalid times.
    * ----------------------------------------------------------------*/
    if (pstrMsg) 
	{ 
		m_MyDateTime.DATETimestampToDateTimeStrs(dFirstTimeInFile, szTempDate, szFirst, GEN_DTF_IAEA, GEN_DTF_HMSM);
		m_MyDateTime.DATETimestampToDateTimeStrs(dLastTimeInDay, szTempDate, szLast, GEN_DTF_IAEA, GEN_DTF_HMSM);		
		TempStr.Format("\n%s  %25s  %s    %s    %s    %5ld", szDateStr, strStationName, m_Dir.StripPathFromFilename(strNameWithPath), szFirst, szLast, ulPtsInDay);
		*pstrMsg += TempStr;
		if (bOverwrote) 
		{
			TempStr.Format("  Overwrote existing day's data.");
			*pstrMsg += TempStr;
		}
		if (bDayAlreadyExists) 
		{
			TempStr.Format("  Added to existing day's data.");
			*pstrMsg += TempStr;
		}
		if (iOutOfOrder > 0) 
		{
			TempStr.Format("  %5d pts out of order.", iOutOfOrder);
			*pstrMsg += TempStr;
		}
		if (iInvalidData > 0) 
		{
			TempStr.Format("  %5d rec(s) with invalid times.",iInvalidData);
			*pstrMsg += TempStr;
		}
		if (iGamAdjust > 0) 
		{
			TempStr.Format("  %5d rec(s) with adjusted gamma values.",iGamAdjust); // 11-Aug-2005 SFK Made message more accurate
			*pstrMsg += TempStr;
		}
    }    
	//MessageBox (NULL, "exiting readdatafile", "heather's debug message", MB_OK|MB_ICONWARNING);
    return(true);
}
コード例 #23
0
ファイル: Utility.hpp プロジェクト: CtrlAltDefeat94/jmmserver
		uint16 operator()(uint16 value) const
		{
			return _byteswap_ushort(value);
		}
コード例 #24
0
void f() {
  (void)_byteswap_ushort(42); // expected-warning{{implicitly declaring library function '_byteswap_ushort}} \
  // expected-note{{include the header <stdlib.h> or explicitly provide a declaration for '_byteswap_ushort'}}
  (void)_byteswap_uint64(42LL); // expected-warning{{implicitly declaring library function '_byteswap_uint64}} \
  // expected-note{{include the header <stdlib.h> or explicitly provide a declaration for '_byteswap_uint64'}}
}
コード例 #25
0
ファイル: CDDAReader.cpp プロジェクト: Murder66/mpc-hc-master
bool CCDDAStream::Load(const WCHAR* fnw)
{
    CString path(fnw);

    int iDriveLetter = path.Find(_T(":\\")) - 1;
    int iTrackIndex = CString(path).MakeLower().Find(_T(".cda")) - 1;
    if (iDriveLetter < 0 || iTrackIndex <= iDriveLetter) {
        return false;
    }

    CString drive = CString(_T("\\\\.\\")) + path[iDriveLetter] + _T(":");
    while (iTrackIndex > 0 && _istdigit(path[iTrackIndex - 1])) {
        iTrackIndex--;
    }
    if (1 != _stscanf_s(path.Mid(iTrackIndex), _T("%d"), &iTrackIndex)) {
        return false;
    }

    if (m_hDrive != INVALID_HANDLE_VALUE) {
        CloseHandle(m_hDrive);
        m_hDrive = INVALID_HANDLE_VALUE;
    }

    m_hDrive = CreateFile(drive, GENERIC_READ, FILE_SHARE_READ, nullptr,
                          OPEN_EXISTING, FILE_ATTRIBUTE_READONLY | FILE_FLAG_SEQUENTIAL_SCAN, (HANDLE)nullptr);
    if (m_hDrive == INVALID_HANDLE_VALUE) {
        return false;
    }

    DWORD BytesReturned;
    if (!DeviceIoControl(m_hDrive, IOCTL_CDROM_READ_TOC, nullptr, 0, &m_TOC, sizeof(m_TOC), &BytesReturned, 0)
            || !(m_TOC.FirstTrack <= iTrackIndex && iTrackIndex <= m_TOC.LastTrack)) {
        CloseHandle(m_hDrive);
        m_hDrive = INVALID_HANDLE_VALUE;
        return false;
    }

    // MMC-3 Draft Revision 10g: Table 222 - Q Sub-channel control field
    m_TOC.TrackData[iTrackIndex - 1].Control &= 5;
    if (!(m_TOC.TrackData[iTrackIndex - 1].Control == 0 || m_TOC.TrackData[iTrackIndex - 1].Control == 1)) {
        CloseHandle(m_hDrive);
        m_hDrive = INVALID_HANDLE_VALUE;
        return false;
    }

    if (m_TOC.TrackData[iTrackIndex - 1].Control & 8) {
        m_header.frm.pcm.wf.nChannels = 4;
    }

    m_nStartSector = MSF2UINT(m_TOC.TrackData[iTrackIndex - 1].Address) - 150; //MSF2UINT(m_TOC.TrackData[0].Address);
    m_nStopSector = MSF2UINT(m_TOC.TrackData[iTrackIndex].Address) - 150;//MSF2UINT(m_TOC.TrackData[0].Address);

    m_llLength = LONGLONG(m_nStopSector - m_nStartSector) * RAW_SECTOR_SIZE;

    m_header.riff.hdr.chunkSize = (long)(m_llLength + sizeof(m_header) - 8);
    m_header.data.hdr.chunkSize = (long)(m_llLength);

    do {
        CDROM_READ_TOC_EX TOCEx;
        ZeroMemory(&TOCEx, sizeof(TOCEx));
        TOCEx.Format = CDROM_READ_TOC_EX_FORMAT_CDTEXT;
        TOCEx.SessionTrack = iTrackIndex;
        WORD size = 0;
        ASSERT(MINIMUM_CDROM_READ_TOC_EX_SIZE == sizeof(size));
        if (!DeviceIoControl(m_hDrive, IOCTL_CDROM_READ_TOC_EX, &TOCEx, sizeof(TOCEx), &size, sizeof(size), &BytesReturned, 0)) {
            break;
        }

        size = _byteswap_ushort(size) + sizeof(size);

        CAutoVectorPtr<BYTE> pCDTextData;
        if (!pCDTextData.Allocate(size)) {
            break;
        }
        ZeroMemory(pCDTextData, size);

        if (!DeviceIoControl(m_hDrive, IOCTL_CDROM_READ_TOC_EX, &TOCEx, sizeof(TOCEx), pCDTextData, size, &BytesReturned, 0)) {
            break;
        }

        size = (WORD)(BytesReturned - sizeof(CDROM_TOC_CD_TEXT_DATA));
        CDROM_TOC_CD_TEXT_DATA_BLOCK* pDesc = ((CDROM_TOC_CD_TEXT_DATA*)(BYTE*)pCDTextData)->Descriptors;

        CStringArray str[16];
        for (int i = 0; i < _countof(str); i++) {
            str[i].SetSize(1 + m_TOC.LastTrack);
        }
        CString last;

        for (int i = 0; size >= sizeof(CDROM_TOC_CD_TEXT_DATA_BLOCK); i++, size -= sizeof(CDROM_TOC_CD_TEXT_DATA_BLOCK), pDesc++) {
            if (pDesc->TrackNumber > m_TOC.LastTrack) {
                continue;
            }

            const int lenU = _countof(pDesc->Text);
            const int lenW = _countof(pDesc->WText);

            CString text = !pDesc->Unicode
                           ? CString(CStringA((CHAR*)pDesc->Text, lenU))
                           : CString(CStringW((WCHAR*)pDesc->WText, lenW));

            int tlen = text.GetLength();
            CString tmp = (tlen < 12 - 1)
                          ? (!pDesc->Unicode
                             ? CString(CStringA((CHAR*)pDesc->Text + tlen + 1, lenU - (tlen + 1)))
                             : CString(CStringW((WCHAR*)pDesc->WText + tlen + 1, lenW - (tlen + 1))))
                          : _T("");

            if (pDesc->PackType < 0x80 || pDesc->PackType >= 0x80 + 0x10) {
                continue;
            }
            pDesc->PackType -= 0x80;

            if (pDesc->CharacterPosition == 0) {
                str[pDesc->PackType][pDesc->TrackNumber] = text;
            } else { // pDesc->CharacterPosition <= 0xf since CharacterPosition is a 4-bit field
                if (pDesc->CharacterPosition < 0xf && !last.IsEmpty()) {
                    str[pDesc->PackType][pDesc->TrackNumber] = last + text;
                } else {
                    str[pDesc->PackType][pDesc->TrackNumber] += text;
                }
            }

            last = tmp;
        }

        m_discTitle = str[0][0];
        m_trackTitle = str[0][iTrackIndex];
        m_discArtist = str[1][0];
        m_trackArtist = str[1][iTrackIndex];
    } while (0);


    return true;
}
コード例 #26
0
ファイル: Parser_UTF16.c プロジェクト: dreamsxin/101_browser
ParseBlocker utf16_parse(
	void *in_out_pParserState, 
	void *in_pReadState, ByteStreamReadInterface_v4 in_readInterface, 
	void *in_pWriteState, ByteStreamWriteInterface_v4 in_writeInterface)
{
	UTF16_State *pUTF16State = (UTF16_State *) in_out_pParserState;
	extern const UnicodeCodePoint cReplacementCharacter;

	assert(in_readInterface.mpfRead != NULL);
	assert(in_readInterface.commonByteStreamInterface.mpfGetStatus != NULL);

	switch (pUTF16State->entryPoint)
	{
	case UTF16_EntryPoint_BeforeReading:
		goto Label_EntryPoint_BeforeReading;
	case UTF16_EntryPoint_BeforeWritingReplacementCharacterAndGotoBegin:
		goto Label_EntryPoint_BeforeWritingReplacementCharacterAndGotoBegin;
	case UTF16_EntryPoint_WriteCodePoint:
		goto Label_EntryPoint_WriteCodePoint;
	case UTF16_EntryPoint_WriteTwoTerminalReplacementCharacters:
		goto Label_EntryPoint_WriteTwoTerminalReplacementCharacters;
	case UTF16_EntryPoint_WriteTerminalReplacementCharacter:
		goto Label_EntryPoint_WriteTerminalReplacementCharacter;
	case UTF16_EntryPoint_Terminated:
		goto Label_EntryPoint_Terminated;
	}

	assert(false);

	while (1)
	{
		size_t rwCount;

		pUTF16State->readCount = 0;

Label_EntryPoint_BeforeReading:
		assert(pUTF16State->readCount < 2);
		rwCount = in_readInterface.mpfRead(in_pReadState, 
			((uint8_t *) &pUTF16State->currentWord) + pUTF16State->readCount, 
			2 - pUTF16State->readCount);

		assert(rwCount <= 2u - pUTF16State->readCount);

		pUTF16State->readCount += (uint8_t) rwCount;

		if (0 == pUTF16State->readCount)
		{
			ByteStreamStatus_v4 status = in_readInterface.
				commonByteStreamInterface.mpfGetStatus(in_pReadState);
			assert(ByteStreamStatus_OK != status);

			if (ByteStreamStatus_Terminated == status)
			{
				if (!pUTF16State->isSecondWord)
					goto terminate;
				else
					goto Label_EntryPoint_WriteTerminalReplacementCharacter;
			}
			else
			{
				pUTF16State->entryPoint = UTF16_EntryPoint_BeforeReading;
				return ParseBlocker_Reader;
			}
		}
		else if (1 == pUTF16State->readCount)
		{
			ByteStreamStatus_v4 status = in_readInterface.
				commonByteStreamInterface.mpfGetStatus(in_pReadState);
			assert(ByteStreamStatus_OK != status);

			if (ByteStreamStatus_Terminated == status)
			{
				if (!pUTF16State->isSecondWord || 
					!pUTF16State->bigEndian || 
					/*
					* Q: Why the bitwise and with 0xFF?
					* A: Because we read only one byte (the lower one), we don't 
					*    know what the value of the higher byte is. It can be
					*    anything.
					*/
					(0xDC <= (pUTF16State->currentWord & 0xFF) && 
					(pUTF16State->currentWord & 0xFF) <= 0xDF))
				{
					goto Label_EntryPoint_WriteTerminalReplacementCharacter;
				}
				else
				{
					assert(pUTF16State->isSecondWord);
					assert(pUTF16State->bigEndian);
					assert((pUTF16State->currentWord & 0xFF) < 0xDC || 
						(pUTF16State->currentWord & 0xFF) > 0xDF);

					goto Label_EntryPoint_WriteTwoTerminalReplacementCharacters;
				}
			}
			else
			{
				pUTF16State->entryPoint = UTF16_EntryPoint_BeforeReading;
				return ParseBlocker_Reader;
			}
		}
		else
		{
			assert(2 == pUTF16State->readCount);

			if (pUTF16State->bigEndian)
				pUTF16State->currentWord = _byteswap_ushort(pUTF16State->currentWord);

			if (!pUTF16State->isSecondWord)
			{
begin_of_S:
				if (pUTF16State->currentWord < 0xD800 || 
					pUTF16State->currentWord >= 0xDC00)
				{
					// 0xDC00 <= pUTF16State->currentWord < 0xE000: low surrogate
					if (0xDC00 <= pUTF16State->currentWord  && 
						pUTF16State->currentWord < 0xE000)
						pUTF16State->currentCodePoint = cReplacementCharacter;
					else
						pUTF16State->currentCodePoint = pUTF16State->currentWord;
				}
				else
				{
					assert(pUTF16State->currentWord >= 0xD800);
					assert(pUTF16State->currentWord <= 0xDBFF);

					pUTF16State->prevWord = pUTF16State->currentWord;
					pUTF16State->isSecondWord = true;

					continue;
				}
			}
			else
			{
				pUTF16State->isSecondWord = false;

				if (pUTF16State->currentWord < 0xDC00 || 0xDFFF < pUTF16State->currentWord)
				{
Label_EntryPoint_BeforeWritingReplacementCharacterAndGotoBegin:
					if (emitCodepoint(in_pWriteState, in_writeInterface, 
						cReplacementCharacter, &pUTF16State->entryPoint, 
						sizeof(UTF16_EntryPoint), 
						UTF16_EntryPoint_BeforeWritingReplacementCharacterAndGotoBegin))
						return ParseBlocker_Writer;

					goto begin_of_S;
				}
				else
				{
					// See http://unicode.org/faq/utf_bom.html#utf16-4
					pUTF16State->currentCodePoint = 
						(pUTF16State->prevWord << 10) + pUTF16State->currentWord + SURROGATE_OFFSET;
				}
			}

Label_EntryPoint_WriteCodePoint:
			if (emitCodepoint(in_pWriteState, in_writeInterface, 
				pUTF16State->currentCodePoint, &pUTF16State->entryPoint, 
				sizeof(UTF16_EntryPoint), 
				UTF16_EntryPoint_WriteCodePoint))
				return ParseBlocker_Writer;
		}
	}

Label_EntryPoint_WriteTwoTerminalReplacementCharacters:
	if (emitCodepoint(in_pWriteState, in_writeInterface, 
		cReplacementCharacter, &pUTF16State->entryPoint, 
		sizeof(UTF16_EntryPoint), 
		UTF16_EntryPoint_WriteTwoTerminalReplacementCharacters))
		return ParseBlocker_Writer;

Label_EntryPoint_WriteTerminalReplacementCharacter:
	assert(ByteStreamStatus_Terminated == in_readInterface.
		commonByteStreamInterface.mpfGetStatus(in_pReadState));

	if (emitCodepoint(in_pWriteState, in_writeInterface, 
		pUTF16State->currentCodePoint, &pUTF16State->entryPoint, 
		sizeof(UTF16_EntryPoint), 
		UTF16_EntryPoint_WriteTerminalReplacementCharacter))
		return ParseBlocker_Writer;

terminate:
	if (!ByteStreamStatus_Error == in_writeInterface.
		commonByteStreamInterface.mpfGetStatus(in_pWriteState))
		in_writeInterface.commonByteStreamInterface.mpfSetStatus(
		in_pWriteState, ByteStreamStatus_Terminated);

	pUTF16State->entryPoint = UTF16_EntryPoint_Terminated;

Label_EntryPoint_Terminated:
	assert(ByteStreamStatus_Terminated == in_readInterface.
		commonByteStreamInterface.mpfGetStatus(in_pReadState));
	return ParseBlocker_Neither;
}
コード例 #27
0
INT_PTR CALLBACK PhpSessionPropertiesDlgProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
    )
{
    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            ULONG sessionId = (ULONG)lParam;
            WINSTATIONINFORMATION winStationInfo;
            BOOLEAN haveWinStationInfo;
            WINSTATIONCLIENT clientInfo;
            BOOLEAN haveClientInfo;
            ULONG returnLength;
            PWSTR stateString;

            SetProp(hwndDlg, L"SessionId", UlongToHandle(sessionId));
            PhCenterWindow(hwndDlg, GetParent(hwndDlg));

            // Query basic session information

            haveWinStationInfo = WinStationQueryInformationW(
                NULL,
                sessionId,
                WinStationInformation,
                &winStationInfo,
                sizeof(WINSTATIONINFORMATION),
                &returnLength
                );

            // Query client information

            haveClientInfo = WinStationQueryInformationW(
                NULL,
                sessionId,
                WinStationClient,
                &clientInfo,
                sizeof(WINSTATIONCLIENT),
                &returnLength
                );

            if (haveWinStationInfo)
            {
                SetDlgItemText(hwndDlg, IDC_USERNAME,
                    PhaFormatString(L"%s\\%s", winStationInfo.Domain, winStationInfo.UserName)->Buffer);
            }

            SetDlgItemInt(hwndDlg, IDC_SESSIONID, sessionId, FALSE);

            if (haveWinStationInfo)
            {
                if (PhFindStringSiKeyValuePairs(
                    PhpConnectStatePairs,
                    sizeof(PhpConnectStatePairs),
                    winStationInfo.ConnectState,
                    &stateString
                    ))
                {
                    SetDlgItemText(hwndDlg, IDC_STATE, stateString);
                }
            }

            if (haveWinStationInfo && winStationInfo.LogonTime.QuadPart != 0)
            {
                SYSTEMTIME systemTime;
                PPH_STRING time;

                PhLargeIntegerToLocalSystemTime(&systemTime, &winStationInfo.LogonTime);
                time = PhFormatDateTime(&systemTime);
                SetDlgItemText(hwndDlg, IDC_LOGONTIME, time->Buffer);
                PhDereferenceObject(time);
            }

            if (haveWinStationInfo && winStationInfo.ConnectTime.QuadPart != 0)
            {
                SYSTEMTIME systemTime;
                PPH_STRING time;

                PhLargeIntegerToLocalSystemTime(&systemTime, &winStationInfo.ConnectTime);
                time = PhFormatDateTime(&systemTime);
                SetDlgItemText(hwndDlg, IDC_CONNECTTIME, time->Buffer);
                PhDereferenceObject(time);
            }

            if (haveWinStationInfo && winStationInfo.DisconnectTime.QuadPart != 0)
            {
                SYSTEMTIME systemTime;
                PPH_STRING time;

                PhLargeIntegerToLocalSystemTime(&systemTime, &winStationInfo.DisconnectTime);
                time = PhFormatDateTime(&systemTime);
                SetDlgItemText(hwndDlg, IDC_DISCONNECTTIME, time->Buffer);
                PhDereferenceObject(time);
            }

            if (haveWinStationInfo && winStationInfo.LastInputTime.QuadPart != 0)
            {
                SYSTEMTIME systemTime;
                PPH_STRING time;

                PhLargeIntegerToLocalSystemTime(&systemTime, &winStationInfo.LastInputTime);
                time = PhFormatDateTime(&systemTime);
                SetDlgItemText(hwndDlg, IDC_LASTINPUTTIME, time->Buffer);
                PhDereferenceObject(time);
            }

            if (haveClientInfo && clientInfo.ClientName[0] != 0)
            {
                WCHAR addressString[65];

                SetDlgItemText(hwndDlg, IDC_CLIENTNAME, clientInfo.ClientName);

                if (clientInfo.ClientAddressFamily == AF_INET6)
                {
                    struct in6_addr address;
                    ULONG i;
                    PUSHORT in;
                    PUSHORT out;

                    // IPv6 is special - the client address data is a reversed version of
                    // the real address.

                    in = (PUSHORT)clientInfo.ClientAddress;
                    out = (PUSHORT)address.u.Word;

                    for (i = 8; i != 0; i--)
                    {
                        *out = _byteswap_ushort(*in);
                        in++;
                        out++;
                    }

                    RtlIpv6AddressToString(&address, addressString);
                }
                else
                {
                    wcscpy_s(addressString, 65, clientInfo.ClientAddress);
                }

                SetDlgItemText(hwndDlg, IDC_CLIENTADDRESS, addressString);

                SetDlgItemText(hwndDlg, IDC_CLIENTDISPLAY,
                    PhaFormatString(L"%ux%u@%u", clientInfo.HRes,
                    clientInfo.VRes, clientInfo.ColorDepth)->Buffer
                    );
            }

            SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hwndDlg, IDOK), TRUE);
        }
        break;
    case WM_DESTROY:
        {
            RemoveProp(hwndDlg, L"SessionId");
        }
        break;
    case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
            case IDCANCEL:
            case IDOK:
                EndDialog(hwndDlg, IDOK);
                break;
            }
        }
        break;
    }

    return FALSE;
}
コード例 #28
0
ファイル: BinaryReaderBE.cpp プロジェクト: Refection/x360emu
u16 BinaryReaderBE::ReadUInt16()
{
	return _byteswap_ushort(BinaryReader::ReadUInt16());
}
unsigned long	readImplicitFile( ifstream& input , unsigned long offset , bool bigEndian , unsigned short target , DicomFileImage& fileInfo )
{
	unsigned long	currentOffset;
	unsigned long	size;
	unsigned short	group;
	unsigned short	element;
	unsigned int	lengthInt;
	char*			value;
	bool			found;
	

	
	try
	{
		currentOffset = offset;
		found = false;
		value = NULL;
		input.seekg(0,ifstream::end);
		size = input.tellg();
		input.seekg(offset,ifstream::beg);
		while( !input.eof()  &&  ( currentOffset = input.tellg() ) < size )
		{
			input.read((char*)&group,2);	// read group code
			input.read((char*)&element,2);	// read element code
			input.read((char*)&lengthInt,4);	// read value length

			// if the transfer syntax is Big Endian perform a byte swap
			if ( bigEndian )
			{
				group = _byteswap_ushort(group);
				element = _byteswap_ushort(element);
				lengthInt = _byteswap_ulong(lengthInt);
			}

			// termination condition update
			if ( group == target  &&  !found )	found = true;
			else if ( group != target  &&  found )	break;


			// if the length is undefined
			if ( lengthInt == 0xFFFFFFFF )
			{
				int	valueSize;



				// read unlimited text 
				value = readUnlimitedText(input,"",true,bigEndian,&valueSize);
				// update DicomFileImage information
				saveInformation(group,element,valueSize,value,fileInfo);
				delete[] value;
				value = NULL;
			}
			else	// if the length is defined
			{
				if ( lengthInt > 0 )
				{
					// read data of size equal to the defined length
					value = new char[lengthInt];
					input.read(value,lengthInt);
					saveInformation(group,element,sizeof(unsigned short),value,fileInfo);
					delete[] value;
					value = NULL;
				}
			}
		}
	}
	catch ( exception &e )
	{
		if ( value != NULL )
			delete[] value;

		throw e;
	}



	return currentOffset;
};
コード例 #30
-1
ファイル: ping.c プロジェクト: lei720/processhacker2
static NTSTATUS PhNetworkPingThreadStart(
    _In_ PVOID Parameter
    )
{
    HANDLE icmpHandle = INVALID_HANDLE_VALUE;
    ULONG icmpCurrentPingMs = 0;
    ULONG icmpCurrentPingTtl = 0;
    ULONG icmpReplyCount = 0;
    ULONG icmpReplyLength = 0;
    PVOID icmpReplyBuffer = NULL;
    PPH_STRING phVersion = NULL;
    PPH_BYTES icmpEchoBuffer = NULL;
    IP_OPTION_INFORMATION pingOptions =
    {
        255,         // Time To Live
        0,           // Type Of Service
        IP_FLAG_DF,  // IP header flags
        0            // Size of options data
    };

    PNETWORK_OUTPUT_CONTEXT context = (PNETWORK_OUTPUT_CONTEXT)Parameter;

    __try
    {
        // Query PH version.
        if ((phVersion = PhGetPhVersion()) == NULL)
            __leave;

        // Create ICMP echo buffer.
        if ((icmpEchoBuffer = PhFormatAnsiString("processhacker_%S_0x0D06F00D_x1", phVersion->Buffer)) == NULL)
            __leave;

        if (context->IpAddress.Type == PH_IPV6_NETWORK_TYPE)
        {
            SOCKADDR_IN6 icmp6LocalAddr = { 0 };
            SOCKADDR_IN6 icmp6RemoteAddr = { 0 };
            PICMPV6_ECHO_REPLY icmp6ReplyStruct = NULL;

            // Create ICMPv6 handle.
            if ((icmpHandle = Icmp6CreateFile()) == INVALID_HANDLE_VALUE)
                __leave;

            // Set Local IPv6-ANY address.
            icmp6LocalAddr.sin6_addr = in6addr_any;
            icmp6LocalAddr.sin6_family = AF_INET6;

            // Set Remote IPv6 address.
            icmp6RemoteAddr.sin6_addr = context->IpAddress.In6Addr;
            icmp6RemoteAddr.sin6_port = _byteswap_ushort((USHORT)context->NetworkItem->RemoteEndpoint.Port);

            // Allocate ICMPv6 message.
            icmpReplyLength = ICMP_BUFFER_SIZE(sizeof(ICMPV6_ECHO_REPLY), icmpEchoBuffer);
            icmpReplyBuffer = PhAllocate(icmpReplyLength);
            memset(icmpReplyBuffer, 0, icmpReplyLength);

            InterlockedIncrement(&context->PingSentCount);

            // Send ICMPv6 ping...
            icmpReplyCount = Icmp6SendEcho2(
                icmpHandle,
                NULL,
                NULL,
                NULL,
                &icmp6LocalAddr,
                &icmp6RemoteAddr,
                icmpEchoBuffer->Buffer,
                (USHORT)icmpEchoBuffer->Length,
                &pingOptions,
                icmpReplyBuffer,
                icmpReplyLength,
                context->MaxPingTimeout
                );

            icmp6ReplyStruct = (PICMPV6_ECHO_REPLY)icmpReplyBuffer;
            if (icmpReplyCount > 0 && icmp6ReplyStruct)
            {
                BOOLEAN icmpPacketSignature = FALSE;

                if (icmp6ReplyStruct->Status != IP_SUCCESS)
                {
                    InterlockedIncrement(&context->PingLossCount);
                }

                if (_memicmp(
                    icmp6ReplyStruct->Address.sin6_addr,
                    context->IpAddress.In6Addr.u.Word,
                    sizeof(icmp6ReplyStruct->Address.sin6_addr)
                    ) != 0)
                {
                    InterlockedIncrement(&context->UnknownAddrCount);
                }

                //if (icmp6ReplyStruct->DataSize == icmpEchoBuffer->MaximumLength)
                //{
                //    icmpPacketSignature = (_memicmp(
                //        icmpEchoBuffer->Buffer,
                //        icmp6ReplyStruct->Data,
                //        icmp6ReplyStruct->DataSize
                //        ) == 0);
                //}

                //if (icmpPacketSignature != TRUE)
                //{
                //    InterlockedIncrement(&context->HashFailCount);
                //}

                icmpCurrentPingMs = icmp6ReplyStruct->RoundTripTime;
                //icmpCurrentPingTtl = icmp6ReplyStruct->Options.Ttl;
            }
            else
            {
                InterlockedIncrement(&context->PingLossCount);
            }
        }
        else
        {
            IPAddr icmpLocalAddr = 0;
            IPAddr icmpRemoteAddr = 0;
            PICMP_ECHO_REPLY icmpReplyStruct = NULL;

            // Create ICMPv4 handle.
            if ((icmpHandle = IcmpCreateFile()) == INVALID_HANDLE_VALUE)
                __leave;

            // Set Local IPv4-ANY address.
            icmpLocalAddr = in4addr_any.s_addr;

            // Set Remote IPv4 address.
            icmpRemoteAddr = context->IpAddress.InAddr.s_addr;

            // Allocate ICMPv4 message.
            icmpReplyLength = ICMP_BUFFER_SIZE(sizeof(ICMP_ECHO_REPLY), icmpEchoBuffer);
            icmpReplyBuffer = PhAllocate(icmpReplyLength);
            memset(icmpReplyBuffer, 0, icmpReplyLength);

            InterlockedIncrement(&context->PingSentCount);

            // Send ICMPv4 ping...
            //if (WindowsVersion > WINDOWS_VISTA)
            //{
            //    // Vista SP1 and up we can specify the source address:
            //    icmpReplyCount = IcmpSendEcho2Ex(
            //        icmpHandle,
            //        NULL,
            //        NULL,
            //        NULL,
            //        icmpLocalAddr,
            //        icmpRemoteAddr,
            //        icmpEchoBuffer->Buffer,
            //        icmpEchoBuffer->MaximumLength,
            //        &pingOptions,
            //        icmpReplyBuffer,
            //        icmpReplyLength,
            //        context->MaxPingTimeout
            //        );
            //}

            icmpReplyCount = IcmpSendEcho2(
                icmpHandle,
                NULL,
                NULL,
                NULL,
                icmpRemoteAddr,
                icmpEchoBuffer->Buffer,
                (USHORT)icmpEchoBuffer->Length,
                &pingOptions,
                icmpReplyBuffer,
                icmpReplyLength,
                context->MaxPingTimeout
                );

            icmpReplyStruct = (PICMP_ECHO_REPLY)icmpReplyBuffer;

            if (icmpReplyStruct && icmpReplyCount > 0)
            {
                BOOLEAN icmpPacketSignature = FALSE;

                if (icmpReplyStruct->Status != IP_SUCCESS)
                {
                    InterlockedIncrement(&context->PingLossCount);
                }

                if (icmpReplyStruct->Address != context->IpAddress.InAddr.s_addr)
                {
                    InterlockedIncrement(&context->UnknownAddrCount);
                }

                if (icmpReplyStruct->DataSize == icmpEchoBuffer->Length)
                {
                    icmpPacketSignature = (_memicmp(
                        icmpEchoBuffer->Buffer,
                        icmpReplyStruct->Data,
                        icmpReplyStruct->DataSize
                        ) == 0);
                }

                icmpCurrentPingMs = icmpReplyStruct->RoundTripTime;
                icmpCurrentPingTtl = icmpReplyStruct->Options.Ttl;

                if (!icmpPacketSignature)
                {
                    InterlockedIncrement(&context->HashFailCount);
                }
            }
            else
            {
                InterlockedIncrement(&context->PingLossCount);
            }
        }

        InterlockedIncrement(&context->PingRecvCount);

        if (context->PingMinMs == 0 || icmpCurrentPingMs < context->PingMinMs)
            context->PingMinMs = icmpCurrentPingMs;
        if (icmpCurrentPingMs > context->PingMaxMs)
            context->PingMaxMs = icmpCurrentPingMs;

        context->CurrentPingMs = icmpCurrentPingMs;

        PhAddItemCircularBuffer_ULONG(&context->PingHistory, icmpCurrentPingMs);
    }
    __finally
    {
        if (phVersion)
        {
            PhDereferenceObject(phVersion);
        }

        if (icmpEchoBuffer)
        {
            PhDereferenceObject(icmpEchoBuffer);
        }

        if (icmpHandle != INVALID_HANDLE_VALUE)
        {
            IcmpCloseHandle(icmpHandle);
        }

        if (icmpReplyBuffer)
        {
            PhFree(icmpReplyBuffer);
        }
    }

    PostMessage(context->WindowHandle, WM_PING_UPDATE, 0, 0);

    return STATUS_SUCCESS;
}