changed build system for Android from Ant to Gradle
[rocksndiamonds.git] / src / network.c
1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // network.c
10 // ============================================================================
11
12 #include <signal.h>
13 #include <sys/time.h>
14
15 #include "libgame/libgame.h"
16
17 #include "network.h"
18 #include "netserv.h"
19 #include "main.h"
20 #include "game.h"
21 #include "tape.h"
22 #include "files.h"
23 #include "tools.h"
24 #include "screens.h"
25 #include "init.h"
26
27 struct NetworkClientPlayerInfo
28 {
29   byte nr;
30   char name[MAX_PLAYER_NAME_LEN + 1];
31   struct NetworkClientPlayerInfo *next;
32 };
33
34 static struct NetworkClientPlayerInfo first_player =
35 {
36   0,
37   EMPTY_PLAYER_NAME,
38   NULL
39 };
40
41 // server stuff
42
43 static TCPsocket sfd;           // TCP server socket
44 static UDPsocket udp;           // UDP server socket
45 static SDLNet_SocketSet rfds;   // socket set
46
47 static struct NetworkBuffer *read_buffer = NULL;
48 static struct NetworkBuffer *write_buffer = NULL;
49
50 static boolean stop_network_game = FALSE;
51 static boolean stop_network_client = FALSE;
52 static char stop_network_client_message[MAX_OUTPUT_LINESIZE + 1];
53
54 static struct NetworkLevelInfo network_level;
55
56 static void DrawNetworkTextExt(char *message, int font_nr, boolean initialize)
57 {
58   static int xpos = 0, ypos = 0;
59   static int max_line_width = 0;
60   int font_width = getFontWidth(font_nr);
61   int font_height = getFontHeight(font_nr);
62   int ypos_1 = 120;
63   int ypos_2 = 150;
64
65   if (initialize)
66   {
67     if (game_status == GAME_MODE_LOADING)
68     {
69       max_line_width = WIN_XSIZE;
70
71       xpos = (max_line_width - getTextWidth(message, font_nr)) / 2;
72       ypos = ypos_1;
73
74       DrawText(xpos, ypos, message, font_nr);
75
76       xpos = 0;
77       ypos = ypos_2;
78     }
79     else
80     {
81       max_line_width = SXSIZE;
82
83       DrawTextSCentered(ypos_1, font_nr, message);
84
85       // calculate offset to x position caused by rounding
86       int max_chars_per_line = max_line_width / font_width;
87       int xoffset = (max_line_width - max_chars_per_line * font_width) / 2;
88
89       xpos = SX + xoffset;
90       ypos = SY + ypos_2;
91     }
92
93     Error(ERR_DEBUG, "========== %s ==========", message);
94   }
95   else
96   {
97     int max_chars_per_line = max_line_width / font_width;
98     int max_lines_per_text = 10;
99     int num_lines_spacing = (font_nr == FC_YELLOW ? 1 : 3);
100     int num_lines_printed = DrawTextBuffer(xpos, ypos, message, font_nr,
101                                            max_chars_per_line, -1,
102                                            max_lines_per_text, 0, -1,
103                                            TRUE, TRUE, FALSE);
104
105     ypos += (num_lines_printed + num_lines_spacing) * font_height;
106
107     Error(ERR_DEBUG, "%s", message);
108   }
109
110   BackToFront();
111 }
112
113 static void DrawNetworkText(char *message)
114 {
115   DrawNetworkTextExt(message, FC_YELLOW, FALSE);
116 }
117
118 static void DrawNetworkText_Success(char *message)
119 {
120   DrawNetworkTextExt(message, FC_GREEN, FALSE);
121 }
122
123 static void DrawNetworkText_Failed(char *message)
124 {
125   DrawNetworkTextExt(message, FC_RED, FALSE);
126 }
127
128 static void DrawNetworkText_Title(char *message)
129 {
130   DrawNetworkTextExt(message, FC_GREEN, TRUE);
131 }
132
133 static void SendNetworkBufferToServer(struct NetworkBuffer *nb)
134 {
135   if (!network.enabled)
136     return;
137
138   // set message length header
139   putNetwork32BitInteger(nb->buffer, nb->size - 4);
140
141   // directly send the buffer to the network server
142   SDLNet_TCP_Send(sfd, nb->buffer, nb->size);
143 }
144
145 static struct NetworkClientPlayerInfo *getNetworkPlayer(int player_nr)
146 {
147   struct NetworkClientPlayerInfo *player = NULL;
148
149   for (player = &first_player; player; player = player->next)
150     if (player->nr == player_nr)
151       break;
152
153   if (player == NULL)   // should not happen
154     Error(ERR_EXIT, "protocol error: reference to non-existing player %d",
155           player_nr);
156
157   return player;
158 }
159
160 char *getNetworkPlayerName(int player_nr)
161 {
162   struct NetworkClientPlayerInfo *player;
163
164   if (player_nr == 0)
165     return("the network game server");
166   else if (player_nr == first_player.nr)
167     return("you");
168   else
169     for (player = &first_player; player; player = player->next)
170       if (player->nr == player_nr && strlen(player->name) > 0)
171         return(player->name);
172
173   return(EMPTY_PLAYER_NAME);
174 }
175
176 boolean hasStartedNetworkGame(void)
177 {
178   return !network_level.use_network_level_files;
179 }
180
181 static boolean hasPathSeparator(char *s)
182 {
183   return (strchr(s, '/') != NULL);
184 }
185
186 static void StartNetworkServer(int port)
187 {
188   static int p;
189
190   p = port;
191
192   server_thread = SDL_CreateThread(NetworkServerThread,
193                                    "NetworkServerThread", &p);
194   network_server = TRUE;
195 }
196
197 boolean ConnectToServer(char *hostname, int port)
198 {
199   IPaddress ip;
200   int server_host = 0;
201   int i;
202
203   if (read_buffer == NULL)
204     read_buffer = newNetworkBuffer();
205
206   if (write_buffer == NULL)
207     write_buffer = newNetworkBuffer();
208
209   DrawNetworkText_Title("Initializing Network");
210
211   if (port == 0)
212     port = DEFAULT_SERVER_PORT;
213
214   if (hostname == NULL)
215   {
216     // if no hostname given, try to auto-detect network server in local network
217     // by doing a UDP broadcast on the network server port and wait for answer
218
219     SDLNet_SocketSet udp_socket_set = SDLNet_AllocSocketSet(1);
220     if (!udp_socket_set)
221       Error(ERR_EXIT, "SDLNet_AllocSocketSet() failed: %s"), SDLNet_GetError();
222
223     udp = SDLNet_UDP_Open(0);
224     if (!udp)
225       Error(ERR_EXIT, "SDLNet_UDP_Open() failed: %s", SDLNet_GetError());
226
227     if (SDLNet_UDP_AddSocket(udp_socket_set, udp) == -1)
228       Error(ERR_EXIT_NETWORK_SERVER, "SDLNet_TCP_AddSocket() failed: %s"),
229         SDLNet_GetError();
230
231     char *data_ptr = "network server UDB broadcast";
232     int data_len = strlen(data_ptr) + 1;
233     IPaddress ip_address;
234
235     SDLNet_Write32(0xffffffff, &ip_address.host);       // 255.255.255.255
236     SDLNet_Write16(port,       &ip_address.port);
237
238     UDPpacket packet =
239     {
240       -1,
241       (Uint8 *)data_ptr,
242       data_len,
243       data_len,
244       0,
245       ip_address
246     };
247
248     SDLNet_UDP_Send(udp, -1, &packet);
249
250     DrawNetworkText("Looking for nearby network server ...");
251
252     // wait for any nearby network server to answer UDP broadcast
253     for (i = 0; i < 5; i++)
254     {
255       if (SDLNet_CheckSockets(udp_socket_set, 0) == 1)
256       {
257         int num_packets = SDLNet_UDP_Recv(udp, &packet);
258
259         if (num_packets == 1)
260         {
261           char message[100];
262
263           server_host = SDLNet_Read32(&packet.address.host);
264
265           sprintf(message, "Network server found at %d.%d.%d.%d!",
266                   (server_host >> 24) & 0xff,
267                   (server_host >> 16) & 0xff,
268                   (server_host >>  8) & 0xff,
269                   (server_host >>  0) & 0xff);
270
271           DrawNetworkText_Success(message);
272         }
273         else
274         {
275           DrawNetworkText_Failed("No answer from network server!");
276         }
277
278         break;
279       }
280       else
281       {
282         Delay_WithScreenUpdates(100);
283       }
284     }
285
286     if (server_host == 0)
287       DrawNetworkText_Failed("No nearby network server found!");
288   }
289
290   rfds = SDLNet_AllocSocketSet(1);
291
292   if (hostname)
293   {
294     char message[100];
295
296     SDLNet_ResolveHost(&ip, hostname, port);
297
298     if (ip.host == INADDR_NONE)
299     {
300       sprintf(message, "Failed to resolve network server hostname '%s'!",
301               hostname);
302
303       DrawNetworkText_Failed(message);
304
305       return FALSE;
306     }
307     else
308     {
309       server_host = SDLNet_Read32(&ip.host);
310     }
311
312     sprintf(message, "Connecting to network server host %s ...", hostname);
313
314     DrawNetworkText(message);
315   }
316   else
317   {
318     // if no hostname was given and no network server was auto-detected in the
319     // local network, try to connect to a network server at the local host
320     if (server_host == 0)
321     {
322       server_host = 0x7f000001;                 // 127.0.0.1
323
324       DrawNetworkText("Looking for local network server ...");
325     }
326     else
327     {
328       DrawNetworkText("Connecting to network server ...");
329     }
330
331     SDLNet_Write32(server_host, &ip.host);
332     SDLNet_Write16(port,        &ip.port);
333   }
334
335   Error(ERR_DEBUG, "trying to connect to network server at %d.%d.%d.%d ...",
336         (server_host >> 24) & 0xff,
337         (server_host >> 16) & 0xff,
338         (server_host >>  8) & 0xff,
339         (server_host >>  0) & 0xff);
340
341   sfd = SDLNet_TCP_Open(&ip);
342
343   if (sfd)
344   {
345     SDLNet_TCP_AddSocket(rfds, sfd);
346
347     DrawNetworkText_Success("Successfully connected!");
348
349     return TRUE;
350   }
351   else
352   {
353     if (hostname)
354       DrawNetworkText_Failed("Failed to connect to network server!");
355     else
356       DrawNetworkText_Failed("No local network server found!");
357
358     printf("SDLNet_TCP_Open(): %s\n", SDLNet_GetError());
359   }
360
361   if (hostname)                 // connect to specified server failed
362     return FALSE;
363
364   DrawNetworkText("Starting new local network server ...");
365
366   StartNetworkServer(port);
367
368   // wait for server to start up and try connecting several times
369   for (i = 0; i < 30; i++)
370   {
371     if ((sfd = SDLNet_TCP_Open(&ip)))           // connected
372     {
373       DrawNetworkText_Success("Successfully connected to newly started network server!");
374
375       SDLNet_TCP_AddSocket(rfds, sfd);
376
377       return TRUE;
378     }
379
380     Delay_WithScreenUpdates(100);
381   }
382
383   DrawNetworkText_Failed("Failed to connect to newly started network server!");
384
385   // when reaching this point, connect to newly started server has failed
386   return FALSE;
387 }
388
389 void SendToServer_PlayerName(char *player_name)
390 {
391   initNetworkBufferForWriting(write_buffer, OP_PLAYER_NAME, 0);
392
393   putNetworkBufferString(write_buffer, player_name);
394
395   SendNetworkBufferToServer(write_buffer);
396
397   Error(ERR_NETWORK_CLIENT, "you set your player name to \"%s\"", player_name);
398 }
399
400 void SendToServer_ProtocolVersion(void)
401 {
402   initNetworkBufferForWriting(write_buffer, OP_PROTOCOL_VERSION, 0);
403
404   putNetworkBuffer8BitInteger(write_buffer, PROTOCOL_VERSION_MAJOR);
405   putNetworkBuffer8BitInteger(write_buffer, PROTOCOL_VERSION_MINOR);
406   putNetworkBuffer8BitInteger(write_buffer, PROTOCOL_VERSION_PATCH);
407
408   SendNetworkBufferToServer(write_buffer);
409 }
410
411 void SendToServer_NrWanted(int nr_wanted)
412 {
413   initNetworkBufferForWriting(write_buffer, OP_NUMBER_WANTED, 0);
414
415   putNetworkBuffer8BitInteger(write_buffer, nr_wanted);
416
417   SendNetworkBufferToServer(write_buffer);
418 }
419
420 void SendToServer_LevelFile(void)
421 {
422   initNetworkBufferForWriting(write_buffer, OP_LEVEL_FILE, 0);
423
424   putNetworkBufferString(      write_buffer, leveldir_current->identifier);
425   putNetworkBuffer16BitInteger(write_buffer, level.file_info.nr);
426   putNetworkBuffer8BitInteger( write_buffer, level.file_info.type);
427   putNetworkBuffer8BitInteger( write_buffer, level.file_info.packed);
428   putNetworkBufferString(      write_buffer, level.file_info.basename);
429   putNetworkBufferFile(        write_buffer, level.file_info.filename);
430   putNetworkBuffer8BitInteger( write_buffer, level.use_custom_template);
431
432   if (level.use_custom_template)
433   {
434     putNetworkBufferString(write_buffer, level_template.file_info.basename);
435     putNetworkBufferFile(  write_buffer, level_template.file_info.filename);
436   }
437
438   SendNetworkBufferToServer(write_buffer);
439
440   setString(&network_level.leveldir_identifier, leveldir_current->identifier);
441
442   // the sending client does not use network level files (but the real ones)
443   network_level.use_network_level_files = FALSE;
444
445 #if 0
446   printf("::: '%s'\n", leveldir_current->identifier);
447   printf("::: '%d'\n", level.file_info.nr);
448   printf("::: '%d'\n", level.file_info.type);
449   printf("::: '%d'\n", level.file_info.packed);
450   printf("::: '%s'\n", level.file_info.basename);
451   printf("::: '%s'\n", level.file_info.filename);
452
453   if (level.use_custom_template)
454     printf("::: '%s'\n", level_template.file_info.filename);
455 #endif
456 }
457
458 void SendToServer_StartPlaying(void)
459 {
460   unsigned int new_random_seed = InitRND(level.random_seed);
461
462   initNetworkBufferForWriting(write_buffer, OP_START_PLAYING, 0);
463
464   putNetworkBufferString(      write_buffer, leveldir_current->identifier);
465   putNetworkBuffer16BitInteger(write_buffer, level_nr);
466   putNetworkBuffer32BitInteger(write_buffer, new_random_seed);
467
468   SendNetworkBufferToServer(write_buffer);
469 }
470
471 void SendToServer_PausePlaying(void)
472 {
473   initNetworkBufferForWriting(write_buffer, OP_PAUSE_PLAYING, 0);
474
475   SendNetworkBufferToServer(write_buffer);
476 }
477
478 void SendToServer_ContinuePlaying(void)
479 {
480   initNetworkBufferForWriting(write_buffer, OP_CONTINUE_PLAYING, 0);
481
482   SendNetworkBufferToServer(write_buffer);
483 }
484
485 void SendToServer_StopPlaying(int cause_for_stopping)
486 {
487   initNetworkBufferForWriting(write_buffer, OP_STOP_PLAYING, 0);
488
489   putNetworkBuffer8BitInteger(write_buffer, cause_for_stopping);
490
491   SendNetworkBufferToServer(write_buffer);
492 }
493
494 void SendToServer_MovePlayer(byte player_action)
495 {
496   initNetworkBufferForWriting(write_buffer, OP_MOVE_PLAYER, 0);
497
498   putNetworkBuffer8BitInteger(write_buffer, player_action);
499
500   SendNetworkBufferToServer(write_buffer);
501 }
502
503 static void Handle_OP_BAD_PROTOCOL_VERSION(void)
504 {
505   int protocol_version_major = getNetworkBuffer8BitInteger(read_buffer);
506   int protocol_version_minor = getNetworkBuffer8BitInteger(read_buffer);
507
508   Error(ERR_WARN, "protocol version mismatch");
509   Error(ERR_WARN, "server expects %d.%d.x instead of %d.%d.%d",
510         protocol_version_major,
511         protocol_version_minor,
512         PROTOCOL_VERSION_MAJOR,
513         PROTOCOL_VERSION_MINOR,
514         PROTOCOL_VERSION_PATCH);
515
516   sprintf(stop_network_client_message, "Network protocol version mismatch! Server expects version %d.%d.x instead of %d.%d.%d!",
517           protocol_version_major,
518           protocol_version_minor,
519           PROTOCOL_VERSION_MAJOR,
520           PROTOCOL_VERSION_MINOR,
521           PROTOCOL_VERSION_PATCH);
522
523   stop_network_client = TRUE;
524 }
525
526 static void Handle_OP_YOUR_NUMBER(void)
527 {
528   int old_client_nr = getNetworkBuffer8BitInteger(read_buffer);
529   int new_client_nr = getNetworkBuffer8BitInteger(read_buffer);
530   int new_index_nr = new_client_nr - 1;
531   struct PlayerInfo *old_local_player = local_player;
532   struct PlayerInfo *new_local_player = &stored_player[new_index_nr];
533
534   printf("OP_YOUR_NUMBER: %d\n", old_client_nr);
535   first_player.nr = new_client_nr;
536
537   if (old_local_player != new_local_player)
538   {
539     // set relevant player settings and change to new player
540
541     local_player = new_local_player;
542
543     old_local_player->connected_locally = FALSE;
544     new_local_player->connected_locally = TRUE;
545
546     old_local_player->connected_network = FALSE;
547     new_local_player->connected_network = TRUE;
548   }
549
550   if (first_player.nr > MAX_PLAYERS)
551     Error(ERR_EXIT, "sorry, more than %d players not allowed", MAX_PLAYERS);
552
553   Error(ERR_NETWORK_CLIENT, "you get client # %d", new_client_nr);
554
555   stored_player[new_index_nr].connected_network = TRUE;
556 }
557
558 static void Handle_OP_NUMBER_WANTED(void)
559 {
560   int old_client_nr    = getNetworkBuffer8BitInteger(read_buffer);
561   int client_nr_wanted = getNetworkBuffer8BitInteger(read_buffer);
562   int new_client_nr    = getNetworkBuffer8BitInteger(read_buffer);
563   int old_index_nr = old_client_nr - 1;
564   int new_index_nr = new_client_nr - 1;
565   int index_nr_wanted = client_nr_wanted - 1;
566   struct PlayerInfo *old_player = &stored_player[old_index_nr];
567   struct PlayerInfo *new_player = &stored_player[new_index_nr];
568
569   printf("OP_NUMBER_WANTED: %d\n", old_client_nr);
570
571   if (new_client_nr == client_nr_wanted)        // switching succeeded
572   {
573     struct NetworkClientPlayerInfo *player;
574
575     if (old_client_nr != client_nr_wanted)      // client's nr has changed
576       Error(ERR_NETWORK_CLIENT, "client %d switches to # %d",
577             old_client_nr, new_client_nr);
578     else if (old_client_nr == first_player.nr)  // local player keeps his nr
579       Error(ERR_NETWORK_CLIENT, "keeping client # %d", new_client_nr);
580
581     if (old_client_nr != new_client_nr)
582     {
583       // set relevant player settings and change to new player
584
585       old_player->connected_network = FALSE;
586       new_player->connected_network = TRUE;
587     }
588
589     player = getNetworkPlayer(old_client_nr);
590     player->nr = new_client_nr;
591
592     if (old_player == local_player)             // local player switched
593     {
594       local_player = new_player;
595
596       old_player->connected_locally = FALSE;
597       new_player->connected_locally = TRUE;
598     }
599   }
600   else if (old_client_nr == first_player.nr)    // failed -- local player?
601   {
602     char request[100];
603
604     sprintf(request, "Sorry! Player %d already exists! You are player %d!",
605             index_nr_wanted + 1, new_index_nr + 1);
606
607     Request(request, REQ_CONFIRM);
608
609     Error(ERR_NETWORK_CLIENT, "cannot switch -- you keep client # %d",
610           new_client_nr);
611   }
612
613   if (game_status == GAME_MODE_MAIN)
614     DrawNetworkPlayers();
615 }
616
617 static void Handle_OP_PLAYER_NAME(void)
618 {
619   int player_nr = getNetworkBuffer8BitInteger(read_buffer);
620   char *player_name = getNetworkBufferString(read_buffer);
621   struct NetworkClientPlayerInfo *player = getNetworkPlayer(player_nr);
622
623   printf("OP_PLAYER_NAME: %d\n", player_nr);
624
625   strncpy(player->name, player_name, MAX_PLAYER_NAME_LEN);
626   player->name[MAX_PLAYER_NAME_LEN] = '\0';
627
628   Error(ERR_NETWORK_CLIENT, "client %d calls itself \"%s\"",
629         player_nr, player->name);
630 }
631
632 static void Handle_OP_PLAYER_CONNECTED(void)
633 {
634   struct NetworkClientPlayerInfo *player, *last_player = NULL;
635   int new_client_nr = getNetworkBuffer8BitInteger(read_buffer);
636   int new_index_nr = new_client_nr - 1;
637
638   printf("OP_PLAYER_CONNECTED: %d\n", new_client_nr);
639   Error(ERR_NETWORK_CLIENT, "new client %d connected", new_client_nr);
640
641   for (player = &first_player; player; player = player->next)
642   {
643     if (player->nr == new_client_nr)
644       Error(ERR_EXIT, "multiplayer server sent duplicate player id");
645
646     last_player = player;
647   }
648
649   last_player->next = player =
650     checked_malloc(sizeof(struct NetworkClientPlayerInfo));
651   player->nr = new_client_nr;
652   player->name[0] = '\0';
653   player->next = NULL;
654
655   stored_player[new_index_nr].connected_network = TRUE;
656 }
657
658 static void Handle_OP_PLAYER_DISCONNECTED(void)
659 {
660   struct NetworkClientPlayerInfo *player, *player_disconnected;
661   int player_nr = getNetworkBuffer8BitInteger(read_buffer);
662   int index_nr = player_nr - 1;
663
664   printf("OP_PLAYER_DISCONNECTED: %d\n", player_nr);
665   player_disconnected = getNetworkPlayer(player_nr);
666   Error(ERR_NETWORK_CLIENT, "client %d (%s) disconnected",
667         player_nr, getNetworkPlayerName(player_nr));
668
669   for (player = &first_player; player; player = player->next)
670     if (player->next == player_disconnected)
671       player->next = player_disconnected->next;
672   free(player_disconnected);
673
674   stored_player[index_nr].connected_locally = FALSE;
675   stored_player[index_nr].connected_network = FALSE;
676
677   if (game_status == GAME_MODE_PLAYING)
678   {
679     char message[100];
680
681     sprintf(message, "Player %d left network server! Network game stopped!",
682             player_nr);
683
684     Request(message, REQ_CONFIRM | REQ_STAY_CLOSED);
685
686     SetGameStatus(GAME_MODE_MAIN);
687
688     DrawMainMenu();
689   }
690   else if (game_status == GAME_MODE_MAIN)
691   {
692     DrawNetworkPlayers();
693   }
694 }
695
696 static void Handle_OP_START_PLAYING(void)
697 {
698   int player_nr = getNetworkBuffer8BitInteger(read_buffer);
699   char *new_leveldir_identifier = getNetworkBufferString(read_buffer);
700   int new_level_nr = getNetworkBuffer16BitInteger(read_buffer);
701   unsigned int new_random_seed = getNetworkBuffer32BitInteger(read_buffer);
702
703   if (!strEqual(new_leveldir_identifier, network_level.leveldir_identifier))
704   {
705     Error(ERR_WARN, "no such level identifier: '%s'", new_leveldir_identifier);
706
707     stop_network_game = TRUE;
708
709     return;
710   }
711
712   printf("OP_START_PLAYING: %d\n", player_nr);
713   Error(ERR_NETWORK_CLIENT,
714         "client %d starts game [level %d from level identifier '%s']\n",
715         player_nr, new_level_nr, new_leveldir_identifier);
716
717   LevelDirTree *new_leveldir =
718     getTreeInfoFromIdentifier(leveldir_first, new_leveldir_identifier);
719
720   if (new_leveldir != NULL)
721   {
722     leveldir_current = new_leveldir;
723     level_nr = new_level_nr;
724   }
725
726   // needed if level set of network game changed graphics, sounds or music
727   ReloadCustomArtwork(0);
728
729   TapeErase();
730
731   if (network_level.use_network_level_files)
732     LoadNetworkLevel(&network_level);
733   else
734     LoadLevel(level_nr);
735
736   StartGameActions(FALSE, setup.autorecord, new_random_seed);
737 }
738
739 static void Handle_OP_PAUSE_PLAYING(void)
740 {
741   int player_nr = getNetworkBuffer8BitInteger(read_buffer);
742
743   printf("OP_PAUSE_PLAYING: %d\n", player_nr);
744   Error(ERR_NETWORK_CLIENT, "client %d pauses game", player_nr);
745
746   if (game_status == GAME_MODE_PLAYING)
747   {
748     tape.pausing = TRUE;
749     DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
750   }
751 }
752
753 static void Handle_OP_CONTINUE_PLAYING(void)
754 {
755   int player_nr = getNetworkBuffer8BitInteger(read_buffer);
756
757   printf("OP_CONTINUE_PLAYING: %d\n", player_nr);
758   Error(ERR_NETWORK_CLIENT, "client %d continues game", player_nr);
759
760   if (game_status == GAME_MODE_PLAYING)
761   {
762     tape.pausing = FALSE;
763     DrawVideoDisplay(VIDEO_STATE_PAUSE_OFF, 0);
764   }
765 }
766
767 static void Handle_OP_STOP_PLAYING(void)
768 {
769   int client_nr = getNetworkBuffer8BitInteger(read_buffer);
770   int cause_for_stopping = getNetworkBuffer8BitInteger(read_buffer);
771
772   printf("OP_STOP_PLAYING: %d [%d]\n", client_nr, cause_for_stopping);
773   Error(ERR_NETWORK_CLIENT, "client %d stops game [%d]",
774         client_nr, cause_for_stopping);
775
776   if (game_status == GAME_MODE_PLAYING)
777   {
778     int index_nr = client_nr - 1;
779     struct PlayerInfo *client_player = &stored_player[index_nr];
780     boolean stopped_by_remote_player = (!client_player->connected_locally);
781     char message[100];
782
783     if (cause_for_stopping == NETWORK_STOP_BY_PLAYER)
784       sprintf(message, "Network game stopped by player %d!", client_nr);
785     else
786       sprintf(message, (cause_for_stopping == NETWORK_STOP_BY_ERROR ?
787                         "Network game stopped due to internal error!" :
788                         "Network game stopped!"));
789
790     if (cause_for_stopping != NETWORK_STOP_BY_PLAYER ||
791         stopped_by_remote_player)
792       Request(message, REQ_CONFIRM | REQ_STAY_CLOSED);
793
794     SetGameStatus(GAME_MODE_MAIN);
795
796     DrawMainMenu();
797   }
798 }
799
800 static void Handle_OP_MOVE_PLAYER(void)
801 {
802   int player_nr = getNetworkBuffer8BitInteger(read_buffer);
803   int server_frame_counter = getNetworkBuffer32BitInteger(read_buffer);
804   int i;
805
806   if (!network_playing)
807     return;
808
809   if (server_frame_counter != FrameCounter)
810   {
811     Error(ERR_INFO, "frame counters of client %d and server out of sync",
812           player_nr);
813     Error(ERR_INFO, "frame counter of client is %d", FrameCounter);
814     Error(ERR_INFO, "frame counter of server is %d", server_frame_counter);
815     Error(ERR_INFO, "this should not happen -- please debug");
816
817     stop_network_game = TRUE;
818
819     return;
820   }
821
822   // copy valid player actions (will be set to 0 for not connected players)
823   for (i = 0; i < MAX_PLAYERS; i++)
824     stored_player[i].effective_action =
825       getNetworkBuffer8BitInteger(read_buffer);
826
827   network_player_action_received = TRUE;
828 }
829
830 static void Handle_OP_BROADCAST_MESSAGE(void)
831 {
832   int player_nr = getNetworkBuffer8BitInteger(read_buffer);
833
834   printf("OP_BROADCAST_MESSAGE: %d\n", player_nr);
835   Error(ERR_NETWORK_CLIENT, "client %d sends message", player_nr);
836 }
837
838 static void Handle_OP_LEVEL_FILE(void)
839 {
840   int player_nr = getNetworkBuffer8BitInteger(read_buffer);
841   char *leveldir_identifier;
842   char *network_level_dir;
843   struct LevelFileInfo *file_info = &network_level.file_info;
844   struct LevelFileInfo *tmpl_info = &network_level.tmpl_info;
845   boolean use_custom_template;
846
847   setString(&network_level.leveldir_identifier, NULL);
848   setString(&network_level.file_info.basename,  NULL);
849   setString(&network_level.file_info.filename,  NULL);
850   setString(&network_level.tmpl_info.basename,  NULL);
851   setString(&network_level.tmpl_info.filename,  NULL);
852
853   printf("OP_LEVEL_FILE: %d\n", player_nr);
854
855   leveldir_identifier = getStringCopy(getNetworkBufferString(read_buffer));
856
857   if (hasPathSeparator(leveldir_identifier))
858     Error(ERR_EXIT, "protocol error: invalid filename from network client");
859
860   InitNetworkLevelDirectory(leveldir_identifier);
861
862   network_level_dir   = getNetworkLevelDir(leveldir_identifier);
863
864   file_info->nr       = getNetworkBuffer16BitInteger(read_buffer);
865   file_info->type     = getNetworkBuffer8BitInteger(read_buffer);
866   file_info->packed   = getNetworkBuffer8BitInteger(read_buffer);
867   file_info->basename = getStringCopy(getNetworkBufferString(read_buffer));
868   file_info->filename = getPath2(network_level_dir, file_info->basename);
869
870   if (hasPathSeparator(file_info->basename))
871     Error(ERR_EXIT, "protocol error: invalid filename from network client");
872
873   int num_bytes = getNetworkBufferFile(read_buffer, file_info->filename);
874
875   // if received level file is empty, remove it (as being non-existent)
876   if (num_bytes == 0)
877     remove(file_info->filename);
878
879   use_custom_template = getNetworkBuffer8BitInteger(read_buffer);
880   if (use_custom_template)
881   {
882     *tmpl_info = *file_info;
883
884     tmpl_info->basename = getStringCopy(getNetworkBufferString(read_buffer));
885     tmpl_info->filename = getPath2(network_level_dir, tmpl_info->basename);
886
887     if (hasPathSeparator(tmpl_info->basename))
888       Error(ERR_EXIT, "protocol error: invalid filename from network client");
889
890     getNetworkBufferFile(read_buffer, tmpl_info->filename);
891
892     // if received level file is empty, use level template file instead
893     if (num_bytes == 0)
894       setString(&file_info->filename,  tmpl_info->filename);
895   }
896
897   network_level.leveldir_identifier = leveldir_identifier;
898   network_level.use_custom_template = use_custom_template;
899
900   // the receiving client(s) use(s) the transferred network level files
901   network_level.use_network_level_files = TRUE;
902
903 #if 0
904   printf("::: '%s'\n", leveldir_identifier);
905   printf("::: '%d'\n", file_info->nr);
906   printf("::: '%d'\n", file_info->type);
907   printf("::: '%d'\n", file_info->packed);
908   printf("::: '%s'\n", file_info->basename);
909   printf("::: '%s'\n", file_info->filename);
910
911   if (use_custom_template)
912     printf("::: '%s'\n", tmpl_info->filename);
913 #endif
914 }
915
916 static void HandleNetworkingMessage(void)
917 {
918   stop_network_game = FALSE;
919
920   initNetworkBufferForReading(read_buffer);
921
922   int message_type = getNetworkBuffer8BitInteger(read_buffer);
923
924   switch (message_type)
925   {
926     case OP_BAD_PROTOCOL_VERSION:
927       Handle_OP_BAD_PROTOCOL_VERSION();
928       break;
929
930     case OP_YOUR_NUMBER:
931       Handle_OP_YOUR_NUMBER();
932       break;
933
934     case OP_NUMBER_WANTED:
935       Handle_OP_NUMBER_WANTED();
936       break;
937
938     case OP_PLAYER_NAME:
939       Handle_OP_PLAYER_NAME();
940       break;
941
942     case OP_PLAYER_CONNECTED:
943       Handle_OP_PLAYER_CONNECTED();
944       break;
945
946     case OP_PLAYER_DISCONNECTED:
947       Handle_OP_PLAYER_DISCONNECTED();
948       break;
949
950     case OP_START_PLAYING:
951       Handle_OP_START_PLAYING();
952       break;
953
954     case OP_PAUSE_PLAYING:
955       Handle_OP_PAUSE_PLAYING();
956       break;
957
958     case OP_CONTINUE_PLAYING:
959       Handle_OP_CONTINUE_PLAYING();
960       break;
961
962     case OP_STOP_PLAYING:
963       Handle_OP_STOP_PLAYING();
964       break;
965
966     case OP_MOVE_PLAYER:
967       Handle_OP_MOVE_PLAYER();
968       break;
969
970     case OP_BROADCAST_MESSAGE:
971       Handle_OP_BROADCAST_MESSAGE();
972       break;
973
974     case OP_LEVEL_FILE:
975       Handle_OP_LEVEL_FILE();
976       break;
977
978     default:
979       if (options.verbose)
980         Error(ERR_NETWORK_CLIENT,
981               "unknown opcode %d from server", message_type);
982   }
983
984   fflush(stdout);
985
986   // in case of internal error, stop network game
987   if (stop_network_game)
988     SendToServer_StopPlaying(NETWORK_STOP_BY_ERROR);
989 }
990
991 static char *HandleNetworkingPackets(void)
992 {
993   while (1)
994   {
995     // ---------- check network server for activity ----------
996
997     int num_active_sockets = SDLNet_CheckSockets(rfds, 0);
998
999     if (num_active_sockets < 0)
1000       return "Error checking network sockets!";
1001
1002     if (num_active_sockets == 0)
1003       break;    // no active sockets, stop here
1004
1005     // ---------- read packets from network server ----------
1006
1007     initNetworkBufferForReceiving(read_buffer);
1008
1009     int num_bytes = receiveNetworkBufferPacket(read_buffer, sfd);
1010
1011     if (num_bytes < 0)
1012       return "Error reading from network server!";
1013
1014     if (num_bytes == 0)
1015       return "Connection to network server lost!";
1016
1017     HandleNetworkingMessage();
1018
1019     if (stop_network_client)
1020       return stop_network_client_message;
1021   }
1022
1023   return NULL;
1024 }
1025
1026 static void FreeNetworkClientPlayerInfo(struct NetworkClientPlayerInfo *player)
1027 {
1028   if (player == NULL)
1029     return;
1030
1031   if (player->next)
1032     FreeNetworkClientPlayerInfo(player->next);
1033
1034   checked_free(player);
1035 }
1036
1037 static void HandleNetworkingDisconnect(void)
1038 {
1039   int i;
1040
1041   SDLNet_TCP_DelSocket(rfds, sfd);
1042   SDLNet_TCP_Close(sfd);
1043
1044   network_playing = FALSE;
1045
1046   network.enabled = FALSE;
1047   network.connected = FALSE;
1048
1049   setup.network_mode = FALSE;
1050
1051   for (i = 0; i < MAX_PLAYERS; i++)
1052     stored_player[i].connected_network = FALSE;
1053
1054   FreeNetworkClientPlayerInfo(first_player.next);
1055
1056   first_player.nr = 0;
1057   first_player.next = NULL;
1058 }
1059
1060 void HandleNetworking(void)
1061 {
1062   // do not handle any networking packets if request dialog is active
1063   if (game.request_active)
1064     return;
1065
1066   char *error_message = HandleNetworkingPackets();
1067
1068   if (error_message != NULL)
1069   {
1070     HandleNetworkingDisconnect();
1071
1072     if (game_status == GAME_MODE_PLAYING)
1073     {
1074       Request(error_message, REQ_CONFIRM | REQ_STAY_CLOSED);
1075
1076       SetGameStatus(GAME_MODE_MAIN);
1077
1078       DrawMainMenu();
1079     }
1080     else
1081     {
1082       Request(error_message, REQ_CONFIRM);
1083
1084       if (game_status == GAME_MODE_MAIN)
1085         ClearNetworkPlayers();
1086     }
1087   }
1088 }
1089
1090 void DisconnectFromNetworkServer(void)
1091 {
1092   DrawNetworkText_Title("Terminating Network");
1093   DrawNetworkText("Disconnecting from network server ...");
1094
1095   HandleNetworkingDisconnect();
1096
1097   DrawNetworkText_Success("Successfully disconnected!");
1098 }