Debian Codegraph @

ping/ping.c

raw
1 /*
2 Copyright (C) 1998-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 #include <signal.h>
26
27 #include <netinet/in.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 <arpa/inet.h>
35 #include <netdb.h>
36 #include <unistd.h>
37 #include <stdlib.h>
38 #include <stdbool.h>
39 #include <string.h>
40 #include <stdio.h>
41 #include <ctype.h>
42 #include <errno.h>
43 #include <limits.h>
44 #ifdef HAVE_LOCALE_H
45 # include <locale.h>
46 #endif
47
48 #include <argp.h>
49 #include <attribute.h>
50 #include <timespec.h>
51 #include <ping.h>
52 #include "ping_impl.h"
53 #include "libinetutils.h"
54
55 extern int ping_echo (char *hostname);
56 extern int ping_timestamp (char *hostname);
57 extern int ping_address (char *hostname);
58 extern int ping_router (char *hostname);
59
60 PING *ping;
61 bool is_root = false;
62 unsigned char *data_buffer;
63 unsigned char *patptr;
64 int pattern_len = MAXPATTERN;
65 int socket_type;
66 size_t count = DEFAULT_PING_COUNT;
67 size_t interval;
68 size_t data_length = PING_DATALEN;
69 unsigned options;
70 unsigned int suboptions;
71 unsigned long preload = 0;
72 int tos = -1; /* Triggers with non-negative values. */
73 int ttl = 0;
74 int timeout = -1;
75 int linger = MAXWAIT;
76 int (*ping_type) (char *hostname) = ping_echo;
77
78 int (*decode_type (const char *arg)) (char *hostname);
79 static int decode_ip_timestamp (char *arg);
80 static int send_echo (PING * ping);
81
82 const char args_doc[] = "HOST ...";
83 const char doc[] = "Send ICMP ECHO_REQUEST packets to network hosts."
84 "\vOptions marked with (root only) are available only to " "superuser.";
85 const char *program_authors[] = {
86 "Sergey Poznyakoff",
87 NULL
88 };
89
90 /* Define keys for long options that do not have short counterparts. */
91 enum
92 {
93 ARG_ECHO = 256,
94 ARG_ADDRESS,
95 ARG_TIMESTAMP,
96 ARG_ROUTERDISCOVERY,
97 ARG_TTL,
98 ARG_IPTIMESTAMP,
99 };
100
101 static struct argp_option argp_options[] = {
102 #define GRP 0
103 {NULL, 0, NULL, 0, "Options controlling ICMP request types:", GRP},
104 {"address", ARG_ADDRESS, NULL, 0, "send ICMP_ADDRESS packets (root only)",
105 GRP + 1},
106 {"echo", ARG_ECHO, NULL, 0, "send ICMP_ECHO packets (default)", GRP + 1},
107 {"mask", ARG_ADDRESS, NULL, 0, "same as --address", GRP + 1},
108 {"timestamp", ARG_TIMESTAMP, NULL, 0, "send ICMP_TIMESTAMP packets",
109 GRP + 1},
110 {"type", 't', "TYPE", 0, "send TYPE packets", GRP + 1},
111 /* This option is not yet fully implemented, so mark it as hidden. */
112 {"router", ARG_ROUTERDISCOVERY, NULL, OPTION_HIDDEN, "send "
113 "ICMP_ROUTERDISCOVERY packets (root only)", GRP + 1},
114 #undef GRP
115 #define GRP 10
116 {NULL, 0, NULL, 0, "Options valid for all request types:", GRP},
117 {"count", 'c', "NUMBER", 0, "stop after sending NUMBER packets", GRP + 1},
118 {"debug", 'd', NULL, 0, "set the SO_DEBUG option", GRP + 1},
119 {"interval", 'i', "NUMBER", 0, "wait NUMBER seconds between sending each "
120 "packet", GRP + 1},
121 {"numeric", 'n', NULL, 0, "do not resolve host addresses", GRP + 1},
122 {"ignore-routing", 'r', NULL, 0, "send directly to a host on an attached "
123 "network", GRP + 1},
124 {"tos", 'T', "NUM", 0, "set type of service (TOS) to NUM", GRP + 1},
125 {"ttl", ARG_TTL, "N", 0, "specify N as time-to-live", GRP + 1},
126 {"verbose", 'v', NULL, 0, "verbose output", GRP + 1},
127 {"timeout", 'w', "N", 0, "stop after N seconds", GRP + 1},
128 {"linger", 'W', "N", 0, "number of seconds to wait for response", GRP + 1},
129 #undef GRP
130 #define GRP 20
131 {NULL, 0, NULL, 0, "Options valid for --echo requests:", GRP},
132 {"flood", 'f', NULL, 0, "flood ping (root only)", GRP + 1},
133 {"preload", 'l', "NUMBER", 0, "send NUMBER packets as fast as possible "
134 "before falling into normal mode of behavior (root only)", GRP + 1},
135 {"pattern", 'p', "PATTERN", 0, "fill ICMP packet with given pattern (hex)",
136 GRP + 1},
137 {"quiet", 'q', NULL, 0, "quiet output", GRP + 1},
138 {"route", 'R', NULL, 0, "record route", GRP + 1},
139 {"ip-timestamp", ARG_IPTIMESTAMP, "FLAG", 0, "IP timestamp of type FLAG, "
140 "which is one of \"tsonly\" and \"tsaddr\"", GRP + 1},
141 {"size", 's', "NUMBER", 0, "send NUMBER data octets", GRP + 1},
142 #undef GRP
143 {NULL, 0, NULL, 0, NULL, 0}
144 };
145
146 static error_t
147 parse_opt (int key, char *arg, struct argp_state *state)
148 {
149 char *endptr;
150 static unsigned char pattern[MAXPATTERN];
151 double v;
152
153 switch (key)
154 {
155 case 'c':
156 count = ping_cvt_number (arg, 0, 1);
157 break;
158
159 case 'd':
160 socket_type |= SO_DEBUG;
161 break;
162
163 case 'i':
164 v = strtod (arg, &endptr);
165 if (*endptr)
166 argp_error (state, "invalid value (`%s' near `%s')", arg, endptr);
167 options |= OPT_INTERVAL;
168 interval = v * PING_PRECISION;
169 if (!is_root && interval < PING_MIN_USER_INTERVAL)
170 error (EXIT_FAILURE, 0, "option value too small: %s", arg);
171 break;
172
173 case 'r':
174 socket_type |= SO_DONTROUTE;
175 break;
176
177 case 's':
178 data_length = ping_cvt_number (arg, PING_MAX_DATALEN, 1);
179 break;
180
181 case 'n':
182 options |= OPT_NUMERIC;
183 break;
184
185 case 'p':
186 decode_pattern (arg, &pattern_len, pattern);
187 patptr = pattern;
188 break;
189
190 case 'q':
191 options |= OPT_QUIET;
192 break;
193
194 case 'T':
195 tos = ping_cvt_number (arg, 255, 1);
196 break;
197
198 case 'w':
199 timeout = ping_cvt_number (arg, INT_MAX, 0);
200 break;
201
202 case 'R':
203 options |= OPT_RROUTE;
204 break;
205
206 case 'W':
207 linger = ping_cvt_number (arg, INT_MAX, 0);
208 break;
209
210 case 'v':
211 options |= OPT_VERBOSE;
212 break;
213
214 case 'l':
215 preload = strtoul (arg, &endptr, 0);
216 if (*endptr || preload > INT_MAX)
217 error (EXIT_FAILURE, 0, "invalid preload value (%s)", arg);
218 break;
219
220 case 'f':
221 options |= OPT_FLOOD;
222 break;
223
224 case 't':
225 ping_type = decode_type (arg);
226 break;
227
228 case ARG_ECHO:
229 ping_type = decode_type ("echo");
230 break;
231
232 case ARG_TIMESTAMP:
233 ping_type = decode_type ("timestamp");
234 break;
235
236 case ARG_ADDRESS:
237 ping_type = decode_type ("address");
238 break;
239
240 case ARG_ROUTERDISCOVERY:
241 ping_type = decode_type ("router");
242 break;
243
244 case ARG_TTL:
245 ttl = ping_cvt_number (arg, 255, 0);
246 break;
247
248 case ARG_IPTIMESTAMP:
249 options |= OPT_IPTIMESTAMP;
250 suboptions |= decode_ip_timestamp (arg);
251 break;
252
253 case ARGP_KEY_NO_ARGS:
254 argp_error (state, "missing host operand");
255
256 /* FALLTHROUGH */
257 default:
258 return ARGP_ERR_UNKNOWN;
259 }
260
261 return 0;
262 }
263
264 static struct argp argp =
265 { argp_options, parse_opt, args_doc, doc, NULL, NULL, NULL };
266
267 int
268 main (int argc, char **argv)
269 {
270 int index;
271 int one = 1;
272 int status = 0;
273
274 set_program_name (argv[0]);
275
276 #ifdef HAVE_SETLOCALE
277 setlocale (LC_ALL, "");
278 #endif
279
280 if (getuid () == 0)
281 is_root = true;
282
283 /* Parse command line */
284 iu_argp_init ("ping", program_authors);
285 argp_parse (&argp, argc, argv, 0, &index, NULL);
286
287 ping = ping_init (ICMP_ECHO, getpid ());
288 if (ping == NULL)
289 /* ping_init() prints our error message. */
290 exit (EXIT_FAILURE);
291
292 ping_set_sockopt (ping, SO_BROADCAST, (char *) &one, sizeof (one));
293
294 /* Reset root privileges */
295 if (setuid (getuid ()) != 0)
296 error (EXIT_FAILURE, errno, "setuid");
297
298 /* Force line buffering regardless of output device. */
299 setvbuf (stdout, NULL, _IOLBF, 0);
300
301 argv += index;
302 argc -= index;
303
304 if (count != 0)
305 ping_set_count (ping, count);
306
307 if (socket_type != 0)
308 ping_set_sockopt (ping, socket_type, &one, sizeof (one));
309
310 if (options & OPT_INTERVAL)
311 ping_set_interval (ping, interval);
312
313 if (ttl > 0)
314 if (setsockopt (ping->ping_fd, IPPROTO_IP, IP_TTL,
315 &ttl, sizeof (ttl)) < 0)
316 error (0, errno, "setsockopt(IP_TTL)");
317
318 if (tos >= 0)
319 if (setsockopt (ping->ping_fd, IPPROTO_IP, IP_TOS,
320 &tos, sizeof (tos)) < 0)
321 error (0, errno, "setsockopt(IP_TOS)");
322
323 init_data_buffer (patptr, pattern_len);
324
325 while (argc--)
326 {
327 status |= (*(ping_type)) (*argv++);
328 ping_reset (ping);
329 }
330
331 free (ping);
332 free (data_buffer);
333 return status;
334 }
335
336 int (*decode_type (const char *arg)) (char *hostname)
337 {
338 int (*ping_type) (char *hostname) = NULL;
339
340 if (strcasecmp (arg, "echo") == 0)
341 ping_type = ping_echo;
342 else if (strcasecmp (arg, "timestamp") == 0)
343 ping_type = ping_timestamp;
344 else if (strcasecmp (arg, "address") == 0)
345 ping_type = ping_address;
346 else if (strcasecmp (arg, "mask") == 0)
347 ping_type = ping_address;
348 #if 0
349 else if (strcasecmp (arg, "router") == 0)
350 ping_type = ping_router;
351 #endif
352 else
353 error (EXIT_FAILURE, 0, "unsupported packet type: %s", arg);
354
355 return ping_type;
356 }
357
358 int
359 decode_ip_timestamp (char *arg)
360 {
361 int sopt = 0;
362
363 if (strcasecmp (arg, "tsonly") == 0)
364 sopt = SOPT_TSONLY;
365 else if (strcasecmp (arg, "tsaddr") == 0)
366 sopt = SOPT_TSADDR;
367 #if 0 /* Not yet implemented. */
368 else if (strcasecmp (arg, "prespec") == 0)
369 sopt = SOPT_TSPRESPEC;
370 #endif
371 else
372 error (EXIT_FAILURE, 0, "unsupported timestamp type: %s", arg);
373
374 return sopt;
375 }
376
377 int volatile stop = 0;
378
379 void
380 sig_int (int signal MAYBE_UNUSED)
381 {
382 stop = 1;
383 }
384
385 int
386 ping_run (PING *ping, int (*finish) (void))
387 {
388 fd_set fdset;
389 int fdmax;
390 struct timespec resp_time;
391 struct timespec last, intvl, now;
392 struct timespec *t = NULL;
393 int finishing = 0;
394 size_t nresp = 0;
395 size_t i;
396
397 signal (SIGINT, sig_int);
398
399 fdmax = ping->ping_fd + 1;
400
401 for (i = 0; i < preload; i++)
402 send_echo (ping);
403
404 if (options & OPT_FLOOD)
405 {
406 intvl.tv_sec = 0;
407 intvl.tv_nsec = 1e7;
408 }
409 else
410 PING_SET_INTERVAL (intvl, ping->ping_interval);
411
412 last = current_timespec ();
413 send_echo (ping);
414
415 while (!stop)
416 {
417 int n;
418
419 FD_ZERO (&fdset);
420 FD_SET (ping->ping_fd, &fdset);
421 now = current_timespec ();
422 resp_time = timespec_sub (timespec_add (last, intvl), now);
423
424 if (timespec_sign (resp_time) == -1)
425 resp_time.tv_sec = resp_time.tv_nsec = 0;
426
427 n = pselect (fdmax, &fdset, NULL, NULL, &resp_time, NULL);
428 if (n < 0)
429 {
430 if (errno != EINTR)
431 error (EXIT_FAILURE, errno, "pselect failed");
432 continue;
433 }
434 else if (n == 1)
435 {
436 if (ping_recv (ping) == 0)
437 nresp++;
438 if (t == 0)
439 {
440 now = current_timespec ();
441 t = &now;
442 }
443
444 if (ping_timeout_p (&ping->ping_start_time, timeout))
445 break;
446
447 if (ping->ping_count && nresp >= ping->ping_count)
448 break;
449 }
450 else
451 {
452 if (!ping->ping_count || ping->ping_num_xmit < ping->ping_count)
453 {
454 send_echo (ping);
455 if (!(options & OPT_QUIET) && options & OPT_FLOOD)
456 putchar ('.');
457
458 if (ping_timeout_p (&ping->ping_start_time, timeout))
459 break;
460 }
461 else if (finishing)
462 break;
463 else
464 {
465 finishing = 1;
466
467 intvl.tv_sec = linger;
468 }
469 last = current_timespec ();
470 }
471 }
472
473 ping_unset_data (ping);
474
475 if (finish)
476 return (*finish) ();
477 return 0;
478 }
479
480 int
481 send_echo (PING *ping)
482 {
483 size_t off = 0;
484 int rc;
485
486 if (PING_TIMING (data_length))
487 {
488 struct timespec now = current_timespec ();
489 /* *INDENT-OFF* */
490 struct timeval tv = { .tv_sec = now.tv_sec,
491 .tv_usec = now.tv_nsec / 1000 };
492 /* *INDENT-ON* */
493 ping_set_data (ping, &tv, 0, sizeof (tv), USE_IPV6);
494 off += sizeof (tv);
495 }
496 if (data_buffer)
497 ping_set_data (ping, data_buffer, off,
498 data_length > off ? data_length - off : data_length,
499 USE_IPV6);
500
501 rc = ping_xmit (ping);
502 if (rc < 0)
503 error (EXIT_FAILURE, errno, "sending packet");
504
505 return rc;
506 }
507
508 int
509 ping_finish (void)
510 {
511 fflush (stdout);
512 printf ("--- %s ping statistics ---\n", ping->ping_hostname);
513 printf ("%zu packets transmitted, ", ping->ping_num_xmit);
514 printf ("%zu packets received, ", ping->ping_num_recv);
515 if (ping->ping_num_rept)
516 printf ("+%zu duplicates, ", ping->ping_num_rept);
517 if (ping->ping_num_xmit)
518 {
519 if (ping->ping_num_recv > ping->ping_num_xmit)
520 printf ("-- somebody is printing forged packets!");
521 else
522 printf ("%d%% packet loss",
523 (int) (((ping->ping_num_xmit - ping->ping_num_recv) * 100) /
524 ping->ping_num_xmit));
525
526 }
527 printf ("\n");
528 return 0;
529 }