PageRenderTime 91ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/rlib/rsocket.py

https://bitbucket.org/dac_io/pypy
Python | 1427 lines | 1402 code | 13 blank | 12 comment | 9 complexity | 51125b8be9cba0a92f0842813767dd14 MD5 | raw file

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

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