]> granicus.if.org Git - strace/blob - socketutils.c
socketutils.c: use xsprintf instead of snprintf
[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 "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 #include "xstring.h"
50
51 typedef struct {
52         unsigned long inode;
53         char *details;
54 } cache_entry;
55
56 #define CACHE_SIZE 1024U
57 static cache_entry cache[CACHE_SIZE];
58 #define CACHE_MASK (CACHE_SIZE - 1)
59
60 static int
61 cache_inode_details(const unsigned long inode, char *const details)
62 {
63         cache_entry *e = &cache[inode & CACHE_MASK];
64         free(e->details);
65         e->inode = inode;
66         e->details = details;
67
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 void *const data, const int data_len,
139                     const unsigned long inode, void *opaque_data)
140 {
141         const char *const proto_name = opaque_data;
142         const struct inet_diag_msg *const diag_msg = data;
143         static const char zero_addr[sizeof(struct in6_addr)];
144         socklen_t addr_size, text_size;
145
146         if (data_len < (int) NLMSG_LENGTH(sizeof(*diag_msg)))
147                 return -1;
148         if (diag_msg->idiag_inode != inode)
149                 return 0;
150
151         switch (diag_msg->idiag_family) {
152                 case AF_INET:
153                         addr_size = sizeof(struct in_addr);
154                         text_size = INET_ADDRSTRLEN;
155                         break;
156                 case AF_INET6:
157                         addr_size = sizeof(struct in6_addr);
158                         text_size = INET6_ADDRSTRLEN;
159                         break;
160                 default:
161                         return -1;
162         }
163
164         char src_buf[text_size];
165         char *details;
166
167         if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_src,
168                        src_buf, text_size))
169                 return -1;
170
171         if (diag_msg->id.idiag_dport ||
172             memcmp(zero_addr, diag_msg->id.idiag_dst, addr_size)) {
173                 char dst_buf[text_size];
174
175                 if (!inet_ntop(diag_msg->idiag_family, diag_msg->id.idiag_dst,
176                                dst_buf, text_size))
177                         return -1;
178
179                 if (asprintf(&details, "%s:[%s:%u->%s:%u]", proto_name,
180                              src_buf, ntohs(diag_msg->id.idiag_sport),
181                              dst_buf, ntohs(diag_msg->id.idiag_dport)) < 0)
182                         return false;
183         } else {
184                 if (asprintf(&details, "%s:[%s:%u]", proto_name, src_buf,
185                              ntohs(diag_msg->id.idiag_sport)) < 0)
186                         return false;
187         }
188
189         return cache_inode_details(inode, details);
190 }
191
192 static bool
193 receive_responses(const int fd, const unsigned long inode,
194                   const unsigned long expected_msg_type,
195                   int (*parser)(const void *, int,
196                                 unsigned long, void *),
197                   void *opaque_data)
198 {
199         static union {
200                 struct nlmsghdr hdr;
201                 long buf[8192 / sizeof(long)];
202         } hdr_buf;
203
204         struct sockaddr_nl nladdr = {
205                 .nl_family = AF_NETLINK
206         };
207         struct iovec iov = {
208                 .iov_base = hdr_buf.buf,
209                 .iov_len = sizeof(hdr_buf.buf)
210         };
211         int flags = 0;
212
213         for (;;) {
214                 struct msghdr msg = {
215                         .msg_name = &nladdr,
216                         .msg_namelen = sizeof(nladdr),
217                         .msg_iov = &iov,
218                         .msg_iovlen = 1
219                 };
220
221                 ssize_t ret = recvmsg(fd, &msg, flags);
222                 if (ret < 0) {
223                         if (errno == EINTR)
224                                 continue;
225                         return false;
226                 }
227
228                 const struct nlmsghdr *h = &hdr_buf.hdr;
229                 if (!NLMSG_OK(h, ret))
230                         return false;
231                 for (; NLMSG_OK(h, ret); h = NLMSG_NEXT(h, ret)) {
232                         if (h->nlmsg_type != expected_msg_type)
233                                 return false;
234                         const int rc = parser(NLMSG_DATA(h),
235                                               h->nlmsg_len, inode, opaque_data);
236                         if (rc > 0)
237                                 return true;
238                         if (rc < 0)
239                                 return false;
240                 }
241                 flags = MSG_DONTWAIT;
242         }
243 }
244
245 static bool
246 unix_send_query(const int fd, const unsigned long inode)
247 {
248         struct {
249                 const struct nlmsghdr nlh;
250                 const struct unix_diag_req udr;
251         } req = {
252                 .nlh = {
253                         .nlmsg_len = sizeof(req),
254                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
255                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
256                 },
257                 .udr = {
258                         .sdiag_family = AF_UNIX,
259                         .udiag_ino = inode,
260                         .udiag_states = -1,
261                         .udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER
262                 }
263         };
264         return send_query(fd, &req, sizeof(req));
265 }
266
267 static int
268 unix_parse_response(const void *data, const int data_len,
269                     const unsigned long inode, void *opaque_data)
270 {
271         const char *proto_name = opaque_data;
272         const struct unix_diag_msg *diag_msg = data;
273         struct rtattr *attr;
274         int rta_len = data_len - NLMSG_LENGTH(sizeof(*diag_msg));
275         uint32_t peer = 0;
276         size_t path_len = 0;
277         char path[UNIX_PATH_MAX + 1];
278
279         if (rta_len < 0)
280                 return -1;
281         if (diag_msg->udiag_ino != inode)
282                 return 0;
283         if (diag_msg->udiag_family != AF_UNIX)
284                 return -1;
285
286         for (attr = (struct rtattr *) (diag_msg + 1);
287              RTA_OK(attr, rta_len);
288              attr = RTA_NEXT(attr, rta_len)) {
289                 switch (attr->rta_type) {
290                 case UNIX_DIAG_NAME:
291                         if (!path_len) {
292                                 path_len = RTA_PAYLOAD(attr);
293                                 if (path_len > UNIX_PATH_MAX)
294                                         path_len = UNIX_PATH_MAX;
295                                 memcpy(path, RTA_DATA(attr), path_len);
296                                 path[path_len] = '\0';
297                         }
298                         break;
299                 case UNIX_DIAG_PEER:
300                         if (RTA_PAYLOAD(attr) >= 4)
301                                 peer = *(uint32_t *) RTA_DATA(attr);
302                         break;
303                 }
304         }
305
306         /*
307          * print obtained information in the following format:
308          * "UNIX:[" SELF_INODE [ "->" PEER_INODE ][ "," SOCKET_FILE ] "]"
309          */
310         if (!peer && !path_len)
311                 return -1;
312
313         char peer_str[3 + sizeof(peer) * 3];
314         if (peer)
315                 xsprintf(peer_str, "->%u", peer);
316         else
317                 peer_str[0] = '\0';
318
319         const char *path_str;
320         if (path_len) {
321                 char *outstr = alloca(4 * path_len + 4);
322
323                 outstr[0] = ',';
324                 if (path[0] == '\0') {
325                         outstr[1] = '@';
326                         string_quote(path + 1, outstr + 2,
327                                      path_len - 1, QUOTE_0_TERMINATED);
328                 } else {
329                         string_quote(path, outstr + 1,
330                                      path_len, QUOTE_0_TERMINATED);
331                 }
332                 path_str = outstr;
333         } else {
334                 path_str = "";
335         }
336
337         char *details;
338         if (asprintf(&details, "%s:[%lu%s%s]", proto_name, inode,
339                      peer_str, path_str) < 0)
340                 return -1;
341
342         return cache_inode_details(inode, details);
343 }
344
345 static bool
346 netlink_send_query(const int fd, const unsigned long inode)
347 {
348         struct {
349                 const struct nlmsghdr nlh;
350                 const struct netlink_diag_req ndr;
351         } req = {
352                 .nlh = {
353                         .nlmsg_len = sizeof(req),
354                         .nlmsg_type = SOCK_DIAG_BY_FAMILY,
355                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST
356                 },
357                 .ndr = {
358                         .sdiag_family = AF_NETLINK,
359                         .sdiag_protocol = NDIAG_PROTO_ALL,
360                         .ndiag_show = NDIAG_SHOW_MEMINFO
361                 }
362         };
363         return send_query(fd, &req, sizeof(req));
364 }
365
366 static int
367 netlink_parse_response(const void *data, const int data_len,
368                        const unsigned long inode, void *opaque_data)
369 {
370         const char *proto_name = opaque_data;
371         const struct netlink_diag_msg *const diag_msg = data;
372         const char *netlink_proto;
373         char *details;
374
375         if (data_len < (int) NLMSG_LENGTH(sizeof(*diag_msg)))
376                 return -1;
377         if (diag_msg->ndiag_ino != inode)
378                 return 0;
379
380         if (diag_msg->ndiag_family != AF_NETLINK)
381                 return -1;
382
383         netlink_proto = xlookup(netlink_protocols,
384                                 diag_msg->ndiag_protocol);
385
386         if (netlink_proto) {
387                 netlink_proto = STR_STRIP_PREFIX(netlink_proto, "NETLINK_");
388                 if (asprintf(&details, "%s:[%s:%u]", proto_name,
389                              netlink_proto, diag_msg->ndiag_portid) < 0)
390                         return -1;
391         } else {
392                 if (asprintf(&details, "%s:[%u]", proto_name,
393                              (unsigned) diag_msg->ndiag_protocol) < 0)
394                         return -1;
395         }
396
397         return cache_inode_details(inode, details);
398 }
399
400 static const char *
401 unix_get(const int fd, const unsigned long inode)
402 {
403         return unix_send_query(fd, inode)
404                 && receive_responses(fd, inode, SOCK_DIAG_BY_FAMILY,
405                                      unix_parse_response, (void *) "UNIX")
406                 ? get_sockaddr_by_inode_cached(inode) : NULL;
407 }
408
409 static const char *
410 inet_get(const int fd, const int family, const int protocol,
411          const unsigned long inode, const char *proto_name)
412 {
413         return inet_send_query(fd, family, protocol)
414                 && receive_responses(fd, inode, SOCK_DIAG_BY_FAMILY,
415                                      inet_parse_response, (void *) proto_name)
416                 ? get_sockaddr_by_inode_cached(inode) : NULL;
417 }
418
419 static const char *
420 tcp_v4_get(const int fd, const unsigned long inode)
421 {
422         return inet_get(fd, AF_INET, IPPROTO_TCP, inode, "TCP");
423 }
424
425 static const char *
426 udp_v4_get(const int fd, const unsigned long inode)
427 {
428         return inet_get(fd, AF_INET, IPPROTO_UDP, inode, "UDP");
429 }
430
431 static const char *
432 tcp_v6_get(const int fd, const unsigned long inode)
433 {
434         return inet_get(fd, AF_INET6, IPPROTO_TCP, inode, "TCPv6");
435 }
436
437 static const char *
438 udp_v6_get(const int fd, const unsigned long inode)
439 {
440         return inet_get(fd, AF_INET6, IPPROTO_UDP, inode, "UDPv6");
441 }
442
443 static const char *
444 netlink_get(const int fd, const unsigned long inode)
445 {
446         return netlink_send_query(fd, inode)
447                 && receive_responses(fd, inode, SOCK_DIAG_BY_FAMILY,
448                                      netlink_parse_response, (void *) "NETLINK")
449                 ? get_sockaddr_by_inode_cached(inode) : NULL;
450 }
451
452 static const struct {
453         const char *const name;
454         const char * (*const get)(int, unsigned long);
455 } protocols[] = {
456         [SOCK_PROTO_UNIX] = { "UNIX", unix_get },
457         [SOCK_PROTO_TCP] = { "TCP", tcp_v4_get },
458         [SOCK_PROTO_UDP] = { "UDP", udp_v4_get },
459         [SOCK_PROTO_TCPv6] = { "TCPv6", tcp_v6_get },
460         [SOCK_PROTO_UDPv6] = { "UDPv6", udp_v6_get },
461         [SOCK_PROTO_NETLINK] = { "NETLINK", netlink_get }
462 };
463
464 enum sock_proto
465 get_proto_by_name(const char *const name)
466 {
467         unsigned int i;
468         for (i = (unsigned int) SOCK_PROTO_UNKNOWN + 1;
469              i < ARRAY_SIZE(protocols); ++i) {
470                 if (protocols[i].name && !strcmp(name, protocols[i].name))
471                         return (enum sock_proto) i;
472         }
473         return SOCK_PROTO_UNKNOWN;
474 }
475
476 static const char *
477 get_sockaddr_by_inode_uncached(const unsigned long inode,
478                                const enum sock_proto proto)
479 {
480         if ((unsigned int) proto >= ARRAY_SIZE(protocols) ||
481             (proto != SOCK_PROTO_UNKNOWN && !protocols[proto].get))
482                 return NULL;
483
484         const int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG);
485         if (fd < 0)
486                 return NULL;
487         const char *details = NULL;
488
489         if (proto != SOCK_PROTO_UNKNOWN) {
490                 details = protocols[proto].get(fd, inode);
491         } else {
492                 unsigned int i;
493                 for (i = (unsigned int) SOCK_PROTO_UNKNOWN + 1;
494                      i < ARRAY_SIZE(protocols); ++i) {
495                         if (!protocols[i].get)
496                                 continue;
497                         details = protocols[i].get(fd, inode);
498                         if (details)
499                                 break;
500                 }
501         }
502
503         close(fd);
504         return details;
505 }
506
507 static bool
508 print_sockaddr_by_inode_uncached(const unsigned long inode,
509                                  const enum sock_proto proto)
510 {
511         const char *details = get_sockaddr_by_inode_uncached(inode, proto);
512
513         if (details) {
514                 tprints(details);
515                 return true;
516         }
517
518         if ((unsigned int) proto < ARRAY_SIZE(protocols) &&
519             protocols[proto].name) {
520                 tprintf("%s:[%lu]", protocols[proto].name, inode);
521                 return true;
522         }
523
524         return false;
525 }
526
527 /* Given an inode number of a socket, return its protocol details.  */
528 const char *
529 get_sockaddr_by_inode(struct tcb *const tcp, const int fd,
530                       const unsigned long inode)
531 {
532         const char *details = get_sockaddr_by_inode_cached(inode);
533         return details ? details :
534                 get_sockaddr_by_inode_uncached(inode, getfdproto(tcp, fd));
535 }
536
537 /* Given an inode number of a socket, print out its protocol details.  */
538 bool
539 print_sockaddr_by_inode(struct tcb *const tcp, const int fd,
540                         const unsigned long inode)
541 {
542         return print_sockaddr_by_inode_cached(inode) ? true :
543                 print_sockaddr_by_inode_uncached(inode, getfdproto(tcp, fd));
544 }
545
546 #ifdef HAVE_LINUX_GENETLINK_H
547 /*
548  * Managing the cache for decoding communications of Netlink GENERIC protocol
549  *
550  * As name shown Netlink GENERIC protocol is generic protocol. The
551  * numbers of msg types used in the protocol are not defined
552  * statically. Kernel defines them on demand.  So the xlat converted
553  * from header files doesn't help for decoding the protocol. Following
554  * codes are building xlat(dyxlat) at runtime.
555  */
556 static bool
557 genl_send_dump_families(const int fd)
558 {
559         struct {
560                 const struct nlmsghdr nlh;
561                 struct genlmsghdr gnlh;
562         } req = {
563                 .nlh = {
564                         .nlmsg_len = sizeof(req),
565                         .nlmsg_type = GENL_ID_CTRL,
566                         .nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
567                 },
568                 .gnlh = {
569                         .cmd = CTRL_CMD_GETFAMILY,
570                 }
571         };
572         return send_query(fd, &req, sizeof(req));
573 }
574
575 static int
576 genl_parse_families_response(const void *const data,
577                              const int data_len, const unsigned long inode,
578                              void *opaque_data)
579 {
580         struct dyxlat *const dyxlat = opaque_data;
581         const struct genlmsghdr *const gnlh = data;
582         struct rtattr *attr;
583         int rta_len = data_len - NLMSG_LENGTH(sizeof(*gnlh));
584
585         char *name = NULL;
586         unsigned int name_len = 0;
587         uint16_t *id = NULL;
588
589         if (rta_len < 0)
590                 return -1;
591         if (gnlh->cmd != CTRL_CMD_NEWFAMILY)
592                 return -1;
593         if (gnlh->version != 2)
594                 return -1;
595
596         for (attr = (struct rtattr *) (gnlh + 1);
597              RTA_OK(attr, rta_len);
598              attr = RTA_NEXT(attr, rta_len)) {
599                 switch (attr->rta_type) {
600                 case CTRL_ATTR_FAMILY_NAME:
601                         if (!name) {
602                                 name = RTA_DATA(attr);
603                                 name_len = RTA_PAYLOAD(attr);
604                         }
605                         break;
606                 case CTRL_ATTR_FAMILY_ID:
607                         if (!id && RTA_PAYLOAD(attr) == sizeof(*id))
608                                 id = RTA_DATA(attr);
609                         break;
610                 }
611
612                 if (name && id) {
613                         dyxlat_add_pair(dyxlat, *id, name, name_len);
614                         name = NULL;
615                         id = NULL;
616                 }
617         }
618
619         return 0;
620 }
621
622 const struct xlat *
623 genl_families_xlat(void)
624 {
625         static struct dyxlat *dyxlat;
626
627         if (!dyxlat) {
628                 dyxlat = dyxlat_alloc(32);
629
630                 int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
631                 if (fd < 0)
632                         goto out;
633
634                 if (genl_send_dump_families(fd))
635                         receive_responses(fd, 0, GENL_ID_CTRL,
636                                           genl_parse_families_response, dyxlat);
637                 close(fd);
638         }
639
640 out:
641         return dyxlat_get(dyxlat);
642 }
643
644 #else /* !HAVE_LINUX_GENETLINK_H */
645
646 const struct xlat *
647 genl_families_xlat(void)
648 {
649         return NULL;
650 }
651 #endif