Ruby  1.9.3p547(2014-05-14revision45962)
unixsocket.c
Go to the documentation of this file.
1 /************************************************
2 
3  unixsocket.c -
4 
5  created at: Thu Mar 31 12:21:29 JST 1994
6 
7  Copyright (C) 1993-2007 Yukihiro Matsumoto
8 
9 ************************************************/
10 
11 #include "rubysocket.h"
12 
13 #ifdef HAVE_SYS_UN_H
14 struct unixsock_arg {
15  struct sockaddr_un *sockaddr;
16  socklen_t sockaddrlen;
17  int fd;
18 };
19 
20 static VALUE
21 unixsock_connect_internal(VALUE a)
22 {
23  struct unixsock_arg *arg = (struct unixsock_arg *)a;
24  return (VALUE)rsock_connect(arg->fd, (struct sockaddr*)arg->sockaddr,
25  arg->sockaddrlen, 0);
26 }
27 
28 VALUE
29 rsock_init_unixsock(VALUE sock, VALUE path, int server)
30 {
31  struct sockaddr_un sockaddr;
32  socklen_t sockaddrlen;
33  int fd, status;
34  rb_io_t *fptr;
35 
36  SafeStringValue(path);
37  fd = rsock_socket(AF_UNIX, SOCK_STREAM, 0);
38  if (fd < 0) {
39  rb_sys_fail("socket(2)");
40  }
41 
42  MEMZERO(&sockaddr, struct sockaddr_un, 1);
43  sockaddr.sun_family = AF_UNIX;
44  if (sizeof(sockaddr.sun_path) < (size_t)RSTRING_LEN(path)) {
45  rb_raise(rb_eArgError, "too long unix socket path (%ldbytes given but %dbytes max)",
46  RSTRING_LEN(path), (int)sizeof(sockaddr.sun_path));
47  }
48  memcpy(sockaddr.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
49  sockaddrlen = rsock_unix_sockaddr_len(path);
50 
51  if (server) {
52  status = bind(fd, (struct sockaddr*)&sockaddr, sockaddrlen);
53  }
54  else {
55  int prot;
56  struct unixsock_arg arg;
57  arg.sockaddr = &sockaddr;
58  arg.sockaddrlen = sockaddrlen;
59  arg.fd = fd;
60  status = (int)rb_protect(unixsock_connect_internal, (VALUE)&arg, &prot);
61  if (prot) {
62  close(fd);
63  rb_jump_tag(prot);
64  }
65  }
66 
67  if (status < 0) {
68  close(fd);
70  }
71 
72  if (server) {
73  if (listen(fd, 5) < 0) {
74  close(fd);
75  rb_sys_fail("listen(2)");
76  }
77  }
78 
79  rsock_init_sock(sock, fd);
80  if (server) {
81  GetOpenFile(sock, fptr);
82  fptr->pathv = rb_str_new_frozen(path);
83  }
84 
85  return sock;
86 }
87 
88 /*
89  * call-seq:
90  * UNIXSocket.new(path) => unixsocket
91  *
92  * Creates a new UNIX client socket connected to _path_.
93  *
94  * s = UNIXSocket.new("/tmp/sock")
95  * s.send "hello", 0
96  *
97  */
98 static VALUE
99 unix_init(VALUE sock, VALUE path)
100 {
101  return rsock_init_unixsock(sock, path, 0);
102 }
103 
104 /*
105  * call-seq:
106  * unixsocket.path => path
107  *
108  * Returns the path of the local address of unixsocket.
109  *
110  * s = UNIXServer.new("/tmp/sock")
111  * p s.path #=> "/tmp/sock"
112  *
113  */
114 static VALUE
115 unix_path(VALUE sock)
116 {
117  rb_io_t *fptr;
118 
119  GetOpenFile(sock, fptr);
120  if (NIL_P(fptr->pathv)) {
121  struct sockaddr_un addr;
122  socklen_t len = (socklen_t)sizeof(addr);
123  socklen_t len0 = len;
124  if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0)
125  rb_sys_fail(0);
126  if (len0 < len) len = len0;
127  fptr->pathv = rb_obj_freeze(rsock_unixpath_str(&addr, len));
128  }
129  return rb_str_dup(fptr->pathv);
130 }
131 
132 /*
133  * call-seq:
134  * unixsocket.recvfrom(maxlen [, flags]) => [mesg, unixaddress]
135  *
136  * Receives a message via _unixsocket_.
137  *
138  * _maxlen_ is the maximum number of bytes to receive.
139  *
140  * _flags_ should be a bitwise OR of Socket::MSG_* constants.
141  *
142  * s1 = Socket.new(:UNIX, :DGRAM, 0)
143  * s1_ai = Addrinfo.unix("/tmp/sock1")
144  * s1.bind(s1_ai)
145  *
146  * s2 = Socket.new(:UNIX, :DGRAM, 0)
147  * s2_ai = Addrinfo.unix("/tmp/sock2")
148  * s2.bind(s2_ai)
149  * s3 = UNIXSocket.for_fd(s2.fileno)
150  *
151  * s1.send "a", 0, s2_ai
152  * p s3.recvfrom(10) #=> ["a", ["AF_UNIX", "/tmp/sock1"]]
153  *
154  */
155 static VALUE
156 unix_recvfrom(int argc, VALUE *argv, VALUE sock)
157 {
158  return rsock_s_recvfrom(sock, argc, argv, RECV_UNIX);
159 }
160 
161 #if defined(HAVE_ST_MSG_CONTROL) && defined(SCM_RIGHTS)
162 #define FD_PASSING_BY_MSG_CONTROL 1
163 #else
164 #define FD_PASSING_BY_MSG_CONTROL 0
165 #endif
166 
167 #if defined(HAVE_ST_MSG_ACCRIGHTS)
168 #define FD_PASSING_BY_MSG_ACCRIGHTS 1
169 #else
170 #define FD_PASSING_BY_MSG_ACCRIGHTS 0
171 #endif
172 
173 struct iomsg_arg {
174  int fd;
175  struct msghdr msg;
176 };
177 
178 #if defined(HAVE_SENDMSG) && (FD_PASSING_BY_MSG_CONTROL || FD_PASSING_BY_MSG_ACCRIGHTS)
179 static VALUE
180 sendmsg_blocking(void *data)
181 {
182  struct iomsg_arg *arg = data;
183  return sendmsg(arg->fd, &arg->msg, 0);
184 }
185 
186 /*
187  * call-seq:
188  * unixsocket.send_io(io) => nil
189  *
190  * Sends _io_ as file descriptor passing.
191  *
192  * s1, s2 = UNIXSocket.pair
193  *
194  * s1.send_io STDOUT
195  * stdout = s2.recv_io
196  *
197  * p STDOUT.fileno #=> 1
198  * p stdout.fileno #=> 6
199  *
200  * stdout.puts "hello" # outputs "hello\n" to standard output.
201  */
202 static VALUE
203 unix_send_io(VALUE sock, VALUE val)
204 {
205  int fd;
206  rb_io_t *fptr;
207  struct iomsg_arg arg;
208  struct iovec vec[1];
209  char buf[1];
210 
211 #if FD_PASSING_BY_MSG_CONTROL
212  struct {
213  struct cmsghdr hdr;
214  char pad[8+sizeof(int)+8];
215  } cmsg;
216 #endif
217 
218  if (rb_obj_is_kind_of(val, rb_cIO)) {
219  rb_io_t *valfptr;
220  GetOpenFile(val, valfptr);
221  fd = valfptr->fd;
222  }
223  else if (FIXNUM_P(val)) {
224  fd = FIX2INT(val);
225  }
226  else {
227  rb_raise(rb_eTypeError, "neither IO nor file descriptor");
228  }
229 
230  GetOpenFile(sock, fptr);
231 
232  arg.msg.msg_name = NULL;
233  arg.msg.msg_namelen = 0;
234 
235  /* Linux and Solaris doesn't work if msg_iov is NULL. */
236  buf[0] = '\0';
237  vec[0].iov_base = buf;
238  vec[0].iov_len = 1;
239  arg.msg.msg_iov = vec;
240  arg.msg.msg_iovlen = 1;
241 
242 #if FD_PASSING_BY_MSG_CONTROL
243  arg.msg.msg_control = (caddr_t)&cmsg;
244  arg.msg.msg_controllen = (socklen_t)CMSG_LEN(sizeof(int));
245  arg.msg.msg_flags = 0;
246  MEMZERO((char*)&cmsg, char, sizeof(cmsg));
247  cmsg.hdr.cmsg_len = (socklen_t)CMSG_LEN(sizeof(int));
248  cmsg.hdr.cmsg_level = SOL_SOCKET;
249  cmsg.hdr.cmsg_type = SCM_RIGHTS;
250  memcpy(CMSG_DATA(&cmsg.hdr), &fd, sizeof(int));
251 #else
252  arg.msg.msg_accrights = (caddr_t)&fd;
253  arg.msg.msg_accrightslen = sizeof(fd);
254 #endif
255 
256  arg.fd = fptr->fd;
257  while ((int)BLOCKING_REGION_FD(sendmsg_blocking, &arg) == -1) {
258  if (!rb_io_wait_writable(arg.fd))
259  rb_sys_fail("sendmsg(2)");
260  }
261 
262  return Qnil;
263 }
264 #else
265 #define unix_send_io rb_f_notimplement
266 #endif
267 
268 #if defined(HAVE_RECVMSG) && (FD_PASSING_BY_MSG_CONTROL || FD_PASSING_BY_MSG_ACCRIGHTS)
269 static VALUE
270 recvmsg_blocking(void *data)
271 {
272  struct iomsg_arg *arg = data;
273  return recvmsg(arg->fd, &arg->msg, 0);
274 }
275 
276 /*
277  * call-seq:
278  * unixsocket.recv_io([klass [, mode]]) => io
279  *
280  * UNIXServer.open("/tmp/sock") {|serv|
281  * UNIXSocket.open("/tmp/sock") {|c|
282  * s = serv.accept
283  *
284  * c.send_io STDOUT
285  * stdout = s.recv_io
286  *
287  * p STDOUT.fileno #=> 1
288  * p stdout.fileno #=> 7
289  *
290  * stdout.puts "hello" # outputs "hello\n" to standard output.
291  * }
292  * }
293  *
294  */
295 static VALUE
296 unix_recv_io(int argc, VALUE *argv, VALUE sock)
297 {
298  VALUE klass, mode;
299  rb_io_t *fptr;
300  struct iomsg_arg arg;
301  struct iovec vec[2];
302  char buf[1];
303 
304  int fd;
305 #if FD_PASSING_BY_MSG_CONTROL
306  struct {
307  struct cmsghdr hdr;
308  char pad[8+sizeof(int)+8];
309  } cmsg;
310 #endif
311 
312  rb_scan_args(argc, argv, "02", &klass, &mode);
313  if (argc == 0)
314  klass = rb_cIO;
315  if (argc <= 1)
316  mode = Qnil;
317 
318  GetOpenFile(sock, fptr);
319 
320  arg.msg.msg_name = NULL;
321  arg.msg.msg_namelen = 0;
322 
323  vec[0].iov_base = buf;
324  vec[0].iov_len = sizeof(buf);
325  arg.msg.msg_iov = vec;
326  arg.msg.msg_iovlen = 1;
327 
328 #if FD_PASSING_BY_MSG_CONTROL
329  arg.msg.msg_control = (caddr_t)&cmsg;
330  arg.msg.msg_controllen = (socklen_t)CMSG_SPACE(sizeof(int));
331  arg.msg.msg_flags = 0;
332  cmsg.hdr.cmsg_len = (socklen_t)CMSG_LEN(sizeof(int));
333  cmsg.hdr.cmsg_level = SOL_SOCKET;
334  cmsg.hdr.cmsg_type = SCM_RIGHTS;
335  fd = -1;
336  memcpy(CMSG_DATA(&cmsg.hdr), &fd, sizeof(int));
337 #else
338  arg.msg.msg_accrights = (caddr_t)&fd;
339  arg.msg.msg_accrightslen = sizeof(fd);
340  fd = -1;
341 #endif
342 
343  arg.fd = fptr->fd;
344  while ((int)BLOCKING_REGION_FD(recvmsg_blocking, &arg) == -1) {
345  if (!rb_io_wait_readable(arg.fd))
346  rb_sys_fail("recvmsg(2)");
347  }
348 
349 #if FD_PASSING_BY_MSG_CONTROL
350  if (arg.msg.msg_controllen < (socklen_t)sizeof(struct cmsghdr)) {
352  "file descriptor was not passed (msg_controllen=%d smaller than sizeof(struct cmsghdr)=%d)",
353  (int)arg.msg.msg_controllen, (int)sizeof(struct cmsghdr));
354  }
355  if (cmsg.hdr.cmsg_level != SOL_SOCKET) {
357  "file descriptor was not passed (cmsg_level=%d, %d expected)",
358  cmsg.hdr.cmsg_level, SOL_SOCKET);
359  }
360  if (cmsg.hdr.cmsg_type != SCM_RIGHTS) {
362  "file descriptor was not passed (cmsg_type=%d, %d expected)",
363  cmsg.hdr.cmsg_type, SCM_RIGHTS);
364  }
365  if (arg.msg.msg_controllen < (socklen_t)CMSG_LEN(sizeof(int))) {
367  "file descriptor was not passed (msg_controllen=%d smaller than CMSG_LEN(sizeof(int))=%d)",
368  (int)arg.msg.msg_controllen, (int)CMSG_LEN(sizeof(int)));
369  }
370  if ((socklen_t)CMSG_SPACE(sizeof(int)) < arg.msg.msg_controllen) {
372  "file descriptor was not passed (msg_controllen=%d bigger than CMSG_SPACE(sizeof(int))=%d)",
373  (int)arg.msg.msg_controllen, (int)CMSG_SPACE(sizeof(int)));
374  }
375  if (cmsg.hdr.cmsg_len != CMSG_LEN(sizeof(int))) {
376  rsock_discard_cmsg_resource(&arg.msg, 0);
378  "file descriptor was not passed (cmsg_len=%d, %d expected)",
379  (int)cmsg.hdr.cmsg_len, (int)CMSG_LEN(sizeof(int)));
380  }
381 #else
382  if (arg.msg.msg_accrightslen != sizeof(fd)) {
384  "file descriptor was not passed (accrightslen) : %d != %d",
385  arg.msg.msg_accrightslen, (int)sizeof(fd));
386  }
387 #endif
388 
389 #if FD_PASSING_BY_MSG_CONTROL
390  memcpy(&fd, CMSG_DATA(&cmsg.hdr), sizeof(int));
391 #endif
392  rb_update_max_fd(fd);
393 
394  if (klass == Qnil)
395  return INT2FIX(fd);
396  else {
397  ID for_fd;
398  int ff_argc;
399  VALUE ff_argv[2];
400  CONST_ID(for_fd, "for_fd");
401  ff_argc = mode == Qnil ? 1 : 2;
402  ff_argv[0] = INT2FIX(fd);
403  ff_argv[1] = mode;
404  return rb_funcall2(klass, for_fd, ff_argc, ff_argv);
405  }
406 }
407 #else
408 #define unix_recv_io rb_f_notimplement
409 #endif
410 
411 /*
412  * call-seq:
413  * unixsocket.addr => [address_family, unix_path]
414  *
415  * Returns the local address as an array which contains
416  * address_family and unix_path.
417  *
418  * Example
419  * serv = UNIXServer.new("/tmp/sock")
420  * p serv.addr #=> ["AF_UNIX", "/tmp/sock"]
421  */
422 static VALUE
423 unix_addr(VALUE sock)
424 {
425  rb_io_t *fptr;
426  struct sockaddr_un addr;
427  socklen_t len = (socklen_t)sizeof addr;
428 
429  GetOpenFile(sock, fptr);
430 
431  if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0)
432  rb_sys_fail("getsockname(2)");
433  return rsock_unixaddr(&addr, len);
434 }
435 
436 /*
437  * call-seq:
438  * unixsocket.peeraddr => [address_family, unix_path]
439  *
440  * Returns the remote address as an array which contains
441  * address_family and unix_path.
442  *
443  * Example
444  * serv = UNIXServer.new("/tmp/sock")
445  * c = UNIXSocket.new("/tmp/sock")
446  * p c.peeraddr #=> ["AF_UNIX", "/tmp/sock"]
447  */
448 static VALUE
449 unix_peeraddr(VALUE sock)
450 {
451  rb_io_t *fptr;
452  struct sockaddr_un addr;
453  socklen_t len = (socklen_t)sizeof addr;
454  socklen_t len0 = len;
455 
456  GetOpenFile(sock, fptr);
457 
458  if (getpeername(fptr->fd, (struct sockaddr*)&addr, &len) < 0)
459  rb_sys_fail("getpeername(2)");
460  if (len0 < len) len = len0;
461  return rsock_unixaddr(&addr, len);
462 }
463 
464 /*
465  * call-seq:
466  * UNIXSocket.pair([type [, protocol]]) => [unixsocket1, unixsocket2]
467  * UNIXSocket.socketpair([type [, protocol]]) => [unixsocket1, unixsocket2]
468  *
469  * Creates a pair of sockets connected each other.
470  *
471  * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
472  *
473  * _protocol_ should be a protocol defined in the domain.
474  * 0 is default protocol for the domain.
475  *
476  * s1, s2 = UNIXSocket.pair
477  * s1.send "a", 0
478  * s1.send "b", 0
479  * p s2.recv(10) #=> "ab"
480  *
481  */
482 static VALUE
483 unix_s_socketpair(int argc, VALUE *argv, VALUE klass)
484 {
485  VALUE domain, type, protocol;
486  VALUE args[3];
487 
488  domain = INT2FIX(PF_UNIX);
489  rb_scan_args(argc, argv, "02", &type, &protocol);
490  if (argc == 0)
491  type = INT2FIX(SOCK_STREAM);
492  if (argc <= 1)
493  protocol = INT2FIX(0);
494 
495  args[0] = domain;
496  args[1] = type;
497  args[2] = protocol;
498 
499  return rsock_sock_s_socketpair(3, args, klass);
500 }
501 #endif
502 
503 void
505 {
506 #ifdef HAVE_SYS_UN_H
507  /*
508  * Document-class: UNIXSocket < BasicSocket
509  *
510  * UNIXSocket represents a UNIX domain stream client socket.
511  */
512  rb_cUNIXSocket = rb_define_class("UNIXSocket", rb_cBasicSocket);
513  rb_define_method(rb_cUNIXSocket, "initialize", unix_init, 1);
514  rb_define_method(rb_cUNIXSocket, "path", unix_path, 0);
515  rb_define_method(rb_cUNIXSocket, "addr", unix_addr, 0);
516  rb_define_method(rb_cUNIXSocket, "peeraddr", unix_peeraddr, 0);
517  rb_define_method(rb_cUNIXSocket, "recvfrom", unix_recvfrom, -1);
518  rb_define_method(rb_cUNIXSocket, "send_io", unix_send_io, 1);
519  rb_define_method(rb_cUNIXSocket, "recv_io", unix_recv_io, -1);
520  rb_define_singleton_method(rb_cUNIXSocket, "socketpair", unix_s_socketpair, -1);
521  rb_define_singleton_method(rb_cUNIXSocket, "pair", unix_s_socketpair, -1);
522 #endif
523 }
void rsock_init_unixsocket(void)
Definition: unixsocket.c:504
#define RSTRING_LEN(string)
Definition: generator.h:45
VALUE rsock_init_unixsock(VALUE sock, VALUE path, int server)
void rb_update_max_fd(int fd)
Definition: io.c:156
VALUE rb_cBasicSocket
Definition: init.c:13
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1343
int sendmsg(int, const struct msghdr *, int)
Definition: win32.c:3158
Definition: io.h:53
Definition: win32.h:223
VALUE rb_eTypeError
Definition: error.c:467
VALUE rsock_init_sock(VALUE sock, int fd)
Definition: init.c:43
VALUE rb_protect(VALUE(*proc)(VALUE), VALUE data, int *state)
Definition: eval.c:704
#define RSTRING_PTR(string)
Definition: generator.h:42
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:1574
VALUE rb_obj_is_kind_of(VALUE, VALUE)
Definition: object.c:525
#define FIXNUM_P(f)
Definition: ruby.h:338
int recvmsg(int, struct msghdr *, int)
Definition: win32.c:3099
#define GetOpenFile(obj, fp)
Definition: io.h:110
int args
Definition: win32ole.c:777
#define MEMZERO(p, type, n)
Definition: ruby.h:1052
VALUE rsock_sock_s_socketpair(int argc, VALUE *argv, VALUE klass)
int rsock_socket(int domain, int type, int proto)
Definition: init.c:243
#define NIL_P(v)
Definition: ruby.h:374
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:469
static char msg[50]
Definition: strerror.c:8
int fd
Definition: io.h:54
int rb_io_wait_writable(int)
Definition: io.c:916
void rb_sys_fail_str(VALUE mesg)
Definition: error.c:1677
int argc
Definition: ruby.c:120
arg
Definition: ripper.y:1287
RUBY_EXTERN VALUE rb_cIO
Definition: ruby.h:1262
VALUE rb_funcall2(VALUE, ID, int, const VALUE *)
Calls a method.
Definition: vm_eval.c:669
VALUE rsock_s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from)
Definition: init.c:105
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:1416
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:3913
unsigned long ID
Definition: ruby.h:89
#define Qnil
Definition: ruby.h:367
int type
Definition: tcltklib.c:107
unsigned long VALUE
Definition: ruby.h:88
#define FIX2INT(x)
Definition: ruby.h:538
Definition: win32.h:219
register unsigned int len
Definition: name2ctype.h:22210
void rb_sys_fail(const char *mesg)
Definition: error.c:1671
void rb_jump_tag(int tag)
Definition: eval.c:598
VALUE rb_str_dup(VALUE)
Definition: string.c:905
VALUE rb_eSocket
Definition: init.c:25
#define INT2FIX(i)
Definition: ruby.h:225
int rsock_connect(int fd, const struct sockaddr *sockaddr, int len, int socks)
Definition: init.c:344
VALUE pathv
Definition: io.h:59
#define SafeStringValue(v)
Definition: ruby.h:472
VALUE rb_str_new_frozen(VALUE)
Definition: string.c:672
VALUE rb_inspect(VALUE)
Definition: object.c:372
#define CONST_ID(var, str)
Definition: ruby.h:1127
VALUE rb_obj_freeze(VALUE)
Definition: object.c:902
#define NULL
Definition: _sdbm.c:107
int rb_io_wait_readable(int)
Definition: io.c:890
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1210
VALUE rb_eArgError
Definition: error.c:468
#define BLOCKING_REGION_FD(func, arg)
Definition: rubysocket.h:201
char ** argv
Definition: ruby.c:121