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