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