add IPv4 multicasting support
[btb/d2x.git] / arch / win32 / winnet.c
1 /* $Id: winnet.c,v 1.10 2003-10-12 09:17:47 btb Exp $ */
2 /*
3 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
4 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
5 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
6 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
7 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
8 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
9 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
10 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
11 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
12 COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
13 */
14
15 /*
16  *
17  * Win32 lower-level network code.
18  * implements functions declared in include/ipx.h
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <conf.h>
24 #endif
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <winsock.h>
30
31 #include "args.h"
32 #include "error.h"
33 #include "ipx.h"
34 #include "ipx_drv.h"
35 #include "ipx_udp.h"
36 #include "ipx_mcast4.h"
37 #include "../../main/player.h"  /* for Players */
38 #include "../../main/multi.h"   /* for NetPlayers */
39
40 extern struct ipx_driver ipx_win;
41
42 #define MAX_IPX_DATA 576
43
44 int ipx_fd;
45 ipx_socket_t ipx_socket_data;
46 ubyte ipx_installed=0;
47 ushort ipx_socket = 0;
48 uint ipx_network = 0;
49 ubyte ipx_MyAddress[10];
50 int ipx_packetnum = 0;                  /* Sequence number */
51
52 /* User defined routing stuff */
53 typedef struct user_address {
54         ubyte network[4];
55         ubyte node[6];
56         ubyte address[6];
57 } user_address;
58 #define MAX_USERS 64
59 int Ipx_num_users = 0;
60 user_address Ipx_users[MAX_USERS];
61
62 #define MAX_NETWORKS 64
63 int Ipx_num_networks = 0;
64 uint Ipx_networks[MAX_NETWORKS];
65
66 int ipx_general_PacketReady(ipx_socket_t *s) {
67         fd_set set;
68         struct timeval tv;
69         
70         FD_ZERO(&set);
71         FD_SET(s->fd, &set);
72         tv.tv_sec = tv.tv_usec = 0;
73         if (select(FD_SETSIZE, &set, NULL, NULL, &tv) > 0)
74                 return 1;
75         else
76                 return 0;
77 }
78
79 struct ipx_driver *driver = &ipx_win;
80
81 ubyte * ipx_get_my_server_address()
82 {
83         return (ubyte *)&ipx_network;
84 }
85
86 ubyte * ipx_get_my_local_address()
87 {
88         return (ubyte *)(ipx_MyAddress + 4);
89 }
90
91 void arch_ipx_set_driver(int ipx_driver)
92 {
93         switch(ipx_driver) {
94         case IPX_DRIVER_IPX: driver = &ipx_win; break;
95         case IPX_DRIVER_UDP: driver = &ipx_udp; break;
96         case IPX_DRIVER_MCAST4: driver = &ipx_mcast4; break;
97         default: Int3();
98         }
99 }
100
101 int ipx_init(int socket_number)
102 {
103         int i;
104
105         WORD wVersionRequested;
106         WSADATA wsaData;
107
108         wVersionRequested = MAKEWORD(2, 0);
109         if (WSAStartup( wVersionRequested, &wsaData))
110         {
111           return IPX_SOCKET_ALREADY_OPEN;
112         }
113
114 #if 0
115         if ( LOBYTE( wsaData.wVersion ) != 2 ||
116           HIBYTE( wsaData.wVersion ) != 0 ) {
117            /* We couldn't find a usable WinSock DLL. */
118            WSACleanup( );
119            return IPX_SOCKET_TABLE_FULL;
120         }
121 #endif
122
123         if ((i = FindArg("-ipxnetwork")) && Args[i + 1]) {
124                 unsigned long n = strtol(Args[i + 1], NULL, 16);
125                 ipx_MyAddress[0] = (unsigned char)n >> 24; ipx_MyAddress[1] = (unsigned char)(n >> 16) & 255;
126                 ipx_MyAddress[2] = (unsigned char)(n >> 8) & 255; ipx_MyAddress[3] = (unsigned char)n & 255;
127                 printf("IPX: Using network %08x\n", (int) n);
128         }
129         if (driver->OpenSocket(&ipx_socket_data, socket_number)) {
130                 return IPX_NOT_INSTALLED;
131         }
132         driver->GetMyAddress();
133         memcpy(&ipx_network, ipx_MyAddress, 4);
134         Ipx_num_networks = 0;
135         memcpy( &Ipx_networks[Ipx_num_networks++], &ipx_network, 4 );
136         ipx_installed = 1;
137         atexit(ipx_close);
138         printf("ipx succesfully installed\n");
139         return IPX_INIT_OK;
140 }
141
142 void ipx_close()
143 {
144         if (ipx_installed) {
145                 WSACleanup();
146                 driver->CloseSocket(&ipx_socket_data);
147         }
148         ipx_installed = 0;
149 }
150
151 int ipx_get_packet_data( ubyte * data )
152 {
153         struct ipx_recv_data rd;
154         char buf[MAX_IPX_DATA];
155 //killed 6-15-99 to get rid of compile warnings - OE
156 //      uint best_id = 0;
157 //      uint pkt_num;
158 //end kill - OE
159         int size;
160         int best_size = 0;
161 //edited 04/12/99 Matt Mueller - duh, we don't want to throw all that data away!
162         //--killed-- Like the original, only take latest packet, throw away rest
163         //do _NOT_ throw them away!
164         while (driver->PacketReady(&ipx_socket_data)) {
165                 if ((size = 
166                      driver->ReceivePacket(&ipx_socket_data, buf, 
167                       sizeof(buf), &rd)) > 4) {
168                      if (!memcmp(rd.src_network, ipx_MyAddress, 10)) 
169                         continue;       /* don't get own pkts */
170 //--killed--                 pkt_num = *(uint *)buf;
171 //--killed--                 if (pkt_num >= best_id) {
172                         memcpy(data, buf + 4, size - 4);
173                                 return size-4;
174 //--killed--                    best_id = pkt_num;
175 //--killed--                    best_size = size - 4;
176 //--killed--                 }
177 //end edit -MM
178                 }
179         }
180         return best_size;
181 }
182
183 void ipx_send_packet_data( ubyte * data, int datasize, ubyte *network, ubyte *address, ubyte *immediate_address )
184 {
185         u_char buf[MAX_IPX_DATA];
186         IPXPacket_t ipx_header;
187         
188         memcpy(ipx_header.Destination.Network, network, 4);
189         memcpy(ipx_header.Destination.Node, immediate_address, 6);
190         *(u_short *)ipx_header.Destination.Socket = htons(ipx_socket_data.socket);
191         ipx_header.PacketType = 4; /* Packet Exchange */
192         *(uint *)buf = ipx_packetnum++;
193         memcpy(buf + 4, data, datasize);
194         driver->SendPacket(&ipx_socket_data, &ipx_header, buf, datasize + 4);
195 }
196
197 void ipx_get_local_target( ubyte * server, ubyte * node, ubyte * local_target )
198 {
199         // let's hope Linux knows how to route it
200         memcpy( local_target, node, 6 );
201 }
202
203 void ipx_send_broadcast_packet_data( ubyte * data, int datasize )       
204 {
205         int i, j;
206         ubyte broadcast[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
207         ubyte local_address[6];
208
209         // Set to all networks besides mine
210         for (i=0; i<Ipx_num_networks; i++ )     {
211                 if ( memcmp( &Ipx_networks[i], &ipx_network, 4 ) )      {
212                         ipx_get_local_target( (ubyte *)&Ipx_networks[i], broadcast, local_address );
213                         ipx_send_packet_data( data, datasize, (ubyte *)&Ipx_networks[i], broadcast, local_address );
214                 } else {
215                         ipx_send_packet_data( data, datasize, (ubyte *)&Ipx_networks[i], broadcast, broadcast );
216                 }
217         }
218
219         //OLDipx_send_packet_data( data, datasize, (ubyte *)&ipx_network, broadcast, broadcast );
220
221         // Send directly to all users not on my network or in the network list.
222         for (i=0; i<Ipx_num_users; i++ )        {
223                 if ( memcmp( Ipx_users[i].network, &ipx_network, 4 ) )  {
224                         for (j=0; j<Ipx_num_networks; j++ )             {
225                                 if (!memcmp( Ipx_users[i].network, &Ipx_networks[j], 4 ))
226                                         goto SkipUser;
227                         }
228                         ipx_send_packet_data( data, datasize, Ipx_users[i].network, Ipx_users[i].node, Ipx_users[i].address );
229 SkipUser:
230                         j = 0;
231                 }
232         }
233 }
234
235 // Sends a non-localized packet... needs 4 byte server, 6 byte address
236 void ipx_send_internetwork_packet_data( ubyte * data, int datasize, ubyte * server, ubyte *address )
237 {
238         ubyte local_address[6];
239
240         if ( (*(uint *)server) != 0 )   {
241                 ipx_get_local_target( server, address, local_address );
242                 ipx_send_packet_data( data, datasize, server, address, local_address );
243         } else {
244                 // Old method, no server info.
245                 ipx_send_packet_data( data, datasize, server, address, address );
246         }
247 }
248
249 int ipx_change_default_socket( ushort socket_number )
250 {
251         if ( !ipx_installed ) return -3;
252
253         driver->CloseSocket(&ipx_socket_data);
254         if (driver->OpenSocket(&ipx_socket_data, socket_number)) {
255                 return -3;
256         }
257         return 0;
258 }
259
260 void ipx_read_user_file(char * filename)
261 {
262         FILE * fp;
263         user_address tmp;
264         char temp_line[132], *p1;
265         int n, ln=0, x;
266
267         if (!filename) return;
268
269         Ipx_num_users = 0;
270
271         fp = fopen( filename, "rt" );
272         if ( !fp ) return;
273
274         printf( "Broadcast Users:\n" );
275
276         while (fgets(temp_line, 132, fp)) {
277                 ln++;
278                 p1 = strchr(temp_line,'\n'); if (p1) *p1 = '\0';
279                 p1 = strchr(temp_line,';'); if (p1) *p1 = '\0';
280 #if 1 // adb: replaced sscanf(..., "%2x...", (char *)...) with better, but longer code
281                 if (strlen(temp_line) >= 21 && temp_line[8] == '/') {
282                         for (n = 0; n < 4; n++) {
283                                 if (sscanf(temp_line + n * 2, "%2x", &x) != 1)
284                                         break;
285                                 tmp.network[n] = x;
286                         }
287                         if (n != 4)
288                                 continue;
289                         for (n = 0; n < 6; n++) {
290                                 if (sscanf(temp_line + 9 + n * 2, "%2x", &x) != 1)
291                                         break;
292                                 tmp.node[n] = x;
293                         }
294                         if (n != 6)
295                                 continue;
296                 } else
297                         continue;
298 #else
299                 n = sscanf( temp_line, "%2x%2x%2x%2x/%2x%2x%2x%2x%2x%2x", &tmp.network[0], &tmp.network[1], &tmp.network[2], &tmp.network[3], &tmp.node[0], &tmp.node[1], &tmp.node[2],&tmp.node[3], &tmp.node[4], &tmp.node[5] );
300                 if ( n != 10 ) continue;
301 #endif
302                 if ( Ipx_num_users < MAX_USERS )        {
303                         ubyte * ipx_real_buffer = (ubyte *)&tmp;
304                         ipx_get_local_target( tmp.network, tmp.node, tmp.address );
305                         Ipx_users[Ipx_num_users++] = tmp;
306                         printf( "%02X%02X%02X%02X/", ipx_real_buffer[0],ipx_real_buffer[1],ipx_real_buffer[2],ipx_real_buffer[3] );
307                         printf( "%02X%02X%02X%02X%02X%02X\n", ipx_real_buffer[4],ipx_real_buffer[5],ipx_real_buffer[6],ipx_real_buffer[7],ipx_real_buffer[8],ipx_real_buffer[9] );
308                 } else {
309                         printf( "Too many addresses in %s! (Limit of %d)\n", filename, MAX_USERS );
310                         fclose(fp);
311                         return;
312                 }
313         }
314         fclose(fp);
315 }
316
317
318 void ipx_read_network_file(char * filename)
319 {
320         FILE * fp;
321         user_address tmp;
322         char temp_line[132], *p1;
323         int i, n, ln=0, x;
324
325         if (!filename) return;
326
327         fp = fopen( filename, "rt" );
328         if ( !fp ) return;
329
330         printf( "Using Networks:\n" );
331         for (i=0; i<Ipx_num_networks; i++ )             {
332                 ubyte * n1 = (ubyte *)&Ipx_networks[i];
333                 printf("* %02x%02x%02x%02x\n", n1[0], n1[1], n1[2], n1[3] );
334         }
335
336         while (fgets(temp_line, 132, fp)) {
337                 ln++;
338                 p1 = strchr(temp_line,'\n'); if (p1) *p1 = '\0';
339                 p1 = strchr(temp_line,';'); if (p1) *p1 = '\0';
340 #if 1 // adb: replaced sscanf(..., "%2x...", (char *)...) with better, but longer code
341                 if (strlen(temp_line) >= 8) {
342                         for (n = 0; n < 4; n++) {
343                                 if (sscanf(temp_line + n * 2, "%2x", &x) != 1)
344                                         break;
345                                 tmp.network[n] = x;
346                         }
347                         if (n != 4)
348                                 continue;
349                 } else
350                         continue;
351 #else
352                 n = sscanf( temp_line, "%2x%2x%2x%2x", &tmp.network[0], &tmp.network[1], &tmp.network[2], &tmp.network[3] );
353                 if ( n != 4 ) continue;
354 #endif
355                 if ( Ipx_num_networks < MAX_NETWORKS  ) {
356                         int j;
357                         for (j=0; j<Ipx_num_networks; j++ )     
358                                 if ( !memcmp( &Ipx_networks[j], tmp.network, 4 ) )
359                                         break;
360                         if ( j >= Ipx_num_networks )    {
361                                 memcpy( &Ipx_networks[Ipx_num_networks++], tmp.network, 4 );
362                                 printf("  %02x%02x%02x%02x\n", tmp.network[0], tmp.network[1], tmp.network[2], tmp.network[3] );
363                         }
364                 } else {
365                         printf( "Too many networks in %s! (Limit of %d)\n", filename, MAX_NETWORKS );
366                         fclose(fp);
367                         return;
368                 }
369         }
370         fclose(fp);
371 }
372
373 // Initalizes the protocol-specific member of the netgame packet.
374 void ipx_init_netgame_aux_data(ubyte buf[])
375 {
376         if(driver->InitNetgameAuxData)
377                 driver->InitNetgameAuxData(&ipx_socket_data, buf);
378 }
379
380 // Handles the protocol-specific member of the netgame packet.
381 int ipx_handle_netgame_aux_data(const ubyte buf[])
382 {
383         if(driver->HandleNetgameAuxData)
384                 return driver->HandleNetgameAuxData(&ipx_socket_data, buf);
385         return 0;
386 }
387
388 // Notifies the protocol that we're done with a particular game
389 void ipx_handle_leave_game()
390 {
391         if(driver->HandleLeaveGame)
392                 driver->HandleLeaveGame(&ipx_socket_data);
393 }
394
395 // Send a packet to every member of the game.
396 int ipx_send_game_packet(ubyte *data, int datasize)
397 {
398         if(driver->SendGamePacket) {
399                 u_char buf[MAX_IPX_DATA];
400
401                 *(uint *)buf = ipx_packetnum++;
402                 memcpy(buf + 4, data, datasize);
403                 *(uint *)data = ipx_packetnum++;
404                 return driver->SendGamePacket(&ipx_socket_data, buf, datasize + 4);
405         } else {
406                 // Loop through all the players unicasting the packet.
407                 int i;
408
409                 //printf("Sending game packet: N_players = %i\n", N_players);
410
411                 for(i=0; i<N_players; i++) {
412                         if(Players[i].connected && (i != Player_num))
413                                 ipx_send_packet_data(data, datasize, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address);
414                 }
415                 return datasize;
416         }
417
418         return 0;
419 }