]> granicus.if.org Git - strace/blob - socketutils.c
socketutils.c: introduce get_sockaddr_by_inode_cached
[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
41 #include <sys/un.h>
42 #ifndef UNIX_PATH_MAX
43 # define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) 0)->sun_path)
44 #endif
45
46 #ifndef NETLINK_SOCK_DIAG
47 # define NETLINK_SOCK_DIAG 4
48 #endif
49
50 typedef struct {
51         unsigned long inode;
52         char *details;
53 } cache_entry;
54
55 #define CACHE_SIZE 1024U
56 static cache_entry cache[CACHE_SIZE];
57 #define CACHE_MASK (CACHE_SIZE - 1)
58
59 static int
60 cache_and_print_inode_details(const unsigned long inode, char *const details)
61 {
62         cache_entry *e = &cache[inode & CACHE_MASK];
63         free(e->details);
64         e->inode = inode;
65         e->details = details;
66
67         tprints(details);
68         return 1;
69 }
70
71 static const char *
72 get_sockaddr_by_inode_cached(const unsigned long inode)
73 {
74         const cache_entry *const e = &cache[inode & CACHE_MASK];
75         return (e && inode == e->inode) ? e->details : NULL;
76 }
77
78 static bool
79 print_sockaddr_by_inode_cached(const unsigned long inode)
80 {
81         const char *const details = get_sockaddr_by_inode_cached(inode);
82         if (details) {
83                 tprints(details);
84                 return true;
85         }
86         return false;
87 }
88
89 static bool
90 send_query(const int fd, void *req, size_t req_size)
91 {
92         struct sockaddr_nl nladdr = {
93                 .nl_family = AF_NETLINK
94         };
95         struct iovec iov = {
96                 .iov_base = req,
97                 .iov_len = req_size
98         };
99         const struct msghdr msg = {
100                 .msg_name = &nladdr,
101                 .msg_namelen = sizeof(nladdr),
102                 .msg_iov = &iov,
103                 .msg_iovlen = 1
104         };
105
106         for (;;) {
107                 if (sendmsg(fd, &msg, 0) < 0) {
108                         if (errno == EINTR)
109                                 continue;
110                         return false;
111                 }
112                 return true;
113         }
114 }
115
116 static bool
117 inet_send_query(const int fd, const int family, const int proto)
118 {
119         struct {
120                 const struct nlmsghdr nlh;
121                 const struct inet_diag_req_v2 idr;
122         } req = {
123                 .nlh = {
124                         .nlmsg_len = sizeof(req),
125                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
126                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
127                 },
128                 .idr = {
129                         .sdiag_family = family,
130                         .sdiag_protocol = proto,
131                         .idiag_states = -1
132                 }
133         };
134         return send_query(fd, &req, sizeof(req));
135 }
136
137 static int
138 inet_parse_response(const char *const proto_name, const void *const data,
139                     const int data_len, const unsigned long inode)
140 {
141         const struct inet_diag_msg *const diag_msg = data;
142         static const char zero_addr[sizeof(struct in6_addr)];
143         socklen_t addr_size, text_size;
144
145         if (data_len < (int) NLMSG_LENGTH(sizeof(*diag_msg)))
146                 return -1;
147         if (diag_msg->idiag_inode != inode)
148                 return 0;
149
150         switch(diag_msg->idiag_family) {
151                 case AF_INET:
152                         addr_size = sizeof(struct in_addr);
153                         text_size = INET_ADDRSTRLEN;
154                         break;
155                 case AF_INET6:
156                         addr_size = sizeof(struct in6_addr);
157                         text_size = INET6_ADDRSTRLEN;
158                         break;
159                 default:
160                         return -1;
161         }
162
163         char src_buf[text_size];
164         char *details;
165
166         if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_src,
167                        src_buf, text_size))
168                 return -1;
169
170         if (diag_msg->id.idiag_dport ||
171             memcmp(zero_addr, diag_msg->id.idiag_dst, addr_size)) {
172                 char dst_buf[text_size];
173
174                 if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_dst,
175                                dst_buf, text_size))
176                         return -1;
177
178                 if (asprintf(&details, "%s:[%s:%u->%s:%u]", proto_name,
179                              src_buf, ntohs(diag_msg->id.idiag_sport),
180                              dst_buf, ntohs(diag_msg->id.idiag_dport)) < 0)
181                         return false;
182         } else {
183                 if (asprintf(&details, "%s:[%s:%u]", proto_name, src_buf,
184                              ntohs(diag_msg->id.idiag_sport)) < 0)
185                         return false;
186         }
187
188         return cache_and_print_inode_details(inode, details);
189 }
190
191 static bool
192 receive_responses(const int fd, const unsigned long inode,
193                   const char *proto_name,
194                   int (* parser) (const char *, const void *,
195                                   int, unsigned long))
196 {
197         static union {
198                 struct nlmsghdr hdr;
199                 long buf[8192 / sizeof(long)];
200         } hdr_buf;
201
202         struct sockaddr_nl nladdr = {
203                 .nl_family = AF_NETLINK
204         };
205         struct iovec iov = {
206                 .iov_base = hdr_buf.buf,
207                 .iov_len = sizeof(hdr_buf.buf)
208         };
209         int flags = 0;
210
211         for (;;) {
212                 struct msghdr msg = {
213                         .msg_name = &nladdr,
214                         .msg_namelen = sizeof(nladdr),
215                         .msg_iov = &iov,
216                         .msg_iovlen = 1
217                 };
218
219                 ssize_t ret = recvmsg(fd, &msg, flags);
220                 if (ret < 0) {
221                         if (errno == EINTR)
222                                 continue;
223                         return false;
224                 }
225
226                 const struct nlmsghdr *h = &hdr_buf.hdr;
227                 if (!NLMSG_OK(h, ret))
228                         return false;
229                 for (; NLMSG_OK(h, ret); h = NLMSG_NEXT(h, ret)) {
230                         if (h->nlmsg_type != SOCK_DIAG_BY_FAMILY)
231                                 return false;
232                         const int rc = parser(proto_name, NLMSG_DATA(h),
233                                               h->nlmsg_len, inode);
234                         if (rc > 0)
235                                 return true;
236                         if (rc < 0)
237                                 return false;
238                 }
239                 flags = MSG_DONTWAIT;
240         }
241 }
242
243 static bool
244 inet_print(const int fd, const int family, const int protocol,
245            const unsigned long inode, const char *proto_name)
246 {
247         return inet_send_query(fd, family, protocol)
248                 && receive_responses(fd, inode, proto_name, inet_parse_response);
249 }
250
251 static bool
252 unix_send_query(const int fd, const unsigned long inode)
253 {
254         struct {
255                 const struct nlmsghdr nlh;
256                 const struct unix_diag_req udr;
257         } req = {
258                 .nlh = {
259                         .nlmsg_len = sizeof(req),
260                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
261                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
262                 },
263                 .udr = {
264                         .sdiag_family = AF_UNIX,
265                         .udiag_ino = inode,
266                         .udiag_states = -1,
267                         .udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER
268                 }
269         };
270         return send_query(fd, &req, sizeof(req));
271 }
272
273 static int
274 unix_parse_response(const char *proto_name, const void *data,
275                     const int data_len, const unsigned long inode)
276 {
277         const struct unix_diag_msg *diag_msg = data;
278         struct rtattr *attr;
279         int rta_len = data_len - NLMSG_LENGTH(sizeof(*diag_msg));
280         uint32_t peer = 0;
281         size_t path_len = 0;
282         char path[UNIX_PATH_MAX + 1];
283
284         if (rta_len < 0)
285                 return -1;
286         if (diag_msg->udiag_ino != inode)
287                 return 0;
288         if (diag_msg->udiag_family != AF_UNIX)
289                 return -1;
290
291         for (attr = (struct rtattr *) (diag_msg + 1);
292              RTA_OK(attr, rta_len);
293              attr = RTA_NEXT(attr, rta_len)) {
294                 switch (attr->rta_type) {
295                 case UNIX_DIAG_NAME:
296                         if (!path_len) {
297                                 path_len = RTA_PAYLOAD(attr);
298                                 if (path_len > UNIX_PATH_MAX)
299                                         path_len = UNIX_PATH_MAX;
300                                 memcpy(path, RTA_DATA(attr), path_len);
301                                 path[path_len] = '\0';
302                         }
303                         break;
304                 case UNIX_DIAG_PEER:
305                         if (RTA_PAYLOAD(attr) >= 4)
306                                 peer = *(uint32_t *) RTA_DATA(attr);
307                         break;
308                 }
309         }
310
311         /*
312          * print obtained information in the following format:
313          * "UNIX:[" SELF_INODE [ "->" PEER_INODE ][ "," SOCKET_FILE ] "]"
314          */
315         if (!peer && !path_len)
316                 return -1;
317
318         char peer_str[3 + sizeof(peer) * 3];
319         if (peer)
320                 snprintf(peer_str, sizeof(peer_str), "->%u", peer);
321         else
322                 peer_str[0] = '\0';
323
324         const char *path_str;
325         if (path_len) {
326                 char *outstr = alloca(4 * path_len + 4);
327
328                 outstr[0] = ',';
329                 if (path[0] == '\0') {
330                         outstr[1] = '@';
331                         string_quote(path + 1, outstr + 2,
332                                      path_len - 1, QUOTE_0_TERMINATED);
333                 } else {
334                         string_quote(path, outstr + 1,
335                                      path_len, QUOTE_0_TERMINATED);
336                 }
337                 path_str = outstr;
338         } else {
339                 path_str = "";
340         }
341
342         char *details;
343         if (asprintf(&details, "%s:[%lu%s%s]", proto_name, inode,
344                      peer_str, path_str) < 0)
345                 return -1;
346
347         return cache_and_print_inode_details(inode, details);
348 }
349
350 static bool
351 netlink_send_query(const int fd, const unsigned long inode)
352 {
353         struct {
354                 const struct nlmsghdr nlh;
355                 const struct netlink_diag_req ndr;
356         } req = {
357                 .nlh = {
358                         .nlmsg_len = sizeof(req),
359                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
360                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
361                 },
362                 .ndr = {
363                         .sdiag_family = AF_NETLINK,
364                         .sdiag_protocol = NDIAG_PROTO_ALL,
365                         .ndiag_show = NDIAG_SHOW_MEMINFO
366                 }
367         };
368         return send_query(fd, &req, sizeof(req));
369 }
370
371 static int
372 netlink_parse_response(const char *proto_name, const void *data,
373                     const int data_len, const unsigned long inode)
374 {
375         const struct netlink_diag_msg *const diag_msg = data;
376         const char *netlink_proto;
377         char *details;
378
379         if (data_len < (int) NLMSG_LENGTH(sizeof(*diag_msg)))
380                 return -1;
381         if (diag_msg->ndiag_ino != inode)
382                 return 0;
383
384         if (diag_msg->ndiag_family != AF_NETLINK)
385                 return -1;
386
387         netlink_proto = xlookup(netlink_protocols,
388                                 diag_msg->ndiag_protocol);
389
390         if (netlink_proto) {
391                 netlink_proto = STR_STRIP_PREFIX(netlink_proto, "NETLINK_");
392                 if (asprintf(&details, "%s:[%s:%u]", proto_name,
393                              netlink_proto, diag_msg->ndiag_portid) < 0)
394                         return -1;
395         } else {
396                 if (asprintf(&details, "%s:[%u]", proto_name,
397                              (unsigned) diag_msg->ndiag_protocol) < 0)
398                         return -1;
399         }
400
401         return cache_and_print_inode_details(inode, details);
402 }
403
404 static bool
405 unix_print(const int fd, const unsigned long inode)
406 {
407         return unix_send_query(fd, inode)
408                 && receive_responses(fd, inode, "UNIX", unix_parse_response);
409 }
410
411 static bool
412 tcp_v4_print(const int fd, const unsigned long inode)
413 {
414         return inet_print(fd, AF_INET, IPPROTO_TCP, inode, "TCP");
415 }
416
417 static bool
418 udp_v4_print(const int fd, const unsigned long inode)
419 {
420         return inet_print(fd, AF_INET, IPPROTO_UDP, inode, "UDP");
421 }
422
423 static bool
424 tcp_v6_print(const int fd, const unsigned long inode)
425 {
426         return inet_print(fd, AF_INET6, IPPROTO_TCP, inode, "TCPv6");
427 }
428
429 static bool
430 udp_v6_print(const int fd, const unsigned long inode)
431 {
432         return inet_print(fd, AF_INET6, IPPROTO_UDP, inode, "UDPv6");
433 }
434
435 static bool
436 netlink_print(const int fd, const unsigned long inode)
437 {
438         return netlink_send_query(fd, inode)
439                 && receive_responses(fd, inode, "NETLINK",
440                                      netlink_parse_response);
441 }
442
443 static const struct {
444         const char *const name;
445         bool (*const print)(int, unsigned long);
446 } protocols[] = {
447         [SOCK_PROTO_UNIX] = { "UNIX", unix_print },
448         [SOCK_PROTO_TCP] = { "TCP", tcp_v4_print },
449         [SOCK_PROTO_UDP] = { "UDP", udp_v4_print },
450         [SOCK_PROTO_TCPv6] = { "TCPv6", tcp_v6_print },
451         [SOCK_PROTO_UDPv6] = { "UDPv6", udp_v6_print },
452         [SOCK_PROTO_NETLINK] = { "NETLINK", netlink_print }
453 };
454
455 enum sock_proto
456 get_proto_by_name(const char *const name)
457 {
458         unsigned int i;
459         for (i = (unsigned int) SOCK_PROTO_UNKNOWN + 1;
460              i < ARRAY_SIZE(protocols); ++i) {
461                 if (protocols[i].name && !strcmp(name, protocols[i].name))
462                         return (enum sock_proto) i;
463         }
464         return SOCK_PROTO_UNKNOWN;
465 }
466
467 static bool
468 print_sockaddr_by_inode_uncached(const unsigned long inode,
469                                  const enum sock_proto proto)
470 {
471         if ((unsigned int) proto >= ARRAY_SIZE(protocols) ||
472             (proto != SOCK_PROTO_UNKNOWN && !protocols[proto].print))
473                 return false;
474
475         const int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG);
476         if (fd < 0)
477                 return false;
478         bool r = false;
479
480         if (proto != SOCK_PROTO_UNKNOWN) {
481                 r = protocols[proto].print(fd, inode);
482                 if (!r) {
483                         tprintf("%s:[%lu]", protocols[proto].name, inode);
484                         r = true;
485                 }
486         } else {
487                 unsigned int i;
488                 for (i = (unsigned int) SOCK_PROTO_UNKNOWN + 1;
489                      i < ARRAY_SIZE(protocols); ++i) {
490                         if (!protocols[i].print)
491                                 continue;
492                         r = protocols[i].print(fd, inode);
493                         if (r)
494                                 break;
495                 }
496         }
497
498         close(fd);
499         return r;
500 }
501
502 /* Given an inode number of a socket, print out its protocol details.  */
503 bool
504 print_sockaddr_by_inode(struct tcb *const tcp, const int fd,
505                         const unsigned long inode)
506 {
507         return print_sockaddr_by_inode_cached(inode) ? true :
508                 print_sockaddr_by_inode_uncached(inode, getfdproto(tcp, fd));
509 }