Debian Codegraph @

rpython/rlib/rsocket.py

raw symbols SCIP
1 """
2 An RPython implementation of sockets based on rffi.
3 Note that the interface has to be slightly different - this is not
4 a drop-in replacement for the 'socket' module.
5 """
6
7 # XXX this does not support yet the least common AF_xxx address families
8 # supported by CPython. See http://bugs.pypy.org/issue1942
9
10 from errno import EINVAL
11 from rpython.rlib import _rsocket_rffi as _c, jit, rgc
12 from rpython.rlib.buffer import LLBuffer
13 from rpython.rlib.unroll import unrolling_iterable
14 from rpython.rlib.objectmodel import (
15 specialize, instantiate, keepalive_until_here)
16 from rpython.rlib.rarithmetic import intmask, r_uint, widen
17 from rpython.rlib import rthread, rposix
18 from rpython.rtyper.lltypesystem import lltype, rffi
19 from rpython.rtyper.lltypesystem.rffi import sizeof, offsetof
20 from rpython.rtyper.extregistry import ExtRegistryEntry
21
22
23 # Usage of @jit.dont_look_inside in this file is possibly temporary
24 # and only because some lltypes declared in _rsocket_rffi choke the
25 # JIT's codewriter right now (notably, FixedSizeArray).
26 INVALID_SOCKET = _c.INVALID_SOCKET
27
28
29 def mallocbuf(buffersize):
30 return lltype.malloc(rffi.CCHARP.TO, buffersize, flavor='raw')
31
32
33 constants = _c.constants
34 locals().update(constants) # Define constants from _c
35
36 HAS_SO_PROTOCOL = hasattr(_c, 'SO_PROTOCOL')
37
38 if _c.WIN32:
39 from rpython.rlib import rwin32
40
41 def rsocket_startup():
42 wsadata = lltype.malloc(_c.WSAData, flavor='raw', zero=True)
43 try:
44 res = _c.WSAStartup(0x0101, wsadata)
45 assert res == 0
46 finally:
47 lltype.free(wsadata, flavor='raw')
48 else:
49 def rsocket_startup():
50 pass
51
52
53 def ntohs(x):
54 assert isinstance(x, int)
55 return rffi.cast(lltype.Signed, _c.ntohs(x))
56
57 def ntohl(x):
58 # accepts and returns an Unsigned
59 return rffi.cast(lltype.Unsigned, _c.ntohl(x))
60
61 def htons(x):
62 assert isinstance(x, int)
63 return rffi.cast(lltype.Signed, _c.htons(x))
64
65 def htonl(x):
66 # accepts and returns an Unsigned
67 return rffi.cast(lltype.Unsigned, _c.htonl(x))
68
69
70 _FAMILIES = {}
71
72 class Address(object):
73 """The base class for RPython-level objects representing addresses.
74 Fields: addr - a _c.sockaddr_ptr (memory owned by the Address instance)
75 addrlen - size used within 'addr'
76 """
77 class __metaclass__(type):
78 def __new__(cls, name, bases, dict):
79 family = dict.get('family')
80 A = type.__new__(cls, name, bases, dict)
81 if family is not None:
82 _FAMILIES[family] = A
83 return A
84
85 # default uninitialized value: NULL ptr
86 addr_p = lltype.nullptr(_c.sockaddr_ptr.TO)
87
88 def __init__(self, addr, addrlen):
89 self.addr_p = addr
90 self.addrlen = addrlen
91
92 @rgc.must_be_light_finalizer
93 def __del__(self):
94 if self.addr_p:
95 lltype.free(self.addr_p, flavor='raw', track_allocation=False)
96
97 @specialize.ll()
98 def setdata(self, addr, addrlen):
99 # initialize self.addr and self.addrlen. 'addr' can be a different
100 # pointer type than exactly sockaddr_ptr, and we cast it for you.
101 assert not self.addr_p
102 self.addr_p = rffi.cast(_c.sockaddr_ptr, addr)
103 self.addrlen = addrlen
104
105 # the following slightly strange interface is needed to manipulate
106 # what self.addr_p points to in a safe way. The problem is that
107 # after inlining we might end up with operations that looks like:
108 # addr = self.addr_p
109 # <self is freed here, and its __del__ calls lltype.free()>
110 # read from addr
111 # To prevent this we have to insert a keepalive after the last
112 # use of 'addr'. The interface to do that is called lock()/unlock()
113 # because it strongly reminds callers not to forget unlock().
114 #
115 @specialize.ll()
116 def lock(self, TYPE=_c.sockaddr):
117 """Return self.addr_p, cast as a pointer to TYPE. Must call unlock()!
118 """
119 return rffi.cast(lltype.Ptr(TYPE), self.addr_p)
120
121 def unlock(self):
122 """To call after we're done with the pointer returned by lock().
123 Note that locking and unlocking costs nothing at run-time.
124 """
125 keepalive_until_here(self)
126
127 # ____________________________________________________________
128
129 def makeipaddr(name, result=None):
130 # Convert a string specifying a host name or one of a few symbolic
131 # names to an IPAddress instance. This usually calls getaddrinfo()
132 # to do the work; the names "" and "<broadcast>" are special.
133 # If 'result' is specified it must be a prebuilt INETAddress or
134 # INET6Address that is filled; otherwise a new INETXAddress is returned.
135 if result is None:
136 family = AF_UNSPEC
137 else:
138 family = result.family
139
140 if len(name) == 0:
141 info = getaddrinfo(None, "0",
142 family=family,
143 socktype=SOCK_DGRAM, # dummy
144 flags=AI_PASSIVE,
145 address_to_fill=result)
146 if len(info) > 1:
147 raise RSocketError("wildcard resolved to multiple addresses")
148 return info[0][4]
149
150 # IPv4 also supports the special name "<broadcast>".
151 if name == '<broadcast>':
152 return makeipv4addr(r_uint(INADDR_BROADCAST), result)
153
154 # "dd.dd.dd.dd" format.
155 digits = name.split('.')
156 if len(digits) == 4:
157 try:
158 d0 = int(digits[0])
159 d1 = int(digits[1])
160 d2 = int(digits[2])
161 d3 = int(digits[3])
162 except ValueError:
163 pass
164 else:
165 if (0 <= d0 <= 255 and 0 <= d1 <= 255 and
166 0 <= d2 <= 255 and 0 <= d3 <= 255):
167 addr = intmask(d0 << 24) | (d1 << 16) | (d2 << 8) | (d3 << 0)
168 addr = rffi.cast(rffi.UINT, addr)
169 addr = htonl(addr)
170 return makeipv4addr(addr, result)
171
172 # generic host name to IP conversion
173 info = getaddrinfo(name, None, family=family, address_to_fill=result)
174 return info[0][4]
175
176 class IPAddress(Address):
177 """AF_INET and AF_INET6 addresses"""
178
179 def get_host(self):
180 # Create a string object representing an IP address.
181 # For IPv4 this is always a string of the form 'dd.dd.dd.dd'
182 # (with variable size numbers).
183 host, serv = getnameinfo(self, NI_NUMERICHOST | NI_NUMERICSERV)
184 return host
185
186 def lock_in_addr(self):
187 """ Purely abstract
188 """
189 raise NotImplementedError
190
191 # ____________________________________________________________
192
193 HAS_AF_PACKET = 'AF_PACKET' in constants
194 if HAS_AF_PACKET:
195 class PacketAddress(Address):
196 family = AF_PACKET
197 struct = _c.sockaddr_ll
198 maxlen = minlen = sizeof(struct)
199 ifr_name_size = _c.ifreq.c_ifr_name.length
200 sll_addr_size = _c.sockaddr_ll.c_sll_addr.length
201
202 def __init__(self, ifindex, protocol, pkttype=0, hatype=0, haddr=""):
203 addr = lltype.malloc(_c.sockaddr_ll, flavor='raw', zero=True,
204 track_allocation=False)
205 self.setdata(addr, PacketAddress.maxlen)
206 rffi.setintfield(addr, 'c_sll_family', AF_PACKET)
207 rffi.setintfield(addr, 'c_sll_protocol', htons(protocol))
208 rffi.setintfield(addr, 'c_sll_ifindex', ifindex)
209 rffi.setintfield(addr, 'c_sll_pkttype', pkttype)
210 rffi.setintfield(addr, 'c_sll_hatype', hatype)
211 halen = rffi.str2chararray(haddr,
212 rffi.cast(rffi.CCHARP, addr.c_sll_addr),
213 PacketAddress.sll_addr_size)
214 rffi.setintfield(addr, 'c_sll_halen', halen)
215
216 @staticmethod
217 def get_ifindex_from_ifname(fd, ifname):
218 p = lltype.malloc(_c.ifreq, flavor='raw')
219 iflen = rffi.str2chararray(ifname,
220 rffi.cast(rffi.CCHARP, p.c_ifr_name),
221 PacketAddress.ifr_name_size - 1)
222 p.c_ifr_name[iflen] = '\0'
223 err = _c.ioctl(fd, _c.SIOCGIFINDEX, p)
224 ifindex = p.c_ifr_ifindex
225 lltype.free(p, flavor='raw')
226 if err != 0:
227 raise RSocketError("invalid interface name")
228 return ifindex
229
230 def get_ifname(self, fd):
231 ifname = ""
232 a = self.lock(_c.sockaddr_ll)
233 ifindex = rffi.getintfield(a, 'c_sll_ifindex')
234 if ifindex:
235 p = lltype.malloc(_c.ifreq, flavor='raw')
236 rffi.setintfield(p, 'c_ifr_ifindex', ifindex)
237 if (_c.ioctl(fd, _c.SIOCGIFNAME, p) == 0):
238 ifname = rffi.charp2strn(
239 rffi.cast(rffi.CCHARP, p.c_ifr_name),
240 PacketAddress.ifr_name_size)
241 lltype.free(p, flavor='raw')
242 self.unlock()
243 return ifname
244
245 def get_protocol(self):
246 a = self.lock(_c.sockaddr_ll)
247 proto = rffi.getintfield(a, 'c_sll_protocol')
248 res = ntohs(proto)
249 self.unlock()
250 return res
251
252 def get_pkttype(self):
253 a = self.lock(_c.sockaddr_ll)
254 res = rffi.getintfield(a, 'c_sll_pkttype')
255 self.unlock()
256 return res
257
258 def get_hatype(self):
259 a = self.lock(_c.sockaddr_ll)
260 res = rffi.getintfield(a, 'c_sll_hatype')
261 self.unlock()
262 return res
263
264 def get_haddr(self):
265 a = self.lock(_c.sockaddr_ll)
266 lgt = rffi.getintfield(a, 'c_sll_halen')
267 d = []
268 for i in range(lgt):
269 d.append(chr(a.c_sll_addr[i]))
270 res = "".join(d)
271 self.unlock()
272 return res
273
274
275 class INETAddress(IPAddress):
276 family = AF_INET
277 struct = _c.sockaddr_in
278 maxlen = minlen = sizeof(struct)
279
280 def __init__(self, host, port):
281 makeipaddr(host, self)
282 a = self.lock(_c.sockaddr_in)
283 rffi.setintfield(a, 'c_sin_port', htons(port))
284 self.unlock()
285
286 def __repr__(self):
287 try:
288 return '<INETAddress %s:%d>' % (self.get_host(), self.get_port())
289 except SocketError:
290 return '<INETAddress ?>'
291
292 def get_port(self):
293 a = self.lock(_c.sockaddr_in)
294 port = ntohs(rffi.getintfield(a, 'c_sin_port'))
295 self.unlock()
296 return port
297
298 def eq(self, other): # __eq__() is not called by RPython :-/
299 return (isinstance(other, INETAddress) and
300 self.get_host() == other.get_host() and
301 self.get_port() == other.get_port())
302
303 def from_in_addr(in_addr):
304 result = instantiate(INETAddress)
305 # store the malloc'ed data into 'result' as soon as possible
306 # to avoid leaks if an exception occurs inbetween
307 sin = lltype.malloc(_c.sockaddr_in, flavor='raw', zero=True,
308 track_allocation=False)
309 result.setdata(sin, sizeof(_c.sockaddr_in))
310 # PLAT sin_len
311 rffi.setintfield(sin, 'c_sin_family', AF_INET)
312 rffi.structcopy(sin.c_sin_addr, in_addr)
313 return result
314 from_in_addr = staticmethod(from_in_addr)
315
316 def lock_in_addr(self):
317 a = self.lock(_c.sockaddr_in)
318 p = rffi.cast(rffi.VOIDP, a.c_sin_addr)
319 return p, sizeof(_c.in_addr)
320
321 # ____________________________________________________________
322
323 class INET6Address(IPAddress):
324 family = AF_INET6
325 struct = _c.sockaddr_in6
326 maxlen = minlen = sizeof(struct)
327
328 def __init__(self, host, port, flowinfo=0, scope_id=0):
329 makeipaddr(host, self)
330 a = self.lock(_c.sockaddr_in6)
331 rffi.setintfield(a, 'c_sin6_port', htons(port))
332 rffi.setintfield(a, 'c_sin6_flowinfo', htonl(flowinfo))
333 rffi.setintfield(a, 'c_sin6_scope_id', scope_id)
334 self.unlock()
335
336 def __repr__(self):
337 try:
338 return '<INET6Address %s:%d %d %d>' % (self.get_host(),
339 self.get_port(),
340 self.get_flowinfo(),
341 self.get_scope_id())
342 except SocketError:
343 return '<INET6Address ?>'
344
345 def get_port(self):
346 a = self.lock(_c.sockaddr_in6)
347 port = ntohs(rffi.getintfield(a, 'c_sin6_port'))
348 self.unlock()
349 return port
350
351 def get_flowinfo(self):
352 a = self.lock(_c.sockaddr_in6)
353 flowinfo = ntohl(a.c_sin6_flowinfo)
354 self.unlock()
355 return rffi.cast(lltype.Unsigned, flowinfo)
356
357 def get_scope_id(self):
358 a = self.lock(_c.sockaddr_in6)
359 scope_id = a.c_sin6_scope_id
360 self.unlock()
361 return rffi.cast(lltype.Unsigned, scope_id)
362
363 def eq(self, other): # __eq__() is not called by RPython :-/
364 return (isinstance(other, INET6Address) and
365 self.get_host() == other.get_host() and
366 self.get_port() == other.get_port() and
367 self.get_flowinfo() == other.get_flowinfo() and
368 self.get_scope_id() == other.get_scope_id())
369
370 def from_in6_addr(in6_addr):
371 result = instantiate(INET6Address)
372 # store the malloc'ed data into 'result' as soon as possible
373 # to avoid leaks if an exception occurs inbetween
374 sin = lltype.malloc(_c.sockaddr_in6, flavor='raw', zero=True,
375 track_allocation=False)
376 result.setdata(sin, sizeof(_c.sockaddr_in6))
377 rffi.setintfield(sin, 'c_sin6_family', AF_INET6)
378 rffi.structcopy(sin.c_sin6_addr, in6_addr)
379 return result
380 from_in6_addr = staticmethod(from_in6_addr)
381
382 def lock_in_addr(self):
383 a = self.lock(_c.sockaddr_in6)
384 p = rffi.cast(rffi.VOIDP, a.c_sin6_addr)
385 return p, sizeof(_c.in6_addr)
386
387 # ____________________________________________________________
388
389 HAS_AF_UNIX = 'AF_UNIX' in constants
390 if HAS_AF_UNIX:
391 class UNIXAddress(Address):
392 family = AF_UNIX
393 struct = _c.sockaddr_un
394 minlen = offsetof(_c.sockaddr_un, 'c_sun_path')
395 maxlen = sizeof(struct)
396
397 def __init__(self, path):
398 sun = lltype.malloc(_c.sockaddr_un, flavor='raw', zero=True,
399 track_allocation=False)
400 baseofs = offsetof(_c.sockaddr_un, 'c_sun_path')
401 self.setdata(sun, baseofs + len(path))
402 rffi.setintfield(sun, 'c_sun_family', AF_UNIX)
403 if _c.linux and path[0] == '\x00':
404 # Linux abstract namespace extension
405 if len(path) > sizeof(_c.sockaddr_un.c_sun_path):
406 raise RSocketError("AF_UNIX path too long")
407 else:
408 # regular NULL-terminated string
409 if len(path) >= sizeof(_c.sockaddr_un.c_sun_path):
410 raise RSocketError("AF_UNIX path too long")
411 sun.c_sun_path[len(path)] = '\x00'
412 for i in range(len(path)):
413 sun.c_sun_path[i] = path[i]
414
415 def __repr__(self):
416 try:
417 return '<UNIXAddress %r>' % (self.get_path(),)
418 except SocketError:
419 return '<UNIXAddress ?>'
420
421 def get_path(self):
422 a = self.lock(_c.sockaddr_un)
423 maxlength = self.addrlen - offsetof(_c.sockaddr_un, 'c_sun_path')
424 if _c.linux and maxlength > 0 and a.c_sun_path[0] == '\x00':
425 # Linux abstract namespace
426 length = maxlength
427 else:
428 # regular NULL-terminated string
429 length = 0
430 while length < maxlength and a.c_sun_path[length] != '\x00':
431 length += 1
432 result = ''.join([a.c_sun_path[i] for i in range(length)])
433 self.unlock()
434 return result
435
436 def eq(self, other): # __eq__() is not called by RPython :-/
437 return (isinstance(other, UNIXAddress) and
438 self.get_path() == other.get_path())
439
440 HAS_AF_NETLINK = 'AF_NETLINK' in constants
441 if HAS_AF_NETLINK:
442 class NETLINKAddress(Address):
443 family = AF_NETLINK
444 struct = _c.sockaddr_nl
445 maxlen = minlen = sizeof(struct)
446
447 def __init__(self, pid, groups):
448 addr = lltype.malloc(_c.sockaddr_nl, flavor='raw', zero=True,
449 track_allocation=False)
450 self.setdata(addr, NETLINKAddress.maxlen)
451 rffi.setintfield(addr, 'c_nl_family', AF_NETLINK)
452 rffi.setintfield(addr, 'c_nl_pid', pid)
453 rffi.setintfield(addr, 'c_nl_groups', groups)
454
455 def get_pid(self):
456 a = self.lock(_c.sockaddr_nl)
457 pid = a.c_nl_pid
458 self.unlock()
459 return rffi.cast(lltype.Unsigned, pid)
460
461 def get_groups(self):
462 a = self.lock(_c.sockaddr_nl)
463 groups = a.c_nl_groups
464 self.unlock()
465 return rffi.cast(lltype.Unsigned, groups)
466
467 def __repr__(self):
468 return '<NETLINKAddress %r %r>' % (self.get_pid(), self.get_groups())
469
470 # ____________________________________________________________
471
472 HAVE_SOCK_NONBLOCK = "SOCK_NONBLOCK" in constants
473 HAVE_SOCK_CLOEXEC = "SOCK_CLOEXEC" in constants
474
475 UNROLLING_FAMILIES = unrolling_iterable(_FAMILIES.items())
476 _FAMILIES = None
477
478 def instantiate_family(family):
479 for f, cls in UNROLLING_FAMILIES:
480 if widen(f) == widen(family):
481 return instantiate(cls)
482 return instantiate(Address)
483
484 def make_address(addrptr, addrlen, result=None):
485 family = rffi.cast(lltype.Signed, addrptr.c_sa_family)
486 if result is None:
487 result = instantiate_family(family)
488 elif result.family != family:
489 raise RSocketError("address family mismatched")
490 # copy into a new buffer the address that 'addrptr' points to
491 addrlen = rffi.cast(lltype.Signed, intmask(addrlen))
492 buf = lltype.malloc(rffi.CCHARP.TO, addrlen, flavor='raw',
493 track_allocation=False)
494 src = rffi.cast(rffi.CCHARP, addrptr)
495 for i in range(addrlen):
496 buf[i] = src[i]
497 result.setdata(buf, addrlen)
498 return result
499
500 def makeipv4addr(s_addr, result=None):
501 if result is None:
502 result = instantiate(INETAddress)
503 elif result.family != AF_INET:
504 raise RSocketError("address family mismatched")
505 sin = lltype.malloc(_c.sockaddr_in, flavor='raw', zero=True,
506 track_allocation=False)
507 result.setdata(sin, sizeof(_c.sockaddr_in))
508 rffi.setintfield(sin, 'c_sin_family', AF_INET) # PLAT sin_len
509 rffi.setintfield(sin.c_sin_addr, 'c_s_addr', s_addr)
510 return result
511
512 def make_null_address(family):
513 result = instantiate_family(family)
514 buf = lltype.malloc(rffi.CCHARP.TO, result.maxlen, flavor='raw', zero=True,
515 track_allocation=False)
516 # Initialize the family to the correct value. Avoids surprizes on
517 # Windows when calling a function that unexpectedly does not set
518 # the output address (e.g. recvfrom() on a connected IPv4 socket).
519 rffi.setintfield(rffi.cast(_c.sockaddr_ptr, buf), 'c_sa_family', family)
520 result.setdata(buf, 0)
521 return result, result.maxlen
522
523 # ____________________________________________________________
524
525 # On windows, _c.INVALID_SOCKET is unsigned
526 INVALID_SOCKET = rffi.cast(lltype.Signed, _c.INVALID_SOCKET)
527
528 class RSocket(object):
529 """RPython-level socket object.
530 """
531 fd = INVALID_SOCKET
532 family = 0
533 type = 0
534 proto = 0
535 timeout = -1.0
536
537 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0,
538 fd=_c.INVALID_SOCKET, inheritable=True):
539 """Create a new socket."""
540 if _c.invalid_socket(fd):
541 if not inheritable and HAVE_SOCK_CLOEXEC:
542 # Non-inheritable: we try to call socket() with
543 # SOCK_CLOEXEC, which may fail. If we get EINVAL,
544 # then we fall back to the SOCK_CLOEXEC-less case.
545 fd = _c.socket(family, type | SOCK_CLOEXEC, proto)
546 if widen(fd) < 0:
547 if _c.geterrno() == EINVAL:
548 # Linux older than 2.6.27 does not support
549 # SOCK_CLOEXEC. An EINVAL might be caused by
550 # random other things, though. Don't cache.
551 pass
552 else:
553 raise self.error_handler()
554 if _c.invalid_socket(fd):
555 fd = _c.socket(family, type, proto)
556 if _c.invalid_socket(fd):
557 raise self.error_handler()
558 if not inheritable:
559 sock_set_inheritable(fd, False)
560 # PLAT RISCOS
561 self.fd = rffi.cast(lltype.Signed, fd)
562 self.family = family
563 self.type = type
564 if HAVE_SOCK_CLOEXEC:
565 self.type &= ~SOCK_CLOEXEC
566 if HAVE_SOCK_NONBLOCK:
567 self.type &= ~SOCK_NONBLOCK
568 self.proto = proto
569 if HAVE_SOCK_NONBLOCK and type & SOCK_NONBLOCK:
570 self.timeout = 0.0
571 else:
572 self.settimeout(defaults.timeout)
573
574 @staticmethod
575 def empty_rsocket():
576 rsocket = instantiate(RSocket)
577 return rsocket
578
579 @rgc.must_be_light_finalizer
580 def __del__(self):
581 fd = self.fd
582 if widen(fd) != INVALID_SOCKET:
583 self.fd = INVALID_SOCKET
584 _c.socketclose_no_errno(fd)
585
586 if hasattr(_c, 'fcntl'):
587 def _setblocking(self, block):
588 orig_delay_flag = intmask(_c.fcntl(self.fd, _c.F_GETFL, 0))
589 if orig_delay_flag == -1:
590 raise self.error_handler()
591 if block:
592 delay_flag = orig_delay_flag & ~_c.O_NONBLOCK
593 else:
594 delay_flag = orig_delay_flag | _c.O_NONBLOCK
595 if orig_delay_flag != delay_flag:
596 if _c.fcntl(self.fd, _c.F_SETFL, delay_flag) == -1:
597 raise self.error_handler()
598 elif hasattr(_c, 'ioctlsocket'):
599 def _setblocking(self, block):
600 flag = lltype.malloc(rffi.ULONGP.TO, 1, flavor='raw')
601 flag[0] = rffi.cast(rffi.ULONG, not block)
602 try:
603 if _c.ioctlsocket(self.fd, _c.FIONBIO, flag) != 0:
604 raise self.error_handler()
605 finally:
606 lltype.free(flag, flavor='raw')
607
608 if hasattr(_c, 'poll') and not _c.poll_may_be_broken:
609 def _select(self, for_writing):
610 """Returns 0 when reading/writing is possible,
611 1 when timing out and -1 on error."""
612 if self.timeout <= 0.0 or widen(self.fd) == INVALID_SOCKET:
613 # blocking I/O or no socket.
614 return 0
615 pollfd = rffi.make(_c.pollfd)
616 try:
617 rffi.setintfield(pollfd, 'c_fd', self.fd)
618 if for_writing:
619 rffi.setintfield(pollfd, 'c_events', _c.POLLOUT)
620 else:
621 rffi.setintfield(pollfd, 'c_events', _c.POLLIN)
622 timeout = int(self.timeout * 1000.0 + 0.5)
623 n = _c.poll(rffi.cast(lltype.Ptr(_c.pollfdarray), pollfd),
624 1, timeout)
625 finally:
626 lltype.free(pollfd, flavor='raw')
627 if n < 0:
628 return -1
629 if n == 0:
630 return 1
631 return 0
632 else:
633 # Version witout poll(): use select()
634 def _select(self, for_writing):
635 """Returns 0 when reading/writing is possible,
636 1 when timing out and -1 on error."""
637 timeout = self.timeout
638 if timeout <= 0.0 or widen(self.fd) == INVALID_SOCKET:
639 # blocking I/O or no socket.
640 return 0
641 tv = rffi.make(_c.timeval)
642 rffi.setintfield(tv, 'c_tv_sec', int(timeout))
643 rffi.setintfield(tv, 'c_tv_usec',
644 int((timeout - int(timeout)) * 1000000))
645 fds = lltype.malloc(_c.fd_set.TO, flavor='raw')
646 _c.FD_ZERO(fds)
647 _c.FD_SET(self.fd, fds)
648 null = lltype.nullptr(_c.fd_set.TO)
649 fd1 = widen(self.fd) + 1
650 if for_writing:
651 n = _c.select(fd1, null, fds, null, tv)
652 else:
653 n = _c.select(fd1, fds, null, null, tv)
654 lltype.free(fds, flavor='raw')
655 lltype.free(tv, flavor='raw')
656 if n < 0:
657 return -1
658 if n == 0:
659 return 1
660 return 0
661
662 def error_handler(self):
663 return last_error()
664
665 # build a null address object, ready to be used as output argument to
666 # C functions that return an address. It must be unlock()ed after you
667 # are done using addr_p.
668 def _addrbuf(self):
669 addr, maxlen = make_null_address(self.family)
670 addrlen_p = lltype.malloc(_c.socklen_t_ptr.TO, flavor='raw')
671 addrlen_p[0] = rffi.cast(_c.socklen_t, maxlen)
672 return addr, addr.addr_p, addrlen_p
673
674 @jit.dont_look_inside
675 def accept(self, inheritable=True):
676 """Wait for an incoming connection.
677 Return (new socket fd, client address)."""
678 if self._select(False) == 1:
679 raise SocketTimeout
680 address, addr_p, addrlen_p = self._addrbuf()
681 try:
682 remove_inheritable = not inheritable
683 if (not inheritable and HAVE_SOCK_CLOEXEC and _c.HAVE_ACCEPT4
684 and _accept4_syscall.attempt_syscall()):
685 newfd = _c.socketaccept4(self.fd, addr_p, addrlen_p,
686 SOCK_CLOEXEC)
687 if _accept4_syscall.fallback(newfd):
688 newfd = _c.socketaccept(self.fd, addr_p, addrlen_p)
689 else:
690 remove_inheritable = False
691 else:
692 newfd = _c.socketaccept(self.fd, addr_p, addrlen_p)
693 addrlen = addrlen_p[0]
694 finally:
695 lltype.free(addrlen_p, flavor='raw')
696 address.unlock()
697 if _c.invalid_socket(newfd):
698 raise self.error_handler()
699 if remove_inheritable:
700 sock_set_inheritable(newfd, False)
701 address.addrlen = rffi.cast(lltype.Signed, intmask(addrlen))
702 if _c._WIN32:
703 newfd = rffi.cast(lltype.Signed, newfd)
704 return (newfd, address)
705
706 def bind(self, address):
707 """Bind the socket to a local address."""
708 addr = address.lock()
709 res = _c.socketbind(self.fd, addr, address.addrlen)
710 address.unlock()
711 if res < 0:
712 raise self.error_handler()
713
714 def close(self):
715 """Close the socket. It cannot be used after this call."""
716 fd = self.fd
717 if widen(fd) != INVALID_SOCKET:
718 self.fd = INVALID_SOCKET
719 res = _c.socketclose(fd)
720 if res != 0:
721 raise self.error_handler()
722
723 def __enter__(self):
724 return self
725
726 def __exit__(self, *args):
727 self.close()
728
729 def detach(self):
730 fd = self.fd
731 self.fd = INVALID_SOCKET
732 return fd
733
734 if _c.WIN32:
735 def _connect(self, address):
736 """Connect the socket to a remote address."""
737 addr = address.lock()
738 res = _c.socketconnect(self.fd, addr, address.addrlen)
739 address.unlock()
740 errno = _c.geterrno()
741 timeout = self.timeout
742 if (timeout > 0.0 and res < 0 and
743 errno in (_c.EWOULDBLOCK, _c.WSAEWOULDBLOCK)):
744 tv = rffi.make(_c.timeval)
745 rffi.setintfield(tv, 'c_tv_sec', int(timeout))
746 rffi.setintfield(tv, 'c_tv_usec',
747 int((timeout - int(timeout)) * 1000000))
748 fds = lltype.malloc(_c.fd_set.TO, flavor='raw')
749 _c.FD_ZERO(fds)
750 _c.FD_SET(self.fd, fds)
751 fds_exc = lltype.malloc(_c.fd_set.TO, flavor='raw')
752 _c.FD_ZERO(fds_exc)
753 _c.FD_SET(self.fd, fds_exc)
754 null = lltype.nullptr(_c.fd_set.TO)
755
756 try:
757 n = _c.select(self.fd + 1, null, fds, fds_exc, tv)
758
759 if n > 0:
760 if _c.FD_ISSET(self.fd, fds):
761 # socket writable == connected
762 return (0, False)
763 else:
764 # per MS docs, call getsockopt() to get error
765 assert _c.FD_ISSET(self.fd, fds_exc)
766 return (self.getsockopt_int(_c.SOL_SOCKET,
767 _c.SO_ERROR), False)
768 elif n == 0:
769 return (_c.WSAEWOULDBLOCK, True)
770 else:
771 return (_c.geterrno(), False)
772
773 finally:
774 lltype.free(fds, flavor='raw')
775 lltype.free(fds_exc, flavor='raw')
776 lltype.free(tv, flavor='raw')
777
778 if res == 0:
779 errno = 0
780 return (errno, False)
781 else:
782 def _connect(self, address):
783 """Connect the socket to a remote address."""
784 addr = address.lock()
785 res = _c.socketconnect(self.fd, addr, address.addrlen)
786 address.unlock()
787 errno = _c.geterrno()
788 if self.timeout > 0.0 and res < 0 and errno == _c.EINPROGRESS:
789 timeout = self._select(True)
790 if timeout == 0:
791 res = self.getsockopt_int(_c.SOL_SOCKET, _c.SO_ERROR)
792 if res == _c.EISCONN:
793 res = 0
794 errno = res
795 elif timeout == -1:
796 return (_c.geterrno(), False)
797 else:
798 return (_c.EWOULDBLOCK, True)
799
800 if res < 0:
801 res = errno
802 return (res, False)
803
804 def connect(self, address):
805 """Connect the socket to a remote address."""
806 err, timeout = self._connect(address)
807 if timeout:
808 raise SocketTimeout
809 if err:
810 raise CSocketError(err)
811
812 def connect_ex(self, address):
813 """This is like connect(address), but returns an error code (the errno
814 value) instead of raising an exception when an error occurs."""
815 err, timeout = self._connect(address)
816 return err
817
818 if hasattr(_c, 'dup'):
819 def dup(self, SocketClass=None):
820 if SocketClass is None:
821 SocketClass = RSocket
822 fd = rffi.cast(lltype.Signed, _c.dup(self.fd))
823 if fd < 0:
824 raise self.error_handler()
825 return make_socket(fd, self.family, self.type, self.proto,
826 SocketClass=SocketClass)
827
828 @jit.dont_look_inside
829 def getpeername(self):
830 """Return the address of the remote endpoint."""
831 address, addr_p, addrlen_p = self._addrbuf()
832 try:
833 res = _c.socketgetpeername(self.fd, addr_p, addrlen_p)
834 addrlen = addrlen_p[0]
835 finally:
836 lltype.free(addrlen_p, flavor='raw')
837 address.unlock()
838 if res < 0:
839 raise self.error_handler()
840 address.addrlen = rffi.cast(lltype.Signed, intmask(addrlen))
841 return address
842
843 @jit.dont_look_inside
844 def getsockname(self):
845 """Return the address of the local endpoint."""
846 address, addr_p, addrlen_p = self._addrbuf()
847 try:
848 res = _c.socketgetsockname(self.fd, addr_p, addrlen_p)
849 addrlen = addrlen_p[0]
850 finally:
851 lltype.free(addrlen_p, flavor='raw')
852 address.unlock()
853 if res < 0:
854 raise self.error_handler()
855 address.addrlen = rffi.cast(lltype.Signed, intmask(addrlen))
856 return address
857
858 @jit.dont_look_inside
859 def getsockopt(self, level, option, maxlen):
860 buf = mallocbuf(maxlen)
861 try:
862 bufsize_p = lltype.malloc(_c.socklen_t_ptr.TO, flavor='raw')
863 try:
864 bufsize_p[0] = rffi.cast(_c.socklen_t, maxlen)
865 res = _c.socketgetsockopt(self.fd, level, option,
866 buf, bufsize_p)
867 if res < 0:
868 raise self.error_handler()
869 size = rffi.cast(lltype.Signed, bufsize_p[0])
870 assert size >= 0 # socklen_t is signed on Windows
871 result = ''.join([buf[i] for i in range(size)])
872 finally:
873 lltype.free(bufsize_p, flavor='raw')
874 finally:
875 lltype.free(buf, flavor='raw')
876 return result
877
878 @jit.dont_look_inside
879 def getsockopt_int(self, level, option):
880 flag_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
881 # some win32 calls use only a byte to represent a bool
882 # zero out so the result is correct anyway
883 flag_p[0] = rffi.cast(rffi.INT, 0)
884 try:
885 flagsize_p = lltype.malloc(_c.socklen_t_ptr.TO, flavor='raw')
886 try:
887 flagsize_p[0] = rffi.cast(_c.socklen_t, rffi.sizeof(rffi.INT))
888 res = _c.socketgetsockopt(self.fd, level, option,
889 rffi.cast(rffi.VOIDP, flag_p),
890 flagsize_p)
891 if res < 0:
892 raise self.error_handler()
893 result = rffi.cast(lltype.Signed, flag_p[0])
894 finally:
895 lltype.free(flagsize_p, flavor='raw')
896 finally:
897 lltype.free(flag_p, flavor='raw')
898 return result
899
900 def gettimeout(self):
901 """Return the timeout of the socket. A timeout < 0 means that
902 timeouts are disabled in the socket."""
903 return self.timeout
904
905 def listen(self, backlog):
906 """Enable a server to accept connections. The backlog argument
907 must be at least 1; it specifies the number of unaccepted connections
908 that the system will allow before refusing new connections."""
909 if backlog < 1:
910 backlog = 1
911 res = _c.socketlisten(self.fd, backlog)
912 if res < 0:
913 raise self.error_handler()
914
915 def wait_for_data(self, for_writing):
916 timeout = self._select(for_writing)
917 if timeout != 0:
918 if timeout == 1:
919 raise SocketTimeout
920 else:
921 raise self.error_handler()
922
923 def recv(self, buffersize, flags=0):
924 """Receive up to buffersize bytes from the socket. For the optional
925 flags argument, see the Unix manual. When no data is available, block
926 until at least one byte is available or until the remote end is closed.
927 When the remote end is closed and all data is read, return the empty
928 string."""
929 with rffi.scoped_alloc_buffer(buffersize) as buf:
930 llbuf = LLBuffer(buf.raw, buffersize)
931 read_bytes = self.recvinto(llbuf, buffersize, flags)
932 if _c.linux and flags & _c.MSG_TRUNC and read_bytes > buffersize:
933 # on linux, if MSG_TRUNC is given, read_bytes is the size of
934 # the packet, not the amounts of bytes written into buf
935 read_bytes = buffersize
936 return buf.str(read_bytes)
937
938 def recvinto(self, rwbuffer, nbytes, flags=0):
939 self.wait_for_data(False)
940 raw = rwbuffer.get_raw_address()
941 read_bytes = _c.socketrecv(self.fd, raw, nbytes, flags)
942 keepalive_until_here(rwbuffer)
943 if read_bytes >= 0:
944 return read_bytes
945 raise self.error_handler()
946
947 @jit.dont_look_inside
948 def recvfrom(self, buffersize, flags=0):
949 """Like recv(buffersize, flags) but also return the sender's
950 address."""
951 with rffi.scoped_alloc_buffer(buffersize) as buf:
952 llbuf = LLBuffer(buf.raw, buffersize)
953 read_bytes, address = self.recvfrom_into(llbuf, buffersize, flags)
954 return buf.str(read_bytes), address
955
956 def recvfrom_into(self, rwbuffer, nbytes, flags=0):
957 self.wait_for_data(False)
958 address, addr_p, addrlen_p = self._addrbuf()
959 try:
960 raw = rwbuffer.get_raw_address()
961 read_bytes = _c.recvfrom(self.fd, raw, nbytes, flags,
962 addr_p, addrlen_p)
963 keepalive_until_here(rwbuffer)
964 addrlen = rffi.cast(lltype.Signed, addrlen_p[0])
965 finally:
966 lltype.free(addrlen_p, flavor='raw')
967 address.unlock()
968 if read_bytes >= 0:
969 if addrlen:
970 address.addrlen = addrlen
971 else:
972 address = None
973 return (read_bytes, address)
974 raise self.error_handler()
975
976 def recvmsg(self, message_size, ancbufsize=0, flags=0):
977 """
978 Receive up to message_size bytes from a message. Also receives ancillary data.
979 Returns the message, ancillary, flag and address of the sender.
980
981 :param message_size: Maximum size of the message to be received
982 :param ancbufsize: Maximum size of the ancillary data to be received
983 :param flags: Receive flag. For more details, please check the Unix manual
984 :return: a tuple consisting of the message, the ancillary data, return flag and the address.
985 """
986 if message_size < 0:
987 raise RSocketError("Invalid message size")
988 with rffi.scoped_alloc_buffer(message_size) as buf:
989 llbuf = LLBuffer(buf.raw, message_size)
990 nbytes, ancdata, flags, address = self.recvmsg_into(
991 [llbuf], ancbufsize, flags)
992 return buf.str(nbytes), ancdata, flags, address
993
994 @jit.dont_look_inside
995 def recvmsg_into(self, buffers, ancbufsize=0, flags=0):
996 if ancbufsize < 0:
997 raise RSocketError("invalid ancillary data buffer length")
998
999 self.wait_for_data(False)
1000 nbuf = len(buffers)
1001 address, addr_p, addrlen_p = self._addrbuf()
1002 message_lengths = lltype.malloc(rffi.INT_realP.TO, nbuf, flavor='raw')
1003 messages = lltype.malloc(rffi.CCHARPP.TO, nbuf, flavor='raw')
1004 for i in range(nbuf):
1005 message_lengths[i] = rffi.cast(rffi.INT_real, buffers[i].getlength())
1006 messages[i] = buffers[i].get_raw_address()
1007 size_of_anc = lltype.malloc(rffi.SIGNEDP.TO, 1, flavor='raw')
1008 size_of_anc[0] = rffi.cast(rffi.SIGNED, 0)
1009 levels = lltype.malloc(rffi.SIGNEDPP.TO, 1, flavor='raw')
1010 types = lltype.malloc(rffi.SIGNEDPP.TO, 1, flavor='raw')
1011 file_descr = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
1012 descr_per_anc = lltype.malloc(rffi.SIGNEDPP.TO, 1, flavor='raw')
1013 retflag = lltype.malloc(rffi.SIGNEDP.TO, 1, flavor='raw')
1014 retflag[0] = rffi.cast(rffi.SIGNED, 0)
1015
1016 # a mask for the SIGNEDP's that need to be cast to int. (long default)
1017 reply = _c.recvmsg(
1018 self.fd,
1019 rffi.cast(lltype.Signed, ancbufsize),
1020 rffi.cast(lltype.Signed, flags),
1021 addr_p, addrlen_p,
1022 message_lengths, messages, rffi.cast(rffi.INT, nbuf),
1023 size_of_anc, levels, types, file_descr, descr_per_anc, retflag)
1024 if reply >= 0:
1025 anc_size = rffi.cast(rffi.SIGNED, size_of_anc[0])
1026 returnflag = rffi.cast(rffi.SIGNED, retflag[0])
1027 addrlen = rffi.cast(rffi.SIGNED, addrlen_p[0])
1028 offset = 0
1029 list_of_tuples = []
1030
1031 pre_anc = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
1032 for i in range(anc_size):
1033 level = rffi.cast(rffi.SIGNED, levels[0][i])
1034 type = rffi.cast(rffi.SIGNED, types[0][i])
1035 bytes_in_anc = rffi.cast(rffi.SIGNED, descr_per_anc[0][i])
1036 pre_anc[0] = lltype.malloc(
1037 rffi.CCHARP.TO, bytes_in_anc, flavor='raw')
1038 _c.memcpy_from_CCHARP_at_offset(
1039 file_descr[0], pre_anc, rffi.cast(rffi.SIGNED, offset),
1040 bytes_in_anc)
1041 anc = rffi.charpsize2str(pre_anc[0], bytes_in_anc)
1042 tup = (level, type, anc)
1043 list_of_tuples.append(tup)
1044 offset += bytes_in_anc
1045 lltype.free(pre_anc[0], flavor='raw')
1046
1047 if addrlen:
1048 address.addrlen = addrlen
1049 else:
1050 address.unlock()
1051 address = None
1052
1053 rettup = (reply, list_of_tuples, returnflag, address)
1054
1055 if address is not None:
1056 address.unlock()
1057 # free underlying complexity first
1058 _c.freeccharp(file_descr)
1059 _c.freesignedp(levels)
1060 _c.freesignedp(types)
1061 _c.freesignedp(descr_per_anc)
1062
1063 lltype.free(pre_anc, flavor='raw')
1064 lltype.free(message_lengths, flavor='raw')
1065 lltype.free(messages, flavor='raw')
1066 lltype.free(file_descr, flavor='raw')
1067 lltype.free(size_of_anc, flavor='raw')
1068 lltype.free(levels, flavor='raw')
1069 lltype.free(types, flavor='raw')
1070 lltype.free(descr_per_anc, flavor='raw')
1071 lltype.free(retflag, flavor='raw')
1072 lltype.free(addrlen_p, flavor='raw')
1073
1074 return rettup
1075 else:
1076 # in case of failure the underlying complexity has already been freed
1077 lltype.free(message_lengths, flavor='raw')
1078 lltype.free(messages, flavor='raw')
1079 lltype.free(file_descr, flavor='raw')
1080 lltype.free(size_of_anc, flavor='raw')
1081 lltype.free(levels, flavor='raw')
1082 lltype.free(types, flavor='raw')
1083 lltype.free(descr_per_anc, flavor='raw')
1084 lltype.free(retflag, flavor='raw')
1085 lltype.free(addrlen_p, flavor='raw')
1086
1087 if address is not None:
1088 address.unlock()
1089 if (_c.geterrno() == _c.EINTR) or (_c.geterrno() == 11):
1090 raise last_error()
1091 if (reply == -10000):
1092 raise RSocketError("Invalid message size")
1093 if (reply == -10001):
1094 raise RSocketError("Invalid ancillary data buffer length")
1095 if (reply == -10002):
1096 raise RSocketError(
1097 "received malformed or improperly truncated "
1098 "ancillary data")
1099 raise last_error()
1100
1101 def send_raw(self, dataptr, length, flags=0):
1102 """Send data from a CCHARP buffer."""
1103 self.wait_for_data(True)
1104 res = _c.send(self.fd, dataptr, length, flags)
1105 if res < 0:
1106 raise self.error_handler()
1107 return res
1108
1109 def send(self, data, flags=0):
1110 """Send a data string to the socket. For the optional flags
1111 argument, see the Unix manual. Return the number of bytes
1112 sent; this may be less than len(data) if the network is busy."""
1113 with rffi.scoped_nonmovingbuffer(data) as dataptr:
1114 return self.send_raw(dataptr, len(data), flags)
1115
1116 def sendall(self, data, flags=0, signal_checker=None):
1117 """Send a data string to the socket. For the optional flags
1118 argument, see the Unix manual. This calls send() repeatedly
1119 until all data is sent. If an error occurs, it's impossible
1120 to tell how much data has been sent."""
1121 with rffi.scoped_nonmovingbuffer(data) as dataptr:
1122 remaining = len(data)
1123 p = dataptr
1124 while remaining > 0:
1125 try:
1126 res = self.send_raw(p, remaining, flags)
1127 p = rffi.ptradd(p, res)
1128 remaining -= res
1129 except CSocketError as e:
1130 if e.errno != _c.EINTR:
1131 raise
1132 if signal_checker is not None:
1133 signal_checker()
1134
1135 def sendto(self, data, length, flags, address):
1136 """Like send(data, flags) but allows specifying the destination
1137 address. (Note that 'flags' is mandatory here.)"""
1138 self.wait_for_data(True)
1139 addr = address.lock()
1140 res = _c.sendto(self.fd, data, length, flags,
1141 addr, address.addrlen)
1142 address.unlock()
1143 if res < 0:
1144 raise self.error_handler()
1145 return res
1146
1147 @jit.dont_look_inside
1148 def sendmsg(self, messages, ancillary=None, flags=0, address=None):
1149 """
1150 Send data and ancillary on a socket. For use of ancillary data, please check the Unix manual.
1151 Work on connectionless sockets via the address parameter.
1152 :param messages: a message that is a list of strings
1153 :param ancillary: data to be sent separate from the message body. Needs to be a list of tuples.
1154 E.g. [(level,type, bytes),...]. Default None.
1155 :param flags: the flag to be set for sendmsg. Please check the Unix manual regarding values. Default 0
1156 :param address: address of the recepient. Useful for when sending on connectionless sockets. Default None
1157 :return: Bytes sent from the message
1158 """
1159 need_to_free_address = True
1160 if address is None:
1161 need_to_free_address = False
1162 addr = lltype.nullptr(_c.sockaddr)
1163 addrlen = 0
1164 else:
1165 addr = address.lock()
1166 addrlen = address.addrlen
1167
1168 no_of_messages = len(messages)
1169 messages_ptr = lltype.malloc(
1170 rffi.CCHARPP.TO, no_of_messages + 1, flavor='raw')
1171 messages_length_ptr = lltype.malloc(
1172 rffi.SIGNEDP.TO, no_of_messages, flavor='raw', zero=True)
1173 counter = 0
1174 for message in messages:
1175 messages_ptr[counter] = rffi.str2charp(message)
1176 messages_length_ptr[counter] = rffi.cast(rffi.SIGNED, len(message))
1177 counter += 1
1178 messages_ptr[counter] = lltype.nullptr(rffi.CCHARP.TO)
1179 if ancillary is not None:
1180 size_of_ancillary = len(ancillary)
1181 else:
1182 size_of_ancillary = 0
1183 levels = lltype.malloc(
1184 rffi.SIGNEDP.TO, size_of_ancillary, flavor='raw', zero=True)
1185 types = lltype.malloc(
1186 rffi.SIGNEDP.TO, size_of_ancillary, flavor='raw', zero=True)
1187 desc_per_ancillary = lltype.malloc(
1188 rffi.SIGNEDP.TO, size_of_ancillary, flavor='raw', zero=True)
1189 file_descr = lltype.malloc(
1190 rffi.CCHARPP.TO, size_of_ancillary, flavor='raw')
1191 if ancillary is not None:
1192 counter = 0
1193 for level, type, content in ancillary:
1194 assert isinstance(type, int)
1195 assert isinstance(level, int)
1196 levels[counter] = rffi.cast(rffi.SIGNED, level)
1197 types[counter] = rffi.cast(rffi.SIGNED, type)
1198 desc_per_ancillary[counter] = rffi.cast(
1199 rffi.SIGNED, (len(content)))
1200 file_descr[counter] = rffi.str2charp(
1201 content, track_allocation=True)
1202 counter += 1
1203 else:
1204 size_of_ancillary = 0
1205 snd_no_msgs = rffi.cast(rffi.SIGNED, no_of_messages)
1206 snd_anc_size = rffi.cast(rffi.SIGNED, size_of_ancillary)
1207
1208 bytes_sent = _c.sendmsg(
1209 self.fd, addr, addrlen, messages_length_ptr, messages_ptr,
1210 snd_no_msgs, levels, types, file_descr,
1211 desc_per_ancillary, snd_anc_size, flags)
1212
1213 if need_to_free_address:
1214 address.unlock()
1215 for i in range(len(messages)):
1216 lltype.free(messages_ptr[i], flavor='raw')
1217 lltype.free(messages_ptr, flavor='raw')
1218 lltype.free(messages_length_ptr, flavor='raw')
1219
1220 if size_of_ancillary > 0:
1221 for i in range(len(ancillary)):
1222 lltype.free(file_descr[i], flavor='raw')
1223 lltype.free(desc_per_ancillary, flavor='raw')
1224 lltype.free(types, flavor='raw')
1225 lltype.free(levels, flavor='raw')
1226 lltype.free(file_descr, flavor='raw')
1227
1228 self.wait_for_data(True)
1229 if ((bytes_sent < 0) and (bytes_sent != -1000) and
1230 (bytes_sent != -1001) and (bytes_sent != -1002)):
1231 raise last_error()
1232
1233 return bytes_sent
1234
1235 def setblocking(self, block):
1236 if block:
1237 timeout = -1.0
1238 else:
1239 timeout = 0.0
1240 self.settimeout(timeout)
1241
1242 def setsockopt(self, level, option, value):
1243 with rffi.scoped_str2charp(value) as buf:
1244 res = _c.socketsetsockopt(self.fd, level, option,
1245 rffi.cast(rffi.VOIDP, buf),
1246 len(value))
1247 if res < 0:
1248 raise self.error_handler()
1249
1250 def setsockopt_int(self, level, option, value):
1251 with lltype.scoped_alloc(rffi.INTP.TO, 1) as flag_p:
1252 flag_p[0] = rffi.cast(rffi.INT, value)
1253 res = _c.socketsetsockopt(self.fd, level, option,
1254 rffi.cast(rffi.VOIDP, flag_p),
1255 rffi.sizeof(rffi.INT))
1256 if res < 0:
1257 raise self.error_handler()
1258
1259 def settimeout(self, timeout):
1260 """Set the timeout of the socket. A timeout < 0 means that
1261 timeouts are dissabled in the socket."""
1262 if timeout < 0.0:
1263 self.timeout = -1.0
1264 else:
1265 self.timeout = timeout
1266 self._setblocking(self.timeout < 0.0)
1267
1268 def shutdown(self, how):
1269 """Shut down the reading side of the socket (flag == SHUT_RD), the
1270 writing side of the socket (flag == SHUT_WR), or both ends
1271 (flag == SHUT_RDWR)."""
1272 res = _c.socketshutdown(self.fd, how)
1273 if res < 0:
1274 raise self.error_handler()
1275
1276 # ____________________________________________________________
1277
1278 @specialize.arg(4)
1279 def make_socket(fd, family, type, proto, SocketClass=RSocket):
1280 result = instantiate(SocketClass)
1281 result.fd = fd
1282 result.family = family
1283 result.type = type
1284 result.proto = proto
1285 result.timeout = defaults.timeout
1286 return result
1287
1288 if _c.WIN32:
1289 def sock_set_inheritable(fd, inheritable):
1290 handle = rffi.cast(rwin32.HANDLE, fd)
1291 try:
1292 rwin32.set_handle_inheritable(handle, inheritable)
1293 except WindowsError:
1294 raise RSocketError("SetHandleInformation failed") # xxx
1295
1296 def sock_get_inheritable(fd):
1297 handle = rffi.cast(rwin32.HANDLE, fd)
1298 try:
1299 return rwin32.get_handle_inheritable(handle)
1300 except WindowsError:
1301 raise RSocketError("GetHandleInformation failed") # xxx
1302 else:
1303 def sock_set_inheritable(fd, inheritable):
1304 try:
1305 rposix.set_inheritable(fd, inheritable)
1306 except OSError as e:
1307 raise CSocketError(e.errno)
1308
1309 def sock_get_inheritable(fd):
1310 try:
1311 return rposix.get_inheritable(fd)
1312 except OSError as e:
1313 raise CSocketError(e.errno)
1314
1315 class SocketError(Exception):
1316 applevelerrcls = 'error'
1317
1318 def __init__(self):
1319 pass
1320
1321 def get_msg(self):
1322 return ''
1323
1324 def get_msg_unicode(self):
1325 return self.get_msg().decode('latin-1')
1326
1327 def get_msg_utf8(self):
1328 msg = self.get_msg()
1329 return msg, len(msg)
1330
1331 def __str__(self):
1332 return self.get_msg()
1333
1334 class SocketErrorWithErrno(SocketError):
1335 def __init__(self, errno):
1336 self.errno = errno
1337
1338 class RSocketError(SocketError):
1339 def __init__(self, message):
1340 self.message = message
1341
1342 def get_msg(self):
1343 return self.message
1344
1345 class CSocketError(SocketErrorWithErrno):
1346 def get_msg(self):
1347 return _c.socket_strerror_str(self.errno)
1348
1349 def get_msg_unicode(self):
1350 return _c.socket_strerror_unicode(self.errno)
1351
1352 def get_msg_utf8(self):
1353 return _c.socket_strerror_utf8(self.errno)
1354
1355
1356 def last_error():
1357 return CSocketError(_c.geterrno())
1358
1359 class GAIError(SocketErrorWithErrno):
1360 applevelerrcls = 'gaierror'
1361
1362 def get_msg(self):
1363 return _c.gai_strerror_str(self.errno)
1364
1365 def get_msg_unicode(self):
1366 return _c.gai_strerror_unicode(self.errno)
1367
1368 def get_msg_utf8(self):
1369 return _c.gai_strerror_utf8(self.errno)
1370
1371 class HSocketError(SocketError):
1372 applevelerrcls = 'herror'
1373
1374 def __init__(self, host):
1375 self.host = host
1376 # XXX h_errno is not easily available, and hstrerror() is
1377 # marked as deprecated in the Linux man pages
1378
1379 def get_msg(self):
1380 return "host lookup failed: '%s'" % (self.host,)
1381
1382 class SocketTimeout(SocketError):
1383 applevelerrcls = 'timeout'
1384 def get_msg(self):
1385 return 'timed out'
1386
1387 class Defaults:
1388 timeout = -1.0 # Blocking
1389 defaults = Defaults()
1390
1391
1392 # ____________________________________________________________
1393 if 'AF_UNIX' not in constants or AF_UNIX is None:
1394 socketpair_default_family = AF_INET
1395 else:
1396 socketpair_default_family = AF_UNIX
1397
1398 if hasattr(_c, 'socketpair'):
1399 def socketpair(family=socketpair_default_family, type=SOCK_STREAM, proto=0,
1400 SocketClass=RSocket, inheritable=True):
1401 """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
1402
1403 Create a pair of socket objects from the sockets returned by the platform
1404 socketpair() function.
1405 The arguments are the same as for socket() except the default family is
1406 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
1407 """
1408 result = lltype.malloc(_c.socketpair_t, 2, flavor='raw')
1409 try:
1410 res = -1
1411 remove_inheritable = not inheritable
1412 if not inheritable and HAVE_SOCK_CLOEXEC:
1413 # Non-inheritable: we try to call socketpair() with
1414 # SOCK_CLOEXEC, which may fail. If we get EINVAL,
1415 # then we fall back to the SOCK_CLOEXEC-less case.
1416 res = _c.socketpair(family, type | SOCK_CLOEXEC,
1417 proto, result)
1418 if res < 0:
1419 if _c.geterrno() == EINVAL:
1420 # Linux older than 2.6.27 does not support
1421 # SOCK_CLOEXEC. An EINVAL might be caused by
1422 # random other things, though. Don't cache.
1423 pass
1424 else:
1425 raise last_error()
1426 else:
1427 remove_inheritable = False
1428 #
1429 if res < 0:
1430 res = _c.socketpair(family, type, proto, result)
1431 if res < 0:
1432 raise last_error()
1433 fd0 = rffi.cast(lltype.Signed, result[0])
1434 fd1 = rffi.cast(lltype.Signed, result[1])
1435 finally:
1436 lltype.free(result, flavor='raw')
1437 if remove_inheritable:
1438 sock_set_inheritable(fd0, False)
1439 sock_set_inheritable(fd1, False)
1440 return (make_socket(fd0, family, type, proto, SocketClass),
1441 make_socket(fd1, family, type, proto, SocketClass))
1442
1443 if _c.HAVE_SENDMSG:
1444 def CMSG_LEN(demanded_len):
1445 """
1446 Socket method to determine the optimal byte size of the ancillary.
1447 Recommended to be used when computing the ancillary size for recvmsg.
1448 :param demanded_len: an integer with the minimum size required.
1449 :return: an integer with the minimum memory needed for the required size. The value is not memory aligned
1450 """
1451 if demanded_len < 0:
1452 return 0
1453 result = _c.CMSG_LEN(demanded_len)
1454 return result
1455
1456 def CMSG_SPACE(demanded_size):
1457 """
1458 Socket method to determine the optimal byte size of the ancillary.
1459 Recommended to be used when computing the ancillary size for recvmsg.
1460 :param demanded_size: an integer with the minimum size required.
1461 :return: an integer with the minimum memory needed for the required size. The value is memory aligned
1462 """
1463 if demanded_size < 0:
1464 return 0
1465 result = _c.CMSG_SPACE(demanded_size)
1466 return result
1467
1468 if _c.WIN32:
1469 def dup(fd, inheritable=True):
1470 with lltype.scoped_alloc(_c.WSAPROTOCOL_INFO, zero=True) as info:
1471 if _c.WSADuplicateSocket(fd, rwin32.GetCurrentProcessId(), info):
1472 raise last_error()
1473 result = _c.WSASocket(
1474 _c.FROM_PROTOCOL_INFO, _c.FROM_PROTOCOL_INFO,
1475 _c.FROM_PROTOCOL_INFO, info, 0, 0)
1476 result = rffi.cast(lltype.Signed, result)
1477 if result == INVALID_SOCKET:
1478 raise last_error()
1479 return result
1480 else:
1481 def dup(fd, inheritable=True):
1482 fd = rposix._dup(fd, inheritable)
1483 if fd < 0:
1484 raise last_error()
1485 return fd
1486
1487 def fromfd(fd, family, type, proto=0, SocketClass=RSocket, inheritable=True):
1488 # Dup the fd so it and the socket can be closed independently
1489 fd = dup(fd, inheritable=inheritable)
1490 return make_socket(fd, family, type, proto, SocketClass)
1491
1492 def getdefaulttimeout():
1493 return defaults.timeout
1494
1495 def gethostname():
1496 size = 1024
1497 buf = lltype.malloc(rffi.CCHARP.TO, size, flavor='raw')
1498 try:
1499 res = _c.gethostname(buf, size)
1500 if res < 0:
1501 raise last_error()
1502 return rffi.charp2strn(buf, size)
1503 finally:
1504 lltype.free(buf, flavor='raw')
1505
1506 def gethostbyname(name):
1507 # this is explicitly not working with IPv6, because the docs say it
1508 # should not. Just use makeipaddr(name) for an IPv6-friendly version...
1509 result = instantiate(INETAddress)
1510 makeipaddr(name, result)
1511 return result
1512
1513 def gethost_common(hostname, hostent, addr=None):
1514 if not hostent:
1515 raise HSocketError(hostname)
1516 family = rffi.getintfield(hostent, 'c_h_addrtype')
1517 if addr is not None and addr.family != family:
1518 raise CSocketError(_c.EAFNOSUPPORT)
1519
1520 h_aliases = hostent.c_h_aliases
1521 if h_aliases: # h_aliases can be NULL, according to SF #1511317
1522 aliases = rffi.charpp2liststr(h_aliases)
1523 else:
1524 aliases = []
1525
1526 address_list = []
1527 h_addr_list = hostent.c_h_addr_list
1528 i = 0
1529 paddr = h_addr_list[0]
1530 while paddr:
1531 if family == AF_INET:
1532 p = rffi.cast(lltype.Ptr(_c.in_addr), paddr)
1533 addr = INETAddress.from_in_addr(p)
1534 elif AF_INET6 is not None and family == AF_INET6:
1535 p = rffi.cast(lltype.Ptr(_c.in6_addr), paddr)
1536 addr = INET6Address.from_in6_addr(p)
1537 else:
1538 raise RSocketError("unknown address family")
1539 address_list.append(addr)
1540 i += 1
1541 paddr = h_addr_list[i]
1542 return (rffi.charp2str(hostent.c_h_name), aliases, address_list)
1543
1544 def gethostbyname_ex(name):
1545 # XXX use gethostbyname_r() if available instead of locks
1546 addr = gethostbyname(name)
1547 with _get_netdb_lock():
1548 hostent = _c.gethostbyname(name)
1549 return gethost_common(name, hostent, addr)
1550
1551 def gethostbyaddr(ip):
1552 # XXX use gethostbyaddr_r() if available, instead of locks
1553 addr = makeipaddr(ip)
1554 assert isinstance(addr, IPAddress)
1555 with _get_netdb_lock():
1556 p, size = addr.lock_in_addr()
1557 try:
1558 hostent = _c.gethostbyaddr(p, size, addr.family)
1559 finally:
1560 addr.unlock()
1561 return gethost_common(ip, hostent, addr)
1562
1563 # RPython magic to make _netdb_lock turn either into a regular
1564 # rthread.Lock or a rthread.DummyLock, depending on the config
1565 def _get_netdb_lock():
1566 return rthread.dummy_lock
1567
1568 class _Entry(ExtRegistryEntry):
1569 _about_ = _get_netdb_lock
1570
1571 def compute_annotation(self):
1572 config = self.bookkeeper.annotator.translator.config
1573 if config.translation.thread:
1574 fn = _get_netdb_lock_thread
1575 else:
1576 fn = _get_netdb_lock_nothread
1577 return self.bookkeeper.immutablevalue(fn)
1578
1579 def _get_netdb_lock_nothread():
1580 return rthread.dummy_lock
1581
1582 class _LockCache(object):
1583 lock = None
1584 _lock_cache = _LockCache()
1585
1586 @jit.elidable
1587 def _get_netdb_lock_thread():
1588 if _lock_cache.lock is None:
1589 _lock_cache.lock = rthread.allocate_lock()
1590 return _lock_cache.lock
1591 # done RPython magic
1592
1593 def getaddrinfo(host, port_or_service,
1594 family=AF_UNSPEC, socktype=0, proto=0, flags=0,
1595 address_to_fill=None):
1596 # port_or_service is a string, not an int (but try str(port_number)).
1597 assert port_or_service is None or isinstance(port_or_service, str)
1598 if _c._MACOSX and flags & AI_NUMERICSERV and \
1599 (port_or_service is None or port_or_service == '0'):
1600 port_or_service = '00'
1601 hints = lltype.malloc(_c.addrinfo, flavor='raw', zero=True)
1602 rffi.setintfield(hints, 'c_ai_family', family)
1603 rffi.setintfield(hints, 'c_ai_socktype', socktype)
1604 rffi.setintfield(hints, 'c_ai_protocol', proto)
1605 rffi.setintfield(hints, 'c_ai_flags', flags)
1606 # XXX need to lock around getaddrinfo() calls?
1607 p_res = lltype.malloc(rffi.CArray(_c.addrinfo_ptr), 1, flavor='raw')
1608 error = intmask(_c.getaddrinfo(host, port_or_service, hints, p_res))
1609 res = p_res[0]
1610 lltype.free(p_res, flavor='raw')
1611 lltype.free(hints, flavor='raw')
1612 if error:
1613 raise GAIError(error)
1614 try:
1615 result = []
1616 info = res
1617 while info:
1618 addr = make_address(info.c_ai_addr,
1619 rffi.getintfield(info, 'c_ai_addrlen'),
1620 address_to_fill)
1621 if info.c_ai_canonname:
1622 canonname = rffi.charp2str(info.c_ai_canonname)
1623 else:
1624 canonname = ""
1625 result.append((rffi.cast(lltype.Signed, info.c_ai_family),
1626 rffi.cast(lltype.Signed, info.c_ai_socktype),
1627 rffi.cast(lltype.Signed, info.c_ai_protocol),
1628 canonname,
1629 addr))
1630 info = info.c_ai_next
1631 address_to_fill = None # don't fill the same address repeatedly
1632 finally:
1633 _c.freeaddrinfo(res)
1634 return result
1635
1636 def getservbyname(name, proto=None):
1637 servent = _c.getservbyname(name, proto)
1638 if not servent:
1639 raise RSocketError("service/proto not found")
1640 port = rffi.getintfield(servent, 'c_s_port')
1641 return ntohs(port)
1642
1643 def getservbyport(port, proto=None):
1644 # This function is only called from pypy/module/_socket and the range of
1645 # port is checked there
1646 assert isinstance(port, int)
1647 servent = _c.getservbyport(htons(port), proto)
1648 if not servent:
1649 raise RSocketError("port/proto not found")
1650 return rffi.charp2str(servent.c_s_name)
1651
1652 def getprotobyname(name):
1653 protoent = _c.getprotobyname(name)
1654 if not protoent:
1655 raise RSocketError("protocol not found")
1656 proto = protoent.c_p_proto
1657 return rffi.cast(lltype.Signed, proto)
1658
1659 def getnameinfo(address, flags):
1660 host = lltype.malloc(rffi.CCHARP.TO, NI_MAXHOST, flavor='raw')
1661 try:
1662 serv = lltype.malloc(rffi.CCHARP.TO, NI_MAXSERV, flavor='raw')
1663 try:
1664 addr = address.lock()
1665 error = intmask(_c.getnameinfo(addr, address.addrlen,
1666 host, NI_MAXHOST,
1667 serv, NI_MAXSERV, flags))
1668 address.unlock()
1669 if error:
1670 raise GAIError(error)
1671 return rffi.charp2str(host), rffi.charp2str(serv)
1672 finally:
1673 lltype.free(serv, flavor='raw')
1674 finally:
1675 lltype.free(host, flavor='raw')
1676
1677 @jit.dont_look_inside
1678 def getsockopt_int(fd, level, option):
1679 # XXX almost the same code as RSocket.getsockopt_int
1680 # some win32 calls use only a byte to represent a bool
1681 # zero out so the result is correct anyway
1682 with lltype.scoped_alloc(rffi.INTP.TO, n=1, zero=True) as flag_p, \
1683 lltype.scoped_alloc(_c.socklen_t_ptr.TO) as flagsize_p:
1684 flagsize_p[0] = rffi.cast(_c.socklen_t, rffi.sizeof(rffi.INT))
1685 res = _c.socketgetsockopt(fd, level, option,
1686 rffi.cast(rffi.VOIDP, flag_p),
1687 flagsize_p)
1688 if res < 0:
1689 raise last_error()
1690 result = rffi.cast(lltype.Signed, flag_p[0])
1691 return result
1692
1693 @jit.dont_look_inside
1694 def get_socket_family(fd):
1695 """Return the family of a file descriptor."""
1696 with lltype.scoped_alloc(_c.sockaddr, zero=True) as addr_p, \
1697 lltype.scoped_alloc(_c.socklen_t_ptr.TO) as addrlen_p:
1698 addrlen_p[0] = rffi.cast(_c.socklen_t, sizeof(_c.sockaddr))
1699 res = _c.socketgetsockname(fd, addr_p, addrlen_p)
1700 addrlen = addrlen_p[0]
1701 result = rffi.cast(lltype.Signed, addr_p.c_sa_family)
1702 if res < 0:
1703 raise last_error()
1704 return result
1705
1706 if hasattr(_c, 'inet_aton'):
1707 def inet_aton(ip):
1708 "IPv4 dotted string -> packed 32-bits string"
1709 size = sizeof(_c.in_addr)
1710 buf = mallocbuf(size)
1711 try:
1712 if _c.inet_aton(ip, rffi.cast(lltype.Ptr(_c.in_addr), buf)):
1713 return ''.join([buf[i] for i in range(size)])
1714 else:
1715 raise RSocketError("illegal IP address string passed to inet_aton")
1716 finally:
1717 lltype.free(buf, flavor='raw')
1718 else:
1719 def inet_aton(ip):
1720 "IPv4 dotted string -> packed 32-bits string"
1721 if ip == "255.255.255.255":
1722 return "\xff\xff\xff\xff"
1723 packed_addr = _c.inet_addr(ip)
1724 if packed_addr == rffi.cast(lltype.Unsigned, INADDR_NONE):
1725 raise RSocketError("illegal IP address string passed to inet_aton")
1726 size = sizeof(_c.in_addr)
1727 buf = mallocbuf(size)
1728 try:
1729 rffi.cast(rffi.UINTP, buf)[0] = rffi.cast(rffi.UINT, packed_addr)
1730 return ''.join([buf[i] for i in range(size)])
1731 finally:
1732 lltype.free(buf, flavor='raw')
1733
1734 def inet_ntoa(packed):
1735 "packet 32-bits string -> IPv4 dotted string"
1736 if len(packed) != sizeof(_c.in_addr):
1737 raise RSocketError("packed IP wrong length for inet_ntoa")
1738 buf = rffi.make(_c.in_addr)
1739 try:
1740 for i in range(sizeof(_c.in_addr)):
1741 rffi.cast(rffi.CCHARP, buf)[i] = packed[i]
1742 return rffi.charp2str(_c.inet_ntoa(buf))
1743 finally:
1744 lltype.free(buf, flavor='raw')
1745
1746 if hasattr(_c, 'inet_pton'):
1747 def inet_pton(family, ip):
1748 "human-readable string -> packed string"
1749 if family == AF_INET:
1750 size = sizeof(_c.in_addr)
1751 elif AF_INET6 is not None and family == AF_INET6:
1752 size = sizeof(_c.in6_addr)
1753 else:
1754 raise RSocketError("unknown address family")
1755 buf = mallocbuf(size)
1756 try:
1757 res = _c.inet_pton(family, ip, buf)
1758 if res < 0:
1759 raise last_error()
1760 elif res == 0:
1761 raise RSocketError("illegal IP address string passed "
1762 "to inet_pton")
1763 else:
1764 return ''.join([buf[i] for i in range(size)])
1765 finally:
1766 lltype.free(buf, flavor='raw')
1767
1768 if hasattr(_c, 'inet_ntop'):
1769 def inet_ntop(family, packed):
1770 "packed string -> human-readable string"
1771 if family == AF_INET:
1772 srcsize = sizeof(_c.in_addr)
1773 dstsize = _c.INET_ADDRSTRLEN
1774 elif AF_INET6 is not None and family == AF_INET6:
1775 srcsize = sizeof(_c.in6_addr)
1776 dstsize = _c.INET6_ADDRSTRLEN
1777 else:
1778 raise RSocketError("unknown address family")
1779 if len(packed) != srcsize:
1780 raise ValueError("packed IP wrong length for inet_ntop")
1781 with rffi.scoped_nonmovingbuffer(packed) as srcbuf:
1782 dstbuf = mallocbuf(dstsize)
1783 try:
1784 res = _c.inet_ntop(family, rffi.cast(rffi.VOIDP, srcbuf),
1785 dstbuf, dstsize)
1786 if not res:
1787 raise last_error()
1788 return rffi.constcharp2str(res)
1789 finally:
1790 lltype.free(dstbuf, flavor='raw')
1791
1792 def setdefaulttimeout(timeout):
1793 if timeout < 0.0:
1794 timeout = -1.0
1795 defaults.timeout = timeout
1796
1797 _accept4_syscall = rposix.ENoSysCache()
1798
1799 if hasattr(_c, 'sethostname'):
1800 def sethostname(hostname):
1801 assert hostname is not None
1802 with rffi.scoped_view_charp(hostname) as buf:
1803 res = _c.sethostname(buf, len(hostname))
1804 if res < 0:
1805 raise last_error()
1806
1807 def if_nameindex():
1808 if_nameindex_s_ptr = _c.if_nameindex()
1809 if not if_nameindex_s_ptr:
1810 raise last_error()
1811 if_nameindex_arr = rffi.cast(rffi.CArrayPtr(_c.if_nameindex_s), if_nameindex_s_ptr)
1812 out = []
1813 i = 0
1814 while 1:
1815 v = if_nameindex_arr[i]
1816 if not v.c_if_name:
1817 break
1818 out.append((v.c_if_index, rffi.charp2str(v.c_if_name)))
1819 i += 1
1820 return out