2 * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
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.
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.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include <gpxe/dhcp.h>
26 #include <gpxe/async.h>
27 #include <gpxe/netdevice.h>
29 #include <usr/ifmgmt.h>
30 #include <usr/dhcpmgmt.h>
38 int dhcp ( struct net_device *netdev ) {
44 /* Avoid dragging in dns.o */
45 struct sockaddr_tcpip nameserver;
47 /* Avoid dragging in syslog.o */
48 struct in_addr syslogserver;
51 * Configure network device via DHCP
53 * @v netdev Network device
54 * @ret rc Return status code
56 int dhcp ( struct net_device *netdev ) {
57 static struct dhcp_option_block *dhcp_options = NULL;
58 struct dhcp_session dhcp;
59 struct in_addr address = { 0 };
60 struct in_addr netmask = { 0 };
61 struct in_addr gateway = { INADDR_NONE };
62 struct sockaddr_in *sin_nameserver;
66 /* Check we can open the interface first */
67 if ( ( rc = ifopen ( netdev ) ) != 0 )
70 /* Free up any previously-acquired options */
72 unregister_dhcp_options ( dhcp_options );
73 dhcpopt_put ( dhcp_options );
77 /* Clear any existing routing table entry */
78 del_ipv4_address ( netdev );
80 /* Issue DHCP request */
81 printf ( "DHCP (%s %s)...", netdev->name, netdev_hwaddr ( netdev ) );
82 memset ( &dhcp, 0, sizeof ( dhcp ) );
84 if ( ( rc = async_block ( &async,
85 start_dhcp ( &dhcp, &async ) ) ) != 0 ) {
86 printf ( "failed (%s)\n", strerror ( rc ) );
91 /* Store and register options */
92 dhcp_options = dhcp.options;
93 register_dhcp_options ( dhcp_options );
95 /* Retrieve IP address configuration */
96 find_dhcp_ipv4_option ( dhcp_options, DHCP_EB_YIADDR, &address );
97 find_dhcp_ipv4_option ( dhcp_options, DHCP_SUBNET_MASK, &netmask );
98 find_dhcp_ipv4_option ( dhcp_options, DHCP_ROUTERS, &gateway );
100 /* Set up new IP address configuration */
101 if ( ( rc = add_ipv4_address ( netdev, address, netmask,
103 printf ( "Could not configure %s with DHCP results: %s\n",
104 netdev->name, strerror ( rc ) );
108 /* Retrieve other DHCP options that we care about */
109 sin_nameserver = ( struct sockaddr_in * ) &nameserver;
110 sin_nameserver->sin_family = AF_INET;
111 find_dhcp_ipv4_option ( dhcp_options, DHCP_DNS_SERVERS,
112 &sin_nameserver->sin_addr );
113 find_dhcp_ipv4_option ( dhcp_options, DHCP_LOG_SERVERS,