]> granicus.if.org Git - strace/blob - socketutils.c
netlink: introduce a basic netlink attributes parser
[strace] / socketutils.c
1 /*
2  * Copyright (c) 2014 Zubin Mithra <zubin.mithra@gmail.com>
3  * Copyright (c) 2014-2016 Dmitry V. Levin <ldv@altlinux.org>
4  * Copyright (c) 2014-2017 The strace developers.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "defs.h"
31 #include <netinet/in.h>
32 #include <sys/socket.h>
33 #include <arpa/inet.h>
34 #include <linux/netlink.h>
35 #include <linux/sock_diag.h>
36 #include <linux/inet_diag.h>
37 #include <linux/unix_diag.h>
38 #include <linux/netlink_diag.h>
39 #include <linux/rtnetlink.h>
40 #if HAVE_LINUX_GENETLINK_H
41 #include <linux/genetlink.h>
42 #endif
43
44 #include <sys/un.h>
45 #ifndef UNIX_PATH_MAX
46 # define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) 0)->sun_path)
47 #endif
48
49 #ifndef NETLINK_SOCK_DIAG
50 # define NETLINK_SOCK_DIAG 4
51 #endif
52
53 typedef struct {
54         unsigned long inode;
55         char *details;
56 } cache_entry;
57
58 #define CACHE_SIZE 1024U
59 static cache_entry cache[CACHE_SIZE];
60 #define CACHE_MASK (CACHE_SIZE - 1)
61
62 static int
63 cache_inode_details(const unsigned long inode, char *const details)
64 {
65         cache_entry *e = &cache[inode & CACHE_MASK];
66         free(e->details);
67         e->inode = inode;
68         e->details = details;
69
70         return 1;
71 }
72
73 static const char *
74 get_sockaddr_by_inode_cached(const unsigned long inode)
75 {
76         const cache_entry *const e = &cache[inode & CACHE_MASK];
77         return (e && inode == e->inode) ? e->details : NULL;
78 }
79
80 static bool
81 print_sockaddr_by_inode_cached(const unsigned long inode)
82 {
83         const char *const details = get_sockaddr_by_inode_cached(inode);
84         if (details) {
85                 tprints(details);
86                 return true;
87         }
88         return false;
89 }
90
91 static bool
92 send_query(const int fd, void *req, size_t req_size)
93 {
94         struct sockaddr_nl nladdr = {
95                 .nl_family = AF_NETLINK
96         };
97         struct iovec iov = {
98                 .iov_base = req,
99                 .iov_len = req_size
100         };
101         const struct msghdr msg = {
102                 .msg_name = &nladdr,
103                 .msg_namelen = sizeof(nladdr),
104                 .msg_iov = &iov,
105                 .msg_iovlen = 1
106         };
107
108         for (;;) {
109                 if (sendmsg(fd, &msg, 0) < 0) {
110                         if (errno == EINTR)
111                                 continue;
112                         return false;
113                 }
114                 return true;
115         }
116 }
117
118 static bool
119 inet_send_query(const int fd, const int family, const int proto)
120 {
121         struct {
122                 const struct nlmsghdr nlh;
123                 const struct inet_diag_req_v2 idr;
124         } req = {
125                 .nlh = {
126                         .nlmsg_len = sizeof(req),
127                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
128                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
129                 },
130                 .idr = {
131                         .sdiag_family = family,
132                         .sdiag_protocol = proto,
133                         .idiag_states = -1
134                 }
135         };
136         return send_query(fd, &req, sizeof(req));
137 }
138
139 static int
140 inet_parse_response(const void *const data, const int data_len,
141                     const unsigned long inode, void *opaque_data)
142 {
143         const char *const proto_name = opaque_data;
144         const struct inet_diag_msg *const diag_msg = data;
145         static const char zero_addr[sizeof(struct in6_addr)];
146         socklen_t addr_size, text_size;
147
148         if (data_len < (int) NLMSG_LENGTH(sizeof(*diag_msg)))
149                 return -1;
150         if (diag_msg->idiag_inode != inode)
151                 return 0;
152
153         switch (diag_msg->idiag_family) {
154                 case AF_INET:
155                         addr_size = sizeof(struct in_addr);
156                         text_size = INET_ADDRSTRLEN;
157                         break;
158                 case AF_INET6:
159                         addr_size = sizeof(struct in6_addr);
160                         text_size = INET6_ADDRSTRLEN;
161                         break;
162                 default:
163                         return -1;
164         }
165
166         char src_buf[text_size];
167         char *details;
168
169         if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_src,
170                        src_buf, text_size))
171                 return -1;
172
173         if (diag_msg->id.idiag_dport ||
174             memcmp(zero_addr, diag_msg->id.idiag_dst, addr_size)) {
175                 char dst_buf[text_size];
176
177                 if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_dst,
178                                dst_buf, text_size))
179                         return -1;
180
181                 if (asprintf(&details, "%s:[%s:%u->%s:%u]", proto_name,
182                              src_buf, ntohs(diag_msg->id.idiag_sport),
183                              dst_buf, ntohs(diag_msg->id.idiag_dport)) < 0)
184                         return false;
185         } else {
186                 if (asprintf(&details, "%s:[%s:%u]", proto_name, src_buf,
187                              ntohs(diag_msg->id.idiag_sport)) < 0)
188                         return false;
189         }
190
191         return cache_inode_details(inode, details);
192 }
193
194 static bool
195 receive_responses(const int fd, const unsigned long inode,
196                   const unsigned long expected_msg_type,
197                   int (*parser)(const void *, int,
198                                 unsigned long, void *),
199                   void *opaque_data)
200 {
201         static union {
202                 struct nlmsghdr hdr;
203                 long buf[8192 / sizeof(long)];
204         } hdr_buf;
205
206         struct sockaddr_nl nladdr = {
207                 .nl_family = AF_NETLINK
208         };
209         struct iovec iov = {
210                 .iov_base = hdr_buf.buf,
211                 .iov_len = sizeof(hdr_buf.buf)
212         };
213         int flags = 0;
214
215         for (;;) {
216                 struct msghdr msg = {
217                         .msg_name = &nladdr,
218                         .msg_namelen = sizeof(nladdr),
219                         .msg_iov = &iov,
220                         .msg_iovlen = 1
221                 };
222
223                 ssize_t ret = recvmsg(fd, &msg, flags);
224                 if (ret < 0) {
225                         if (errno == EINTR)
226                                 continue;
227                         return false;
228                 }
229
230                 const struct nlmsghdr *h = &hdr_buf.hdr;
231                 if (!NLMSG_OK(h, ret))
232                         return false;
233                 for (; NLMSG_OK(h, ret); h = NLMSG_NEXT(h, ret)) {
234                         if (h->nlmsg_type != expected_msg_type)
235                                 return false;
236                         const int rc = parser(NLMSG_DATA(h),
237                                               h->nlmsg_len, inode, opaque_data);
238                         if (rc > 0)
239                                 return true;
240                         if (rc < 0)
241                                 return false;
242                 }
243                 flags = MSG_DONTWAIT;
244         }
245 }
246
247 static bool
248 unix_send_query(const int fd, const unsigned long inode)
249 {
250         struct {
251                 const struct nlmsghdr nlh;
252                 const struct unix_diag_req udr;
253         } req = {
254                 .nlh = {
255                         .nlmsg_len = sizeof(req),
256                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
257                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
258                 },
259                 .udr = {
260                         .sdiag_family = AF_UNIX,
261                         .udiag_ino = inode,
262                         .udiag_states = -1,
263                         .udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER
264                 }
265         };
266         return send_query(fd, &req, sizeof(req));
267 }
268
269 static int
270 unix_parse_response(const void *data, const int data_len,
271                     const unsigned long inode, void *opaque_data)
272 {
273         const char *proto_name = opaque_data;
274         const struct unix_diag_msg *diag_msg = data;
275         struct rtattr *attr;
276         int rta_len = data_len - NLMSG_LENGTH(sizeof(*diag_msg));
277         uint32_t peer = 0;
278         size_t path_len = 0;
279         char path[UNIX_PATH_MAX + 1];
280
281         if (rta_len < 0)
282                 return -1;
283         if (diag_msg->udiag_ino != inode)
284                 return 0;
285         if (diag_msg->udiag_family != AF_UNIX)
286                 return -1;
287
288         for (attr = (struct rtattr *) (diag_msg + 1);
289              RTA_OK(attr, rta_len);
290              attr = RTA_NEXT(attr, rta_len)) {
291                 switch (attr->rta_type) {
292                 case UNIX_DIAG_NAME:
293                         if (!path_len) {
294                                 path_len = RTA_PAYLOAD(attr);
295                                 if (path_len > UNIX_PATH_MAX)
296                                         path_len = UNIX_PATH_MAX;
297                                 memcpy(path, RTA_DATA(attr), path_len);
298                                 path[path_len] = '\0';
299                         }
300                         break;
301                 case UNIX_DIAG_PEER:
302                         if (RTA_PAYLOAD(attr) >= 4)
303                                 peer = *(uint32_t *) RTA_DATA(attr);
304                         break;
305                 }
306         }
307
308         /*
309          * print obtained information in the following format:
310          * "UNIX:[" SELF_INODE [ "->" PEER_INODE ][ "," SOCKET_FILE ] "]"
311          */
312         if (!peer && !path_len)
313                 return -1;
314
315         char peer_str[3 + sizeof(peer) * 3];
316         if (peer)
317                 snprintf(peer_str, sizeof(peer_str), "->%u", peer);
318         else
319                 peer_str[0] = '\0';
320
321         const char *path_str;
322         if (path_len) {
323                 char *outstr = alloca(4 * path_len + 4);
324
325                 outstr[0] = ',';
326                 if (path[0] == '\0') {
327                         outstr[1] = '@';
328                         string_quote(path + 1, outstr + 2,
329                                      path_len - 1, QUOTE_0_TERMINATED);
330                 } else {
331                         string_quote(path, outstr + 1,
332                                      path_len, QUOTE_0_TERMINATED);
333                 }
334                 path_str = outstr;
335         } else {
336                 path_str = "";
337         }
338
339         char *details;
340         if (asprintf(&details, "%s:[%lu%s%s]", proto_name, inode,
341                      peer_str, path_str) < 0)
342                 return -1;
343
344         return cache_inode_details(inode, details);
345 }
346
347 static bool
348 netlink_send_query(const int fd, const unsigned long inode)
349 {
350         struct {
351                 const struct nlmsghdr nlh;
352                 const struct netlink_diag_req ndr;
353         } req = {
354                 .nlh = {
355                         .nlmsg_len = sizeof(req),
356                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
357                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
358                 },
359                 .ndr = {
360                         .sdiag_family = AF_NETLINK,
361                         .sdiag_protocol = NDIAG_PROTO_ALL,
362                         .ndiag_show = NDIAG_SHOW_MEMINFO
363                 }
364         };
365         return send_query(fd, &req, sizeof(req));
366 }
367
368 static int
369 netlink_parse_response(const void *data, const int data_len,
370                        const unsigned long inode, void *opaque_data)
371 {
372         const char *proto_name = opaque_data;
373         const struct netlink_diag_msg *const diag_msg = data;
374         const char *netlink_proto;
375         char *details;
376
377         if (data_len < (int) NLMSG_LENGTH(sizeof(*diag_msg)))
378                 return -1;
379         if (diag_msg->ndiag_ino != inode)
380                 return 0;
381
382         if (diag_msg->ndiag_family != AF_NETLINK)
383                 return -1;
384
385         netlink_proto = xlookup(netlink_protocols,
386                                 diag_msg->ndiag_protocol);
387
388         if (netlink_proto) {
389                 netlink_proto = STR_STRIP_PREFIX(netlink_proto, "NETLINK_");
390                 if (asprintf(&details, "%s:[%s:%u]", proto_name,
391                              netlink_proto, diag_msg->ndiag_portid) < 0)
392                         return -1;
393         } else {
394                 if (asprintf(&details, "%s:[%u]", proto_name,
395                              (unsigned) diag_msg->ndiag_protocol) < 0)
396                         return -1;
397         }
398
399         return cache_inode_details(inode, details);
400 }
401
402 static const char *
403 unix_get(const int fd, const unsigned long inode)
404 {
405         return unix_send_query(fd, inode)
406                 && receive_responses(fd, inode, SOCK_DIAG_BY_FAMILY,
407                                      unix_parse_response, (void *) "UNIX")
408                 ? get_sockaddr_by_inode_cached(inode) : NULL;
409 }
410
411 static const char *
412 inet_get(const int fd, const int family, const int protocol,
413          const unsigned long inode, const char *proto_name)
414 {
415         return inet_send_query(fd, family, protocol)
416                 && receive_responses(fd, inode, SOCK_DIAG_BY_FAMILY,
417                                      inet_parse_response, (void *) proto_name)
418                 ? get_sockaddr_by_inode_cached(inode) : NULL;
419 }
420
421 static const char *
422 tcp_v4_get(const int fd, const unsigned long inode)
423 {
424         return inet_get(fd, AF_INET, IPPROTO_TCP, inode, "TCP");
425 }
426
427 static const char *
428 udp_v4_get(const int fd, const unsigned long inode)
429 {
430         return inet_get(fd, AF_INET, IPPROTO_UDP, inode, "UDP");
431 }
432
433 static const char *
434 tcp_v6_get(const int fd, const unsigned long inode)
435 {
436         return inet_get(fd, AF_INET6, IPPROTO_TCP, inode, "TCPv6");
437 }
438
439 static const char *
440 udp_v6_get(const int fd, const unsigned long inode)
441 {
442         return inet_get(fd, AF_INET6, IPPROTO_UDP, inode, "UDPv6");
443 }
444
445 static const char *
446 netlink_get(const int fd, const unsigned long inode)
447 {
448         return netlink_send_query(fd, inode)
449                 && receive_responses(fd, inode, SOCK_DIAG_BY_FAMILY,
450                                      netlink_parse_response, (void *) "NETLINK")
451                 ? get_sockaddr_by_inode_cached(inode) : NULL;
452 }
453
454 static const struct {
455         const char *const name;
456         const char * (*const get)(int, unsigned long);
457 } protocols[] = {
458         [SOCK_PROTO_UNIX] = { "UNIX", unix_get },
459         [SOCK_PROTO_TCP] = { "TCP", tcp_v4_get },
460         [SOCK_PROTO_UDP] = { "UDP", udp_v4_get },
461         [SOCK_PROTO_TCPv6] = { "TCPv6", tcp_v6_get },
462         [SOCK_PROTO_UDPv6] = { "UDPv6", udp_v6_get },
463         [SOCK_PROTO_NETLINK] = { "NETLINK", netlink_get }
464 };
465
466 enum sock_proto
467 get_proto_by_name(const char *const name)
468 {
469         unsigned int i;
470         for (i = (unsigned int) SOCK_PROTO_UNKNOWN + 1;
471              i < ARRAY_SIZE(protocols); ++i) {
472                 if (protocols[i].name && !strcmp(name, protocols[i].name))
473                         return (enum sock_proto) i;
474         }
475         return SOCK_PROTO_UNKNOWN;
476 }
477
478 static const char *
479 get_sockaddr_by_inode_uncached(const unsigned long inode,
480                                const enum sock_proto proto)
481 {
482         if ((unsigned int) proto >= ARRAY_SIZE(protocols) ||
483             (proto != SOCK_PROTO_UNKNOWN && !protocols[proto].get))
484                 return NULL;
485
486         const int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG);
487         if (fd < 0)
488                 return NULL;
489         const char *details = NULL;
490
491         if (proto != SOCK_PROTO_UNKNOWN) {
492                 details = protocols[proto].get(fd, inode);
493         } else {
494                 unsigned int i;
495                 for (i = (unsigned int) SOCK_PROTO_UNKNOWN + 1;
496                      i < ARRAY_SIZE(protocols); ++i) {
497                         if (!protocols[i].get)
498                                 continue;
499                         details = protocols[i].get(fd, inode);
500                         if (details)
501                                 break;
502                 }
503         }
504
505         close(fd);
506         return details;
507 }
508
509 static bool
510 print_sockaddr_by_inode_uncached(const unsigned long inode,
511                                  const enum sock_proto proto)
512 {
513         const char *details = get_sockaddr_by_inode_uncached(inode, proto);
514
515         if (details) {
516                 tprints(details);
517                 return true;
518         }
519
520         if ((unsigned int) proto < ARRAY_SIZE(protocols) &&
521             protocols[proto].name) {
522                 tprintf("%s:[%lu]", protocols[proto].name, inode);
523                 return true;
524         }
525
526         return false;
527 }
528
529 /* Given an inode number of a socket, return its protocol details.  */
530 const char *
531 get_sockaddr_by_inode(struct tcb *const tcp, const int fd,
532                       const unsigned long inode)
533 {
534         const char *details = get_sockaddr_by_inode_cached(inode);
535         return details ? details :
536                 get_sockaddr_by_inode_uncached(inode, getfdproto(tcp, fd));
537 }
538
539 /* Given an inode number of a socket, print out its protocol details.  */
540 bool
541 print_sockaddr_by_inode(struct tcb *const tcp, const int fd,
542                         const unsigned long inode)
543 {
544         return print_sockaddr_by_inode_cached(inode) ? true :
545                 print_sockaddr_by_inode_uncached(inode, getfdproto(tcp, fd));
546 }
547
548 #ifdef HAVE_LINUX_GENETLINK_H
549 /*
550  * Managing the cache for decoding communications of Netlink GENERIC protocol
551  *
552  * As name shown Netlink GENERIC protocol is generic protocol. The
553  * numbers of msg types used in the protocol are not defined
554  * statically. Kernel defines them on demand.  So the xlat converted
555  * from header files doesn't help for decoding the protocol. Following
556  * codes are building xlat(dyxlat) at runtime.
557  */
558 static bool
559 genl_send_dump_families(const int fd)
560 {
561         struct {
562                 const struct nlmsghdr nlh;
563                 struct genlmsghdr gnlh;
564         } req = {
565                 .nlh = {
566                         .nlmsg_len = sizeof(req),
567                         .nlmsg_type = GENL_ID_CTRL,
568                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
569                 },
570                 .gnlh = {
571                         .cmd = CTRL_CMD_GETFAMILY,
572                 }
573         };
574         return send_query(fd, &req, sizeof(req));
575 }
576
577 static int
578 genl_parse_families_response(const void *const data,
579                              const int data_len, const unsigned long inode,
580                              void *opaque_data)
581 {
582         struct dyxlat *const dyxlat = opaque_data;
583         const struct genlmsghdr *const gnlh = data;
584         struct rtattr *attr;
585         int rta_len = data_len - NLMSG_LENGTH(sizeof(*gnlh));
586
587         char *name = NULL;
588         unsigned int name_len = 0;
589         uint16_t *id = NULL;
590
591         if (rta_len < 0)
592                 return -1;
593         if (gnlh->cmd != CTRL_CMD_NEWFAMILY)
594                 return -1;
595         if (gnlh->version != 2)
596                 return -1;
597
598         for (attr = (struct rtattr *) (gnlh + 1);
599              RTA_OK(attr, rta_len);
600              attr = RTA_NEXT(attr, rta_len)) {
601                 switch (attr->rta_type) {
602                 case CTRL_ATTR_FAMILY_NAME:
603                         if (!name) {
604                                 name = RTA_DATA(attr);
605                                 name_len = RTA_PAYLOAD(attr);
606                         }
607                         break;
608                 case CTRL_ATTR_FAMILY_ID:
609                         if (!id && RTA_PAYLOAD(attr) == sizeof(*id))
610                                 id = RTA_DATA(attr);
611                         break;
612                 }
613
614                 if (name && id) {
615                         dyxlat_add_pair(dyxlat, *id, name, name_len);
616                         name = NULL;
617                         id = NULL;
618                 }
619         }
620
621         return 0;
622 }
623
624 const struct xlat *
625 genl_families_xlat(void)
626 {
627         static struct dyxlat *dyxlat;
628
629         if (!dyxlat) {
630                 dyxlat = dyxlat_alloc(32);
631
632                 int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
633                 if (fd < 0)
634                         goto out;
635
636                 if (genl_send_dump_families(fd))
637                         receive_responses(fd, 0, GENL_ID_CTRL,
638                                           genl_parse_families_response, dyxlat);
639                 close(fd);
640         }
641
642 out:
643         return dyxlat_get(dyxlat);
644 }
645
646 #else /* !HAVE_LINUX_GENETLINK_H */
647
648 const struct xlat *
649 genl_families_xlat(void)
650 {
651         return NULL;
652 }
653 #endif