nativesockets.nim 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Dominik Picheta
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a low-level cross-platform sockets interface. Look
  10. ## at the ``net`` module for the higher-level version.
  11. # TODO: Clean up the exports a bit and everything else in general.
  12. import os, options
  13. when hostOS == "solaris":
  14. {.passl: "-lsocket -lnsl".}
  15. const useWinVersion = defined(Windows) or defined(nimdoc)
  16. when useWinVersion:
  17. import winlean
  18. export WSAEWOULDBLOCK, WSAECONNRESET, WSAECONNABORTED, WSAENETRESET,
  19. WSANOTINITIALISED, WSAENOTSOCK, WSAEINPROGRESS, WSAEINTR,
  20. WSAEDISCON, ERROR_NETNAME_DELETED
  21. else:
  22. import posix
  23. export fcntl, F_GETFL, O_NONBLOCK, F_SETFL, EAGAIN, EWOULDBLOCK, MSG_NOSIGNAL,
  24. EINTR, EINPROGRESS, ECONNRESET, EPIPE, ENETRESET, EBADF
  25. export Sockaddr_storage, Sockaddr_un, Sockaddr_un_path_length
  26. export SocketHandle, Sockaddr_in, Addrinfo, INADDR_ANY, SockAddr, SockLen,
  27. Sockaddr_in6, Sockaddr_storage,
  28. inet_ntoa, recv, `==`, connect, send, accept, recvfrom, sendto,
  29. freeAddrInfo
  30. export
  31. SO_ERROR,
  32. SOL_SOCKET,
  33. SOMAXCONN,
  34. SO_ACCEPTCONN, SO_BROADCAST, SO_DEBUG, SO_DONTROUTE,
  35. SO_KEEPALIVE, SO_OOBINLINE, SO_REUSEADDR, SO_REUSEPORT,
  36. MSG_PEEK
  37. when defined(macosx) and not defined(nimdoc):
  38. export SO_NOSIGPIPE
  39. type
  40. Port* = distinct uint16 ## port type
  41. Domain* = enum ## domain, which specifies the protocol family of the
  42. ## created socket. Other domains than those that are listed
  43. ## here are unsupported.
  44. AF_UNSPEC = 0, ## unspecified domain (can be detected automatically by
  45. ## some procedures, such as getaddrinfo)
  46. AF_UNIX = 1, ## for local socket (using a file). Unsupported on Windows.
  47. AF_INET = 2, ## for network protocol IPv4 or
  48. AF_INET6 = when defined(macosx): 30 else: 23 ## for network protocol IPv6.
  49. SockType* = enum ## second argument to `socket` proc
  50. SOCK_STREAM = 1, ## reliable stream-oriented service or Stream Sockets
  51. SOCK_DGRAM = 2, ## datagram service or Datagram Sockets
  52. SOCK_RAW = 3, ## raw protocols atop the network layer.
  53. SOCK_SEQPACKET = 5 ## reliable sequenced packet service
  54. Protocol* = enum ## third argument to `socket` proc
  55. IPPROTO_TCP = 6, ## Transmission control protocol.
  56. IPPROTO_UDP = 17, ## User datagram protocol.
  57. IPPROTO_IP, ## Internet protocol. Unsupported on Windows.
  58. IPPROTO_IPV6, ## Internet Protocol Version 6. Unsupported on Windows.
  59. IPPROTO_RAW, ## Raw IP Packets Protocol. Unsupported on Windows.
  60. IPPROTO_ICMP ## Control message protocol. Unsupported on Windows.
  61. Servent* = object ## information about a service
  62. name*: string
  63. aliases*: seq[string]
  64. port*: Port
  65. proto*: string
  66. Hostent* = object ## information about a given host
  67. name*: string
  68. aliases*: seq[string]
  69. addrtype*: Domain
  70. length*: int
  71. addrList*: seq[string]
  72. when useWinVersion:
  73. let
  74. osInvalidSocket* = winlean.INVALID_SOCKET
  75. const
  76. IOCPARM_MASK* = 127
  77. IOC_IN* = int(-2147483648)
  78. FIONBIO* = IOC_IN.int32 or ((sizeof(int32) and IOCPARM_MASK) shl 16) or
  79. (102 shl 8) or 126
  80. nativeAfInet = winlean.AF_INET
  81. nativeAfInet6 = winlean.AF_INET6
  82. proc ioctlsocket*(s: SocketHandle, cmd: clong,
  83. argptr: ptr clong): cint {.
  84. stdcall, importc: "ioctlsocket", dynlib: "ws2_32.dll".}
  85. else:
  86. let
  87. osInvalidSocket* = posix.INVALID_SOCKET
  88. nativeAfInet = posix.AF_INET
  89. nativeAfInet6 = posix.AF_INET6
  90. proc `==`*(a, b: Port): bool {.borrow.}
  91. ## ``==`` for ports.
  92. proc `$`*(p: Port): string {.borrow.}
  93. ## returns the port number as a string
  94. proc toInt*(domain: Domain): cint
  95. ## Converts the Domain enum to a platform-dependent ``cint``.
  96. proc toInt*(typ: SockType): cint
  97. ## Converts the SockType enum to a platform-dependent ``cint``.
  98. proc toInt*(p: Protocol): cint
  99. ## Converts the Protocol enum to a platform-dependent ``cint``.
  100. when not useWinVersion:
  101. proc toInt(domain: Domain): cint =
  102. case domain
  103. of AF_UNSPEC: result = posix.AF_UNSPEC.cint
  104. of AF_UNIX: result = posix.AF_UNIX.cint
  105. of AF_INET: result = posix.AF_INET.cint
  106. of AF_INET6: result = posix.AF_INET6.cint
  107. proc toKnownDomain*(family: cint): Option[Domain] =
  108. ## Converts the platform-dependent ``cint`` to the Domain or none(),
  109. ## if the ``cint`` is not known.
  110. result = if family == posix.AF_UNSPEC: some(Domain.AF_UNSPEC)
  111. elif family == posix.AF_UNIX: some(Domain.AF_UNIX)
  112. elif family == posix.AF_INET: some(Domain.AF_INET)
  113. elif family == posix.AF_INET6: some(Domain.AF_INET6)
  114. else: none(Domain)
  115. proc toInt(typ: SockType): cint =
  116. case typ
  117. of SOCK_STREAM: result = posix.SOCK_STREAM
  118. of SOCK_DGRAM: result = posix.SOCK_DGRAM
  119. of SOCK_SEQPACKET: result = posix.SOCK_SEQPACKET
  120. of SOCK_RAW: result = posix.SOCK_RAW
  121. proc toInt(p: Protocol): cint =
  122. case p
  123. of IPPROTO_TCP: result = posix.IPPROTO_TCP
  124. of IPPROTO_UDP: result = posix.IPPROTO_UDP
  125. of IPPROTO_IP: result = posix.IPPROTO_IP
  126. of IPPROTO_IPV6: result = posix.IPPROTO_IPV6
  127. of IPPROTO_RAW: result = posix.IPPROTO_RAW
  128. of IPPROTO_ICMP: result = posix.IPPROTO_ICMP
  129. else:
  130. proc toInt(domain: Domain): cint =
  131. result = toU32(ord(domain)).cint
  132. proc toKnownDomain*(family: cint): Option[Domain] =
  133. ## Converts the platform-dependent ``cint`` to the Domain or none(),
  134. ## if the ``cint`` is not known.
  135. result = if family == winlean.AF_UNSPEC: some(Domain.AF_UNSPEC)
  136. elif family == winlean.AF_INET: some(Domain.AF_INET)
  137. elif family == winlean.AF_INET6: some(Domain.AF_INET6)
  138. else: none(Domain)
  139. proc toInt(typ: SockType): cint =
  140. result = cint(ord(typ))
  141. proc toInt(p: Protocol): cint =
  142. result = cint(ord(p))
  143. proc toSockType*(protocol: Protocol): SockType =
  144. result = case protocol
  145. of IPPROTO_TCP:
  146. SOCK_STREAM
  147. of IPPROTO_UDP:
  148. SOCK_DGRAM
  149. of IPPROTO_IP, IPPROTO_IPV6, IPPROTO_RAW, IPPROTO_ICMP:
  150. SOCK_RAW
  151. proc createNativeSocket*(domain: Domain = AF_INET,
  152. sockType: SockType = SOCK_STREAM,
  153. protocol: Protocol = IPPROTO_TCP): SocketHandle =
  154. ## Creates a new socket; returns `osInvalidSocket` if an error occurs.
  155. socket(toInt(domain), toInt(sockType), toInt(protocol))
  156. proc createNativeSocket*(domain: cint, sockType: cint,
  157. protocol: cint): SocketHandle =
  158. ## Creates a new socket; returns `osInvalidSocket` if an error occurs.
  159. ##
  160. ## Use this overload if one of the enums specified above does
  161. ## not contain what you need.
  162. socket(domain, sockType, protocol)
  163. proc newNativeSocket*(domain: Domain = AF_INET,
  164. sockType: SockType = SOCK_STREAM,
  165. protocol: Protocol = IPPROTO_TCP): SocketHandle
  166. {.deprecated.} =
  167. ## Creates a new socket; returns `osInvalidSocket` if an error occurs.
  168. ##
  169. ## **Deprecated since v0.18.0:** Use ``createNativeSocket`` instead.
  170. createNativeSocket(domain, sockType, protocol)
  171. proc newNativeSocket*(domain: cint, sockType: cint,
  172. protocol: cint): SocketHandle
  173. {.deprecated.} =
  174. ## Creates a new socket; returns `osInvalidSocket` if an error occurs.
  175. ##
  176. ## Use this overload if one of the enums specified above does
  177. ## not contain what you need.
  178. ##
  179. ## **Deprecated since v0.18.0:** Use ``createNativeSocket`` instead.
  180. createNativeSocket(domain, sockType, protocol)
  181. proc close*(socket: SocketHandle) =
  182. ## closes a socket.
  183. when useWinVersion:
  184. discard winlean.closesocket(socket)
  185. else:
  186. discard posix.close(socket)
  187. # TODO: These values should not be discarded. An OSError should be raised.
  188. # http://stackoverflow.com/questions/12463473/what-happens-if-you-call-close-on-a-bsd-socket-multiple-times
  189. proc bindAddr*(socket: SocketHandle, name: ptr SockAddr, namelen: SockLen): cint =
  190. result = bindSocket(socket, name, namelen)
  191. proc listen*(socket: SocketHandle, backlog = SOMAXCONN): cint {.tags: [ReadIOEffect].} =
  192. ## Marks ``socket`` as accepting connections.
  193. ## ``Backlog`` specifies the maximum length of the
  194. ## queue of pending connections.
  195. when useWinVersion:
  196. result = winlean.listen(socket, cint(backlog))
  197. else:
  198. result = posix.listen(socket, cint(backlog))
  199. proc getAddrInfo*(address: string, port: Port, domain: Domain = AF_INET,
  200. sockType: SockType = SOCK_STREAM,
  201. protocol: Protocol = IPPROTO_TCP): ptr AddrInfo =
  202. ##
  203. ##
  204. ## **Warning**: The resulting ``ptr AddrInfo`` must be freed using ``freeAddrInfo``!
  205. var hints: AddrInfo
  206. result = nil
  207. hints.ai_family = toInt(domain)
  208. hints.ai_socktype = toInt(sockType)
  209. hints.ai_protocol = toInt(protocol)
  210. # OpenBSD doesn't support AI_V4MAPPED and doesn't define the macro AI_V4MAPPED.
  211. # FreeBSD, Haiku don't support AI_V4MAPPED but defines the macro.
  212. # https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=198092
  213. # https://dev.haiku-os.org/ticket/14323
  214. when not defined(freebsd) and not defined(openbsd) and not defined(netbsd) and not defined(android) and not defined(haiku):
  215. if domain == AF_INET6:
  216. hints.ai_flags = AI_V4MAPPED
  217. var gaiResult = getaddrinfo(address, $port, addr(hints), result)
  218. if gaiResult != 0'i32:
  219. when useWinVersion:
  220. raiseOSError(osLastError())
  221. else:
  222. raiseOSError(osLastError(), $gai_strerror(gaiResult))
  223. proc dealloc*(ai: ptr AddrInfo) {.deprecated.} =
  224. ## Deprecated since 0.16.2. Use ``freeAddrInfo`` instead.
  225. freeaddrinfo(ai)
  226. proc ntohl*(x: uint32): uint32 =
  227. ## Converts 32-bit unsigned integers from network to host byte order.
  228. ## On machines where the host byte order is the same as network byte order,
  229. ## this is a no-op; otherwise, it performs a 4-byte swap operation.
  230. when cpuEndian == bigEndian: result = x
  231. else: result = (x shr 24'u32) or
  232. (x shr 8'u32 and 0xff00'u32) or
  233. (x shl 8'u32 and 0xff0000'u32) or
  234. (x shl 24'u32)
  235. template ntohl*(x: int32): untyped {.deprecated.} =
  236. ## Converts 32-bit integers from network to host byte order.
  237. ## On machines where the host byte order is the same as network byte order,
  238. ## this is a no-op; otherwise, it performs a 4-byte swap operation.
  239. ## **Warning**: This template is deprecated since 0.14.0, IPv4
  240. ## addresses are now treated as unsigned integers. Please use the unsigned
  241. ## version of this template.
  242. cast[int32](nativesockets.ntohl(cast[uint32](x)))
  243. proc ntohs*(x: uint16): uint16 =
  244. ## Converts 16-bit unsigned integers from network to host byte order. On
  245. ## machines where the host byte order is the same as network byte order,
  246. ## this is a no-op; otherwise, it performs a 2-byte swap operation.
  247. when cpuEndian == bigEndian: result = x
  248. else: result = (x shr 8'u16) or (x shl 8'u16)
  249. template ntohs*(x: int16): untyped {.deprecated.} =
  250. ## Converts 16-bit integers from network to host byte order. On
  251. ## machines where the host byte order is the same as network byte order,
  252. ## this is a no-op; otherwise, it performs a 2-byte swap operation.
  253. ## **Warning**: This template is deprecated since 0.14.0, where port
  254. ## numbers became unsigned integers. Please use the unsigned version of
  255. ## this template.
  256. cast[int16](nativesockets.ntohs(cast[uint16](x)))
  257. template htonl*(x: int32): untyped {.deprecated.} =
  258. ## Converts 32-bit integers from host to network byte order. On machines
  259. ## where the host byte order is the same as network byte order, this is
  260. ## a no-op; otherwise, it performs a 4-byte swap operation.
  261. ## **Warning**: This template is deprecated since 0.14.0, IPv4
  262. ## addresses are now treated as unsigned integers. Please use the unsigned
  263. ## version of this template.
  264. nativesockets.ntohl(x)
  265. template htonl*(x: uint32): untyped =
  266. ## Converts 32-bit unsigned integers from host to network byte order. On
  267. ## machines where the host byte order is the same as network byte order,
  268. ## this is a no-op; otherwise, it performs a 4-byte swap operation.
  269. nativesockets.ntohl(x)
  270. template htons*(x: int16): untyped {.deprecated.} =
  271. ## Converts 16-bit integers from host to network byte order.
  272. ## On machines where the host byte order is the same as network byte
  273. ## order, this is a no-op; otherwise, it performs a 2-byte swap operation.
  274. ## **Warning**: This template is deprecated since 0.14.0, where port
  275. ## numbers became unsigned integers. Please use the unsigned version of
  276. ## this template.
  277. nativesockets.ntohs(x)
  278. template htons*(x: uint16): untyped =
  279. ## Converts 16-bit unsigned integers from host to network byte order.
  280. ## On machines where the host byte order is the same as network byte
  281. ## order, this is a no-op; otherwise, it performs a 2-byte swap operation.
  282. nativesockets.ntohs(x)
  283. proc getServByName*(name, proto: string): Servent {.tags: [ReadIOEffect].} =
  284. ## Searches the database from the beginning and finds the first entry for
  285. ## which the service name specified by ``name`` matches the s_name member
  286. ## and the protocol name specified by ``proto`` matches the s_proto member.
  287. ##
  288. ## On posix this will search through the ``/etc/services`` file.
  289. when useWinVersion:
  290. var s = winlean.getservbyname(name, proto)
  291. else:
  292. var s = posix.getservbyname(name, proto)
  293. if s == nil: raiseOSError(osLastError(), "Service not found.")
  294. result.name = $s.s_name
  295. result.aliases = cstringArrayToSeq(s.s_aliases)
  296. result.port = Port(s.s_port)
  297. result.proto = $s.s_proto
  298. proc getServByPort*(port: Port, proto: string): Servent {.tags: [ReadIOEffect].} =
  299. ## Searches the database from the beginning and finds the first entry for
  300. ## which the port specified by ``port`` matches the s_port member and the
  301. ## protocol name specified by ``proto`` matches the s_proto member.
  302. ##
  303. ## On posix this will search through the ``/etc/services`` file.
  304. when useWinVersion:
  305. var s = winlean.getservbyport(ze(int16(port)).cint, proto)
  306. else:
  307. var s = posix.getservbyport(ze(int16(port)).cint, proto)
  308. if s == nil: raiseOSError(osLastError(), "Service not found.")
  309. result.name = $s.s_name
  310. result.aliases = cstringArrayToSeq(s.s_aliases)
  311. result.port = Port(s.s_port)
  312. result.proto = $s.s_proto
  313. proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
  314. ## This function will lookup the hostname of an IP Address.
  315. var myaddr: InAddr
  316. myaddr.s_addr = inet_addr(ip)
  317. when useWinVersion:
  318. var s = winlean.gethostbyaddr(addr(myaddr), sizeof(myaddr).cuint,
  319. cint(AF_INET))
  320. if s == nil: raiseOSError(osLastError())
  321. else:
  322. var s =
  323. when defined(android4):
  324. posix.gethostbyaddr(cast[cstring](addr(myaddr)), sizeof(myaddr).cint,
  325. cint(posix.AF_INET))
  326. else:
  327. posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).Socklen,
  328. cint(posix.AF_INET))
  329. if s == nil:
  330. raiseOSError(osLastError(), $hstrerror(h_errno))
  331. result.name = $s.h_name
  332. result.aliases = cstringArrayToSeq(s.h_aliases)
  333. when useWinVersion:
  334. result.addrtype = Domain(s.h_addrtype)
  335. else:
  336. if s.h_addrtype == posix.AF_INET:
  337. result.addrtype = AF_INET
  338. elif s.h_addrtype == posix.AF_INET6:
  339. result.addrtype = AF_INET6
  340. else:
  341. raiseOSError(osLastError(), "unknown h_addrtype")
  342. if result.addrtype == AF_INET:
  343. result.addrlist = @[]
  344. var i = 0
  345. while not isNil(s.h_addrlist[i]):
  346. var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i])
  347. result.addrlist.add($inet_ntoa(inaddr_ptr[]))
  348. inc(i)
  349. else:
  350. result.addrList = cstringArrayToSeq(s.h_addr_list)
  351. result.length = int(s.h_length)
  352. proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} =
  353. ## This function will lookup the IP address of a hostname.
  354. when useWinVersion:
  355. var s = winlean.gethostbyname(name)
  356. else:
  357. var s = posix.gethostbyname(name)
  358. if s == nil: raiseOSError(osLastError())
  359. result.name = $s.h_name
  360. result.aliases = cstringArrayToSeq(s.h_aliases)
  361. when useWinVersion:
  362. result.addrtype = Domain(s.h_addrtype)
  363. else:
  364. if s.h_addrtype == posix.AF_INET:
  365. result.addrtype = AF_INET
  366. elif s.h_addrtype == posix.AF_INET6:
  367. result.addrtype = AF_INET6
  368. else:
  369. raiseOSError(osLastError(), "unknown h_addrtype")
  370. if result.addrtype == AF_INET:
  371. result.addrlist = @[]
  372. var i = 0
  373. while not isNil(s.h_addrlist[i]):
  374. var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i])
  375. result.addrlist.add($inet_ntoa(inaddr_ptr[]))
  376. inc(i)
  377. else:
  378. result.addrList = cstringArrayToSeq(s.h_addr_list)
  379. result.length = int(s.h_length)
  380. proc getHostname*(): string {.tags: [ReadIOEffect].} =
  381. ## Returns the local hostname (not the FQDN)
  382. # https://tools.ietf.org/html/rfc1035#section-2.3.1
  383. # https://tools.ietf.org/html/rfc2181#section-11
  384. const size = 64
  385. result = newString(size)
  386. when useWinVersion:
  387. let success = winlean.getHostname(result, size)
  388. else:
  389. # Posix
  390. let success = posix.getHostname(result, size)
  391. if success != 0.cint:
  392. raiseOSError(osLastError())
  393. let x = len(cstring(result))
  394. result.setLen(x)
  395. proc getSockDomain*(socket: SocketHandle): Domain =
  396. ## returns the socket's domain (AF_INET or AF_INET6).
  397. var name: Sockaddr_in6
  398. var namelen = sizeof(name).SockLen
  399. if getsockname(socket, cast[ptr SockAddr](addr(name)),
  400. addr(namelen)) == -1'i32:
  401. raiseOSError(osLastError())
  402. try:
  403. result = toKnownDomain(name.sin6_family.cint).get()
  404. except UnpackError:
  405. raise newException(IOError, "Unknown socket family in getSockDomain")
  406. proc getAddrString*(sockAddr: ptr SockAddr): string =
  407. ## return the string representation of address within sockAddr
  408. if sockAddr.sa_family.cint == nativeAfInet:
  409. result = $inet_ntoa(cast[ptr Sockaddr_in](sockAddr).sin_addr)
  410. elif sockAddr.sa_family.cint == nativeAfInet6:
  411. let addrLen = when not useWinVersion: posix.INET6_ADDRSTRLEN
  412. else: 46 # it's actually 46 in both cases
  413. result = newString(addrLen)
  414. let addr6 = addr cast[ptr Sockaddr_in6](sockAddr).sin6_addr
  415. when not useWinVersion:
  416. if posix.inet_ntop(posix.AF_INET6, addr6, addr result[0],
  417. result.len.int32) == nil:
  418. raiseOSError(osLastError())
  419. if posix.IN6_IS_ADDR_V4MAPPED(addr6) != 0:
  420. result = result.substr("::ffff:".len)
  421. else:
  422. if winlean.inet_ntop(winlean.AF_INET6, addr6, addr result[0],
  423. result.len.int32) == nil:
  424. raiseOSError(osLastError())
  425. setLen(result, len(cstring(result)))
  426. else:
  427. raise newException(IOError, "Unknown socket family in getAddrString")
  428. proc getSockName*(socket: SocketHandle): Port =
  429. ## returns the socket's associated port number.
  430. var name: Sockaddr_in
  431. when useWinVersion:
  432. name.sin_family = uint16(ord(AF_INET))
  433. else:
  434. name.sin_family = uint16(posix.AF_INET)
  435. #name.sin_port = htons(cint16(port))
  436. #name.sin_addr.s_addr = htonl(INADDR_ANY)
  437. var namelen = sizeof(name).SockLen
  438. if getsockname(socket, cast[ptr SockAddr](addr(name)),
  439. addr(namelen)) == -1'i32:
  440. raiseOSError(osLastError())
  441. result = Port(nativesockets.ntohs(name.sin_port))
  442. proc getLocalAddr*(socket: SocketHandle, domain: Domain): (string, Port) =
  443. ## returns the socket's local address and port number.
  444. ##
  445. ## Similar to POSIX's `getsockname`:idx:.
  446. case domain
  447. of AF_INET:
  448. var name: Sockaddr_in
  449. when useWinVersion:
  450. name.sin_family = uint16(ord(AF_INET))
  451. else:
  452. name.sin_family = uint16(posix.AF_INET)
  453. var namelen = sizeof(name).SockLen
  454. if getsockname(socket, cast[ptr SockAddr](addr(name)),
  455. addr(namelen)) == -1'i32:
  456. raiseOSError(osLastError())
  457. result = ($inet_ntoa(name.sin_addr),
  458. Port(nativesockets.ntohs(name.sin_port)))
  459. of AF_INET6:
  460. var name: Sockaddr_in6
  461. when useWinVersion:
  462. name.sin6_family = uint16(ord(AF_INET6))
  463. else:
  464. name.sin6_family = uint16(posix.AF_INET6)
  465. var namelen = sizeof(name).SockLen
  466. if getsockname(socket, cast[ptr SockAddr](addr(name)),
  467. addr(namelen)) == -1'i32:
  468. raiseOSError(osLastError())
  469. # Cannot use INET6_ADDRSTRLEN here, because it's a C define.
  470. result[0] = newString(64)
  471. if inet_ntop(name.sin6_family.cint,
  472. addr name.sin6_addr, addr result[0][0], (result[0].len+1).int32).isNil:
  473. raiseOSError(osLastError())
  474. setLen(result[0], result[0].cstring.len)
  475. result[1] = Port(nativesockets.ntohs(name.sin6_port))
  476. else:
  477. raiseOSError(OSErrorCode(-1), "invalid socket family in getLocalAddr")
  478. proc getPeerAddr*(socket: SocketHandle, domain: Domain): (string, Port) =
  479. ## returns the socket's peer address and port number.
  480. ##
  481. ## Similar to POSIX's `getpeername`:idx:
  482. case domain
  483. of AF_INET:
  484. var name: Sockaddr_in
  485. when useWinVersion:
  486. name.sin_family = uint16(ord(AF_INET))
  487. else:
  488. name.sin_family = uint16(posix.AF_INET)
  489. var namelen = sizeof(name).SockLen
  490. if getpeername(socket, cast[ptr SockAddr](addr(name)),
  491. addr(namelen)) == -1'i32:
  492. raiseOSError(osLastError())
  493. result = ($inet_ntoa(name.sin_addr),
  494. Port(nativesockets.ntohs(name.sin_port)))
  495. of AF_INET6:
  496. var name: Sockaddr_in6
  497. when useWinVersion:
  498. name.sin6_family = uint16(ord(AF_INET6))
  499. else:
  500. name.sin6_family = uint16(posix.AF_INET6)
  501. var namelen = sizeof(name).SockLen
  502. if getpeername(socket, cast[ptr SockAddr](addr(name)),
  503. addr(namelen)) == -1'i32:
  504. raiseOSError(osLastError())
  505. # Cannot use INET6_ADDRSTRLEN here, because it's a C define.
  506. result[0] = newString(64)
  507. if inet_ntop(name.sin6_family.cint,
  508. addr name.sin6_addr, addr result[0][0], (result[0].len+1).int32).isNil:
  509. raiseOSError(osLastError())
  510. setLen(result[0], result[0].cstring.len)
  511. result[1] = Port(nativesockets.ntohs(name.sin6_port))
  512. else:
  513. raiseOSError(OSErrorCode(-1), "invalid socket family in getLocalAddr")
  514. proc getSockOptInt*(socket: SocketHandle, level, optname: int): int {.
  515. tags: [ReadIOEffect].} =
  516. ## getsockopt for integer options.
  517. var res: cint
  518. var size = sizeof(res).SockLen
  519. if getsockopt(socket, cint(level), cint(optname),
  520. addr(res), addr(size)) < 0'i32:
  521. raiseOSError(osLastError())
  522. result = int(res)
  523. proc setSockOptInt*(socket: SocketHandle, level, optname, optval: int) {.
  524. tags: [WriteIOEffect].} =
  525. ## setsockopt for integer options.
  526. var value = cint(optval)
  527. if setsockopt(socket, cint(level), cint(optname), addr(value),
  528. sizeof(value).SockLen) < 0'i32:
  529. raiseOSError(osLastError())
  530. proc setBlocking*(s: SocketHandle, blocking: bool) =
  531. ## Sets blocking mode on socket.
  532. ##
  533. ## Raises OSError on error.
  534. when useWinVersion:
  535. var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking
  536. if ioctlsocket(s, FIONBIO, addr(mode)) == -1:
  537. raiseOSError(osLastError())
  538. else: # BSD sockets
  539. var x: int = fcntl(s, F_GETFL, 0)
  540. if x == -1:
  541. raiseOSError(osLastError())
  542. else:
  543. var mode = if blocking: x and not O_NONBLOCK else: x or O_NONBLOCK
  544. if fcntl(s, F_SETFL, mode) == -1:
  545. raiseOSError(osLastError())
  546. proc timeValFromMilliseconds(timeout = 500): Timeval =
  547. if timeout != -1:
  548. var seconds = timeout div 1000
  549. when useWinVersion:
  550. result.tv_sec = seconds.int32
  551. result.tv_usec = ((timeout - seconds * 1000) * 1000).int32
  552. else:
  553. result.tv_sec = seconds.Time
  554. result.tv_usec = ((timeout - seconds * 1000) * 1000).Suseconds
  555. proc createFdSet(fd: var TFdSet, s: seq[SocketHandle], m: var int) =
  556. FD_ZERO(fd)
  557. for i in items(s):
  558. m = max(m, int(i))
  559. FD_SET(i, fd)
  560. proc pruneSocketSet(s: var seq[SocketHandle], fd: var TFdSet) =
  561. var i = 0
  562. var L = s.len
  563. while i < L:
  564. if FD_ISSET(s[i], fd) == 0'i32:
  565. s[i] = s[L-1]
  566. dec(L)
  567. else:
  568. inc(i)
  569. setLen(s, L)
  570. proc select*(readfds: var seq[SocketHandle], timeout = 500): int {.deprecated: "use selectRead instead".} =
  571. ## When a socket in ``readfds`` is ready to be read from then a non-zero
  572. ## value will be returned specifying the count of the sockets which can be
  573. ## read from. The sockets which can be read from will also be removed
  574. ## from ``readfds``.
  575. ##
  576. ## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
  577. ## an unlimited time.
  578. ## **Warning:** This is deprecated since version 0.16.2.
  579. ## Use the ``selectRead`` procedure instead.
  580. var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
  581. var rd: TFdSet
  582. var m = 0
  583. createFdSet((rd), readfds, m)
  584. if timeout != -1:
  585. result = int(select(cint(m+1), addr(rd), nil, nil, addr(tv)))
  586. else:
  587. result = int(select(cint(m+1), addr(rd), nil, nil, nil))
  588. pruneSocketSet(readfds, (rd))
  589. proc selectRead*(readfds: var seq[SocketHandle], timeout = 500): int =
  590. ## When a socket in ``readfds`` is ready to be read from then a non-zero
  591. ## value will be returned specifying the count of the sockets which can be
  592. ## read from. The sockets which can be read from will also be removed
  593. ## from ``readfds``.
  594. ##
  595. ## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
  596. ## an unlimited time.
  597. var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
  598. var rd: TFdSet
  599. var m = 0
  600. createFdSet((rd), readfds, m)
  601. if timeout != -1:
  602. result = int(select(cint(m+1), addr(rd), nil, nil, addr(tv)))
  603. else:
  604. result = int(select(cint(m+1), addr(rd), nil, nil, nil))
  605. pruneSocketSet(readfds, (rd))
  606. proc selectWrite*(writefds: var seq[SocketHandle],
  607. timeout = 500): int {.tags: [ReadIOEffect].} =
  608. ## When a socket in ``writefds`` is ready to be written to then a non-zero
  609. ## value will be returned specifying the count of the sockets which can be
  610. ## written to. The sockets which can be written to will also be removed
  611. ## from ``writefds``.
  612. ##
  613. ## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
  614. ## an unlimited time.
  615. var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
  616. var wr: TFdSet
  617. var m = 0
  618. createFdSet((wr), writefds, m)
  619. if timeout != -1:
  620. result = int(select(cint(m+1), nil, addr(wr), nil, addr(tv)))
  621. else:
  622. result = int(select(cint(m+1), nil, addr(wr), nil, nil))
  623. pruneSocketSet(writefds, (wr))
  624. proc accept*(fd: SocketHandle): (SocketHandle, string) =
  625. ## Accepts a new client connection.
  626. ##
  627. ## Returns (osInvalidSocket, "") if an error occurred.
  628. var sockAddress: Sockaddr_in
  629. var addrLen = sizeof(sockAddress).SockLen
  630. var sock = accept(fd, cast[ptr SockAddr](addr(sockAddress)),
  631. addr(addrLen))
  632. if sock == osInvalidSocket:
  633. return (osInvalidSocket, "")
  634. else:
  635. return (sock, $inet_ntoa(sockAddress.sin_addr))
  636. when defined(Windows):
  637. var wsa: WSAData
  638. if wsaStartup(0x0101'i16, addr wsa) != 0: raiseOSError(osLastError())