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