Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / src / net / udp / dhcp.c
1 /*
2  * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  */
19
20 FILE_LICENCE ( GPL2_OR_LATER );
21
22 #include <string.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <byteswap.h>
29 #include <ipxe/if_ether.h>
30 #include <ipxe/iobuf.h>
31 #include <ipxe/netdevice.h>
32 #include <ipxe/device.h>
33 #include <ipxe/xfer.h>
34 #include <ipxe/open.h>
35 #include <ipxe/job.h>
36 #include <ipxe/retry.h>
37 #include <ipxe/tcpip.h>
38 #include <ipxe/ip.h>
39 #include <ipxe/uuid.h>
40 #include <ipxe/timer.h>
41 #include <ipxe/settings.h>
42 #include <ipxe/dhcp.h>
43 #include <ipxe/dhcpopts.h>
44 #include <ipxe/dhcppkt.h>
45 #include <ipxe/dhcp_arch.h>
46 #include <ipxe/features.h>
47
48 /** @file
49  *
50  * Dynamic Host Configuration Protocol
51  *
52  */
53
54 struct dhcp_session;
55 static int dhcp_tx ( struct dhcp_session *dhcp );
56
57 /**
58  * DHCP operation types
59  *
60  * This table maps from DHCP message types (i.e. values of the @c
61  * DHCP_MESSAGE_TYPE option) to values of the "op" field within a DHCP
62  * packet.
63  */
64 static const uint8_t dhcp_op[] = {
65         [DHCPDISCOVER]  = BOOTP_REQUEST,
66         [DHCPOFFER]     = BOOTP_REPLY,
67         [DHCPREQUEST]   = BOOTP_REQUEST,
68         [DHCPDECLINE]   = BOOTP_REQUEST,
69         [DHCPACK]       = BOOTP_REPLY,
70         [DHCPNAK]       = BOOTP_REPLY,
71         [DHCPRELEASE]   = BOOTP_REQUEST,
72         [DHCPINFORM]    = BOOTP_REQUEST,
73 };
74
75 /** Raw option data for options common to all DHCP requests */
76 static uint8_t dhcp_request_options_data[] = {
77         DHCP_MESSAGE_TYPE, DHCP_BYTE ( 0 ),
78         DHCP_MAX_MESSAGE_SIZE,
79         DHCP_WORD ( ETH_MAX_MTU - 20 /* IP header */ - 8 /* UDP header */ ),
80         DHCP_CLIENT_ARCHITECTURE, DHCP_ARCH_CLIENT_ARCHITECTURE,
81         DHCP_CLIENT_NDI, DHCP_ARCH_CLIENT_NDI,
82         DHCP_VENDOR_CLASS_ID, DHCP_ARCH_VENDOR_CLASS_ID,
83         DHCP_USER_CLASS_ID, DHCP_STRING ( 'i', 'P', 'X', 'E' ),
84         DHCP_PARAMETER_REQUEST_LIST,
85         DHCP_OPTION ( DHCP_SUBNET_MASK, DHCP_ROUTERS, DHCP_DNS_SERVERS,
86                       DHCP_LOG_SERVERS, DHCP_HOST_NAME, DHCP_DOMAIN_NAME,
87                       DHCP_ROOT_PATH, DHCP_VENDOR_ENCAP, DHCP_VENDOR_CLASS_ID,
88                       DHCP_TFTP_SERVER_NAME, DHCP_BOOTFILE_NAME,
89                       DHCP_DOMAIN_SEARCH,
90                       128, 129, 130, 131, 132, 133, 134, 135, /* for PXE */
91                       DHCP_EB_ENCAP, DHCP_ISCSI_INITIATOR_IQN ),
92         DHCP_END
93 };
94
95 /** DHCP server address setting */
96 const struct setting dhcp_server_setting __setting ( SETTING_MISC,
97                                                      dhcp-server ) = {
98         .name = "dhcp-server",
99         .description = "DHCP server",
100         .tag = DHCP_SERVER_IDENTIFIER,
101         .type = &setting_type_ipv4,
102 };
103
104 /**
105  * Most recent DHCP transaction ID
106  *
107  * This is exposed for use by the fakedhcp code when reconstructing
108  * DHCP packets for PXE NBPs.
109  */
110 uint32_t dhcp_last_xid;
111
112 /**
113  * Name a DHCP packet type
114  *
115  * @v msgtype           DHCP message type
116  * @ret string          DHCP mesasge type name
117  */
118 static inline const char * dhcp_msgtype_name ( unsigned int msgtype ) {
119         switch ( msgtype ) {
120         case DHCPNONE:          return "BOOTP"; /* Non-DHCP packet */
121         case DHCPDISCOVER:      return "DHCPDISCOVER";
122         case DHCPOFFER:         return "DHCPOFFER";
123         case DHCPREQUEST:       return "DHCPREQUEST";
124         case DHCPDECLINE:       return "DHCPDECLINE";
125         case DHCPACK:           return "DHCPACK";
126         case DHCPNAK:           return "DHCPNAK";
127         case DHCPRELEASE:       return "DHCPRELEASE";
128         case DHCPINFORM:        return "DHCPINFORM";
129         default:                return "DHCP<invalid>";
130         }
131 }
132
133 /****************************************************************************
134  *
135  * DHCP session
136  *
137  */
138
139 struct dhcp_session;
140
141 /** DHCP session state operations */
142 struct dhcp_session_state {
143         /** State name */
144         const char *name;
145         /**
146          * Construct transmitted packet
147          *
148          * @v dhcp              DHCP session
149          * @v dhcppkt           DHCP packet
150          * @v peer              Destination address
151          */
152         int ( * tx ) ( struct dhcp_session *dhcp,
153                        struct dhcp_packet *dhcppkt,
154                        struct sockaddr_in *peer );
155         /** Handle received packet
156          *
157          * @v dhcp              DHCP session
158          * @v dhcppkt           DHCP packet
159          * @v peer              DHCP server address
160          * @v msgtype           DHCP message type
161          * @v server_id         DHCP server ID
162          */
163         void ( * rx ) ( struct dhcp_session *dhcp,
164                         struct dhcp_packet *dhcppkt,
165                         struct sockaddr_in *peer,
166                         uint8_t msgtype, struct in_addr server_id );
167         /** Handle timer expiry
168          *
169          * @v dhcp              DHCP session
170          */
171         void ( * expired ) ( struct dhcp_session *dhcp );
172         /** Transmitted message type */
173         uint8_t tx_msgtype;
174         /** Apply minimum timeout */
175         uint8_t apply_min_timeout;
176 };
177
178 static struct dhcp_session_state dhcp_state_discover;
179 static struct dhcp_session_state dhcp_state_request;
180 static struct dhcp_session_state dhcp_state_proxy;
181 static struct dhcp_session_state dhcp_state_pxebs;
182
183 /** A DHCP session */
184 struct dhcp_session {
185         /** Reference counter */
186         struct refcnt refcnt;
187         /** Job control interface */
188         struct interface job;
189         /** Data transfer interface */
190         struct interface xfer;
191
192         /** Network device being configured */
193         struct net_device *netdev;
194         /** Local socket address */
195         struct sockaddr_in local;
196         /** State of the session */
197         struct dhcp_session_state *state;
198         /** Transaction ID (in network-endian order) */
199         uint32_t xid;
200
201         /** Offered IP address */
202         struct in_addr offer;
203         /** DHCP server */
204         struct in_addr server;
205         /** DHCP offer priority */
206         int priority;
207
208         /** ProxyDHCP protocol extensions should be ignored */
209         int no_pxedhcp;
210         /** ProxyDHCP server */
211         struct in_addr proxy_server;
212         /** ProxyDHCP offer */
213         struct dhcp_packet *proxy_offer;
214         /** ProxyDHCP offer priority */
215         int proxy_priority;
216
217         /** PXE Boot Server type */
218         uint16_t pxe_type;
219         /** List of PXE Boot Servers to attempt */
220         struct in_addr *pxe_attempt;
221         /** List of PXE Boot Servers to accept */
222         struct in_addr *pxe_accept;
223
224         /** Retransmission timer */
225         struct retry_timer timer;
226         /** Transmission counter */
227         unsigned int count;
228         /** Start time of the current state (in ticks) */
229         unsigned long start;
230 };
231
232 /**
233  * Free DHCP session
234  *
235  * @v refcnt            Reference counter
236  */
237 static void dhcp_free ( struct refcnt *refcnt ) {
238         struct dhcp_session *dhcp =
239                 container_of ( refcnt, struct dhcp_session, refcnt );
240
241         netdev_put ( dhcp->netdev );
242         dhcppkt_put ( dhcp->proxy_offer );
243         free ( dhcp );
244 }
245
246 /**
247  * Mark DHCP session as complete
248  *
249  * @v dhcp              DHCP session
250  * @v rc                Return status code
251  */
252 static void dhcp_finished ( struct dhcp_session *dhcp, int rc ) {
253
254         /* Stop retry timer */
255         stop_timer ( &dhcp->timer );
256
257         /* Shut down interfaces */
258         intf_shutdown ( &dhcp->xfer, rc );
259         intf_shutdown ( &dhcp->job, rc );
260 }
261
262 /**
263  * Transition to new DHCP session state
264  *
265  * @v dhcp              DHCP session
266  * @v state             New session state
267  */
268 static void dhcp_set_state ( struct dhcp_session *dhcp,
269                              struct dhcp_session_state *state ) {
270
271         DBGC ( dhcp, "DHCP %p entering %s state\n", dhcp, state->name );
272         dhcp->state = state;
273         dhcp->start = currticks();
274         stop_timer ( &dhcp->timer );
275         dhcp->timer.min_timeout =
276                 ( state->apply_min_timeout ? DHCP_MIN_TIMEOUT : 0 );
277         dhcp->timer.max_timeout = DHCP_MAX_TIMEOUT;
278         start_timer_nodelay ( &dhcp->timer );
279 }
280
281 /**
282  * Check if DHCP packet contains PXE options
283  *
284  * @v dhcppkt           DHCP packet
285  * @ret has_pxeopts     DHCP packet contains PXE options
286  *
287  * It is assumed that the packet is already known to contain option 60
288  * set to "PXEClient".
289  */
290 static int dhcp_has_pxeopts ( struct dhcp_packet *dhcppkt ) {
291
292         /* Check for a boot filename */
293         if ( dhcppkt_fetch ( dhcppkt, DHCP_BOOTFILE_NAME, NULL, 0 ) > 0 )
294                 return 1;
295
296         /* Check for a PXE boot menu */
297         if ( dhcppkt_fetch ( dhcppkt, DHCP_PXE_BOOT_MENU, NULL, 0 ) > 0 )
298                 return 1;
299
300         return 0;
301 }
302
303 /****************************************************************************
304  *
305  * DHCP state machine
306  *
307  */
308
309 /**
310  * Construct transmitted packet for DHCP discovery
311  *
312  * @v dhcp              DHCP session
313  * @v dhcppkt           DHCP packet
314  * @v peer              Destination address
315  */
316 static int dhcp_discovery_tx ( struct dhcp_session *dhcp,
317                                struct dhcp_packet *dhcppkt __unused,
318                                struct sockaddr_in *peer ) {
319
320         DBGC ( dhcp, "DHCP %p DHCPDISCOVER\n", dhcp );
321
322         /* Set server address */
323         peer->sin_addr.s_addr = INADDR_BROADCAST;
324         peer->sin_port = htons ( BOOTPS_PORT );
325
326         return 0;
327 }
328
329 /**
330  * Handle received packet during DHCP discovery
331  *
332  * @v dhcp              DHCP session
333  * @v dhcppkt           DHCP packet
334  * @v peer              DHCP server address
335  * @v msgtype           DHCP message type
336  * @v server_id         DHCP server ID
337  */
338 static void dhcp_discovery_rx ( struct dhcp_session *dhcp,
339                                 struct dhcp_packet *dhcppkt,
340                                 struct sockaddr_in *peer, uint8_t msgtype,
341                                 struct in_addr server_id ) {
342         struct in_addr ip;
343         char vci[9]; /* "PXEClient" */
344         int vci_len;
345         int has_pxeclient;
346         int8_t priority = 0;
347         uint8_t no_pxedhcp = 0;
348         unsigned long elapsed;
349
350         DBGC ( dhcp, "DHCP %p %s from %s:%d", dhcp,
351                dhcp_msgtype_name ( msgtype ), inet_ntoa ( peer->sin_addr ),
352                ntohs ( peer->sin_port ) );
353         if ( server_id.s_addr != peer->sin_addr.s_addr )
354                 DBGC ( dhcp, " (%s)", inet_ntoa ( server_id ) );
355
356         /* Identify offered IP address */
357         ip = dhcppkt->dhcphdr->yiaddr;
358         if ( ip.s_addr )
359                 DBGC ( dhcp, " for %s", inet_ntoa ( ip ) );
360
361         /* Identify "PXEClient" vendor class */
362         vci_len = dhcppkt_fetch ( dhcppkt, DHCP_VENDOR_CLASS_ID,
363                                   vci, sizeof ( vci ) );
364         has_pxeclient = ( ( vci_len >= ( int ) sizeof ( vci ) ) &&
365                           ( strncmp ( "PXEClient", vci, sizeof (vci) ) == 0 ));
366         if ( has_pxeclient ) {
367                 DBGC ( dhcp, "%s",
368                        ( dhcp_has_pxeopts ( dhcppkt ) ? " pxe" : " proxy" ) );
369         }
370
371         /* Identify priority */
372         dhcppkt_fetch ( dhcppkt, DHCP_EB_PRIORITY, &priority,
373                         sizeof ( priority ) );
374         if ( priority )
375                 DBGC ( dhcp, " pri %d", priority );
376
377         /* Identify ignore-PXE flag */
378         dhcppkt_fetch ( dhcppkt, DHCP_EB_NO_PXEDHCP, &no_pxedhcp,
379                         sizeof ( no_pxedhcp ) );
380         if ( no_pxedhcp )
381                 DBGC ( dhcp, " nopxe" );
382         DBGC ( dhcp, "\n" );
383
384         /* Select as DHCP offer, if applicable */
385         if ( ip.s_addr && ( peer->sin_port == htons ( BOOTPS_PORT ) ) &&
386              ( ( msgtype == DHCPOFFER ) || ( ! msgtype /* BOOTP */ ) ) &&
387              ( priority >= dhcp->priority ) ) {
388                 dhcp->offer = ip;
389                 dhcp->server = server_id;
390                 dhcp->priority = priority;
391                 dhcp->no_pxedhcp = no_pxedhcp;
392         }
393
394         /* Select as ProxyDHCP offer, if applicable */
395         if ( server_id.s_addr && has_pxeclient &&
396              ( priority >= dhcp->proxy_priority ) ) {
397                 dhcppkt_put ( dhcp->proxy_offer );
398                 dhcp->proxy_server = server_id;
399                 dhcp->proxy_offer = dhcppkt_get ( dhcppkt );
400                 dhcp->proxy_priority = priority;
401         }
402
403         /* We can exit the discovery state when we have a valid
404          * DHCPOFFER, and either:
405          *
406          *  o  The DHCPOFFER instructs us to ignore ProxyDHCPOFFERs, or
407          *  o  We have a valid ProxyDHCPOFFER, or
408          *  o  We have allowed sufficient time for ProxyDHCPOFFERs.
409          */
410
411         /* If we don't yet have a DHCPOFFER, do nothing */
412         if ( ! dhcp->offer.s_addr )
413                 return;
414
415         /* If we can't yet transition to DHCPREQUEST, do nothing */
416         elapsed = ( currticks() - dhcp->start );
417         if ( ! ( dhcp->no_pxedhcp || dhcp->proxy_offer ||
418                  ( elapsed > PROXYDHCP_MAX_TIMEOUT ) ) )
419                 return;
420
421         /* Transition to DHCPREQUEST */
422         dhcp_set_state ( dhcp, &dhcp_state_request );
423 }
424
425 /**
426  * Handle timer expiry during DHCP discovery
427  *
428  * @v dhcp              DHCP session
429  */
430 static void dhcp_discovery_expired ( struct dhcp_session *dhcp ) {
431         unsigned long elapsed = ( currticks() - dhcp->start );
432
433         /* Give up waiting for ProxyDHCP before we reach the failure point */
434         if ( dhcp->offer.s_addr && ( elapsed > PROXYDHCP_MAX_TIMEOUT ) ) {
435                 dhcp_set_state ( dhcp, &dhcp_state_request );
436                 return;
437         }
438
439         /* Otherwise, retransmit current packet */
440         dhcp_tx ( dhcp );
441 }
442
443 /** DHCP discovery state operations */
444 static struct dhcp_session_state dhcp_state_discover = {
445         .name                   = "discovery",
446         .tx                     = dhcp_discovery_tx,
447         .rx                     = dhcp_discovery_rx,
448         .expired                = dhcp_discovery_expired,
449         .tx_msgtype             = DHCPDISCOVER,
450         .apply_min_timeout      = 1,
451 };
452
453 /**
454  * Construct transmitted packet for DHCP request
455  *
456  * @v dhcp              DHCP session
457  * @v dhcppkt           DHCP packet
458  * @v peer              Destination address
459  */
460 static int dhcp_request_tx ( struct dhcp_session *dhcp,
461                              struct dhcp_packet *dhcppkt,
462                              struct sockaddr_in *peer ) {
463         int rc;
464
465         DBGC ( dhcp, "DHCP %p DHCPREQUEST to %s:%d",
466                dhcp, inet_ntoa ( dhcp->server ), BOOTPS_PORT );
467         DBGC ( dhcp, " for %s\n", inet_ntoa ( dhcp->offer ) );
468
469         /* Set server ID */
470         if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_SERVER_IDENTIFIER,
471                                     &dhcp->server,
472                                     sizeof ( dhcp->server ) ) ) != 0 )
473                 return rc;
474
475         /* Set requested IP address */
476         if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_REQUESTED_ADDRESS,
477                                     &dhcp->offer,
478                                     sizeof ( dhcp->offer ) ) ) != 0 )
479                 return rc;
480
481         /* Set server address */
482         peer->sin_addr.s_addr = INADDR_BROADCAST;
483         peer->sin_port = htons ( BOOTPS_PORT );
484
485         return 0;
486 }
487
488 /**
489  * Handle received packet during DHCP request
490  *
491  * @v dhcp              DHCP session
492  * @v dhcppkt           DHCP packet
493  * @v peer              DHCP server address
494  * @v msgtype           DHCP message type
495  * @v server_id         DHCP server ID
496  */
497 static void dhcp_request_rx ( struct dhcp_session *dhcp,
498                               struct dhcp_packet *dhcppkt,
499                               struct sockaddr_in *peer, uint8_t msgtype,
500                               struct in_addr server_id ) {
501         struct in_addr ip;
502         struct settings *parent;
503         struct settings *settings;
504         int rc;
505
506         DBGC ( dhcp, "DHCP %p %s from %s:%d", dhcp,
507                dhcp_msgtype_name ( msgtype ), inet_ntoa ( peer->sin_addr ),
508                ntohs ( peer->sin_port ) );
509         if ( server_id.s_addr != peer->sin_addr.s_addr )
510                 DBGC ( dhcp, " (%s)", inet_ntoa ( server_id ) );
511
512         /* Identify leased IP address */
513         ip = dhcppkt->dhcphdr->yiaddr;
514         if ( ip.s_addr )
515                 DBGC ( dhcp, " for %s", inet_ntoa ( ip ) );
516         DBGC ( dhcp, "\n" );
517
518         /* Filter out unacceptable responses */
519         if ( peer->sin_port != htons ( BOOTPS_PORT ) )
520                 return;
521         if ( msgtype /* BOOTP */ && ( msgtype != DHCPACK ) )
522                 return;
523         if ( server_id.s_addr != dhcp->server.s_addr )
524                 return;
525         if ( ip.s_addr != dhcp->offer.s_addr )
526                 return;
527
528         /* Record assigned address */
529         dhcp->local.sin_addr = ip;
530
531         /* Register settings */
532         parent = netdev_settings ( dhcp->netdev );
533         settings = &dhcppkt->settings;
534         if ( ( rc = register_settings ( settings, parent,
535                                         DHCP_SETTINGS_NAME ) ) != 0 ) {
536                 DBGC ( dhcp, "DHCP %p could not register settings: %s\n",
537                        dhcp, strerror ( rc ) );
538                 dhcp_finished ( dhcp, rc );
539                 return;
540         }
541
542         /* Perform ProxyDHCP if applicable */
543         if ( dhcp->proxy_offer /* Have ProxyDHCP offer */ &&
544              ( ! dhcp->no_pxedhcp ) /* ProxyDHCP not disabled */ ) {
545                 if ( dhcp_has_pxeopts ( dhcp->proxy_offer ) ) {
546                         /* PXE options already present; register settings
547                          * without performing a ProxyDHCPREQUEST
548                          */
549                         settings = &dhcp->proxy_offer->settings;
550                         if ( ( rc = register_settings ( settings, NULL,
551                                            PROXYDHCP_SETTINGS_NAME ) ) != 0 ) {
552                                 DBGC ( dhcp, "DHCP %p could not register "
553                                        "proxy settings: %s\n",
554                                        dhcp, strerror ( rc ) );
555                                 dhcp_finished ( dhcp, rc );
556                                 return;
557                         }
558                 } else {
559                         /* PXE options not present; use a ProxyDHCPREQUEST */
560                         dhcp_set_state ( dhcp, &dhcp_state_proxy );
561                         return;
562                 }
563         }
564
565         /* Terminate DHCP */
566         dhcp_finished ( dhcp, 0 );
567 }
568
569 /**
570  * Handle timer expiry during DHCP discovery
571  *
572  * @v dhcp              DHCP session
573  */
574 static void dhcp_request_expired ( struct dhcp_session *dhcp ) {
575
576         /* Retransmit current packet */
577         dhcp_tx ( dhcp );
578 }
579
580 /** DHCP request state operations */
581 static struct dhcp_session_state dhcp_state_request = {
582         .name                   = "request",
583         .tx                     = dhcp_request_tx,
584         .rx                     = dhcp_request_rx,
585         .expired                = dhcp_request_expired,
586         .tx_msgtype             = DHCPREQUEST,
587         .apply_min_timeout      = 0,
588 };
589
590 /**
591  * Construct transmitted packet for ProxyDHCP request
592  *
593  * @v dhcp              DHCP session
594  * @v dhcppkt           DHCP packet
595  * @v peer              Destination address
596  */
597 static int dhcp_proxy_tx ( struct dhcp_session *dhcp,
598                            struct dhcp_packet *dhcppkt,
599                            struct sockaddr_in *peer ) {
600         int rc;
601
602         DBGC ( dhcp, "DHCP %p ProxyDHCP REQUEST to %s\n", dhcp,
603                inet_ntoa ( dhcp->proxy_server ) );
604
605         /* Set server ID */
606         if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_SERVER_IDENTIFIER,
607                                     &dhcp->proxy_server,
608                                     sizeof ( dhcp->proxy_server ) ) ) != 0 )
609                 return rc;
610
611         /* Set server address */
612         peer->sin_addr = dhcp->proxy_server;
613         peer->sin_port = htons ( PXE_PORT );
614
615         return 0;
616 }
617
618 /**
619  * Handle received packet during ProxyDHCP request
620  *
621  * @v dhcp              DHCP session
622  * @v dhcppkt           DHCP packet
623  * @v peer              DHCP server address
624  * @v msgtype           DHCP message type
625  * @v server_id         DHCP server ID
626  */
627 static void dhcp_proxy_rx ( struct dhcp_session *dhcp,
628                             struct dhcp_packet *dhcppkt,
629                             struct sockaddr_in *peer, uint8_t msgtype,
630                             struct in_addr server_id ) {
631         struct settings *settings = &dhcppkt->settings;
632         int rc;
633
634         DBGC ( dhcp, "DHCP %p %s from %s:%d", dhcp,
635                dhcp_msgtype_name ( msgtype ), inet_ntoa ( peer->sin_addr ),
636                ntohs ( peer->sin_port ) );
637         if ( server_id.s_addr != peer->sin_addr.s_addr )
638                 DBGC ( dhcp, " (%s)", inet_ntoa ( server_id ) );
639         DBGC ( dhcp, "\n" );
640
641         /* Filter out unacceptable responses */
642         if ( peer->sin_port != ntohs ( PXE_PORT ) )
643                 return;
644         if ( ( msgtype != DHCPOFFER ) && ( msgtype != DHCPACK ) )
645                 return;
646         if ( server_id.s_addr /* Linux PXE server omits server ID */ &&
647              ( server_id.s_addr != dhcp->proxy_server.s_addr ) )
648                 return;
649
650         /* Register settings */
651         if ( ( rc = register_settings ( settings, NULL,
652                                         PROXYDHCP_SETTINGS_NAME ) ) != 0 ) {
653                 DBGC ( dhcp, "DHCP %p could not register proxy settings: %s\n",
654                        dhcp, strerror ( rc ) );
655                 dhcp_finished ( dhcp, rc );
656                 return;
657         }
658
659         /* Terminate DHCP */
660         dhcp_finished ( dhcp, 0 );
661 }
662
663 /**
664  * Handle timer expiry during ProxyDHCP request
665  *
666  * @v dhcp              DHCP session
667  */
668 static void dhcp_proxy_expired ( struct dhcp_session *dhcp ) {
669         unsigned long elapsed = ( currticks() - dhcp->start );
670
671         /* Give up waiting for ProxyDHCP before we reach the failure point */
672         if ( elapsed > PROXYDHCP_MAX_TIMEOUT ) {
673                 dhcp_finished ( dhcp, 0 );
674                 return;
675         }
676
677         /* Retransmit current packet */
678         dhcp_tx ( dhcp );
679 }
680
681 /** ProxyDHCP request state operations */
682 static struct dhcp_session_state dhcp_state_proxy = {
683         .name                   = "ProxyDHCP",
684         .tx                     = dhcp_proxy_tx,
685         .rx                     = dhcp_proxy_rx,
686         .expired                = dhcp_proxy_expired,
687         .tx_msgtype             = DHCPREQUEST,
688         .apply_min_timeout      = 0,
689 };
690
691 /**
692  * Construct transmitted packet for PXE Boot Server Discovery
693  *
694  * @v dhcp              DHCP session
695  * @v dhcppkt           DHCP packet
696  * @v peer              Destination address
697  */
698 static int dhcp_pxebs_tx ( struct dhcp_session *dhcp,
699                            struct dhcp_packet *dhcppkt,
700                            struct sockaddr_in *peer ) {
701         struct dhcp_pxe_boot_menu_item menu_item = { 0, 0 };
702         int rc;
703
704         /* Set server address */
705         peer->sin_addr = *(dhcp->pxe_attempt);
706         peer->sin_port = ( ( peer->sin_addr.s_addr == INADDR_BROADCAST ) ?
707                            htons ( BOOTPS_PORT ) : htons ( PXE_PORT ) );
708
709         DBGC ( dhcp, "DHCP %p PXEBS REQUEST to %s:%d for type %d\n",
710                dhcp, inet_ntoa ( peer->sin_addr ), ntohs ( peer->sin_port ),
711                le16_to_cpu ( dhcp->pxe_type ) );
712
713         /* Set boot menu item */
714         menu_item.type = dhcp->pxe_type;
715         if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_PXE_BOOT_MENU_ITEM,
716                                     &menu_item, sizeof ( menu_item ) ) ) != 0 )
717                 return rc;
718
719         return 0;
720 }
721
722 /**
723  * Check to see if PXE Boot Server address is acceptable
724  *
725  * @v dhcp              DHCP session
726  * @v bs                Boot Server address
727  * @ret accept          Boot Server is acceptable
728  */
729 static int dhcp_pxebs_accept ( struct dhcp_session *dhcp,
730                                struct in_addr bs ) {
731         struct in_addr *accept;
732
733         /* Accept if we have no acceptance filter */
734         if ( ! dhcp->pxe_accept )
735                 return 1;
736
737         /* Scan through acceptance list */
738         for ( accept = dhcp->pxe_accept ; accept->s_addr ; accept++ ) {
739                 if ( accept->s_addr == bs.s_addr )
740                         return 1;
741         }
742
743         DBGC ( dhcp, "DHCP %p rejecting server %s\n",
744                dhcp, inet_ntoa ( bs ) );
745         return 0;
746 }
747
748 /**
749  * Handle received packet during PXE Boot Server Discovery
750  *
751  * @v dhcp              DHCP session
752  * @v dhcppkt           DHCP packet
753  * @v peer              DHCP server address
754  * @v msgtype           DHCP message type
755  * @v server_id         DHCP server ID
756  */
757 static void dhcp_pxebs_rx ( struct dhcp_session *dhcp,
758                             struct dhcp_packet *dhcppkt,
759                             struct sockaddr_in *peer, uint8_t msgtype,
760                             struct in_addr server_id ) {
761         struct dhcp_pxe_boot_menu_item menu_item = { 0, 0 };
762         int rc;
763
764         DBGC ( dhcp, "DHCP %p %s from %s:%d", dhcp,
765                dhcp_msgtype_name ( msgtype ), inet_ntoa ( peer->sin_addr ),
766                ntohs ( peer->sin_port ) );
767         if ( server_id.s_addr != peer->sin_addr.s_addr )
768                 DBGC ( dhcp, " (%s)", inet_ntoa ( server_id ) );
769
770         /* Identify boot menu item */
771         dhcppkt_fetch ( dhcppkt, DHCP_PXE_BOOT_MENU_ITEM,
772                         &menu_item, sizeof ( menu_item ) );
773         if ( menu_item.type )
774                 DBGC ( dhcp, " for type %d", ntohs ( menu_item.type ) );
775         DBGC ( dhcp, "\n" );
776
777         /* Filter out unacceptable responses */
778         if ( ( peer->sin_port != htons ( BOOTPS_PORT ) ) &&
779              ( peer->sin_port != htons ( PXE_PORT ) ) )
780                 return;
781         if ( msgtype != DHCPACK )
782                 return;
783         if ( menu_item.type != dhcp->pxe_type )
784                 return;
785         if ( ! dhcp_pxebs_accept ( dhcp, ( server_id.s_addr ?
786                                            server_id : peer->sin_addr ) ) )
787                 return;
788
789         /* Register settings */
790         if ( ( rc = register_settings ( &dhcppkt->settings, NULL,
791                                         PXEBS_SETTINGS_NAME ) ) != 0 ) {
792                 DBGC ( dhcp, "DHCP %p could not register settings: %s\n",
793                        dhcp, strerror ( rc ) );
794                 dhcp_finished ( dhcp, rc );
795                 return;
796         }
797
798         /* Terminate DHCP */
799         dhcp_finished ( dhcp, 0 );
800 }
801
802 /**
803  * Handle timer expiry during PXE Boot Server Discovery
804  *
805  * @v dhcp              DHCP session
806  */
807 static void dhcp_pxebs_expired ( struct dhcp_session *dhcp ) {
808         unsigned long elapsed = ( currticks() - dhcp->start );
809
810         /* Give up waiting before we reach the failure point, and fail
811          * over to the next server in the attempt list
812          */
813         if ( elapsed > PXEBS_MAX_TIMEOUT ) {
814                 dhcp->pxe_attempt++;
815                 if ( dhcp->pxe_attempt->s_addr ) {
816                         dhcp_set_state ( dhcp, &dhcp_state_pxebs );
817                         return;
818                 } else {
819                         dhcp_finished ( dhcp, -ETIMEDOUT );
820                         return;
821                 }
822         }
823
824         /* Retransmit current packet */
825         dhcp_tx ( dhcp );
826 }
827
828 /** PXE Boot Server Discovery state operations */
829 static struct dhcp_session_state dhcp_state_pxebs = {
830         .name                   = "PXEBS",
831         .tx                     = dhcp_pxebs_tx,
832         .rx                     = dhcp_pxebs_rx,
833         .expired                = dhcp_pxebs_expired,
834         .tx_msgtype             = DHCPREQUEST,
835         .apply_min_timeout      = 1,
836 };
837
838 /****************************************************************************
839  *
840  * Packet construction
841  *
842  */
843
844 /**
845  * Create a DHCP packet
846  *
847  * @v dhcppkt           DHCP packet structure to fill in
848  * @v netdev            Network device
849  * @v msgtype           DHCP message type
850  * @v xid               Transaction ID (in network-endian order)
851  * @v options           Initial options to include (or NULL)
852  * @v options_len       Length of initial options
853  * @v data              Buffer for DHCP packet
854  * @v max_len           Size of DHCP packet buffer
855  * @ret rc              Return status code
856  *
857  * Creates a DHCP packet in the specified buffer, and initialise a
858  * DHCP packet structure.
859  */
860 int dhcp_create_packet ( struct dhcp_packet *dhcppkt,
861                          struct net_device *netdev, uint8_t msgtype,
862                          uint32_t xid, const void *options, size_t options_len,
863                          void *data, size_t max_len ) {
864         struct dhcphdr *dhcphdr = data;
865         int rc;
866
867         /* Sanity check */
868         if ( max_len < ( sizeof ( *dhcphdr ) + options_len ) )
869                 return -ENOSPC;
870
871         /* Initialise DHCP packet content */
872         memset ( dhcphdr, 0, max_len );
873         dhcphdr->xid = xid;
874         dhcphdr->magic = htonl ( DHCP_MAGIC_COOKIE );
875         dhcphdr->htype = ntohs ( netdev->ll_protocol->ll_proto );
876         dhcphdr->op = dhcp_op[msgtype];
877         dhcphdr->hlen = netdev->ll_protocol->ll_addr_len;
878         memcpy ( dhcphdr->chaddr, netdev->ll_addr,
879                  netdev->ll_protocol->ll_addr_len );
880         memcpy ( dhcphdr->options, options, options_len );
881
882         /* If the local link-layer address functions only as a name
883          * (i.e. cannot be used as a destination address), then
884          * request broadcast responses.
885          */
886         if ( netdev->ll_protocol->flags & LL_NAME_ONLY )
887                 dhcphdr->flags |= htons ( BOOTP_FL_BROADCAST );
888
889         /* If the network device already has an IPv4 address then
890          * unicast responses from the DHCP server may be rejected, so
891          * request broadcast responses.
892          */
893         if ( ipv4_has_any_addr ( netdev ) )
894                 dhcphdr->flags |= htons ( BOOTP_FL_BROADCAST );
895
896         /* Initialise DHCP packet structure */
897         memset ( dhcppkt, 0, sizeof ( *dhcppkt ) );
898         dhcppkt_init ( dhcppkt, data, max_len );
899         
900         /* Set DHCP_MESSAGE_TYPE option */
901         if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_MESSAGE_TYPE,
902                                     &msgtype, sizeof ( msgtype ) ) ) != 0 )
903                 return rc;
904
905         return 0;
906 }
907
908 /**
909  * Create DHCP request packet
910  *
911  * @v dhcppkt           DHCP packet structure to fill in
912  * @v netdev            Network device
913  * @v msgtype           DHCP message type
914  * @v xid               Transaction ID (in network-endian order)
915  * @v ciaddr            Client IP address
916  * @v data              Buffer for DHCP packet
917  * @v max_len           Size of DHCP packet buffer
918  * @ret rc              Return status code
919  *
920  * Creates a DHCP request packet in the specified buffer, and
921  * initialise a DHCP packet structure.
922  */
923 int dhcp_create_request ( struct dhcp_packet *dhcppkt,
924                           struct net_device *netdev, unsigned int msgtype,
925                           uint32_t xid, struct in_addr ciaddr,
926                           void *data, size_t max_len ) {
927         struct dhcp_netdev_desc dhcp_desc;
928         struct dhcp_client_id client_id;
929         struct dhcp_client_uuid client_uuid;
930         uint8_t *dhcp_features;
931         size_t dhcp_features_len;
932         size_t ll_addr_len;
933         void *user_class;
934         ssize_t len;
935         int rc;
936
937         /* Create DHCP packet */
938         if ( ( rc = dhcp_create_packet ( dhcppkt, netdev, msgtype, xid,
939                                          dhcp_request_options_data,
940                                          sizeof ( dhcp_request_options_data ),
941                                          data, max_len ) ) != 0 ) {
942                 DBG ( "DHCP could not create DHCP packet: %s\n",
943                       strerror ( rc ) );
944                 goto err_create_packet;
945         }
946
947         /* Set client IP address */
948         dhcppkt->dhcphdr->ciaddr = ciaddr;
949
950         /* Add options to identify the feature list */
951         dhcp_features = table_start ( DHCP_FEATURES );
952         dhcp_features_len = table_num_entries ( DHCP_FEATURES );
953         if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_EB_ENCAP, dhcp_features,
954                                     dhcp_features_len ) ) != 0 ) {
955                 DBG ( "DHCP could not set features list option: %s\n",
956                       strerror ( rc ) );
957                 goto err_store_features;
958         }
959
960         /* Add options to identify the network device */
961         fetch_raw_setting ( netdev_settings ( netdev ), &busid_setting,
962                             &dhcp_desc, sizeof ( dhcp_desc ) );
963         if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_EB_BUS_ID, &dhcp_desc,
964                                     sizeof ( dhcp_desc ) ) ) != 0 ) {
965                 DBG ( "DHCP could not set bus ID option: %s\n",
966                       strerror ( rc ) );
967                 goto err_store_busid;
968         }
969
970         /* Add DHCP client identifier.  Required for Infiniband, and
971          * doesn't hurt other link layers.
972          */
973         client_id.ll_proto = ntohs ( netdev->ll_protocol->ll_proto );
974         ll_addr_len = netdev->ll_protocol->ll_addr_len;
975         assert ( ll_addr_len <= sizeof ( client_id.ll_addr ) );
976         memcpy ( client_id.ll_addr, netdev->ll_addr, ll_addr_len );
977         if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_CLIENT_ID, &client_id,
978                                     ( ll_addr_len + 1 ) ) ) != 0 ) {
979                 DBG ( "DHCP could not set client ID: %s\n",
980                       strerror ( rc ) );
981                 goto err_store_client_id;
982         }
983
984         /* Add client UUID, if we have one.  Required for PXE.  The
985          * PXE spec does not specify a byte ordering for UUIDs, but
986          * RFC4578 suggests that it follows the EFI spec, in which the
987          * first three fields are little-endian.
988          */
989         client_uuid.type = DHCP_CLIENT_UUID_TYPE;
990         if ( ( len = fetch_uuid_setting ( NULL, &uuid_setting,
991                                           &client_uuid.uuid ) ) >= 0 ) {
992                 uuid_mangle ( &client_uuid.uuid );
993                 if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_CLIENT_UUID,
994                                             &client_uuid,
995                                             sizeof ( client_uuid ) ) ) != 0 ) {
996                         DBG ( "DHCP could not set client UUID: %s\n",
997                               strerror ( rc ) );
998                         goto err_store_client_uuid;
999                 }
1000         }
1001
1002         /* Add user class, if we have one. */
1003         if ( ( len = fetch_raw_setting_copy ( NULL, &user_class_setting,
1004                                               &user_class ) ) >= 0 ) {
1005                 if ( ( rc = dhcppkt_store ( dhcppkt, DHCP_USER_CLASS_ID,
1006                                             user_class, len ) ) != 0 ) {
1007                         DBG ( "DHCP could not set user class: %s\n",
1008                               strerror ( rc ) );
1009                         goto err_store_user_class;
1010                 }
1011         }
1012
1013  err_store_user_class:
1014         free ( user_class );
1015  err_store_client_uuid:
1016  err_store_client_id:
1017  err_store_busid:
1018  err_store_features:
1019  err_create_packet:
1020         return rc;
1021 }
1022
1023 /****************************************************************************
1024  *
1025  * Data transfer interface
1026  *
1027  */
1028
1029 /**
1030  * Transmit DHCP request
1031  *
1032  * @v dhcp              DHCP session
1033  * @ret rc              Return status code
1034  */
1035 static int dhcp_tx ( struct dhcp_session *dhcp ) {
1036         static struct sockaddr_in peer = {
1037                 .sin_family = AF_INET,
1038         };
1039         struct xfer_metadata meta = {
1040                 .netdev = dhcp->netdev,
1041                 .src = ( struct sockaddr * ) &dhcp->local,
1042                 .dest = ( struct sockaddr * ) &peer,
1043         };
1044         struct io_buffer *iobuf;
1045         uint8_t msgtype = dhcp->state->tx_msgtype;
1046         struct dhcp_packet dhcppkt;
1047         int rc;
1048
1049         /* Start retry timer.  Do this first so that failures to
1050          * transmit will be retried.
1051          */
1052         start_timer ( &dhcp->timer );
1053
1054         /* Allocate buffer for packet */
1055         iobuf = xfer_alloc_iob ( &dhcp->xfer, DHCP_MIN_LEN );
1056         if ( ! iobuf )
1057                 return -ENOMEM;
1058
1059         /* Create basic DHCP packet in temporary buffer */
1060         if ( ( rc = dhcp_create_request ( &dhcppkt, dhcp->netdev, msgtype,
1061                                           dhcp->xid, dhcp->local.sin_addr,
1062                                           iobuf->data,
1063                                           iob_tailroom ( iobuf ) ) ) != 0 ) {
1064                 DBGC ( dhcp, "DHCP %p could not construct DHCP request: %s\n",
1065                        dhcp, strerror ( rc ) );
1066                 goto done;
1067         }
1068
1069         /* (Ab)use the "secs" field to convey metadata about the DHCP
1070          * session state into packet traces.  Useful for extracting
1071          * debug information from non-debug builds.
1072          */
1073         dhcppkt.dhcphdr->secs = htons ( ( ++(dhcp->count) << 2 ) |
1074                                         ( dhcp->offer.s_addr ? 0x02 : 0 ) |
1075                                         ( dhcp->proxy_offer ? 0x01 : 0 ) );
1076
1077         /* Fill in packet based on current state */
1078         if ( ( rc = dhcp->state->tx ( dhcp, &dhcppkt, &peer ) ) != 0 ) {
1079                 DBGC ( dhcp, "DHCP %p could not fill DHCP request: %s\n",
1080                        dhcp, strerror ( rc ) );
1081                 goto done;
1082         }
1083
1084         /* Transmit the packet */
1085         iob_put ( iobuf, dhcppkt_len ( &dhcppkt ) );
1086         if ( ( rc = xfer_deliver ( &dhcp->xfer, iob_disown ( iobuf ),
1087                                    &meta ) ) != 0 ) {
1088                 DBGC ( dhcp, "DHCP %p could not transmit UDP packet: %s\n",
1089                        dhcp, strerror ( rc ) );
1090                 goto done;
1091         }
1092
1093  done:
1094         free_iob ( iobuf );
1095         return rc;
1096 }
1097
1098 /**
1099  * Receive new data
1100  *
1101  * @v dhcp              DHCP session
1102  * @v iobuf             I/O buffer
1103  * @v meta              Transfer metadata
1104  * @ret rc              Return status code
1105  */
1106 static int dhcp_deliver ( struct dhcp_session *dhcp,
1107                           struct io_buffer *iobuf,
1108                           struct xfer_metadata *meta ) {
1109         struct net_device *netdev = dhcp->netdev;
1110         struct ll_protocol *ll_protocol = netdev->ll_protocol;
1111         struct sockaddr_in *peer;
1112         size_t data_len;
1113         struct dhcp_packet *dhcppkt;
1114         struct dhcphdr *dhcphdr;
1115         uint8_t msgtype = 0;
1116         struct in_addr server_id = { 0 };
1117         int rc = 0;
1118
1119         /* Sanity checks */
1120         if ( ! meta->src ) {
1121                 DBGC ( dhcp, "DHCP %p received packet without source port\n",
1122                        dhcp );
1123                 rc = -EINVAL;
1124                 goto err_no_src;
1125         }
1126         peer = ( struct sockaddr_in * ) meta->src;
1127
1128         /* Create a DHCP packet containing the I/O buffer contents.
1129          * Whilst we could just use the original buffer in situ, that
1130          * would waste the unused space in the packet buffer, and also
1131          * waste a relatively scarce fully-aligned I/O buffer.
1132          */
1133         data_len = iob_len ( iobuf );
1134         dhcppkt = zalloc ( sizeof ( *dhcppkt ) + data_len );
1135         if ( ! dhcppkt ) {
1136                 rc = -ENOMEM;
1137                 goto err_alloc_dhcppkt;
1138         }
1139         dhcphdr = ( ( ( void * ) dhcppkt ) + sizeof ( *dhcppkt ) );
1140         memcpy ( dhcphdr, iobuf->data, data_len );
1141         dhcppkt_init ( dhcppkt, dhcphdr, data_len );
1142
1143         /* Identify message type */
1144         dhcppkt_fetch ( dhcppkt, DHCP_MESSAGE_TYPE, &msgtype,
1145                         sizeof ( msgtype ) );
1146
1147         /* Identify server ID */
1148         dhcppkt_fetch ( dhcppkt, DHCP_SERVER_IDENTIFIER,
1149                         &server_id, sizeof ( server_id ) );
1150
1151         /* Check for matching transaction ID */
1152         if ( dhcphdr->xid != dhcp->xid ) {
1153                 DBGC ( dhcp, "DHCP %p %s from %s:%d has bad transaction "
1154                        "ID\n", dhcp, dhcp_msgtype_name ( msgtype ),
1155                        inet_ntoa ( peer->sin_addr ),
1156                        ntohs ( peer->sin_port ) );
1157                 rc = -EINVAL;
1158                 goto err_xid;
1159         };
1160
1161         /* Check for matching client hardware address */
1162         if ( memcmp ( dhcphdr->chaddr, netdev->ll_addr,
1163                       ll_protocol->ll_addr_len ) != 0 ) {
1164                 DBGC ( dhcp, "DHCP %p %s from %s:%d has bad chaddr %s\n",
1165                        dhcp, dhcp_msgtype_name ( msgtype ),
1166                        inet_ntoa ( peer->sin_addr ), ntohs ( peer->sin_port ),
1167                        ll_protocol->ntoa ( dhcphdr->chaddr ) );
1168                 rc = -EINVAL;
1169                 goto err_chaddr;
1170         }
1171
1172         /* Handle packet based on current state */
1173         dhcp->state->rx ( dhcp, dhcppkt, peer, msgtype, server_id );
1174
1175  err_chaddr:
1176  err_xid:
1177         dhcppkt_put ( dhcppkt );
1178  err_alloc_dhcppkt:
1179  err_no_src:
1180         free_iob ( iobuf );
1181         return rc;
1182 }
1183
1184 /** DHCP data transfer interface operations */
1185 static struct interface_operation dhcp_xfer_operations[] = {
1186         INTF_OP ( xfer_deliver, struct dhcp_session *, dhcp_deliver ),
1187 };
1188
1189 /** DHCP data transfer interface descriptor */
1190 static struct interface_descriptor dhcp_xfer_desc =
1191         INTF_DESC ( struct dhcp_session, xfer, dhcp_xfer_operations );
1192
1193 /**
1194  * Handle DHCP retry timer expiry
1195  *
1196  * @v timer             DHCP retry timer
1197  * @v fail              Failure indicator
1198  */
1199 static void dhcp_timer_expired ( struct retry_timer *timer, int fail ) {
1200         struct dhcp_session *dhcp =
1201                 container_of ( timer, struct dhcp_session, timer );
1202
1203         /* If we have failed, terminate DHCP */
1204         if ( fail ) {
1205                 dhcp_finished ( dhcp, -ETIMEDOUT );
1206                 return;
1207         }
1208
1209         /* Handle timer expiry based on current state */
1210         dhcp->state->expired ( dhcp );
1211 }
1212
1213 /****************************************************************************
1214  *
1215  * Job control interface
1216  *
1217  */
1218
1219 /** DHCP job control interface operations */
1220 static struct interface_operation dhcp_job_op[] = {
1221         INTF_OP ( intf_close, struct dhcp_session *, dhcp_finished ),
1222 };
1223
1224 /** DHCP job control interface descriptor */
1225 static struct interface_descriptor dhcp_job_desc =
1226         INTF_DESC ( struct dhcp_session, job, dhcp_job_op );
1227
1228 /****************************************************************************
1229  *
1230  * Instantiators
1231  *
1232  */
1233
1234 /**
1235  * DHCP peer address for socket opening
1236  *
1237  * This is a dummy address; the only useful portion is the socket
1238  * family (so that we get a UDP connection).  The DHCP client will set
1239  * the IP address and source port explicitly on each transmission.
1240  */
1241 static struct sockaddr dhcp_peer = {
1242         .sa_family = AF_INET,
1243 };
1244
1245 /**
1246  * Start DHCP state machine on a network device
1247  *
1248  * @v job               Job control interface
1249  * @v netdev            Network device
1250  * @ret rc              Return status code
1251  *
1252  * Starts DHCP on the specified network device.  If successful, the
1253  * DHCPACK (and ProxyDHCPACK, if applicable) will be registered as
1254  * option sources.
1255  */
1256 int start_dhcp ( struct interface *job, struct net_device *netdev ) {
1257         struct dhcp_session *dhcp;
1258         int rc;
1259
1260         /* Allocate and initialise structure */
1261         dhcp = zalloc ( sizeof ( *dhcp ) );
1262         if ( ! dhcp )
1263                 return -ENOMEM;
1264         ref_init ( &dhcp->refcnt, dhcp_free );
1265         intf_init ( &dhcp->job, &dhcp_job_desc, &dhcp->refcnt );
1266         intf_init ( &dhcp->xfer, &dhcp_xfer_desc, &dhcp->refcnt );
1267         timer_init ( &dhcp->timer, dhcp_timer_expired, &dhcp->refcnt );
1268         dhcp->netdev = netdev_get ( netdev );
1269         dhcp->local.sin_family = AF_INET;
1270         dhcp->local.sin_port = htons ( BOOTPC_PORT );
1271         dhcp->xid = random();
1272
1273         /* Store DHCP transaction ID for fakedhcp code */
1274         dhcp_last_xid = dhcp->xid;
1275
1276         /* Instantiate child objects and attach to our interfaces */
1277         if ( ( rc = xfer_open_socket ( &dhcp->xfer, SOCK_DGRAM, &dhcp_peer,
1278                                   ( struct sockaddr * ) &dhcp->local ) ) != 0 )
1279                 goto err;
1280
1281         /* Enter DHCPDISCOVER state */
1282         dhcp_set_state ( dhcp, &dhcp_state_discover );
1283
1284         /* Attach parent interface, mortalise self, and return */
1285         intf_plug_plug ( &dhcp->job, job );
1286         ref_put ( &dhcp->refcnt );
1287         return 0;
1288
1289  err:
1290         dhcp_finished ( dhcp, rc );
1291         ref_put ( &dhcp->refcnt );
1292         return rc;
1293 }
1294
1295 /**
1296  * Retrieve list of PXE boot servers for a given server type
1297  *
1298  * @v dhcp              DHCP session
1299  * @v raw               DHCP PXE boot server list
1300  * @v raw_len           Length of DHCP PXE boot server list
1301  * @v ip                IP address list to fill in
1302  *
1303  * The caller must ensure that the IP address list has sufficient
1304  * space.
1305  */
1306 static void pxebs_list ( struct dhcp_session *dhcp, void *raw,
1307                          size_t raw_len, struct in_addr *ip ) {
1308         struct dhcp_pxe_boot_server *server = raw;
1309         size_t server_len;
1310         unsigned int i;
1311
1312         while ( raw_len ) {
1313                 if ( raw_len < sizeof ( *server ) ) {
1314                         DBGC ( dhcp, "DHCP %p malformed PXE server list\n",
1315                                dhcp );
1316                         break;
1317                 }
1318                 server_len = offsetof ( typeof ( *server ),
1319                                         ip[ server->num_ip ] );
1320                 if ( raw_len < server_len ) {
1321                         DBGC ( dhcp, "DHCP %p malformed PXE server list\n",
1322                                dhcp );
1323                         break;
1324                 }
1325                 if ( server->type == dhcp->pxe_type ) {
1326                         for ( i = 0 ; i < server->num_ip ; i++ )
1327                                 *(ip++) = server->ip[i];
1328                 }
1329                 server = ( ( ( void * ) server ) + server_len );
1330                 raw_len -= server_len;
1331         }
1332 }
1333
1334 /**
1335  * Start PXE Boot Server Discovery on a network device
1336  *
1337  * @v job               Job control interface
1338  * @v netdev            Network device
1339  * @v pxe_type          PXE server type
1340  * @ret rc              Return status code
1341  *
1342  * Starts PXE Boot Server Discovery on the specified network device.
1343  * If successful, the Boot Server ACK will be registered as an option
1344  * source.
1345  */
1346 int start_pxebs ( struct interface *job, struct net_device *netdev,
1347                   unsigned int pxe_type ) {
1348         struct setting pxe_discovery_control_setting =
1349                 { .tag = DHCP_PXE_DISCOVERY_CONTROL };
1350         struct setting pxe_boot_servers_setting =
1351                 { .tag = DHCP_PXE_BOOT_SERVERS };
1352         struct setting pxe_boot_server_mcast_setting =
1353                 { .tag = DHCP_PXE_BOOT_SERVER_MCAST };
1354         ssize_t pxebs_list_len;
1355         struct dhcp_session *dhcp;
1356         struct in_addr *ip;
1357         unsigned int pxe_discovery_control;
1358         int rc;
1359
1360         /* Get upper bound for PXE boot server IP address list */
1361         pxebs_list_len = fetch_raw_setting ( NULL, &pxe_boot_servers_setting,
1362                                              NULL, 0 );
1363         if ( pxebs_list_len < 0 )
1364                 pxebs_list_len = 0;
1365
1366         /* Allocate and initialise structure */
1367         dhcp = zalloc ( sizeof ( *dhcp ) + sizeof ( *ip ) /* mcast */ +
1368                         sizeof ( *ip ) /* bcast */ + pxebs_list_len +
1369                         sizeof ( *ip ) /* terminator */ );
1370         if ( ! dhcp )
1371                 return -ENOMEM;
1372         ref_init ( &dhcp->refcnt, dhcp_free );
1373         intf_init ( &dhcp->job, &dhcp_job_desc, &dhcp->refcnt );
1374         intf_init ( &dhcp->xfer, &dhcp_xfer_desc, &dhcp->refcnt );
1375         timer_init ( &dhcp->timer, dhcp_timer_expired, &dhcp->refcnt );
1376         dhcp->netdev = netdev_get ( netdev );
1377         dhcp->local.sin_family = AF_INET;
1378         fetch_ipv4_setting ( netdev_settings ( netdev ), &ip_setting,
1379                              &dhcp->local.sin_addr );
1380         dhcp->local.sin_port = htons ( BOOTPC_PORT );
1381         dhcp->pxe_type = cpu_to_le16 ( pxe_type );
1382
1383         /* Construct PXE boot server IP address lists */
1384         pxe_discovery_control =
1385                 fetch_uintz_setting ( NULL, &pxe_discovery_control_setting );
1386         ip = ( ( ( void * ) dhcp ) + sizeof ( *dhcp ) );
1387         dhcp->pxe_attempt = ip;
1388         if ( ! ( pxe_discovery_control & PXEBS_NO_MULTICAST ) ) {
1389                 fetch_ipv4_setting ( NULL, &pxe_boot_server_mcast_setting, ip);
1390                 if ( ip->s_addr )
1391                         ip++;
1392         }
1393         if ( ! ( pxe_discovery_control & PXEBS_NO_BROADCAST ) )
1394                 (ip++)->s_addr = INADDR_BROADCAST;
1395         if ( pxe_discovery_control & PXEBS_NO_UNKNOWN_SERVERS )
1396                 dhcp->pxe_accept = ip;
1397         if ( pxebs_list_len ) {
1398                 uint8_t buf[pxebs_list_len];
1399
1400                 fetch_raw_setting ( NULL, &pxe_boot_servers_setting,
1401                                     buf, sizeof ( buf ) );
1402                 pxebs_list ( dhcp, buf, sizeof ( buf ), ip );
1403         }
1404         if ( ! dhcp->pxe_attempt->s_addr ) {
1405                 DBGC ( dhcp, "DHCP %p has no PXE boot servers for type %04x\n",
1406                        dhcp, pxe_type );
1407                 rc = -EINVAL;
1408                 goto err;
1409         }
1410
1411         /* Dump out PXE server lists */
1412         DBGC ( dhcp, "DHCP %p attempting", dhcp );
1413         for ( ip = dhcp->pxe_attempt ; ip->s_addr ; ip++ )
1414                 DBGC ( dhcp, " %s", inet_ntoa ( *ip ) );
1415         DBGC ( dhcp, "\n" );
1416         if ( dhcp->pxe_accept ) {
1417                 DBGC ( dhcp, "DHCP %p accepting", dhcp );
1418                 for ( ip = dhcp->pxe_accept ; ip->s_addr ; ip++ )
1419                         DBGC ( dhcp, " %s", inet_ntoa ( *ip ) );
1420                 DBGC ( dhcp, "\n" );
1421         }
1422
1423         /* Instantiate child objects and attach to our interfaces */
1424         if ( ( rc = xfer_open_socket ( &dhcp->xfer, SOCK_DGRAM, &dhcp_peer,
1425                                   ( struct sockaddr * ) &dhcp->local ) ) != 0 )
1426                 goto err;
1427
1428         /* Enter PXEBS state */
1429         dhcp_set_state ( dhcp, &dhcp_state_pxebs );
1430
1431         /* Attach parent interface, mortalise self, and return */
1432         intf_plug_plug ( &dhcp->job, job );
1433         ref_put ( &dhcp->refcnt );
1434         return 0;
1435
1436  err:
1437         dhcp_finished ( dhcp, rc );
1438         ref_put ( &dhcp->refcnt );
1439         return rc;
1440 }
1441
1442 /** DHCP network device configurator */
1443 struct net_device_configurator dhcp_configurator __net_device_configurator = {
1444         .name = "dhcp",
1445         .start = start_dhcp,
1446 };