/
NetPlayServer.cpp
718 lines (592 loc) · 16.2 KB
/
NetPlayServer.cpp
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// Copyright 2013 Dolphin Emulator Project
// Licensed under GPLv2
// Refer to the license.txt file included.
#include "NetPlayServer.h"
NetPlayServer::~NetPlayServer()
{
if (is_connected)
{
m_do_loop = false;
m_thread.join();
m_socket.Close();
}
#ifdef USE_UPNP
if (m_upnp_thread.joinable())
m_upnp_thread.join();
m_upnp_thread = std::thread(&NetPlayServer::unmapPortThread);
m_upnp_thread.join();
#endif
}
// called from ---GUI--- thread
NetPlayServer::NetPlayServer(const u16 port) : is_connected(false), m_is_running(false)
{
memset(m_pad_map, -1, sizeof(m_pad_map));
memset(m_wiimote_map, -1, sizeof(m_wiimote_map));
if (m_socket.Listen(port))
{
is_connected = true;
m_do_loop = true;
m_selector.Add(m_socket);
m_thread = std::thread(std::mem_fun(&NetPlayServer::ThreadFunc), this);
m_target_buffer_size = 20;
}
}
// called from ---NETPLAY--- thread
void NetPlayServer::ThreadFunc()
{
while (m_do_loop)
{
// update pings every so many seconds
if ((m_ping_timer.GetTimeElapsed() > (10 * 1000)) || m_update_pings)
{
//PanicAlertT("Sending pings");
m_ping_key = Common::Timer::GetTimeMs();
sf::Packet spac;
spac << (MessageId)NP_MSG_PING;
spac << m_ping_key;
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
m_ping_timer.Start();
SendToClients(spac);
m_update_pings = false;
}
// check which sockets need attention
const unsigned int num = m_selector.Wait(0.01f);
for (unsigned int i=0; i<num; ++i)
{
sf::SocketTCP ready_socket = m_selector.GetSocketReady(i);
// listening socket
if (ready_socket == m_socket)
{
sf::SocketTCP accept_socket;
m_socket.Accept(accept_socket);
unsigned int error;
{
std::lock_guard<std::recursive_mutex> lkg(m_crit.game);
error = OnConnect(accept_socket);
}
if (error)
{
sf::Packet spac;
spac << (MessageId)error;
// don't need to lock, this client isn't in the client map
accept_socket.Send(spac);
// TODO: not sure if client gets the message if i close right away
accept_socket.Close();
}
}
// client socket
else
{
sf::Packet rpac;
switch (ready_socket.Receive(rpac))
{
case sf::Socket::Done :
// if a bad packet is received, disconnect the client
if (0 == OnData(rpac, ready_socket))
break;
//case sf::Socket::Disconnected :
default :
{
std::lock_guard<std::recursive_mutex> lkg(m_crit.game);
OnDisconnect(ready_socket);
break;
}
}
}
}
}
// close listening socket and client sockets
{
std::map<sf::SocketTCP, Client>::reverse_iterator
i = m_players.rbegin(),
e = m_players.rend();
for ( ; i!=e; ++i)
i->second.socket.Close();
}
return;
}
// called from ---NETPLAY--- thread
unsigned int NetPlayServer::OnConnect(sf::SocketTCP& socket)
{
sf::Packet rpac;
// TODO: make this not hang / check if good packet
socket.Receive(rpac);
std::string npver;
rpac >> npver;
// dolphin netplay version
if (npver != NETPLAY_VERSION)
return CON_ERR_VERSION_MISMATCH;
// game is currently running
if (m_is_running)
return CON_ERR_GAME_RUNNING;
// too many players
if (m_players.size() >= 255)
return CON_ERR_SERVER_FULL;
// cause pings to be updated
m_update_pings = true;
Client player;
player.socket = socket;
rpac >> player.revision;
rpac >> player.name;
// give new client first available id
player.pid = m_players.size() + 1;
// try to automatically assign new user a pad
for (unsigned int m = 0; m < 4; ++m)
{
if (m_pad_map[m] == -1)
{
m_pad_map[m] = player.pid;
break;
}
}
{
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
// send join message to already connected clients
sf::Packet spac;
spac << (MessageId)NP_MSG_PLAYER_JOIN;
spac << player.pid << player.name << player.revision;
SendToClients(spac);
// send new client success message with their id
spac.Clear();
spac << (MessageId)0;
spac << player.pid;
socket.Send(spac);
// send new client the selected game
if (m_selected_game != "")
{
spac.Clear();
spac << (MessageId)NP_MSG_CHANGE_GAME;
spac << m_selected_game;
socket.Send(spac);
}
// send the pad buffer value
spac.Clear();
spac << (MessageId)NP_MSG_PAD_BUFFER;
spac << (u32)m_target_buffer_size;
socket.Send(spac);
// sync values with new client
std::map<sf::SocketTCP, Client>::const_iterator
i,
e = m_players.end();
for (i = m_players.begin(); i!=e; ++i)
{
spac.Clear();
spac << (MessageId)NP_MSG_PLAYER_JOIN;
spac << i->second.pid << i->second.name << i->second.revision;
socket.Send(spac);
}
} // unlock send
// add client to the player list
{
std::lock_guard<std::recursive_mutex> lkp(m_crit.players);
m_players[socket] = player;
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
UpdatePadMapping(); // sync pad mappings with everyone
UpdateWiimoteMapping();
}
// add client to selector/ used for receiving
m_selector.Add(socket);
return 0;
}
// called from ---NETPLAY--- thread
unsigned int NetPlayServer::OnDisconnect(sf::SocketTCP& socket)
{
PlayerId pid = m_players[socket].pid;
if (m_is_running)
{
for (int i = 0; i < 4; i++)
{
if (m_pad_map[i] == pid)
{
PanicAlertT("Client disconnect while game is running!! NetPlay is disabled. You must manually stop the game.");
std::lock_guard<std::recursive_mutex> lkg(m_crit.game);
m_is_running = false;
sf::Packet spac;
spac << (MessageId)NP_MSG_DISABLE_GAME;
// this thread doesn't need players lock
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac);
break;
}
}
}
sf::Packet spac;
spac << (MessageId)NP_MSG_PLAYER_LEAVE;
spac << pid;
m_selector.Remove(socket);
std::lock_guard<std::recursive_mutex> lkp(m_crit.players);
m_players.erase(m_players.find(socket));
// alert other players of disconnect
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac);
for (int i = 0; i < 4; i++)
if (m_pad_map[i] == pid)
m_pad_map[i] = -1;
UpdatePadMapping();
for (int i = 0; i < 4; i++)
if (m_wiimote_map[i] == pid)
m_wiimote_map[i] = -1;
UpdateWiimoteMapping();
return 0;
}
// called from ---GUI--- thread
void NetPlayServer::GetPadMapping(PadMapping map[4])
{
for (int i = 0; i < 4; i++)
map[i] = m_pad_map[i];
}
void NetPlayServer::GetWiimoteMapping(PadMapping map[4])
{
for (int i = 0; i < 4; i++)
map[i] = m_wiimote_map[i];
}
// called from ---GUI--- thread
void NetPlayServer::SetPadMapping(const PadMapping map[4])
{
for (int i = 0; i < 4; i++)
m_pad_map[i] = map[i];
UpdatePadMapping();
}
// called from ---GUI--- thread
void NetPlayServer::SetWiimoteMapping(const PadMapping map[4])
{
for (int i = 0; i < 4; i++)
m_wiimote_map[i] = map[i];
UpdateWiimoteMapping();
}
// called from ---GUI--- thread and ---NETPLAY--- thread
void NetPlayServer::UpdatePadMapping()
{
sf::Packet spac;
spac << (MessageId)NP_MSG_PAD_MAPPING;
for (int i = 0; i < 4; i++)
spac << m_pad_map[i];
SendToClients(spac);
}
// called from ---NETPLAY--- thread
void NetPlayServer::UpdateWiimoteMapping()
{
sf::Packet spac;
spac << (MessageId)NP_MSG_WIIMOTE_MAPPING;
for (int i = 0; i < 4; i++)
spac << m_wiimote_map[i];
SendToClients(spac);
}
// called from ---GUI--- thread and ---NETPLAY--- thread
void NetPlayServer::AdjustPadBufferSize(unsigned int size)
{
std::lock_guard<std::recursive_mutex> lkg(m_crit.game);
m_target_buffer_size = size;
// tell clients to change buffer size
sf::Packet spac;
spac << (MessageId)NP_MSG_PAD_BUFFER;
spac << (u32)m_target_buffer_size;
std::lock_guard<std::recursive_mutex> lkp(m_crit.players);
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac);
}
// called from ---NETPLAY--- thread
unsigned int NetPlayServer::OnData(sf::Packet& packet, sf::SocketTCP& socket)
{
MessageId mid;
packet >> mid;
// don't need lock because this is the only thread that modifies the players
// only need locks for writes to m_players in this thread
Client& player = m_players[socket];
switch (mid)
{
case NP_MSG_CHAT_MESSAGE :
{
std::string msg;
packet >> msg;
// send msg to other clients
sf::Packet spac;
spac << (MessageId)NP_MSG_CHAT_MESSAGE;
spac << player.pid;
spac << msg;
{
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac, player.pid);
}
}
break;
case NP_MSG_PAD_DATA :
{
// if this is pad data from the last game still being received, ignore it
if (player.current_game != m_current_game)
break;
PadMapping map = 0;
int hi, lo;
packet >> map >> hi >> lo;
// If the data is not from the correct player,
// then disconnect them.
if (m_pad_map[map] != player.pid)
return 1;
// Relay to clients
sf::Packet spac;
spac << (MessageId)NP_MSG_PAD_DATA;
spac << map << hi << lo;
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac, player.pid);
}
break;
case NP_MSG_WIIMOTE_DATA :
{
// if this is wiimote data from the last game still being received, ignore it
if (player.current_game != m_current_game)
break;
PadMapping map = 0;
u8 size;
packet >> map >> size;
u8* data = new u8[size];
for (unsigned int i = 0; i < size; ++i)
packet >> data[i];
// If the data is not from the correct player,
// then disconnect them.
if (m_wiimote_map[map] != player.pid)
{
delete[] data;
return 1;
}
// relay to clients
sf::Packet spac;
spac << (MessageId)NP_MSG_WIIMOTE_DATA;
spac << map;
spac << size;
for (unsigned int i = 0; i < size; ++i)
spac << data[i];
delete[] data;
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac, player.pid);
}
break;
case NP_MSG_PONG :
{
const u32 ping = m_ping_timer.GetTimeElapsed();
u32 ping_key = 0;
packet >> ping_key;
if (m_ping_key == ping_key)
player.ping = ping;
sf::Packet spac;
spac << (MessageId)NP_MSG_PLAYER_PING_DATA;
spac << player.pid;
spac << player.ping;
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac);
}
break;
case NP_MSG_START_GAME :
{
packet >> player.current_game;
}
break;
case NP_MSG_STOP_GAME:
{
// tell clients to stop game
sf::Packet spac;
spac << (MessageId)NP_MSG_STOP_GAME;
std::lock_guard<std::recursive_mutex> lkp(m_crit.players);
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac);
m_is_running = false;
}
break;
default :
PanicAlertT("Unknown message with id:%d received from player:%d Kicking player!", mid, player.pid);
// unknown message, kick the client
return 1;
break;
}
return 0;
}
// called from ---GUI--- thread / and ---NETPLAY--- thread
void NetPlayServer::SendChatMessage(const std::string& msg)
{
sf::Packet spac;
spac << (MessageId)NP_MSG_CHAT_MESSAGE;
spac << (PlayerId)0; // server id always 0
spac << msg;
std::lock_guard<std::recursive_mutex> lkp(m_crit.players);
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac);
}
// called from ---GUI--- thread
bool NetPlayServer::ChangeGame(const std::string &game)
{
std::lock_guard<std::recursive_mutex> lkg(m_crit.game);
m_selected_game = game;
// send changed game to clients
sf::Packet spac;
spac << (MessageId)NP_MSG_CHANGE_GAME;
spac << game;
std::lock_guard<std::recursive_mutex> lkp(m_crit.players);
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac);
return true;
}
// called from ---GUI--- thread
void NetPlayServer::SetNetSettings(const NetSettings &settings)
{
m_settings = settings;
}
// called from ---GUI--- thread
bool NetPlayServer::StartGame(const std::string &path)
{
std::lock_guard<std::recursive_mutex> lkg(m_crit.game);
m_current_game = Common::Timer::GetTimeMs();
// no change, just update with clients
AdjustPadBufferSize(m_target_buffer_size);
// tell clients to start game
sf::Packet spac;
spac << (MessageId)NP_MSG_START_GAME;
spac << m_current_game;
spac << m_settings.m_CPUthread;
spac << m_settings.m_DSPEnableJIT;
spac << m_settings.m_DSPHLE;
spac << m_settings.m_WriteToMemcard;
spac << m_settings.m_EXIDevice[0];
spac << m_settings.m_EXIDevice[1];
std::lock_guard<std::recursive_mutex> lkp(m_crit.players);
std::lock_guard<std::recursive_mutex> lks(m_crit.send);
SendToClients(spac);
m_is_running = true;
return true;
}
// called from multiple threads
void NetPlayServer::SendToClients(sf::Packet& packet, const PlayerId skip_pid)
{
std::map<sf::SocketTCP, Client>::iterator
i = m_players.begin(),
e = m_players.end();
for ( ; i!=e; ++i)
if (i->second.pid && (i->second.pid != skip_pid))
i->second.socket.Send(packet);
}
#ifdef USE_UPNP
#include <miniwget.h>
#include <miniupnpc.h>
#include <upnpcommands.h>
struct UPNPUrls NetPlayServer::m_upnp_urls;
struct IGDdatas NetPlayServer::m_upnp_data;
u16 NetPlayServer::m_upnp_mapped = 0;
bool NetPlayServer::m_upnp_inited = false;
bool NetPlayServer::m_upnp_error = false;
std::thread NetPlayServer::m_upnp_thread;
// called from ---GUI--- thread
void NetPlayServer::TryPortmapping(u16 port)
{
if (m_upnp_thread.joinable())
m_upnp_thread.join();
m_upnp_thread = std::thread(&NetPlayServer::mapPortThread, port);
}
// UPnP thread: try to map a port
void NetPlayServer::mapPortThread(const u16 port)
{
std::string ourIP = sf::IPAddress::GetLocalAddress().ToString();
if (!m_upnp_inited)
if (!initUPnP())
goto fail;
if (!UPnPMapPort(ourIP, port))
goto fail;
NOTICE_LOG(NETPLAY, "Successfully mapped port %d to %s.", port, ourIP.c_str());
return;
fail:
WARN_LOG(NETPLAY, "Failed to map port %d to %s.", port, ourIP.c_str());
return;
}
// UPnP thread: try to unmap a port
void NetPlayServer::unmapPortThread()
{
if (m_upnp_mapped > 0)
UPnPUnmapPort(m_upnp_mapped);
}
// called from ---UPnP--- thread
// discovers the IGD
bool NetPlayServer::initUPnP()
{
UPNPDev *devlist, *dev;
std::vector<UPNPDev *> igds;
int descXMLsize = 0, upnperror = 0;
char *descXML;
// Don't init if already inited
if (m_upnp_inited)
return true;
// Don't init if it failed before
if (m_upnp_error)
return false;
memset(&m_upnp_urls, 0, sizeof(UPNPUrls));
memset(&m_upnp_data, 0, sizeof(IGDdatas));
// Find all UPnP devices
devlist = upnpDiscover(2000, NULL, NULL, 0, 0, &upnperror);
if (!devlist)
{
WARN_LOG(NETPLAY, "An error occured trying to discover UPnP devices.");
m_upnp_error = true;
m_upnp_inited = false;
return false;
}
// Look for the IGD
dev = devlist;
while (dev)
{
if (strstr(dev->st, "InternetGatewayDevice"))
igds.push_back(dev);
dev = dev->pNext;
}
std::vector<UPNPDev *>::iterator i;
for (i = igds.begin(); i != igds.end(); i++)
{
dev = *i;
descXML = (char *) miniwget(dev->descURL, &descXMLsize, 0);
if (descXML)
{
parserootdesc(descXML, descXMLsize, &m_upnp_data);
free(descXML);
descXML = 0;
GetUPNPUrls(&m_upnp_urls, &m_upnp_data, dev->descURL, 0);
NOTICE_LOG(NETPLAY, "Got info from IGD at %s.", dev->descURL);
break;
}
else
{
WARN_LOG(NETPLAY, "Error getting info from IGD at %s.", dev->descURL);
}
}
freeUPNPDevlist(devlist);
return true;
}
// called from ---UPnP--- thread
// Attempt to portforward!
bool NetPlayServer::UPnPMapPort(const std::string& addr, const u16 port)
{
char port_str[6] = { 0 };
int result;
if (m_upnp_mapped > 0)
UPnPUnmapPort(m_upnp_mapped);
sprintf(port_str, "%d", port);
result = UPNP_AddPortMapping(m_upnp_urls.controlURL, m_upnp_data.first.servicetype,
port_str, port_str, addr.c_str(),
(std::string("dolphin-emu TCP on ") + addr).c_str(),
"TCP", NULL, NULL);
if(result != 0)
return false;
m_upnp_mapped = port;
return true;
}
// called from ---UPnP--- thread
// Attempt to stop portforwarding.
// --
// NOTE: It is important that this happens! A few very crappy routers
// apparently do not delete UPnP mappings on their own, so if you leave them
// hanging, the NVRAM will fill with portmappings, and eventually all UPnP
// requests will fail silently, with the only recourse being a factory reset.
// --
bool NetPlayServer::UPnPUnmapPort(const u16 port)
{
char port_str[6] = { 0 };
sprintf(port_str, "%d", port);
UPNP_DeletePortMapping(m_upnp_urls.controlURL, m_upnp_data.first.servicetype,
port_str, "TCP", NULL);
return true;
}
#endif