This repository was archived by the owner on Jan 19, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.cpp
More file actions
498 lines (414 loc) · 18.1 KB
/
Copy pathsocket.cpp
File metadata and controls
498 lines (414 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
/******************************************************************************\
* Copyright (c) 2004-2024
*
* Author(s):
* Volker Fischer
*
******************************************************************************
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
\******************************************************************************/
#include "socket.h"
#include "server.h"
#include "global.h" //cbvb-pcmjam debugging
#include <QDebug>
#include <iomanip> //cbvb-pcmjam For std::setw and std::setfill
#include <sstream> //cbvb-pcmjam For std::ostringstream
#ifdef _WIN32
# include <winsock2.h>
# include <ws2tcpip.h>
#else
# include <arpa/inet.h>
#endif
/* Implementation *************************************************************/
// Connections -------------------------------------------------------------
// it is important to do the following connections in this class since we
// have a thread transition
// we have different connections for client and server, created after Init in corresponding constructor
CSocket::CSocket ( CChannel* pNewChannel, const quint16 iPortNumber, const quint16 iQosNumber, const QString& strServerBindIP, bool bEnableIPv6 ) :
pChannel ( pNewChannel ),
bIsClient ( true ),
bJitterBufferOK ( true ),
bEnableIPv6 ( bEnableIPv6 )
{
Init ( iPortNumber, iQosNumber, strServerBindIP );
// client connections:
QObject::connect ( this, &CSocket::ProtocolMessageReceived, pChannel, &CChannel::OnProtocolMessageReceived );
QObject::connect ( this, &CSocket::ProtocolCLMessageReceived, pChannel, &CChannel::OnProtocolCLMessageReceived );
QObject::connect ( this, static_cast<void ( CSocket::* )()> ( &CSocket::NewConnection ), pChannel, &CChannel::OnNewConnection );
}
CSocket::CSocket ( CServer* pNServP, const quint16 iPortNumber, const quint16 iQosNumber, const QString& strServerBindIP, bool bEnableIPv6 ) :
pServer ( pNServP ),
bIsClient ( false ),
bJitterBufferOK ( true ),
bEnableIPv6 ( bEnableIPv6 )
{
Init ( iPortNumber, iQosNumber, strServerBindIP );
// server connections:
QObject::connect ( this, &CSocket::ProtocolMessageReceived, pServer, &CServer::OnProtocolMessageReceived );
QObject::connect ( this, &CSocket::ProtocolCLMessageReceived, pServer, &CServer::OnProtocolCLMessageReceived );
QObject::connect ( this,
static_cast<void ( CSocket::* ) ( int, int, CHostAddress )> ( &CSocket::NewConnection ),
pServer,
&CServer::OnNewConnection );
QObject::connect ( this, &CSocket::ServerFull, pServer, &CServer::OnServerFull );
}
void CSocket::Init ( const quint16 iNewPortNumber, const quint16 iNewQosNumber, const QString& strNewServerBindIP )
{
uSockAddr UdpSocketAddr;
int UdpSocketAddrLen;
uint16_t* UdpPort;
// first store parameters, in case reinit is required (mostly for iOS)
iPortNumber = iNewPortNumber;
iQosNumber = iNewQosNumber;
strServerBindIP = strNewServerBindIP;
#ifdef _WIN32
// for the Windows socket usage we have to start it up first
//### TODO: BEGIN ###//
// check for error and exit application on error
//### TODO: END ###//
WSADATA wsa;
WSAStartup ( MAKEWORD ( 1, 0 ), &wsa );
#endif
memset ( &UdpSocketAddr, 0, sizeof ( UdpSocketAddr ) );
if ( bEnableIPv6 )
{
// try to create a IPv6 UDP socket
UdpSocket = socket ( AF_INET6, SOCK_DGRAM, 0 );
if ( UdpSocket == -1 )
{
// IPv6 requested but not available, throw error
throw CGenErr ( "IPv6 requested but not available on this system.", "Network Error" );
}
// The IPV6_V6ONLY socket option must be false in order for the socket to listen on both protocols.
// On Linux it's false by default on most (all?) distros, but on Windows it is true by default
const uint8_t no = 0;
setsockopt ( UdpSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*) &no, sizeof ( no ) );
// set the QoS
const char tos = (char) iQosNumber; // Quality of Service
setsockopt ( UdpSocket, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof ( tos ) );
UdpSocketAddr.sa6.sin6_family = AF_INET6;
UdpSocketAddr.sa6.sin6_addr = in6addr_any;
UdpSocketAddrLen = sizeof ( UdpSocketAddr.sa6 );
UdpPort = &UdpSocketAddr.sa6.sin6_port; // where to put the port number
// FIXME: If binding a dual-protocol interface to a specific address, does it cease to be dual-protocol?
// TODO - ALLOW IPV6 ADDRESS
// if ( !strServerBindIP.isEmpty() )
//{
// UdpSocketInAddr.sin_addr.s_addr = htonl ( QHostAddress ( strServerBindIP ).toIPv4Address() );
//}
// END TODO - ALLOW IPV6 ADDRESS
}
else
{
// create the UDP socket for IPv4
UdpSocket = socket ( AF_INET, SOCK_DGRAM, 0 );
if ( UdpSocket == -1 )
{
// IPv4 requested but not available, throw error (should never happen, but check anyway)
throw CGenErr ( "IPv4 requested but not available on this system.", "Network Error" );
}
// set the QoS
const char tos = (char) iQosNumber; // Quality of Service
setsockopt ( UdpSocket, IPPROTO_IP, IP_TOS, &tos, sizeof ( tos ) );
// preinitialize socket in address (only the port number is missing)
UdpSocketAddr.sa4.sin_family = AF_INET;
UdpSocketAddr.sa4.sin_addr.s_addr = INADDR_ANY;
UdpSocketAddrLen = sizeof ( UdpSocketAddr.sa4 );
UdpPort = &UdpSocketAddr.sa4.sin_port; // where to put the port number
if ( !strServerBindIP.isEmpty() )
{
UdpSocketAddr.sa4.sin_addr.s_addr = htonl ( QHostAddress ( strServerBindIP ).toIPv4Address() );
}
}
#ifdef Q_OS_IOS
// ignore the broken pipe signal to avoid crash (iOS)
int valueone = 1;
setsockopt ( UdpSocket, SOL_SOCKET, SO_NOSIGPIPE, &valueone, sizeof ( valueone ) );
#endif
// allocate memory for network receive and send buffer in samples
vecbyRecBuf.Init ( MAX_SIZE_BYTES_NETW_BUF );
// initialize the listening socket
bool bSuccess;
if ( bIsClient )
{
if ( iPortNumber == 0 )
{
// if port number is 0, bind the client to a random available port
*UdpPort = htons ( 0 );
bSuccess = ( ::bind ( UdpSocket, &UdpSocketAddr.sa, UdpSocketAddrLen ) == 0 );
}
else
{
// If the port is not available, try "NUM_SOCKET_PORTS_TO_TRY" times
// with incremented port numbers. Randomize the start port, in case a
// faulty router gets stuck and confused by a particular port (like
// the starting port). Might work around frustrating "cannot connect"
// problems (#568)
const quint16 startingPortNumber = iPortNumber + rand() % NUM_SOCKET_PORTS_TO_TRY;
quint16 iClientPortIncrement = 0;
bSuccess = false; // initialization for while loop
while ( !bSuccess && ( iClientPortIncrement <= NUM_SOCKET_PORTS_TO_TRY ) )
{
*UdpPort = htons ( startingPortNumber + iClientPortIncrement );
bSuccess = ( ::bind ( UdpSocket, &UdpSocketAddr.sa, UdpSocketAddrLen ) == 0 );
iClientPortIncrement++;
}
}
}
else
{
// for the server, only try the given port number and do not try out
// other port numbers to bind since it is important that the server
// gets the desired port number
*UdpPort = htons ( iPortNumber );
bSuccess = ( ::bind ( UdpSocket, &UdpSocketAddr.sa, UdpSocketAddrLen ) == 0 );
}
if ( !bSuccess )
{
// we cannot bind socket, throw error
throw CGenErr ( "Cannot bind the socket (maybe "
"the software is already running).",
"Network Error" );
}
}
void CSocket::Close()
{
#ifdef _WIN32
// closesocket will cause recvfrom to return with an error because the
// socket is closed -> then the thread can safely be shut down
closesocket ( UdpSocket );
#elif defined( __APPLE__ ) || defined( __MACOSX )
// on Mac the general close has the same effect as closesocket on Windows
close ( UdpSocket );
#else
// on Linux the shutdown call cancels the recvfrom
shutdown ( UdpSocket, SHUT_RDWR );
#endif
}
CSocket::~CSocket()
{
// cleanup the socket (on Windows the WSA cleanup must also be called)
#ifdef _WIN32
closesocket ( UdpSocket );
WSACleanup();
#else
close ( UdpSocket );
#endif
}
void CSocket::SendPacket(const CVector<uint8_t>& vecbySendBuf, const CHostAddress& HostAddr)
{
int status = 0;
uSockAddr UdpSocketAddr;
memset(&UdpSocketAddr, 0, sizeof(UdpSocketAddr));
QMutexLocker locker(&Mutex);
DebugLog(DEBUG_NETWORK, "SendPacket: Socket initialization verified. VecBuf size: " << vecbySendBuf.Size());
const int iVecSizeOut = vecbySendBuf.Size();
if (iVecSizeOut > 0)
{
//DebugLog(DEBUG_NETWORK, "SendPacket: Preparing to send " << iVecSizeOut << " bytes.");
}
else
{
DebugLog(DEBUG_NETWORK, "SendPacket: Empty buffer! Message size is 0.");
}
// Hex dump the buffer content
std::ostringstream hexStream;
hexStream << std::hex << std::uppercase;
for (int i = 0; i < iVecSizeOut; i++) // Use consistent type
{
hexStream << std::setw(2) << std::setfill('0') << static_cast<int>(vecbySendBuf[i]);
if (i != iVecSizeOut - 1)
{
hexStream << " ";
}
}
//DebugLog(DEBUG_NETWORK, "Buffer content: " << hexStream.str());
for (int tries = 0; tries < 2; tries++) // Retry loop in case send fails on iOS
{
if (HostAddr.InetAddr.protocol() == QAbstractSocket::IPv4Protocol)
{
if (bEnableIPv6)
{
// Dual-stack IPv6 socket handling
UdpSocketAddr.sa6.sin6_family = AF_INET6;
UdpSocketAddr.sa6.sin6_port = htons(HostAddr.iPort);
uint32_t* addr = (uint32_t*)&UdpSocketAddr.sa6.sin6_addr;
addr[0] = 0;
addr[1] = 0;
addr[2] = htonl(0xFFFF);
addr[3] = htonl(HostAddr.InetAddr.toIPv4Address());
status = sendto(UdpSocket,
(const char*)vecbySendBuf.data(),
iVecSizeOut,
0,
&UdpSocketAddr.sa,
sizeof(UdpSocketAddr.sa6));
}
else
{
UdpSocketAddr.sa4.sin_family = AF_INET;
UdpSocketAddr.sa4.sin_port = htons(HostAddr.iPort);
UdpSocketAddr.sa4.sin_addr.s_addr = htonl(HostAddr.InetAddr.toIPv4Address());
status = sendto(UdpSocket,
(const char*)vecbySendBuf.data(),
iVecSizeOut,
0,
&UdpSocketAddr.sa,
sizeof(UdpSocketAddr.sa4));
}
}
else if (bEnableIPv6)
{
UdpSocketAddr.sa6.sin6_family = AF_INET6;
UdpSocketAddr.sa6.sin6_port = htons(HostAddr.iPort);
inet_pton(AF_INET6, HostAddr.InetAddr.toString().toLocal8Bit().constData(), &UdpSocketAddr.sa6.sin6_addr);
status = sendto(UdpSocket,
(const char*)vecbySendBuf.data(),
iVecSizeOut,
0,
&UdpSocketAddr.sa,
sizeof(UdpSocketAddr.sa6));
}
if (status >= 0)
{
DebugLog(DEBUG_NETWORK, "SendPacket: Successfully sent " << iVecSizeOut << " bytes.");
break; // Do not retry if success
}
#ifdef Q_OS_IOS
Init(iPortNumber, iQosNumber, strServerBindIP); // Reinitialize for retry
#endif
}
if (status < 0)
{
DebugLog(DEBUG_NETWORK, "SendPacket: Failed to send packet after retries.");
}
}
bool CSocket::GetAndResetbJitterBufferOKFlag()
{
// check jitter buffer status
if ( !bJitterBufferOK )
{
// reset flag and return "not OK" status
bJitterBufferOK = true;
return false;
}
// the buffer was OK, we do not have to reset anything and just return the
// OK status
return true;
}
//cbvb-pcmjam
static uint32_t ExtractValFromStream(const CVector<uint8_t>& vecIn, int& iPos, const int iNumOfBytes) {
Q_ASSERT((iNumOfBytes > 0) && (iNumOfBytes <= 4));
Q_ASSERT(vecIn.Size() >= iPos + iNumOfBytes);
uint32_t iRet = 0;
for (int i = 0; i < iNumOfBytes; i++) {
iRet |= vecIn[iPos] << (i * 8); // Combine bytes
iPos++;
}
return iRet;
}
//cbvb-pcmjam changed logic to detect audio as pcm was recognized as proto... now it sorta is..
void CSocket::OnDataReceived() {
CHostAddress RecHostAddr;
// Read block from network interface and query address of sender
uSockAddr UdpSocketAddr;
#ifdef _WIN32
int SenderAddrSize = sizeof(UdpSocketAddr);
#else
socklen_t SenderAddrSize = sizeof(UdpSocketAddr);
#endif
const long iNumBytesRead = recvfrom(UdpSocket, (char*)&vecbyRecBuf[0], MAX_SIZE_BYTES_NETW_BUF, 0, &UdpSocketAddr.sa, &SenderAddrSize);
// Check if an error occurred or no data could be read
if (iNumBytesRead <= 0) {
DebugLog(DEBUG_PROTOCOL, "No data read or error occurred in recvfrom.");
return;
}
// Convert address of client
if (UdpSocketAddr.sa.sa_family == AF_INET6) {
if (IN6_IS_ADDR_V4MAPPED(&(UdpSocketAddr.sa6.sin6_addr))) {
const uint32_t addr = ((const uint32_t*)(&(UdpSocketAddr.sa6.sin6_addr)))[3];
RecHostAddr.InetAddr.setAddress(ntohl(addr));
} else {
RecHostAddr.InetAddr.setAddress(UdpSocketAddr.sa6.sin6_addr.s6_addr);
}
RecHostAddr.iPort = ntohs(UdpSocketAddr.sa6.sin6_port);
} else {
RecHostAddr.InetAddr.setAddress(ntohl(UdpSocketAddr.sa4.sin_addr.s_addr));
RecHostAddr.iPort = ntohs(UdpSocketAddr.sa4.sin_port);
}
// PCM-specific logic
int pos = 0; // Initialize position for parsing
const int iTag = static_cast<int>(ExtractValFromStream(vecbyRecBuf, pos, 2));
const int iID = static_cast<int>(ExtractValFromStream(vecbyRecBuf, pos, 2));
if (iTag == 0 && iID == PROTMESSID_PCM_AUDIO) {
const int payloadStart = pos;
const int payloadSize = iNumBytesRead - payloadStart;
CVector<uint8_t> vecPCMData(payloadSize);
std::copy(vecbyRecBuf.begin() + payloadStart, vecbyRecBuf.begin() + iNumBytesRead, vecPCMData.begin());
// Client or server-specific processing
if (bIsClient) {
switch (pChannel->PutAudioData(vecPCMData, payloadSize, RecHostAddr)) {
case PS_NEW_CONNECTION:
emit NewConnection();
DebugLog(DEBUG_PROTOCOL, "New client connection established.");
break;
case PS_AUDIO_ERR:
case PS_GEN_ERROR:
bJitterBufferOK = false;
DebugLog(DEBUG_PROTOCOL, "Audio error occurred while processing client data.");
break;
case PS_AUDIO_INVALID:
emit InvalidPacketReceived(RecHostAddr);
DebugLog(DEBUG_PROTOCOL, "Invalid PCM audio packet received.");
break;
default:
// Process audio for existing connection
break;
}
} else {
int iCurChanID = INVALID_CHANNEL_ID;
const bool isNewConnection = pServer->PutAudioData(vecPCMData, payloadSize, RecHostAddr, iCurChanID);
if (isNewConnection) {
emit NewConnection(iCurChanID, pServer->GetNumberOfConnectedClients(), RecHostAddr);
DebugLog(DEBUG_PROTOCOL, "OnDataReceived: New PCM connection established. Channel ID: " << iCurChanID);
// Wake up the server if it is sleeping
if (!pServer->IsRunning()) {
QCoreApplication::postEvent(pServer, new CCustomEvent(MS_PACKET_RECEIVED, 0, 0));
DebugLog(DEBUG_PROTOCOL, "OnDataReceived: Server was sleeping. Wake-up event posted.");
}
} else if (iCurChanID == INVALID_CHANNEL_ID) {
emit ServerFull(RecHostAddr);
DebugLog(DEBUG_PROTOCOL, "OnDataReceived: Server full. Connection rejected for: " << RecHostAddr.InetAddr.toString().toStdString());
}
}
return; // PCM processing done
}
// Protocol message fallback
int iRecCounter;
int iRecID;
CVector<uint8_t> vecbyMesBodyData;
if (!CProtocol::ParseMessageFrame(vecbyRecBuf, iNumBytesRead, vecbyMesBodyData, iRecCounter, iRecID)) {
DebugLog(DEBUG_PROTOCOL, "Message received. ID: " << iRecID << ", Counter: " << iRecCounter);
if (CProtocol::IsConnectionLessMessageID(iRecID)) {
emit ProtocolCLMessageReceived(iRecID, vecbyMesBodyData, RecHostAddr);
DebugLog(DEBUG_PROTOCOL, "ProtocolCLMessageReceived emitted. ID: " << iRecID);
} else {
emit ProtocolMessageReceived(iRecCounter, iRecID, vecbyMesBodyData, RecHostAddr);
DebugLog(DEBUG_PROTOCOL, "ProtocolMessageReceived emitted. ID: " << iRecID << ", Counter: " << iRecCounter);
}
}
}