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