1 /***********************************************************
2 * Rocks'n'Diamonds -- McDuffin Strikes Back! *
3 *----------------------------------------------------------*
4 * (c) 1995-2006 Artsoft Entertainment *
6 * Detmolder Strasse 189 *
9 * e-mail: info@artsoft.org *
10 *----------------------------------------------------------*
12 ***********************************************************/
14 #include "libgame/platform.h"
16 #if defined(NETWORK_AVALIABLE)
21 #if defined(TARGET_SDL)
25 #include <sys/socket.h>
26 #include <netinet/in.h>
27 #include <netinet/tcp.h>
28 #include <arpa/inet.h>
32 #include "libgame/libgame.h"
42 struct NetworkClientPlayerInfo
45 char name[MAX_PLAYER_NAME_LEN + 1];
46 struct NetworkClientPlayerInfo *next;
49 static struct NetworkClientPlayerInfo first_player =
58 #if defined(TARGET_SDL)
59 static TCPsocket sfd; /* server socket */
60 static SDLNet_SocketSet rfds; /* socket set */
62 static int sfd; /* server socket */
65 static byte realbuffer[512];
66 static byte readbuffer[MAX_BUFFER_SIZE], writbuffer[MAX_BUFFER_SIZE];
67 static byte *buffer = realbuffer + 4;
68 static int nread = 0, nwrite = 0;
69 static boolean stop_network_game = FALSE;
71 static void SendBufferToServer(int size)
76 realbuffer[0] = realbuffer[1] = realbuffer[2] = 0;
77 realbuffer[3] = (byte)size;
80 if (nwrite + 4 + size >= MAX_BUFFER_SIZE)
81 Error(ERR_EXIT, "internal error: network send buffer overflow");
83 memcpy(writbuffer + nwrite, realbuffer, 4 + size);
86 /* directly send the buffer to the network server */
87 #if defined(TARGET_SDL)
88 SDLNet_TCP_Send(sfd, writbuffer, nwrite);
90 write(sfd, writbuffer, nwrite);
95 struct NetworkClientPlayerInfo *getNetworkPlayer(int player_nr)
97 struct NetworkClientPlayerInfo *player = NULL;
99 for (player = &first_player; player; player = player->next)
100 if (player->nr == player_nr)
103 if (player == NULL) /* should not happen */
104 Error(ERR_EXIT, "protocol error: reference to non-existing player %d",
110 char *getNetworkPlayerName(int player_nr)
112 struct NetworkClientPlayerInfo *player;
115 return("the network game server");
116 else if (player_nr == first_player.nr)
119 for (player = &first_player; player; player = player->next)
120 if (player->nr == player_nr && player->name && strlen(player->name))
121 return(player->name);
123 return(EMPTY_PLAYER_NAME);
126 static void StartNetworkServer(int port)
128 #if defined(TARGET_SDL)
132 server_thread = SDL_CreateThread(NetworkServerThread, &p);
133 network_server = TRUE;
140 NetworkServer(port, options.serveronly);
147 "cannot create network server process - no network playing");
148 options.network = FALSE;
152 /* we are parent process -- resume normal operation */
158 #if defined(TARGET_SDL)
159 boolean ConnectToServer(char *hostname, int port)
165 port = DEFAULT_SERVER_PORT;
167 rfds = SDLNet_AllocSocketSet(1);
171 SDLNet_ResolveHost(&ip, hostname, port);
172 if (ip.host == INADDR_NONE)
173 Error(ERR_EXIT, "cannot locate host '%s'", hostname);
177 SDLNet_Write32(0x7f000001, &ip.host); /* 127.0.0.1 */
178 SDLNet_Write16(port, &ip.port);
181 sfd = SDLNet_TCP_Open(&ip);
185 SDLNet_TCP_AddSocket(rfds, sfd);
190 printf("SDLNet_TCP_Open(): %s\n", SDLNet_GetError());
193 if (hostname) /* connect to specified server failed */
196 printf("No rocksndiamonds server on localhost -- starting up one ...\n");
197 StartNetworkServer(port);
199 /* wait for server to start up and try connecting several times */
200 for (i = 0; i < 6; i++)
202 Delay(500); /* wait 500 ms == 0.5 seconds */
204 if ((sfd = SDLNet_TCP_Open(&ip))) /* connected */
206 SDLNet_TCP_AddSocket(rfds, sfd);
211 /* when reaching this point, connect to newly started server has failed */
217 boolean ConnectToServer(char *hostname, int port)
219 struct sockaddr_in s;
220 struct protoent *tcpproto;
225 if ((s.sin_addr.s_addr = inet_addr(hostname)) == -1)
227 struct hostent *host;
229 if ((host = gethostbyname(hostname)) == NULL)
230 Error(ERR_EXIT, "cannot locate host '%s'", hostname);
232 s.sin_addr = *(struct in_addr *)(host->h_addr_list[0]);
236 s.sin_addr.s_addr = inet_addr("127.0.0.1"); /* localhost */
239 port = DEFAULT_SERVER_PORT;
241 s.sin_port = htons(port);
242 s.sin_family = AF_INET;
244 sfd = socket(PF_INET, SOCK_STREAM, 0);
246 Error(ERR_EXIT, "out of file descriptors");
248 if ((tcpproto = getprotobyname("tcp")) != NULL)
249 setsockopt(sfd, tcpproto->p_proto, TCP_NODELAY, (char *)&on, sizeof(int));
251 if (connect(sfd, (struct sockaddr *)&s, sizeof(s)) == 0) /* connected */
254 if (hostname) /* connect to specified server failed */
257 printf("No rocksndiamonds server on localhost -- starting up one ...\n");
258 StartNetworkServer(port);
260 /* wait for server to start up and try connecting several times */
261 for (i = 0; i < 6; i++)
263 Delay(500); /* wait 500 ms == 0.5 seconds */
266 sfd = socket(PF_INET, SOCK_STREAM, 0);
268 Error(ERR_EXIT, "out of file descriptors");
270 setsockopt(sfd, tcpproto->p_proto, TCP_NODELAY, (char *)&on, sizeof(int));
272 if (connect(sfd, (struct sockaddr *)&s, sizeof(s)) >= 0) /* connected */
276 /* when reaching this point, connect to newly started server has failed */
279 #endif /* defined(TARGET_SDL) */
281 void SendToServer_PlayerName(char *player_name)
283 int len_player_name = strlen(player_name);
285 buffer[1] = OP_PLAYER_NAME;
286 memcpy(&buffer[2], player_name, len_player_name);
287 SendBufferToServer(2 + len_player_name);
288 Error(ERR_NETWORK_CLIENT, "you set your player name to \"%s\"", player_name);
291 void SendToServer_ProtocolVersion()
293 buffer[1] = OP_PROTOCOL_VERSION;
294 buffer[2] = PROTOCOL_VERSION_1;
295 buffer[3] = PROTOCOL_VERSION_2;
296 buffer[4] = PROTOCOL_VERSION_3;
298 SendBufferToServer(5);
301 void SendToServer_NrWanted(int nr_wanted)
303 buffer[1] = OP_NUMBER_WANTED;
304 buffer[2] = nr_wanted;
306 SendBufferToServer(3);
309 void SendToServer_StartPlaying()
311 unsigned long new_random_seed = InitRND(level.random_seed);
313 int dummy = 0; /* !!! HAS NO MEANING ANYMORE !!! */
314 /* the name of the level must be enough */
316 buffer[1] = OP_START_PLAYING;
317 buffer[2] = (byte)(level_nr >> 8);
318 buffer[3] = (byte)(level_nr & 0xff);
319 buffer[4] = (byte)(dummy >> 8);
320 buffer[5] = (byte)(dummy & 0xff);
322 buffer[6] = (unsigned char)((new_random_seed >> 24) & 0xff);
323 buffer[7] = (unsigned char)((new_random_seed >> 16) & 0xff);
324 buffer[8] = (unsigned char)((new_random_seed >> 8) & 0xff);
325 buffer[9] = (unsigned char)((new_random_seed >> 0) & 0xff);
327 strcpy((char *)&buffer[10], leveldir_current->identifier);
329 SendBufferToServer(10 + strlen(leveldir_current->identifier) + 1);
332 void SendToServer_PausePlaying()
334 buffer[1] = OP_PAUSE_PLAYING;
336 SendBufferToServer(2);
339 void SendToServer_ContinuePlaying()
341 buffer[1] = OP_CONTINUE_PLAYING;
343 SendBufferToServer(2);
346 void SendToServer_StopPlaying(int cause_for_stopping)
348 buffer[1] = OP_STOP_PLAYING;
349 buffer[2] = cause_for_stopping;
351 SendBufferToServer(3);
354 void SendToServer_MovePlayer(byte player_action)
356 buffer[1] = OP_MOVE_PLAYER;
357 buffer[2] = player_action;
359 SendBufferToServer(3);
362 static void Handle_OP_BAD_PROTOCOL_VERSION()
364 Error(ERR_WARN, "protocol version mismatch");
365 Error(ERR_EXIT, "server expects %d.%d.x instead of %d.%d.%d",
366 buffer[2], buffer[3],
367 PROTOCOL_VERSION_1, PROTOCOL_VERSION_2, PROTOCOL_VERSION_3);
370 static void Handle_OP_YOUR_NUMBER()
372 int new_client_nr = buffer[2];
373 int new_index_nr = new_client_nr - 1;
374 struct PlayerInfo *old_local_player = local_player;
375 struct PlayerInfo *new_local_player = &stored_player[new_index_nr];
377 printf("OP_YOUR_NUMBER: %d\n", buffer[0]);
378 first_player.nr = new_client_nr;
380 if (old_local_player != new_local_player)
382 /* copy existing player settings and change to new player */
384 *new_local_player = *old_local_player;
385 old_local_player->connected = FALSE;
386 local_player = new_local_player;
389 if (first_player.nr > MAX_PLAYERS)
390 Error(ERR_EXIT, "sorry, more than %d players not allowed", MAX_PLAYERS);
392 Error(ERR_NETWORK_CLIENT, "you get client # %d", new_client_nr);
395 static void Handle_OP_NUMBER_WANTED()
397 int client_nr_wanted = buffer[2];
398 int old_client_nr = buffer[0];
399 int new_client_nr = buffer[3];
400 int old_index_nr = old_client_nr - 1;
401 int new_index_nr = new_client_nr - 1;
402 int index_nr_wanted = client_nr_wanted - 1;
403 struct PlayerInfo *old_player = &stored_player[old_index_nr];
404 struct PlayerInfo *new_player = &stored_player[new_index_nr];
406 printf("OP_NUMBER_WANTED: %d\n", buffer[0]);
408 if (new_client_nr == client_nr_wanted) /* switching succeeded */
410 struct NetworkClientPlayerInfo *player;
412 if (old_client_nr != client_nr_wanted) /* client's nr has changed */
413 Error(ERR_NETWORK_CLIENT, "client %d switches to # %d",
414 old_client_nr, new_client_nr);
415 else if (old_client_nr == first_player.nr) /* local player keeps his nr */
416 Error(ERR_NETWORK_CLIENT, "keeping client # %d", new_client_nr);
418 if (old_client_nr != new_client_nr)
420 /* copy existing player settings and change to new player */
422 *new_player = *old_player;
423 old_player->connected = FALSE;
426 player = getNetworkPlayer(old_client_nr);
427 player->nr = new_client_nr;
429 if (old_player == local_player) /* local player switched */
430 local_player = new_player;
432 else if (old_client_nr == first_player.nr) /* failed -- local player? */
436 sprintf(request, "Sorry ! Player %d already exists ! You are player %d !",
437 index_nr_wanted + 1, new_index_nr + 1);
439 Request(request, REQ_CONFIRM);
441 Error(ERR_NETWORK_CLIENT, "cannot switch -- you keep client # %d",
446 static void Handle_OP_PLAYER_NAME(unsigned int len)
448 struct NetworkClientPlayerInfo *player;
449 int player_nr = (int)buffer[0];
451 printf("OP_PLAYER_NAME: %d\n", player_nr);
452 player = getNetworkPlayer(player_nr);
454 Error(ERR_NETWORK_CLIENT, "client %d calls itself \"%s\"",
455 buffer[0], &buffer[2]);
456 strncpy(player->name, (char *)&buffer[2], MAX_PLAYER_NAME_LEN);
459 static void Handle_OP_PLAYER_CONNECTED()
461 struct NetworkClientPlayerInfo *player, *last_player = NULL;
462 int new_client_nr = (int)buffer[0];
463 int new_index_nr = new_client_nr - 1;
465 printf("OP_PLAYER_CONNECTED: %d\n", new_client_nr);
466 Error(ERR_NETWORK_CLIENT, "new client %d connected", new_client_nr);
468 for (player = &first_player; player; player = player->next)
470 if (player->nr == new_client_nr)
471 Error(ERR_EXIT, "multiplayer server sent duplicate player id");
473 last_player = player;
476 last_player->next = player =
477 checked_malloc(sizeof(struct NetworkClientPlayerInfo));
478 player->nr = new_client_nr;
479 player->name[0] = '\0';
482 stored_player[new_index_nr].connected = TRUE;
485 static void Handle_OP_PLAYER_DISCONNECTED()
487 struct NetworkClientPlayerInfo *player, *player_disconnected;
488 int player_nr = (int)buffer[0];
490 printf("OP_PLAYER_DISCONNECTED: %d\n", player_nr);
491 player_disconnected = getNetworkPlayer(player_nr);
492 Error(ERR_NETWORK_CLIENT, "client %d (%s) disconnected",
493 player_nr, getNetworkPlayerName(buffer[0]));
495 for (player = &first_player; player; player = player->next)
496 if (player->next == player_disconnected)
497 player->next = player_disconnected->next;
498 free(player_disconnected);
501 static void Handle_OP_START_PLAYING()
503 LevelDirTree *new_leveldir;
506 unsigned long new_random_seed;
507 char *new_leveldir_identifier;
509 new_level_nr = (buffer[2] << 8) + buffer[3];
510 dummy = (buffer[4] << 8) + buffer[5]; /* (obsolete) */
512 (buffer[6] << 24) | (buffer[7] << 16) | (buffer[8] << 8) | (buffer[9]);
513 new_leveldir_identifier = (char *)&buffer[10];
515 new_leveldir = getTreeInfoFromIdentifier(leveldir_first,
516 new_leveldir_identifier);
517 if (new_leveldir == NULL)
519 Error(ERR_WARN, "no such level identifier: '%s'", new_leveldir_identifier);
521 new_leveldir = leveldir_first;
522 Error(ERR_WARN, "using default level set: '%s'", new_leveldir->identifier);
525 printf("OP_START_PLAYING: %d\n", buffer[0]);
526 Error(ERR_NETWORK_CLIENT,
527 "client %d starts game [level %d from level identifier '%s']\n",
528 buffer[0], new_level_nr, new_leveldir->identifier);
530 leveldir_current = new_leveldir;
531 level_nr = new_level_nr;
537 StartGameActions(FALSE, setup.autorecord, new_random_seed);
540 static void Handle_OP_PAUSE_PLAYING()
542 printf("OP_PAUSE_PLAYING: %d\n", buffer[0]);
543 Error(ERR_NETWORK_CLIENT, "client %d pauses game", buffer[0]);
546 DrawVideoDisplay(VIDEO_STATE_PAUSE_ON,0);
549 static void Handle_OP_CONTINUE_PLAYING()
551 printf("OP_CONTINUE_PLAYING: %d\n", buffer[0]);
552 Error(ERR_NETWORK_CLIENT, "client %d continues game", buffer[0]);
554 tape.pausing = FALSE;
555 DrawVideoDisplay(VIDEO_STATE_PAUSE_OFF,0);
558 static void Handle_OP_STOP_PLAYING()
560 printf("OP_STOP_PLAYING: %d [%d]\n", buffer[0], buffer[2]);
561 Error(ERR_NETWORK_CLIENT, "client %d stops game [%d]", buffer[0], buffer[2]);
563 if (game_status == GAME_MODE_PLAYING)
565 if (buffer[2] == NETWORK_STOP_BY_PLAYER)
566 Request("Network game stopped by player!", REQ_CONFIRM);
567 else if (buffer[2] == NETWORK_STOP_BY_ERROR)
568 Request("Network game stopped due to internal error!", REQ_CONFIRM);
570 Request("Network game stopped !", REQ_CONFIRM);
573 game_status = GAME_MODE_MAIN;
577 static void Handle_OP_MOVE_PLAYER(unsigned int len)
579 int server_frame_counter;
582 if (!network_playing)
585 server_frame_counter =
586 (buffer[2] << 24) | (buffer[3] << 16) | (buffer[4] << 8) | (buffer[5]);
589 Error(ERR_NETWORK_CLIENT, "receiving server frame counter value %d [%d]",
590 server_frame_counter, FrameCounter);
593 if (server_frame_counter != FrameCounter)
595 Error(ERR_INFO, "client and servers frame counters out of sync");
596 Error(ERR_INFO, "frame counter of client is %d", FrameCounter);
597 Error(ERR_INFO, "frame counter of server is %d", server_frame_counter);
598 Error(ERR_INFO, "this should not happen -- please debug");
600 stop_network_game = TRUE;
605 /* copy valid player actions */
606 for (i = 0; i < MAX_PLAYERS; i++)
607 stored_player[i].effective_action =
608 (i < len - 6 && stored_player[i].active ? buffer[6 + i] : 0);
610 network_player_action_received = TRUE;
613 static void HandleNetworkingMessages()
615 unsigned int message_length;
617 stop_network_game = FALSE;
619 while (nread >= 4 && nread >= 4 + readbuffer[3])
621 message_length = readbuffer[3];
622 if (readbuffer[0] || readbuffer[1] || readbuffer[2])
623 Error(ERR_EXIT, "wrong network server line length");
625 memcpy(buffer, &readbuffer[4], message_length);
626 nread -= 4 + message_length;
627 memmove(readbuffer, readbuffer + 4 + message_length, nread);
631 case OP_BAD_PROTOCOL_VERSION:
632 Handle_OP_BAD_PROTOCOL_VERSION();
636 Handle_OP_YOUR_NUMBER();
639 case OP_NUMBER_WANTED:
640 Handle_OP_NUMBER_WANTED();
644 Handle_OP_PLAYER_NAME(message_length);
647 case OP_PLAYER_CONNECTED:
648 Handle_OP_PLAYER_CONNECTED();
651 case OP_PLAYER_DISCONNECTED:
652 Handle_OP_PLAYER_DISCONNECTED();
655 case OP_START_PLAYING:
656 Handle_OP_START_PLAYING();
659 case OP_PAUSE_PLAYING:
660 Handle_OP_PAUSE_PLAYING();
663 case OP_CONTINUE_PLAYING:
664 Handle_OP_CONTINUE_PLAYING();
667 case OP_STOP_PLAYING:
668 Handle_OP_STOP_PLAYING();
672 Handle_OP_MOVE_PLAYER(message_length);
675 case OP_BROADCAST_MESSAGE:
676 printf("OP_BROADCAST_MESSAGE: %d\n", buffer[0]);
677 Error(ERR_NETWORK_CLIENT, "client %d sends message", buffer[0]);
684 /* in case of internal error, stop network game */
685 if (stop_network_game)
686 SendToServer_StopPlaying(NETWORK_STOP_BY_ERROR);
691 void HandleNetworking()
693 #if !defined(TARGET_SDL)
694 static struct timeval tv = { 0, 0 };
701 #if defined(TARGET_SDL)
702 if ((r = SDLNet_CheckSockets(rfds, 1)) < 0)
703 Error(ERR_EXIT, "HandleNetworking(): SDLNet_CheckSockets() failed");
710 r = select(sfd + 1, &rfds, NULL, NULL, &tv);
712 if (r < 0 && errno != EINTR)
713 Error(ERR_EXIT, "HandleNetworking(): select() failed");
719 #if defined(TARGET_SDL)
722 if (FD_ISSET(sfd, &rfds))
725 #if defined(TARGET_SDL)
726 r = SDLNet_TCP_Recv(sfd, readbuffer + nread, 1);
728 r = read(sfd, readbuffer + nread, MAX_BUFFER_SIZE - nread);
732 Error(ERR_EXIT, "error reading from network server");
735 Error(ERR_EXIT, "connection to network server lost");
739 HandleNetworkingMessages();
745 #endif /* PLATFORM_UNIX */