Debian Codegraph @

ping/ping_echo.c

raw
1 /*
2 Copyright (C) 2001-2026 Free Software Foundation, Inc.
3
4 This file is part of GNU Inetutils.
5
6 GNU Inetutils is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or (at
9 your option) any later version.
10
11 GNU Inetutils is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see `http://www.gnu.org/licenses/'. */
18
19 #include <config.h>
20
21 #include <sys/param.h>
22 #include <sys/socket.h>
23 #include <sys/file.h>
24 #include <sys/time.h>
25
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28
29 /*#include <netinet/ip_icmp.h> -- deliberately not including this */
30 #ifdef HAVE_NETINET_IP_VAR_H
31 # include <netinet/ip_var.h>
32 #endif
33
34 #include <netdb.h>
35 #include <unistd.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <ctype.h>
40 #include <errno.h>
41 #include <limits.h>
42 #include <attribute.h>
43 #include <timespec.h>
44
45 #include <ping.h>
46 #include "ping_impl.h"
47
48 #ifndef MAX_IPOPTLEN
49 # define MAX_IPOPTLEN 40
50 #endif
51
52 #include <xalloc.h>
53
54 static int handler (int code, void *closure,
55 struct sockaddr_in *dest, struct sockaddr_in *from,
56 struct ip *ip, icmphdr_t * icmp, int datalen);
57 int print_echo (int dup, struct ping_stat *stat,
58 struct sockaddr_in *dest, struct sockaddr_in *from,
59 struct ip *ip, icmphdr_t * icmp, int datalen);
60 static int echo_finish (void);
61
62 void print_icmp_header (struct sockaddr_in *from,
63 struct ip *ip, icmphdr_t * icmp, int len);
64 static void print_ip_opt (struct ip *ip, int hlen);
65
66 int
67 ping_echo (char *hostname)
68 {
69 #ifdef IP_OPTIONS
70 char rspace[MAX_IPOPTLEN]; /* Maximal IP option space. */
71 #endif
72 struct ping_stat ping_stat;
73 int status;
74
75 if (options & OPT_FLOOD && options & OPT_INTERVAL)
76 error (EXIT_FAILURE, 0, "-f and -i incompatible options");
77
78 memset (&ping_stat, 0, sizeof (ping_stat));
79 ping_stat.tmin = 999999999.0;
80
81 ping_set_type (ping, ICMP_ECHO);
82 ping_set_packetsize (ping, data_length);
83 ping_set_event_handler (ping, handler, &ping_stat);
84
85 if (ping_set_dest (ping, hostname))
86 error (EXIT_FAILURE, 0, "unknown host");
87
88 if (options & OPT_RROUTE)
89 {
90 #ifdef IP_OPTIONS
91 memset (rspace, 0, sizeof (rspace));
92 rspace[IPOPT_OPTVAL] = IPOPT_RR;
93 rspace[IPOPT_OLEN] = sizeof (rspace) - 1;
94 rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
95 if (setsockopt (ping->ping_fd, IPPROTO_IP,
96 IP_OPTIONS, rspace, sizeof (rspace)) < 0)
97 error (EXIT_FAILURE, errno, "setsockopt");
98 #else
99 error (EXIT_FAILURE, 0, "record route not available in this "
100 "implementation.");
101 #endif /* IP_OPTIONS */
102 }
103 else if (options & OPT_IPTIMESTAMP)
104 {
105 int type;
106
107 if (suboptions & SOPT_TSPRESPEC)
108 #ifdef IPOPT_TS_PRESPEC_RFC791
109 type = IPOPT_TS_PRESPEC_RFC791;
110 #else
111 type = IPOPT_TS_PRESPEC;
112 #endif
113 else if (suboptions & SOPT_TSADDR)
114 type = IPOPT_TS_TSANDADDR;
115 else
116 type = IPOPT_TS_TSONLY;
117
118 #ifdef IP_OPTIONS
119 memset (rspace, 0, sizeof (rspace));
120 rspace[IPOPT_OPTVAL] = IPOPT_TS;
121 rspace[IPOPT_OLEN] = sizeof (rspace);
122 if (type != IPOPT_TS_TSONLY)
123 rspace[IPOPT_OLEN] -= sizeof (n_time); /* Exsessive part. */
124 rspace[IPOPT_OFFSET] = IPOPT_MINOFF + 1;
125
126 # ifdef IPOPT_POS_OV_FLG
127 rspace[IPOPT_POS_OV_FLG] = type;
128 # else
129 rspace[3] = type;
130 # endif/* !IPOPT_POS_OV_FLG */
131
132 if (setsockopt (ping->ping_fd, IPPROTO_IP,
133 IP_OPTIONS, rspace, rspace[IPOPT_OLEN]) < 0)
134 error (EXIT_FAILURE, errno, "setsockopt");
135 #else /* !IP_OPTIONS */
136 error (EXIT_FAILURE, 0, "IP timestamp not available in this "
137 "implementation.");
138 #endif /* IP_OPTIONS */
139 }
140
141 printf ("PING %s (%s): %zu data bytes",
142 ping->ping_hostname,
143 inet_ntoa (ping->ping_dest.ping_sockaddr.sin_addr), data_length);
144 if (options & OPT_VERBOSE)
145 printf (", id 0x%04x = %u", ping->ping_ident, ping->ping_ident);
146
147 printf ("\n");
148
149 status = ping_run (ping, echo_finish);
150 free (ping->ping_hostname);
151 return status;
152 }
153
154 int
155 handler (int code, void *closure,
156 struct sockaddr_in *dest, struct sockaddr_in *from,
157 struct ip *ip, icmphdr_t *icmp, int datalen)
158 {
159 switch (code)
160 {
161 case PEV_RESPONSE:
162 case PEV_DUPLICATE:
163 print_echo (code == PEV_DUPLICATE,
164 (struct ping_stat *) closure, dest, from, ip, icmp,
165 datalen);
166 break;
167 case PEV_NOECHO:;
168 print_icmp_header (from, ip, icmp, datalen);
169 }
170 return 0;
171 }
172
173 int
174 print_echo (int dupflag, struct ping_stat *ping_stat,
175 struct sockaddr_in *dest MAYBE_UNUSED,
176 struct sockaddr_in *from,
177 struct ip *ip, icmphdr_t *icmp, int datalen)
178 {
179 int hlen;
180 bool timing = false;
181 double triptime = 0.0;
182
183 /* Length of IP header */
184 hlen = ip->ip_hl << 2;
185
186 /* Length of ICMP header+payload */
187 datalen -= hlen;
188
189 /* Do timing */
190 if (PING_TIMING (datalen - PING_HEADER_LEN))
191 {
192 struct timeval tv;
193 struct timespec ts;
194
195 timing = true;
196
197 /* Avoid unaligned data. */
198 memcpy (&tv, icmp->icmp_data, sizeof (tv));
199 /* *INDENT-OFF* */
200 ts = timespec_sub (current_timespec (),
201 (struct timespec) { .tv_sec = tv.tv_sec,
202 .tv_nsec = tv.tv_usec * 1000 });
203 /* *INDENT-ON* */
204
205 triptime = timespectod (ts) * 1000.0;
206 ping_stat->tsum += triptime;
207 ping_stat->tsumsq += triptime * triptime;
208 if (triptime < ping_stat->tmin)
209 ping_stat->tmin = triptime;
210 if (triptime > ping_stat->tmax)
211 ping_stat->tmax = triptime;
212 }
213
214 if (options & OPT_QUIET)
215 return 0;
216 if (options & OPT_FLOOD)
217 {
218 putchar ('\b');
219 return 0;
220 }
221
222 printf ("%d bytes from %s: icmp_seq=%u", datalen,
223 inet_ntoa (*(struct in_addr *) &from->sin_addr.s_addr),
224 ntohs (icmp->icmp_seq));
225 printf (" ttl=%d", ip->ip_ttl);
226 if (timing)
227 printf (" time=%.3f ms", triptime);
228 if (dupflag)
229 printf (" (DUP!)");
230
231 print_ip_opt (ip, hlen);
232 printf ("\n");
233
234 return 0;
235 }
236
237 #define NITEMS(a) sizeof(a)/sizeof((a)[0])
238
239 struct icmp_diag
240 {
241 int type;
242 char *text;
243 void (*fun) (icmphdr_t *, void *data);
244 void *data;
245 };
246
247 struct icmp_code_descr
248 {
249 int type;
250 int code;
251 char *diag;
252 } icmp_code_descr[] = {
253 {ICMP_DEST_UNREACH, ICMP_NET_UNREACH, "Destination Net Unreachable"},
254 {ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, "Destination Host Unreachable"},
255 {ICMP_DEST_UNREACH, ICMP_PROT_UNREACH, "Destination Protocol Unreachable"},
256 {ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, "Destination Port Unreachable"},
257 {ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED, "Fragmentation needed and DF set"},
258 {ICMP_DEST_UNREACH, ICMP_SR_FAILED, "Source Route Failed"},
259 {ICMP_DEST_UNREACH, ICMP_NET_UNKNOWN, "Network Unknown"},
260 {ICMP_DEST_UNREACH, ICMP_HOST_UNKNOWN, "Host Unknown"},
261 {ICMP_DEST_UNREACH, ICMP_HOST_ISOLATED, "Host Isolated"},
262 {ICMP_DEST_UNREACH, ICMP_NET_UNR_TOS,
263 "Destination Network Unreachable At This TOS"},
264 {ICMP_DEST_UNREACH, ICMP_HOST_UNR_TOS,
265 "Destination Host Unreachable At This TOS"},
266 #ifdef ICMP_PKT_FILTERED
267 {ICMP_DEST_UNREACH, ICMP_PKT_FILTERED, "Packet Filtered"},
268 #endif
269 #ifdef ICMP_PREC_VIOLATION
270 {ICMP_DEST_UNREACH, ICMP_PREC_VIOLATION, "Precedence Violation"},
271 #endif
272 #ifdef ICMP_PREC_CUTOFF
273 {ICMP_DEST_UNREACH, ICMP_PREC_CUTOFF, "Precedence Cutoff"},
274 #endif
275 {ICMP_REDIRECT, ICMP_REDIR_NET, "Redirect Network"},
276 {ICMP_REDIRECT, ICMP_REDIR_HOST, "Redirect Host"},
277 {ICMP_REDIRECT, ICMP_REDIR_NETTOS, "Redirect Type of Service and Network"},
278 {ICMP_REDIRECT, ICMP_REDIR_HOSTTOS, "Redirect Type of Service and Host"},
279 {ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, "Time to live exceeded"},
280 {ICMP_TIME_EXCEEDED, ICMP_EXC_FRAGTIME, "Frag reassembly time exceeded"}
281 };
282
283 static void
284 print_icmp_code (int type, int code, char *prefix)
285 {
286 struct icmp_code_descr *p;
287
288 for (p = icmp_code_descr; p < icmp_code_descr + NITEMS (icmp_code_descr);
289 p++)
290 if (p->type == type && p->code == code)
291 {
292 printf ("%s\n", p->diag);
293 return;
294 }
295
296 printf ("%s, Unknown Code: %d\n", prefix, code);
297 }
298
299 static void
300 print_ip_header (struct ip *ip)
301 {
302 size_t hlen;
303 unsigned char *cp;
304
305 hlen = ip->ip_hl << 2;
306 cp = (unsigned char *) ip + sizeof (*ip); /* point to options */
307
308 if (options & OPT_VERBOSE)
309 {
310 size_t j;
311
312 printf ("IP Hdr Dump:\n ");
313 for (j = 0; j < sizeof (*ip); ++j)
314 printf ("%02x%s", *((unsigned char *) ip + j), (j % 2) ? " " : ""); /* Group bytes two by two. */
315 printf ("\n");
316 }
317
318 printf ("Vr HL TOS Len ID Flg off TTL Pro cks Src\tDst\tData\n");
319 printf (" %1x %1x %02x", ip->ip_v, ip->ip_hl, ip->ip_tos);
320 /*
321 * The member `ip_len' is not portably reported in any byte order.
322 * Use a simple heuristic to print a reasonable value.
323 */
324 printf (" %04x %04x",
325 (ip->ip_len > 0x2000) ? ntohs (ip->ip_len) : ip->ip_len,
326 ntohs (ip->ip_id));
327 printf (" %1x %04x", (ntohs (ip->ip_off) & 0xe000) >> 13,
328 ntohs (ip->ip_off) & 0x1fff);
329 printf (" %02x %02x %04x", ip->ip_ttl, ip->ip_p, ntohs (ip->ip_sum));
330 printf (" %s ", inet_ntoa (*((struct in_addr *) &ip->ip_src)));
331 printf (" %s ", inet_ntoa (*((struct in_addr *) &ip->ip_dst)));
332 while (hlen-- > sizeof (*ip))
333 printf ("%02x", *cp++);
334
335 printf ("\n");
336 }
337
338 void
339 print_ip_data (icmphdr_t *icmp, void *data MAYBE_UNUSED)
340 {
341 int hlen;
342 unsigned char *cp;
343 struct ip *ip = &icmp->icmp_ip;
344
345 print_ip_header (ip);
346
347 hlen = ip->ip_hl << 2;
348 cp = (unsigned char *) ip + hlen;
349
350 if (ip->ip_p == IPPROTO_TCP)
351 printf ("TCP: from port %u, to port %u (decimal)\n",
352 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
353 else if (ip->ip_p == IPPROTO_UDP)
354 printf ("UDP: from port %u, to port %u (decimal)\n",
355 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
356 else if (ip->ip_p == IPPROTO_ICMP)
357 {
358 int type = *cp;
359 int code = *(cp + 1);
360
361 printf ("ICMP: type %u, code %u, size %u", type, code,
362 ntohs (ip->ip_len) - hlen);
363 if (type == ICMP_ECHOREPLY || type == ICMP_ECHO)
364 printf (", id 0x%04x, seq 0x%04x", *(cp + 4) * 256 + *(cp + 5),
365 *(cp + 6) * 256 + *(cp + 7));
366 printf ("\n");
367 }
368 }
369
370 static void
371 print_icmp (icmphdr_t *icmp, void *data)
372 {
373 print_icmp_code (icmp->icmp_type, icmp->icmp_code, data);
374 if (options & OPT_VERBOSE)
375 print_ip_data (icmp, NULL);
376 }
377
378 static void
379 print_parameterprob (icmphdr_t *icmp, void *data)
380 {
381 printf ("Parameter problem: IP address = %s\n",
382 inet_ntoa (icmp->icmp_gwaddr));
383 print_ip_data (icmp, data);
384 }
385
386 struct icmp_diag icmp_diag[] = {
387 {ICMP_ECHOREPLY, "Echo Reply", NULL, NULL},
388 {ICMP_DEST_UNREACH, NULL, print_icmp, "Dest Unreachable"},
389 {ICMP_SOURCE_QUENCH, "Source Quench", print_ip_data, NULL},
390 {ICMP_REDIRECT, NULL, print_icmp, "Redirect"},
391 {ICMP_ECHO, "Echo Request", NULL, NULL},
392 {ICMP_ROUTERADV, "Router Advertisement", NULL, NULL},
393 {ICMP_ROUTERDISCOVERY, "Router Discovery", NULL, NULL},
394 {ICMP_TIME_EXCEEDED, NULL, print_icmp, "Time exceeded"},
395 {ICMP_PARAMETERPROB, NULL, print_parameterprob, NULL},
396 {ICMP_TIMESTAMP, "Timestamp", NULL, NULL},
397 {ICMP_TIMESTAMPREPLY, "Timestamp Reply", NULL, NULL},
398 {ICMP_INFO_REQUEST, "Information Request", NULL, NULL},
399 {ICMP_INFO_REPLY, "Information Reply", NULL, NULL},
400 {ICMP_ADDRESS, "Address Mask Request", NULL, NULL},
401 {ICMP_ADDRESSREPLY, "Address Mask Reply", NULL, NULL},
402 };
403
404 void
405 print_icmp_header (struct sockaddr_in *from,
406 struct ip *ip, icmphdr_t *icmp, int len)
407 {
408 int hlen;
409 struct ip *orig_ip;
410 char *s;
411 struct icmp_diag *p;
412
413 /* Length of the IP header */
414 hlen = ip->ip_hl << 2;
415 /* Original IP header */
416 orig_ip = &icmp->icmp_ip;
417
418 if (!(options & OPT_VERBOSE
419 || orig_ip->ip_dst.s_addr ==
420 ping->ping_dest.ping_sockaddr.sin_addr.s_addr))
421 return;
422
423 s = ipaddr2str ((struct sockaddr *) from, sizeof (*from));
424 printf ("%d bytes from %s: ", len - hlen, s);
425 free (s);
426
427 for (p = icmp_diag; p < icmp_diag + NITEMS (icmp_diag); p++)
428 {
429 if (p->type == icmp->icmp_type)
430 {
431 if (p->text)
432 printf ("%s\n", p->text);
433 if (p->fun)
434 p->fun (icmp, p->data);
435 return;
436 }
437 }
438 printf ("Bad ICMP type: %d\n", icmp->icmp_type);
439 }
440
441 void
442 print_ip_opt (struct ip *ip, int hlen)
443 {
444 unsigned char *cp;
445 int i, j, k, l;
446 static int old_rrlen;
447 static char old_rr[MAX_IPOPTLEN];
448
449 cp = (unsigned char *) (ip + 1);
450
451 for (; hlen > (int) sizeof (struct ip); --hlen, ++cp)
452 switch (*cp)
453 {
454 case IPOPT_EOL:
455 hlen = 0;
456 break;
457
458 case IPOPT_LSRR:
459 case IPOPT_SSRR:
460 printf ("\n%cSRR: ", (*cp == IPOPT_LSRR) ? 'L' : 'S');
461 hlen -= 2;
462 j = *++cp;
463 ++cp;
464 if (j > IPOPT_MINOFF)
465 for (;;)
466 {
467 /* Fetch in network byte order, calculate as host. */
468 l = *++cp;
469 l = (l << 8) + *++cp;
470 l = (l << 8) + *++cp;
471 l = (l << 8) + *++cp;
472 if (l == 0)
473 {
474 printf ("\t0.0.0.0");
475 }
476 else
477 {
478 struct in_addr ina;
479 char *s;
480
481 ina.s_addr = htonl (l);
482 printf ("\t%s", s = sinaddr2str (ina));
483 free (s);
484 }
485 hlen -= 4;
486 j -= 4;
487 if (j <= IPOPT_MINOFF)
488 break;
489 putchar ('\n');
490 }
491 break;
492
493 case IPOPT_RR:
494 j = *++cp;
495 i = *++cp;
496 hlen -= 2;
497 if (i > j)
498 i = j;
499 i -= IPOPT_MINOFF;
500 if (i <= 0)
501 break;
502 if (i == old_rrlen
503 && cp == (unsigned char *) (ip + 1) + 2
504 && !memcmp ((char *) cp, old_rr, i) && !(options & OPT_FLOOD))
505 {
506 printf ("\t (same route)");
507 i = ((i + 3) / 4) * 4;
508 hlen -= i;
509 cp += i;
510 break;
511 }
512 if (i < MAX_IPOPTLEN)
513 {
514 old_rrlen = i;
515 memmove (old_rr, cp, i);
516 }
517 else
518 old_rrlen = 0;
519
520 printf ("\nRR: ");
521 j = 0;
522 for (;;)
523 {
524 /* Fetch in network byte order, calculate as host. */
525 l = *++cp;
526 l = (l << 8) + *++cp;
527 l = (l << 8) + *++cp;
528 l = (l << 8) + *++cp;
529 if (l == 0)
530 {
531 printf ("\t0.0.0.0");
532 }
533 else
534 {
535 struct in_addr ina;
536 char *s;
537
538 ina.s_addr = htonl (l);
539 printf ("\t%s", s = sinaddr2str (ina));
540 free (s);
541 }
542 hlen -= 4;
543 i -= 4;
544 j += 4;
545 if (i <= 0)
546 break;
547 if (j >= MAX_IPOPTLEN)
548 {
549 printf ("\t (truncated route)");
550 break;
551 }
552 putchar ('\n');
553 }
554 break;
555
556 case IPOPT_TS:
557 j = *++cp; /* len */
558 i = *++cp; /* ptr */
559 hlen -= 2;
560 if (i > j)
561 i = j;
562
563 /* Check minimal sizing. */
564 if (j <= (int) (IPOPT_MINOFF + sizeof (n_time)))
565 break;
566
567 k = *++cp; /* OV, FL */
568 ++cp; /* Points at first content. */
569 hlen -= 2;
570
571 printf ("\nTS:");
572 j = 5; /* First possible slot. */
573 for (;;)
574 {
575 char timestr[16];
576
577 if ((k & 0x0f) != IPOPT_TS_TSONLY && ((j / 4) % 2 == 1)) /* find 5, 13, 21, 29 */
578 {
579 /* IP addresses */
580 struct in_addr ina;
581 char *s;
582
583 ina.s_addr = *((in_addr_t *) cp);
584 printf ("\t%s", s = sinaddr2str (ina));
585 free (s);
586
587 hlen -= sizeof (in_addr_t);
588 cp += sizeof (in_addr_t);
589 j += sizeof (in_addr_t);
590 }
591 else
592 {
593 /* Timestamps */
594 printf ("\t%s ms",
595 ping_cvt_time (timestr, sizeof (timestr),
596 ntohl (*(n_time *) cp)));
597 if (options & OPT_VERBOSE)
598 printf (" = 0x%08x", ntohl (*(n_time *) cp));
599
600 hlen -= sizeof (n_time);
601 cp += sizeof (n_time);
602 j += sizeof (n_time);
603
604 putchar ('\n');
605 }
606
607 if (j >= i)
608 break;
609 }
610
611 if (k & 0xf0)
612 printf ("\t(%u overflowing hosts)", k >> 4);
613 break;
614
615 case IPOPT_NOP:
616 printf ("\nNOP");
617 break;
618
619 default:
620 printf ("\nunknown option %x", *cp);
621 break;
622 }
623 }
624
625 int
626 echo_finish (void)
627 {
628 ping_finish ();
629 if (ping->ping_num_recv && PING_TIMING (data_length))
630 {
631 struct ping_stat *ping_stat = (struct ping_stat *) ping->ping_closure;
632 double total = ping->ping_num_recv + ping->ping_num_rept;
633 double avg = ping_stat->tsum / total;
634 double vari = ping_stat->tsumsq / total - avg * avg;
635
636 printf ("round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
637 ping_stat->tmin, avg, ping_stat->tmax, nsqrt (vari, 0.0005));
638 }
639 return (ping->ping_num_recv == 0);
640 }