rnd-20030417-1-src
[rocksndiamonds.git] / src / netserv.c
1 /***********************************************************
2 * Rocks'n'Diamonds -- McDuffin Strikes Back!               *
3 *----------------------------------------------------------*
4 * (c) 1995-2002 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * network.c                                                *
12 ***********************************************************/
13
14 #include "libgame/platform.h"
15
16 #if defined(PLATFORM_UNIX)
17
18 #include <fcntl.h>
19 #include <sys/time.h>
20 #include <signal.h>
21 #include <sys/socket.h>
22 #include <errno.h>
23 #include <string.h>
24 #include <netinet/in.h>
25 #include <netinet/tcp.h>
26 #include <arpa/inet.h>
27 #include <netdb.h>
28
29 #include "libgame/libgame.h"
30
31 #include "netserv.h"
32
33 static int clients = 0;
34 static int onceonly = 0;
35
36 struct NetworkServerPlayerInfo
37 {
38   int fd;
39   char player_name[16];
40   unsigned char number;
41   struct NetworkServerPlayerInfo *next;
42   char active;
43   char introduced;
44   unsigned char readbuffer[MAX_BUFFER_SIZE];
45   unsigned char writbuffer[MAX_BUFFER_SIZE];
46   int nread, nwrite;
47   byte action;
48   boolean action_received;
49 };
50
51 static struct NetworkServerPlayerInfo *first_player = NULL;
52
53 #define NEXT(player) ((player)->next ? (player)->next : first_player)
54
55 static struct sockaddr_in saddr;
56 static int lfd;
57 static unsigned char realbuffer[512], *buffer = realbuffer + 4;
58
59 static int interrupt;
60 static int tcp = -1;
61
62 static unsigned long ServerFrameCounter = 0;
63
64 static fd_set fds;
65
66 static void addtobuffer(struct NetworkServerPlayerInfo *player,
67                         unsigned char *b, int len)
68 {
69   if (player->nwrite + len >= MAX_BUFFER_SIZE)
70     Error(ERR_EXIT_NETWORK_SERVER,
71           "internal error: network send buffer overflow");
72
73   memcpy(player->writbuffer + player->nwrite, b, len);
74   player->nwrite += len;
75 }
76
77 static void flushuser(struct NetworkServerPlayerInfo *player)
78 {
79   if (player->nwrite)
80   {
81     write(player->fd, player->writbuffer, player->nwrite);
82     player->nwrite = 0;
83   }
84 }
85
86 static void broadcast(struct NetworkServerPlayerInfo *except,
87                       int len, int activeonly)
88 {
89   struct NetworkServerPlayerInfo *player;
90
91   realbuffer[0] = realbuffer[1] = realbuffer[2] = 0;
92   realbuffer[3] = (unsigned char)len;
93   for (player=first_player; player; player=player->next)
94     if (player != except && (player->active || !activeonly) && player->introduced)
95       addtobuffer(player, realbuffer, 4 + len);
96 }
97
98 static void sendtoone(struct NetworkServerPlayerInfo *to, int len)
99 {
100   realbuffer[0] = realbuffer[1] = realbuffer[2] = 0;
101   realbuffer[3] = (unsigned char)len;
102   addtobuffer(to, realbuffer, 4 + len);
103 }
104
105 static void RemovePlayer(struct NetworkServerPlayerInfo *player)
106 {
107   struct NetworkServerPlayerInfo *v;
108   
109   if (options.verbose)
110     Error(ERR_NETWORK_SERVER, "dropping client %d (%s)",
111           player->number, player->player_name);
112
113   if (player == first_player)
114     first_player = player->next;
115   else
116   {
117     for (v=first_player; v; v=v->next)
118     {
119       if (v->next && v->next == player)
120       {
121         v->next = player->next;
122         break;
123       }
124     }
125   }
126   close(player->fd);
127
128   if (player->introduced)
129   {
130     buffer[0] = player->number;
131     buffer[1] = OP_PLAYER_DISCONNECTED;
132     broadcast(player, 2, 0);
133   }
134
135   free(player);
136   clients--;
137
138   if (onceonly && clients == 0)
139   {
140     if (options.verbose)
141     {
142       Error(ERR_NETWORK_SERVER, "no clients left");
143       Error(ERR_NETWORK_SERVER, "aborting");
144     }
145     exit(0);
146   }
147 }
148
149 static void AddPlayer(int fd)
150 {
151   struct NetworkServerPlayerInfo *player, *v;
152   unsigned char nxn;
153
154   player = checked_malloc(sizeof (struct NetworkServerPlayerInfo));
155
156   player->fd = fd;
157   player->player_name[0] = 0;
158   player->next = first_player;
159   player->active = 0;
160   player->nread = 0;
161   player->nwrite = 0;
162   player->introduced = 0;
163   player->action = 0;
164   player->action_received = FALSE;
165
166   first_player = player;
167
168   nxn = 1;
169
170  again:
171   v = player->next;
172   while(v)
173   {
174     if (v->number == nxn)
175     {
176       nxn++;
177       goto again;
178     }
179     v = v->next;
180   }
181
182   player->number = nxn;
183   if (options.verbose)
184     Error(ERR_NETWORK_SERVER, "client %d connecting from %s",
185           nxn, inet_ntoa(saddr.sin_addr));
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) still 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 still 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 levedir %d (%s)]",
335           player->number, player->player_name,
336           (buffer[2] << 8) + buffer[3],
337           (buffer[4] << 8) + buffer[5],
338           &buffer[6]);
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   /* reset player actions */
348   for (v=first_player; v; v=v->next)
349   {
350     v->action = 0;
351     v->action_received = FALSE;
352   }
353
354   broadcast(NULL, 10 + strlen((char *)&buffer[10])+1, 0);
355 }
356
357 static void Handle_OP_PAUSE_PLAYING(struct NetworkServerPlayerInfo *player)
358 {
359   if (options.verbose)
360     Error(ERR_NETWORK_SERVER, "client %d (%s) pauses game",
361           player->number, player->player_name);
362   broadcast(NULL, 2, 0);
363 }
364
365 static void Handle_OP_CONTINUE_PLAYING(struct NetworkServerPlayerInfo *player)
366 {
367   if (options.verbose)
368     Error(ERR_NETWORK_SERVER, "client %d (%s) continues game",
369           player->number, player->player_name);
370   broadcast(NULL, 2, 0);
371 }
372
373 static void Handle_OP_STOP_PLAYING(struct NetworkServerPlayerInfo *player)
374 {
375   if (options.verbose)
376     Error(ERR_NETWORK_SERVER, "client %d (%s) stops game",
377           player->number, player->player_name);
378   broadcast(NULL, 2, 0);
379 }
380
381 static void Handle_OP_MOVE_FIGURE(struct NetworkServerPlayerInfo *player)
382 {
383   struct NetworkServerPlayerInfo *v;
384   int last_client_nr = 0;
385   int i;
386
387   /* store player action */
388   for (v=first_player; v; v=v->next)
389   {
390     if (v->number == player->number)
391     {
392       v->action = buffer[2];
393       v->action_received = TRUE;
394     }
395   }
396
397   /* check if server received action from each player */
398   for (v=first_player; v; v=v->next)
399   {
400     if (!v->action_received)
401       return;
402
403     if (v->number > last_client_nr)
404       last_client_nr = v->number;
405   }
406
407   /* initialize all player actions to zero */
408   for (i=0; i<last_client_nr; i++)
409     buffer[6 + i] = 0;
410
411   /* broadcast actions of all players to all players */
412   for (v=first_player; v; v=v->next)
413   {
414     buffer[6 + v->number-1] = v->action;
415     v->action = 0;
416     v->action_received = FALSE;
417   }
418
419   buffer[2] = (unsigned char)((ServerFrameCounter >> 24) & 0xff);
420   buffer[3] = (unsigned char)((ServerFrameCounter >> 16) & 0xff);
421   buffer[4] = (unsigned char)((ServerFrameCounter >>  8) & 0xff);
422   buffer[5] = (unsigned char)((ServerFrameCounter >>  0) & 0xff);
423
424   broadcast(NULL, 6 + last_client_nr, 0);
425
426   ServerFrameCounter++;
427 }
428
429 void NetworkServer(int port, int serveronly)
430 {
431   int i, sl, on;
432   struct NetworkServerPlayerInfo *player;
433   int mfd;
434   int r; 
435   unsigned int len;
436   struct protoent *tcpproto;
437   struct timeval tv;
438   int is_daemon = 0;
439
440 #ifndef NeXT
441   struct sigaction sact;
442 #endif
443
444   if (port == 0)
445     port = DEFAULT_SERVER_PORT;
446
447   if (!serveronly)
448     onceonly = 1;
449
450   if ((tcpproto = getprotobyname("tcp")) != NULL)
451     tcp = tcpproto->p_proto;
452
453 #ifdef NeXT
454   signal(SIGPIPE, SIG_IGN);
455 #else
456   sact.sa_handler = SIG_IGN;
457   sigemptyset(&sact.sa_mask);
458   sact.sa_flags = 0;
459   sigaction(SIGPIPE, &sact, NULL);
460 #endif
461
462
463   if ((lfd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
464     Error(ERR_EXIT_NETWORK_SERVER, "socket() failed");
465
466   saddr.sin_family = AF_INET;
467   saddr.sin_addr.s_addr = htonl(INADDR_ANY);
468   saddr.sin_port = htons(port);
469
470   on = 1;
471
472   setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(int));
473   if (bind(lfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
474     Error(ERR_EXIT_NETWORK_SERVER, "bind() failed");
475
476   listen(lfd, 5);
477
478   if (is_daemon)
479   {
480     /* become a daemon, breaking all ties with the controlling terminal */
481     options.verbose = FALSE;
482     for (i=0; i<255; i++)
483     {
484       if (i != lfd)
485         close(i);
486     }
487
488     if (fork())
489       exit(0);
490     setsid();
491     if (fork())
492       exit(0);
493     chdir("/");
494
495     /* open a fake stdin, stdout, stderr, just in case */
496     open("/dev/null", O_RDONLY);
497     open("/dev/null", O_WRONLY);
498     open("/dev/null", O_WRONLY);
499   }
500
501   if (options.verbose)
502   {
503     Error(ERR_NETWORK_SERVER, "started up, listening on port %d", port);
504     Error(ERR_NETWORK_SERVER, "using protocol version %d.%d.%d",
505           PROTOCOL_VERSION_1, PROTOCOL_VERSION_2, PROTOCOL_VERSION_3);
506   }
507
508   while(1)
509   {
510     interrupt = 0;
511
512     for (player=first_player; player; player=player->next)
513       flushuser(player);
514
515     FD_ZERO(&fds);
516     mfd = lfd;
517     player = first_player;
518     while (player)
519     {
520       FD_SET(player->fd, &fds);
521       if (player->fd > mfd)
522         mfd = player->fd;
523       player = player->next;
524     }
525     FD_SET(lfd, &fds);
526     tv.tv_sec = 0;
527     tv.tv_usec = 500000;
528     if ((sl = select(mfd + 1, &fds, NULL, NULL, &tv)) < 0)
529     {
530       if (errno != EINTR)
531         Error(ERR_EXIT_NETWORK_SERVER, "select() failed");
532       else
533         continue;
534     }
535
536     if (sl < 0)
537       continue;
538     
539     if (sl == 0)
540       continue;
541
542     if (FD_ISSET(lfd, &fds))
543     {
544       int newfd, slen;
545
546       slen = sizeof(saddr);
547       newfd = accept(lfd, (struct sockaddr *)&saddr, &slen);
548       if (newfd < 0)
549       {
550         if (errno != EINTR)
551           Error(ERR_EXIT_NETWORK_SERVER, "accept() failed");
552       }
553       else
554       {
555         if (tcp != -1)
556         {
557           on = 1;
558           setsockopt(newfd, tcp, TCP_NODELAY, (char *)&on, sizeof(int));
559         }
560         AddPlayer(newfd);
561       }
562       continue;
563     }
564
565     player = first_player;
566
567     do
568     {
569       if (FD_ISSET(player->fd, &fds))
570       {
571         r = read(player->fd, player->readbuffer + player->nread, MAX_BUFFER_SIZE - player->nread);
572         if (r <= 0)
573         {
574           if (options.verbose)
575             Error(ERR_NETWORK_SERVER, "EOF from client %d (%s)",
576                   player->number, player->player_name);
577           RemovePlayer(player);
578           interrupt = 1;
579           break;
580         }
581         player->nread += r;
582         while (player->nread >= 4 && player->nread >= 4 + player->readbuffer[3])
583         {
584           len = player->readbuffer[3];
585           if (player->readbuffer[0] || player->readbuffer[1] || player->readbuffer[2])
586           {
587             if (options.verbose)
588               Error(ERR_NETWORK_SERVER, "crap from client %d (%s)",
589                     player->number, player->player_name);
590             RemovePlayer(player);
591             interrupt = 1;
592             break;
593           }
594           memcpy(buffer, &player->readbuffer[4], len);
595           player->nread -= 4 + len;
596           memmove(player->readbuffer, player->readbuffer + 4 + len, player->nread);
597
598           buffer[0] = player->number;
599           if (!player->introduced && buffer[1] != OP_PLAYER_NAME)
600           {
601             if (options.verbose)
602               Error(ERR_NETWORK_SERVER, "!(client %d)->introduced && buffer[1]==%d (expected OP_PLAYER_NAME)", buffer[0], buffer[1]);
603
604             RemovePlayer(player);
605             interrupt = 1;
606             break;
607           }
608
609           switch(buffer[1])
610           {
611             case OP_PLAYER_NAME:
612               Handle_OP_PLAYER_NAME(player, len);
613               break;
614
615             case OP_PROTOCOL_VERSION:
616               Handle_OP_PROTOCOL_VERSION(player, len);
617               break;
618
619             case OP_NUMBER_WANTED:
620               Handle_OP_NUMBER_WANTED(player);
621               break;
622
623             case OP_START_PLAYING:
624               Handle_OP_START_PLAYING(player);
625               break;
626
627             case OP_PAUSE_PLAYING:
628               Handle_OP_PAUSE_PLAYING(player);
629               break;
630
631             case OP_CONTINUE_PLAYING:
632               Handle_OP_CONTINUE_PLAYING(player);
633               break;
634
635             case OP_STOP_PLAYING:
636               Handle_OP_STOP_PLAYING(player);
637               break;
638
639             case OP_MOVE_FIGURE:
640               Handle_OP_MOVE_FIGURE(player);
641               break;
642
643             case OP_BROADCAST_MESSAGE:
644               buffer[len] = '\0';
645               if (options.verbose)
646                 Error(ERR_NETWORK_SERVER, "client %d (%s) sends message: %s",
647                       player->number, player->player_name, &buffer[2]);
648               broadcast(player, len, 0);
649               break;
650             
651             default:
652               if (options.verbose)
653                 Error(ERR_NETWORK_SERVER,
654                       "unknown opcode %d from client %d (%s)",
655                       buffer[0], player->number, player->player_name);
656           }
657         }
658       }
659
660       if (player && !interrupt)
661         player = player->next;
662     }
663     while (player && !interrupt);
664   }
665 }
666
667 #endif /* PLATFORM_UNIX */