/[gxemul]/trunk/src/net/net.c
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Annotation of /trunk/src/net/net.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 32 - (hide annotations)
Mon Oct 8 16:20:58 2007 UTC (16 years, 6 months ago) by dpavlin
File MIME type: text/plain
File size: 22004 byte(s)
++ trunk/HISTORY	(local)
$Id: HISTORY,v 1.1421 2006/11/06 05:32:37 debug Exp $
20060816	Adding a framework for emulated/virtual timers (src/timer.c),
		using only setitimer().
		Rewriting the mc146818 to use the new timer framework.
20060817	Adding a call to gettimeofday() every now and then (once every
		second, at the moment) to resynch the timer if it drifts.
		Beginning to convert the ISA timer interrupt mechanism (8253
		and 8259) to use the new timer framework.
		Removing the -I command line option.
20060819	Adding the -I command line option again, with new semantics.
		Working on Footbridge timer interrupts; NetBSD/NetWinder and
		NetBSD/CATS now run at correct speed, but unfortunately with
		HUGE delays during bootup.
20060821	Some minor m68k updates. Adding the first instruction: nop. :)
		Minor Alpha emulation updates.
20060822	Adding a FreeBSD development specific YAMON environment
		variable ("khz") (as suggested by Bruce M. Simpson).
		Moving YAMON environment variable initialization from
		machine_evbmips.c into promemul/yamon.c, and adding some more
		variables.
		Continuing on the LCA PCI bus controller (for Alpha machines).
20060823	Continuing on the timer stuff: experimenting with MIPS count/
		compare interrupts connected to the timer framework.
20060825	Adding bogus SCSI commands 0x51 (SCSICDROM_READ_DISCINFO) and
		0x52 (SCSICDROM_READ_TRACKINFO) to the SCSI emulation layer,
		to allow NetBSD/pmax 4.0_BETA to be installed from CDROM.
		Minor updates to the LCA PCI controller.
20060827	Implementing a CHIP8 cpu mode, and a corresponding CHIP8
		machine, for fun. Disassembly support for all instructions,
		and most of the common instructions have been implemented: mvi,
		mov_imm, add_imm, jmp, rand, cls, sprite, skeq_imm, jsr,
		skne_imm, bcd, rts, ldr, str, mov, or, and, xor, add, sub,
		font, ssound, sdelay, gdelay, bogus skup/skpr, skeq, skne.
20060828	Beginning to convert the CHIP8 cpu in the CHIP8 machine to a
		(more correct) RCA 180x cpu. (Disassembly for all 1802
		instructions has been implemented, but no execution yet, and
		no 1805 extended instructions.)
20060829	Minor Alpha emulation updates.
20060830	Beginning to experiment a little with PCI IDE for SGI O2.
		Fixing the cursor key mappings for MobilePro 770 emulation.
		Fixing the LK201 warning caused by recent NetBSD/pmax.
		The MIPS R41xx standby, suspend, and hibernate instructions now
		behave like the RM52xx/MIPS32/MIPS64 wait instruction.
		Fixing dev_wdc so it calculates correct (64-bit) offsets before
		giving them to diskimage_access().
20060831	Continuing on Alpha emulation (OSF1 PALcode).
20060901	Minor Alpha updates; beginning on virtual memory pagetables.
		Removed the limit for max nr of devices (in preparation for
		allowing devices' base addresses to be changed during runtime).
		Adding a hack for MIPS [d]mfc0 select 0 (except the count
		register), so that the coproc register is simply copied.
		The MIPS suspend instruction now exits the emulator, instead
		of being treated as a wait instruction (this causes NetBSD/
		hpcmips to get correct 'halt' behavior).
		The VR41xx RTC now returns correct time.
		Connecting the VR41xx timer to the timer framework (fixed at
		128 Hz, for now).
		Continuing on SPARC emulation, adding more instructions:
		restore, ba_xcc, ble. The rectangle drawing demo works :)
		Removing the last traces of the old ENABLE_CACHE_EMULATION
		MIPS stuff (not usable with dyntrans anyway).
20060902	Splitting up src/net.c into several smaller files in its own
		subdirectory (src/net/).
20060903	Cleanup of the files in src/net/, to make them less ugly.
20060904	Continuing on the 'settings' subsystem.
		Minor progress on the SPARC emulation mode.
20060905	Cleanup of various things, and connecting the settings
		infrastructure to various subsystems (emul, machine, cpu, etc).
		Changing the lk201 mouse update routine to not rely on any
		emulated hardware framebuffer cursor coordinates, but instead
		always do (semi-usable) relative movements.
20060906	Continuing on the lk201 mouse stuff. Mouse behaviour with
		multiple framebuffers (which was working in Ultrix) is now
		semi-broken (but it still works, in a way).
		Moving the documentation about networking into its own file
		(networking.html), and refreshing it a bit. Adding an example
		of how to use ethernet frame direct-access (udp_snoop).
20060907	Continuing on the settings infrastructure.
20060908	Minor updates to SH emulation: for 32-bit emulation: delay
		slots and the 'jsr @Rn' instruction. I'm putting 64-bit SH5 on
		ice, for now.
20060909-10	Implementing some more 32-bit SH instructions. Removing the
		64-bit mode completely. Enough has now been implemented to run
		the rectangle drawing demo. :-)
20060912	Adding more SH instructions.
20060916	Continuing on SH emulation (some more instructions: div0u,
		div1, rotcl/rotcr, more mov instructions, dt, braf, sets, sett,
		tst_imm, dmuls.l, subc, ldc_rm_vbr, movt, clrt, clrs, clrmac).
		Continuing on the settings subsystem (beginning on reading/
		writing settings, removing bugs, and connecting more cpus to
		the framework).
20060919	More work on SH emulation; adding an ldc banked instruction,
		and attaching a 640x480 framebuffer to the Dreamcast machine
		mode (NetBSD/dreamcast prints the NetBSD copyright banner :-),
		and then panics).
20060920	Continuing on the settings subsystem.
20060921	Fixing the Footbridge timer stuff so that NetBSD/cats and
		NetBSD/netwinder boot up without the delays.
20060922	Temporarily hardcoding MIPS timer interrupt to 100 Hz. With
		'wait' support disabled, NetBSD/malta and Linux/malta run at
		correct speed.
20060923	Connecting dev_gt to the timer framework, so that NetBSD/cobalt
		runs at correct speed.
		Moving SH4-specific memory mapped registers into its own
		device (dev_sh4.c).
		Running with -N now prints "idling" instead of bogus nr of
		instrs/second (which isn't valid anyway) while idling.
20060924	Algor emulation should now run at correct speed.
		Adding disassembly support for some MIPS64 revision 2
		instructions: ext, dext, dextm, dextu.
20060926	The timer framework now works also when the MIPS wait
		instruction is used.
20060928	Re-implementing checks for coprocessor availability for MIPS
		cop0 instructions. (Thanks to Carl van Schaik for noticing the
		lack of cop0 availability checks.)
20060929	Implementing an instruction combination hack which treats
		NetBSD/pmax' idle loop as a wait-like instruction.
20060930	The ENTRYHI_R_MASK was missing in (at least) memory_mips_v2p.c,
		causing TLB lookups to sometimes succeed when they should have
		failed. (A big thank you to Juli Mallett for noticing the
		problem.)
		Adding disassembly support for more MIPS64 revision 2 opcodes
		(seb, seh, wsbh, jalr.hb, jr.hb, synci, ins, dins, dinsu,
		dinsm, dsbh, dshd, ror, dror, rorv, drorv, dror32). Also
		implementing seb, seh, dsbh, dshd, and wsbh.
		Implementing an instruction combination hack for Linux/pmax'
		idle loop, similar to the NetBSD/pmax case.
20061001	Changing the NetBSD/sgimips install instructions to extract
		files from an iso image, instead of downloading them via ftp.
20061002	More-than-31-bit userland addresses in memory_mips_v2p.c were
		not actually working; applying a fix from Carl van Schaik to
		enable them to work + making some other updates (adding kuseg
		support).
		Fixing hpcmips (vr41xx) timer initialization.
		Experimenting with O(n)->O(1) reduction in the MIPS TLB lookup
		loop. Seems to work both for R3000 and non-R3000.
20061003	Continuing a little on SH emulation (adding more control
		registers; mini-cleanup of memory_sh.c).
20061004	Beginning on a dev_rtc, a clock/timer device for the test
		machines; also adding a demo, and some documentation.
		Fixing a bug in SH "mov.w @(disp,pc),Rn" (the result wasn't
		sign-extended), and adding the addc and ldtlb instructions.
20061005	Contining on SH emulation: virtual to physical address
		translation, and a skeleton exception mechanism.
20061006	Adding more SH instructions (various loads and stores, rte,
		negc, muls.w, various privileged register-move instructions).
20061007	More SH instructions: various move instructions, trapa, div0s,
		float, fdiv, ftrc.
		Continuing on dev_rtc; removing the rtc demo.
20061008	Adding a dummy Dreamcast PROM module. (Homebrew Dreamcast
		programs using KOS libs need this.)
		Adding more SH instructions: "stc vbr,rn", rotl, rotr, fsca,
		fmul, fadd, various floating-point moves, etc. A 256-byte
		demo for Dreamcast runs :-)
20061012	Adding the SH "lds Rm,pr" and bsr instructions.
20061013	More SH instructions: "sts fpscr,rn", tas.b, and some more
		floating point instructions, cmp/str, and more moves.
		Adding a dummy dev_pvr (Dreamcast graphics controller).
20061014	Generalizing the expression evaluator (used in the built-in
		debugger) to support parentheses and +-*/%^&|.
20061015	Removing the experimental tlb index hint code in
		mips_memory_v2p.c, since it didn't really have any effect.
20061017	Minor SH updates; adding the "sts pr,Rn", fcmp/gt, fneg,
		frchg, and some other instructions. Fixing missing sign-
		extension in an 8-bit load instruction.
20061019	Adding a simple dev_dreamcast_rtc.
		Implementing memory-mapped access to the SH ITLB/UTLB arrays.
20061021	Continuing on various SH and Dreamcast things: sh4 timers,
		debug messages for dev_pvr, fixing some virtual address
		translation bugs, adding the bsrf instruction.
		The NetBSD/dreamcast GENERIC_MD kernel now reaches userland :)
		Adding a dummy dev_dreamcast_asic.c (not really useful yet).
		Implementing simple support for Store Queues.
		Beginning on the PVR Tile Accelerator.
20061022	Generalizing the PVR framebuffer to support off-screen drawing,
		multiple bit-depths, etc. (A small speed penalty, but most
		likely worth it.)
		Adding more SH instructions (mulu.w, fcmp/eq, fsub, fmac,
		fschg, and some more); correcting bugs in "fsca" and "float".
20061024	Adding the SH ftrv (matrix * vector) instruction. Marcus
		Comstedt's "tatest" example runs :) (wireframe only).
		Correcting disassembly for SH floating point instructions that
		use the xd* registers.
		Adding the SH fsts instruction.
		In memory_device_dyntrans_access(), only the currently used
		range is now invalidated, and not the entire device range.
20061025	Adding a dummy AVR32 cpu mode skeleton.
20061026	Various Dreamcast updates; beginning on a Maple bus controller.
20061027	Continuing on the Maple bus. A bogus Controller, Keyboard, and
		Mouse can now be detected by NetBSD and KOS homebrew programs.
		Cleaning up the SH4 Timer Management Unit, and beginning on
		SH4 interrupts.
		Implementing the Dreamcast SYSASIC.
20061028	Continuing on the SYSASIC.
		Adding the SH fsqrt instruction.
		memory_sh.c now actually scans the ITLB.
		Fixing a bug in dev_sh4.c, related to associative writes into
		the memory-mapped UTLB array. NetBSD/dreamcast now reaches
		userland stably, and prints the "Terminal type?" message :-]
		Implementing enough of the Dreamcast keyboard to make NetBSD
		accept it for input.
		Enabling SuperH for stable (non-development) builds.
		Adding NetBSD/dreamcast to the documentation, although it
		doesn't support root-on-nfs yet.
20061029	Changing usleep(1) calls in the debugger to to usleep(10000)
		(according to Brian Foley, this makes GXemul run better on
		MacOS X).
		Making the Maple "Controller" do something (enough to barely
		interact with dcircus.elf).
20061030-31	Some progress on the PVR. More test programs start running (but
		with strange output).
		Various other SH4-related updates.
20061102	Various Dreamcast and SH4 updates; more KOS demos run now.
20061104	Adding a skeleton dev_mb8696x.c (the Dreamcast's LAN adapter).
20061105	Continuing on the MB8696x; NetBSD/dreamcast detects it as mbe0.
		Testing for the release.

==============  RELEASE 0.4.3  ==============


1 dpavlin 32 /*
2     * Copyright (C) 2004-2006 Anders Gavare. All rights reserved.
3     *
4     * Redistribution and use in source and binary forms, with or without
5     * modification, are permitted provided that the following conditions are met:
6     *
7     * 1. Redistributions of source code must retain the above copyright
8     * notice, this list of conditions and the following disclaimer.
9     * 2. Redistributions in binary form must reproduce the above copyright
10     * notice, this list of conditions and the following disclaimer in the
11     * documentation and/or other materials provided with the distribution.
12     * 3. The name of the author may not be used to endorse or promote products
13     * derived from this software without specific prior written permission.
14     *
15     * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16     * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17     * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18     * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19     * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20     * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21     * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24     * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25     * SUCH DAMAGE.
26     *
27     *
28     * $Id: net.c,v 1.6 2006/09/05 06:58:29 debug Exp $
29     *
30     * Emulated network.
31     *
32     * (Read the README file in this directory for more details.)
33     *
34     *
35     * NOTE: The 'extra' argument used in many functions in this file is a pointer
36     * to something unique for each NIC (i.e. the NIC itself :-), so that if
37     * multiple NICs are emulated concurrently, they will not get packets that
38     * are meant for some other controller.
39     */
40    
41     #include <stdio.h>
42     #include <stdlib.h>
43     #include <string.h>
44     #include <unistd.h>
45     #include <errno.h>
46     #include <sys/types.h>
47     #include <sys/socket.h>
48     #include <netinet/in.h>
49     #include <arpa/inet.h>
50     #include <netdb.h>
51     #include <fcntl.h>
52     #include <signal.h>
53    
54     #include "machine.h"
55     #include "misc.h"
56     #include "net.h"
57    
58    
59     /* #define debug fatal */
60    
61    
62     /*
63     * net_allocate_ethernet_packet_link():
64     *
65     * This routine allocates an ethernet_packet_link struct, and adds it at
66     * the end of the packet chain. A data buffer is allocated, and the data,
67     * extra, and len fields of the link are set.
68     *
69     * Note: The data buffer is not zeroed.
70     *
71     * Return value is a pointer to the link on success. It doesn't return on
72     * failure.
73     */
74     struct ethernet_packet_link *net_allocate_ethernet_packet_link(
75     struct net *net, void *extra, size_t len)
76     {
77     struct ethernet_packet_link *lp;
78    
79     lp = malloc(sizeof(struct ethernet_packet_link));
80     if (lp == NULL)
81     goto fail;
82    
83     lp->len = len;
84     lp->extra = extra;
85     lp->data = malloc(len);
86     if (lp->data == NULL)
87     goto fail;
88    
89     lp->next = NULL;
90    
91     /* Add last in the link chain: */
92     lp->prev = net->last_ethernet_packet;
93     if (lp->prev != NULL)
94     lp->prev->next = lp;
95     else
96     net->first_ethernet_packet = lp;
97     net->last_ethernet_packet = lp;
98    
99     return lp;
100    
101     fail:
102     fprintf(stderr, "net_allocate_ethernet_packet_link(): out of memory\n");
103     exit(1);
104     }
105    
106    
107     /*
108     * net_arp():
109     *
110     * Handle an ARP (or RARP) packet, coming from the emulated NIC.
111     *
112     * An ARP packet might look like this:
113     *
114     * ARP header:
115     * ARP hardware addr family: 0001
116     * ARP protocol addr family: 0800
117     * ARP addr lengths: 06 04
118     * ARP request: 0001
119     * ARP from: 112233445566 01020304
120     * ARP to: 000000000000 01020301
121     *
122     * An ARP request with a 'to' IP value of the gateway should cause an
123     * ARP response packet to be created.
124     *
125     * An ARP request with the same from and to IP addresses should be ignored.
126     * (This would be a host testing to see if there is an IP collision.)
127     */
128     static void net_arp(struct net *net, void *extra,
129     unsigned char *packet, int len, int reverse)
130     {
131     int q;
132     int i;
133    
134     /* TODO: This debug dump assumes ethernet->IPv4 translation: */
135     if (reverse)
136     debug("[ net: RARP: ");
137     else
138     debug("[ net: ARP: ");
139     for (i=0; i<2; i++)
140     debug("%02x", packet[i]);
141     debug(" ");
142     for (i=2; i<4; i++)
143     debug("%02x", packet[i]);
144     debug(" ");
145     debug("%02x", packet[4]);
146     debug(" ");
147     debug("%02x", packet[5]);
148     debug(" req=");
149     debug("%02x", packet[6]); /* Request type */
150     debug("%02x", packet[7]);
151     debug(" from=");
152     for (i=8; i<18; i++)
153     debug("%02x", packet[i]);
154     debug(" to=");
155     for (i=18; i<28; i++)
156     debug("%02x", packet[i]);
157     debug(" ]\n");
158    
159     if (packet[0] == 0x00 && packet[1] == 0x01 &&
160     packet[2] == 0x08 && packet[3] == 0x00 &&
161     packet[4] == 0x06 && packet[5] == 0x04) {
162     int r = (packet[6] << 8) + packet[7];
163     struct ethernet_packet_link *lp;
164    
165     switch (r) {
166     case 1: /* Request */
167     /* Only create a reply if this was meant for the
168     gateway: */
169     if (memcmp(packet+24, net->gateway_ipv4_addr, 4) != 0)
170     break;
171    
172     lp = net_allocate_ethernet_packet_link(
173     net, extra, 60 + 14);
174    
175     /* Copy the old packet first: */
176     memset(lp->data, 0, 60 + 14);
177     memcpy(lp->data + 14, packet, len);
178    
179     /* Add ethernet ARP header: */
180     memcpy(lp->data + 0, lp->data + 8 + 14, 6);
181     memcpy(lp->data + 6, net->gateway_ethernet_addr, 6);
182     lp->data[12] = 0x08; lp->data[13] = 0x06;
183    
184     /* Address of the emulated machine: */
185     memcpy(lp->data + 18 + 14, lp->data + 8 + 14, 10);
186    
187     /* Address of the gateway: */
188     memcpy(lp->data + 8 + 14, net->gateway_ethernet_addr,
189     6);
190     memcpy(lp->data + 14 + 14, net->gateway_ipv4_addr, 4);
191    
192     /* This is a Reply: */
193     lp->data[6 + 14] = 0x00; lp->data[7 + 14] = 0x02;
194    
195     break;
196     case 3: /* Reverse Request */
197     lp = net_allocate_ethernet_packet_link(
198     net, extra, 60 + 14);
199    
200     /* Copy the old packet first: */
201     memset(lp->data, 0, 60 + 14);
202     memcpy(lp->data + 14, packet, len);
203    
204     /* Add ethernet RARP header: */
205     memcpy(lp->data + 0, packet + 8, 6);
206     memcpy(lp->data + 6, net->gateway_ethernet_addr, 6);
207     lp->data[12] = 0x80; lp->data[13] = 0x35;
208    
209     /* This is a RARP reply: */
210     lp->data[6 + 14] = 0x00; lp->data[7 + 14] = 0x04;
211    
212     /* Address of the gateway: */
213     memcpy(lp->data + 8 + 14, net->gateway_ethernet_addr,
214     6);
215     memcpy(lp->data + 14 + 14, net->gateway_ipv4_addr, 4);
216    
217     /* MAC address of emulated machine: */
218     memcpy(lp->data + 18 + 14, packet + 8, 6);
219    
220     /*
221     * IP address of the emulated machine: Automagically
222     * generated from the MAC address. :-)
223     *
224     * packet+8 points to the client's mac address,
225     * for example 10:20:30:00:00:z0, where z is 0..15.
226     * 10:20:30:00:00:10 results in 10.0.0.1.
227     */
228     /* q = (packet[8 + 3]) >> 4; */
229     /* q = q*15 + ((packet[8 + 4]) >> 4); */
230     q = (packet[8 + 5]) >> 4;
231     lp->data[24 + 14] = 10;
232     lp->data[25 + 14] = 0;
233     lp->data[26 + 14] = 0;
234     lp->data[27 + 14] = q;
235     break;
236     case 2: /* Reply */
237     case 4: /* Reverse Reply */
238     default:
239     fatal("[ net: ARP: UNIMPLEMENTED request type "
240     "0x%04x ]\n", r);
241     }
242     } else {
243     fatal("[ net: ARP: UNIMPLEMENTED arp packet type: ");
244     for (i=0; i<len; i++)
245     fatal("%02x", packet[i]);
246     fatal(" ]\n");
247     }
248     }
249    
250    
251     /*
252     * net_ethernet_rx_avail():
253     *
254     * Return 1 if there is a packet available for this 'extra' pointer, otherwise
255     * return 0.
256     *
257     * Appart from actually checking for incoming packets from the outside world,
258     * this function basically works like net_ethernet_rx() but it only receives
259     * a return value telling us whether there is a packet or not, we don't
260     * actually get the packet.
261     */
262     int net_ethernet_rx_avail(struct net *net, void *extra)
263     {
264     if (net == NULL)
265     return 0;
266    
267     /*
268     * If the network is distributed across multiple emulator processes,
269     * then receive incoming packets from those processes.
270     */
271     if (net->local_port != 0) {
272     struct sockaddr_in si;
273     socklen_t si_len = sizeof(si);
274     int res, i, nreceived = 0;
275     unsigned char buf[60000];
276    
277     do {
278     res = recvfrom(net->local_port_socket, buf,
279     sizeof(buf), 0, (struct sockaddr *)&si, &si_len);
280    
281     if (res != -1) {
282     nreceived ++;
283    
284     /* fatal("[ incoming DISTRIBUTED packet, %i "
285     "bytes from %s:%d\n", res,
286     inet_ntoa(si.sin_addr),
287     ntohs(si.sin_port)); */
288    
289     /* Add the packet to all "our" NICs on this
290     network: */
291     for (i=0; i<net->n_nics; i++) {
292     struct ethernet_packet_link *lp;
293     lp = net_allocate_ethernet_packet_link(
294     net, net->nic_extra[i], res);
295     memcpy(lp->data, buf, res);
296     }
297     }
298     } while (res != -1 && nreceived < 100);
299     }
300    
301     /* IP protocol specific: */
302     net_udp_rx_avail(net, extra);
303     net_tcp_rx_avail(net, extra);
304    
305     return net_ethernet_rx(net, extra, NULL, NULL);
306     }
307    
308    
309     /*
310     * net_ethernet_rx():
311     *
312     * Receive an ethernet packet. (This means handing over an already prepared
313     * packet from this module to a specific ethernet controller device.)
314     *
315     * Return value is 1 if there was a packet available. *packetp and *lenp
316     * will be set to the packet's data pointer and length, respectively, and
317     * the packet will be removed from the linked list). If there was no packet
318     * available, 0 is returned.
319     *
320     * If packetp is NULL, then the search is aborted as soon as a packet with
321     * the correct 'extra' field is found, and a 1 is returned, but as packetp
322     * is NULL we can't return the actual packet. (This is the internal form
323     * if net_ethernet_rx_avail().)
324     */
325     int net_ethernet_rx(struct net *net, void *extra,
326     unsigned char **packetp, int *lenp)
327     {
328     struct ethernet_packet_link *lp, *prev;
329    
330     if (net == NULL)
331     return 0;
332    
333     /* Find the first packet which has the right 'extra' field. */
334    
335     lp = net->first_ethernet_packet;
336     prev = NULL;
337     while (lp != NULL) {
338     if (lp->extra == extra) {
339     /* We found a packet for this controller! */
340     if (packetp == NULL || lenp == NULL)
341     return 1;
342    
343     /* Let's return it: */
344     (*packetp) = lp->data;
345     (*lenp) = lp->len;
346    
347     /* Remove this link from the linked list: */
348     if (prev == NULL)
349     net->first_ethernet_packet = lp->next;
350     else
351     prev->next = lp->next;
352    
353     if (lp->next == NULL)
354     net->last_ethernet_packet = prev;
355     else
356     lp->next->prev = prev;
357    
358     free(lp);
359    
360     /* ... and return successfully: */
361     return 1;
362     }
363    
364     prev = lp;
365     lp = lp->next;
366     }
367    
368     /* No packet found. :-( */
369     return 0;
370     }
371    
372    
373     /*
374     * net_ethernet_tx():
375     *
376     * Transmit an ethernet packet, as seen from the emulated ethernet controller.
377     * If the packet can be handled here, it will not necessarily be transmitted
378     * to the outside world.
379     */
380     void net_ethernet_tx(struct net *net, void *extra,
381     unsigned char *packet, int len)
382     {
383     int i, eth_type, for_the_gateway;
384    
385     if (net == NULL)
386     return;
387    
388     for_the_gateway = !memcmp(packet, net->gateway_ethernet_addr, 6);
389    
390     /* Drop too small packets: */
391     if (len < 20) {
392     fatal("[ net_ethernet_tx: Warning: dropping tiny packet "
393     "(%i bytes) ]\n", len);
394     return;
395     }
396    
397     /*
398     * Copy this packet to all other NICs on this network (except if
399     * it is aimed specifically at the gateway's ethernet address):
400     */
401     if (!for_the_gateway && extra != NULL && net->n_nics > 0) {
402     for (i=0; i<net->n_nics; i++)
403     if (extra != net->nic_extra[i]) {
404     struct ethernet_packet_link *lp;
405     lp = net_allocate_ethernet_packet_link(net,
406     net->nic_extra[i], len);
407    
408     /* Copy the entire packet: */
409     memcpy(lp->data, packet, len);
410     }
411     }
412    
413     /*
414     * If this network is distributed across multiple emulator processes,
415     * then transmit the packet to those other processes.
416     */
417     if (!for_the_gateway && net->remote_nets != NULL) {
418     struct remote_net *rnp = net->remote_nets;
419     while (rnp != NULL) {
420     send_udp(&rnp->ipv4_addr, rnp->portnr, packet, len);
421     rnp = rnp->next;
422     }
423     }
424    
425    
426     /*
427     * The code below simulates the behaviour of a "NAT"-style gateway.
428     *
429     * Packets that are not destined for the gateway are dropped first:
430     * (DHCP packets are let through, though.)
431     */
432    
433     if (!for_the_gateway && packet[0] != 0xff && packet[0] != 0x00)
434     return;
435    
436     #if 0
437     fatal("[ net: ethernet: ");
438     for (i=0; i<6; i++) fatal("%02x", packet[i]); fatal(" ");
439     for (i=6; i<12; i++) fatal("%02x", packet[i]); fatal(" ");
440     for (i=12; i<14; i++) fatal("%02x", packet[i]); fatal(" ");
441     for (i=14; i<len; i++) fatal("%02x", packet[i]); fatal(" ]\n");
442     #endif
443    
444     eth_type = (packet[12] << 8) + packet[13];
445    
446     /* IP: */
447     if (eth_type == ETHERTYPE_IP) {
448     /* Routed via the gateway? */
449     if (for_the_gateway) {
450     net_ip(net, extra, packet, len);
451     return;
452     }
453    
454     /* Broadcast? (DHCP does this.) */
455     if (packet[0] == 0xff && packet[1] == 0xff &&
456     packet[2] == 0xff && packet[3] == 0xff &&
457     packet[4] == 0xff && packet[5] == 0xff) {
458     net_ip_broadcast(net, extra, packet, len);
459     return;
460     }
461    
462     if (net->n_nics < 2) {
463     fatal("[ net_ethernet_tx: IP packet not for gateway, "
464     "and not broadcast: ");
465     for (i=0; i<14; i++)
466     fatal("%02x", packet[i]);
467     fatal(" ]\n");
468     }
469     return;
470     }
471    
472     /* ARP: */
473     if (eth_type == ETHERTYPE_ARP) {
474     if (len != 42 && len != 60)
475     fatal("[ net_ethernet_tx: WARNING! unusual "
476     "ARP len (%i) ]\n", len);
477     net_arp(net, extra, packet + 14, len - 14, 0);
478     return;
479     }
480    
481     /* RARP: */
482     if (eth_type == ETHERTYPE_REVARP) {
483     net_arp(net, extra, packet + 14, len - 14, 1);
484     return;
485     }
486    
487     /* Sprite: */
488     if (eth_type == ETHERTYPE_SPRITE) {
489     /* TODO. */
490     fatal("[ net: TX: UNIMPLEMENTED Sprite packet ]\n");
491     return;
492     }
493    
494     /* IPv6: */
495     if (eth_type == ETHERTYPE_IPV6) {
496     /* TODO. */
497     fatal("[ net_ethernet_tx: IPv6 is not implemented yet! ]\n");
498     return;
499     }
500    
501     fatal("[ net_ethernet_tx: ethernet packet type 0x%04x not yet "
502     "implemented ]\n", eth_type);
503     }
504    
505    
506     /*
507     * parse_resolvconf():
508     *
509     * This function parses "/etc/resolv.conf" to figure out the nameserver
510     * and domain used by the host.
511     */
512     static void parse_resolvconf(struct net *net)
513     {
514     FILE *f;
515     char buf[8000];
516     size_t len;
517     int res;
518     unsigned int i, start;
519    
520     /*
521     * This is a very ugly hack, which tries to figure out which
522     * nameserver the host uses by looking for the string 'nameserver'
523     * in /etc/resolv.conf.
524     *
525     * This can later on be used for DHCP autoconfiguration. (TODO)
526     *
527     * TODO: This is hardcoded to use /etc/resolv.conf. Not all
528     * operating systems use that filename.
529     *
530     * TODO: This is hardcoded for AF_INET (that is, IPv4).
531     *
532     * TODO: This assumes that the first nameserver listed is the
533     * one to use.
534     */
535     f = fopen("/etc/resolv.conf", "r");
536     if (f == NULL)
537     return;
538    
539     /* TODO: get rid of the hardcoded values */
540     memset(buf, 0, sizeof(buf));
541     len = fread(buf, 1, sizeof(buf) - 100, f);
542     fclose(f);
543     buf[sizeof(buf) - 1] = '\0';
544    
545     for (i=0; i<len; i++)
546     if (strncmp(buf+i, "nameserver", 10) == 0) {
547     char *p;
548    
549     /*
550     * "nameserver" (1 or more whitespace)
551     * "x.y.z.w" (non-digit)
552     */
553    
554     /* debug("found nameserver at offset %i\n", i); */
555     i += 10;
556     while (i<len && (buf[i]==' ' || buf[i]=='\t'))
557     i++;
558     if (i >= len)
559     break;
560     start = i;
561    
562     p = buf+start;
563     while ((*p >= '0' && *p <= '9') || *p == '.')
564     p++;
565     *p = '\0';
566    
567     #ifdef HAVE_INET_PTON
568     res = inet_pton(AF_INET, buf + start,
569     &net->nameserver_ipv4);
570     #else
571     res = inet_aton(buf + start, &net->nameserver_ipv4);
572     #endif
573     if (res < 1)
574     break;
575    
576     net->nameserver_known = 1;
577     break;
578     }
579    
580     for (i=0; i<len; i++)
581     if (strncmp(buf+i, "domain", 6) == 0) {
582     /* "domain" (1 or more whitespace) domain_name */
583     i += 6;
584     while (i<len && (buf[i]==' ' || buf[i]=='\t'))
585     i++;
586     if (i >= len)
587     break;
588    
589     start = i;
590     while (i<len && buf[i]!='\n' && buf[i]!='\r')
591     i++;
592     if (i < len)
593     buf[i] = '\0';
594     /* fatal("DOMAIN='%s'\n", buf + start); */
595     net->domain_name = strdup(buf + start);
596     break;
597     }
598     }
599    
600    
601     /*
602     * net_add_nic():
603     *
604     * Add a NIC to a network. (All NICs on a network will see each other's
605     * packets.)
606     */
607     void net_add_nic(struct net *net, void *extra, unsigned char *macaddr)
608     {
609     if (net == NULL)
610     return;
611    
612     if (extra == NULL) {
613     fprintf(stderr, "net_add_nic(): extra = NULL\n");
614     exit(1);
615     }
616    
617     net->n_nics ++;
618     net->nic_extra = realloc(net->nic_extra, sizeof(void *)
619     * net->n_nics);
620     if (net->nic_extra == NULL) {
621     fprintf(stderr, "net_add_nic(): out of memory\n");
622     exit(1);
623     }
624    
625     net->nic_extra[net->n_nics - 1] = extra;
626     }
627    
628    
629     /*
630     * net_gateway_init():
631     *
632     * This function creates a "gateway" machine (for example at IPv4 address
633     * 10.0.0.254, if the net is 10.0.0.0/8), which acts as a gateway/router/
634     * nameserver etc.
635     */
636     static void net_gateway_init(struct net *net)
637     {
638     unsigned char *p = (void *) &net->netmask_ipv4;
639     uint32_t x;
640     int xl;
641    
642     x = (p[0] << 24) + (p[1] << 16) + (p[2] << 8) + p[3];
643     xl = 32 - net->netmask_ipv4_len;
644     if (xl > 8)
645     xl = 8;
646     x |= ((1 << xl) - 1) & ~1;
647    
648     net->gateway_ipv4_addr[0] = x >> 24;
649     net->gateway_ipv4_addr[1] = x >> 16;
650     net->gateway_ipv4_addr[2] = x >> 8;
651     net->gateway_ipv4_addr[3] = x;
652    
653     net->gateway_ethernet_addr[0] = 0x60;
654     net->gateway_ethernet_addr[1] = 0x50;
655     net->gateway_ethernet_addr[2] = 0x40;
656     net->gateway_ethernet_addr[3] = 0x30;
657     net->gateway_ethernet_addr[4] = 0x20;
658     net->gateway_ethernet_addr[5] = 0x10;
659     }
660    
661    
662     /*
663     * net_dumpinfo():
664     *
665     * Called from the debugger's "machine" command, to print some info about
666     * a network.
667     */
668     void net_dumpinfo(struct net *net)
669     {
670     int iadd = DEBUG_INDENTATION;
671     struct remote_net *rnp;
672    
673     debug("net: simulating ");
674    
675     net_debugaddr(&net->netmask_ipv4, NET_ADDR_IPV4);
676     debug("/%i", net->netmask_ipv4_len);
677    
678     debug(" (max outgoing: TCP=%i, UDP=%i)\n",
679     MAX_TCP_CONNECTIONS, MAX_UDP_CONNECTIONS);
680    
681     debug_indentation(iadd);
682    
683     debug("simulated gateway: ");
684     net_debugaddr(&net->gateway_ipv4_addr, NET_ADDR_IPV4);
685     debug(" (");
686     net_debugaddr(&net->gateway_ethernet_addr, NET_ADDR_ETHERNET);
687     debug(")\n");
688    
689     debug_indentation(iadd);
690     if (!net->nameserver_known) {
691     debug("(could not determine nameserver)");
692     } else {
693     debug("using nameserver ");
694     net_debugaddr(&net->nameserver_ipv4, NET_ADDR_IPV4);
695     }
696     if (net->domain_name != NULL && net->domain_name[0])
697     debug(", domain \"%s\"", net->domain_name);
698     debug("\n");
699     debug_indentation(-iadd);
700    
701     rnp = net->remote_nets;
702     if (net->local_port != 0)
703     debug("distributed network: local port = %i\n",
704     net->local_port);
705     debug_indentation(iadd);
706     while (rnp != NULL) {
707     debug("remote \"%s\": ", rnp->name);
708     net_debugaddr(&rnp->ipv4_addr, NET_ADDR_IPV4);
709     debug(" port %i\n", rnp->portnr);
710     rnp = rnp->next;
711     }
712     debug_indentation(-iadd);
713    
714     debug_indentation(-iadd);
715     }
716    
717    
718     /*
719     * net_init():
720     *
721     * This function creates a network, and returns a pointer to it.
722     *
723     * ipv4addr should be something like "10.0.0.0", netipv4len = 8.
724     *
725     * If n_remote is more than zero, remote should be a pointer to an array
726     * of strings of the following format: "host:portnr".
727     *
728     * Network settings are registered if settings_prefix is non-NULL.
729     * (The one calling net_init() is also responsible for calling net_deinit().)
730     *
731     * On failure, exit() is called.
732     */
733     struct net *net_init(struct emul *emul, int init_flags,
734     const char *ipv4addr, int netipv4len,
735     char **remote, int n_remote, int local_port,
736     const char *settings_prefix)
737     {
738     struct net *net;
739     int res;
740    
741     net = malloc(sizeof(struct net));
742     if (net == NULL) {
743     fprintf(stderr, "net_init(): out of memory\n");
744     exit(1);
745     }
746    
747     memset(net, 0, sizeof(struct net));
748    
749     /* Set the back pointer: */
750     net->emul = emul;
751    
752     /* Sane defaults: */
753     net->timestamp = 0;
754     net->first_ethernet_packet = net->last_ethernet_packet = NULL;
755    
756     #ifdef HAVE_INET_PTON
757     res = inet_pton(AF_INET, ipv4addr, &net->netmask_ipv4);
758     #else
759     res = inet_aton(ipv4addr, &net->netmask_ipv4);
760     #endif
761     if (res < 1) {
762     fprintf(stderr, "net_init(): could not parse IPv4 address"
763     " '%s'\n", ipv4addr);
764     exit(1);
765     }
766    
767     if (netipv4len < 1 || netipv4len > 30) {
768     fprintf(stderr, "net_init(): extremely weird ipv4 "
769     "network length (%i)\n", netipv4len);
770     exit(1);
771     }
772     net->netmask_ipv4_len = netipv4len;
773    
774     net->nameserver_known = 0;
775     net->domain_name = "";
776     parse_resolvconf(net);
777    
778     /* Distributed network? Then add remote hosts: */
779     if (local_port != 0) {
780     struct sockaddr_in si_self;
781    
782     net->local_port = local_port;
783     net->local_port_socket = socket(AF_INET, SOCK_DGRAM, 0);
784     if (net->local_port_socket < 0) {
785     perror("socket");
786     exit(1);
787     }
788    
789     memset((char *)&si_self, sizeof(si_self), 0);
790     si_self.sin_family = AF_INET;
791     si_self.sin_port = htons(local_port);
792     si_self.sin_addr.s_addr = htonl(INADDR_ANY);
793     if (bind(net->local_port_socket, (struct sockaddr *)&si_self,
794     sizeof(si_self)) < 0) {
795     perror("bind");
796     exit(1);
797     }
798    
799     /* Set the socket to non-blocking: */
800     res = fcntl(net->local_port_socket, F_GETFL);
801     fcntl(net->local_port_socket, F_SETFL, res | O_NONBLOCK);
802     }
803     if (n_remote != 0) {
804     struct remote_net *rnp;
805     while ((n_remote--) != 0) {
806     struct hostent *hp;
807    
808     /* debug("adding '%s'\n", remote[n_remote]); */
809     rnp = malloc(sizeof(struct remote_net));
810     memset(rnp, 0, sizeof(struct remote_net));
811    
812     rnp->next = net->remote_nets;
813     net->remote_nets = rnp;
814    
815     rnp->name = strdup(remote[n_remote]);
816     if (strchr(rnp->name, ':') != NULL)
817     strchr(rnp->name, ':')[0] = '\0';
818    
819     hp = gethostbyname(rnp->name);
820     if (hp == NULL) {
821     fprintf(stderr, "could not resolve '%s'\n",
822     rnp->name);
823     exit(1);
824     }
825     memcpy(&rnp->ipv4_addr, hp->h_addr, hp->h_length);
826     free(rnp->name);
827    
828     /* And again: */
829     rnp->name = strdup(remote[n_remote]);
830     if (strchr(rnp->name, ':') == NULL) {
831     fprintf(stderr, "Remote network '%s' is not "
832     "'host:portnr'?\n", rnp->name);
833     exit(1);
834     }
835     rnp->portnr = atoi(strchr(rnp->name, ':') + 1);
836     }
837     }
838    
839     if (init_flags & NET_INIT_FLAG_GATEWAY)
840     net_gateway_init(net);
841    
842     net_dumpinfo(net);
843    
844     /* This is necessary when using the real network: */
845     signal(SIGPIPE, SIG_IGN);
846    
847     return net;
848     }
849    

  ViewVC Help
Powered by ViewVC 1.1.26