]> icculus.org git repositories - btb/d2x.git/blob - arch/linux/ipx_udp.c
enabled linux joystick, kali
[btb/d2x.git] / arch / linux / ipx_udp.c
1 /* $Id: */
2
3 /*
4  *
5  * IPX driver for native Linux TCP/IP networking (UDP implementation)
6  *   Version 0.99.2
7  * Contact Jan [Lace] Kratochvil <short@ucw.cz> for assistance
8  * (no "It somehow doesn't work! What should I do?" complaints, please)
9  * Special thanks to Vojtech Pavlik <vojtech@ucw.cz> for testing.
10  *
11  * Also you may see KIX - KIX kix out KaliNix (in Linux-Linux only):
12  *   http://atrey.karlin.mff.cuni.cz/~short/sw/kix.c.gz
13  *
14  * Primarily based on ipx_kali.c - "IPX driver for KaliNix interface"
15  *   which is probably mostly by Jay Cotton <jay@kali.net>.
16  * Parts shamelessly stolen from my KIX v0.99.2 and GGN v0.100
17  *
18  * Changes:
19  * --------
20  * 0.99.1 - now the default broadcast list also contains all point-to-point
21  *          links with their destination peer addresses
22  * 0.99.2 - commented a bit :-) 
23  *        - now adds to broadcast list each host it gets some packet from
24  *          which is already not covered by local physical ethernet broadcast
25  *        - implemented short-signature packet format
26  *        - compatibility mode for old D1X releases due to the previous bullet
27  *
28  * Configuration:
29  * --------------
30  * No network server software is needed, neither KIX nor KaliNIX.
31  *
32  * Add command line argument "-udp". In default operation D1X will send
33  * broadcasts too all the local interfaces found. But you may also use
34  * additional parameter specified after "-udp" to modify the default
35  * broadcasting style and UDP port numbers binding:
36  *
37  * ./d1x -udp [@SHIFT]=HOST_LIST   Broadcast ONLY to HOST_LIST
38  * ./d1x -udp [@SHIFT]+HOST_LIST   Broadcast both to local ifaces & to HOST_LIST
39  *
40  * HOST_LIST is a comma (',') separated list of HOSTs:
41  * HOST is an IPv4 address (so-called quad like 192.168.1.2) or regular hostname
42  * HOST can also be in form 'address:SHIFT'
43  * SHIFT sets the UDP port base offset (e.g. +2), can be used to run multiple
44  *       clients on one host simultaneously. This SHIFT has nothing to do
45  *       with the dynamic-sockets (PgUP/PgDOWN) option in Descent, it's another
46  *       higher-level differentiation option.
47  *
48  * Examples:
49  * ---------
50  * ./d1x -udp
51  *  - Run D1X to participate in normal local network (Linux only, of course)
52  *
53  * ./d1x -udp @1=localhost:2 & ./d1x -udp @2=localhost:1
54  *  - Run two clients simultaneously fighting each other (only each other)
55  *
56  * ./d1x -udp =192.168.4.255
57  *  - Run distant Descent which will participate with remote network
58  *    192.168.4.0 with netmask 255.255.255.0 (broadcast has 192.168.4.255)
59  *  - You'll have to also setup hosts in that network accordingly:
60  * ./d1x -udp +UPPER_DISTANT_MACHINE_NAME
61  *
62  * Have fun!
63  *
64  */
65
66 #ifdef HAVE_CONFIG_H
67 #include <conf.h>
68 #endif
69
70 #include <stdio.h>
71 #include <string.h>
72 #include <netinet/in.h> /* for htons & co. */
73 #include <unistd.h>
74 #include <stdarg.h>
75 #include <netdb.h>
76 #include <stdlib.h>
77 #include <net/if.h>
78 #include <sys/ioctl.h>
79 #include <ctype.h>
80
81 #include "ipx_drv.h"
82 #include "args.h"
83
84 extern unsigned char ipx_MyAddress[10];
85
86 // #define UDPDEBUG
87
88 #define UDP_BASEPORT 28342
89 #define PORTSHIFT_TOLERANCE 0x100
90 #define MAX_PACKETSIZE 8192
91
92 /* Packet format: first is the signature { 0xD1,'X' } which can be also
93  * { 'D','1','X','u','d','p'} for old-fashioned packets.
94  * Then follows virtual socket number (as changed during PgDOWN/PgUP)
95  * in network-byte-order as 2 bytes (u_short). After such 4/8 byte header
96  * follows raw data as communicated with D1X network core functions.
97  */
98
99 // Length HAS TO BE 6!
100 #define D1Xudp "D1Xudp"
101 // Length HAS TO BE 2!
102 #define D1Xid "\xD1X"
103
104 static int open_sockets = 0;
105 static int dynamic_socket = 0x401;
106 static const int val_one=1;
107
108 /* OUR port. Can be changed by "@X[+=]..." argument (X is the shift value)
109  */
110
111 static int baseport=UDP_BASEPORT;
112
113 /* Have we some old D1X in network and have we to maintain compatibility?
114  * FIXME: Following scenario is braindead:
115  *                                           A  (NEW) , B  (OLD) , C  (NEW)
116  *   host A) We start new D1X.               A-newcomm, B-none   , C-none
117  *   host B) We start OLD D1X.               A-newcomm, B-oldcomm, C-none
118  *   Now host A hears host B and switches:   A-oldcomm, B-oldcomm, C-none
119  *   host C) We start new D1X.               A-oldcomm, B-oldcomm, C-newcomm
120  *   Now host C hears host A/B and switches: A-oldcomm, B-oldcomm, C-oldcomm
121  *   Now host B finishes:                    A-oldcomm, B-none   , C-oldcomm
122  *
123  * But right now we have hosts A and C, both new code equipped but
124  * communicating wastefully by the OLD protocol! Bummer.
125  */
126
127 static char compatibility=0;
128
129 static int have_empty_address() {
130         int i;
131         for (i = 0; i < 10 && !ipx_MyAddress[i]; i++) ;
132         return i == 10;
133 }
134
135 #define MSGHDR "IPX_udp: "
136
137 static void msg(const char *fmt,...)
138 {
139 va_list ap;
140         fputs(MSGHDR,stdout);
141         va_start(ap,fmt);
142         vprintf(fmt,ap);
143         va_end(ap);
144         putchar('\n');
145 }
146
147 static void chk(void *p)
148 {
149         if (p) return;
150         msg("FATAL: Virtual memory exhausted!");
151         exit(EXIT_FAILURE);
152 }
153
154 #define FAIL(m...) do { msg(#m); return -1; } while (0)
155
156 /* Find as much as MAX_BRDINTERFACES during local iface autoconfiguration.
157  * Note that more interfaces can be added during manual configuration
158  * or host-received-packet autoconfiguration
159  */
160
161 #define MAX_BRDINTERFACES 16
162
163 /* We require the interface to be UP and RUNNING to accept it.
164  */
165
166 #define IF_REQFLAGS (IFF_UP|IFF_RUNNING)
167
168 /* We reject any interfaces declared as LOOPBACK type.
169  */
170 #define IF_NOTFLAGS (IFF_LOOPBACK)
171
172 static struct sockaddr_in *broads,broadmasks[MAX_BRDINTERFACES];
173 static int broadnum,masksnum,broadsize;
174
175 /* We'll check whether the "broads" array of destination addresses is now
176  * full and so needs expanding.
177  */
178
179 static void chkbroadsize(void)
180 {
181         if (broadnum<broadsize) return;
182         broadsize=broadsize?broadsize*2:8;
183         chk(broads=realloc(broads,sizeof(*broads)*broadsize));
184 }
185
186 /* This function is called during init and has to grab all system interfaces
187  * and collect their broadcast-destination addresses (and their netmasks).
188  * Typically it founds only one ethernet card and so returns address in
189  * the style "192.168.1.255" with netmask "255.255.255.0".
190  * Broadcast addresses are filled into "broads", netmasks to "broadmasks".
191  */
192
193 /* Stolen from my GGN */
194 static int addiflist(void)
195 {
196 unsigned cnt=MAX_BRDINTERFACES,i,j;
197 struct ifconf ifconf;
198 int sock;
199 struct sockaddr_in *sinp,*sinmp;
200
201         free(broads);
202         if ((sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))<0)
203                 FAIL("Creating socket() failure during broadcast detection: %m");
204
205 #ifdef SIOCGIFCOUNT
206         if (ioctl(sock,SIOCGIFCOUNT,&cnt))
207                 { /* msg("Getting iterface count error: %m"); */ }
208         else
209                 cnt=cnt*2+2;
210 #endif
211
212         chk(ifconf.ifc_req=alloca((ifconf.ifc_len=cnt*sizeof(struct ifreq))));
213         if (ioctl(sock,SIOCGIFCONF,&ifconf)||ifconf.ifc_len%sizeof(struct ifreq)) {
214                 close(sock);
215                 FAIL("ioctl(SIOCGIFCONF) failure during broadcast detection: %m");
216                 }
217         cnt=ifconf.ifc_len/sizeof(struct ifreq);
218         chk(broads=malloc(cnt*sizeof(*broads)));
219         broadsize=cnt;
220         for (i=j=0;i<cnt;i++) {
221                 if (ioctl(sock,SIOCGIFFLAGS,ifconf.ifc_req+i)) {
222                         close(sock);
223                         FAIL("ioctl(udp,\"%s\",SIOCGIFFLAGS) error: %m",ifconf.ifc_req[i].ifr_name);
224                         }
225                 if (((ifconf.ifc_req[i].ifr_flags&IF_REQFLAGS)!=IF_REQFLAGS)||
226                                  (ifconf.ifc_req[i].ifr_flags&IF_NOTFLAGS))
227                         continue;
228                 if (ioctl(sock,(ifconf.ifc_req[i].ifr_flags&IFF_BROADCAST?SIOCGIFBRDADDR:SIOCGIFDSTADDR),ifconf.ifc_req+i)) {
229                         close(sock);
230                         FAIL("ioctl(udp,\"%s\",SIOCGIF{DST/BRD}ADDR) error: %m",ifconf.ifc_req[i].ifr_name);
231                         }
232
233                 sinp =(struct sockaddr_in *)&ifconf.ifc_req[i].ifr_broadaddr;
234                 sinmp=(struct sockaddr_in *)&ifconf.ifc_req[i].ifr_netmask  ;
235                 if (sinp->sin_family!=AF_INET || sinmp->sin_family!=AF_INET) continue;
236                 broads[j]=*sinp;
237                 broads[j].sin_port=UDP_BASEPORT; //FIXME: No possibility to override from cmdline
238                 broadmasks[j]=*sinmp;
239                 j++;
240                 }
241         broadnum=j;
242         masksnum=j;
243         return(0);
244 }
245
246 #define addreq(a,b) ((a).sin_port==(b).sin_port&&(a).sin_addr.s_addr==(b).sin_addr.s_addr)
247
248 /* Previous function addiflist() can (and probably will) report multiple
249  * same addresses. On some Linux boxes is present both device "eth0" and
250  * "dummy0" with the same IP addreesses - we'll filter it here.
251  */
252
253 static void unifyiflist(void)
254 {
255 int d=0,s,i;
256
257         for (s=0;s<broadnum;s++) {
258                 for (i=0;i<s;i++)
259                         if (addreq(broads[s],broads[i])) break;
260                 if (i>=s) broads[d++]=broads[s];
261                 }
262         broadnum=d;
263 }
264
265 static unsigned char qhbuf[6];
266
267 /* Parse PORTSHIFT numeric parameter
268  */
269
270 static void portshift(const char *cs)
271 {
272 long port;
273 unsigned short ports=0;
274
275         port=atol(cs);
276         if (port<-PORTSHIFT_TOLERANCE || port>+PORTSHIFT_TOLERANCE)
277                 msg("Invalid portshift in \"%s\", tolerance is +/-%d",cs,PORTSHIFT_TOLERANCE);
278         else ports=htons(port);
279         memcpy(qhbuf+4,&ports,2);
280 }
281
282 /* Do hostname resolve on name "buf" and return the address in buffer "qhbuf".
283  */
284 static unsigned char *queryhost(char *buf)
285 {
286 struct hostent *he;
287 char *s;
288 char c=0;
289
290         if ((s=strrchr(buf,':'))) {
291           c=*s;
292           *s='\0';
293           portshift(s+1);
294           }
295         else memset(qhbuf+4,0,2);
296         he=gethostbyname((char *)buf);
297         if (s) *s=c;
298         if (!he) {
299                 msg("Error resolving my hostname \"%s\"",buf);
300                 return(NULL);
301                 }
302         if (he->h_addrtype!=AF_INET || he->h_length!=4) {
303           msg("Error parsing resolved my hostname \"%s\"",buf);
304                 return(NULL);
305                 }
306         if (!*he->h_addr_list) {
307           msg("My resolved hostname \"%s\" address list empty",buf);
308                 return(NULL);
309                 }
310         memcpy(qhbuf,(*he->h_addr_list),4);
311         return(qhbuf);
312 }
313
314 /* Dump raw form of IP address/port by fancy output to user
315  */
316 static void dumpraddr(unsigned char *a)
317 {
318 short port;
319         printf("[%u.%u.%u.%u]",a[0],a[1],a[2],a[3]);
320         port=(signed short)ntohs(*(unsigned short *)(a+4));
321         if (port) printf(":%+d",port);
322 }
323
324 /* Like dumpraddr() but for structure "sockaddr_in"
325  */
326
327 static void dumpaddr(struct sockaddr_in *sin)
328 {
329 unsigned short ports;
330
331         memcpy(qhbuf+0,&sin->sin_addr,4);
332         ports=htons(((short)ntohs(sin->sin_port))-UDP_BASEPORT);
333         memcpy(qhbuf+4,&ports,2);
334         dumpraddr(qhbuf);
335 }
336
337 /* Startup... Uninteresting parsing...
338  */
339
340 static int ipx_udp_GetMyAddress(void) {
341
342 char buf[256];
343 int i;
344 char *s,*s2,*ns;
345
346         if (!have_empty_address())
347                 return 0;
348
349         if (!((i=FindArg("-udp")) && (s=Args[i+1]) && (*s=='=' || *s=='+' || *s=='@'))) s=NULL;
350
351         if (gethostname(buf,sizeof(buf))) FAIL("Error getting my hostname");
352         if (!(queryhost(buf))) FAIL("Querying my own hostname \"%s\"",buf);
353
354         if (s) while (*s=='@') {
355                 portshift(++s);
356                 while (isdigit(*s)) s++;
357                 }
358
359         memset(ipx_MyAddress+0,0,4);
360         memcpy(ipx_MyAddress+4,qhbuf,6);
361         baseport+=(short)ntohs(*(unsigned short *)(qhbuf+4));
362
363         if (!s || (s && !*s)) addiflist();
364         else {
365                 if (*s=='+') addiflist();
366                 s++;
367                 for (;;) {
368 struct sockaddr_in *sin;
369                         while (isspace(*s)) s++;
370                         if (!*s) break;
371                         for (s2=s;*s2 && *s2!=',';s2++);
372                         chk(ns=malloc(s2-s+1));
373                         memcpy(ns,s,s2-s);
374                         ns[s2-s]='\0';
375                         if (!queryhost(ns)) msg("Ignored broadcast-destination \"%s\" as being invalid",ns);
376                         free(ns);
377                         chkbroadsize();
378                         sin=broads+(broadnum++);
379                         sin->sin_family=AF_INET;
380                         memcpy(&sin->sin_addr,qhbuf+0,4);
381                         sin->sin_port=htons(((short)ntohs(*(unsigned short *)(qhbuf+4)))+UDP_BASEPORT);
382                         s=s2+(*s2==',');
383                         }
384                 }
385
386         unifyiflist();
387
388         printf(MSGHDR "Using TCP/IP address ");
389         dumpraddr(ipx_MyAddress+4);
390         putchar('\n');
391         if (broadnum) {
392                 printf(MSGHDR "Using %u broadcast-dest%s:",broadnum,(broadnum==1?"":"s"));
393                 for (i=0;i<broadnum;i++) {
394                         putchar(' ');
395                         dumpaddr(broads+i);
396                         }
397                 putchar('\n');
398                 }
399
400         return 0;
401 }
402
403 /* We should probably avoid such insanity here as during PgUP/PgDOWN
404  * (virtual port number change) we wastefully destroy/create the same
405  * socket here (binded always to "baseport"). FIXME.
406  * "open_sockets" can be only 0 or 1 anyway.
407  */
408
409 static int ipx_udp_OpenSocket(ipx_socket_t *sk, int port) {
410 struct sockaddr_in sin;
411
412         if (!open_sockets)
413                 if (have_empty_address())
414                 if (ipx_udp_GetMyAddress() < 0) FAIL("Error getting my address");
415
416         msg("OpenSocket on D1X socket port %d",port);
417
418         if (!port)
419                 port = dynamic_socket++;
420
421         if ((sk->fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0) {
422                 sk->fd = -1;
423                 FAIL("socket() creation failed on port %d: %m",port);
424                 }
425   if (setsockopt(sk->fd,SOL_SOCKET,SO_BROADCAST,&val_one,sizeof(val_one))) {
426                 if (close(sk->fd)) msg("close() failed during error recovery: %m");
427                 sk->fd=-1;
428                 FAIL("setsockopt(SO_BROADCAST) failed: %m");
429                 }
430         sin.sin_family=AF_INET;
431         sin.sin_addr.s_addr=htonl(INADDR_ANY);
432         sin.sin_port=htons(baseport);
433         if (bind(sk->fd,(struct sockaddr *)&sin,sizeof(sin))) {
434                 if (close(sk->fd)) msg("close() failed during error recovery: %m");
435                 sk->fd=-1;
436                 FAIL("bind() to UDP port %d failed: %m",baseport);
437                 }
438
439         open_sockets++;
440         sk->socket = port;
441         return 0;
442 }
443
444 /* The same comment as in previous "ipx_udp_OpenSocket"...
445  */
446
447 static void ipx_udp_CloseSocket(ipx_socket_t *mysock) {
448         if (!open_sockets) {
449                 msg("close w/o open");
450                 return;
451         }
452         msg("CloseSocket on D1X socket port %d",mysock->socket);
453         if (close(mysock->fd))
454                 msg("close() failed on CloseSocket D1X socket port %d: %m",mysock->socket);
455         mysock->fd=-1;
456         if (--open_sockets) {
457                 msg("(closesocket) %d sockets left", open_sockets);
458                 return;
459         }
460 }
461
462 /* Here we'll send the packet to our host. If it is unicast packet, send
463  * it to IP address/port as retrieved from IPX address. Otherwise (broadcast)
464  * we'll repeat the same data to each host in our broadcasting list.
465  */
466
467 static int ipx_udp_SendPacket(ipx_socket_t *mysock, IPXPacket_t *IPXHeader,
468  u_char *data, int dataLen) {
469         struct sockaddr_in toaddr,*dest;
470         int i=dataLen;
471         int bcast;
472         char *buf;
473
474 #ifdef UDPDEBUG
475         msg("SendPacket enter, dataLen=%d",dataLen);
476 #endif
477         if (dataLen<0 || dataLen>MAX_PACKETSIZE) return -1;
478         chk(buf=alloca(8+dataLen));
479         if (compatibility) memcpy(buf+0,D1Xudp,6),buf+=6;
480         else               memcpy(buf+0,D1Xid ,2),buf+=2;
481         memcpy(buf+0,IPXHeader->Destination.Socket,2);
482         memcpy(buf+2,data,dataLen);
483  
484         toaddr.sin_family=AF_INET;
485         memcpy(&toaddr.sin_addr,IPXHeader->Destination.Node+0,4);
486         toaddr.sin_port=htons(((short)ntohs(*(unsigned short *)(IPXHeader->Destination.Node+4)))+UDP_BASEPORT);
487
488         for (bcast=(toaddr.sin_addr.s_addr==htonl(INADDR_BROADCAST)?0:-1);bcast<broadnum;bcast++) {
489                 if (bcast>=0) dest=broads+bcast;
490                 else dest=&toaddr;
491         
492 #ifdef UDPDEBUG
493                 printf(MSGHDR "sendto((%d),Node=[4] %02X %02X,Socket=%02X %02X,s_port=%u,",
494                         dataLen,
495                         IPXHeader->Destination.Node  [4],IPXHeader->Destination.Node  [5],
496                         IPXHeader->Destination.Socket[0],IPXHeader->Destination.Socket[1],
497                         ntohs(dest->sin_port));
498                 dumpaddr(dest);
499                 puts(").");
500 #endif
501                 i=sendto(mysock->fd,buf-(compatibility?6:2),(compatibility?8:4)+dataLen,
502                         0,(struct sockaddr *)dest,sizeof(*dest));
503                 if (bcast==-1) return (i<8?-1:i-8);
504                 }
505         return(dataLen);
506 }
507
508 /* Here we will receive new packet to the given buffer. Both formats of packets
509  * are supported, we fallback to old format when first obsolete packet is seen.
510  * If the (valid) packet is received from unknown host, we will add it to our
511  * broadcasting list. FIXME: For now such autoconfigured hosts are NEVER removed.
512  */
513
514 static int ipx_udp_ReceivePacket(ipx_socket_t *s, char *outbuf, int outbufsize, 
515  struct ipx_recv_data *rd) {
516         int size;
517         struct sockaddr_in fromaddr;
518         int fromaddrsize=sizeof(fromaddr);
519         unsigned short ports;
520         size_t offs;
521         int i;
522
523         if ((size=recvfrom(s->fd,outbuf,outbufsize,0,(struct sockaddr *)&fromaddr,&fromaddrsize))<0)
524                 return -1;
525 #ifdef UDPDEBUG
526         printf(MSGHDR "recvfrom((%d-8=%d),",size,size-8);
527         dumpaddr(&fromaddr);
528         puts(").");
529 #endif
530         if (fromaddr.sin_family!=AF_INET) return -1;
531         if (size<4) return -1;
532         if (memcmp(outbuf+0,D1Xid,2)) {
533                 if (size<8 || memcmp(outbuf+0,D1Xudp,6)) return -1;
534                 if (!compatibility) {
535                         compatibility=1;
536                         fputs(MSGHDR "Received obsolete packet from ",stdout);
537                         dumpaddr(&fromaddr);
538                         puts(", upgrade that machine.\n" MSGHDR "Turning on compatibility mode...");
539                         }
540                 offs=6;
541                 }
542         else offs=2;
543
544         /* Lace: (dst_socket & src_socket) should be network-byte-order by comment in include/ipx_drv.h */
545         /*       This behaviour presented here is broken. It is not used anywhere, so why bother? */
546         rd->src_socket = ntohs(*(unsigned short *)(outbuf+offs));
547         if (rd->src_socket != s->socket) {
548 #ifdef UDPDEBUG
549                 msg(" - pkt was dropped (dst=%d,my=%d)",rd->src_socket,s->socket);
550 #endif
551                 return -1;
552                 }
553         rd->dst_socket = s->socket;
554
555         for (i=0;i<broadnum;i++) {
556                 if (i>=masksnum) {
557                         if (addreq(fromaddr,broads[i])) break; 
558                         }
559                 else {
560                         if (fromaddr.sin_port==broads[i].sin_port
561                         &&( fromaddr.sin_addr.s_addr & broadmasks[i].sin_addr.s_addr)
562                         ==(broads[i].sin_addr.s_addr & broadmasks[i].sin_addr.s_addr)) break;
563                         }
564                 }
565         if (i>=broadnum) {
566                 chkbroadsize();
567                 broads[broadnum++]=fromaddr;
568                 fputs(MSGHDR "Adding host ",stdout);
569                 dumpaddr(&fromaddr);
570                 puts(" to broadcasting address list");
571                 }
572
573         memmove(outbuf,outbuf+offs+2,size-(offs+2));
574         size-=offs+2;
575
576         memcpy(rd->src_node+0,&fromaddr.sin_addr,4);
577         ports=htons(ntohs(fromaddr.sin_port)-UDP_BASEPORT);
578         memcpy(rd->src_node+4,&ports,2);
579         memset(rd->src_network, 0, 4);
580         rd->pkt_type = 0;
581 #ifdef UDPDEBUG
582         printf(MSGHDR "ReceivePacket: size=%d,from=",size);
583         dumpraddr(rd->src_node);
584         putchar('\n');
585 #endif
586
587         return size;
588 }
589
590 struct ipx_driver ipx_udp = {
591         ipx_udp_GetMyAddress,
592         ipx_udp_OpenSocket,
593         ipx_udp_CloseSocket,
594         ipx_udp_SendPacket,
595         ipx_udp_ReceivePacket,
596         ipx_general_PacketReady
597 };