dhcp: disable extraneous vlib_log spew
[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   b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED;
520
521   if (ADJ_INDEX_INVALID == c->ai_ucast)
522     is_broadcast = 1;
523
524   if (is_broadcast)
525     {
526       node_index = ip4_rewrite_node.index;
527       vnet_buffer (b)->ip.adj_index[VLIB_TX] = c->ai_bcast;
528     }
529   else
530     {
531       ip_adjacency_t *adj = adj_get (c->ai_ucast);
532
533       if (IP_LOOKUP_NEXT_ARP == adj->lookup_next_index)
534         node_index = ip4_arp_node.index;
535       else
536         node_index = ip4_rewrite_node.index;
537       vnet_buffer (b)->ip.adj_index[VLIB_TX] = c->ai_ucast;
538     }
539
540   /* Enqueue the packet right now */
541   f = vlib_get_frame_to_node (vm, node_index);
542   to_next = vlib_frame_vector_args (f);
543   to_next[0] = bi;
544   f->n_vectors = 1;
545   vlib_put_frame_to_node (vm, node_index, f);
546
547   /* build the headers */
548   ip = vlib_buffer_get_current (b);
549   udp = (udp_header_t *) (ip + 1);
550   dhcp = (dhcp_header_t *) (udp + 1);
551
552   /* $$$ optimize, maybe */
553   clib_memset (ip, 0, sizeof (*ip) + sizeof (*udp) + sizeof (*dhcp));
554
555   ip->ip_version_and_header_length = 0x45;
556   ip->ttl = 128;
557   ip->protocol = IP_PROTOCOL_UDP;
558
559   ip->tos = c->dscp;
560
561   if (ip->tos)
562     {
563       /*
564        * Setup the buffer's QoS settings so any QoS marker on the egress
565        * interface, that might set VLAN CoS bits, based on this DSCP setting
566        */
567       vnet_buffer2 (b)->qos.source = QOS_SOURCE_IP;
568       vnet_buffer2 (b)->qos.bits = ip->tos;
569       b->flags |= VNET_BUFFER_F_QOS_DATA_VALID;
570     }
571
572   if (is_broadcast)
573     {
574       /* src = 0.0.0.0, dst = 255.255.255.255 */
575       ip->dst_address.as_u32 = ~0;
576     }
577   else
578     {
579       /* Renewing an active lease, plain old ip4 src/dst */
580       ip->src_address.as_u32 = c->learned.leased_address.as_u32;
581       ip->dst_address.as_u32 = c->learned.dhcp_server.as_u32;
582     }
583
584   udp->src_port = clib_host_to_net_u16 (UDP_DST_PORT_dhcp_to_client);
585   udp->dst_port = clib_host_to_net_u16 (UDP_DST_PORT_dhcp_to_server);
586
587   /* Send the interface MAC address */
588   clib_memcpy (dhcp->client_hardware_address,
589                vnet_sw_interface_get_hw_address (vnm, c->sw_if_index), 6);
590
591   /* And remember it for rx-packet-for-us checking */
592   clib_memcpy (c->client_hardware_address, dhcp->client_hardware_address,
593                sizeof (c->client_hardware_address));
594
595   /* Lease renewal, set up client_ip_address */
596   if (is_broadcast == 0)
597     dhcp->client_ip_address.as_u32 = c->learned.leased_address.as_u32;
598
599   dhcp->opcode = 1;             /* request, all we send */
600   dhcp->hardware_type = 1;      /* ethernet */
601   dhcp->hardware_address_length = 6;
602   dhcp->transaction_identifier = c->transaction_id;
603   dhcp->flags =
604     clib_host_to_net_u16 (is_broadcast && c->set_broadcast_flag ?
605                           DHCP_FLAG_BROADCAST : 0);
606   dhcp->magic_cookie.as_u32 = DHCP_MAGIC;
607
608   o = (dhcp_option_t *) dhcp->options;
609
610   /* Send option 53, the DHCP message type */
611   o->option = DHCP_PACKET_OPTION_MSG_TYPE;
612   o->length = 1;
613   o->data[0] = type;
614   o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
615
616   /* Send option 57, max msg length */
617   if (0 /* not needed, apparently */ )
618     {
619       o->option = 57;
620       o->length = 2;
621       {
622         u16 *o2 = (u16 *) o->data;
623         *o2 = clib_host_to_net_u16 (1152);
624         o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
625       }
626     }
627
628   /*
629    * If server ip address is available with non-zero value,
630    * option 54 (DHCP Server Identifier) is sent.
631    */
632   if (c->learned.dhcp_server.as_u32)
633     {
634       o->option = 54;
635       o->length = 4;
636       clib_memcpy (o->data, &c->learned.dhcp_server.as_u32, 4);
637       o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
638     }
639
640   /* send option 50, requested IP address */
641   if (c->learned.leased_address.as_u32)
642     {
643       o->option = 50;
644       o->length = 4;
645       clib_memcpy (o->data, &c->learned.leased_address.as_u32, 4);
646       o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
647     }
648
649   /* send option 12, host name */
650   if (vec_len (c->hostname))
651     {
652       o->option = 12;
653       o->length = vec_len (c->hostname);
654       clib_memcpy (o->data, c->hostname, vec_len (c->hostname));
655       o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
656     }
657
658   /* send option 61, client_id */
659   if (vec_len (c->client_identifier))
660     {
661       o->option = 61;
662       o->length = vec_len (c->client_identifier) + 1;
663       /* Set type to zero, apparently some dhcp servers care */
664       o->data[0] = 0;
665       clib_memcpy (o->data + 1, c->client_identifier,
666                    vec_len (c->client_identifier));
667       o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
668     }
669
670   /* $$ maybe send the client s/w version if anyone cares */
671
672   /*
673    * send option 55, parameter request list
674    * The current list - see below, matches the Linux dhcp client's list
675    * Any specific dhcp server config and/or dhcp server may or may
676    * not yield specific options.
677    */
678   o->option = 55;
679   o->length = vec_len (c->option_55_data);
680   clib_memcpy (o->data, c->option_55_data, vec_len (c->option_55_data));
681   o = (dhcp_option_t *) (((uword) o) + (o->length + 2));
682
683   /* End of list */
684   o->option = 0xff;
685   o->length = 0;
686   o++;
687
688   b->current_length = ((u8 *) o) - b->data;
689
690   /* fix ip length, checksum and udp length */
691   ip_length = vlib_buffer_length_in_chain (vm, b);
692
693   ip->length = clib_host_to_net_u16 (ip_length);
694   ip->checksum = ip4_header_checksum (ip);
695
696   udp_length = ip_length - (sizeof (*ip));
697   udp->length = clib_host_to_net_u16 (udp_length);
698
699   switch (type)
700     {
701 #define _(a,b) case DHCP_PACKET_##a: {counter_index = DHCP_STAT_##a; break;}
702       foreach_dhcp_sent_packet_stat
703 #undef _
704     default:
705       counter_index = DHCP_STAT_UNKNOWN;
706       break;
707     }
708
709   vlib_node_increment_counter (vm, dhcp_client_process_node.index,
710                                counter_index, 1);
711 }
712
713 static int
714 dhcp_discover_state (dhcp_client_main_t * dcm, dhcp_client_t * c, f64 now)
715 {
716   /*
717    * State machine "DISCOVER" state. Send a dhcp discover packet,
718    * eventually back off the retry rate.
719    */
720   DHCP_INFO ("enter discover: %U", format_dhcp_client, dcm, c);
721
722   /*
723    * In order to accept any OFFER, whether broadcasted or unicasted, we
724    * need to configure the dhcp-client-detect feature as an input feature
725    * so the DHCP OFFER is sent to the ip4-local node. Without this a
726    * broadcasted OFFER hits the 255.255.255.255/32 address and a unicast
727    * hits 0.0.0.0/0 both of which default to drop and the latter may forward
728    * of box - not what we want. Nor to we want to change these route for
729    * all interfaces in this table
730    */
731   if (c->client_detect_feature_enabled == 0)
732     {
733       vnet_feature_enable_disable ("ip4-unicast",
734                                    "ip4-dhcp-client-detect",
735                                    c->sw_if_index, 1 /* enable */ , 0, 0);
736       c->client_detect_feature_enabled = 1;
737     }
738
739   send_dhcp_pkt (dcm, c, DHCP_PACKET_DISCOVER, 1 /* is_broadcast */ );
740
741   c->retry_count++;
742   if (c->retry_count > 10)
743     c->next_transmit = now + 5.0;
744   else
745     c->next_transmit = now + 1.0;
746   return 0;
747 }
748
749 static int
750 dhcp_request_state (dhcp_client_main_t * dcm, dhcp_client_t * c, f64 now)
751 {
752   /*
753    * State machine "REQUEST" state. Send a dhcp request packet,
754    * eventually drop back to the discover state.
755    */
756   DHCP_INFO ("enter request: %U", format_dhcp_client, dcm, c);
757
758   send_dhcp_pkt (dcm, c, DHCP_PACKET_REQUEST, 1 /* is_broadcast */ );
759
760   c->retry_count++;
761   if (c->retry_count > 7 /* lucky you */ )
762     {
763       c->state = DHCP_DISCOVER;
764       c->next_transmit = now;
765       c->retry_count = 0;
766       return 1;
767     }
768   c->next_transmit = now + 1.0;
769   return 0;
770 }
771
772 static int
773 dhcp_bound_state (dhcp_client_main_t * dcm, dhcp_client_t * c, f64 now)
774 {
775   /*
776    * We disable the client detect feature when we bind a
777    * DHCP address. Turn it back on again on first renew attempt.
778    * Otherwise, if the DHCP server replies we'll never see it.
779    */
780   if (c->client_detect_feature_enabled == 0)
781     {
782       vnet_feature_enable_disable ("ip4-unicast",
783                                    "ip4-dhcp-client-detect",
784                                    c->sw_if_index, 1 /* enable */ , 0, 0);
785       c->client_detect_feature_enabled = 1;
786     }
787
788   /*
789    * State machine "BOUND" state. Send a dhcp request packet to renew
790    * the lease.
791    * Eventually, when the lease expires, forget the dhcp data
792    * and go back to the stone age.
793    */
794   if (now > c->lease_expires)
795     {
796       DHCP_INFO ("lease expired: %U", format_dhcp_client, dcm, c);
797
798       /* reset all data for the client. do not send any more messages
799        * since the objects to do so have been lost */
800       dhcp_client_reset (dcm, c);
801       return 1;
802     }
803
804   DHCP_INFO ("enter bound: %U", format_dhcp_client, dcm, c);
805   send_dhcp_pkt (dcm, c, DHCP_PACKET_REQUEST, 0 /* is_broadcast */ );
806
807   c->retry_count++;
808   if (c->retry_count > 10)
809     c->next_transmit = now + 5.0;
810   else
811     c->next_transmit = now + 1.0;
812
813   return 0;
814 }
815
816 static f64
817 dhcp_client_sm (f64 now, f64 timeout, uword pool_index)
818 {
819   dhcp_client_main_t *dcm = &dhcp_client_main;
820   dhcp_client_t *c;
821
822   /* deleted, pooched, yadda yadda yadda */
823   if (pool_is_free_index (dcm->clients, pool_index))
824     return timeout;
825
826   c = pool_elt_at_index (dcm->clients, pool_index);
827
828   /* Time for us to do something with this client? */
829   if (now < c->next_transmit)
830     return timeout;
831
832 again:
833   switch (c->state)
834     {
835     case DHCP_DISCOVER: /* send a discover */
836       if (dhcp_discover_state (dcm, c, now))
837         goto again;
838       break;
839
840     case DHCP_REQUEST:          /* send a request */
841       if (dhcp_request_state (dcm, c, now))
842         goto again;
843       break;
844
845     case DHCP_BOUND:            /* bound, renew needed? */
846       if (dhcp_bound_state (dcm, c, now))
847         goto again;
848       break;
849
850     default:
851       clib_warning ("dhcp client %d bogus state %d",
852                     c - dcm->clients, c->state);
853       break;
854     }
855
856   if (c->next_transmit < now + timeout)
857     return c->next_transmit - now;
858
859   return timeout;
860 }
861
862 static uword
863 dhcp_client_process (vlib_main_t * vm,
864                      vlib_node_runtime_t * rt, vlib_frame_t * f)
865 {
866   f64 timeout = 100.0;
867   f64 now;
868   uword event_type;
869   uword *event_data = 0;
870   dhcp_client_main_t *dcm = &dhcp_client_main;
871   dhcp_client_t *c;
872   int i;
873
874   while (1)
875     {
876       vlib_process_wait_for_event_or_clock (vm, timeout);
877
878       event_type = vlib_process_get_events (vm, &event_data);
879
880       now = vlib_time_now (vm);
881
882       switch (event_type)
883         {
884         case EVENT_DHCP_CLIENT_WAKEUP:
885           for (i = 0; i < vec_len (event_data); i++)
886             timeout = dhcp_client_sm (now, timeout, event_data[i]);
887           break;
888
889         case ~0:
890           if (pool_elts (dcm->clients))
891             {
892               DHCP_INFO ("timeout");
893               /* *INDENT-OFF* */
894               pool_foreach (c, dcm->clients,
895               ({
896                 timeout = dhcp_client_sm (now, timeout,
897                                           (uword) (c - dcm->clients));
898               }));
899               /* *INDENT-ON* */
900             }
901           else
902             timeout = 100.0;
903           break;
904         }
905
906       vec_reset_length (event_data);
907     }
908
909   /* NOTREACHED */
910   return 0;
911 }
912
913 /* *INDENT-OFF* */
914 VLIB_REGISTER_NODE (dhcp_client_process_node,static) = {
915     .function = dhcp_client_process,
916     .type = VLIB_NODE_TYPE_PROCESS,
917     .name = "dhcp-client-process",
918     .process_log2_n_stack_bytes = 16,
919     .n_errors = ARRAY_LEN(dhcp_client_process_stat_strings),
920     .error_strings = dhcp_client_process_stat_strings,
921 };
922 /* *INDENT-ON* */
923
924 static clib_error_t *
925 show_dhcp_client_command_fn (vlib_main_t * vm,
926                              unformat_input_t * input,
927                              vlib_cli_command_t * cmd)
928 {
929   dhcp_client_main_t *dcm = &dhcp_client_main;
930   dhcp_client_t *c;
931   int verbose = 0;
932   u32 sw_if_index = ~0;
933   uword *p;
934
935   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
936     {
937       if (unformat (input, "intfc %U",
938                     unformat_vnet_sw_interface, dcm->vnet_main, &sw_if_index))
939         ;
940       else if (unformat (input, "verbose"))
941         verbose = 1;
942       else
943         break;
944     }
945
946   if (sw_if_index != ~0)
947     {
948       p = hash_get (dcm->client_by_sw_if_index, sw_if_index);
949       if (p == 0)
950         return clib_error_return (0, "dhcp client not configured");
951       c = pool_elt_at_index (dcm->clients, p[0]);
952       vlib_cli_output (vm, "%U", format_dhcp_client, dcm, c, verbose);
953       return 0;
954     }
955
956   /* *INDENT-OFF* */
957   pool_foreach (c, dcm->clients,
958   ({
959     vlib_cli_output (vm, "%U",
960                      format_dhcp_client, dcm,
961                      c, verbose);
962   }));
963   /* *INDENT-ON* */
964
965   return 0;
966 }
967
968 /* *INDENT-OFF* */
969 VLIB_CLI_COMMAND (show_dhcp_client_command, static) = {
970   .path = "show dhcp client",
971   .short_help = "show dhcp client [intfc <intfc>][verbose]",
972   .function = show_dhcp_client_command_fn,
973 };
974 /* *INDENT-ON* */
975
976
977 int
978 dhcp_client_add_del (dhcp_client_add_del_args_t * a)
979 {
980   dhcp_client_main_t *dcm = &dhcp_client_main;
981   vlib_main_t *vm = dcm->vlib_main;
982   dhcp_client_t *c;
983   uword *p;
984
985   p = hash_get (dcm->client_by_sw_if_index, a->sw_if_index);
986
987   if ((p && a->is_add) || (!p && a->is_add == 0))
988     return VNET_API_ERROR_INVALID_VALUE;
989
990   if (a->is_add)
991     {
992       dhcp_maybe_register_udp_ports (DHCP_PORT_REG_CLIENT);
993       pool_get (dcm->clients, c);
994       clib_memset (c, 0, sizeof (*c));
995       c->state = DHCP_DISCOVER;
996       c->sw_if_index = a->sw_if_index;
997       c->client_index = a->client_index;
998       c->pid = a->pid;
999       c->event_callback = a->event_callback;
1000       c->option_55_data = a->option_55_data;
1001       c->hostname = a->hostname;
1002       c->client_identifier = a->client_identifier;
1003       c->set_broadcast_flag = a->set_broadcast_flag;
1004       c->dscp = a->dscp;
1005       c->ai_ucast = ADJ_INDEX_INVALID;
1006       c->ai_bcast = adj_nbr_add_or_lock (FIB_PROTOCOL_IP4,
1007                                          VNET_LINK_IP4,
1008                                          &ADJ_BCAST_ADDR, c->sw_if_index);
1009
1010       do
1011         {
1012           c->transaction_id = random_u32 (&dcm->seed);
1013         }
1014       while (c->transaction_id == 0);
1015
1016       hash_set (dcm->client_by_sw_if_index, a->sw_if_index, c - dcm->clients);
1017
1018       vlib_process_signal_event (vm, dhcp_client_process_node.index,
1019                                  EVENT_DHCP_CLIENT_WAKEUP, c - dcm->clients);
1020
1021       DHCP_INFO ("create: %U", format_dhcp_client, dcm, c);
1022     }
1023   else
1024     {
1025       c = pool_elt_at_index (dcm->clients, p[0]);
1026
1027       dhcp_client_reset (dcm, c);
1028
1029       adj_unlock (c->ai_bcast);
1030
1031       vec_free (c->domain_server_address);
1032       vec_free (c->option_55_data);
1033       vec_free (c->hostname);
1034       vec_free (c->client_identifier);
1035       hash_unset (dcm->client_by_sw_if_index, c->sw_if_index);
1036       pool_put (dcm->clients, c);
1037     }
1038   return 0;
1039 }
1040
1041 int
1042 dhcp_client_config (u32 is_add,
1043                     u32 client_index,
1044                     vlib_main_t * vm,
1045                     u32 sw_if_index,
1046                     u8 * hostname,
1047                     u8 * client_id,
1048                     dhcp_event_cb_t event_callback,
1049                     u8 set_broadcast_flag, ip_dscp_t dscp, u32 pid)
1050 {
1051   dhcp_client_add_del_args_t _a, *a = &_a;
1052   int rv;
1053
1054   clib_memset (a, 0, sizeof (*a));
1055   a->is_add = is_add;
1056   a->sw_if_index = sw_if_index;
1057   a->client_index = client_index;
1058   a->pid = pid;
1059   a->event_callback = event_callback;
1060   a->set_broadcast_flag = set_broadcast_flag;
1061   a->dscp = dscp;
1062   vec_validate (a->hostname, strlen ((char *) hostname) - 1);
1063   strncpy ((char *) a->hostname, (char *) hostname, vec_len (a->hostname));
1064   vec_validate (a->client_identifier, strlen ((char *) client_id) - 1);
1065   strncpy ((char *) a->client_identifier, (char *) client_id,
1066            vec_len (a->client_identifier));
1067
1068   /*
1069    * Option 55 request list. These data precisely match
1070    * the Ubuntu dhcp client. YMMV.
1071    */
1072
1073   /* Subnet Mask */
1074   vec_add1 (a->option_55_data, 1);
1075   /* Broadcast address */
1076   vec_add1 (a->option_55_data, 28);
1077   /* time offset */
1078   vec_add1 (a->option_55_data, 2);
1079   /* Router */
1080   vec_add1 (a->option_55_data, 3);
1081   /* Domain Name */
1082   vec_add1 (a->option_55_data, 15);
1083   /* DNS */
1084   vec_add1 (a->option_55_data, 6);
1085   /* Domain search */
1086   vec_add1 (a->option_55_data, 119);
1087   /* Host name */
1088   vec_add1 (a->option_55_data, 12);
1089   /* NetBIOS name server */
1090   vec_add1 (a->option_55_data, 44);
1091   /* NetBIOS Scope */
1092   vec_add1 (a->option_55_data, 47);
1093   /* MTU */
1094   vec_add1 (a->option_55_data, 26);
1095   /* Classless static route */
1096   vec_add1 (a->option_55_data, 121);
1097   /* NTP servers */
1098   vec_add1 (a->option_55_data, 42);
1099
1100   rv = dhcp_client_add_del (a);
1101
1102   switch (rv)
1103     {
1104     case 0:
1105       break;
1106
1107     case VNET_API_ERROR_INVALID_VALUE:
1108
1109       vec_free (a->hostname);
1110       vec_free (a->client_identifier);
1111       vec_free (a->option_55_data);
1112
1113       if (is_add)
1114         DHCP_INFO ("dhcp client already enabled on intf_idx %d", sw_if_index);
1115       else
1116         DHCP_INFO ("not enabled on on intf_idx %d", sw_if_index);
1117       break;
1118
1119     default:
1120       DHCP_INFO ("dhcp_client_add_del returned %d", rv);
1121     }
1122
1123   return rv;
1124 }
1125
1126 void
1127 dhcp_client_walk (dhcp_client_walk_cb_t cb, void *ctx)
1128 {
1129   dhcp_client_main_t *dcm = &dhcp_client_main;
1130   dhcp_client_t *c;
1131
1132   /* *INDENT-OFF* */
1133   pool_foreach (c, dcm->clients,
1134   ({
1135     if (!cb(c, ctx))
1136       break;
1137   }));
1138   /* *INDENT-ON* */
1139
1140 }
1141
1142 static clib_error_t *
1143 dhcp_client_set_command_fn (vlib_main_t * vm,
1144                             unformat_input_t * input,
1145                             vlib_cli_command_t * cmd)
1146 {
1147
1148   dhcp_client_main_t *dcm = &dhcp_client_main;
1149   u32 sw_if_index;
1150   u8 *hostname = 0;
1151   u8 sw_if_index_set = 0;
1152   u8 set_broadcast_flag = 1;
1153   int is_add = 1;
1154   dhcp_client_add_del_args_t _a, *a = &_a;
1155   int rv;
1156
1157   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1158     {
1159       if (unformat (input, "intfc %U",
1160                     unformat_vnet_sw_interface, dcm->vnet_main, &sw_if_index))
1161         sw_if_index_set = 1;
1162       else if (unformat (input, "hostname %v", &hostname))
1163         ;
1164       else if (unformat (input, "del"))
1165         is_add = 0;
1166       else if (unformat (input, "broadcast", &set_broadcast_flag))
1167         is_add = 0;
1168       else
1169         break;
1170     }
1171
1172   if (sw_if_index_set == 0)
1173     return clib_error_return (0, "interface not specified");
1174
1175   clib_memset (a, 0, sizeof (*a));
1176   a->is_add = is_add;
1177   a->sw_if_index = sw_if_index;
1178   a->hostname = hostname;
1179   a->client_identifier = format (0, "vpp 1.1%c", 0);
1180   a->set_broadcast_flag = set_broadcast_flag;
1181
1182   /*
1183    * Option 55 request list. These data precisely match
1184    * the Ubuntu dhcp client. YMMV.
1185    */
1186
1187   /* Subnet Mask */
1188   vec_add1 (a->option_55_data, 1);
1189   /* Broadcast address */
1190   vec_add1 (a->option_55_data, 28);
1191   /* time offset */
1192   vec_add1 (a->option_55_data, 2);
1193   /* Router */
1194   vec_add1 (a->option_55_data, 3);
1195   /* Domain Name */
1196   vec_add1 (a->option_55_data, 15);
1197   /* DNS */
1198   vec_add1 (a->option_55_data, 6);
1199   /* Domain search */
1200   vec_add1 (a->option_55_data, 119);
1201   /* Host name */
1202   vec_add1 (a->option_55_data, 12);
1203   /* NetBIOS name server */
1204   vec_add1 (a->option_55_data, 44);
1205   /* NetBIOS Scope */
1206   vec_add1 (a->option_55_data, 47);
1207   /* MTU */
1208   vec_add1 (a->option_55_data, 26);
1209   /* Classless static route */
1210   vec_add1 (a->option_55_data, 121);
1211   /* NTP servers */
1212   vec_add1 (a->option_55_data, 42);
1213
1214   rv = dhcp_client_add_del (a);
1215
1216   switch (rv)
1217     {
1218     case 0:
1219       break;
1220
1221     case VNET_API_ERROR_INVALID_VALUE:
1222
1223       vec_free (a->hostname);
1224       vec_free (a->client_identifier);
1225       vec_free (a->option_55_data);
1226       if (is_add)
1227         return clib_error_return (0, "dhcp client already enabled on %U",
1228                                   format_vnet_sw_if_index_name,
1229                                   dcm->vnet_main, sw_if_index);
1230       else
1231         return clib_error_return (0, "dhcp client not enabled on %U",
1232                                   format_vnet_sw_if_index_name,
1233                                   dcm->vnet_main, sw_if_index);
1234       break;
1235
1236     default:
1237       vlib_cli_output (vm, "dhcp_client_add_del returned %d", rv);
1238     }
1239
1240   return 0;
1241 }
1242
1243 /* *INDENT-OFF* */
1244 VLIB_CLI_COMMAND (dhcp_client_set_command, static) = {
1245   .path = "set dhcp client",
1246   .short_help = "set dhcp client [del] intfc <interface> [hostname <name>]",
1247   .function = dhcp_client_set_command_fn,
1248 };
1249 /* *INDENT-ON* */
1250
1251 static clib_error_t *
1252 dhcp_client_init (vlib_main_t * vm)
1253 {
1254   dhcp_client_main_t *dcm = &dhcp_client_main;
1255
1256   dcm->vlib_main = vm;
1257   dcm->vnet_main = vnet_get_main ();
1258   dcm->seed = (u32) clib_cpu_time_now ();
1259
1260   dhcp_logger = vlib_log_register_class ("dhcp", "client");
1261   DHCP_INFO ("plugin initialized");
1262
1263   return 0;
1264 }
1265
1266 VLIB_INIT_FUNCTION (dhcp_client_init);
1267
1268 /*
1269  * fd.io coding-style-patch-verification: ON
1270  *
1271  * Local Variables:
1272  * eval: (c-set-style "gnu")
1273  * End:
1274  */