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