예제 #1
0
파일: Package.cpp 프로젝트: Patuti/seed
const void *Package::GetFile(const char *filename, u32 *filesize)
{
	const void *file = NULL;

	const u8 *ptr = static_cast<const u8 *>(stFile.GetData());
	SKIP_STRUCT(ObjectHeader, ptr);
	u32 foo;
	READ_U32(foo, ptr);

	for (u32 i = 0; i < iFilesAmount; i++)
	{
		u32 offset = 0;
		u32 size = 0;
		char *name = NULL;

		READ_U32(offset, ptr);
		READ_U32(size, ptr);
		READ_STR(name, ptr);

		if (!STRCMP(name, filename))
		{
			const u8 *filePtr = static_cast<const u8 *>(stFile.GetData());
			file = &filePtr[offset];

			*filesize = size;
			break;
		}
	}

	return file;
}
예제 #2
0
파일: Font.cpp 프로젝트: doorxp/seed
BOOL Font::Load(const char *filename, ResourceManager *res, IMemoryPool *pool)
{
	ASSERT_NULL(filename);
	ASSERT_NULL(res);
	ASSERT_NULL(pool);

	if (this->Unload())
	{
		this->pFilename = filename;
		this->pRes = res;
		this->pPool = pool;

		stFile.Close();
		SECURITY_CHECK(pFileSystem->Open(filename, &stFile, pool), "Could not open font file.");
		const u8 *ptr = static_cast<const u8 *>(stFile.GetData());
		ObjectHeader *block = NULL;
		READ_STRUCT(block, ObjectHeader, ptr);
		SECURITY_CHECK(seed_validate_block(&stFile, block, FONT_OBJECT_MAGIC, FONT_OBJECT_VERSION), "Invalid block header for font.");

		READ_F32(this->fTracking, ptr);
		READ_F32(this->fSpacing, ptr);
		READ_F32(this->fSpaceWidth, ptr);

	/*
		const char *file = NULL;
		READ_STR(file, ptr);
		ASSERT_NULL(file);

		const char *ext = NULL;
		READ_STR(ext, ptr);
	*/
		u32 file = 0;
		READ_U32(file, ptr);

		u32 ext = 0;
		READ_U32(ext, ptr);

		if (ext != SEED_INVALID_ID /*&& pSystem->GetLanguage() != Seed::en_US*/)
		{
			File extf;
			if (pFileSystem->Open(_F(ext), &extf, pool))
			{
				extf.Close();
				this->mFontExt.Load(_F(ext), res, pool);
				this->pGlyphs = pDictionary->GetGlyphTable(&this->iTotalGlyphs);
			}
		}

		this->mFont.Load(_F(file), res, pool);
		this->fHeight	= mFont.GetHeight();
		this->fWidth	= mFont.GetWidth();

		this->bLoaded	= TRUE;
	}

	return bLoaded;
}
예제 #3
0
void SoundSource::Load(const char *filename, ResourceManager *res, IMemoryPool *pool)
{
	ASSERT_NULL(filename);
	ASSERT_NULL(pool);
	ASSERT_NULL(res);

	if (pSoundSystem->IsInitialized())
	{
		this->Unload();

		/* Open file .sound */
		SECURITY_CHECK(pFileSystem->Open(filename, &stFile, pool), "Sound object couldn't be opened");

		const u8 *ptr = static_cast<const u8 *>(stFile.GetData());
		ObjectHeader *block = NULL;
		READ_STRUCT(block, ObjectHeader, ptr);
		SECURITY_CHECK(seed_validate_block(&stFile, block, SOUND_OBJECT_MAGIC, SOUND_OBJECT_VERSION), "Invalid block header for sound.");

		u32 volume = 0;
		READ_U32(volume, ptr);
		this->fVolume  = volume / 100.0f;

		u32 flags = 0;
		READ_U32(flags, ptr);
		this->bLoop = ((flags & 0x01) == 0x01); // FIXME

		const char *fname = NULL;
		READ_STR(fname, ptr);
		ASSERT_NULL(fname);

		/* Get the resource */
		pSound = static_cast<Sound *>(res->Get(fname, Seed::ObjectSound, pool));

		if (iSource)
			alDeleteSources(1, &iSource);
		ALenum err = alGetError();

		alGenSources(1, &iSource);
		err = alGetError();
		if (err != AL_NO_ERROR)
			Info(TAG "Could not create OpenAL Source: %4x", err);

		const ALint *buffer = static_cast<const ALint *>(pSound->GetData());

		alSourcef(iSource, AL_PITCH, 1.0f);
		alSource3f(iSource, AL_POSITION, cPosition.x, cPosition.y, cPosition.z);
		alSource3f(iSource, AL_VELOCITY, cVelocity.x, cVelocity.y, cVelocity.z);
		alSourcei(iSource, AL_LOOPING, this->bLoop);
		alSourcei(iSource, AL_BUFFER, *buffer);
		this->SetVolume(this->fVolume);
	}
}
예제 #4
0
ssize_t microchip_udp_read(UDP_SOCKET socket, uint8_t* buf, size_t len, uint32_t* addr, uint16_t* port) {
    ssize_t rlen;
#if NABTO_LOG_CHECK(NABTO_LOG_SEVERITY_TRACE)
    UDP_SOCKET_INFO* debug;
    uint32_t sourceIp;
#endif
    if (UDPIsGetReady(socket)) {
#if NABTO_LOG_CHECK(NABTO_LOG_SEVERITY_TRACE)
        debug = &UDPSocketInfo[socket];
        READ_U32(sourceIp, &debug->remote.remoteNode.IPAddr.Val);
#endif

        unabto_microchip_arp_add_resolved(&(UDPSocketInfo[socket].remote.remoteNode));
        //        *addr = ntohl(UDPSocketInfo[socket].remote.remoteNode.IPAddr.Val);
        WRITE_U32(addr, UDPSocketInfo[socket].remote.remoteNode.IPAddr.Val);
        *port = UDPSocketInfo[socket].remotePort;
        rlen = (ssize_t) UDPGetArray(buf, len);
        NABTO_LOG_TRACE(("UDP read length: %i, %" PRIu16 " <- " PRIip ":%" PRIu16, rlen, debug->localPort, MAKE_IP_PRINTABLE(sourceIp), debug->remotePort));

        NABTO_LOG_BUFFER(NABTO_LOG_SEVERITY_TRACE, ("UDP in datagram"), buf, rlen);

        return rlen;
    }

    return 0;
}
예제 #5
0
파일: lba_pci.c 프로젝트: 020gzh/linux
static int mercury_cfg_write(struct pci_bus *bus, unsigned int devfn, int pos, int size, u32 data)
{
	struct lba_device *d = LBA_DEV(parisc_walk_tree(bus->bridge));
	void __iomem *data_reg = d->hba.base_addr + LBA_PCI_CFG_DATA;
	u32 local_bus = (bus->parent == NULL) ? 0 : bus->busn_res.start;
	u32 tok = LBA_CFG_TOK(local_bus,devfn);

	if ((pos > 255) || (devfn > 255))
		return -EINVAL;

	DBG_CFG("%s(%x+%2x) <- 0x%x (c)\n", __func__, tok, pos, data);

	LBA_CFG_TR4_ADDR_SETUP(d, tok | pos);
	switch(size) {
	case 1:
		WRITE_REG8 (data, data_reg + (pos & 3));
		break;
	case 2:
		WRITE_REG16(data, data_reg + (pos & 2));
		break;
	case 4:
		WRITE_REG32(data, data_reg);
		break;
	}

	/* flush posted write */
	lba_t32 = READ_U32(d->hba.base_addr + LBA_PCI_CFG_ADDR);
	return 0;
}
bool readPacket(unabto_api_stream_t stream, uint8_t** packet, size_t* packetLength) {
    uint8_t lengthBuffer[sizeof(uint32_t)];
    uint32_t len;
    uint8_t* buf;
    if (unabto_api_stream_read_all(stream, lengthBuffer, sizeof(uint32_t)) != UNABTO_API_OK) {
        NABTO_LOG_TRACE(("failed to read length of event"));
        return false;
    }
    
    unabto_api_lock();
    READ_U32(len, lengthBuffer);
    unabto_api_unlock();
    
    //if (len > 100) {
        NABTO_LOG_TRACE(("packet length: %i", len));
        //}

    buf = (uint8_t*)pvPortMalloc(len);
    if (buf == NULL) {
        NABTO_LOG_TRACE(("Receive Event failed to allocate %ul bytes.", len));
        NABTO_LOG_BUFFER(NABTO_LOG_SEVERITY_TRACE, ("Length buffer"),lengthBuffer,sizeof(uint32_t));
        return false;
    }

    if (unabto_api_stream_read_all(stream, buf, len) != UNABTO_API_OK) {
        NABTO_LOG_TRACE(("failed to read event"));
        vPortFree(buf);
        return false;
    }

    *packetLength = len;
    *packet = buf;
    return true;
}
예제 #7
0
파일: Package.cpp 프로젝트: Patuti/seed
BOOL Package::Load(const void *data, ResourceManager *res, IMemoryPool *pool)
{
	UNUSED(res);
	UNUSED(pool);

	this->pPool = pool;
	this->pRes = res;

	//BOOL result = FALSE;
	const u8 *ptr = static_cast<const u8 *>(data);

	stFile.SetData(data);
	ObjectHeader *block = NULL;
	READ_STRUCT(block, ObjectHeader, ptr);

	SECURITY_CHECK(seed_validate_block(&stFile, block, PACKAGE_OBJECT_MAGIC, PACKAGE_OBJECT_VERSION), "Invalid block header for font.");
	READ_U32(iFilesAmount, ptr);

	if (!iFilesAmount)
	{
		Log(TAG "Package %s is empty.", stFile.GetName());
		pFileSystem->Close(&stFile);
		bLoaded = FALSE;
	}
	else
	{
		bLoaded = TRUE;
	}

	return bLoaded;
}
예제 #8
0
bool unabto_util_test(void) {

    uint8_t buf[] = {0x00,0x00,0x00,0x00,0x12, 0x34, 0x56, 0x78};
    uint32_t* buf2 = (uint32_t*)buf;
    uint32_t testNr;
    uint16_t testu16;
    bool ret = true;
    READ_U32(testNr, buf+4);
    if (testNr != 305419896) {       // 0x12345678 in host byte order
        NABTO_LOG_TRACE(("testNr: %i", testNr));
        ret = false;
    }
    
    READ_U32(testNr, buf2+1);
    if (testNr != 0x12345678) {
        NABTO_LOG_TRACE(("testNr: %i", testNr));
        ret = false;
    }

    READ_U16(testu16, buf+4);
    if (testu16 != 4660) {
        NABTO_LOG_TRACE(("testu16 read failed %i", testu16));
        ret = false;
    }

    WRITE_U32(buf, 0x01020304);
    if (buf[0] != 0x01 ||
        buf[1] != 0x02 || 
        buf[2] != 0x03 ||
        buf[3] != 0x04) {
        NABTO_LOG_TRACE(("WRITE u32 failed"));
        ret = false;
    }
    
    WRITE_U16(buf, 0x0506);
    if (buf[0] != 0x05 || 
        buf[1] != 0x06) {
        NABTO_LOG_TRACE(("WRITE u16 failed"));
        ret = false;
    }

    return ret;
    
}
예제 #9
0
파일: Dictionary.cpp 프로젝트: Patuti/seed
INLINE void Dictionary::SetLanguage(Seed::eLanguage lang, IMemoryPool *pool)
{
	// REQUIREMENT:
	/*
	The first file from filelist MUST BE strings.dict.
	This is because strings.dict is unique for each language, and we must know it's ID because
	currently we can only open "localized" files BY ID.

	A possible fix for this is that Dictionary can have an array of possible filenames to try and then open.
	*/
	this->Reset();
	this->pPool = pool;

	const char *file = _F(0);
	if (!file || !pFileSystem->Open(file, &stFile, pool))
	{
		Info(TAG, "strings.dict not found, skipping dictionary.");
		return;
	}

	const u8 *ptr = static_cast<const u8 *>(stFile.GetData());
	ObjectHeader *block = NULL;
	READ_STRUCT(block, ObjectHeader, ptr);
	SECURITY_CHECK(seed_validate_block(&stFile, block, DICT_OBJECT_MAGIC, DICT_OBJECT_VERSION), "Invalid block header for dictionary.");

	u32 code = 0;
	READ_U32(code, ptr);
	ASSERT_MSG(static_cast<u32>(lang) == code, "Dictionary has an invalid language code.");
	this->iLang = lang;

	READ_U32(this->iTotalGlyphs, ptr);
	READ_U32(this->iTotalStrings, ptr);

	if (this->iTotalGlyphs)
		this->pGlyphs = reinterpret_cast<const u16 *>(ptr);

	if (this->iTotalStrings)
		this->pStrings = reinterpret_cast<const u16 *>(ptr + iTotalGlyphs + iTotalGlyphs);

	// we can alloc a table for strings using a structure {u32, u16 *}
	// and map them on load too but I will not do it. Or, I can do
	// this table inside the file and update the pointers (take care
	// of 32bit-64bit portability) on load.
}
예제 #10
0
파일: IFileSystem.cpp 프로젝트: Patuti/seed
void IFileSystem::BuildFileTable()
{
	if (!pFile)
	{
		pFile = New(File(FILESYSTEM_TABLE_FILE));
		//ASSERT_NULL(pFile->pData);
		if (pFile->pData)
		{
			const u8 *ptr = static_cast<const u8 *>(pFile->pData);
			ObjectHeader *block = NULL;
			READ_STRUCT(block, ObjectHeader, ptr);

			SECURITY_CHECK(seed_validate_block(pFile, block, FST_OBJECT_MAGIC, FST_OBJECT_VERSION), "Invalid block header for filelist.");
			READ_U32(iLangCount, ptr);
			READ_U32(iFileCount, ptr);

			pFileTable = (StringFile *)pMemoryManager->Alloc(iLangCount * iFileCount * sizeof(const char *));
			for (u32 l = 0; l < iLangCount; l++)
			{
				u32 lang = 0;
				READ_U32(lang, ptr);
				pLangTable[lang] = &pFileTable[l * iFileCount];

				for (u32 s = 0; s < iFileCount; s++)
				{
					char *str = NULL;
					READ_STR(str, ptr);
					pFileTable[(l*iFileCount)+s] = str;
				}
			}

			pOldTable = pCurrentTable = pLangTable[pSystem->GetLanguage()];
			pSystem->AddListener(this);
		}
		else
		{
			Info(TAG "Could not find %s, not using localization file table and file by id feature.", FILESYSTEM_TABLE_FILE);
		}
	}
}
예제 #11
0
/*--[guid2string]--------------------------------------------------------------
 |
 | Careful - uses a static string.  Will be awkward if called the same
 | time in a statement.
 | Assumes GUID is in Little Endian Order
 |
*/
const char * guid2string(U8 * guid)
{
    static char guid_buffer[7+8+4+4+4+12+1];

    sprintf(guid_buffer, "{%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
        (U32)READ_U32(guid), (U16)READ_U16((guid+4)),
        (U16)READ_U16((guid+6)),
        (U8)*(guid+8), (U8)*(guid+9), /*-*/
        (U8)*(guid+10), (U8)*(guid+11), (U8)*(guid+12),
        (U8)*(guid+13), (U8)*(guid+14),
        (U8)*(guid+15));
   return guid_buffer;
}
예제 #12
0
파일: Dictionary.cpp 프로젝트: Patuti/seed
const u16 *Dictionary::GetString(u32 stringId, u32 *outLen) const
{
	ASSERT_MSG(stringId != SEED_INVALID_ID, "Error: stringId is invalid. Rebuild your assets.");
	const void *ret = NULL;

	if (stringId < this->iTotalStrings)
	{
		u32 len = 0;
		const u8 *ptr = reinterpret_cast<const u8 *>(this->pStrings);
		READ_U32(len, ptr);
		for (u32 i = 0; i < stringId; i++)
		{
			ptr += ((len + 1) * sizeof(u16));
			READ_U32(len, ptr);
		}

		if (outLen)
			*outLen = len;

		ret = reinterpret_cast<const void *>(ptr);
	}

	return (const WideString)ret;
}
예제 #13
0
bool platform_initialize() {
    uint32_t lastIp;
    nabto_stamp_t timeout;

    // Configure TCP/IP stack stuff
    AppConfig.Flags.bIsDHCPEnabled = true;
    AppConfig.Flags.bInConfigMode = true;
    AppConfig.MyIPAddr.Val = MY_DEFAULT_IP_ADDR_BYTE1 | MY_DEFAULT_IP_ADDR_BYTE2 << 8ul | MY_DEFAULT_IP_ADDR_BYTE3 << 16ul | MY_DEFAULT_IP_ADDR_BYTE4 << 24ul;
    AppConfig.DefaultIPAddr.Val = AppConfig.MyIPAddr.Val;
    AppConfig.MyMask.Val = MY_DEFAULT_MASK_BYTE1 | MY_DEFAULT_MASK_BYTE2 << 8ul | MY_DEFAULT_MASK_BYTE3 << 16ul | MY_DEFAULT_MASK_BYTE4 << 24ul;
    AppConfig.DefaultMask.Val = AppConfig.MyMask.Val;
    AppConfig.MyGateway.Val = MY_DEFAULT_GATE_BYTE1 | MY_DEFAULT_GATE_BYTE2 << 8ul | MY_DEFAULT_GATE_BYTE3 << 16ul | MY_DEFAULT_GATE_BYTE4 << 24ul;
    AppConfig.PrimaryDNSServer.Val = MY_DEFAULT_PRIMARY_DNS_BYTE1 | MY_DEFAULT_PRIMARY_DNS_BYTE2 << 8ul | MY_DEFAULT_PRIMARY_DNS_BYTE3 << 16ul | MY_DEFAULT_PRIMARY_DNS_BYTE4 << 24ul;
    AppConfig.SecondaryDNSServer.Val = MY_DEFAULT_SECONDARY_DNS_BYTE1 | MY_DEFAULT_SECONDARY_DNS_BYTE2 << 8ul | MY_DEFAULT_SECONDARY_DNS_BYTE3 << 16ul | MY_DEFAULT_SECONDARY_DNS_BYTE4 << 24ul;

    TickInit();
    
    StackInit();

    
    unabto_microchip_arp_reset();
    

// Wait for dhcp.
    lastIp = AppConfig.MyIPAddr.Val;

#if ENABLE_DHCP_BUG_WORKAROUND == 1
    nabtoSetFutureStamp(&timeout, 5000);
#endif

    NABTO_LOG_DEBUG(("Acquiring IP from DHCP server..."));

    while (lastIp == AppConfig.MyIPAddr.Val) {
        StackTask();

#if ENABLE_DHCP_BUG_WORKAROUND == 1
        if (nabtoIsStampPassed(&timeout)) {
            Reset();
        }
#endif
    }

    READ_U32(lastIp, &AppConfig.MyIPAddr.Val);

    NABTO_LOG_DEBUG(("Got IP from DHCP server: "PRIip, MAKE_IP_PRINTABLE(lastIp)));

    return true;
}
예제 #14
0
ssize_t microchip_udp_write(UDP_SOCKET socket, const uint8_t* buf, size_t len, uint32_t addr, uint16_t port) {
    NODE_INFO remoteInfo;
    ssize_t size;
    uint32_t addrNetworkOrder;
#if NABTO_LOG_CHECK(NABTO_LOG_SEVERITY_TRACE)
    UDP_SOCKET_INFO* debug;
    uint32_t sourceIp;
#endif

    if (addr == 0 || port == 0) {
        return 0;
    }
    
    WRITE_U32(&addrNetworkOrder, addr);

    if (unabto_microchip_arp_resolve(addrNetworkOrder, &remoteInfo.MACAddr)) {
        remoteInfo.IPAddr.Val = addrNetworkOrder;
        memcpy((void*) &UDPSocketInfo[socket].remote.remoteNode, (void*) &remoteInfo, sizeof (NODE_INFO));
    } else {
        if (UDPSocketInfo[socket].remote.remoteNode.IPAddr.Val != addrNetworkOrder) {
            return 0;
        }
        // the arp resolve is not finished but the socket already knows
        // a mac address, lets just use it.
    }
    if (UDPIsPutReady(socket) >= len) {
#if NABTO_LOG_CHECK(NABTO_LOG_SEVERITY_TRACE)
        debug = &UDPSocketInfo[socket];
        READ_U32(sourceIp, &debug->remote.remoteNode.IPAddr.Val);
#endif

        UDPSocketInfo[socket].remotePort = port;
        size = (ssize_t) UDPPutArray((BYTE*) buf, len);
        UDPFlush();
        NABTO_LOG_TRACE(("UDP write length: %i, %" PRIu16 " -> " PRIip ":%" PRIu16, size, debug->localPort, MAKE_IP_PRINTABLE(sourceIp), debug->remotePort));

        NABTO_LOG_BUFFER(NABTO_LOG_SEVERITY_TRACE, ("UDP out datagram"), buf, len);

        return size;
    } else {
        NABTO_LOG_TRACE(("Socket was not put ready %i", socket));
    }

    return 0;
}
예제 #15
0
파일: dhcp.c 프로젝트: bonnefoa/junkie
static enum proto_parse_status dhcp_parse(struct parser *parser, struct proto_info *parent, unsigned way, uint8_t const *payload, size_t cap_len, size_t wire_len, struct timeval const *now, size_t tot_cap_len, uint8_t const *tot_packet)
{
    struct dhcp const *dhcp = (struct dhcp *)payload;

    // Sanity Checks

    // Check that we have at least the size of an DHCP packet for IP protocol
    if (wire_len < sizeof(*dhcp)) return PROTO_PARSE_ERR;
    // And that we have enough data to parse it
    if (cap_len < sizeof(*dhcp)) return PROTO_TOO_SHORT;

    if (0 != memcmp(dhcp->cookie, &magic_cookie, sizeof(magic_cookie))) {
        SLOG(LOG_DEBUG, "Bad magic Cookie");
        return PROTO_PARSE_ERR;
    }

    struct dhcp_proto_info info;
    proto_info_ctor(&info.info, parser, parent, wire_len, 0);
    info.opcode = READ_U8(&dhcp->op);
    if (info.opcode != BOOTP_REQUEST && info.opcode != BOOTP_REPLY) {
        SLOG(LOG_DEBUG, "Unknown DHCP opcode (%u)", info.opcode);
        return PROTO_PARSE_ERR;
    }
    uint8_t const hlen = READ_U8(&dhcp->hlen);
    if (hlen > sizeof(dhcp->chaddr)) {
        SLOG(LOG_DEBUG, "Bad hlen in DHCP (%u)", hlen);
        return PROTO_PARSE_ERR;
    }
    info.xid = READ_U32N(&dhcp->xid);
    info.set_values = 0;
    uint32_t const addr = READ_U32(&dhcp->yiaddr);
    if (addr) {
        info.set_values |= DHCP_CLIENT_SET;
        ip_addr_ctor_from_ip4(&info.client, addr);
    }
    uint8_t const htype = READ_U8(&dhcp->htype);
    info.hw_addr_is_eth = htype == 1;
    if (info.hw_addr_is_eth) {
        if (hlen != sizeof(info.client_mac)) {
            SLOG(LOG_DEBUG, "Bad hlen (%u) for Eth type", hlen);
            return PROTO_PARSE_ERR;
        }
        memcpy(info.client_mac, dhcp->chaddr, sizeof(info.client_mac));
    } else {
        memset(info.client_mac, 0, sizeof(info.client_mac));
    }

    memcpy(info.server_name, dhcp->sname, sizeof(info.server_name));

    SLOG(LOG_DEBUG, "New DHCP %s", dhcp_opcode_2_str(info.opcode));

    // parse options
    info.msg_type = 0;  // mandatory
    struct cursor c;
    cursor_ctor(&c, dhcp->options, cap_len - offsetof(struct dhcp, options));
    while (c.cap_len >= 2) {
        uint8_t const type = cursor_read_u8(&c);
        uint8_t const len  = cursor_read_u8(&c);
        if (c.cap_len < len) {
            SLOG(LOG_DEBUG, "Cannot read options");
            return PROTO_PARSE_ERR;
        }
        switch (type) {
            case 53:    // msg type
                if (len != 1) {
                    SLOG(LOG_DEBUG, "Bad length (%"PRIu8") for msg type DHCP option", len);
                    return PROTO_PARSE_ERR;
                }
                info.msg_type = cursor_read_u8(&c);
                if (info.msg_type > DHCP_INFORM) {
                    SLOG(LOG_DEBUG, "Bad DHCP msg type (%u)", info.msg_type);
                    return PROTO_PARSE_ERR;
                }
                break;
            default:
                cursor_drop(&c, len);
                break;
        }
    }
    if (0 == info.msg_type) {   // not found
        SLOG(LOG_DEBUG, "DHCP msg without msg type");
        return PROTO_PARSE_ERR;
    }

    return proto_parse(NULL, &info.info, way, NULL, 0, 0, now, tot_cap_len, tot_packet);
}
예제 #16
0
int CDVDOverlayCodecTX3G::Decode(DemuxPacket *pPacket)
{
  if (m_pOverlay)
    SAFE_RELEASE(m_pOverlay);

  m_pOverlay = new CDVDOverlayText();
  CDVDOverlayCodec::GetAbsoluteTimes(m_pOverlay->iPTSStartTime, m_pOverlay->iPTSStopTime, pPacket, m_pOverlay->replace);

  // do not move this. READ_XXXX macros modify pos.
  uint8_t  *pos = pPacket->pData;
  uint8_t  *end = pPacket->pData + pPacket->iSize;

  // Parse the packet as a TX3G TextSample.
  // Look for a single StyleBox ('styl') and 
  // read all contained StyleRecords.
  // Ignore all other box types.
  // NOTE: Buffer overflows on read are not checked.
  // ALSO: READ_XXXX/SKIP_XXXX macros will modify pos.
  LEN_CHECK(2);
  uint16_t textLength = READ_U16();
  LEN_CHECK(textLength);
  uint8_t *text = READ_ARRAY(textLength);

  int numStyleRecords = 0;
  // reserve one more style slot for broken encoders

  XUTILS::auto_buffer bgnStyle(textLength+1);
  XUTILS::auto_buffer endStyle(textLength+1);

  memset(bgnStyle.get(), 0, textLength+1);
  memset(endStyle.get(), 0, textLength+1);

  int bgnColorIndex = 0, endColorIndex = 0;
  uint32_t textColorRGBA = m_textColor;
  while (pos < end)
  {
    // Read TextSampleModifierBox
    LEN_CHECK(4);
    uint32_t size = READ_U32();
    if (size == 0)
      size = pos - end;   // extends to end of packet
    if (size == 1)
    {
      CLog::Log(LOGDEBUG, "CDVDOverlayCodecTX3G: TextSampleModifierBox has unsupported large size" );
      break;
    }
    LEN_CHECK(4);
    uint32_t type = READ_U32();
    if (type == FOURCC("uuid"))
    {
      CLog::Log(LOGDEBUG, "CDVDOverlayCodecTX3G: TextSampleModifierBox has unsupported extended type" );
      break;
    }

    if (type == FOURCC("styl"))
    {
      // Found a StyleBox. Parse the contained StyleRecords
      if ( numStyleRecords != 0 )
      {
        CLog::Log(LOGDEBUG, "CDVDOverlayCodecTX3G: found additional StyleBoxes on subtitle; skipping" );
        LEN_CHECK(size);
        SKIP_ARRAY(size);
        continue;
      }

      LEN_CHECK(2);
      numStyleRecords = READ_U16();
      for (int i = 0; i < numStyleRecords; i++)
      {
        StyleRecord curRecord;
        LEN_CHECK(12);
        curRecord.bgnChar         = READ_U16();
        curRecord.endChar         = READ_U16();
        curRecord.fontID          = READ_U16();
        curRecord.faceStyleFlags  = READ_U8();
        curRecord.fontSize        = READ_U8();
        curRecord.textColorRGBA   = READ_U32();
        // clamp bgnChar/bgnChar to textLength,
        // we alloc enough space above and this
        // fixes borken encoders that do not handle
        // endChar correctly.
        if (curRecord.bgnChar > textLength)
          curRecord.bgnChar = textLength;
        if (curRecord.endChar > textLength)
          curRecord.endChar = textLength;

        bgnStyle.get()[curRecord.bgnChar] |= curRecord.faceStyleFlags;
        endStyle.get()[curRecord.endChar] |= curRecord.faceStyleFlags;
        bgnColorIndex = curRecord.bgnChar;
        endColorIndex = curRecord.endChar;
        textColorRGBA = curRecord.textColorRGBA;
      }
    }
    else
    {
      // Found some other kind of TextSampleModifierBox. Skip it.
      LEN_CHECK(size);
      SKIP_ARRAY(size);
    }
  }

  // Copy text to out and add HTML markup for the style records
  int charIndex = 0;
  std::string strUTF8;
  // index over textLength chars to include broken encoders,
  // so we pickup closing styles on broken encoders
  for (pos = text, end = text + textLength; pos <= end; pos++)
  {
    if ((*pos & 0xC0) == 0x80)
    {
      // Is a non-first byte of a multi-byte UTF-8 character
      strUTF8.append((const char*)pos, 1);
      continue;   // ...without incrementing 'charIndex'
    }

    uint8_t bgnStyles = bgnStyle.get()[charIndex];
    uint8_t endStyles = endStyle.get()[charIndex];

    // [B] or [/B] -> toggle bold on and off
    // [I] or [/I] -> toggle italics on and off
    // [COLOR ffab007f] or [/COLOR] -> toggle color on and off
    // [CAPS <option>]  or [/CAPS]  -> toggle capatilization on and off

    if (endStyles & BOLD)
      strUTF8.append("[/B]");
    if (endStyles & ITALIC)
      strUTF8.append("[/I]");
    // we do not support underline
    //if (endStyles & UNDERLINE)
    //  strUTF8.append("[/U]");
    if (endColorIndex == charIndex && textColorRGBA != m_textColor)
      strUTF8.append("[/COLOR]");

    // invert the order from above so we bracket the text correctly.
    if (bgnColorIndex == charIndex && textColorRGBA != m_textColor)
      strUTF8 += StringUtils::Format("[COLOR %8x]", textColorRGBA);
    // we do not support underline
    //if (bgnStyles & UNDERLINE)
    //  strUTF8.append("[U]");
    if (bgnStyles & ITALIC)
      strUTF8.append("[I]");
    if (bgnStyles & BOLD)
      strUTF8.append("[B]");

    // stuff the UTF8 char
    strUTF8.append((const char*)pos, 1);

    // this is a char index, not a byte index.
    charIndex++;
  }
  
  if (strUTF8.empty())
    return OC_BUFFER;

  if (strUTF8[strUTF8.size()-1] == '\n')
    strUTF8.erase(strUTF8.size()-1);

  // add a new text element to our container
  m_pOverlay->AddElement(new CDVDOverlayText::CElementText(strUTF8.c_str()));

  return OC_OVERLAY;
}
예제 #17
0
파일: Button.cpp 프로젝트: doorxp/seed
BOOL Button::Load(const char *filename, ResourceManager *res, IMemoryPool *pool)
{
	ASSERT_NULL(filename);
	ASSERT_NULL(res);
	ASSERT_NULL(pool);

	if (this->Unload())
	{
		pRes = res;
		pPool = pool;
		pFilename = filename;

		/* Isso deveria ser um objeto como SpriteObject -> ButtonObject, para que o .button seja reaproveitado. */
		SECURITY_CHECK(pFileSystem->Open(filename, &stFile, pool), "Could not open button file.");

		const u8 *ptr = static_cast<const u8 *>(stFile.GetData());
		ObjectHeader *block = NULL;
		READ_STRUCT(block, ObjectHeader, ptr);
		SECURITY_CHECK(seed_validate_block(&stFile, block, BUTTON_OBJECT_MAGIC, BUTTON_OBJECT_VERSION), "Invalid block header for button.");

		/*
		We check if any property is already set so we WON'T change it. This will allow the user to do Set* things befora doing the Load.
		If the user want that the object properties are loaded it will need call Reset before Load.
		*/
		if (!iId)
			READ_U32(iId, ptr);

		if (!iPriority)
			READ_U32(iPriority, ptr);

		f32 x = 0;
		f32 y = 0;

		READ_F32(x, ptr);
		READ_F32(y, ptr);

		if (!this->GetX())
			this->SetX(x);

		if (!this->GetY())
			this->SetY(y);

		u32 masktype = 0;
		READ_U32(masktype, ptr);

		u32 labelid = 0;
		READ_U32(labelid, ptr);

		//const char *sprite = NULL;
		//READ_STR(sprite, ptr);
		u32 sprFileId = 0;
		READ_U32(sprFileId, ptr);
		if (sprFileId != SEED_INVALID_ID)
			this->SetSprite(_F(sprFileId), res, pool);

		u32 mask = 0;
		if (masktype == 1)
		{
			READ_U32(mask, ptr);
			if (mask != SEED_INVALID_ID && eButtonCollision == CollisionNone)
				this->SetMask(_F(mask), res, pool);
		}

		bLoaded = TRUE;
	}

	return bLoaded;
}
예제 #18
0
static inline S32 READ_S32( U8* buffer )
{
    return (S32)READ_U32( buffer );
}
예제 #19
0
static inline F32 READ_F32( U8* buffer )
{
    U32 floatData = READ_U32( buffer );
    return *((F32*)&floatData);
}
예제 #20
0
/*--[lit_i_read_directory]-----------------------------------------------------
 |
 | This reads the directory chunks from the piece and converts the list into
 | entry elements in the lit_file structure.
 |
*/
int lit_i_read_directory(lit_file * litfile, U8 * piece, int piece_size)
{
    U8      * p = NULL;
    int     nEntries, nRemaining, nChunks, chunk, idx, sizeChunk;
    entry_type * entry, * prev;

    if (!piece || (READ_U32(piece) != IFCM_TAG)) {
        lit_error(ERR_R,
           "Header Piece #3 is not the main directory! (TAG=%08lx)",
           (piece)?(READ_U32(piece)):0);
        return E_LIT_FORMAT_ERROR;
    }
    sizeChunk = READ_INT32(piece + 8);
    nChunks = READ_INT32(piece + 24);

    if ((32 + (nChunks * sizeChunk)) !=  piece_size) {
        lit_error(ERR_R, "IFCM HEADER (%d chunks of %d bytes) != %d total.",
        nChunks, sizeChunk, piece_size - 32);
        return E_LIT_FORMAT_ERROR;
    }
    prev = NULL;
    for (chunk = 0; chunk < nChunks; chunk++)
    {
        p = piece + 32 + (chunk * sizeChunk);

        /* This can either be AOLL or AOLI.
         * AOLI isn't useful for reading */
        if (READ_U32(p) != AOLL_TAG)  continue;

        nRemaining = READ_INT32(p + 4);
        if (nRemaining >= sizeChunk) {
            lit_error(ERR_R,
"AOLL remaining count is NEGATIVE! (%d of %d) %x\n",
            (int)nRemaining, (int)sizeChunk, (int)nRemaining);
            return E_LIT_FORMAT_ERROR;
        }
        nRemaining = sizeChunk - (nRemaining + 48);

        nEntries = READ_U16(p + sizeChunk - 2);

        /* Sometimes, the nEntries doesn't get written. When this happens,
         * I don't know how many to read.  Fortunately, there is "nRemaining",
         * and if everything is working fine, read_entry will consume JUST
         * enough bytes */
        if (!nEntries) nEntries = 65535;

        p += 48;
        if (nRemaining < 0) return E_LIT_FORMAT_ERROR;
        for (idx = 0; idx < nEntries; idx ++) {
            if (nRemaining <= 0) break;
            entry = read_entry(&p, &nRemaining);
            if (!entry) {
                return E_LIT_FORMAT_ERROR;
            }
            if (!prev) {
                litfile->entry = entry;
                prev = entry;
            } else {
                prev->next = entry;
                prev = entry;
            }
        }
    }
    return 0;
}
예제 #21
0
bool CXBTFReader::Open(const std::string& fileName)
{
  m_fileName = fileName;

#ifdef TARGET_WINDOWS
  std::wstring strPathW;
  g_charsetConverter.utf8ToW(CSpecialProtocol::TranslatePath(m_fileName), strPathW, false);
  m_file = _wfopen(strPathW.c_str(), L"rb");
#else
  m_file = fopen(m_fileName.c_str(), "rb");
#endif
  if (m_file == NULL)
  {
    return false;
  }

  char magic[4];
  READ_STR(magic, 4, m_file);

  if (strncmp(magic, XBTF_MAGIC, sizeof(magic)) != 0)
  {
    return false;
  }

  char version[1];
  READ_STR(version, 1, m_file);

  if (strncmp(version, XBTF_VERSION, sizeof(version)) != 0)
  {
    return false;
  }

  unsigned int nofFiles;
  READ_U32(nofFiles, m_file);
  for (unsigned int i = 0; i < nofFiles; i++)
  {
    CXBTFFile file;
    unsigned int u32;
    uint64_t u64;

    READ_STR(file.GetPath(), 256, m_file);
    READ_U32(u32, m_file);
    file.SetLoop(u32);

    unsigned int nofFrames;
    READ_U32(nofFrames, m_file);

    for (unsigned int j = 0; j < nofFrames; j++)
    {
      CXBTFFrame frame;

      READ_U32(u32, m_file);
      frame.SetWidth(u32);
      READ_U32(u32, m_file);
      frame.SetHeight(u32);
      READ_U32(u32, m_file);
      frame.SetFormat(u32);
      READ_U64(u64, m_file);
      frame.SetPackedSize(u64);
      READ_U64(u64, m_file);
      frame.SetUnpackedSize(u64);
      READ_U32(u32, m_file);
      frame.SetDuration(u32);
      READ_U64(u64, m_file);
      frame.SetOffset(u64);

      file.GetFrames().push_back(frame);
    }

    m_xbtf.GetFiles().push_back(file);

    m_filesMap[file.GetPath()] = file;
  }

  // Sanity check
  int64_t pos = ftell(m_file);
  if (pos != (int64_t)m_xbtf.GetHeaderSize())
  {
    printf("Expected header size (%" PRId64") != actual size (%" PRId64")\n", m_xbtf.GetHeaderSize(), pos);
    return false;
  }

  return true;
}
nabto_connect* nabto_init_connection(nabto_packet_header* hdr, uint32_t* nsi, uint32_t* ec, bool isLocal)
{
    uint8_t  type;
    uint8_t  flags;   /* NP_PAYLOAD_IPX_FLAG_* */
    nabto_connect* con;

    const uint8_t* end = nabtoCommunicationBuffer + hdr->len;
    uint8_t* ptr = nabtoCommunicationBuffer + hdr->hlen;
    uint16_t res;
    uint16_t ipxPayloadLength;
    
    ipxPayloadLength = nabto_rd_payload(ptr, end, &type); ptr += SIZE_PAYLOAD_HEADER;
    
    *nsi = 0;
    *ec  = 0;

    if ((ipxPayloadLength != IPX_PAYLOAD_LENGTH_WITHOUT_NSI) && 
        (ipxPayloadLength != IPX_PAYLOAD_LENGTH_WITH_NSI) && 
        (ipxPayloadLength != IPX_PAYLOAD_LENGTH_FULL_NSI)) {
        NABTO_LOG_TRACE(("Illegal payload size in U_CONNECT request from GSP: %" PRIu16 " %" PRIu8, ipxPayloadLength, type));
        return 0;
    }
    if (type != NP_PAYLOAD_TYPE_IPX) {
        NABTO_LOG_TRACE(("Illegal payload type in U_CONNECT request from GSP: %" PRIu16 " %" PRIu8, ipxPayloadLength, type));
        return 0;
    }
    
    if (ipxPayloadLength == IPX_PAYLOAD_LENGTH_WITH_NSI || 
        ipxPayloadLength == IPX_PAYLOAD_LENGTH_FULL_NSI) {
        READ_U32(*nsi, ptr + 13);
        NABTO_LOG_TRACE(("IPX payload with NSI (SPNSI=%" PRIu32 ")", *nsi));
    } else {
        *nsi = fresh_nsi();
        NABTO_LOG_TRACE(("IPX payload without NSI (fresh NSI=%" PRIu32 ")", *nsi));
    }

    if (*nsi == 0) {
        NABTO_LOG_ERROR(("Trying to create connection with spnsi == 0"));
        return 0;
    }

    if (nabto_find_connection(*nsi)) {
        NABTO_LOG_DEBUG((PRInsi " A connection already exists this is probably a retransmission", MAKE_NSI_PRINTABLE(0, *nsi, 0)));
        *ec = NOTIFY_CONNECT_OK;
        return 0;
    }

    con = nabto_init_connection_real(*nsi);

    if (con == 0) {
        if (nabto_find_connection(*nsi)) {
            NABTO_LOG_DEBUG((PRInsi " U_CONNECT: A connection resource is already pending new connection", MAKE_NSI_PRINTABLE(0, *nsi, 0)));
        } else {
            NABTO_LOG_INFO((PRInsi " U_CONNECT: No connection resources free for new connection", MAKE_NSI_PRINTABLE(0, *nsi, 0)));
#if NABTO_ENABLE_DEVICE_BUSY_AS_FATAL
            NABTO_LOG_FATAL((PRInsi " U_CONNECT: No free connections configured to be considered fatal", MAKE_NSI_PRINTABLE(0, *nsi, 0)));
#endif
        }
        *ec = NOTIFY_ERROR_BUSY_MICRO;
        return 0;
    }

    NABTO_LOG_DEBUG((PRInsi " U_CONNECT: Connecting using record %i", MAKE_NSI_PRINTABLE(0, *nsi, 0), nabto_connection_index(con)));
    READ_U32(con->cp.privateEndpoint.addr, ptr +  0);
    READ_U16(con->cp.privateEndpoint.port, ptr +  4);
    READ_U32(con->cp.globalEndpoint.addr, ptr +  6);
    READ_U16(con->cp.globalEndpoint.port, ptr + 10);
    READ_U8(flags,                ptr + 12); /* the final word (4 bytes) has been read already (nsi) */
    con->noRendezvous = (flags & NP_PAYLOAD_IPX_FLAG_NO_RENDEZVOUS) ? 1 : 0;
    con->cpEqual      = EP_EQUAL(con->cp.privateEndpoint, con->cp.globalEndpoint);
    con->cpAsync      = (flags & NP_PAYLOAD_IPX_FLAG_CP_ASYNC) ? 1 : 0;
    con->clientNatType      = (flags & NP_PAYLOAD_IPX_NAT_MASK);
    con->isLocal      = isLocal;
    NABTO_LOG_INFO((PRInsi " U_CONNECT: cp.private: " PRIep " cp.global: " PRIep ", noRdv=%" PRIu8 ", cpeq=%" PRIu8 ", asy=%" PRIu8 ", NATType: %" PRIu8 , MAKE_NSI_PRINTABLE(0, *nsi, 0), MAKE_EP_PRINTABLE(con->cp.privateEndpoint), MAKE_EP_PRINTABLE(con->cp.globalEndpoint), con->noRendezvous, con->cpEqual, con->cpAsync, con->clientNatType));

#if NABTO_ENABLE_TCP_FALLBACK
    if (ipxPayloadLength == IPX_PAYLOAD_LENGTH_FULL_NSI) {
        memcpy(con->consi, ptr+17, 8);
        con->nsico = con->consi;
        READ_U32(con->cpnsi, ptr+25);
    }
#endif

    ptr += ipxPayloadLength;  //IPX_PAYLOAD_LENGTH_WITHOUT_NSI or IPX_PAYLOAD_LENGTH_WITH_NSI
        
    con->clientId[0]  = 0;
    res = nabto_rd_payload(ptr, end, &type);
    if (type == NP_PAYLOAD_TYPE_CP_ID) {
        uint8_t idType;
        ptr += SIZE_PAYLOAD_HEADER;
        if (res > 0) {
            READ_U8(idType, ptr); ++ptr; --res;
            if (idType == 1) { // 1 == EMAIL
                size_t sz = res;
                if (sz >= sizeof(con->clientId)) {
                    if (sizeof(con->clientId) > 1) {
                        NABTO_LOG_WARN(("Client ID truncated"));
                    }
                    sz = sizeof(con->clientId) - 1;
                }
                if (sz) {
                    memcpy(con->clientId, (const void*) ptr, sz);
                }
                con->clientId[sz] = 0;
            }
        }
        NABTO_LOG_TRACE(("Connection opened from '%s' (to %s)", con->clientId, nmc.nabtoMainSetup.id));
        ptr += res;
    }
#if NABTO_ENABLE_CONNECTION_ESTABLISHMENT_ACL_CHECK
    if (!allow_client_access(con)) {
        *ec = NOTIFY_ERROR_CP_ACCESS;
        goto init_error;
    }
#endif

#if NABTO_ENABLE_TCP_FALLBACK
    {
        uint8_t* gatewayPtr = ptr;
        res = nabto_rd_payload(ptr, end, &type);
        if (type == NP_PAYLOAD_TYPE_GW && ipxPayloadLength == IPX_PAYLOAD_LENGTH_FULL_NSI) {
            uint8_t* gatewayEndPtr;
            size_t idLength;
            NABTO_LOG_TRACE(("The connect contains a gateway payload."));
            ptr += res + SIZE_PAYLOAD_HEADER;
            gatewayPtr += SIZE_PAYLOAD_HEADER;
            gatewayEndPtr = ptr;

            READ_U32(con->fallbackHost.addr, gatewayPtr); gatewayPtr+=4;
            READ_U16(con->fallbackHost.port, gatewayPtr); gatewayPtr+=2;
            // skip the nsi
            gatewayPtr+=4;
        
            idLength = gatewayEndPtr-gatewayPtr;
            if (idLength != 20) {
                NABTO_LOG_FATAL(("The id length should be 20 bytes. bytes=%" PRIsize, idLength));
                // todo
            } 
            memcpy(con->gatewayId, gatewayPtr, 20);
            con->hasTcpFallbackCapabilities = true;
        }
    }
#endif


#if NABTO_ENABLE_UCRYPTO
    if (nmc.context.nonceSize == NONCE_SIZE) {
        uint8_t* decryptedDataStart;
        uint16_t decryptedDataLength;
        if (!unabto_connection_verify_and_decrypt_connect_packet(hdr, &decryptedDataStart, &decryptedDataLength)) {
            NABTO_LOG_TRACE(("Failed to read crypto payload in U_CONNECT"));
        } else {
            unabto_crypto_reinit_d(&con->cryptoctx, nmc.nabtoMainSetup.cryptoSuite, decryptedDataStart, decryptedDataLength);
        }
    } else
#endif
    {
        NABTO_LOG_TRACE(("########    U_CONNECT without crypto payload"));
        unabto_crypto_reinit_d(&con->cryptoctx, CRYPT_W_NULL_DATA, 0, 0);
    }


    con->timeOut = CONNECTION_TIMEOUT;
    nabtoSetFutureStamp(&con->stamp, 20000); /* give much extra time during initialisation */

    if (!verify_connection_encryption(con)) {
        goto init_crypto_error;
    }

    if (con->cpEqual) {
        NABTO_LOG_DEBUG((PRInsi " U_CONNECT: addr:" PRIep " rendezvous:%" PRIu8, MAKE_NSI_PRINTABLE(0, *nsi, 0), MAKE_EP_PRINTABLE(con->cp.privateEndpoint), !con->noRendezvous));
    } else {
        NABTO_LOG_DEBUG((PRInsi " U_CONNECT: private:" PRIep ", global:" PRIep " rendezvous:%" PRIu8, MAKE_NSI_PRINTABLE(0, *nsi, 0), MAKE_EP_PRINTABLE(con->cp.privateEndpoint), MAKE_EP_PRINTABLE(con->cp.globalEndpoint), !con->noRendezvous));
    }

    NABTO_LOG_INFO(("Connection opened from '%s' (to %s). Encryption code %i", con->clientId, nmc.nabtoMainSetup.id, con->cryptoctx.code));

    return con;

init_crypto_error:
    *ec = NOTIFY_ERROR_ENCR_MISMATCH;

#if NABTO_ENABLE_CONNECTION_ESTABLISHMENT_ACL_CHECK
init_error:
    nabto_release_connection(con);
#endif

    return 0;
}
예제 #23
0
int CDVDOverlayCodecTX3G::Decode(BYTE* data, int size, double pts, double duration)
{
  if (m_pOverlay)
    SAFE_RELEASE(m_pOverlay);

  m_pOverlay = new CDVDOverlayText();
  m_pOverlay->iPTSStartTime = pts;
  m_pOverlay->iPTSStopTime  = pts + duration;

  // do not move this. READ_XXXX macros modify pos.
  uint8_t  *pos = data;
  uint8_t  *end = pos + size;

  // Parse the packet as a TX3G TextSample.
  // Look for a single StyleBox ('styl') and 
  // read all contained StyleRecords.
  // Ignore all other box types.
  // NOTE: Buffer overflows on read are not checked.
  // ALSO: READ_XXXX/SKIP_XXXX macros will modify pos.
  uint16_t textLength = READ_U16();
  uint8_t *text = READ_ARRAY(textLength);

  int numStyleRecords = 0;
  uint8_t *bgnStyle   = (uint8_t*)calloc(textLength, 1);
  uint8_t *endStyle   = (uint8_t*)calloc(textLength, 1);
  int bgnColorIndex = 0, endColorIndex = 0;
  uint32_t textColorRGBA = m_textColor;
  while (pos < end)
  {
    // Read TextSampleModifierBox
    uint32_t size = READ_U32();
    if (size == 0)
      size = pos - end;   // extends to end of packet
    if (size == 1)
    {
      CLog::Log(LOGDEBUG, "CDVDOverlayCodecTX3G: TextSampleModifierBox has unsupported large size" );
      break;
    }
    uint32_t type = READ_U32();
    if (type == FOURCC("uuid"))
    {
      CLog::Log(LOGDEBUG, "CDVDOverlayCodecTX3G: TextSampleModifierBox has unsupported extended type" );
      break;
    }

    if (type == FOURCC("styl"))
    {
      // Found a StyleBox. Parse the contained StyleRecords
      if ( numStyleRecords != 0 )
      {
        CLog::Log(LOGDEBUG, "CDVDOverlayCodecTX3G: found additional StyleBoxes on subtitle; skipping" );
        SKIP_ARRAY(size);
        continue;
      }

      numStyleRecords = READ_U16();
      for (int i = 0; i < numStyleRecords; i++)
      {
        StyleRecord curRecord;
        curRecord.bgnChar         = READ_U16();
        curRecord.endChar         = READ_U16();
        curRecord.fontID          = READ_U16();
        curRecord.faceStyleFlags  = READ_U8();
        curRecord.fontSize        = READ_U8();
        curRecord.textColorRGBA   = READ_U32();

        bgnStyle[curRecord.bgnChar] |= curRecord.faceStyleFlags;
        endStyle[curRecord.endChar] |= curRecord.faceStyleFlags;
        bgnColorIndex = curRecord.bgnChar;
        endColorIndex = curRecord.endChar;
        textColorRGBA = curRecord.textColorRGBA;
      }
    }
    else
    {
      // Found some other kind of TextSampleModifierBox. Skip it.
      SKIP_ARRAY(size);
    }
  }

  // Copy text to out and add HTML markup for the style records
  int charIndex = 0;
  CStdStringA strUTF8;
  for (pos = text, end = text + textLength; pos < end; pos++)
  {
    if ((*pos & 0xC0) == 0x80)
    {
      // Is a non-first byte of a multi-byte UTF-8 character
      strUTF8.append((const char*)pos, 1);
      continue;   // ...without incrementing 'charIndex'
    }

    uint8_t bgnStyles = bgnStyle[charIndex];
    uint8_t endStyles = endStyle[charIndex];

    // [B] or [/B] -> toggle bold on and off
    // [I] or [/I] -> toggle italics on and off
    // [COLOR ffab007f] or [/COLOR] -> toggle color on and off
    // [CAPS <option>]  or [/CAPS]  -> toggle capatilization on and off

    if (endStyles & BOLD)
      strUTF8.append("[/B]");
    if (endStyles & ITALIC)
      strUTF8.append("[/I]");
    // we do not support underline
    //if (endStyles & UNDERLINE)
    //  strUTF8.append("[/U]");
    if (endColorIndex == charIndex && textColorRGBA != m_textColor)
      strUTF8.append("[/COLOR]");

    // invert the order from above so we bracket the text correctly.
    if (bgnColorIndex == charIndex && textColorRGBA != m_textColor)
      strUTF8.AppendFormat("[COLOR %8x]", textColorRGBA);
    // we do not support underline
    //if (bgnStyles & UNDERLINE)
    //  strUTF8.append("[U]");
    if (bgnStyles & ITALIC)
      strUTF8.append("[I]");
    if (bgnStyles & BOLD)
      strUTF8.append("[B]");

    // stuff the UTF8 char
    strUTF8.append((const char*)pos, 1);

    // this is a char index, not a byte index.
    charIndex++;
  }
  
  free(bgnStyle);
  free(endStyle);
    
  if (strUTF8.IsEmpty())
    return OC_BUFFER;

  if (strUTF8[strUTF8.size()-1] == '\n')
    strUTF8.Delete(strUTF8.size()-1);

  // add a new text element to our container
  m_pOverlay->AddElement(new CDVDOverlayText::CElementText(strUTF8.c_str()));

  return OC_OVERLAY;
}
예제 #24
0
static void cifs_proto_info_ctor(struct cifs_proto_info *info, struct parser *parser, struct proto_info *parent, size_t header, size_t payload, struct cifs_hdr const * cifshdr)
{
    proto_info_ctor(&info->info, parser, parent, header, payload);
    info->command = READ_U8(&cifshdr->command);
    info->status = READ_U32(&cifshdr->status);
}
예제 #25
0
static hb_buffer_t *tx3g_decode_to_utf8( hb_buffer_t *in )
{
    uint8_t *pos = in->data;
    uint8_t *end = in->data + in->size;
    
    uint16_t numStyleRecords = 0;
    
    uint8_t *startStyle;
    uint8_t *endStyle;
    
    /*
     * Parse the packet as a TX3G TextSample.
     * 
     * Look for a single StyleBox ('styl') and read all contained StyleRecords.
     * Ignore all other box types.
     * 
     * NOTE: Buffer overflows on read are not checked.
     */
    uint16_t textLength = READ_U16();
    uint8_t *text = READ_ARRAY(textLength);
    startStyle = calloc( textLength, 1 );
    endStyle = calloc( textLength, 1 );
    while ( pos < end ) {
        /*
         * Read TextSampleModifierBox
         */
        uint32_t size = READ_U32();
        if ( size == 0 ) {
            size = pos - end;   // extends to end of packet
        }
        if ( size == 1 ) {
            hb_log( "dectx3gsub: TextSampleModifierBox has unsupported large size" );
            break;
        }
        uint32_t type = READ_U32();
        if ( type == FOURCC("uuid") ) {
            hb_log( "dectx3gsub: TextSampleModifierBox has unsupported extended type" );
            break;
        }
        
        if ( type == FOURCC("styl") ) {
            // Found a StyleBox. Parse the contained StyleRecords
            
            if ( numStyleRecords != 0 ) {
                hb_log( "dectx3gsub: found additional StyleBoxes on subtitle; skipping" );
                SKIP_ARRAY(size);
                continue;
            }
            
            numStyleRecords = READ_U16();
            
            int i;
            for (i=0; i<numStyleRecords; i++) {
                StyleRecord curRecord;
                curRecord.startChar         = READ_U16();
                curRecord.endChar           = READ_U16();
                curRecord.fontID            = READ_U16();
                curRecord.faceStyleFlags    = READ_U8();
                curRecord.fontSize          = READ_U8();
                curRecord.textColorRGBA     = READ_U32();
                
                startStyle[curRecord.startChar] |= curRecord.faceStyleFlags;
                endStyle[curRecord.endChar]     |= curRecord.faceStyleFlags;
            }
        } else {
            // Found some other kind of TextSampleModifierBox. Skip it.
            SKIP_ARRAY(size);
        }
    }
    
    /*
     * Copy text to output buffer, and add HTML markup for the style records
     */
    int maxOutputSize = textLength + (numStyleRecords * NUM_FACE_STYLE_FLAGS * (MAX_OPEN_TAG_SIZE + MAX_CLOSE_TAG_SIZE));
    hb_buffer_t *out = hb_buffer_init( maxOutputSize );
    if ( out == NULL )
        goto fail;
    uint8_t *dst = out->data;
    int charIndex = 0;
    for ( pos = text, end = text + textLength; pos < end; pos++ ) {
        if (IS_10xxxxxx(*pos)) {
            // Is a non-first byte of a multi-byte UTF-8 character
            WRITE_CHAR(*pos);
            continue;   // ...without incrementing 'charIndex'
        }
        
        uint8_t plusStyles = startStyle[charIndex];
        uint8_t minusStyles = endStyle[charIndex];
        
        if (minusStyles & UNDERLINE)
            WRITE_END_TAG('u');
        if (minusStyles & ITALIC)
            WRITE_END_TAG('i');
        if (minusStyles & BOLD)
            WRITE_END_TAG('b');
        
        if (plusStyles & BOLD)
            WRITE_START_TAG('b');
        if (plusStyles & ITALIC)
            WRITE_START_TAG('i');
        if (plusStyles & UNDERLINE)
            WRITE_START_TAG('u');
        
        WRITE_CHAR(*pos);
        charIndex++;
    }
    
    // Trim output buffer to the actual amount of data written
    out->size = dst - out->data;
    
    // Copy metadata from the input packet to the output packet
    out->s.start = in->s.start;
    out->s.stop = in->s.stop;
    
fail:
    free( startStyle );
    free( endStyle );
    
    return out;
}
bool rendezvous_event(message_event* event, nabto_packet_header* hdr)
{
    uint8_t*          end = nabtoCommunicationBuffer + hdr->len;
    uint16_t          res = hdr->hlen;

    uint8_t*          ptr;
    uint8_t           type;
    nabto_endpoint  epUD;
    nabto_connect*  con   = 0;
    nabto_endpoint  src;
    uint32_t        interval = 5000;

    src = event->udpMessage.peer;
    NABTO_LOG_TRACE((PRInsi " Received from " PRIep " seq=%" PRIu16, MAKE_NSI_PRINTABLE(0, hdr->nsi_sp, 0), MAKE_EP_PRINTABLE(src), hdr->seq));

    ptr = nabtoCommunicationBuffer + res;
    res = nabto_rd_payload(ptr, end, &type); ptr += SIZE_PAYLOAD_HEADER;
    if (res != 6 || type != NP_PAYLOAD_TYPE_EP) {
        NABTO_LOG_TRACE(("Can't read first EP"));
        return false;
    }
    READ_U32(epUD.addr, ptr); ptr += 4;
    READ_U16(epUD.port, ptr); ptr += 2;
    res = nabto_rd_payload(ptr, end, &type); ptr += SIZE_PAYLOAD_HEADER;
    if (res == 6 && type == NP_PAYLOAD_TYPE_EP) {
        // The second EP is not neccessary since we read the destination ep from the udp packet.
        
        ptr += 6;
        res = nabto_rd_payload(ptr, end, &type); ptr += SIZE_PAYLOAD_HEADER;
        if (res == 4 && type == NP_PAYLOAD_TYPE_NONCE) {
            READ_U32(interval, ptr);
            NABTO_LOG_TRACE((PRInsi " Read interval from packet: %" PRIu32, MAKE_NSI_PRINTABLE(0, hdr->nsi_sp, 0), interval));
            if (interval == 0) {
                NABTO_LOG_WARN(("Interval was 0, setting to 5000"));
                interval = 5000;
            }
        }
    }

    con  = nabto_find_connection(hdr->nsi_sp);

    if (!con) {
        NABTO_LOG_ERROR(("Connection was not found, nsi: %i", hdr->nsi_sp));
    } else {
        if (hdr->seq == 0) {
            send_rendezvous_socket(event->udpMessage.socket, con, 1, &src, &epUD);
        } else if (hdr->seq == 1) {
            send_rendezvous_socket(event->udpMessage.socket, con, 2, &src, &epUD);
            if (!conclude_connection(con, &src, interval)) {
                return false;
            }
        } else if (hdr->seq == 2) {
            if (!conclude_connection(con, &src, interval)) {
                return false;
            }
        } else {
            NABTO_LOG_ERROR(("Invalid Sequence Number"));
        }
    }
    return false;
}
예제 #27
0
static void SHA256_Transform(sha256_ctx* context, const sha2_word32* data) {
	sha2_word32	a, b, c, d, e, f, g, h, s0, s1;
	sha2_word32	T1, T2, *W256;
	uint8_t		j;

	W256 = (sha2_word32*)context->buffer;

	/* Initialize registers with the prev. intermediate value */
	a = context->state[0];
	b = context->state[1];
	c = context->state[2];
	d = context->state[3];
	e = context->state[4];
	f = context->state[5];
	g = context->state[6];
	h = context->state[7];
  

	j = 0;
	do {
		/* Copy data while converting to host byte order */
        READ_U32(W256[j],data++);

		/* Apply the SHA-256 compression function to update a..h */
		T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j];
		T2 = Sigma0_256(a) + Maj(a, b, c);
		h = g;
		g = f;
		f = e;
		e = d + T1;
		d = c;
		c = b;
		b = a;
		a = T1 + T2;

		j++;
	} while (j < 16);

	do {
		/* Part of the message block expansion: */
		s0 = W256[(j+1)&0x0f];
		s0 = sigma0_256(s0);
		s1 = W256[(j+14)&0x0f];	
		s1 = sigma1_256(s1);

		/* Apply the SHA-256 compression function to update a..h */
		T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0);
		T2 = Sigma0_256(a) + Maj(a, b, c);
		h = g;
		g = f;
		f = e;
		e = d + T1;
		d = c;
		c = b;
		b = a;
		a = T1 + T2;

		j++;
	} while (j < 64);

	/* Compute the current intermediate hash value */
	context->state[0] += a;
	context->state[1] += b;
	context->state[2] += c;
	context->state[3] += d;
	context->state[4] += e;
	context->state[5] += f;
	context->state[6] += g;
	context->state[7] += h;

	/* Clean up */
	a = b = c = d = e = f = g = h = T1 = T2 = 0;
}
예제 #28
0
/*--[decompress_section]-------------------------------------------------------
 |
 | A somewhat tricky routine as it handles interfacing with the external
 | LZX library. There is a reason for using the ResetTable here, as
 | otherwise certain files will not be correctly handled!
 |
 | Generally --
 | I need to get the LZXC control information to get the window size.
 | This lets me initialize the LZX library.
 |
 | From there, I read the ResetTable to know the uncompressed length and
 | each "LZXReset()" point.
 |
 | Note that the LZXReset() that this routine requires is not part of the
 | standard lzx distribution. The version that works with these files is from
 | the chmlib implementation and already has been modified.
*/
int decompress_section(lit_file * litfile, char * section_name,
    U8 * pControl, int sizeControl, U8 * pContent, int sizeContent,
    U8 ** ppUncompressed, int * psizeUncompressed)
{
    char        *path;
    int         sizeRT, ofsEntry, base, dst, u;
    int         bytesRemaining, uclength, window_bytes, accum, size;
    U8          * ptr, * pRT;
    int         window_size, status;

    if ((sizeControl < 32) || (READ_U32(pControl+CONTROL_TAG) != LZXC_TAG)) {
        lit_error(ERR_R, "Invalid ControlData tag value %08lx should be %08lx!",
            (sizeControl > 8)?READ_U32(pControl+CONTROL_TAG):0,
            LZXC_TAG);
        return E_LIT_FORMAT_ERROR;
    }

    window_size = 14;
    u = READ_U32(pControl + CONTROL_WINDOW_SIZE);
    while (u) {
        u >>= 1;
        window_size++;
    }
    if ((window_size < 15) || (window_size > 21)) {
        lit_error(ERR_R, "Invalid window in ControlData - %d from %lx.",
            window_size, READ_U32(pControl+CONTROL_WINDOW_SIZE));
        return -1;
    }

    status = LZXinit(window_size);
    if (status) {
        lit_error(ERR_R, "LZXinit(%d) failed, status = %d.",
            window_size, status);
        return E_LIT_LZX_ERROR;
    }

    path = lit_i_strmerge(storage_string,section_name,"/Transform/",
      lzxcompress_guid, rt_tail, NULL);
    if (!path) {
        return E_LIT_OUT_OF_MEMORY;
    }
    status = lit_get_file(litfile, path, &pRT, &sizeRT);
    if (status) { free(path); return status;}

    free(path);
    path = NULL;

    if (sizeRT < (RESET_INTERVAL+8)) {
        lit_error(ERR_R, "Reset table is too short (%d bytes).",
            sizeRT);
        free(pRT);
        return E_LIT_FORMAT_ERROR;
    }
    if (READ_U32(pRT + RESET_UCLENGTH + 4)) {
        lit_error(ERR_R,"Reset table has 64bit value for UCLENGTH!");
        free(pRT);
        return E_LIT_64BIT_VALUE;
    }

    /* Skip first entry -- always 0! */
    ofsEntry = READ_INT32(pRT + RESET_HDRLEN) + 8;
    uclength = READ_INT32(pRT + RESET_UCLENGTH);
    accum    = READ_INT32(pRT + RESET_INTERVAL);

    ptr = malloc(uclength+1);
    /* Check for corruption */
    ptr[uclength] = 0xCC;

    if (!ptr) {
        lit_error(ERR_R, "Unable to malloc uc length (%d bytes)!",
            uclength);
        free(pRT);
        return E_LIT_OUT_OF_MEMORY;
    }
    bytesRemaining = uclength;
    window_bytes = (1 << window_size);

    base = 0;
    dst  = 0;

    while (ofsEntry  < sizeRT)
    {
        if (accum == window_bytes) {
            accum = 0;

            size = READ_INT32(pRT + ofsEntry);
            u = READ_INT32(pRT + ofsEntry + 4);
            if (u) {
                lit_error(ERR_R, "Reset table entry greater than 32 bits!");
                free(pRT); free(ptr);
                return E_LIT_64BIT_VALUE;
            }
            if (size >= sizeContent) {
                lit_error(ERR_R, "ResetTable entry out of bounds, %lx. (%d)",
                    size, ofsEntry);
                free(ptr); free(pRT); return E_LIT_FORMAT_ERROR;
            }
            status = 0;
            if (bytesRemaining >= window_bytes) {
                LZXreset();
                status = LZXdecompress(pContent + base, ptr+dst,
                    size - base, window_bytes);
                bytesRemaining -= window_bytes;
                dst += window_bytes;
                base = size;
            }
            if (status) {
                lit_error(ERR_R, "LZXdecompress failed, status = %d.",
                    status);
                free(ptr);
                free(pRT);
                return -1;
            }
        }
        accum += READ_INT32(pRT + RESET_INTERVAL);
        ofsEntry += 8;
    }
    free(pRT);
    if (bytesRemaining < window_bytes) {
        LZXreset();
        status = LZXdecompress(pContent + base, ptr + dst,
            sizeContent - base, bytesRemaining);
        bytesRemaining = 0;
    }
    if (ptr[uclength] != 0xCC)
    {
        lit_error(ERR_R,
"LZXdecompress overflowed memory. (%02x). \n"\
"This is a serious bug, please report this.\n", ptr[uclength]);

        /* Can't really free, anything may be corrupted at this point */
        return -1;
    }
    if (status) {
        lit_error(ERR_R, "LZXdecompress failed, status = %d.", status);
        free(ptr);
        return E_LIT_LZX_ERROR;
    }

    if (bytesRemaining) {
        lit_error(ERR_R, "Failed to completely decompress section! (%d left).",            bytesRemaining);
        free(ptr);
        return E_LIT_LZX_ERROR;
    }

    if (ppUncompressed) *ppUncompressed = ptr;
    else free(ptr);
    if (psizeUncompressed) *psizeUncompressed = uclength;
    return 0;
}