PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/rpython/rlib/rsocket.py

https://bitbucket.org/pypy/pypy/
Python | 1407 lines | 1356 code | 24 blank | 27 comment | 20 complexity | ce91b91f583060403f57819fbad3dc2b MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. from __future__ import with_statement
  2. """
  3. An RPython implementation of sockets based on rffi.
  4. Note that the interface has to be slightly different - this is not
  5. a drop-in replacement for the 'socket' module.
  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. from rpython.rlib import _rsocket_rffi as _c, jit, rgc
  10. from rpython.rlib.objectmodel import instantiate, keepalive_until_here
  11. from rpython.rlib.rarithmetic import intmask, r_uint
  12. from rpython.rlib import rthread
  13. from rpython.rtyper.lltypesystem import lltype, rffi
  14. from rpython.rtyper.lltypesystem.rffi import sizeof, offsetof
  15. from rpython.rtyper.extregistry import ExtRegistryEntry
  16. # Usage of @jit.dont_look_inside in this file is possibly temporary
  17. # and only because some lltypes declared in _rsocket_rffi choke the
  18. # JIT's codewriter right now (notably, FixedSizeArray).
  19. INVALID_SOCKET = _c.INVALID_SOCKET
  20. def mallocbuf(buffersize):
  21. return lltype.malloc(rffi.CCHARP.TO, buffersize, flavor='raw')
  22. constants = _c.constants
  23. locals().update(constants) # Define constants from _c
  24. if _c.WIN32:
  25. from rpython.rlib import rwin32
  26. def rsocket_startup():
  27. wsadata = lltype.malloc(_c.WSAData, flavor='raw', zero=True)
  28. try:
  29. res = _c.WSAStartup(0x0101, wsadata)
  30. assert res == 0
  31. finally:
  32. lltype.free(wsadata, flavor='raw')
  33. else:
  34. def rsocket_startup():
  35. pass
  36. def ntohs(x):
  37. assert isinstance(x, int)
  38. return rffi.cast(lltype.Signed, _c.ntohs(x))
  39. def ntohl(x):
  40. # accepts and returns an Unsigned
  41. return rffi.cast(lltype.Unsigned, _c.ntohl(x))
  42. def htons(x):
  43. assert isinstance(x, int)
  44. return rffi.cast(lltype.Signed, _c.htons(x))
  45. def htonl(x):
  46. # accepts and returns an Unsigned
  47. return rffi.cast(lltype.Unsigned, _c.htonl(x))
  48. _FAMILIES = {}
  49. class Address(object):
  50. """The base class for RPython-level objects representing addresses.
  51. Fields: addr - a _c.sockaddr_ptr (memory owned by the Address instance)
  52. addrlen - size used within 'addr'
  53. """
  54. class __metaclass__(type):
  55. def __new__(cls, name, bases, dict):
  56. family = dict.get('family')
  57. A = type.__new__(cls, name, bases, dict)
  58. if family is not None:
  59. _FAMILIES[family] = A
  60. return A
  61. # default uninitialized value: NULL ptr
  62. addr_p = lltype.nullptr(_c.sockaddr_ptr.TO)
  63. def __init__(self, addr, addrlen):
  64. self.addr_p = addr
  65. self.addrlen = addrlen
  66. @rgc.must_be_light_finalizer
  67. def __del__(self):
  68. if self.addr_p:
  69. lltype.free(self.addr_p, flavor='raw', track_allocation=False)
  70. def setdata(self, addr, addrlen):
  71. # initialize self.addr and self.addrlen. 'addr' can be a different
  72. # pointer type than exactly sockaddr_ptr, and we cast it for you.
  73. assert not self.addr_p
  74. self.addr_p = rffi.cast(_c.sockaddr_ptr, addr)
  75. self.addrlen = addrlen
  76. setdata._annspecialcase_ = 'specialize:ll'
  77. # the following slightly strange interface is needed to manipulate
  78. # what self.addr_p points to in a safe way. The problem is that
  79. # after inlining we might end up with operations that looks like:
  80. # addr = self.addr_p
  81. # <self is freed here, and its __del__ calls lltype.free()>
  82. # read from addr
  83. # To prevent this we have to insert a keepalive after the last
  84. # use of 'addr'. The interface to do that is called lock()/unlock()
  85. # because it strongly reminds callers not to forget unlock().
  86. #
  87. def lock(self, TYPE=_c.sockaddr):
  88. """Return self.addr_p, cast as a pointer to TYPE. Must call unlock()!
  89. """
  90. return rffi.cast(lltype.Ptr(TYPE), self.addr_p)
  91. lock._annspecialcase_ = 'specialize:ll'
  92. def unlock(self):
  93. """To call after we're done with the pointer returned by lock().
  94. Note that locking and unlocking costs nothing at run-time.
  95. """
  96. keepalive_until_here(self)
  97. # ____________________________________________________________
  98. def makeipaddr(name, result=None):
  99. # Convert a string specifying a host name or one of a few symbolic
  100. # names to an IPAddress instance. This usually calls getaddrinfo()
  101. # to do the work; the names "" and "<broadcast>" are special.
  102. # If 'result' is specified it must be a prebuilt INETAddress or
  103. # INET6Address that is filled; otherwise a new INETXAddress is returned.
  104. if result is None:
  105. family = AF_UNSPEC
  106. else:
  107. family = result.family
  108. if len(name) == 0:
  109. info = getaddrinfo(None, "0",
  110. family=family,
  111. socktype=SOCK_DGRAM, # dummy
  112. flags=AI_PASSIVE,
  113. address_to_fill=result)
  114. if len(info) > 1:
  115. raise RSocketError("wildcard resolved to multiple addresses")
  116. return info[0][4]
  117. # IPv4 also supports the special name "<broadcast>".
  118. if name == '<broadcast>':
  119. return makeipv4addr(r_uint(INADDR_BROADCAST), result)
  120. # "dd.dd.dd.dd" format.
  121. digits = name.split('.')
  122. if len(digits) == 4:
  123. try:
  124. d0 = int(digits[0])
  125. d1 = int(digits[1])
  126. d2 = int(digits[2])
  127. d3 = int(digits[3])
  128. except ValueError:
  129. pass
  130. else:
  131. if (0 <= d0 <= 255 and
  132. 0 <= d1 <= 255 and
  133. 0 <= d2 <= 255 and
  134. 0 <= d3 <= 255):
  135. addr = intmask(d0 << 24) | (d1 << 16) | (d2 << 8) | (d3 << 0)
  136. addr = rffi.cast(rffi.UINT, addr)
  137. addr = htonl(addr)
  138. return makeipv4addr(addr, result)
  139. # generic host name to IP conversion
  140. info = getaddrinfo(name, None, family=family, address_to_fill=result)
  141. return info[0][4]
  142. class IPAddress(Address):
  143. """AF_INET and AF_INET6 addresses"""
  144. def get_host(self):
  145. # Create a string object representing an IP address.
  146. # For IPv4 this is always a string of the form 'dd.dd.dd.dd'
  147. # (with variable size numbers).
  148. host, serv = getnameinfo(self, NI_NUMERICHOST | NI_NUMERICSERV)
  149. return host
  150. def lock_in_addr(self):
  151. """ Purely abstract
  152. """
  153. raise NotImplementedError
  154. # ____________________________________________________________
  155. HAS_AF_PACKET = 'AF_PACKET' in constants
  156. if HAS_AF_PACKET:
  157. class PacketAddress(Address):
  158. family = AF_PACKET
  159. struct = _c.sockaddr_ll
  160. maxlen = minlen = sizeof(struct)
  161. ifr_name_size = _c.ifreq.c_ifr_name.length
  162. sll_addr_size = _c.sockaddr_ll.c_sll_addr.length
  163. def __init__(self, ifindex, protocol, pkttype=0, hatype=0, haddr=""):
  164. addr = lltype.malloc(_c.sockaddr_ll, flavor='raw', zero=True,
  165. track_allocation=False)
  166. self.setdata(addr, PacketAddress.maxlen)
  167. rffi.setintfield(addr, 'c_sll_family', AF_PACKET)
  168. rffi.setintfield(addr, 'c_sll_protocol', htons(protocol))
  169. rffi.setintfield(addr, 'c_sll_ifindex', ifindex)
  170. rffi.setintfield(addr, 'c_sll_pkttype', pkttype)
  171. rffi.setintfield(addr, 'c_sll_hatype', hatype)
  172. halen = rffi.str2chararray(haddr,
  173. rffi.cast(rffi.CCHARP, addr.c_sll_addr),
  174. PacketAddress.sll_addr_size)
  175. rffi.setintfield(addr, 'c_sll_halen', halen)
  176. @staticmethod
  177. def get_ifindex_from_ifname(fd, ifname):
  178. p = lltype.malloc(_c.ifreq, flavor='raw')
  179. iflen = rffi.str2chararray(ifname,
  180. rffi.cast(rffi.CCHARP, p.c_ifr_name),
  181. PacketAddress.ifr_name_size - 1)
  182. p.c_ifr_name[iflen] = '\0'
  183. err = _c.ioctl(fd, _c.SIOCGIFINDEX, p)
  184. ifindex = p.c_ifr_ifindex
  185. lltype.free(p, flavor='raw')
  186. if err != 0:
  187. raise RSocketError("invalid interface name")
  188. return ifindex
  189. def get_ifname(self, fd):
  190. ifname = ""
  191. a = self.lock(_c.sockaddr_ll)
  192. ifindex = rffi.getintfield(a, 'c_sll_ifindex')
  193. if ifindex:
  194. p = lltype.malloc(_c.ifreq, flavor='raw')
  195. rffi.setintfield(p, 'c_ifr_ifindex', ifindex)
  196. if (_c.ioctl(fd, _c.SIOCGIFNAME, p) == 0):
  197. ifname = rffi.charp2strn(
  198. rffi.cast(rffi.CCHARP, p.c_ifr_name),
  199. PacketAddress.ifr_name_size)
  200. lltype.free(p, flavor='raw')
  201. self.unlock()
  202. return ifname
  203. def get_protocol(self):
  204. a = self.lock(_c.sockaddr_ll)
  205. proto = rffi.getintfield(a, 'c_sll_protocol')
  206. res = ntohs(proto)
  207. self.unlock()
  208. return res
  209. def get_pkttype(self):
  210. a = self.lock(_c.sockaddr_ll)
  211. res = rffi.getintfield(a, 'c_sll_pkttype')
  212. self.unlock()
  213. return res
  214. def get_hatype(self):
  215. a = self.lock(_c.sockaddr_ll)
  216. res = rffi.getintfield(a, 'c_sll_hatype')
  217. self.unlock()
  218. return res
  219. def get_haddr(self):
  220. a = self.lock(_c.sockaddr_ll)
  221. lgt = rffi.getintfield(a, 'c_sll_halen')
  222. d = []
  223. for i in range(lgt):
  224. d.append(a.c_sll_addr[i])
  225. res = "".join(d)
  226. self.unlock()
  227. return res
  228. class INETAddress(IPAddress):
  229. family = AF_INET
  230. struct = _c.sockaddr_in
  231. maxlen = minlen = sizeof(struct)
  232. def __init__(self, host, port):
  233. makeipaddr(host, self)
  234. a = self.lock(_c.sockaddr_in)
  235. rffi.setintfield(a, 'c_sin_port', htons(port))
  236. self.unlock()
  237. def __repr__(self):
  238. try:
  239. return '<INETAddress %s:%d>' % (self.get_host(), self.get_port())
  240. except SocketError:
  241. return '<INETAddress ?>'
  242. def get_port(self):
  243. a = self.lock(_c.sockaddr_in)
  244. port = ntohs(rffi.getintfield(a, 'c_sin_port'))
  245. self.unlock()
  246. return port
  247. def eq(self, other): # __eq__() is not called by RPython :-/
  248. return (isinstance(other, INETAddress) and
  249. self.get_host() == other.get_host() and
  250. self.get_port() == other.get_port())
  251. def from_in_addr(in_addr):
  252. result = instantiate(INETAddress)
  253. # store the malloc'ed data into 'result' as soon as possible
  254. # to avoid leaks if an exception occurs inbetween
  255. sin = lltype.malloc(_c.sockaddr_in, flavor='raw', zero=True,
  256. track_allocation=False)
  257. result.setdata(sin, sizeof(_c.sockaddr_in))
  258. # PLAT sin_len
  259. rffi.setintfield(sin, 'c_sin_family', AF_INET)
  260. rffi.structcopy(sin.c_sin_addr, in_addr)
  261. return result
  262. from_in_addr = staticmethod(from_in_addr)
  263. def lock_in_addr(self):
  264. a = self.lock(_c.sockaddr_in)
  265. p = rffi.cast(rffi.VOIDP, a.c_sin_addr)
  266. return p, sizeof(_c.in_addr)
  267. # ____________________________________________________________
  268. class INET6Address(IPAddress):
  269. family = AF_INET6
  270. struct = _c.sockaddr_in6
  271. maxlen = minlen = sizeof(struct)
  272. def __init__(self, host, port, flowinfo=0, scope_id=0):
  273. makeipaddr(host, self)
  274. a = self.lock(_c.sockaddr_in6)
  275. rffi.setintfield(a, 'c_sin6_port', htons(port))
  276. rffi.setintfield(a, 'c_sin6_flowinfo', htonl(flowinfo))
  277. rffi.setintfield(a, 'c_sin6_scope_id', scope_id)
  278. self.unlock()
  279. def __repr__(self):
  280. try:
  281. return '<INET6Address %s:%d %d %d>' % (self.get_host(),
  282. self.get_port(),
  283. self.get_flowinfo(),
  284. self.get_scope_id())
  285. except SocketError:
  286. return '<INET6Address ?>'
  287. def get_port(self):
  288. a = self.lock(_c.sockaddr_in6)
  289. port = ntohs(rffi.getintfield(a, 'c_sin6_port'))
  290. self.unlock()
  291. return port
  292. def get_flowinfo(self):
  293. a = self.lock(_c.sockaddr_in6)
  294. flowinfo = ntohl(a.c_sin6_flowinfo)
  295. self.unlock()
  296. return rffi.cast(lltype.Unsigned, flowinfo)
  297. def get_scope_id(self):
  298. a = self.lock(_c.sockaddr_in6)
  299. scope_id = a.c_sin6_scope_id
  300. self.unlock()
  301. return rffi.cast(lltype.Unsigned, scope_id)
  302. def eq(self, other): # __eq__() is not called by RPython :-/
  303. return (isinstance(other, INET6Address) and
  304. self.get_host() == other.get_host() and
  305. self.get_port() == other.get_port() and
  306. self.get_flowinfo() == other.get_flowinfo() and
  307. self.get_scope_id() == other.get_scope_id())
  308. def from_in6_addr(in6_addr):
  309. result = instantiate(INET6Address)
  310. # store the malloc'ed data into 'result' as soon as possible
  311. # to avoid leaks if an exception occurs inbetween
  312. sin = lltype.malloc(_c.sockaddr_in6, flavor='raw', zero=True,
  313. track_allocation=False)
  314. result.setdata(sin, sizeof(_c.sockaddr_in6))
  315. rffi.setintfield(sin, 'c_sin6_family', AF_INET6)
  316. rffi.structcopy(sin.c_sin6_addr, in6_addr)
  317. return result
  318. from_in6_addr = staticmethod(from_in6_addr)
  319. def lock_in_addr(self):
  320. a = self.lock(_c.sockaddr_in6)
  321. p = rffi.cast(rffi.VOIDP, a.c_sin6_addr)
  322. return p, sizeof(_c.in6_addr)
  323. # ____________________________________________________________
  324. HAS_AF_UNIX = 'AF_UNIX' in constants
  325. if HAS_AF_UNIX:
  326. class UNIXAddress(Address):
  327. family = AF_UNIX
  328. struct = _c.sockaddr_un
  329. minlen = offsetof(_c.sockaddr_un, 'c_sun_path')
  330. maxlen = sizeof(struct)
  331. def __init__(self, path):
  332. sun = lltype.malloc(_c.sockaddr_un, flavor='raw', zero=True,
  333. track_allocation=False)
  334. baseofs = offsetof(_c.sockaddr_un, 'c_sun_path')
  335. self.setdata(sun, baseofs + len(path))
  336. rffi.setintfield(sun, 'c_sun_family', AF_UNIX)
  337. if _c.linux and path.startswith('\x00'):
  338. # Linux abstract namespace extension
  339. if len(path) > sizeof(_c.sockaddr_un.c_sun_path):
  340. raise RSocketError("AF_UNIX path too long")
  341. else:
  342. # regular NULL-terminated string
  343. if len(path) >= sizeof(_c.sockaddr_un.c_sun_path):
  344. raise RSocketError("AF_UNIX path too long")
  345. sun.c_sun_path[len(path)] = '\x00'
  346. for i in range(len(path)):
  347. sun.c_sun_path[i] = path[i]
  348. def __repr__(self):
  349. try:
  350. return '<UNIXAddress %r>' % (self.get_path(),)
  351. except SocketError:
  352. return '<UNIXAddress ?>'
  353. def get_path(self):
  354. a = self.lock(_c.sockaddr_un)
  355. maxlength = self.addrlen - offsetof(_c.sockaddr_un, 'c_sun_path')
  356. if _c.linux and maxlength > 0 and a.c_sun_path[0] == '\x00':
  357. # Linux abstract namespace
  358. length = maxlength
  359. else:
  360. # regular NULL-terminated string
  361. length = 0
  362. while length < maxlength and a.c_sun_path[length] != '\x00':
  363. length += 1
  364. result = ''.join([a.c_sun_path[i] for i in range(length)])
  365. self.unlock()
  366. return result
  367. def eq(self, other): # __eq__() is not called by RPython :-/
  368. return (isinstance(other, UNIXAddress) and
  369. self.get_path() == other.get_path())
  370. HAS_AF_NETLINK = 'AF_NETLINK' in constants
  371. if HAS_AF_NETLINK:
  372. class NETLINKAddress(Address):
  373. family = AF_NETLINK
  374. struct = _c.sockaddr_nl
  375. maxlen = minlen = sizeof(struct)
  376. def __init__(self, pid, groups):
  377. addr = lltype.malloc(_c.sockaddr_nl, flavor='raw', zero=True,
  378. track_allocation=False)
  379. self.setdata(addr, NETLINKAddress.maxlen)
  380. rffi.setintfield(addr, 'c_nl_family', AF_NETLINK)
  381. rffi.setintfield(addr, 'c_nl_pid', pid)
  382. rffi.setintfield(addr, 'c_nl_groups', groups)
  383. def get_pid(self):
  384. a = self.lock(_c.sockaddr_nl)
  385. pid = a.c_nl_pid
  386. self.unlock()
  387. return rffi.cast(lltype.Unsigned, pid)
  388. def get_groups(self):
  389. a = self.lock(_c.sockaddr_nl)
  390. groups = a.c_nl_groups
  391. self.unlock()
  392. return rffi.cast(lltype.Unsigned, groups)
  393. def __repr__(self):
  394. return '<NETLINKAddress %r>' % (self.get_pid(), self.get_groups())
  395. # ____________________________________________________________
  396. def familyclass(family):
  397. return _FAMILIES.get(family, Address)
  398. af_get = familyclass
  399. def make_address(addrptr, addrlen, result=None):
  400. family = rffi.cast(lltype.Signed, addrptr.c_sa_family)
  401. if result is None:
  402. result = instantiate(familyclass(family))
  403. elif result.family != family:
  404. raise RSocketError("address family mismatched")
  405. # copy into a new buffer the address that 'addrptr' points to
  406. addrlen = rffi.cast(lltype.Signed, addrlen)
  407. buf = lltype.malloc(rffi.CCHARP.TO, addrlen, flavor='raw',
  408. track_allocation=False)
  409. src = rffi.cast(rffi.CCHARP, addrptr)
  410. for i in range(addrlen):
  411. buf[i] = src[i]
  412. result.setdata(buf, addrlen)
  413. return result
  414. def makeipv4addr(s_addr, result=None):
  415. if result is None:
  416. result = instantiate(INETAddress)
  417. elif result.family != AF_INET:
  418. raise RSocketError("address family mismatched")
  419. sin = lltype.malloc(_c.sockaddr_in, flavor='raw', zero=True,
  420. track_allocation=False)
  421. result.setdata(sin, sizeof(_c.sockaddr_in))
  422. rffi.setintfield(sin, 'c_sin_family', AF_INET) # PLAT sin_len
  423. rffi.setintfield(sin.c_sin_addr, 'c_s_addr', s_addr)
  424. return result
  425. def make_null_address(family):
  426. klass = familyclass(family)
  427. result = instantiate(klass)
  428. buf = lltype.malloc(rffi.CCHARP.TO, klass.maxlen, flavor='raw', zero=True,
  429. track_allocation=False)
  430. # Initialize the family to the correct value. Avoids surprizes on
  431. # Windows when calling a function that unexpectedly does not set
  432. # the output address (e.g. recvfrom() on a connected IPv4 socket).
  433. rffi.setintfield(rffi.cast(_c.sockaddr_ptr, buf), 'c_sa_family', family)
  434. result.setdata(buf, 0)
  435. return result, klass.maxlen
  436. # ____________________________________________________________
  437. class RSocket(object):
  438. """RPython-level socket object.
  439. """
  440. fd = _c.INVALID_SOCKET
  441. family = 0
  442. type = 0
  443. proto = 0
  444. timeout = -1.0
  445. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0,
  446. fd=_c.INVALID_SOCKET):
  447. """Create a new socket."""
  448. if _c.invalid_socket(fd):
  449. fd = _c.socket(family, type, proto)
  450. if _c.invalid_socket(fd):
  451. raise self.error_handler()
  452. # PLAT RISCOS
  453. self.fd = fd
  454. self.family = family
  455. self.type = type
  456. self.proto = proto
  457. self.timeout = defaults.timeout
  458. @staticmethod
  459. def empty_rsocket():
  460. rsocket = instantiate(RSocket)
  461. return rsocket
  462. @rgc.must_be_light_finalizer
  463. def __del__(self):
  464. fd = self.fd
  465. if fd != _c.INVALID_SOCKET:
  466. self.fd = _c.INVALID_SOCKET
  467. _c.socketclose_no_errno(fd)
  468. if hasattr(_c, 'fcntl'):
  469. def _setblocking(self, block):
  470. orig_delay_flag = intmask(_c.fcntl(self.fd, _c.F_GETFL, 0))
  471. if block:
  472. delay_flag = orig_delay_flag & ~_c.O_NONBLOCK
  473. else:
  474. delay_flag = orig_delay_flag | _c.O_NONBLOCK
  475. if orig_delay_flag != delay_flag:
  476. _c.fcntl(self.fd, _c.F_SETFL, delay_flag)
  477. elif hasattr(_c, 'ioctlsocket'):
  478. def _setblocking(self, block):
  479. flag = lltype.malloc(rffi.ULONGP.TO, 1, flavor='raw')
  480. flag[0] = rffi.cast(rffi.ULONG, not block)
  481. _c.ioctlsocket(self.fd, _c.FIONBIO, flag)
  482. lltype.free(flag, flavor='raw')
  483. if hasattr(_c, 'poll') and not _c.poll_may_be_broken:
  484. def _select(self, for_writing):
  485. """Returns 0 when reading/writing is possible,
  486. 1 when timing out and -1 on error."""
  487. if self.timeout <= 0.0 or self.fd == _c.INVALID_SOCKET:
  488. # blocking I/O or no socket.
  489. return 0
  490. pollfd = rffi.make(_c.pollfd)
  491. try:
  492. rffi.setintfield(pollfd, 'c_fd', self.fd)
  493. if for_writing:
  494. rffi.setintfield(pollfd, 'c_events', _c.POLLOUT)
  495. else:
  496. rffi.setintfield(pollfd, 'c_events', _c.POLLIN)
  497. timeout = int(self.timeout * 1000.0 + 0.5)
  498. n = _c.poll(rffi.cast(lltype.Ptr(_c.pollfdarray), pollfd),
  499. 1, timeout)
  500. finally:
  501. lltype.free(pollfd, flavor='raw')
  502. if n < 0:
  503. return -1
  504. if n == 0:
  505. return 1
  506. return 0
  507. else:
  508. # Version witout poll(): use select()
  509. def _select(self, for_writing):
  510. """Returns 0 when reading/writing is possible,
  511. 1 when timing out and -1 on error."""
  512. timeout = self.timeout
  513. if timeout <= 0.0 or self.fd == _c.INVALID_SOCKET:
  514. # blocking I/O or no socket.
  515. return 0
  516. tv = rffi.make(_c.timeval)
  517. rffi.setintfield(tv, 'c_tv_sec', int(timeout))
  518. rffi.setintfield(tv, 'c_tv_usec', int((timeout-int(timeout))
  519. * 1000000))
  520. fds = lltype.malloc(_c.fd_set.TO, flavor='raw')
  521. _c.FD_ZERO(fds)
  522. _c.FD_SET(self.fd, fds)
  523. null = lltype.nullptr(_c.fd_set.TO)
  524. if for_writing:
  525. n = _c.select(self.fd + 1, null, fds, null, tv)
  526. else:
  527. n = _c.select(self.fd + 1, fds, null, null, tv)
  528. lltype.free(fds, flavor='raw')
  529. lltype.free(tv, flavor='raw')
  530. if n < 0:
  531. return -1
  532. if n == 0:
  533. return 1
  534. return 0
  535. def error_handler(self):
  536. return last_error()
  537. # build a null address object, ready to be used as output argument to
  538. # C functions that return an address. It must be unlock()ed after you
  539. # are done using addr_p.
  540. def _addrbuf(self):
  541. addr, maxlen = make_null_address(self.family)
  542. addrlen_p = lltype.malloc(_c.socklen_t_ptr.TO, flavor='raw')
  543. addrlen_p[0] = rffi.cast(_c.socklen_t, maxlen)
  544. return addr, addr.addr_p, addrlen_p
  545. @jit.dont_look_inside
  546. def accept(self):
  547. """Wait for an incoming connection.
  548. Return (new socket fd, client address)."""
  549. if self._select(False) == 1:
  550. raise SocketTimeout
  551. address, addr_p, addrlen_p = self._addrbuf()
  552. try:
  553. newfd = _c.socketaccept(self.fd, addr_p, addrlen_p)
  554. addrlen = addrlen_p[0]
  555. finally:
  556. lltype.free(addrlen_p, flavor='raw')
  557. address.unlock()
  558. if _c.invalid_socket(newfd):
  559. raise self.error_handler()
  560. address.addrlen = rffi.cast(lltype.Signed, addrlen)
  561. return (newfd, address)
  562. def bind(self, address):
  563. """Bind the socket to a local address."""
  564. addr = address.lock()
  565. res = _c.socketbind(self.fd, addr, address.addrlen)
  566. address.unlock()
  567. if res < 0:
  568. raise self.error_handler()
  569. def close(self):
  570. """Close the socket. It cannot be used after this call."""
  571. fd = self.fd
  572. if fd != _c.INVALID_SOCKET:
  573. self.fd = _c.INVALID_SOCKET
  574. res = _c.socketclose(fd)
  575. if res != 0:
  576. raise self.error_handler()
  577. def detach(self):
  578. fd = self.fd
  579. self.fd = _c.INVALID_SOCKET
  580. return fd
  581. if _c.WIN32:
  582. def _connect(self, address):
  583. """Connect the socket to a remote address."""
  584. addr = address.lock()
  585. res = _c.socketconnect(self.fd, addr, address.addrlen)
  586. address.unlock()
  587. errno = _c.geterrno()
  588. timeout = self.timeout
  589. if timeout > 0.0 and res < 0 and errno == _c.EWOULDBLOCK:
  590. tv = rffi.make(_c.timeval)
  591. rffi.setintfield(tv, 'c_tv_sec', int(timeout))
  592. rffi.setintfield(tv, 'c_tv_usec',
  593. int((timeout-int(timeout)) * 1000000))
  594. fds = lltype.malloc(_c.fd_set.TO, flavor='raw')
  595. _c.FD_ZERO(fds)
  596. _c.FD_SET(self.fd, fds)
  597. fds_exc = lltype.malloc(_c.fd_set.TO, flavor='raw')
  598. _c.FD_ZERO(fds_exc)
  599. _c.FD_SET(self.fd, fds_exc)
  600. null = lltype.nullptr(_c.fd_set.TO)
  601. try:
  602. n = _c.select(self.fd + 1, null, fds, fds_exc, tv)
  603. if n > 0:
  604. if _c.FD_ISSET(self.fd, fds):
  605. # socket writable == connected
  606. return (0, False)
  607. else:
  608. # per MS docs, call getsockopt() to get error
  609. assert _c.FD_ISSET(self.fd, fds_exc)
  610. return (self.getsockopt_int(_c.SOL_SOCKET,
  611. _c.SO_ERROR), False)
  612. elif n == 0:
  613. return (_c.EWOULDBLOCK, True)
  614. else:
  615. return (_c.geterrno(), False)
  616. finally:
  617. lltype.free(fds, flavor='raw')
  618. lltype.free(fds_exc, flavor='raw')
  619. lltype.free(tv, flavor='raw')
  620. if res == 0:
  621. errno = 0
  622. return (errno, False)
  623. else:
  624. def _connect(self, address):
  625. """Connect the socket to a remote address."""
  626. addr = address.lock()
  627. res = _c.socketconnect(self.fd, addr, address.addrlen)
  628. address.unlock()
  629. errno = _c.geterrno()
  630. if self.timeout > 0.0 and res < 0 and errno == _c.EINPROGRESS:
  631. timeout = self._select(True)
  632. if timeout == 0:
  633. res = self.getsockopt_int(_c.SOL_SOCKET, _c.SO_ERROR)
  634. if res == _c.EISCONN:
  635. res = 0
  636. errno = res
  637. elif timeout == -1:
  638. return (_c.geterrno(), False)
  639. else:
  640. return (_c.EWOULDBLOCK, True)
  641. if res < 0:
  642. res = errno
  643. return (res, False)
  644. def connect(self, address):
  645. """Connect the socket to a remote address."""
  646. err, timeout = self._connect(address)
  647. if timeout:
  648. raise SocketTimeout
  649. if err:
  650. raise CSocketError(err)
  651. def connect_ex(self, address):
  652. """This is like connect(address), but returns an error code (the errno
  653. value) instead of raising an exception when an error occurs."""
  654. err, timeout = self._connect(address)
  655. return err
  656. if hasattr(_c, 'dup'):
  657. def dup(self, SocketClass=None):
  658. if SocketClass is None:
  659. SocketClass = RSocket
  660. fd = _c.dup(self.fd)
  661. if fd < 0:
  662. raise self.error_handler()
  663. return make_socket(fd, self.family, self.type, self.proto,
  664. SocketClass=SocketClass)
  665. @jit.dont_look_inside
  666. def getpeername(self):
  667. """Return the address of the remote endpoint."""
  668. address, addr_p, addrlen_p = self._addrbuf()
  669. try:
  670. res = _c.socketgetpeername(self.fd, addr_p, addrlen_p)
  671. addrlen = addrlen_p[0]
  672. finally:
  673. lltype.free(addrlen_p, flavor='raw')
  674. address.unlock()
  675. if res < 0:
  676. raise self.error_handler()
  677. address.addrlen = rffi.cast(lltype.Signed, addrlen)
  678. return address
  679. @jit.dont_look_inside
  680. def getsockname(self):
  681. """Return the address of the local endpoint."""
  682. address, addr_p, addrlen_p = self._addrbuf()
  683. try:
  684. res = _c.socketgetsockname(self.fd, addr_p, addrlen_p)
  685. addrlen = addrlen_p[0]
  686. finally:
  687. lltype.free(addrlen_p, flavor='raw')
  688. address.unlock()
  689. if res < 0:
  690. raise self.error_handler()
  691. address.addrlen = rffi.cast(lltype.Signed, addrlen)
  692. return address
  693. @jit.dont_look_inside
  694. def getsockopt(self, level, option, maxlen):
  695. buf = mallocbuf(maxlen)
  696. try:
  697. bufsize_p = lltype.malloc(_c.socklen_t_ptr.TO, flavor='raw')
  698. try:
  699. bufsize_p[0] = rffi.cast(_c.socklen_t, maxlen)
  700. res = _c.socketgetsockopt(self.fd, level, option,
  701. buf, bufsize_p)
  702. if res < 0:
  703. raise self.error_handler()
  704. size = rffi.cast(lltype.Signed, bufsize_p[0])
  705. assert size >= 0 # socklen_t is signed on Windows
  706. result = ''.join([buf[i] for i in range(size)])
  707. finally:
  708. lltype.free(bufsize_p, flavor='raw')
  709. finally:
  710. lltype.free(buf, flavor='raw')
  711. return result
  712. @jit.dont_look_inside
  713. def getsockopt_int(self, level, option):
  714. flag_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
  715. try:
  716. flagsize_p = lltype.malloc(_c.socklen_t_ptr.TO, flavor='raw')
  717. try:
  718. flagsize_p[0] = rffi.cast(_c.socklen_t, rffi.sizeof(rffi.INT))
  719. res = _c.socketgetsockopt(self.fd, level, option,
  720. rffi.cast(rffi.VOIDP, flag_p),
  721. flagsize_p)
  722. if res < 0:
  723. raise self.error_handler()
  724. result = rffi.cast(lltype.Signed, flag_p[0])
  725. finally:
  726. lltype.free(flagsize_p, flavor='raw')
  727. finally:
  728. lltype.free(flag_p, flavor='raw')
  729. return result
  730. def gettimeout(self):
  731. """Return the timeout of the socket. A timeout < 0 means that
  732. timeouts are disabled in the socket."""
  733. return self.timeout
  734. def listen(self, backlog):
  735. """Enable a server to accept connections. The backlog argument
  736. must be at least 1; it specifies the number of unaccepted connections
  737. that the system will allow before refusing new connections."""
  738. if backlog < 1:
  739. backlog = 1
  740. res = _c.socketlisten(self.fd, backlog)
  741. if res < 0:
  742. raise self.error_handler()
  743. def wait_for_data(self, for_writing):
  744. timeout = self._select(for_writing)
  745. if timeout != 0:
  746. if timeout == 1:
  747. raise SocketTimeout
  748. else:
  749. raise self.error_handler()
  750. def recv(self, buffersize, flags=0):
  751. """Receive up to buffersize bytes from the socket. For the optional
  752. flags argument, see the Unix manual. When no data is available, block
  753. until at least one byte is available or until the remote end is closed.
  754. When the remote end is closed and all data is read, return the empty
  755. string."""
  756. self.wait_for_data(False)
  757. with rffi.scoped_alloc_buffer(buffersize) as buf:
  758. read_bytes = _c.socketrecv(self.fd, buf.raw, buffersize, flags)
  759. if read_bytes >= 0:
  760. return buf.str(read_bytes)
  761. raise self.error_handler()
  762. def recvinto(self, rwbuffer, nbytes, flags=0):
  763. try:
  764. rwbuffer.get_raw_address()
  765. except ValueError:
  766. buf = self.recv(nbytes, flags)
  767. rwbuffer.setslice(0, buf)
  768. return len(buf)
  769. else:
  770. self.wait_for_data(False)
  771. raw = rwbuffer.get_raw_address()
  772. read_bytes = _c.socketrecv(self.fd, raw, nbytes, flags)
  773. keepalive_until_here(rwbuffer)
  774. if read_bytes >= 0:
  775. return read_bytes
  776. raise self.error_handler()
  777. @jit.dont_look_inside
  778. def recvfrom(self, buffersize, flags=0):
  779. """Like recv(buffersize, flags) but also return the sender's
  780. address."""
  781. self.wait_for_data(False)
  782. with rffi.scoped_alloc_buffer(buffersize) as buf:
  783. address, addr_p, addrlen_p = self._addrbuf()
  784. try:
  785. read_bytes = _c.recvfrom(self.fd, buf.raw, buffersize, flags,
  786. addr_p, addrlen_p)
  787. addrlen = rffi.cast(lltype.Signed, addrlen_p[0])
  788. finally:
  789. lltype.free(addrlen_p, flavor='raw')
  790. address.unlock()
  791. if read_bytes >= 0:
  792. if addrlen:
  793. address.addrlen = addrlen
  794. else:
  795. address = None
  796. data = buf.str(read_bytes)
  797. return (data, address)
  798. raise self.error_handler()
  799. def recvfrom_into(self, rwbuffer, nbytes, flags=0):
  800. try:
  801. rwbuffer.get_raw_address()
  802. except ValueError:
  803. buf, addr = self.recvfrom(nbytes, flags)
  804. rwbuffer.setslice(0, buf)
  805. return len(buf), addr
  806. else:
  807. self.wait_for_data(False)
  808. address, addr_p, addrlen_p = self._addrbuf()
  809. try:
  810. raw = rwbuffer.get_raw_address()
  811. read_bytes = _c.recvfrom(self.fd, raw, nbytes, flags,
  812. addr_p, addrlen_p)
  813. keepalive_until_here(rwbuffer)
  814. addrlen = rffi.cast(lltype.Signed, addrlen_p[0])
  815. finally:
  816. lltype.free(addrlen_p, flavor='raw')
  817. address.unlock()
  818. if read_bytes >= 0:
  819. if addrlen:
  820. address.addrlen = addrlen
  821. else:
  822. address = None
  823. return (read_bytes, address)
  824. raise self.error_handler()
  825. def send_raw(self, dataptr, length, flags=0):
  826. """Send data from a CCHARP buffer."""
  827. self.wait_for_data(True)
  828. res = _c.send(self.fd, dataptr, length, flags)
  829. if res < 0:
  830. raise self.error_handler()
  831. return res
  832. def send(self, data, flags=0):
  833. """Send a data string to the socket. For the optional flags
  834. argument, see the Unix manual. Return the number of bytes
  835. sent; this may be less than len(data) if the network is busy."""
  836. with rffi.scoped_nonmovingbuffer(data) as dataptr:
  837. return self.send_raw(dataptr, len(data), flags)
  838. def sendall(self, data, flags=0, signal_checker=None):
  839. """Send a data string to the socket. For the optional flags
  840. argument, see the Unix manual. This calls send() repeatedly
  841. until all data is sent. If an error occurs, it's impossible
  842. to tell how much data has been sent."""
  843. with rffi.scoped_nonmovingbuffer(data) as dataptr:
  844. remaining = len(data)
  845. p = dataptr
  846. while remaining > 0:
  847. try:
  848. res = self.send_raw(p, remaining, flags)
  849. p = rffi.ptradd(p, res)
  850. remaining -= res
  851. except CSocketError as e:
  852. if e.errno != _c.EINTR:
  853. raise
  854. if signal_checker is not None:
  855. signal_checker()
  856. def sendto(self, data, flags, address):
  857. """Like send(data, flags) but allows specifying the destination
  858. address. (Note that 'flags' is mandatory here.)"""
  859. self.wait_for_data(True)
  860. addr = address.lock()
  861. res = _c.sendto(self.fd, data, len(data), flags,
  862. addr, address.addrlen)
  863. address.unlock()
  864. if res < 0:
  865. raise self.error_handler()
  866. return res
  867. def setblocking(self, block):
  868. if block:
  869. timeout = -1.0
  870. else:
  871. timeout = 0.0
  872. self.settimeout(timeout)
  873. def setsockopt(self, level, option, value):
  874. with rffi.scoped_str2charp(value) as buf:
  875. res = _c.socketsetsockopt(self.fd, level, option,
  876. rffi.cast(rffi.VOIDP, buf),
  877. len(value))
  878. if res < 0:
  879. raise self.error_handler()
  880. def setsockopt_int(self, level, option, value):
  881. with lltype.scoped_alloc(rffi.INTP.TO, 1) as flag_p:
  882. flag_p[0] = rffi.cast(rffi.INT, value)
  883. res = _c.socketsetsockopt(self.fd, level, option,
  884. rffi.cast(rffi.VOIDP, flag_p),
  885. rffi.sizeof(rffi.INT))
  886. if res < 0:
  887. raise self.error_handler()
  888. def settimeout(self, timeout):
  889. """Set the timeout of the socket. A timeout < 0 means that
  890. timeouts are dissabled in the socket."""
  891. if timeout < 0.0:
  892. self.timeout = -1.0
  893. else:
  894. self.timeout = timeout
  895. self._setblocking(self.timeout < 0.0)
  896. def shutdown(self, how):
  897. """Shut down the reading side of the socket (flag == SHUT_RD), the
  898. writing side of the socket (flag == SHUT_WR), or both ends
  899. (flag == SHUT_RDWR)."""
  900. res = _c.socketshutdown(self.fd, how)
  901. if res < 0:
  902. raise self.error_handler()
  903. # ____________________________________________________________
  904. def make_socket(fd, family, type, proto, SocketClass=RSocket):
  905. result = instantiate(SocketClass)
  906. result.fd = fd
  907. result.family = family
  908. result.type = type
  909. result.proto = proto
  910. result.timeout = defaults.timeout
  911. return result
  912. make_socket._annspecialcase_ = 'specialize:arg(4)'
  913. class SocketError(Exception):
  914. applevelerrcls = 'error'
  915. def __init__(self):
  916. pass
  917. def get_msg(self):
  918. return ''
  919. def __str__(self):
  920. return self.get_msg()
  921. class SocketErrorWithErrno(SocketError):
  922. def __init__(self, errno):
  923. self.errno = errno
  924. class RSocketError(SocketError):
  925. def __init__(self, message):
  926. self.message = message
  927. def get_msg(self):
  928. return self.message
  929. class CSocketError(SocketErrorWithErrno):
  930. def get_msg(self):
  931. return _c.socket_strerror_str(self.errno)
  932. def last_error():
  933. return CSocketError(_c.geterrno())
  934. class GAIError(SocketErrorWithErrno):
  935. applevelerrcls = 'gaierror'
  936. def get_msg(self):
  937. return _c.gai_strerror_str(self.errno)
  938. class HSocketError(SocketError):
  939. applevelerrcls = 'herror'
  940. def __init__(self, host):
  941. self.host = host
  942. # XXX h_errno is not easily available, and hstrerror() is
  943. # marked as deprecated in the Linux man pages
  944. def get_msg(self):
  945. return "host lookup failed: '%s'" % (self.host,)
  946. class SocketTimeout(SocketError):
  947. applevelerrcls = 'timeout'
  948. def get_msg(self):
  949. return 'timed out'
  950. class Defaults:
  951. timeout = -1.0 # Blocking
  952. defaults = Defaults()
  953. # ____________________________________________________________
  954. if 'AF_UNIX' not in constants or AF_UNIX is None:
  955. socketpair_default_family = AF_INET
  956. else:
  957. socketpair_default_family = AF_UNIX
  958. if hasattr(_c, 'socketpair'):
  959. def socketpair(family=socketpair_default_family, type=SOCK_STREAM, proto=0,
  960. SocketClass=RSocket):
  961. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  962. Create a pair of socket objects from the sockets returned by the platform
  963. socketpair() function.
  964. The arguments are the same as for socket() except the default family is
  965. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  966. """
  967. result = lltype.malloc(_c.socketpair_t, 2, flavor='raw')
  968. res = _c.socketpair(family, type, proto, result)
  969. if res < 0:
  970. raise last_error()
  971. fd0 = rffi.cast(lltype.Signed, result[0])
  972. fd1 = rffi.cast(lltype.Signed, result[1])
  973. lltype.free(result, flavor='raw')
  974. return (make_socket(fd0, family, type, proto, SocketClass),
  975. make_socket(fd1, family, type, proto, SocketClass))
  976. if _c.WIN32:
  977. def dup(fd):
  978. with lltype.scoped_alloc(_c.WSAPROTOCOL_INFO, zero=True) as info:
  979. if _c.WSADuplicateSocket(fd, rwin32.GetCurrentProcessId(), info):
  980. raise last_error()
  981. result = _c.WSASocket(
  982. _c.FROM_PROTOCOL_INFO, _c.FROM_PROTOCOL_INFO,
  983. _c.FROM_PROTOCOL_INFO, info, 0, 0)
  984. if result == INVALID_SOCKET:
  985. raise last_error()
  986. return result
  987. else:
  988. def dup(fd):
  989. return _c.dup(fd)
  990. def fromfd(fd, family, type, proto=0, SocketClass=RSocket):
  991. # Dup the fd so it and the socket can be closed independently
  992. fd = _c.dup(fd)
  993. if fd < 0:
  994. raise last_error()
  995. return make_socket(fd, family, type, proto, SocketClass)
  996. def getdefaulttimeout():
  997. return defaults.timeout
  998. def gethostname():
  999. size = 1024
  1000. buf = lltype.malloc(rffi.CCHARP.TO, size, flavor='raw')
  1001. try:
  1002. res = _c.gethostname(buf, size)
  1003. if res < 0:
  1004. raise last_error()
  1005. return rffi.charp2strn(buf, size)
  1006. finally:
  1007. lltype.free(buf, flavor='raw')
  1008. def gethostbyname(name):
  1009. # this is explicitly not working with IPv6, because the docs say it
  1010. # should not. Just use makeipaddr(name) for an IPv6-friendly version...
  1011. result = instantiate(INETAddress)
  1012. makeipaddr(name, result)
  1013. return result
  1014. def gethost_common(hostname, hostent, addr=None):
  1015. if not hostent:
  1016. raise HSocketError(hostname)
  1017. family = rffi.getintfield(hostent, 'c_h_addrtype')
  1018. if addr is not None and addr.family != family:
  1019. raise CSocketError(_c.EAFNOSUPPORT)
  1020. h_aliases = hostent.c_h_aliases
  1021. if h_aliases: # h_aliases can be NULL, according to SF #1511317
  1022. aliases = rffi.charpp2liststr(h_aliases)
  1023. else:
  1024. aliases = []
  1025. address_list = []
  1026. h_addr_list = hostent.c_h_addr_list
  1027. i = 0
  1028. paddr = h_addr_list[0]
  1029. while paddr:
  1030. if family == AF_INET:
  1031. p = rffi.cast(lltype.Ptr(_c.in_addr), paddr)
  1032. addr = INETAddress.from_in_addr(p)
  1033. elif AF_INET6 is not None and family == AF_INET6:
  1034. p = rffi.cast(lltype.Ptr(_c.in6_addr), paddr)
  1035. addr = INET6Address.from_in6_addr(p)
  1036. else:
  1037. raise RSocketError("unknown address family")
  1038. address_list.append(addr)
  1039. i += 1
  1040. paddr = h_addr_list[i]
  1041. return (rffi.charp2str(hostent.c_h_name), aliases, address_list)
  1042. def gethostbyname_ex(name):
  1043. # XXX use gethostbyname_r() if available instead of locks
  1044. addr = gethostbyname(name)
  1045. with _get_netdb_lock():
  1046. hostent = _c.gethostbyname(name)
  1047. return gethost_common(name, hostent, addr)
  1048. def gethostbyaddr(ip):
  1049. # XXX use gethostbyaddr_r() if available, instead of locks
  1050. addr = makeipaddr(ip)
  1051. assert isinstance(addr, IPAddress)
  1052. with _get_netdb_lock():
  1053. p, size = addr.lock_in_addr()
  1054. try:
  1055. hostent = _c.gethostbyaddr(p, size, addr.family)
  1056. finally:
  1057. addr.unlock()
  1058. return gethost_common(ip, hostent, addr)
  1059. # RPython magic to make _netdb_lock turn either into a regular
  1060. # rthread.Lock or a rthread.DummyLock, depending on the config
  1061. def _get_netdb_lock():
  1062. return rthread.dummy_lock
  1063. class _Entry(ExtRegistryEntry):
  1064. _about_ = _get_netdb_lock
  1065. def compute_annotation(self):
  1066. config = self.bookkeeper.annotator.translator.config
  1067. if config.translation.thread:
  1068. fn = _get_netdb_lock_thread
  1069. else:
  1070. fn = _get_netdb_lock_nothread
  1071. return self.bookkeeper.immutablevalue(fn)
  1072. def _get_netdb_lock_nothread():
  1073. return rthread.dummy_lock
  1074. class _LockCache(object):
  1075. lock = None
  1076. _lock_cache = _LockCache()
  1077. @jit.elidable
  1078. def _get_netdb_lock_thread():
  1079. if _lock_cache.lock is None:
  1080. _lock_cache.lock = rthread.allocate_lock()
  1081. return _lock_cache.lock
  1082. # done RPython magic
  1083. def getaddrinfo(host, port_or_service,
  1084. family=AF_UNSPEC, socktype=0, proto=0, flags=0,
  1085. address_to_fill=None):
  1086. # port_or_service is a string, not an int (but try str(port_number)).
  1087. assert port_or_service is None or isinstance(port_or_service, str)
  1088. if _c._MACOSX and flags & AI_NUMERICSERV and \
  1089. (port_or_service is None or port_or_service == '0'):
  1090. port_or_service = '00'
  1091. hints = lltype.malloc(_c.addrinfo, flavor='raw', zero=True)
  1092. rffi.setintfield(hints, 'c_ai_family', family)
  1093. rffi.setintfield(hints, 'c_ai_socktype', socktype)
  1094. rffi.setintfield(hints, 'c_ai_protocol', proto)
  1095. rffi.setintfield(hints, 'c_ai_flags' , flags)
  1096. # XXX need to lock around getaddrinfo() calls?
  1097. p_res = lltype.malloc(rffi.CArray(_c.addrinfo_ptr), 1, flavor='raw')
  1098. error = intmask(_c.getaddrinfo(host, port_or_service, hints, p_res))
  1099. res = p_res[0]
  1100. lltype.free(p_res, flavor='raw')
  1101. lltype.free(hints, flavor='raw')
  1102. if error:
  1103. raise GAIError(error)
  1104. try:
  1105. result = []
  1106. info = res
  1107. while info:
  1108. addr = make_address(info.c_ai_addr,
  1109. rffi.getintfield(info, 'c_ai_addrlen'),
  1110. address_to_fill)
  1111. if info.c_ai_canonname:
  1112. canonname = rffi.charp2str(info.c_ai_canonname)
  1113. else:
  1114. canonname = ""
  1115. result.append((rffi.cast(lltype.Signed, info.c_ai_family),
  1116. rffi.cast(lltype.Signed, info.c_ai_socktype),
  1117. rffi.cast(lltype.Signed, info.c_ai_protocol),
  1118. canonname,
  1119. addr))
  1120. info = info.c_ai_next
  1121. address_to_fill = None # don't fill the same address repeatedly
  1122. finally:
  1123. _c.freeaddrinfo(res)
  1124. return result
  1125. def getservbyname(name, proto=None):
  1126. servent = _c.getservbyname(name, proto)
  1127. if not servent:
  1128. raise RSocketError("service/proto not found")
  1129. port = rffi.getintfield(servent, 'c_s_port')
  1130. return ntohs(port)
  1131. def getservbyport(port, proto=None):
  1132. # This function is only called from pypy/module/_socket and the range of
  1133. # port is checked there
  1134. assert isinstance(port, int)
  1135. servent = _c.getservbyport(htons(port), proto)
  1136. if not servent:
  1137. raise RSocketError("port/proto not found")
  1138. return rffi.charp2str(servent.c_s_name)
  1139. def getprotobyname(name):
  1140. protoent = _c.getprotobyname(name)
  1141. if not protoent:
  1142. raise RSocketError("protocol not found")
  1143. proto = protoent.c_p_proto
  1144. return rffi.cast(lltype.Signed, proto)
  1145. def getnameinfo(address, flags):
  1146. host = lltype.malloc(rffi.CCHARP.TO, NI_MAXHOST, flavor='raw')
  1147. try:
  1148. serv = lltype.malloc(rffi.CCHARP.TO, NI_MAXSERV, flavor='raw')
  1149. try:
  1150. addr = address.lock()
  1151. error = intmask(_c.getnameinfo(addr, address.addrlen,
  1152. host, NI_MAXHOST,
  1153. serv, NI_MAXSERV, flags))
  1154. address.unlock()
  1155. if error:
  1156. raise GAIError(error)
  1157. return rffi.charp2str(host), rffi.charp2str(serv)
  1158. finally:
  1159. lltype.free(serv, flavor='raw')
  1160. finally:
  1161. lltype.free(host, flavor='raw')
  1162. if hasattr(_c, 'inet_aton'):
  1163. def inet_aton(ip):
  1164. "IPv4 dotted string -> packed 32-bits string"
  1165. size = sizeof(_c.in_addr)
  1166. buf = mallocbuf(size)
  1167. try:
  1168. if _c.inet_aton(ip, rffi.cast(lltype.Ptr(_c.in_addr), buf)):
  1169. return ''.join([buf[i] for i in range(size)])
  1170. else:
  1171. raise RSocketError("illegal IP address string passed to inet_aton")
  1172. finally:
  1173. lltype.free(buf, flavor='raw')
  1174. else:
  1175. def inet_aton(ip):
  1176. "IPv4 dotted string -> packed 32-bits string"
  1177. if ip == "255.255.255.255":
  1178. return "\xff\xff\xff\xff"
  1179. packed_addr = _c.inet_addr(ip)
  1180. if packed_addr == rffi.cast(lltype.Unsigned, INADDR_NONE):
  1181. raise RSocketError("illegal IP address string passed to inet_aton")
  1182. size = sizeof(_c.in_addr)
  1183. buf = mallocbuf(size)
  1184. try:
  1185. rffi.cast(rffi.UINTP, buf)[0] = packed_addr
  1186. return ''.join([buf[i] for i in range(size)])
  1187. finally:
  1188. lltype.free(buf, flavor='raw')
  1189. def inet_ntoa(packed):
  1190. "packet 32-bits string -> IPv4 dotted string"
  1191. if len(packed) != sizeof(_c.in_addr):
  1192. raise RSocketError("packed IP wrong length for inet_ntoa")
  1193. buf = rffi.make(_c.in_addr)
  1194. try:
  1195. for i in range(sizeof(_c.in_addr)):
  1196. rffi.cast(rffi.CCHARP, buf)[i] = packed[i]
  1197. return rffi.charp2str(_c.inet_ntoa(buf))
  1198. finally:
  1199. lltype.free(buf, flavor='raw')
  1200. if hasattr(_c, 'inet_pton'):
  1201. def inet_pton(family, ip):
  1202. "human-readable string -> packed string"
  1203. if family == AF_INET:

Large files files are truncated, but you can click here to view the full file