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