1 /*
2  *  Copyright (C) 2005-2018 Team Kodi
3  *  This file is part of Kodi - https://kodi.tv
4  *
5  *  SPDX-License-Identifier: GPL-2.0-or-later
6  *  See LICENSES/README.md for more information.
7  */
8 
9 #include "EventPacket.h"
10 
11 #include "Socket.h"
12 #include "utils/log.h"
13 
14 using namespace EVENTPACKET;
15 
16 /************************************************************************/
17 /* CEventPacket                                                         */
18 /************************************************************************/
Parse(int datasize,const void * data)19 bool CEventPacket::Parse(int datasize, const void *data)
20 {
21   unsigned char* buf = const_cast<unsigned char*>((const unsigned char *)data);
22   if (datasize < HEADER_SIZE || datasize > PACKET_SIZE)
23     return false;
24 
25   // check signature
26   if (memcmp(data, (const void*)HEADER_SIG, HEADER_SIG_LENGTH) != 0)
27     return false;
28 
29   buf += HEADER_SIG_LENGTH;
30 
31   // extract protocol version
32   m_cMajVer = (*buf++);
33   m_cMinVer = (*buf++);
34 
35   if (m_cMajVer != 2 && m_cMinVer != 0)
36     return false;
37 
38   // get packet type
39   m_eType = (PacketType)ntohs(*((uint16_t*)buf));
40 
41   if (m_eType < (unsigned short)PT_HELO || m_eType >= (unsigned short)PT_LAST)
42     return false;
43 
44   // get packet sequence id
45   buf += 2;
46   m_iSeq  = ntohl(*((uint32_t*)buf));
47 
48   // get total message length
49   buf += 4;
50   m_iTotalPackets = ntohl(*((uint32_t*)buf));
51 
52   // get payload size
53   buf += 4;
54   m_iPayloadSize = ntohs(*((uint16_t*)buf));
55 
56   if ((m_iPayloadSize + HEADER_SIZE) != (unsigned int)datasize)
57     return false;
58 
59   // get the client's token
60   buf += 2;
61   m_iClientToken = ntohl(*((uint32_t*)buf));
62 
63   buf += 4;
64 
65   // get payload
66   if (m_iPayloadSize)
67   {
68     // forward past reserved bytes
69     buf += 10;
70 
71     if (m_pPayload)
72     {
73       free(m_pPayload);
74       m_pPayload = NULL;
75     }
76 
77     m_pPayload = malloc(m_iPayloadSize);
78     if (!m_pPayload)
79     {
80       CLog::Log(LOGERROR, "ES: Out of memory");
81       return false;
82     }
83     memcpy(m_pPayload, buf, (size_t)m_iPayloadSize);
84   }
85   m_bValid = true;
86   return true;
87 }
88