Debian Codegraph @

src/Session.cpp

raw
1 /*
2 * Copyright (C) 2010-2021 Team Kodi (https://kodi.tv)
3 * Copyright (C) 2010 Alwin Esch (Team Kodi)
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSE.md for more information.
7 */
8
9 #include "Session.h"
10
11 #include "ClientInstance.h"
12 #include "RequestPacket.h"
13 #include "ResponsePacket.h"
14 #include "Settings.h"
15 #include "Tools.h"
16 #include "vnsicommand.h"
17
18 #include <chrono>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <kodi/addon-instance/inputstream/DemuxPacket.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <thread>
25
26 /* Needed on Mac OS/X */
27
28 #ifndef SOL_TCP
29 #define SOL_TCP IPPROTO_TCP
30 #endif
31
32 cVNSISession::cVNSISession(kodi::addon::CInstancePVRClient& instance) : m_instance(instance)
33 {
34 }
35
36 cVNSISession::~cVNSISession()
37 {
38 Close();
39 }
40
41 void cVNSISession::Close()
42 {
43 std::lock_guard<std::recursive_mutex> lock(m_mutex);
44 if (m_socket)
45 {
46 m_socket->Shutdown();
47 m_socket->Close();
48 }
49
50 delete m_socket;
51 m_socket = nullptr;
52 }
53
54 bool cVNSISession::Open(const std::string& hostname, int port, const char* name)
55 {
56 using namespace std::chrono;
57
58 Close();
59
60 auto iNow = system_clock::now();
61 auto iTarget = iNow + milliseconds(CVNSISettings::Get().GetConnectTimeout() * 1000);
62
63 if (!m_socket)
64 m_socket = new vdrvnsi::TCPSocket(hostname, port);
65 while (!m_socket->IsOpen() && iNow < iTarget && !m_abort)
66 {
67 uint64_t ms = duration_cast<milliseconds>(iTarget - iNow).count();
68 if (!m_socket->Open(duration_cast<milliseconds>(iTarget - iNow).count()))
69 std::this_thread::sleep_for(milliseconds(100));
70 iNow = system_clock::now();
71 }
72
73 if (!m_socket->IsOpen() && !m_abort)
74 {
75 kodi::Log(ADDON_LOG_DEBUG, "%s - failed to connect to the backend", __func__);
76 return false;
77 }
78
79 // store connection data
80 m_hostname = hostname;
81 m_port = port;
82
83 if (name != nullptr)
84 m_name = name;
85
86 return true;
87 }
88
89 bool cVNSISession::Login()
90 {
91 try
92 {
93 cRequestPacket vrp;
94 vrp.init(VNSI_LOGIN);
95 vrp.add_U32(VNSI_PROTOCOLVERSION);
96 vrp.add_U8(false); // netlog
97 if (!m_name.empty())
98 {
99 vrp.add_String(m_name.c_str());
100 }
101 else
102 {
103 vrp.add_String("XBMC Media Center");
104 }
105
106 // read welcome
107 std::unique_ptr<cResponsePacket> vresp(ReadResult(&vrp));
108 if (!vresp)
109 throw "failed to read greeting from server";
110
111 uint32_t protocol = vresp->extract_U32();
112 uint32_t vdrTime = vresp->extract_U32();
113 int32_t vdrTimeOffset = vresp->extract_S32();
114 const char* serverName = vresp->extract_String();
115 const char* serverVersion = vresp->extract_String();
116
117 m_server = serverName;
118 m_version = serverVersion;
119 m_protocol = static_cast<int>(protocol);
120
121 if (m_protocol < VNSI_MIN_PROTOCOLVERSION)
122 throw "Protocol versions do not match";
123
124 if (m_name.empty())
125 {
126 kodi::Log(ADDON_LOG_INFO,
127 "Logged in at '%lu+%i' to '%s' Version: '%s' with protocol version '%d'", vdrTime,
128 vdrTimeOffset, serverName, serverVersion, protocol);
129 }
130 }
131 catch (const std::out_of_range& e)
132 {
133 kodi::Log(ADDON_LOG_ERROR, "%s - %s", __func__, e.what());
134 Close();
135 return false;
136 }
137 catch (const char* str)
138 {
139 kodi::Log(ADDON_LOG_ERROR, "%s - %s", __func__, str);
140 Close();
141 return false;
142 }
143
144 return true;
145 }
146
147 std::unique_ptr<cResponsePacket> cVNSISession::ReadMessage(int iInitialTimeout /*= 10000*/,
148 int iDatapacketTimeout /*= 10000*/)
149 {
150 uint32_t channelID = 0;
151 uint32_t userDataLength = 0;
152 uint8_t* userData = nullptr;
153
154 cResponsePacket* vresp = nullptr;
155
156 if (!ReadData(reinterpret_cast<uint8_t*>(&channelID), sizeof(uint32_t), iInitialTimeout))
157 return nullptr;
158
159 // Data was read
160
161 channelID = ntohl(channelID);
162 if (channelID == VNSI_CHANNEL_STREAM)
163 {
164 vresp = new cResponsePacket(m_instance);
165
166 if (!ReadData(vresp->getHeader(), vresp->getStreamHeaderLength(), iDatapacketTimeout))
167 {
168 delete vresp;
169 kodi::Log(ADDON_LOG_ERROR, "%s - lost sync on channel stream packet", __func__);
170 SignalConnectionLost();
171 return nullptr;
172 }
173 vresp->extractStreamHeader();
174 userDataLength = vresp->getUserDataLength();
175
176 if (vresp->getOpCodeID() == VNSI_STREAM_MUXPKT)
177 {
178 DEMUX_PACKET* p = m_instance.AllocateDemuxPacket(userDataLength);
179 userData = (uint8_t*)p;
180 if (userDataLength > 0)
181 {
182 if (!userData)
183 return nullptr;
184 if (!ReadData(p->pData, userDataLength, iDatapacketTimeout))
185 {
186 m_instance.FreeDemuxPacket(p);
187 delete vresp;
188 kodi::Log(ADDON_LOG_ERROR, "%s - lost sync on channel stream mux packet", __func__);
189 SignalConnectionLost();
190 return nullptr;
191 }
192 }
193 }
194 else if (userDataLength > 0)
195 {
196 userData = static_cast<uint8_t*>(malloc(userDataLength));
197 if (!userData)
198 return nullptr;
199 if (!ReadData(userData, userDataLength, iDatapacketTimeout))
200 {
201 free(userData);
202 delete vresp;
203 kodi::Log(ADDON_LOG_ERROR, "%s - lost sync on channel stream (other) packet", __func__);
204 SignalConnectionLost();
205 return nullptr;
206 }
207 }
208 vresp->setStream(userData, userDataLength);
209 }
210 else if (channelID == VNSI_CHANNEL_OSD)
211 {
212 vresp = new cResponsePacket(m_instance);
213
214 if (!ReadData(vresp->getHeader(), vresp->getOSDHeaderLength(), iDatapacketTimeout))
215 {
216 kodi::Log(ADDON_LOG_ERROR, "%s - lost sync on osd packet", __func__);
217 SignalConnectionLost();
218 return nullptr;
219 }
220 vresp->extractOSDHeader();
221 userDataLength = vresp->getUserDataLength();
222
223 userData = nullptr;
224 if (userDataLength > 0)
225 {
226 userData = static_cast<uint8_t*>(malloc(userDataLength));
227 if (!userData)
228 return nullptr;
229 if (!ReadData(userData, userDataLength, iDatapacketTimeout))
230 {
231 free(userData);
232 delete vresp;
233 kodi::Log(ADDON_LOG_ERROR, "%s - lost sync on additional osd packet", __func__);
234 SignalConnectionLost();
235 return nullptr;
236 }
237 }
238 vresp->setOSD(userData, userDataLength);
239 }
240 else
241 {
242 vresp = new cResponsePacket(m_instance);
243
244 if (!ReadData(vresp->getHeader(), vresp->getHeaderLength(), iDatapacketTimeout))
245 {
246 delete vresp;
247 kodi::Log(ADDON_LOG_ERROR, "%s - lost sync on response packet", __func__);
248 SignalConnectionLost();
249 return nullptr;
250 }
251 vresp->extractHeader();
252 userDataLength = vresp->getUserDataLength();
253
254 userData = nullptr;
255 if (userDataLength > 0)
256 {
257 userData = static_cast<uint8_t*>(malloc(userDataLength));
258 if (!userData)
259 return nullptr;
260 if (!ReadData(userData, userDataLength, iDatapacketTimeout))
261 {
262 free(userData);
263 delete vresp;
264 kodi::Log(ADDON_LOG_ERROR, "%s - lost sync on additional response packet", __func__);
265 SignalConnectionLost();
266 return nullptr;
267 }
268 }
269
270 if (channelID == VNSI_CHANNEL_STATUS)
271 vresp->setStatus(userData, userDataLength);
272 else
273 vresp->setResponse(userData, userDataLength);
274 }
275
276 return std::unique_ptr<cResponsePacket>(vresp);
277 }
278
279 bool cVNSISession::TransmitMessage(cRequestPacket* vrp)
280 {
281 std::lock_guard<std::recursive_mutex> lock(m_mutex);
282
283 if (!IsOpen())
284 return false;
285
286 int64_t iWriteResult = m_socket->Write(vrp->getPtr(), vrp->getLen());
287 if (iWriteResult != static_cast<int64_t>(vrp->getLen()))
288 {
289 kodi::Log(ADDON_LOG_ERROR, "%s - Failed to write packet, bytes written: %d of total: %d",
290 __func__, iWriteResult, vrp->getLen());
291 return false;
292 }
293 return true;
294 }
295
296 std::unique_ptr<cResponsePacket> cVNSISession::ReadResult(cRequestPacket* vrp)
297 {
298 if (!TransmitMessage(vrp))
299 {
300 SignalConnectionLost();
301 return nullptr;
302 }
303
304 std::unique_ptr<cResponsePacket> pkt;
305
306 while ((pkt = ReadMessage(10000, 10000)))
307 {
308 // Discard everything other as response packets until it is received
309 if (pkt->getChannelID() == VNSI_CHANNEL_REQUEST_RESPONSE &&
310 pkt->getRequestID() == vrp->getSerial())
311 {
312 return pkt;
313 }
314 }
315
316 SignalConnectionLost();
317 return nullptr;
318 }
319
320 bool cVNSISession::ReadSuccess(cRequestPacket* vrp)
321 {
322 std::unique_ptr<cResponsePacket> pkt;
323 if ((pkt = ReadResult(vrp)) == nullptr)
324 {
325 return false;
326 }
327 uint32_t retCode = pkt->extract_U32();
328
329 if (retCode != VNSI_RET_OK)
330 {
331 kodi::Log(ADDON_LOG_ERROR, "%s - failed with error code '%i'", __func__, retCode);
332 return false;
333 }
334 return true;
335 }
336
337 void cVNSISession::OnReconnect()
338 {
339 }
340
341 void cVNSISession::OnDisconnect()
342 {
343 }
344
345 cVNSISession::eCONNECTIONSTATE cVNSISession::TryReconnect()
346 {
347 if (!Open(m_hostname, m_port))
348 return CONN_HOST_NOT_REACHABLE;
349
350 if (!Login())
351 return CONN_LOGIN_FAILED;
352
353 kodi::Log(ADDON_LOG_DEBUG, "%s - reconnected", __func__);
354 m_connectionLost = false;
355
356 OnReconnect();
357
358 return CONN_ESABLISHED;
359 }
360
361 bool cVNSISession::IsOpen()
362 {
363 std::lock_guard<std::recursive_mutex> lock(m_mutex);
364 return m_socket && m_socket->IsOpen();
365 }
366
367 void cVNSISession::SignalConnectionLost()
368 {
369 if (m_connectionLost)
370 return;
371
372 kodi::Log(ADDON_LOG_ERROR, "%s - connection lost !!!", __func__);
373
374 m_connectionLost = true;
375 Close();
376
377 OnDisconnect();
378 }
379
380 bool cVNSISession::ReadData(uint8_t* buffer, int totalBytes, int timeout)
381 {
382 int bytesRead = m_socket->Read(buffer, totalBytes, timeout);
383 if (bytesRead == totalBytes)
384 {
385 return true;
386 }
387 else if (bytesRead > 0)
388 {
389 // we did read something. try to finish the read
390 bytesRead += m_socket->Read(buffer + bytesRead, totalBytes - bytesRead, timeout);
391 if (bytesRead == totalBytes)
392 return true;
393 }
394 else if (m_socket->LastError() == vdrvnsi::SocketError::TimeOut)
395 {
396 return false;
397 }
398
399 SignalConnectionLost();
400 return false;
401 }
402
403 void cVNSISession::SleepMs(int ms)
404 {
405 std::this_thread::sleep_for(std::chrono::milliseconds(ms));
406 }