vnet: ping: rewrite for maintainability and multicore support
[vpp.git] / src / vnet / ip / ping.c
1 /*
2  * Copyright (c) 2016 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
16 #include <stddef.h>
17 #include <vnet/ip/ping.h>
18 #include <vnet/fib/ip6_fib.h>
19 #include <vnet/fib/ip4_fib.h>
20 #include <vnet/fib/fib_entry.h>
21 #include <vlib/vlib.h>
22
23 ping_main_t ping_main;
24
25 /**
26  * @file
27  * @brief IPv4 and IPv6 ICMP Ping.
28  *
29  * This file contains code to suppport IPv4 or IPv6 ICMP ECHO_REQUEST to
30  * network hosts.
31  *
32  */
33
34 typedef struct
35 {
36   u16 id;
37   u16 seq;
38   u32 cli_process_node;
39   u8 is_ip6;
40 } icmp_echo_trace_t;
41
42
43 u8 *
44 format_icmp_echo_trace (u8 * s, va_list * va)
45 {
46   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*va, vlib_main_t *);
47   CLIB_UNUSED (vlib_node_t * node) = va_arg (*va, vlib_node_t *);
48   icmp_echo_trace_t *t = va_arg (*va, icmp_echo_trace_t *);
49
50   s =
51     format (s, "ICMP%s echo id %d seq %d", t->is_ip6 ? "6" : "4", t->id,
52             t->seq);
53   if (t->cli_process_node == PING_CLI_UNKNOWN_NODE)
54     {
55       s = format (s, " (unknown)");
56     }
57   else
58     {
59       s = format (s, " send to cli node %d", t->cli_process_node);
60     }
61
62   return s;
63 }
64
65
66 static u8 *
67 format_ip46_ping_result (u8 * s, va_list * args)
68 {
69   send_ip46_ping_result_t res = va_arg (*args, send_ip46_ping_result_t);
70
71   switch (res)
72     {
73 #define _(v, n) case SEND_PING_##v: s = format(s, "%s", n);break;
74       foreach_ip46_ping_result
75 #undef _
76     }
77
78   return (s);
79 }
80
81
82 /*
83  * Poor man's get-set-clear functions
84  * for manipulation of icmp_id -> cli_process_id
85  * mappings.
86  *
87  * There should normally be very few (0..1..2) of these
88  * mappings, so the linear search is a good strategy.
89  *
90  * Make them thread-safe via a simple spinlock.
91  *
92  */
93
94
95 static_always_inline uword
96 get_cli_process_id_by_icmp_id_mt (vlib_main_t * vm, u16 icmp_id)
97 {
98   ping_main_t *pm = &ping_main;
99   uword cli_process_id = PING_CLI_UNKNOWN_NODE;
100   ping_run_t *pr;
101
102   clib_spinlock_lock_if_init (&pm->ping_run_check_lock);
103   vec_foreach (pr, pm->active_ping_runs)
104   {
105     if (pr->icmp_id == icmp_id)
106       {
107         cli_process_id = pr->cli_process_id;
108         break;
109       }
110   }
111   clib_spinlock_unlock_if_init (&pm->ping_run_check_lock);
112   return cli_process_id;
113 }
114
115
116 static_always_inline void
117 set_cli_process_id_by_icmp_id_mt (vlib_main_t * vm, u16 icmp_id,
118                                   uword cli_process_id)
119 {
120   ping_main_t *pm = &ping_main;
121   ping_run_t *pr;
122
123   clib_spinlock_lock_if_init (&pm->ping_run_check_lock);
124   vec_foreach (pr, pm->active_ping_runs)
125   {
126     if (pr->icmp_id == icmp_id)
127       {
128         pr->cli_process_id = cli_process_id;
129         goto have_found_and_set;
130       }
131   }
132   /* no such key yet - add a new one */
133   ping_run_t new_pr = {.icmp_id = icmp_id,.cli_process_id = cli_process_id };
134   vec_add1 (pm->active_ping_runs, new_pr);
135 have_found_and_set:
136   clib_spinlock_unlock_if_init (&pm->ping_run_check_lock);
137 }
138
139
140 static_always_inline void
141 clear_cli_process_id_by_icmp_id_mt (vlib_main_t * vm, u16 icmp_id)
142 {
143   ping_main_t *pm = &ping_main;
144   ping_run_t *pr;
145
146   clib_spinlock_lock_if_init (&pm->ping_run_check_lock);
147   vec_foreach (pr, pm->active_ping_runs)
148   {
149     if (pr->icmp_id == icmp_id)
150       {
151         vec_del1 (pm->active_ping_runs, pm->active_ping_runs - pr);
152         break;
153       }
154   }
155   clib_spinlock_unlock_if_init (&pm->ping_run_check_lock);
156 }
157
158 static_always_inline int
159 ip46_get_icmp_id_and_seq (vlib_main_t * vm, vlib_buffer_t * b0,
160                           u16 * out_icmp_id, u16 * out_icmp_seq, int is_ip6)
161 {
162   int l4_offset;
163   if (is_ip6)
164     {
165       ip6_header_t *ip6 = vlib_buffer_get_current (b0);
166       if (ip6->protocol != IP_PROTOCOL_ICMP6)
167         {
168           return 0;
169         }
170       l4_offset = sizeof (*ip6);        // IPv6 EH
171     }
172   else
173     {
174       ip4_header_t *ip4 = vlib_buffer_get_current (b0);
175       l4_offset = ip4_header_bytes (ip4);
176
177     }
178   icmp46_header_t *icmp46 = vlib_buffer_get_current (b0) + l4_offset;
179   icmp46_echo_request_t *icmp46_echo = (icmp46_echo_request_t *) (icmp46 + 1);
180
181   *out_icmp_id = clib_net_to_host_u16 (icmp46_echo->id);
182   *out_icmp_seq = clib_net_to_host_u16 (icmp46_echo->seq);
183   return 1;
184 }
185
186 /*
187  * post the buffer to a given cli process node - the caller should forget bi0 after return.
188  */
189
190 static_always_inline void
191 ip46_post_icmp_reply_event (vlib_main_t * vm, uword cli_process_id, u32 bi0,
192                             int is_ip6)
193 {
194   vlib_buffer_t *b0 = vlib_get_buffer (vm, bi0);
195   u64 nowts = clib_cpu_time_now ();
196
197   /* Pass the timestamp to the cli_process thanks to the vnet_buffer unused metadata field */
198
199   /* Camping on unused data... just ensure statically that there is enough space */
200   STATIC_ASSERT (ARRAY_LEN (vnet_buffer (b0)->unused) *
201                  sizeof (vnet_buffer (b0)->unused[0]) > sizeof (nowts),
202                  "ping reply timestamp fits within remaining space of vnet_buffer unused data");
203   u64 *pnowts = (void *) &vnet_buffer (b0)->unused[0];
204   *pnowts = nowts;
205
206   u32 event_id = is_ip6 ? PING_RESPONSE_IP6 : PING_RESPONSE_IP4;
207   vlib_process_signal_event_mt (vm, cli_process_id, event_id, bi0);
208 }
209
210
211 static_always_inline void
212 ip46_echo_reply_maybe_trace_buffer (vlib_main_t * vm,
213                                     vlib_node_runtime_t * node,
214                                     uword cli_process_id, u16 id, u16 seq,
215                                     vlib_buffer_t * b0, int is_ip6)
216 {
217   if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
218     {
219       icmp_echo_trace_t *tr = vlib_add_trace (vm, node, b0, sizeof (*tr));
220       tr->id = id;
221       tr->seq = seq;
222       tr->cli_process_node = cli_process_id;
223       tr->is_ip6 = is_ip6;
224     }
225 }
226
227
228 static_always_inline uword
229 ip46_icmp_echo_reply_inner_node_fn (vlib_main_t * vm,
230                                     vlib_node_runtime_t * node,
231                                     vlib_frame_t * frame, int do_trace,
232                                     int is_ip6)
233 {
234   u32 n_left_from, *from, *to_next;
235   icmp46_echo_reply_next_t next_index;
236
237   from = vlib_frame_vector_args (frame);
238   n_left_from = frame->n_vectors;
239
240   next_index = node->cached_next_index;
241
242   while (n_left_from > 0)
243     {
244       u32 n_left_to_next;
245       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
246
247       while (n_left_from > 0 && n_left_to_next > 0)
248         {
249           u32 bi0;
250           vlib_buffer_t *b0;
251           /*
252            * The buffers (replies) are either posted to the CLI thread
253            * awaiting for them for subsequent analysis and disposal,
254            * or are sent to the punt node.
255            *
256            * So the only "next" node is a punt, normally.
257            */
258           u32 next0 = ICMP46_ECHO_REPLY_NEXT_PUNT;
259
260           bi0 = from[0];
261           b0 = vlib_get_buffer (vm, bi0);
262           from += 1;
263           n_left_from -= 1;
264
265           u16 icmp_id = ~0;
266           u16 icmp_seq = ~0;
267           uword cli_process_id = PING_CLI_UNKNOWN_NODE;
268
269           if (ip46_get_icmp_id_and_seq (vm, b0, &icmp_id, &icmp_seq, is_ip6))
270             {
271               cli_process_id = get_cli_process_id_by_icmp_id_mt (vm, icmp_id);
272             }
273
274           if (do_trace)
275             ip46_echo_reply_maybe_trace_buffer (vm, node, cli_process_id,
276                                                 icmp_id, icmp_seq, b0,
277                                                 is_ip6);
278
279           if (~0 == cli_process_id)
280             {
281               /* no outstanding requests for this reply, punt */
282               /* speculatively enqueue b0 to the current next frame */
283               to_next[0] = bi0;
284               to_next += 1;
285               n_left_to_next -= 1;
286               /* verify speculative enqueue, maybe switch current next frame */
287               vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
288                                                to_next, n_left_to_next,
289                                                bi0, next0);
290             }
291           else
292             {
293               /* Post the buffer to CLI thread. It will take care of freeing it. */
294               ip46_post_icmp_reply_event (vm, cli_process_id, bi0, is_ip6);
295             }
296         }
297       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
298     }
299   return frame->n_vectors;
300 }
301
302 /*
303  * select "with-trace" or "without-trace" codepaths upfront.
304  */
305 static_always_inline uword
306 ip46_icmp_echo_reply_outer_node_fn (vlib_main_t * vm,
307                                     vlib_node_runtime_t * node,
308                                     vlib_frame_t * frame, int is_ip6)
309 {
310   if (node->flags & VLIB_NODE_FLAG_TRACE)
311     return ip46_icmp_echo_reply_inner_node_fn (vm, node, frame,
312                                                1 /* do_trace */ , is_ip6);
313   else
314     return ip46_icmp_echo_reply_inner_node_fn (vm, node, frame,
315                                                0 /* do_trace */ , is_ip6);
316 }
317
318 static uword
319 ip4_icmp_echo_reply_node_fn (vlib_main_t * vm,
320                              vlib_node_runtime_t * node, vlib_frame_t * frame)
321 {
322   return ip46_icmp_echo_reply_outer_node_fn (vm, node, frame,
323                                              0 /* is_ip6 */ );
324 }
325
326 static uword
327 ip6_icmp_echo_reply_node_fn (vlib_main_t * vm,
328                              vlib_node_runtime_t * node, vlib_frame_t * frame)
329 {
330   return ip46_icmp_echo_reply_outer_node_fn (vm, node, frame,
331                                              1 /* is_ip6 */ );
332 }
333
334 /* *INDENT-OFF* */
335 VLIB_REGISTER_NODE (ip6_icmp_echo_reply_node, static) =
336 {
337   .function = ip6_icmp_echo_reply_node_fn,
338   .name = "ip6-icmp-echo-reply",
339   .vector_size = sizeof (u32),
340   .format_trace = format_icmp_echo_trace,
341   .n_next_nodes = ICMP46_ECHO_REPLY_N_NEXT,
342   .next_nodes = {
343     [ICMP46_ECHO_REPLY_NEXT_DROP] = "ip6-drop",
344     [ICMP46_ECHO_REPLY_NEXT_PUNT] = "ip6-punt",
345   },
346 };
347
348 VLIB_REGISTER_NODE (ip4_icmp_echo_reply_node, static) =
349 {
350   .function = ip4_icmp_echo_reply_node_fn,
351   .name = "ip4-icmp-echo-reply",
352   .vector_size = sizeof (u32),
353   .format_trace = format_icmp_echo_trace,
354   .n_next_nodes = ICMP46_ECHO_REPLY_N_NEXT,
355   .next_nodes = {
356     [ICMP46_ECHO_REPLY_NEXT_DROP] = "ip4-drop",
357     [ICMP46_ECHO_REPLY_NEXT_PUNT] = "ip4-punt",
358   },
359 };
360 /* *INDENT-ON* */
361
362
363 /*
364  * A swarm of address-family agnostic helper functions
365  * for building and sending the ICMP echo request.
366  *
367  * Deliberately mostly "static" rather than "static inline"
368  * so one can trace them sanely if needed in debugger, if needed.
369  *
370  */
371
372 static_always_inline u8
373 get_icmp_echo_payload_byte (int offset)
374 {
375   return (offset % 256);
376 }
377
378 /* Fill in the ICMP ECHO structure, return the safety-checked and possibly shrunk data_len */
379 static u16
380 init_icmp46_echo_request (vlib_main_t * vm, vlib_buffer_t * b0,
381                           int l4_header_offset,
382                           icmp46_echo_request_t * icmp46_echo, u16 seq_host,
383                           u16 id_host, u64 now, u16 data_len)
384 {
385   int i;
386
387
388   int l34_len =
389     l4_header_offset + sizeof (icmp46_header_t) +
390     offsetof (icmp46_echo_request_t, data);
391   int max_data_len = VLIB_BUFFER_DATA_SIZE - l34_len;
392
393   int first_buf_data_len = data_len < max_data_len ? data_len : max_data_len;
394
395   int payload_offset = 0;
396   for (i = 0; i < first_buf_data_len; i++)
397     icmp46_echo->data[i] = get_icmp_echo_payload_byte (payload_offset++);
398
399   /* inspired by vlib_buffer_add_data */
400   vlib_buffer_t *hb = b0;
401   int remaining_data_len = data_len - first_buf_data_len;
402   while (remaining_data_len)
403     {
404       int this_buf_data_len =
405         remaining_data_len <
406         VLIB_BUFFER_DATA_SIZE ? remaining_data_len : VLIB_BUFFER_DATA_SIZE;
407       int n_alloc = vlib_buffer_alloc_from_free_list (vm, &b0->next_buffer, 1,
408                                                       hb->free_list_index);
409       if (n_alloc < 1)
410         {
411           /* That is how much we have so far - return it... */
412           return (data_len - remaining_data_len);
413         }
414       b0->flags |= VLIB_BUFFER_NEXT_PRESENT;
415       /* move on to the newly acquired buffer */
416       b0 = vlib_get_buffer (vm, b0->next_buffer);
417       /* initialize the data */
418       for (i = 0; i < this_buf_data_len; i++)
419         {
420           b0->data[i] = get_icmp_echo_payload_byte (payload_offset++);
421         }
422       b0->current_length = this_buf_data_len;
423       b0->current_data = 0;
424       remaining_data_len -= this_buf_data_len;
425     }
426   hb->flags |= VLIB_BUFFER_TOTAL_LENGTH_VALID;
427   hb->current_length = l34_len + first_buf_data_len;
428   hb->total_length_not_including_first_buffer = data_len - first_buf_data_len;
429
430   icmp46_echo->time_sent = now;
431   icmp46_echo->seq = clib_host_to_net_u16 (seq_host);
432   icmp46_echo->id = clib_host_to_net_u16 (id_host);
433   return data_len;
434 }
435
436
437 static u32
438 ip46_fib_index_from_table_id (u32 table_id, int is_ip6)
439 {
440   u32 fib_index = is_ip6 ?
441     ip6_fib_index_from_table_id (table_id) :
442     ip4_fib_index_from_table_id (table_id);
443   return fib_index;
444 }
445
446 static fib_node_index_t
447 ip46_fib_table_lookup_host (u32 fib_index, ip46_address_t * pa46, int is_ip6)
448 {
449   fib_node_index_t fib_entry_index = is_ip6 ?
450     ip6_fib_table_lookup (fib_index, &pa46->ip6, 128) :
451     ip4_fib_table_lookup (ip4_fib_get (fib_index), &pa46->ip4, 32);
452   return fib_entry_index;
453 }
454
455 static u32
456 ip46_get_resolving_interface (u32 fib_index, ip46_address_t * pa46,
457                               int is_ip6)
458 {
459   u32 sw_if_index = ~0;
460   if (~0 != fib_index)
461     {
462       fib_node_index_t fib_entry_index;
463       fib_entry_index = ip46_fib_table_lookup_host (fib_index, pa46, is_ip6);
464       sw_if_index = fib_entry_get_resolving_interface (fib_entry_index);
465     }
466   return sw_if_index;
467 }
468
469 static u32
470 ip46_fib_table_get_index_for_sw_if_index (u32 sw_if_index, int is_ip6)
471 {
472   u32 fib_table_index = is_ip6 ?
473     ip6_fib_table_get_index_for_sw_if_index (sw_if_index) :
474     ip4_fib_table_get_index_for_sw_if_index (sw_if_index);
475   return fib_table_index;
476
477 }
478
479
480 static int
481 ip46_fill_l3_header (ip46_address_t * pa46, vlib_buffer_t * b0, int is_ip6)
482 {
483   if (is_ip6)
484     {
485       ip6_header_t *ip6 = vlib_buffer_get_current (b0);
486       /* Fill in ip6 header fields */
487       ip6->ip_version_traffic_class_and_flow_label =
488         clib_host_to_net_u32 (0x6 << 28);
489       ip6->payload_length = 0;  /* will be set later */
490       ip6->protocol = IP_PROTOCOL_ICMP6;
491       ip6->hop_limit = 255;
492       ip6->dst_address = pa46->ip6;
493       ip6->src_address = pa46->ip6;
494       return (sizeof (ip6_header_t));
495     }
496   else
497     {
498       ip4_header_t *ip4 = vlib_buffer_get_current (b0);
499       /* Fill in ip4 header fields */
500       ip4->checksum = 0;
501       ip4->ip_version_and_header_length = 0x45;
502       ip4->tos = 0;
503       ip4->length = 0;          /* will be set later */
504       ip4->fragment_id = 0;
505       ip4->flags_and_fragment_offset = 0;
506       ip4->ttl = 0xff;
507       ip4->protocol = IP_PROTOCOL_ICMP;
508       ip4->src_address = pa46->ip4;
509       ip4->dst_address = pa46->ip4;
510       return (sizeof (ip4_header_t));
511     }
512 }
513
514 static int
515 ip46_set_src_address (u32 sw_if_index, vlib_buffer_t * b0, int is_ip6)
516 {
517   int res;
518   if (is_ip6)
519     {
520       ip6_main_t *im = &ip6_main;
521       ip6_header_t *ip6 = vlib_buffer_get_current (b0);
522       res =
523         ip6_src_address_for_packet (&im->lookup_main, sw_if_index,
524                                     &ip6->dst_address, &ip6->src_address);
525     }
526   else
527     {
528       ip4_main_t *im = &ip4_main;
529       ip4_header_t *ip4 = vlib_buffer_get_current (b0);
530       res =
531         ip4_src_address_for_packet (&im->lookup_main, sw_if_index,
532                                     &ip4->src_address);
533       /* IP4 and IP6 paths have the inverse logic. Harmonize. */
534       res = !res;
535     }
536   return res;
537 }
538
539 static void
540 ip46_print_buffer_src_address (vlib_main_t * vm, vlib_buffer_t * b0,
541                                int is_ip6)
542 {
543   void *format_addr_func;
544   void *paddr;
545   if (is_ip6)
546     {
547       ip6_header_t *ip6 = vlib_buffer_get_current (b0);
548       format_addr_func = format_ip6_address;
549       paddr = &ip6->src_address;
550     }
551   else
552     {
553       ip4_header_t *ip4 = vlib_buffer_get_current (b0);
554       format_addr_func = format_ip4_address;
555       paddr = &ip4->src_address;
556     }
557   vlib_cli_output (vm, "Source address: %U ", format_addr_func, paddr);
558 }
559
560 static u16
561 ip46_fill_icmp_request_at (vlib_main_t * vm, int l4_offset, u16 seq_host,
562                            u16 id_host, u16 data_len, vlib_buffer_t * b0,
563                            int is_ip6)
564 {
565   icmp46_header_t *icmp46 = vlib_buffer_get_current (b0) + l4_offset;
566
567   icmp46->type = is_ip6 ? ICMP6_echo_request : ICMP4_echo_request;
568   icmp46->code = 0;
569   icmp46->checksum = 0;
570
571   icmp46_echo_request_t *icmp46_echo = (icmp46_echo_request_t *) (icmp46 + 1);
572
573   data_len =
574     init_icmp46_echo_request (vm, b0, l4_offset, icmp46_echo, seq_host,
575                               id_host, clib_cpu_time_now (), data_len);
576   return data_len;
577 }
578
579
580 /* Compute ICMP4 checksum with multibuffer support. */
581 u16
582 ip4_icmp_compute_checksum (vlib_main_t * vm, vlib_buffer_t * p0,
583                            ip4_header_t * ip0)
584 {
585   ip_csum_t sum0;
586   u32 ip_header_length, payload_length_host_byte_order;
587   u32 n_this_buffer, n_bytes_left, n_ip_bytes_this_buffer;
588   u16 sum16;
589   void *data_this_buffer;
590
591   ip_header_length = ip4_header_bytes (ip0);
592   payload_length_host_byte_order =
593     clib_net_to_host_u16 (ip0->length) - ip_header_length;
594
595   /* ICMP4 checksum does not include the IP header */
596   sum0 = 0;
597
598   n_bytes_left = n_this_buffer = payload_length_host_byte_order;
599   data_this_buffer = (void *) ip0 + ip_header_length;
600   n_ip_bytes_this_buffer =
601     p0->current_length - (((u8 *) ip0 - p0->data) - p0->current_data);
602   if (n_this_buffer + ip_header_length > n_ip_bytes_this_buffer)
603     {
604       n_this_buffer = n_ip_bytes_this_buffer > ip_header_length ?
605         n_ip_bytes_this_buffer - ip_header_length : 0;
606     }
607   while (1)
608     {
609       sum0 = ip_incremental_checksum (sum0, data_this_buffer, n_this_buffer);
610       n_bytes_left -= n_this_buffer;
611       if (n_bytes_left == 0)
612         break;
613
614       ASSERT (p0->flags & VLIB_BUFFER_NEXT_PRESENT);
615       p0 = vlib_get_buffer (vm, p0->next_buffer);
616       data_this_buffer = vlib_buffer_get_current (p0);
617       n_this_buffer = p0->current_length;
618     }
619
620   sum16 = ~ip_csum_fold (sum0);
621
622   return sum16;
623 }
624
625
626 static void
627 ip46_fix_len_and_csum (vlib_main_t * vm, int l4_offset, u16 data_len,
628                        vlib_buffer_t * b0, int is_ip6)
629 {
630   u16 payload_length =
631     data_len + sizeof (icmp46_header_t) + offsetof (icmp46_echo_request_t,
632                                                     data);
633   u16 total_length = payload_length + l4_offset;
634   icmp46_header_t *icmp46 = vlib_buffer_get_current (b0) + l4_offset;
635   icmp46->checksum = 0;
636
637   if (is_ip6)
638     {
639       ip6_header_t *ip6 = vlib_buffer_get_current (b0);
640       ip6->payload_length = clib_host_to_net_u16 (payload_length);
641
642       int bogus_length = 0;
643       icmp46->checksum =
644         ip6_tcp_udp_icmp_compute_checksum (vm, b0, ip6, &bogus_length);
645     }
646   else
647     {
648       ip4_header_t *ip4 = vlib_buffer_get_current (b0);
649       ip4->length = clib_host_to_net_u16 (total_length);
650
651       ip4->checksum = ip4_header_checksum (ip4);
652       icmp46->checksum = ip4_icmp_compute_checksum (vm, b0, ip4);
653     }
654 }
655
656 static u16
657 at_most_a_frame (u32 count)
658 {
659   return count > VLIB_FRAME_SIZE ? VLIB_FRAME_SIZE : count;
660 }
661
662 static int
663 ip46_enqueue_packet (vlib_main_t * vm, vlib_buffer_t * b0, u32 burst,
664                      int is_ip6)
665 {
666   vlib_frame_t *f = 0;
667   u32 lookup_node_index =
668     is_ip6 ? ip6_lookup_node.index : ip4_lookup_node.index;
669   int n_sent = 0;
670
671   u16 n_to_send;
672
673   /*
674    * Enqueue the packet, possibly as one or more frames of copies to make
675    * bursts. We enqueue b0 as the very last buffer, when there is no possibility
676    * for error in vlib_buffer_copy, so as to allow the caller to free it
677    * in case we encounter the error in the middle of the loop.
678    */
679   for (n_to_send = at_most_a_frame (burst), burst -= n_to_send; n_to_send > 0;
680        n_to_send = at_most_a_frame (burst), burst -= n_to_send)
681     {
682       f = vlib_get_frame_to_node (vm, lookup_node_index);
683       /* f can not be NULL here - frame allocation failure causes panic */
684
685       u32 *to_next = vlib_frame_vector_args (f);
686       f->n_vectors = n_to_send;
687
688       while (n_to_send > 1)
689         {
690           vlib_buffer_t *b0copy = vlib_buffer_copy (vm, b0);
691           if (PREDICT_FALSE (b0copy == NULL))
692             goto ship_and_ret;
693           *to_next++ = vlib_get_buffer_index (vm, b0copy);
694           n_to_send--;
695           n_sent++;
696         }
697
698       /* n_to_send is guaranteed to equal 1 here */
699       if (burst > 0)
700         {
701           /* not the last burst, so still make a copy for the last buffer */
702           vlib_buffer_t *b0copy = vlib_buffer_copy (vm, b0);
703           if (PREDICT_FALSE (b0copy == NULL))
704             goto ship_and_ret;
705           n_to_send--;
706           *to_next++ = vlib_get_buffer_index (vm, b0copy);
707         }
708       else
709         {
710           /* put the original buffer as the last one of an error-free run */
711           *to_next++ = vlib_get_buffer_index (vm, b0);
712         }
713       vlib_put_frame_to_node (vm, lookup_node_index, f);
714       n_sent += f->n_vectors;
715     }
716   return n_sent;
717   /*
718    * We reach here in case we already enqueued one or more buffers
719    * and maybe one or more frames but could not make more copies.
720    * There is an outstanding frame - so ship it and return.
721    * Caller will have to free the b0 in this case, since
722    * we did not enqueue it here yet.
723    */
724 ship_and_ret:
725   n_sent += f->n_vectors;
726   vlib_put_frame_to_node (vm, lookup_node_index, f);
727   return n_sent;
728 }
729
730
731 /*
732  * An address-family agnostic ping send function.
733  */
734
735 #define ERROR_OUT(e) do { err = e; goto done; } while (0)
736
737 static send_ip46_ping_result_t
738 send_ip46_ping (vlib_main_t * vm,
739                 u32 table_id,
740                 ip46_address_t * pa46,
741                 u32 sw_if_index,
742                 u16 seq_host, u16 id_host, u16 data_len, u32 burst,
743                 u8 verbose, int is_ip6)
744 {
745   int err = SEND_PING_OK;
746   u32 bi0 = 0;
747   int n_buf0 = 0;
748   vlib_buffer_t *b0;
749   vlib_buffer_free_list_t *fl;
750
751   n_buf0 = vlib_buffer_alloc (vm, &bi0, 1);
752   if (n_buf0 < 1)
753     ERROR_OUT (SEND_PING_ALLOC_FAIL);
754
755   b0 = vlib_get_buffer (vm, bi0);
756   fl = vlib_buffer_get_free_list (vm, VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX);
757   vlib_buffer_init_for_free_list (b0, fl);
758   VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b0);
759
760   /*
761    * if the user did not provide a source interface,
762    * perform a resolution and use an interface
763    * via which it succeeds.
764    */
765   u32 fib_index;
766   if (~0 == sw_if_index)
767     {
768       fib_index = ip46_fib_index_from_table_id (table_id, is_ip6);
769       sw_if_index = ip46_get_resolving_interface (fib_index, pa46, is_ip6);
770     }
771   else
772     fib_index =
773       ip46_fib_table_get_index_for_sw_if_index (sw_if_index, is_ip6);
774
775   if (~0 == fib_index)
776     ERROR_OUT (SEND_PING_NO_TABLE);
777   if (~0 == sw_if_index)
778     ERROR_OUT (SEND_PING_NO_INTERFACE);
779
780   vnet_buffer (b0)->sw_if_index[VLIB_RX] = sw_if_index;
781   vnet_buffer (b0)->sw_if_index[VLIB_TX] = fib_index;
782
783   int l4_header_offset = ip46_fill_l3_header (pa46, b0, is_ip6);
784
785   /* set the src address in the buffer */
786   if (!ip46_set_src_address (sw_if_index, b0, is_ip6))
787     ERROR_OUT (SEND_PING_NO_SRC_ADDRESS);
788   if (verbose)
789     ip46_print_buffer_src_address (vm, b0, is_ip6);
790
791   data_len =
792     ip46_fill_icmp_request_at (vm, l4_header_offset, seq_host, id_host,
793                                data_len, b0, is_ip6);
794
795   ip46_fix_len_and_csum (vm, l4_header_offset, data_len, b0, is_ip6);
796
797   int n_sent = ip46_enqueue_packet (vm, b0, burst, is_ip6);
798   if (n_sent < burst)
799     err = SEND_PING_NO_BUFFERS;
800
801 done:
802   if (err != SEND_PING_OK)
803     {
804       if (n_buf0 > 0)
805         vlib_buffer_free (vm, &bi0, 1);
806     }
807   return err;
808 }
809
810 static send_ip46_ping_result_t
811 send_ip6_ping (vlib_main_t * vm,
812                u32 table_id, ip6_address_t * pa6,
813                u32 sw_if_index, u16 seq_host, u16 id_host, u16 data_len,
814                u32 burst, u8 verbose)
815 {
816   ip46_address_t target;
817   target.ip6 = *pa6;
818   return send_ip46_ping (vm, table_id, &target, sw_if_index, seq_host,
819                          id_host, data_len, burst, verbose, 1 /* is_ip6 */ );
820 }
821
822 static send_ip46_ping_result_t
823 send_ip4_ping (vlib_main_t * vm,
824                u32 table_id, ip4_address_t * pa4,
825                u32 sw_if_index, u16 seq_host, u16 id_host, u16 data_len,
826                u32 burst, u8 verbose)
827 {
828   ip46_address_t target;
829   ip46_address_set_ip4 (&target, pa4);
830   return send_ip46_ping (vm, table_id, &target, sw_if_index, seq_host,
831                          id_host, data_len, burst, verbose, 0 /* is_ip6 */ );
832 }
833
834 static void
835 print_ip46_icmp_reply (vlib_main_t * vm, u32 bi0, int is_ip6)
836 {
837   vlib_buffer_t *b0 = vlib_get_buffer (vm, bi0);
838   int l4_offset;
839   void *paddr;
840   void *format_addr_func;
841   u16 payload_length;
842   u8 ttl;
843   if (is_ip6)
844     {
845       ip6_header_t *ip6 = vlib_buffer_get_current (b0);
846       paddr = (void *) &ip6->src_address;
847       format_addr_func = (void *) format_ip6_address;
848       ttl = ip6->hop_limit;
849       l4_offset = sizeof (ip6_header_t);        // FIXME - EH processing ?
850       payload_length = clib_net_to_host_u16 (ip6->payload_length);
851     }
852   else
853     {
854       ip4_header_t *ip4 = vlib_buffer_get_current (b0);
855       paddr = (void *) &ip4->src_address;
856       format_addr_func = (void *) format_ip4_address;
857       ttl = ip4->ttl;
858       l4_offset = ip4_header_bytes (ip4);
859       payload_length =
860         clib_net_to_host_u16 (ip4->length) + ip4_header_bytes (ip4);
861     }
862   icmp46_header_t *icmp = vlib_buffer_get_current (b0) + l4_offset;
863   icmp46_echo_request_t *icmp_echo = (icmp46_echo_request_t *) (icmp + 1);
864   u64 *dataplane_ts = (u64 *) & vnet_buffer (b0)->unused[0];
865
866   f64 clocks_per_second = ((f64) vm->clib_time.clocks_per_second);
867   f64 rtt =
868     ((f64) (*dataplane_ts - icmp_echo->time_sent)) / clocks_per_second;
869
870   vlib_cli_output (vm,
871                    "%d bytes from %U: icmp_seq=%d ttl=%d time=%.4f ms",
872                    payload_length,
873                    format_addr_func,
874                    paddr,
875                    clib_host_to_net_u16 (icmp_echo->seq), ttl, rtt * 1000.0);
876 }
877
878 /*
879  * Perform the ping run with the given parameters in the current CLI process.
880  * Depending on whether pa4 or pa6 is set, runs IPv4 or IPv6 ping.
881  * The amusing side effect is of course if both are set, then both pings are sent.
882  * This behavior can be used to ping a dualstack host over IPv4 and IPv6 at once.
883  */
884
885 static void
886 run_ping_ip46_address (vlib_main_t * vm, u32 table_id, ip4_address_t * pa4,
887                        ip6_address_t * pa6, u32 sw_if_index,
888                        f64 ping_interval, u32 ping_repeat, u32 data_len,
889                        u32 ping_burst, u32 verbose)
890 {
891   int i;
892   uword curr_proc = vlib_current_process (vm);
893   u32 n_replies = 0;
894   u32 n_requests = 0;
895   u16 icmp_id;
896
897   static u32 rand_seed = 0;
898
899   if (PREDICT_FALSE (!rand_seed))
900     rand_seed = random_default_seed ();
901
902   icmp_id = random_u32 (&rand_seed) & 0xffff;
903
904   while (~0 != get_cli_process_id_by_icmp_id_mt (vm, icmp_id))
905     {
906       vlib_cli_output (vm, "ICMP ID collision at %d, incrementing", icmp_id);
907       icmp_id++;
908     }
909
910   set_cli_process_id_by_icmp_id_mt (vm, icmp_id, curr_proc);
911
912   for (i = 1; i <= ping_repeat; i++)
913     {
914       send_ip46_ping_result_t res = SEND_PING_OK;
915       f64 sleep_interval;
916       f64 time_ping_sent = vlib_time_now (vm);
917       if (pa6)
918         {
919           res = send_ip6_ping (vm, table_id,
920                                pa6, sw_if_index, i, icmp_id,
921                                data_len, ping_burst, verbose);
922           if (SEND_PING_OK == res)
923             n_requests += ping_burst;
924           else
925             vlib_cli_output (vm, "Failed: %U", format_ip46_ping_result, res);
926         }
927       if (pa4)
928         {
929           res = send_ip4_ping (vm, table_id, pa4,
930                                sw_if_index, i, icmp_id, data_len,
931                                ping_burst, verbose);
932           if (SEND_PING_OK == res)
933             n_requests += ping_burst;
934           else
935             vlib_cli_output (vm, "Failed: %U", format_ip46_ping_result, res);
936         }
937
938       /* Collect and print the responses until it is time to send a next ping */
939
940       while ((i <= ping_repeat)
941              &&
942              ((sleep_interval =
943                time_ping_sent + ping_interval - vlib_time_now (vm)) > 0.0))
944         {
945           uword event_type, *event_data = 0;
946           vlib_process_wait_for_event_or_clock (vm, sleep_interval);
947           event_type = vlib_process_get_events (vm, &event_data);
948           switch (event_type)
949             {
950             case ~0:            /* no events => timeout */
951               break;
952             case PING_RESPONSE_IP6:
953               /* fall-through */
954             case PING_RESPONSE_IP4:
955               {
956                 int ii;
957                 int is_ip6 = (event_type == PING_RESPONSE_IP6);
958                 for (ii = 0; ii < vec_len (event_data); ii++)
959                   {
960                     u32 bi0 = event_data[ii];
961                     print_ip46_icmp_reply (vm, bi0, is_ip6);
962                     n_replies++;
963                     if (0 != bi0)
964                       vlib_buffer_free (vm, &bi0, 1);
965                   }
966               }
967               break;
968             default:
969               /* someone pressed a key, abort */
970               vlib_cli_output (vm, "Aborted due to a keypress.");
971               goto double_break;
972               break;
973             }
974           vec_free (event_data);
975         }
976     }
977 double_break:
978   vlib_cli_output (vm, "\n");
979   {
980     float loss =
981       (0 ==
982        n_requests) ? 0 : 100.0 * ((float) n_requests -
983                                   (float) n_replies) / (float) n_requests;
984     vlib_cli_output (vm,
985                      "Statistics: %u sent, %u received, %f%% packet loss\n",
986                      n_requests, n_replies, loss);
987     clear_cli_process_id_by_icmp_id_mt (vm, icmp_id);
988   }
989 }
990
991
992
993 static clib_error_t *
994 ping_ip_address (vlib_main_t * vm,
995                  unformat_input_t * input, vlib_cli_command_t * cmd)
996 {
997   ip4_address_t a4;
998   ip6_address_t a6;
999   clib_error_t *error = 0;
1000   u32 ping_repeat = 5;
1001   u32 ping_burst = 1;
1002   u8 ping_ip4, ping_ip6;
1003   vnet_main_t *vnm = vnet_get_main ();
1004   u32 data_len = PING_DEFAULT_DATA_LEN;
1005   u32 verbose = 0;
1006   f64 ping_interval = PING_DEFAULT_INTERVAL;
1007   u32 sw_if_index, table_id;
1008
1009   table_id = 0;
1010   ping_ip4 = ping_ip6 = 0;
1011   sw_if_index = ~0;
1012
1013   if (unformat (input, "%U", unformat_ip4_address, &a4))
1014     {
1015       ping_ip4 = 1;
1016     }
1017   else if (unformat (input, "%U", unformat_ip6_address, &a6))
1018     {
1019       ping_ip6 = 1;
1020     }
1021   else if (unformat (input, "ipv4"))
1022     {
1023       if (unformat (input, "%U", unformat_ip4_address, &a4))
1024         {
1025           ping_ip4 = 1;
1026         }
1027       else
1028         {
1029           error =
1030             clib_error_return (0,
1031                                "expecting IPv4 address but got `%U'",
1032                                format_unformat_error, input);
1033         }
1034     }
1035   else if (unformat (input, "ipv6"))
1036     {
1037       if (unformat (input, "%U", unformat_ip6_address, &a6))
1038         {
1039           ping_ip6 = 1;
1040         }
1041       else
1042         {
1043           error =
1044             clib_error_return (0,
1045                                "expecting IPv6 address but got `%U'",
1046                                format_unformat_error, input);
1047         }
1048     }
1049   else
1050     {
1051       error =
1052         clib_error_return (0,
1053                            "expecting IP4/IP6 address `%U'. Usage: ping <addr> [source <intf>] [size <datasz>] [repeat <count>] [verbose]",
1054                            format_unformat_error, input);
1055       goto done;
1056     }
1057
1058   /* allow for the second AF in the same ping */
1059   if (!ping_ip4 && (unformat (input, "ipv4")))
1060     {
1061       if (unformat (input, "%U", unformat_ip4_address, &a4))
1062         {
1063           ping_ip4 = 1;
1064         }
1065     }
1066   else if (!ping_ip6 && (unformat (input, "ipv6")))
1067     {
1068       if (unformat (input, "%U", unformat_ip6_address, &a6))
1069         {
1070           ping_ip6 = 1;
1071         }
1072     }
1073
1074   /* parse the rest of the parameters  in a cycle */
1075   while (!unformat_eof (input, NULL))
1076     {
1077       if (unformat (input, "source"))
1078         {
1079           if (!unformat_user
1080               (input, unformat_vnet_sw_interface, vnm, &sw_if_index))
1081             {
1082               error =
1083                 clib_error_return (0,
1084                                    "unknown interface `%U'",
1085                                    format_unformat_error, input);
1086               goto done;
1087             }
1088         }
1089       else if (unformat (input, "size"))
1090         {
1091           if (!unformat (input, "%u", &data_len))
1092             {
1093               error =
1094                 clib_error_return (0,
1095                                    "expecting size but got `%U'",
1096                                    format_unformat_error, input);
1097               goto done;
1098             }
1099           if (data_len > PING_MAXIMUM_DATA_SIZE)
1100             {
1101               error =
1102                 clib_error_return (0,
1103                                    "%d is bigger than maximum allowed payload size %d",
1104                                    data_len, PING_MAXIMUM_DATA_SIZE);
1105               goto done;
1106             }
1107         }
1108       else if (unformat (input, "table-id"))
1109         {
1110           if (!unformat (input, "%u", &table_id))
1111             {
1112               error =
1113                 clib_error_return (0,
1114                                    "expecting table-id but got `%U'",
1115                                    format_unformat_error, input);
1116               goto done;
1117             }
1118         }
1119       else if (unformat (input, "interval"))
1120         {
1121           if (!unformat (input, "%f", &ping_interval))
1122             {
1123               error =
1124                 clib_error_return (0,
1125                                    "expecting interval (floating point number) got `%U'",
1126                                    format_unformat_error, input);
1127               goto done;
1128             }
1129         }
1130       else if (unformat (input, "repeat"))
1131         {
1132           if (!unformat (input, "%u", &ping_repeat))
1133             {
1134               error =
1135                 clib_error_return (0,
1136                                    "expecting repeat count but got `%U'",
1137                                    format_unformat_error, input);
1138               goto done;
1139             }
1140         }
1141       else if (unformat (input, "burst"))
1142         {
1143           if (!unformat (input, "%u", &ping_burst))
1144             {
1145               error =
1146                 clib_error_return (0,
1147                                    "expecting burst count but got `%U'",
1148                                    format_unformat_error, input);
1149               goto done;
1150             }
1151         }
1152       else if (unformat (input, "verbose"))
1153         {
1154           verbose = 1;
1155         }
1156       else
1157         {
1158           error = clib_error_return (0, "unknown input `%U'",
1159                                      format_unformat_error, input);
1160           goto done;
1161         }
1162     }
1163
1164 /*
1165  * Operationally, one won't (and shouldn't) need to send more than a frame worth of pings.
1166  * But it may be handy during the debugging.
1167  */
1168
1169 #ifdef CLIB_DEBUG
1170 #define MAX_PING_BURST (10*VLIB_FRAME_SIZE)
1171 #else
1172 #define MAX_PING_BURST (VLIB_FRAME_SIZE)
1173 #endif
1174
1175   if (ping_burst < 1 || ping_burst > MAX_PING_BURST)
1176     return clib_error_return (0, "burst size must be between 1 and %u",
1177                               MAX_PING_BURST);
1178
1179   run_ping_ip46_address (vm, table_id, ping_ip4 ? &a4 : NULL,
1180                          ping_ip6 ? &a6 : NULL, sw_if_index, ping_interval,
1181                          ping_repeat, data_len, ping_burst, verbose);
1182 done:
1183   return error;
1184 }
1185
1186 /*?
1187  * This command sends an ICMP ECHO_REQUEST to network hosts. The address
1188  * can be an IPv4 or IPv6 address (or both at the same time).
1189  *
1190  * @cliexpar
1191  * @parblock
1192  * Example of how ping an IPv4 address:
1193  * @cliexstart{ping 172.16.1.2 source GigabitEthernet2/0/0 repeat 2}
1194  * 64 bytes from 172.16.1.2: icmp_seq=1 ttl=64 time=.1090 ms
1195  * 64 bytes from 172.16.1.2: icmp_seq=2 ttl=64 time=.0914 ms
1196  *
1197  * Statistics: 2 sent, 2 received, 0% packet loss
1198  * @cliexend
1199  *
1200  * Example of how ping both an IPv4 address and IPv6 address at the same time:
1201  * @cliexstart{ping 172.16.1.2 ipv6 fe80::24a5:f6ff:fe9c:3a36 source GigabitEthernet2/0/0 repeat 2 verbose}
1202  * Adjacency index: 10, sw_if_index: 1
1203  * Adj: ip6-discover-neighbor
1204  * Adj Interface: 0
1205  * Forced set interface: 1
1206  * Adjacency index: 0, sw_if_index: 4294967295
1207  * Adj: ip4-miss
1208  * Adj Interface: 0
1209  * Forced set interface: 1
1210  * Source address: 172.16.1.1
1211  * 64 bytes from 172.16.1.2: icmp_seq=1 ttl=64 time=.1899 ms
1212  * Adjacency index: 10, sw_if_index: 1
1213  * Adj: ip6-discover-neighbor
1214  * Adj Interface: 0
1215  * Forced set interface: 1
1216  * Adjacency index: 0, sw_if_index: 4294967295
1217  * Adj: ip4-miss
1218  * Adj Interface: 0
1219  * Forced set interface: 1
1220  * Source address: 172.16.1.1
1221  * 64 bytes from 172.16.1.2: icmp_seq=2 ttl=64 time=.0910 ms
1222  *
1223  * Statistics: 4 sent, 2 received, 50% packet loss
1224  * @cliexend
1225  * @endparblock
1226 ?*/
1227 /* *INDENT-OFF* */
1228 VLIB_CLI_COMMAND (ping_command, static) =
1229 {
1230   .path = "ping",
1231   .function = ping_ip_address,
1232   .short_help = "ping {<ip-addr> | ipv4 <ip4-addr> | ipv6 <ip6-addr>}"
1233   " [ipv4 <ip4-addr> | ipv6 <ip6-addr>] [source <interface>]"
1234   " [size <pktsize>] [interval <sec>] [repeat <cnt>] [table-id <id>]"
1235   " [verbose]",
1236   .is_mp_safe = 1,
1237 };
1238 /* *INDENT-ON* */
1239
1240 static clib_error_t *
1241 ping_cli_init (vlib_main_t * vm)
1242 {
1243   vlib_thread_main_t *tm = vlib_get_thread_main ();
1244   ping_main_t *pm = &ping_main;
1245
1246   pm->ip6_main = &ip6_main;
1247   pm->ip4_main = &ip4_main;
1248   icmp6_register_type (vm, ICMP6_echo_reply, ip6_icmp_echo_reply_node.index);
1249   ip4_icmp_register_type (vm, ICMP4_echo_reply,
1250                           ip4_icmp_echo_reply_node.index);
1251   if (tm->n_vlib_mains > 1)
1252     clib_spinlock_init (&pm->ping_run_check_lock);
1253   return 0;
1254 }
1255
1256 VLIB_INIT_FUNCTION (ping_cli_init);
1257
1258 /*
1259  * fd.io coding-style-patch-verification: ON
1260  *
1261  * Local Variables:
1262  * eval: (c-set-style "gnu")
1263  * End:
1264  */