winlean.nim 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a small wrapper for some needed Win API procedures,
  10. ## so that the Nim compiler does not depend on the huge Windows module.
  11. import dynlib
  12. when defined(nimHasStyleChecks):
  13. {.push styleChecks: off.}
  14. {.passc: "-DWIN32_LEAN_AND_MEAN".}
  15. when defined(nimPreviewSlimSystem):
  16. from std/syncio import FileHandle
  17. import std/widestrs
  18. type WinChar* = Utf16Char
  19. # See https://docs.microsoft.com/en-us/windows/win32/winprog/windows-data-types
  20. type
  21. Handle* = int
  22. LONG* = int32
  23. ULONG* = int32
  24. PULONG* = ptr int
  25. WINBOOL* = int32
  26. ## `WINBOOL` uses opposite convention as posix, !=0 meaning success.
  27. # xxx this should be distinct int32, distinct would make code less error prone
  28. PBOOL* = ptr WINBOOL
  29. DWORD* = int32
  30. PDWORD* = ptr DWORD
  31. LPINT* = ptr int32
  32. ULONG_PTR* = uint
  33. PULONG_PTR* = ptr uint
  34. HDC* = Handle
  35. HGLRC* = Handle
  36. BYTE* = uint8
  37. SECURITY_ATTRIBUTES* = object
  38. nLength*: int32
  39. lpSecurityDescriptor*: pointer
  40. bInheritHandle*: WINBOOL
  41. STARTUPINFO* = object
  42. cb*: int32
  43. lpReserved*: cstring
  44. lpDesktop*: cstring
  45. lpTitle*: cstring
  46. dwX*: int32
  47. dwY*: int32
  48. dwXSize*: int32
  49. dwYSize*: int32
  50. dwXCountChars*: int32
  51. dwYCountChars*: int32
  52. dwFillAttribute*: int32
  53. dwFlags*: int32
  54. wShowWindow*: int16
  55. cbReserved2*: int16
  56. lpReserved2*: pointer
  57. hStdInput*: Handle
  58. hStdOutput*: Handle
  59. hStdError*: Handle
  60. PROCESS_INFORMATION* = object
  61. hProcess*: Handle
  62. hThread*: Handle
  63. dwProcessId*: int32
  64. dwThreadId*: int32
  65. FILETIME* = object ## CANNOT BE int64 BECAUSE OF ALIGNMENT
  66. dwLowDateTime*: DWORD
  67. dwHighDateTime*: DWORD
  68. BY_HANDLE_FILE_INFORMATION* = object
  69. dwFileAttributes*: DWORD
  70. ftCreationTime*: FILETIME
  71. ftLastAccessTime*: FILETIME
  72. ftLastWriteTime*: FILETIME
  73. dwVolumeSerialNumber*: DWORD
  74. nFileSizeHigh*: DWORD
  75. nFileSizeLow*: DWORD
  76. nNumberOfLinks*: DWORD
  77. nFileIndexHigh*: DWORD
  78. nFileIndexLow*: DWORD
  79. OSVERSIONINFO* = object
  80. dwOSVersionInfoSize*: DWORD
  81. dwMajorVersion*: DWORD
  82. dwMinorVersion*: DWORD
  83. dwBuildNumber*: DWORD
  84. dwPlatformId*: DWORD
  85. szCSDVersion*: array[0..127, WinChar]
  86. Protoent* = object
  87. p_name*: cstring
  88. p_aliases*: cstringArray
  89. p_proto*: cshort
  90. const
  91. STARTF_USESHOWWINDOW* = 1'i32
  92. STARTF_USESTDHANDLES* = 256'i32
  93. HIGH_PRIORITY_CLASS* = 128'i32
  94. IDLE_PRIORITY_CLASS* = 64'i32
  95. NORMAL_PRIORITY_CLASS* = 32'i32
  96. REALTIME_PRIORITY_CLASS* = 256'i32
  97. WAIT_OBJECT_0* = 0'i32
  98. WAIT_TIMEOUT* = 0x00000102'i32
  99. WAIT_FAILED* = 0xFFFFFFFF'i32
  100. INFINITE* = -1'i32
  101. STILL_ACTIVE* = 0x00000103'i32
  102. STD_INPUT_HANDLE* = -10'i32
  103. STD_OUTPUT_HANDLE* = -11'i32
  104. STD_ERROR_HANDLE* = -12'i32
  105. DETACHED_PROCESS* = 8'i32
  106. SW_SHOWNORMAL* = 1'i32
  107. INVALID_HANDLE_VALUE* = Handle(-1)
  108. CREATE_UNICODE_ENVIRONMENT* = 1024'i32
  109. PIPE_ACCESS_DUPLEX* = 0x00000003'i32
  110. PIPE_ACCESS_INBOUND* = 1'i32
  111. PIPE_ACCESS_OUTBOUND* = 2'i32
  112. PIPE_NOWAIT* = 0x00000001'i32
  113. SYNCHRONIZE* = 0x00100000'i32
  114. CREATE_NO_WINDOW* = 0x08000000'i32
  115. HANDLE_FLAG_INHERIT* = 0x00000001'i32
  116. proc isSuccess*(a: WINBOOL): bool {.inline.} =
  117. ## Returns true if `a != 0`. Windows uses a different convention than POSIX,
  118. ## where `a == 0` is commonly used on success.
  119. a != 0
  120. proc getVersionExW*(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL {.
  121. stdcall, dynlib: "kernel32", importc: "GetVersionExW", sideEffect.}
  122. proc getVersionExA*(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL {.
  123. stdcall, dynlib: "kernel32", importc: "GetVersionExA", sideEffect.}
  124. proc getVersion*(): DWORD {.stdcall, dynlib: "kernel32", importc: "GetVersion", sideEffect.}
  125. proc closeHandle*(hObject: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
  126. importc: "CloseHandle".}
  127. proc readFile*(hFile: Handle, buffer: pointer, nNumberOfBytesToRead: int32,
  128. lpNumberOfBytesRead: ptr int32, lpOverlapped: pointer): WINBOOL{.
  129. stdcall, dynlib: "kernel32", importc: "ReadFile", sideEffect.}
  130. proc writeFile*(hFile: Handle, buffer: pointer, nNumberOfBytesToWrite: int32,
  131. lpNumberOfBytesWritten: ptr int32,
  132. lpOverlapped: pointer): WINBOOL{.
  133. stdcall, dynlib: "kernel32", importc: "WriteFile", sideEffect.}
  134. proc createPipe*(hReadPipe, hWritePipe: var Handle,
  135. lpPipeAttributes: var SECURITY_ATTRIBUTES,
  136. nSize: int32): WINBOOL{.
  137. stdcall, dynlib: "kernel32", importc: "CreatePipe", sideEffect.}
  138. proc createNamedPipe*(lpName: WideCString,
  139. dwOpenMode, dwPipeMode, nMaxInstances, nOutBufferSize,
  140. nInBufferSize, nDefaultTimeOut: int32,
  141. lpSecurityAttributes: ptr SECURITY_ATTRIBUTES): Handle {.
  142. stdcall, dynlib: "kernel32", importc: "CreateNamedPipeW", sideEffect.}
  143. proc peekNamedPipe*(hNamedPipe: Handle, lpBuffer: pointer=nil,
  144. nBufferSize: int32 = 0,
  145. lpBytesRead: ptr int32 = nil,
  146. lpTotalBytesAvail: ptr int32 = nil,
  147. lpBytesLeftThisMessage: ptr int32 = nil): bool {.
  148. stdcall, dynlib: "kernel32", importc: "PeekNamedPipe".}
  149. proc createProcessW*(lpApplicationName, lpCommandLine: WideCString,
  150. lpProcessAttributes: ptr SECURITY_ATTRIBUTES,
  151. lpThreadAttributes: ptr SECURITY_ATTRIBUTES,
  152. bInheritHandles: WINBOOL, dwCreationFlags: int32,
  153. lpEnvironment, lpCurrentDirectory: WideCString,
  154. lpStartupInfo: var STARTUPINFO,
  155. lpProcessInformation: var PROCESS_INFORMATION): WINBOOL{.
  156. stdcall, dynlib: "kernel32", importc: "CreateProcessW", sideEffect.}
  157. proc suspendThread*(hThread: Handle): int32 {.stdcall, dynlib: "kernel32",
  158. importc: "SuspendThread", sideEffect.}
  159. proc resumeThread*(hThread: Handle): int32 {.stdcall, dynlib: "kernel32",
  160. importc: "ResumeThread", sideEffect.}
  161. proc waitForSingleObject*(hHandle: Handle, dwMilliseconds: int32): int32 {.
  162. stdcall, dynlib: "kernel32", importc: "WaitForSingleObject", sideEffect.}
  163. proc terminateProcess*(hProcess: Handle, uExitCode: int): WINBOOL {.stdcall,
  164. dynlib: "kernel32", importc: "TerminateProcess", sideEffect.}
  165. proc getExitCodeProcess*(hProcess: Handle, lpExitCode: var int32): WINBOOL {.
  166. stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".}
  167. proc getStdHandle*(nStdHandle: int32): Handle {.stdcall, dynlib: "kernel32",
  168. importc: "GetStdHandle".}
  169. proc setStdHandle*(nStdHandle: int32, hHandle: Handle): WINBOOL {.stdcall,
  170. dynlib: "kernel32", importc: "SetStdHandle", sideEffect.}
  171. proc flushFileBuffers*(hFile: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
  172. importc: "FlushFileBuffers", sideEffect.}
  173. proc getLastError*(): int32 {.importc: "GetLastError",
  174. stdcall, dynlib: "kernel32", sideEffect.}
  175. proc setLastError*(error: int32) {.importc: "SetLastError",
  176. stdcall, dynlib: "kernel32", sideEffect.}
  177. proc formatMessageW*(dwFlags: int32, lpSource: pointer,
  178. dwMessageId, dwLanguageId: int32,
  179. lpBuffer: pointer, nSize: int32,
  180. arguments: pointer): int32 {.
  181. importc: "FormatMessageW", stdcall, dynlib: "kernel32".}
  182. proc localFree*(p: pointer) {.
  183. importc: "LocalFree", stdcall, dynlib: "kernel32".}
  184. proc getCurrentDirectoryW*(nBufferLength: int32,
  185. lpBuffer: WideCString): int32 {.
  186. importc: "GetCurrentDirectoryW", dynlib: "kernel32", stdcall, sideEffect.}
  187. proc setCurrentDirectoryW*(lpPathName: WideCString): int32 {.
  188. importc: "SetCurrentDirectoryW", dynlib: "kernel32", stdcall, sideEffect.}
  189. proc createDirectoryW*(pathName: WideCString, security: pointer=nil): int32 {.
  190. importc: "CreateDirectoryW", dynlib: "kernel32", stdcall, sideEffect.}
  191. proc removeDirectoryW*(lpPathName: WideCString): int32 {.
  192. importc: "RemoveDirectoryW", dynlib: "kernel32", stdcall, sideEffect.}
  193. proc setEnvironmentVariableW*(lpName, lpValue: WideCString): int32 {.
  194. stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW", sideEffect.}
  195. proc getModuleFileNameW*(handle: Handle, buf: WideCString,
  196. size: int32): int32 {.importc: "GetModuleFileNameW",
  197. dynlib: "kernel32", stdcall.}
  198. proc createSymbolicLinkW*(lpSymlinkFileName, lpTargetFileName: WideCString,
  199. flags: DWORD): int32 {.
  200. importc:"CreateSymbolicLinkW", dynlib: "kernel32", stdcall, sideEffect.}
  201. proc createHardLinkW*(lpFileName, lpExistingFileName: WideCString,
  202. security: pointer=nil): int32 {.
  203. importc:"CreateHardLinkW", dynlib: "kernel32", stdcall, sideEffect.}
  204. const
  205. FILE_ATTRIBUTE_READONLY* = 0x00000001'i32
  206. FILE_ATTRIBUTE_HIDDEN* = 0x00000002'i32
  207. FILE_ATTRIBUTE_SYSTEM* = 0x00000004'i32
  208. FILE_ATTRIBUTE_DIRECTORY* = 0x00000010'i32
  209. FILE_ATTRIBUTE_ARCHIVE* = 0x00000020'i32
  210. FILE_ATTRIBUTE_DEVICE* = 0x00000040'i32
  211. FILE_ATTRIBUTE_NORMAL* = 0x00000080'i32
  212. FILE_ATTRIBUTE_TEMPORARY* = 0x00000100'i32
  213. FILE_ATTRIBUTE_SPARSE_FILE* = 0x00000200'i32
  214. FILE_ATTRIBUTE_REPARSE_POINT* = 0x00000400'i32
  215. FILE_ATTRIBUTE_COMPRESSED* = 0x00000800'i32
  216. FILE_ATTRIBUTE_OFFLINE* = 0x00001000'i32
  217. FILE_ATTRIBUTE_NOT_CONTENT_INDEXED* = 0x00002000'i32
  218. FILE_FLAG_FIRST_PIPE_INSTANCE* = 0x00080000'i32
  219. FILE_FLAG_OPEN_NO_RECALL* = 0x00100000'i32
  220. FILE_FLAG_OPEN_REPARSE_POINT* = 0x00200000'i32
  221. FILE_FLAG_POSIX_SEMANTICS* = 0x01000000'i32
  222. FILE_FLAG_BACKUP_SEMANTICS* = 0x02000000'i32
  223. FILE_FLAG_DELETE_ON_CLOSE* = 0x04000000'i32
  224. FILE_FLAG_SEQUENTIAL_SCAN* = 0x08000000'i32
  225. FILE_FLAG_RANDOM_ACCESS* = 0x10000000'i32
  226. FILE_FLAG_NO_BUFFERING* = 0x20000000'i32
  227. FILE_FLAG_OVERLAPPED* = 0x40000000'i32
  228. FILE_FLAG_WRITE_THROUGH* = 0x80000000'i32
  229. MAX_PATH* = 260
  230. MOVEFILE_COPY_ALLOWED* = 0x2'i32
  231. MOVEFILE_CREATE_HARDLINK* = 0x10'i32
  232. MOVEFILE_DELAY_UNTIL_REBOOT* = 0x4'i32
  233. MOVEFILE_FAIL_IF_NOT_TRACKABLE* = 0x20'i32
  234. MOVEFILE_REPLACE_EXISTING* = 0x1'i32
  235. MOVEFILE_WRITE_THROUGH* = 0x8'i32
  236. type
  237. WIN32_FIND_DATA* {.pure.} = object
  238. dwFileAttributes*: int32
  239. ftCreationTime*: FILETIME
  240. ftLastAccessTime*: FILETIME
  241. ftLastWriteTime*: FILETIME
  242. nFileSizeHigh*: int32
  243. nFileSizeLow*: int32
  244. dwReserved0: int32
  245. dwReserved1: int32
  246. cFileName*: array[0..(MAX_PATH) - 1, WinChar]
  247. cAlternateFileName*: array[0..13, WinChar]
  248. proc findFirstFileW*(lpFileName: WideCString,
  249. lpFindFileData: var WIN32_FIND_DATA): Handle {.
  250. stdcall, dynlib: "kernel32", importc: "FindFirstFileW", sideEffect.}
  251. proc findNextFileW*(hFindFile: Handle,
  252. lpFindFileData: var WIN32_FIND_DATA): int32 {.
  253. stdcall, dynlib: "kernel32", importc: "FindNextFileW", sideEffect.}
  254. proc findClose*(hFindFile: Handle) {.stdcall, dynlib: "kernel32",
  255. importc: "FindClose".}
  256. proc getFullPathNameW*(lpFileName: WideCString, nBufferLength: int32,
  257. lpBuffer: WideCString,
  258. lpFilePart: var WideCString): int32 {.
  259. stdcall, dynlib: "kernel32",
  260. importc: "GetFullPathNameW", sideEffect.}
  261. proc getFileAttributesW*(lpFileName: WideCString): int32 {.
  262. stdcall, dynlib: "kernel32",
  263. importc: "GetFileAttributesW", sideEffect.}
  264. proc setFileAttributesW*(lpFileName: WideCString,
  265. dwFileAttributes: int32): WINBOOL {.
  266. stdcall, dynlib: "kernel32", importc: "SetFileAttributesW", sideEffect.}
  267. proc copyFileW*(lpExistingFileName, lpNewFileName: WideCString,
  268. bFailIfExists: WINBOOL): WINBOOL {.
  269. importc: "CopyFileW", stdcall, dynlib: "kernel32", sideEffect.}
  270. proc moveFileW*(lpExistingFileName, lpNewFileName: WideCString): WINBOOL {.
  271. importc: "MoveFileW", stdcall, dynlib: "kernel32", sideEffect.}
  272. proc moveFileExW*(lpExistingFileName, lpNewFileName: WideCString,
  273. flags: DWORD): WINBOOL {.
  274. importc: "MoveFileExW", stdcall, dynlib: "kernel32", sideEffect.}
  275. proc getEnvironmentStringsW*(): WideCString {.
  276. stdcall, dynlib: "kernel32", importc: "GetEnvironmentStringsW", sideEffect.}
  277. proc freeEnvironmentStringsW*(para1: WideCString): int32 {.
  278. stdcall, dynlib: "kernel32", importc: "FreeEnvironmentStringsW", sideEffect.}
  279. proc getCommandLineW*(): WideCString {.importc: "GetCommandLineW",
  280. stdcall, dynlib: "kernel32", sideEffect.}
  281. proc rdFileTime*(f: FILETIME): int64 =
  282. result = int64(cast[uint32](f.dwLowDateTime)) or (int64(cast[uint32](f.dwHighDateTime)) shl 32)
  283. proc rdFileSize*(f: WIN32_FIND_DATA): int64 =
  284. result = int64(cast[uint32](f.nFileSizeLow)) or (int64(cast[uint32](f.nFileSizeHigh)) shl 32)
  285. proc getSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var FILETIME) {.
  286. importc: "GetSystemTimeAsFileTime", dynlib: "kernel32", stdcall, sideEffect.}
  287. proc sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32",
  288. importc: "Sleep", sideEffect.}
  289. proc shellExecuteW*(hwnd: Handle, lpOperation, lpFile,
  290. lpParameters, lpDirectory: WideCString,
  291. nShowCmd: int32): Handle{.
  292. stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW", sideEffect.}
  293. proc getFileInformationByHandle*(hFile: Handle,
  294. lpFileInformation: ptr BY_HANDLE_FILE_INFORMATION): WINBOOL{.
  295. stdcall, dynlib: "kernel32", importc: "GetFileInformationByHandle", sideEffect.}
  296. const
  297. WSADESCRIPTION_LEN* = 256
  298. WSASYS_STATUS_LEN* = 128
  299. FD_SETSIZE* = 64
  300. MSG_PEEK* = 2
  301. INADDR_ANY* = 0'u32
  302. INADDR_LOOPBACK* = 0x7F000001
  303. INADDR_BROADCAST* = -1
  304. INADDR_NONE* = -1
  305. ws2dll = "Ws2_32.dll"
  306. proc wsaGetLastError*(): cint {.importc: "WSAGetLastError", dynlib: ws2dll, sideEffect.}
  307. type
  308. SocketHandle* = distinct int
  309. type
  310. WSAData* {.importc: "WSADATA", header: "winsock2.h".} = object
  311. wVersion, wHighVersion: int16
  312. szDescription: array[0..WSADESCRIPTION_LEN, char]
  313. szSystemStatus: array[0..WSASYS_STATUS_LEN, char]
  314. iMaxSockets, iMaxUdpDg: int16
  315. lpVendorInfo: cstring
  316. SockAddr* {.importc: "SOCKADDR", header: "winsock2.h".} = object
  317. sa_family*: uint16
  318. sa_data*: array[0..13, char]
  319. PSockAddr = ptr SockAddr
  320. InAddr* {.importc: "IN_ADDR", header: "winsock2.h", union.} = object
  321. s_addr*: uint32 # IP address
  322. Sockaddr_in* {.importc: "SOCKADDR_IN",
  323. header: "winsock2.h".} = object
  324. sin_family*: uint16
  325. sin_port*: uint16
  326. sin_addr*: InAddr
  327. sin_zero*: array[0..7, char]
  328. In6_addr* {.importc: "IN6_ADDR", header: "winsock2.h".} = object
  329. bytes* {.importc: "u.Byte".}: array[0..15, char]
  330. Sockaddr_in6* {.importc: "SOCKADDR_IN6",
  331. header: "ws2tcpip.h".} = object
  332. sin6_family*: uint16
  333. sin6_port*: uint16
  334. sin6_flowinfo*: int32 # unsigned
  335. sin6_addr*: In6_addr
  336. sin6_scope_id*: int32 # unsigned
  337. Sockaddr_storage* {.importc: "SOCKADDR_STORAGE",
  338. header: "winsock2.h".} = object
  339. ss_family*: uint16
  340. ss_pad1 {.importc: "__ss_pad1".}: array[6, byte]
  341. ss_align {.importc: "__ss_align".}: int64
  342. ss_pad2 {.importc: "__ss_pad2".}: array[112, byte]
  343. Servent* = object
  344. s_name*: cstring
  345. s_aliases*: cstringArray
  346. when defined(cpu64):
  347. s_proto*: cstring
  348. s_port*: int16
  349. else:
  350. s_port*: int16
  351. s_proto*: cstring
  352. Hostent* = object
  353. h_name*: cstring
  354. h_aliases*: cstringArray
  355. h_addrtype*: int16
  356. h_length*: int16
  357. h_addr_list*: cstringArray
  358. TFdSet* = object
  359. fd_count*: cint # unsigned
  360. fd_array*: array[0..FD_SETSIZE-1, SocketHandle]
  361. AddrInfo* = object
  362. ai_flags*: cint ## Input flags.
  363. ai_family*: cint ## Address family of socket.
  364. ai_socktype*: cint ## Socket type.
  365. ai_protocol*: cint ## Protocol of socket.
  366. ai_addrlen*: csize_t ## Length of socket address.
  367. ai_canonname*: cstring ## Canonical name of service location.
  368. ai_addr*: ptr SockAddr ## Socket address of socket.
  369. ai_next*: ptr AddrInfo ## Pointer to next in list.
  370. SockLen* = cuint
  371. type
  372. Timeval* {.importc: "struct timeval", header: "<time.h>".} = object
  373. tv_sec*, tv_usec*: int32
  374. var
  375. SOMAXCONN* {.importc, header: "winsock2.h".}: cint
  376. INVALID_SOCKET* {.importc, header: "winsock2.h".}: SocketHandle
  377. SOL_SOCKET* {.importc, header: "winsock2.h".}: cint
  378. SO_DEBUG* {.importc, header: "winsock2.h".}: cint ## turn on debugging info recording
  379. SO_ACCEPTCONN* {.importc, header: "winsock2.h".}: cint # socket has had listen()
  380. SO_REUSEADDR* {.importc, header: "winsock2.h".}: cint # allow local address reuse
  381. SO_REUSEPORT* {.importc: "SO_REUSEADDR", header: "winsock2.h".}: cint # allow port reuse. Since Windows does not really support it, mapped to SO_REUSEADDR. This shouldn't cause problems.
  382. SO_KEEPALIVE* {.importc, header: "winsock2.h".}: cint # keep connections alive
  383. SO_DONTROUTE* {.importc, header: "winsock2.h".}: cint # just use interface addresses
  384. SO_BROADCAST* {.importc, header: "winsock2.h".}: cint # permit sending of broadcast msgs
  385. SO_USELOOPBACK* {.importc, header: "winsock2.h".}: cint # bypass hardware when possible
  386. SO_LINGER* {.importc, header: "winsock2.h".}: cint # linger on close if data present
  387. SO_OOBINLINE* {.importc, header: "winsock2.h".}: cint # leave received OOB data in line
  388. SO_DONTLINGER* {.importc, header: "winsock2.h".}: cint
  389. SO_EXCLUSIVEADDRUSE* {.importc, header: "winsock2.h".}: cint # disallow local address reuse
  390. SO_ERROR* {.importc, header: "winsock2.h".}: cint
  391. TCP_NODELAY* {.importc, header: "winsock2.h".}: cint
  392. proc `==`*(x, y: SocketHandle): bool {.borrow.}
  393. proc getservbyname*(name, proto: cstring): ptr Servent {.
  394. stdcall, importc: "getservbyname", dynlib: ws2dll, sideEffect.}
  395. proc getservbyport*(port: cint, proto: cstring): ptr Servent {.
  396. stdcall, importc: "getservbyport", dynlib: ws2dll, sideEffect.}
  397. proc gethostbyaddr*(ip: ptr InAddr, len: cuint, theType: cint): ptr Hostent {.
  398. stdcall, importc: "gethostbyaddr", dynlib: ws2dll, sideEffect.}
  399. proc gethostbyname*(name: cstring): ptr Hostent {.
  400. stdcall, importc: "gethostbyname", dynlib: ws2dll, sideEffect.}
  401. proc gethostname*(hostname: cstring, len: cint): cint {.
  402. stdcall, importc: "gethostname", dynlib: ws2dll, sideEffect.}
  403. proc getprotobyname*(
  404. name: cstring
  405. ): ptr Protoent {.stdcall, importc: "getprotobyname", dynlib: ws2dll, sideEffect.}
  406. proc getprotobynumber*(
  407. proto: cint
  408. ): ptr Protoent {.stdcall, importc: "getprotobynumber", dynlib: ws2dll, sideEffect.}
  409. proc socket*(af, typ, protocol: cint): SocketHandle {.
  410. stdcall, importc: "socket", dynlib: ws2dll.}
  411. proc closesocket*(s: SocketHandle): cint {.
  412. stdcall, importc: "closesocket", dynlib: ws2dll.}
  413. proc accept*(s: SocketHandle, a: ptr SockAddr, addrlen: ptr SockLen): SocketHandle {.
  414. stdcall, importc: "accept", dynlib: ws2dll.}
  415. proc bindSocket*(s: SocketHandle, name: ptr SockAddr, namelen: SockLen): cint {.
  416. stdcall, importc: "bind", dynlib: ws2dll.}
  417. proc connect*(s: SocketHandle, name: ptr SockAddr, namelen: SockLen): cint {.
  418. stdcall, importc: "connect", dynlib: ws2dll.}
  419. proc getsockname*(s: SocketHandle, name: ptr SockAddr,
  420. namelen: ptr SockLen): cint {.
  421. stdcall, importc: "getsockname", dynlib: ws2dll.}
  422. proc getpeername*(s: SocketHandle, name: ptr SockAddr,
  423. namelen: ptr SockLen): cint {.
  424. stdcall, importc, dynlib: ws2dll.}
  425. proc getsockopt*(s: SocketHandle, level, optname: cint, optval: pointer,
  426. optlen: ptr SockLen): cint {.
  427. stdcall, importc: "getsockopt", dynlib: ws2dll.}
  428. proc setsockopt*(s: SocketHandle, level, optname: cint, optval: pointer,
  429. optlen: SockLen): cint {.
  430. stdcall, importc: "setsockopt", dynlib: ws2dll.}
  431. proc listen*(s: SocketHandle, backlog: cint): cint {.
  432. stdcall, importc: "listen", dynlib: ws2dll.}
  433. proc recv*(s: SocketHandle, buf: pointer, len, flags: cint): cint {.
  434. stdcall, importc: "recv", dynlib: ws2dll.}
  435. proc recvfrom*(s: SocketHandle, buf: cstring, len, flags: cint,
  436. fromm: ptr SockAddr, fromlen: ptr SockLen): cint {.
  437. stdcall, importc: "recvfrom", dynlib: ws2dll.}
  438. proc select*(nfds: cint, readfds, writefds, exceptfds: ptr TFdSet,
  439. timeout: ptr Timeval): cint {.
  440. stdcall, importc: "select", dynlib: ws2dll.}
  441. proc send*(s: SocketHandle, buf: pointer, len, flags: cint): cint {.
  442. stdcall, importc: "send", dynlib: ws2dll.}
  443. proc sendto*(s: SocketHandle, buf: pointer, len, flags: cint,
  444. to: ptr SockAddr, tolen: SockLen): cint {.
  445. stdcall, importc: "sendto", dynlib: ws2dll.}
  446. proc shutdown*(s: SocketHandle, how: cint): cint {.
  447. stdcall, importc: "shutdown", dynlib: ws2dll.}
  448. proc getnameinfo*(a1: ptr SockAddr, a2: SockLen,
  449. a3: cstring, a4: SockLen, a5: cstring,
  450. a6: SockLen, a7: cint): cint {.
  451. stdcall, importc: "getnameinfo", dynlib: ws2dll.}
  452. proc inet_addr*(cp: cstring): uint32 {.
  453. stdcall, importc: "inet_addr", dynlib: ws2dll.}
  454. proc WSAFDIsSet(s: SocketHandle, set: var TFdSet): bool {.
  455. stdcall, importc: "__WSAFDIsSet", dynlib: ws2dll, noSideEffect.}
  456. proc FD_ISSET*(socket: SocketHandle, set: var TFdSet): cint =
  457. result = if WSAFDIsSet(socket, set): 1'i32 else: 0'i32
  458. proc FD_SET*(socket: SocketHandle, s: var TFdSet) =
  459. if s.fd_count < FD_SETSIZE:
  460. s.fd_array[int(s.fd_count)] = socket
  461. inc(s.fd_count)
  462. proc FD_ZERO*(s: var TFdSet) =
  463. s.fd_count = 0
  464. proc wsaStartup*(wVersionRequired: int16, WSData: ptr WSAData): cint {.
  465. stdcall, importc: "WSAStartup", dynlib: ws2dll.}
  466. proc getaddrinfo*(nodename, servname: cstring, hints: ptr AddrInfo,
  467. res: var ptr AddrInfo): cint {.
  468. stdcall, importc: "getaddrinfo", dynlib: ws2dll.}
  469. proc freeAddrInfo*(ai: ptr AddrInfo) {.
  470. stdcall, importc: "freeaddrinfo", dynlib: ws2dll.}
  471. proc inet_ntoa*(i: InAddr): cstring {.
  472. stdcall, importc, dynlib: ws2dll.}
  473. const
  474. MAXIMUM_WAIT_OBJECTS* = 0x00000040
  475. type
  476. WOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, Handle]
  477. PWOHandleArray* = ptr WOHandleArray
  478. proc waitForMultipleObjects*(nCount: DWORD, lpHandles: PWOHandleArray,
  479. bWaitAll: WINBOOL, dwMilliseconds: DWORD): DWORD{.
  480. stdcall, dynlib: "kernel32", importc: "WaitForMultipleObjects".}
  481. # for memfiles.nim:
  482. const
  483. GENERIC_READ* = 0x80000000'i32
  484. GENERIC_WRITE* = 0x40000000'i32
  485. GENERIC_ALL* = 0x10000000'i32
  486. FILE_SHARE_READ* = 1'i32
  487. FILE_SHARE_DELETE* = 4'i32
  488. FILE_SHARE_WRITE* = 2'i32
  489. CREATE_ALWAYS* = 2'i32
  490. CREATE_NEW* = 1'i32
  491. OPEN_EXISTING* = 3'i32
  492. OPEN_ALWAYS* = 4'i32
  493. FILE_BEGIN* = 0'i32
  494. INVALID_SET_FILE_POINTER* = -1'i32
  495. NO_ERROR* = 0'i32
  496. PAGE_NOACCESS* = 0x01'i32
  497. PAGE_EXECUTE* = 0x10'i32
  498. PAGE_EXECUTE_READ* = 0x20'i32
  499. PAGE_EXECUTE_READWRITE* = 0x40'i32
  500. PAGE_READONLY* = 2'i32
  501. PAGE_READWRITE* = 4'i32
  502. FILE_MAP_READ* = 4'i32
  503. FILE_MAP_WRITE* = 2'i32
  504. INVALID_FILE_SIZE* = -1'i32
  505. DUPLICATE_SAME_ACCESS* = 2
  506. FILE_READ_DATA* = 0x00000001 # file & pipe
  507. FILE_WRITE_DATA* = 0x00000002 # file & pipe
  508. # Error Constants
  509. const
  510. ERROR_FILE_NOT_FOUND* = 2 ## https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
  511. ERROR_PATH_NOT_FOUND* = 3
  512. ERROR_ACCESS_DENIED* = 5
  513. ERROR_NO_MORE_FILES* = 18
  514. ERROR_LOCK_VIOLATION* = 33
  515. ERROR_HANDLE_EOF* = 38
  516. ERROR_FILE_EXISTS* = 80
  517. ERROR_BAD_ARGUMENTS* = 165
  518. proc duplicateHandle*(hSourceProcessHandle: Handle, hSourceHandle: Handle,
  519. hTargetProcessHandle: Handle,
  520. lpTargetHandle: ptr Handle,
  521. dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
  522. dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
  523. importc: "DuplicateHandle".}
  524. proc getHandleInformation*(hObject: Handle, lpdwFlags: ptr DWORD): WINBOOL {.
  525. stdcall, dynlib: "kernel32", importc: "GetHandleInformation".}
  526. proc setHandleInformation*(hObject: Handle, dwMask: DWORD,
  527. dwFlags: DWORD): WINBOOL {.stdcall,
  528. dynlib: "kernel32", importc: "SetHandleInformation".}
  529. proc getCurrentProcess*(): Handle{.stdcall, dynlib: "kernel32",
  530. importc: "GetCurrentProcess".}
  531. proc createFileW*(lpFileName: WideCString, dwDesiredAccess, dwShareMode: DWORD,
  532. lpSecurityAttributes: pointer,
  533. dwCreationDisposition, dwFlagsAndAttributes: DWORD,
  534. hTemplateFile: Handle): Handle {.
  535. stdcall, dynlib: "kernel32", importc: "CreateFileW".}
  536. proc deleteFileW*(pathName: WideCString): int32 {.
  537. importc: "DeleteFileW", dynlib: "kernel32", stdcall.}
  538. proc createFileA*(lpFileName: cstring, dwDesiredAccess, dwShareMode: DWORD,
  539. lpSecurityAttributes: pointer,
  540. dwCreationDisposition, dwFlagsAndAttributes: DWORD,
  541. hTemplateFile: Handle): Handle {.
  542. stdcall, dynlib: "kernel32", importc: "CreateFileA".}
  543. proc deleteFileA*(pathName: cstring): int32 {.
  544. importc: "DeleteFileA", dynlib: "kernel32", stdcall.}
  545. proc setEndOfFile*(hFile: Handle): WINBOOL {.stdcall, dynlib: "kernel32",
  546. importc: "SetEndOfFile".}
  547. proc setFilePointer*(hFile: Handle, lDistanceToMove: LONG,
  548. lpDistanceToMoveHigh: ptr LONG,
  549. dwMoveMethod: DWORD): DWORD {.
  550. stdcall, dynlib: "kernel32", importc: "SetFilePointer".}
  551. proc getFileSize*(hFile: Handle, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall,
  552. dynlib: "kernel32", importc: "GetFileSize".}
  553. when defined(cpu32):
  554. type
  555. WinSizeT* = uint32
  556. else:
  557. type
  558. WinSizeT* = uint64
  559. proc mapViewOfFileEx*(hFileMappingObject: Handle, dwDesiredAccess: DWORD,
  560. dwFileOffsetHigh, dwFileOffsetLow: DWORD,
  561. dwNumberOfBytesToMap: WinSizeT,
  562. lpBaseAddress: pointer): pointer{.
  563. stdcall, dynlib: "kernel32", importc: "MapViewOfFileEx".}
  564. proc createFileMappingW*(hFile: Handle,
  565. lpFileMappingAttributes: pointer,
  566. flProtect, dwMaximumSizeHigh: DWORD,
  567. dwMaximumSizeLow: DWORD,
  568. lpName: pointer): Handle {.
  569. stdcall, dynlib: "kernel32", importc: "CreateFileMappingW".}
  570. proc unmapViewOfFile*(lpBaseAddress: pointer): WINBOOL {.stdcall,
  571. dynlib: "kernel32", importc: "UnmapViewOfFile".}
  572. proc flushViewOfFile*(lpBaseAddress: pointer, dwNumberOfBytesToFlush: DWORD): WINBOOL {.
  573. stdcall, dynlib: "kernel32", importc: "FlushViewOfFile".}
  574. type
  575. OVERLAPPED* {.pure, inheritable.} = object
  576. internal*: PULONG
  577. internalHigh*: PULONG
  578. offset*: DWORD
  579. offsetHigh*: DWORD
  580. hEvent*: Handle
  581. POVERLAPPED* = ptr OVERLAPPED
  582. POVERLAPPED_COMPLETION_ROUTINE* = proc (para1: DWORD, para2: DWORD,
  583. para3: POVERLAPPED){.stdcall.}
  584. GUID* = object
  585. D1*: int32
  586. D2*: int16
  587. D3*: int16
  588. D4*: array[0..7, int8]
  589. const
  590. ERROR_IO_PENDING* = 997 # a.k.a WSA_IO_PENDING
  591. WSAECONNABORTED* = 10053
  592. WSAEADDRINUSE* = 10048
  593. WSAECONNRESET* = 10054
  594. WSAEDISCON* = 10101
  595. WSAENETRESET* = 10052
  596. WSAETIMEDOUT* = 10060
  597. WSANOTINITIALISED* = 10093
  598. WSAENOTSOCK* = 10038
  599. WSAEINPROGRESS* = 10036
  600. WSAEINTR* = 10004
  601. WSAEWOULDBLOCK* = 10035
  602. WSAESHUTDOWN* = 10058
  603. ERROR_NETNAME_DELETED* = 64
  604. STATUS_PENDING* = 0x103
  605. proc createIoCompletionPort*(FileHandle: Handle, ExistingCompletionPort: Handle,
  606. CompletionKey: ULONG_PTR,
  607. NumberOfConcurrentThreads: DWORD): Handle{.stdcall,
  608. dynlib: "kernel32", importc: "CreateIoCompletionPort".}
  609. proc getQueuedCompletionStatus*(CompletionPort: Handle,
  610. lpNumberOfBytesTransferred: PDWORD, lpCompletionKey: PULONG_PTR,
  611. lpOverlapped: ptr POVERLAPPED,
  612. dwMilliseconds: DWORD): WINBOOL{.stdcall,
  613. dynlib: "kernel32", importc: "GetQueuedCompletionStatus".}
  614. proc getOverlappedResult*(hFile: Handle, lpOverlapped: POVERLAPPED,
  615. lpNumberOfBytesTransferred: var DWORD, bWait: WINBOOL): WINBOOL{.
  616. stdcall, dynlib: "kernel32", importc: "GetOverlappedResult".}
  617. # this is copy of HasOverlappedIoCompleted() macro from <winbase.h>
  618. # because we have declared own OVERLAPPED structure with member names not
  619. # compatible with original names.
  620. template hasOverlappedIoCompleted*(lpOverlapped): bool =
  621. (cast[uint](lpOverlapped.internal) != STATUS_PENDING)
  622. const
  623. IOC_OUT* = 0x40000000'i32
  624. IOC_IN* = 0x80000000'i32
  625. IOC_WS2* = 0x08000000'i32
  626. IOC_INOUT* = IOC_IN or IOC_OUT
  627. template WSAIORW*(x,y): untyped = (IOC_INOUT or x or y)
  628. const
  629. SIO_GET_EXTENSION_FUNCTION_POINTER* = WSAIORW(IOC_WS2,6).DWORD
  630. SO_UPDATE_ACCEPT_CONTEXT* = 0x700B
  631. AI_V4MAPPED* = 0x0008
  632. AF_UNSPEC* = 0
  633. AF_INET* = 2
  634. AF_INET6* = 23
  635. var
  636. WSAID_CONNECTEX*: GUID = GUID(D1: 0x25a207b9, D2: 0xddf3'i16, D3: 0x4660, D4: [
  637. 0x8e'i8, 0xe9'i8, 0x76'i8, 0xe5'i8, 0x8c'i8, 0x74'i8, 0x06'i8, 0x3e'i8])
  638. WSAID_ACCEPTEX*: GUID = GUID(D1: 0xb5367df1'i32, D2: 0xcbac'i16, D3: 0x11cf, D4: [
  639. 0x95'i8, 0xca'i8, 0x00'i8, 0x80'i8, 0x5f'i8, 0x48'i8, 0xa1'i8, 0x92'i8])
  640. WSAID_GETACCEPTEXSOCKADDRS*: GUID = GUID(D1: 0xb5367df2'i32, D2: 0xcbac'i16, D3: 0x11cf, D4: [
  641. 0x95'i8, 0xca'i8, 0x00'i8, 0x80'i8, 0x5f'i8, 0x48'i8, 0xa1'i8, 0x92'i8])
  642. proc WSAIoctl*(s: SocketHandle, dwIoControlCode: DWORD, lpvInBuffer: pointer,
  643. cbInBuffer: DWORD, lpvOutBuffer: pointer, cbOutBuffer: DWORD,
  644. lpcbBytesReturned: PDWORD, lpOverlapped: POVERLAPPED,
  645. lpCompletionRoutine: POVERLAPPED_COMPLETION_ROUTINE): cint
  646. {.stdcall, importc: "WSAIoctl", dynlib: "Ws2_32.dll".}
  647. type
  648. TWSABuf* {.importc: "WSABUF", header: "winsock2.h".} = object
  649. len*: ULONG
  650. buf*: cstring
  651. proc WSARecv*(s: SocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
  652. bytesReceived, flags: PDWORD, lpOverlapped: POVERLAPPED,
  653. completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
  654. stdcall, importc: "WSARecv", dynlib: "Ws2_32.dll".}
  655. proc WSARecvFrom*(s: SocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
  656. bytesReceived: PDWORD, flags: PDWORD, name: ptr SockAddr,
  657. namelen: ptr cint, lpOverlapped: POVERLAPPED,
  658. completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
  659. stdcall, importc: "WSARecvFrom", dynlib: "Ws2_32.dll".}
  660. proc WSASend*(s: SocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
  661. bytesSent: PDWORD, flags: DWORD, lpOverlapped: POVERLAPPED,
  662. completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
  663. stdcall, importc: "WSASend", dynlib: "Ws2_32.dll".}
  664. proc WSASendTo*(s: SocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
  665. bytesSent: PDWORD, flags: DWORD, name: ptr SockAddr,
  666. namelen: cint, lpOverlapped: POVERLAPPED,
  667. completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
  668. stdcall, importc: "WSASendTo", dynlib: "Ws2_32.dll".}
  669. proc get_osfhandle*(fd:FileHandle): Handle {.
  670. importc: "_get_osfhandle", header:"<io.h>".}
  671. proc getSystemTimes*(lpIdleTime, lpKernelTime,
  672. lpUserTime: var FILETIME): WINBOOL {.stdcall,
  673. dynlib: "kernel32", importc: "GetSystemTimes".}
  674. proc getProcessTimes*(hProcess: Handle; lpCreationTime, lpExitTime,
  675. lpKernelTime, lpUserTime: var FILETIME): WINBOOL {.stdcall,
  676. dynlib: "kernel32", importc: "GetProcessTimes".}
  677. proc getSystemTimePreciseAsFileTime*(lpSystemTimeAsFileTime: var FILETIME) {.
  678. importc: "GetSystemTimePreciseAsFileTime", dynlib: "kernel32", stdcall, sideEffect.}
  679. type inet_ntop_proc = proc(family: cint, paddr: pointer, pStringBuffer: cstring,
  680. stringBufSize: int32): cstring {.gcsafe, stdcall, tags: [].}
  681. var inet_ntop_real: inet_ntop_proc = nil
  682. let ws2 = loadLib(ws2dll)
  683. if ws2 != nil:
  684. inet_ntop_real = cast[inet_ntop_proc](symAddr(ws2, "inet_ntop"))
  685. proc WSAAddressToStringA(pAddr: ptr SockAddr, addrSize: DWORD, unused: pointer, pBuff: cstring, pBuffSize: ptr DWORD): cint {.stdcall, importc, dynlib: ws2dll.}
  686. proc inet_ntop_emulated(family: cint, paddr: pointer, pStringBuffer: cstring,
  687. stringBufSize: int32): cstring {.stdcall.} =
  688. case family
  689. of AF_INET:
  690. var sa: Sockaddr_in
  691. sa.sin_family = AF_INET
  692. sa.sin_addr = cast[ptr InAddr](paddr)[]
  693. var bs = stringBufSize.DWORD
  694. let r = WSAAddressToStringA(cast[ptr SockAddr](sa.addr), sa.sizeof.DWORD, nil, pStringBuffer, bs.addr)
  695. if r != 0:
  696. result = nil
  697. else:
  698. result = pStringBuffer
  699. of AF_INET6:
  700. var sa: Sockaddr_in6
  701. sa.sin6_family = AF_INET6
  702. sa.sin6_addr = cast[ptr In6_addr](paddr)[]
  703. var bs = stringBufSize.DWORD
  704. let r = WSAAddressToStringA(cast[ptr SockAddr](sa.addr), sa.sizeof.DWORD, nil, pStringBuffer, bs.addr)
  705. if r != 0:
  706. result = nil
  707. else:
  708. result = pStringBuffer
  709. else:
  710. setLastError(ERROR_BAD_ARGUMENTS)
  711. result = nil
  712. proc inet_ntop*(family: cint, paddr: pointer, pStringBuffer: cstring,
  713. stringBufSize: int32): cstring {.stdcall.} =
  714. var ver: OSVERSIONINFO
  715. ver.dwOSVersionInfoSize = sizeof(ver).DWORD
  716. let res = getVersionExW(ver.addr)
  717. if res == 0:
  718. result = nil
  719. elif ver.dwMajorVersion >= 6:
  720. if inet_ntop_real == nil:
  721. quit("Can't load inet_ntop proc from " & ws2dll)
  722. result = inet_ntop_real(family, paddr, pStringBuffer, stringBufSize)
  723. else:
  724. result = inet_ntop_emulated(family, paddr, pStringBuffer, stringBufSize)
  725. type
  726. WSAPROC_ACCEPTEX* = proc (sListenSocket: SocketHandle,
  727. sAcceptSocket: SocketHandle,
  728. lpOutputBuffer: pointer, dwReceiveDataLength: DWORD,
  729. dwLocalAddressLength: DWORD,
  730. dwRemoteAddressLength: DWORD,
  731. lpdwBytesReceived: ptr DWORD,
  732. lpOverlapped: POVERLAPPED): bool {.
  733. stdcall, gcsafe, raises: [].}
  734. WSAPROC_CONNECTEX* = proc (s: SocketHandle, name: ptr SockAddr, namelen: cint,
  735. lpSendBuffer: pointer, dwSendDataLength: DWORD,
  736. lpdwBytesSent: ptr DWORD,
  737. lpOverlapped: POVERLAPPED): bool {.
  738. stdcall, gcsafe, raises: [].}
  739. WSAPROC_GETACCEPTEXSOCKADDRS* = proc(lpOutputBuffer: pointer,
  740. dwReceiveDataLength: DWORD,
  741. dwLocalAddressLength: DWORD,
  742. dwRemoteAddressLength: DWORD,
  743. LocalSockaddr: ptr PSockAddr,
  744. LocalSockaddrLength: ptr cint,
  745. RemoteSockaddr: ptr PSockAddr,
  746. RemoteSockaddrLength: ptr cint) {.
  747. stdcall, gcsafe, raises: [].}
  748. const
  749. WT_EXECUTEDEFAULT* = 0x00000000'i32
  750. WT_EXECUTEINIOTHREAD* = 0x00000001'i32
  751. WT_EXECUTEINUITHREAD* = 0x00000002'i32
  752. WT_EXECUTEINWAITTHREAD* = 0x00000004'i32
  753. WT_EXECUTEONLYONCE* = 0x00000008'i32
  754. WT_EXECUTELONGFUNCTION* = 0x00000010'i32
  755. WT_EXECUTEINTIMERTHREAD* = 0x00000020'i32
  756. WT_EXECUTEINPERSISTENTIOTHREAD* = 0x00000040'i32
  757. WT_EXECUTEINPERSISTENTTHREAD* = 0x00000080'i32
  758. WT_TRANSFER_IMPERSONATION* = 0x00000100'i32
  759. PROCESS_TERMINATE* = 0x00000001'i32
  760. PROCESS_CREATE_THREAD* = 0x00000002'i32
  761. PROCESS_SET_SESSIONID* = 0x00000004'i32
  762. PROCESS_VM_OPERATION* = 0x00000008'i32
  763. PROCESS_VM_READ* = 0x00000010'i32
  764. PROCESS_VM_WRITE* = 0x00000020'i32
  765. PROCESS_DUP_HANDLE* = 0x00000040'i32
  766. PROCESS_CREATE_PROCESS* = 0x00000080'i32
  767. PROCESS_SET_QUOTA* = 0x00000100'i32
  768. PROCESS_SET_INFORMATION* = 0x00000200'i32
  769. PROCESS_QUERY_INFORMATION* = 0x00000400'i32
  770. PROCESS_SUSPEND_RESUME* = 0x00000800'i32
  771. PROCESS_QUERY_LIMITED_INFORMATION* = 0x00001000'i32
  772. PROCESS_SET_LIMITED_INFORMATION* = 0x00002000'i32
  773. type
  774. WAITORTIMERCALLBACK* = proc(para1: pointer, para2: int32) {.stdcall.}
  775. proc postQueuedCompletionStatus*(CompletionPort: Handle,
  776. dwNumberOfBytesTransferred: DWORD,
  777. dwCompletionKey: ULONG_PTR,
  778. lpOverlapped: pointer): bool
  779. {.stdcall, dynlib: "kernel32", importc: "PostQueuedCompletionStatus".}
  780. proc registerWaitForSingleObject*(phNewWaitObject: ptr Handle, hObject: Handle,
  781. Callback: WAITORTIMERCALLBACK,
  782. Context: pointer,
  783. dwMilliseconds: ULONG,
  784. dwFlags: ULONG): bool
  785. {.stdcall, dynlib: "kernel32", importc: "RegisterWaitForSingleObject".}
  786. proc unregisterWait*(WaitHandle: Handle): DWORD
  787. {.stdcall, dynlib: "kernel32", importc: "UnregisterWait".}
  788. proc openProcess*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
  789. dwProcessId: DWORD): Handle
  790. {.stdcall, dynlib: "kernel32", importc: "OpenProcess".}
  791. proc createEvent*(lpEventAttributes: ptr SECURITY_ATTRIBUTES,
  792. bManualReset: DWORD, bInitialState: DWORD,
  793. lpName: ptr Utf16Char): Handle
  794. {.stdcall, dynlib: "kernel32", importc: "CreateEventW".}
  795. proc setEvent*(hEvent: Handle): cint
  796. {.stdcall, dynlib: "kernel32", importc: "SetEvent".}
  797. const
  798. FD_READ* = 0x00000001'i32
  799. FD_WRITE* = 0x00000002'i32
  800. FD_OOB* = 0x00000004'i32
  801. FD_ACCEPT* = 0x00000008'i32
  802. FD_CONNECT* = 0x00000010'i32
  803. FD_CLOSE* = 0x00000020'i32
  804. FD_QQS* = 0x00000040'i32
  805. FD_GROUP_QQS* = 0x00000080'i32
  806. FD_ROUTING_INTERFACE_CHANGE* = 0x00000100'i32
  807. FD_ADDRESS_LIST_CHANGE* = 0x00000200'i32
  808. FD_ALL_EVENTS* = 0x000003FF'i32
  809. proc wsaEventSelect*(s: SocketHandle, hEventObject: Handle,
  810. lNetworkEvents: clong): cint
  811. {.stdcall, importc: "WSAEventSelect", dynlib: "ws2_32.dll".}
  812. proc wsaCreateEvent*(): Handle
  813. {.stdcall, importc: "WSACreateEvent", dynlib: "ws2_32.dll".}
  814. proc wsaCloseEvent*(hEvent: Handle): bool
  815. {.stdcall, importc: "WSACloseEvent", dynlib: "ws2_32.dll".}
  816. proc wsaResetEvent*(hEvent: Handle): bool
  817. {.stdcall, importc: "WSAResetEvent", dynlib: "ws2_32.dll".}
  818. type
  819. KEY_EVENT_RECORD* = object
  820. eventType*: int16
  821. bKeyDown*: WINBOOL
  822. wRepeatCount*: int16
  823. wVirtualKeyCode*: int16
  824. wVirtualScanCode*: int16
  825. uChar*: int16
  826. dwControlKeyState*: DWORD
  827. proc readConsoleInput*(hConsoleInput: Handle, lpBuffer: pointer, nLength: cint,
  828. lpNumberOfEventsRead: ptr cint): cint
  829. {.stdcall, dynlib: "kernel32", importc: "ReadConsoleInputW".}
  830. type
  831. LPFIBER_START_ROUTINE* = proc (param: pointer) {.stdcall.}
  832. const
  833. FIBER_FLAG_FLOAT_SWITCH* = 0x01
  834. proc CreateFiber*(stackSize: int, fn: LPFIBER_START_ROUTINE, param: pointer): pointer {.stdcall, discardable, dynlib: "kernel32", importc.}
  835. proc CreateFiberEx*(stkCommit: int, stkReserve: int, flags: int32, fn: LPFIBER_START_ROUTINE, param: pointer): pointer {.stdcall, discardable, dynlib: "kernel32", importc.}
  836. proc ConvertThreadToFiber*(param: pointer): pointer {.stdcall, discardable, dynlib: "kernel32", importc.}
  837. proc ConvertThreadToFiberEx*(param: pointer, flags: int32): pointer {.stdcall, discardable, dynlib: "kernel32", importc.}
  838. proc DeleteFiber*(fiber: pointer) {.stdcall, discardable, dynlib: "kernel32", importc.}
  839. proc SwitchToFiber*(fiber: pointer) {.stdcall, discardable, dynlib: "kernel32", importc.}
  840. proc GetCurrentFiber*(): pointer {.stdcall, importc, header: "windows.h".}
  841. proc toFILETIME*(t: int64): FILETIME =
  842. ## Convert the Windows file time timestamp `t` to `FILETIME`.
  843. result = FILETIME(dwLowDateTime: cast[DWORD](t), dwHighDateTime: DWORD(t shr 32))
  844. type
  845. LPFILETIME* = ptr FILETIME
  846. proc setFileTime*(hFile: Handle, lpCreationTime: LPFILETIME,
  847. lpLastAccessTime: LPFILETIME, lpLastWriteTime: LPFILETIME): WINBOOL
  848. {.stdcall, dynlib: "kernel32", importc: "SetFileTime".}
  849. type
  850. # https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-sid_identifier_authority
  851. SID_IDENTIFIER_AUTHORITY* {.importc, header: "<windows.h>".} = object
  852. value* {.importc: "Value".}: array[6, BYTE]
  853. # https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-sid
  854. SID* {.importc, header: "<windows.h>".} = object
  855. Revision: BYTE
  856. SubAuthorityCount: BYTE
  857. IdentifierAuthority: SID_IDENTIFIER_AUTHORITY
  858. SubAuthority: ptr ptr DWORD
  859. PSID* = ptr SID
  860. const
  861. # https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-components
  862. # https://github.com/mirror/mingw-w64/blob/84c950bdab7c999ace49fe8383856be77f88c4a8/mingw-w64-headers/include/winnt.h#L2994
  863. SECURITY_NT_AUTHORITY* = [BYTE(0), BYTE(0), BYTE(0), BYTE(0), BYTE(0), BYTE(5)]
  864. SECURITY_BUILTIN_DOMAIN_RID* = 32
  865. DOMAIN_ALIAS_RID_ADMINS* = 544
  866. proc allocateAndInitializeSid*(pIdentifierAuthority: ptr SID_IDENTIFIER_AUTHORITY,
  867. nSubAuthorityCount: BYTE,
  868. nSubAuthority0: DWORD,
  869. nSubAuthority1: DWORD,
  870. nSubAuthority2: DWORD,
  871. nSubAuthority3: DWORD,
  872. nSubAuthority4: DWORD,
  873. nSubAuthority5: DWORD,
  874. nSubAuthority6: DWORD,
  875. nSubAuthority7: DWORD,
  876. pSid: ptr PSID): WINBOOL
  877. {.stdcall, dynlib: "Advapi32", importc: "AllocateAndInitializeSid".}
  878. proc checkTokenMembership*(tokenHandle: Handle, sidToCheck: PSID,
  879. isMember: PBOOL): WINBOOL
  880. {.stdcall, dynlib: "Advapi32", importc: "CheckTokenMembership".}
  881. proc freeSid*(pSid: PSID): PSID
  882. {.stdcall, dynlib: "Advapi32", importc: "FreeSid".}
  883. when defined(nimHasStyleChecks):
  884. {.pop.} # {.push styleChecks: off.}