net.nim 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174
  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 high-level cross-platform sockets interface.
  10. ## The procedures implemented in this module are primarily for blocking sockets.
  11. ## For asynchronous non-blocking sockets use the `asyncnet` module together
  12. ## with the `asyncdispatch` module.
  13. ##
  14. ## The first thing you will always need to do in order to start using sockets,
  15. ## is to create a new instance of the `Socket` type using the `newSocket`
  16. ## procedure.
  17. ##
  18. ## SSL
  19. ## ====
  20. ##
  21. ## In order to use the SSL procedures defined in this module, you will need to
  22. ## compile your application with the `-d:ssl` flag. See the
  23. ## `newContext<net.html#newContext%2Cstring%2Cstring%2Cstring%2Cstring>`_
  24. ## procedure for additional details.
  25. ##
  26. ##
  27. ## SSL on Windows
  28. ## ==============
  29. ##
  30. ## On Windows the SSL library checks for valid certificates.
  31. ## It uses the `cacert.pem` file for this purpose which was extracted
  32. ## from `https://curl.se/ca/cacert.pem`. Besides
  33. ## the OpenSSL DLLs (e.g. libssl-1_1-x64.dll, libcrypto-1_1-x64.dll) you
  34. ## also need to ship `cacert.pem` with your `.exe` file.
  35. ##
  36. ##
  37. ## Examples
  38. ## ========
  39. ##
  40. ## Connecting to a server
  41. ## ----------------------
  42. ##
  43. ## After you create a socket with the `newSocket` procedure, you can easily
  44. ## connect it to a server running at a known hostname (or IP address) and port.
  45. ## To do so over TCP, use the example below.
  46. runnableExamples("-r:off"):
  47. let socket = newSocket()
  48. socket.connect("google.com", Port(80))
  49. ## For SSL, use the following example:
  50. runnableExamples("-r:off -d:ssl"):
  51. let socket = newSocket()
  52. let ctx = newContext()
  53. wrapSocket(ctx, socket)
  54. socket.connect("google.com", Port(443))
  55. ## UDP is a connectionless protocol, so UDP sockets don't have to explicitly
  56. ## call the `connect <net.html#connect%2CSocket%2Cstring>`_ procedure. They can
  57. ## simply start sending data immediately.
  58. runnableExamples("-r:off"):
  59. let socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  60. socket.sendTo("192.168.0.1", Port(27960), "status\n")
  61. runnableExamples("-r:off"):
  62. let socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  63. let ip = parseIpAddress("192.168.0.1")
  64. doAssert socket.sendTo(ip, Port(27960), "status\c\l") == 8
  65. ## Creating a server
  66. ## -----------------
  67. ##
  68. ## After you create a socket with the `newSocket` procedure, you can create a
  69. ## TCP server by calling the `bindAddr` and `listen` procedures.
  70. runnableExamples("-r:off"):
  71. let socket = newSocket()
  72. socket.bindAddr(Port(1234))
  73. socket.listen()
  74. # You can then begin accepting connections using the `accept` procedure.
  75. var client: Socket
  76. var address = ""
  77. while true:
  78. socket.acceptAddr(client, address)
  79. echo "Client connected from: ", address
  80. import std/private/since
  81. when defined(nimPreviewSlimSystem):
  82. import std/assertions
  83. import nativesockets
  84. import os, strutils, times, sets, options, std/monotimes
  85. import ssl_config
  86. export nativesockets.Port, nativesockets.`$`, nativesockets.`==`
  87. export Domain, SockType, Protocol
  88. const useWinVersion = defined(windows) or defined(nimdoc)
  89. const useNimNetLite = defined(nimNetLite) or defined(freertos) or defined(zephyr) or
  90. defined(nuttx)
  91. const defineSsl = defined(ssl) or defined(nimdoc)
  92. when useWinVersion:
  93. from winlean import WSAESHUTDOWN
  94. when defineSsl:
  95. import openssl
  96. when not defined(nimDisableCertificateValidation):
  97. from ssl_certs import scanSSLCertificates
  98. # Note: The enumerations are mapped to Window's constants.
  99. when defineSsl:
  100. type
  101. Certificate* = string ## DER encoded certificate
  102. SslError* = object of CatchableError
  103. SslCVerifyMode* = enum
  104. CVerifyNone, CVerifyPeer, CVerifyPeerUseEnvVars
  105. SslProtVersion* = enum
  106. protSSLv2, protSSLv3, protTLSv1, protSSLv23
  107. SslContext* = ref object
  108. context*: SslCtx
  109. referencedData: HashSet[int]
  110. extraInternal: SslContextExtraInternal
  111. SslAcceptResult* = enum
  112. AcceptNoClient = 0, AcceptNoHandshake, AcceptSuccess
  113. SslHandshakeType* = enum
  114. handshakeAsClient, handshakeAsServer
  115. SslClientGetPskFunc* = proc(hint: string): tuple[identity: string, psk: string]
  116. SslServerGetPskFunc* = proc(identity: string): string
  117. SslContextExtraInternal = ref object of RootRef
  118. serverGetPskFunc: SslServerGetPskFunc
  119. clientGetPskFunc: SslClientGetPskFunc
  120. else:
  121. type
  122. SslContext* = ref object # TODO: Workaround #4797.
  123. const
  124. BufferSize*: int = 4000 ## size of a buffered socket's buffer
  125. MaxLineLength* = 1_000_000
  126. type
  127. SocketImpl* = object ## socket type
  128. fd: SocketHandle
  129. isBuffered: bool # determines whether this socket is buffered.
  130. buffer: array[0..BufferSize, char]
  131. currPos: int # current index in buffer
  132. bufLen: int # current length of buffer
  133. when defineSsl:
  134. isSsl: bool
  135. sslHandle: SslPtr
  136. sslContext: SslContext
  137. sslNoHandshake: bool # True if needs handshake.
  138. sslHasPeekChar: bool
  139. sslPeekChar: char
  140. sslNoShutdown: bool # True if shutdown shouldn't be done.
  141. lastError: OSErrorCode ## stores the last error on this socket
  142. domain: Domain
  143. sockType: SockType
  144. protocol: Protocol
  145. Socket* = ref SocketImpl
  146. SOBool* = enum ## Boolean socket options.
  147. OptAcceptConn, OptBroadcast, OptDebug, OptDontRoute, OptKeepAlive,
  148. OptOOBInline, OptReuseAddr, OptReusePort, OptNoDelay
  149. ReadLineResult* = enum ## result for readLineAsync
  150. ReadFullLine, ReadPartialLine, ReadDisconnected, ReadNone
  151. TimeoutError* = object of CatchableError
  152. SocketFlag* {.pure.} = enum
  153. Peek,
  154. SafeDisconn ## Ensures disconnection exceptions (ECONNRESET, EPIPE etc) are not thrown.
  155. when defined(nimHasStyleChecks):
  156. {.push styleChecks: off.}
  157. type
  158. IpAddressFamily* {.pure.} = enum ## Describes the type of an IP address
  159. IPv6, ## IPv6 address
  160. IPv4 ## IPv4 address
  161. IpAddress* = object ## stores an arbitrary IP address
  162. case family*: IpAddressFamily ## the type of the IP address (IPv4 or IPv6)
  163. of IpAddressFamily.IPv6:
  164. address_v6*: array[0..15, uint8] ## Contains the IP address in bytes in
  165. ## case of IPv6
  166. of IpAddressFamily.IPv4:
  167. address_v4*: array[0..3, uint8] ## Contains the IP address in bytes in
  168. ## case of IPv4
  169. when defined(nimHasStyleChecks):
  170. {.pop.}
  171. when defined(posix) and not defined(lwip):
  172. from posix import TPollfd, POLLIN, POLLPRI, POLLOUT, POLLWRBAND, Tnfds
  173. template monitorPollEvent(x: var SocketHandle, y: cint, timeout: int): int =
  174. var tpollfd: TPollfd
  175. tpollfd.fd = cast[cint](x)
  176. tpollfd.events = y
  177. posix.poll(addr(tpollfd), Tnfds(1), timeout)
  178. proc timeoutRead(fd: var SocketHandle, timeout = 500): int =
  179. when defined(windows) or defined(lwip):
  180. var fds = @[fd]
  181. selectRead(fds, timeout)
  182. else:
  183. monitorPollEvent(fd, POLLIN or POLLPRI, timeout)
  184. proc timeoutWrite(fd: var SocketHandle, timeout = 500): int =
  185. when defined(windows) or defined(lwip):
  186. var fds = @[fd]
  187. selectWrite(fds, timeout)
  188. else:
  189. monitorPollEvent(fd, POLLOUT or POLLWRBAND, timeout)
  190. proc socketError*(socket: Socket, err: int = -1, async = false,
  191. lastError = (-1).OSErrorCode,
  192. flags: set[SocketFlag] = {}) {.gcsafe.}
  193. proc isDisconnectionError*(flags: set[SocketFlag],
  194. lastError: OSErrorCode): bool =
  195. ## Determines whether `lastError` is a disconnection error. Only does this
  196. ## if flags contains `SafeDisconn`.
  197. when useWinVersion:
  198. SocketFlag.SafeDisconn in flags and
  199. (lastError.int32 == WSAECONNRESET or
  200. lastError.int32 == WSAECONNABORTED or
  201. lastError.int32 == WSAENETRESET or
  202. lastError.int32 == WSAEDISCON or
  203. lastError.int32 == WSAESHUTDOWN or
  204. lastError.int32 == ERROR_NETNAME_DELETED)
  205. else:
  206. SocketFlag.SafeDisconn in flags and
  207. (lastError.int32 == ECONNRESET or
  208. lastError.int32 == EPIPE or
  209. lastError.int32 == ENETRESET)
  210. proc toOSFlags*(socketFlags: set[SocketFlag]): cint =
  211. ## Converts the flags into the underlying OS representation.
  212. for f in socketFlags:
  213. case f
  214. of SocketFlag.Peek:
  215. result = result or MSG_PEEK
  216. of SocketFlag.SafeDisconn: continue
  217. proc newSocket*(fd: SocketHandle, domain: Domain = AF_INET,
  218. sockType: SockType = SOCK_STREAM,
  219. protocol: Protocol = IPPROTO_TCP, buffered = true): owned(Socket) =
  220. ## Creates a new socket as specified by the params.
  221. assert fd != osInvalidSocket
  222. result = Socket(
  223. fd: fd,
  224. isBuffered: buffered,
  225. domain: domain,
  226. sockType: sockType,
  227. protocol: protocol)
  228. if buffered:
  229. result.currPos = 0
  230. # Set SO_NOSIGPIPE on OS X.
  231. when defined(macosx) and not defined(nimdoc):
  232. setSockOptInt(fd, SOL_SOCKET, SO_NOSIGPIPE, 1)
  233. proc newSocket*(domain, sockType, protocol: cint, buffered = true,
  234. inheritable = defined(nimInheritHandles)): owned(Socket) =
  235. ## Creates a new socket.
  236. ##
  237. ## The SocketHandle associated with the resulting Socket will not be
  238. ## inheritable by child processes by default. This can be changed via
  239. ## the `inheritable` parameter.
  240. ##
  241. ## If an error occurs OSError will be raised.
  242. let fd = createNativeSocket(domain, sockType, protocol, inheritable)
  243. if fd == osInvalidSocket:
  244. raiseOSError(osLastError())
  245. result = newSocket(fd, domain.Domain, sockType.SockType, protocol.Protocol,
  246. buffered)
  247. proc newSocket*(domain: Domain = AF_INET, sockType: SockType = SOCK_STREAM,
  248. protocol: Protocol = IPPROTO_TCP, buffered = true,
  249. inheritable = defined(nimInheritHandles)): owned(Socket) =
  250. ## Creates a new socket.
  251. ##
  252. ## The SocketHandle associated with the resulting Socket will not be
  253. ## inheritable by child processes by default. This can be changed via
  254. ## the `inheritable` parameter.
  255. ##
  256. ## If an error occurs OSError will be raised.
  257. let fd = createNativeSocket(domain, sockType, protocol, inheritable)
  258. if fd == osInvalidSocket:
  259. raiseOSError(osLastError())
  260. result = newSocket(fd, domain, sockType, protocol, buffered)
  261. proc parseIPv4Address(addressStr: string): IpAddress =
  262. ## Parses IPv4 addresses
  263. ## Raises ValueError on errors
  264. var
  265. byteCount = 0
  266. currentByte: uint16 = 0
  267. separatorValid = false
  268. leadingZero = false
  269. result = IpAddress(family: IpAddressFamily.IPv4)
  270. for i in 0 .. high(addressStr):
  271. if addressStr[i] in strutils.Digits: # Character is a number
  272. if leadingZero:
  273. raise newException(ValueError,
  274. "Invalid IP address. Octal numbers are not allowed")
  275. currentByte = currentByte * 10 +
  276. cast[uint16](ord(addressStr[i]) - ord('0'))
  277. if currentByte == 0'u16:
  278. leadingZero = true
  279. elif currentByte > 255'u16:
  280. raise newException(ValueError,
  281. "Invalid IP Address. Value is out of range")
  282. separatorValid = true
  283. elif addressStr[i] == '.': # IPv4 address separator
  284. if not separatorValid or byteCount >= 3:
  285. raise newException(ValueError,
  286. "Invalid IP Address. The address consists of too many groups")
  287. result.address_v4[byteCount] = cast[uint8](currentByte)
  288. currentByte = 0
  289. byteCount.inc
  290. separatorValid = false
  291. leadingZero = false
  292. else:
  293. raise newException(ValueError,
  294. "Invalid IP Address. Address contains an invalid character")
  295. if byteCount != 3 or not separatorValid:
  296. raise newException(ValueError, "Invalid IP Address")
  297. result.address_v4[byteCount] = cast[uint8](currentByte)
  298. proc parseIPv6Address(addressStr: string): IpAddress =
  299. ## Parses IPv6 addresses
  300. ## Raises ValueError on errors
  301. result = IpAddress(family: IpAddressFamily.IPv6)
  302. if addressStr.len < 2:
  303. raise newException(ValueError, "Invalid IP Address")
  304. var
  305. groupCount = 0
  306. currentGroupStart = 0
  307. currentShort: uint32 = 0
  308. separatorValid = true
  309. dualColonGroup = -1
  310. lastWasColon = false
  311. v4StartPos = -1
  312. byteCount = 0
  313. for i, c in addressStr:
  314. if c == ':':
  315. if not separatorValid:
  316. raise newException(ValueError,
  317. "Invalid IP Address. Address contains an invalid separator")
  318. if lastWasColon:
  319. if dualColonGroup != -1:
  320. raise newException(ValueError,
  321. "Invalid IP Address. Address contains more than one \"::\" separator")
  322. dualColonGroup = groupCount
  323. separatorValid = false
  324. elif i != 0 and i != high(addressStr):
  325. if groupCount >= 8:
  326. raise newException(ValueError,
  327. "Invalid IP Address. The address consists of too many groups")
  328. result.address_v6[groupCount*2] = cast[uint8](currentShort shr 8)
  329. result.address_v6[groupCount*2+1] = cast[uint8](currentShort and 0xFF)
  330. currentShort = 0
  331. groupCount.inc()
  332. if dualColonGroup != -1: separatorValid = false
  333. elif i == 0: # only valid if address starts with ::
  334. if addressStr[1] != ':':
  335. raise newException(ValueError,
  336. "Invalid IP Address. Address may not start with \":\"")
  337. else: # i == high(addressStr) - only valid if address ends with ::
  338. if addressStr[high(addressStr)-1] != ':':
  339. raise newException(ValueError,
  340. "Invalid IP Address. Address may not end with \":\"")
  341. lastWasColon = true
  342. currentGroupStart = i + 1
  343. elif c == '.': # Switch to parse IPv4 mode
  344. if i < 3 or not separatorValid or groupCount >= 7:
  345. raise newException(ValueError, "Invalid IP Address")
  346. v4StartPos = currentGroupStart
  347. currentShort = 0
  348. separatorValid = false
  349. break
  350. elif c in strutils.HexDigits:
  351. if c in strutils.Digits: # Normal digit
  352. currentShort = (currentShort shl 4) + cast[uint32](ord(c) - ord('0'))
  353. elif c >= 'a' and c <= 'f': # Lower case hex
  354. currentShort = (currentShort shl 4) + cast[uint32](ord(c) - ord('a')) + 10
  355. else: # Upper case hex
  356. currentShort = (currentShort shl 4) + cast[uint32](ord(c) - ord('A')) + 10
  357. if currentShort > 65535'u32:
  358. raise newException(ValueError,
  359. "Invalid IP Address. Value is out of range")
  360. lastWasColon = false
  361. separatorValid = true
  362. else:
  363. raise newException(ValueError,
  364. "Invalid IP Address. Address contains an invalid character")
  365. if v4StartPos == -1: # Don't parse v4. Copy the remaining v6 stuff
  366. if separatorValid: # Copy remaining data
  367. if groupCount >= 8:
  368. raise newException(ValueError,
  369. "Invalid IP Address. The address consists of too many groups")
  370. result.address_v6[groupCount*2] = cast[uint8](currentShort shr 8)
  371. result.address_v6[groupCount*2+1] = cast[uint8](currentShort and 0xFF)
  372. groupCount.inc()
  373. else: # Must parse IPv4 address
  374. var leadingZero = false
  375. for i, c in addressStr[v4StartPos..high(addressStr)]:
  376. if c in strutils.Digits: # Character is a number
  377. if leadingZero:
  378. raise newException(ValueError,
  379. "Invalid IP address. Octal numbers not allowed")
  380. currentShort = currentShort * 10 + cast[uint32](ord(c) - ord('0'))
  381. if currentShort == 0'u32:
  382. leadingZero = true
  383. elif currentShort > 255'u32:
  384. raise newException(ValueError,
  385. "Invalid IP Address. Value is out of range")
  386. separatorValid = true
  387. elif c == '.': # IPv4 address separator
  388. if not separatorValid or byteCount >= 3:
  389. raise newException(ValueError, "Invalid IP Address")
  390. result.address_v6[groupCount*2 + byteCount] = cast[uint8](currentShort)
  391. currentShort = 0
  392. byteCount.inc()
  393. separatorValid = false
  394. leadingZero = false
  395. else: # Invalid character
  396. raise newException(ValueError,
  397. "Invalid IP Address. Address contains an invalid character")
  398. if byteCount != 3 or not separatorValid:
  399. raise newException(ValueError, "Invalid IP Address")
  400. result.address_v6[groupCount*2 + byteCount] = cast[uint8](currentShort)
  401. groupCount += 2
  402. # Shift and fill zeros in case of ::
  403. if groupCount > 8:
  404. raise newException(ValueError,
  405. "Invalid IP Address. The address consists of too many groups")
  406. elif groupCount < 8: # must fill
  407. if dualColonGroup == -1:
  408. raise newException(ValueError,
  409. "Invalid IP Address. The address consists of too few groups")
  410. var toFill = 8 - groupCount # The number of groups to fill
  411. var toShift = groupCount - dualColonGroup # Nr of known groups after ::
  412. for i in 0..2*toShift-1: # shift
  413. result.address_v6[15-i] = result.address_v6[groupCount*2-i-1]
  414. for i in 0..2*toFill-1: # fill with 0s
  415. result.address_v6[dualColonGroup*2+i] = 0
  416. elif dualColonGroup != -1:
  417. raise newException(ValueError,
  418. "Invalid IP Address. The address consists of too many groups")
  419. proc parseIpAddress*(addressStr: string): IpAddress =
  420. ## Parses an IP address
  421. ##
  422. ## Raises ValueError on error.
  423. ##
  424. ## For IPv4 addresses, only the strict form as
  425. ## defined in RFC 6943 is considered valid, see
  426. ## https://datatracker.ietf.org/doc/html/rfc6943#section-3.1.1.
  427. if addressStr.len == 0:
  428. raise newException(ValueError, "IP Address string is empty")
  429. if addressStr.contains(':'):
  430. return parseIPv6Address(addressStr)
  431. else:
  432. return parseIPv4Address(addressStr)
  433. proc isIpAddress*(addressStr: string): bool {.tags: [].} =
  434. ## Checks if a string is an IP address
  435. ## Returns true if it is, false otherwise
  436. try:
  437. discard parseIpAddress(addressStr)
  438. except ValueError:
  439. return false
  440. return true
  441. proc toSockAddr*(address: IpAddress, port: Port, sa: var Sockaddr_storage,
  442. sl: var SockLen) =
  443. ## Converts `IpAddress` and `Port` to `SockAddr` and `SockLen`
  444. let port = htons(uint16(port))
  445. case address.family
  446. of IpAddressFamily.IPv4:
  447. sl = sizeof(Sockaddr_in).SockLen
  448. let s = cast[ptr Sockaddr_in](addr sa)
  449. s.sin_family = typeof(s.sin_family)(toInt(AF_INET))
  450. s.sin_port = port
  451. copyMem(addr s.sin_addr, unsafeAddr address.address_v4[0],
  452. sizeof(s.sin_addr))
  453. of IpAddressFamily.IPv6:
  454. sl = sizeof(Sockaddr_in6).SockLen
  455. let s = cast[ptr Sockaddr_in6](addr sa)
  456. s.sin6_family = typeof(s.sin6_family)(toInt(AF_INET6))
  457. s.sin6_port = port
  458. copyMem(addr s.sin6_addr, unsafeAddr address.address_v6[0],
  459. sizeof(s.sin6_addr))
  460. proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: SockLen,
  461. address: var IpAddress, port: var Port) =
  462. if sa.ss_family.cint == toInt(AF_INET) and sl == sizeof(Sockaddr_in).SockLen:
  463. address = IpAddress(family: IpAddressFamily.IPv4)
  464. let s = cast[ptr Sockaddr_in](sa)
  465. copyMem(addr address.address_v4[0], addr s.sin_addr,
  466. sizeof(address.address_v4))
  467. port = ntohs(s.sin_port).Port
  468. elif sa.ss_family.cint == toInt(AF_INET6) and
  469. sl == sizeof(Sockaddr_in6).SockLen:
  470. address = IpAddress(family: IpAddressFamily.IPv6)
  471. let s = cast[ptr Sockaddr_in6](sa)
  472. copyMem(addr address.address_v6[0], addr s.sin6_addr,
  473. sizeof(address.address_v6))
  474. port = ntohs(s.sin6_port).Port
  475. else:
  476. raise newException(ValueError, "Neither IPv4 nor IPv6")
  477. proc fromSockAddr*(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6,
  478. sl: SockLen, address: var IpAddress, port: var Port) {.inline.} =
  479. ## Converts `SockAddr` and `SockLen` to `IpAddress` and `Port`. Raises
  480. ## `ObjectConversionDefect` in case of invalid `sa` and `sl` arguments.
  481. fromSockAddrAux(cast[ptr Sockaddr_storage](unsafeAddr sa), sl, address, port)
  482. when defineSsl:
  483. # OpenSSL >= 1.1.0 does not need explicit init.
  484. when not useOpenssl3:
  485. CRYPTO_malloc_init()
  486. doAssert SslLibraryInit() == 1
  487. SSL_load_error_strings()
  488. ERR_load_BIO_strings()
  489. OpenSSL_add_all_algorithms()
  490. proc sslHandle*(self: Socket): SslPtr =
  491. ## Retrieve the ssl pointer of `socket`.
  492. ## Useful for interfacing with `openssl`.
  493. self.sslHandle
  494. proc raiseSSLError*(s = "") {.raises: [SslError].}=
  495. ## Raises a new SSL error.
  496. if s != "":
  497. raise newException(SslError, s)
  498. let err = ERR_peek_last_error()
  499. if err == 0:
  500. raise newException(SslError, "No error reported.")
  501. var errStr = $ERR_error_string(err, nil)
  502. case err
  503. of 336032814, 336032784:
  504. errStr = "Please upgrade your OpenSSL library, it does not support the " &
  505. "necessary protocols. OpenSSL error is: " & errStr
  506. else:
  507. discard
  508. raise newException(SslError, errStr)
  509. proc getExtraData*(ctx: SslContext, index: int): RootRef =
  510. ## Retrieves arbitrary data stored inside SslContext.
  511. if index notin ctx.referencedData:
  512. raise newException(IndexDefect, "No data with that index.")
  513. let res = ctx.context.SSL_CTX_get_ex_data(index.cint)
  514. if cast[int](res) == 0:
  515. raiseSSLError()
  516. return cast[RootRef](res)
  517. proc setExtraData*(ctx: SslContext, index: int, data: RootRef) =
  518. ## Stores arbitrary data inside SslContext. The unique `index`
  519. ## should be retrieved using getSslContextExtraDataIndex.
  520. if index in ctx.referencedData:
  521. GC_unref(getExtraData(ctx, index))
  522. if ctx.context.SSL_CTX_set_ex_data(index.cint, cast[pointer](data)) == -1:
  523. raiseSSLError()
  524. if index notin ctx.referencedData:
  525. ctx.referencedData.incl(index)
  526. GC_ref(data)
  527. # http://simplestcodings.blogspot.co.uk/2010/08/secure-server-client-using-openssl-in-c.html
  528. proc loadCertificates(ctx: SslCtx, certFile, keyFile: string) =
  529. if certFile != "" and not fileExists(certFile):
  530. raise newException(system.IOError,
  531. "Certificate file could not be found: " & certFile)
  532. if keyFile != "" and not fileExists(keyFile):
  533. raise newException(system.IOError, "Key file could not be found: " & keyFile)
  534. if certFile != "":
  535. var ret = SSL_CTX_use_certificate_chain_file(ctx, certFile)
  536. if ret != 1:
  537. raiseSSLError()
  538. # TODO: Password? www.rtfm.com/openssl-examples/part1.pdf
  539. if keyFile != "":
  540. if SSL_CTX_use_PrivateKey_file(ctx, keyFile,
  541. SSL_FILETYPE_PEM) != 1:
  542. raiseSSLError()
  543. if SSL_CTX_check_private_key(ctx) != 1:
  544. raiseSSLError("Verification of private key file failed.")
  545. proc newContext*(protVersion = protSSLv23, verifyMode = CVerifyPeer,
  546. certFile = "", keyFile = "", cipherList = CiphersIntermediate,
  547. caDir = "", caFile = "", ciphersuites = CiphersModern): SslContext =
  548. ## Creates an SSL context.
  549. ##
  550. ## Protocol version is currently ignored by default and TLS is used.
  551. ## With `-d:openssl10`, only SSLv23 and TLSv1 may be used.
  552. ##
  553. ## There are three options for verify mode:
  554. ## `CVerifyNone`: certificates are not verified;
  555. ## `CVerifyPeer`: certificates are verified;
  556. ## `CVerifyPeerUseEnvVars`: certificates are verified and the optional
  557. ## environment variables SSL_CERT_FILE and SSL_CERT_DIR are also used to
  558. ## locate certificates
  559. ##
  560. ## The `nimDisableCertificateValidation` define overrides verifyMode and
  561. ## disables certificate verification globally!
  562. ##
  563. ## CA certificates will be loaded, in the following order, from:
  564. ##
  565. ## - caFile, caDir, parameters, if set
  566. ## - if `verifyMode` is set to `CVerifyPeerUseEnvVars`,
  567. ## the SSL_CERT_FILE and SSL_CERT_DIR environment variables are used
  568. ## - a set of files and directories from the `ssl_certs <ssl_certs.html>`_ file.
  569. ##
  570. ## The last two parameters specify the certificate file path and the key file
  571. ## path, a server socket will most likely not work without these.
  572. ##
  573. ## Certificates can be generated using the following command:
  574. ## - `openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout mykey.pem -out mycert.pem`
  575. ## or using ECDSA:
  576. ## - `openssl ecparam -out mykey.pem -name secp256k1 -genkey`
  577. ## - `openssl req -new -key mykey.pem -x509 -nodes -days 365 -out mycert.pem`
  578. var mtd: PSSL_METHOD
  579. when defined(openssl10):
  580. case protVersion
  581. of protSSLv23:
  582. mtd = SSLv23_method()
  583. of protSSLv2:
  584. raiseSSLError("SSLv2 is no longer secure and has been deprecated, use protSSLv23")
  585. of protSSLv3:
  586. raiseSSLError("SSLv3 is no longer secure and has been deprecated, use protSSLv23")
  587. of protTLSv1:
  588. mtd = TLSv1_method()
  589. else:
  590. mtd = TLS_method()
  591. if mtd == nil:
  592. raiseSSLError("Failed to create TLS context")
  593. var newCTX = SSL_CTX_new(mtd)
  594. if newCTX == nil:
  595. raiseSSLError("Failed to create TLS context")
  596. if newCTX.SSL_CTX_set_cipher_list(cipherList) != 1:
  597. raiseSSLError()
  598. when not defined(openssl10) and not defined(libressl):
  599. let sslVersion = getOpenSSLVersion()
  600. if sslVersion >= 0x010101000 and sslVersion != 0x020000000:
  601. # In OpenSSL >= 1.1.1, TLSv1.3 cipher suites can only be configured via
  602. # this API.
  603. if newCTX.SSL_CTX_set_ciphersuites(ciphersuites) != 1:
  604. raiseSSLError()
  605. # Automatically the best ECDH curve for client exchange. Without this, ECDH
  606. # ciphers will be ignored by the server.
  607. #
  608. # From OpenSSL >= 1.1.0, this setting is set by default and can't be
  609. # overridden.
  610. if newCTX.SSL_CTX_set_ecdh_auto(1) != 1:
  611. raiseSSLError()
  612. when defined(nimDisableCertificateValidation):
  613. newCTX.SSL_CTX_set_verify(SSL_VERIFY_NONE, nil)
  614. else:
  615. case verifyMode
  616. of CVerifyPeer, CVerifyPeerUseEnvVars:
  617. newCTX.SSL_CTX_set_verify(SSL_VERIFY_PEER, nil)
  618. of CVerifyNone:
  619. newCTX.SSL_CTX_set_verify(SSL_VERIFY_NONE, nil)
  620. if newCTX == nil:
  621. raiseSSLError()
  622. discard newCTX.SSLCTXSetMode(SSL_MODE_AUTO_RETRY)
  623. newCTX.loadCertificates(certFile, keyFile)
  624. const VerifySuccess = 1 # SSL_CTX_load_verify_locations returns 1 on success.
  625. when not defined(nimDisableCertificateValidation):
  626. if verifyMode != CVerifyNone:
  627. # Use the caDir and caFile parameters if set
  628. if caDir != "" or caFile != "":
  629. if newCTX.SSL_CTX_load_verify_locations(if caFile == "": nil else: caFile.cstring, if caDir == "": nil else: caDir.cstring) != VerifySuccess:
  630. raise newException(IOError, "Failed to load SSL/TLS CA certificate(s).")
  631. else:
  632. # Scan for certs in known locations. For CVerifyPeerUseEnvVars also scan
  633. # the SSL_CERT_FILE and SSL_CERT_DIR env vars
  634. var found = false
  635. let useEnvVars = (if verifyMode == CVerifyPeerUseEnvVars: true else: false)
  636. for fn in scanSSLCertificates(useEnvVars = useEnvVars):
  637. if fn.extractFilename == "":
  638. if newCTX.SSL_CTX_load_verify_locations(nil, cstring(fn.normalizePathEnd(false))) == VerifySuccess:
  639. found = true
  640. break
  641. elif newCTX.SSL_CTX_load_verify_locations(cstring(fn), nil) == VerifySuccess:
  642. found = true
  643. break
  644. if not found:
  645. raise newException(IOError, "No SSL/TLS CA certificates found.")
  646. result = SslContext(context: newCTX, referencedData: initHashSet[int](),
  647. extraInternal: new(SslContextExtraInternal))
  648. proc getExtraInternal(ctx: SslContext): SslContextExtraInternal =
  649. return ctx.extraInternal
  650. proc destroyContext*(ctx: SslContext) =
  651. ## Free memory referenced by SslContext.
  652. # We assume here that OpenSSL's internal indexes increase by 1 each time.
  653. # That means we can assume that the next internal index is the length of
  654. # extra data indexes.
  655. for i in ctx.referencedData:
  656. GC_unref(getExtraData(ctx, i))
  657. ctx.context.SSL_CTX_free()
  658. proc `pskIdentityHint=`*(ctx: SslContext, hint: string) =
  659. ## Sets the identity hint passed to server.
  660. ##
  661. ## Only used in PSK ciphersuites.
  662. if ctx.context.SSL_CTX_use_psk_identity_hint(hint) <= 0:
  663. raiseSSLError()
  664. proc clientGetPskFunc*(ctx: SslContext): SslClientGetPskFunc =
  665. return ctx.getExtraInternal().clientGetPskFunc
  666. proc pskClientCallback(ssl: SslPtr; hint: cstring; identity: cstring;
  667. max_identity_len: cuint; psk: ptr uint8;
  668. max_psk_len: cuint): cuint {.cdecl.} =
  669. let ctx = SslContext(context: ssl.SSL_get_SSL_CTX)
  670. let hintString = if hint == nil: "" else: $hint
  671. let (identityString, pskString) = (ctx.clientGetPskFunc)(hintString)
  672. if pskString.len.cuint > max_psk_len:
  673. return 0
  674. if identityString.len.cuint >= max_identity_len:
  675. return 0
  676. copyMem(identity, identityString.cstring, identityString.len + 1) # with the last zero byte
  677. copyMem(psk, pskString.cstring, pskString.len)
  678. return pskString.len.cuint
  679. proc `clientGetPskFunc=`*(ctx: SslContext, fun: SslClientGetPskFunc) =
  680. ## Sets function that returns the client identity and the PSK based on identity
  681. ## hint from the server.
  682. ##
  683. ## Only used in PSK ciphersuites.
  684. ctx.getExtraInternal().clientGetPskFunc = fun
  685. ctx.context.SSL_CTX_set_psk_client_callback(
  686. if fun == nil: nil else: pskClientCallback)
  687. proc serverGetPskFunc*(ctx: SslContext): SslServerGetPskFunc =
  688. return ctx.getExtraInternal().serverGetPskFunc
  689. proc pskServerCallback(ssl: SslCtx; identity: cstring; psk: ptr uint8;
  690. max_psk_len: cint): cuint {.cdecl.} =
  691. let ctx = SslContext(context: ssl.SSL_get_SSL_CTX)
  692. let pskString = (ctx.serverGetPskFunc)($identity)
  693. if pskString.len.cint > max_psk_len:
  694. return 0
  695. copyMem(psk, pskString.cstring, pskString.len)
  696. return pskString.len.cuint
  697. proc `serverGetPskFunc=`*(ctx: SslContext, fun: SslServerGetPskFunc) =
  698. ## Sets function that returns PSK based on the client identity.
  699. ##
  700. ## Only used in PSK ciphersuites.
  701. ctx.getExtraInternal().serverGetPskFunc = fun
  702. ctx.context.SSL_CTX_set_psk_server_callback(if fun == nil: nil
  703. else: pskServerCallback)
  704. proc getPskIdentity*(socket: Socket): string =
  705. ## Gets the PSK identity provided by the client.
  706. assert socket.isSsl
  707. return $(socket.sslHandle.SSL_get_psk_identity)
  708. proc wrapSocket*(ctx: SslContext, socket: Socket) =
  709. ## Wraps a socket in an SSL context. This function effectively turns
  710. ## `socket` into an SSL socket.
  711. ##
  712. ## This must be called on an unconnected socket; an SSL session will
  713. ## be started when the socket is connected.
  714. ##
  715. ## FIXME:
  716. ## **Disclaimer**: This code is not well tested, may be very unsafe and
  717. ## prone to security vulnerabilities.
  718. assert(not socket.isSsl)
  719. socket.isSsl = true
  720. socket.sslContext = ctx
  721. socket.sslHandle = SSL_new(socket.sslContext.context)
  722. socket.sslNoHandshake = false
  723. socket.sslHasPeekChar = false
  724. socket.sslNoShutdown = false
  725. if socket.sslHandle == nil:
  726. raiseSSLError()
  727. if SSL_set_fd(socket.sslHandle, socket.fd) != 1:
  728. raiseSSLError()
  729. proc checkCertName(socket: Socket, hostname: string) {.raises: [SslError], tags:[RootEffect].} =
  730. ## Check if the certificate Subject Alternative Name (SAN) or Subject CommonName (CN) matches hostname.
  731. ## Wildcards match only in the left-most label.
  732. ## When name starts with a dot it will be matched by a certificate valid for any subdomain
  733. when not defined(nimDisableCertificateValidation) and not defined(windows):
  734. assert socket.isSsl
  735. try:
  736. let certificate = socket.sslHandle.SSL_get_peer_certificate()
  737. if certificate.isNil:
  738. raiseSSLError("No SSL certificate found.")
  739. const X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT = 0x1.cuint
  740. # https://www.openssl.org/docs/man1.1.1/man3/X509_check_host.html
  741. let match = certificate.X509_check_host(hostname.cstring, hostname.len.cint,
  742. X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, nil)
  743. # https://www.openssl.org/docs/man1.1.1/man3/SSL_get_peer_certificate.html
  744. X509_free(certificate)
  745. if match != 1:
  746. raiseSSLError("SSL Certificate check failed.")
  747. except LibraryError:
  748. raiseSSLError("SSL import failed")
  749. proc wrapConnectedSocket*(ctx: SslContext, socket: Socket,
  750. handshake: SslHandshakeType,
  751. hostname: string = "") =
  752. ## Wraps a connected socket in an SSL context. This function effectively
  753. ## turns `socket` into an SSL socket.
  754. ## `hostname` should be specified so that the client knows which hostname
  755. ## the server certificate should be validated against.
  756. ##
  757. ## This should be called on a connected socket, and will perform
  758. ## an SSL handshake immediately.
  759. ##
  760. ## FIXME:
  761. ## **Disclaimer**: This code is not well tested, may be very unsafe and
  762. ## prone to security vulnerabilities.
  763. wrapSocket(ctx, socket)
  764. case handshake
  765. of handshakeAsClient:
  766. if hostname.len > 0 and not isIpAddress(hostname):
  767. # Discard result in case OpenSSL version doesn't support SNI, or we're
  768. # not using TLSv1+
  769. discard SSL_set_tlsext_host_name(socket.sslHandle, hostname)
  770. ErrClearError()
  771. let ret = SSL_connect(socket.sslHandle)
  772. socketError(socket, ret)
  773. when not defined(nimDisableCertificateValidation) and not defined(windows):
  774. # FIXME: this should be skipped on CVerifyNone
  775. if hostname.len > 0 and not isIpAddress(hostname):
  776. socket.checkCertName(hostname)
  777. of handshakeAsServer:
  778. ErrClearError()
  779. let ret = SSL_accept(socket.sslHandle)
  780. socketError(socket, ret)
  781. proc getPeerCertificates*(sslHandle: SslPtr): seq[Certificate] {.since: (1, 1).} =
  782. ## Returns the certificate chain received by the peer we are connected to
  783. ## through the OpenSSL connection represented by `sslHandle`.
  784. ## The handshake must have been completed and the certificate chain must
  785. ## have been verified successfully or else an empty sequence is returned.
  786. ## The chain is ordered from leaf certificate to root certificate.
  787. result = newSeq[Certificate]()
  788. if SSL_get_verify_result(sslHandle) != X509_V_OK:
  789. return
  790. let stack = SSL_get0_verified_chain(sslHandle)
  791. if stack == nil:
  792. return
  793. let length = OPENSSL_sk_num(stack)
  794. if length == 0:
  795. return
  796. for i in 0 .. length - 1:
  797. let x509 = cast[PX509](OPENSSL_sk_value(stack, i))
  798. result.add(i2d_X509(x509))
  799. proc getPeerCertificates*(socket: Socket): seq[Certificate] {.since: (1, 1).} =
  800. ## Returns the certificate chain received by the peer we are connected to
  801. ## through the given socket.
  802. ## The handshake must have been completed and the certificate chain must
  803. ## have been verified successfully or else an empty sequence is returned.
  804. ## The chain is ordered from leaf certificate to root certificate.
  805. if not socket.isSsl:
  806. result = newSeq[Certificate]()
  807. else:
  808. result = getPeerCertificates(socket.sslHandle)
  809. proc `sessionIdContext=`*(ctx: SslContext, sidCtx: string) =
  810. ## Sets the session id context in which a session can be reused.
  811. ## Used for permitting clients to reuse a session id instead of
  812. ## doing a new handshake.
  813. ##
  814. ## TLS clients might attempt to resume a session using the session id context,
  815. ## thus it must be set if verifyMode is set to CVerifyPeer or CVerifyPeerUseEnvVars,
  816. ## otherwise the connection will fail and SslError will be raised if resumption occurs.
  817. ##
  818. ## - Only useful if set server-side.
  819. ## - Should be unique per-application to prevent clients from malfunctioning.
  820. ## - sidCtx must be at most 32 characters in length.
  821. if sidCtx.len > 32:
  822. raiseSSLError("sessionIdContext must be shorter than 32 characters")
  823. SSL_CTX_set_session_id_context(ctx.context, sidCtx, sidCtx.len)
  824. proc getSocketError*(socket: Socket): OSErrorCode =
  825. ## Checks `osLastError` for a valid error. If it has been reset it uses
  826. ## the last error stored in the socket object.
  827. result = osLastError()
  828. if result == 0.OSErrorCode:
  829. result = socket.lastError
  830. if result == 0.OSErrorCode:
  831. raiseOSError(result, "No valid socket error code available")
  832. proc socketError*(socket: Socket, err: int = -1, async = false,
  833. lastError = (-1).OSErrorCode,
  834. flags: set[SocketFlag] = {}) =
  835. ## Raises an OSError based on the error code returned by `SSL_get_error`
  836. ## (for SSL sockets) and `osLastError` otherwise.
  837. ##
  838. ## If `async` is `true` no error will be thrown in the case when the
  839. ## error was caused by no data being available to be read.
  840. ##
  841. ## If `err` is not lower than 0 no exception will be raised.
  842. ##
  843. ## If `flags` contains `SafeDisconn`, no exception will be raised
  844. ## when the error was caused by a peer disconnection.
  845. when defineSsl:
  846. if socket.isSsl:
  847. if err <= 0:
  848. var ret = SSL_get_error(socket.sslHandle, err.cint)
  849. case ret
  850. of SSL_ERROR_ZERO_RETURN:
  851. raiseSSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
  852. of SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT:
  853. if async:
  854. return
  855. else: raiseSSLError("Not enough data on socket.")
  856. of SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_READ:
  857. if async:
  858. return
  859. else: raiseSSLError("Not enough data on socket.")
  860. of SSL_ERROR_WANT_X509_LOOKUP:
  861. raiseSSLError("Function for x509 lookup has been called.")
  862. of SSL_ERROR_SYSCALL:
  863. # SSL shutdown must not be done if a fatal error occurred.
  864. socket.sslNoShutdown = true
  865. let osErr = osLastError()
  866. if not flags.isDisconnectionError(osErr):
  867. var errStr = "IO error has occurred "
  868. let sslErr = ERR_peek_last_error()
  869. if sslErr == 0 and err == 0:
  870. errStr.add "because an EOF was observed that violates the protocol"
  871. elif sslErr == 0 and err == -1:
  872. errStr.add "in the BIO layer"
  873. else:
  874. let errStr = $ERR_error_string(sslErr, nil)
  875. raiseSSLError(errStr & ": " & errStr)
  876. raiseOSError(osErr, errStr)
  877. of SSL_ERROR_SSL:
  878. # SSL shutdown must not be done if a fatal error occurred.
  879. socket.sslNoShutdown = true
  880. raiseSSLError()
  881. else: raiseSSLError("Unknown Error")
  882. if err == -1 and not (when defineSsl: socket.isSsl else: false):
  883. var lastE = if lastError.int == -1: getSocketError(socket) else: lastError
  884. if not flags.isDisconnectionError(lastE):
  885. if async:
  886. when useWinVersion:
  887. if lastE.int32 == WSAEWOULDBLOCK:
  888. return
  889. else: raiseOSError(lastE)
  890. else:
  891. if lastE.int32 == EAGAIN or lastE.int32 == EWOULDBLOCK:
  892. return
  893. else: raiseOSError(lastE)
  894. else: raiseOSError(lastE)
  895. proc listen*(socket: Socket, backlog = SOMAXCONN) {.tags: [ReadIOEffect].} =
  896. ## Marks `socket` as accepting connections.
  897. ## `Backlog` specifies the maximum length of the
  898. ## queue of pending connections.
  899. ##
  900. ## Raises an OSError error upon failure.
  901. if nativesockets.listen(socket.fd, backlog) < 0'i32:
  902. raiseOSError(osLastError())
  903. proc bindAddr*(socket: Socket, port = Port(0), address = "") {.
  904. tags: [ReadIOEffect].} =
  905. ## Binds `address`:`port` to the socket.
  906. ##
  907. ## If `address` is "" then ADDR_ANY will be bound.
  908. var realaddr = address
  909. if realaddr == "":
  910. case socket.domain
  911. of AF_INET6: realaddr = "::"
  912. of AF_INET: realaddr = "0.0.0.0"
  913. else:
  914. raise newException(ValueError,
  915. "Unknown socket address family and no address specified to bindAddr")
  916. var aiList = getAddrInfo(realaddr, port, socket.domain)
  917. if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
  918. freeAddrInfo(aiList)
  919. var address2: string
  920. address2.addQuoted address
  921. raiseOSError(osLastError(), "address: $# port: $#" % [address2, $port])
  922. freeAddrInfo(aiList)
  923. proc acceptAddr*(server: Socket, client: var owned(Socket), address: var string,
  924. flags = {SocketFlag.SafeDisconn},
  925. inheritable = defined(nimInheritHandles)) {.
  926. tags: [ReadIOEffect], gcsafe.} =
  927. ## Blocks until a connection is being made from a client. When a connection
  928. ## is made sets `client` to the client socket and `address` to the address
  929. ## of the connecting client.
  930. ## This function will raise OSError if an error occurs.
  931. ##
  932. ## The resulting client will inherit any properties of the server socket. For
  933. ## example: whether the socket is buffered or not.
  934. ##
  935. ## The SocketHandle associated with the resulting client will not be
  936. ## inheritable by child processes by default. This can be changed via
  937. ## the `inheritable` parameter.
  938. ##
  939. ## The `accept` call may result in an error if the connecting socket
  940. ## disconnects during the duration of the `accept`. If the `SafeDisconn`
  941. ## flag is specified then this error will not be raised and instead
  942. ## accept will be called again.
  943. if client.isNil:
  944. new(client)
  945. let ret = accept(server.fd, inheritable)
  946. let sock = ret[0]
  947. if sock == osInvalidSocket:
  948. let err = osLastError()
  949. if flags.isDisconnectionError(err):
  950. acceptAddr(server, client, address, flags, inheritable)
  951. raiseOSError(err)
  952. else:
  953. address = ret[1]
  954. client.fd = sock
  955. client.domain = getSockDomain(sock)
  956. client.isBuffered = server.isBuffered
  957. # Handle SSL.
  958. when defineSsl:
  959. if server.isSsl:
  960. # We must wrap the client sock in a ssl context.
  961. server.sslContext.wrapSocket(client)
  962. ErrClearError()
  963. let ret = SSL_accept(client.sslHandle)
  964. socketError(client, ret, false)
  965. when false: #defineSsl:
  966. proc acceptAddrSSL*(server: Socket, client: var Socket,
  967. address: var string): SSL_acceptResult {.
  968. tags: [ReadIOEffect].} =
  969. ## This procedure should only be used for non-blocking **SSL** sockets.
  970. ## It will immediately return with one of the following values:
  971. ##
  972. ## `AcceptSuccess` will be returned when a client has been successfully
  973. ## accepted and the handshake has been successfully performed between
  974. ## `server` and the newly connected client.
  975. ##
  976. ## `AcceptNoHandshake` will be returned when a client has been accepted
  977. ## but no handshake could be performed. This can happen when the client
  978. ## connects but does not yet initiate a handshake. In this case
  979. ## `acceptAddrSSL` should be called again with the same parameters.
  980. ##
  981. ## `AcceptNoClient` will be returned when no client is currently attempting
  982. ## to connect.
  983. template doHandshake(): untyped =
  984. when defineSsl:
  985. if server.isSsl:
  986. client.setBlocking(false)
  987. # We must wrap the client sock in a ssl context.
  988. if not client.isSsl or client.sslHandle == nil:
  989. server.sslContext.wrapSocket(client)
  990. ErrClearError()
  991. let ret = SSL_accept(client.sslHandle)
  992. while ret <= 0:
  993. let err = SSL_get_error(client.sslHandle, ret)
  994. if err != SSL_ERROR_WANT_ACCEPT:
  995. case err
  996. of SSL_ERROR_ZERO_RETURN:
  997. raiseSSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
  998. of SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE,
  999. SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT:
  1000. client.sslNoHandshake = true
  1001. return AcceptNoHandshake
  1002. of SSL_ERROR_WANT_X509_LOOKUP:
  1003. raiseSSLError("Function for x509 lookup has been called.")
  1004. of SSL_ERROR_SYSCALL, SSL_ERROR_SSL:
  1005. raiseSSLError()
  1006. else:
  1007. raiseSSLError("Unknown error")
  1008. client.sslNoHandshake = false
  1009. if client.isSsl and client.sslNoHandshake:
  1010. doHandshake()
  1011. return AcceptSuccess
  1012. else:
  1013. acceptAddrPlain(AcceptNoClient, AcceptSuccess):
  1014. doHandshake()
  1015. proc accept*(server: Socket, client: var owned(Socket),
  1016. flags = {SocketFlag.SafeDisconn},
  1017. inheritable = defined(nimInheritHandles))
  1018. {.tags: [ReadIOEffect].} =
  1019. ## Equivalent to `acceptAddr` but doesn't return the address, only the
  1020. ## socket.
  1021. ##
  1022. ## The SocketHandle associated with the resulting client will not be
  1023. ## inheritable by child processes by default. This can be changed via
  1024. ## the `inheritable` parameter.
  1025. ##
  1026. ## The `accept` call may result in an error if the connecting socket
  1027. ## disconnects during the duration of the `accept`. If the `SafeDisconn`
  1028. ## flag is specified then this error will not be raised and instead
  1029. ## accept will be called again.
  1030. var addrDummy = ""
  1031. acceptAddr(server, client, addrDummy, flags)
  1032. when defined(posix) and not defined(lwip):
  1033. from posix import Sigset, sigwait, sigismember, sigemptyset, sigaddset,
  1034. sigprocmask, pthread_sigmask, SIGPIPE, SIG_BLOCK, SIG_UNBLOCK
  1035. template blockSigpipe(body: untyped): untyped =
  1036. ## Temporary block SIGPIPE within the provided code block. If SIGPIPE is
  1037. ## raised for the duration of the code block, it will be queued and will be
  1038. ## raised once the block ends.
  1039. ##
  1040. ## Within the block a `selectSigpipe()` template is provided which can be
  1041. ## used to remove SIGPIPE from the queue. Note that if SIGPIPE is **not**
  1042. ## raised at the time of call, it will block until SIGPIPE is raised.
  1043. ##
  1044. ## If SIGPIPE has already been blocked at the time of execution, the
  1045. ## signal mask is left as-is and `selectSigpipe()` will become a no-op.
  1046. ##
  1047. ## For convenience, this template is also available for non-POSIX system,
  1048. ## where `body` will be executed as-is.
  1049. when not defined(posix) or defined(lwip):
  1050. body
  1051. else:
  1052. template sigmask(how: cint, set, oset: var Sigset): untyped {.gensym.} =
  1053. ## Alias for pthread_sigmask or sigprocmask depending on the status
  1054. ## of --threads
  1055. when compileOption("threads"):
  1056. pthread_sigmask(how, set, oset)
  1057. else:
  1058. sigprocmask(how, set, oset)
  1059. var oldSet, watchSet: Sigset
  1060. if sigemptyset(oldSet) == -1:
  1061. raiseOSError(osLastError())
  1062. if sigemptyset(watchSet) == -1:
  1063. raiseOSError(osLastError())
  1064. if sigaddset(watchSet, SIGPIPE) == -1:
  1065. raiseOSError(osLastError(), "Couldn't add SIGPIPE to Sigset")
  1066. if sigmask(SIG_BLOCK, watchSet, oldSet) == -1:
  1067. raiseOSError(osLastError(), "Couldn't block SIGPIPE")
  1068. let alreadyBlocked = sigismember(oldSet, SIGPIPE) == 1
  1069. template selectSigpipe(): untyped {.used.} =
  1070. if not alreadyBlocked:
  1071. var signal: cint
  1072. let err = sigwait(watchSet, signal)
  1073. if err != 0:
  1074. raiseOSError(err.OSErrorCode, "Couldn't select SIGPIPE")
  1075. assert signal == SIGPIPE
  1076. try:
  1077. body
  1078. finally:
  1079. if not alreadyBlocked:
  1080. if sigmask(SIG_UNBLOCK, watchSet, oldSet) == -1:
  1081. raiseOSError(osLastError(), "Couldn't unblock SIGPIPE")
  1082. proc close*(socket: Socket, flags = {SocketFlag.SafeDisconn}) =
  1083. ## Closes a socket.
  1084. ##
  1085. ## If `socket` is an SSL/TLS socket, this proc will also send a closure
  1086. ## notification to the peer. If `SafeDisconn` is in `flags`, failure to do so
  1087. ## due to disconnections will be ignored. This is generally safe in
  1088. ## practice. See
  1089. ## `here <https://security.stackexchange.com/a/82044>`_ for more details.
  1090. try:
  1091. when defineSsl:
  1092. if socket.isSsl and socket.sslHandle != nil:
  1093. # Don't call SSL_shutdown if the connection has not been fully
  1094. # established, see:
  1095. # https://github.com/openssl/openssl/issues/710#issuecomment-253897666
  1096. if not socket.sslNoShutdown and SSL_in_init(socket.sslHandle) == 0:
  1097. # As we are closing the underlying socket immediately afterwards,
  1098. # it is valid, under the TLS standard, to perform a unidirectional
  1099. # shutdown i.e not wait for the peers "close notify" alert with a second
  1100. # call to SSL_shutdown
  1101. blockSigpipe:
  1102. ErrClearError()
  1103. let res = SSL_shutdown(socket.sslHandle)
  1104. if res == 0:
  1105. discard
  1106. elif res != 1:
  1107. let
  1108. err = osLastError()
  1109. sslError = SSL_get_error(socket.sslHandle, res)
  1110. # If a close notification is received, failures outside of the
  1111. # protocol will be returned as SSL_ERROR_ZERO_RETURN instead
  1112. # of SSL_ERROR_SYSCALL. This fact is deduced by digging into
  1113. # SSL_get_error() source code.
  1114. if sslError == SSL_ERROR_ZERO_RETURN or
  1115. sslError == SSL_ERROR_SYSCALL:
  1116. when defined(posix) and not defined(macosx) and
  1117. not defined(nimdoc):
  1118. if err == EPIPE.OSErrorCode:
  1119. # Clear the SIGPIPE that's been raised due to
  1120. # the disconnection.
  1121. selectSigpipe()
  1122. else:
  1123. discard
  1124. if not flags.isDisconnectionError(err):
  1125. socketError(socket, res, lastError = err, flags = flags)
  1126. else:
  1127. socketError(socket, res, lastError = err, flags = flags)
  1128. finally:
  1129. when defineSsl:
  1130. if socket.isSsl and socket.sslHandle != nil:
  1131. SSL_free(socket.sslHandle)
  1132. socket.sslHandle = nil
  1133. socket.fd.close()
  1134. socket.fd = osInvalidSocket
  1135. when defined(posix):
  1136. from posix import TCP_NODELAY
  1137. else:
  1138. from winlean import TCP_NODELAY
  1139. proc toCInt*(opt: SOBool): cint =
  1140. ## Converts a `SOBool` into its Socket Option cint representation.
  1141. case opt
  1142. of OptAcceptConn: SO_ACCEPTCONN
  1143. of OptBroadcast: SO_BROADCAST
  1144. of OptDebug: SO_DEBUG
  1145. of OptDontRoute: SO_DONTROUTE
  1146. of OptKeepAlive: SO_KEEPALIVE
  1147. of OptOOBInline: SO_OOBINLINE
  1148. of OptReuseAddr: SO_REUSEADDR
  1149. of OptReusePort: SO_REUSEPORT
  1150. of OptNoDelay: TCP_NODELAY
  1151. proc getSockOpt*(socket: Socket, opt: SOBool, level = SOL_SOCKET): bool {.
  1152. tags: [ReadIOEffect].} =
  1153. ## Retrieves option `opt` as a boolean value.
  1154. var res = getSockOptInt(socket.fd, cint(level), toCInt(opt))
  1155. result = res != 0
  1156. proc getLocalAddr*(socket: Socket): (string, Port) =
  1157. ## Get the socket's local address and port number.
  1158. ##
  1159. ## This is high-level interface for `getsockname`:idx:.
  1160. getLocalAddr(socket.fd, socket.domain)
  1161. when not useNimNetLite:
  1162. proc getPeerAddr*(socket: Socket): (string, Port) =
  1163. ## Get the socket's peer address and port number.
  1164. ##
  1165. ## This is high-level interface for `getpeername`:idx:.
  1166. getPeerAddr(socket.fd, socket.domain)
  1167. proc setSockOpt*(socket: Socket, opt: SOBool, value: bool,
  1168. level = SOL_SOCKET) {.tags: [WriteIOEffect].} =
  1169. ## Sets option `opt` to a boolean value specified by `value`.
  1170. runnableExamples("-r:off"):
  1171. let socket = newSocket()
  1172. socket.setSockOpt(OptReusePort, true)
  1173. socket.setSockOpt(OptNoDelay, true, level = IPPROTO_TCP.cint)
  1174. var valuei = cint(if value: 1 else: 0)
  1175. setSockOptInt(socket.fd, cint(level), toCInt(opt), valuei)
  1176. when defined(nimdoc) or (defined(posix) and not useNimNetLite):
  1177. proc connectUnix*(socket: Socket, path: string) =
  1178. ## Connects to Unix socket on `path`.
  1179. ## This only works on Unix-style systems: Mac OS X, BSD and Linux
  1180. when not defined(nimdoc):
  1181. var socketAddr = makeUnixAddr(path)
  1182. if socket.fd.connect(cast[ptr SockAddr](addr socketAddr),
  1183. (sizeof(socketAddr.sun_family) + path.len).SockLen) != 0'i32:
  1184. raiseOSError(osLastError())
  1185. proc bindUnix*(socket: Socket, path: string) =
  1186. ## Binds Unix socket to `path`.
  1187. ## This only works on Unix-style systems: Mac OS X, BSD and Linux
  1188. when not defined(nimdoc):
  1189. var socketAddr = makeUnixAddr(path)
  1190. if socket.fd.bindAddr(cast[ptr SockAddr](addr socketAddr),
  1191. (sizeof(socketAddr.sun_family) + path.len).SockLen) != 0'i32:
  1192. raiseOSError(osLastError())
  1193. when defineSsl:
  1194. proc gotHandshake*(socket: Socket): bool =
  1195. ## Determines whether a handshake has occurred between a client (`socket`)
  1196. ## and the server that `socket` is connected to.
  1197. ##
  1198. ## Throws SslError if `socket` is not an SSL socket.
  1199. if socket.isSsl:
  1200. return not socket.sslNoHandshake
  1201. else:
  1202. raiseSSLError("Socket is not an SSL socket.")
  1203. proc hasDataBuffered*(s: Socket): bool =
  1204. ## Determines whether a socket has data buffered.
  1205. result = false
  1206. if s.isBuffered:
  1207. result = s.bufLen > 0 and s.currPos != s.bufLen
  1208. when defineSsl:
  1209. if s.isSsl and not result:
  1210. result = s.sslHasPeekChar
  1211. proc isClosed(socket: Socket): bool =
  1212. socket.fd == osInvalidSocket
  1213. proc uniRecv(socket: Socket, buffer: pointer, size, flags: cint): int =
  1214. ## Handles SSL and non-ssl recv in a nice package.
  1215. ##
  1216. ## In particular handles the case where socket has been closed properly
  1217. ## for both SSL and non-ssl.
  1218. result = 0
  1219. assert(not socket.isClosed, "Cannot `recv` on a closed socket")
  1220. when defineSsl:
  1221. if socket.isSsl:
  1222. ErrClearError()
  1223. return SSL_read(socket.sslHandle, buffer, size)
  1224. return recv(socket.fd, buffer, size, flags)
  1225. proc readIntoBuf(socket: Socket, flags: int32): int =
  1226. result = 0
  1227. result = uniRecv(socket, addr(socket.buffer), socket.buffer.high, flags)
  1228. if result < 0:
  1229. # Save it in case it gets reset (the Nim codegen occasionally may call
  1230. # Win API functions which reset it).
  1231. socket.lastError = osLastError()
  1232. if result <= 0:
  1233. socket.bufLen = 0
  1234. socket.currPos = 0
  1235. return result
  1236. socket.bufLen = result
  1237. socket.currPos = 0
  1238. template retRead(flags, readBytes: int) {.dirty.} =
  1239. let res = socket.readIntoBuf(flags.int32)
  1240. if res <= 0:
  1241. if readBytes > 0:
  1242. return readBytes
  1243. else:
  1244. return res
  1245. proc recv*(socket: Socket, data: pointer, size: int): int {.tags: [
  1246. ReadIOEffect].} =
  1247. ## Receives data from a socket.
  1248. ##
  1249. ## **Note**: This is a low-level function, you may be interested in the higher
  1250. ## level versions of this function which are also named `recv`.
  1251. if size == 0: return
  1252. if socket.isBuffered:
  1253. if socket.bufLen == 0:
  1254. retRead(0'i32, 0)
  1255. var read = 0
  1256. while read < size:
  1257. if socket.currPos >= socket.bufLen:
  1258. retRead(0'i32, read)
  1259. let chunk = min(socket.bufLen-socket.currPos, size-read)
  1260. var d = cast[cstring](data)
  1261. assert size-read >= chunk
  1262. copyMem(addr(d[read]), addr(socket.buffer[socket.currPos]), chunk)
  1263. read.inc(chunk)
  1264. socket.currPos.inc(chunk)
  1265. result = read
  1266. else:
  1267. when defineSsl:
  1268. if socket.isSsl:
  1269. if socket.sslHasPeekChar: # TODO: Merge this peek char mess into uniRecv
  1270. copyMem(data, addr(socket.sslPeekChar), 1)
  1271. socket.sslHasPeekChar = false
  1272. if size-1 > 0:
  1273. var d = cast[cstring](data)
  1274. result = uniRecv(socket, addr(d[1]), cint(size-1), 0'i32) + 1
  1275. else:
  1276. result = 1
  1277. else:
  1278. result = uniRecv(socket, data, size.cint, 0'i32)
  1279. else:
  1280. result = recv(socket.fd, data, size.cint, 0'i32)
  1281. else:
  1282. result = recv(socket.fd, data, size.cint, 0'i32)
  1283. if result < 0:
  1284. # Save the error in case it gets reset.
  1285. socket.lastError = osLastError()
  1286. proc waitFor(socket: Socket, waited: var Duration, timeout, size: int,
  1287. funcName: string): int {.tags: [TimeEffect].} =
  1288. ## determines the amount of characters that can be read. Result will never
  1289. ## be larger than `size`. For unbuffered sockets this will be `1`.
  1290. ## For buffered sockets it can be as big as `BufferSize`.
  1291. ##
  1292. ## If this function does not determine that there is data on the socket
  1293. ## within `timeout` ms, a TimeoutError error will be raised.
  1294. result = 1
  1295. if size <= 0: assert false
  1296. if timeout == -1: return size
  1297. if socket.isBuffered and socket.bufLen != 0 and
  1298. socket.bufLen != socket.currPos:
  1299. result = socket.bufLen - socket.currPos
  1300. result = min(result, size)
  1301. else:
  1302. if timeout - waited.inMilliseconds < 1:
  1303. raise newException(TimeoutError, "Call to '" & funcName & "' timed out.")
  1304. when defineSsl:
  1305. if socket.isSsl:
  1306. if socket.hasDataBuffered:
  1307. # sslPeekChar is present.
  1308. return 1
  1309. let sslPending = SSL_pending(socket.sslHandle)
  1310. if sslPending != 0:
  1311. return min(sslPending, size)
  1312. var startTime = getMonoTime()
  1313. let selRet = if socket.hasDataBuffered: 1
  1314. else:
  1315. timeoutRead(socket.fd, (timeout - waited.inMilliseconds).int)
  1316. if selRet < 0: raiseOSError(osLastError())
  1317. if selRet != 1:
  1318. raise newException(TimeoutError, "Call to '" & funcName & "' timed out.")
  1319. waited += (getMonoTime() - startTime)
  1320. proc recv*(socket: Socket, data: pointer, size: int, timeout: int): int {.
  1321. tags: [ReadIOEffect, TimeEffect].} =
  1322. ## overload with a `timeout` parameter in milliseconds.
  1323. var waited: Duration # duration already waited
  1324. var read = 0
  1325. while read < size:
  1326. let avail = waitFor(socket, waited, timeout, size-read, "recv")
  1327. var d = cast[cstring](data)
  1328. assert avail <= size-read
  1329. result = recv(socket, addr(d[read]), avail)
  1330. if result == 0: break
  1331. if result < 0:
  1332. return result
  1333. inc(read, result)
  1334. result = read
  1335. proc recv*(socket: Socket, data: var string, size: int, timeout = -1,
  1336. flags = {SocketFlag.SafeDisconn}): int =
  1337. ## Higher-level version of `recv`.
  1338. ##
  1339. ## Reads **up to** `size` bytes from `socket` into `data`.
  1340. ##
  1341. ## For buffered sockets this function will attempt to read all the requested
  1342. ## data. It will read this data in `BufferSize` chunks.
  1343. ##
  1344. ## For unbuffered sockets this function makes no effort to read
  1345. ## all the data requested. It will return as much data as the operating system
  1346. ## gives it.
  1347. ##
  1348. ## When 0 is returned the socket's connection has been closed.
  1349. ##
  1350. ## This function will throw an OSError exception when an error occurs. A value
  1351. ## lower than 0 is never returned.
  1352. ##
  1353. ## A timeout may be specified in milliseconds, if enough data is not received
  1354. ## within the time specified a TimeoutError exception will be raised.
  1355. ##
  1356. ## .. warning:: Only the `SafeDisconn` flag is currently supported.
  1357. data.setLen(size)
  1358. result =
  1359. if timeout == -1:
  1360. recv(socket, cstring(data), size)
  1361. else:
  1362. recv(socket, cstring(data), size, timeout)
  1363. if result < 0:
  1364. data.setLen(0)
  1365. let lastError = getSocketError(socket)
  1366. socket.socketError(result, lastError = lastError, flags = flags)
  1367. else:
  1368. data.setLen(result)
  1369. proc recv*(socket: Socket, size: int, timeout = -1,
  1370. flags = {SocketFlag.SafeDisconn}): string {.inline.} =
  1371. ## Higher-level version of `recv` which returns a string.
  1372. ##
  1373. ## Reads **up to** `size` bytes from `socket` into the result.
  1374. ##
  1375. ## For buffered sockets this function will attempt to read all the requested
  1376. ## data. It will read this data in `BufferSize` chunks.
  1377. ##
  1378. ## For unbuffered sockets this function makes no effort to read
  1379. ## all the data requested. It will return as much data as the operating system
  1380. ## gives it.
  1381. ##
  1382. ## When `""` is returned the socket's connection has been closed.
  1383. ##
  1384. ## This function will throw an OSError exception when an error occurs.
  1385. ##
  1386. ## A timeout may be specified in milliseconds, if enough data is not received
  1387. ## within the time specified a TimeoutError exception will be raised.
  1388. ##
  1389. ##
  1390. ## .. warning:: Only the `SafeDisconn` flag is currently supported.
  1391. result = newString(size)
  1392. discard recv(socket, result, size, timeout, flags)
  1393. proc peekChar(socket: Socket, c: var char): int {.tags: [ReadIOEffect].} =
  1394. if socket.isBuffered:
  1395. result = 1
  1396. if socket.bufLen == 0 or socket.currPos > socket.bufLen-1:
  1397. var res = socket.readIntoBuf(0'i32)
  1398. if res <= 0:
  1399. result = res
  1400. c = socket.buffer[socket.currPos]
  1401. else:
  1402. when defineSsl:
  1403. if socket.isSsl:
  1404. if not socket.sslHasPeekChar:
  1405. result = uniRecv(socket, addr(socket.sslPeekChar), 1, 0'i32)
  1406. socket.sslHasPeekChar = true
  1407. c = socket.sslPeekChar
  1408. return
  1409. result = recv(socket.fd, addr(c), 1, MSG_PEEK)
  1410. proc readLine*(socket: Socket, line: var string, timeout = -1,
  1411. flags = {SocketFlag.SafeDisconn}, maxLength = MaxLineLength) {.
  1412. tags: [ReadIOEffect, TimeEffect].} =
  1413. ## Reads a line of data from `socket`.
  1414. ##
  1415. ## If a full line is read `\r\L` is not
  1416. ## added to `line`, however if solely `\r\L` is read then `line`
  1417. ## will be set to it.
  1418. ##
  1419. ## If the socket is disconnected, `line` will be set to `""`.
  1420. ##
  1421. ## An OSError exception will be raised in the case of a socket error.
  1422. ##
  1423. ## A timeout can be specified in milliseconds, if data is not received within
  1424. ## the specified time a TimeoutError exception will be raised.
  1425. ##
  1426. ## The `maxLength` parameter determines the maximum amount of characters
  1427. ## that can be read. The result is truncated after that.
  1428. ##
  1429. ## .. warning:: Only the `SafeDisconn` flag is currently supported.
  1430. template addNLIfEmpty() =
  1431. if line.len == 0:
  1432. line.add("\c\L")
  1433. template raiseSockError() {.dirty.} =
  1434. let lastError = getSocketError(socket)
  1435. if flags.isDisconnectionError(lastError):
  1436. setLen(line, 0)
  1437. socket.socketError(n, lastError = lastError, flags = flags)
  1438. return
  1439. var waited: Duration
  1440. setLen(line, 0)
  1441. while true:
  1442. var c: char
  1443. discard waitFor(socket, waited, timeout, 1, "readLine")
  1444. var n = recv(socket, addr(c), 1)
  1445. if n < 0: raiseSockError()
  1446. elif n == 0: setLen(line, 0); return
  1447. if c == '\r':
  1448. discard waitFor(socket, waited, timeout, 1, "readLine")
  1449. n = peekChar(socket, c)
  1450. if n > 0 and c == '\L':
  1451. discard recv(socket, addr(c), 1)
  1452. elif n <= 0: raiseSockError()
  1453. addNLIfEmpty()
  1454. return
  1455. elif c == '\L':
  1456. addNLIfEmpty()
  1457. return
  1458. add(line, c)
  1459. # Verify that this isn't a DOS attack: #3847.
  1460. if line.len > maxLength: break
  1461. proc recvLine*(socket: Socket, timeout = -1,
  1462. flags = {SocketFlag.SafeDisconn},
  1463. maxLength = MaxLineLength): string =
  1464. ## Reads a line of data from `socket`.
  1465. ##
  1466. ## If a full line is read `\r\L` is not
  1467. ## added to the result, however if solely `\r\L` is read then the result
  1468. ## will be set to it.
  1469. ##
  1470. ## If the socket is disconnected, the result will be set to `""`.
  1471. ##
  1472. ## An OSError exception will be raised in the case of a socket error.
  1473. ##
  1474. ## A timeout can be specified in milliseconds, if data is not received within
  1475. ## the specified time a TimeoutError exception will be raised.
  1476. ##
  1477. ## The `maxLength` parameter determines the maximum amount of characters
  1478. ## that can be read. The result is truncated after that.
  1479. ##
  1480. ## .. warning:: Only the `SafeDisconn` flag is currently supported.
  1481. result = ""
  1482. readLine(socket, result, timeout, flags, maxLength)
  1483. proc recvFrom*[T: string | IpAddress](socket: Socket, data: var string, length: int,
  1484. address: var T, port: var Port, flags = 0'i32): int {.
  1485. tags: [ReadIOEffect].} =
  1486. ## Receives data from `socket`. This function should normally be used with
  1487. ## connection-less sockets (UDP sockets). The source address of the data
  1488. ## packet is stored in the `address` argument as either a string or an IpAddress.
  1489. ##
  1490. ## If an error occurs an OSError exception will be raised. Otherwise the return
  1491. ## value will be the length of data received.
  1492. ##
  1493. ## .. warning:: This function does not yet have a buffered implementation,
  1494. ## so when `socket` is buffered the non-buffered implementation will be
  1495. ## used. Therefore if `socket` contains something in its buffer this
  1496. ## function will make no effort to return it.
  1497. template adaptRecvFromToDomain(sockAddress: untyped, domain: Domain) =
  1498. var addrLen = SockLen(sizeof(sockAddress))
  1499. result = recvfrom(socket.fd, cstring(data), length.cint, flags.cint,
  1500. cast[ptr SockAddr](addr(sockAddress)), addr(addrLen))
  1501. if result != -1:
  1502. data.setLen(result)
  1503. when typeof(address) is string:
  1504. address = getAddrString(cast[ptr SockAddr](addr(sockAddress)))
  1505. when domain == AF_INET6:
  1506. port = ntohs(sockAddress.sin6_port).Port
  1507. else:
  1508. port = ntohs(sockAddress.sin_port).Port
  1509. else:
  1510. data.setLen(result)
  1511. sockAddress.fromSockAddr(addrLen, address, port)
  1512. else:
  1513. raiseOSError(osLastError())
  1514. assert(socket.protocol != IPPROTO_TCP, "Cannot `recvFrom` on a TCP socket")
  1515. # TODO: Buffered sockets
  1516. data.setLen(length)
  1517. case socket.domain
  1518. of AF_INET6:
  1519. var sockAddress: Sockaddr_in6
  1520. adaptRecvFromToDomain(sockAddress, AF_INET6)
  1521. of AF_INET:
  1522. var sockAddress: Sockaddr_in
  1523. adaptRecvFromToDomain(sockAddress, AF_INET)
  1524. else:
  1525. raise newException(ValueError, "Unknown socket address family")
  1526. proc skip*(socket: Socket, size: int, timeout = -1) =
  1527. ## Skips `size` amount of bytes.
  1528. ##
  1529. ## An optional timeout can be specified in milliseconds, if skipping the
  1530. ## bytes takes longer than specified a TimeoutError exception will be raised.
  1531. ##
  1532. ## Returns the number of skipped bytes.
  1533. var waited: Duration
  1534. var dummy = alloc(size)
  1535. var bytesSkipped = 0
  1536. while bytesSkipped != size:
  1537. let avail = waitFor(socket, waited, timeout, size-bytesSkipped, "skip")
  1538. bytesSkipped += recv(socket, dummy, avail)
  1539. dealloc(dummy)
  1540. proc send*(socket: Socket, data: pointer, size: int): int {.
  1541. tags: [WriteIOEffect].} =
  1542. ## Sends data to a socket.
  1543. ##
  1544. ## **Note**: This is a low-level version of `send`. You likely should use
  1545. ## the version below.
  1546. assert(not socket.isClosed, "Cannot `send` on a closed socket")
  1547. when defineSsl:
  1548. if socket.isSsl:
  1549. ErrClearError()
  1550. return SSL_write(socket.sslHandle, cast[cstring](data), size)
  1551. when useWinVersion or defined(macosx):
  1552. result = send(socket.fd, data, size.cint, 0'i32)
  1553. else:
  1554. when defined(solaris):
  1555. const MSG_NOSIGNAL = 0
  1556. result = send(socket.fd, data, size, int32(MSG_NOSIGNAL))
  1557. proc send*(socket: Socket, data: string,
  1558. flags = {SocketFlag.SafeDisconn}, maxRetries = 100) {.tags: [WriteIOEffect].} =
  1559. ## Sends data to a socket. Will try to send all the data by handling interrupts
  1560. ## and incomplete writes up to `maxRetries`.
  1561. var written = 0
  1562. var attempts = 0
  1563. while data.len - written > 0:
  1564. let sent = send(socket, cstring(data), data.len)
  1565. if sent < 0:
  1566. let lastError = osLastError()
  1567. let isBlockingErr =
  1568. when defined(nimdoc):
  1569. false
  1570. elif useWinVersion:
  1571. lastError.int32 == WSAEINTR or
  1572. lastError.int32 == WSAEWOULDBLOCK
  1573. else:
  1574. lastError.int32 == EINTR or
  1575. lastError.int32 == EWOULDBLOCK or
  1576. lastError.int32 == EAGAIN
  1577. if not isBlockingErr:
  1578. let lastError = osLastError()
  1579. socketError(socket, lastError = lastError, flags = flags)
  1580. else:
  1581. attempts.inc()
  1582. if attempts > maxRetries:
  1583. raiseOSError(osLastError(), "Could not send all data.")
  1584. else:
  1585. written.inc(sent)
  1586. template `&=`*(socket: Socket; data: typed) =
  1587. ## an alias for 'send'.
  1588. send(socket, data)
  1589. proc trySend*(socket: Socket, data: string): bool {.tags: [WriteIOEffect].} =
  1590. ## Safe alternative to `send`. Does not raise an OSError when an error occurs,
  1591. ## and instead returns `false` on failure.
  1592. result = send(socket, cstring(data), data.len) == data.len
  1593. proc sendTo*(socket: Socket, address: string, port: Port, data: pointer,
  1594. size: int, af: Domain = AF_INET, flags = 0'i32) {.
  1595. tags: [WriteIOEffect].} =
  1596. ## This proc sends `data` to the specified `address`,
  1597. ## which may be an IP address or a hostname, if a hostname is specified
  1598. ## this function will try each IP of that hostname. This function
  1599. ## should normally be used with connection-less sockets (UDP sockets).
  1600. ##
  1601. ## If an error occurs an OSError exception will be raised.
  1602. ##
  1603. ## **Note:** You may wish to use the high-level version of this function
  1604. ## which is defined below.
  1605. ##
  1606. ## **Note:** This proc is not available for SSL sockets.
  1607. assert(socket.protocol != IPPROTO_TCP, "Cannot `sendTo` on a TCP socket")
  1608. assert(not socket.isClosed, "Cannot `sendTo` on a closed socket")
  1609. var aiList = getAddrInfo(address, port, af, socket.sockType, socket.protocol)
  1610. # try all possibilities:
  1611. var success = false
  1612. var it = aiList
  1613. var result = 0
  1614. while it != nil:
  1615. result = sendto(socket.fd, data, size.cint, flags.cint, it.ai_addr,
  1616. it.ai_addrlen.SockLen)
  1617. if result != -1'i32:
  1618. success = true
  1619. break
  1620. it = it.ai_next
  1621. let osError = osLastError()
  1622. freeAddrInfo(aiList)
  1623. if not success:
  1624. raiseOSError(osError)
  1625. proc sendTo*(socket: Socket, address: string, port: Port,
  1626. data: string) {.tags: [WriteIOEffect].} =
  1627. ## This proc sends `data` to the specified `address`,
  1628. ## which may be an IP address or a hostname, if a hostname is specified
  1629. ## this function will try each IP of that hostname.
  1630. ##
  1631. ## Generally for use with connection-less (UDP) sockets.
  1632. ##
  1633. ## If an error occurs an OSError exception will be raised.
  1634. ##
  1635. ## This is the high-level version of the above `sendTo` function.
  1636. socket.sendTo(address, port, cstring(data), data.len, socket.domain)
  1637. proc sendTo*(socket: Socket, address: IpAddress, port: Port,
  1638. data: string, flags = 0'i32): int {.
  1639. discardable, tags: [WriteIOEffect].} =
  1640. ## This proc sends `data` to the specified `IpAddress` and returns
  1641. ## the number of bytes written.
  1642. ##
  1643. ## Generally for use with connection-less (UDP) sockets.
  1644. ##
  1645. ## If an error occurs an OSError exception will be raised.
  1646. ##
  1647. ## This is the high-level version of the above `sendTo` function.
  1648. assert(socket.protocol != IPPROTO_TCP, "Cannot `sendTo` on a TCP socket")
  1649. assert(not socket.isClosed, "Cannot `sendTo` on a closed socket")
  1650. var sa: Sockaddr_storage
  1651. var sl: SockLen
  1652. toSockAddr(address, port, sa, sl)
  1653. result = sendto(socket.fd, cstring(data), data.len().cint, flags.cint,
  1654. cast[ptr SockAddr](addr sa), sl)
  1655. if result == -1'i32:
  1656. let osError = osLastError()
  1657. raiseOSError(osError)
  1658. proc isSsl*(socket: Socket): bool =
  1659. ## Determines whether `socket` is a SSL socket.
  1660. when defineSsl:
  1661. result = socket.isSsl
  1662. else:
  1663. result = false
  1664. proc getFd*(socket: Socket): SocketHandle = return socket.fd
  1665. ## Returns the socket's file descriptor
  1666. when defined(zephyr) or defined(nimNetSocketExtras): # Remove in future
  1667. proc getDomain*(socket: Socket): Domain = return socket.domain
  1668. ## Returns the socket's domain
  1669. proc getType*(socket: Socket): SockType = return socket.sockType
  1670. ## Returns the socket's type
  1671. proc getProtocol*(socket: Socket): Protocol = return socket.protocol
  1672. ## Returns the socket's protocol
  1673. when defined(nimHasStyleChecks):
  1674. {.push styleChecks: off.}
  1675. proc IPv4_any*(): IpAddress =
  1676. ## Returns the IPv4 any address, which can be used to listen on all available
  1677. ## network adapters
  1678. result = IpAddress(
  1679. family: IpAddressFamily.IPv4,
  1680. address_v4: [0'u8, 0, 0, 0])
  1681. proc IPv4_loopback*(): IpAddress =
  1682. ## Returns the IPv4 loopback address (127.0.0.1)
  1683. result = IpAddress(
  1684. family: IpAddressFamily.IPv4,
  1685. address_v4: [127'u8, 0, 0, 1])
  1686. proc IPv4_broadcast*(): IpAddress =
  1687. ## Returns the IPv4 broadcast address (255.255.255.255)
  1688. result = IpAddress(
  1689. family: IpAddressFamily.IPv4,
  1690. address_v4: [255'u8, 255, 255, 255])
  1691. proc IPv6_any*(): IpAddress =
  1692. ## Returns the IPv6 any address (::0), which can be used
  1693. ## to listen on all available network adapters
  1694. result = IpAddress(
  1695. family: IpAddressFamily.IPv6,
  1696. address_v6: [0'u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
  1697. proc IPv6_loopback*(): IpAddress =
  1698. ## Returns the IPv6 loopback address (::1)
  1699. result = IpAddress(
  1700. family: IpAddressFamily.IPv6,
  1701. address_v6: [0'u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
  1702. when defined(nimHasStyleChecks):
  1703. {.pop.}
  1704. proc `==`*(lhs, rhs: IpAddress): bool =
  1705. ## Compares two IpAddresses for Equality. Returns true if the addresses are equal
  1706. if lhs.family != rhs.family: return false
  1707. if lhs.family == IpAddressFamily.IPv4:
  1708. for i in low(lhs.address_v4) .. high(lhs.address_v4):
  1709. if lhs.address_v4[i] != rhs.address_v4[i]: return false
  1710. else: # IPv6
  1711. for i in low(lhs.address_v6) .. high(lhs.address_v6):
  1712. if lhs.address_v6[i] != rhs.address_v6[i]: return false
  1713. return true
  1714. proc `$`*(address: IpAddress): string =
  1715. ## Converts an IpAddress into the textual representation
  1716. case address.family
  1717. of IpAddressFamily.IPv4:
  1718. result = newStringOfCap(15)
  1719. result.addInt address.address_v4[0]
  1720. result.add '.'
  1721. result.addInt address.address_v4[1]
  1722. result.add '.'
  1723. result.addInt address.address_v4[2]
  1724. result.add '.'
  1725. result.addInt address.address_v4[3]
  1726. of IpAddressFamily.IPv6:
  1727. result = newStringOfCap(39)
  1728. var
  1729. currentZeroStart = -1
  1730. currentZeroCount = 0
  1731. biggestZeroStart = -1
  1732. biggestZeroCount = 0
  1733. # Look for the largest block of zeros
  1734. for i in 0..7:
  1735. var isZero = address.address_v6[i*2] == 0 and address.address_v6[i*2+1] == 0
  1736. if isZero:
  1737. if currentZeroStart == -1:
  1738. currentZeroStart = i
  1739. currentZeroCount = 1
  1740. else:
  1741. currentZeroCount.inc()
  1742. if currentZeroCount > biggestZeroCount:
  1743. biggestZeroCount = currentZeroCount
  1744. biggestZeroStart = currentZeroStart
  1745. else:
  1746. currentZeroStart = -1
  1747. if biggestZeroCount == 8: # Special case ::0
  1748. result.add("::")
  1749. else: # Print address
  1750. var printedLastGroup = false
  1751. for i in 0..7:
  1752. var word: uint16 = (cast[uint16](address.address_v6[i*2])) shl 8
  1753. word = word or cast[uint16](address.address_v6[i*2+1])
  1754. if biggestZeroCount != 0 and # Check if group is in skip group
  1755. (i >= biggestZeroStart and i < (biggestZeroStart + biggestZeroCount)):
  1756. if i == biggestZeroStart: # skip start
  1757. result.add("::")
  1758. printedLastGroup = false
  1759. else:
  1760. if printedLastGroup:
  1761. result.add(':')
  1762. var
  1763. afterLeadingZeros = false
  1764. mask = 0xF000'u16
  1765. for j in 0'u16..3'u16:
  1766. var val = (mask and word) shr (4'u16*(3'u16-j))
  1767. if val != 0 or afterLeadingZeros:
  1768. if val < 0xA:
  1769. result.add(chr(uint16(ord('0'))+val))
  1770. else: # val >= 0xA
  1771. result.add(chr(uint16(ord('a'))+val-0xA))
  1772. afterLeadingZeros = true
  1773. mask = mask shr 4
  1774. if not afterLeadingZeros:
  1775. result.add '0'
  1776. printedLastGroup = true
  1777. proc dial*(address: string, port: Port,
  1778. protocol = IPPROTO_TCP, buffered = true): owned(Socket)
  1779. {.tags: [ReadIOEffect, WriteIOEffect].} =
  1780. ## Establishes connection to the specified `address`:`port` pair via the
  1781. ## specified protocol. The procedure iterates through possible
  1782. ## resolutions of the `address` until it succeeds, meaning that it
  1783. ## seamlessly works with both IPv4 and IPv6.
  1784. ## Returns Socket ready to send or receive data.
  1785. let sockType = protocol.toSockType()
  1786. let aiList = getAddrInfo(address, port, AF_UNSPEC, sockType, protocol)
  1787. var fdPerDomain: array[low(Domain).ord..high(Domain).ord, SocketHandle]
  1788. for i in low(fdPerDomain)..high(fdPerDomain):
  1789. fdPerDomain[i] = osInvalidSocket
  1790. template closeUnusedFds(domainToKeep = -1) {.dirty.} =
  1791. for i, fd in fdPerDomain:
  1792. if fd != osInvalidSocket and i != domainToKeep:
  1793. fd.close()
  1794. var success = false
  1795. var lastError: OSErrorCode
  1796. var it = aiList
  1797. var domain: Domain
  1798. var lastFd: SocketHandle
  1799. while it != nil:
  1800. let domainOpt = it.ai_family.toKnownDomain()
  1801. if domainOpt.isNone:
  1802. it = it.ai_next
  1803. continue
  1804. domain = domainOpt.unsafeGet()
  1805. lastFd = fdPerDomain[ord(domain)]
  1806. if lastFd == osInvalidSocket:
  1807. lastFd = createNativeSocket(domain, sockType, protocol)
  1808. if lastFd == osInvalidSocket:
  1809. # we always raise if socket creation failed, because it means a
  1810. # network system problem (e.g. not enough FDs), and not an unreachable
  1811. # address.
  1812. let err = osLastError()
  1813. freeAddrInfo(aiList)
  1814. closeUnusedFds()
  1815. raiseOSError(err)
  1816. fdPerDomain[ord(domain)] = lastFd
  1817. if connect(lastFd, it.ai_addr, it.ai_addrlen.SockLen) == 0'i32:
  1818. success = true
  1819. break
  1820. lastError = osLastError()
  1821. it = it.ai_next
  1822. freeAddrInfo(aiList)
  1823. closeUnusedFds(ord(domain))
  1824. if success:
  1825. result = newSocket(lastFd, domain, sockType, protocol, buffered)
  1826. elif lastError != 0.OSErrorCode:
  1827. raiseOSError(lastError)
  1828. else:
  1829. raise newException(IOError, "Couldn't resolve address: " & address)
  1830. proc connect*(socket: Socket, address: string,
  1831. port = Port(0)) {.tags: [ReadIOEffect, RootEffect].} =
  1832. ## Connects socket to `address`:`port`. `Address` can be an IP address or a
  1833. ## host name. If `address` is a host name, this function will try each IP
  1834. ## of that host name. `htons` is already performed on `port` so you must
  1835. ## not do it.
  1836. ##
  1837. ## If `socket` is an SSL socket a handshake will be automatically performed.
  1838. var aiList = getAddrInfo(address, port, socket.domain)
  1839. # try all possibilities:
  1840. var success = false
  1841. var lastError: OSErrorCode
  1842. var it = aiList
  1843. while it != nil:
  1844. if connect(socket.fd, it.ai_addr, it.ai_addrlen.SockLen) == 0'i32:
  1845. success = true
  1846. break
  1847. else: lastError = osLastError()
  1848. it = it.ai_next
  1849. freeAddrInfo(aiList)
  1850. if not success: raiseOSError(lastError)
  1851. when defineSsl:
  1852. if socket.isSsl:
  1853. # RFC3546 for SNI specifies that IP addresses are not allowed.
  1854. if not isIpAddress(address):
  1855. # Discard result in case OpenSSL version doesn't support SNI, or we're
  1856. # not using TLSv1+
  1857. discard SSL_set_tlsext_host_name(socket.sslHandle, address)
  1858. ErrClearError()
  1859. let ret = SSL_connect(socket.sslHandle)
  1860. socketError(socket, ret)
  1861. when not defined(nimDisableCertificateValidation) and not defined(windows):
  1862. if not isIpAddress(address):
  1863. socket.checkCertName(address)
  1864. proc connectAsync(socket: Socket, name: string, port = Port(0),
  1865. af: Domain = AF_INET) {.tags: [ReadIOEffect].} =
  1866. ## A variant of `connect` for non-blocking sockets.
  1867. ##
  1868. ## This procedure will immediately return, it will not block until a connection
  1869. ## is made. It is up to the caller to make sure the connection has been established
  1870. ## by checking (using `select`) whether the socket is writeable.
  1871. ##
  1872. ## **Note**: For SSL sockets, the `handshake` procedure must be called
  1873. ## whenever the socket successfully connects to a server.
  1874. var aiList = getAddrInfo(name, port, af)
  1875. # try all possibilities:
  1876. var success = false
  1877. var lastError: OSErrorCode
  1878. var it = aiList
  1879. while it != nil:
  1880. var ret = connect(socket.fd, it.ai_addr, it.ai_addrlen.SockLen)
  1881. if ret == 0'i32:
  1882. success = true
  1883. break
  1884. else:
  1885. lastError = osLastError()
  1886. when useWinVersion:
  1887. # Windows EINTR doesn't behave same as POSIX.
  1888. if lastError.int32 == WSAEWOULDBLOCK:
  1889. success = true
  1890. break
  1891. else:
  1892. if lastError.int32 == EINTR or lastError.int32 == EINPROGRESS:
  1893. success = true
  1894. break
  1895. it = it.ai_next
  1896. freeAddrInfo(aiList)
  1897. if not success: raiseOSError(lastError)
  1898. proc connect*(socket: Socket, address: string, port = Port(0),
  1899. timeout: int) {.tags: [ReadIOEffect, WriteIOEffect, RootEffect].} =
  1900. ## Connects to server as specified by `address` on port specified by `port`.
  1901. ##
  1902. ## The `timeout` parameter specifies the time in milliseconds to allow for
  1903. ## the connection to the server to be made.
  1904. socket.fd.setBlocking(false)
  1905. socket.connectAsync(address, port, socket.domain)
  1906. if timeoutWrite(socket.fd, timeout) != 1:
  1907. raise newException(TimeoutError, "Call to 'connect' timed out.")
  1908. else:
  1909. let res = getSockOptInt(socket.fd, SOL_SOCKET, SO_ERROR)
  1910. if res != 0:
  1911. raiseOSError(OSErrorCode(res))
  1912. when defineSsl and not defined(nimdoc):
  1913. if socket.isSsl:
  1914. socket.fd.setBlocking(true)
  1915. # RFC3546 for SNI specifies that IP addresses are not allowed.
  1916. if not isIpAddress(address):
  1917. # Discard result in case OpenSSL version doesn't support SNI, or we're
  1918. # not using TLSv1+
  1919. discard SSL_set_tlsext_host_name(socket.sslHandle, address)
  1920. ErrClearError()
  1921. let ret = SSL_connect(socket.sslHandle)
  1922. socketError(socket, ret)
  1923. when not defined(nimDisableCertificateValidation):
  1924. if not isIpAddress(address):
  1925. socket.checkCertName(address)
  1926. socket.fd.setBlocking(true)
  1927. proc getPrimaryIPAddr*(dest = parseIpAddress("8.8.8.8")): IpAddress =
  1928. ## Finds the local IP address, usually assigned to eth0 on LAN or wlan0 on WiFi,
  1929. ## used to reach an external address. Useful to run local services.
  1930. ##
  1931. ## No traffic is sent.
  1932. ##
  1933. ## Supports IPv4 and v6.
  1934. ## Raises OSError if external networking is not set up.
  1935. runnableExamples("-r:off"):
  1936. echo getPrimaryIPAddr() # "192.168.1.2"
  1937. let socket =
  1938. if dest.family == IpAddressFamily.IPv4:
  1939. newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  1940. else:
  1941. newSocket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)
  1942. try:
  1943. socket.connect($dest, 80.Port)
  1944. result = socket.getLocalAddr()[0].parseIpAddress()
  1945. finally:
  1946. socket.close()