1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
7 // https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
10 // ============================================================================
17 #include "libgame/libgame.h"
23 static int num_clients = 0;
24 static boolean run_server_only_once = FALSE;
26 struct NetworkServerPlayerInfo
29 char player_name[MAX_PLAYER_NAME_LEN + 1];
34 boolean action_received;
36 struct NetworkServerPlayerInfo *next;
39 static struct NetworkServerPlayerInfo *first_player = NULL;
41 #define NEXT(player) ((player)->next ? (player)->next : first_player)
44 static TCPsocket lfd; // listening TCP socket
45 static UDPsocket udp; // listening UDP socket
46 static SDLNet_SocketSet fds; // socket set
48 static struct NetworkBuffer *read_buffer = NULL;
49 static struct NetworkBuffer *write_buffer = NULL;
51 static unsigned int ServerFrameCounter = 0;
54 int getNetwork8BitInteger(byte *ptr)
59 int putNetwork8BitInteger(byte *ptr, int value)
66 int getNetwork16BitInteger(byte *ptr)
68 return ((ptr[0] << 8) |
72 int putNetwork16BitInteger(byte *ptr, int value)
74 ptr[0] = (value >> 8) & 0xff;
75 ptr[1] = (value >> 0) & 0xff;
80 int getNetwork32BitInteger(byte *ptr)
82 return ((ptr[0] << 24) |
88 int putNetwork32BitInteger(byte *ptr, int value)
90 ptr[0] = (value >> 24) & 0xff;
91 ptr[1] = (value >> 16) & 0xff;
92 ptr[2] = (value >> 8) & 0xff;
93 ptr[3] = (value >> 0) & 0xff;
98 char *getNetworkString(byte *ptr)
103 int putNetworkString(byte *ptr, char *s)
105 strcpy((char *)ptr, s);
107 return strlen(s) + 1;
110 struct NetworkBuffer *newNetworkBuffer(void)
112 struct NetworkBuffer *new = checked_calloc(sizeof(struct NetworkBuffer));
114 new->max_size = MAX_BUFFER_SIZE;
118 new->buffer = checked_calloc(new->max_size);
123 static void resetNetworkBufferForReading(struct NetworkBuffer *nb)
128 static void resetNetworkBufferForWriting(struct NetworkBuffer *nb)
134 void initNetworkBufferForReceiving(struct NetworkBuffer *nb)
136 resetNetworkBufferForWriting(nb);
139 void initNetworkBufferForReading(struct NetworkBuffer *nb)
141 resetNetworkBufferForReading(nb);
143 // skip message length header
144 getNetworkBuffer32BitInteger(nb);
147 void initNetworkBufferForWriting(struct NetworkBuffer *nb, int message_type,
150 resetNetworkBufferForWriting(nb);
152 // will be replaced with message length before sending
153 putNetworkBuffer32BitInteger(nb, 0);
155 putNetworkBuffer8BitInteger(nb, message_type);
156 putNetworkBuffer8BitInteger(nb, player_nr);
159 static void copyNetworkBufferForWriting(struct NetworkBuffer *nb_from,
160 struct NetworkBuffer *nb_to,
163 initNetworkBufferForReading(nb_from);
165 int message_type = getNetworkBuffer8BitInteger(nb_from);
167 // skip player number
168 getNetworkBuffer8BitInteger(nb_from);
170 initNetworkBufferForWriting(nb_to, message_type, player_nr);
172 while (nb_from->pos < nb_from->size)
174 int b = getNetworkBuffer8BitInteger(nb_from);
176 putNetworkBuffer8BitInteger(nb_to, b);
180 static void increaseNetworkBuffer(struct NetworkBuffer *nb, int additional_size)
182 // add some more buffer size than is really required this time
183 nb->max_size += additional_size + MAX_BUFFER_SIZE;
184 nb->buffer = checked_realloc(nb->buffer, nb->max_size);
187 int receiveNetworkBufferBytes(struct NetworkBuffer *nb, TCPsocket socket,
190 if (num_bytes > MAX_PACKET_SIZE)
192 Debug("network:server", "protocol error: invalid packet size %d",
198 if (nb->pos + num_bytes > nb->max_size)
199 increaseNetworkBuffer(nb, num_bytes);
201 int result = SDLNet_TCP_Recv(socket, &nb->buffer[nb->pos], num_bytes);
203 if (result != num_bytes)
206 nb->pos += num_bytes;
212 int receiveNetworkBufferPacket(struct NetworkBuffer *nb, TCPsocket socket)
214 int num_bytes, num_bytes_head, num_bytes_body;
217 num_bytes = receiveNetworkBufferBytes(nb, socket, num_bytes_head);
219 if (num_bytes != num_bytes_head)
222 num_bytes_body = getNetwork32BitInteger(nb->buffer);
223 num_bytes = receiveNetworkBufferBytes(nb, socket, num_bytes_body);
228 int getNetworkBuffer8BitInteger(struct NetworkBuffer *nb)
232 if (nb->pos + num_bytes > nb->size)
235 int value = getNetwork8BitInteger(&nb->buffer[nb->pos]);
237 nb->pos += num_bytes;
242 void putNetworkBuffer8BitInteger(struct NetworkBuffer *nb, int value)
246 if (nb->pos + num_bytes > nb->max_size)
247 increaseNetworkBuffer(nb, num_bytes);
249 nb->pos += putNetwork8BitInteger(&nb->buffer[nb->pos], value);
253 int getNetworkBuffer16BitInteger(struct NetworkBuffer *nb)
257 if (nb->pos + num_bytes > nb->size)
260 int value = getNetwork16BitInteger(&nb->buffer[nb->pos]);
262 nb->pos += num_bytes;
267 void putNetworkBuffer16BitInteger(struct NetworkBuffer *nb, int value)
271 if (nb->pos + num_bytes > nb->max_size)
272 increaseNetworkBuffer(nb, num_bytes);
274 nb->pos += putNetwork16BitInteger(&nb->buffer[nb->pos], value);
278 int getNetworkBuffer32BitInteger(struct NetworkBuffer *nb)
282 if (nb->pos + num_bytes > nb->size)
285 int value = getNetwork32BitInteger(&nb->buffer[nb->pos]);
287 nb->pos += num_bytes;
292 void putNetworkBuffer32BitInteger(struct NetworkBuffer *nb, int value)
296 if (nb->pos + num_bytes > nb->max_size)
297 increaseNetworkBuffer(nb, num_bytes);
299 nb->pos += putNetwork32BitInteger(&nb->buffer[nb->pos], value);
303 char *getNetworkBufferString(struct NetworkBuffer *nb)
305 char *s = getNetworkString(&nb->buffer[nb->pos]);
307 nb->pos += strlen(s) + 1;
312 void putNetworkBufferString(struct NetworkBuffer *nb, char *s)
314 int num_bytes = strlen(s) + 1;
316 if (nb->pos + num_bytes > nb->max_size)
317 increaseNetworkBuffer(nb, num_bytes);
319 nb->pos += putNetworkString(&nb->buffer[nb->pos], s);
323 int getNetworkBufferFile(struct NetworkBuffer *nb, char *filename)
326 int num_bytes = getNetworkBuffer32BitInteger(nb);
329 if (!(file = fopen(filename, MODE_WRITE)))
331 Warn("cannot write file '%s' from network buffer", filename);
336 for (i = 0; i < num_bytes; i++)
338 int b = getNetworkBuffer8BitInteger(nb);
340 putFile8Bit(file, b);
348 int putNetworkBufferFile(struct NetworkBuffer *nb, char *filename)
351 int filesize_pos = nb->pos;
354 // will be replaced with file size
355 putNetworkBuffer32BitInteger(nb, 0);
357 if (!(file = openFile(filename, MODE_READ)))
359 Warn("cannot read file '%s' to network buffer", filename);
366 int b = getFile8Bit(file);
368 if (checkEndOfFile(file))
371 putNetworkBuffer8BitInteger(nb, b);
379 putNetwork32BitInteger(&nb->buffer[filesize_pos], num_bytes);
384 void dumpNetworkBuffer(struct NetworkBuffer *nb)
388 Debug("network:buffer", "network buffer maximum size: %d\n", nb->max_size);
389 Debug("network:buffer", "network buffer size: %d\n", nb->size);
390 Debug("network:buffer", "network buffer position : %d\n", nb->pos);
392 for (i = 0; i < nb->size; i++)
395 DebugContinued("network:buffer", "\n");
397 DebugContinued("", "%02x ", nb->buffer[i]);
400 DebugContinued("network:buffer", "\n");
403 static void SendNetworkBufferToAllButOne(struct NetworkBuffer *nb,
404 struct NetworkServerPlayerInfo *except)
406 struct NetworkServerPlayerInfo *player;
408 // set message length header
409 putNetwork32BitInteger(nb->buffer, nb->size - 4);
411 for (player = first_player; player != NULL; player = player->next)
413 if (player != except && player->introduced)
415 // directly send the buffer to the network client
416 SDLNet_TCP_Send(player->fd, nb->buffer, nb->size);
421 static void SendNetworkBufferToAll(struct NetworkBuffer *nb)
423 SendNetworkBufferToAllButOne(nb, NULL);
426 static void SendNetworkBufferToClient(struct NetworkBuffer *nb,
427 struct NetworkServerPlayerInfo *player)
429 // set message length header
430 putNetwork32BitInteger(nb->buffer, nb->size - 4);
432 // directly send the buffer to the network client
433 SDLNet_TCP_Send(player->fd, nb->buffer, nb->size);
436 static void RemovePlayer(struct NetworkServerPlayerInfo *player)
438 Debug("network:server", "dropping client %d (%s)",
439 player->number, player->player_name);
441 SDLNet_TCP_DelSocket(fds, player->fd);
442 SDLNet_TCP_Close(player->fd);
444 if (player == first_player)
446 first_player = player->next;
450 struct NetworkServerPlayerInfo *p;
452 for (p = first_player; p != NULL; p = p->next)
454 if (p->next && p->next == player)
456 p->next = player->next;
463 if (player->introduced)
465 initNetworkBufferForWriting(write_buffer, OP_PLAYER_DISCONNECTED,
468 SendNetworkBufferToAllButOne(write_buffer, player);
474 #if 0 // do not terminate network server if last player disconnected
475 if (run_server_only_once && num_clients == 0)
477 Debug("network:server", "no clients left");
478 Debug("network:server", "aborting");
485 static void AddPlayer(TCPsocket fd)
487 struct NetworkServerPlayerInfo *player, *p;
489 boolean again = TRUE;
491 SDLNet_TCP_AddSocket(fds, fd);
493 player = checked_calloc(sizeof(struct NetworkServerPlayerInfo));
496 player->player_name[0] = 0;
497 player->active = FALSE;
498 player->introduced = FALSE;
500 player->action_received = FALSE;
501 player->next = first_player;
503 first_player = player;
512 if (p->number == number)
525 player->number = number;
528 initNetworkBufferForWriting(write_buffer, OP_YOUR_NUMBER, 0);
530 putNetworkBuffer8BitInteger(write_buffer, player->number);
532 SendNetworkBufferToClient(write_buffer, player);
535 static void Handle_OP_PROTOCOL_VERSION(struct NetworkServerPlayerInfo *player)
537 int protocol_version_major = getNetworkBuffer8BitInteger(read_buffer);
538 int protocol_version_minor = getNetworkBuffer8BitInteger(read_buffer);
539 int protocol_version_patch = getNetworkBuffer8BitInteger(read_buffer);
541 if (protocol_version_major != PROTOCOL_VERSION_MAJOR ||
542 protocol_version_minor != PROTOCOL_VERSION_MINOR)
544 Debug("network:server",
545 "client %d (%s) has wrong protocol version %d.%d.%d",
546 player->number, player->player_name,
547 protocol_version_major,
548 protocol_version_minor,
549 protocol_version_patch);
551 initNetworkBufferForWriting(write_buffer, OP_BAD_PROTOCOL_VERSION, 0);
553 putNetworkBuffer8BitInteger(write_buffer, PROTOCOL_VERSION_MAJOR);
554 putNetworkBuffer8BitInteger(write_buffer, PROTOCOL_VERSION_MINOR);
555 putNetworkBuffer8BitInteger(write_buffer, PROTOCOL_VERSION_PATCH);
557 SendNetworkBufferToClient(write_buffer, player);
559 RemovePlayer(player);
563 Debug("network:server",
564 "client %d (%s) uses protocol version %d.%d.%d",
565 player->number, player->player_name,
566 protocol_version_major,
567 protocol_version_minor,
568 protocol_version_patch);
572 static void Handle_OP_NUMBER_WANTED(struct NetworkServerPlayerInfo *player)
574 int nr_wanted = getNetworkBuffer8BitInteger(read_buffer);
575 int client_nr = player->number;
576 boolean nr_is_free = TRUE;
577 struct NetworkServerPlayerInfo *p;
579 Debug("network:server", "client %d (%s) wants to switch to # %d",
580 player->number, player->player_name, nr_wanted);
582 for (p = first_player; p != NULL; p = p->next)
584 if (p->number == nr_wanted)
593 Debug("network:server", "client %d (%s) switches to # %d",
594 player->number, player->player_name, nr_wanted);
595 else if (player->number == nr_wanted)
596 Debug("network:server", "client %d (%s) already has # %d",
597 player->number, player->player_name, nr_wanted);
599 Debug("network:server",
600 "client %d (%s) cannot switch (client %d already exists)",
601 player->number, player->player_name, nr_wanted);
604 player->number = nr_wanted;
606 initNetworkBufferForWriting(write_buffer, OP_NUMBER_WANTED, client_nr);
608 putNetworkBuffer8BitInteger(write_buffer, nr_wanted);
609 putNetworkBuffer8BitInteger(write_buffer, player->number);
611 SendNetworkBufferToAll(write_buffer);
614 static void Handle_OP_PLAYER_NAME(struct NetworkServerPlayerInfo *player)
616 char *player_name = getNetworkBufferString(read_buffer);
619 strncpy(player->player_name, player_name, MAX_PLAYER_NAME_LEN);
620 player->player_name[MAX_PLAYER_NAME_LEN] = '\0';
622 for (i = 0; i < MAX_PLAYER_NAME_LEN; i++)
624 if (player->player_name[i] < ' ' ||
625 ((unsigned char)(player->player_name[i]) > 0x7e &&
626 (unsigned char)(player->player_name[i]) <= 0xa0))
628 player->player_name[i] = 0;
634 if (!player->introduced)
636 initNetworkBufferForWriting(write_buffer, OP_PLAYER_CONNECTED,
639 SendNetworkBufferToAllButOne(write_buffer, player);
642 Debug("network:server", "client %d calls itself \"%s\"",
643 player->number, player->player_name);
645 copyNetworkBufferForWriting(read_buffer, write_buffer, player->number);
647 SendNetworkBufferToAllButOne(write_buffer, player);
649 if (!player->introduced)
651 struct NetworkServerPlayerInfo *p;
653 for (p = first_player; p != NULL; p = p->next)
655 if (p != player && p->introduced)
657 initNetworkBufferForWriting(write_buffer, OP_PLAYER_CONNECTED,
660 SendNetworkBufferToClient(write_buffer, player);
662 initNetworkBufferForWriting(write_buffer, OP_PLAYER_NAME, p->number);
664 putNetworkBufferString(write_buffer, p->player_name);
666 SendNetworkBufferToClient(write_buffer, player);
671 player->introduced = TRUE;
674 static void Handle_OP_START_PLAYING(struct NetworkServerPlayerInfo *player)
676 char *new_leveldir_identifier = getNetworkBufferString(read_buffer);
677 int level_nr = getNetworkBuffer16BitInteger(read_buffer);
679 Debug("network:server",
680 "client %d (%s) starts game [level %d from level set '%s']",
681 player->number, player->player_name, level_nr,
682 new_leveldir_identifier);
684 struct NetworkServerPlayerInfo *p;
686 // reset frame counter
687 ServerFrameCounter = 0;
689 Debug("network:server", "resetting ServerFrameCounter to 0");
691 // reset player actions
692 for (p = first_player; p != NULL; p = p->next)
695 p->action_received = FALSE;
701 copyNetworkBufferForWriting(read_buffer, write_buffer, player->number);
703 SendNetworkBufferToAll(write_buffer);
706 static void Handle_OP_PAUSE_PLAYING(struct NetworkServerPlayerInfo *player)
708 Debug("network:server", "client %d (%s) pauses game",
709 player->number, player->player_name);
711 copyNetworkBufferForWriting(read_buffer, write_buffer, player->number);
713 SendNetworkBufferToAll(write_buffer);
716 static void Handle_OP_CONTINUE_PLAYING(struct NetworkServerPlayerInfo *player)
718 Debug("network:server", "client %d (%s) continues game",
719 player->number, player->player_name);
721 copyNetworkBufferForWriting(read_buffer, write_buffer, player->number);
723 SendNetworkBufferToAll(write_buffer);
726 static void Handle_OP_STOP_PLAYING(struct NetworkServerPlayerInfo *player)
728 int cause_for_stopping = getNetworkBuffer8BitInteger(read_buffer);
730 Debug("network:server", "client %d (%s) stops game [%d]",
731 player->number, player->player_name, cause_for_stopping);
733 copyNetworkBufferForWriting(read_buffer, write_buffer, player->number);
735 SendNetworkBufferToAll(write_buffer);
738 static void Handle_OP_MOVE_PLAYER(struct NetworkServerPlayerInfo *player)
740 int player_action = getNetworkBuffer8BitInteger(read_buffer);
741 int last_client_nr = 0;
742 struct NetworkServerPlayerInfo *p;
745 // store player action
746 for (p = first_player; p != NULL; p = p->next)
748 if (p->number == player->number)
750 p->action = player_action;
751 p->action_received = TRUE;
755 // check if server received action from each player
756 for (p = first_player; p != NULL; p = p->next)
758 if (!p->action_received)
761 if (p->number > last_client_nr)
762 last_client_nr = p->number;
765 int player_action_all[last_client_nr];
767 // initialize all player actions to zero
768 for (i = 0; i < last_client_nr; i++)
769 player_action_all[i] = 0;
771 // broadcast actions of all players to all players
772 for (p = first_player; p != NULL; p = p->next)
774 player_action_all[p->number - 1] = p->action;
777 p->action_received = FALSE;
780 initNetworkBufferForWriting(write_buffer, OP_MOVE_PLAYER, player->number);
782 putNetworkBuffer32BitInteger(write_buffer, ServerFrameCounter);
784 for (i = 0; i < last_client_nr; i++)
785 putNetworkBuffer8BitInteger(write_buffer, player_action_all[i]);
787 SendNetworkBufferToAll(write_buffer);
789 ServerFrameCounter++;
792 static void Handle_OP_BROADCAST_MESSAGE(struct NetworkServerPlayerInfo *player)
794 char *message = getNetworkBufferString(read_buffer);
796 Debug("network:server", "client %d (%s) sends message: %s",
797 player->number, player->player_name, message);
799 copyNetworkBufferForWriting(read_buffer, write_buffer, player->number);
801 SendNetworkBufferToAllButOne(write_buffer, player);
804 static void Handle_OP_LEVEL_FILE(struct NetworkServerPlayerInfo *player)
806 copyNetworkBufferForWriting(read_buffer, write_buffer, player->number);
808 SendNetworkBufferToAllButOne(write_buffer, player);
811 static void ExitNetworkServer(int exit_value)
813 Debug("network:server", "exiting network server");
818 // the following is not used for a standalone server;
819 // the pointer points to an integer containing the port-number
820 int NetworkServerThread(void *ptr)
822 network.is_server_thread = TRUE;
824 NetworkServer(*((int *) ptr), 0);
826 // should never be reached
830 void NetworkServer(int port, int serveronly)
832 struct NetworkServerPlayerInfo *player;
835 #if defined(PLATFORM_UNIX) && !defined(PLATFORM_NEXT)
836 struct sigaction sact;
839 if (read_buffer == NULL)
840 read_buffer = newNetworkBuffer();
842 if (write_buffer == NULL)
843 write_buffer = newNetworkBuffer();
846 port = DEFAULT_SERVER_PORT;
848 // if only running the network server, exit on Ctrl-C
850 signal(SIGINT, ExitNetworkServer);
853 run_server_only_once = TRUE;
855 #if defined(PLATFORM_UNIX)
856 #if defined(PLATFORM_NEXT)
857 signal(SIGPIPE, SIG_IGN);
859 sact.sa_handler = SIG_IGN;
860 sigemptyset(&sact.sa_mask);
862 sigaction(SIGPIPE, &sact, NULL);
866 if (SDLNet_ResolveHost(&ip, NULL, port) == -1)
867 Fail("SDLNet_ResolveHost() failed: %s", SDLNet_GetError());
869 if ((fds = SDLNet_AllocSocketSet(MAX_PLAYERS + 1 + 1)) == NULL)
870 Fail("SDLNet_AllocSocketSet() failed: %s"), SDLNet_GetError();
872 if ((lfd = SDLNet_TCP_Open(&ip)) == NULL)
873 Fail("SDLNet_TCP_Open() failed: %s"), SDLNet_GetError();
875 if (SDLNet_TCP_AddSocket(fds, lfd) == -1)
876 Fail("SDLNet_TCP_AddSocket() failed: %s"), SDLNet_GetError();
878 if ((udp = SDLNet_UDP_Open(port)) == NULL)
879 Fail("SDLNet_UDP_Open() failed: %s", SDLNet_GetError());
881 if (SDLNet_UDP_AddSocket(fds, udp) == -1)
882 Fail("SDLNet_TCP_AddSocket() failed: %s"), SDLNet_GetError();
884 Debug("network:server", "started up, listening on port %d", port);
885 Debug("network:server", "using protocol version %d.%d.%d",
886 PROTOCOL_VERSION_MAJOR,
887 PROTOCOL_VERSION_MINOR,
888 PROTOCOL_VERSION_PATCH);
892 // wait for 100 ms for activity on open network sockets
893 if (SDLNet_CheckSockets(fds, 100) < 1)
896 // accept incoming TCP connections
897 if (SDLNet_SocketReady(lfd))
899 Debug("network:server", "got TCP packet");
903 newsock = SDLNet_TCP_Accept(lfd);
909 // accept incoming UDP packets
910 if (SDLNet_SocketReady(udp))
912 Debug("network:server", "got UDP packet");
914 static UDPpacket packet;
916 int num_packets = SDLNet_UDP_Recv(udp, &packet);
918 if (num_packets == 1)
921 SDLNet_UDP_Send(udp, -1, &packet);
925 for (player = first_player; player != NULL; player = player->next)
927 if (!SDLNet_SocketReady(player->fd))
930 initNetworkBufferForReceiving(read_buffer);
932 int num_bytes = receiveNetworkBufferPacket(read_buffer, player->fd);
936 Debug("network:server", "EOF from client %d (%s)",
937 player->number, player->player_name);
939 RemovePlayer(player);
944 initNetworkBufferForReading(read_buffer);
946 int message_type = getNetworkBuffer8BitInteger(read_buffer);
948 // skip player number
949 getNetworkBuffer8BitInteger(read_buffer);
951 if (!player->introduced &&
952 message_type != OP_PLAYER_NAME &&
953 message_type != OP_PROTOCOL_VERSION)
955 Debug("network:server", "got opcode %d for client %d which is not introduced yet (expected OP_PLAYER_NAME or OP_PROTOCOL_VERSION)", message_type, player->number);
957 RemovePlayer(player);
962 switch (message_type)
964 case OP_PROTOCOL_VERSION:
965 Handle_OP_PROTOCOL_VERSION(player);
968 case OP_NUMBER_WANTED:
969 Handle_OP_NUMBER_WANTED(player);
973 Handle_OP_PLAYER_NAME(player);
976 case OP_START_PLAYING:
977 Handle_OP_START_PLAYING(player);
980 case OP_PAUSE_PLAYING:
981 Handle_OP_PAUSE_PLAYING(player);
984 case OP_CONTINUE_PLAYING:
985 Handle_OP_CONTINUE_PLAYING(player);
988 case OP_STOP_PLAYING:
989 Handle_OP_STOP_PLAYING(player);
993 Handle_OP_MOVE_PLAYER(player);
996 case OP_BROADCAST_MESSAGE:
997 Handle_OP_BROADCAST_MESSAGE(player);
1001 Handle_OP_LEVEL_FILE(player);
1005 Debug("network:server", "unknown opcode %d from client %d (%s)",
1006 message_type, player->number, player->player_name);