Document memory ownership.
[gpxe.git] / src / net / udp / dhcp.c
blob466259aed099f779ca589cbbeac1812593b924b1
1 /*
2 * Copyright (C) 2006 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.
19 #include <string.h>
20 #include <errno.h>
21 #include <assert.h>
22 #include <byteswap.h>
23 #include <gpxe/if_ether.h>
24 #include <gpxe/netdevice.h>
25 #include <gpxe/udp.h>
26 #include <gpxe/dhcp.h>
28 /** @file
30 * Dynamic Host Configuration Protocol
34 /** DHCP operation types
36 * This table maps from DHCP message types (i.e. values of the @c
37 * DHCP_MESSAGE_TYPE option) to values of the "op" field within a DHCP
38 * packet.
40 static const uint8_t dhcp_op[] = {
41 [DHCPDISCOVER] = BOOTP_REQUEST,
42 [DHCPOFFER] = BOOTP_REPLY,
43 [DHCPREQUEST] = BOOTP_REQUEST,
44 [DHCPDECLINE] = BOOTP_REQUEST,
45 [DHCPACK] = BOOTP_REPLY,
46 [DHCPNAK] = BOOTP_REPLY,
47 [DHCPRELEASE] = BOOTP_REQUEST,
48 [DHCPINFORM] = BOOTP_REQUEST,
51 /** Raw option data for options common to all DHCP requests */
52 static uint8_t dhcp_request_options_data[] = {
53 DHCP_MAX_MESSAGE_SIZE, DHCP_WORD ( ETH_MAX_MTU ),
54 DHCP_VENDOR_CLASS_ID,
55 DHCP_STRING ( 'E', 't', 'h', 'e', 'r', 'b', 'o', 'o', 't' ),
56 DHCP_PARAMETER_REQUEST_LIST,
57 DHCP_OPTION ( DHCP_SUBNET_MASK, DHCP_ROUTERS, DHCP_HOST_NAME ),
58 DHCP_END
61 /**
62 * Name a DHCP packet type
64 * @v msgtype DHCP message type
65 * @ret string DHCP mesasge type name
67 static inline const char * dhcp_msgtype_name ( unsigned int msgtype ) {
68 switch ( msgtype ) {
69 case 0: return "BOOTP"; /* Non-DHCP packet */
70 case DHCPDISCOVER: return "DHCPDISCOVER";
71 case DHCPOFFER: return "DHCPOFFER";
72 case DHCPREQUEST: return "DHCPREQUEST";
73 case DHCPDECLINE: return "DHCPDECLINE";
74 case DHCPACK: return "DHCPACK";
75 case DHCPNAK: return "DHCPNAK";
76 case DHCPRELEASE: return "DHCPRELEASE";
77 case DHCPINFORM: return "DHCPINFORM";
78 default: return "DHCP<invalid>";
82 /** Options common to all DHCP requests */
83 static struct dhcp_option_block dhcp_request_options = {
84 .data = dhcp_request_options_data,
85 .max_len = sizeof ( dhcp_request_options_data ),
86 .len = sizeof ( dhcp_request_options_data ),
89 /**
90 * Set option within DHCP packet
92 * @v dhcppkt DHCP packet
93 * @v tag DHCP option tag
94 * @v data New value for DHCP option
95 * @v len Length of value, in bytes
96 * @ret rc Return status code
98 * Sets the option within the first available options block within the
99 * DHCP packet. Option blocks are tried in the order specified by @c
100 * dhcp_option_block_fill_order.
102 * The magic options @c DHCP_EB_YIADDR and @c DHCP_EB_SIADDR are
103 * intercepted and inserted into the appropriate fixed fields within
104 * the DHCP packet. The option @c DHCP_OPTION_OVERLOAD is silently
105 * ignored, since our DHCP packet assembly method relies on always
106 * having option overloading in use.
108 static int set_dhcp_packet_option ( struct dhcp_packet *dhcppkt,
109 unsigned int tag, const void *data,
110 size_t len ) {
111 struct dhcphdr *dhcphdr = dhcppkt->dhcphdr;
112 struct dhcp_option_block *options = dhcppkt->options;
113 struct dhcp_option *option = NULL;
115 /* Special-case the magic options */
116 switch ( tag ) {
117 case DHCP_OPTION_OVERLOAD:
118 /* Hard-coded in packets we create; always ignore */
119 return 0;
120 case DHCP_EB_YIADDR:
121 memcpy ( &dhcphdr->yiaddr, data, sizeof ( dhcphdr->yiaddr ) );
122 return 0;
123 case DHCP_EB_SIADDR:
124 memcpy ( &dhcphdr->siaddr, data, sizeof ( dhcphdr->siaddr ) );
125 return 0;
126 case DHCP_MESSAGE_TYPE:
127 case DHCP_REQUESTED_ADDRESS:
128 /* These options have to be within the main options
129 * block. This doesn't seem to be required by the
130 * RFCs, but at least ISC dhcpd refuses to recognise
131 * them otherwise.
133 options = &dhcppkt->options[OPTS_MAIN];
134 break;
135 default:
136 /* Continue processing as normal */
137 break;
140 /* Set option in first available options block */
141 for ( ; options < &dhcppkt->options[NUM_OPT_BLOCKS] ; options++ ) {
142 option = set_dhcp_option ( options, tag, data, len );
143 if ( option )
144 break;
147 /* Update DHCP packet length */
148 dhcppkt->len = ( offsetof ( typeof ( *dhcppkt->dhcphdr ), options )
149 + dhcppkt->options[OPTS_MAIN].len );
151 return ( option ? 0 : -ENOSPC );
155 * Copy option into DHCP packet
157 * @v dhcppkt DHCP packet
158 * @v options DHCP option block, or NULL
159 * @v tag DHCP option tag to search for
160 * @v new_tag DHCP option tag to use for copied option
161 * @ret rc Return status code
163 * Copies a single option, if present, from the DHCP options block
164 * into a DHCP packet. The tag for the option may be changed if
165 * desired; this is required by other parts of the DHCP code.
167 * @c options may specify a single options block, or be left as NULL
168 * in order to search for the option within all registered options
169 * blocks.
171 static int copy_dhcp_packet_option ( struct dhcp_packet *dhcppkt,
172 struct dhcp_option_block *options,
173 unsigned int tag, unsigned int new_tag ) {
174 struct dhcp_option *option;
175 int rc;
177 option = find_dhcp_option ( options, tag );
178 if ( option ) {
179 if ( ( rc = set_dhcp_packet_option ( dhcppkt, new_tag,
180 &option->data,
181 option->len ) ) != 0 )
182 return rc;
184 return 0;
188 * Copy options into DHCP packet
190 * @v dhcppkt DHCP packet
191 * @v options DHCP option block, or NULL
192 * @v encapsulator Encapsulating option, or zero
193 * @ret rc Return status code
195 * Copies options with the specified encapsulator from DHCP options
196 * blocks into a DHCP packet. Most options are copied verbatim.
197 * Recognised encapsulated options fields are handled as such.
199 * @c options may specify a single options block, or be left as NULL
200 * in order to copy options from all registered options blocks.
202 static int copy_dhcp_packet_encap_options ( struct dhcp_packet *dhcppkt,
203 struct dhcp_option_block *options,
204 unsigned int encapsulator ) {
205 unsigned int subtag;
206 unsigned int tag;
207 int rc;
209 for ( subtag = DHCP_MIN_OPTION; subtag <= DHCP_MAX_OPTION; subtag++ ) {
210 tag = DHCP_ENCAP_OPT ( encapsulator, subtag );
211 switch ( tag ) {
212 case DHCP_EB_ENCAP:
213 case DHCP_VENDOR_ENCAP:
214 /* Process encapsulated options field */
215 if ( ( rc = copy_dhcp_packet_encap_options ( dhcppkt,
216 options,
217 tag)) !=0)
218 return rc;
219 break;
220 default:
221 /* Copy option to reassembled packet */
222 if ( ( rc = copy_dhcp_packet_option ( dhcppkt, options,
223 tag, tag ) ) !=0)
224 return rc;
225 break;
229 return 0;
233 * Copy options into DHCP packet
235 * @v dhcppkt DHCP packet
236 * @v options DHCP option block, or NULL
237 * @ret rc Return status code
239 * Copies options from DHCP options blocks into a DHCP packet. Most
240 * options are copied verbatim. Recognised encapsulated options
241 * fields are handled as such.
243 * @c options may specify a single options block, or be left as NULL
244 * in order to copy options from all registered options blocks.
246 static int copy_dhcp_packet_options ( struct dhcp_packet *dhcppkt,
247 struct dhcp_option_block *options ) {
248 return copy_dhcp_packet_encap_options ( dhcppkt, options, 0 );
252 * Create a DHCP packet
254 * @v dhcp DHCP session
255 * @v msgtype DHCP message type
256 * @v data Buffer for DHCP packet
257 * @v max_len Size of DHCP packet buffer
258 * @v dhcppkt DHCP packet structure to fill in
259 * @ret rc Return status code
261 * Creates a DHCP packet in the specified buffer, and fills out a @c
262 * dhcp_packet structure that can be passed to
263 * set_dhcp_packet_option() or copy_dhcp_packet_options().
265 static int create_dhcp_packet ( struct dhcp_session *dhcp, uint8_t msgtype,
266 void *data, size_t max_len,
267 struct dhcp_packet *dhcppkt ) {
268 struct dhcphdr *dhcphdr = data;
269 static const uint8_t overloading = ( DHCP_OPTION_OVERLOAD_FILE |
270 DHCP_OPTION_OVERLOAD_SNAME );
271 int rc;
273 /* Sanity check */
274 if ( max_len < sizeof ( *dhcphdr ) )
275 return -ENOSPC;
277 /* Initialise DHCP packet content */
278 memset ( dhcphdr, 0, max_len );
279 dhcphdr->xid = dhcp->xid;
280 dhcphdr->magic = htonl ( DHCP_MAGIC_COOKIE );
281 dhcphdr->htype = ntohs ( dhcp->netdev->ll_protocol->ll_proto );
282 dhcphdr->hlen = dhcp->netdev->ll_protocol->ll_addr_len;
283 memcpy ( dhcphdr->chaddr, dhcp->netdev->ll_addr, dhcphdr->hlen );
284 dhcphdr->op = dhcp_op[msgtype];
286 /* Initialise DHCP packet structure */
287 dhcppkt->dhcphdr = dhcphdr;
288 dhcppkt->max_len = max_len;
289 init_dhcp_options ( &dhcppkt->options[OPTS_MAIN], dhcphdr->options,
290 ( max_len -
291 offsetof ( typeof ( *dhcphdr ), options ) ) );
292 init_dhcp_options ( &dhcppkt->options[OPTS_FILE], dhcphdr->file,
293 sizeof ( dhcphdr->file ) );
294 init_dhcp_options ( &dhcppkt->options[OPTS_SNAME], dhcphdr->sname,
295 sizeof ( dhcphdr->sname ) );
297 /* Set DHCP_OPTION_OVERLOAD option within the main options block */
298 if ( set_dhcp_option ( &dhcppkt->options[OPTS_MAIN],
299 DHCP_OPTION_OVERLOAD, &overloading,
300 sizeof ( overloading ) ) == NULL )
301 return -ENOSPC;
303 /* Set DHCP_MESSAGE_TYPE option */
304 if ( ( rc = set_dhcp_packet_option ( dhcppkt, DHCP_MESSAGE_TYPE,
305 &msgtype,
306 sizeof ( msgtype ) ) ) != 0 )
307 return rc;
309 return 0;
313 * Calculate used length of a field containing DHCP options
315 * @v data Field containing DHCP options
316 * @v max_len Field length
317 * @ret len Used length (excluding the @c DHCP_END tag)
319 static size_t dhcp_field_len ( const void *data, size_t max_len ) {
320 struct dhcp_option_block options;
321 struct dhcp_option *end;
323 options.data = ( ( void * ) data );
324 options.len = max_len;
325 end = find_dhcp_option ( &options, DHCP_END );
326 return ( end ? ( ( ( void * ) end ) - data ) : 0 );
330 * Merge field containing DHCP options or string into DHCP options block
332 * @v options DHCP option block
333 * @v data Field containing DHCP options
334 * @v max_len Field length
335 * @v tag DHCP option tag, or 0
337 * If @c tag is non-zero, the field will be treated as a
338 * NUL-terminated string representing the value of the specified DHCP
339 * option. If @c tag is zero, the field will be treated as a block of
340 * DHCP options, and simply appended to the existing options in the
341 * option block.
343 * The caller must ensure that there is enough space in the options
344 * block to perform the merge.
346 static void merge_dhcp_field ( struct dhcp_option_block *options,
347 const void *data, size_t max_len,
348 unsigned int tag ) {
349 size_t len;
350 void *dest;
351 struct dhcp_option *end;
353 if ( tag ) {
354 set_dhcp_option ( options, tag, data, strlen ( data ) );
355 } else {
356 len = dhcp_field_len ( data, max_len );
357 dest = ( options->data + options->len - 1 );
358 memcpy ( dest, data, len );
359 options->len += len;
360 end = ( dest + len );
361 end->tag = DHCP_END;
366 * Parse DHCP packet and construct DHCP options block
368 * @v dhcphdr DHCP packet
369 * @v len Length of DHCP packet
370 * @ret options DHCP options block, or NULL
372 * Parses a received DHCP packet and canonicalises its contents into a
373 * single DHCP options block. The "file" and "sname" fields are
374 * converted into the corresponding DHCP options (@c
375 * DHCP_BOOTFILE_NAME and @c DHCP_TFTP_SERVER_NAME respectively). If
376 * these fields are used for option overloading, their options are
377 * merged in to the options block.
379 * The values of the "yiaddr" and "siaddr" fields will be stored
380 * within the options block as the magic options @c DHCP_EB_YIADDR and
381 * @c DHCP_EB_SIADDR.
383 * Note that this call allocates new memory for the constructed DHCP
384 * options block; it is the responsibility of the caller to eventually
385 * free this memory.
387 static struct dhcp_option_block * dhcp_parse ( struct dhcphdr *dhcphdr,
388 size_t len ) {
389 struct dhcp_option_block *options;
390 size_t options_len;
391 unsigned int overloading;
393 /* Sanity check */
394 if ( len < sizeof ( *dhcphdr ) )
395 return NULL;
397 /* Calculate size of resulting concatenated option block:
399 * The "options" field : length of the field minus the DHCP_END tag.
401 * The "file" field : maximum length of the field minus the
402 * NUL terminator, plus a 2-byte DHCP header or, if used for
403 * option overloading, the length of the field minus the
404 * DHCP_END tag.
406 * The "sname" field : as for the "file" field.
408 * 15 bytes for an encapsulated options field to contain the
409 * value of the "yiaddr" and "siaddr" fields
411 * 1 byte for a final terminating DHCP_END tag.
413 options_len = ( ( len - offsetof ( typeof ( *dhcphdr ), options ) ) - 1
414 + ( sizeof ( dhcphdr->file ) + 1 )
415 + ( sizeof ( dhcphdr->sname ) + 1 )
416 + 15 /* yiaddr and siaddr */
417 + 1 /* DHCP_END tag */ );
419 /* Allocate empty options block of required size */
420 options = alloc_dhcp_options ( options_len );
421 if ( ! options ) {
422 DBG ( "DHCP could not allocate %d-byte option block\n",
423 options_len );
424 return NULL;
427 /* Merge in "options" field, if this is a DHCP packet */
428 if ( dhcphdr->magic == htonl ( DHCP_MAGIC_COOKIE ) ) {
429 merge_dhcp_field ( options, dhcphdr->options,
430 ( len -
431 offsetof ( typeof (*dhcphdr), options ) ),
432 0 /* Always contains options */ );
435 /* Identify overloaded fields */
436 overloading = find_dhcp_num_option ( options, DHCP_OPTION_OVERLOAD );
438 /* Merge in "file" and "sname" fields */
439 merge_dhcp_field ( options, dhcphdr->file, sizeof ( dhcphdr->file ),
440 ( ( overloading & DHCP_OPTION_OVERLOAD_FILE ) ?
441 DHCP_BOOTFILE_NAME : 0 ) );
442 merge_dhcp_field ( options, dhcphdr->sname, sizeof ( dhcphdr->sname ),
443 ( ( overloading & DHCP_OPTION_OVERLOAD_SNAME ) ?
444 DHCP_TFTP_SERVER_NAME : 0 ) );
446 /* Set magic options for "yiaddr" and "siaddr", if present */
447 if ( dhcphdr->yiaddr.s_addr ) {
448 set_dhcp_option ( options, DHCP_EB_YIADDR,
449 &dhcphdr->yiaddr, sizeof (dhcphdr->yiaddr) );
451 if ( dhcphdr->siaddr.s_addr ) {
452 set_dhcp_option ( options, DHCP_EB_SIADDR,
453 &dhcphdr->siaddr, sizeof (dhcphdr->siaddr) );
456 assert ( options->len <= options->max_len );
458 return options;
461 /****************************************************************************
463 * DHCP to UDP interface
467 static inline struct dhcp_session *
468 udp_to_dhcp ( struct udp_connection *conn ) {
469 return container_of ( conn, struct dhcp_session, udp );
473 * Mark DHCP session as complete
475 * @v dhcp DHCP session
476 * @v rc Return status code
478 static void dhcp_done ( struct dhcp_session *dhcp, int rc ) {
479 /* Mark async operation as complete */
480 async_done ( &dhcp->aop, rc );
483 /** Address for transmitting DHCP requests */
484 static struct sockaddr sa_dhcp_server = {
485 .sa_family = AF_INET,
486 .sin = {
487 .sin_addr.s_addr = INADDR_BROADCAST,
488 .sin_port = htons ( BOOTPS_PORT ),
493 * Transmit DHCP request
495 * @v conn UDP connection
496 * @v buf Temporary data buffer
497 * @v len Length of temporary data buffer
499 static void dhcp_senddata ( struct udp_connection *conn,
500 void *buf, size_t len ) {
501 struct dhcp_session *dhcp = udp_to_dhcp ( conn );
502 struct dhcp_packet dhcppkt;
503 int rc;
505 DBG ( "Transmitting %s\n", dhcp_msgtype_name ( dhcp->state ) );
507 assert ( ( dhcp->state == DHCPDISCOVER ) ||
508 ( dhcp->state == DHCPREQUEST ) );
510 /* Create DHCP packet in temporary buffer */
511 if ( ( rc = create_dhcp_packet ( dhcp, dhcp->state, buf, len,
512 &dhcppkt ) ) != 0 ) {
513 DBG ( "Could not create DHCP packet\n" );
514 return;
517 /* Copy in options common to all requests */
518 if ( ( rc = copy_dhcp_packet_options ( &dhcppkt,
519 &dhcp_request_options ) ) != 0){
520 DBG ( "Could not set common DHCP options\n" );
521 return;
524 /* Copy any required options from previous server repsonse */
525 if ( dhcp->options ) {
526 if ( ( rc = copy_dhcp_packet_option ( &dhcppkt, dhcp->options,
527 DHCP_SERVER_IDENTIFIER,
528 DHCP_SERVER_IDENTIFIER ) ) != 0 ) {
529 DBG ( "Could not set server identifier option\n" );
530 return;
532 if ( ( rc = copy_dhcp_packet_option ( &dhcppkt, dhcp->options,
533 DHCP_EB_YIADDR,
534 DHCP_REQUESTED_ADDRESS ) ) != 0 ) {
535 DBG ( "Could not set requested address option\n" );
536 return;
540 /* Transmit the packet */
541 if ( ( rc = udp_sendto ( conn, &sa_dhcp_server,
542 dhcppkt.dhcphdr, dhcppkt.len ) ) != 0 ) {
543 DBG ( "Could not transmit UDP packet\n" );
544 return;
549 * Transmit DHCP request
551 * @v dhcp DHCP session
553 static void dhcp_send_request ( struct dhcp_session *dhcp ) {
554 start_timer ( &dhcp->timer );
555 udp_senddata ( &dhcp->udp );
559 * Handle DHCP retry timer expiry
561 * @v timer DHCP retry timer
562 * @v fail Failure indicator
564 static void dhcp_timer_expired ( struct retry_timer *timer, int fail ) {
565 struct dhcp_session *dhcp =
566 container_of ( timer, struct dhcp_session, timer );
568 if ( fail ) {
569 dhcp_done ( dhcp, -ETIMEDOUT );
570 } else {
571 dhcp_send_request ( dhcp );
576 * Receive new data
578 * @v udp UDP connection
579 * @v data Received data
580 * @v len Length of received data
582 static void dhcp_newdata ( struct udp_connection *conn,
583 void *data, size_t len ) {
584 struct dhcp_session *dhcp = udp_to_dhcp ( conn );
585 struct dhcphdr *dhcphdr = data;
586 struct dhcp_option_block *options;
587 unsigned int msgtype;
589 /* Check for matching transaction ID */
590 if ( dhcphdr->xid != dhcp->xid ) {
591 DBG ( "DHCP wrong transaction ID (wanted %08lx, got %08lx)\n",
592 ntohl ( dhcphdr->xid ), ntohl ( dhcp->xid ) );
593 return;
596 /* Parse packet and create options structure */
597 options = dhcp_parse ( dhcphdr, len );
598 if ( ! options ) {
599 DBG ( "Could not parse DHCP packet\n" );
600 return;
603 /* Determine message type */
604 msgtype = find_dhcp_num_option ( options, DHCP_MESSAGE_TYPE );
605 DBG ( "Received %s\n", dhcp_msgtype_name ( msgtype ) );
607 /* Handle DHCP reply */
608 switch ( dhcp->state ) {
609 case DHCPDISCOVER:
610 if ( msgtype != DHCPOFFER )
611 goto out_discard;
612 dhcp->state = DHCPREQUEST;
613 break;
614 case DHCPREQUEST:
615 if ( msgtype != DHCPACK )
616 goto out_discard;
617 dhcp->state = DHCPACK;
618 break;
619 default:
620 assert ( 0 );
621 goto out_discard;
624 /* Stop timer and update stored options */
625 stop_timer ( &dhcp->timer );
626 if ( dhcp->options )
627 free_dhcp_options ( dhcp->options );
628 dhcp->options = options;
630 /* Transmit next packet, or terminate session */
631 if ( dhcp->state < DHCPACK ) {
632 dhcp_send_request ( dhcp );
633 } else {
634 dhcp_done ( dhcp, 0 );
636 return;
638 out_discard:
639 free_dhcp_options ( options );
642 /** DHCP UDP operations */
643 static struct udp_operations dhcp_udp_operations = {
644 .senddata = dhcp_senddata,
645 .newdata = dhcp_newdata,
649 * Initiate DHCP on a network interface
651 * @v dhcp DHCP session
652 * @ret aop Asynchronous operation
654 * If the DHCP operation completes successfully, the
655 * dhcp_session::options field will be filled in with the resulting
656 * options block. The caller takes responsibility for eventually
657 * calling free_dhcp_options().
659 struct async_operation * start_dhcp ( struct dhcp_session *dhcp ) {
660 int rc;
662 /* Initialise DHCP session */
663 dhcp->udp.udp_op = &dhcp_udp_operations;
664 dhcp->timer.expired = dhcp_timer_expired;
665 dhcp->state = DHCPDISCOVER;
666 /* Use least significant 32 bits of link-layer address as XID */
667 memcpy ( &dhcp->xid, ( dhcp->netdev->ll_addr
668 + dhcp->netdev->ll_protocol->ll_addr_len
669 - sizeof ( dhcp->xid ) ), sizeof ( dhcp->xid ));
671 /* Bind to local port */
672 if ( ( rc = udp_open ( &dhcp->udp, htons ( BOOTPC_PORT ) ) ) != 0 ) {
673 async_done ( &dhcp->aop, rc );
674 goto out;
677 /* Proof of concept: just send a single DHCPDISCOVER */
678 dhcp_send_request ( dhcp );
680 out:
681 return &dhcp->aop;