1 /* $Id: ipx_udp.c,v 1.8 2003-10-12 09:17:47 btb Exp $ */
4 * IPX driver for native Linux TCP/IP networking (UDP implementation)
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.
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
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
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
29 * No network server software is needed, neither KIX nor KaliNIX.
31 * NOTE: with the change to allow the user to choose the network
32 * driver from the game menu, the following is not anymore precise:
33 * the command line argument "-udp" is only necessary to supply udp
36 * Add command line argument "-udp". In default operation D1X will send
37 * broadcasts too all the local interfaces found. But you may also use
38 * additional parameter specified after "-udp" to modify the default
39 * broadcasting style and UDP port numbers binding:
41 * ./d1x -udp [@SHIFT]=HOST_LIST Broadcast ONLY to HOST_LIST
42 * ./d1x -udp [@SHIFT]+HOST_LIST Broadcast both to local ifaces & to HOST_LIST
44 * HOST_LIST is a comma (',') separated list of HOSTs:
45 * HOST is an IPv4 address (so-called quad like 192.168.1.2) or regular hostname
46 * HOST can also be in form 'address:SHIFT'
47 * SHIFT sets the UDP port base offset (e.g. +2), can be used to run multiple
48 * clients on one host simultaneously. This SHIFT has nothing to do
49 * with the dynamic-sockets (PgUP/PgDOWN) option in Descent, it's another
50 * higher-level differentiation option.
55 * - Run D1X to participate in normal local network (Linux only, of course)
57 * ./d1x -udp @1=localhost:2 & ./d1x -udp @2=localhost:1
58 * - Run two clients simultaneously fighting each other (only each other)
60 * ./d1x -udp =192.168.4.255
61 * - Run distant Descent which will participate with remote network
62 * 192.168.4.0 with netmask 255.255.255.0 (broadcast has 192.168.4.255)
63 * - You'll have to also setup hosts in that network accordingly:
64 * ./d1x -udp +UPPER_DISTANT_MACHINE_NAME
76 #include <netinet/in.h> /* for htons & co. */
81 #include <sys/ioctl.h>
82 #include <sys/socket.h>
84 # include <sys/sockio.h>
92 extern unsigned char ipx_MyAddress[10];
96 #define UDP_BASEPORT 28342
97 #define PORTSHIFT_TOLERANCE 0x100
98 #define MAX_PACKETSIZE 8192
100 /* Packet format: first is the signature { 0xD1,'X' } which can be also
101 * { 'D','1','X','u','d','p'} for old-fashioned packets.
102 * Then follows virtual socket number (as changed during PgDOWN/PgUP)
103 * in network-byte-order as 2 bytes (u_short). After such 4/8 byte header
104 * follows raw data as communicated with D1X network core functions.
107 // Length HAS TO BE 6!
108 #define D1Xudp "D1Xudp"
109 // Length HAS TO BE 2!
110 #define D1Xid "\xD1X"
112 static int open_sockets = 0;
113 static int dynamic_socket = 0x401;
114 static const int val_one=1;
116 /* OUR port. Can be changed by "@X[+=]..." argument (X is the shift value)
119 static int baseport=UDP_BASEPORT;
121 /* Have we some old D1X in network and have we to maintain compatibility?
122 * FIXME: Following scenario is braindead:
123 * A (NEW) , B (OLD) , C (NEW)
124 * host A) We start new D1X. A-newcomm, B-none , C-none
125 * host B) We start OLD D1X. A-newcomm, B-oldcomm, C-none
126 * Now host A hears host B and switches: A-oldcomm, B-oldcomm, C-none
127 * host C) We start new D1X. A-oldcomm, B-oldcomm, C-newcomm
128 * Now host C hears host A/B and switches: A-oldcomm, B-oldcomm, C-oldcomm
129 * Now host B finishes: A-oldcomm, B-none , C-oldcomm
131 * But right now we have hosts A and C, both new code equipped but
132 * communicating wastefully by the OLD protocol! Bummer.
135 static char compatibility=0;
137 static int have_empty_address() {
139 for (i = 0; i < 10 && !ipx_MyAddress[i]; i++) ;
143 #define MSGHDR "IPX_udp: "
145 static void msg(const char *fmt,...)
148 fputs(MSGHDR,stdout);
155 static void chk(void *p)
158 msg("FATAL: Virtual memory exhausted!");
162 #define FAIL(m...) do { msg(#m); return -1; } while (0)
164 /* Find as much as MAX_BRDINTERFACES during local iface autoconfiguration.
165 * Note that more interfaces can be added during manual configuration
166 * or host-received-packet autoconfiguration
169 #define MAX_BRDINTERFACES 16
171 /* We require the interface to be UP and RUNNING to accept it.
174 #define IF_REQFLAGS (IFF_UP|IFF_RUNNING)
176 /* We reject any interfaces declared as LOOPBACK type.
178 #define IF_NOTFLAGS (IFF_LOOPBACK)
180 static struct sockaddr_in *broads,broadmasks[MAX_BRDINTERFACES];
181 static int broadnum,masksnum,broadsize;
183 /* We'll check whether the "broads" array of destination addresses is now
184 * full and so needs expanding.
187 static void chkbroadsize(void)
189 if (broadnum<broadsize) return;
190 broadsize=broadsize?broadsize*2:8;
191 chk(broads=realloc(broads,sizeof(*broads)*broadsize));
194 /* This function is called during init and has to grab all system interfaces
195 * and collect their broadcast-destination addresses (and their netmasks).
196 * Typically it founds only one ethernet card and so returns address in
197 * the style "192.168.1.255" with netmask "255.255.255.0".
198 * Broadcast addresses are filled into "broads", netmasks to "broadmasks".
201 /* Stolen from my GGN */
202 static int addiflist(void)
204 unsigned cnt=MAX_BRDINTERFACES,i,j;
205 struct ifconf ifconf;
207 struct sockaddr_in *sinp,*sinmp;
210 if ((sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))<0)
211 FAIL("Creating socket() failure during broadcast detection: %m");
214 if (ioctl(sock,SIOCGIFCOUNT,&cnt))
215 { /* msg("Getting iterface count error: %m"); */ }
220 chk(ifconf.ifc_req=alloca((ifconf.ifc_len=cnt*sizeof(struct ifreq))));
221 if (ioctl(sock,SIOCGIFCONF,&ifconf)||ifconf.ifc_len%sizeof(struct ifreq)) {
223 FAIL("ioctl(SIOCGIFCONF) failure during broadcast detection: %m");
225 cnt=ifconf.ifc_len/sizeof(struct ifreq);
226 chk(broads=malloc(cnt*sizeof(*broads)));
228 for (i=j=0;i<cnt;i++) {
229 if (ioctl(sock,SIOCGIFFLAGS,ifconf.ifc_req+i)) {
231 FAIL("ioctl(udp,\"%s\",SIOCGIFFLAGS) error: %m",ifconf.ifc_req[i].ifr_name);
233 if (((ifconf.ifc_req[i].ifr_flags&IF_REQFLAGS)!=IF_REQFLAGS)||
234 (ifconf.ifc_req[i].ifr_flags&IF_NOTFLAGS))
236 if (ioctl(sock,(ifconf.ifc_req[i].ifr_flags&IFF_BROADCAST?SIOCGIFBRDADDR:SIOCGIFDSTADDR),ifconf.ifc_req+i)) {
238 FAIL("ioctl(udp,\"%s\",SIOCGIF{DST/BRD}ADDR) error: %m",ifconf.ifc_req[i].ifr_name);
241 sinp = (struct sockaddr_in *)&ifconf.ifc_req[i].ifr_broadaddr;
242 #if 0 // old, not portable code
243 sinmp = (struct sockaddr_in *)&ifconf.ifc_req[i].ifr_netmask;
244 #else // portable code
245 if (ioctl(sock, SIOCGIFNETMASK, ifconf.ifc_req+i)) {
247 FAIL("ioctl(udp,\"%s\",SIOCGIFNETMASK) error: %m", ifconf.ifc_req[i].ifr_name);
249 sinmp = (struct sockaddr_in *)&ifconf.ifc_req[i].ifr_addr;
251 if (sinp->sin_family!=AF_INET || sinmp->sin_family!=AF_INET) continue;
253 broads[j].sin_port=UDP_BASEPORT; //FIXME: No possibility to override from cmdline
254 broadmasks[j]=*sinmp;
262 #define addreq(a,b) ((a).sin_port==(b).sin_port&&(a).sin_addr.s_addr==(b).sin_addr.s_addr)
264 /* Previous function addiflist() can (and probably will) report multiple
265 * same addresses. On some Linux boxes is present both device "eth0" and
266 * "dummy0" with the same IP addreesses - we'll filter it here.
269 static void unifyiflist(void)
273 for (s=0;s<broadnum;s++) {
275 if (addreq(broads[s],broads[i])) break;
276 if (i>=s) broads[d++]=broads[s];
281 static unsigned char qhbuf[6];
283 /* Parse PORTSHIFT numeric parameter
286 static void portshift(const char *cs)
289 unsigned short ports=0;
292 if (port<-PORTSHIFT_TOLERANCE || port>+PORTSHIFT_TOLERANCE)
293 msg("Invalid portshift in \"%s\", tolerance is +/-%d",cs,PORTSHIFT_TOLERANCE);
294 else ports=htons(port);
295 memcpy(qhbuf+4,&ports,2);
298 /* Do hostname resolve on name "buf" and return the address in buffer "qhbuf".
300 static unsigned char *queryhost(char *buf)
306 if ((s=strrchr(buf,':'))) {
311 else memset(qhbuf+4,0,2);
312 he=gethostbyname((char *)buf);
315 msg("Error resolving my hostname \"%s\"",buf);
318 if (he->h_addrtype!=AF_INET || he->h_length!=4) {
319 msg("Error parsing resolved my hostname \"%s\"",buf);
322 if (!*he->h_addr_list) {
323 msg("My resolved hostname \"%s\" address list empty",buf);
326 memcpy(qhbuf,(*he->h_addr_list),4);
330 /* Dump raw form of IP address/port by fancy output to user
332 static void dumpraddr(unsigned char *a)
335 printf("[%u.%u.%u.%u]",a[0],a[1],a[2],a[3]);
336 port=(signed short)ntohs(*(unsigned short *)(a+4));
337 if (port) printf(":%+d",port);
340 /* Like dumpraddr() but for structure "sockaddr_in"
343 static void dumpaddr(struct sockaddr_in *sin)
345 unsigned short ports;
347 memcpy(qhbuf+0,&sin->sin_addr,4);
348 ports=htons(((short)ntohs(sin->sin_port))-UDP_BASEPORT);
349 memcpy(qhbuf+4,&ports,2);
353 /* Startup... Uninteresting parsing...
356 int ipx_udp_GetMyAddress(void) {
362 if (!have_empty_address())
365 if (!((i=FindArg("-udp")) && (s=Args[i+1]) && (*s=='=' || *s=='+' || *s=='@'))) s=NULL;
367 if (gethostname(buf,sizeof(buf))) FAIL("Error getting my hostname");
368 if (!(queryhost(buf))) FAIL("Querying my own hostname \"%s\"",buf);
370 if (s) while (*s=='@') {
372 while (isdigit(*s)) s++;
375 memset(ipx_MyAddress+0,0,4);
376 memcpy(ipx_MyAddress+4,qhbuf,6);
377 baseport+=(short)ntohs(*(unsigned short *)(qhbuf+4));
379 if (!s || (s && !*s)) addiflist();
381 if (*s=='+') addiflist();
384 struct sockaddr_in *sin;
385 while (isspace(*s)) s++;
387 for (s2=s;*s2 && *s2!=',';s2++);
388 chk(ns=malloc(s2-s+1));
391 if (!queryhost(ns)) msg("Ignored broadcast-destination \"%s\" as being invalid",ns);
394 sin=broads+(broadnum++);
395 sin->sin_family=AF_INET;
396 memcpy(&sin->sin_addr,qhbuf+0,4);
397 sin->sin_port=htons(((short)ntohs(*(unsigned short *)(qhbuf+4)))+UDP_BASEPORT);
404 printf(MSGHDR "Using TCP/IP address ");
405 dumpraddr(ipx_MyAddress+4);
408 printf(MSGHDR "Using %u broadcast-dest%s:",broadnum,(broadnum==1?"":"s"));
409 for (i=0;i<broadnum;i++) {
419 /* We should probably avoid such insanity here as during PgUP/PgDOWN
420 * (virtual port number change) we wastefully destroy/create the same
421 * socket here (binded always to "baseport"). FIXME.
422 * "open_sockets" can be only 0 or 1 anyway.
425 static int ipx_udp_OpenSocket(ipx_socket_t *sk, int port) {
426 struct sockaddr_in sin;
429 if (have_empty_address())
430 if (ipx_udp_GetMyAddress() < 0) FAIL("Error getting my address");
432 msg("OpenSocket on D1X socket port %d",port);
435 port = dynamic_socket++;
437 if ((sk->fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0) {
439 FAIL("socket() creation failed on port %d: %m",port);
441 if (setsockopt(sk->fd,SOL_SOCKET,SO_BROADCAST,&val_one,sizeof(val_one))) {
442 if (close(sk->fd)) msg("close() failed during error recovery: %m");
444 FAIL("setsockopt(SO_BROADCAST) failed: %m");
446 sin.sin_family=AF_INET;
447 sin.sin_addr.s_addr=htonl(INADDR_ANY);
448 sin.sin_port=htons(baseport);
449 if (bind(sk->fd,(struct sockaddr *)&sin,sizeof(sin))) {
450 if (close(sk->fd)) msg("close() failed during error recovery: %m");
452 FAIL("bind() to UDP port %d failed: %m",baseport);
460 /* The same comment as in previous "ipx_udp_OpenSocket"...
463 static void ipx_udp_CloseSocket(ipx_socket_t *mysock) {
465 msg("close w/o open");
468 msg("CloseSocket on D1X socket port %d",mysock->socket);
469 if (close(mysock->fd))
470 msg("close() failed on CloseSocket D1X socket port %d: %m",mysock->socket);
472 if (--open_sockets) {
473 msg("(closesocket) %d sockets left", open_sockets);
478 /* Here we'll send the packet to our host. If it is unicast packet, send
479 * it to IP address/port as retrieved from IPX address. Otherwise (broadcast)
480 * we'll repeat the same data to each host in our broadcasting list.
483 static int ipx_udp_SendPacket(ipx_socket_t *mysock, IPXPacket_t *IPXHeader,
484 u_char *data, int dataLen) {
485 struct sockaddr_in toaddr,*dest;
491 msg("SendPacket enter, dataLen=%d",dataLen);
493 if (dataLen<0 || dataLen>MAX_PACKETSIZE) return -1;
494 chk(buf=alloca(8+dataLen));
495 if (compatibility) memcpy(buf+0,D1Xudp,6),buf+=6;
496 else memcpy(buf+0,D1Xid ,2),buf+=2;
497 memcpy(buf+0,IPXHeader->Destination.Socket,2);
498 memcpy(buf+2,data,dataLen);
500 toaddr.sin_family=AF_INET;
501 memcpy(&toaddr.sin_addr,IPXHeader->Destination.Node+0,4);
502 toaddr.sin_port=htons(((short)ntohs(*(unsigned short *)(IPXHeader->Destination.Node+4)))+UDP_BASEPORT);
504 for (bcast=(toaddr.sin_addr.s_addr==htonl(INADDR_BROADCAST)?0:-1);bcast<broadnum;bcast++) {
505 if (bcast>=0) dest=broads+bcast;
509 printf(MSGHDR "sendto((%d),Node=[4] %02X %02X,Socket=%02X %02X,s_port=%u,",
511 IPXHeader->Destination.Node [4],IPXHeader->Destination.Node [5],
512 IPXHeader->Destination.Socket[0],IPXHeader->Destination.Socket[1],
513 ntohs(dest->sin_port));
517 i=sendto(mysock->fd,buf-(compatibility?6:2),(compatibility?8:4)+dataLen,
518 0,(struct sockaddr *)dest,sizeof(*dest));
519 if (bcast==-1) return (i<8?-1:i-8);
524 /* Here we will receive new packet to the given buffer. Both formats of packets
525 * are supported, we fallback to old format when first obsolete packet is seen.
526 * If the (valid) packet is received from unknown host, we will add it to our
527 * broadcasting list. FIXME: For now such autoconfigured hosts are NEVER removed.
530 static int ipx_udp_ReceivePacket(ipx_socket_t *s, char *outbuf, int outbufsize,
531 struct ipx_recv_data *rd) {
533 struct sockaddr_in fromaddr;
534 int fromaddrsize=sizeof(fromaddr);
535 unsigned short ports;
539 if ((size=recvfrom(s->fd,outbuf,outbufsize,0,(struct sockaddr *)&fromaddr,&fromaddrsize))<0)
542 printf(MSGHDR "recvfrom((%d-8=%d),",size,size-8);
546 if (fromaddr.sin_family!=AF_INET) return -1;
547 if (size<4) return -1;
548 if (memcmp(outbuf+0,D1Xid,2)) {
549 if (size<8 || memcmp(outbuf+0,D1Xudp,6)) return -1;
550 if (!compatibility) {
552 fputs(MSGHDR "Received obsolete packet from ",stdout);
554 puts(", upgrade that machine.\n" MSGHDR "Turning on compatibility mode...");
560 /* Lace: (dst_socket & src_socket) should be network-byte-order by comment in include/ipx_drv.h */
561 /* This behaviour presented here is broken. It is not used anywhere, so why bother? */
562 rd->src_socket = ntohs(*(unsigned short *)(outbuf+offs));
563 if (rd->src_socket != s->socket) {
565 msg(" - pkt was dropped (dst=%d,my=%d)",rd->src_socket,s->socket);
569 rd->dst_socket = s->socket;
571 // check if we already have sender of this packet in broadcast list
572 for (i=0;i<broadnum;i++) {
574 if (addreq(fromaddr,broads[i])) break;
577 if (fromaddr.sin_port==broads[i].sin_port
578 &&( fromaddr.sin_addr.s_addr & broadmasks[i].sin_addr.s_addr)
579 ==(broads[i].sin_addr.s_addr & broadmasks[i].sin_addr.s_addr)) break;
582 if (i>=broadnum) { // we don't have sender of this packet in our broadcast list
584 broads[broadnum++]=fromaddr;
585 fputs(MSGHDR "Adding host ",stdout);
587 puts(" to broadcasting address list");
590 memmove(outbuf,outbuf+offs+2,size-(offs+2));
593 memcpy(rd->src_node+0,&fromaddr.sin_addr,4);
594 ports=htons(ntohs(fromaddr.sin_port)-UDP_BASEPORT);
595 memcpy(rd->src_node+4,&ports,2);
596 memset(rd->src_network, 0, 4);
599 printf(MSGHDR "ReceivePacket: size=%d,from=",size);
600 dumpraddr(rd->src_node);
607 struct ipx_driver ipx_udp = {
608 ipx_udp_GetMyAddress,
612 ipx_udp_ReceivePacket,
613 ipx_general_PacketReady,
614 NULL, // InitNetgameAuxData
615 NULL, // HandleNetgameAuxData
616 NULL, // HandleLeaveGame
617 NULL // SendGamePacket