net.nim 80 KB

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