e6d7366be96a62b08021e0f3614578b78126fc12
[raindrops.git] / ext / raindrops / linux_inet_diag.c
blobe6d7366be96a62b08021e0f3614578b78126fc12
1 #include <ruby.h>
2 #ifdef HAVE_RUBY_ST_H
3 # include <ruby/st.h>
4 #else
5 # include <st.h>
6 #endif
7 #include "my_fileno.h"
8 #ifdef __linux__
10 /* Ruby 1.8.6+ macros (for compatibility with Ruby 1.9) */
11 #ifndef RSTRING_LEN
12 # define RSTRING_LEN(s) (RSTRING(s)->len)
13 #endif
15 /* partial emulation of the 1.9 rb_thread_blocking_region under 1.8 */
16 #ifndef HAVE_RB_THREAD_BLOCKING_REGION
17 # include <rubysig.h>
18 # define RUBY_UBF_IO ((rb_unblock_function_t *)-1)
19 typedef void rb_unblock_function_t(void *);
20 typedef VALUE rb_blocking_function_t(void *);
21 static VALUE
22 rb_thread_blocking_region(
23 rb_blocking_function_t *func, void *data1,
24 rb_unblock_function_t *ubf, void *data2)
26 VALUE rv;
28 TRAP_BEG;
29 rv = func(data1);
30 TRAP_END;
32 return rv;
34 #endif /* ! HAVE_RB_THREAD_BLOCKING_REGION */
36 #ifndef HAVE_RB_THREAD_IO_BLOCKING_REGION
37 # define rb_thread_io_blocking_region(fn,data,fd) \
38 rb_thread_blocking_region((fn),(data),RUBY_UBF_IO,0)
39 #endif /* HAVE_RB_THREAD_IO_BLOCKING_REGION */
41 #include <assert.h>
42 #include <errno.h>
43 #include <sys/socket.h>
44 #include <sys/types.h>
45 #include <netdb.h>
46 #include <unistd.h>
47 #include <fcntl.h>
48 #include <string.h>
49 #include <asm/types.h>
50 #include <netinet/in.h>
51 #include <arpa/inet.h>
52 #include <netinet/tcp.h>
53 #include <linux/netlink.h>
54 #include <linux/rtnetlink.h>
55 #include <linux/inet_diag.h>
57 union any_addr {
58 struct sockaddr_storage ss;
59 struct sockaddr sa;
60 struct sockaddr_in in;
61 struct sockaddr_in6 in6;
64 static size_t page_size;
65 static unsigned g_seq;
66 static VALUE cListenStats, cIDSock;
67 static ID id_new;
69 struct listen_stats {
70 uint32_t active;
71 uint32_t listener_p:1;
72 uint32_t queued:31;
75 #define OPLEN (sizeof(struct inet_diag_bc_op) + \
76 sizeof(struct inet_diag_hostcond) + \
77 sizeof(struct sockaddr_storage))
79 struct nogvl_args {
80 st_table *table;
81 struct iovec iov[3]; /* last iov holds inet_diag bytecode */
82 struct listen_stats stats;
83 int fd;
86 #ifdef SOCK_CLOEXEC
87 # define my_SOCK_RAW (SOCK_RAW|SOCK_CLOEXEC)
88 # define FORCE_CLOEXEC(v) (v)
89 #else
90 # define my_SOCK_RAW SOCK_RAW
91 static VALUE FORCE_CLOEXEC(VALUE io)
93 int fd = my_fileno(io);
94 int flags = fcntl(fd, F_SETFD, FD_CLOEXEC);
95 if (flags == -1)
96 rb_sys_fail("fcntl(F_SETFD, FD_CLOEXEC)");
97 return io;
99 #endif
102 * call-seq:
103 * Raindrops::InetDiagSocket.new -> Socket
105 * Creates a new Socket object for the netlink inet_diag facility
107 static VALUE ids_s_new(VALUE klass)
109 VALUE argv[3];
111 argv[0] = INT2NUM(AF_NETLINK);
112 argv[1] = INT2NUM(my_SOCK_RAW);
113 argv[2] = INT2NUM(NETLINK_INET_DIAG);
115 return FORCE_CLOEXEC(rb_call_super(3, argv));
118 /* creates a Ruby ListenStats Struct based on our internal listen_stats */
119 static VALUE rb_listen_stats(struct listen_stats *stats)
121 VALUE active = UINT2NUM(stats->active);
122 VALUE queued = UINT2NUM(stats->queued);
124 return rb_struct_new(cListenStats, active, queued);
127 static int st_free_data(st_data_t key, st_data_t value, st_data_t ignored)
129 xfree((void *)key);
130 xfree((void *)value);
132 return ST_DELETE;
135 static int st_to_hash(st_data_t key, st_data_t value, VALUE hash)
137 struct listen_stats *stats = (struct listen_stats *)value;
139 if (stats->listener_p) {
140 VALUE k = rb_str_new2((const char *)key);
141 VALUE v = rb_listen_stats(stats);
143 OBJ_FREEZE(k);
144 rb_hash_aset(hash, k, v);
146 return st_free_data(key, value, 0);
149 static int st_AND_hash(st_data_t key, st_data_t value, VALUE hash)
151 struct listen_stats *stats = (struct listen_stats *)value;
153 if (stats->listener_p) {
154 VALUE k = rb_str_new2((const char *)key);
156 if (rb_hash_lookup(hash, k) == Qtrue) {
157 VALUE v = rb_listen_stats(stats);
158 OBJ_FREEZE(k);
159 rb_hash_aset(hash, k, v);
162 return st_free_data(key, value, 0);
165 static const char *addr_any(sa_family_t family)
167 static const char ipv4[] = "0.0.0.0";
168 static const char ipv6[] = "[::]";
170 if (family == AF_INET)
171 return ipv4;
172 assert(family == AF_INET6 && "unknown family");
173 return ipv6;
176 static void bug_warn(void)
178 fprintf(stderr, "Please report how you produced this at "\
179 "raindrops@librelist.org\n");
180 fflush(stderr);
183 static struct listen_stats *stats_for(st_table *table, struct inet_diag_msg *r)
185 char *key, *port, *old_key;
186 size_t alloca_len;
187 struct listen_stats *stats;
188 size_t keylen;
189 size_t portlen = sizeof("65535");
190 union any_addr sa = { 0 };
191 socklen_t len = sizeof(struct sockaddr_storage);
192 int rc;
193 int flags = NI_NUMERICHOST | NI_NUMERICSERV;
195 switch ((sa.ss.ss_family = r->idiag_family)) {
196 case AF_INET: {
197 sa.in.sin_port = r->id.idiag_sport;
198 sa.in.sin_addr.s_addr = r->id.idiag_src[0];
199 keylen = INET_ADDRSTRLEN;
200 alloca_len = keylen + 1 + portlen;
201 key = alloca(alloca_len);
202 key[keylen] = 0; /* will be ':' later */
203 port = key + keylen + 1;
204 rc = getnameinfo(&sa.sa, len,
205 key, keylen, port, portlen, flags);
206 break;
208 case AF_INET6: {
209 sa.in6.sin6_port = r->id.idiag_sport;
210 memcpy(&sa.in6.sin6_addr, &r->id.idiag_src, sizeof(__be32[4]));
211 keylen = INET6_ADDRSTRLEN;
212 /* [ ] */
213 alloca_len = 1 + keylen + 1 + 1 + portlen;
214 key = alloca(alloca_len);
215 *key = '[';
216 key[1 + keylen + 1] = 0; /* will be ':' later */
217 port = 1 + key + keylen + 1 + 1;
218 rc = getnameinfo(&sa.sa, len,
219 key + 1, keylen, port, portlen, flags);
220 break;
222 default:
223 assert(0 && "unsupported address family, could that be IPv7?!");
225 if (rc != 0) {
226 fprintf(stderr, "BUG: getnameinfo: %s\n", gai_strerror(rc));
227 bug_warn();
228 *key = 0;
231 keylen = strlen(key);
232 portlen = strlen(port);
234 switch (sa.ss.ss_family) {
235 case AF_INET:
236 key[keylen] = ':';
237 memmove(key + keylen + 1, port, portlen + 1);
238 break;
239 case AF_INET6:
240 key[keylen] = ']';
241 key[keylen + 1] = ':';
242 memmove(key + keylen + 2, port, portlen + 1);
243 keylen++;
244 break;
245 default:
246 assert(0 && "unsupported address family, could that be IPv7?!");
249 if (st_lookup(table, (st_data_t)key, (st_data_t *)&stats))
250 return stats;
252 old_key = key;
254 if (r->idiag_state == TCP_ESTABLISHED) {
255 int n = snprintf(key, alloca_len, "%s:%u",
256 addr_any(sa.ss.ss_family),
257 ntohs(r->id.idiag_sport));
258 if (n <= 0) {
259 fprintf(stderr, "BUG: snprintf: %d\n", n);
260 bug_warn();
262 if (st_lookup(table, (st_data_t)key, (st_data_t *)&stats))
263 return stats;
264 if (n <= 0) {
265 key = xmalloc(1);
266 *key = '\0';
267 } else {
268 old_key = key;
269 key = xmalloc(n + 1);
270 memcpy(key, old_key, n + 1);
272 } else {
273 key = xmalloc(keylen + 1 + portlen + 1);
274 memcpy(key, old_key, keylen + 1 + portlen + 1);
276 stats = xcalloc(1, sizeof(struct listen_stats));
277 st_insert(table, (st_data_t)key, (st_data_t)stats);
278 return stats;
281 static void table_incr_active(st_table *table, struct inet_diag_msg *r)
283 struct listen_stats *stats = stats_for(table, r);
284 ++stats->active;
287 static void table_set_queued(st_table *table, struct inet_diag_msg *r)
289 struct listen_stats *stats = stats_for(table, r);
290 stats->listener_p = 1;
291 stats->queued = r->idiag_rqueue;
294 /* inner loop of inet_diag, called for every socket returned by netlink */
295 static inline void r_acc(struct nogvl_args *args, struct inet_diag_msg *r)
298 * inode == 0 means the connection is still in the listen queue
299 * and has not yet been accept()-ed by the server. The
300 * inet_diag bytecode cannot filter this for us.
302 if (r->idiag_inode == 0)
303 return;
304 if (r->idiag_state == TCP_ESTABLISHED) {
305 if (args->table)
306 table_incr_active(args->table, r);
307 else
308 args->stats.active++;
309 } else { /* if (r->idiag_state == TCP_LISTEN) */
310 if (args->table)
311 table_set_queued(args->table, r);
312 else
313 args->stats.queued = r->idiag_rqueue;
316 * we wont get anything else because of the idiag_states filter
320 static const char err_sendmsg[] = "sendmsg";
321 static const char err_recvmsg[] = "recvmsg";
322 static const char err_nlmsg[] = "nlmsg";
324 struct diag_req {
325 struct nlmsghdr nlh;
326 struct inet_diag_req r;
329 static void prep_msghdr(
330 struct msghdr *msg,
331 struct nogvl_args *args,
332 struct sockaddr_nl *nladdr,
333 size_t iovlen)
335 memset(msg, 0, sizeof(struct msghdr));
336 msg->msg_name = (void *)nladdr;
337 msg->msg_namelen = sizeof(struct sockaddr_nl);
338 msg->msg_iov = args->iov;
339 msg->msg_iovlen = iovlen;
342 static void prep_diag_args(
343 struct nogvl_args *args,
344 struct sockaddr_nl *nladdr,
345 struct rtattr *rta,
346 struct diag_req *req,
347 struct msghdr *msg)
349 memset(req, 0, sizeof(struct diag_req));
350 memset(nladdr, 0, sizeof(struct sockaddr_nl));
352 nladdr->nl_family = AF_NETLINK;
354 req->nlh.nlmsg_len = sizeof(struct diag_req) +
355 RTA_LENGTH(args->iov[2].iov_len);
356 req->nlh.nlmsg_type = TCPDIAG_GETSOCK;
357 req->nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;
358 req->nlh.nlmsg_pid = getpid();
359 req->r.idiag_states = (1<<TCP_ESTABLISHED) | (1<<TCP_LISTEN);
360 rta->rta_type = INET_DIAG_REQ_BYTECODE;
361 rta->rta_len = RTA_LENGTH(args->iov[2].iov_len);
363 args->iov[0].iov_base = req;
364 args->iov[0].iov_len = sizeof(struct diag_req);
365 args->iov[1].iov_base = rta;
366 args->iov[1].iov_len = sizeof(struct rtattr);
368 prep_msghdr(msg, args, nladdr, 3);
371 static void prep_recvmsg_buf(struct nogvl_args *args)
373 /* reuse buffer that was allocated for bytecode */
374 args->iov[0].iov_len = page_size;
375 args->iov[0].iov_base = args->iov[2].iov_base;
378 /* does the inet_diag stuff with netlink(), this is called w/o GVL */
379 static VALUE diag(void *ptr)
381 struct nogvl_args *args = ptr;
382 struct sockaddr_nl nladdr;
383 struct rtattr rta;
384 struct diag_req req;
385 struct msghdr msg;
386 const char *err = NULL;
387 unsigned seq = ++g_seq;
389 prep_diag_args(args, &nladdr, &rta, &req, &msg);
390 req.nlh.nlmsg_seq = seq;
392 if (sendmsg(args->fd, &msg, 0) < 0) {
393 err = err_sendmsg;
394 goto out;
397 prep_recvmsg_buf(args);
399 while (1) {
400 ssize_t readed;
401 size_t r;
402 struct nlmsghdr *h = (struct nlmsghdr *)args->iov[0].iov_base;
404 prep_msghdr(&msg, args, &nladdr, 1);
405 readed = recvmsg(args->fd, &msg, 0);
406 if (readed < 0) {
407 if (errno == EINTR)
408 continue;
409 err = err_recvmsg;
410 goto out;
412 if (readed == 0)
413 goto out;
414 r = (size_t)readed;
415 for ( ; NLMSG_OK(h, r); h = NLMSG_NEXT(h, r)) {
416 if (h->nlmsg_seq != seq)
417 continue;
418 if (h->nlmsg_type == NLMSG_DONE)
419 goto out;
420 if (h->nlmsg_type == NLMSG_ERROR) {
421 err = err_nlmsg;
422 goto out;
424 r_acc(args, NLMSG_DATA(h));
427 out:
429 int save_errno = errno;
430 if (err && args->table) {
431 st_foreach(args->table, st_free_data, 0);
432 st_free_table(args->table);
434 errno = save_errno;
436 return (VALUE)err;
439 /* populates sockaddr_storage struct by parsing +addr+ */
440 static void parse_addr(union any_addr *inet, VALUE addr)
442 char *host_ptr;
443 char *check;
444 char *colon = NULL;
445 char *rbracket = NULL;
446 void *dst;
447 long host_len;
448 int af, rc;
449 uint16_t *portdst;
450 unsigned long port;
452 Check_Type(addr, T_STRING);
453 host_ptr = StringValueCStr(addr);
454 host_len = RSTRING_LEN(addr);
455 if (*host_ptr == '[') { /* ipv6 address format (rfc2732) */
456 rbracket = memchr(host_ptr + 1, ']', host_len - 1);
458 if (rbracket == NULL)
459 rb_raise(rb_eArgError, "']' not found in IPv6 addr=%s",
460 host_ptr);
461 if (rbracket[1] != ':')
462 rb_raise(rb_eArgError, "':' not found in IPv6 addr=%s",
463 host_ptr);
464 colon = rbracket + 1;
465 host_ptr++;
466 *rbracket = 0;
467 inet->ss.ss_family = af = AF_INET6;
468 dst = &inet->in6.sin6_addr;
469 portdst = &inet->in6.sin6_port;
470 } else { /* ipv4 */
471 colon = memchr(host_ptr, ':', host_len);
472 inet->ss.ss_family = af = AF_INET;
473 dst = &inet->in.sin_addr;
474 portdst = &inet->in.sin_port;
477 if (!colon)
478 rb_raise(rb_eArgError, "port not found in: `%s'", host_ptr);
479 port = strtoul(colon + 1, &check, 10);
480 *colon = 0;
481 rc = inet_pton(af, host_ptr, dst);
482 *colon = ':';
483 if (rbracket) *rbracket = ']';
484 if (*check || ((uint16_t)port != port))
485 rb_raise(rb_eArgError, "invalid port: %s", colon + 1);
486 if (rc != 1)
487 rb_raise(rb_eArgError, "inet_pton failed for: `%s' with %d",
488 host_ptr, rc);
489 *portdst = ntohs((uint16_t)port);
492 /* generates inet_diag bytecode to match all addrs */
493 static void gen_bytecode_all(struct iovec *iov)
495 struct inet_diag_bc_op *op;
496 struct inet_diag_hostcond *cond;
498 /* iov_len was already set and base allocated in a parent function */
499 assert(iov->iov_len == OPLEN && iov->iov_base && "iov invalid");
500 op = iov->iov_base;
501 op->code = INET_DIAG_BC_S_COND;
502 op->yes = OPLEN;
503 op->no = sizeof(struct inet_diag_bc_op) + OPLEN;
504 cond = (struct inet_diag_hostcond *)(op + 1);
505 cond->family = AF_UNSPEC;
506 cond->port = -1;
507 cond->prefix_len = 0;
510 /* generates inet_diag bytecode to match a single addr */
511 static void gen_bytecode(struct iovec *iov, union any_addr *inet)
513 struct inet_diag_bc_op *op;
514 struct inet_diag_hostcond *cond;
516 /* iov_len was already set and base allocated in a parent function */
517 assert(iov->iov_len == OPLEN && iov->iov_base && "iov invalid");
518 op = iov->iov_base;
519 op->code = INET_DIAG_BC_S_COND;
520 op->yes = OPLEN;
521 op->no = sizeof(struct inet_diag_bc_op) + OPLEN;
523 cond = (struct inet_diag_hostcond *)(op + 1);
524 cond->family = inet->ss.ss_family;
525 switch (inet->ss.ss_family) {
526 case AF_INET: {
527 cond->port = ntohs(inet->in.sin_port);
528 cond->prefix_len = inet->in.sin_addr.s_addr == 0 ? 0 :
529 sizeof(inet->in.sin_addr.s_addr) * CHAR_BIT;
530 *cond->addr = inet->in.sin_addr.s_addr;
532 break;
533 case AF_INET6: {
534 cond->port = ntohs(inet->in6.sin6_port);
535 cond->prefix_len = memcmp(&in6addr_any, &inet->in6.sin6_addr,
536 sizeof(struct in6_addr)) == 0 ?
537 0 : sizeof(inet->in6.sin6_addr) * CHAR_BIT;
538 memcpy(&cond->addr, &inet->in6.sin6_addr,
539 sizeof(struct in6_addr));
541 break;
542 default:
543 assert(0 && "unsupported address family, could that be IPv7?!");
547 static void nl_errcheck(VALUE r)
549 const char *err = (const char *)r;
551 if (err) {
552 if (err == err_nlmsg)
553 rb_raise(rb_eRuntimeError, "NLMSG_ERROR");
554 else
555 rb_sys_fail(err);
559 static VALUE tcp_stats(struct nogvl_args *args, VALUE addr)
561 union any_addr query_addr;
563 parse_addr(&query_addr, addr);
564 gen_bytecode(&args->iov[2], &query_addr);
566 memset(&args->stats, 0, sizeof(struct listen_stats));
567 nl_errcheck(rb_thread_io_blocking_region(diag, args, args->fd));
569 return rb_listen_stats(&args->stats);
573 * call-seq:
574 * Raindrops::Linux.tcp_listener_stats([addrs[, sock]]) => hash
576 * If specified, +addr+ may be a string or array of strings representing
577 * listen addresses to filter for. Returns a hash with given addresses as
578 * keys and ListenStats objects as the values or a hash of all addresses.
580 * addrs = %w(0.0.0.0:80 127.0.0.1:8080)
582 * If +addr+ is nil or not specified, all (IPv4) addresses are returned.
583 * If +sock+ is specified, it should be a Raindrops::InetDiagSock object.
585 static VALUE tcp_listener_stats(int argc, VALUE *argv, VALUE self)
587 VALUE *ary;
588 long i;
589 VALUE rv = rb_hash_new();
590 struct nogvl_args args;
591 VALUE addrs, sock;
593 rb_scan_args(argc, argv, "02", &addrs, &sock);
596 * allocating page_size instead of OP_LEN since we'll reuse the
597 * buffer for recvmsg() later, we already checked for
598 * OPLEN <= page_size at initialization
600 args.iov[2].iov_len = OPLEN;
601 args.iov[2].iov_base = alloca(page_size);
602 args.table = NULL;
603 if (NIL_P(sock))
604 sock = rb_funcall(cIDSock, id_new, 0);
605 args.fd = my_fileno(sock);
607 switch (TYPE(addrs)) {
608 case T_STRING:
609 rb_hash_aset(rv, addrs, tcp_stats(&args, addrs));
610 return rv;
611 case T_ARRAY:
612 ary = RARRAY_PTR(addrs);
613 i = RARRAY_LEN(addrs);
614 if (i == 1) {
615 rb_hash_aset(rv, *ary, tcp_stats(&args, *ary));
616 return rv;
618 for (; --i >= 0; ary++) {
619 union any_addr check;
621 parse_addr(&check, *ary);
622 rb_hash_aset(rv, *ary, Qtrue);
624 /* fall through */
625 case T_NIL:
626 args.table = st_init_strtable();
627 gen_bytecode_all(&args.iov[2]);
628 break;
629 default:
630 rb_raise(rb_eArgError,
631 "addr must be an array of strings, a string, or nil");
634 nl_errcheck(rb_thread_io_blocking_region(diag, &args, args.fd));
636 st_foreach(args.table, NIL_P(addrs) ? st_to_hash : st_AND_hash, rv);
637 st_free_table(args.table);
639 /* let GC deal with corner cases */
640 if (argc < 2) rb_io_close(sock);
641 return rv;
644 void Init_raindrops_linux_inet_diag(void)
646 VALUE cRaindrops = rb_const_get(rb_cObject, rb_intern("Raindrops"));
647 VALUE mLinux = rb_define_module_under(cRaindrops, "Linux");
649 rb_require("socket");
650 cIDSock = rb_const_get(rb_cObject, rb_intern("Socket"));
651 id_new = rb_intern("new");
654 * Document-class: Raindrops::InetDiagSocket
656 * This is a subclass of +Socket+ specifically for talking
657 * to the inet_diag facility of Netlink.
659 cIDSock = rb_define_class_under(cRaindrops, "InetDiagSocket", cIDSock);
660 rb_define_singleton_method(cIDSock, "new", ids_s_new, 0);
662 cListenStats = rb_const_get(cRaindrops, rb_intern("ListenStats"));
664 rb_define_module_function(mLinux, "tcp_listener_stats",
665 tcp_listener_stats, -1);
667 page_size = getpagesize();
669 assert(OPLEN <= page_size && "bytecode OPLEN is not <= PAGE_SIZE");
671 #endif /* __linux__ */