rnd-20001205-1-src
[rocksndiamonds.git] / src / network.c
1 /***********************************************************
2 *  Rocks'n'Diamonds -- McDuffin Strikes Back!              *
3 *----------------------------------------------------------*
4 *  (c) 1995-98 Artsoft Entertainment                       *
5 *              Holger Schemel                              *
6 *              Oststrasse 11a                              *
7 *              33604 Bielefeld                             *
8 *              phone: ++49 +521 290471                     *
9 *              email: aeglos@valinor.owl.de                *
10 *----------------------------------------------------------*
11 *  network.c                                               *
12 ***********************************************************/
13
14 #include "libgame/libgame.h"
15
16 #if defined(PLATFORM_UNIX)
17
18 #include <signal.h>
19 #include <sys/time.h>
20 #include <sys/wait.h>
21 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <netinet/tcp.h>
24 #include <arpa/inet.h>
25 #include <netdb.h>
26
27 #if 0
28 #include "libgame/libgame.h"
29 #endif
30
31 #include "network.h"
32 #include "netserv.h"
33 #include "game.h"
34 #include "tape.h"
35 #include "files.h"
36 #include "tools.h"
37 #include "screens.h"
38
39 struct NetworkClientPlayerInfo
40 {
41   byte nr;
42   char name[MAX_PLAYER_NAME_LEN + 1];
43   struct NetworkClientPlayerInfo *next;
44 };
45
46 static struct NetworkClientPlayerInfo first_player =
47 {
48   0,
49   EMPTY_PLAYER_NAME,
50   NULL
51 };
52
53 /* server stuff */
54
55 static int sfd;
56 static byte realbuffer[512];
57 static byte readbuffer[MAX_BUFFER_SIZE], writbuffer[MAX_BUFFER_SIZE];
58 static byte *buffer = realbuffer + 4;
59 static int nread = 0, nwrite = 0;
60
61 static void SendBufferToServer(int size)
62 {
63   if (!options.network)
64     return;
65
66   realbuffer[0] = realbuffer[1] = realbuffer[2] = 0;
67   realbuffer[3] = (byte)size;
68   buffer[0] = 0;
69
70   if (nwrite + 4 + size >= MAX_BUFFER_SIZE)
71     Error(ERR_EXIT, "internal error: network send buffer overflow");
72
73   memcpy(writbuffer + nwrite, realbuffer, 4 + size);
74   nwrite += 4 + size;
75
76   /* directly send the buffer to the network server */
77   write(sfd, writbuffer, nwrite);
78   nwrite = 0;
79 }
80
81 struct NetworkClientPlayerInfo *getNetworkPlayer(int player_nr)
82 {
83   struct NetworkClientPlayerInfo *player = NULL;
84
85   for (player = &first_player; player; player = player->next)
86     if (player->nr == player_nr)
87       break;
88
89   if (player == NULL)   /* should not happen */
90     Error(ERR_EXIT, "protocol error: reference to non-existing player %d",
91           player_nr);
92
93   return player;
94 }
95
96 char *getNetworkPlayerName(int player_nr)
97 {
98   struct NetworkClientPlayerInfo *player;
99
100   if (player_nr == 0)
101     return("the network game server");
102   else if (player_nr == first_player.nr)
103     return("you");
104   else
105     for (player=&first_player; player; player=player->next)
106       if (player->nr == player_nr && player->name && strlen(player->name))
107         return(player->name);
108
109   return(EMPTY_PLAYER_NAME);
110 }
111
112 static void StartNetworkServer(int port)
113 {
114   switch (fork())
115   {
116     case 0:
117       NetworkServer(port, options.serveronly);
118
119       /* never reached */
120       exit(0);
121
122     case -1:
123       Error(ERR_WARN,
124             "cannot create network server process - no network playing");
125       options.network = FALSE;
126       return;
127
128     default:
129       /* we are parent process -- resume normal operation */
130       return;
131   }
132 }
133
134 boolean ConnectToServer(char *hostname, int port)
135 {
136   struct sockaddr_in s;
137   struct protoent *tcpproto;
138   int on = 1, i;
139
140   if (hostname)
141   {
142     if ((s.sin_addr.s_addr = inet_addr(hostname)) == -1)
143     {
144       struct hostent *host;
145
146       if ((host = gethostbyname(hostname)) == NULL)
147         Error(ERR_EXIT, "cannot locate host '%s'", hostname);
148
149       s.sin_addr = *(struct in_addr *)(host->h_addr_list[0]);
150     }
151   }
152   else
153     s.sin_addr.s_addr = inet_addr("127.0.0.1");         /* localhost */
154
155   if (port == 0)
156     port = DEFAULT_SERVER_PORT;
157
158   s.sin_port = htons(port);
159   s.sin_family = AF_INET;
160
161   sfd = socket(PF_INET, SOCK_STREAM, 0);
162   if (sfd < 0)
163     Error(ERR_EXIT, "out of file descriptors");
164
165   if ((tcpproto = getprotobyname("tcp")) != NULL)
166     setsockopt(sfd, tcpproto->p_proto, TCP_NODELAY, (char *)&on, sizeof(int));
167
168   if (connect(sfd, (struct sockaddr *)&s, sizeof(s)) == 0)      /* connected */
169     return TRUE;
170
171   if (hostname) /* connect to specified server failed */
172     return FALSE;
173
174   printf("No rocksndiamonds server on localhost - starting up one ...\n");
175   StartNetworkServer(port);
176
177   /* wait for server to start up and try connecting several times */
178   for (i=0; i<6; i++)
179   {
180     Delay(500);         /* wait 500 ms == 0.5 seconds */
181     close(sfd);
182
183     sfd = socket(PF_INET, SOCK_STREAM, 0);
184     if (sfd < 0)
185       Error(ERR_EXIT, "out of file descriptors");
186
187     setsockopt(sfd, tcpproto->p_proto, TCP_NODELAY, (char *)&on, sizeof(int));
188
189     if (connect(sfd, (struct sockaddr *)&s, sizeof(s)) >= 0)    /* connected */
190       return TRUE;
191   }
192
193   /* when reaching this point, connect to newly started server has failed */
194   return FALSE;
195 }
196
197 void SendToServer_PlayerName(char *player_name)
198 {
199   int len_player_name = strlen(player_name);
200
201   buffer[1] = OP_PLAYER_NAME;
202   memcpy(&buffer[2], player_name, len_player_name);
203   SendBufferToServer(2 + len_player_name);
204   Error(ERR_NETWORK_CLIENT, "you set your player name to \"%s\"", player_name);
205 }
206
207 void SendToServer_ProtocolVersion()
208 {
209   buffer[1] = OP_PROTOCOL_VERSION;
210   buffer[2] = PROTOCOL_VERSION_1;
211   buffer[3] = PROTOCOL_VERSION_2;
212   buffer[4] = PROTOCOL_VERSION_3;
213
214   SendBufferToServer(5);
215 }
216
217 void SendToServer_NrWanted(int nr_wanted)
218 {
219   buffer[1] = OP_NUMBER_WANTED;
220   buffer[2] = nr_wanted;
221
222   SendBufferToServer(3);
223 }
224
225 void SendToServer_StartPlaying()
226 {
227   unsigned long new_random_seed = InitRND(NEW_RANDOMIZE);
228
229   int dummy = 0;                /* !!! HAS NO MEANING ANYMORE !!! */
230                                 /* the name of the level must be enough */
231
232   buffer[1] = OP_START_PLAYING;
233   buffer[2] = (byte)(level_nr >> 8);
234   buffer[3] = (byte)(level_nr & 0xff);
235   buffer[4] = (byte)(dummy >> 8);
236   buffer[5] = (byte)(dummy & 0xff);
237
238   buffer[6] = (unsigned char)((new_random_seed >> 24) & 0xff);
239   buffer[7] = (unsigned char)((new_random_seed >> 16) & 0xff);
240   buffer[8] = (unsigned char)((new_random_seed >>  8) & 0xff);
241   buffer[9] = (unsigned char)((new_random_seed >>  0) & 0xff);
242
243   strcpy((char *)&buffer[10], leveldir_current->filename);
244
245   SendBufferToServer(10 + strlen(leveldir_current->filename) + 1);
246 }
247
248 void SendToServer_PausePlaying()
249 {
250   buffer[1] = OP_PAUSE_PLAYING;
251
252   SendBufferToServer(2);
253 }
254
255 void SendToServer_ContinuePlaying()
256 {
257   buffer[1] = OP_CONTINUE_PLAYING;
258
259   SendBufferToServer(2);
260 }
261
262 void SendToServer_StopPlaying()
263 {
264   buffer[1] = OP_STOP_PLAYING;
265
266   SendBufferToServer(2);
267 }
268
269 void SendToServer_MovePlayer(byte player_action)
270 {
271   buffer[1] = OP_MOVE_FIGURE;
272   buffer[2] = player_action;
273
274   SendBufferToServer(3);
275 }
276
277 static void Handle_OP_BAD_PROTOCOL_VERSION()
278 {
279   Error(ERR_WARN, "protocol version mismatch");
280   Error(ERR_EXIT, "server expects %d.%d.x instead of %d.%d.%d",
281         buffer[2], buffer[3],
282         PROTOCOL_VERSION_1, PROTOCOL_VERSION_2, PROTOCOL_VERSION_3);
283 }
284
285 static void Handle_OP_YOUR_NUMBER()
286 {
287   int new_client_nr = buffer[2];
288   int new_index_nr = new_client_nr - 1;
289   struct PlayerInfo *old_local_player = local_player;
290   struct PlayerInfo *new_local_player = &stored_player[new_index_nr];
291
292   printf("OP_YOUR_NUMBER: %d\n", buffer[0]);
293   first_player.nr = new_client_nr;
294
295   if (old_local_player != new_local_player)
296   {
297     /* copy existing player settings and change to new player */
298
299     *new_local_player = *old_local_player;
300     old_local_player->connected = FALSE;
301     local_player = new_local_player;
302   }
303
304   if (first_player.nr > MAX_PLAYERS)
305     Error(ERR_EXIT, "sorry - no more than %d players", MAX_PLAYERS);
306
307   Error(ERR_NETWORK_CLIENT, "you get client # %d", new_client_nr);
308 }
309
310 static void Handle_OP_NUMBER_WANTED()
311 {
312   int client_nr_wanted = buffer[2];
313   int old_client_nr = buffer[0];
314   int new_client_nr = buffer[3];
315   int old_index_nr = old_client_nr - 1;
316   int new_index_nr = new_client_nr - 1;
317   int index_nr_wanted = client_nr_wanted - 1;
318   struct PlayerInfo *old_player = &stored_player[old_index_nr];
319   struct PlayerInfo *new_player = &stored_player[new_index_nr];
320
321   printf("OP_NUMBER_WANTED: %d\n", buffer[0]);
322
323   if (new_client_nr == client_nr_wanted)        /* switching succeeded */
324   {
325     struct NetworkClientPlayerInfo *player;
326
327     if (old_client_nr != client_nr_wanted)      /* client's nr has changed */
328       Error(ERR_NETWORK_CLIENT, "client %d switches to # %d",
329             old_client_nr, new_client_nr);
330     else if (old_client_nr == first_player.nr)  /* local player keeps his nr */
331       Error(ERR_NETWORK_CLIENT, "keeping client # %d", new_client_nr);
332
333     if (old_client_nr != new_client_nr)
334     {
335       /* copy existing player settings and change to new player */
336
337       *new_player = *old_player;
338       old_player->connected = FALSE;
339     }
340
341     player = getNetworkPlayer(old_client_nr);
342     player->nr = new_client_nr;
343
344     if (old_player == local_player)             /* local player switched */
345       local_player = new_player;
346   }
347   else if (old_client_nr == first_player.nr)    /* failed -- local player? */
348   {
349     char *color[] = { "yellow", "red", "green", "blue" };
350     char request[100];
351
352     sprintf(request, "Sorry ! %s player still exists ! You are %s player !",
353             color[index_nr_wanted], color[new_index_nr]);
354     Request(request, REQ_CONFIRM);
355
356     Error(ERR_NETWORK_CLIENT, "cannot switch -- you keep client # %d",
357           new_client_nr);
358   }
359 }
360
361 static void Handle_OP_PLAYER_NAME(unsigned int len)
362 {
363   struct NetworkClientPlayerInfo *player;
364   int player_nr = (int)buffer[0];
365
366   printf("OP_PLAYER_NAME: %d\n", player_nr);
367   player = getNetworkPlayer(player_nr);
368   buffer[len] = 0;
369   Error(ERR_NETWORK_CLIENT, "client %d calls itself \"%s\"",
370         buffer[0], &buffer[2]);
371   strncpy(player->name, (char *)&buffer[2], MAX_PLAYER_NAME_LEN);
372 }
373
374 static void Handle_OP_PLAYER_CONNECTED()
375 {
376   struct NetworkClientPlayerInfo *player, *last_player = NULL;
377   int new_client_nr = (int)buffer[0];
378   int new_index_nr = new_client_nr - 1;
379
380   printf("OP_PLAYER_CONNECTED: %d\n", new_client_nr);
381   Error(ERR_NETWORK_CLIENT, "new client %d connected", new_client_nr);
382
383   for (player=&first_player; player; player=player->next)
384   {
385     if (player->nr == new_client_nr)
386       Error(ERR_EXIT, "multiplayer server sent duplicate player id");
387
388     last_player = player;
389   }
390
391   last_player->next = player =
392     checked_malloc(sizeof(struct NetworkClientPlayerInfo));
393   player->nr = new_client_nr;
394   player->name[0] = '\0';
395   player->next = NULL;
396
397   stored_player[new_index_nr].connected = TRUE;
398 }
399
400 static void Handle_OP_PLAYER_DISCONNECTED()
401 {
402   struct NetworkClientPlayerInfo *player, *player_disconnected;
403   int player_nr = (int)buffer[0];
404
405   printf("OP_PLAYER_DISCONNECTED: %d\n", player_nr);
406   player_disconnected = getNetworkPlayer(player_nr);
407   Error(ERR_NETWORK_CLIENT, "client %d (%s) disconnected",
408         player_nr, getNetworkPlayerName(buffer[0]));
409
410   for (player=&first_player; player; player=player->next)
411     if (player->next == player_disconnected)
412       player->next = player_disconnected->next;
413   free(player_disconnected);
414 }
415
416 static void Handle_OP_START_PLAYING()
417 {
418   struct LevelDirInfo *new_leveldir;
419   int new_level_nr;
420   int dummy;                            /* !!! HAS NO MEANING ANYMORE !!! */
421   unsigned long new_random_seed;
422   char *new_leveldir_filename;
423
424   new_level_nr = (buffer[2] << 8) + buffer[3];
425   dummy = (buffer[4] << 8) + buffer[5];
426   new_random_seed =
427     (buffer[6] << 24) | (buffer[7] << 16) | (buffer[8] << 8) | (buffer[9]);
428   new_leveldir_filename = (char *)&buffer[10];
429
430   new_leveldir = getLevelDirInfoFromFilename(new_leveldir_filename);
431   if (new_leveldir == NULL)
432   {
433     Error(ERR_WARN, "no such level directory: '%s'", new_leveldir_filename);
434
435     new_leveldir = leveldir_first;
436     Error(ERR_WARN, "using default level directory: '%s'", new_leveldir->name);
437   }
438
439   printf("OP_START_PLAYING: %d\n", buffer[0]);
440   Error(ERR_NETWORK_CLIENT,
441         "client %d starts game [level %d from leveldir '%s']\n",
442         buffer[0], new_level_nr, new_leveldir->name);
443
444   leveldir_current = new_leveldir;
445   level_nr = new_level_nr;
446
447   TapeErase();
448   LoadTape(level_nr);
449   LoadLevel(level_nr);
450
451   if (setup.autorecord)
452     TapeStartRecording();
453
454   if (tape.recording)
455     tape.random_seed = new_random_seed;
456
457   InitRND(new_random_seed);
458
459   game_status = PLAYING;
460   InitGame();
461 }
462
463 static void Handle_OP_PAUSE_PLAYING()
464 {
465   printf("OP_PAUSE_PLAYING: %d\n", buffer[0]);
466   Error(ERR_NETWORK_CLIENT, "client %d pauses game", buffer[0]);
467
468   tape.pausing = TRUE;
469   DrawVideoDisplay(VIDEO_STATE_PAUSE_ON,0);
470 }
471
472 static void Handle_OP_CONTINUE_PLAYING()
473 {
474   printf("OP_CONTINUE_PLAYING: %d\n", buffer[0]);
475   Error(ERR_NETWORK_CLIENT, "client %d continues game", buffer[0]);
476
477   tape.pausing = FALSE;
478   DrawVideoDisplay(VIDEO_STATE_PAUSE_OFF,0);
479 }
480
481 static void Handle_OP_STOP_PLAYING()
482 {
483   printf("OP_STOP_PLAYING: %d\n", buffer[0]);
484   Error(ERR_NETWORK_CLIENT, "client %d stops game", buffer[0]);
485
486   game_status = MAINMENU;
487   DrawMainMenu();
488 }
489
490 static void Handle_OP_MOVE_FIGURE(unsigned int len)
491 {
492   int server_frame_counter;
493   int i;
494
495   if (!network_playing)
496     return;
497
498   server_frame_counter =
499     (buffer[2] << 24) | (buffer[3] << 16) | (buffer[4] << 8) | (buffer[5]);
500
501   if (server_frame_counter != FrameCounter)
502   {
503     Error(ERR_RETURN, "client and servers frame counters out of sync");
504     Error(ERR_RETURN, "frame counter of client is %d", FrameCounter);
505     Error(ERR_RETURN, "frame counter of server is %d", server_frame_counter);
506     Error(ERR_EXIT,   "this should not happen -- please debug");
507   }
508
509   /* copy valid player actions */
510   for (i=0; i<MAX_PLAYERS; i++)
511     stored_player[i].effective_action =
512       (i < len - 6 && stored_player[i].active ? buffer[6 + i] : 0);
513
514   network_player_action_received = TRUE;
515 }
516
517 static void HandleNetworkingMessages()
518 {
519   unsigned int message_length;
520
521   while (nread >= 4 && nread >= 4 + readbuffer[3])
522   {
523     message_length = readbuffer[3];
524     if (readbuffer[0] || readbuffer[1] || readbuffer[2])
525       Error(ERR_EXIT, "wrong network server line length");
526
527     memcpy(buffer, &readbuffer[4], message_length);
528     nread -= 4 + message_length;
529     memmove(readbuffer, readbuffer + 4 + message_length, nread);
530
531     switch(buffer[1])
532     {
533       case OP_BAD_PROTOCOL_VERSION:
534         Handle_OP_BAD_PROTOCOL_VERSION();
535         break;
536
537       case OP_YOUR_NUMBER:
538         Handle_OP_YOUR_NUMBER();
539         break;
540
541       case OP_NUMBER_WANTED:
542         Handle_OP_NUMBER_WANTED();
543         break;
544
545       case OP_PLAYER_NAME:
546         Handle_OP_PLAYER_NAME(message_length);
547         break;
548
549       case OP_PLAYER_CONNECTED:
550         Handle_OP_PLAYER_CONNECTED();
551         break;
552       
553       case OP_PLAYER_DISCONNECTED:
554         Handle_OP_PLAYER_DISCONNECTED();
555         break;
556
557       case OP_START_PLAYING:
558         Handle_OP_START_PLAYING();
559         break;
560
561       case OP_PAUSE_PLAYING:
562         Handle_OP_PAUSE_PLAYING();
563         break;
564
565       case OP_CONTINUE_PLAYING:
566         Handle_OP_CONTINUE_PLAYING();
567         break;
568
569       case OP_STOP_PLAYING:
570         Handle_OP_STOP_PLAYING();
571         break;
572
573       case OP_MOVE_FIGURE:
574         Handle_OP_MOVE_FIGURE(message_length);
575         break;
576
577       case OP_BROADCAST_MESSAGE:
578         printf("OP_BROADCAST_MESSAGE: %d\n", buffer[0]);
579         Error(ERR_NETWORK_CLIENT, "client %d sends message", buffer[0]);
580         break;
581     }
582   }
583
584   fflush(stdout);
585 }
586
587 void HandleNetworking()
588 {
589   static struct timeval tv = { 0, 0 };
590   fd_set rfds;
591   int r = 0;
592
593   FD_ZERO(&rfds);
594   FD_SET(sfd, &rfds);
595
596   r = select(sfd + 1, &rfds, NULL, NULL, &tv);
597
598   if (r < 0 && errno != EINTR)
599     Error(ERR_EXIT, "HandleNetworking(): select() failed");
600
601   if (r < 0)
602     FD_ZERO(&rfds);
603
604   if (FD_ISSET(sfd, &rfds))
605   {
606     int r;
607
608     r = read(sfd, readbuffer + nread, MAX_BUFFER_SIZE - nread);
609
610     if (r < 0)
611       Error(ERR_EXIT, "error reading from network server");
612
613     if (r == 0)
614       Error(ERR_EXIT, "connection to network server lost");
615
616     nread += r;
617
618     HandleNetworkingMessages();
619   }
620 }
621
622 #endif /* PLATFORM_UNIX */