Updates to -DPXE_DHCP_STRICT from Roland Kuhn
[etherboot.git] / src / core / nic.c
1 /**************************************************************************
2 Etherboot -  Network Bootstrap Program
3
4 Literature dealing with the network protocols:
5         ARP - RFC826
6         RARP - RFC903
7         IP - RFC791
8         UDP - RFC768
9         BOOTP - RFC951, RFC2132 (vendor extensions)
10         DHCP - RFC2131, RFC2132, RFC3004 (options)
11         TFTP - RFC1350, RFC2347 (options), RFC2348 (blocksize), RFC2349 (tsize)
12         RPC - RFC1831, RFC1832 (XDR), RFC1833 (rpcbind/portmapper)
13         NFS - RFC1094, RFC1813 (v3, useful for clarifications, not implemented)
14         IGMP - RFC1112, RFC2113, RFC2365, RFC2236, RFC3171
15
16 **************************************************************************/
17 #include "etherboot.h"
18 #include "nic.h"
19 #include "elf.h" /* FOR EM_CURRENT */
20
21 struct arptable_t       arptable[MAX_ARP];
22 #if MULTICAST_LEVEL2
23 unsigned long last_igmpv1 = 0;
24 struct igmptable_t      igmptable[MAX_IGMP];
25 #endif
26 /* Put rom_info in .nocompress section so romprefix.S can write to it */
27 struct rom_info rom __attribute__ ((section (".text16.nocompress"))) = {0,0};
28 static unsigned long    netmask;
29 /* Used by nfs.c */
30 char *hostname = "";
31 int hostnamelen = 0;
32 #ifndef USE_STATIC_BOOT_INFO
33 static uint32_t xid;
34 #endif
35 static uint16_t sport;
36 unsigned char *end_of_rfc1533 = NULL;
37 unsigned char *addparam;
38 int addparamlen;
39
40 #ifdef IMAGE_FREEBSD
41 int freebsd_howto = 0;
42 char freebsd_kernel_env[FREEBSD_KERNEL_ENV_SIZE];
43 #endif /* IMAGE_FREEBSD */
44
45 static int vendorext_isvalid;
46 static const unsigned char vendorext_magic[] = {0xE4,0x45,0x74,0x68}; /* √§Eth */
47 static const unsigned char broadcast[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
48 static const in_addr zeroIP = { 0L };
49
50 struct bootpd_t bootp_data;
51
52 #ifdef PXE_DHCP_STRICT
53 #define MAX_BOOT_MENU 5
54 #define MAX_BOOT_ENTRY_LENGTH 60
55 struct {
56   uint16_t id;
57   unsigned char text[MAX_BOOT_ENTRY_LENGTH+1];
58   in_addr ip;
59 } pxe_boot_menu[MAX_BOOT_MENU];
60 static unsigned char num_boot_menu = 0;
61 #endif /* PXE_DHCP_STRICT */
62
63 #ifdef  NO_DHCP_SUPPORT
64 static unsigned char    rfc1533_cookie[5] = { RFC1533_COOKIE, RFC1533_END };
65 #else   /* NO_DHCP_SUPPORT */
66 static int dhcp_reply;
67 static in_addr dhcp_server = { 0L };
68 static unsigned char    rfc1533_cookie[] = { RFC1533_COOKIE };
69 #define DHCP_MACHINE_INFO_SIZE (sizeof dhcp_machine_info)
70 #ifndef USE_STATIC_BOOT_INFO
71 static in_addr dhcp_addr = { 0L };
72 static unsigned char dhcp_machine_info[] = {
73         /* Our enclosing DHCP tag */
74         RFC1533_VENDOR_ETHERBOOT_ENCAP, 11,
75         /* Our boot device */
76         RFC1533_VENDOR_NIC_DEV_ID, 5, PCI_BUS_TYPE, 0, 0, 0, 0,
77         /* Our current architecture */
78         RFC1533_VENDOR_ARCH, 2, EM_CURRENT & 0xff, (EM_CURRENT >> 8) & 0xff,
79 #ifdef EM_CURRENT_64
80         /* The 64bit version of our current architecture */
81         RFC1533_VENDOR_ARCH, 2, EM_CURRENT_64 & 0xff, (EM_CURRENT_64 >> 8) & 0xff,
82 #undef DHCP_MACHINE_INFO_SIZE
83 #define DHCP_MACHINE_INFO_SIZE (sizeof(dhcp_machine_info) - (EM_CURRENT_64_PRESENT? 0: 4))
84 #endif /* EM_CURRENT_64 */
85 };
86 #endif /* USE_STATIC_BOOT_INFO */
87 static const unsigned char dhcpdiscover[] = {
88         RFC2132_MSG_TYPE,1,DHCPDISCOVER,
89         RFC2132_MAX_SIZE,2,     /* request as much as we can */
90         ETH_MAX_MTU / 256, ETH_MAX_MTU % 256,
91 #ifdef PXE_DHCP_STRICT
92         RFC3679_PXE_CLIENT_UUID,RFC3679_PXE_CLIENT_UUID_LENGTH,RFC3679_PXE_CLIENT_UUID_DEFAULT,
93         RFC3679_PXE_CLIENT_ARCH,RFC3679_PXE_CLIENT_ARCH_LENGTH,RFC3679_PXE_CLIENT_ARCH_IAX86PC,
94         RFC3679_PXE_CLIENT_NDI, RFC3679_PXE_CLIENT_NDI_LENGTH, RFC3679_PXE_CLIENT_NDI_21,
95         RFC2132_VENDOR_CLASS_ID,RFC2132_VENDOR_CLASS_ID_PXE_LENGTH,RFC2132_VENDOR_CLASS_ID_PXE,
96 #else
97         RFC2132_VENDOR_CLASS_ID,13,'E','t','h','e','r','b','o','o','t',
98         '-',VERSION_MAJOR+'0','.',VERSION_MINOR+'0',
99 #endif /* PXE_DHCP_STRICT */
100 #ifdef DHCP_CLIENT_ID
101         /* Client ID Option */
102         RFC2132_CLIENT_ID, ( DHCP_CLIENT_ID_LEN + 1 ),
103         DHCP_CLIENT_ID_TYPE, DHCP_CLIENT_ID,
104 #endif /* DHCP_CLIENT_ID */
105 #ifdef DHCP_USER_CLASS
106         /* User Class Option */
107         RFC3004_USER_CLASS, DHCP_USER_CLASS_LEN, DHCP_USER_CLASS,
108 #endif /* DHCP_USER_CLASS */
109         RFC2132_PARAM_LIST,
110 #define DHCPDISCOVER_PARAMS_BASE 4
111 #ifdef  PXE_DHCP_STRICT
112 #define DHCPDISCOVER_PARAMS_PXE ( 1 + 8 )
113 #else
114 #define DHCPDISCOVER_PARAMS_PXE 0
115 #endif /* PXE_DHCP_STRICT */
116 #ifdef  DNS_RESOLVER
117 #define DHCPDISCOVER_PARAMS_DNS  1
118 #else
119 #define DHCPDISCOVER_PARAMS_DNS  0
120 #endif /* DNS_RESOLVER */
121         ( DHCPDISCOVER_PARAMS_BASE +
122           DHCPDISCOVER_PARAMS_PXE+
123           DHCPDISCOVER_PARAMS_DNS ),
124         RFC1533_NETMASK,
125         RFC1533_GATEWAY,
126         RFC1533_HOSTNAME,
127         RFC1533_VENDOR
128 #ifdef PXE_DHCP_STRICT
129         ,RFC2132_VENDOR_CLASS_ID,
130         RFC1533_VENDOR_PXE_OPT128,
131         RFC1533_VENDOR_PXE_OPT129,
132         RFC1533_VENDOR_PXE_OPT130,
133         RFC1533_VENDOR_PXE_OPT131,
134         RFC1533_VENDOR_PXE_OPT132,
135         RFC1533_VENDOR_PXE_OPT133,
136         RFC1533_VENDOR_PXE_OPT134,
137         RFC1533_VENDOR_PXE_OPT135
138 #endif /* PXE_DHCP_STRICT */
139 #ifdef  DNS_RESOLVER
140         ,RFC1533_DNS
141 #endif
142 };
143 static const unsigned char dhcprequest [] = {
144         RFC2132_MSG_TYPE,1,DHCPREQUEST,
145         RFC2132_SRV_ID,4,0,0,0,0,
146         RFC2132_REQ_ADDR,4,0,0,0,0,
147         RFC2132_MAX_SIZE,2,     /* request as much as we can */
148         ETH_MAX_MTU / 256, ETH_MAX_MTU % 256,
149 #ifdef PXE_DHCP_STRICT
150         RFC3679_PXE_CLIENT_UUID,RFC3679_PXE_CLIENT_UUID_LENGTH,RFC3679_PXE_CLIENT_UUID_DEFAULT,
151         RFC3679_PXE_CLIENT_ARCH,RFC3679_PXE_CLIENT_ARCH_LENGTH,RFC3679_PXE_CLIENT_ARCH_IAX86PC,
152         RFC3679_PXE_CLIENT_NDI, RFC3679_PXE_CLIENT_NDI_LENGTH, RFC3679_PXE_CLIENT_NDI_21,
153         RFC2132_VENDOR_CLASS_ID,RFC2132_VENDOR_CLASS_ID_PXE_LENGTH,RFC2132_VENDOR_CLASS_ID_PXE,
154 #else
155         RFC2132_VENDOR_CLASS_ID,13,'E','t','h','e','r','b','o','o','t',
156         '-',VERSION_MAJOR+'0','.',VERSION_MINOR+'0',
157 #endif /* PXE_DHCP_STRICT */
158 #ifdef DHCP_CLIENT_ID
159         /* Client ID Option */
160         RFC2132_CLIENT_ID, ( DHCP_CLIENT_ID_LEN + 1 ),
161         DHCP_CLIENT_ID_TYPE, DHCP_CLIENT_ID,
162 #endif /* DHCP_CLIENT_ID */
163 #ifdef DHCP_USER_CLASS
164         /* User Class Option */
165         RFC3004_USER_CLASS, DHCP_USER_CLASS_LEN, DHCP_USER_CLASS,
166 #endif /* DHCP_USER_CLASS */
167         /* request parameters */
168         RFC2132_PARAM_LIST,
169 #define DHCPREQUEST_PARAMS_BASE 5  
170 #ifdef  PXE_DHCP_STRICT
171 #define DHCPREQUEST_PARAMS_PXE 1
172 #define DHCPREQUEST_PARAMS_VENDOR_PXE 8
173 #define DHCPREQUEST_PARAMS_VENDOR_EB 0
174 #else
175 #define DHCPREQUEST_PARAMS_PXE 0
176 #define DHCPREQUEST_PARAMS_VENDOR_PXE 0
177 #define DHCPREQUEST_PARAMS_VENDOR_EB 4
178 #endif /* PXE_DHCP_STRICT */
179 #ifdef  IMAGE_FREEBSD
180 #define DHCPREQUEST_PARAMS_FREEBSD 2
181 #else
182 #define DHCPREQUEST_PARAMS_FREEBSD 0
183 #endif /* IMAGE_FREEBSD */
184 #ifdef  DNS_RESOLVER
185 #define DHCPREQUEST_PARAMS_DNS     1
186 #else
187 #define DHCPREQUEST_PARAMS_DNS     0
188 #endif /* DNS_RESOLVER */
189         ( DHCPREQUEST_PARAMS_BASE +
190           DHCPREQUEST_PARAMS_PXE +
191           DHCPREQUEST_PARAMS_VENDOR_PXE +
192           DHCPREQUEST_PARAMS_VENDOR_EB +
193           DHCPREQUEST_PARAMS_DNS +
194           DHCPREQUEST_PARAMS_FREEBSD ),
195         /* 5 Standard parameters */
196         RFC1533_NETMASK,
197         RFC1533_GATEWAY,
198         RFC1533_HOSTNAME,
199         RFC1533_VENDOR,
200         RFC1533_ROOTPATH,       /* only passed to the booted image */
201 #ifndef PXE_DHCP_STRICT
202         /* 4 Etherboot vendortags */
203         RFC1533_VENDOR_MAGIC,
204         RFC1533_VENDOR_ADDPARM,
205         RFC1533_VENDOR_ETHDEV,
206         RFC1533_VENDOR_ETHERBOOT_ENCAP,
207 #endif /* ! PXE_DHCP_STRICT */
208 #ifdef  IMAGE_FREEBSD
209         /* 2 FreeBSD options */
210         RFC1533_VENDOR_HOWTO,
211         RFC1533_VENDOR_KERNEL_ENV,
212 #endif
213 #ifdef  DNS_RESOLVER
214         /* 1 DNS option */
215         RFC1533_DNS,
216 #endif
217 #ifdef  PXE_DHCP_STRICT
218         RFC2132_VENDOR_CLASS_ID,
219         RFC1533_VENDOR_PXE_OPT128,
220         RFC1533_VENDOR_PXE_OPT129,
221         RFC1533_VENDOR_PXE_OPT130,
222         RFC1533_VENDOR_PXE_OPT131,
223         RFC1533_VENDOR_PXE_OPT132,
224         RFC1533_VENDOR_PXE_OPT133,
225         RFC1533_VENDOR_PXE_OPT134,
226         RFC1533_VENDOR_PXE_OPT135,
227 #endif /* PXE_DHCP_STRICT */
228 };
229 #ifdef PXE_EXPORT
230 static const unsigned char proxydhcprequest [] = {
231         RFC2132_MSG_TYPE,1,DHCPREQUEST,
232         RFC2132_MAX_SIZE,2,     /* request as much as we can */
233         ETH_MAX_MTU / 256, ETH_MAX_MTU % 256,
234 #ifdef  PXE_DHCP_STRICT
235         RFC3679_PXE_CLIENT_UUID,RFC3679_PXE_CLIENT_UUID_LENGTH,RFC3679_PXE_CLIENT_UUID_DEFAULT,
236         RFC3679_PXE_CLIENT_ARCH,RFC3679_PXE_CLIENT_ARCH_LENGTH,RFC3679_PXE_CLIENT_ARCH_IAX86PC,
237         RFC3679_PXE_CLIENT_NDI, RFC3679_PXE_CLIENT_NDI_LENGTH, RFC3679_PXE_CLIENT_NDI_21,
238         RFC2132_VENDOR_CLASS_ID,RFC2132_VENDOR_CLASS_ID_PXE_LENGTH,RFC2132_VENDOR_CLASS_ID_PXE,
239 #endif /* PXE_DHCP_STRICT */
240 };
241 #endif
242
243 #ifdef PXE_DHCP_STRICT
244 static const unsigned char pxedhcprequest [] = {
245         RFC2132_MSG_TYPE,1,DHCPREQUEST,
246         RFC1533_VENDOR,6,PXE_BOOT_ITEM,4,0,0,0,0,
247         RFC3679_PXE_CLIENT_UUID,RFC3679_PXE_CLIENT_UUID_LENGTH,RFC3679_PXE_CLIENT_UUID_DEFAULT,
248         RFC3679_PXE_CLIENT_ARCH,RFC3679_PXE_CLIENT_ARCH_LENGTH,RFC3679_PXE_CLIENT_ARCH_IAX86PC,
249         RFC3679_PXE_CLIENT_NDI, RFC3679_PXE_CLIENT_NDI_LENGTH, RFC3679_PXE_CLIENT_NDI_21,
250         RFC2132_VENDOR_CLASS_ID,RFC2132_VENDOR_CLASS_ID_PXE_LENGTH,RFC2132_VENDOR_CLASS_ID_PXE
251 };
252 #endif /* PXE_DHCP_STRICT */
253
254 #ifdef  REQUIRE_VCI_ETHERBOOT
255 int     vci_etherboot;
256 #endif
257 #endif  /* NO_DHCP_SUPPORT */
258
259 static int dummy(void *unused __unused)
260 {
261         return (0);
262 }
263
264 /* Careful.  We need an aligned buffer to avoid problems on machines
265  * that care about alignment.  To trivally align the ethernet data
266  * (the ip hdr and arp requests) we offset the packet by 2 bytes.
267  * leaving the ethernet data 16 byte aligned.  Beyond this
268  * we use memmove but this makes the common cast simple and fast.
269  */
270 static char     packet[ETH_FRAME_LEN + ETH_DATA_ALIGN] __aligned;
271
272 struct nic      nic =
273 {
274         {
275                 0,                              /* dev.disable */
276                 {
277                         0,
278                         0,
279                         PCI_BUS_TYPE,
280                 },                              /* dev.devid */
281                 0,                              /* index */
282                 0,                              /* type */
283                 PROBE_FIRST,                    /* how_pobe */
284                 PROBE_NONE,                     /* to_probe */
285                 0,                              /* failsafe */
286                 0,                              /* type_index */
287                 {},                             /* state */
288         },
289         (int (*)(struct nic *, int))dummy,      /* poll */
290         (void (*)(struct nic *, const char *,
291                 unsigned int, unsigned int,
292                 const char *))dummy,            /* transmit */
293         (void (*)(struct nic *,
294                  irq_action_t))dummy,           /* irq */
295         0,                                      /* flags */
296         &rom,                                   /* rom_info */
297         arptable[ARP_CLIENT].node,              /* node_addr */
298         packet + ETH_DATA_ALIGN,                /* packet */
299         0,                                      /* packetlen */
300         0,                                      /* ioaddr */
301         0,                                      /* irqno */
302         0,                                      /* priv_data */
303 };
304
305 #ifdef RARP_NOT_BOOTP
306 static int rarp(void);
307 #else
308 #ifdef USE_STATIC_BOOT_INFO
309 static int get_static_boot_info(void);
310 #else
311 static int bootp(void);
312 #endif /* USE_STATIC_BOOT_INFO */
313 #endif /* RARP_NOT_BOOTP */
314 static unsigned short tcpudpchksum(struct iphdr *ip);
315
316
317 int eth_probe(struct dev *dev)
318 {
319         return probe(dev);
320 }
321
322 int eth_poll(int retrieve)
323 {
324         return ((*nic.poll)(&nic, retrieve));
325 }
326
327 void eth_transmit(const char *d, unsigned int t, unsigned int s, const void *p)
328 {
329         (*nic.transmit)(&nic, d, t, s, p);
330         if (t == ETH_P_IP) twiddle();
331 }
332
333 void eth_disable(void)
334 {
335 #ifdef MULTICAST_LEVEL2
336         int i;
337         for(i = 0; i < MAX_IGMP; i++) {
338                 leave_group(i);
339         }
340 #endif
341         disable(&nic.dev);
342 }
343
344 void eth_irq (irq_action_t action)
345 {
346         (*nic.irq)(&nic,action);
347 }
348
349 /*
350  * Find out what our boot parameters are
351  */
352 int eth_load_configuration(struct dev *dev __unused)
353 {
354         int server_found;
355         /* Find a server to get BOOTP reply from */
356 #ifdef  USE_STATIC_BOOT_INFO
357         printf("Using Static IP Information...");
358 #else   
359 #ifdef  RARP_NOT_BOOTP
360         printf("Searching for server (RARP)...");
361 #else
362 #ifndef NO_DHCP_SUPPORT
363         printf("Searching for server (DHCP)...");
364 #else
365         printf("Searching for server (BOOTP)...");
366 #endif
367 #endif
368 #endif
369         
370 #ifdef  USE_STATIC_BOOT_INFO
371         server_found = get_static_boot_info();
372 #else   
373 #ifdef  RARP_NOT_BOOTP
374         server_found = rarp();
375 #else
376         server_found = bootp();
377 #endif
378 #endif
379         if (!server_found) {
380                 printf("No Server found\n");
381                 longjmp(restart_etherboot, -1);
382         }
383         return 0;
384 }
385
386
387 /**************************************************************************
388 LOAD - Try to get booted
389 **************************************************************************/
390 int eth_load(struct dev *dev __unused)
391 {
392         const char      *kernel;
393         printf("\nMe: %@", arptable[ARP_CLIENT].ipaddr.s_addr );
394 #ifndef USE_STATIC_BOOT_INFO
395 #ifndef NO_DHCP_SUPPORT
396         printf(", DHCP: %@", dhcp_server );
397 #ifdef PXE_EXPORT       
398         if (arptable[ARP_PROXYDHCP].ipaddr.s_addr)
399                 printf(" (& %@)",
400                        arptable[ARP_PROXYDHCP].ipaddr.s_addr);
401 #endif /* PXE_EXPORT */
402 #endif /* ! NO_DHCP_SUPPORT */
403 #endif /* USE_STATIC_BOOT_INFO */       
404         printf(", TFTP: %@", arptable[ARP_SERVER].ipaddr.s_addr);
405         if (bootp_data.bootp_reply.bp_giaddr.s_addr)
406                 printf(", Relay: %@", bootp_data.bootp_reply.bp_giaddr.s_addr);
407         if (arptable[ARP_GATEWAY].ipaddr.s_addr)
408                 printf(", Gateway %@", arptable[ARP_GATEWAY].ipaddr.s_addr);
409 #ifdef  DNS_RESOLVER
410         if (arptable[ARP_NAMESERVER].ipaddr.s_addr)
411                 printf(", Nameserver %@", arptable[ARP_NAMESERVER].ipaddr.s_addr);
412 #endif
413         putchar('\n');
414
415 #ifdef  MDEBUG
416         printf("\n=>>"); getchar();
417 #endif
418
419         /* Now use TFTP to load file */
420 #ifdef  DOWNLOAD_PROTO_NFS
421         rpc_init();
422 #endif
423
424         /* Handle boot filename static and default cases */
425
426         if ( KERNEL_BUF[0] != '\0' ) {
427           kernel = KERNEL_BUF;
428         } else {
429 #if defined(USE_STATIC_BOOT_INFO) && defined(STATIC_BOOTFILE)
430           kernel = STATIC_BOOTFILE;
431 #elif defined(DEFAULT_BOOTFILE)
432           kernel = DEFAULT_BOOTFILE;
433 #else
434           kernel = NULL;
435 #endif
436         }
437
438         /* Remove .zpxe from filename if it exists */
439
440 #ifdef  ZPXE_SUFFIX_STRIP
441         {
442           int i = 0;
443           while (kernel[i++]);
444           if(i > 5) {
445             if(kernel[i - 6] == '.' &&
446                kernel[i - 5] == 'z' &&
447                kernel[i - 4] == 'p' &&
448                kernel[i - 3] == 'x' &&
449                kernel[i - 2] == 'e') {
450               printf("Trimming .zpxe extension\n");
451               kernel[i - 6] = 0;
452             }
453           }
454         }
455 #endif
456
457         if ( kernel ) {
458                 loadkernel(kernel); /* We don't return except on error */
459                 printf("Unable to load file.\n");
460 #ifdef EXIT_ON_FILE_LOAD_ERROR
461                 longjmp(restart_etherboot, 255);
462 #endif
463         } else {        
464                 printf("No filename\n");
465         }
466         interruptible_sleep(2);         /* lay off the server for a while */
467         longjmp(restart_etherboot, -1);
468 }
469
470
471 /**************************************************************************
472 DEFAULT_NETMASK - Return default netmask for IP address
473 **************************************************************************/
474 static inline unsigned long default_netmask(void)
475 {
476         int net = ntohl(arptable[ARP_CLIENT].ipaddr.s_addr) >> 24;
477         if (net <= 127)
478                 return(htonl(0xff000000));
479         else if (net < 192)
480                 return(htonl(0xffff0000));
481         else
482                 return(htonl(0xffffff00));
483 }
484
485 /**************************************************************************
486 IP_TRANSMIT - Send an IP datagram
487 **************************************************************************/
488 static int await_arp(int ival, void *ptr,
489         unsigned short ptype, struct iphdr *ip __unused, struct udphdr *udp __unused,
490         struct tcphdr *tcp __unused)
491 {
492         struct  arprequest *arpreply;
493         if (ptype != ETH_P_ARP)
494                 return 0;
495         if (nic.packetlen < ETH_HLEN + sizeof(struct arprequest))
496                 return 0;
497         arpreply = (struct arprequest *)&nic.packet[ETH_HLEN];
498
499         if (arpreply->opcode != htons(ARP_REPLY)) 
500                 return 0;
501         if (memcmp(arpreply->sipaddr, ptr, sizeof(in_addr)) != 0)
502                 return 0;
503         memcpy(arptable[ival].node, arpreply->shwaddr, ETH_ALEN);
504         return 1;
505 }
506
507 int ip_transmit(int len, const void *buf)
508 {
509         unsigned long destip;
510         struct iphdr *ip;
511         struct arprequest arpreq;
512         int arpentry, i;
513         int retry;
514
515         ip = (struct iphdr *)buf;
516         destip = ip->dest.s_addr;
517         if (destip == IP_BROADCAST) {
518                 eth_transmit(broadcast, ETH_P_IP, len, buf);
519 #ifdef MULTICAST_LEVEL1 
520         } else if ((destip & htonl(MULTICAST_MASK)) == htonl(MULTICAST_NETWORK)) {
521                 unsigned char multicast[6];
522                 unsigned long hdestip;
523                 hdestip = ntohl(destip);
524                 multicast[0] = 0x01;
525                 multicast[1] = 0x00;
526                 multicast[2] = 0x5e;
527                 multicast[3] = (hdestip >> 16) & 0x7;
528                 multicast[4] = (hdestip >> 8) & 0xff;
529                 multicast[5] = hdestip & 0xff;
530                 eth_transmit(multicast, ETH_P_IP, len, buf);
531 #endif
532         } else {
533                 if (((destip & netmask) !=
534                         (arptable[ARP_CLIENT].ipaddr.s_addr & netmask)) &&
535                         arptable[ARP_GATEWAY].ipaddr.s_addr)
536                                 destip = arptable[ARP_GATEWAY].ipaddr.s_addr;
537                 for(arpentry = 0; arpentry<MAX_ARP; arpentry++)
538                         if (arptable[arpentry].ipaddr.s_addr == destip) break;
539                 if (arpentry == MAX_ARP) {
540                         printf("%@ is not in my arp table!\n", destip);
541                         return(0);
542                 }
543                 for (i = 0; i < ETH_ALEN; i++)
544                         if (arptable[arpentry].node[i])
545                                 break;
546                 if (i == ETH_ALEN) {    /* Need to do arp request */
547                         arpreq.hwtype = htons(1);
548                         arpreq.protocol = htons(IP);
549                         arpreq.hwlen = ETH_ALEN;
550                         arpreq.protolen = 4;
551                         arpreq.opcode = htons(ARP_REQUEST);
552                         memcpy(arpreq.shwaddr, arptable[ARP_CLIENT].node, ETH_ALEN);
553                         memcpy(arpreq.sipaddr, &arptable[ARP_CLIENT].ipaddr, sizeof(in_addr));
554                         memset(arpreq.thwaddr, 0, ETH_ALEN);
555                         memcpy(arpreq.tipaddr, &destip, sizeof(in_addr));
556                         for (retry = 1; retry <= MAX_ARP_RETRIES; retry++) {
557                                 long timeout;
558                                 eth_transmit(broadcast, ETH_P_ARP, sizeof(arpreq),
559                                         &arpreq);
560                                 timeout = rfc2131_sleep_interval(TIMEOUT, retry);
561                                 if (await_reply(await_arp, arpentry,
562                                         arpreq.tipaddr, timeout)) goto xmit;
563                         }
564                         return(0);
565                 }
566 xmit:
567                 eth_transmit(arptable[arpentry].node, ETH_P_IP, len, buf);
568         }
569         return 1;
570 }
571
572 void build_ip_hdr(unsigned long destip, int ttl, int protocol, int option_len,
573         int len, const void *buf)
574 {
575         struct iphdr *ip;
576         ip = (struct iphdr *)buf;
577         ip->verhdrlen = 0x45;
578         ip->verhdrlen += (option_len/4);
579         ip->service = 0;
580         ip->len = htons(len);
581         ip->ident = 0;
582         ip->frags = 0; /* Should we set don't fragment? */
583         ip->ttl = ttl;
584         ip->protocol = protocol;
585         ip->chksum = 0;
586         ip->src.s_addr = arptable[ARP_CLIENT].ipaddr.s_addr;
587         ip->dest.s_addr = destip;
588         ip->chksum = ipchksum(buf, sizeof(struct iphdr) + option_len);
589 }
590
591 void build_udp_hdr(unsigned long destip, 
592         unsigned int srcsock, unsigned int destsock, int ttl,
593         int len, const void *buf)
594 {
595         struct iphdr *ip;
596         struct udphdr *udp;
597         ip = (struct iphdr *)buf;
598         build_ip_hdr(destip, ttl, IP_UDP, 0, len, buf);
599         udp = (struct udphdr *)((char *)buf + sizeof(struct iphdr));
600         udp->src = htons(srcsock);
601         udp->dest = htons(destsock);
602         udp->len = htons(len - sizeof(struct iphdr));
603         udp->chksum = 0;
604         if ((udp->chksum = tcpudpchksum(ip)) == 0)
605                 udp->chksum = 0xffff;
606 }
607
608 #ifdef DOWNLOAD_PROTO_HTTP
609 void build_tcp_hdr(unsigned long destip, unsigned int srcsock,
610                   unsigned int destsock, long send_seq, long recv_seq,
611                   int window, int flags, int ttl, int len, const void *buf)
612 {
613        struct iphdr *ip;
614        struct tcphdr *tcp;
615        ip = (struct iphdr *)buf;
616        build_ip_hdr(destip, ttl, IP_TCP, 0, len, buf);
617        tcp = (struct tcphdr *)(ip + 1);
618        tcp->src = htons(srcsock);
619        tcp->dst = htons(destsock);
620        tcp->seq = htonl(send_seq);
621        tcp->ack = htonl(recv_seq);
622        tcp->ctrl = htons(flags + (5 << 12)); /* No TCP options */
623        tcp->window = htons(window);
624        tcp->chksum = 0;
625        if ((tcp->chksum = tcpudpchksum(ip)) == 0)
626                tcp->chksum = 0xffff;
627 }
628 #endif
629
630
631 /**************************************************************************
632 UDP_TRANSMIT - Send an UDP datagram
633 **************************************************************************/
634 int udp_transmit(unsigned long destip, unsigned int srcsock,
635         unsigned int destsock, int len, const void *buf)
636 {
637         sport = srcsock;
638         build_udp_hdr(destip, srcsock, destsock, 60, len, buf);
639         return ip_transmit(len, buf);
640 }
641
642 /**************************************************************************
643 TCP_TRANSMIT - Send a TCP packet
644 **************************************************************************/
645 #ifdef DOWNLOAD_PROTO_HTTP
646 int tcp_transmit(unsigned long destip, unsigned int srcsock,
647                 unsigned int destsock, long send_seq, long recv_seq,
648                 int window, int flags, int len, const void *buf)
649 {
650        build_tcp_hdr(destip, srcsock, destsock, send_seq, recv_seq,
651                      window, flags, 60, len, buf);
652        return ip_transmit(len, buf);
653 }
654
655 int tcp_reset(struct iphdr *ip) {
656        struct tcphdr *tcp = (struct tcphdr *)(ip + 1);
657        char buf[sizeof(struct iphdr) + sizeof(struct tcphdr)];
658
659        if (!(tcp->ctrl & htons(RST))) {
660               long seq = ntohl(tcp->seq) + ntohs(ip->len) -
661                          sizeof(struct iphdr) -
662                          ((ntohs(tcp->ctrl) >> 10) & 0x3C);
663               if (tcp->ctrl & htons(SYN|FIN))
664                       seq++;
665               return tcp_transmit(ntohl(ip->src.s_addr),
666                                   ntohs(tcp->dst), ntohs(tcp->src),
667                                   tcp->ctrl&htons(ACK) ? ntohl(tcp->ack) : 0,
668                                   seq, TCP_MAX_WINDOW, RST, sizeof(buf), buf);
669        }
670        return (1);
671 }
672 #endif
673
674 /**************************************************************************
675 QDRAIN - clear the nic's receive queue
676 **************************************************************************/
677 static int await_qdrain(int ival __unused, void *ptr __unused,
678         unsigned short ptype __unused, 
679         struct iphdr *ip __unused, struct udphdr *udp __unused,
680         struct tcphdr *tcp __unused)
681 {
682         return 0;
683 }
684
685 void rx_qdrain(void)
686 {
687         /* Clear out the Rx queue first.  It contains nothing of interest,
688          * except possibly ARP requests from the DHCP/TFTP server.  We use
689          * polling throughout Etherboot, so some time may have passed since we
690          * last polled the receive queue, which may now be filled with
691          * broadcast packets.  This will cause the reply to the packets we are
692          * about to send to be lost immediately.  Not very clever.  */
693         await_reply(await_qdrain, 0, NULL, 0);
694 }
695
696 #ifdef  DOWNLOAD_PROTO_TFTP
697 /**************************************************************************
698 TFTP - Download extended BOOTP data, or kernel image
699 **************************************************************************/
700 static int await_tftp(int ival, void *ptr __unused,
701         unsigned short ptype __unused, struct iphdr *ip, struct udphdr *udp,
702         struct tcphdr *tcp __unused)
703 {
704         if (!udp) {
705                 return 0;
706         }
707         if (arptable[ARP_CLIENT].ipaddr.s_addr != ip->dest.s_addr)
708                 return 0;
709         if (ntohs(udp->dest) != ival)
710                 return 0;
711         return 1;
712 }
713
714 int tftp ( const char *name,
715            int (*fnc)(unsigned char *, unsigned int, unsigned int, int) )
716 {
717         struct tftpreq_info_t request_data =
718                 { name, TFTP_PORT, TFTP_MAX_PACKET };
719         struct tftpreq_info_t *request = &request_data;
720         struct tftpblk_info_t block;
721         int rc;
722
723         while ( tftp_block ( request, &block ) ) {
724                 request = NULL; /* Send request only once */
725                 rc = fnc ( block.data, block.block, block.len, block.eof );
726                 if ( rc <= 0 ) return (rc);
727                 if ( block.eof ) {
728                         /* fnc should not have returned */
729                         printf ( "TFTP download complete, but\n" );
730                         return (0);
731                 }
732         }
733         return (0);
734 }
735
736 int tftp_block ( struct tftpreq_info_t *request, struct tftpblk_info_t *block )
737 {
738         static unsigned short lport = 2000; /* local port */
739         static unsigned short rport = TFTP_PORT; /* remote port */
740         struct tftp_t *rcvd = NULL;
741         static struct tftpreq_t xmit;
742         static unsigned short xmitlen = 0;
743         static unsigned short blockidx = 0; /* Last block received */
744         static unsigned short retry = 0; /* Retry attempts on last block */
745         static int blksize = 0;
746         unsigned short recvlen = 0;
747
748         /* If this is a new request (i.e. if name is set), fill in
749          * transmit block with RRQ and send it.
750          */
751         if ( request ) {
752                 rx_qdrain(); /* Flush receive queue */
753                 xmit.opcode = htons(TFTP_RRQ);
754                 xmitlen = (void*)&xmit.u.rrq - (void*)&xmit +
755                         sprintf((char*)xmit.u.rrq, "%s%coctet%cblksize%c%d",
756                                 request->name, 0, 0, 0, request->blksize)
757                         + 1; /* null terminator */
758                 blockidx = 0; /* Reset counters */
759                 retry = 0;
760                 blksize = TFTP_DEFAULTSIZE_PACKET;
761                 lport++; /* Use new local port */
762                 rport = request->port;
763                 if ( !udp_transmit(arptable[ARP_SERVER].ipaddr.s_addr, lport,
764                                    rport, xmitlen, &xmit) )
765                         return (0);
766         }
767         /* Exit if no transfer in progress */
768         if ( !blksize ) return (0);
769         /* Loop to wait until we get a packet we're interested in */
770         block->data = NULL; /* Used as flag */
771         while ( block->data == NULL ) {
772                 long timeout = rfc2131_sleep_interval ( blockidx ? TFTP_REXMT :
773                                                         TIMEOUT, retry );
774                 if ( !await_reply(await_tftp, lport, NULL, timeout) ) {
775                         /* No packet received */
776                         if ( retry++ > MAX_TFTP_RETRIES ) break;
777                         /* Retransmit last packet */
778                         if ( !blockidx ) lport++; /* New lport if new RRQ */
779                         if ( !udp_transmit(arptable[ARP_SERVER].ipaddr.s_addr,
780                                            lport, rport, xmitlen, &xmit) )
781                                 return (0);
782                         continue; /* Back to waiting for packet */
783                 }
784                 /* Packet has been received */
785                 rcvd = (struct tftp_t *)&nic.packet[ETH_HLEN];
786                 recvlen = ntohs(rcvd->udp.len) - sizeof(struct udphdr)
787                         - sizeof(rcvd->opcode);
788                 rport = ntohs(rcvd->udp.src);
789                 retry = 0; /* Reset retry counter */
790                 switch ( htons(rcvd->opcode) ) {
791                 case TFTP_ERROR : {
792                         printf ( "TFTP error %d (%s)\n",
793                                  ntohs(rcvd->u.err.errcode),
794                                  rcvd->u.err.errmsg );
795                         return (0); /* abort */
796                 }
797                 case TFTP_OACK : {
798                         const char *p = rcvd->u.oack.data;
799                         const char *e = p + recvlen - 10; /* "blksize\0\d\0" */
800
801                         *((char*)(p+recvlen-1)) = '\0'; /* Force final 0 */
802                         if ( blockidx || !request ) break; /* Too late */
803                         if ( recvlen <= TFTP_MAX_PACKET ) /* sanity */ {
804                                 /* Check for blksize option honoured */
805                                 while ( p < e ) {
806                                         if ( strcasecmp("blksize",p) == 0 &&
807                                              p[7] == '\0' ) {
808                                                 blksize = strtoul(p+8,&p,10);
809                                                 p++; /* skip null */
810                                         }
811                                         while ( *(p++) ) {};
812                                 }
813                         }
814                         if ( blksize < TFTP_DEFAULTSIZE_PACKET || blksize > request->blksize ) {
815                                 /* Incorrect blksize - error and abort */
816                                 xmit.opcode = htons(TFTP_ERROR);
817                                 xmit.u.err.errcode = 8;
818                                 xmitlen = (void*)&xmit.u.err.errmsg
819                                         - (void*)&xmit
820                                         + sprintf((char*)xmit.u.err.errmsg,
821                                                   "RFC1782 error")
822                                         + 1;
823                                 udp_transmit(
824                                     arptable[ARP_SERVER].ipaddr.s_addr,
825                                     lport, rport, xmitlen, &xmit);
826                                 return (0);
827                         }
828                 } break;
829                 case TFTP_DATA :
830                         if ( ntohs(rcvd->u.data.block) != ( blockidx + 1 ) )
831                                 break; /* Re-ACK last block sent */
832                         if ( recvlen > ( blksize+sizeof(rcvd->u.data.block) ) )
833                                 break; /* Too large; ignore */
834                         block->data = rcvd->u.data.download;
835                         block->block = ++blockidx;
836                         block->len = recvlen - sizeof(rcvd->u.data.block);
837                         block->eof = ( (unsigned short)block->len < blksize );
838                         /* If EOF, zero blksize to indicate transfer done */
839                         if ( block->eof ) blksize = 0;
840                         break;
841                 default: break; /* Do nothing */
842                 }
843                 /* Send ACK */
844                 xmit.opcode = htons(TFTP_ACK);
845                 xmit.u.ack.block = htons(blockidx);
846                 xmitlen = TFTP_MIN_PACKET;
847                 udp_transmit ( arptable[ARP_SERVER].ipaddr.s_addr,
848                                lport, rport, xmitlen, &xmit );
849         }
850         return ( block->data ? 1 : 0 );
851 }
852 #endif  /* DOWNLOAD_PROTO_TFTP */
853
854 #ifdef  USE_STATIC_BOOT_INFO
855 /***************************************************************************
856 get_static_boot_info - construct bootp response from supplied CFLAG values
857 ***************************************************************************/
858 static int get_static_boot_info (void)
859 {
860         in_addr client_addr, server_addr, gateway_addr, netmask_addr;
861
862         inet_aton( STATIC_CLIENT_IP, &client_addr );
863         memcpy ( &arptable[ARP_CLIENT].ipaddr, &client_addr.s_addr, sizeof(in_addr) );
864
865         inet_aton( STATIC_SERVER_IP, &server_addr );
866         memcpy( &arptable[ARP_SERVER].ipaddr, &server_addr.s_addr, sizeof(in_addr) );
867
868         inet_aton( STATIC_GATEWAY_IP, &gateway_addr );
869         memcpy( &arptable[ARP_GATEWAY].ipaddr, &gateway_addr.s_addr, sizeof(in_addr) );
870
871         inet_aton( STATIC_SUBNET_MASK, &netmask_addr );
872         netmask = ntohl( netmask_addr.s_addr );
873
874         bootp_data.bootp_reply.bp_op = BOOTP_REPLY;
875
876         return (1);
877 }
878 #endif
879 #ifdef  RARP_NOT_BOOTP
880
881 /**************************************************************************
882 RARP - Get my IP address and load information
883 **************************************************************************/
884 static int await_rarp(int ival, void *ptr,
885         unsigned short ptype, struct iphdr *ip, struct udphdr *udp,
886         struct tcphdr *tcp __unused)
887 {
888         struct arprequest *arpreply;
889         if (ptype != ETH_P_RARP)
890                 return 0;
891         if (nic.packetlen < ETH_HLEN + sizeof(struct arprequest))
892                 return 0;
893         arpreply = (struct arprequest *)&nic.packet[ETH_HLEN];
894         if (arpreply->opcode != htons(RARP_REPLY))
895                 return 0;
896         if ((arpreply->opcode == htons(RARP_REPLY)) &&
897                 (memcmp(arpreply->thwaddr, ptr, ETH_ALEN) == 0)) {
898                 memcpy(arptable[ARP_SERVER].node, arpreply->shwaddr, ETH_ALEN);
899                 memcpy(&arptable[ARP_SERVER].ipaddr, arpreply->sipaddr, sizeof(in_addr));
900                 memcpy(&arptable[ARP_CLIENT].ipaddr, arpreply->tipaddr, sizeof(in_addr));
901                 return 1;
902         }
903         return 0;
904 }
905
906 static int rarp(void)
907 {
908         int retry;
909
910         /* arp and rarp requests share the same packet structure. */
911         struct arprequest rarpreq;
912
913         memset(&rarpreq, 0, sizeof(rarpreq));
914
915         rarpreq.hwtype = htons(1);
916         rarpreq.protocol = htons(IP);
917         rarpreq.hwlen = ETH_ALEN;
918         rarpreq.protolen = 4;
919         rarpreq.opcode = htons(RARP_REQUEST);
920         memcpy(&rarpreq.shwaddr, arptable[ARP_CLIENT].node, ETH_ALEN);
921         /* sipaddr is already zeroed out */
922         memcpy(&rarpreq.thwaddr, arptable[ARP_CLIENT].node, ETH_ALEN);
923         /* tipaddr is already zeroed out */
924
925         for (retry = 0; retry < MAX_ARP_RETRIES; ++retry) {
926                 long timeout;
927                 eth_transmit(broadcast, ETH_P_RARP, sizeof(rarpreq), &rarpreq);
928
929                 timeout = rfc2131_sleep_interval(TIMEOUT, retry);
930                 if (await_reply(await_rarp, 0, rarpreq.shwaddr, timeout))
931                         break;
932         }
933
934         if (retry < MAX_ARP_RETRIES) {
935                 (void)sprintf(KERNEL_BUF, DEFAULT_KERNELPATH, arptable[ARP_CLIENT].ipaddr);
936
937                 return (1);
938         }
939         return (0);
940 }
941
942 #else
943
944 #ifdef PXE_DHCP_STRICT
945 /**************************************************************************
946 FIND_VCI_PXECLIENT - Looks for "PXEClient" Vendor Class Identifier
947 Upon entry p points after rfc1533_cookie.
948 **************************************************************************/
949 static int find_vci_pxeclient(unsigned char*p)
950 {
951         for (; *p != RFC1533_END; p += TAG_LEN(p) + 2)
952                 if (*p == RFC2132_VENDOR_CLASS_ID)
953                         if (memcmp(p + 2, "PXEClient", 9) == 0)
954                                 return 1;
955         return 0;
956 }
957 #endif
958
959 #ifndef USE_STATIC_BOOT_INFO
960 /**************************************************************************
961 BOOTP - Get my IP address and load information
962 **************************************************************************/
963 static int await_bootp(int ival __unused, void *ptr __unused,
964         unsigned short ptype __unused, struct iphdr *ip __unused, 
965         struct udphdr *udp, struct tcphdr *tcp __unused)
966 {
967         struct  bootp_t *bootpreply;
968         if (!udp) {
969                 return 0;
970         }
971         bootpreply = (struct bootp_t *)&nic.packet[ETH_HLEN + 
972                 sizeof(struct iphdr) + sizeof(struct udphdr)];
973         if (nic.packetlen < ETH_HLEN + sizeof(struct iphdr) + 
974                 sizeof(struct udphdr) + 
975 #ifdef NO_DHCP_SUPPORT
976                 sizeof(struct bootp_t)
977 #else
978                 sizeof(struct bootp_t) - DHCP_OPT_LEN
979 #endif  /* NO_DHCP_SUPPORT */
980                 ) {
981                 return 0;
982         }
983         if (udp->dest != htons(sport))
984                 return 0;
985         if (bootpreply->bp_op != BOOTP_REPLY)
986                 return 0;
987         if (bootpreply->bp_xid != xid)
988                 return 0;
989 #ifdef PXE_DHCP_STRICT
990         /* in principle one could check here:
991          *
992          * - DHCPACK
993          * - BOOT_ITEM
994          * - RFC2132_SRV_ID
995          * - UUID
996          */
997         if (sport == PXE_BOOT_CLIENT) {
998                 if (!find_vci_pxeclient(bootpreply->bp_vend + sizeof rfc1533_cookie)) {
999                         return 0;
1000                 }
1001                 /* we only solicited this packet for the options and the bp_file */
1002                 memcpy((char*)&bootp_data, (char*)bootpreply, sizeof(struct bootpd_t));
1003                 memcpy(KERNEL_BUF, bootpreply->bp_file, sizeof(KERNEL_BUF));
1004                 return 1;
1005         }                       
1006 #endif /* PXE_DHCP_STRICT */
1007         if (memcmp(&bootpreply->bp_siaddr, &zeroIP, sizeof(in_addr)) == 0)
1008                 return 0;
1009         if ((memcmp(broadcast, bootpreply->bp_hwaddr, ETH_ALEN) != 0) &&
1010                 (memcmp(arptable[ARP_CLIENT].node, bootpreply->bp_hwaddr, ETH_ALEN) != 0)) {
1011                 return 0;
1012         }
1013         if ( bootpreply->bp_siaddr.s_addr ) {
1014                 arptable[ARP_SERVER].ipaddr.s_addr = bootpreply->bp_siaddr.s_addr;
1015                 memset(arptable[ARP_SERVER].node, 0, ETH_ALEN);  /* Kill arp */
1016         }
1017         if ( bootpreply->bp_giaddr.s_addr ) {
1018                 arptable[ARP_GATEWAY].ipaddr.s_addr = bootpreply->bp_giaddr.s_addr;
1019                 memset(arptable[ARP_GATEWAY].node, 0, ETH_ALEN);  /* Kill arp */
1020         }
1021         if (bootpreply->bp_yiaddr.s_addr) {
1022                 /* Offer with an IP address */
1023                 arptable[ARP_CLIENT].ipaddr.s_addr = bootpreply->bp_yiaddr.s_addr;
1024 #ifndef NO_DHCP_SUPPORT
1025                 dhcp_addr.s_addr = bootpreply->bp_yiaddr.s_addr;
1026 #endif  /* !NO_DHCP_SUPPORT */
1027                 netmask = default_netmask();
1028                 /* bootpreply->bp_file will be copied to KERNEL_BUF in the memcpy */
1029                 memcpy((char *)&bootp_data, (char *)bootpreply, sizeof(struct bootpd_t));
1030                 decode_rfc1533(bootp_data.bootp_reply.bp_vend, 0,
1031 #ifdef  NO_DHCP_SUPPORT
1032                                BOOTP_VENDOR_LEN + MAX_BOOTP_EXTLEN, 
1033 #else
1034                                DHCP_OPT_LEN + MAX_BOOTP_EXTLEN, 
1035 #endif  /* NO_DHCP_SUPPORT */
1036                                1);
1037 #ifdef PXE_EXPORT
1038         } else {
1039                 /* Offer without an IP address - use as ProxyDHCP server */
1040                 arptable[ARP_PROXYDHCP].ipaddr.s_addr = bootpreply->bp_siaddr.s_addr;
1041                 memset(arptable[ARP_PROXYDHCP].node, 0, ETH_ALEN);       /* Kill arp */
1042                 /* Grab only the bootfile name from a ProxyDHCP packet */
1043                 memcpy(KERNEL_BUF, bootpreply->bp_file, sizeof(KERNEL_BUF));
1044 #endif /* PXE_EXPORT */
1045         }
1046 #ifdef  REQUIRE_VCI_ETHERBOOT
1047         if (!vci_etherboot)
1048                 return (0);
1049 #endif
1050         return(1);
1051 }
1052
1053 static int bootp(void)
1054 {
1055         int retry;
1056 #ifndef NO_DHCP_SUPPORT
1057         int reqretry;
1058 #endif  /* !NO_DHCP_SUPPORT */
1059         struct bootpip_t ip;
1060         unsigned long  starttime;
1061         unsigned char *bp_vend;
1062
1063 #ifndef NO_DHCP_SUPPORT
1064         dhcp_machine_info[4] = nic.dev.devid.bus_type;
1065         dhcp_machine_info[5] = nic.dev.devid.vendor_id & 0xff;
1066         dhcp_machine_info[6] = ((nic.dev.devid.vendor_id) >> 8) & 0xff;
1067         dhcp_machine_info[7] = nic.dev.devid.device_id & 0xff;
1068         dhcp_machine_info[8] = ((nic.dev.devid.device_id) >> 8) & 0xff;
1069 #endif  /* !NO_DHCP_SUPPORT */
1070         memset(&ip, 0, sizeof(struct bootpip_t));
1071         ip.bp.bp_op = BOOTP_REQUEST;
1072         ip.bp.bp_htype = 1;
1073         ip.bp.bp_hlen = ETH_ALEN;
1074         starttime = currticks();
1075         /* Use lower 32 bits of node address, more likely to be
1076            distinct than the time since booting */
1077         memcpy(&xid, &arptable[ARP_CLIENT].node[2], sizeof(xid));
1078         ip.bp.bp_xid = xid += htonl(starttime);
1079         memcpy(ip.bp.bp_hwaddr, arptable[ARP_CLIENT].node, ETH_ALEN);
1080 #ifdef  NO_DHCP_SUPPORT
1081         memcpy(ip.bp.bp_vend, rfc1533_cookie, 5); /* request RFC-style options */
1082 #else
1083         memcpy(ip.bp.bp_vend, rfc1533_cookie, sizeof rfc1533_cookie); /* request RFC-style options */
1084         memcpy(ip.bp.bp_vend + sizeof rfc1533_cookie, dhcpdiscover, sizeof dhcpdiscover);
1085         /* Append machine_info to end, in encapsulated option */
1086         bp_vend = ip.bp.bp_vend + sizeof rfc1533_cookie + sizeof dhcpdiscover;
1087         memcpy(bp_vend, dhcp_machine_info, DHCP_MACHINE_INFO_SIZE);
1088         bp_vend += DHCP_MACHINE_INFO_SIZE;
1089         *bp_vend++ = RFC1533_END;
1090 #endif  /* NO_DHCP_SUPPORT */
1091
1092         for (retry = 0; retry < MAX_BOOTP_RETRIES; ) {
1093                 uint8_t my_hwaddr[ETH_ALEN];
1094                 unsigned long stop_time;
1095                 long remaining_time;
1096
1097                 rx_qdrain();
1098
1099                 /* Kill arptable to avoid keeping stale entries */
1100                 memcpy ( my_hwaddr, arptable[ARP_CLIENT].node, ETH_ALEN );
1101                 memset ( arptable, 0, sizeof(arptable) );
1102                 memcpy ( arptable[ARP_CLIENT].node, my_hwaddr, ETH_ALEN );
1103
1104                 udp_transmit(IP_BROADCAST, BOOTP_CLIENT, BOOTP_SERVER,
1105                         sizeof(struct bootpip_t), &ip);
1106                 remaining_time = rfc2131_sleep_interval(BOOTP_TIMEOUT, retry++);
1107                 stop_time = currticks() + remaining_time;
1108 #ifdef PXE_DHCP_STRICT
1109                 num_boot_menu = 0;
1110 #endif /* PXE_DHCP_STRICT */
1111 #ifdef  NO_DHCP_SUPPORT
1112                 if (await_reply(await_bootp, 0, NULL, remaining_time))
1113                         return(1);
1114 #else
1115                 while ( remaining_time > 0 ) {
1116                         if (await_reply(await_bootp, 0, NULL, remaining_time)){
1117                                 if (arptable[ARP_CLIENT].ipaddr.s_addr)
1118                                         break;
1119                         }
1120                         remaining_time = stop_time - currticks();
1121                 }
1122                 if ( ! arptable[ARP_CLIENT].ipaddr.s_addr ) {
1123                         printf("No IP address\n");
1124                         continue;
1125                 }
1126                 /* If not a DHCPOFFER then must be just a BOOTP reply,
1127                  * be backward compatible with BOOTP then */
1128                 if (dhcp_reply != DHCPOFFER)
1129                         return(1);
1130                 dhcp_reply = 0;
1131                 /* Construct the DHCPREQUEST packet */
1132                 memcpy(ip.bp.bp_vend, rfc1533_cookie, sizeof rfc1533_cookie);
1133                 memcpy(ip.bp.bp_vend + sizeof rfc1533_cookie, dhcprequest, sizeof dhcprequest);
1134                 /* Beware: the magic numbers 9 and 15 depend on
1135                    the layout of dhcprequest */
1136                 memcpy(&ip.bp.bp_vend[9], &dhcp_server, sizeof(in_addr));
1137                 memcpy(&ip.bp.bp_vend[15], &dhcp_addr, sizeof(in_addr));
1138                 bp_vend = ip.bp.bp_vend + sizeof rfc1533_cookie + sizeof dhcprequest;
1139                 /* Append machine_info to end, in encapsulated option */
1140                 memcpy(bp_vend, dhcp_machine_info, DHCP_MACHINE_INFO_SIZE);
1141                 bp_vend += DHCP_MACHINE_INFO_SIZE;
1142                 *bp_vend++ = RFC1533_END;
1143                 for (reqretry = 0; reqretry < MAX_BOOTP_RETRIES; ) {
1144                         unsigned long timeout;
1145
1146                         udp_transmit(IP_BROADCAST, BOOTP_CLIENT, BOOTP_SERVER,
1147                                      sizeof(struct bootpip_t), &ip);
1148                         dhcp_reply=0;
1149                         timeout = rfc2131_sleep_interval(TIMEOUT, reqretry++);
1150                         if (!await_reply(await_bootp, 0, NULL, timeout))
1151                                 continue;
1152                         if (dhcp_reply != DHCPACK)
1153                                 continue;
1154                         dhcp_reply = 0;
1155 #ifdef PXE_EXPORT                       
1156                         if ( arptable[ARP_PROXYDHCP].ipaddr.s_addr ) {
1157 #ifdef PXE_DHCP_STRICT
1158                                 /* boot menu items must not be mixed from different servers */
1159                                 num_boot_menu = 0;
1160 #endif /* PXE_DHCP_STRICT */
1161                                 /* Construct the ProxyDHCPREQUEST packet */
1162                                 memcpy(ip.bp.bp_vend, rfc1533_cookie, sizeof rfc1533_cookie);
1163                                 memcpy(ip.bp.bp_vend + sizeof rfc1533_cookie, proxydhcprequest, sizeof proxydhcprequest);
1164                                 for (reqretry = 0; reqretry < MAX_BOOTP_RETRIES; ) {
1165                                         printf ( "\nSending ProxyDHCP request to %@...", arptable[ARP_PROXYDHCP].ipaddr.s_addr);
1166                                         udp_transmit(arptable[ARP_PROXYDHCP].ipaddr.s_addr, BOOTP_CLIENT, PROXYDHCP_SERVER,
1167                                                      sizeof(struct bootpip_t), &ip);
1168                                         timeout = rfc2131_sleep_interval(TIMEOUT, reqretry++);
1169                                         if (await_reply(await_bootp, 0, NULL, timeout)) {
1170                                                 break;
1171                                         }
1172                                 }
1173                         }
1174 #ifdef PXE_DHCP_STRICT
1175                         if (num_boot_menu) {
1176                                 int i;
1177                                 printf("\nreceived PXE boot menu:\n");
1178                                 for (i = 0; i < num_boot_menu; ++i) {
1179                                         printf("%d %s %@\n", pxe_boot_menu[i].id, pxe_boot_menu[i].text, pxe_boot_menu[i].ip.s_addr);
1180                                 }
1181                                 ip.bp.bp_siaddr.s_addr = zeroIP.s_addr;
1182                                 ip.bp.bp_yiaddr.s_addr = zeroIP.s_addr;
1183                                 ip.bp.bp_ciaddr.s_addr = arptable[ARP_CLIENT].ipaddr.s_addr;
1184                                 memcpy(ip.bp.bp_vend, rfc1533_cookie, sizeof rfc1533_cookie);
1185                                 bp_vend = ip.bp.bp_vend + sizeof rfc1533_cookie;
1186                                 /* for now simply select the first entry */
1187                                 *(uint16_t*)(pxedhcprequest + 7) = htons(pxe_boot_menu[0].id);
1188                                 memcpy(bp_vend, pxedhcprequest, sizeof pxedhcprequest);
1189                                 bp_vend += sizeof pxedhcprequest;
1190                                 *bp_vend = RFC1533_END;
1191                                 for (reqretry = 0; reqretry < MAX_BOOTP_RETRIES; ) {
1192                                         printf("\nselecting boot item [%s] ... ", pxe_boot_menu[0].text);
1193                                         arptable[ARP_SERVER].ipaddr.s_addr = pxe_boot_menu[0].ip.s_addr;
1194                                         memset(&arptable[ARP_SERVER].node, 0, ETH_ALEN);
1195                                         udp_transmit(pxe_boot_menu[0].ip.s_addr, PXE_BOOT_CLIENT,
1196                                                      PXE_BOOT_SERVER, sizeof(struct bootpip_t), &ip);
1197                                         timeout = rfc2131_sleep_interval(TIMEOUT, reqretry++);
1198                                         if (await_reply(await_bootp, 0, NULL, timeout)) {
1199                                                 break;
1200                                         }
1201                                 }
1202                         }
1203 #endif /* PXE_DHCP_STRICT */
1204 #endif /* PXE_EXPORT */
1205                         return(1);
1206                 }
1207 #endif  /* NO_DHCP_SUPPORT */
1208                 ip.bp.bp_secs = htons((currticks()-starttime)/TICKS_PER_SEC);
1209         }
1210         return(0);
1211 }
1212
1213 #endif /* USE_STATIC_BOOT_INFO */
1214
1215 #endif  /* RARP_NOT_BOOTP */
1216
1217 static uint16_t tcpudpchksum(struct iphdr *ip)
1218 {
1219         struct udp_pseudo_hdr pseudo;
1220         uint16_t checksum;
1221
1222         /* Compute the pseudo header */
1223         pseudo.src.s_addr  = ip->src.s_addr;
1224         pseudo.dest.s_addr = ip->dest.s_addr;
1225         pseudo.unused      = 0;
1226         pseudo.protocol    = ip->protocol;
1227         pseudo.len         = htons(ntohs(ip->len) - sizeof(struct iphdr));
1228
1229         /* Sum the pseudo header */
1230         checksum = ipchksum(&pseudo, 12);
1231
1232         /* Sum the rest of the tcp/udp packet */
1233         checksum = add_ipchksums(12, checksum, ipchksum(ip + 1,
1234                                  ntohs(ip->len) - sizeof(struct iphdr)));
1235         return checksum;
1236 }
1237
1238 #ifdef MULTICAST_LEVEL2
1239 static void send_igmp_reports(unsigned long now)
1240 {
1241         int i;
1242         for(i = 0; i < MAX_IGMP; i++) {
1243                 if (igmptable[i].time && (now >= igmptable[i].time)) {
1244                         struct igmp_ip_t igmp;
1245                         igmp.router_alert[0] = 0x94;
1246                         igmp.router_alert[1] = 0x04;
1247                         igmp.router_alert[2] = 0;
1248                         igmp.router_alert[3] = 0;
1249                         build_ip_hdr(igmptable[i].group.s_addr, 
1250                                 1, IP_IGMP, sizeof(igmp.router_alert), sizeof(igmp), &igmp);
1251                         igmp.igmp.type = IGMPv2_REPORT;
1252                         if (last_igmpv1 && 
1253                                 (now < last_igmpv1 + IGMPv1_ROUTER_PRESENT_TIMEOUT)) {
1254                                 igmp.igmp.type = IGMPv1_REPORT;
1255                         }
1256                         igmp.igmp.response_time = 0;
1257                         igmp.igmp.chksum = 0;
1258                         igmp.igmp.group.s_addr = igmptable[i].group.s_addr;
1259                         igmp.igmp.chksum = ipchksum(&igmp.igmp, sizeof(igmp.igmp));
1260                         ip_transmit(sizeof(igmp), &igmp);
1261 #ifdef  MDEBUG
1262                         printf("Sent IGMP report to: %@\n", igmp.igmp.group.s_addr);
1263 #endif
1264                         /* Don't send another igmp report until asked */
1265                         igmptable[i].time = 0;
1266                 }
1267         }
1268 }
1269
1270 static void process_igmp(struct iphdr *ip, unsigned long now)
1271 {
1272         struct igmp *igmp;
1273         int i;
1274         unsigned iplen;
1275         if (!ip || (ip->protocol == IP_IGMP) ||
1276                 (nic.packetlen < sizeof(struct iphdr) + sizeof(struct igmp))) {
1277                 return;
1278         }
1279         iplen = (ip->verhdrlen & 0xf)*4;
1280         igmp = (struct igmp *)&nic.packet[sizeof(struct iphdr)];
1281         if (ipchksum(igmp, ntohs(ip->len) - iplen) != 0)
1282                 return;
1283         if ((igmp->type == IGMP_QUERY) && 
1284                 (ip->dest.s_addr == htonl(GROUP_ALL_HOSTS))) {
1285                 unsigned long interval = IGMP_INTERVAL;
1286                 if (igmp->response_time == 0) {
1287                         last_igmpv1 = now;
1288                 } else {
1289                         interval = (igmp->response_time * TICKS_PER_SEC)/10;
1290                 }
1291                 
1292 #ifdef  MDEBUG
1293                 printf("Received IGMP query for: %@\n", igmp->group.s_addr);
1294 #endif                         
1295                 for(i = 0; i < MAX_IGMP; i++) {
1296                         uint32_t group = igmptable[i].group.s_addr;
1297                         if ((group == 0) || (group == igmp->group.s_addr)) {
1298                                 unsigned long time;
1299                                 time = currticks() + rfc1112_sleep_interval(interval, 0);
1300                                 if (time < igmptable[i].time) {
1301                                         igmptable[i].time = time;
1302                                 }
1303                         }
1304                 }
1305         }
1306         if (((igmp->type == IGMPv1_REPORT) || (igmp->type == IGMPv2_REPORT)) &&
1307                 (ip->dest.s_addr == igmp->group.s_addr)) {
1308 #ifdef  MDEBUG
1309                 printf("Received IGMP report for: %@\n", igmp->group.s_addr);
1310 #endif                         
1311                 for(i = 0; i < MAX_IGMP; i++) {
1312                         if ((igmptable[i].group.s_addr == igmp->group.s_addr) &&
1313                                 igmptable[i].time != 0) {
1314                                 igmptable[i].time = 0;
1315                         }
1316                 }
1317         }
1318 }
1319
1320 void leave_group(int slot)
1321 {
1322         /* Be very stupid and always send a leave group message if 
1323          * I have subscribed.  Imperfect but it is standards
1324          * compliant, easy and reliable to implement.
1325          *
1326          * The optimal group leave method is to only send leave when,
1327          * we were the last host to respond to a query on this group,
1328          * and igmpv1 compatibility is not enabled.
1329          */
1330         if (igmptable[slot].group.s_addr) {
1331                 struct igmp_ip_t igmp;
1332                 igmp.router_alert[0] = 0x94;
1333                 igmp.router_alert[1] = 0x04;
1334                 igmp.router_alert[2] = 0;
1335                 igmp.router_alert[3] = 0;
1336                 build_ip_hdr(htonl(GROUP_ALL_HOSTS),
1337                         1, IP_IGMP, sizeof(igmp.router_alert), sizeof(igmp), &igmp);
1338                 igmp.igmp.type = IGMP_LEAVE;
1339                 igmp.igmp.response_time = 0;
1340                 igmp.igmp.chksum = 0;
1341                 igmp.igmp.group.s_addr = igmptable[slot].group.s_addr;
1342                 igmp.igmp.chksum = ipchksum(&igmp.igmp, sizeof(igmp));
1343                 ip_transmit(sizeof(igmp), &igmp);
1344 #ifdef  MDEBUG
1345                 printf("Sent IGMP leave for: %@\n", igmp.igmp.group.s_addr);
1346 #endif  
1347         }
1348         memset(&igmptable[slot], 0, sizeof(igmptable[0]));
1349 }
1350
1351 void join_group(int slot, unsigned long group)
1352 {
1353         /* I have already joined */
1354         if (igmptable[slot].group.s_addr == group)
1355                 return;
1356         if (igmptable[slot].group.s_addr) {
1357                 leave_group(slot);
1358         }
1359         /* Only join a group if we are given a multicast ip, this way
1360          * code can be given a non-multicast (broadcast or unicast ip)
1361          * and still work... 
1362          */
1363         if ((group & htonl(MULTICAST_MASK)) == htonl(MULTICAST_NETWORK)) {
1364                 igmptable[slot].group.s_addr = group;
1365                 igmptable[slot].time = currticks();
1366         }
1367 }
1368 #else
1369 #define send_igmp_reports(now) do {} while(0)
1370 #define process_igmp(ip, now)  do {} while(0)
1371 #endif
1372
1373 #include "proto_eth_slow.c"
1374
1375 /**************************************************************************
1376 TCP - Simple-minded TCP stack. Can only send data once and then
1377       receive the response. The algorithm for computing window
1378       sizes and delaying ack's is currently broken, and thus
1379       disabled. Performance would probably improve a little, if
1380       this gets fixed. FIXME
1381 **************************************************************************/
1382 #ifdef DOWNLOAD_PROTO_HTTP
1383 static int await_tcp(int ival, void *ptr, unsigned short ptype __unused,
1384                     struct iphdr *ip, struct udphdr *udp __unused,
1385                     struct tcphdr *tcp)
1386 {
1387        if (!tcp) {
1388                return 0;
1389        }
1390        if (arptable[ARP_CLIENT].ipaddr.s_addr != ip->dest.s_addr)
1391                return 0;
1392        if (ntohs(tcp->dst) != ival) {
1393                tcp_reset(ip);
1394                return 0;
1395        }
1396        *(void **)ptr = tcp;
1397        return 1;
1398 }
1399
1400 int tcp_transaction(unsigned long destip, unsigned int destsock, void *ptr,
1401                    int (*send)(int len, void *buf, void *ptr),
1402                    int (*recv)(int len, const void *buf, void *ptr)) {
1403        static uint16_t srcsock = 0;
1404        int             rc = 1;
1405        long            send_seq = currticks();
1406        long            recv_seq = 0;
1407        int             can_send = 0;
1408        int             sent_all = 0;
1409        struct iphdr   *ip;
1410        struct tcphdr  *tcp;
1411        int             ctrl = SYN;
1412        char            buf[128]; /* Small outgoing buffer */
1413        long            payload;
1414        int             header_size;
1415        int             window = 3*TCP_MIN_WINDOW;
1416        long            last_ack = 0;
1417        long            last_sent = 0;
1418        long            rtt = 0;
1419        long            srtt = 0;
1420        long            rto = TCP_INITIAL_TIMEOUT;
1421        int             retry = TCP_MAX_TIMEOUT/TCP_INITIAL_TIMEOUT;
1422        enum { CLOSED, SYN_RCVD, ESTABLISHED,
1423               FIN_WAIT_1, FIN_WAIT_2 } state = CLOSED;
1424
1425        if (!srcsock) {
1426                srcsock = currticks();
1427        }
1428        if (++srcsock < 1024)
1429                srcsock += 1024;
1430
1431        await_reply(await_qdrain, 0, NULL, 0);
1432
1433  send_data:
1434        if (ctrl & ACK)
1435                last_ack = recv_seq;
1436        if (!tcp_transmit(destip, srcsock, destsock, send_seq,
1437                          recv_seq, window, ctrl,
1438                          sizeof(struct iphdr) + sizeof(struct tcphdr)+
1439                          can_send, buf)) {
1440                return (0);
1441        }
1442        last_sent = currticks();
1443
1444  recv_data:
1445        if (!await_reply(await_tcp, srcsock, &tcp,
1446                         (state == ESTABLISHED && !can_send)
1447                         ? TCP_MAX_TIMEOUT : rto)) {
1448                if (state == ESTABLISHED) {
1449  close:
1450                        ctrl = FIN|ACK;
1451                        state = FIN_WAIT_1;
1452                        rc = 0;
1453                        goto send_data;
1454                }
1455
1456                if (state == FIN_WAIT_1 || state == FIN_WAIT_2)
1457                        return (rc);
1458
1459                if (--retry <= 0) {
1460                        /* time out */
1461                        if (state == SYN_RCVD) {
1462                                tcp_transmit(destip, srcsock, destsock,
1463                                             send_seq, 0, window, RST,
1464                                             sizeof(struct iphdr) +
1465                                             sizeof(struct tcphdr), buf);
1466                        }
1467                        return (0);
1468                }
1469                /* retransmit */
1470                goto send_data;
1471        }
1472  got_data:
1473        retry = TCP_MAX_RETRY;
1474
1475        if (tcp->ctrl & htons(ACK) ) {
1476                char *data;
1477                int syn_ack, consumed;
1478
1479                if (state == FIN_WAIT_1 || state == FIN_WAIT_2) {
1480                        state = FIN_WAIT_2;
1481                        ctrl = ACK;
1482                        goto consume_data;
1483                }
1484                syn_ack = state == CLOSED || state == SYN_RCVD;
1485                consumed = ntohl(tcp->ack) - send_seq - syn_ack;
1486                if (consumed < 0 || consumed > can_send) {
1487                        tcp_reset((struct iphdr *)&nic.packet[ETH_HLEN]);
1488                        goto recv_data;
1489                }
1490
1491                rtt = currticks() - last_sent;
1492                srtt = !srtt ? rtt : (srtt*4 + rtt)/5;
1493                rto = srtt + srtt/2;
1494                if (rto < TCP_MIN_TIMEOUT)
1495                        rto = TCP_MIN_TIMEOUT;
1496                else if (rto > TCP_MAX_TIMEOUT)
1497                        rto = TCP_MAX_TIMEOUT;
1498
1499                can_send -= consumed;
1500                send_seq += consumed + syn_ack;
1501                data = buf + sizeof(struct iphdr) + sizeof(struct tcphdr);
1502                if (can_send) {
1503                        memmove(data, data + consumed, can_send);
1504                }
1505                if (!sent_all) {
1506                        int more_data;
1507                        data += can_send;
1508                        more_data = buf + sizeof(buf) - data;
1509                        if (more_data > 0) {
1510                                more_data = send(more_data, data, ptr);
1511                                can_send += more_data;
1512                        }
1513                        sent_all = !more_data;
1514                }
1515                if (state == SYN_RCVD) {
1516                        state = ESTABLISHED;
1517                        ctrl = PSH|ACK;
1518                        goto consume_data;
1519                }
1520                if (tcp->ctrl & htons(RST))
1521                        return (0);
1522        } else if (tcp->ctrl & htons(RST)) {
1523                if (state == CLOSED)
1524                        goto recv_data;
1525                return (0);
1526        }
1527
1528  consume_data:
1529        ip  = (struct iphdr *)&nic.packet[ETH_HLEN];
1530        header_size = sizeof(struct iphdr) + ((ntohs(tcp->ctrl)>>10)&0x3C);
1531        payload = ntohs(ip->len) - header_size;
1532        if (payload > 0 && state == ESTABLISHED) {
1533                int old_bytes = recv_seq - (long)ntohl(tcp->seq);
1534                if (old_bytes >= 0 && payload - old_bytes > 0) {
1535                        recv_seq += payload - old_bytes;
1536                        if (state != FIN_WAIT_1 && state != FIN_WAIT_2 &&
1537                            !recv(payload - old_bytes,
1538                                  &nic.packet[ETH_HLEN+header_size+old_bytes],
1539                                  ptr)) {
1540                                goto close;
1541                        }
1542                        if ((state == ESTABLISHED || state == SYN_RCVD) &&
1543                            !(tcp->ctrl & htons(FIN))) {
1544                                int in_window = window - 2*TCP_MIN_WINDOW >
1545                                                 recv_seq - last_ack;
1546                                ctrl = can_send ? PSH|ACK : ACK;
1547                                if (!can_send && in_window) {
1548 /* Window scaling is broken right now, just fall back to acknowledging every */
1549 /* packet immediately and unconditionally. FIXME                       */ /***/
1550 /*                                     if (await_reply(await_tcp, srcsock,
1551                                                        &tcp, rto))
1552                                                goto got_data;
1553                                        else */
1554                                                goto send_data;
1555                                }
1556                                if (!in_window) {
1557                                        window += TCP_MIN_WINDOW;
1558                                        if (window > TCP_MAX_WINDOW)
1559                                                window = TCP_MAX_WINDOW;
1560                                }
1561                                goto send_data;
1562                        }
1563                } else {
1564                        /* saw old data again, must have lost packets */
1565                        window /= 2;
1566                        if (window < 2*TCP_MIN_WINDOW)
1567                                window = 2*TCP_MIN_WINDOW;
1568                }
1569        }
1570
1571        if (tcp->ctrl & htons(FIN)) {
1572                if (state == ESTABLISHED) {
1573                        ctrl = FIN|ACK;
1574                } else if (state == FIN_WAIT_1 || state == FIN_WAIT_2) {
1575                        ctrl = ACK;
1576                } else {
1577                        ctrl = RST;
1578                }
1579                return (tcp_transmit(destip, srcsock, destsock,
1580                                     send_seq, recv_seq + 1, window, ctrl,
1581                                     sizeof(struct iphdr) +
1582                                     sizeof(struct tcphdr), buf) &&
1583                        (state == ESTABLISHED ||
1584                         state == FIN_WAIT_1 || state == FIN_WAIT_2) &&
1585                        !can_send);
1586        }
1587
1588        if (state == CLOSED) {
1589                if (tcp->ctrl & htons(SYN)) {
1590                        recv_seq = ntohl(tcp->seq) + 1;
1591                        if (!(tcp->ctrl & htons(ACK))) {
1592                                state = SYN_RCVD;
1593                                ctrl = SYN|ACK|PSH;
1594                                goto send_data;
1595                        } else {
1596                                state = ESTABLISHED;
1597                                ctrl = PSH|ACK;
1598                        }
1599                }
1600        }
1601
1602        if (can_send || payload) {
1603                goto send_data;
1604        }
1605        goto recv_data;
1606 }
1607 #endif
1608
1609 /**************************************************************************
1610 AWAIT_REPLY - Wait until we get a response for our request
1611 ************f**************************************************************/
1612 int await_reply(reply_t reply, int ival, void *ptr, long timeout)
1613 {
1614         unsigned long time, now;
1615         struct  iphdr *ip;
1616         unsigned iplen = 0;
1617         struct  udphdr *udp;
1618         struct  tcphdr *tcp;
1619         unsigned short ptype;
1620         int result;
1621
1622         time = timeout + currticks();
1623         /* The timeout check is done below.  The timeout is only checked if
1624          * there is no packet in the Rx queue.  This assumes that eth_poll()
1625          * needs a negligible amount of time.  
1626          */
1627         for (;;) {
1628                 now = currticks();
1629                 send_eth_slow_reports(now);
1630                 send_igmp_reports(now);
1631                 result = eth_poll(1);
1632                 if (result == 0) {
1633                         /* We don't have anything */
1634                 
1635                         /* Check for abort key only if the Rx queue is empty -
1636                          * as long as we have something to process, don't
1637                          * assume that something failed.  It is unlikely that
1638                          * we have no processing time left between packets.  */
1639                         poll_interruptions();
1640                         /* Do the timeout after at least a full queue walk.  */
1641                         if ((timeout == 0) || (currticks() > time)) {
1642                                 break;
1643                         }
1644                         continue;
1645                 }
1646         
1647                 /* We have something! */
1648
1649                 /* Find the Ethernet packet type */
1650                 if (nic.packetlen >= ETH_HLEN) {
1651                         ptype = ((unsigned short) nic.packet[12]) << 8
1652                                 | ((unsigned short) nic.packet[13]);
1653                 } else continue; /* what else could we do with it? */
1654                 /* Verify an IP header */
1655                 ip = 0;
1656                 if ((ptype == ETH_P_IP) && (nic.packetlen >= ETH_HLEN + sizeof(struct iphdr))) {
1657                         unsigned ipoptlen;
1658                         ip = (struct iphdr *)&nic.packet[ETH_HLEN];
1659                         if ((ip->verhdrlen < 0x45) || (ip->verhdrlen > 0x4F)) 
1660                                 continue;
1661                         iplen = (ip->verhdrlen & 0xf) * 4;
1662                         if (ipchksum(ip, iplen) != 0)
1663                                 continue;
1664                         if (ip->frags & htons(0x3FFF)) {
1665                                 static int warned_fragmentation = 0;
1666                                 if (!warned_fragmentation) {
1667                                         printf("ALERT: got a fragmented packet - reconfigure your server\n");
1668                                         warned_fragmentation = 1;
1669                                 }
1670                                 continue;
1671                         }
1672                         if (ntohs(ip->len) > ETH_MAX_MTU)
1673                                 continue;
1674
1675                         ipoptlen = iplen - sizeof(struct iphdr);
1676                         if (ipoptlen) {
1677                                 /* Delete the ip options, to guarantee
1678                                  * good alignment, and make etherboot simpler.
1679                                  */
1680                                 memmove(&nic.packet[ETH_HLEN + sizeof(struct iphdr)], 
1681                                         &nic.packet[ETH_HLEN + iplen],
1682                                         nic.packetlen - ipoptlen);
1683                                 nic.packetlen -= ipoptlen;
1684                         }
1685                 }
1686                 udp = 0;
1687                 if (ip && (ip->protocol == IP_UDP) && 
1688                         (nic.packetlen >= 
1689                         ETH_HLEN + sizeof(struct iphdr) + sizeof(struct udphdr))) {
1690                         udp = (struct udphdr *)&nic.packet[ETH_HLEN + sizeof(struct iphdr)];
1691
1692                         /* Make certain we have a reasonable packet length */
1693                         if (ntohs(udp->len) > (ntohs(ip->len) - iplen))
1694                                 continue;
1695
1696                         if (udp->chksum && tcpudpchksum(ip)) {
1697                                 printf("UDP checksum error\n");
1698                                 continue;
1699                         }
1700                 }
1701                 tcp = 0;
1702 #ifdef DOWNLOAD_PROTO_HTTP
1703                 if (ip && (ip->protocol == IP_TCP) &&
1704                     (nic.packetlen >=
1705                      ETH_HLEN + sizeof(struct iphdr) + sizeof(struct tcphdr))){
1706                         tcp = (struct tcphdr *)&nic.packet[ETH_HLEN +
1707                                                          sizeof(struct iphdr)];
1708                         /* Make certain we have a reasonable packet length */
1709                         if (((ntohs(tcp->ctrl) >> 10) & 0x3C) >
1710                             ntohs(ip->len) - (int)iplen)
1711                                 continue;
1712                         if (tcpudpchksum(ip)) {
1713                                 printf("TCP checksum error\n");
1714                                 continue;
1715                         }
1716
1717                 }
1718 #endif
1719                 result = reply(ival, ptr, ptype, ip, udp, tcp);
1720                 if (result > 0) {
1721                         return result;
1722                 }
1723                 
1724                 /* If it isn't a packet the upper layer wants see if there is a default
1725                  * action.  This allows us reply to arp, igmp, and lacp queries.
1726                  */
1727                 if ((ptype == ETH_P_ARP) &&
1728                         (nic.packetlen >= ETH_HLEN + sizeof(struct arprequest))) {
1729                         struct  arprequest *arpreply;
1730                         unsigned long tmp;
1731                 
1732                         arpreply = (struct arprequest *)&nic.packet[ETH_HLEN];
1733                         memcpy(&tmp, arpreply->tipaddr, sizeof(in_addr));
1734                         if ((arpreply->opcode == htons(ARP_REQUEST)) &&
1735                                 (tmp == arptable[ARP_CLIENT].ipaddr.s_addr)) {
1736                                 arpreply->opcode = htons(ARP_REPLY);
1737                                 memcpy(arpreply->tipaddr, arpreply->sipaddr, sizeof(in_addr));
1738                                 memcpy(arpreply->thwaddr, arpreply->shwaddr, ETH_ALEN);
1739                                 memcpy(arpreply->sipaddr, &arptable[ARP_CLIENT].ipaddr, sizeof(in_addr));
1740                                 memcpy(arpreply->shwaddr, arptable[ARP_CLIENT].node, ETH_ALEN);
1741                                 eth_transmit(arpreply->thwaddr, ETH_P_ARP,
1742                                         sizeof(struct  arprequest),
1743                                         arpreply);
1744 #ifdef  MDEBUG
1745                                 memcpy(&tmp, arpreply->tipaddr, sizeof(in_addr));
1746                                 printf("Sent ARP reply to: %@\n",tmp);
1747 #endif  /* MDEBUG */
1748                         }
1749                 }
1750                 process_eth_slow(ptype, now);
1751                 process_igmp(ip, now);
1752         }
1753         return(0);
1754 }
1755
1756 #ifdef  REQUIRE_VCI_ETHERBOOT
1757 /**************************************************************************
1758 FIND_VCI_ETHERBOOT - Looks for "Etherboot" in Vendor Encapsulated Identifiers
1759 On entry p points to byte count of VCI options
1760 **************************************************************************/
1761 static int find_vci_etherboot(unsigned char *p)
1762 {
1763         unsigned char   *end = p + 1 + *p;
1764
1765         for (p++; p < end; ) {
1766                 if (*p == RFC2132_VENDOR_CLASS_ID) {
1767                         if (strncmp("Etherboot", p + 2, sizeof("Etherboot") - 1) == 0)
1768                                 return (1);
1769                 } else if (*p == RFC1533_END)
1770                         return (0);
1771                 p += TAG_LEN(p) + 2;
1772         }
1773         return (0);
1774 }
1775 #endif  /* REQUIRE_VCI_ETHERBOOT */
1776
1777 #ifdef PXE_DHCP_STRICT
1778 /**************************************************************************
1779 DECODE_PXE_BOOT_SERVERS - Decodes the IP addresses of boot servers
1780 **************************************************************************/
1781 static void decode_pxe_boot_servers(unsigned char*p)
1782 {
1783         unsigned short item = ntohs(*(unsigned short*)p);
1784         unsigned char i;
1785
1786         for (i = 0; i < num_boot_menu; ++i) {
1787                 if (pxe_boot_menu[i].id == item)
1788                         break;
1789         }
1790         if (i == MAX_BOOT_MENU) return;
1791         if (i == num_boot_menu) {
1792                 ++num_boot_menu;
1793                 pxe_boot_menu[i].id = item;
1794         }
1795         memcpy(&pxe_boot_menu[i].ip, p + 3, sizeof(in_addr));
1796 }
1797
1798 /**************************************************************************
1799 DECODE_PXE_BOOT_MENU - Decodes the boot menu items
1800 **************************************************************************/
1801 static void decode_pxe_boot_menu(unsigned char*p)
1802 {
1803         unsigned short item = ntohs(*(unsigned short*)p);
1804         unsigned char i, size;
1805
1806         for (i = 0; i < num_boot_menu; ++i) {
1807                 if (pxe_boot_menu[i].id == item)
1808                         break;
1809         }
1810         if (i == MAX_BOOT_MENU) return;
1811         if (i == num_boot_menu) {
1812                 ++num_boot_menu;
1813                 pxe_boot_menu[i].id = item;
1814         }
1815         memset(pxe_boot_menu[i].text, 0, sizeof(pxe_boot_menu[i].text));
1816         size = p[2];
1817         if (size > MAX_BOOT_ENTRY_LENGTH)
1818                 size = MAX_BOOT_ENTRY_LENGTH;
1819         memcpy(pxe_boot_menu[i].text, p + 3, size);
1820 }
1821 #endif /* PXE_DHCP_STRICT */
1822
1823 #if 0
1824 static void dump(unsigned char*p, unsigned char len)
1825 {
1826         unsigned char*end = p+len;
1827         printf("\n");
1828         while (p<end) {
1829                 printf("%hhX ",*p);
1830                 ++p;
1831         }
1832 }
1833 #endif
1834
1835 /**************************************************************************
1836 DECODE_RFC1533 - Decodes RFC1533 header
1837 **************************************************************************/
1838 int decode_rfc1533(unsigned char *p, unsigned int block, unsigned int len, int eof)
1839 {
1840         static unsigned char *extdata = NULL, *extend = NULL;
1841         unsigned char        *extpath = NULL;
1842         unsigned char        *endp;
1843         static unsigned char in_encapsulated_options = 0;
1844 #ifdef PXE_DHCP_STRICT
1845         static unsigned char in_pxe_encapsulated_options = 0;
1846         unsigned char        pxeclient;
1847 #endif
1848
1849         if (eof == -1) {
1850                 /* Encapsulated option block */
1851                 endp = p + len;
1852         }
1853         else if (block == 0) {
1854 #ifdef  REQUIRE_VCI_ETHERBOOT
1855                 vci_etherboot = 0;
1856 #endif
1857                 end_of_rfc1533 = NULL;
1858 #ifdef  IMAGE_FREEBSD
1859                 /* yes this is a pain FreeBSD uses this for swap, however,
1860                    there are cases when you don't want swap and then
1861                    you want this set to get the extra features so lets
1862                    just set if dealing with FreeBSD.  I haven't run into
1863                    any troubles with this but I have without it
1864                 */
1865                 vendorext_isvalid = 1;
1866 #ifdef FREEBSD_KERNEL_ENV
1867                 memcpy(freebsd_kernel_env, FREEBSD_KERNEL_ENV,
1868                        sizeof(FREEBSD_KERNEL_ENV));
1869                 /* FREEBSD_KERNEL_ENV had better be a string constant */
1870 #else
1871                 freebsd_kernel_env[0]='\0';
1872 #endif
1873 #else
1874                 vendorext_isvalid = 0;
1875 #endif
1876                 addparam = NULL;
1877                 addparamlen = 0;
1878                 if (memcmp(p, rfc1533_cookie, 4))
1879                         return(0); /* no RFC 1533 header found */
1880                 p += 4;
1881                 endp = p + len;
1882         } else {
1883                 if (block == 1) {
1884                         if (memcmp(p, rfc1533_cookie, 4))
1885                                 return(0); /* no RFC 1533 header found */
1886                         p += 4;
1887                         len -= 4; }
1888                 if (extend + len <= (unsigned char *)&(bootp_data.bootp_extension[MAX_BOOTP_EXTLEN])) {
1889                         memcpy(extend, p, len);
1890                         extend += len;
1891                 } else {
1892                         printf("Overflow in vendor data buffer! Aborting...\n");
1893                         *extdata = RFC1533_END;
1894                         return(0);
1895                 }
1896                 p = extdata; endp = extend;
1897         }
1898         if (!eof)
1899                 return 1;
1900 #ifdef PXE_DHCP_STRICT
1901         pxeclient = find_vci_pxeclient(p);
1902 #endif
1903         while (p < endp) {
1904                 unsigned char c = *p;
1905                 if (c == RFC1533_PAD) {
1906                         p++;
1907                         continue;
1908                 }
1909                 else if (c == RFC1533_END) {
1910                         end_of_rfc1533 = endp = p;
1911                         continue;
1912                 }
1913                 else if (NON_ENCAP_OPT c == RFC1533_NETMASK)
1914                         memcpy(&netmask, p+2, sizeof(in_addr));
1915                 else if (NON_ENCAP_OPT c == RFC1533_GATEWAY) {
1916                         /* This is a little simplistic, but it will
1917                            usually be sufficient.
1918                            Take only the first entry */
1919                         if (TAG_LEN(p) >= sizeof(in_addr))
1920                                 memcpy(&arptable[ARP_GATEWAY].ipaddr, p+2, sizeof(in_addr));
1921                 }
1922                 else if (c == RFC1533_EXTENSIONPATH)
1923                         extpath = p;
1924 #ifndef NO_DHCP_SUPPORT
1925 #ifdef  REQUIRE_VCI_ETHERBOOT
1926                 else if (NON_ENCAP_OPT c == RFC1533_VENDOR) {
1927                         vci_etherboot = find_vci_etherboot(p+1);
1928 #ifdef  MDEBUG
1929                         printf("vci_etherboot %d\n", vci_etherboot);
1930 #endif
1931                 }
1932 #endif  /* REQUIRE_VCI_ETHERBOOT */
1933                 else if (NON_ENCAP_OPT c == RFC2132_MSG_TYPE)
1934                         dhcp_reply=*(p+2);
1935                 else if (NON_ENCAP_OPT c == RFC2132_SRV_ID)
1936                         memcpy(&dhcp_server, p+2, sizeof(in_addr));
1937 #endif  /* !NO_DHCP_SUPPORT */
1938                 else if (NON_ENCAP_OPT c == RFC1533_HOSTNAME) {
1939                         hostname = p + 2;
1940                         hostnamelen = *(p + 1);
1941                 }
1942 #ifdef PXE_DHCP_STRICT
1943                 else if (PXE_ENCAP_OPT c == PXE_BOOT_SERVERS) {
1944                         unsigned char *q = p + 2;
1945                         unsigned char *end = q + TAG_LEN(p);
1946                         while (q < end) {
1947                                 decode_pxe_boot_servers(q);
1948                                 q += q[2] * 4 + 3;
1949                         }
1950                 }
1951                 else if (PXE_ENCAP_OPT c == PXE_BOOT_MENU) {
1952                         unsigned char *q = p + 2;
1953                         unsigned char *end = q + TAG_LEN(p);
1954                         while (q < end) {
1955                                 decode_pxe_boot_menu(q);
1956                                 q += q[2] + 3;
1957                         }
1958                 }
1959                 else if (NON_ENCAP_OPT c == RFC1533_VENDOR && pxeclient) {
1960                         in_pxe_encapsulated_options = 1;
1961                         decode_rfc1533(p+2, 0, TAG_LEN(p), -1);
1962                         in_pxe_encapsulated_options = 0;
1963                 }
1964 #endif /* PXE_DHCP_STRICT */
1965                 else if (ENCAP_OPT c == RFC1533_VENDOR_MAGIC
1966                          && TAG_LEN(p) >= 6 &&
1967                           !memcmp(p+2,vendorext_magic,4) &&
1968                           p[6] == RFC1533_VENDOR_MAJOR
1969                         )
1970                         vendorext_isvalid++;
1971                 else if (c == RFC1533_VENDOR_ADDPARM) {
1972                         /* This tag intentionally works for BOTH the encapsulated and
1973                          * non-encapsulated case, since the current menu code (in mknbi)
1974                          * creates this tag without encapsulation.  In the future both the
1975                          * menu from mknbi and this code should learn about the proper
1976                          * encapsulation (which will require substantial changes to various
1977                          * stuff from mknbi, which will break compatibility with older
1978                          * versions of Etherboot).  */
1979                         addparam = p + 2;
1980                         addparamlen = *(p + 1);
1981                 }
1982                 else if (NON_ENCAP_OPT c == RFC1533_VENDOR_ETHERBOOT_ENCAP) {
1983                         in_encapsulated_options = 1;
1984                         decode_rfc1533(p+2, 0, TAG_LEN(p), -1);
1985                         in_encapsulated_options = 0;
1986                 }
1987 #ifdef  IMAGE_FREEBSD
1988                 else if (NON_ENCAP_OPT c == RFC1533_VENDOR_HOWTO)
1989                         freebsd_howto = ((p[2]*256+p[3])*256+p[4])*256+p[5];
1990                 else if (NON_ENCAP_OPT c == RFC1533_VENDOR_KERNEL_ENV){
1991                         if(*(p + 1) < sizeof(freebsd_kernel_env)){
1992                                 memcpy(freebsd_kernel_env,p+2,*(p+1));
1993                         }else{
1994                                 printf("Only support %ld bytes in Kernel Env\n",
1995                                         sizeof(freebsd_kernel_env));
1996                         }
1997                 }
1998 #endif
1999 #ifdef  DNS_RESOLVER
2000                 else if (NON_ENCAP_OPT c == RFC1533_DNS) {
2001                         // TODO: Copy the DNS IP somewhere reasonable
2002                         if (TAG_LEN(p) >= sizeof(in_addr))
2003                                 memcpy(&arptable[ARP_NAMESERVER].ipaddr, p+2, sizeof(in_addr));
2004                 }
2005 #endif
2006                 else {
2007 #if 0
2008                         unsigned char *q;
2009                         printf("Unknown RFC1533-tag ");
2010                         for(q=p;q<p+2+TAG_LEN(p);q++)
2011                                 printf("%hhX ",*q);
2012                         putchar('\n');
2013 #endif
2014                 }
2015                 p += TAG_LEN(p) + 2;
2016         }
2017         extdata = extend = endp;
2018         if (block <= 0 && extpath != NULL) {
2019                 char fname[64];
2020                 memcpy(fname, extpath+2, TAG_LEN(extpath));
2021                 fname[(int)TAG_LEN(extpath)] = '\0';
2022                 printf("Loading BOOTP-extension file: %s\n",fname);
2023                 tftp(fname, decode_rfc1533);
2024         }
2025         return 1;       /* proceed with next block */
2026 }
2027
2028
2029 /* FIXME double check TWO_SECOND_DIVISOR */
2030 #define TWO_SECOND_DIVISOR (RAND_MAX/TICKS_PER_SEC)
2031 /**************************************************************************
2032 RFC2131_SLEEP_INTERVAL - sleep for expotentially longer times (base << exp) +- 1 sec)
2033 **************************************************************************/
2034 long rfc2131_sleep_interval(long base, int exp)
2035 {
2036         unsigned long tmo;
2037 #ifdef BACKOFF_LIMIT
2038         if (exp > BACKOFF_LIMIT)
2039                 exp = BACKOFF_LIMIT;
2040 #endif
2041         tmo = (base << exp) + (TICKS_PER_SEC - (random()/TWO_SECOND_DIVISOR));
2042         return tmo;
2043 }
2044
2045 #ifdef MULTICAST_LEVEL2
2046 /**************************************************************************
2047 RFC1112_SLEEP_INTERVAL - sleep for expotentially longer times, up to (base << exp)
2048 **************************************************************************/
2049 long rfc1112_sleep_interval(long base, int exp)
2050 {
2051         unsigned long divisor, tmo;
2052 #ifdef BACKOFF_LIMIT
2053         if (exp > BACKOFF_LIMIT)
2054                 exp = BACKOFF_LIMIT;
2055 #endif
2056         divisor = RAND_MAX/(base << exp);
2057         tmo = random()/divisor;
2058         return tmo;
2059 }
2060 #endif /* MULTICAST_LEVEL_2 */