rnd-19981123-6
[rocksndiamonds.git] / src / netserv.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 <stdio.h>
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <fcntl.h>
18 #include <sys/types.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 "netserv.h"
30 #include "misc.h"
31
32 static int clients = 0;
33 static int onceonly = 0;
34 static int is_daemon = 0;
35
36 struct user
37 {
38   int fd;
39   unsigned char nick[16];
40   unsigned char number;
41   struct user *next, *nextvictim;
42   char active;
43   char introduced;
44   unsigned char readbuf[MAX_BUFFER_SIZE];
45   int nread;
46   unsigned char writbuf[MAX_BUFFER_SIZE];
47   int nwrite;
48   char playing;
49   unsigned int games;
50   unsigned char action;
51   int action_received;
52 };
53
54 static struct user *user0 = NULL;
55
56 #define NEXT(u) ((u)->next ? (u)->next : user0)
57
58 static struct sockaddr_in saddr;
59 static int lfd;
60 static unsigned char realbuf[512], *buf = realbuf + 4;
61
62 static int interrupt;
63 static int tcp = -1;
64
65 static unsigned long frame_counter = 0;
66
67 static fd_set fds;
68
69 static void syserr(char *s)
70 {
71   if (!is_daemon)
72     fprintf(stderr, "fatal: %s failed.\n", s);
73   exit(1);
74 }
75
76 static void addtobuffer(struct user *u, unsigned char *b, int len)
77 {
78   if (u->nwrite + len >= MAX_BUFFER_SIZE)
79     Error(ERR_EXIT, "internal error: network send buffer overflow");
80
81   memcpy(u->writbuf + u->nwrite, b, len);
82   u->nwrite += len;
83 }
84
85 static void flushuser(struct user *u)
86 {
87   if (u->nwrite)
88   {
89     write(u->fd, u->writbuf, u->nwrite);
90     u->nwrite = 0;
91   }
92 }
93
94 static void broadcast(struct user *except, int len, int activeonly)
95 {
96   struct user *u;
97
98   realbuf[0] = realbuf[1] = realbuf[2] = 0;
99   realbuf[3] = (unsigned char)len;
100   for (u=user0; u; u=u->next)
101     if (u != except && (u->active || !activeonly) && u->introduced)
102       addtobuffer(u, realbuf, 4 + len);
103 }
104
105 static void sendtoone(struct user *to, int len)
106 {
107   realbuf[0] = realbuf[1] = realbuf[2] = 0;
108   realbuf[3] = (unsigned char)len;
109   addtobuffer(to, realbuf, 4 + len);
110 }
111
112 static void dropuser(struct user *u)
113 {
114   struct user *v, *w;
115   
116   if (options.verbose)
117     printf("RND_SERVER: dropping client %d (%s)\n", u->number, u->nick);
118
119   if (u == user0)
120     user0 = u->next;
121   else
122   {
123     for (v=user0; v; v=v->next)
124     {
125       if (v->next && v->next == u)
126       {
127         v->next = u->next;
128         break;
129       }
130     }
131   }
132   close(u->fd);
133
134   if (u->introduced)
135   {
136     buf[0] = u->number;
137     buf[1] = OP_PLAYER_DISCONNECTED;
138     broadcast(u, 2, 0);
139   }
140
141   for (v=user0; v; v=v->next)
142   {
143     if (v->nextvictim == u)
144     {
145       for (w=NEXT(v); w!=v; w=NEXT(w))
146       {
147         if (w->active && w->playing)
148         {
149           v->nextvictim = w;
150           break;
151         }
152       }
153       if (v->nextvictim == u)
154         v->nextvictim = NULL;
155     }
156   }
157
158   free(u);
159   clients--;
160
161   if (onceonly && clients == 0)
162   {
163     if (options.verbose)
164     {
165       printf("RND_SERVER: no clients left\n");
166       printf("RND_SERVER: aborting\n");
167     }
168     exit(0);
169   }
170 }
171
172 static void new_connect(int fd)
173 {
174   struct user *u, *v;
175   unsigned char nxn;
176
177   u = checked_malloc(sizeof (struct user));
178
179   u->fd = fd;
180   u->nick[0] = 0;
181   u->next = user0;
182   u->nextvictim = NULL;
183   u->active = 0;
184   u->nread = 0;
185   u->nwrite = 0;
186   u->playing = 0;
187   u->introduced = 0;
188   u->games = 0;
189   u->action = 0;
190   u->action_received = 0;
191
192   user0 = u;
193
194   nxn = 1;
195
196  again:
197   v = u->next;
198   while(v)
199   {
200     if (v->number == nxn)
201     {
202       nxn++;
203       goto again;
204     }
205     v = v->next;
206   }
207
208   u->number = nxn;
209   if (options.verbose)
210     printf("RND_SERVER: client %d connecting from %s\n", nxn, inet_ntoa(saddr.sin_addr));
211   clients++;
212
213   buf[0] = 0;
214   buf[1] = OP_YOUR_NUMBER;
215   buf[2] = u->number;
216   sendtoone(u, 3);
217 }
218
219 static void Handle_OP_PROTOCOL_VERSION(struct user *u, unsigned int len)
220 {
221   if (len != 5 || buf[2] != PROTOCOL_VERSION_1 || buf[3] != PROTOCOL_VERSION_2)
222   {
223     if (options.verbose)
224       printf("RND_SERVER: client %d (%s) has wrong protocol version %d.%d.%d\n", u->number, u->nick, buf[2], buf[3], buf[4]);
225
226     buf[0] = 0;
227     buf[1] = OP_BADVERS;
228     buf[2] = PROTOCOL_VERSION_1;
229     buf[3] = PROTOCOL_VERSION_2;
230     buf[4] = PROTOCOL_VERSION_3;
231     sendtoone(u, 5);
232     flushuser(u);
233
234     dropuser(u);
235     interrupt = 1;
236   }
237   else
238   {
239     if (options.verbose)
240       printf("RND_SERVER: client %d (%s) uses protocol version %d.%d.%d\n", u->number, u->nick, buf[2], buf[3], buf[4]);
241   }
242 }
243
244 static void Handle_OP_NUMBER_WANTED(struct user *u)
245 {
246   struct user *v;
247   int client_nr = u->number;
248   int nr_wanted = buf[2];
249   int nr_is_free = 1;
250
251   if (options.verbose)
252     printf("RND_SERVER: client %d (%s) wants to switch to # %d\n",
253            u->number, u->nick, nr_wanted);
254
255   for (v=user0; v; v=v->next)
256   {
257     if (v->number == nr_wanted)
258     {
259       nr_is_free = 0;
260       break;
261     }
262   }
263
264   if (options.verbose)
265   {
266     if (nr_is_free)
267       printf("RND_SERVER: client %d (%s) switches to # %d\n",
268              u->number, u->nick, nr_wanted);
269     else if (u->number == nr_wanted)
270       printf("RND_SERVER: client %d (%s) still has # %d\n",
271              u->number, u->nick, nr_wanted);
272     else
273       printf("RND_SERVER: client %d (%s) cannot switch (client %d still exists)\n",
274              u->number, u->nick, nr_wanted);
275   }
276
277   if (nr_is_free)
278     u->number = nr_wanted;
279
280   buf[0] = client_nr;
281   buf[1] = OP_NUMBER_WANTED;
282   buf[2] = nr_wanted;
283   buf[3] = u->number;
284
285   /*
286   sendtoone(u, 4);
287   */
288
289   broadcast(NULL, 4, 0);
290 }
291
292 static void Handle_OP_NICKNAME(struct user *u, unsigned int len)
293 {
294   struct user *v;
295   int i;
296
297   if (len>16)
298     len=16;
299   memcpy(u->nick, &buf[2], len-2);
300   u->nick[len-2] = 0;
301   for (i=0; i<len-2; i++)
302   {
303     if (u->nick[i] < ' ' || 
304         (u->nick[i] > 0x7e && u->nick[i] <= 0xa0))
305     {
306       u->nick[i] = 0;
307       break;
308     }
309   }
310
311   if (!u->introduced)
312   {
313     buf[0] = u->number;
314     buf[1] = OP_PLAYER_CONNECTED;
315     broadcast(u, 2, 0);
316   }
317               
318   if (options.verbose)
319     printf("RND_SERVER: client %d calls itself \"%s\"\n", u->number, u->nick);
320   buf[1] = OP_NICKNAME;
321   broadcast(u, len, 0);
322
323   if (!u->introduced)
324   {
325     for (v=user0; v; v=v->next)
326     {
327       if (v != u && v->introduced)
328       {
329         buf[0] = v->number;
330         buf[1] = OP_PLAYER_CONNECTED;
331         buf[2] = (v->games >> 8);
332         buf[3] = (v->games & 0xff);
333         sendtoone(u, 4);
334         buf[1] = OP_NICKNAME;
335         memcpy(&buf[2], v->nick, 14);
336         sendtoone(u, 2+strlen(v->nick));
337       }
338     }
339   }
340
341   u->introduced = 1;
342 }
343
344 static void Handle_OP_START_PLAYING(struct user *u)
345 {
346   struct user *v, *w;
347
348   if (options.verbose)
349     printf("RND_SERVER: client %d (%s) starts game [level %d from levedir %d (%s)]\n",
350            u->number, u->nick,
351            (buf[2] << 8) + buf[3],
352            (buf[4] << 8) + buf[5],
353            &buf[6]);
354
355   for (w=user0; w; w=w->next)
356   {
357     if (w->introduced)
358     {
359       w->active = 1;
360       w->playing = 1;
361       w->nextvictim = NULL;
362       for (v=NEXT(w); v!=w; v=NEXT(v))
363       {
364         if (v->introduced)
365         {
366           w->nextvictim = v;
367           break;
368         }
369       }
370     }
371   }
372
373   /* reset frame counter */
374   frame_counter = 0;
375
376   /* reset player actions */
377   for (v=user0; v; v=v->next)
378   {
379     v->action = 0;
380     v->action_received = 0;
381   }
382
383   broadcast(NULL, 10 + strlen(&buf[10])+1, 0);
384 }
385
386 static void Handle_OP_PAUSE_PLAYING(struct user *u)
387 {
388   if (options.verbose)
389     printf("RND_SERVER: client %d (%s) pauses game\n", u->number, u->nick);
390   broadcast(NULL, 2, 0);
391 }
392
393 static void Handle_OP_CONTINUE_PLAYING(struct user *u)
394 {
395   if (options.verbose)
396     printf("RND_SERVER: client %d (%s) continues game\n", u->number, u->nick);
397   broadcast(NULL, 2, 0);
398 }
399
400 static void Handle_OP_STOP_PLAYING(struct user *u)
401 {
402   if (options.verbose)
403     printf("RND_SERVER: client %d (%s) stops game\n", u->number, u->nick);
404   broadcast(NULL, 2, 0);
405 }
406
407 static void Handle_OP_MOVE_FIGURE(struct user *u)
408 {
409   struct user *v;
410   int last_client_nr = 0;
411   int i;
412
413   /* store player action */
414   for (v=user0; v; v=v->next)
415   {
416     if (v->number == u->number)
417     {
418       v->action = buf[2];
419       v->action_received = 1;
420     }
421   }
422
423   /* check if server received action from each player */
424   for (v=user0; v; v=v->next)
425   {
426     if (!v->action_received)
427       return;
428
429     if (v->number > last_client_nr)
430       last_client_nr = v->number;
431   }
432
433   /* initialize all player actions to zero */
434   for (i=0; i<last_client_nr; i++)
435     buf[6 + i] = 0;
436
437   /* broadcast actions of all players to all players */
438   for (v=user0; v; v=v->next)
439   {
440     buf[6 + v->number-1] = v->action;
441     v->action = 0;
442     v->action_received = 0;
443   }
444
445   buf[2] = (unsigned char)((frame_counter >> 24) & 0xff);
446   buf[3] = (unsigned char)((frame_counter >> 16) & 0xff);
447   buf[4] = (unsigned char)((frame_counter >>  8) & 0xff);
448   buf[5] = (unsigned char)((frame_counter >>  0) & 0xff);
449
450   broadcast(NULL, 6 + last_client_nr, 0);
451
452   frame_counter++;
453
454   /*
455     if (verbose)
456     printf("RND_SERVER: frame %d: client %d (%s) moves player [0x%02x]\n",
457     frame_counter,
458     u->number, u->nick, buf[2]);
459   */
460 }
461
462 void NetworkServer(int port, int serveronly)
463 {
464   int i, sl, on;
465   struct user *u;
466   int mfd;
467   int r; 
468   unsigned int len;
469   struct protoent *tcpproto;
470   struct timeval tv;
471   int is_daemon = 0;
472
473 #ifndef NeXT
474   struct sigaction sact;
475 #endif
476
477   if (port == 0)
478     port = DEFAULTPORT;
479
480   if (!serveronly)
481     onceonly = 1;
482
483   if ((tcpproto = getprotobyname("tcp")) != NULL)
484     tcp = tcpproto->p_proto;
485
486 #ifdef NeXT
487   signal(SIGPIPE, SIG_IGN);
488 #else
489   sact.sa_handler = SIG_IGN;
490   sigemptyset(&sact.sa_mask);
491   sact.sa_flags = 0;
492   sigaction(SIGPIPE, &sact, NULL);
493 #endif
494
495
496   lfd = socket(PF_INET, SOCK_STREAM, 0);
497   saddr.sin_family = AF_INET;
498   saddr.sin_addr.s_addr = htonl(INADDR_ANY);
499   saddr.sin_port = htons(port);
500
501   if (lfd < 0)
502     syserr("socket");
503   on = 1;
504
505   setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(int));
506   if (bind(lfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
507     syserr("bind");
508
509   listen(lfd, 5);
510
511   if (is_daemon)
512   {
513     /* become a daemon, breaking all ties with the controlling terminal */
514     options.verbose = 0;
515     for (i=0; i<255; i++)
516     {
517       if (i != lfd)
518         close(i);
519     }
520
521     if (fork())
522       exit(0);
523     setsid();
524     if (fork())
525       exit(0);
526     chdir("/");
527
528     /* open a fake stdin, stdout, stderr, just in case */
529     open("/dev/null", O_RDONLY);
530     open("/dev/null", O_WRONLY);
531     open("/dev/null", O_WRONLY);
532   }
533
534   if (options.verbose)
535   {
536     printf("rocksndiamonds network server: started up, listening on port %d\n",
537            port);
538     printf("rocksndiamonds network server: using protocol version %d.%d.%d\n",
539            PROTOCOL_VERSION_1, PROTOCOL_VERSION_2, PROTOCOL_VERSION_3);
540   }
541
542   while(1)
543   {
544     interrupt = 0;
545
546     for (u=user0; u; u=u->next)
547       flushuser(u);
548
549     FD_ZERO(&fds);
550     mfd = lfd;
551     u = user0;
552     while (u)
553     {
554       FD_SET(u->fd, &fds);
555       if (u->fd > mfd)
556         mfd = u->fd;
557       u = u->next;
558     }
559     FD_SET(lfd, &fds);
560     tv.tv_sec = 0;
561     tv.tv_usec = 500000;
562     if ((sl = select(mfd + 1, &fds, NULL, NULL, &tv)) < 0)
563     {
564       if (errno != EINTR)
565         syserr("select");
566       else
567         continue;
568     }
569
570     if (sl < 0)
571       continue;
572     
573     if (sl == 0)
574       continue;
575
576     if (FD_ISSET(lfd, &fds))
577     {
578       int newfd, slen;
579
580       slen = sizeof(saddr);
581       newfd = accept(lfd, (struct sockaddr *)&saddr, &slen);
582       if (newfd < 0)
583       {
584         if (errno != EINTR)
585           syserr("accept");
586       }
587       else
588       {
589         if (tcp != -1)
590         {
591           on = 1;
592           setsockopt(newfd, tcp, TCP_NODELAY, (char *)&on, sizeof(int));
593         }
594         new_connect(newfd);
595       }
596       continue;
597     }
598
599     u = user0;
600
601     do
602     {
603       if (FD_ISSET(u->fd, &fds))
604       {
605         r = read(u->fd, u->readbuf + u->nread, MAX_BUFFER_SIZE - u->nread);
606         if (r <= 0)
607         {
608           if (options.verbose)
609             printf("RND_SERVER: EOF from client %d (%s)\n", u->number, u->nick);
610           dropuser(u);
611           interrupt = 1;
612           break;
613         }
614         u->nread += r;
615         while (u->nread >= 4 && u->nread >= 4 + u->readbuf[3])
616         {
617           len = u->readbuf[3];
618           if (u->readbuf[0] || u->readbuf[1] || u->readbuf[2])
619           {
620             if (options.verbose)
621               printf("RND_SERVER: crap from client %d (%s)\n", u->number, u->nick);
622             write(u->fd, "\033]50;kanji24\007\033#8\033(0", 19);
623             dropuser(u);
624             interrupt = 1;
625             break;
626           }
627           memcpy(buf, &u->readbuf[4], len);
628           u->nread -= 4 + len;
629           memmove(u->readbuf, u->readbuf + 4 + len, u->nread);
630
631           buf[0] = u->number;
632           if (!u->introduced && buf[1] != OP_NICKNAME)
633           {
634             if (options.verbose)
635               printf("RND_SERVER: !(client %d)->introduced && buf[1]==%d (expected OP_NICKNAME)\n", buf[0], buf[1]);
636
637             dropuser(u);
638             interrupt = 1;
639             break;
640           }
641
642           switch(buf[1])
643           {
644             case OP_NICKNAME:
645               Handle_OP_NICKNAME(u, len);
646               break;
647
648             case OP_PROTOCOL_VERSION:
649               Handle_OP_PROTOCOL_VERSION(u, len);
650               break;
651
652             case OP_NUMBER_WANTED:
653               Handle_OP_NUMBER_WANTED(u);
654               break;
655
656             case OP_START_PLAYING:
657               Handle_OP_START_PLAYING(u);
658               break;
659
660             case OP_PAUSE_PLAYING:
661               Handle_OP_PAUSE_PLAYING(u);
662               break;
663
664             case OP_CONTINUE_PLAYING:
665               Handle_OP_CONTINUE_PLAYING(u);
666               break;
667
668             case OP_STOP_PLAYING:
669               Handle_OP_STOP_PLAYING(u);
670               break;
671
672             case OP_MOVE_FIGURE:
673               Handle_OP_MOVE_FIGURE(u);
674               break;
675
676             case OP_MSG:
677               buf[len] = '\0';
678               if (options.verbose)
679                 printf("RND_SERVER: client %d (%s) sends message: %s\n", u->number, u->nick, &buf[2]);
680               broadcast(u, len, 0);
681               break;
682             
683             default:
684               if (options.verbose)
685                 printf("RND_SERVER: opcode %d from client %d (%s) not understood\n", buf[0], u->number, u->nick);
686           }
687         }
688       }
689
690       if (u && !interrupt)
691         u = u->next;
692     }
693     while (u && !interrupt);
694   }
695 }