Debian Codegraph @

madrisan-nagios-plugins-linux/nagios-plugins-linux/lib/netinfo-private.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 /*
3 * License: GPLv3+
4 * Copyright (c) 2014,2020 Davide Madrisan <[email protected]>
5 *
6 * A library for getting some network interfaces.statistics.
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *
21 */
22
23 #include <errno.h>
24 #include <ifaddrs.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/ioctl.h>
29 #include <unistd.h>
30 #include <linux/ethtool.h>
31 #ifdef HAVE_LINUX_IF_LINK_H
32 # include <linux/if_link.h>
33 #endif
34 #include <linux/netlink.h>
35 #include <linux/rtnetlink.h>
36 #include <linux/sockios.h>
37 #include <linux/wireless.h>
38
39 #include "common.h"
40 #include "logging.h"
41 #include "messages.h"
42 #include "netinfo.h"
43 #include "string-macros.h"
44 #include "system.h"
45 #include "xalloc.h"
46
47 typedef struct nl_req_s
48 {
49 struct nlmsghdr hdr;
50 struct rtgenmsg gen;
51 } nl_req_t;
52
53 const char *const duplex_table[_DUP_MAX] = {
54 [DUPLEX_HALF] = "half",
55 [DUPLEX_FULL] = "full"
56 };
57
58 const struct link_speed
59 {
60 long phy_speed;
61 const char *phy_speed_str;
62 } phy_speed_to_str[] = {
63 { SPEED_10, "10Mbps" },
64 { SPEED_100, "100Mbps" },
65 { SPEED_1000, "1Gbps" },
66 { SPEED_2500, "2.5Gbps" },
67 { SPEED_5000, "5Gbps" },
68 { SPEED_10000, "10Gbps" },
69 #if defined (SPEED_14000)
70 { SPEED_14000, "14Gbps" },
71 #endif
72 #if defined (SPEED_20000)
73 { SPEED_20000, "20Gbps" },
74 #endif
75 #if defined (SPEED_25000)
76 { SPEED_25000, "25Gbps" },
77 #endif
78 #if defined (SPEED_40000)
79 { SPEED_40000, "40Gbps" },
80 #endif
81 #if defined (SPEED_50000)
82 { SPEED_50000, "50Gbps" },
83 #endif
84 #if defined (SPEED_56000)
85 { SPEED_56000, "56Gbps" },
86 #endif
87 #if defined (SPEED_100000)
88 { SPEED_100000, "100Gbps" },
89 #endif
90 { SPEED_UNKNOWN, "unknown!" }
91 };
92 static const size_t link_speed_size =
93 sizeof (phy_speed_to_str) / sizeof (phy_speed_to_str[0]);
94
95 static int
96 get_ctl_fd (void)
97 {
98 int fd;
99 int s_errno;
100
101 if ((fd = socket (PF_INET, SOCK_DGRAM, 0)) >= 0)
102 return fd;
103 s_errno = errno;
104 if ((fd = socket (PF_PACKET, SOCK_DGRAM, 0)) >= 0)
105 return fd;
106 if ((fd = socket (PF_INET6, SOCK_DGRAM, 0)) >= 0)
107 return fd;
108
109 errno = s_errno;
110 return -1;
111 }
112
113 static const char *
114 map_speed_value_for_key (const struct link_speed * map, long phy_speed)
115 {
116 const char* ret = NULL;
117 for (size_t i = 0 ; i < link_speed_size && ret == NULL; i++)
118 if (map[i].phy_speed == phy_speed)
119 ret = map[i].phy_speed_str;
120
121 return ret ? ret : "unknown!";
122 }
123
124 /* Determines network interface speed from ETHTOOL_GLINKSETTINGS
125 * (requires Linux kernel 4.9+).
126 * In case of failure revert to obsolete ETHTOOL_GSET. */
127
128 static int
129 check_link_speed (const char *ifname, uint32_t *speed, uint8_t *duplex)
130 {
131 int fd, ret = -1;
132 struct ifreq ifr = {};
133 struct ethtool_cmd ecmd = {
134 .cmd = ETHTOOL_GSET
135 };
136 #ifdef ETHTOOL_GLINKSETTINGS
137 # define ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NU32 (SCHAR_MAX)
138 struct elinkset {
139 uint32_t link_mode_data[3 * ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NU32];
140 struct ethtool_link_settings req;
141 } elinkset;
142 #endif
143
144 if ((fd = get_ctl_fd ()) < 0)
145 plugin_error (STATE_UNKNOWN, errno, "socket() failed");
146
147 *duplex = DUPLEX_UNKNOWN;
148 *speed = 0; /* SPEED_UNKNOWN */
149 STRNCPY_TERMINATED (ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
150
151 #ifdef ETHTOOL_GLINKSETTINGS
152
153 /* The interaction user/kernel via the new API requires a small
154 * ETHTOOL_GLINKSETTINGS handshake first to agree on the length
155 * of the link mode bitmaps. If kernel doesn't agree with user,
156 * it returns the bitmap length it is expecting from user as a
157 * negative length (and cmd field is 0). When kernel and user
158 * agree, kernel returns valid info in all fields (ie. link mode
159 * length > 0 and cmd is ETHTOOL_GLINKSETTINGS). Based on
160 * https://github.com/torvalds/linux/commit/3f1ac7a700d039c61d8d8b99f28d605d489a60cf
161 */
162
163 dbg ("ETHTOOL_GLINKSETTINGS is defined\n");
164 memset (&elinkset, 0, sizeof (elinkset));
165 elinkset.req.cmd = ETHTOOL_GLINKSETTINGS;
166 ifr.ifr_data = (void *) &elinkset;
167
168 ret = ioctl (fd, SIOCETHTOOL, &ifr);
169 /* see above: we expect a strictly negative value from kernel. */
170 if (ret >= 0 && (elinkset.req.link_mode_masks_nwords < 0))
171 {
172 elinkset.req.cmd = ETHTOOL_GLINKSETTINGS;
173 elinkset.req.link_mode_masks_nwords = -elinkset.req.link_mode_masks_nwords;
174
175 ret = ioctl (fd, SIOCETHTOOL, &ifr);
176 if (ret < 0 || elinkset.req.link_mode_masks_nwords <= 0
177 || elinkset.req.cmd != ETHTOOL_GLINKSETTINGS)
178 ret = -ENOTSUP;
179 }
180
181 #endif
182
183 if (ret < 0)
184 {
185 dbg ("%s: revert to the obsolete ETHTOOL_GSET...\n", ifname);
186 ifr.ifr_data = (void *) &ecmd;
187 if ((ret = ioctl (fd, SIOCETHTOOL, &ifr)) == 0)
188 {
189 *duplex = ecmd.duplex;
190 *speed = ecmd.speed;
191 }
192 else
193 dbg ("%s: no link speed associated to this interface\n", ifname);
194 }
195 #ifdef ETHTOOL_GLINKSETTINGS
196 else
197 {
198 *duplex = elinkset.req.duplex;
199 *speed = elinkset.req.speed;
200 }
201 #endif
202
203 dbg ("%s: duplex %s (%d), speed is %s (%u)\n"
204 , ifname
205 , *duplex == _DUP_UNKNOWN ? "invalid" : duplex_table[*duplex]
206 , *duplex
207 , map_speed_value_for_key (phy_speed_to_str, *speed)
208 , *speed);
209
210 /* normalize the unknown speed values */
211 if (*speed == (uint16_t)(-1) || *speed == (uint32_t)(-1))
212 {
213 dbg ("%s: normalizing the unknown speed to zero...\n", ifname);
214 *speed = 0;
215 }
216
217 close (fd);
218 return ret;
219 }
220
221 static bool
222 link_wireless (const char *ifname)
223 {
224 bool is_wireless = false;
225 int sock;
226 struct iwreq pwrq;
227
228 if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0)
229 plugin_error (STATE_UNKNOWN, errno, "socket() failed");
230
231 memset (&pwrq, 0, sizeof (pwrq));
232 strncpy (pwrq.ifr_name, ifname, IFNAMSIZ);
233
234 if (ioctl (sock, SIOCGIWNAME, &pwrq) != -1)
235 {
236 dbg ("%s: wireless interface (%s)\n"
237 , ifname
238 , pwrq.u.name);
239 is_wireless = true;
240 }
241
242 close (sock);
243 return is_wireless;
244 }
245
246 /* Get the RTNL socket */
247 static int
248 get_rtnl_fd ()
249 {
250 int fd;
251 union
252 {
253 struct sockaddr addr;
254 struct sockaddr_nl local; /* local (user space) addr struct */
255 } u;
256
257 fd = socket (AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
258 if (fd < 0)
259 plugin_error (STATE_UNKNOWN, errno, "failed to create netlink socket");
260
261 memset (&u.local, 0, sizeof (u.local));
262 u.local.nl_family = AF_NETLINK;
263 u.local.nl_groups = 0;
264 u.local.nl_pid = 0;
265
266 if (bind (fd, &u.addr, sizeof (u.addr)) < 0)
267 {
268 close (fd);
269 plugin_error (STATE_UNKNOWN, errno, "failed to bind netlink socket");
270 }
271
272 return fd;
273 }
274
275 /* Prepare and send the RTNL request for dumping the network links
276 * configuration */
277 static int
278 sendmsg_rtnl_links_dump (int fd, struct iovec *iov, struct sockaddr_nl *kernel)
279 {
280 nl_req_t req; /* structure that describes the rtnetlink packet itself */
281 struct msghdr rtnl_msg; /* generic msghdr struct for use with sendmsg */
282
283 memset (&rtnl_msg, 0, sizeof (rtnl_msg));
284 memset (kernel, 0, sizeof (*kernel));
285 memset (&req, 0, sizeof (req));
286
287 kernel->nl_family = AF_NETLINK;
288
289 req.hdr.nlmsg_len = NLMSG_LENGTH (sizeof (struct rtgenmsg));
290 req.hdr.nlmsg_type = RTM_GETLINK;
291 req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
292 req.hdr.nlmsg_seq = 1;
293 req.hdr.nlmsg_pid = getpid ();
294 /* no preferred AF, we will get all interfaces */
295 req.gen.rtgen_family = AF_PACKET;
296
297 iov->iov_base = &req;
298 iov->iov_len = req.hdr.nlmsg_len;
299 rtnl_msg.msg_iov = iov;
300 rtnl_msg.msg_iovlen = 1;
301 rtnl_msg.msg_name = kernel;
302 rtnl_msg.msg_namelen = sizeof (*kernel);
303
304 if (sendmsg (fd, (struct msghdr *) &rtnl_msg, 0) < 0)
305 return errno;
306
307 return 0;
308 }
309
310 static int
311 parse_rtattr (struct rtattr *tb[], int max, struct rtattr *rta, int len)
312 {
313 memset (tb, 0, sizeof (struct rtattr *) * (max + 1));
314
315 while (RTA_OK (rta, len))
316 {
317 if (rta->rta_type <= max)
318 tb[rta->rta_type] = rta;
319 rta = RTA_NEXT (rta,len);
320 }
321
322 return 0;
323 }
324
325 #define IFLIST_REPLY_BUFFER 8192
326
327 struct iflist *
328 get_netinfo_snapshot (unsigned int options, const regex_t *if_regex)
329 {
330 bool msg_done = false,
331 opt_ignore_loopback = (options & NO_LOOPBACK),
332 opt_ignore_wireless = (options & NO_WIRELESS);
333 char reply[IFLIST_REPLY_BUFFER];
334 int fd, ret;
335 struct iflist *iflhead = NULL, *iflprev = NULL;
336
337 /* netlink structures */
338 struct iovec iov; /* IO vector for sendmsg */
339 /* the remote (kernel space) side of the communication */
340 struct sockaddr_nl kernel;
341
342 fd = get_rtnl_fd ();
343 ret = sendmsg_rtnl_links_dump (fd, &iov, &kernel);
344 if (ret != 0)
345 plugin_error (STATE_UNKNOWN, ret, "error in sendmsg");
346
347 while (!msg_done)
348 {
349 /* parse reply */
350 ssize_t len;
351 struct nlmsghdr *h;
352 struct msghdr rtnl_reply;
353 struct iovec io_reply;
354
355 memset (&io_reply, 0, sizeof (io_reply));
356 memset (&rtnl_reply, 0, sizeof (rtnl_reply));
357
358 iov.iov_base = reply;
359 iov.iov_len = IFLIST_REPLY_BUFFER;
360 rtnl_reply.msg_iov = &iov;
361 rtnl_reply.msg_iovlen = 1;
362 rtnl_reply.msg_name = &kernel;
363 rtnl_reply.msg_namelen = sizeof (kernel);
364
365 /* read as much data as fits in the receive buffer */
366 if ((len = recvmsg (fd, &rtnl_reply, MSG_DONTWAIT)) < 0)
367 {
368 usleep (250000); /* sleep for a while */
369 continue;
370 }
371
372 char name[IFNAMSIZ];
373 int attr_len;
374 struct iflist *ifl;
375 struct ifinfomsg *ifi;
376 struct rtattr *tb[IFLA_MAX+1];
377 struct rtnl_link_stats *stats;
378
379 for (h = (struct nlmsghdr *) reply;
380 NLMSG_OK (h, len); h = NLMSG_NEXT (h, len))
381 {
382 switch (h->nlmsg_type)
383 {
384 /* this is the special meaning NLMSG_DONE message we asked for
385 * by using NLM_F_DUMP flag */
386 case NLMSG_DONE:
387 msg_done = true;
388 break;
389 case RTM_NEWLINK:
390 ifi = NLMSG_DATA (h);
391 attr_len = h->nlmsg_len - NLMSG_LENGTH (sizeof (*ifi));
392
393 parse_rtattr (tb, IFLA_MAX, IFLA_RTA (ifi), attr_len);
394 if (NULL == tb[IFLA_IFNAME])
395 plugin_error (STATE_UNKNOWN, 0,
396 "BUG: nil ifname returned by parse_rtattr()");
397
398 strcpy (name, (char *) RTA_DATA (tb[IFLA_IFNAME]));
399
400 bool is_loopback = if_flags_LOOPBACK (ifi->ifi_flags);
401 bool is_wireless = link_wireless (name);
402 bool skip_interface =
403 ((is_loopback && opt_ignore_loopback)
404 || (is_wireless && opt_ignore_wireless)
405 || (regexec (if_regex, name, (size_t) 0, NULL, 0)));
406 if (skip_interface)
407 {
408 dbg ("skipping network interface '%s'...\n", name);
409 continue;
410 }
411
412 /* create a new list structure 'ifl' and initialize
413 * all the members, except stats-related ones */
414 ifl = xmalloc (sizeof (struct iflist));
415 ifl->ifname = xstrdup (name);
416 ifl->flags = ifi->ifi_flags;
417 check_link_speed (name, &(ifl->speed), &(ifl->duplex));
418
419 ifl->next = NULL;
420 ifl->stats = NULL;
421
422 if (NULL == iflhead)
423 iflhead = ifl;
424 else
425 iflprev->next = ifl;
426 iflprev = ifl;
427
428 stats = (struct rtnl_link_stats *) RTA_DATA (tb[IFLA_STATS]);
429 if (stats)
430 {
431 /* copy the link statistics into the list structure 'ifl' */
432 ifl->stats = xmalloc (sizeof (struct ifstats));
433 ifl->stats->collisions = stats->collisions;
434 ifl->stats->multicast = stats->multicast;
435 ifl->stats->tx_packets = stats->tx_packets;
436 ifl->stats->rx_packets = stats->rx_packets;
437 ifl->stats->tx_bytes = stats->tx_bytes;
438 ifl->stats->rx_bytes = stats->rx_bytes;
439 ifl->stats->tx_errors = stats->tx_errors;
440 ifl->stats->rx_errors = stats->rx_errors;
441 ifl->stats->tx_dropped = stats->tx_dropped;
442 ifl->stats->rx_dropped = stats->rx_dropped;
443 }
444 else
445 dbg ("no network interface stats for '%s'...\n", name);
446 break;
447 }
448 }
449 }
450
451 close (fd);
452 return iflhead;
453 }
454
455 #undef IFLIST_REPLY_BUFFER