1 /*  RetroArch - A frontend for libretro.
2  *  Copyright (C) 2010-2014 - Hans-Kristian Arntzen
3  *  Copyright (C) 2011-2021 - Daniel De Matteis
4  *  Copyright (C) 2016-2017 - Gregor Richards
5  *
6  *  RetroArch is free software: you can redistribute it and/or modify it under the terms
7  *  of the GNU General Public License as published by the Free Software Found-
8  *  ation, either version 3 of the License, or (at your option) any later version.
9  *
10  *  RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
11  *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
12  *  PURPOSE.  See the GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License along with RetroArch.
15  *  If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #if defined(_MSC_VER) && !defined(_XBOX)
19 #pragma comment(lib, "ws2_32")
20 #endif
21 
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <sys/types.h>
25 
26 #include <boolean.h>
27 #include <compat/strl.h>
28 #include <encodings/crc32.h>
29 
30 #include <net/net_compat.h>
31 #include <net/net_socket.h>
32 
33 #include "netplay_private.h"
34 #include "netplay_discovery.h"
35 
36 #include "../../autosave.h"
37 #include "../../configuration.h"
38 #include "../../driver.h"
39 #include "../../retroarch.h"
40 #include "../../command.h"
41 #include "../../tasks/tasks_internal.h"
42 
43 #include "../../input/input_driver.h"
44 
45 #if defined(AF_INET6) && !defined(HAVE_SOCKET_LEGACY) && !defined(_3DS)
46 #define HAVE_INET6 1
47 #endif
48 
49 #ifdef HAVE_DISCORD
50 #include "../discord.h"
51 
52 /* TODO/FIXME - global public variable */
53 extern bool discord_is_inited;
54 #endif
55 
56 struct vote_count
57 {
58    uint16_t votes[32];
59 };
60 
61 /* The mapping of keys from netplay (network) to libretro (host) */
62 const uint16_t netplay_key_ntoh_mapping[] = {
63    (uint16_t) RETROK_UNKNOWN,
64 #define K(k) (uint16_t) RETROK_ ## k,
65 #define KL(k,l) (uint16_t) l,
66 #include "netplay_keys.h"
67 #undef KL
68 #undef K
69    0
70 };
71 
72 /* TODO/FIXME - static global variables */
73 static uint16_t netplay_mapping[RETROK_LAST];
74 
75 /* The mapping of keys from libretro (host) to netplay (network) */
netplay_key_hton(unsigned key)76 uint32_t netplay_key_hton(unsigned key)
77 {
78    if (key >= RETROK_LAST)
79       return NETPLAY_KEY_UNKNOWN;
80    return netplay_mapping[key];
81 }
82 
83 /* Because the hton keymapping has to be generated, call this before using
84  * netplay_key_hton */
netplay_key_hton_init(void)85 void netplay_key_hton_init(void)
86 {
87    static bool mapping_defined = false;
88 
89    if (!mapping_defined)
90    {
91       uint16_t i;
92       for (i = 0; i < NETPLAY_KEY_LAST; i++)
93          netplay_mapping[NETPLAY_KEY_NTOH(i)] = i;
94       mapping_defined = true;
95    }
96 }
97 
clear_input(netplay_input_state_t istate)98 static void clear_input(netplay_input_state_t istate)
99 {
100    while (istate)
101    {
102       istate->used = false;
103       istate       = istate->next;
104    }
105 }
106 
107 /**
108  * netplay_delta_frame_ready
109  *
110  * Prepares, if possible, a delta frame for input, and reports whether it is
111  * ready.
112  *
113  * Returns: True if the delta frame is ready for input at the given frame,
114  * false otherwise.
115  */
netplay_delta_frame_ready(netplay_t * netplay,struct delta_frame * delta,uint32_t frame)116 bool netplay_delta_frame_ready(netplay_t *netplay, struct delta_frame *delta,
117    uint32_t frame)
118 {
119    size_t i;
120    if (delta->used)
121    {
122       if (delta->frame == frame)
123          return true;
124       /* We haven't even replayed this frame yet,
125        * so we can't overwrite it! */
126       if (netplay->other_frame_count <= delta->frame)
127          return false;
128    }
129 
130    delta->used  = true;
131    delta->frame = frame;
132    delta->crc   = 0;
133 
134    for (i = 0; i < MAX_INPUT_DEVICES; i++)
135    {
136       clear_input(delta->resolved_input[i]);
137       clear_input(delta->real_input[i]);
138       clear_input(delta->simlated_input[i]);
139    }
140    delta->have_local = false;
141    for (i = 0; i < MAX_CLIENTS; i++)
142       delta->have_real[i] = false;
143    return true;
144 }
145 
146 /**
147  * netplay_delta_frame_crc
148  *
149  * Get the CRC for the serialization of this frame.
150  */
netplay_delta_frame_crc(netplay_t * netplay,struct delta_frame * delta)151 static uint32_t netplay_delta_frame_crc(netplay_t *netplay,
152       struct delta_frame *delta)
153 {
154    return encoding_crc32(0L, (const unsigned char*)delta->state,
155          netplay->state_size);
156 }
157 
158 /*
159  * Free an input state list
160  */
free_input_state(netplay_input_state_t * list)161 static void free_input_state(netplay_input_state_t *list)
162 {
163    netplay_input_state_t cur, next;
164    cur = *list;
165    while (cur)
166    {
167       next = cur->next;
168       free(cur);
169       cur = next;
170    }
171    *list = NULL;
172 }
173 
174 /**
175  * netplay_delta_frame_free
176  *
177  * Free a delta frame's dependencies
178  */
netplay_delta_frame_free(struct delta_frame * delta)179 static void netplay_delta_frame_free(struct delta_frame *delta)
180 {
181    uint32_t i;
182 
183    if (delta->state)
184    {
185       free(delta->state);
186       delta->state = NULL;
187    }
188 
189    for (i = 0; i < MAX_INPUT_DEVICES; i++)
190    {
191       free_input_state(&delta->resolved_input[i]);
192       free_input_state(&delta->real_input[i]);
193       free_input_state(&delta->simlated_input[i]);
194    }
195 }
196 
197 /**
198  * netplay_input_state_for
199  *
200  * Get an input state for a particular client
201  */
netplay_input_state_for(netplay_input_state_t * list,uint32_t client_num,size_t size,bool must_create,bool must_not_create)202 netplay_input_state_t netplay_input_state_for(
203       netplay_input_state_t *list,
204       uint32_t client_num, size_t size,
205       bool must_create, bool must_not_create)
206 {
207    netplay_input_state_t ret;
208    while (*list)
209    {
210       ret = *list;
211       if (!ret->used && !must_not_create && ret->size == size)
212       {
213          ret->client_num = client_num;
214          ret->used       = true;
215          memset(ret->data, 0, size*sizeof(uint32_t));
216          return ret;
217       }
218       else if (ret->used && ret->client_num == client_num)
219       {
220          if (!must_create && ret->size == size)
221             return ret;
222          return NULL;
223       }
224       list = &(ret->next);
225    }
226 
227    if (must_not_create)
228       return NULL;
229 
230    /* Couldn't find a slot, allocate a fresh one */
231    if (size > 1)
232       ret = (netplay_input_state_t)calloc(1, sizeof(struct netplay_input_state) + (size-1) * sizeof(uint32_t));
233 	else
234       ret = (netplay_input_state_t)calloc(1, sizeof(struct netplay_input_state));
235    if (!ret)
236       return NULL;
237    *list           = ret;
238    ret->client_num = client_num;
239    ret->used       = true;
240    ret->size       = (uint32_t)size;
241    return ret;
242 }
243 
244 /**
245  * netplay_expected_input_size
246  *
247  * Size in words for a given set of devices.
248  */
netplay_expected_input_size(netplay_t * netplay,uint32_t devices)249 uint32_t netplay_expected_input_size(netplay_t *netplay, uint32_t devices)
250 {
251    uint32_t ret = 0, device;
252 
253    for (device = 0; device < MAX_INPUT_DEVICES; device++)
254    {
255       if (!(devices & (1<<device)))
256          continue;
257 
258       switch (netplay->config_devices[device]&RETRO_DEVICE_MASK)
259       {
260          /* These are all essentially magic numbers, but each device has a
261           * fixed size, documented in network/netplay/README */
262          case RETRO_DEVICE_JOYPAD:
263             ret += 1;
264             break;
265          case RETRO_DEVICE_MOUSE:
266             ret += 2;
267             break;
268          case RETRO_DEVICE_KEYBOARD:
269             ret += 5;
270             break;
271          case RETRO_DEVICE_LIGHTGUN:
272             ret += 2;
273             break;
274          case RETRO_DEVICE_ANALOG:
275             ret += 3;
276             break;
277          default:
278             break; /* Unsupported */
279       }
280    }
281 
282    return ret;
283 }
284 
buf_used(struct socket_buffer * sbuf)285 static size_t buf_used(struct socket_buffer *sbuf)
286 {
287    if (sbuf->end < sbuf->start)
288    {
289       size_t newend = sbuf->end;
290       while (newend < sbuf->start)
291          newend += sbuf->bufsz;
292       return newend - sbuf->start;
293    }
294 
295    return sbuf->end - sbuf->start;
296 }
297 
buf_unread(struct socket_buffer * sbuf)298 static size_t buf_unread(struct socket_buffer *sbuf)
299 {
300    if (sbuf->end < sbuf->read)
301    {
302       size_t newend = sbuf->end;
303       while (newend < sbuf->read)
304          newend += sbuf->bufsz;
305       return newend - sbuf->read;
306    }
307 
308    return sbuf->end - sbuf->read;
309 }
310 
buf_remaining(struct socket_buffer * sbuf)311 static size_t buf_remaining(struct socket_buffer *sbuf)
312 {
313    return sbuf->bufsz - buf_used(sbuf) - 1;
314 }
315 
316 /**
317  * netplay_init_socket_buffer
318  *
319  * Initialize a new socket buffer.
320  */
netplay_init_socket_buffer(struct socket_buffer * sbuf,size_t size)321 static bool netplay_init_socket_buffer(
322       struct socket_buffer *sbuf, size_t size)
323 {
324    sbuf->data = (unsigned char*)malloc(size);
325    if (!sbuf->data)
326       return false;
327    sbuf->bufsz = size;
328    sbuf->start = sbuf->read = sbuf->end = 0;
329    return true;
330 }
331 
332 /**
333  * netplay_resize_socket_buffer
334  *
335  * Resize the given socket_buffer's buffer to the requested size.
336  */
netplay_resize_socket_buffer(struct socket_buffer * sbuf,size_t newsize)337 static bool netplay_resize_socket_buffer(
338       struct socket_buffer *sbuf, size_t newsize)
339 {
340    unsigned char *newdata = (unsigned char*)malloc(newsize);
341    if (!newdata)
342       return false;
343 
344     /* Copy in the old data */
345     if (sbuf->end < sbuf->start)
346     {
347        memcpy(newdata,
348              sbuf->data + sbuf->start,
349              sbuf->bufsz - sbuf->start);
350        memcpy(newdata + sbuf->bufsz - sbuf->start,
351              sbuf->data,
352              sbuf->end);
353     }
354     else if (sbuf->end > sbuf->start)
355        memcpy(newdata,
356              sbuf->data + sbuf->start,
357              sbuf->end - sbuf->start);
358 
359     /* Adjust our read offset */
360     if (sbuf->read < sbuf->start)
361        sbuf->read += sbuf->bufsz - sbuf->start;
362     else
363        sbuf->read -= sbuf->start;
364 
365     /* Adjust start and end */
366     sbuf->end      = buf_used(sbuf);
367     sbuf->start    = 0;
368 
369     /* Free the old one and replace it with the new one */
370     free(sbuf->data);
371     sbuf->data     = newdata;
372     sbuf->bufsz    = newsize;
373 
374     return true;
375 }
376 
377 /**
378  * netplay_deinit_socket_buffer
379  *
380  * Free a socket buffer.
381  */
netplay_deinit_socket_buffer(struct socket_buffer * sbuf)382 static void netplay_deinit_socket_buffer(struct socket_buffer *sbuf)
383 {
384    if (sbuf->data)
385       free(sbuf->data);
386 }
387 
388 #if 0
389 static void netplay_clear_socket_buffer(struct socket_buffer *sbuf)
390 {
391    sbuf->start = sbuf->read = sbuf->end = 0;
392 }
393 #endif
394 
395 /**
396  * netplay_send
397  *
398  * Queue the given data for sending.
399  */
netplay_send(struct socket_buffer * sbuf,int sockfd,const void * buf,size_t len)400 bool netplay_send(
401       struct socket_buffer *sbuf,
402       int sockfd, const void *buf,
403       size_t len)
404 {
405    if (buf_remaining(sbuf) < len)
406    {
407       /* Need to force a blocking send */
408       if (!netplay_send_flush(sbuf, sockfd, true))
409          return false;
410    }
411 
412    if (buf_remaining(sbuf) < len)
413    {
414       /* Can only be that this is simply too big
415        * for our buffer, in which case we just
416        * need to do a blocking send */
417       if (!socket_send_all_blocking(sockfd, buf, len, false))
418          return false;
419       return true;
420    }
421 
422    /* Copy it into our buffer */
423    if (sbuf->bufsz - sbuf->end < len)
424    {
425       /* Half at a time */
426       size_t chunka = sbuf->bufsz - sbuf->end,
427              chunkb = len - chunka;
428       memcpy(sbuf->data + sbuf->end, buf, chunka);
429       memcpy(sbuf->data, (const unsigned char *)buf + chunka, chunkb);
430       sbuf->end = chunkb;
431 
432    }
433    else
434    {
435       /* Straight in */
436       memcpy(sbuf->data + sbuf->end, buf, len);
437       sbuf->end += len;
438    }
439 
440    return true;
441 }
442 
443 /**
444  * netplay_send_flush
445  *
446  * Flush unsent data in the given socket buffer, blocking to do so if
447  * requested.
448  *
449  * Returns false only on socket failures, true otherwise.
450  */
netplay_send_flush(struct socket_buffer * sbuf,int sockfd,bool block)451 bool netplay_send_flush(struct socket_buffer *sbuf, int sockfd, bool block)
452 {
453    ssize_t sent;
454 
455    if (buf_used(sbuf) == 0)
456       return true;
457 
458    if (sbuf->end > sbuf->start)
459    {
460       /* Usual case: Everything's in order */
461       if (block)
462       {
463          if (!socket_send_all_blocking(
464                   sockfd, sbuf->data + sbuf->start,
465                   buf_used(sbuf), true))
466             return false;
467 
468          sbuf->start = sbuf->end = 0;
469       }
470       else
471       {
472          sent = socket_send_all_nonblocking(
473                sockfd, sbuf->data + sbuf->start,
474                buf_used(sbuf), true);
475 
476          if (sent < 0)
477             return false;
478 
479          sbuf->start += sent;
480 
481          if (sbuf->start == sbuf->end)
482             sbuf->start = sbuf->end = 0;
483       }
484    }
485    else
486    {
487       /* Unusual case: Buffer overlaps break */
488       if (block)
489       {
490          if (!socket_send_all_blocking(
491                   sockfd, sbuf->data + sbuf->start,
492                   sbuf->bufsz - sbuf->start, true))
493             return false;
494 
495          sbuf->start = 0;
496 
497          return netplay_send_flush(sbuf, sockfd, true);
498       }
499       else
500       {
501          sent = socket_send_all_nonblocking(
502                sockfd, sbuf->data + sbuf->start,
503                sbuf->bufsz - sbuf->start, true);
504 
505          if (sent < 0)
506             return false;
507 
508          sbuf->start += sent;
509 
510          if (sbuf->start >= sbuf->bufsz)
511          {
512             sbuf->start = 0;
513             return netplay_send_flush(sbuf, sockfd, false);
514          }
515       }
516 
517    }
518 
519    return true;
520 }
521 
522 /**
523  * netplay_recv
524  *
525  * Receive buffered or fresh data.
526  *
527  * Returns number of bytes returned, which may be short or 0, or -1 on error.
528  */
netplay_recv(struct socket_buffer * sbuf,int sockfd,void * buf,size_t len,bool block)529 ssize_t netplay_recv(struct socket_buffer *sbuf, int sockfd, void *buf,
530    size_t len, bool block)
531 {
532    ssize_t recvd;
533    bool error    = false;
534 
535    /* Receive whatever we can into the buffer */
536    if (sbuf->end >= sbuf->start)
537    {
538       recvd = socket_receive_all_nonblocking(sockfd, &error,
539          sbuf->data + sbuf->end, sbuf->bufsz - sbuf->end -
540          ((sbuf->start == 0) ? 1 : 0));
541 
542       if (recvd < 0 || error)
543          return -1;
544 
545       sbuf->end += recvd;
546 
547       if (sbuf->end >= sbuf->bufsz)
548       {
549          sbuf->end = 0;
550          error     = false;
551          recvd     = socket_receive_all_nonblocking(
552                sockfd, &error, sbuf->data, sbuf->start - 1);
553 
554          if (recvd < 0 || error)
555             return -1;
556 
557          sbuf->end += recvd;
558       }
559    }
560    else
561    {
562       recvd = socket_receive_all_nonblocking(
563             sockfd, &error, sbuf->data + sbuf->end,
564             sbuf->start - sbuf->end - 1);
565 
566       if (recvd < 0 || error)
567          return -1;
568 
569       sbuf->end += recvd;
570    }
571 
572    /* Now copy it into the reader */
573    if (sbuf->end >= sbuf->read || (sbuf->bufsz - sbuf->read) >= len)
574    {
575       size_t unread = buf_unread(sbuf);
576       if (len <= unread)
577       {
578          memcpy(buf, sbuf->data + sbuf->read, len);
579          sbuf->read += len;
580          if (sbuf->read >= sbuf->bufsz)
581             sbuf->read = 0;
582          recvd = len;
583 
584       }
585       else
586       {
587          memcpy(buf, sbuf->data + sbuf->read, unread);
588          sbuf->read += unread;
589          if (sbuf->read >= sbuf->bufsz)
590             sbuf->read = 0;
591          recvd = unread;
592       }
593    }
594    else
595    {
596       /* Our read goes around the edge */
597       size_t chunka = sbuf->bufsz - sbuf->read,
598              pchunklen = len - chunka,
599              chunkb = (pchunklen >= sbuf->end) ? sbuf->end : pchunklen;
600       memcpy(buf, sbuf->data + sbuf->read, chunka);
601       memcpy((unsigned char *) buf + chunka, sbuf->data, chunkb);
602       sbuf->read = chunkb;
603       recvd      = chunka + chunkb;
604    }
605 
606    /* Perhaps block for more data */
607    if (block)
608    {
609       sbuf->start = sbuf->read;
610       if (recvd < 0 || recvd < (ssize_t) len)
611       {
612          if (!socket_receive_all_blocking(
613                   sockfd, (unsigned char *)buf + recvd, len - recvd))
614             return -1;
615          recvd = len;
616       }
617    }
618 
619    return recvd;
620 }
621 
622 /**
623  * netplay_recv_reset
624  *
625  * Reset our recv buffer so that future netplay_recvs
626  * will read the same data again.
627  */
netplay_recv_reset(struct socket_buffer * sbuf)628 void netplay_recv_reset(struct socket_buffer *sbuf)
629 {
630    sbuf->read = sbuf->start;
631 }
632 
633 /**
634  * netplay_recv_flush
635  *
636  * Flush our recv buffer, so a future netplay_recv_reset will reset to this
637  * point.
638  */
netplay_recv_flush(struct socket_buffer * sbuf)639 void netplay_recv_flush(struct socket_buffer *sbuf)
640 {
641    sbuf->start = sbuf->read;
642 }
643 
644 /**
645  * netplay_cmd_crc
646  *
647  * Send a CRC command to all active clients.
648  */
netplay_cmd_crc(netplay_t * netplay,struct delta_frame * delta)649 static bool netplay_cmd_crc(netplay_t *netplay, struct delta_frame *delta)
650 {
651    size_t i;
652    uint32_t payload[2];
653    bool success = true;
654 
655    payload[0]   = htonl(delta->frame);
656    payload[1]   = htonl(delta->crc);
657 
658    for (i = 0; i < netplay->connections_size; i++)
659    {
660       if (netplay->connections[i].active &&
661             netplay->connections[i].mode >= NETPLAY_CONNECTION_CONNECTED)
662          success = netplay_send_raw_cmd(netplay, &netplay->connections[i],
663             NETPLAY_CMD_CRC, payload, sizeof(payload)) && success;
664    }
665    return success;
666 }
667 
668 /**
669  * netplay_cmd_request_savestate
670  *
671  * Send a savestate request command.
672  */
netplay_cmd_request_savestate(netplay_t * netplay)673 static bool netplay_cmd_request_savestate(netplay_t *netplay)
674 {
675    if (netplay->connections_size == 0 ||
676        !netplay->connections[0].active ||
677        netplay->connections[0].mode < NETPLAY_CONNECTION_CONNECTED)
678       return false;
679    if (netplay->savestate_request_outstanding)
680       return true;
681    netplay->savestate_request_outstanding = true;
682    return netplay_send_raw_cmd(netplay, &netplay->connections[0],
683       NETPLAY_CMD_REQUEST_SAVESTATE, NULL, 0);
684 }
685 
686 /**
687  * netplay_cmd_stall
688  *
689  * Send a stall command.
690  */
netplay_cmd_stall(netplay_t * netplay,struct netplay_connection * connection,uint32_t frames)691 static bool netplay_cmd_stall(netplay_t *netplay,
692    struct netplay_connection *connection,
693    uint32_t frames)
694 {
695    frames = htonl(frames);
696    return netplay_send_raw_cmd(netplay, connection, NETPLAY_CMD_STALL, &frames, sizeof(frames));
697 }
698 
699 
700 
701 static void handle_play_spectate(netplay_t *netplay, uint32_t client_num,
702       struct netplay_connection *connection, uint32_t cmd, uint32_t cmd_size,
703       uint32_t *payload);
704 
705 #if 0
706 #define DEBUG_NONDETERMINISTIC_CORES
707 #endif
708 
709 /**
710  * netplay_update_unread_ptr
711  *
712  * Update the global unread_ptr and unread_frame_count to correspond to the
713  * earliest unread frame count of any connected player
714  */
netplay_update_unread_ptr(netplay_t * netplay)715 void netplay_update_unread_ptr(netplay_t *netplay)
716 {
717    if (netplay->is_server && netplay->connected_players<=1)
718    {
719       /* Nothing at all to read! */
720       netplay->unread_ptr         = netplay->self_ptr;
721       netplay->unread_frame_count = netplay->self_frame_count;
722 
723    }
724    else
725    {
726       size_t           new_unread_ptr = 0;
727       uint32_t new_unread_frame_count = (uint32_t) -1;
728       uint32_t client;
729 
730       for (client = 0; client < MAX_CLIENTS; client++)
731       {
732          if (!(netplay->connected_players & (1 << client)))
733             continue;
734          if ((netplay->connected_slaves   & (1 << client)))
735             continue;
736 
737          if (netplay->read_frame_count[client] < new_unread_frame_count)
738          {
739             new_unread_ptr         = netplay->read_ptr[client];
740             new_unread_frame_count = netplay->read_frame_count[client];
741          }
742       }
743 
744       if ( !netplay->is_server &&
745             netplay->server_frame_count < new_unread_frame_count)
746       {
747          new_unread_ptr              = netplay->server_ptr;
748          new_unread_frame_count      = netplay->server_frame_count;
749       }
750 
751       if (new_unread_frame_count != (uint32_t) -1)
752       {
753          netplay->unread_ptr         = new_unread_ptr;
754          netplay->unread_frame_count = new_unread_frame_count;
755       }
756       else
757       {
758          netplay->unread_ptr         = netplay->self_ptr;
759          netplay->unread_frame_count = netplay->self_frame_count;
760       }
761    }
762 }
763 
764 /**
765  * netplay_device_client_state
766  * @netplay             : pointer to netplay object
767  * @simframe            : frame in which merging is being performed
768  * @device              : device being merged
769  * @client              : client to find state for
770  */
netplay_device_client_state(netplay_t * netplay,struct delta_frame * simframe,uint32_t device,uint32_t client)771 netplay_input_state_t netplay_device_client_state(netplay_t *netplay,
772       struct delta_frame *simframe, uint32_t device, uint32_t client)
773 {
774    uint32_t                 dsize =
775       netplay_expected_input_size(netplay, 1 << device);
776    netplay_input_state_t simstate =
777       netplay_input_state_for(
778          &simframe->real_input[device], client,
779          dsize, false, true);
780 
781    if (!simstate)
782    {
783       if (netplay->read_frame_count[client] > simframe->frame)
784          return NULL;
785       simstate = netplay_input_state_for(&simframe->simlated_input[device],
786             client, dsize, false, true);
787    }
788    return simstate;
789 }
790 
791 /**
792  * netplay_merge_digital
793  * @netplay             : pointer to netplay object
794  * @resstate            : state being resolved
795  * @simframe            : frame in which merging is being performed
796  * @device              : device being merged
797  * @clients             : bitmap of clients being merged
798  * @digital             : bitmap of digital bits
799  */
netplay_merge_digital(netplay_t * netplay,netplay_input_state_t resstate,struct delta_frame * simframe,uint32_t device,uint32_t clients,const uint32_t * digital)800 static void netplay_merge_digital(netplay_t *netplay,
801       netplay_input_state_t resstate, struct delta_frame *simframe,
802       uint32_t device, uint32_t clients, const uint32_t *digital)
803 {
804    netplay_input_state_t simstate;
805    uint32_t word, bit, client;
806    uint8_t share_mode = netplay->device_share_modes[device]
807       & NETPLAY_SHARE_DIGITAL_BITS;
808 
809    /* Make sure all real clients are accounted for */
810    for (simstate = simframe->real_input[device];
811          simstate; simstate = simstate->next)
812    {
813       if (!simstate->used || simstate->size != resstate->size)
814          continue;
815       clients |= 1 << simstate->client_num;
816    }
817 
818    if (share_mode == NETPLAY_SHARE_DIGITAL_VOTE)
819    {
820       unsigned i, j;
821       /* This just assumes we have no more than
822        * three words, will need to be adjusted for new devices */
823       struct vote_count votes[3];
824       /* Vote mode requires counting all the bits */
825       uint32_t client_count      = 0;
826 
827       for (i = 0; i < 3; i++)
828          for (j = 0; j < 32; j++)
829             votes[i].votes[j] = 0;
830 
831       for (client = 0; client < MAX_CLIENTS; client++)
832       {
833          if (!(clients & (1 << client)))
834             continue;
835 
836          simstate = netplay_device_client_state(
837                netplay, simframe, device, client);
838 
839          if (!simstate)
840             continue;
841          client_count++;
842 
843          for (word = 0; word < resstate->size; word++)
844          {
845             if (!digital[word])
846                continue;
847             for (bit = 0; bit < 32; bit++)
848             {
849                if (!(digital[word] & (1 << bit)))
850                   continue;
851                if (simstate->data[word] & (1 << bit))
852                   votes[word].votes[bit]++;
853             }
854          }
855       }
856 
857       /* Now count all the bits */
858       client_count /= 2;
859       for (word = 0; word < resstate->size; word++)
860       {
861          for (bit = 0; bit < 32; bit++)
862          {
863             if (votes[word].votes[bit] > client_count)
864                resstate->data[word] |= (1 << bit);
865          }
866       }
867    }
868    else /* !VOTE */
869    {
870       for (client = 0; client < MAX_CLIENTS; client++)
871       {
872          if (!(clients & (1 << client)))
873             continue;
874          simstate = netplay_device_client_state(
875                netplay, simframe, device, client);
876 
877          if (!simstate)
878             continue;
879          for (word = 0; word < resstate->size; word++)
880          {
881             uint32_t part;
882             if (!digital[word])
883                continue;
884             part = simstate->data[word];
885 
886             if (digital[word] == (uint32_t) -1)
887             {
888                /* Combine the whole word */
889                switch (share_mode)
890                {
891                   case NETPLAY_SHARE_DIGITAL_XOR:
892                      resstate->data[word] ^= part;
893                      break;
894                   default:
895                      resstate->data[word] |= part;
896                }
897 
898             }
899             else /* !whole word */
900             {
901                for (bit = 0; bit < 32; bit++)
902                {
903                   if (!(digital[word] & (1 << bit)))
904                      continue;
905                   switch (share_mode)
906                   {
907                      case NETPLAY_SHARE_DIGITAL_XOR:
908                         resstate->data[word] ^= part & (1 << bit);
909                         break;
910                      default:
911                         resstate->data[word] |= part & (1 << bit);
912                   }
913                }
914             }
915          }
916       }
917 
918    }
919 }
920 
921 /**
922  * merge_analog_part
923  * @netplay             : pointer to netplay object
924  * @resstate            : state being resolved
925  * @simframe            : frame in which merging is being performed
926  * @device              : device being merged
927  * @clients             : bitmap of clients being merged
928  * @word                : word to merge
929  * @bit                 : first bit to merge
930  */
merge_analog_part(netplay_t * netplay,netplay_input_state_t resstate,struct delta_frame * simframe,uint32_t device,uint32_t clients,uint32_t word,uint8_t bit)931 static void merge_analog_part(netplay_t *netplay,
932       netplay_input_state_t resstate, struct delta_frame *simframe,
933       uint32_t device, uint32_t clients, uint32_t word, uint8_t bit)
934 {
935    netplay_input_state_t simstate;
936    uint32_t client, client_count = 0;
937    uint8_t share_mode            = netplay->device_share_modes[device]
938       & NETPLAY_SHARE_ANALOG_BITS;
939    int32_t value                 = 0, new_value;
940 
941    /* Make sure all real clients are accounted for */
942    for (simstate = simframe->real_input[device]; simstate; simstate = simstate->next)
943    {
944       if (!simstate->used || simstate->size != resstate->size)
945          continue;
946       clients |= 1 << simstate->client_num;
947    }
948 
949    for (client = 0; client < MAX_CLIENTS; client++)
950    {
951       if (!(clients & (1 << client)))
952          continue;
953       simstate = netplay_device_client_state(
954             netplay, simframe, device, client);
955       if (!simstate)
956          continue;
957       client_count++;
958       new_value = (int16_t) ((simstate->data[word]>>bit) & 0xFFFF);
959       switch (share_mode)
960       {
961          case NETPLAY_SHARE_ANALOG_AVERAGE:
962             value += (int32_t) new_value;
963             break;
964          default:
965             if (abs(new_value) > abs(value) ||
966                 (abs(new_value) == abs(value) && new_value > value))
967                value = new_value;
968       }
969    }
970 
971    if (share_mode == NETPLAY_SHARE_ANALOG_AVERAGE)
972       if (client_count > 0) /* Prevent potential divide by zero */
973          value /= client_count;
974 
975    resstate->data[word] |= ((uint32_t) (uint16_t) value) << bit;
976 }
977 
978 /**
979  * netplay_merge_analog
980  * @netplay             : pointer to netplay object
981  * @resstate            : state being resolved
982  * @simframe            : frame in which merging is being performed
983  * @device              : device being merged
984  * @clients             : bitmap of clients being merged
985  * @dtype               : device type
986  */
netplay_merge_analog(netplay_t * netplay,netplay_input_state_t resstate,struct delta_frame * simframe,uint32_t device,uint32_t clients,unsigned dtype)987 static void netplay_merge_analog(netplay_t *netplay,
988       netplay_input_state_t resstate, struct delta_frame *simframe,
989       uint32_t device, uint32_t clients, unsigned dtype)
990 {
991    /* Devices with no analog parts */
992    if (dtype == RETRO_DEVICE_JOYPAD || dtype == RETRO_DEVICE_KEYBOARD)
993       return;
994 
995    /* All other devices have at least one analog word */
996    merge_analog_part(netplay, resstate, simframe, device, clients, 1, 0);
997    merge_analog_part(netplay, resstate, simframe, device, clients, 1, 16);
998 
999    /* And the ANALOG device has two (two sticks) */
1000    if (dtype == RETRO_DEVICE_ANALOG)
1001    {
1002       merge_analog_part(netplay, resstate, simframe, device, clients, 2, 0);
1003       merge_analog_part(netplay, resstate, simframe, device, clients, 2, 16);
1004    }
1005 }
1006 
1007 /**
1008  * netplay_resolve_input
1009  * @netplay             : pointer to netplay object
1010  * @sim_ptr             : frame pointer for which to resolve input
1011  * @resim               : are we resimulating, or simulating this frame for the
1012  *                        first time?
1013  *
1014  * "Simulate" input by assuming it hasn't changed since the last read input.
1015  * Returns true if the resolved input changed from the last time it was
1016  * resolved.
1017  */
netplay_resolve_input(netplay_t * netplay,size_t sim_ptr,bool resim)1018 bool netplay_resolve_input(netplay_t *netplay, size_t sim_ptr, bool resim)
1019 {
1020    size_t prev;
1021    uint32_t device;
1022    uint32_t clients, client, client_count;
1023    netplay_input_state_t simstate, client_state = NULL,
1024                          resstate, oldresstate, pstate;
1025    bool ret                     = false;
1026    struct delta_frame *pframe   = NULL;
1027    struct delta_frame *simframe = &netplay->buffer[sim_ptr];
1028 
1029    for (device = 0; device < MAX_INPUT_DEVICES; device++)
1030    {
1031       unsigned dtype = netplay->config_devices[device]&RETRO_DEVICE_MASK;
1032       uint32_t dsize = netplay_expected_input_size(netplay, 1 << device);
1033       clients        = netplay->device_clients[device];
1034       client_count   = 0;
1035 
1036       /* Make sure all real clients are accounted for */
1037       for (simstate = simframe->real_input[device]; simstate; simstate = simstate->next)
1038       {
1039          if (!simstate->used || simstate->size != dsize)
1040             continue;
1041          clients |= 1 << simstate->client_num;
1042       }
1043 
1044       for (client = 0; client < MAX_CLIENTS; client++)
1045       {
1046          if (!(clients & (1 << client)))
1047             continue;
1048 
1049          /* Resolve this client-device */
1050          simstate = netplay_input_state_for(
1051                &simframe->real_input[device], client, dsize, false, true);
1052          if (!simstate)
1053          {
1054             /* Don't already have this input, so must
1055              * simulate if we're supposed to have it at all */
1056             if (netplay->read_frame_count[client] > simframe->frame)
1057                continue;
1058             simstate = netplay_input_state_for(&simframe->simlated_input[device], client, dsize, false, false);
1059             if (!simstate)
1060                continue;
1061 
1062             prev = PREV_PTR(netplay->read_ptr[client]);
1063             pframe = &netplay->buffer[prev];
1064             pstate = netplay_input_state_for(&pframe->real_input[device], client, dsize, false, true);
1065             if (!pstate)
1066                continue;
1067 
1068             if (resim && (dtype == RETRO_DEVICE_JOYPAD || dtype == RETRO_DEVICE_ANALOG))
1069             {
1070                /* In resimulation mode, we only copy the buttons. The reason for this
1071                 * is nonobvious:
1072                 *
1073                 * If we resimulated nothing, then the /duration/ with which any input
1074                 * was pressed would be approximately correct, since the original
1075                 * simulation came in as the input came in, but the /number of times/
1076                 * the input was pressed would be wrong, as there would be an
1077                 * advancing wavefront of real data overtaking the simulated data
1078                 * (which is really just real data offset by some frames).
1079                 *
1080                 * That's acceptable for arrows in most situations, since the amount
1081                 * you move is tied to the duration, but unacceptable for buttons,
1082                 * which will seem to jerkily be pressed numerous times with those
1083                 * wavefronts.
1084                 */
1085                const uint32_t keep =
1086                   (UINT32_C(1) << RETRO_DEVICE_ID_JOYPAD_UP) |
1087                   (UINT32_C(1) << RETRO_DEVICE_ID_JOYPAD_DOWN) |
1088                   (UINT32_C(1) << RETRO_DEVICE_ID_JOYPAD_LEFT) |
1089                   (UINT32_C(1) << RETRO_DEVICE_ID_JOYPAD_RIGHT);
1090                simstate->data[0] &= keep;
1091                simstate->data[0] |= pstate->data[0] & ~keep;
1092             }
1093             else
1094                memcpy(simstate->data, pstate->data,
1095                      dsize * sizeof(uint32_t));
1096          }
1097 
1098          client_state = simstate;
1099          client_count++;
1100       }
1101 
1102       /* The frontend always uses the first resolved input,
1103        * so make sure it's right */
1104       while (simframe->resolved_input[device]
1105             && (simframe->resolved_input[device]->size != dsize
1106                   || simframe->resolved_input[device]->client_num != 0))
1107       {
1108          /* The default resolved input is of the wrong size! */
1109          netplay_input_state_t nextistate =
1110             simframe->resolved_input[device]->next;
1111          free(simframe->resolved_input[device]);
1112          simframe->resolved_input[device] = nextistate;
1113       }
1114 
1115       /* Now we copy the state, whether real or simulated,
1116        * out into the resolved state */
1117       resstate = netplay_input_state_for(
1118             &simframe->resolved_input[device], 0,
1119             dsize, false, false);
1120       if (!resstate)
1121          continue;
1122 
1123       if (client_count == 1)
1124       {
1125          /* Trivial in the common 1-client case */
1126          if (memcmp(resstate->data, client_state->data,
1127                   dsize * sizeof(uint32_t)))
1128             ret = true;
1129          memcpy(resstate->data, client_state->data,
1130                dsize * sizeof(uint32_t));
1131 
1132       }
1133       else if (client_count == 0)
1134       {
1135          uint32_t word;
1136          for (word = 0; word < dsize; word++)
1137          {
1138             if (resstate->data[word])
1139                ret = true;
1140             resstate->data[word] = 0;
1141          }
1142 
1143       }
1144       else
1145       {
1146          /* Merge them */
1147          /* Most devices have all the digital parts in the first word. */
1148          static const uint32_t digital_common[3]   = {~0u, 0u, 0u};
1149          static const uint32_t digital_keyboard[5] = {~0u, ~0u, ~0u, ~0u, ~0u};
1150          const uint32_t *digital                   = digital_common;
1151 
1152          if (dtype == RETRO_DEVICE_KEYBOARD)
1153             digital = digital_keyboard;
1154 
1155          oldresstate = netplay_input_state_for(
1156                &simframe->resolved_input[device], 1, dsize, false, false);
1157 
1158          if (!oldresstate)
1159             continue;
1160          memcpy(oldresstate->data, resstate->data, dsize * sizeof(uint32_t));
1161          memset(resstate->data, 0, dsize * sizeof(uint32_t));
1162 
1163          netplay_merge_digital(netplay, resstate, simframe,
1164                device, clients, digital);
1165          netplay_merge_analog(netplay, resstate, simframe,
1166                device, clients, dtype);
1167 
1168          if (memcmp(resstate->data, oldresstate->data,
1169                   dsize * sizeof(uint32_t)))
1170             ret = true;
1171 
1172       }
1173    }
1174 
1175    return ret;
1176 }
1177 
netplay_handle_frame_hash(netplay_t * netplay,struct delta_frame * delta)1178 static void netplay_handle_frame_hash(netplay_t *netplay,
1179       struct delta_frame *delta)
1180 {
1181    if (netplay->is_server)
1182    {
1183       if (netplay->check_frames &&
1184           delta->frame % abs(netplay->check_frames) == 0)
1185       {
1186          if (netplay->state_size)
1187             delta->crc = netplay_delta_frame_crc(netplay, delta);
1188          else
1189             delta->crc = 0;
1190          netplay_cmd_crc(netplay, delta);
1191       }
1192    }
1193    else if (delta->crc && netplay->crcs_valid)
1194    {
1195       /* We have a remote CRC, so check it */
1196       uint32_t local_crc = 0;
1197       if (netplay->state_size)
1198          local_crc = netplay_delta_frame_crc(netplay, delta);
1199 
1200       if (local_crc != delta->crc)
1201       {
1202          /* If the very first check frame is wrong,
1203           * they probably just don't work */
1204          if (!netplay->crc_validity_checked)
1205             netplay->crcs_valid = false;
1206          else if (netplay->crcs_valid)
1207          {
1208             /* Fix this! */
1209             if (netplay->check_frames < 0)
1210             {
1211                /* Just report */
1212                RARCH_ERR("Netplay CRCs mismatch!\n");
1213             }
1214             else
1215                netplay_cmd_request_savestate(netplay);
1216          }
1217       }
1218       else if (!netplay->crc_validity_checked)
1219          netplay->crc_validity_checked = true;
1220    }
1221 }
1222 
1223 /**
1224  * netplay_sync_pre_frame
1225  * @netplay              : pointer to netplay object
1226  *
1227  * Pre-frame for Netplay synchronization.
1228  */
netplay_sync_pre_frame(netplay_t * netplay)1229 bool netplay_sync_pre_frame(netplay_t *netplay)
1230 {
1231    retro_ctx_serialize_info_t serial_info;
1232 
1233    if (netplay_delta_frame_ready(netplay,
1234             &netplay->buffer[netplay->run_ptr], netplay->run_frame_count))
1235    {
1236       serial_info.data_const = NULL;
1237       serial_info.data       = netplay->buffer[netplay->run_ptr].state;
1238       serial_info.size       = netplay->state_size;
1239 
1240       memset(serial_info.data, 0, serial_info.size);
1241       if ((netplay->quirks & NETPLAY_QUIRK_INITIALIZATION)
1242             || netplay->run_frame_count == 0)
1243       {
1244          /* Don't serialize until it's safe */
1245       }
1246       else if (!(netplay->quirks & NETPLAY_QUIRK_NO_SAVESTATES)
1247             && core_serialize(&serial_info))
1248       {
1249          if (netplay->force_send_savestate && !netplay->stall
1250                && !netplay->remote_paused)
1251          {
1252             /* Bring our running frame and input frames into
1253              * parity so we don't send old info. */
1254             if (netplay->run_ptr != netplay->self_ptr)
1255             {
1256                memcpy(netplay->buffer[netplay->self_ptr].state,
1257                   netplay->buffer[netplay->run_ptr].state,
1258                   netplay->state_size);
1259                netplay->run_ptr         = netplay->self_ptr;
1260                netplay->run_frame_count = netplay->self_frame_count;
1261             }
1262 
1263             /* Send this along to the other side */
1264             serial_info.data_const = netplay->buffer[netplay->run_ptr].state;
1265             netplay_load_savestate(netplay, &serial_info, false);
1266             netplay->force_send_savestate = false;
1267          }
1268       }
1269       else
1270       {
1271          /* If the core can't serialize properly, we must stall for the
1272           * remote input on EVERY frame, because we can't recover */
1273          netplay->quirks |= NETPLAY_QUIRK_NO_SAVESTATES;
1274          netplay->stateless_mode = true;
1275       }
1276 
1277       /* If we can't transmit savestates, we must stall
1278        * until the client is ready. */
1279       if (netplay->run_frame_count > 0 &&
1280           (netplay->quirks & (NETPLAY_QUIRK_NO_SAVESTATES|NETPLAY_QUIRK_NO_TRANSMISSION)) &&
1281           (netplay->connections_size == 0 || !netplay->connections[0].active ||
1282            netplay->connections[0].mode < NETPLAY_CONNECTION_CONNECTED))
1283          netplay->stall = NETPLAY_STALL_NO_CONNECTION;
1284    }
1285 
1286    if (netplay->is_server)
1287    {
1288       fd_set fds;
1289       struct timeval tmp_tv = {0};
1290       int new_fd;
1291       struct sockaddr_storage their_addr;
1292       socklen_t addr_size;
1293       struct netplay_connection *connection;
1294       size_t connection_num;
1295 
1296       /* Check for a connection */
1297       FD_ZERO(&fds);
1298       FD_SET(netplay->listen_fd, &fds);
1299       if (socket_select(netplay->listen_fd + 1,
1300                &fds, NULL, NULL, &tmp_tv) > 0 &&
1301           FD_ISSET(netplay->listen_fd, &fds))
1302       {
1303          addr_size = sizeof(their_addr);
1304          new_fd = accept(netplay->listen_fd,
1305                (struct sockaddr*)&their_addr, &addr_size);
1306 
1307          if (new_fd < 0)
1308          {
1309             RARCH_ERR("%s\n", msg_hash_to_str(MSG_NETPLAY_FAILED));
1310             goto process;
1311          }
1312 
1313          /* Set the socket nonblocking */
1314          if (!socket_nonblock(new_fd))
1315          {
1316             /* Catastrophe! */
1317             socket_close(new_fd);
1318             goto process;
1319          }
1320 
1321 #if defined(IPPROTO_TCP) && defined(TCP_NODELAY)
1322          {
1323             int flag = 1;
1324             if (setsockopt(new_fd, IPPROTO_TCP, TCP_NODELAY,
1325 #ifdef _WIN32
1326                (const char*)
1327 #else
1328                (const void*)
1329 #endif
1330                &flag,
1331                sizeof(int)) < 0)
1332                RARCH_WARN("Could not set netplay TCP socket to nodelay. Expect jitter.\n");
1333          }
1334 #endif
1335 
1336 #if defined(F_SETFD) && defined(FD_CLOEXEC)
1337          /* Don't let any inherited processes keep open our port */
1338          if (fcntl(new_fd, F_SETFD, FD_CLOEXEC) < 0)
1339             RARCH_WARN("Cannot set Netplay port to close-on-exec. It may fail to reopen if the client disconnects.\n");
1340 #endif
1341 
1342          /* Allocate a connection */
1343          for (connection_num = 0; connection_num < netplay->connections_size; connection_num++)
1344             if (!netplay->connections[connection_num].active &&
1345                   netplay->connections[connection_num].mode != NETPLAY_CONNECTION_DELAYED_DISCONNECT)
1346                break;
1347          if (connection_num == netplay->connections_size)
1348          {
1349             if (connection_num == 0)
1350             {
1351                netplay->connections = (struct netplay_connection*)
1352                   malloc(sizeof(struct netplay_connection));
1353 
1354                if (!netplay->connections)
1355                {
1356                   socket_close(new_fd);
1357                   goto process;
1358                }
1359                netplay->connections_size = 1;
1360 
1361             }
1362             else
1363             {
1364                size_t new_connections_size = netplay->connections_size * 2;
1365                struct netplay_connection
1366                   *new_connections         = (struct netplay_connection*)
1367 
1368                   realloc(netplay->connections,
1369                      new_connections_size*sizeof(struct netplay_connection));
1370 
1371                if (!new_connections)
1372                {
1373                   socket_close(new_fd);
1374                   goto process;
1375                }
1376 
1377                memset(new_connections + netplay->connections_size, 0,
1378                   netplay->connections_size * sizeof(struct netplay_connection));
1379                netplay->connections = new_connections;
1380                netplay->connections_size = new_connections_size;
1381 
1382             }
1383          }
1384          connection         = &netplay->connections[connection_num];
1385 
1386          /* Set it up */
1387          memset(connection, 0, sizeof(*connection));
1388          connection->active = true;
1389          connection->fd     = new_fd;
1390          connection->mode   = NETPLAY_CONNECTION_INIT;
1391 
1392          if (!netplay_init_socket_buffer(&connection->send_packet_buffer,
1393                netplay->packet_buffer_size) ||
1394              !netplay_init_socket_buffer(&connection->recv_packet_buffer,
1395                netplay->packet_buffer_size))
1396          {
1397             if (connection->send_packet_buffer.data)
1398                netplay_deinit_socket_buffer(&connection->send_packet_buffer);
1399             connection->active = false;
1400             socket_close(new_fd);
1401             goto process;
1402          }
1403 
1404          netplay_handshake_init_send(netplay, connection);
1405 
1406       }
1407    }
1408 
1409 process:
1410    netplay->can_poll = true;
1411    input_poll_net();
1412 
1413    return (netplay->stall != NETPLAY_STALL_NO_CONNECTION);
1414 }
1415 
1416 /**
1417  * netplay_sync_post_frame
1418  * @netplay              : pointer to netplay object
1419  *
1420  * Post-frame for Netplay synchronization.
1421  * We check if we have new input and replay from recorded input.
1422  */
netplay_sync_post_frame(netplay_t * netplay,bool stalled)1423 void netplay_sync_post_frame(netplay_t *netplay, bool stalled)
1424 {
1425    uint32_t lo_frame_count, hi_frame_count;
1426 
1427    /* Unless we're stalling, we've just finished running a frame */
1428    if (!stalled)
1429    {
1430       netplay->run_ptr = NEXT_PTR(netplay->run_ptr);
1431       netplay->run_frame_count++;
1432    }
1433 
1434    /* We've finished an input frame even if we're stalling */
1435    if ((!stalled || netplay->stall == NETPLAY_STALL_INPUT_LATENCY) &&
1436        netplay->self_frame_count <
1437        netplay->run_frame_count + netplay->input_latency_frames)
1438    {
1439       netplay->self_ptr = NEXT_PTR(netplay->self_ptr);
1440       netplay->self_frame_count++;
1441    }
1442 
1443    /* Only relevant if we're connected and not in a desynching operation */
1444    if ((netplay->is_server && (netplay->connected_players<=1)) ||
1445        (netplay->self_mode < NETPLAY_CONNECTION_CONNECTED)     ||
1446        (netplay->desync))
1447    {
1448       netplay->other_frame_count = netplay->self_frame_count;
1449       netplay->other_ptr         = netplay->self_ptr;
1450 
1451       /* FIXME: Duplication */
1452       if (netplay->catch_up)
1453       {
1454          netplay->catch_up = false;
1455          input_driver_unset_nonblock_state();
1456          driver_set_nonblock_state();
1457       }
1458       return;
1459    }
1460 
1461    /* Reset if it was requested */
1462    if (netplay->force_reset)
1463    {
1464       core_reset();
1465       netplay->force_reset = false;
1466    }
1467 
1468    netplay->replay_ptr = netplay->other_ptr;
1469    netplay->replay_frame_count = netplay->other_frame_count;
1470 
1471 #ifndef DEBUG_NONDETERMINISTIC_CORES
1472    if (!netplay->force_rewind)
1473    {
1474       bool cont = true;
1475 
1476       /* Skip ahead if we predicted correctly.
1477        * Skip until our simulation failed. */
1478       while (netplay->other_frame_count < netplay->unread_frame_count &&
1479              netplay->other_frame_count < netplay->run_frame_count)
1480       {
1481          struct delta_frame *ptr = &netplay->buffer[netplay->other_ptr];
1482 
1483          /* If resolving the input changes it, we used bad input */
1484          if (netplay_resolve_input(netplay, netplay->other_ptr, true))
1485          {
1486             cont = false;
1487             break;
1488          }
1489 
1490          netplay_handle_frame_hash(netplay, ptr);
1491          netplay->other_ptr = NEXT_PTR(netplay->other_ptr);
1492          netplay->other_frame_count++;
1493       }
1494       netplay->replay_ptr = netplay->other_ptr;
1495       netplay->replay_frame_count = netplay->other_frame_count;
1496 
1497       if (cont)
1498       {
1499          while (netplay->replay_frame_count < netplay->run_frame_count)
1500          {
1501             if (netplay_resolve_input(netplay, netplay->replay_ptr, true))
1502                break;
1503             netplay->replay_ptr = NEXT_PTR(netplay->replay_ptr);
1504             netplay->replay_frame_count++;
1505          }
1506       }
1507    }
1508 #endif
1509 
1510    /* Now replay the real input if we've gotten ahead of it */
1511    if (netplay->force_rewind ||
1512        netplay->replay_frame_count < netplay->run_frame_count)
1513    {
1514       retro_ctx_serialize_info_t serial_info;
1515 
1516       /* Replay frames. */
1517       netplay->is_replay = true;
1518 
1519       /* If we have a keyboard device, we replay the previous frame's input
1520        * just to assert that the keydown/keyup events work if the core
1521        * translates them in that way */
1522       if (netplay->have_updown_device)
1523       {
1524          netplay->replay_ptr = PREV_PTR(netplay->replay_ptr);
1525          netplay->replay_frame_count--;
1526 #ifdef HAVE_THREADS
1527          autosave_lock();
1528 #endif
1529          core_run();
1530 #ifdef HAVE_THREADS
1531          autosave_unlock();
1532 #endif
1533          netplay->replay_ptr = NEXT_PTR(netplay->replay_ptr);
1534          netplay->replay_frame_count++;
1535       }
1536 
1537       if (netplay->quirks & NETPLAY_QUIRK_INITIALIZATION)
1538          /* Make sure we're initialized before we start loading things */
1539          netplay_wait_and_init_serialization(netplay);
1540 
1541       serial_info.data       = NULL;
1542       serial_info.data_const = netplay->buffer[netplay->replay_ptr].state;
1543       serial_info.size       = netplay->state_size;
1544 
1545       if (!core_unserialize(&serial_info))
1546       {
1547          RARCH_ERR("Netplay savestate loading failed: Prepare for desync!\n");
1548       }
1549 
1550       while (netplay->replay_frame_count < netplay->run_frame_count)
1551       {
1552          retro_time_t start, tm;
1553          struct delta_frame *ptr = &netplay->buffer[netplay->replay_ptr];
1554 
1555          serial_info.data        = ptr->state;
1556          serial_info.size        = netplay->state_size;
1557          serial_info.data_const  = NULL;
1558 
1559          start                   = cpu_features_get_time_usec();
1560 
1561          /* Remember the current state */
1562          memset(serial_info.data, 0, serial_info.size);
1563          core_serialize(&serial_info);
1564          if (netplay->replay_frame_count < netplay->unread_frame_count)
1565             netplay_handle_frame_hash(netplay, ptr);
1566 
1567          /* Re-simulate this frame's input */
1568          netplay_resolve_input(netplay, netplay->replay_ptr, true);
1569 
1570 #ifdef HAVE_THREADS
1571          autosave_lock();
1572 #endif
1573          core_run();
1574 #ifdef HAVE_THREADS
1575          autosave_unlock();
1576 #endif
1577          netplay->replay_ptr = NEXT_PTR(netplay->replay_ptr);
1578          netplay->replay_frame_count++;
1579 
1580 #ifdef DEBUG_NONDETERMINISTIC_CORES
1581          if (ptr->have_remote && netplay_delta_frame_ready(netplay, &netplay->buffer[netplay->replay_ptr], netplay->replay_frame_count))
1582          {
1583             RARCH_LOG("PRE  %u: %X\n", netplay->replay_frame_count-1, netplay->state_size ? netplay_delta_frame_crc(netplay, ptr) : 0);
1584             if (netplay->is_server)
1585                RARCH_LOG("INP  %X %X\n", ptr->real_input_state[0], ptr->self_state[0]);
1586             else
1587                RARCH_LOG("INP  %X %X\n", ptr->self_state[0], ptr->real_input_state[0]);
1588             ptr = &netplay->buffer[netplay->replay_ptr];
1589             serial_info.data = ptr->state;
1590             memset(serial_info.data, 0, serial_info.size);
1591             core_serialize(&serial_info);
1592             RARCH_LOG("POST %u: %X\n", netplay->replay_frame_count-1, netplay->state_size ? netplay_delta_frame_crc(netplay, ptr) : 0);
1593          }
1594 #endif
1595 
1596          /* Get our time window */
1597          tm = cpu_features_get_time_usec() - start;
1598          netplay->frame_run_time_sum -= netplay->frame_run_time[netplay->frame_run_time_ptr];
1599          netplay->frame_run_time[netplay->frame_run_time_ptr] = tm;
1600          netplay->frame_run_time_sum += tm;
1601          netplay->frame_run_time_ptr++;
1602          if (netplay->frame_run_time_ptr >= NETPLAY_FRAME_RUN_TIME_WINDOW)
1603             netplay->frame_run_time_ptr = 0;
1604       }
1605 
1606       /* Average our time */
1607       netplay->frame_run_time_avg   = netplay->frame_run_time_sum / NETPLAY_FRAME_RUN_TIME_WINDOW;
1608 
1609       if (netplay->unread_frame_count < netplay->run_frame_count)
1610       {
1611          netplay->other_ptr         = netplay->unread_ptr;
1612          netplay->other_frame_count = netplay->unread_frame_count;
1613       }
1614       else
1615       {
1616          netplay->other_ptr         = netplay->run_ptr;
1617          netplay->other_frame_count = netplay->run_frame_count;
1618       }
1619       netplay->is_replay            = false;
1620       netplay->force_rewind         = false;
1621    }
1622 
1623    if (netplay->is_server)
1624    {
1625       uint32_t client;
1626 
1627       lo_frame_count = hi_frame_count = netplay->unread_frame_count;
1628 
1629       /* Look for players that are ahead of us */
1630       for (client = 0; client < MAX_CLIENTS; client++)
1631       {
1632          if (!(netplay->connected_players & (1 << client)))
1633             continue;
1634          if (netplay->read_frame_count[client] > hi_frame_count)
1635             hi_frame_count = netplay->read_frame_count[client];
1636       }
1637    }
1638    else
1639       lo_frame_count = hi_frame_count = netplay->server_frame_count;
1640 
1641    /* If we're behind, try to catch up */
1642    if (netplay->catch_up)
1643    {
1644       /* Are we caught up? */
1645       if (netplay->self_frame_count + 1 >= lo_frame_count)
1646       {
1647          netplay->catch_up = false;
1648          input_driver_unset_nonblock_state();
1649          driver_set_nonblock_state();
1650       }
1651 
1652    }
1653    else if (!stalled)
1654    {
1655       if (netplay->self_frame_count + 3 < lo_frame_count)
1656       {
1657          retro_time_t cur_time = cpu_features_get_time_usec();
1658          uint32_t cur_behind = lo_frame_count - netplay->self_frame_count;
1659 
1660          /* We're behind, but we'll only try to catch up if we're actually
1661           * falling behind, i.e. if we're more behind after some time */
1662          if (netplay->catch_up_time == 0)
1663          {
1664             /* Record our current time to check for catch-up later */
1665             netplay->catch_up_time = cur_time;
1666             netplay->catch_up_behind = cur_behind;
1667 
1668          }
1669          else if (cur_time - netplay->catch_up_time > CATCH_UP_CHECK_TIME_USEC)
1670          {
1671             /* Time to check how far behind we are */
1672             if (netplay->catch_up_behind <= cur_behind)
1673             {
1674                /* We're definitely falling behind! */
1675                netplay->catch_up      = true;
1676                netplay->catch_up_time = 0;
1677                input_driver_set_nonblock_state();
1678                driver_set_nonblock_state();
1679             }
1680             else
1681             {
1682                /* Check again in another period */
1683                netplay->catch_up_time   = cur_time;
1684                netplay->catch_up_behind = cur_behind;
1685             }
1686          }
1687 
1688       }
1689       else if (netplay->self_frame_count + 3 < hi_frame_count)
1690       {
1691          size_t i;
1692          netplay->catch_up_time = 0;
1693 
1694          /* We're falling behind some clients but not others, so request that
1695           * clients ahead of us stall */
1696          for (i = 0; i < netplay->connections_size; i++)
1697          {
1698             uint32_t client_num;
1699             struct netplay_connection *connection = &netplay->connections[i];
1700 
1701             if (!connection->active ||
1702                 connection->mode != NETPLAY_CONNECTION_PLAYING)
1703                continue;
1704 
1705             client_num = (uint32_t)(i + 1);
1706 
1707             /* Are they ahead? */
1708             if (netplay->self_frame_count + 3 < netplay->read_frame_count[client_num])
1709             {
1710                /* Tell them to stall */
1711                if (connection->stall_frame + NETPLAY_MAX_REQ_STALL_FREQUENCY <
1712                      netplay->self_frame_count)
1713                {
1714                   connection->stall_frame = netplay->self_frame_count;
1715                   netplay_cmd_stall(netplay, connection,
1716                      netplay->read_frame_count[client_num] -
1717                      netplay->self_frame_count + 1);
1718                }
1719             }
1720          }
1721       }
1722       else
1723          netplay->catch_up_time = 0;
1724    }
1725    else
1726       netplay->catch_up_time =  0;
1727 }
1728 
1729 #if 0
1730 #define DEBUG_NETPLAY_STEPS 1
1731 
1732 static void print_state(netplay_t *netplay)
1733 {
1734    char msg[512];
1735    size_t cur = 0;
1736    uint32_t client;
1737 
1738 #define APPEND(out) cur += snprintf out
1739 #define M msg + cur, sizeof(msg) - cur
1740 
1741    APPEND((M, "NETPLAY: S:%u U:%u O:%u", netplay->self_frame_count, netplay->unread_frame_count, netplay->other_frame_count));
1742    if (!netplay->is_server)
1743       APPEND((M, " H:%u", netplay->server_frame_count));
1744    for (client = 0; client < MAX_USERS; client++)
1745    {
1746       if ((netplay->connected_players & (1<<client)))
1747          APPEND((M, " %u:%u", client, netplay->read_frame_count[client]));
1748    }
1749    msg[sizeof(msg)-1] = '\0';
1750 
1751    RARCH_LOG("[netplay] %s\n", msg);
1752 
1753 #undef APPEND
1754 #undef M
1755 }
1756 #endif
1757 
1758 /**
1759  * remote_unpaused
1760  *
1761  * Mark a particular remote connection as unpaused and, if relevant, inform
1762  * every one else that they may resume.
1763  */
remote_unpaused(netplay_t * netplay,struct netplay_connection * connection)1764 static void remote_unpaused(netplay_t *netplay,
1765       struct netplay_connection *connection)
1766 {
1767     size_t i;
1768     connection->paused = false;
1769     netplay->remote_paused = false;
1770     for (i = 0; i < netplay->connections_size; i++)
1771     {
1772        struct netplay_connection *sc = &netplay->connections[i];
1773        if (sc->active && sc->paused)
1774        {
1775           netplay->remote_paused = true;
1776           break;
1777        }
1778     }
1779     if (!netplay->remote_paused && !netplay->local_paused)
1780        netplay_send_raw_cmd_all(netplay, connection, NETPLAY_CMD_RESUME, NULL, 0);
1781 }
1782 
1783 /**
1784  * netplay_hangup:
1785  *
1786  * Disconnects an active Netplay connection due to an error
1787  */
netplay_hangup(netplay_t * netplay,struct netplay_connection * connection)1788 void netplay_hangup(netplay_t *netplay,
1789       struct netplay_connection *connection)
1790 {
1791    char msg[512];
1792    const char *dmsg;
1793    size_t i;
1794 
1795    if (!netplay)
1796       return;
1797    if (!connection->active)
1798       return;
1799 
1800    msg[0] = msg[sizeof(msg)-1] = '\0';
1801    dmsg = msg;
1802 
1803    /* Report this disconnection */
1804    if (netplay->is_server)
1805    {
1806       if (connection->nick[0])
1807          snprintf(msg, sizeof(msg)-1, msg_hash_to_str(MSG_NETPLAY_SERVER_NAMED_HANGUP), connection->nick);
1808       else
1809          dmsg = msg_hash_to_str(MSG_NETPLAY_SERVER_HANGUP);
1810    }
1811    else
1812    {
1813       dmsg = msg_hash_to_str(MSG_NETPLAY_CLIENT_HANGUP);
1814 #ifdef HAVE_DISCORD
1815       if (discord_is_inited)
1816       {
1817          discord_userdata_t userdata;
1818          userdata.status = DISCORD_PRESENCE_NETPLAY_NETPLAY_STOPPED;
1819          command_event(CMD_EVENT_DISCORD_UPDATE, &userdata);
1820       }
1821 #endif
1822       netplay->is_connected = false;
1823    }
1824    RARCH_LOG("[netplay] %s\n", dmsg);
1825    runloop_msg_queue_push(dmsg, 1, 180, false, NULL, MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
1826 
1827    socket_close(connection->fd);
1828    connection->active = false;
1829    netplay_deinit_socket_buffer(&connection->send_packet_buffer);
1830    netplay_deinit_socket_buffer(&connection->recv_packet_buffer);
1831 
1832    if (!netplay->is_server)
1833    {
1834       netplay->self_mode = NETPLAY_CONNECTION_NONE;
1835       netplay->connected_players &= (1L<<netplay->self_client_num);
1836       for (i = 0; i < MAX_CLIENTS; i++)
1837       {
1838          if (i == netplay->self_client_num)
1839             continue;
1840          netplay->client_devices[i] = 0;
1841       }
1842       for (i = 0; i < MAX_INPUT_DEVICES; i++)
1843          netplay->device_clients[i] &= (1L<<netplay->self_client_num);
1844       netplay->stall = NETPLAY_STALL_NONE;
1845 
1846    }
1847    else
1848    {
1849       uint32_t client_num = (uint32_t)(connection - netplay->connections + 1);
1850 
1851       /* Mark the player for removal */
1852       if (connection->mode == NETPLAY_CONNECTION_PLAYING ||
1853           connection->mode == NETPLAY_CONNECTION_SLAVE)
1854       {
1855          /* This special mode keeps the connection object alive long enough to
1856           * send the disconnection message at the correct time */
1857          connection->mode = NETPLAY_CONNECTION_DELAYED_DISCONNECT;
1858          connection->delay_frame = netplay->read_frame_count[client_num];
1859 
1860          /* Mark them as not playing anymore */
1861          netplay->connected_players &= ~(1L<<client_num);
1862          netplay->connected_slaves  &= ~(1L<<client_num);
1863          netplay->client_devices[client_num] = 0;
1864          for (i = 0; i < MAX_INPUT_DEVICES; i++)
1865             netplay->device_clients[i] &= ~(1L<<client_num);
1866 
1867       }
1868 
1869    }
1870 
1871    /* Unpause them */
1872    if (connection->paused)
1873       remote_unpaused(netplay, connection);
1874 }
1875 
1876 /**
1877  * netplay_delayed_state_change:
1878  *
1879  * Handle any pending state changes which are ready
1880  * as of the beginning of the current frame.
1881  */
netplay_delayed_state_change(netplay_t * netplay)1882 void netplay_delayed_state_change(netplay_t *netplay)
1883 {
1884    unsigned i;
1885 
1886    for (i = 0; i < netplay->connections_size; i++)
1887    {
1888       uint32_t client_num                   = (uint32_t)(i + 1);
1889       struct netplay_connection *connection = &netplay->connections[i];
1890 
1891       if ((connection->active || connection->mode == NETPLAY_CONNECTION_DELAYED_DISCONNECT) &&
1892           connection->delay_frame &&
1893           connection->delay_frame <= netplay->self_frame_count)
1894       {
1895          /* Something was delayed! Prepare the MODE command */
1896          uint32_t payload[15] = {0};
1897          payload[0]           = htonl(connection->delay_frame);
1898          payload[1]           = htonl(client_num);
1899          payload[2]           = htonl(0);
1900 
1901          memcpy(payload + 3, netplay->device_share_modes, sizeof(netplay->device_share_modes));
1902          strncpy((char *) (payload + 7), connection->nick, NETPLAY_NICK_LEN);
1903 
1904          /* Remove the connection entirely if relevant */
1905          if (connection->mode == NETPLAY_CONNECTION_DELAYED_DISCONNECT)
1906             connection->mode = NETPLAY_CONNECTION_NONE;
1907 
1908          /* Then send the mode change packet */
1909          netplay_send_raw_cmd_all(netplay, connection, NETPLAY_CMD_MODE, payload, sizeof(payload));
1910 
1911          /* And forget the delay frame */
1912          connection->delay_frame = 0;
1913       }
1914    }
1915 }
1916 
1917 /* Send the specified input data */
send_input_frame(netplay_t * netplay,struct delta_frame * dframe,struct netplay_connection * only,struct netplay_connection * except,uint32_t client_num,bool slave)1918 static bool send_input_frame(netplay_t *netplay, struct delta_frame *dframe,
1919       struct netplay_connection *only, struct netplay_connection *except,
1920       uint32_t client_num, bool slave)
1921 {
1922 #define BUFSZ 16 /* FIXME: Arbitrary restriction */
1923    uint32_t buffer[BUFSZ], devices, device;
1924    size_t bufused, i;
1925 
1926    /* Set up the basic buffer */
1927    bufused = 4;
1928    buffer[0] = htonl(NETPLAY_CMD_INPUT);
1929    buffer[2] = htonl(dframe->frame);
1930    buffer[3] = htonl(client_num);
1931 
1932    /* Add the device data */
1933    devices = netplay->client_devices[client_num];
1934    for (device = 0; device < MAX_INPUT_DEVICES; device++)
1935    {
1936       netplay_input_state_t istate;
1937       if (!(devices & (1<<device)))
1938          continue;
1939       istate = dframe->real_input[device];
1940       while (istate && (!istate->used || istate->client_num != (slave?MAX_CLIENTS:client_num)))
1941          istate = istate->next;
1942       if (!istate)
1943          continue;
1944       if (bufused + istate->size >= BUFSZ)
1945          continue; /* FIXME: More severe? */
1946       for (i = 0; i < istate->size; i++)
1947          buffer[bufused+i] = htonl(istate->data[i]);
1948       bufused += istate->size;
1949    }
1950    buffer[1] = htonl((bufused-2) * sizeof(uint32_t));
1951 
1952 #ifdef DEBUG_NETPLAY_STEPS
1953    RARCH_LOG("[netplay] Sending input for client %u\n", (unsigned) client_num);
1954    print_state(netplay);
1955 #endif
1956 
1957    if (only)
1958    {
1959       if (!netplay_send(&only->send_packet_buffer, only->fd, buffer, bufused*sizeof(uint32_t)))
1960       {
1961          netplay_hangup(netplay, only);
1962          return false;
1963       }
1964    }
1965    else
1966    {
1967       for (i = 0; i < netplay->connections_size; i++)
1968       {
1969          struct netplay_connection *connection = &netplay->connections[i];
1970          if (connection == except)
1971             continue;
1972          if (connection->active &&
1973              connection->mode >= NETPLAY_CONNECTION_CONNECTED &&
1974              (connection->mode != NETPLAY_CONNECTION_PLAYING ||
1975               i+1 != client_num))
1976          {
1977             if (!netplay_send(&connection->send_packet_buffer, connection->fd,
1978                   buffer, bufused*sizeof(uint32_t)))
1979                netplay_hangup(netplay, connection);
1980          }
1981       }
1982    }
1983 
1984    return true;
1985 #undef BUFSZ
1986 }
1987 
1988 /**
1989  * netplay_send_cur_input
1990  *
1991  * Send the current input frame to a given connection.
1992  *
1993  * Returns true if successful, false otherwise.
1994  */
netplay_send_cur_input(netplay_t * netplay,struct netplay_connection * connection)1995 bool netplay_send_cur_input(netplay_t *netplay,
1996    struct netplay_connection *connection)
1997 {
1998    uint32_t from_client, to_client;
1999    struct delta_frame *dframe = &netplay->buffer[netplay->self_ptr];
2000 
2001    if (netplay->is_server)
2002    {
2003       to_client = (uint32_t)(connection - netplay->connections + 1);
2004 
2005       /* Send the other players' input data (FIXME: This involves an
2006        * unacceptable amount of recalculating) */
2007       for (from_client = 1; from_client < MAX_CLIENTS; from_client++)
2008       {
2009          if (from_client == to_client)
2010             continue;
2011 
2012          if ((netplay->connected_players & (1<<from_client)))
2013          {
2014             if (dframe->have_real[from_client])
2015             {
2016                if (!send_input_frame(netplay, dframe, connection, NULL, from_client, false))
2017                   return false;
2018             }
2019          }
2020       }
2021 
2022       /* If we're not playing, send a NOINPUT */
2023       if (netplay->self_mode != NETPLAY_CONNECTION_PLAYING)
2024       {
2025          uint32_t payload = htonl(netplay->self_frame_count);
2026          if (!netplay_send_raw_cmd(netplay, connection, NETPLAY_CMD_NOINPUT,
2027                &payload, sizeof(payload)))
2028             return false;
2029       }
2030 
2031    }
2032 
2033    /* Send our own data */
2034    if (netplay->self_mode == NETPLAY_CONNECTION_PLAYING
2035          || netplay->self_mode == NETPLAY_CONNECTION_SLAVE)
2036    {
2037       if (!send_input_frame(netplay, dframe, connection, NULL,
2038             netplay->self_client_num,
2039             netplay->self_mode == NETPLAY_CONNECTION_SLAVE))
2040          return false;
2041    }
2042 
2043    if (!netplay_send_flush(&connection->send_packet_buffer, connection->fd,
2044          false))
2045       return false;
2046 
2047    return true;
2048 }
2049 
2050 /**
2051  * netplay_send_raw_cmd
2052  *
2053  * Send a raw Netplay command to the given connection.
2054  *
2055  * Returns true on success, false on failure.
2056  */
netplay_send_raw_cmd(netplay_t * netplay,struct netplay_connection * connection,uint32_t cmd,const void * data,size_t size)2057 bool netplay_send_raw_cmd(netplay_t *netplay,
2058    struct netplay_connection *connection, uint32_t cmd, const void *data,
2059    size_t size)
2060 {
2061    uint32_t cmdbuf[2];
2062 
2063    cmdbuf[0] = htonl(cmd);
2064    cmdbuf[1] = htonl(size);
2065 
2066    if (!netplay_send(&connection->send_packet_buffer, connection->fd, cmdbuf,
2067          sizeof(cmdbuf)))
2068       return false;
2069 
2070    if (size > 0)
2071       if (!netplay_send(&connection->send_packet_buffer, connection->fd, data, size))
2072          return false;
2073 
2074    return true;
2075 }
2076 
2077 /**
2078  * netplay_send_raw_cmd_all
2079  *
2080  * Send a raw Netplay command to all connections, optionally excluding one
2081  * (typically the client that the relevant command came from)
2082  */
netplay_send_raw_cmd_all(netplay_t * netplay,struct netplay_connection * except,uint32_t cmd,const void * data,size_t size)2083 void netplay_send_raw_cmd_all(netplay_t *netplay,
2084    struct netplay_connection *except, uint32_t cmd, const void *data,
2085    size_t size)
2086 {
2087    size_t i;
2088    for (i = 0; i < netplay->connections_size; i++)
2089    {
2090       struct netplay_connection *connection = &netplay->connections[i];
2091       if (connection == except)
2092          continue;
2093       if (connection->active && connection->mode >= NETPLAY_CONNECTION_CONNECTED)
2094       {
2095          if (!netplay_send_raw_cmd(netplay, connection, cmd, data, size))
2096             netplay_hangup(netplay, connection);
2097       }
2098    }
2099 }
2100 
2101 /**
2102  * netplay_send_flush_all
2103  *
2104  * Flush all of our output buffers
2105  */
netplay_send_flush_all(netplay_t * netplay,struct netplay_connection * except)2106 static void netplay_send_flush_all(netplay_t *netplay,
2107    struct netplay_connection *except)
2108 {
2109    size_t i;
2110    for (i = 0; i < netplay->connections_size; i++)
2111    {
2112       struct netplay_connection *connection = &netplay->connections[i];
2113       if (connection == except)
2114          continue;
2115       if (connection->active && connection->mode >= NETPLAY_CONNECTION_CONNECTED)
2116       {
2117          if (!netplay_send_flush(&connection->send_packet_buffer,
2118             connection->fd, true))
2119             netplay_hangup(netplay, connection);
2120       }
2121    }
2122 }
2123 
netplay_cmd_nak(netplay_t * netplay,struct netplay_connection * connection)2124 static bool netplay_cmd_nak(netplay_t *netplay,
2125    struct netplay_connection *connection)
2126 {
2127    netplay_send_raw_cmd(netplay, connection, NETPLAY_CMD_NAK, NULL, 0);
2128    return false;
2129 }
2130 
2131 /**
2132  * netplay_settings_share_mode
2133  *
2134  * Get the preferred share mode
2135  */
netplay_settings_share_mode(unsigned share_digital,unsigned share_analog)2136 static uint8_t netplay_settings_share_mode(
2137       unsigned share_digital, unsigned share_analog)
2138 {
2139    if (share_digital || share_analog)
2140    {
2141       uint8_t share_mode     = 0;
2142 
2143       switch (share_digital)
2144       {
2145          case RARCH_NETPLAY_SHARE_DIGITAL_OR:
2146             share_mode |= NETPLAY_SHARE_DIGITAL_OR;
2147             break;
2148          case RARCH_NETPLAY_SHARE_DIGITAL_XOR:
2149             share_mode |= NETPLAY_SHARE_DIGITAL_XOR;
2150             break;
2151          case RARCH_NETPLAY_SHARE_DIGITAL_VOTE:
2152             share_mode |= NETPLAY_SHARE_DIGITAL_VOTE;
2153             break;
2154          default:
2155             share_mode |= NETPLAY_SHARE_NO_PREFERENCE;
2156       }
2157 
2158       switch (share_analog)
2159       {
2160          case RARCH_NETPLAY_SHARE_ANALOG_MAX:
2161             share_mode |= NETPLAY_SHARE_ANALOG_MAX;
2162             break;
2163          case RARCH_NETPLAY_SHARE_ANALOG_AVERAGE:
2164             share_mode |= NETPLAY_SHARE_ANALOG_AVERAGE;
2165             break;
2166          default:
2167             share_mode |= NETPLAY_SHARE_NO_PREFERENCE;
2168       }
2169 
2170       return share_mode;
2171    }
2172    return 0;
2173 }
2174 
2175 /**
2176  * netplay_cmd_mode
2177  *
2178  * Send a mode change request. As a server, the request is to ourself, and so
2179  * honored instantly.
2180  */
netplay_cmd_mode(netplay_t * netplay,enum rarch_netplay_connection_mode mode)2181 bool netplay_cmd_mode(netplay_t *netplay,
2182    enum rarch_netplay_connection_mode mode)
2183 {
2184    uint32_t cmd, device;
2185    uint32_t payload_buf = 0, *payload    = NULL;
2186    uint8_t share_mode                    = 0;
2187    struct netplay_connection *connection = NULL;
2188 
2189    if (!netplay->is_server)
2190       connection = &netplay->one_connection;
2191 
2192    switch (mode)
2193    {
2194       case NETPLAY_CONNECTION_SPECTATING:
2195          cmd = NETPLAY_CMD_SPECTATE;
2196          break;
2197 
2198       case NETPLAY_CONNECTION_SLAVE:
2199          payload_buf = NETPLAY_CMD_PLAY_BIT_SLAVE;
2200          /* no break */
2201 
2202       case NETPLAY_CONNECTION_PLAYING:
2203          {
2204             settings_t *settings = config_get_ptr();
2205             payload = &payload_buf;
2206 
2207             /* Add a share mode if requested */
2208             share_mode = netplay_settings_share_mode(
2209                   settings->uints.netplay_share_digital,
2210                   settings->uints.netplay_share_analog
2211                   );
2212             payload_buf |= ((uint32_t) share_mode) << 16;
2213 
2214             /* Request devices */
2215             for (device = 0; device < MAX_INPUT_DEVICES; device++)
2216             {
2217                if (settings->bools.netplay_request_devices[device])
2218                   payload_buf |= 1<<device;
2219             }
2220 
2221             payload_buf = htonl(payload_buf);
2222             cmd         = NETPLAY_CMD_PLAY;
2223          }
2224          break;
2225 
2226       default:
2227          return false;
2228    }
2229 
2230    if (netplay->is_server)
2231    {
2232       handle_play_spectate(netplay, 0, NULL, cmd, payload ? sizeof(uint32_t) : 0, payload);
2233       return true;
2234    }
2235 
2236    return netplay_send_raw_cmd(netplay, connection, cmd, payload,
2237          payload ? sizeof(uint32_t) : 0);
2238 }
2239 
2240 /**
2241  * announce_play_spectate
2242  *
2243  * Announce a play or spectate mode change
2244  */
announce_play_spectate(netplay_t * netplay,const char * nick,enum rarch_netplay_connection_mode mode,uint32_t devices)2245 static void announce_play_spectate(netplay_t *netplay,
2246       const char *nick,
2247       enum rarch_netplay_connection_mode mode, uint32_t devices)
2248 {
2249    char msg[512];
2250    msg[0] = msg[sizeof(msg) - 1] = '\0';
2251 
2252    switch (mode)
2253    {
2254       case NETPLAY_CONNECTION_SPECTATING:
2255          if (nick)
2256             snprintf(msg, sizeof(msg) - 1,
2257                   msg_hash_to_str(MSG_NETPLAY_PLAYER_S_LEFT), NETPLAY_NICK_LEN,
2258                   nick);
2259          else
2260             strlcpy(msg, msg_hash_to_str(MSG_NETPLAY_YOU_HAVE_LEFT_THE_GAME), sizeof(msg));
2261          break;
2262 
2263       case NETPLAY_CONNECTION_PLAYING:
2264       case NETPLAY_CONNECTION_SLAVE:
2265       {
2266          uint32_t device;
2267          uint32_t one_device = (uint32_t) -1;
2268          char device_str[512];
2269          size_t device_str_len;
2270 
2271          for (device = 0; device < MAX_INPUT_DEVICES; device++)
2272          {
2273             if (!(devices & (1<<device)))
2274                continue;
2275             if (one_device == (uint32_t) -1)
2276                one_device = device;
2277             else
2278             {
2279                one_device = (uint32_t) -1;
2280                break;
2281             }
2282          }
2283 
2284          if (one_device != (uint32_t) -1)
2285          {
2286             /* Only have one device, simpler message */
2287             if (nick)
2288                snprintf(msg, sizeof(msg) - 1,
2289                      msg_hash_to_str(MSG_NETPLAY_S_HAS_JOINED_AS_PLAYER_N),
2290                      NETPLAY_NICK_LEN, nick, one_device + 1);
2291             else
2292                snprintf(msg, sizeof(msg) - 1,
2293                      msg_hash_to_str(MSG_NETPLAY_YOU_HAVE_JOINED_AS_PLAYER_N),
2294                      one_device + 1);
2295          }
2296          else
2297          {
2298             /* Multiple devices, so step one is to make the device string listing them all */
2299             device_str[0] = 0;
2300             device_str_len = 0;
2301             for (device = 0; device < MAX_INPUT_DEVICES; device++)
2302             {
2303                if (!(devices & (1<<device)))
2304                   continue;
2305                if (device_str_len)
2306                   device_str_len += snprintf(device_str + device_str_len,
2307                         sizeof(device_str) - 1 - device_str_len, ", ");
2308                device_str_len += snprintf(device_str + device_str_len,
2309                      sizeof(device_str) - 1 - device_str_len, "%u",
2310                      (unsigned) (device+1));
2311             }
2312 
2313             /* Then we make the final string */
2314             if (nick)
2315                snprintf(msg, sizeof(msg) - 1,
2316                      msg_hash_to_str(
2317                            MSG_NETPLAY_S_HAS_JOINED_WITH_INPUT_DEVICES_S),
2318                      NETPLAY_NICK_LEN, nick, sizeof(device_str),
2319                      device_str);
2320             else
2321                snprintf(msg, sizeof(msg) - 1,
2322                      msg_hash_to_str(
2323                            MSG_NETPLAY_YOU_HAVE_JOINED_WITH_INPUT_DEVICES_S),
2324                      sizeof(device_str), device_str);
2325          }
2326 
2327          break;
2328       }
2329 
2330       default: /* wrong usage */
2331          break;
2332    }
2333 
2334    if (msg[0])
2335    {
2336       RARCH_LOG("[netplay] %s\n", msg);
2337       runloop_msg_queue_push(msg, 1, 180, false, NULL, MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
2338    }
2339 }
2340 
2341 /**
2342  * handle_play_spectate
2343  *
2344  * Handle a play or spectate request
2345  */
handle_play_spectate(netplay_t * netplay,uint32_t client_num,struct netplay_connection * connection,uint32_t cmd,uint32_t cmd_size,uint32_t * in_payload)2346 static void handle_play_spectate(netplay_t *netplay, uint32_t client_num,
2347       struct netplay_connection *connection, uint32_t cmd, uint32_t cmd_size,
2348       uint32_t *in_payload)
2349 {
2350    /*
2351     * MODE payload:
2352     * word 0: frame number
2353     * word 1: mode info (playing, slave, client number)
2354     * word 2: device bitmap
2355     * words 3-6: share modes for all devices
2356     * words 7-14: client nick
2357     */
2358    uint32_t payload[15] = {0};
2359 
2360    switch (cmd)
2361    {
2362       case NETPLAY_CMD_SPECTATE:
2363       {
2364          size_t i;
2365 
2366          /* The frame we haven't received is their end frame */
2367          if (connection)
2368             connection->delay_frame = netplay->read_frame_count[client_num];
2369 
2370          /* Mark them as not playing anymore */
2371          if (connection)
2372             connection->mode = NETPLAY_CONNECTION_SPECTATING;
2373          else
2374          {
2375             netplay->self_devices = 0;
2376             netplay->self_mode = NETPLAY_CONNECTION_SPECTATING;
2377          }
2378          netplay->connected_players &= ~(1 << client_num);
2379          netplay->connected_slaves &= ~(1 << client_num);
2380          netplay->client_devices[client_num] = 0;
2381          for (i = 0; i < MAX_INPUT_DEVICES; i++)
2382             netplay->device_clients[i] &= ~(1 << client_num);
2383 
2384          /* Tell someone */
2385          payload[0] = htonl(netplay->read_frame_count[client_num]);
2386          payload[2] = htonl(0);
2387          memcpy(payload + 3, netplay->device_share_modes, sizeof(netplay->device_share_modes));
2388          if (connection)
2389          {
2390             /* Only tell the player. The others will be told at delay_frame */
2391             payload[1] = htonl(NETPLAY_CMD_MODE_BIT_YOU | client_num);
2392             strncpy((char *) (payload + 7), connection->nick, NETPLAY_NICK_LEN);
2393             netplay_send_raw_cmd(netplay, connection, NETPLAY_CMD_MODE, payload, sizeof(payload));
2394 
2395          }
2396          else
2397          {
2398             /* It was the server, so tell everyone else */
2399             payload[1] = htonl(0);
2400             strncpy((char *) (payload + 7), netplay->nick, NETPLAY_NICK_LEN);
2401             netplay_send_raw_cmd_all(netplay, NULL, NETPLAY_CMD_MODE, payload, sizeof(payload));
2402 
2403          }
2404 
2405          /* Announce it */
2406          announce_play_spectate(netplay, connection ? connection->nick : NULL,
2407                NETPLAY_CONNECTION_SPECTATING, 0);
2408          break;
2409       }
2410 
2411       case NETPLAY_CMD_PLAY:
2412       {
2413          uint32_t mode, devices = 0, device;
2414          uint8_t share_mode;
2415          bool slave = false;
2416          settings_t *settings = config_get_ptr();
2417 
2418          if (cmd_size != sizeof(uint32_t) || !in_payload)
2419             return;
2420          mode = ntohl(in_payload[0]);
2421 
2422          /* Check the requested mode */
2423          slave = (mode&NETPLAY_CMD_PLAY_BIT_SLAVE)?true:false;
2424          share_mode = (mode>>16)&0xFF;
2425 
2426          /* And the requested devices */
2427          devices = mode&0xFFFF;
2428 
2429          /* Check if their slave mode request corresponds with what we allow */
2430          if (connection)
2431          {
2432             if (settings->bools.netplay_require_slaves)
2433                slave = true;
2434             else if (!settings->bools.netplay_allow_slaves)
2435                slave = false;
2436          }
2437          else
2438             slave = false;
2439 
2440          /* Fix our share mode */
2441          if (share_mode)
2442          {
2443             if ((share_mode & NETPLAY_SHARE_DIGITAL_BITS) == 0)
2444                share_mode |= NETPLAY_SHARE_DIGITAL_OR;
2445             if ((share_mode & NETPLAY_SHARE_ANALOG_BITS) == 0)
2446                share_mode |= NETPLAY_SHARE_ANALOG_MAX;
2447             share_mode &= ~NETPLAY_SHARE_NO_PREFERENCE;
2448          }
2449 
2450          /* They start at the next frame, but we start immediately */
2451          if (connection)
2452          {
2453             netplay->read_ptr[client_num] = NEXT_PTR(netplay->self_ptr);
2454             netplay->read_frame_count[client_num] = netplay->self_frame_count + 1;
2455          }
2456          else
2457          {
2458             netplay->read_ptr[client_num] = netplay->self_ptr;
2459             netplay->read_frame_count[client_num] = netplay->self_frame_count;
2460          }
2461          payload[0] = htonl(netplay->read_frame_count[client_num]);
2462 
2463          if (devices)
2464          {
2465             /* Make sure the devices are available and/or shareable */
2466             for (device = 0; device < MAX_INPUT_DEVICES; device++)
2467             {
2468                if (!(devices & (1<<device)))
2469                   continue;
2470                if (!netplay->device_clients[device])
2471                   continue;
2472                if (netplay->device_share_modes[device] && share_mode)
2473                   continue;
2474 
2475                /* Device already taken and unshareable */
2476                payload[0] = htonl(NETPLAY_CMD_MODE_REFUSED_REASON_NOT_AVAILABLE);
2477                /* FIXME: Refusal message for the server */
2478                if (connection)
2479                   netplay_send_raw_cmd(netplay, connection, NETPLAY_CMD_MODE_REFUSED, payload, sizeof(uint32_t));
2480                devices = 0;
2481                break;
2482             }
2483             if (devices == 0)
2484                break;
2485 
2486             /* Set the share mode on any new devices */
2487             for (device = 0; device < MAX_INPUT_DEVICES; device++)
2488             {
2489                if (!(devices & (1<<device)))
2490                   continue;
2491                if (!netplay->device_clients[device])
2492                   netplay->device_share_modes[device] = share_mode;
2493             }
2494 
2495          }
2496          else
2497          {
2498             /* Find an available device */
2499             for (device = 0; device < MAX_INPUT_DEVICES; device++)
2500             {
2501                if (netplay->config_devices[device] == RETRO_DEVICE_NONE)
2502                {
2503                   device = MAX_INPUT_DEVICES;
2504                   break;
2505                }
2506                if (!netplay->device_clients[device])
2507                   break;
2508             }
2509             if (device >= MAX_INPUT_DEVICES &&
2510                 netplay->config_devices[1] == RETRO_DEVICE_NONE && share_mode)
2511             {
2512                /* No device free and no device specifically asked for, but only
2513                 * one device, so share it */
2514                if (netplay->device_share_modes[0])
2515                {
2516                   device     = 0;
2517                   share_mode = netplay->device_share_modes[0];
2518                   break;
2519                }
2520             }
2521             if (device >= MAX_INPUT_DEVICES)
2522             {
2523                /* No slots free! */
2524                payload[0] = htonl(NETPLAY_CMD_MODE_REFUSED_REASON_NO_SLOTS);
2525                /* FIXME: Message for the server */
2526                if (connection)
2527                   netplay_send_raw_cmd(netplay, connection, NETPLAY_CMD_MODE_REFUSED, payload, sizeof(uint32_t));
2528                break;
2529             }
2530             devices = 1<<device;
2531             netplay->device_share_modes[device] = share_mode;
2532 
2533          }
2534 
2535          payload[2] = htonl(devices);
2536 
2537          /* Mark them as playing */
2538          if (connection)
2539             connection->mode =
2540                   slave ? NETPLAY_CONNECTION_SLAVE : NETPLAY_CONNECTION_PLAYING;
2541          else
2542          {
2543             netplay->self_devices = devices;
2544             netplay->self_mode = NETPLAY_CONNECTION_PLAYING;
2545          }
2546          netplay->connected_players |= 1 << client_num;
2547          if (slave)
2548             netplay->connected_slaves |= 1 << client_num;
2549          netplay->client_devices[client_num] = devices;
2550          for (device = 0; device < MAX_INPUT_DEVICES; device++)
2551          {
2552             if (!(devices & (1<<device)))
2553                continue;
2554             netplay->device_clients[device] |= 1 << client_num;
2555          }
2556 
2557          /* Tell everyone */
2558          payload[1] = htonl(
2559                NETPLAY_CMD_MODE_BIT_PLAYING
2560                      | (slave ? NETPLAY_CMD_MODE_BIT_SLAVE : 0) | client_num);
2561          memcpy(payload + 3, netplay->device_share_modes, sizeof(netplay->device_share_modes));
2562          if (connection)
2563             strncpy((char *) (payload + 7), connection->nick, NETPLAY_NICK_LEN);
2564          else
2565             strncpy((char *) (payload + 7), netplay->nick, NETPLAY_NICK_LEN);
2566          netplay_send_raw_cmd_all(netplay, connection, NETPLAY_CMD_MODE,
2567                payload, sizeof(payload));
2568 
2569          /* Tell the player */
2570          if (connection)
2571          {
2572             payload[1] = htonl(NETPLAY_CMD_MODE_BIT_PLAYING |
2573                                ((connection->mode == NETPLAY_CONNECTION_SLAVE)?
2574                                 NETPLAY_CMD_MODE_BIT_SLAVE:0) |
2575                                NETPLAY_CMD_MODE_BIT_YOU |
2576                                client_num);
2577             netplay_send_raw_cmd(netplay, connection, NETPLAY_CMD_MODE, payload, sizeof(payload));
2578          }
2579 
2580          /* Announce it */
2581          announce_play_spectate(netplay, connection ? connection->nick : NULL,
2582                NETPLAY_CONNECTION_PLAYING, devices);
2583          break;
2584       }
2585    }
2586 }
2587 
2588 #undef RECV
2589 #define RECV(buf, sz) \
2590 recvd = netplay_recv(&connection->recv_packet_buffer, connection->fd, (buf), \
2591 (sz), false); \
2592 if (recvd >= 0 && recvd < (ssize_t) (sz)) goto shrt; \
2593 else if (recvd < 0)
2594 
netplay_get_cmd(netplay_t * netplay,struct netplay_connection * connection,bool * had_input)2595 static bool netplay_get_cmd(netplay_t *netplay,
2596    struct netplay_connection *connection, bool *had_input)
2597 {
2598    uint32_t cmd;
2599    uint32_t cmd_size;
2600    ssize_t recvd;
2601 
2602    /* We don't handle the initial handshake here */
2603    if (connection->mode < NETPLAY_CONNECTION_CONNECTED)
2604       return netplay_handshake(netplay, connection, had_input);
2605 
2606    RECV(&cmd, sizeof(cmd))
2607       return false;
2608 
2609    cmd      = ntohl(cmd);
2610 
2611    RECV(&cmd_size, sizeof(cmd_size))
2612       return false;
2613 
2614    cmd_size = ntohl(cmd_size);
2615 
2616 #ifdef DEBUG_NETPLAY_STEPS
2617    RARCH_LOG("[netplay] Received netplay command %X (%u) from %u\n", cmd, cmd_size,
2618          (unsigned) (connection - netplay->connections));
2619 #endif
2620 
2621    netplay->timeout_cnt = 0;
2622 
2623    switch (cmd)
2624    {
2625       case NETPLAY_CMD_ACK:
2626          /* Why are we even bothering? */
2627          break;
2628 
2629       case NETPLAY_CMD_NAK:
2630          /* Disconnect now! */
2631          return false;
2632 
2633       case NETPLAY_CMD_INPUT:
2634          {
2635             uint32_t frame_num, client_num, input_size, devices, device;
2636             struct delta_frame *dframe;
2637 
2638             if (cmd_size < 2*sizeof(uint32_t))
2639             {
2640                RARCH_ERR("NETPLAY_CMD_INPUT too short, no frame/client number.");
2641                return netplay_cmd_nak(netplay, connection);
2642             }
2643 
2644             RECV(&frame_num, sizeof(frame_num))
2645                return false;
2646             RECV(&client_num, sizeof(client_num))
2647                return false;
2648             frame_num = ntohl(frame_num);
2649             client_num = ntohl(client_num);
2650             client_num &= 0xFFFF;
2651 
2652             if (netplay->is_server)
2653             {
2654                /* Ignore the claimed client #, must be this client */
2655                if (connection->mode != NETPLAY_CONNECTION_PLAYING &&
2656                    connection->mode != NETPLAY_CONNECTION_SLAVE)
2657                {
2658                   RARCH_ERR("Netplay input from non-participating player.\n");
2659                   return netplay_cmd_nak(netplay, connection);
2660                }
2661                client_num = (uint32_t)(connection - netplay->connections + 1);
2662             }
2663 
2664             if (client_num > MAX_CLIENTS)
2665             {
2666                RARCH_ERR("NETPLAY_CMD_INPUT received data for an unsupported client.\n");
2667                return netplay_cmd_nak(netplay, connection);
2668             }
2669 
2670             /* Figure out how much input is expected */
2671             devices = netplay->client_devices[client_num];
2672             input_size = netplay_expected_input_size(netplay, devices);
2673 
2674             if (cmd_size != (2+input_size) * sizeof(uint32_t))
2675             {
2676                RARCH_ERR("NETPLAY_CMD_INPUT received an unexpected payload size.\n");
2677                return netplay_cmd_nak(netplay, connection);
2678             }
2679 
2680             if (client_num >= MAX_CLIENTS || !(netplay->connected_players & (1<<client_num)))
2681             {
2682                RARCH_ERR("Invalid NETPLAY_CMD_INPUT player number.\n");
2683                return netplay_cmd_nak(netplay, connection);
2684             }
2685 
2686             /* Check the frame number only if they're not in slave mode */
2687             if (connection->mode == NETPLAY_CONNECTION_PLAYING)
2688             {
2689                if (frame_num < netplay->read_frame_count[client_num])
2690                {
2691                   uint32_t buf;
2692                   /* We already had this, so ignore the new transmission */
2693                   for (; input_size; input_size--)
2694                   {
2695                      RECV(&buf, sizeof(uint32_t))
2696                         return netplay_cmd_nak(netplay, connection);
2697                   }
2698                   break;
2699                }
2700                else if (frame_num > netplay->read_frame_count[client_num])
2701                {
2702                   /* Out of order = out of luck */
2703                   RARCH_ERR("Netplay input out of order.\n");
2704                   return netplay_cmd_nak(netplay, connection);
2705                }
2706             }
2707 
2708             /* The data's good! */
2709             dframe = &netplay->buffer[netplay->read_ptr[client_num]];
2710             if (!netplay_delta_frame_ready(netplay, dframe, netplay->read_frame_count[client_num]))
2711             {
2712                /* Hopefully we'll be ready after another round of input */
2713                goto shrt;
2714             }
2715 
2716             /* Copy in the input */
2717             for (device = 0; device < MAX_INPUT_DEVICES; device++)
2718             {
2719                netplay_input_state_t istate;
2720                uint32_t dsize, di;
2721                if (!(devices & (1<<device)))
2722                   continue;
2723 
2724                dsize = netplay_expected_input_size(netplay, 1 << device);
2725                istate = netplay_input_state_for(&dframe->real_input[device],
2726                      client_num, dsize,
2727                      false /* Must be false because of slave-mode clients */,
2728                      false);
2729                if (!istate)
2730                {
2731                   /* Catastrophe! */
2732                   return netplay_cmd_nak(netplay, connection);
2733                }
2734                RECV(istate->data, dsize*sizeof(uint32_t))
2735                   return false;
2736                for (di = 0; di < dsize; di++)
2737                   istate->data[di] = ntohl(istate->data[di]);
2738             }
2739             dframe->have_real[client_num] = true;
2740 
2741             /* Slaves may go through several packets of data in the same frame
2742              * if latency is choppy, so we advance and send their data after
2743              * handling all network data this frame */
2744             if (connection->mode == NETPLAY_CONNECTION_PLAYING)
2745             {
2746                netplay->read_ptr[client_num] = NEXT_PTR(netplay->read_ptr[client_num]);
2747                netplay->read_frame_count[client_num]++;
2748 
2749                if (netplay->is_server)
2750                {
2751                   /* Forward it on if it's past data */
2752                   if (dframe->frame <= netplay->self_frame_count)
2753                      send_input_frame(netplay, dframe, NULL, connection, client_num, false);
2754                }
2755             }
2756 
2757             /* If this was server data, advance our server pointer too */
2758             if (!netplay->is_server && client_num == 0)
2759             {
2760                netplay->server_ptr = netplay->read_ptr[0];
2761                netplay->server_frame_count = netplay->read_frame_count[0];
2762             }
2763 
2764 #ifdef DEBUG_NETPLAY_STEPS
2765             RARCH_LOG("[netplay] Received input from %u\n", client_num);
2766             print_state(netplay);
2767 #endif
2768             break;
2769          }
2770 
2771       case NETPLAY_CMD_NOINPUT:
2772          {
2773             uint32_t frame;
2774 
2775             if (netplay->is_server)
2776             {
2777                RARCH_ERR("NETPLAY_CMD_NOINPUT from a client.\n");
2778                return netplay_cmd_nak(netplay, connection);
2779             }
2780 
2781             RECV(&frame, sizeof(frame))
2782             {
2783                RARCH_ERR("Failed to receive NETPLAY_CMD_NOINPUT payload.\n");
2784                return netplay_cmd_nak(netplay, connection);
2785             }
2786 
2787             frame = ntohl(frame);
2788 
2789             /* We already had this, so ignore the new transmission */
2790             if (frame < netplay->server_frame_count)
2791                break;
2792 
2793             if (frame != netplay->server_frame_count)
2794             {
2795                RARCH_ERR("NETPLAY_CMD_NOINPUT for invalid frame.\n");
2796                return netplay_cmd_nak(netplay, connection);
2797             }
2798 
2799             netplay->server_ptr = NEXT_PTR(netplay->server_ptr);
2800             netplay->server_frame_count++;
2801 #ifdef DEBUG_NETPLAY_STEPS
2802             RARCH_LOG("[netplay] Received server noinput\n");
2803             print_state(netplay);
2804 #endif
2805             break;
2806          }
2807 
2808       case NETPLAY_CMD_SPECTATE:
2809       {
2810          uint32_t client_num;
2811 
2812          if (!netplay->is_server)
2813          {
2814             RARCH_ERR("NETPLAY_CMD_SPECTATE from a server.\n");
2815             return netplay_cmd_nak(netplay, connection);
2816          }
2817 
2818          if (cmd_size != 0)
2819          {
2820             RARCH_ERR("Unexpected payload in NETPLAY_CMD_SPECTATE.\n");
2821             return netplay_cmd_nak(netplay, connection);
2822          }
2823 
2824          if (connection->mode != NETPLAY_CONNECTION_PLAYING &&
2825              connection->mode != NETPLAY_CONNECTION_SLAVE)
2826          {
2827             /* They were confused */
2828             return netplay_cmd_nak(netplay, connection);
2829          }
2830 
2831          client_num = (uint32_t)(connection - netplay->connections + 1);
2832 
2833          handle_play_spectate(netplay, client_num, connection, cmd, 0, NULL);
2834          break;
2835       }
2836 
2837       case NETPLAY_CMD_PLAY:
2838       {
2839          uint32_t client_num;
2840          uint32_t payload[1];
2841 
2842          if (cmd_size != sizeof(uint32_t))
2843          {
2844             RARCH_ERR("Incorrect NETPLAY_CMD_PLAY payload size.\n");
2845             return netplay_cmd_nak(netplay, connection);
2846          }
2847          RECV(payload, sizeof(uint32_t))
2848          {
2849             RARCH_ERR("Failed to receive NETPLAY_CMD_PLAY payload.\n");
2850             return netplay_cmd_nak(netplay, connection);
2851          }
2852 
2853          if (!netplay->is_server)
2854          {
2855             RARCH_ERR("NETPLAY_CMD_PLAY from a server.\n");
2856             return netplay_cmd_nak(netplay, connection);
2857          }
2858 
2859          if (connection->delay_frame)
2860          {
2861             /* Can't switch modes while a mode switch is already in progress. */
2862             payload[0] = htonl(NETPLAY_CMD_MODE_REFUSED_REASON_TOO_FAST);
2863             netplay_send_raw_cmd(netplay, connection, NETPLAY_CMD_MODE_REFUSED, payload, sizeof(uint32_t));
2864             break;
2865          }
2866 
2867          if (!connection->can_play)
2868          {
2869             /* Not allowed to play */
2870             payload[0] = htonl(NETPLAY_CMD_MODE_REFUSED_REASON_UNPRIVILEGED);
2871             netplay_send_raw_cmd(netplay, connection, NETPLAY_CMD_MODE_REFUSED, payload, sizeof(uint32_t));
2872             break;
2873          }
2874 
2875          /* They were obviously confused */
2876          if (
2877                   connection->mode == NETPLAY_CONNECTION_PLAYING
2878                || connection->mode == NETPLAY_CONNECTION_SLAVE)
2879             return netplay_cmd_nak(netplay, connection);
2880 
2881          client_num = (unsigned)(connection - netplay->connections + 1);
2882 
2883          handle_play_spectate(netplay, client_num, connection, cmd, cmd_size, payload);
2884          break;
2885       }
2886 
2887       case NETPLAY_CMD_MODE:
2888       {
2889          uint32_t payload[15];
2890          uint32_t frame, mode, client_num, devices, device;
2891          size_t ptr;
2892          struct delta_frame *dframe;
2893          const char *nick;
2894 
2895 #define START(which) \
2896          do { \
2897             ptr    = which; \
2898             dframe = &netplay->buffer[ptr]; \
2899          } while (0)
2900 #define NEXT() \
2901          do { \
2902             ptr    = NEXT_PTR(ptr); \
2903             dframe = &netplay->buffer[ptr]; \
2904          } while (0)
2905 
2906          if (netplay->is_server)
2907          {
2908             RARCH_ERR("NETPLAY_CMD_MODE from client.\n");
2909             return netplay_cmd_nak(netplay, connection);
2910          }
2911 
2912          if (cmd_size != sizeof(payload))
2913          {
2914             RARCH_ERR("Invalid payload size for NETPLAY_CMD_MODE.\n");
2915             return netplay_cmd_nak(netplay, connection);
2916          }
2917 
2918          RECV(payload, sizeof(payload))
2919          {
2920             RARCH_ERR("NETPLAY_CMD_MODE failed to receive payload.\n");
2921             return netplay_cmd_nak(netplay, connection);
2922          }
2923 
2924          frame = ntohl(payload[0]);
2925 
2926          /* We're changing past input, so must replay it */
2927          if (frame < netplay->self_frame_count)
2928             netplay->force_rewind = true;
2929 
2930          mode = ntohl(payload[1]);
2931          client_num = mode & 0xFFFF;
2932          if (client_num >= MAX_CLIENTS)
2933          {
2934             RARCH_ERR("Received NETPLAY_CMD_MODE for a higher player number than we support.\n");
2935             return netplay_cmd_nak(netplay, connection);
2936          }
2937 
2938          devices = ntohl(payload[2]);
2939          memcpy(netplay->device_share_modes, payload + 3, sizeof(netplay->device_share_modes));
2940          nick = (const char *) (payload + 7);
2941 
2942          if (mode & NETPLAY_CMD_MODE_BIT_YOU)
2943          {
2944             /* A change to me! */
2945             if (mode & NETPLAY_CMD_MODE_BIT_PLAYING)
2946             {
2947                if (frame != netplay->server_frame_count)
2948                {
2949                   RARCH_ERR("Received mode change out of order.\n");
2950                   return netplay_cmd_nak(netplay, connection);
2951                }
2952 
2953                /* Hooray, I get to play now! */
2954                if (netplay->self_mode == NETPLAY_CONNECTION_PLAYING)
2955                {
2956                   RARCH_ERR("Received player mode change even though I'm already a player.\n");
2957                   return netplay_cmd_nak(netplay, connection);
2958                }
2959 
2960                /* Our mode is based on whether we have the slave bit set */
2961                if (mode & NETPLAY_CMD_MODE_BIT_SLAVE)
2962                   netplay->self_mode = NETPLAY_CONNECTION_SLAVE;
2963                else
2964                   netplay->self_mode = NETPLAY_CONNECTION_PLAYING;
2965 
2966                netplay->connected_players |= (1<<client_num);
2967                netplay->client_devices[client_num] = devices;
2968                for (device = 0; device < MAX_INPUT_DEVICES; device++)
2969                   if (devices & (1<<device))
2970                      netplay->device_clients[device] |= (1<<client_num);
2971                netplay->self_devices = devices;
2972 
2973                netplay->read_ptr[client_num] = netplay->server_ptr;
2974                netplay->read_frame_count[client_num] = netplay->server_frame_count;
2975 
2976                /* Fix up current frame info */
2977                if (!(mode & NETPLAY_CMD_MODE_BIT_SLAVE) && frame <= netplay->self_frame_count)
2978                {
2979                   /* It wanted past frames, better send 'em! */
2980                   START(netplay->server_ptr);
2981                   while (dframe->used && dframe->frame <= netplay->self_frame_count)
2982                   {
2983                      for (device = 0; device < MAX_INPUT_DEVICES; device++)
2984                      {
2985                         uint32_t dsize;
2986                         netplay_input_state_t istate;
2987                         if (!(devices & (1<<device)))
2988                            continue;
2989                         dsize = netplay_expected_input_size(netplay, 1 << device);
2990                         istate = netplay_input_state_for(
2991                               &dframe->real_input[device], client_num, dsize,
2992                               false, false);
2993                         if (!istate)
2994                            continue;
2995                         memset(istate->data, 0, dsize*sizeof(uint32_t));
2996                      }
2997                      dframe->have_local = true;
2998                      dframe->have_real[client_num] = true;
2999                      send_input_frame(netplay, dframe, connection, NULL, client_num, false);
3000                      if (dframe->frame == netplay->self_frame_count) break;
3001                      NEXT();
3002                   }
3003 
3004                }
3005                else
3006                {
3007                   uint32_t frame_count;
3008 
3009                   /* It wants future frames, make sure we don't capture or send intermediate ones */
3010                   START(netplay->self_ptr);
3011                   frame_count = netplay->self_frame_count;
3012 
3013                   for (;;)
3014                   {
3015                      if (!dframe->used)
3016                      {
3017                         /* Make sure it's ready */
3018                         if (!netplay_delta_frame_ready(netplay, dframe, frame_count))
3019                         {
3020                            RARCH_ERR("Received mode change but delta frame isn't ready!\n");
3021                            return netplay_cmd_nak(netplay, connection);
3022                         }
3023                      }
3024 
3025                      dframe->have_local = true;
3026 
3027                      /* Go on to the next delta frame */
3028                      NEXT();
3029                      frame_count++;
3030 
3031                      if (frame_count >= frame)
3032                         break;
3033                   }
3034 
3035                }
3036 
3037                /* Announce it */
3038                announce_play_spectate(netplay, NULL, NETPLAY_CONNECTION_PLAYING, devices);
3039 
3040 #ifdef DEBUG_NETPLAY_STEPS
3041                RARCH_LOG("[netplay] Received mode change self->%X\n", devices);
3042                print_state(netplay);
3043 #endif
3044 
3045             }
3046             else /* YOU && !PLAYING */
3047             {
3048                /* I'm no longer playing, but I should already know this */
3049                if (netplay->self_mode != NETPLAY_CONNECTION_SPECTATING)
3050                {
3051                   RARCH_ERR("Received mode change to spectator unprompted.\n");
3052                   return netplay_cmd_nak(netplay, connection);
3053                }
3054 
3055                /* Unmark ourself, in case we were in slave mode */
3056                netplay->connected_players &= ~(1<<client_num);
3057                netplay->client_devices[client_num] = 0;
3058                for (device = 0; device < MAX_INPUT_DEVICES; device++)
3059                   netplay->device_clients[device] &= ~(1<<client_num);
3060 
3061                /* Announce it */
3062                announce_play_spectate(netplay, NULL, NETPLAY_CONNECTION_SPECTATING, 0);
3063 
3064 #ifdef DEBUG_NETPLAY_STEPS
3065                RARCH_LOG("[netplay] Received mode change self->spectating\n");
3066                print_state(netplay);
3067 #endif
3068 
3069             }
3070 
3071          }
3072          else /* !YOU */
3073          {
3074             /* Somebody else is joining or parting */
3075             if (mode & NETPLAY_CMD_MODE_BIT_PLAYING)
3076             {
3077                if (frame != netplay->server_frame_count)
3078                {
3079                   RARCH_ERR("Received mode change out of order.\n");
3080                   return netplay_cmd_nak(netplay, connection);
3081                }
3082 
3083                netplay->connected_players |= (1<<client_num);
3084                netplay->client_devices[client_num] = devices;
3085                for (device = 0; device < MAX_INPUT_DEVICES; device++)
3086                   if (devices & (1<<device))
3087                      netplay->device_clients[device] |= (1<<client_num);
3088 
3089                netplay->read_ptr[client_num] = netplay->server_ptr;
3090                netplay->read_frame_count[client_num] = netplay->server_frame_count;
3091 
3092                /* Announce it */
3093                announce_play_spectate(netplay, nick, NETPLAY_CONNECTION_PLAYING, devices);
3094 
3095 #ifdef DEBUG_NETPLAY_STEPS
3096                RARCH_LOG("[netplay] Received mode change %u->%u\n", client_num, devices);
3097                print_state(netplay);
3098 #endif
3099 
3100             }
3101             else
3102             {
3103                netplay->connected_players &= ~(1<<client_num);
3104                netplay->client_devices[client_num] = 0;
3105                for (device = 0; device < MAX_INPUT_DEVICES; device++)
3106                   netplay->device_clients[device] &= ~(1<<client_num);
3107 
3108                /* Announce it */
3109                announce_play_spectate(netplay, nick, NETPLAY_CONNECTION_SPECTATING, 0);
3110 
3111 #ifdef DEBUG_NETPLAY_STEPS
3112                RARCH_LOG("[netplay] Received mode change %u->spectator\n", client_num);
3113                print_state(netplay);
3114 #endif
3115 
3116             }
3117 
3118          }
3119 
3120          break;
3121 
3122 #undef START
3123 #undef NEXT
3124       }
3125 
3126       case NETPLAY_CMD_MODE_REFUSED:
3127          {
3128             uint32_t reason;
3129             const char *dmsg = NULL;
3130 
3131             if (netplay->is_server)
3132             {
3133                RARCH_ERR("NETPLAY_CMD_MODE_REFUSED from client.\n");
3134                return netplay_cmd_nak(netplay, connection);
3135             }
3136 
3137             if (cmd_size != sizeof(uint32_t))
3138             {
3139                RARCH_ERR("Received invalid payload size for NETPLAY_CMD_MODE_REFUSED.\n");
3140                return netplay_cmd_nak(netplay, connection);
3141             }
3142 
3143             RECV(&reason, sizeof(reason))
3144             {
3145                RARCH_ERR("Failed to receive NETPLAY_CMD_MODE_REFUSED payload.\n");
3146                return netplay_cmd_nak(netplay, connection);
3147             }
3148             reason = ntohl(reason);
3149 
3150             switch (reason)
3151             {
3152                case NETPLAY_CMD_MODE_REFUSED_REASON_UNPRIVILEGED:
3153                   dmsg = msg_hash_to_str(MSG_NETPLAY_CANNOT_PLAY_UNPRIVILEGED);
3154                   break;
3155 
3156                case NETPLAY_CMD_MODE_REFUSED_REASON_NO_SLOTS:
3157                   dmsg = msg_hash_to_str(MSG_NETPLAY_CANNOT_PLAY_NO_SLOTS);
3158                   break;
3159 
3160                case NETPLAY_CMD_MODE_REFUSED_REASON_NOT_AVAILABLE:
3161                   dmsg = msg_hash_to_str(MSG_NETPLAY_CANNOT_PLAY_NOT_AVAILABLE);
3162                   break;
3163 
3164                default:
3165                   dmsg = msg_hash_to_str(MSG_NETPLAY_CANNOT_PLAY);
3166             }
3167 
3168             if (dmsg)
3169             {
3170                RARCH_LOG("[netplay] %s\n", dmsg);
3171                runloop_msg_queue_push(dmsg, 1, 180, false, NULL, MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
3172             }
3173             break;
3174          }
3175 
3176       case NETPLAY_CMD_DISCONNECT:
3177          netplay_hangup(netplay, connection);
3178          return true;
3179 
3180       case NETPLAY_CMD_CRC:
3181          {
3182             uint32_t buffer[2];
3183             size_t tmp_ptr = netplay->run_ptr;
3184             bool found = false;
3185 
3186             if (cmd_size != sizeof(buffer))
3187             {
3188                RARCH_ERR("NETPLAY_CMD_CRC received unexpected payload size.\n");
3189                return netplay_cmd_nak(netplay, connection);
3190             }
3191 
3192             RECV(buffer, sizeof(buffer))
3193             {
3194                RARCH_ERR("NETPLAY_CMD_CRC failed to receive payload.\n");
3195                return netplay_cmd_nak(netplay, connection);
3196             }
3197 
3198             buffer[0] = ntohl(buffer[0]);
3199             buffer[1] = ntohl(buffer[1]);
3200 
3201             /* Received a CRC for some frame. If we still have it, check if it
3202              * matched. This approach could be improved with some quick modular
3203              * arithmetic. */
3204             do
3205             {
3206                if (     netplay->buffer[tmp_ptr].used
3207                      && netplay->buffer[tmp_ptr].frame == buffer[0])
3208                {
3209                   found = true;
3210                   break;
3211                }
3212 
3213                tmp_ptr = PREV_PTR(tmp_ptr);
3214             } while (tmp_ptr != netplay->run_ptr);
3215 
3216             /* Oh well, we got rid of it! */
3217             if (!found)
3218                break;
3219 
3220             if (buffer[0] <= netplay->other_frame_count)
3221             {
3222                /* We've already replayed up to this frame, so we can check it
3223                 * directly */
3224                uint32_t local_crc = 0;
3225                if (netplay->state_size)
3226                   local_crc       = netplay_delta_frame_crc(
3227                         netplay, &netplay->buffer[tmp_ptr]);
3228 
3229                /* Problem! */
3230                if (buffer[1] != local_crc)
3231                   netplay_cmd_request_savestate(netplay);
3232             }
3233             else
3234             {
3235                /* We'll have to check it when we catch up */
3236                netplay->buffer[tmp_ptr].crc = buffer[1];
3237             }
3238 
3239             break;
3240          }
3241 
3242       case NETPLAY_CMD_REQUEST_SAVESTATE:
3243          /* Delay until next frame so we don't send the savestate after the
3244           * input */
3245          netplay->force_send_savestate = true;
3246          break;
3247 
3248       case NETPLAY_CMD_LOAD_SAVESTATE:
3249       case NETPLAY_CMD_RESET:
3250          {
3251             uint32_t frame;
3252             uint32_t isize;
3253             uint32_t rd, wn;
3254             uint32_t client;
3255             uint32_t load_frame_count;
3256             size_t load_ptr;
3257             struct compression_transcoder *ctrans = NULL;
3258             uint32_t                   client_num = (uint32_t)
3259              (connection - netplay->connections + 1);
3260 
3261             /* Make sure we're ready for it */
3262             if (netplay->quirks & NETPLAY_QUIRK_INITIALIZATION)
3263             {
3264                if (!netplay->is_replay)
3265                {
3266                   netplay->is_replay          = true;
3267                   netplay->replay_ptr         = netplay->run_ptr;
3268                   netplay->replay_frame_count = netplay->run_frame_count;
3269                   netplay_wait_and_init_serialization(netplay);
3270                   netplay->is_replay         = false;
3271                }
3272                else
3273                   netplay_wait_and_init_serialization(netplay);
3274             }
3275 
3276             /* Only players may load states */
3277             if (connection->mode != NETPLAY_CONNECTION_PLAYING &&
3278                 connection->mode != NETPLAY_CONNECTION_SLAVE)
3279             {
3280                RARCH_ERR("Netplay state load from a spectator.\n");
3281                return netplay_cmd_nak(netplay, connection);
3282             }
3283 
3284             /* We only allow players to load state if we're in a simple
3285              * two-player situation */
3286             if (netplay->is_server && netplay->connections_size > 1)
3287             {
3288                RARCH_ERR("Netplay state load from a client with other clients connected disallowed.\n");
3289                return netplay_cmd_nak(netplay, connection);
3290             }
3291 
3292             /* There is a subtlty in whether the load comes before or after the
3293              * current frame:
3294              *
3295              * If it comes before the current frame, then we need to force a
3296              * rewind to that point.
3297              *
3298              * If it comes after the current frame, we need to jump ahead, then
3299              * (strangely) force a rewind to the frame we're already on, so it
3300              * gets loaded. This is just to avoid having reloading implemented in
3301              * too many places. */
3302 
3303             /* Check the payload size */
3304             if ((cmd == NETPLAY_CMD_LOAD_SAVESTATE &&
3305                  (cmd_size < 2*sizeof(uint32_t) || cmd_size > netplay->zbuffer_size + 2*sizeof(uint32_t))) ||
3306                 (cmd == NETPLAY_CMD_RESET && cmd_size != sizeof(uint32_t)))
3307             {
3308                RARCH_ERR("CMD_LOAD_SAVESTATE received an unexpected payload size.\n");
3309                return netplay_cmd_nak(netplay, connection);
3310             }
3311 
3312             RECV(&frame, sizeof(frame))
3313             {
3314                RARCH_ERR("CMD_LOAD_SAVESTATE failed to receive savestate frame.\n");
3315                return netplay_cmd_nak(netplay, connection);
3316             }
3317             frame = ntohl(frame);
3318 
3319             if (netplay->is_server)
3320             {
3321                load_ptr = netplay->read_ptr[client_num];
3322                load_frame_count = netplay->read_frame_count[client_num];
3323             }
3324             else
3325             {
3326                load_ptr = netplay->server_ptr;
3327                load_frame_count = netplay->server_frame_count;
3328             }
3329 
3330             if (frame != load_frame_count)
3331             {
3332                RARCH_ERR("CMD_LOAD_SAVESTATE loading a state out of order!\n");
3333                return netplay_cmd_nak(netplay, connection);
3334             }
3335 
3336             if (!netplay_delta_frame_ready(netplay, &netplay->buffer[load_ptr], load_frame_count))
3337             {
3338                /* Hopefully it will be after another round of input */
3339                goto shrt;
3340             }
3341 
3342             /* Now we switch based on whether we're loading a state or resetting */
3343             if (cmd == NETPLAY_CMD_LOAD_SAVESTATE)
3344             {
3345                RECV(&isize, sizeof(isize))
3346                {
3347                   RARCH_ERR("CMD_LOAD_SAVESTATE failed to receive inflated size.\n");
3348                   return netplay_cmd_nak(netplay, connection);
3349                }
3350                isize = ntohl(isize);
3351 
3352                if (isize != netplay->state_size)
3353                {
3354                   RARCH_ERR("CMD_LOAD_SAVESTATE received an unexpected save state size.\n");
3355                   return netplay_cmd_nak(netplay, connection);
3356                }
3357 
3358                RECV(netplay->zbuffer, cmd_size - 2*sizeof(uint32_t))
3359                {
3360                   RARCH_ERR("CMD_LOAD_SAVESTATE failed to receive savestate.\n");
3361                   return netplay_cmd_nak(netplay, connection);
3362                }
3363 
3364                /* And decompress it */
3365                switch (connection->compression_supported)
3366                {
3367                   case NETPLAY_COMPRESSION_ZLIB:
3368                      ctrans = &netplay->compress_zlib;
3369                      break;
3370                   default:
3371                      ctrans = &netplay->compress_nil;
3372                }
3373                ctrans->decompression_backend->set_in(ctrans->decompression_stream,
3374                   netplay->zbuffer, cmd_size - 2*sizeof(uint32_t));
3375                ctrans->decompression_backend->set_out(ctrans->decompression_stream,
3376                   (uint8_t*)netplay->buffer[load_ptr].state,
3377                   (unsigned)netplay->state_size);
3378                ctrans->decompression_backend->trans(ctrans->decompression_stream,
3379                   true, &rd, &wn, NULL);
3380 
3381                /* Force a rewind to the relevant frame */
3382                netplay->force_rewind = true;
3383             }
3384             else
3385             {
3386                /* Resetting */
3387                netplay->force_reset = true;
3388 
3389             }
3390 
3391             /* Skip ahead if it's past where we are */
3392             if (load_frame_count > netplay->run_frame_count ||
3393                 cmd == NETPLAY_CMD_RESET)
3394             {
3395                /* This is squirrely: We need to assure that when we advance the
3396                 * frame in post_frame, THEN we're referring to the frame to
3397                 * load into. If we refer directly to read_ptr, then we'll end
3398                 * up never reading the input for read_frame_count itself, which
3399                 * will make the other side unhappy. */
3400                netplay->run_ptr           = PREV_PTR(load_ptr);
3401                netplay->run_frame_count   = load_frame_count - 1;
3402                if (frame > netplay->self_frame_count)
3403                {
3404                   netplay->self_ptr         = netplay->run_ptr;
3405                   netplay->self_frame_count = netplay->run_frame_count;
3406                }
3407             }
3408 
3409             /* Don't expect earlier data from other clients */
3410             for (client = 0; client < MAX_CLIENTS; client++)
3411             {
3412                if (!(netplay->connected_players & (1<<client)))
3413                   continue;
3414 
3415                if (frame > netplay->read_frame_count[client])
3416                {
3417                   netplay->read_ptr[client] = load_ptr;
3418                   netplay->read_frame_count[client] = load_frame_count;
3419                }
3420             }
3421 
3422             /* Make sure our states are correct */
3423             netplay->savestate_request_outstanding = false;
3424             netplay->other_ptr                     = load_ptr;
3425             netplay->other_frame_count             = load_frame_count;
3426 
3427 #ifdef DEBUG_NETPLAY_STEPS
3428             RARCH_LOG("[netplay] Loading state at %u\n", load_frame_count);
3429             print_state(netplay);
3430 #endif
3431 
3432             break;
3433          }
3434 
3435       case NETPLAY_CMD_PAUSE:
3436          {
3437             char msg[512], nick[NETPLAY_NICK_LEN];
3438             msg[sizeof(msg)-1] = '\0';
3439 
3440             /* Read in the paused nick */
3441             if (cmd_size != sizeof(nick))
3442             {
3443                RARCH_ERR("NETPLAY_CMD_PAUSE received invalid payload size.\n");
3444                return netplay_cmd_nak(netplay, connection);
3445             }
3446             RECV(nick, sizeof(nick))
3447             {
3448                RARCH_ERR("Failed to receive paused nickname.\n");
3449                return netplay_cmd_nak(netplay, connection);
3450             }
3451             nick[sizeof(nick)-1] = '\0';
3452 
3453             /* We outright ignore pausing from spectators and slaves */
3454             if (connection->mode != NETPLAY_CONNECTION_PLAYING)
3455                break;
3456 
3457             connection->paused = true;
3458             netplay->remote_paused = true;
3459             if (netplay->is_server)
3460             {
3461                /* Inform peers */
3462                snprintf(msg, sizeof(msg)-1, msg_hash_to_str(MSG_NETPLAY_PEER_PAUSED), connection->nick);
3463                netplay_send_raw_cmd_all(netplay, connection, NETPLAY_CMD_PAUSE,
3464                      connection->nick, NETPLAY_NICK_LEN);
3465 
3466                /* We may not reach post_frame soon, so flush the pause message
3467                 * immediately. */
3468                netplay_send_flush_all(netplay, connection);
3469             }
3470             else
3471             {
3472                snprintf(msg, sizeof(msg)-1, msg_hash_to_str(MSG_NETPLAY_PEER_PAUSED), nick);
3473             }
3474             RARCH_LOG("[netplay] %s\n", msg);
3475             runloop_msg_queue_push(msg, 1, 180, false, NULL, MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
3476             break;
3477          }
3478 
3479       case NETPLAY_CMD_RESUME:
3480          remote_unpaused(netplay, connection);
3481          break;
3482 
3483       case NETPLAY_CMD_STALL:
3484          {
3485             uint32_t frames;
3486 
3487             if (cmd_size != sizeof(uint32_t))
3488             {
3489                RARCH_ERR("NETPLAY_CMD_STALL with incorrect payload size.\n");
3490                return netplay_cmd_nak(netplay, connection);
3491             }
3492 
3493             RECV(&frames, sizeof(frames))
3494             {
3495                RARCH_ERR("Failed to receive NETPLAY_CMD_STALL payload.\n");
3496                return netplay_cmd_nak(netplay, connection);
3497             }
3498             frames = ntohl(frames);
3499             if (frames > NETPLAY_MAX_REQ_STALL_TIME)
3500                frames = NETPLAY_MAX_REQ_STALL_TIME;
3501 
3502             if (netplay->is_server)
3503             {
3504                /* Only servers can request a stall! */
3505                RARCH_ERR("Netplay client requested a stall?\n");
3506                return netplay_cmd_nak(netplay, connection);
3507             }
3508 
3509             /* We can only stall for one reason at a time */
3510             if (!netplay->stall)
3511             {
3512                connection->stall = netplay->stall = NETPLAY_STALL_SERVER_REQUESTED;
3513                netplay->stall_time = 0;
3514                connection->stall_frame = frames;
3515             }
3516             break;
3517          }
3518 
3519       default:
3520          RARCH_ERR("%s.\n", msg_hash_to_str(MSG_UNKNOWN_NETPLAY_COMMAND_RECEIVED));
3521          return netplay_cmd_nak(netplay, connection);
3522    }
3523 
3524    netplay_recv_flush(&connection->recv_packet_buffer);
3525    netplay->timeout_cnt = 0;
3526    if (had_input)
3527       *had_input = true;
3528    return true;
3529 
3530 shrt:
3531    /* No more data, reset and try again */
3532    netplay_recv_reset(&connection->recv_packet_buffer);
3533    return true;
3534 
3535 #undef RECV
3536 }
3537 
3538 /**
3539  * netplay_poll_net_input
3540  *
3541  * Poll input from the network
3542  */
netplay_poll_net_input(netplay_t * netplay,bool block)3543 int netplay_poll_net_input(netplay_t *netplay, bool block)
3544 {
3545    bool had_input = false;
3546    int max_fd = 0;
3547    size_t i;
3548 
3549    for (i = 0; i < netplay->connections_size; i++)
3550    {
3551       struct netplay_connection *connection = &netplay->connections[i];
3552       if (connection->active && connection->fd >= max_fd)
3553          max_fd = connection->fd + 1;
3554    }
3555 
3556    if (max_fd == 0)
3557       return 0;
3558 
3559    netplay->timeout_cnt = 0;
3560 
3561    do
3562    {
3563       had_input = false;
3564 
3565       netplay->timeout_cnt++;
3566 
3567       /* Read input from each connection */
3568       for (i = 0; i < netplay->connections_size; i++)
3569       {
3570          struct netplay_connection *connection = &netplay->connections[i];
3571          if (connection->active && !netplay_get_cmd(netplay, connection, &had_input))
3572             netplay_hangup(netplay, connection);
3573       }
3574 
3575       if (block)
3576       {
3577          netplay_update_unread_ptr(netplay);
3578 
3579          /* If we were blocked for input, pass if we have this frame's input */
3580          if (netplay->unread_frame_count > netplay->run_frame_count)
3581             break;
3582 
3583          /* If we're supposed to block but we didn't have enough input, wait for it */
3584          if (!had_input)
3585          {
3586             fd_set fds;
3587             struct timeval tv = {0};
3588             tv.tv_usec = RETRY_MS * 1000;
3589 
3590             FD_ZERO(&fds);
3591             for (i = 0; i < netplay->connections_size; i++)
3592             {
3593                struct netplay_connection *connection = &netplay->connections[i];
3594                if (connection->active)
3595                   FD_SET(connection->fd, &fds);
3596             }
3597 
3598             if (socket_select(max_fd, &fds, NULL, NULL, &tv) < 0)
3599                return -1;
3600 
3601             RARCH_LOG("[netplay] Network is stalling at frame %u, count %u of %d ...\n",
3602                   netplay->run_frame_count, netplay->timeout_cnt, MAX_RETRIES);
3603 
3604             if (netplay->timeout_cnt >= MAX_RETRIES && !netplay->remote_paused)
3605                return -1;
3606          }
3607       }
3608    } while (had_input || block);
3609 
3610    return 0;
3611 }
3612 
3613 /**
3614  * netplay_handle_slaves
3615  *
3616  * Handle any slave connections
3617  */
netplay_handle_slaves(netplay_t * netplay)3618 void netplay_handle_slaves(netplay_t *netplay)
3619 {
3620    struct delta_frame *oframe, *frame = &netplay->buffer[netplay->self_ptr];
3621    size_t i;
3622    for (i = 0; i < netplay->connections_size; i++)
3623    {
3624       struct netplay_connection *connection = &netplay->connections[i];
3625       if (connection->active &&
3626           connection->mode == NETPLAY_CONNECTION_SLAVE)
3627       {
3628          uint32_t devices, device;
3629          uint32_t client_num = (uint32_t)(i + 1);
3630 
3631          /* This is a slave connection. First, should we do anything at all? If
3632           * we've already "read" this data, then we can just ignore it */
3633          if (netplay->read_frame_count[client_num] > netplay->self_frame_count)
3634             continue;
3635 
3636          /* Alright, we have to send something. Do we need to generate it first? */
3637          if (!frame->have_real[client_num])
3638          {
3639             devices = netplay->client_devices[client_num];
3640 
3641             /* Copy the previous frame's data */
3642             oframe = &netplay->buffer[PREV_PTR(netplay->self_ptr)];
3643             for (device = 0; device < MAX_INPUT_DEVICES; device++)
3644             {
3645                netplay_input_state_t istate_out, istate_in;
3646                if (!(devices & (1<<device)))
3647                   continue;
3648                istate_in = oframe->real_input[device];
3649                while (istate_in && istate_in->client_num != client_num)
3650                   istate_in = istate_in->next;
3651                if (!istate_in)
3652                {
3653                   /* Start with blank input */
3654                   netplay_input_state_for(&frame->real_input[device],
3655                         client_num,
3656                         netplay_expected_input_size(netplay, 1 << device), true,
3657                         false);
3658 
3659                }
3660                else
3661                {
3662                   /* Copy the previous input */
3663                   istate_out = netplay_input_state_for(&frame->real_input[device],
3664                         client_num, istate_in->size, true, false);
3665                   memcpy(istate_out->data, istate_in->data,
3666                         istate_in->size * sizeof(uint32_t));
3667                }
3668             }
3669             frame->have_real[client_num] = true;
3670          }
3671 
3672          /* Send it along */
3673          send_input_frame(netplay, frame, NULL, NULL, client_num, false);
3674 
3675          /* And mark it as "read" */
3676          netplay->read_ptr[client_num] = NEXT_PTR(netplay->self_ptr);
3677          netplay->read_frame_count[client_num] = netplay->self_frame_count + 1;
3678       }
3679    }
3680 }
3681 
3682 /**
3683  * netplay_announce_nat_traversal
3684  *
3685  * Announce successful NAT traversal.
3686  */
netplay_announce_nat_traversal(netplay_t * netplay)3687 void netplay_announce_nat_traversal(netplay_t *netplay)
3688 {
3689 #ifndef HAVE_SOCKET_LEGACY
3690    char msg[4200], host[PATH_MAX_LENGTH], port[6];
3691 
3692    if (netplay->nat_traversal_state.have_inet4)
3693    {
3694       if (getnameinfo((const struct sockaddr *) &netplay->nat_traversal_state.ext_inet4_addr,
3695                sizeof(struct sockaddr_in),
3696                host, PATH_MAX_LENGTH, port, 6, NI_NUMERICHOST|NI_NUMERICSERV) != 0)
3697          return;
3698 
3699    }
3700 #ifdef HAVE_INET6
3701    else if (netplay->nat_traversal_state.have_inet6)
3702    {
3703       if (getnameinfo((const struct sockaddr *) &netplay->nat_traversal_state.ext_inet6_addr,
3704                sizeof(struct sockaddr_in6),
3705                host, PATH_MAX_LENGTH, port, 6, NI_NUMERICHOST|NI_NUMERICSERV) != 0)
3706          return;
3707 
3708    }
3709 #endif
3710    else
3711    {
3712       snprintf(msg, sizeof(msg), "%s\n",
3713             msg_hash_to_str(MSG_UPNP_FAILED));
3714       runloop_msg_queue_push(msg, 1, 180, false, NULL, MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
3715       RARCH_LOG("[netplay] %s\n", msg);
3716       return;
3717    }
3718 
3719    snprintf(msg, sizeof(msg), "%s: %s:%s\n",
3720          msg_hash_to_str(MSG_PUBLIC_ADDRESS),
3721          host, port);
3722    runloop_msg_queue_push(msg, 1, 180, false, NULL, MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
3723    RARCH_LOG("[netplay] %s\n", msg);
3724 #endif
3725 }
3726 
3727 /**
3728  * netplay_init_nat_traversal
3729  *
3730  * Initialize the NAT traversal library and try to open a port
3731  */
netplay_init_nat_traversal(netplay_t * netplay)3732 void netplay_init_nat_traversal(netplay_t *netplay)
3733 {
3734    memset(&netplay->nat_traversal_state, 0, sizeof(netplay->nat_traversal_state));
3735    netplay->nat_traversal_task_oustanding = true;
3736    task_push_netplay_nat_traversal(&netplay->nat_traversal_state, netplay->tcp_port);
3737 }
3738 
init_tcp_connection(const struct addrinfo * res,bool server,struct sockaddr * other_addr,socklen_t addr_size)3739 static int init_tcp_connection(const struct addrinfo *res,
3740       bool server,
3741       struct sockaddr *other_addr, socklen_t addr_size)
3742 {
3743    bool ret = true;
3744    int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
3745 
3746    if (fd < 0)
3747    {
3748       ret = false;
3749       goto end;
3750    }
3751 
3752 #if defined(IPPROTO_TCP) && defined(TCP_NODELAY)
3753    {
3754       int flag = 1;
3755       if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
3756 #ifdef _WIN32
3757          (const char*)
3758 #else
3759          (const void*)
3760 #endif
3761          &flag,
3762          sizeof(int)) < 0)
3763          RARCH_WARN("Could not set netplay TCP socket to nodelay. Expect jitter.\n");
3764    }
3765 #endif
3766 
3767 #if defined(F_SETFD) && defined(FD_CLOEXEC)
3768    /* Don't let any inherited processes keep open our port */
3769    if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
3770       RARCH_WARN("Cannot set Netplay port to close-on-exec. It may fail to reopen if the client disconnects.\n");
3771 #endif
3772 
3773    if (server)
3774    {
3775       if (socket_connect(fd, (void*)res, false) < 0)
3776       {
3777          ret = false;
3778          goto end;
3779       }
3780    }
3781    else
3782    {
3783 #if defined(HAVE_INET6) && defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
3784       /* Make sure we accept connections on both IPv6 and IPv4 */
3785       int on = 0;
3786       if (res->ai_family == AF_INET6)
3787       {
3788          if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) < 0)
3789             RARCH_WARN("Failed to listen on both IPv6 and IPv4\n");
3790       }
3791 #endif
3792       if (  !socket_bind(fd, (void*)res) ||
3793             listen(fd, 1024) < 0)
3794       {
3795          ret = false;
3796          goto end;
3797       }
3798    }
3799 
3800 end:
3801    if (!ret && fd >= 0)
3802    {
3803       socket_close(fd);
3804       fd = -1;
3805    }
3806 
3807    return fd;
3808 }
3809 
init_tcp_socket(netplay_t * netplay,void * direct_host,const char * server,uint16_t port)3810 static bool init_tcp_socket(netplay_t *netplay, void *direct_host,
3811       const char *server, uint16_t port)
3812 {
3813    char port_buf[16];
3814    bool ret                        = false;
3815    const struct addrinfo *tmp_info = NULL;
3816    struct addrinfo *res            = NULL;
3817    struct addrinfo hints           = {0};
3818 
3819    port_buf[0] = '\0';
3820 
3821    if (!direct_host)
3822    {
3823 #ifdef HAVE_INET6
3824       /* Default to hosting on IPv6 and IPv4 */
3825       if (!server)
3826          hints.ai_family = AF_INET6;
3827 #endif
3828       hints.ai_socktype = SOCK_STREAM;
3829       if (!server)
3830          hints.ai_flags = AI_PASSIVE;
3831 
3832       snprintf(port_buf, sizeof(port_buf), "%hu", (unsigned short)port);
3833       if (getaddrinfo_retro(server, port_buf, &hints, &res) != 0)
3834       {
3835 #ifdef HAVE_INET6
3836       try_wildcard:
3837          if (!server)
3838          {
3839             /* Didn't work with IPv6, try wildcard */
3840             hints.ai_family = 0;
3841             if (getaddrinfo_retro(server, port_buf, &hints, &res) != 0)
3842                return false;
3843          }
3844          else
3845 #endif
3846          return false;
3847       }
3848 
3849       if (!res)
3850          return false;
3851 
3852    }
3853    else
3854    {
3855       /* I'll build my own addrinfo! */
3856       struct netplay_host *host = (struct netplay_host *)direct_host;
3857       hints.ai_family           = host->addr.sa_family;
3858       hints.ai_socktype         = SOCK_STREAM;
3859       hints.ai_protocol         = 0;
3860       hints.ai_addrlen          = host->addrlen;
3861       hints.ai_addr             = &host->addr;
3862       res                       = &hints;
3863 
3864    }
3865 
3866    /* If we're serving on IPv6, make sure we accept all connections, including
3867     * IPv4 */
3868 #ifdef HAVE_INET6
3869    if (!direct_host && !server && res->ai_family == AF_INET6)
3870    {
3871       struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) res->ai_addr;
3872 #if defined(_MSC_VER) && _MSC_VER <= 1200
3873 	  IN6ADDR_SETANY(sin6);
3874 #else
3875       sin6->sin6_addr           = in6addr_any;
3876 #endif
3877    }
3878 #endif
3879 
3880    /* If "localhost" is used, it is important to check every possible
3881     * address for IPv4/IPv6. */
3882    tmp_info = res;
3883 
3884    while (tmp_info)
3885    {
3886       struct sockaddr_storage sad = {0};
3887       int fd = init_tcp_connection(
3888             tmp_info,
3889             direct_host || server,
3890             (struct sockaddr*)&sad,
3891             sizeof(sad));
3892 
3893       if (fd >= 0)
3894       {
3895          ret = true;
3896          if (direct_host || server)
3897          {
3898             netplay->connections[0].active = true;
3899             netplay->connections[0].fd     = fd;
3900             netplay->connections[0].addr   = sad;
3901          }
3902          else
3903          {
3904             netplay->listen_fd = fd;
3905          }
3906          break;
3907       }
3908 
3909       tmp_info = tmp_info->ai_next;
3910    }
3911 
3912    if (res && !direct_host)
3913       freeaddrinfo_retro(res);
3914 
3915    if (!ret)
3916    {
3917 #ifdef HAVE_INET6
3918       if (!direct_host && (hints.ai_family == AF_INET6))
3919          goto try_wildcard;
3920 #endif
3921       RARCH_ERR("Failed to set up netplay sockets.\n");
3922    }
3923 
3924    return ret;
3925 }
3926 
init_socket(netplay_t * netplay,void * direct_host,const char * server,uint16_t port)3927 static bool init_socket(netplay_t *netplay, void *direct_host,
3928       const char *server, uint16_t port)
3929 {
3930    if (!network_init())
3931       return false;
3932 
3933    if (!init_tcp_socket(netplay, direct_host, server, port))
3934       return false;
3935 
3936    if (netplay->is_server && netplay->nat_traversal)
3937       netplay_init_nat_traversal(netplay);
3938 
3939    return true;
3940 }
3941 
netplay_init_socket_buffers(netplay_t * netplay)3942 static bool netplay_init_socket_buffers(netplay_t *netplay)
3943 {
3944    /* Make our packet buffer big enough for a save state and stall-frames-many
3945     * frames of input data, plus the headers for each of them */
3946    size_t i;
3947    size_t packet_buffer_size = netplay->zbuffer_size +
3948       NETPLAY_MAX_STALL_FRAMES * 16;
3949    netplay->packet_buffer_size = packet_buffer_size;
3950 
3951    for (i = 0; i < netplay->connections_size; i++)
3952    {
3953       struct netplay_connection *connection = &netplay->connections[i];
3954       if (connection->active)
3955       {
3956          if (connection->send_packet_buffer.data)
3957          {
3958             if (!netplay_resize_socket_buffer(&connection->send_packet_buffer,
3959                   packet_buffer_size) ||
3960                 !netplay_resize_socket_buffer(&connection->recv_packet_buffer,
3961                   packet_buffer_size))
3962                return false;
3963          }
3964          else
3965          {
3966             if (!netplay_init_socket_buffer(&connection->send_packet_buffer,
3967                   packet_buffer_size) ||
3968                 !netplay_init_socket_buffer(&connection->recv_packet_buffer,
3969                   packet_buffer_size))
3970                return false;
3971          }
3972       }
3973    }
3974 
3975    return true;
3976 }
3977 
netplay_init_serialization(netplay_t * netplay)3978 static bool netplay_init_serialization(netplay_t *netplay)
3979 {
3980    unsigned i;
3981    retro_ctx_size_info_t info;
3982 
3983    if (netplay->state_size)
3984       return true;
3985 
3986    core_serialize_size(&info);
3987 
3988    if (!info.size)
3989       return false;
3990 
3991    netplay->state_size = info.size;
3992 
3993    for (i = 0; i < netplay->buffer_size; i++)
3994    {
3995       netplay->buffer[i].state = calloc(netplay->state_size, 1);
3996 
3997       if (!netplay->buffer[i].state)
3998       {
3999          netplay->quirks |= NETPLAY_QUIRK_NO_SAVESTATES;
4000          return false;
4001       }
4002    }
4003 
4004    netplay->zbuffer_size = netplay->state_size * 2;
4005    netplay->zbuffer = (uint8_t *) calloc(netplay->zbuffer_size, 1);
4006    if (!netplay->zbuffer)
4007    {
4008       netplay->quirks |= NETPLAY_QUIRK_NO_TRANSMISSION;
4009       netplay->zbuffer_size = 0;
4010       return false;
4011    }
4012 
4013    return true;
4014 }
4015 
4016 /**
4017  * netplay_try_init_serialization
4018  *
4019  * Try to initialize serialization. For quirky cores.
4020  *
4021  * Returns true if serialization is now ready, false otherwise.
4022  */
netplay_try_init_serialization(netplay_t * netplay)4023 bool netplay_try_init_serialization(netplay_t *netplay)
4024 {
4025    retro_ctx_serialize_info_t serial_info;
4026 
4027    if (netplay->state_size)
4028       return true;
4029 
4030    if (!netplay_init_serialization(netplay))
4031       return false;
4032 
4033    /* Check if we can actually save */
4034    serial_info.data_const = NULL;
4035    serial_info.data       = netplay->buffer[netplay->run_ptr].state;
4036    serial_info.size       = netplay->state_size;
4037 
4038    if (!core_serialize(&serial_info))
4039       return false;
4040 
4041    /* Once initialized, we no longer exhibit this quirk */
4042    netplay->quirks &= ~((uint64_t) NETPLAY_QUIRK_INITIALIZATION);
4043 
4044    return netplay_init_socket_buffers(netplay);
4045 }
4046 
4047 /**
4048  * netplay_wait_and_init_serialization
4049  *
4050  * Try very hard to initialize serialization, simulating multiple frames if
4051  * necessary. For quirky cores.
4052  *
4053  * Returns true if serialization is now ready, false otherwise.
4054  */
netplay_wait_and_init_serialization(netplay_t * netplay)4055 bool netplay_wait_and_init_serialization(netplay_t *netplay)
4056 {
4057    int frame;
4058 
4059    if (netplay->state_size)
4060       return true;
4061 
4062    /* Wait a maximum of 60 frames */
4063    for (frame = 0; frame < 60; frame++)
4064    {
4065       if (netplay_try_init_serialization(netplay))
4066          return true;
4067 
4068 #if defined(HAVE_THREADS)
4069       autosave_lock();
4070 #endif
4071       core_run();
4072 #if defined(HAVE_THREADS)
4073       autosave_unlock();
4074 #endif
4075    }
4076 
4077    return false;
4078 }
4079 
netplay_init_buffers(netplay_t * netplay)4080 static bool netplay_init_buffers(netplay_t *netplay)
4081 {
4082    struct delta_frame *delta_frames = NULL;
4083 
4084    /* Enough to get ahead or behind by MAX_STALL_FRAMES frames, plus one for
4085     * other remote clients, plus one to send the stall message */
4086    netplay->buffer_size = NETPLAY_MAX_STALL_FRAMES + 2;
4087 
4088    /* If we're the server, we need enough to get ahead AND behind by
4089     * MAX_STALL_FRAMES frame */
4090    if (netplay->is_server)
4091       netplay->buffer_size *= 2;
4092 
4093    delta_frames = (struct delta_frame*)calloc(netplay->buffer_size,
4094          sizeof(*delta_frames));
4095 
4096    if (!delta_frames)
4097       return false;
4098 
4099    netplay->buffer = delta_frames;
4100 
4101    if (!(netplay->quirks & (NETPLAY_QUIRK_NO_SAVESTATES|NETPLAY_QUIRK_INITIALIZATION)))
4102       netplay_init_serialization(netplay);
4103 
4104    return netplay_init_socket_buffers(netplay);
4105 }
4106 
4107 /**
4108  * netplay_new:
4109  * @direct_host          : Netplay host discovered from scanning.
4110  * @server               : IP address of server.
4111  * @port                 : Port of server.
4112  * @stateless_mode       : Shall we use stateless mode?
4113  * @check_frames         : Frequency with which to check CRCs.
4114  * @cb                   : Libretro callbacks.
4115  * @nat_traversal        : If true, attempt NAT traversal.
4116  * @nick                 : Nickname of user.
4117  * @quirks               : Netplay quirks required for this session.
4118  *
4119  * Creates a new netplay handle. A NULL server means we're
4120  * hosting.
4121  *
4122  * Returns: new netplay data.
4123  */
netplay_new(void * direct_host,const char * server,uint16_t port,bool stateless_mode,int check_frames,const struct retro_callbacks * cb,bool nat_traversal,const char * nick,uint64_t quirks)4124 netplay_t *netplay_new(void *direct_host, const char *server, uint16_t port,
4125    bool stateless_mode, int check_frames,
4126    const struct retro_callbacks *cb, bool nat_traversal, const char *nick,
4127    uint64_t quirks)
4128 {
4129    netplay_t *netplay = (netplay_t*)calloc(1, sizeof(*netplay));
4130    if (!netplay)
4131       return NULL;
4132 
4133    netplay->listen_fd            = -1;
4134    netplay->tcp_port             = port;
4135    netplay->cbs                  = *cb;
4136    netplay->is_server            = (direct_host == NULL && server == NULL);
4137    netplay->is_connected         = false;
4138    netplay->nat_traversal        = netplay->is_server ? nat_traversal : false;
4139    netplay->stateless_mode       = stateless_mode;
4140    netplay->check_frames         = check_frames;
4141    netplay->crc_validity_checked = false;
4142    netplay->crcs_valid           = true;
4143    netplay->quirks               = quirks;
4144    netplay->self_mode            = netplay->is_server ?
4145                                 NETPLAY_CONNECTION_SPECTATING :
4146                                 NETPLAY_CONNECTION_NONE;
4147 
4148    if (netplay->is_server)
4149    {
4150       netplay->connections       = NULL;
4151       netplay->connections_size  = 0;
4152    }
4153    else
4154    {
4155       netplay->connections       = &netplay->one_connection;
4156       netplay->connections_size  = 1;
4157       netplay->connections[0].fd = -1;
4158    }
4159 
4160    strlcpy(netplay->nick, nick[0]
4161          ? nick : RARCH_DEFAULT_NICK,
4162          sizeof(netplay->nick));
4163 
4164    if (!init_socket(netplay, direct_host, server, port))
4165    {
4166       free(netplay);
4167       return NULL;
4168    }
4169 
4170    if (!netplay_init_buffers(netplay))
4171    {
4172       free(netplay);
4173       return NULL;
4174    }
4175 
4176    if (netplay->is_server)
4177    {
4178       /* Clients get device info from the server */
4179       unsigned i;
4180       for (i = 0; i < MAX_INPUT_DEVICES; i++)
4181       {
4182          uint32_t dtype = input_config_get_device(i);
4183          netplay->config_devices[i] = dtype;
4184          if ((dtype&RETRO_DEVICE_MASK) == RETRO_DEVICE_KEYBOARD)
4185          {
4186             netplay->have_updown_device = true;
4187             netplay_key_hton_init();
4188          }
4189          if (dtype != RETRO_DEVICE_NONE && !netplay_expected_input_size(netplay, 1<<i))
4190             RARCH_WARN("Netplay does not support input device %u\n", i+1);
4191       }
4192    }
4193    else
4194    {
4195       /* Start our handshake */
4196       netplay_handshake_init_send(netplay, &netplay->connections[0]);
4197 
4198       netplay->connections[0].mode = NETPLAY_CONNECTION_INIT;
4199       netplay->self_mode           = NETPLAY_CONNECTION_INIT;
4200    }
4201 
4202    /* FIXME: Not really the right place to do this,
4203     * socket initialization needs to be fixed in general. */
4204    if (netplay->is_server)
4205    {
4206       if (!socket_nonblock(netplay->listen_fd))
4207          goto error;
4208    }
4209    else
4210    {
4211       if (!socket_nonblock(netplay->connections[0].fd))
4212          goto error;
4213    }
4214 
4215    return netplay;
4216 
4217 error:
4218    if (netplay->listen_fd >= 0)
4219       socket_close(netplay->listen_fd);
4220 
4221    if (netplay->connections && netplay->connections[0].fd >= 0)
4222       socket_close(netplay->connections[0].fd);
4223 
4224    free(netplay);
4225    return NULL;
4226 }
4227 
4228 /**
4229  * netplay_free
4230  * @netplay              : pointer to netplay object
4231  *
4232  * Frees netplay data/
4233  */
netplay_free(netplay_t * netplay)4234 void netplay_free(netplay_t *netplay)
4235 {
4236    size_t i;
4237 
4238    if (netplay->listen_fd >= 0)
4239       socket_close(netplay->listen_fd);
4240 
4241    for (i = 0; i < netplay->connections_size; i++)
4242    {
4243       struct netplay_connection *connection = &netplay->connections[i];
4244       if (connection->active)
4245       {
4246          socket_close(connection->fd);
4247          netplay_deinit_socket_buffer(&connection->send_packet_buffer);
4248          netplay_deinit_socket_buffer(&connection->recv_packet_buffer);
4249       }
4250    }
4251 
4252    if (netplay->connections && netplay->connections != &netplay->one_connection)
4253       free(netplay->connections);
4254 
4255    if (netplay->nat_traversal)
4256       natt_free(&netplay->nat_traversal_state);
4257 
4258    if (netplay->buffer)
4259    {
4260       for (i = 0; i < netplay->buffer_size; i++)
4261          netplay_delta_frame_free(&netplay->buffer[i]);
4262 
4263       free(netplay->buffer);
4264    }
4265 
4266    if (netplay->zbuffer)
4267       free(netplay->zbuffer);
4268 
4269    if (netplay->compress_nil.compression_stream)
4270    {
4271       netplay->compress_nil.compression_backend->stream_free(netplay->compress_nil.compression_stream);
4272       netplay->compress_nil.decompression_backend->stream_free(netplay->compress_nil.decompression_stream);
4273    }
4274    if (netplay->compress_zlib.compression_stream)
4275    {
4276       netplay->compress_zlib.compression_backend->stream_free(netplay->compress_zlib.compression_stream);
4277       netplay->compress_zlib.decompression_backend->stream_free(netplay->compress_zlib.decompression_stream);
4278    }
4279 
4280    if (netplay->addr)
4281       freeaddrinfo_retro(netplay->addr);
4282 
4283    free(netplay);
4284 }
4285