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