472de5253ef87de40e3685789f72cc945fd79604
[vpp.git] / src / vnet / dhcp / client.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <vlib/vlib.h>
16 #include <vlibmemory/api.h>
17 #include <vnet/dhcp/client.h>
18 #include <vnet/dhcp/dhcp_proxy.h>
19 #include <vnet/fib/fib_table.h>
20
21 dhcp_client_main_t dhcp_client_main;
22 static u8 *format_dhcp_client_state (u8 * s, va_list * va);
23 static vlib_node_registration_t dhcp_client_process_node;
24
25 #define foreach_dhcp_sent_packet_stat           \
26 _(DISCOVER, "DHCP discover packets sent")       \
27 _(OFFER, "DHCP offer packets sent")             \
28 _(REQUEST, "DHCP request packets sent")         \
29 _(ACK, "DHCP ack packets sent")
30
31 #define foreach_dhcp_error_counter                                      \
32 _(NOT_FOR_US, "DHCP packets for other hosts, dropped")                  \
33 _(NAK, "DHCP nak packets received")                                     \
34 _(NON_OFFER_DISCOVER, "DHCP non-offer packets in discover state")       \
35 _(ODDBALL, "DHCP non-ack, non-offer packets received")                  \
36 _(BOUND, "DHCP bind success")
37
38 typedef enum
39 {
40 #define _(sym,str) DHCP_STAT_##sym,
41   foreach_dhcp_sent_packet_stat foreach_dhcp_error_counter
42 #undef _
43     DHCP_STAT_UNKNOWN,
44   DHCP_STAT_N_STAT,
45 } sample_error_t;
46
47 static char *dhcp_client_process_stat_strings[] = {
48 #define _(sym,string) string,
49   foreach_dhcp_sent_packet_stat foreach_dhcp_error_counter
50 #undef _
51     "DHCP unknown packets sent",
52 };
53
54 static void
55 dhcp_client_acquire_address (dhcp_client_main_t * dcm, dhcp_client_t * c)
56 {
57   /*
58    * Install any/all info gleaned from dhcp, right here
59    */
60   ip4_add_del_interface_address (dcm->vlib_main, c->sw_if_index,
61                                  (void *) &c->leased_address,
62                                  c->subnet_mask_width, 0 /*is_del */ );
63 }
64
65 static void
66 dhcp_client_release_address (dhcp_client_main_t * dcm, dhcp_client_t * c)
67 {
68   /*
69    * Remove any/all info gleaned from dhcp, right here. Caller(s)
70    * have not wiped out the info yet.
71    */
72
73   ip4_add_del_interface_address (dcm->vlib_main, c->sw_if_index,
74                                  (void *) &c->leased_address,
75                                  c->subnet_mask_width, 1 /*is_del */ );
76 }
77
78 static void
79 dhcp_client_proc_callback (uword * client_index)
80 {
81   vlib_main_t *vm = vlib_get_main ();
82   ASSERT (vlib_get_thread_index () == 0);
83   vlib_process_signal_event (vm, dhcp_client_process_node.index,
84                              EVENT_DHCP_CLIENT_WAKEUP, *client_index);
85 }
86
87 static void
88 dhcp_client_addr_callback (dhcp_client_t * c)
89 {
90   dhcp_client_main_t *dcm = &dhcp_client_main;
91
92   /* disable the feature */
93   vnet_feature_enable_disable ("ip4-unicast",
94                                "ip4-dhcp-client-detect",
95                                c->sw_if_index, 0 /* disable */ , 0, 0);
96   c->client_detect_feature_enabled = 0;
97
98   /* if renewing the lease, the address and route have already been added */
99   if (c->state == DHCP_BOUND)
100     return;
101
102   /* add the address to the interface */
103   dhcp_client_acquire_address (dcm, c);
104
105   /*
106    * Configure default IP route:
107    */
108   if (c->router_address.as_u32)
109     {
110       fib_prefix_t all_0s = {
111         .fp_len = 0,
112         .fp_addr.ip4.as_u32 = 0x0,
113         .fp_proto = FIB_PROTOCOL_IP4,
114       };
115       ip46_address_t nh = {
116         .ip4 = c->router_address,
117       };
118
119       /* *INDENT-OFF* */
120       fib_table_entry_path_add (
121         fib_table_get_index_for_sw_if_index (
122           FIB_PROTOCOL_IP4,
123           c->sw_if_index),
124           &all_0s,
125           FIB_SOURCE_DHCP,
126           FIB_ENTRY_FLAG_NONE,
127           DPO_PROTO_IP4,
128           &nh, c->sw_if_index,
129           ~0, 1, NULL,  // no label stack
130           FIB_ROUTE_PATH_FLAG_NONE);
131       /* *INDENT-ON* */
132     }
133   if (c->dhcp_server.as_u32)
134     {
135       ip46_address_t dst = {
136         .ip4 = c->dhcp_server,
137       };
138       c->ai_ucast = adj_nbr_add_or_lock (FIB_PROTOCOL_IP4,
139                                          VNET_LINK_IP4, &dst, c->sw_if_index);
140     }
141
142   /*
143    * Call the user's event callback to report DHCP information
144    */
145   if (c->event_callback)
146     c->event_callback (c->client_index, c);
147 }
148
149 /*
150  * dhcp_client_for_us - server-to-client callback.
151  * Called from proxy_node.c:dhcp_proxy_to_client_input().
152  * This function first decides that the packet in question is
153  * actually for the dhcp client code in case we're also acting as
154  * a dhcp proxy. Ay caramba, what a folly!
155  */
156 int
157 dhcp_client_for_us (u32 bi, vlib_buffer_t * b,
158                     ip4_header_t * ip,
159                     udp_header_t * udp, dhcp_header_t * dhcp)
160 {
161   dhcp_client_main_t *dcm = &dhcp_client_main;
162   vlib_main_t *vm = dcm->vlib_main;
163   dhcp_client_t *c;
164   uword *p;
165   f64 now = vlib_time_now (dcm->vlib_main);
166   u8 dhcp_message_type = 0;
167   dhcp_option_t *o;
168
169   /*
170    * Doing dhcp client on this interface?
171    * Presumably we will always receive dhcp clnt for-us pkts on
172    * the interface that's asking for an address.
173    */
174   p = hash_get (dcm->client_by_sw_if_index,
175                 vnet_buffer (b)->sw_if_index[VLIB_RX]);
176   if (p == 0)
177     return 0;                   /* no */
178
179   c = pool_elt_at_index (dcm->clients, p[0]);
180
181   /* Mixing dhcp relay and dhcp proxy? DGMS... */
182   if (c->state == DHCP_BOUND && c->retry_count == 0)
183     return 0;
184
185   /* Packet not for us? Turf it... */
186   if (memcmp (dhcp->client_hardware_address, c->client_hardware_address,
187               sizeof (c->client_hardware_address)))
188     {
189       vlib_node_increment_counter (vm, dhcp_client_process_node.index,
190                                    DHCP_STAT_NOT_FOR_US, 1);
191       return 0;
192     }
193
194   /* parse through the packet, learn what we can */
195   if (dhcp->your_ip_address.as_u32)
196     c->leased_address.as_u32 = dhcp->your_ip_address.as_u32;
197
198   c->dhcp_server.as_u32 = dhcp->server_ip_address.as_u32;
199
200   o = (dhcp_option_t *) dhcp->options;
201
202   while (o->option != 0xFF /* end of options */  &&
203          (u8 *) o < (b->data + b->current_data + b->current_length))
204     {
205       switch (o->option)
206         {
207         case 53:                /* dhcp message type */
208           dhcp_message_type = o->data[0];
209           break;
210
211         case 51:                /* lease time */
212           {
213             u32 lease_time_in_seconds =
214               clib_host_to_net_u32 (o->data_as_u32[0]);
215             // for debug: lease_time_in_seconds = 20; /*$$$$*/
216             c->lease_expires = now + (f64) lease_time_in_seconds;
217             c->lease_lifetime = lease_time_in_seconds;
218             /* Set a sensible default, in case we don't get opt 58 */
219             c->lease_renewal_interval = lease_time_in_seconds / 2;
220           }
221           break;
222
223         case 58:                /* lease renew time in seconds */
224           {
225             u32 lease_renew_time_in_seconds =
226               clib_host_to_net_u32 (o->data_as_u32[0]);
227             c->lease_renewal_interval = lease_renew_time_in_seconds;
228           }
229           break;
230
231         case 54:                /* dhcp server address */
232           c->dhcp_server.as_u32 = o->data_as_u32[0];
233           break;
234
235         case 1:         /* subnet mask */
236           {
237             u32 subnet_mask = clib_host_to_net_u32 (o->data_as_u32[0]);
238             c->subnet_mask_width = count_set_bits (subnet_mask);
239           }
240           break;
241         case 3:         /* router address */
242           {
243             u32 router_address = o->data_as_u32[0];
244             c->router_address.as_u32 = router_address;
245           }
246           break;
247         case 6:         /* domain server address */
248           {
249             vec_free (c->domain_server_address);
250             vec_validate (c->domain_server_address,
251                           o->length / sizeof (ip4_address_t) - 1);
252             clib_memcpy (c->domain_server_address, o->data, o->length);
253           }
254           break;
255         case 12:                /* hostname */
256           {
257             /* Replace the existing hostname if necessary */
258             vec_free (c->hostname);
259             vec_validate (c->hostname, o->length - 1);
260             clib_memcpy (c->hostname, o->data, o->length);
261           }
262           break;
263
264           /* $$$$ Your message in this space, parse more options */
265         default:
266           break;
267         }
268
269       o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
270     }
271
272   switch (c->state)
273     {
274     case DHCP_DISCOVER:
275       if (dhcp_message_type != DHCP_PACKET_OFFER)
276         {
277           vlib_node_increment_counter (vm, dhcp_client_process_node.index,
278                                        DHCP_STAT_NON_OFFER_DISCOVER, 1);
279           c->next_transmit = now + 5.0;
280           break;
281         }
282
283       /* Received an offer, go send a request */
284       c->state = DHCP_REQUEST;
285       c->retry_count = 0;
286       c->next_transmit = 0;     /* send right now... */
287       /* Poke the client process, which will send the request */
288       uword client_id = c - dcm->clients;
289       vl_api_rpc_call_main_thread (dhcp_client_proc_callback,
290                                    (u8 *) & client_id, sizeof (uword));
291       break;
292
293     case DHCP_BOUND:
294     case DHCP_REQUEST:
295       if (dhcp_message_type == DHCP_PACKET_NAK)
296         {
297           vlib_node_increment_counter (vm, dhcp_client_process_node.index,
298                                        DHCP_STAT_NAK, 1);
299           /* Probably never happens in bound state, but anyhow... */
300           if (c->state == DHCP_BOUND)
301             {
302               ip4_add_del_interface_address (dcm->vlib_main, c->sw_if_index,
303                                              (void *) &c->leased_address,
304                                              c->subnet_mask_width,
305                                              1 /*is_del */ );
306               vnet_feature_enable_disable ("ip4-unicast",
307                                            "ip4-dhcp-client-detect",
308                                            c->sw_if_index, 1 /* enable */ ,
309                                            0, 0);
310               c->client_detect_feature_enabled = 1;
311             }
312           /* Wipe out any memory of the address we had... */
313           c->state = DHCP_DISCOVER;
314           c->next_transmit = now;
315           c->retry_count = 0;
316           c->leased_address.as_u32 = 0;
317           c->subnet_mask_width = 0;
318           c->router_address.as_u32 = 0;
319           c->lease_renewal_interval = 0;
320           c->dhcp_server.as_u32 = 0;
321           vec_free (c->domain_server_address);
322           break;
323         }
324
325       if (dhcp_message_type != DHCP_PACKET_ACK &&
326           dhcp_message_type != DHCP_PACKET_OFFER)
327         {
328           vlib_node_increment_counter (vm, dhcp_client_process_node.index,
329                                        DHCP_STAT_NON_OFFER_DISCOVER, 1);
330           clib_warning ("sw_if_index %d state %U message type %d",
331                         c->sw_if_index, format_dhcp_client_state,
332                         c->state, dhcp_message_type);
333           c->next_transmit = now + 5.0;
334           break;
335         }
336       /* OK, we own the address (etc), add to the routing table(s) */
337       vl_api_rpc_call_main_thread (dhcp_client_addr_callback,
338                                    (u8 *) c, sizeof (*c));
339
340       c->state = DHCP_BOUND;
341       c->retry_count = 0;
342       c->next_transmit = now + (f64) c->lease_renewal_interval;
343       c->lease_expires = now + (f64) c->lease_lifetime;
344       vlib_node_increment_counter (vm, dhcp_client_process_node.index,
345                                    DHCP_STAT_BOUND, 1);
346       break;
347
348     default:
349       clib_warning ("client %d bogus state %d", c - dcm->clients, c->state);
350       break;
351     }
352
353   /* drop the pkt, return 1 */
354   vlib_buffer_free (vm, &bi, 1);
355   return 1;
356 }
357
358 static void
359 send_dhcp_pkt (dhcp_client_main_t * dcm, dhcp_client_t * c,
360                dhcp_packet_type_t type, int is_broadcast)
361 {
362   vlib_main_t *vm = dcm->vlib_main;
363   vnet_main_t *vnm = dcm->vnet_main;
364   vnet_hw_interface_t *hw = vnet_get_sup_hw_interface (vnm, c->sw_if_index);
365   vnet_sw_interface_t *sup_sw
366     = vnet_get_sup_sw_interface (vnm, c->sw_if_index);
367   vnet_sw_interface_t *sw = vnet_get_sw_interface (vnm, c->sw_if_index);
368   vlib_buffer_t *b;
369   u32 bi;
370   ip4_header_t *ip;
371   udp_header_t *udp;
372   dhcp_header_t *dhcp;
373   u32 *to_next;
374   vlib_frame_t *f;
375   dhcp_option_t *o;
376   u16 udp_length, ip_length;
377   u32 counter_index, node_index;
378
379   /* Interface(s) down? */
380   if ((hw->flags & VNET_HW_INTERFACE_FLAG_LINK_UP) == 0)
381     return;
382   if ((sup_sw->flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) == 0)
383     return;
384   if ((sw->flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) == 0)
385     return;
386
387   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
388     {
389       clib_warning ("buffer allocation failure");
390       c->next_transmit = 0;
391       return;
392     }
393
394   /* Build a dhcpv4 pkt from whole cloth */
395   b = vlib_get_buffer (vm, bi);
396   VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b);
397
398   ASSERT (b->current_data == 0);
399
400   vnet_buffer (b)->sw_if_index[VLIB_RX] = c->sw_if_index;
401
402   if (is_broadcast)
403     {
404       node_index = ip4_rewrite_node.index;
405       vnet_buffer (b)->ip.adj_index[VLIB_TX] = c->ai_bcast;
406     }
407   else
408     {
409       ip_adjacency_t *adj = adj_get (c->ai_ucast);
410
411       if (IP_LOOKUP_NEXT_ARP == adj->lookup_next_index)
412         node_index = ip4_arp_node.index;
413       else
414         node_index = ip4_rewrite_node.index;
415       vnet_buffer (b)->ip.adj_index[VLIB_TX] = c->ai_ucast;
416     }
417
418   /* Enqueue the packet right now */
419   f = vlib_get_frame_to_node (vm, node_index);
420   to_next = vlib_frame_vector_args (f);
421   to_next[0] = bi;
422   f->n_vectors = 1;
423   vlib_put_frame_to_node (vm, node_index, f);
424
425   /* build the headers */
426   ip = vlib_buffer_get_current (b);
427   udp = (udp_header_t *) (ip + 1);
428   dhcp = (dhcp_header_t *) (udp + 1);
429
430   /* $$$ optimize, maybe */
431   clib_memset (ip, 0, sizeof (*ip) + sizeof (*udp) + sizeof (*dhcp));
432
433   ip->ip_version_and_header_length = 0x45;
434   ip->ttl = 128;
435   ip->protocol = IP_PROTOCOL_UDP;
436
437   if (is_broadcast)
438     {
439       /* src = 0.0.0.0, dst = 255.255.255.255 */
440       ip->dst_address.as_u32 = ~0;
441     }
442   else
443     {
444       /* Renewing an active lease, plain old ip4 src/dst */
445       ip->src_address.as_u32 = c->leased_address.as_u32;
446       ip->dst_address.as_u32 = c->dhcp_server.as_u32;
447     }
448
449   udp->src_port = clib_host_to_net_u16 (UDP_DST_PORT_dhcp_to_client);
450   udp->dst_port = clib_host_to_net_u16 (UDP_DST_PORT_dhcp_to_server);
451
452   /* Send the interface MAC address */
453   clib_memcpy (dhcp->client_hardware_address,
454                vnet_sw_interface_get_hw_address (vnm, c->sw_if_index), 6);
455
456   /* And remember it for rx-packet-for-us checking */
457   clib_memcpy (c->client_hardware_address, dhcp->client_hardware_address,
458                sizeof (c->client_hardware_address));
459
460   /* Lease renewal, set up client_ip_address */
461   if (is_broadcast == 0)
462     dhcp->client_ip_address.as_u32 = c->leased_address.as_u32;
463
464   dhcp->opcode = 1;             /* request, all we send */
465   dhcp->hardware_type = 1;      /* ethernet */
466   dhcp->hardware_address_length = 6;
467   dhcp->transaction_identifier = c->transaction_id;
468   dhcp->flags =
469     clib_host_to_net_u16 (is_broadcast && c->set_broadcast_flag ?
470                           DHCP_FLAG_BROADCAST : 0);
471   dhcp->magic_cookie.as_u32 = DHCP_MAGIC;
472
473   o = (dhcp_option_t *) dhcp->options;
474
475   /* Send option 53, the DHCP message type */
476   o->option = DHCP_PACKET_OPTION_MSG_TYPE;
477   o->length = 1;
478   o->data[0] = type;
479   o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
480
481   /* Send option 57, max msg length */
482   if (0 /* not needed, apparently */ )
483     {
484       o->option = 57;
485       o->length = 2;
486       {
487         u16 *o2 = (u16 *) o->data;
488         *o2 = clib_host_to_net_u16 (1152);
489         o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
490       }
491     }
492
493   /*
494    * If server ip address is available with non-zero value,
495    * option 54 (DHCP Server Identifier) is sent.
496    */
497   if (c->dhcp_server.as_u32)
498     {
499       o->option = 54;
500       o->length = 4;
501       clib_memcpy (o->data, &c->dhcp_server.as_u32, 4);
502       o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
503     }
504
505   /* send option 50, requested IP address */
506   if (c->leased_address.as_u32)
507     {
508       o->option = 50;
509       o->length = 4;
510       clib_memcpy (o->data, &c->leased_address.as_u32, 4);
511       o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
512     }
513
514   /* send option 12, host name */
515   if (vec_len (c->hostname))
516     {
517       o->option = 12;
518       o->length = vec_len (c->hostname);
519       clib_memcpy (o->data, c->hostname, vec_len (c->hostname));
520       o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
521     }
522
523   /* send option 61, client_id */
524   if (vec_len (c->client_identifier))
525     {
526       o->option = 61;
527       o->length = vec_len (c->client_identifier);
528       clib_memcpy (o->data, c->client_identifier,
529                    vec_len (c->client_identifier));
530       o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
531     }
532
533   /* $$ maybe send the client s/w version if anyone cares */
534
535   /*
536    * send option 55, parameter request list
537    * The current list - see below, matches the Linux dhcp client's list
538    * Any specific dhcp server config and/or dhcp server may or may
539    * not yield specific options.
540    */
541   o->option = 55;
542   o->length = vec_len (c->option_55_data);
543   clib_memcpy (o->data, c->option_55_data, vec_len (c->option_55_data));
544   o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
545
546   /* End of list */
547   o->option = 0xff;
548   o->length = 0;
549   o++;
550
551   b->current_length = ((u8 *) o) - b->data;
552
553   /* fix ip length, checksum and udp length */
554   ip_length = vlib_buffer_length_in_chain (vm, b);
555
556   ip->length = clib_host_to_net_u16 (ip_length);
557   ip->checksum = ip4_header_checksum (ip);
558
559   udp_length = ip_length - (sizeof (*ip));
560   udp->length = clib_host_to_net_u16 (udp_length);
561
562   switch (type)
563     {
564 #define _(a,b) case DHCP_PACKET_##a: {counter_index = DHCP_STAT_##a; break;}
565       foreach_dhcp_sent_packet_stat
566 #undef _
567     default:
568       counter_index = DHCP_STAT_UNKNOWN;
569       break;
570     }
571
572   vlib_node_increment_counter (vm, dhcp_client_process_node.index,
573                                counter_index, 1);
574 }
575
576 static int
577 dhcp_discover_state (dhcp_client_main_t * dcm, dhcp_client_t * c, f64 now)
578 {
579   /*
580    * State machine "DISCOVER" state. Send a dhcp discover packet,
581    * eventually back off the retry rate.
582    */
583
584   if (c->client_detect_feature_enabled == 0)
585     {
586       vnet_feature_enable_disable ("ip4-unicast",
587                                    "ip4-dhcp-client-detect",
588                                    c->sw_if_index, 1 /* enable */ , 0, 0);
589       c->client_detect_feature_enabled = 1;
590     }
591
592   send_dhcp_pkt (dcm, c, DHCP_PACKET_DISCOVER, 1 /* is_broadcast */ );
593
594   c->retry_count++;
595   if (c->retry_count > 10)
596     c->next_transmit = now + 5.0;
597   else
598     c->next_transmit = now + 1.0;
599   return 0;
600 }
601
602 static int
603 dhcp_request_state (dhcp_client_main_t * dcm, dhcp_client_t * c, f64 now)
604 {
605   /*
606    * State machine "REQUEST" state. Send a dhcp request packet,
607    * eventually drop back to the discover state.
608    */
609   send_dhcp_pkt (dcm, c, DHCP_PACKET_REQUEST, 1 /* is_broadcast */ );
610
611   c->retry_count++;
612   if (c->retry_count > 7 /* lucky you */ )
613     {
614       c->state = DHCP_DISCOVER;
615       c->next_transmit = now;
616       c->retry_count = 0;
617       return 1;
618     }
619   c->next_transmit = now + 1.0;
620   return 0;
621 }
622
623 static int
624 dhcp_bound_state (dhcp_client_main_t * dcm, dhcp_client_t * c, f64 now)
625 {
626   /*
627    * State machine "BOUND" state. Send a dhcp request packet to renew
628    * the lease.
629    * Eventually, when the lease expires, forget the dhcp data
630    * and go back to the stone age.
631    */
632
633   /*
634    * We disable the client detect feature when we bind a
635    * DHCP address. Turn it back on again on first renew attempt.
636    * Otherwise, if the DHCP server replies we'll never see it.
637    */
638   if (c->client_detect_feature_enabled == 0)
639     {
640       vnet_feature_enable_disable ("ip4-unicast",
641                                    "ip4-dhcp-client-detect",
642                                    c->sw_if_index, 1 /* enable */ , 0, 0);
643       c->client_detect_feature_enabled = 1;
644     }
645
646   send_dhcp_pkt (dcm, c, DHCP_PACKET_REQUEST, 0 /* is_broadcast */ );
647
648   c->retry_count++;
649   if (c->retry_count > 10)
650     c->next_transmit = now + 5.0;
651   else
652     c->next_transmit = now + 1.0;
653
654   if (now > c->lease_expires)
655     {
656       /* Remove the default route */
657       if (c->router_address.as_u32)
658         {
659           fib_prefix_t all_0s = {
660             .fp_len = 0,
661             .fp_addr.ip4.as_u32 = 0x0,
662             .fp_proto = FIB_PROTOCOL_IP4,
663           };
664           ip46_address_t nh = {
665             .ip4 = c->router_address,
666           };
667
668           fib_table_entry_path_remove (fib_table_get_index_for_sw_if_index
669                                        (FIB_PROTOCOL_IP4, c->sw_if_index),
670                                        &all_0s, FIB_SOURCE_DHCP,
671                                        DPO_PROTO_IP4, &nh, c->sw_if_index, ~0,
672                                        1, FIB_ROUTE_PATH_FLAG_NONE);
673         }
674       /* Remove the interface address */
675       dhcp_client_release_address (dcm, c);
676       c->state = DHCP_DISCOVER;
677       c->next_transmit = now;
678       c->retry_count = 0;
679       /* Wipe out any memory of the address we had... */
680       c->leased_address.as_u32 = 0;
681       c->subnet_mask_width = 0;
682       c->router_address.as_u32 = 0;
683       c->lease_renewal_interval = 0;
684       c->dhcp_server.as_u32 = 0;
685       return 1;
686     }
687   return 0;
688 }
689
690 static f64
691 dhcp_client_sm (f64 now, f64 timeout, uword pool_index)
692 {
693   dhcp_client_main_t *dcm = &dhcp_client_main;
694   dhcp_client_t *c;
695
696   /* deleted, pooched, yadda yadda yadda */
697   if (pool_is_free_index (dcm->clients, pool_index))
698     return timeout;
699
700   c = pool_elt_at_index (dcm->clients, pool_index);
701
702   /* Time for us to do something with this client? */
703   if (now < c->next_transmit)
704     return timeout;
705
706 again:
707   switch (c->state)
708     {
709     case DHCP_DISCOVER: /* send a discover */
710       if (dhcp_discover_state (dcm, c, now))
711         goto again;
712       break;
713
714     case DHCP_REQUEST:          /* send a request */
715       if (dhcp_request_state (dcm, c, now))
716         goto again;
717       break;
718
719     case DHCP_BOUND:            /* bound, renew needed? */
720       if (dhcp_bound_state (dcm, c, now))
721         goto again;
722       break;
723
724     default:
725       clib_warning ("dhcp client %d bogus state %d",
726                     c - dcm->clients, c->state);
727       break;
728     }
729
730   if (c->next_transmit < now + timeout)
731     return c->next_transmit - now;
732
733   return timeout;
734 }
735
736 static uword
737 dhcp_client_process (vlib_main_t * vm,
738                      vlib_node_runtime_t * rt, vlib_frame_t * f)
739 {
740   f64 timeout = 100.0;
741   f64 now;
742   uword event_type;
743   uword *event_data = 0;
744   dhcp_client_main_t *dcm = &dhcp_client_main;
745   dhcp_client_t *c;
746   int i;
747
748   while (1)
749     {
750       vlib_process_wait_for_event_or_clock (vm, timeout);
751
752       event_type = vlib_process_get_events (vm, &event_data);
753
754       now = vlib_time_now (vm);
755
756       switch (event_type)
757         {
758         case EVENT_DHCP_CLIENT_WAKEUP:
759           for (i = 0; i < vec_len (event_data); i++)
760             timeout = dhcp_client_sm (now, timeout, event_data[i]);
761           break;
762
763         case ~0:
764           /* *INDENT-OFF* */
765           pool_foreach (c, dcm->clients,
766           ({
767             timeout = dhcp_client_sm (now, timeout,
768                                       (uword) (c - dcm->clients));
769           }));
770           /* *INDENT-ON* */
771           if (pool_elts (dcm->clients) == 0)
772             timeout = 100.0;
773           break;
774         }
775
776       vec_reset_length (event_data);
777     }
778
779   /* NOTREACHED */
780   return 0;
781 }
782
783 /* *INDENT-OFF* */
784 VLIB_REGISTER_NODE (dhcp_client_process_node,static) = {
785     .function = dhcp_client_process,
786     .type = VLIB_NODE_TYPE_PROCESS,
787     .name = "dhcp-client-process",
788     .process_log2_n_stack_bytes = 16,
789     .n_errors = ARRAY_LEN(dhcp_client_process_stat_strings),
790     .error_strings = dhcp_client_process_stat_strings,
791 };
792 /* *INDENT-ON* */
793
794 static u8 *
795 format_dhcp_client_state (u8 * s, va_list * va)
796 {
797   dhcp_client_state_t state = va_arg (*va, dhcp_client_state_t);
798   char *str = "BOGUS!";
799
800   switch (state)
801     {
802 #define _(a)                                    \
803     case a:                                     \
804       str = #a;                                 \
805         break;
806       foreach_dhcp_client_state;
807 #undef _
808     default:
809       break;
810     }
811
812   s = format (s, "%s", str);
813   return s;
814 }
815
816 static u8 *
817 format_dhcp_client (u8 * s, va_list * va)
818 {
819   dhcp_client_main_t *dcm = va_arg (*va, dhcp_client_main_t *);
820   dhcp_client_t *c = va_arg (*va, dhcp_client_t *);
821   int verbose = va_arg (*va, int);
822   ip4_address_t *addr;
823
824   s = format (s, "[%d] %U state %U ", c - dcm->clients,
825               format_vnet_sw_if_index_name, dcm->vnet_main, c->sw_if_index,
826               format_dhcp_client_state, c->state);
827
828   if (c->leased_address.as_u32)
829     {
830       s = format (s, "addr %U/%d gw %U",
831                   format_ip4_address, &c->leased_address,
832                   c->subnet_mask_width, format_ip4_address,
833                   &c->router_address);
834
835       vec_foreach (addr, c->domain_server_address)
836         s = format (s, " dns %U", format_ip4_address, addr);
837     }
838   else
839     {
840       s = format (s, "no address\n");
841     }
842
843   if (verbose)
844     {
845       s =
846         format (s,
847                 "\n lease: lifetime:%d renewal-interval:%d expires:%.2f (now:%.2f)",
848                 c->lease_lifetime, c->lease_renewal_interval,
849                 c->lease_expires, vlib_time_now (dcm->vlib_main));
850       s =
851         format (s, "\n retry-count:%d, next-xmt:%.2f", c->retry_count,
852                 c->next_transmit);
853       s =
854         format (s, "\n adjacencies:[unicast:%d broadcast:%d]", c->ai_ucast,
855                 c->ai_bcast);
856     }
857   return s;
858 }
859
860 static clib_error_t *
861 show_dhcp_client_command_fn (vlib_main_t * vm,
862                              unformat_input_t * input,
863                              vlib_cli_command_t * cmd)
864 {
865   dhcp_client_main_t *dcm = &dhcp_client_main;
866   dhcp_client_t *c;
867   int verbose = 0;
868   u32 sw_if_index = ~0;
869   uword *p;
870
871   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
872     {
873       if (unformat (input, "intfc %U",
874                     unformat_vnet_sw_interface, dcm->vnet_main, &sw_if_index))
875         ;
876       else if (unformat (input, "verbose"))
877         verbose = 1;
878       else
879         break;
880     }
881
882   if (sw_if_index != ~0)
883     {
884       p = hash_get (dcm->client_by_sw_if_index, sw_if_index);
885       if (p == 0)
886         return clib_error_return (0, "dhcp client not configured");
887       c = pool_elt_at_index (dcm->clients, p[0]);
888       vlib_cli_output (vm, "%U", format_dhcp_client, dcm, c, verbose);
889       return 0;
890     }
891
892   /* *INDENT-OFF* */
893   pool_foreach (c, dcm->clients,
894   ({
895     vlib_cli_output (vm, "%U",
896                      format_dhcp_client, dcm,
897                      c, verbose);
898   }));
899   /* *INDENT-ON* */
900
901   return 0;
902 }
903
904 /* *INDENT-OFF* */
905 VLIB_CLI_COMMAND (show_dhcp_client_command, static) = {
906   .path = "show dhcp client",
907   .short_help = "show dhcp client [intfc <intfc>][verbose]",
908   .function = show_dhcp_client_command_fn,
909 };
910 /* *INDENT-ON* */
911
912
913 int
914 dhcp_client_add_del (dhcp_client_add_del_args_t * a)
915 {
916   dhcp_client_main_t *dcm = &dhcp_client_main;
917   vlib_main_t *vm = dcm->vlib_main;
918   dhcp_client_t *c;
919   uword *p;
920   fib_prefix_t all_0s = {
921     .fp_len = 0,
922     .fp_addr.ip4.as_u32 = 0x0,
923     .fp_proto = FIB_PROTOCOL_IP4,
924   };
925
926   p = hash_get (dcm->client_by_sw_if_index, a->sw_if_index);
927
928   if ((p && a->is_add) || (!p && a->is_add == 0))
929     return VNET_API_ERROR_INVALID_VALUE;
930
931   if (a->is_add)
932     {
933       dhcp_maybe_register_udp_ports (DHCP_PORT_REG_CLIENT);
934       pool_get (dcm->clients, c);
935       clib_memset (c, 0, sizeof (*c));
936       c->state = DHCP_DISCOVER;
937       c->sw_if_index = a->sw_if_index;
938       c->client_index = a->client_index;
939       c->pid = a->pid;
940       c->event_callback = a->event_callback;
941       c->option_55_data = a->option_55_data;
942       c->hostname = a->hostname;
943       c->client_identifier = a->client_identifier;
944       c->set_broadcast_flag = a->set_broadcast_flag;
945       c->ai_ucast = ADJ_INDEX_INVALID;
946       c->ai_bcast = adj_nbr_add_or_lock (FIB_PROTOCOL_IP4,
947                                          VNET_LINK_IP4,
948                                          &ADJ_BCAST_ADDR, c->sw_if_index);
949
950       do
951         {
952           c->transaction_id = random_u32 (&dcm->seed);
953         }
954       while (c->transaction_id == 0);
955
956       hash_set (dcm->client_by_sw_if_index, a->sw_if_index, c - dcm->clients);
957
958       /*
959        * In order to accept any OFFER, whether broadcasted or unicasted, we
960        * need to configure the dhcp-client-detect feature as an input feature
961        * so the DHCP OFFER is sent to the ip4-local node. Without this a
962        * broadcasted OFFER hits the 255.255.255.255/32 address and a unicast
963        * hits 0.0.0.0/0 both of which default to drop and the latter may forward
964        * of box - not what we want. Nor to we want to change these route for
965        * all interfaces in this table
966        */
967       vnet_feature_enable_disable ("ip4-unicast",
968                                    "ip4-dhcp-client-detect",
969                                    c->sw_if_index, 1 /* enable */ , 0, 0);
970       c->client_detect_feature_enabled = 1;
971
972       vlib_process_signal_event (vm, dhcp_client_process_node.index,
973                                  EVENT_DHCP_CLIENT_WAKEUP, c - dcm->clients);
974     }
975   else
976     {
977       c = pool_elt_at_index (dcm->clients, p[0]);
978
979       if (c->router_address.as_u32)
980         {
981           ip46_address_t nh = {
982             .ip4 = c->router_address,
983           };
984
985           fib_table_entry_path_remove (fib_table_get_index_for_sw_if_index
986                                        (FIB_PROTOCOL_IP4, c->sw_if_index),
987                                        &all_0s, FIB_SOURCE_DHCP,
988                                        DPO_PROTO_IP4, &nh, c->sw_if_index, ~0,
989                                        1, FIB_ROUTE_PATH_FLAG_NONE);
990         }
991       dhcp_client_release_address (dcm, c);
992
993       adj_unlock (c->ai_ucast);
994       adj_unlock (c->ai_bcast);
995
996       vec_free (c->domain_server_address);
997       vec_free (c->option_55_data);
998       vec_free (c->hostname);
999       vec_free (c->client_identifier);
1000       hash_unset (dcm->client_by_sw_if_index, c->sw_if_index);
1001       pool_put (dcm->clients, c);
1002     }
1003   return 0;
1004 }
1005
1006 int
1007 dhcp_client_config (u32 is_add,
1008                     u32 client_index,
1009                     vlib_main_t * vm,
1010                     u32 sw_if_index,
1011                     u8 * hostname,
1012                     u8 * client_id,
1013                     dhcp_event_cb_t event_callback,
1014                     u8 set_broadcast_flag, u32 pid)
1015 {
1016   dhcp_client_add_del_args_t _a, *a = &_a;
1017   int rv;
1018
1019   clib_memset (a, 0, sizeof (*a));
1020   a->is_add = is_add;
1021   a->sw_if_index = sw_if_index;
1022   a->client_index = client_index;
1023   a->pid = pid;
1024   a->event_callback = event_callback;
1025   a->set_broadcast_flag = set_broadcast_flag;
1026   vec_validate (a->hostname, strlen ((char *) hostname) - 1);
1027   strncpy ((char *) a->hostname, (char *) hostname, vec_len (a->hostname));
1028   vec_validate (a->client_identifier, strlen ((char *) client_id) - 1);
1029   strncpy ((char *) a->client_identifier, (char *) client_id,
1030            vec_len (a->client_identifier));
1031
1032   /*
1033    * Option 55 request list. These data precisely match
1034    * the Ubuntu dhcp client. YMMV.
1035    */
1036
1037   /* Subnet Mask */
1038   vec_add1 (a->option_55_data, 1);
1039   /* Broadcast address */
1040   vec_add1 (a->option_55_data, 28);
1041   /* time offset */
1042   vec_add1 (a->option_55_data, 2);
1043   /* Router */
1044   vec_add1 (a->option_55_data, 3);
1045   /* Domain Name */
1046   vec_add1 (a->option_55_data, 15);
1047   /* DNS */
1048   vec_add1 (a->option_55_data, 6);
1049   /* Domain search */
1050   vec_add1 (a->option_55_data, 119);
1051   /* Host name */
1052   vec_add1 (a->option_55_data, 12);
1053   /* NetBIOS name server */
1054   vec_add1 (a->option_55_data, 44);
1055   /* NetBIOS Scope */
1056   vec_add1 (a->option_55_data, 47);
1057   /* MTU */
1058   vec_add1 (a->option_55_data, 26);
1059   /* Classless static route */
1060   vec_add1 (a->option_55_data, 121);
1061   /* NTP servers */
1062   vec_add1 (a->option_55_data, 42);
1063
1064   rv = dhcp_client_add_del (a);
1065
1066   switch (rv)
1067     {
1068     case 0:
1069       break;
1070
1071     case VNET_API_ERROR_INVALID_VALUE:
1072
1073       vec_free (a->hostname);
1074       vec_free (a->client_identifier);
1075       vec_free (a->option_55_data);
1076
1077       if (is_add)
1078         clib_warning ("dhcp client already enabled on intf_idx %d",
1079                       sw_if_index);
1080       else
1081         clib_warning ("dhcp client not enabled on on intf_idx %d",
1082                       sw_if_index);
1083       break;
1084
1085     default:
1086       clib_warning ("dhcp_client_add_del returned %d", rv);
1087     }
1088
1089   return rv;
1090 }
1091
1092 void
1093 dhcp_client_walk (dhcp_client_walk_cb_t cb, void *ctx)
1094 {
1095   dhcp_client_main_t *dcm = &dhcp_client_main;
1096   dhcp_client_t *c;
1097
1098   /* *INDENT-OFF* */
1099   pool_foreach (c, dcm->clients,
1100   ({
1101     if (!cb(c, ctx))
1102       break;
1103   }));
1104   /* *INDENT-ON* */
1105
1106 }
1107
1108 static clib_error_t *
1109 dhcp_client_set_command_fn (vlib_main_t * vm,
1110                             unformat_input_t * input,
1111                             vlib_cli_command_t * cmd)
1112 {
1113
1114   dhcp_client_main_t *dcm = &dhcp_client_main;
1115   u32 sw_if_index;
1116   u8 *hostname = 0;
1117   u8 sw_if_index_set = 0;
1118   u8 set_broadcast_flag = 1;
1119   int is_add = 1;
1120   dhcp_client_add_del_args_t _a, *a = &_a;
1121   int rv;
1122
1123   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1124     {
1125       if (unformat (input, "intfc %U",
1126                     unformat_vnet_sw_interface, dcm->vnet_main, &sw_if_index))
1127         sw_if_index_set = 1;
1128       else if (unformat (input, "hostname %v", &hostname))
1129         ;
1130       else if (unformat (input, "del"))
1131         is_add = 0;
1132       else if (unformat (input, "broadcast", &set_broadcast_flag))
1133         is_add = 0;
1134       else
1135         break;
1136     }
1137
1138   if (sw_if_index_set == 0)
1139     return clib_error_return (0, "interface not specified");
1140
1141   clib_memset (a, 0, sizeof (*a));
1142   a->is_add = is_add;
1143   a->sw_if_index = sw_if_index;
1144   a->hostname = hostname;
1145   a->client_identifier = format (0, "vpe 1.0%c", 0);
1146   a->set_broadcast_flag = set_broadcast_flag;
1147
1148   /*
1149    * Option 55 request list. These data precisely match
1150    * the Ubuntu dhcp client. YMMV.
1151    */
1152
1153   /* Subnet Mask */
1154   vec_add1 (a->option_55_data, 1);
1155   /* Broadcast address */
1156   vec_add1 (a->option_55_data, 28);
1157   /* time offset */
1158   vec_add1 (a->option_55_data, 2);
1159   /* Router */
1160   vec_add1 (a->option_55_data, 3);
1161   /* Domain Name */
1162   vec_add1 (a->option_55_data, 15);
1163   /* DNS */
1164   vec_add1 (a->option_55_data, 6);
1165   /* Domain search */
1166   vec_add1 (a->option_55_data, 119);
1167   /* Host name */
1168   vec_add1 (a->option_55_data, 12);
1169   /* NetBIOS name server */
1170   vec_add1 (a->option_55_data, 44);
1171   /* NetBIOS Scope */
1172   vec_add1 (a->option_55_data, 47);
1173   /* MTU */
1174   vec_add1 (a->option_55_data, 26);
1175   /* Classless static route */
1176   vec_add1 (a->option_55_data, 121);
1177   /* NTP servers */
1178   vec_add1 (a->option_55_data, 42);
1179
1180   rv = dhcp_client_add_del (a);
1181
1182   switch (rv)
1183     {
1184     case 0:
1185       break;
1186
1187     case VNET_API_ERROR_INVALID_VALUE:
1188
1189       vec_free (a->hostname);
1190       vec_free (a->client_identifier);
1191       vec_free (a->option_55_data);
1192       if (is_add)
1193         return clib_error_return (0, "dhcp client already enabled on %U",
1194                                   format_vnet_sw_if_index_name,
1195                                   dcm->vnet_main, sw_if_index);
1196       else
1197         return clib_error_return (0, "dhcp client not enabled on %U",
1198                                   format_vnet_sw_if_index_name,
1199                                   dcm->vnet_main, sw_if_index);
1200       break;
1201
1202     default:
1203       vlib_cli_output (vm, "dhcp_client_add_del returned %d", rv);
1204     }
1205
1206   return 0;
1207 }
1208
1209 /* *INDENT-OFF* */
1210 VLIB_CLI_COMMAND (dhcp_client_set_command, static) = {
1211   .path = "set dhcp client",
1212   .short_help = "set dhcp client [del] intfc <interface> [hostname <name>]",
1213   .function = dhcp_client_set_command_fn,
1214 };
1215 /* *INDENT-ON* */
1216
1217 static clib_error_t *
1218 dhcp_client_init (vlib_main_t * vm)
1219 {
1220   dhcp_client_main_t *dcm = &dhcp_client_main;
1221
1222   dcm->vlib_main = vm;
1223   dcm->vnet_main = vnet_get_main ();
1224   dcm->seed = (u32) clib_cpu_time_now ();
1225   return 0;
1226 }
1227
1228 VLIB_INIT_FUNCTION (dhcp_client_init);
1229
1230 /*
1231  * fd.io coding-style-patch-verification: ON
1232  *
1233  * Local Variables:
1234  * eval: (c-set-style "gnu")
1235  * End:
1236  */