]> granicus.if.org Git - strace/blob - socketutils.c
Fix build with old linux/netlink.h
[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  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "defs.h"
30 #include <netinet/in.h>
31 #include <sys/socket.h>
32 #include <arpa/inet.h>
33 #include <linux/netlink.h>
34 #include <linux/sock_diag.h>
35 #include <linux/inet_diag.h>
36 #include <linux/unix_diag.h>
37 #include <linux/netlink_diag.h>
38 #include <linux/rtnetlink.h>
39
40 #include <sys/un.h>
41 #ifndef UNIX_PATH_MAX
42 # define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) 0)->sun_path)
43 #endif
44
45 #ifndef NETLINK_SOCK_DIAG
46 # define NETLINK_SOCK_DIAG 4
47 #endif
48
49 typedef struct {
50         unsigned long inode;
51         char *details;
52 } cache_entry;
53
54 #define CACHE_SIZE 1024U
55 static cache_entry cache[CACHE_SIZE];
56 #define CACHE_MASK (CACHE_SIZE - 1)
57
58 static int
59 cache_and_print_inode_details(const unsigned long inode, char *const details)
60 {
61         cache_entry *e = &cache[inode & CACHE_MASK];
62         free(e->details);
63         e->inode = inode;
64         e->details = details;
65
66         tprints(details);
67         return 1;
68 }
69
70 bool
71 print_sockaddr_by_inode_cached(const unsigned long inode)
72 {
73         const cache_entry *const e = &cache[inode & CACHE_MASK];
74         if (e && inode == e->inode) {
75                 tprints(e->details);
76                 return true;
77         }
78         return false;
79 }
80
81 static bool
82 send_query(const int fd, void *req, size_t req_size)
83 {
84         struct sockaddr_nl nladdr = {
85                 .nl_family = AF_NETLINK
86         };
87         struct iovec iov = {
88                 .iov_base = req,
89                 .iov_len = req_size
90         };
91         const struct msghdr msg = {
92                 .msg_name = &nladdr,
93                 .msg_namelen = sizeof(nladdr),
94                 .msg_iov = &iov,
95                 .msg_iovlen = 1
96         };
97
98         for (;;) {
99                 if (sendmsg(fd, &msg, 0) < 0) {
100                         if (errno == EINTR)
101                                 continue;
102                         return false;
103                 }
104                 return true;
105         }
106 }
107
108 static bool
109 inet_send_query(const int fd, const int family, const int proto)
110 {
111         struct {
112                 const struct nlmsghdr nlh;
113                 const struct inet_diag_req_v2 idr;
114         } req = {
115                 .nlh = {
116                         .nlmsg_len = sizeof(req),
117                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
118                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
119                 },
120                 .idr = {
121                         .sdiag_family = family,
122                         .sdiag_protocol = proto,
123                         .idiag_states = -1
124                 }
125         };
126         return send_query(fd, &req, sizeof(req));
127 }
128
129 static int
130 inet_parse_response(const char *const proto_name, const void *const data,
131                     const int data_len, const unsigned long inode)
132 {
133         const struct inet_diag_msg *const diag_msg = data;
134         static const char zero_addr[sizeof(struct in6_addr)];
135         socklen_t addr_size, text_size;
136
137         if (data_len < (int) NLMSG_LENGTH(sizeof(*diag_msg)))
138                 return -1;
139         if (diag_msg->idiag_inode != inode)
140                 return 0;
141
142         switch(diag_msg->idiag_family) {
143                 case AF_INET:
144                         addr_size = sizeof(struct in_addr);
145                         text_size = INET_ADDRSTRLEN;
146                         break;
147                 case AF_INET6:
148                         addr_size = sizeof(struct in6_addr);
149                         text_size = INET6_ADDRSTRLEN;
150                         break;
151                 default:
152                         return -1;
153         }
154
155         char src_buf[text_size];
156         char *details;
157
158         if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_src,
159                        src_buf, text_size))
160                 return -1;
161
162         if (diag_msg->id.idiag_dport ||
163             memcmp(zero_addr, diag_msg->id.idiag_dst, addr_size)) {
164                 char dst_buf[text_size];
165
166                 if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_dst,
167                                dst_buf, text_size))
168                         return -1;
169
170                 if (asprintf(&details, "%s:[%s:%u->%s:%u]", proto_name,
171                              src_buf, ntohs(diag_msg->id.idiag_sport),
172                              dst_buf, ntohs(diag_msg->id.idiag_dport)) < 0)
173                         return false;
174         } else {
175                 if (asprintf(&details, "%s:[%s:%u]", proto_name, src_buf,
176                              ntohs(diag_msg->id.idiag_sport)) < 0)
177                         return false;
178         }
179
180         return cache_and_print_inode_details(inode, details);
181 }
182
183 static bool
184 receive_responses(const int fd, const unsigned long inode,
185                   const char *proto_name,
186                   int (* parser) (const char *, const void *,
187                                   int, unsigned long))
188 {
189         static union {
190                 struct nlmsghdr hdr;
191                 long buf[8192 / sizeof(long)];
192         } hdr_buf;
193
194         struct sockaddr_nl nladdr = {
195                 .nl_family = AF_NETLINK
196         };
197         struct iovec iov = {
198                 .iov_base = hdr_buf.buf,
199                 .iov_len = sizeof(hdr_buf.buf)
200         };
201         int flags = 0;
202
203         for (;;) {
204                 struct msghdr msg = {
205                         .msg_name = &nladdr,
206                         .msg_namelen = sizeof(nladdr),
207                         .msg_iov = &iov,
208                         .msg_iovlen = 1
209                 };
210
211                 ssize_t ret = recvmsg(fd, &msg, flags);
212                 if (ret < 0) {
213                         if (errno == EINTR)
214                                 continue;
215                         return false;
216                 }
217
218                 const struct nlmsghdr *h = &hdr_buf.hdr;
219                 if (!NLMSG_OK(h, ret))
220                         return false;
221                 for (; NLMSG_OK(h, ret); h = NLMSG_NEXT(h, ret)) {
222                         if (h->nlmsg_type != SOCK_DIAG_BY_FAMILY)
223                                 return false;
224                         const int rc = parser(proto_name, NLMSG_DATA(h),
225                                               h->nlmsg_len, inode);
226                         if (rc > 0)
227                                 return true;
228                         if (rc < 0)
229                                 return false;
230                 }
231                 flags = MSG_DONTWAIT;
232         }
233 }
234
235 static bool
236 inet_print(const int fd, const int family, const int protocol,
237            const unsigned long inode, const char *proto_name)
238 {
239         return inet_send_query(fd, family, protocol)
240                 && receive_responses(fd, inode, proto_name, inet_parse_response);
241 }
242
243 static bool
244 unix_send_query(const int fd, const unsigned long inode)
245 {
246         struct {
247                 const struct nlmsghdr nlh;
248                 const struct unix_diag_req udr;
249         } req = {
250                 .nlh = {
251                         .nlmsg_len = sizeof(req),
252                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
253                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
254                 },
255                 .udr = {
256                         .sdiag_family = AF_UNIX,
257                         .udiag_ino = inode,
258                         .udiag_states = -1,
259                         .udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER
260                 }
261         };
262         return send_query(fd, &req, sizeof(req));
263 }
264
265 static int
266 unix_parse_response(const char *proto_name, const void *data,
267                     const int data_len, const unsigned long inode)
268 {
269         const struct unix_diag_msg *diag_msg = data;
270         struct rtattr *attr;
271         int rta_len = data_len - NLMSG_LENGTH(sizeof(*diag_msg));
272         uint32_t peer = 0;
273         size_t path_len = 0;
274         char path[UNIX_PATH_MAX + 1];
275
276         if (rta_len < 0)
277                 return -1;
278         if (diag_msg->udiag_ino != inode)
279                 return 0;
280         if (diag_msg->udiag_family != AF_UNIX)
281                 return -1;
282
283         for (attr = (struct rtattr *) (diag_msg + 1);
284              RTA_OK(attr, rta_len);
285              attr = RTA_NEXT(attr, rta_len)) {
286                 switch (attr->rta_type) {
287                 case UNIX_DIAG_NAME:
288                         if (!path_len) {
289                                 path_len = RTA_PAYLOAD(attr);
290                                 if (path_len > UNIX_PATH_MAX)
291                                         path_len = UNIX_PATH_MAX;
292                                 memcpy(path, RTA_DATA(attr), path_len);
293                                 path[path_len] = '\0';
294                         }
295                         break;
296                 case UNIX_DIAG_PEER:
297                         if (RTA_PAYLOAD(attr) >= 4)
298                                 peer = *(uint32_t *) RTA_DATA(attr);
299                         break;
300                 }
301         }
302
303         /*
304          * print obtained information in the following format:
305          * "UNIX:[" SELF_INODE [ "->" PEER_INODE ][ "," SOCKET_FILE ] "]"
306          */
307         if (!peer && !path_len)
308                 return -1;
309
310         char peer_str[3 + sizeof(peer) * 3];
311         if (peer)
312                 snprintf(peer_str, sizeof(peer_str), "->%u", peer);
313         else
314                 peer_str[0] = '\0';
315
316         const char *path_str;
317         if (path_len) {
318                 char *outstr = alloca(4 * path_len + 4);
319
320                 outstr[0] = ',';
321                 if (path[0] == '\0') {
322                         outstr[1] = '@';
323                         string_quote(path + 1, outstr + 2,
324                                      path_len - 1, QUOTE_0_TERMINATED);
325                 } else {
326                         string_quote(path, outstr + 1,
327                                      path_len, QUOTE_0_TERMINATED);
328                 }
329                 path_str = outstr;
330         } else {
331                 path_str = "";
332         }
333
334         char *details;
335         if (asprintf(&details, "%s:[%lu%s%s]", proto_name, inode,
336                      peer_str, path_str) < 0)
337                 return -1;
338
339         return cache_and_print_inode_details(inode, details);
340 }
341
342 static bool
343 netlink_send_query(const int fd, const unsigned long inode)
344 {
345         struct {
346                 const struct nlmsghdr nlh;
347                 const struct netlink_diag_req ndr;
348         } req = {
349                 .nlh = {
350                         .nlmsg_len = sizeof(req),
351                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
352                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
353                 },
354                 .ndr = {
355                         .sdiag_family = AF_NETLINK,
356                         .sdiag_protocol = NDIAG_PROTO_ALL,
357                         .ndiag_show = NDIAG_SHOW_MEMINFO
358                 }
359         };
360         return send_query(fd, &req, sizeof(req));
361 }
362
363 static int
364 netlink_parse_response(const char *proto_name, const void *data,
365                     const int data_len, const unsigned long inode)
366 {
367         const struct netlink_diag_msg *const diag_msg = data;
368         const char *netlink_proto;
369         char *details;
370
371         if (data_len < (int) NLMSG_LENGTH(sizeof(*diag_msg)))
372                 return -1;
373         if (diag_msg->ndiag_ino != inode)
374                 return 0;
375
376         if (diag_msg->ndiag_family != AF_NETLINK)
377                 return -1;
378
379         netlink_proto = xlookup(netlink_protocols,
380                                 diag_msg->ndiag_protocol);
381
382         if (netlink_proto) {
383                 static const char netlink_prefix[] = "NETLINK_";
384                 const size_t netlink_prefix_len =
385                         sizeof(netlink_prefix) -1;
386                 if (strncmp(netlink_proto, netlink_prefix,
387                             netlink_prefix_len) == 0)
388                         netlink_proto += netlink_prefix_len;
389                 if (asprintf(&details, "%s:[%s:%u]", proto_name,
390                              netlink_proto, diag_msg->ndiag_portid) < 0)
391                         return -1;
392         } else {
393                 if (asprintf(&details, "%s:[%u]", proto_name,
394                              (unsigned) diag_msg->ndiag_protocol) < 0)
395                         return -1;
396         }
397
398         return cache_and_print_inode_details(inode, details);
399 }
400
401 static bool
402 unix_print(const int fd, const unsigned long inode)
403 {
404         return unix_send_query(fd, inode)
405                 && receive_responses(fd, inode, "UNIX", unix_parse_response);
406 }
407
408 static bool
409 tcp_v4_print(const int fd, const unsigned long inode)
410 {
411         return inet_print(fd, AF_INET, IPPROTO_TCP, inode, "TCP");
412 }
413
414 static bool
415 udp_v4_print(const int fd, const unsigned long inode)
416 {
417         return inet_print(fd, AF_INET, IPPROTO_UDP, inode, "UDP");
418 }
419
420 static bool
421 tcp_v6_print(const int fd, const unsigned long inode)
422 {
423         return inet_print(fd, AF_INET6, IPPROTO_TCP, inode, "TCPv6");
424 }
425
426 static bool
427 udp_v6_print(const int fd, const unsigned long inode)
428 {
429         return inet_print(fd, AF_INET6, IPPROTO_UDP, inode, "UDPv6");
430 }
431
432 static bool
433 netlink_print(const int fd, const unsigned long inode)
434 {
435         return netlink_send_query(fd, inode)
436                 && receive_responses(fd, inode, "NETLINK",
437                                      netlink_parse_response);
438 }
439
440 static const struct {
441         const char *const name;
442         bool (*const print)(int, unsigned long);
443 } protocols[] = {
444         [SOCK_PROTO_UNIX] = { "UNIX", unix_print },
445         [SOCK_PROTO_TCP] = { "TCP", tcp_v4_print },
446         [SOCK_PROTO_UDP] = { "UDP", udp_v4_print },
447         [SOCK_PROTO_TCPv6] = { "TCPv6", tcp_v6_print },
448         [SOCK_PROTO_UDPv6] = { "UDPv6", udp_v6_print },
449         [SOCK_PROTO_NETLINK] = { "NETLINK", netlink_print }
450 };
451
452 enum sock_proto
453 get_proto_by_name(const char *const name)
454 {
455         unsigned int i;
456         for (i = (unsigned int) SOCK_PROTO_UNKNOWN + 1;
457              i < ARRAY_SIZE(protocols); ++i) {
458                 if (protocols[i].name && !strcmp(name, protocols[i].name))
459                         return (enum sock_proto) i;
460         }
461         return SOCK_PROTO_UNKNOWN;
462 }
463
464 /* Given an inode number of a socket, print out the details
465  * of the ip address and port. */
466
467 bool
468 print_sockaddr_by_inode(const unsigned long inode, const enum sock_proto proto)
469 {
470         if ((unsigned int) proto >= ARRAY_SIZE(protocols) ||
471             (proto != SOCK_PROTO_UNKNOWN && !protocols[proto].print))
472                 return false;
473
474         const int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG);
475         if (fd < 0)
476                 return false;
477         bool r = false;
478
479         if (proto != SOCK_PROTO_UNKNOWN) {
480                 r = protocols[proto].print(fd, inode);
481                 if (!r) {
482                         tprintf("%s:[%lu]", protocols[proto].name, inode);
483                         r = true;
484                 }
485         } else {
486                 unsigned int i;
487                 for (i = (unsigned int) SOCK_PROTO_UNKNOWN + 1;
488                      i < ARRAY_SIZE(protocols); ++i) {
489                         if (!protocols[i].print)
490                                 continue;
491                         r = protocols[i].print(fd, inode);
492                         if (r)
493                                 break;
494                 }
495         }
496
497         close(fd);
498         return r;
499 }