improved handling network protocol version mismatch
[rocksndiamonds.git] / src / network.c
index 104b83f9bb2df69b3e36c2f83107fe37d0bd6772..b0a6a0eee2fcc78096a6c25eae72a34cd4358b94 100644 (file)
@@ -1,38 +1,22 @@
-/***********************************************************
-* Rocks'n'Diamonds -- McDuffin Strikes Back!               *
-*----------------------------------------------------------*
-* (c) 1995-2002 Artsoft Entertainment                      *
-*               Holger Schemel                             *
-*               Detmolder Strasse 189                      *
-*               33604 Bielefeld                            *
-*               Germany                                    *
-*               e-mail: info@artsoft.org                   *
-*----------------------------------------------------------*
-* network.c                                                *
-***********************************************************/
-
-#include "libgame/platform.h"
-
-#if defined(NETWORK_AVALIABLE)
+// ============================================================================
+// Rocks'n'Diamonds - McDuffin Strikes Back!
+// ----------------------------------------------------------------------------
+// (c) 1995-2014 by Artsoft Entertainment
+//                         Holger Schemel
+//                 info@artsoft.org
+//                 http://www.artsoft.org/
+// ----------------------------------------------------------------------------
+// network.c
+// ============================================================================
 
 #include <signal.h>
 #include <sys/time.h>
 
-#if defined(TARGET_SDL)
-#include "main.h"
-#else
-#include <sys/wait.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <arpa/inet.h>
-#include <netdb.h>
-#endif
-
 #include "libgame/libgame.h"
 
 #include "network.h"
 #include "netserv.h"
+#include "main.h"
 #include "game.h"
 #include "tape.h"
 #include "files.h"
@@ -55,21 +39,98 @@ static struct NetworkClientPlayerInfo first_player =
 
 /* server stuff */
 
-#if defined(TARGET_SDL)
-static TCPsocket sfd;          /* server socket */
+static TCPsocket sfd;          /* TCP server socket */
+static UDPsocket udp;          /* UDP server socket */
 static SDLNet_SocketSet rfds;  /* socket set */
-#else
-static int sfd;                        /* server socket */
-#endif
 
 static byte realbuffer[512];
 static byte readbuffer[MAX_BUFFER_SIZE], writbuffer[MAX_BUFFER_SIZE];
 static byte *buffer = realbuffer + 4;
 static int nread = 0, nwrite = 0;
+static boolean stop_network_game = FALSE;
+static boolean stop_network_client = FALSE;
+static char stop_network_client_message[MAX_OUTPUT_LINESIZE + 1];
+
+static void DrawNetworkTextExt(char *message, int font_nr, boolean initialize)
+{
+  static int xpos = 0, ypos = 0;
+  static int max_line_width = 0;
+  int font_width = getFontWidth(font_nr);
+  int font_height = getFontHeight(font_nr);
+  int ypos_1 = 120;
+  int ypos_2 = 150;
+
+  if (initialize)
+  {
+    if (game_status == GAME_MODE_LOADING)
+    {
+      max_line_width = WIN_XSIZE;
+
+      xpos = (max_line_width - getTextWidth(message, font_nr)) / 2;
+      ypos = ypos_1;
+
+      DrawText(xpos, ypos, message, font_nr);
+
+      xpos = 0;
+      ypos = ypos_2;
+    }
+    else
+    {
+      max_line_width = SXSIZE;
+
+      DrawTextSCentered(ypos_1, font_nr, message);
+
+      /* calculate offset to x position caused by rounding */
+      int max_chars_per_line = max_line_width / font_width;
+      int xoffset = (max_line_width - max_chars_per_line * font_width) / 2;
+
+      xpos = SX + xoffset;
+      ypos = SY + ypos_2;
+    }
+
+    Error(ERR_DEBUG, "========== %s ==========", message);
+  }
+  else
+  {
+    int max_chars_per_line = max_line_width / font_width;
+    int max_lines_per_text = 10;
+    int num_lines_spacing = (font_nr == FC_YELLOW ? 1 : 3);
+    int num_lines_printed = DrawTextBuffer(xpos, ypos, message, font_nr,
+                                          max_chars_per_line, -1,
+                                          max_lines_per_text, 0, -1,
+                                          TRUE, TRUE, FALSE);
+
+    ypos += (num_lines_printed + num_lines_spacing) * font_height;
+
+    Error(ERR_DEBUG, "%s", message);
+  }
+
+  BackToFront();
+}
+
+static void DrawNetworkText(char *message)
+{
+  DrawNetworkTextExt(message, FC_YELLOW, FALSE);
+}
+
+static void DrawNetworkText_Success(char *message)
+{
+  DrawNetworkTextExt(message, FC_GREEN, FALSE);
+}
+
+static void DrawNetworkText_Failed(char *message)
+{
+  DrawNetworkTextExt(message, FC_RED, FALSE);
+}
+
+static void DrawNetworkText_Title(char *message)
+{
+  DrawNetworkTextExt(message, FC_GREEN, TRUE);
+}
 
 static void SendBufferToServer(int size)
 {
-  if (!options.network)
+  if (!network.enabled)
     return;
 
   realbuffer[0] = realbuffer[1] = realbuffer[2] = 0;
@@ -83,11 +144,7 @@ static void SendBufferToServer(int size)
   nwrite += 4 + size;
 
   /* directly send the buffer to the network server */
-#if defined(TARGET_SDL)
   SDLNet_TCP_Send(sfd, writbuffer, nwrite);
-#else
-  write(sfd, writbuffer, nwrite);
-#endif
   nwrite = 0;
 }
 
@@ -116,7 +173,7 @@ char *getNetworkPlayerName(int player_nr)
     return("you");
   else
     for (player = &first_player; player; player = player->next)
-      if (player->nr == player_nr && player->name && strlen(player->name))
+      if (player->nr == player_nr && strlen(player->name) > 0)
        return(player->name);
 
   return(EMPTY_PLAYER_NAME);
@@ -124,158 +181,172 @@ char *getNetworkPlayerName(int player_nr)
 
 static void StartNetworkServer(int port)
 {
-#if defined(TARGET_SDL)
   static int p;
 
   p = port;
-  server_thread = SDL_CreateThread(NetworkServerThread, &p);
-  network_server = TRUE;
-
+#if defined(TARGET_SDL2)
+  server_thread = SDL_CreateThread(NetworkServerThread,
+                                  "NetworkServerThread", &p);
 #else
-
-  switch (fork())
-  {
-    case 0:
-      NetworkServer(port, options.serveronly);
-
-      /* never reached */
-      exit(0);
-
-    case -1:
-      Error(ERR_WARN,
-           "cannot create network server process - no network playing");
-      options.network = FALSE;
-      return;
-
-    default:
-      /* we are parent process -- resume normal operation */
-      return;
-  }
+  server_thread = SDL_CreateThread(NetworkServerThread, &p);
 #endif
+  network_server = TRUE;
 }
 
-#if defined(TARGET_SDL)
 boolean ConnectToServer(char *hostname, int port)
 {
   IPaddress ip;
+  int server_host = 0;
   int i;
 
+  DrawNetworkText_Title("Initializing Network");
+
   if (port == 0)
     port = DEFAULT_SERVER_PORT;
 
+  if (hostname == NULL)
+  {
+    // if no hostname given, try to auto-detect network server in local network
+    // by doing a UDP broadcast on the network server port and wait for answer
+
+    SDLNet_SocketSet udp_socket_set = SDLNet_AllocSocketSet(1);
+    if (!udp_socket_set)
+      Error(ERR_EXIT, "SDLNet_AllocSocketSet() failed: %s"), SDLNet_GetError();
+
+    udp = SDLNet_UDP_Open(0);
+    if(!udp)
+      Error(ERR_EXIT, "SDLNet_UDP_Open() failed: %s", SDLNet_GetError());
+
+    if (SDLNet_UDP_AddSocket(udp_socket_set, udp) == -1)
+      Error(ERR_EXIT_NETWORK_SERVER, "SDLNet_TCP_AddSocket() failed: %s"),
+        SDLNet_GetError();
+
+    char *data_ptr = "network server UDB broadcast";
+    int data_len = strlen(data_ptr) + 1;
+    IPaddress ip_address;
+
+    SDLNet_Write32(0xffffffff, &ip_address.host);      /* 255.255.255.255 */
+    SDLNet_Write16(port,       &ip_address.port);
+
+    UDPpacket packet =
+    {
+      -1,
+      (Uint8 *)data_ptr,
+      data_len,
+      data_len,
+      0,
+      ip_address
+    };
+
+    SDLNet_UDP_Send(udp, -1, &packet);
+
+    DrawNetworkText("Looking for local network server ...");
+
+    /* wait for any local network server to answer UDP broadcast */
+    for (i = 0; i < 5; i++)
+    {
+      if (SDLNet_CheckSockets(udp_socket_set, 0) == 1)
+      {
+       int num_packets = SDLNet_UDP_Recv(udp, &packet);
+
+       if (num_packets == 1)
+       {
+         DrawNetworkText_Success("Network server found!");
+
+         server_host = SDLNet_Read32(&packet.address.host);
+       }
+       else
+       {
+         DrawNetworkText_Failed("No answer from network server!");
+       }
+
+       break;
+      }
+      else
+      {
+       Delay_WithScreenUpdates(100);
+      }
+    }
+
+    if (server_host == 0)
+      DrawNetworkText_Failed("No network server found!");
+  }
+
   rfds = SDLNet_AllocSocketSet(1);
 
   if (hostname)
   {
     SDLNet_ResolveHost(&ip, hostname, port);
+
     if (ip.host == INADDR_NONE)
       Error(ERR_EXIT, "cannot locate host '%s'", hostname);
+    else
+      server_host = SDLNet_Read32(&ip.host);
+
+    DrawNetworkText("Connecting to remote host ...");
   }
   else
   {
-    SDLNet_Write32(0x7f000001, &ip.host);      /* 127.0.0.1 */
-    SDLNet_Write16(port, &ip.port);
+    // if no hostname was given and no network server was auto-detected in the
+    // local network, try to connect to a network server at the local host
+    if (server_host == 0)
+      server_host = 0x7f000001;                        /* 127.0.0.1 */
+
+    SDLNet_Write32(server_host, &ip.host);
+    SDLNet_Write16(port,        &ip.port);
+
+    DrawNetworkText("Connecting to local host ...");
   }
 
+  Error(ERR_DEBUG, "trying to connect to network server at %d.%d.%d.%d ...",
+        (server_host >> 24) & 0xff,
+        (server_host >> 16) & 0xff,
+        (server_host >>  8) & 0xff,
+        (server_host >>  0) & 0xff);
+
   sfd = SDLNet_TCP_Open(&ip);
 
   if (sfd)
   {
     SDLNet_TCP_AddSocket(rfds, sfd);
+
+    DrawNetworkText_Success("Successfully connected!");
+
     return TRUE;
   }
   else
   {
+    DrawNetworkText_Failed("Failed to connect to network server!");
+
     printf("SDLNet_TCP_Open(): %s\n", SDLNet_GetError());
   }
 
   if (hostname)                        /* connect to specified server failed */
     return FALSE;
 
-  printf("No rocksndiamonds server on localhost -- starting up one ...\n");
+  DrawNetworkText("Starting new local network server ...");
+
   StartNetworkServer(port);
 
   /* wait for server to start up and try connecting several times */
-  for (i = 0; i < 6; i++)
+  for (i = 0; i < 30; i++)
   {
-    Delay(500);                        /* wait 500 ms == 0.5 seconds */
-
     if ((sfd = SDLNet_TCP_Open(&ip)))          /* connected */
     {
+      DrawNetworkText_Success("Successfully connected!");
+
       SDLNet_TCP_AddSocket(rfds, sfd);
       return TRUE;
     }
-  }
-
-  /* when reaching this point, connect to newly started server has failed */
-  return FALSE;
-}
-
-#else
-
-boolean ConnectToServer(char *hostname, int port)
-{
-  struct sockaddr_in s;
-  struct protoent *tcpproto;
-  int on = 1, i;
-
-  if (hostname)
-  {
-    if ((s.sin_addr.s_addr = inet_addr(hostname)) == -1)
-    {
-      struct hostent *host;
-
-      if ((host = gethostbyname(hostname)) == NULL)
-       Error(ERR_EXIT, "cannot locate host '%s'", hostname);
 
-      s.sin_addr = *(struct in_addr *)(host->h_addr_list[0]);
-    }
+    Delay_WithScreenUpdates(100);
   }
-  else
-    s.sin_addr.s_addr = inet_addr("127.0.0.1");                /* localhost */
-
-  if (port == 0)
-    port = DEFAULT_SERVER_PORT;
-
-  s.sin_port = htons(port);
-  s.sin_family = AF_INET;
 
-  sfd = socket(PF_INET, SOCK_STREAM, 0);
-  if (sfd < 0)
-    Error(ERR_EXIT, "out of file descriptors");
-
-  if ((tcpproto = getprotobyname("tcp")) != NULL)
-    setsockopt(sfd, tcpproto->p_proto, TCP_NODELAY, (char *)&on, sizeof(int));
-
-  if (connect(sfd, (struct sockaddr *)&s, sizeof(s)) == 0)     /* connected */
-    return TRUE;
-
-  if (hostname)        /* connect to specified server failed */
-    return FALSE;
-
-  printf("No rocksndiamonds server on localhost -- starting up one ...\n");
-  StartNetworkServer(port);
-
-  /* wait for server to start up and try connecting several times */
-  for (i = 0; i < 6; i++)
-  {
-    Delay(500);                /* wait 500 ms == 0.5 seconds */
-    close(sfd);
-
-    sfd = socket(PF_INET, SOCK_STREAM, 0);
-    if (sfd < 0)
-      Error(ERR_EXIT, "out of file descriptors");
-
-    setsockopt(sfd, tcpproto->p_proto, TCP_NODELAY, (char *)&on, sizeof(int));
-
-    if (connect(sfd, (struct sockaddr *)&s, sizeof(s)) >= 0)   /* connected */
-      return TRUE;
-  }
+  DrawNetworkText_Failed("Failed to connect to network server!");
 
   /* when reaching this point, connect to newly started server has failed */
   return FALSE;
 }
-#endif /* defined(TARGET_SDL) */
 
 void SendToServer_PlayerName(char *player_name)
 {
@@ -307,7 +378,7 @@ void SendToServer_NrWanted(int nr_wanted)
 
 void SendToServer_StartPlaying()
 {
-  unsigned long new_random_seed = InitRND(NEW_RANDOMIZE);
+  unsigned int new_random_seed = InitRND(level.random_seed);
 
   int dummy = 0;               /* !!! HAS NO MEANING ANYMORE !!! */
                                /* the name of the level must be enough */
@@ -342,11 +413,12 @@ void SendToServer_ContinuePlaying()
   SendBufferToServer(2);
 }
 
-void SendToServer_StopPlaying()
+void SendToServer_StopPlaying(int cause_for_stopping)
 {
   buffer[1] = OP_STOP_PLAYING;
+  buffer[2] = cause_for_stopping;
 
-  SendBufferToServer(2);
+  SendBufferToServer(3);
 }
 
 void SendToServer_MovePlayer(byte player_action)
@@ -360,9 +432,15 @@ void SendToServer_MovePlayer(byte player_action)
 static void Handle_OP_BAD_PROTOCOL_VERSION()
 {
   Error(ERR_WARN, "protocol version mismatch");
-  Error(ERR_EXIT, "server expects %d.%d.x instead of %d.%d.%d",
+  Error(ERR_WARN, "server expects %d.%d.x instead of %d.%d.%d",
        buffer[2], buffer[3],
        PROTOCOL_VERSION_1, PROTOCOL_VERSION_2, PROTOCOL_VERSION_3);
+
+  sprintf(stop_network_client_message, "Network protocol version mismatch! Server expects version %d.%d.x instead of %d.%d.%d!",
+         buffer[2], buffer[3],
+         PROTOCOL_VERSION_1, PROTOCOL_VERSION_2, PROTOCOL_VERSION_3);
+
+  stop_network_client = TRUE;
 }
 
 static void Handle_OP_YOUR_NUMBER()
@@ -377,17 +455,23 @@ static void Handle_OP_YOUR_NUMBER()
 
   if (old_local_player != new_local_player)
   {
-    /* copy existing player settings and change to new player */
+    /* set relevant player settings and change to new player */
 
-    *new_local_player = *old_local_player;
-    old_local_player->connected = FALSE;
     local_player = new_local_player;
+
+    old_local_player->connected_locally = FALSE;
+    new_local_player->connected_locally = TRUE;
+
+    old_local_player->connected_network = FALSE;
+    new_local_player->connected_network = TRUE;
   }
 
   if (first_player.nr > MAX_PLAYERS)
     Error(ERR_EXIT, "sorry, more than %d players not allowed", MAX_PLAYERS);
 
   Error(ERR_NETWORK_CLIENT, "you get client # %d", new_client_nr);
+
+  stored_player[new_index_nr].connected_network = TRUE;
 }
 
 static void Handle_OP_NUMBER_WANTED()
@@ -415,30 +499,38 @@ static void Handle_OP_NUMBER_WANTED()
 
     if (old_client_nr != new_client_nr)
     {
-      /* copy existing player settings and change to new player */
+      /* set relevant player settings and change to new player */
 
-      *new_player = *old_player;
-      old_player->connected = FALSE;
+      old_player->connected_network = FALSE;
+      new_player->connected_network = TRUE;
     }
 
     player = getNetworkPlayer(old_client_nr);
     player->nr = new_client_nr;
 
     if (old_player == local_player)            /* local player switched */
+    {
       local_player = new_player;
+
+      old_player->connected_locally = FALSE;
+      new_player->connected_locally = TRUE;
+    }
   }
   else if (old_client_nr == first_player.nr)   /* failed -- local player? */
   {
-    char *color[] = { "yellow", "red", "green", "blue" };
     char request[100];
 
-    sprintf(request, "Sorry ! %s player still exists ! You are %s player !",
-           color[index_nr_wanted], color[new_index_nr]);
+    sprintf(request, "Sorry! Player %d already exists! You are player %d!",
+           index_nr_wanted + 1, new_index_nr + 1);
+
     Request(request, REQ_CONFIRM);
 
     Error(ERR_NETWORK_CLIENT, "cannot switch -- you keep client # %d",
          new_client_nr);
   }
+
+  if (game_status == GAME_MODE_MAIN)
+    DrawNetworkPlayers();
 }
 
 static void Handle_OP_PLAYER_NAME(unsigned int len)
@@ -477,13 +569,14 @@ static void Handle_OP_PLAYER_CONNECTED()
   player->name[0] = '\0';
   player->next = NULL;
 
-  stored_player[new_index_nr].connected = TRUE;
+  stored_player[new_index_nr].connected_network = TRUE;
 }
 
 static void Handle_OP_PLAYER_DISCONNECTED()
 {
   struct NetworkClientPlayerInfo *player, *player_disconnected;
   int player_nr = (int)buffer[0];
+  int index_nr = player_nr - 1;
 
   printf("OP_PLAYER_DISCONNECTED: %d\n", player_nr);
   player_disconnected = getNetworkPlayer(player_nr);
@@ -494,18 +587,37 @@ static void Handle_OP_PLAYER_DISCONNECTED()
     if (player->next == player_disconnected)
       player->next = player_disconnected->next;
   free(player_disconnected);
+
+  stored_player[index_nr].connected_locally = FALSE;
+  stored_player[index_nr].connected_network = FALSE;
+
+  if (game_status == GAME_MODE_PLAYING)
+  {
+    char message[100];
+
+    sprintf(message, "Player %d left network server! Network game stopped!",
+           player_nr);
+
+    Request(message, REQ_CONFIRM | REQ_STAY_CLOSED);
+
+    SetGameStatus(GAME_MODE_MAIN);
+
+    DrawMainMenu();
+  }
+  else if (game_status == GAME_MODE_MAIN)
+  {
+    DrawNetworkPlayers();
+  }
 }
 
 static void Handle_OP_START_PLAYING()
 {
   LevelDirTree *new_leveldir;
   int new_level_nr;
-  int dummy;
-  unsigned long new_random_seed;
+  unsigned int new_random_seed;
   char *new_leveldir_identifier;
 
   new_level_nr = (buffer[2] << 8) + buffer[3];
-  dummy = (buffer[4] << 8) + buffer[5];                        /* (obsolete) */
   new_random_seed =
     (buffer[6] << 24) | (buffer[7] << 16) | (buffer[8] << 8) | (buffer[9]);
   new_leveldir_identifier = (char *)&buffer[10];
@@ -516,8 +628,9 @@ static void Handle_OP_START_PLAYING()
   {
     Error(ERR_WARN, "no such level identifier: '%s'", new_leveldir_identifier);
 
-    new_leveldir = leveldir_first;
-    Error(ERR_WARN, "using default level set: '%s'", new_leveldir->identifier);
+    stop_network_game = TRUE;
+
+    return;
   }
 
   printf("OP_START_PLAYING: %d\n", buffer[0]);
@@ -532,20 +645,7 @@ static void Handle_OP_START_PLAYING()
   LoadTape(level_nr);
   LoadLevel(level_nr);
 
-#if 1
   StartGameActions(FALSE, setup.autorecord, new_random_seed);
-#else
-  if (setup.autorecord)
-    TapeStartRecording();
-
-  if (tape.recording)
-    tape.random_seed = new_random_seed;
-
-  InitRND(new_random_seed);
-
-  game_status = GAME_MODE_PLAYING;
-  InitGame();
-#endif
 }
 
 static void Handle_OP_PAUSE_PLAYING()
@@ -553,8 +653,11 @@ static void Handle_OP_PAUSE_PLAYING()
   printf("OP_PAUSE_PLAYING: %d\n", buffer[0]);
   Error(ERR_NETWORK_CLIENT, "client %d pauses game", buffer[0]);
 
-  tape.pausing = TRUE;
-  DrawVideoDisplay(VIDEO_STATE_PAUSE_ON,0);
+  if (game_status == GAME_MODE_PLAYING)
+  {
+    tape.pausing = TRUE;
+    DrawVideoDisplay(VIDEO_STATE_PAUSE_ON,0);
+  }
 }
 
 static void Handle_OP_CONTINUE_PLAYING()
@@ -562,17 +665,39 @@ static void Handle_OP_CONTINUE_PLAYING()
   printf("OP_CONTINUE_PLAYING: %d\n", buffer[0]);
   Error(ERR_NETWORK_CLIENT, "client %d continues game", buffer[0]);
 
-  tape.pausing = FALSE;
-  DrawVideoDisplay(VIDEO_STATE_PAUSE_OFF,0);
+  if (game_status == GAME_MODE_PLAYING)
+  {
+    tape.pausing = FALSE;
+    DrawVideoDisplay(VIDEO_STATE_PAUSE_OFF,0);
+  }
 }
 
 static void Handle_OP_STOP_PLAYING()
 {
-  printf("OP_STOP_PLAYING: %d\n", buffer[0]);
-  Error(ERR_NETWORK_CLIENT, "client %d stops game", buffer[0]);
+  printf("OP_STOP_PLAYING: %d [%d]\n", buffer[0], buffer[2]);
+  Error(ERR_NETWORK_CLIENT, "client %d stops game [%d]", buffer[0], buffer[2]);
+
+  if (game_status == GAME_MODE_PLAYING)
+  {
+    int client_nr = buffer[0];
+    int index_nr = client_nr - 1;
+    struct PlayerInfo *client_player = &stored_player[index_nr];
+    boolean stopped_by_remote_player = (!client_player->connected_locally);
+    char message[100];
+
+    sprintf(message, (buffer[2] == NETWORK_STOP_BY_PLAYER ?
+                     "Network game stopped by player %d!" :
+                     buffer[2] == NETWORK_STOP_BY_ERROR ?
+                     "Network game stopped due to internal error!" :
+                     "Network game stopped!"), client_nr);
+
+    if (buffer[2] != NETWORK_STOP_BY_PLAYER || stopped_by_remote_player)
+      Request(message, REQ_CONFIRM | REQ_STAY_CLOSED);
+
+    SetGameStatus(GAME_MODE_MAIN);
 
-  game_status = GAME_MODE_MAIN;
-  DrawMainMenu();
+    DrawMainMenu();
+  }
 }
 
 static void Handle_OP_MOVE_PLAYER(unsigned int len)
@@ -588,16 +713,20 @@ static void Handle_OP_MOVE_PLAYER(unsigned int len)
 
   if (server_frame_counter != FrameCounter)
   {
-    Error(ERR_RETURN, "client and servers frame counters out of sync");
-    Error(ERR_RETURN, "frame counter of client is %d", FrameCounter);
-    Error(ERR_RETURN, "frame counter of server is %d", server_frame_counter);
-    Error(ERR_EXIT,   "this should not happen -- please debug");
+    Error(ERR_INFO, "client and servers frame counters out of sync");
+    Error(ERR_INFO, "frame counter of client is %d", FrameCounter);
+    Error(ERR_INFO, "frame counter of server is %d", server_frame_counter);
+    Error(ERR_INFO, "this should not happen -- please debug");
+
+    stop_network_game = TRUE;
+
+    return;
   }
 
   /* copy valid player actions */
   for (i = 0; i < MAX_PLAYERS; i++)
     stored_player[i].effective_action =
-      (i < len - 6 && stored_player[i].active ? buffer[6 + i] : 0);
+      (i < len - 6 ? buffer[6 + i] : 0);
 
   network_player_action_received = TRUE;
 }
@@ -606,6 +735,8 @@ static void HandleNetworkingMessages()
 {
   unsigned int message_length;
 
+  stop_network_game = FALSE;
+
   while (nread >= 4 && nread >= 4 + readbuffer[3])
   {
     message_length = readbuffer[3];
@@ -616,7 +747,7 @@ static void HandleNetworkingMessages()
     nread -= 4 + message_length;
     memmove(readbuffer, readbuffer + 4 + message_length, nread);
 
-    switch(buffer[1])
+    switch (buffer[1])
     {
       case OP_BAD_PROTOCOL_VERSION:
        Handle_OP_BAD_PROTOCOL_VERSION();
@@ -670,62 +801,116 @@ static void HandleNetworkingMessages()
   }
 
   fflush(stdout);
+
+  /* in case of internal error, stop network game */
+  if (stop_network_game)
+    SendToServer_StopPlaying(NETWORK_STOP_BY_ERROR);
 }
 
-/* TODO */
+static char *HandleNetworkingPackets()
+{
+  while (1)
+  {
+    /* ---------- check network server for activity ---------- */
+
+    int num_active_sockets = SDLNet_CheckSockets(rfds, 1);
 
-void HandleNetworking()
+    if (num_active_sockets < 0)
+      return "Error checking network sockets!";
+
+    if (num_active_sockets == 0)
+      break;   // no active sockets, stop here
+
+    /* ---------- read packets from network server ---------- */
+
+    int num_bytes = SDLNet_TCP_Recv(sfd, readbuffer + nread, 1);
+
+    if (num_bytes < 0)
+      return "Error reading from network server!";
+
+    if (num_bytes == 0)
+      return "Connection to network server lost!";
+
+    nread += num_bytes;
+
+    HandleNetworkingMessages();
+
+    if (stop_network_client)
+      return stop_network_client_message;
+  }
+
+  return NULL;
+}
+
+static void FreeNetworkClientPlayerInfo(struct NetworkClientPlayerInfo *player)
 {
-#if !defined(TARGET_SDL)
-  static struct timeval tv = { 0, 0 };
-  fd_set rfds;
-#endif
-  int r = 0;
+  if (player == NULL)
+    return;
 
-  do
-  {
-#if defined(TARGET_SDL)
-    if ((r = SDLNet_CheckSockets(rfds, 1)) < 0)
-      Error(ERR_EXIT, "HandleNetworking(): SDLNet_CheckSockets() failed");
+  if (player->next)
+    FreeNetworkClientPlayerInfo(player->next);
 
-#else
+  checked_free(player);
+}
 
-    FD_ZERO(&rfds);
-    FD_SET(sfd, &rfds);
+static void HandleNetworkingDisconnect()
+{
+  int i;
 
-    r = select(sfd + 1, &rfds, NULL, NULL, &tv);
+  SDLNet_TCP_DelSocket(rfds, sfd);
+  SDLNet_TCP_Close(sfd);
 
-    if (r < 0 && errno != EINTR)
-      Error(ERR_EXIT, "HandleNetworking(): select() failed");
+  network_playing = FALSE;
 
-    if (r < 0)
-      FD_ZERO(&rfds);
-#endif
+  network.enabled = FALSE;
+  network.connected = FALSE;
 
-#if defined(TARGET_SDL)
-    if (r > 0)
-#else
-    if (FD_ISSET(sfd, &rfds))
-#endif
-    {
-#if defined(TARGET_SDL)
-      r = SDLNet_TCP_Recv(sfd, readbuffer + nread, 1);
-#else
-      r = read(sfd, readbuffer + nread, MAX_BUFFER_SIZE - nread);
-#endif
+  setup.network_mode = FALSE;
+
+  for (i = 0; i < MAX_PLAYERS; i++)
+    stored_player[i].connected_network = FALSE;
+
+  FreeNetworkClientPlayerInfo(first_player.next);
+
+  first_player.nr = 0;
+  first_player.next = NULL;
+}
 
-      if (r < 0)
-       Error(ERR_EXIT, "error reading from network server");
+void HandleNetworking()
+{
+  char *error_message = HandleNetworkingPackets();
 
-      if (r == 0)
-       Error(ERR_EXIT, "connection to network server lost");
+  if (error_message != NULL)
+  {
+    HandleNetworkingDisconnect();
 
-      nread += r;
+    if (game_status == GAME_MODE_PLAYING)
+    {
+      Request(error_message, REQ_CONFIRM | REQ_STAY_CLOSED);
 
-      HandleNetworkingMessages();
+      SetGameStatus(GAME_MODE_MAIN);
+
+      DrawMainMenu();
+    }
+    else
+    {
+      Request(error_message, REQ_CONFIRM);
+
+      if (game_status == GAME_MODE_MAIN)
+       ClearNetworkPlayers();
     }
   }
-  while (r > 0);
 }
 
-#endif /* PLATFORM_UNIX */
+void DisconnectFromNetworkServer()
+{
+  DrawNetworkText_Title("Terminating Network");
+  DrawNetworkText("Disconnecting from network server ...");
+
+  HandleNetworkingDisconnect();
+
+  DrawNetworkText_Success("Successfully disconnected!");
+
+  /* short time to recognize result of network initialization */
+  Delay_WithScreenUpdates(1000);
+}