net.nim 80 KB

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