e6d7366be96a62b08021e0f3614578b78126fc12
10 /* Ruby 1.8.6+ macros (for compatibility with Ruby 1.9) */
12 # define RSTRING_LEN(s) (RSTRING(s)->len)
15 /* partial emulation of the 1.9 rb_thread_blocking_region under 1.8 */
16 #ifndef HAVE_RB_THREAD_BLOCKING_REGION
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 *);
22 rb_thread_blocking_region(
23 rb_blocking_function_t
*func
, void *data1
,
24 rb_unblock_function_t
*ubf
, void *data2
)
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 */
43 #include <sys/socket.h>
44 #include <sys/types.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>
58 struct sockaddr_storage ss
;
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
;
71 uint32_t listener_p
:1;
75 #define OPLEN (sizeof(struct inet_diag_bc_op) + \
76 sizeof(struct inet_diag_hostcond) + \
77 sizeof(struct sockaddr_storage))
81 struct iovec iov
[3]; /* last iov holds inet_diag bytecode */
82 struct listen_stats stats
;
87 # define my_SOCK_RAW (SOCK_RAW|SOCK_CLOEXEC)
88 # define FORCE_CLOEXEC(v) (v)
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
);
96 rb_sys_fail("fcntl(F_SETFD, FD_CLOEXEC)");
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
)
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
)
130 xfree((void *)value
);
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
);
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
);
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
)
172 assert(family
== AF_INET6
&& "unknown family");
176 static void bug_warn(void)
178 fprintf(stderr
, "Please report how you produced this at "\
179 "raindrops@librelist.org\n");
183 static struct listen_stats
*stats_for(st_table
*table
, struct inet_diag_msg
*r
)
185 char *key
, *port
, *old_key
;
187 struct listen_stats
*stats
;
189 size_t portlen
= sizeof("65535");
190 union any_addr sa
= { 0 };
191 socklen_t len
= sizeof(struct sockaddr_storage
);
193 int flags
= NI_NUMERICHOST
| NI_NUMERICSERV
;
195 switch ((sa
.ss
.ss_family
= r
->idiag_family
)) {
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
);
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
;
213 alloca_len
= 1 + keylen
+ 1 + 1 + portlen
;
214 key
= alloca(alloca_len
);
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
);
223 assert(0 && "unsupported address family, could that be IPv7?!");
226 fprintf(stderr
, "BUG: getnameinfo: %s\n", gai_strerror(rc
));
231 keylen
= strlen(key
);
232 portlen
= strlen(port
);
234 switch (sa
.ss
.ss_family
) {
237 memmove(key
+ keylen
+ 1, port
, portlen
+ 1);
241 key
[keylen
+ 1] = ':';
242 memmove(key
+ keylen
+ 2, port
, portlen
+ 1);
246 assert(0 && "unsupported address family, could that be IPv7?!");
249 if (st_lookup(table
, (st_data_t
)key
, (st_data_t
*)&stats
))
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
));
259 fprintf(stderr
, "BUG: snprintf: %d\n", n
);
262 if (st_lookup(table
, (st_data_t
)key
, (st_data_t
*)&stats
))
269 key
= xmalloc(n
+ 1);
270 memcpy(key
, old_key
, n
+ 1);
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
);
281 static void table_incr_active(st_table
*table
, struct inet_diag_msg
*r
)
283 struct listen_stats
*stats
= stats_for(table
, r
);
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)
304 if (r
->idiag_state
== TCP_ESTABLISHED
) {
306 table_incr_active(args
->table
, r
);
308 args
->stats
.active
++;
309 } else { /* if (r->idiag_state == TCP_LISTEN) */
311 table_set_queued(args
->table
, r
);
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";
326 struct inet_diag_req r
;
329 static void prep_msghdr(
331 struct nogvl_args
*args
,
332 struct sockaddr_nl
*nladdr
,
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
,
346 struct diag_req
*req
,
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
;
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) {
397 prep_recvmsg_buf(args
);
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);
415 for ( ; NLMSG_OK(h
, r
); h
= NLMSG_NEXT(h
, r
)) {
416 if (h
->nlmsg_seq
!= seq
)
418 if (h
->nlmsg_type
== NLMSG_DONE
)
420 if (h
->nlmsg_type
== NLMSG_ERROR
) {
424 r_acc(args
, NLMSG_DATA(h
));
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
);
439 /* populates sockaddr_storage struct by parsing +addr+ */
440 static void parse_addr(union any_addr
*inet
, VALUE addr
)
445 char *rbracket
= NULL
;
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",
461 if (rbracket
[1] != ':')
462 rb_raise(rb_eArgError
, "':' not found in IPv6 addr=%s",
464 colon
= rbracket
+ 1;
467 inet
->ss
.ss_family
= af
= AF_INET6
;
468 dst
= &inet
->in6
.sin6_addr
;
469 portdst
= &inet
->in6
.sin6_port
;
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
;
478 rb_raise(rb_eArgError
, "port not found in: `%s'", host_ptr
);
479 port
= strtoul(colon
+ 1, &check
, 10);
481 rc
= inet_pton(af
, host_ptr
, dst
);
483 if (rbracket
) *rbracket
= ']';
484 if (*check
|| ((uint16_t)port
!= port
))
485 rb_raise(rb_eArgError
, "invalid port: %s", colon
+ 1);
487 rb_raise(rb_eArgError
, "inet_pton failed for: `%s' with %d",
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");
501 op
->code
= INET_DIAG_BC_S_COND
;
503 op
->no
= sizeof(struct inet_diag_bc_op
) + OPLEN
;
504 cond
= (struct inet_diag_hostcond
*)(op
+ 1);
505 cond
->family
= AF_UNSPEC
;
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");
519 op
->code
= INET_DIAG_BC_S_COND
;
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
) {
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
;
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
));
543 assert(0 && "unsupported address family, could that be IPv7?!");
547 static void nl_errcheck(VALUE r
)
549 const char *err
= (const char *)r
;
552 if (err
== err_nlmsg
)
553 rb_raise(rb_eRuntimeError
, "NLMSG_ERROR");
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
);
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
)
589 VALUE rv
= rb_hash_new();
590 struct nogvl_args args
;
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
);
604 sock
= rb_funcall(cIDSock
, id_new
, 0);
605 args
.fd
= my_fileno(sock
);
607 switch (TYPE(addrs
)) {
609 rb_hash_aset(rv
, addrs
, tcp_stats(&args
, addrs
));
612 ary
= RARRAY_PTR(addrs
);
613 i
= RARRAY_LEN(addrs
);
615 rb_hash_aset(rv
, *ary
, tcp_stats(&args
, *ary
));
618 for (; --i
>= 0; ary
++) {
619 union any_addr check
;
621 parse_addr(&check
, *ary
);
622 rb_hash_aset(rv
, *ary
, Qtrue
);
626 args
.table
= st_init_strtable();
627 gen_bytecode_all(&args
.iov
[2]);
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
);
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__ */