added setup option to directly play the next level after solving a level
[rocksndiamonds.git] / src / netserv.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 // netserv.c
10 // ============================================================================
11
12 #include <fcntl.h>
13 #include <sys/time.h>
14 #include <signal.h>
15 #include <errno.h>
16
17 #include "libgame/libgame.h"
18
19 #include "netserv.h"
20 #include "main.h"
21
22
23 static int clients = 0;
24 static int onceonly = 0;
25
26 struct NetworkServerPlayerInfo
27 {
28   TCPsocket fd;
29   char player_name[16];
30   unsigned char number;
31   struct NetworkServerPlayerInfo *next;
32   char active;
33   char introduced;
34   unsigned char readbuffer[MAX_BUFFER_SIZE];
35   unsigned char writbuffer[MAX_BUFFER_SIZE];
36   int nread, nwrite;
37   byte action;
38   boolean action_received;
39 };
40
41 static struct NetworkServerPlayerInfo *first_player = NULL;
42
43 #define NEXT(player) ((player)->next ? (player)->next : first_player)
44
45 /* TODO: peer address */
46 static TCPsocket lfd;           /* listening TCP socket */
47 static UDPsocket udp;           /* listening UDP socket */
48 static SDLNet_SocketSet fds;    /* socket set */
49
50 static unsigned char realbuffer[512], *buffer = realbuffer + 4;
51
52 static int interrupt;
53
54 static unsigned int ServerFrameCounter = 0;
55
56 static void addtobuffer(struct NetworkServerPlayerInfo *player,
57                         unsigned char *b, int len)
58 {
59   if (player->nwrite + len >= MAX_BUFFER_SIZE)
60     Error(ERR_EXIT_NETWORK_SERVER,
61           "internal error: network send buffer overflow");
62
63   memcpy(player->writbuffer + player->nwrite, b, len);
64   player->nwrite += len;
65 }
66
67 static void flushuser(struct NetworkServerPlayerInfo *player)
68 {
69   if (player->nwrite)
70   {
71     SDLNet_TCP_Send(player->fd, player->writbuffer, player->nwrite);
72
73     player->nwrite = 0;
74   }
75 }
76
77 static void broadcast(struct NetworkServerPlayerInfo *except,
78                       int len, int activeonly)
79 {
80   struct NetworkServerPlayerInfo *player;
81
82   realbuffer[0] = realbuffer[1] = realbuffer[2] = 0;
83   realbuffer[3] = (unsigned char)len;
84   for (player = first_player; player; player = player->next)
85     if (player != except && player->introduced &&
86         (player->active || !activeonly))
87       addtobuffer(player, realbuffer, 4 + len);
88 }
89
90 static void sendtoone(struct NetworkServerPlayerInfo *to, int len)
91 {
92   realbuffer[0] = realbuffer[1] = realbuffer[2] = 0;
93   realbuffer[3] = (unsigned char)len;
94   addtobuffer(to, realbuffer, 4 + len);
95 }
96
97 static void RemovePlayer(struct NetworkServerPlayerInfo *player)
98 {
99   struct NetworkServerPlayerInfo *v;
100   
101   if (options.verbose)
102     Error(ERR_NETWORK_SERVER, "dropping client %d (%s)",
103           player->number, player->player_name);
104
105   if (player == first_player)
106     first_player = player->next;
107   else
108   {
109     for (v = first_player; v; v = v->next)
110     {
111       if (v->next && v->next == player)
112       {
113         v->next = player->next;
114         break;
115       }
116     }
117   }
118
119   SDLNet_TCP_DelSocket(fds, player->fd);
120   SDLNet_TCP_Close(player->fd);
121
122   if (player->introduced)
123   {
124     buffer[0] = player->number;
125     buffer[1] = OP_PLAYER_DISCONNECTED;
126     broadcast(player, 2, 0);
127   }
128
129   free(player);
130   clients--;
131
132   if (onceonly && clients == 0)
133   {
134     if (options.verbose)
135     {
136       Error(ERR_NETWORK_SERVER, "no clients left");
137       Error(ERR_NETWORK_SERVER, "aborting");
138     }
139     exit(0);
140   }
141 }
142
143 static void AddPlayer(TCPsocket fd)
144 {
145   struct NetworkServerPlayerInfo *player, *v;
146   unsigned char nxn;
147   boolean again = TRUE;
148
149   player = checked_malloc(sizeof (struct NetworkServerPlayerInfo));
150
151   player->fd = fd;
152   player->player_name[0] = 0;
153   player->next = first_player;
154   player->active = 0;
155   player->nread = 0;
156   player->nwrite = 0;
157   player->introduced = 0;
158   player->action = 0;
159   player->action_received = FALSE;
160
161   SDLNet_TCP_AddSocket(fds, fd);
162
163   first_player = player;
164
165   nxn = 1;
166
167   while (again)
168   {
169     again = FALSE;
170     v = player->next;
171
172     while (v)
173     {
174       if (v->number == nxn)
175       {
176         nxn++;
177
178         again = TRUE;
179         break;
180       }
181       v = v->next;
182     }
183   }
184
185   player->number = nxn;
186   clients++;
187
188   buffer[0] = 0;
189   buffer[1] = OP_YOUR_NUMBER;
190   buffer[2] = player->number;
191   sendtoone(player, 3);
192 }
193
194 static void Handle_OP_PROTOCOL_VERSION(struct NetworkServerPlayerInfo *player,
195                                        unsigned int len)
196 {
197   if (len != 5 ||
198       buffer[2] != PROTOCOL_VERSION_1 ||
199       buffer[3] != PROTOCOL_VERSION_2)
200   {
201     if (options.verbose)
202       Error(ERR_NETWORK_SERVER,
203             "client %d (%s) has wrong protocol version %d.%d.%d",
204             player->number, player->player_name, buffer[2], buffer[3], buffer[4]);
205
206     buffer[0] = 0;
207     buffer[1] = OP_BAD_PROTOCOL_VERSION;
208     buffer[2] = PROTOCOL_VERSION_1;
209     buffer[3] = PROTOCOL_VERSION_2;
210     buffer[4] = PROTOCOL_VERSION_3;
211     sendtoone(player, 5);
212     flushuser(player);
213
214     RemovePlayer(player);
215     interrupt = 1;
216   }
217   else
218   {
219     if (options.verbose)
220       Error(ERR_NETWORK_SERVER,
221             "client %d (%s) uses protocol version %d.%d.%d",
222             player->number, player->player_name, buffer[2], buffer[3], buffer[4]);
223   }
224 }
225
226 static void Handle_OP_NUMBER_WANTED(struct NetworkServerPlayerInfo *player)
227 {
228   struct NetworkServerPlayerInfo *v;
229   int client_nr = player->number;
230   int nr_wanted = buffer[2];
231   int nr_is_free = 1;
232
233   if (options.verbose)
234       Error(ERR_NETWORK_SERVER, "client %d (%s) wants to switch to # %d",
235             player->number, player->player_name, nr_wanted);
236
237   for (v = first_player; v; v = v->next)
238   {
239     if (v->number == nr_wanted)
240     {
241       nr_is_free = 0;
242       break;
243     }
244   }
245
246   if (options.verbose)
247   {
248     if (nr_is_free)
249       Error(ERR_NETWORK_SERVER, "client %d (%s) switches to # %d",
250             player->number, player->player_name, nr_wanted);
251     else if (player->number == nr_wanted)
252       Error(ERR_NETWORK_SERVER, "client %d (%s) already has # %d",
253             player->number, player->player_name, nr_wanted);
254     else
255       Error(ERR_NETWORK_SERVER,
256             "client %d (%s) cannot switch (client %d already exists)",
257             player->number, player->player_name, nr_wanted);
258   }
259
260   if (nr_is_free)
261     player->number = nr_wanted;
262
263   buffer[0] = client_nr;
264   buffer[1] = OP_NUMBER_WANTED;
265   buffer[2] = nr_wanted;
266   buffer[3] = player->number;
267
268   /*
269   sendtoone(player, 4);
270   */
271
272   broadcast(NULL, 4, 0);
273 }
274
275 static void Handle_OP_PLAYER_NAME(struct NetworkServerPlayerInfo *player,
276                                   unsigned int len)
277 {
278   struct NetworkServerPlayerInfo *v;
279   int i;
280
281   if (len>16)
282     len=16;
283   memcpy(player->player_name, &buffer[2], len-2);
284   player->player_name[len-2] = 0;
285   for (i = 0; i < len - 2; i++)
286   {
287     if (player->player_name[i] < ' ' || 
288         ((unsigned char)(player->player_name[i]) > 0x7e &&
289          (unsigned char)(player->player_name[i]) <= 0xa0))
290     {
291       player->player_name[i] = 0;
292       break;
293     }
294   }
295
296   if (!player->introduced)
297   {
298     buffer[0] = player->number;
299     buffer[1] = OP_PLAYER_CONNECTED;
300     broadcast(player, 2, 0);
301   }
302               
303   if (options.verbose)
304     Error(ERR_NETWORK_SERVER, "client %d calls itself \"%s\"",
305           player->number, player->player_name);
306   buffer[1] = OP_PLAYER_NAME;
307   broadcast(player, len, 0);
308
309   if (!player->introduced)
310   {
311     for (v = first_player; v; v = v->next)
312     {
313       if (v != player && v->introduced)
314       {
315         buffer[0] = v->number;
316         buffer[1] = OP_PLAYER_CONNECTED;
317         sendtoone(player, 2);
318         buffer[1] = OP_PLAYER_NAME;
319         memcpy(&buffer[2], v->player_name, 14);
320         sendtoone(player, 2+strlen(v->player_name));
321       }
322     }
323   }
324
325   player->introduced = 1;
326 }
327
328 static void Handle_OP_START_PLAYING(struct NetworkServerPlayerInfo *player)
329 {
330   struct NetworkServerPlayerInfo *v, *w;
331
332   if (options.verbose)
333     Error(ERR_NETWORK_SERVER,
334           "client %d (%s) starts game [level %d from leveldir %d (%s)]",
335           player->number, player->player_name,
336           (buffer[2] << 8) + buffer[3],
337           (buffer[4] << 8) + buffer[5],
338           &buffer[10]);
339
340   for (w = first_player; w; w = w->next)
341     if (w->introduced)
342       w->active = 1;
343
344   /* reset frame counter */
345   ServerFrameCounter = 0;
346
347   Error(ERR_NETWORK_SERVER, "resetting ServerFrameCounter to 0");
348
349   /* reset player actions */
350   for (v = first_player; v; v = v->next)
351   {
352     v->action = 0;
353     v->action_received = FALSE;
354   }
355
356   broadcast(NULL, 10 + strlen((char *)&buffer[10])+1, 0);
357 }
358
359 static void Handle_OP_PAUSE_PLAYING(struct NetworkServerPlayerInfo *player)
360 {
361   if (options.verbose)
362     Error(ERR_NETWORK_SERVER, "client %d (%s) pauses game",
363           player->number, player->player_name);
364   broadcast(NULL, 2, 0);
365 }
366
367 static void Handle_OP_CONTINUE_PLAYING(struct NetworkServerPlayerInfo *player)
368 {
369   if (options.verbose)
370     Error(ERR_NETWORK_SERVER, "client %d (%s) continues game",
371           player->number, player->player_name);
372   broadcast(NULL, 2, 0);
373 }
374
375 static void Handle_OP_STOP_PLAYING(struct NetworkServerPlayerInfo *player)
376 {
377   int cause_for_stopping = buffer[2];
378
379   if (options.verbose)
380     Error(ERR_NETWORK_SERVER, "client %d (%s) stops game [%d]",
381           player->number, player->player_name, cause_for_stopping);
382   broadcast(NULL, 3, 0);
383 }
384
385 static void Handle_OP_MOVE_PLAYER(struct NetworkServerPlayerInfo *player)
386 {
387   struct NetworkServerPlayerInfo *v;
388   int last_client_nr = 0;
389   int i;
390
391   /* store player action */
392   for (v = first_player; v; v = v->next)
393   {
394     if (v->number == player->number)
395     {
396       v->action = buffer[2];
397       v->action_received = TRUE;
398     }
399   }
400
401   /* check if server received action from each player */
402   for (v = first_player; v; v = v->next)
403   {
404     if (!v->action_received)
405       return;
406
407     if (v->number > last_client_nr)
408       last_client_nr = v->number;
409   }
410
411   /* initialize all player actions to zero */
412   for (i = 0; i < last_client_nr; i++)
413     buffer[6 + i] = 0;
414
415   /* broadcast actions of all players to all players */
416   for (v = first_player; v; v = v->next)
417   {
418     buffer[6 + v->number-1] = v->action;
419     v->action = 0;
420     v->action_received = FALSE;
421   }
422
423   buffer[2] = (unsigned char)((ServerFrameCounter >> 24) & 0xff);
424   buffer[3] = (unsigned char)((ServerFrameCounter >> 16) & 0xff);
425   buffer[4] = (unsigned char)((ServerFrameCounter >>  8) & 0xff);
426   buffer[5] = (unsigned char)((ServerFrameCounter >>  0) & 0xff);
427
428   broadcast(NULL, 6 + last_client_nr, 0);
429
430   ServerFrameCounter++;
431 }
432
433 void ExitNetworkServer(int exit_value)
434 {
435   Error(ERR_NETWORK_SERVER, "exiting network server");
436
437   exit(exit_value);
438 }
439
440 /* the following is not used for a standalone server;
441    the pointer points to an integer containing the port-number */
442 int NetworkServerThread(void *ptr)
443 {
444   NetworkServer(*((int *) ptr), 0);
445
446   /* should never be reached */
447   return 0;
448 }
449
450 void NetworkServer(int port, int serveronly)
451 {
452   struct NetworkServerPlayerInfo *player;
453   int r; 
454   unsigned int len;
455   IPaddress ip;
456
457 #if defined(PLATFORM_UNIX) && !defined(PLATFORM_NEXT)
458   struct sigaction sact;
459 #endif
460
461   if (port == 0)
462     port = DEFAULT_SERVER_PORT;
463
464   // if only running the network server, exit on Ctrl-C
465   if (serveronly)
466     signal(SIGINT, ExitNetworkServer);
467
468   if (!serveronly)
469     onceonly = 1;
470
471 #if defined(PLATFORM_UNIX)
472 #if defined(PLATFORM_NEXT)
473   signal(SIGPIPE, SIG_IGN);
474 #else
475   sact.sa_handler = SIG_IGN;
476   sigemptyset(&sact.sa_mask);
477   sact.sa_flags = 0;
478   sigaction(SIGPIPE, &sact, NULL);
479 #endif
480 #endif
481
482   if (SDLNet_ResolveHost(&ip, NULL, port) == -1)
483     Error(ERR_EXIT_NETWORK_SERVER, "SDLNet_ResolveHost() failed: %s",
484           SDLNet_GetError());
485
486   if ((fds = SDLNet_AllocSocketSet(MAX_PLAYERS + 1 + 1)) == NULL)
487     Error(ERR_EXIT_NETWORK_SERVER, "SDLNet_AllocSocketSet() failed: %s"),
488       SDLNet_GetError();
489
490   if ((lfd = SDLNet_TCP_Open(&ip)) == NULL)
491     Error(ERR_EXIT_NETWORK_SERVER, "SDLNet_TCP_Open() failed: %s"),
492       SDLNet_GetError();
493
494   if (SDLNet_TCP_AddSocket(fds, lfd) == -1)
495     Error(ERR_EXIT_NETWORK_SERVER, "SDLNet_TCP_AddSocket() failed: %s"),
496       SDLNet_GetError();
497
498   if ((udp = SDLNet_UDP_Open(port)) == NULL)
499     Error(ERR_EXIT_NETWORK_SERVER, "SDLNet_UDP_Open() failed: %s",
500           SDLNet_GetError());
501
502   if (SDLNet_UDP_AddSocket(fds, udp) == -1)
503     Error(ERR_EXIT_NETWORK_SERVER, "SDLNet_TCP_AddSocket() failed: %s"),
504       SDLNet_GetError();
505
506   if (options.verbose)
507   {
508     Error(ERR_NETWORK_SERVER, "started up, listening on port %d", port);
509     Error(ERR_NETWORK_SERVER, "using protocol version %d.%d.%d",
510           PROTOCOL_VERSION_1, PROTOCOL_VERSION_2, PROTOCOL_VERSION_3);
511   }
512
513   while (1)
514   {
515     interrupt = 0;
516
517     for (player = first_player; player; player = player->next)
518       flushuser(player);
519
520     // wait for 100 ms for activity on open network sockets
521     if (SDLNet_CheckSockets(fds, 100) < 1)
522       continue;
523
524     /* accept incoming TCP connections */
525     if (SDLNet_SocketReady(lfd))
526     {
527       Error(ERR_DEBUG, "got TCP packet");
528
529       TCPsocket newsock;
530
531       newsock = SDLNet_TCP_Accept(lfd);
532
533       if (newsock)
534         AddPlayer(newsock);
535     }
536
537     /* accept incoming UDP packets */
538     if (SDLNet_SocketReady(udp))
539     {
540       Error(ERR_DEBUG, "got UDP packet");
541
542       static UDPpacket packet;
543
544       int num_packets = SDLNet_UDP_Recv(udp, &packet);
545
546       if (num_packets == 1)
547       {
548         // bounce packet
549         SDLNet_UDP_Send(udp, -1, &packet);
550       }
551     }
552
553     player = first_player;
554
555     while (player && !interrupt)
556     {
557       if (SDLNet_SocketReady(player->fd))
558       {
559         /* read only 1 byte, because SDLNet blocks when we want more than is
560            in the buffer */
561         r = SDLNet_TCP_Recv(player->fd, player->readbuffer + player->nread, 1);
562
563         if (r <= 0)
564         {
565           if (options.verbose)
566             Error(ERR_NETWORK_SERVER, "EOF from client %d (%s)",
567                   player->number, player->player_name);
568           RemovePlayer(player);
569           interrupt = 1;
570           break;
571         }
572         player->nread += r;
573         while (player->nread >= 4 && player->nread >= 4 + player->readbuffer[3])
574         {
575           len = player->readbuffer[3];
576           if (player->readbuffer[0] || player->readbuffer[1] || player->readbuffer[2])
577           {
578             if (options.verbose)
579               Error(ERR_NETWORK_SERVER, "crap from client %d (%s)",
580                     player->number, player->player_name);
581             RemovePlayer(player);
582             interrupt = 1;
583             break;
584           }
585           memcpy(buffer, &player->readbuffer[4], len);
586           player->nread -= 4 + len;
587           memmove(player->readbuffer, player->readbuffer + 4 + len, player->nread);
588
589           buffer[0] = player->number;
590           if (!player->introduced && buffer[1] != OP_PLAYER_NAME)
591           {
592             if (options.verbose)
593               Error(ERR_NETWORK_SERVER, "!(client %d)->introduced && buffer[1]==%d (expected OP_PLAYER_NAME)", buffer[0], buffer[1]);
594
595             RemovePlayer(player);
596             interrupt = 1;
597             break;
598           }
599
600           switch (buffer[1])
601           {
602             case OP_PLAYER_NAME:
603               Handle_OP_PLAYER_NAME(player, len);
604               break;
605
606             case OP_PROTOCOL_VERSION:
607               Handle_OP_PROTOCOL_VERSION(player, len);
608               break;
609
610             case OP_NUMBER_WANTED:
611               Handle_OP_NUMBER_WANTED(player);
612               break;
613
614             case OP_START_PLAYING:
615               Handle_OP_START_PLAYING(player);
616               break;
617
618             case OP_PAUSE_PLAYING:
619               Handle_OP_PAUSE_PLAYING(player);
620               break;
621
622             case OP_CONTINUE_PLAYING:
623               Handle_OP_CONTINUE_PLAYING(player);
624               break;
625
626             case OP_STOP_PLAYING:
627               Handle_OP_STOP_PLAYING(player);
628               break;
629
630             case OP_MOVE_PLAYER:
631               Handle_OP_MOVE_PLAYER(player);
632               break;
633
634             case OP_BROADCAST_MESSAGE:
635               buffer[len] = '\0';
636               if (options.verbose)
637                 Error(ERR_NETWORK_SERVER, "client %d (%s) sends message: %s",
638                       player->number, player->player_name, &buffer[2]);
639               broadcast(player, len, 0);
640               break;
641             
642             default:
643               if (options.verbose)
644                 Error(ERR_NETWORK_SERVER,
645                       "unknown opcode %d from client %d (%s)",
646                       buffer[0], player->number, player->player_name);
647           }
648         }
649       }
650
651       if (player && !interrupt)
652         player = player->next;
653     }
654   }
655 }