-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.c
4701 lines (4350 loc) · 127 KB
/
socket.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/************************************************
socket.c -
$Author: knu $
$Date: 2007-02-19 18:34:19 +0900 (Mon, 19 Feb 2007) $
created at: Thu Mar 31 12:21:29 JST 1994
Copyright (C) 1993-2001 Yukihiro Matsumoto
************************************************/
#include "ruby.h"
#include "rubyio.h"
#include "rubysig.h"
#include "util.h"
#include <stdio.h>
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif
#ifndef _WIN32
#if defined(__BEOS__)
# include <net/socket.h>
#else
# include <sys/socket.h>
# define pseudo_AF_FTIP pseudo_AF_RTIP /* workaround for NetBSD and etc. */
#endif
#include <netinet/in.h>
#ifdef HAVE_NETINET_IN_SYSTM_H
# include <netinet/in_systm.h>
#endif
#ifdef HAVE_NETINET_TCP_H
# include <netinet/tcp.h>
#endif
#ifdef HAVE_NETINET_UDP_H
# include <netinet/udp.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#include <netdb.h>
#endif
#include <errno.h>
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#if defined(HAVE_FCNTL)
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK EAGAIN
#endif
#ifndef HAVE_GETADDRINFO
# include "addrinfo.h"
#endif
#include "sockport.h"
#if defined(__vms)
#include <tcp.h>
#endif
static int do_not_reverse_lookup = 0;
VALUE rb_cBasicSocket;
VALUE rb_cIPSocket;
VALUE rb_cTCPSocket;
VALUE rb_cTCPServer;
VALUE rb_cUDPSocket;
#ifdef AF_UNIX
VALUE rb_cUNIXSocket;
VALUE rb_cUNIXServer;
#endif
VALUE rb_cSocket;
static VALUE rb_eSocket;
#ifdef SOCKS
VALUE rb_cSOCKSSocket;
#ifdef SOCKS5
#include <socks.h>
#else
void SOCKSinit();
int Rconnect();
#endif
#endif
#define INET_CLIENT 0
#define INET_SERVER 1
#define INET_SOCKS 2
#ifndef HAVE_SOCKADDR_STORAGE
/*
* RFC 2553: protocol-independent placeholder for socket addresses
*/
#define _SS_MAXSIZE 128
#define _SS_ALIGNSIZE (sizeof(double))
#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(unsigned char) * 2)
#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(unsigned char) * 2 - \
_SS_PAD1SIZE - _SS_ALIGNSIZE)
struct sockaddr_storage {
#ifdef HAVE_SA_LEN
unsigned char ss_len; /* address length */
unsigned char ss_family; /* address family */
#else
unsigned short ss_family;
#endif
char __ss_pad1[_SS_PAD1SIZE];
double __ss_align; /* force desired structure storage alignment */
char __ss_pad2[_SS_PAD2SIZE];
};
#endif
#if defined(INET6) && (defined(LOOKUP_ORDER_HACK_INET) || defined(LOOKUP_ORDER_HACK_INET6))
#define LOOKUP_ORDERS 3
static int lookup_order_table[LOOKUP_ORDERS] = {
#if defined(LOOKUP_ORDER_HACK_INET)
PF_INET, PF_INET6, PF_UNSPEC,
#elif defined(LOOKUP_ORDER_HACK_INET6)
PF_INET6, PF_INET, PF_UNSPEC,
#else
/* should not happen */
#endif
};
static int
ruby_getaddrinfo(nodename, servname, hints, res)
char *nodename;
char *servname;
struct addrinfo *hints;
struct addrinfo **res;
{
struct addrinfo tmp_hints;
int i, af, error;
if (hints->ai_family != PF_UNSPEC) {
return getaddrinfo(nodename, servname, hints, res);
}
for (i = 0; i < LOOKUP_ORDERS; i++) {
af = lookup_order_table[i];
MEMCPY(&tmp_hints, hints, struct addrinfo, 1);
tmp_hints.ai_family = af;
error = getaddrinfo(nodename, servname, &tmp_hints, res);
if (error) {
if (tmp_hints.ai_family == PF_UNSPEC) {
break;
}
}
else {
break;
}
}
return error;
}
#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo((node),(serv),(hints),(res))
#endif
#if defined(_AIX)
static int
ruby_getaddrinfo__aix(nodename, servname, hints, res)
char *nodename;
char *servname;
struct addrinfo *hints;
struct addrinfo **res;
{
int error = getaddrinfo(nodename, servname, hints, res);
struct addrinfo *r;
if (error)
return error;
for (r = *res; r != NULL; r = r->ai_next) {
if (r->ai_addr->sa_family == 0)
r->ai_addr->sa_family = r->ai_family;
if (r->ai_addr->sa_len == 0)
r->ai_addr->sa_len = r->ai_addrlen;
}
return 0;
}
#undef getaddrinfo
#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__aix((node),(serv),(hints),(res))
static int
ruby_getnameinfo__aix(sa, salen, host, hostlen, serv, servlen, flags)
const struct sockaddr *sa;
size_t salen;
char *host;
size_t hostlen;
char *serv;
size_t servlen;
int flags;
{
struct sockaddr_in6 *sa6;
u_int32_t *a6;
if (sa->sa_family == AF_INET6) {
sa6 = (struct sockaddr_in6 *)sa;
a6 = sa6->sin6_addr.u6_addr.u6_addr32;
if (a6[0] == 0 && a6[1] == 0 && a6[2] == 0 && a6[3] == 0) {
strncpy(host, "::", hostlen);
snprintf(serv, servlen, "%d", sa6->sin6_port);
return 0;
}
}
return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
}
#undef getnameinfo
#define getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) \
ruby_getnameinfo__aix((sa), (salen), (host), (hostlen), (serv), (servlen), (flags))
#ifndef CMSG_SPACE
# define CMSG_SPACE(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + _CMSG_ALIGN(len))
#endif
#ifndef CMSG_LEN
# define CMSG_LEN(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + (len))
#endif
#endif
#ifdef HAVE_CLOSESOCKET
#undef close
#define close closesocket
#endif
static VALUE
init_sock(sock, fd)
VALUE sock;
int fd;
{
OpenFile *fp;
MakeOpenFile(sock, fp);
fp->f = rb_fdopen(fd, "r");
fp->f2 = rb_fdopen(fd, "w");
fp->mode = FMODE_READWRITE;
rb_io_synchronized(fp);
return sock;
}
static VALUE
bsock_s_for_fd(klass, fd)
VALUE klass, fd;
{
OpenFile *fptr;
VALUE sock = init_sock(rb_obj_alloc(klass), NUM2INT(fd));
GetOpenFile(sock, fptr);
return sock;
}
static VALUE
bsock_shutdown(argc, argv, sock)
int argc;
VALUE *argv;
VALUE sock;
{
VALUE howto;
int how;
OpenFile *fptr;
if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
rb_raise(rb_eSecurityError, "Insecure: can't shutdown socket");
}
rb_scan_args(argc, argv, "01", &howto);
if (howto == Qnil)
how = 2;
else {
how = NUM2INT(howto);
if (how < 0 || 2 < how) {
rb_raise(rb_eArgError, "`how' should be either 0, 1, 2");
}
}
GetOpenFile(sock, fptr);
if (shutdown(fileno(fptr->f), how) == -1)
rb_sys_fail(0);
return INT2FIX(0);
}
static VALUE
bsock_close_read(sock)
VALUE sock;
{
OpenFile *fptr;
if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
rb_raise(rb_eSecurityError, "Insecure: can't close socket");
}
GetOpenFile(sock, fptr);
shutdown(fileno(fptr->f), 0);
if (!(fptr->mode & FMODE_WRITABLE)) {
return rb_io_close(sock);
}
fptr->mode &= ~FMODE_READABLE;
return Qnil;
}
static VALUE
bsock_close_write(sock)
VALUE sock;
{
OpenFile *fptr;
if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
rb_raise(rb_eSecurityError, "Insecure: can't close socket");
}
GetOpenFile(sock, fptr);
if (!(fptr->mode & FMODE_READABLE)) {
return rb_io_close(sock);
}
shutdown(fileno(fptr->f2), 1);
fptr->mode &= ~FMODE_WRITABLE;
return Qnil;
}
/*
* Document-method: setsockopt
* call-seq: setsockopt(level, optname, optval)
*
* Sets a socket option. These are protocol and system specific, see your
* local sytem documentation for details.
*
* === Parameters
* * +level+ is an integer, usually one of the SOL_ constants such as
* Socket::SOL_SOCKET, or a protocol level.
* * +optname+ is an integer, usually one of the SO_ constants, such
* as Socket::SO_REUSEADDR.
* * +optval+ is the value of the option, it is passed to the underlying
* setsockopt() as a pointer to a certain number of bytes. How this is
* done depends on the type:
* - Fixnum: value is assigned to an int, and a pointer to the int is
* passed, with length of sizeof(int).
* - true or false: 1 or 0 (respectively) is assigned to an int, and the
* int is passed as for a Fixnum. Note that +false+ must be passed,
* not +nil+.
* - String: the string's data and length is passed to the socket.
*
* === Examples
*
* Some socket options are integers with boolean values, in this case
* #setsockopt could be called like this:
* sock.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
*
* Some socket options are integers with numeric values, in this case
* #setsockopt could be called like this:
* sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, 255)
*
* Option values may be structs. Passing them can be complex as it involves
* examining your system headers to determine the correct definition. An
* example is an +ip_mreq+, which may be defined in your system headers as:
* struct ip_mreq {
* struct in_addr imr_multiaddr;
* struct in_addr imr_interface;
* };
*
* In this case #setsockopt could be called like this:
* optval = IPAddr.new("224.0.0.251") + Socket::INADDR_ANY
* sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, optval)
*
*/
static VALUE
bsock_setsockopt(sock, lev, optname, val)
VALUE sock, lev, optname, val;
{
int level, option;
OpenFile *fptr;
int i;
char *v;
int vlen;
rb_secure(2);
level = NUM2INT(lev);
option = NUM2INT(optname);
switch (TYPE(val)) {
case T_FIXNUM:
i = FIX2INT(val);
goto numval;
case T_FALSE:
i = 0;
goto numval;
case T_TRUE:
i = 1;
numval:
v = (char*)&i; vlen = sizeof(i);
break;
default:
StringValue(val);
v = RSTRING(val)->ptr;
vlen = RSTRING(val)->len;
break;
}
GetOpenFile(sock, fptr);
if (setsockopt(fileno(fptr->f), level, option, v, vlen) < 0)
rb_sys_fail(fptr->path);
return INT2FIX(0);
}
/*
* Document-method: getsockopt
* call-seq: getsockopt(level, optname)
*
* Gets a socket option. These are protocol and system specific, see your
* local sytem documentation for details. The option is returned as
* a String with the data being the binary value of the socket option.
*
* === Parameters
* * +level+ is an integer, usually one of the SOL_ constants such as
* Socket::SOL_SOCKET, or a protocol level.
* * +optname+ is an integer, usually one of the SO_ constants, such
* as Socket::SO_REUSEADDR.
*
* === Examples
*
* Some socket options are integers with boolean values, in this case
* #getsockopt could be called like this:
* optval = sock.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR)
* optval = optval.unpack "i"
* reuseaddr = optval[0] == 0 ? false : true
*
* Some socket options are integers with numeric values, in this case
* #getsockopt could be called like this:
* optval = sock.getsockopt(Socket::IPPROTO_IP, Socket::IP_TTL)
* ipttl = optval.unpack("i")[0]
*
* Option values may be structs. Decoding them can be complex as it involves
* examining your system headers to determine the correct definition. An
* example is a +struct linger+, which may be defined in your system headers
* as:
* struct linger {
* int l_onoff;
* int l_linger;
* };
*
* In this case #getsockopt could be called like this:
* optval = sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER)
* onoff, linger = optval.unpack "ii"
*/
static VALUE
bsock_getsockopt(sock, lev, optname)
VALUE sock, lev, optname;
{
#if !defined(__BEOS__)
int level, option;
socklen_t len;
char *buf;
OpenFile *fptr;
level = NUM2INT(lev);
option = NUM2INT(optname);
len = 256;
buf = ALLOCA_N(char,len);
GetOpenFile(sock, fptr);
GetOpenFile(sock, fptr);
if (getsockopt(fileno(fptr->f), level, option, buf, &len) < 0)
rb_sys_fail(fptr->path);
return rb_str_new(buf, len);
#else
rb_notimplement();
#endif
}
static VALUE
bsock_getsockname(sock)
VALUE sock;
{
char buf[1024];
socklen_t len = sizeof buf;
OpenFile *fptr;
GetOpenFile(sock, fptr);
if (getsockname(fileno(fptr->f), (struct sockaddr*)buf, &len) < 0)
rb_sys_fail("getsockname(2)");
return rb_str_new(buf, len);
}
static VALUE
bsock_getpeername(sock)
VALUE sock;
{
char buf[1024];
socklen_t len = sizeof buf;
OpenFile *fptr;
GetOpenFile(sock, fptr);
if (getpeername(fileno(fptr->f), (struct sockaddr*)buf, &len) < 0)
rb_sys_fail("getpeername(2)");
return rb_str_new(buf, len);
}
static VALUE
bsock_send(argc, argv, sock)
int argc;
VALUE *argv;
VALUE sock;
{
VALUE mesg, to;
VALUE flags;
OpenFile *fptr;
FILE *f;
int fd, n;
rb_secure(4);
rb_scan_args(argc, argv, "21", &mesg, &flags, &to);
StringValue(mesg);
if (!NIL_P(to)) StringValue(to);
GetOpenFile(sock, fptr);
f = GetWriteFile(fptr);
fd = fileno(f);
rb_thread_fd_writable(fd);
retry:
if (!NIL_P(to)) {
TRAP_BEG;
n = sendto(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags),
(struct sockaddr*)RSTRING(to)->ptr, RSTRING(to)->len);
TRAP_END;
}
else {
TRAP_BEG;
n = send(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags));
TRAP_END;
}
if (n < 0) {
if (rb_io_wait_writable(fd)) {
goto retry;
}
rb_sys_fail("send(2)");
}
return INT2FIX(n);
}
static VALUE ipaddr _((struct sockaddr*));
#ifdef HAVE_SYS_UN_H
static VALUE unixaddr _((struct sockaddr_un*, socklen_t));
#endif
enum sock_recv_type {
RECV_RECV, /* BasicSocket#recv(no from) */
RECV_IP, /* IPSocket#recvfrom */
RECV_UNIX, /* UNIXSocket#recvfrom */
RECV_SOCKET /* Socket#recvfrom */
};
static VALUE
s_recvfrom(sock, argc, argv, from)
VALUE sock;
int argc;
VALUE *argv;
enum sock_recv_type from;
{
OpenFile *fptr;
VALUE str;
char buf[1024];
socklen_t alen = sizeof buf;
VALUE len, flg;
long buflen;
long slen;
int fd, flags;
rb_scan_args(argc, argv, "11", &len, &flg);
if (flg == Qnil) flags = 0;
else flags = NUM2INT(flg);
buflen = NUM2INT(len);
GetOpenFile(sock, fptr);
if (rb_read_pending(fptr->f)) {
rb_raise(rb_eIOError, "recv for buffered IO");
}
fd = fileno(fptr->f);
str = rb_tainted_str_new(0, buflen);
retry:
rb_str_locktmp(str);
rb_thread_wait_fd(fd);
TRAP_BEG;
slen = recvfrom(fd, RSTRING(str)->ptr, buflen, flags, (struct sockaddr*)buf, &alen);
TRAP_END;
rb_str_unlocktmp(str);
if (slen < 0) {
if (rb_io_wait_readable(fd)) {
goto retry;
}
rb_sys_fail("recvfrom(2)");
}
if (slen < RSTRING(str)->len) {
RSTRING(str)->len = slen;
RSTRING(str)->ptr[slen] = '\0';
}
rb_obj_taint(str);
switch (from) {
case RECV_RECV:
return (VALUE)str;
case RECV_IP:
#if 0
if (alen != sizeof(struct sockaddr_in)) {
rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
}
#endif
if (alen) /* OSX doesn't return a 'from' result from recvfrom for connection-oriented sockets */
return rb_assoc_new(str, ipaddr((struct sockaddr*)buf));
else
return rb_assoc_new(str, Qnil);
#ifdef HAVE_SYS_UN_H
case RECV_UNIX:
return rb_assoc_new(str, unixaddr((struct sockaddr_un*)buf, alen));
#endif
case RECV_SOCKET:
return rb_assoc_new(str, rb_str_new(buf, alen));
default:
rb_bug("s_recvfrom called with bad value");
}
}
static VALUE
s_recvfrom_nonblock(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from)
{
OpenFile *fptr;
VALUE str;
char buf[1024];
socklen_t alen = sizeof buf;
VALUE len, flg;
long buflen;
long slen;
int fd, flags;
VALUE addr = Qnil;
rb_scan_args(argc, argv, "11", &len, &flg);
if (flg == Qnil) flags = 0;
else flags = NUM2INT(flg);
buflen = NUM2INT(len);
#ifdef MSG_DONTWAIT
/* MSG_DONTWAIT avoids the race condition between fcntl and recvfrom.
It is not portable, though. */
flags |= MSG_DONTWAIT;
#endif
GetOpenFile(sock, fptr);
if (rb_read_pending(fptr->f)) {
rb_raise(rb_eIOError, "recvfrom for buffered IO");
}
fd = fileno(fptr->f);
str = rb_tainted_str_new(0, buflen);
rb_io_check_closed(fptr);
rb_io_set_nonblock(fptr);
slen = recvfrom(fd, RSTRING(str)->ptr, buflen, flags, (struct sockaddr*)buf, &alen);
if (slen < 0) {
rb_sys_fail("recvfrom(2)");
}
if (slen < RSTRING(str)->len) {
RSTRING(str)->len = slen;
RSTRING(str)->ptr[slen] = '\0';
}
rb_obj_taint(str);
switch (from) {
case RECV_RECV:
return str;
case RECV_IP:
if (alen) /* connection-oriented socket may not return a from result */
addr = ipaddr((struct sockaddr*)buf);
break;
case RECV_SOCKET:
addr = rb_str_new(buf, alen);
break;
default:
rb_bug("s_recvfrom_nonblock called with bad value");
}
return rb_assoc_new(str, addr);
}
static VALUE
bsock_recv(argc, argv, sock)
int argc;
VALUE *argv;
VALUE sock;
{
return s_recvfrom(sock, argc, argv, RECV_RECV);
}
/*
* call-seq:
* basicsocket.recv_nonblock(maxlen) => mesg
* basicsocket.recv_nonblock(maxlen, flags) => mesg
*
* Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after
* O_NONBLOCK is set for the underlying file descriptor.
* _flags_ is zero or more of the +MSG_+ options.
* The result, _mesg_, is the data received.
*
* When recvfrom(2) returns 0, Socket#recv_nonblock returns
* an empty string as data.
* The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.
*
* === Parameters
* * +maxlen+ - the number of bytes to receive from the socket
* * +flags+ - zero or more of the +MSG_+ options
*
* === Example
* serv = TCPServer.new("127.0.0.1", 0)
* af, port, host, addr = serv.addr
* c = TCPSocket.new(addr, port)
* s = serv.accept
* c.send "aaa", 0
* IO.select([s])
* p s.recv_nonblock(10) #=> "aaa"
*
* Refer to Socket#recvfrom for the exceptions that may be thrown if the call
* to _recv_nonblock_ fails.
*
* BasicSocket#recv_nonblock may raise any error corresponding to recvfrom(2) failure,
* including Errno::EAGAIN.
*
* === See
* * Socket#recvfrom
*/
static VALUE
bsock_recv_nonblock(argc, argv, sock)
int argc;
VALUE *argv;
VALUE sock;
{
return s_recvfrom_nonblock(sock, argc, argv, RECV_RECV);
}
static VALUE
bsock_do_not_rev_lookup()
{
return do_not_reverse_lookup?Qtrue:Qfalse;
}
static VALUE
bsock_do_not_rev_lookup_set(self, val)
VALUE self, val;
{
rb_secure(4);
do_not_reverse_lookup = RTEST(val);
return val;
}
static void
make_ipaddr0(addr, buf, len)
struct sockaddr *addr;
char *buf;
size_t len;
{
int error;
error = getnameinfo(addr, SA_LEN(addr), buf, len, NULL, 0, NI_NUMERICHOST);
if (error) {
rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error));
}
}
static VALUE
make_ipaddr(addr)
struct sockaddr *addr;
{
char buf[1024];
make_ipaddr0(addr, buf, sizeof(buf));
return rb_str_new2(buf);
}
static void
make_inetaddr(host, buf, len)
long host;
char *buf;
size_t len;
{
struct sockaddr_in sin;
MEMZERO(&sin, struct sockaddr_in, 1);
sin.sin_family = AF_INET;
SET_SIN_LEN(&sin, sizeof(sin));
sin.sin_addr.s_addr = host;
make_ipaddr0((struct sockaddr*)&sin, buf, len);
}
static int
str_isnumber(p)
const char *p;
{
char *ep;
if (!p || *p == '\0')
return 0;
ep = NULL;
(void)strtoul(p, &ep, 10);
if (ep && *ep == '\0')
return 1;
else
return 0;
}
static char *
host_str(host, hbuf, len)
VALUE host;
char *hbuf;
size_t len;
{
if (NIL_P(host)) {
return NULL;
}
else if (rb_obj_is_kind_of(host, rb_cInteger)) {
long i = NUM2LONG(host);
make_inetaddr(htonl(i), hbuf, len);
return hbuf;
}
else {
char *name;
SafeStringValue(host);
name = RSTRING(host)->ptr;
if (!name || *name == 0 || (name[0] == '<' && strcmp(name, "<any>") == 0)) {
make_inetaddr(INADDR_ANY, hbuf, len);
}
else if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
make_inetaddr(INADDR_BROADCAST, hbuf, len);
}
else if (strlen(name) >= len) {
rb_raise(rb_eArgError, "hostname too long (%d)", strlen(name));
}
else {
strcpy(hbuf, name);
}
return hbuf;
}
}
static char *
port_str(port, pbuf, len)
VALUE port;
char *pbuf;
size_t len;
{
if (NIL_P(port)) {
return 0;
}
else if (FIXNUM_P(port)) {
snprintf(pbuf, len, "%ld", FIX2LONG(port));
return pbuf;
}
else {
char *serv;
SafeStringValue(port);
serv = RSTRING(port)->ptr;
if (strlen(serv) >= len) {
rb_raise(rb_eArgError, "service name too long (%d)", strlen(serv));
}
strcpy(pbuf, serv);
return pbuf;
}
}
#ifndef NI_MAXHOST
# define 1025
#endif
#ifndef NI_MAXSERV
# define 32
#endif
static struct addrinfo*
sock_addrinfo(host, port, socktype, flags)
VALUE host, port;
int socktype, flags;
{
struct addrinfo hints;
struct addrinfo* res = NULL;
char *hostp, *portp;
int error;
char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
hostp = host_str(host, hbuf, sizeof(hbuf));
portp = port_str(port, pbuf, sizeof(pbuf));
if (socktype == 0 && flags == 0 && str_isnumber(portp)) {
socktype = SOCK_DGRAM;
}
MEMZERO(&hints, struct addrinfo, 1);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = socktype;
hints.ai_flags = flags;
error = getaddrinfo(hostp, portp, &hints, &res);
if (error) {
if (hostp && hostp[strlen(hostp)-1] == '\n') {
rb_raise(rb_eSocket, "newline at the end of hostname");
}
rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error));
}
#if defined(__APPLE__) && defined(__MACH__)
{
struct addrinfo *r;
r = res;
while (r) {
if (! r->ai_socktype) r->ai_socktype = hints.ai_socktype;
if (! r->ai_protocol) {
if (r->ai_socktype == SOCK_DGRAM) {
r->ai_protocol = IPPROTO_UDP;
} else if (r->ai_socktype == SOCK_STREAM) {
r->ai_protocol = IPPROTO_TCP;
}
}
r = r->ai_next;
}
}
#endif
return res;
}
static VALUE
ipaddr(sockaddr)
struct sockaddr *sockaddr;
{
VALUE family, port, addr1, addr2;
VALUE ary;
int error;
char hbuf[1024], pbuf[1024];
switch (sockaddr->sa_family) {
case AF_UNSPEC:
family = rb_str_new2("AF_UNSPEC");
break;
case AF_INET:
family = rb_str_new2("AF_INET");
break;
#ifdef INET6
case AF_INET6:
family = rb_str_new2("AF_INET6");
break;
#endif
#ifdef AF_LOCAL
case AF_LOCAL:
family = rb_str_new2("AF_LOCAL");
break;
#elif AF_UNIX
case AF_UNIX:
family = rb_str_new2("AF_UNIX");
break;
#endif
default:
sprintf(pbuf, "unknown:%d", sockaddr->sa_family);
family = rb_str_new2(pbuf);
break;
}
addr1 = Qnil;
if (!do_not_reverse_lookup) {
error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf),
NULL, 0, 0);
if (! error) {
addr1 = rb_str_new2(hbuf);
}
}
error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf),
pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV);
if (error) {
rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error));
}
addr2 = rb_str_new2(hbuf);