authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-10-20 11:12:08-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-10-29 06:20:50-07:00
log34891b528e11afe1a1818a18d8ae01035542bb27
treeedf82ad005982080ab30a7e11833c79e02a9e336
parent62c0496d0a3bed811174080f651408c89bdce0c9

std.Io.Threaded: implement netListen for Windows


6 files changed, 479 insertions(+), 639 deletions(-)

lib/std/Io/Threaded.zig+272-23
......@@ -4,6 +4,7 @@ const builtin = @import("builtin");
44const native_os = builtin.os.tag;
55const is_windows = native_os == .windows;
66const windows = std.os.windows;
7const ws2_32 = std.os.windows.ws2_32;
78
89const std = @import("../std.zig");
910const Io = std.Io;
......@@ -24,6 +25,7 @@ threads: std.ArrayListUnmanaged(std.Thread),
2425stack_size: usize,
2526cpu_count: std.Thread.CpuCountError!usize,
2627concurrent_count: usize,
28wsa: if (is_windows) Wsa else struct {} = .{},
2729
2830threadlocal var current_closure: ?*Closure = null;
2931
......@@ -105,6 +107,9 @@ pub fn deinit(t: *Threaded) void {
105107 const gpa = t.allocator;
106108 t.join();
107109 t.threads.deinit(gpa);
110 if (is_windows and t.wsa.status == .initialized) {
111 if (ws2_32.WSACleanup() != 0) recoverableOsBugDetected();
112 }
108113 t.* = undefined;
109114}
110115
......@@ -234,7 +239,7 @@ pub fn io(t: *Threaded) Io {
234239 },
235240
236241 .netListenIp = switch (builtin.os.tag) {
237 .windows => @panic("TODO"),
242 .windows => netListenIpWindows,
238243 else => netListenIpPosix,
239244 },
240245 .netListenUnix = netListenUnix,
......@@ -2797,6 +2802,116 @@ fn netListenIpPosix(
27972802 };
27982803}
27992804
2805fn netListenIpWindows(
2806 userdata: ?*anyopaque,
2807 address: IpAddress,
2808 options: IpAddress.ListenOptions,
2809) IpAddress.ListenError!net.Server {
2810 if (!have_networking) return error.NetworkDown;
2811 const t: *Threaded = @ptrCast(@alignCast(userdata));
2812 const family = posixAddressFamily(&address);
2813 const mode = posixSocketMode(options.mode);
2814 const protocol = posixProtocol(options.protocol);
2815
2816 const socket_handle = while (true) {
2817 try t.checkCancel();
2818 const flags: u32 = ws2_32.WSA_FLAG_OVERLAPPED | ws2_32.WSA_FLAG_NO_HANDLE_INHERIT;
2819 const rc = ws2_32.WSASocketW(family, @bitCast(mode), @bitCast(protocol), null, 0, flags);
2820 if (rc != ws2_32.INVALID_SOCKET) break rc;
2821 switch (ws2_32.WSAGetLastError()) {
2822 .EINTR => continue,
2823 .ECANCELLED, .E_CANCELLED => return error.Canceled,
2824 .NOTINITIALISED => {
2825 try initializeWsa(t);
2826 continue;
2827 },
2828 .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
2829 .EMFILE => return error.ProcessFdQuotaExceeded,
2830 .ENOBUFS => return error.SystemResources,
2831 .EPROTONOSUPPORT => return error.ProtocolUnsupportedBySystem,
2832 else => |err| return windows.unexpectedWSAError(err),
2833 }
2834 };
2835 errdefer closeSocketWindows(socket_handle);
2836
2837 if (options.reuse_address)
2838 try setSocketOptionWsa(t, socket_handle, posix.SOL.SOCKET, posix.SO.REUSEADDR, 1);
2839
2840 var storage: WsaAddress = undefined;
2841 var addr_len = addressToWsa(&address, &storage);
2842
2843 while (true) {
2844 try t.checkCancel();
2845 const rc = ws2_32.bind(socket_handle, &storage.any, addr_len);
2846 if (rc != ws2_32.SOCKET_ERROR) break;
2847 switch (ws2_32.WSAGetLastError()) {
2848 .EINTR => continue,
2849 .ECANCELLED, .E_CANCELLED => return error.Canceled,
2850 .NOTINITIALISED => {
2851 try initializeWsa(t);
2852 continue;
2853 },
2854 .EADDRINUSE => return error.AddressInUse,
2855 .EADDRNOTAVAIL => return error.AddressUnavailable,
2856 .ENOTSOCK => |err| return wsaErrorBug(err),
2857 .EFAULT => |err| return wsaErrorBug(err),
2858 .EINVAL => |err| return wsaErrorBug(err),
2859 .ENOBUFS => return error.SystemResources,
2860 .ENETDOWN => return error.NetworkDown,
2861 else => |err| return windows.unexpectedWSAError(err),
2862 }
2863 }
2864
2865 while (true) {
2866 try t.checkCancel();
2867 const rc = ws2_32.listen(socket_handle, options.kernel_backlog);
2868 if (rc != ws2_32.SOCKET_ERROR) break;
2869 switch (ws2_32.WSAGetLastError()) {
2870 .EINTR => continue,
2871 .ECANCELLED, .E_CANCELLED => return error.Canceled,
2872 .NOTINITIALISED => {
2873 try initializeWsa(t);
2874 continue;
2875 },
2876 .ENETDOWN => return error.NetworkDown,
2877 .EADDRINUSE => return error.AddressInUse,
2878 .EISCONN => |err| return wsaErrorBug(err),
2879 .EINVAL => |err| return wsaErrorBug(err),
2880 .EMFILE, .ENOBUFS => return error.SystemResources,
2881 .ENOTSOCK => |err| return wsaErrorBug(err),
2882 .EOPNOTSUPP => |err| return wsaErrorBug(err),
2883 .EINPROGRESS => |err| return wsaErrorBug(err),
2884 else => |err| return windows.unexpectedWSAError(err),
2885 }
2886 }
2887
2888 while (true) {
2889 try t.checkCancel();
2890 const rc = ws2_32.getsockname(socket_handle, &storage.any, &addr_len);
2891 if (rc != ws2_32.SOCKET_ERROR) break;
2892 switch (ws2_32.WSAGetLastError()) {
2893 .EINTR => continue,
2894 .ECANCELLED, .E_CANCELLED => return error.Canceled,
2895 .NOTINITIALISED => {
2896 try initializeWsa(t);
2897 continue;
2898 },
2899 .ENETDOWN => return error.NetworkDown,
2900 .EFAULT => |err| return wsaErrorBug(err),
2901 .ENOTSOCK => |err| return wsaErrorBug(err),
2902 .EINVAL => |err| return wsaErrorBug(err),
2903 else => |err| return windows.unexpectedWSAError(err),
2904 }
2905 }
2906
2907 return .{
2908 .socket = .{
2909 .handle = socket_handle,
2910 .address = addressFromWsa(&storage),
2911 },
2912 };
2913}
2914
28002915fn netListenUnix(
28012916 userdata: ?*anyopaque,
28022917 address: *const net.UnixAddress,
......@@ -2971,7 +3086,7 @@ fn setSocketOption(t: *Threaded, fd: posix.fd_t, level: i32, opt_name: u32, opti
29713086 .CANCELED => return error.Canceled,
29723087
29733088 .BADF => |err| return errnoBug(err), // File descriptor used after closed.
2974 .NOTSOCK => |err| return errnoBug(err), // always a race condition
3089 .NOTSOCK => |err| return errnoBug(err),
29753090 .INVAL => |err| return errnoBug(err),
29763091 .FAULT => |err| return errnoBug(err),
29773092 else => |err| return posix.unexpectedErrno(err),
......@@ -2979,6 +3094,27 @@ fn setSocketOption(t: *Threaded, fd: posix.fd_t, level: i32, opt_name: u32, opti
29793094 }
29803095}
29813096
3097fn setSocketOptionWsa(t: *Threaded, socket: Io.net.Socket.Handle, level: i32, opt_name: u32, option: u32) !void {
3098 const o: []const u8 = @ptrCast(&option);
3099 const rc = ws2_32.setsockopt(socket, level, @bitCast(opt_name), o.ptr, @intCast(o.len));
3100 while (true) {
3101 if (rc != ws2_32.SOCKET_ERROR) return;
3102 switch (ws2_32.WSAGetLastError()) {
3103 .EINTR => continue,
3104 .ECANCELLED, .E_CANCELLED => return error.Canceled,
3105 .NOTINITIALISED => {
3106 try initializeWsa(t);
3107 continue;
3108 },
3109 .ENETDOWN => return error.NetworkDown,
3110 .EFAULT => |err| return wsaErrorBug(err),
3111 .ENOTSOCK => |err| return wsaErrorBug(err),
3112 .EINVAL => |err| return wsaErrorBug(err),
3113 else => |err| return windows.unexpectedWSAError(err),
3114 }
3115 }
3116}
3117
29823118fn netConnectIpPosix(
29833119 userdata: ?*anyopaque,
29843120 address: *const IpAddress,
......@@ -3263,25 +3399,31 @@ fn netSendOne(
32633399 try t.checkCancel();
32643400 const rc = posix.system.sendmsg(handle, &msg, flags);
32653401 if (is_windows) {
3266 if (rc == windows.ws2_32.SOCKET_ERROR) {
3267 switch (windows.ws2_32.WSAGetLastError()) {
3268 .WSAEACCES => return error.AccessDenied,
3269 .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
3270 .WSAECONNRESET => return error.ConnectionResetByPeer,
3271 .WSAEMSGSIZE => return error.MessageOversize,
3272 .WSAENOBUFS => return error.SystemResources,
3273 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
3274 .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
3275 .WSAEDESTADDRREQ => unreachable, // A destination address is required.
3276 .WSAEFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
3277 .WSAEHOSTUNREACH => return error.NetworkUnreachable,
3278 .WSAEINVAL => unreachable,
3279 .WSAENETDOWN => return error.NetworkDown,
3280 .WSAENETRESET => return error.ConnectionResetByPeer,
3281 .WSAENETUNREACH => return error.NetworkUnreachable,
3282 .WSAENOTCONN => return error.SocketUnconnected,
3283 .WSAESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
3284 .WSANOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
3402 if (rc == ws2_32.SOCKET_ERROR) {
3403 switch (ws2_32.WSAGetLastError()) {
3404 .EINTR => continue,
3405 .ECANCELLED, .E_CANCELLED => return error.Canceled,
3406 .NOTINITIALISED => {
3407 try initializeWsa(t);
3408 continue;
3409 },
3410 .EACCES => return error.AccessDenied,
3411 .EADDRNOTAVAIL => return error.AddressUnavailable,
3412 .ECONNRESET => return error.ConnectionResetByPeer,
3413 .EMSGSIZE => return error.MessageOversize,
3414 .ENOBUFS => return error.SystemResources,
3415 .ENOTSOCK => return error.FileDescriptorNotASocket,
3416 .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
3417 .EDESTADDRREQ => unreachable, // A destination address is required.
3418 .EFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
3419 .EHOSTUNREACH => return error.NetworkUnreachable,
3420 .EINVAL => unreachable,
3421 .ENETDOWN => return error.NetworkDown,
3422 .ENETRESET => return error.ConnectionResetByPeer,
3423 .ENETUNREACH => return error.NetworkUnreachable,
3424 .ENOTCONN => return error.SocketUnconnected,
3425 .ESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
3426 .NOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
32853427 else => |err| return windows.unexpectedWSAError(err),
32863428 }
32873429 } else {
......@@ -3613,7 +3755,7 @@ fn netClose(userdata: ?*anyopaque, handle: net.Socket.Handle) void {
36133755 const t: *Threaded = @ptrCast(@alignCast(userdata));
36143756 _ = t;
36153757 switch (native_os) {
3616 .windows => windows.closesocket(handle) catch recoverableOsBugDetected(),
3758 .windows => closeSocketWindows(handle) catch recoverableOsBugDetected(),
36173759 else => posix.close(handle),
36183760 }
36193761}
......@@ -3664,7 +3806,7 @@ fn netInterfaceNameResolve(
36643806
36653807 if (native_os == .windows) {
36663808 try t.checkCancel();
3667 const index = windows.ws2_32.if_nametoindex(&name.bytes);
3809 const index = ws2_32.if_nametoindex(&name.bytes);
36683810 if (index == 0) return error.InterfaceNotFound;
36693811 return .{ .index = index };
36703812 }
......@@ -3881,6 +4023,13 @@ const UnixAddress = extern union {
38814023 un: posix.sockaddr.un,
38824024};
38834025
4026const WsaAddress = extern union {
4027 any: ws2_32.sockaddr,
4028 in: ws2_32.sockaddr.in,
4029 in6: ws2_32.sockaddr.in6,
4030 un: ws2_32.sockaddr.un,
4031};
4032
38844033fn posixAddressFamily(a: *const IpAddress) posix.sa_family_t {
38854034 return switch (a.*) {
38864035 .ip4 => posix.AF.INET,
......@@ -3896,6 +4045,14 @@ fn addressFromPosix(posix_address: *const PosixAddress) IpAddress {
38964045 };
38974046}
38984047
4048fn addressFromWsa(wsa_address: *const WsaAddress) IpAddress {
4049 return switch (wsa_address.any.family) {
4050 posix.AF.INET => .{ .ip4 = address4FromWsa(&wsa_address.in) },
4051 posix.AF.INET6 => .{ .ip6 = address6FromWsa(&wsa_address.in6) },
4052 else => .{ .ip4 = .loopback(0) },
4053 };
4054}
4055
38994056fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_t {
39004057 return switch (a.*) {
39014058 .ip4 => |ip4| {
......@@ -3909,6 +4066,19 @@ fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_t {
39094066 };
39104067}
39114068
4069fn addressToWsa(a: *const IpAddress, storage: *WsaAddress) i32 {
4070 return switch (a.*) {
4071 .ip4 => |ip4| {
4072 storage.in = address4ToPosix(ip4);
4073 return @sizeOf(posix.sockaddr.in);
4074 },
4075 .ip6 => |*ip6| {
4076 storage.in6 = address6ToPosix(ip6);
4077 return @sizeOf(posix.sockaddr.in6);
4078 },
4079 };
4080}
4081
39124082fn addressUnixToPosix(a: *const net.UnixAddress, storage: *UnixAddress) posix.socklen_t {
39134083 @memcpy(storage.un.path[0..a.path.len], a.path);
39144084 storage.un.family = posix.AF.UNIX;
......@@ -3932,6 +4102,22 @@ fn address6FromPosix(in6: *const posix.sockaddr.in6) net.Ip6Address {
39324102 };
39334103}
39344104
4105fn address4FromWsa(in: *const ws2_32.sockaddr.in) net.Ip4Address {
4106 return .{
4107 .port = std.mem.bigToNative(u16, in.port),
4108 .bytes = @bitCast(in.addr),
4109 };
4110}
4111
4112fn address6FromWsa(in6: *const ws2_32.sockaddr.in6) net.Ip6Address {
4113 return .{
4114 .port = std.mem.bigToNative(u16, in6.port),
4115 .bytes = in6.addr,
4116 .flow = in6.flowinfo,
4117 .interface = .{ .index = in6.scope_id },
4118 };
4119}
4120
39354121fn address4ToPosix(a: net.Ip4Address) posix.sockaddr.in {
39364122 return .{
39374123 .port = std.mem.nativeToBig(u16, a.port),
......@@ -3955,6 +4141,13 @@ fn errnoBug(err: posix.E) Io.UnexpectedError {
39554141 }
39564142}
39574143
4144fn wsaErrorBug(err: ws2_32.WinsockError) Io.UnexpectedError {
4145 switch (builtin.mode) {
4146 .Debug => std.debug.panic("programmer bug caused syscall error: {t}", .{err}),
4147 else => return error.Unexpected,
4148 }
4149}
4150
39584151fn posixSocketMode(mode: net.Socket.Mode) u32 {
39594152 return switch (mode) {
39604153 .stream => posix.SOCK.STREAM,
......@@ -4814,3 +5007,59 @@ pub const ResetEvent = enum(u32) {
48145007 @atomicStore(ResetEvent, re, .unset, .monotonic);
48155008 }
48165009};
5010
5011fn closeSocketWindows(s: ws2_32.SOCKET) void {
5012 const rc = ws2_32.closesocket(s);
5013 if (builtin.mode == .Debug) switch (rc) {
5014 0 => {},
5015 ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
5016 else => unreachable,
5017 },
5018 else => unreachable,
5019 };
5020}
5021
5022const Wsa = struct {
5023 status: Status = .uninitialized,
5024 mutex: Io.Mutex = .init,
5025 init_error: ?Wsa.InitError = null,
5026
5027 const Status = enum { uninitialized, initialized, failure };
5028
5029 const InitError = error{
5030 ProcessFdQuotaExceeded,
5031 NetworkDown,
5032 VersionUnsupported,
5033 BlockingOperationInProgress,
5034 } || Io.UnexpectedError;
5035};
5036
5037fn initializeWsa(t: *Threaded) error{NetworkDown}!void {
5038 const t_io = t.io();
5039 const wsa = &t.wsa;
5040 wsa.mutex.lockUncancelable(t_io);
5041 defer wsa.mutex.unlock(t_io);
5042 switch (wsa.status) {
5043 .uninitialized => {
5044 var wsa_data: ws2_32.WSADATA = undefined;
5045 const minor_version = 2;
5046 const major_version = 2;
5047 switch (ws2_32.WSAStartup((@as(windows.WORD, minor_version) << 8) | major_version, &wsa_data)) {
5048 0 => {
5049 wsa.status = .initialized;
5050 return;
5051 },
5052 else => |err_int| switch (@as(ws2_32.WinsockError, @enumFromInt(@as(u16, @intCast(err_int))))) {
5053 .SYSNOTREADY => wsa.init_error = error.NetworkDown,
5054 .VERNOTSUPPORTED => wsa.init_error = error.VersionUnsupported,
5055 .EINPROGRESS => wsa.init_error = error.BlockingOperationInProgress,
5056 .EPROCLIM => wsa.init_error = error.ProcessFdQuotaExceeded,
5057 else => |err| wsa.init_error = windows.unexpectedWSAError(err),
5058 },
5059 }
5060 },
5061 .initialized => return,
5062 .failure => {},
5063 }
5064 return error.NetworkDown;
5065}
lib/std/os/windows.zig-152
......@@ -1574,131 +1574,11 @@ pub fn GetFileAttributesW(lpFileName: [*:0]const u16) GetFileAttributesError!DWO
15741574 return rc;
15751575}
15761576
1577pub fn WSAStartup(majorVersion: u8, minorVersion: u8) !ws2_32.WSADATA {
1578 var wsadata: ws2_32.WSADATA = undefined;
1579 return switch (ws2_32.WSAStartup((@as(WORD, minorVersion) << 8) | majorVersion, &wsadata)) {
1580 0 => wsadata,
1581 else => |err_int| switch (@as(ws2_32.WinsockError, @enumFromInt(@as(u16, @intCast(err_int))))) {
1582 .WSASYSNOTREADY => return error.SystemNotAvailable,
1583 .WSAVERNOTSUPPORTED => return error.VersionNotSupported,
1584 .WSAEINPROGRESS => return error.BlockingOperationInProgress,
1585 .WSAEPROCLIM => return error.ProcessFdQuotaExceeded,
1586 else => |err| return unexpectedWSAError(err),
1587 },
1588 };
1589}
1590
1591pub fn WSACleanup() !void {
1592 return switch (ws2_32.WSACleanup()) {
1593 0 => {},
1594 ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
1595 .WSANOTINITIALISED => return error.NotInitialized,
1596 .WSAENETDOWN => return error.NetworkNotAvailable,
1597 .WSAEINPROGRESS => return error.BlockingOperationInProgress,
1598 else => |err| return unexpectedWSAError(err),
1599 },
1600 else => unreachable,
1601 };
1602}
1603
1604var wsa_startup_mutex: std.Thread.Mutex = .{};
1605
1606pub fn callWSAStartup() !void {
1607 wsa_startup_mutex.lock();
1608 defer wsa_startup_mutex.unlock();
1609
1610 // Here we could use a flag to prevent multiple threads to prevent
1611 // multiple calls to WSAStartup, but it doesn't matter. We're globally
1612 // leaking the resource intentionally, and the mutex already prevents
1613 // data races within the WSAStartup function.
1614 _ = WSAStartup(2, 2) catch |err| switch (err) {
1615 error.SystemNotAvailable => return error.SystemResources,
1616 error.VersionNotSupported => return error.Unexpected,
1617 error.BlockingOperationInProgress => return error.Unexpected,
1618 error.ProcessFdQuotaExceeded => return error.ProcessFdQuotaExceeded,
1619 error.Unexpected => return error.Unexpected,
1620 };
1621}
1622
1623/// Microsoft requires WSAStartup to be called to initialize, or else
1624/// WSASocketW will return WSANOTINITIALISED.
1625/// Since this is a standard library, we do not have the luxury of
1626/// putting initialization code anywhere, because we would not want
1627/// to pay the cost of calling WSAStartup if there ended up being no
1628/// networking. Also, if Zig code is used as a library, Zig is not in
1629/// charge of the start code, and we couldn't put in any initialization
1630/// code even if we wanted to.
1631/// The documentation for WSAStartup mentions that there must be a
1632/// matching WSACleanup call. It is not possible for the Zig Standard
1633/// Library to honor this for the same reason - there is nowhere to put
1634/// deinitialization code.
1635/// So, API users of the zig std lib have two options:
1636/// * (recommended) The simple, cross-platform way: just call `WSASocketW`
1637/// and don't worry about it. Zig will call WSAStartup() in a thread-safe
1638/// manner and never deinitialize networking. This is ideal for an
1639/// application which has the capability to do networking.
1640/// * The getting-your-hands-dirty way: call `WSAStartup()` before doing
1641/// networking, so that the error handling code for WSANOTINITIALISED never
1642/// gets run, which then allows the application or library to call `WSACleanup()`.
1643/// This could make sense for a library, which has init and deinit
1644/// functions for the whole library's lifetime.
1645pub fn WSASocketW(
1646 af: i32,
1647 socket_type: i32,
1648 protocol: i32,
1649 protocolInfo: ?*ws2_32.WSAPROTOCOL_INFOW,
1650 g: ws2_32.GROUP,
1651 dwFlags: DWORD,
1652) !ws2_32.SOCKET {
1653 var first = true;
1654 while (true) {
1655 const rc = ws2_32.WSASocketW(af, socket_type, protocol, protocolInfo, g, dwFlags);
1656 if (rc == ws2_32.INVALID_SOCKET) {
1657 switch (ws2_32.WSAGetLastError()) {
1658 .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
1659 .WSAEMFILE => return error.ProcessFdQuotaExceeded,
1660 .WSAENOBUFS => return error.SystemResources,
1661 .WSAEPROTONOSUPPORT => return error.ProtocolNotSupported,
1662 .WSANOTINITIALISED => {
1663 if (!first) return error.Unexpected;
1664 first = false;
1665 try callWSAStartup();
1666 continue;
1667 },
1668 else => |err| return unexpectedWSAError(err),
1669 }
1670 }
1671 return rc;
1672 }
1673}
1674
1675pub fn bind(s: ws2_32.SOCKET, name: *const ws2_32.sockaddr, namelen: ws2_32.socklen_t) i32 {
1676 return ws2_32.bind(s, name, @as(i32, @intCast(namelen)));
1677}
1678
1679pub fn listen(s: ws2_32.SOCKET, backlog: u31) i32 {
1680 return ws2_32.listen(s, backlog);
1681}
1682
1683pub fn closesocket(s: ws2_32.SOCKET) !void {
1684 switch (ws2_32.closesocket(s)) {
1685 0 => {},
1686 ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
1687 else => |err| return unexpectedWSAError(err),
1688 },
1689 else => unreachable,
1690 }
1691}
1692
16931577pub fn accept(s: ws2_32.SOCKET, name: ?*ws2_32.sockaddr, namelen: ?*ws2_32.socklen_t) ws2_32.SOCKET {
16941578 assert((name == null) == (namelen == null));
16951579 return ws2_32.accept(s, name, @as(?*i32, @ptrCast(namelen)));
16961580}
16971581
1698pub fn getsockname(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 {
1699 return ws2_32.getsockname(s, name, @as(*i32, @ptrCast(namelen)));
1700}
1701
17021582pub fn getpeername(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 {
17031583 return ws2_32.getpeername(s, name, @as(*i32, @ptrCast(namelen)));
17041584}
......@@ -2816,38 +2696,6 @@ inline fn MAKELANGID(p: c_ushort, s: c_ushort) LANGID {
28162696 return (s << 10) | p;
28172697}
28182698
2819/// Loads a Winsock extension function in runtime specified by a GUID.
2820pub fn loadWinsockExtensionFunction(comptime T: type, sock: ws2_32.SOCKET, guid: GUID) !T {
2821 var function: T = undefined;
2822 var num_bytes: DWORD = undefined;
2823
2824 const rc = ws2_32.WSAIoctl(
2825 sock,
2826 ws2_32.SIO_GET_EXTENSION_FUNCTION_POINTER,
2827 &guid,
2828 @sizeOf(GUID),
2829 @as(?*anyopaque, @ptrFromInt(@intFromPtr(&function))),
2830 @sizeOf(T),
2831 &num_bytes,
2832 null,
2833 null,
2834 );
2835
2836 if (rc == ws2_32.SOCKET_ERROR) {
2837 return switch (ws2_32.WSAGetLastError()) {
2838 .WSAEOPNOTSUPP => error.OperationNotSupported,
2839 .WSAENOTSOCK => error.FileDescriptorNotASocket,
2840 else => |err| unexpectedWSAError(err),
2841 };
2842 }
2843
2844 if (num_bytes != @sizeOf(T)) {
2845 return error.ShortRead;
2846 }
2847
2848 return function;
2849}
2850
28512699/// Call this when you made a windows DLL call or something that does SetLastError
28522700/// and you get an unexpected error.
28532701pub fn unexpectedError(err: Win32Error) UnexpectedError {
lib/std/os/windows/test.zig-25
......@@ -237,28 +237,3 @@ test "removeDotDirs" {
237237 try testRemoveDotDirs("a\\b\\..\\", "a\\");
238238 try testRemoveDotDirs("a\\b\\..\\c", "a\\c");
239239}
240
241test "loadWinsockExtensionFunction" {
242 _ = try windows.WSAStartup(2, 2);
243 defer windows.WSACleanup() catch unreachable;
244
245 const LPFN_CONNECTEX = *const fn (
246 Socket: windows.ws2_32.SOCKET,
247 SockAddr: *const windows.ws2_32.sockaddr,
248 SockLen: std.posix.socklen_t,
249 SendBuf: ?*const anyopaque,
250 SendBufLen: windows.DWORD,
251 BytesSent: *windows.DWORD,
252 Overlapped: *windows.OVERLAPPED,
253 ) callconv(.winapi) windows.BOOL;
254
255 _ = windows.loadWinsockExtensionFunction(
256 LPFN_CONNECTEX,
257 try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0),
258 windows.ws2_32.WSAID_CONNECTEX,
259 ) catch |err| switch (err) {
260 error.OperationNotSupported => unreachable,
261 error.ShortRead => unreachable,
262 else => |e| return e,
263 };
264}
lib/std/os/windows/ws2_32.zig+96-191
......@@ -1271,130 +1271,105 @@ pub const timeval = extern struct {
12711271 usec: LONG,
12721272};
12731273
1274// https://docs.microsoft.com/en-au/windows/win32/winsock/windows-sockets-error-codes-2
1274/// https://docs.microsoft.com/en-au/windows/win32/winsock/windows-sockets-error-codes-2
12751275pub const WinsockError = enum(u16) {
12761276 /// Specified event object handle is invalid.
12771277 /// An application attempts to use an event object, but the specified handle is not valid.
1278 WSA_INVALID_HANDLE = 6,
1279
1278 INVALID_HANDLE = 6,
12801279 /// Insufficient memory available.
12811280 /// An application used a Windows Sockets function that directly maps to a Windows function.
12821281 /// The Windows function is indicating a lack of required memory resources.
1283 WSA_NOT_ENOUGH_MEMORY = 8,
1284
1282 NOT_ENOUGH_MEMORY = 8,
12851283 /// One or more parameters are invalid.
12861284 /// An application used a Windows Sockets function which directly maps to a Windows function.
12871285 /// The Windows function is indicating a problem with one or more parameters.
1288 WSA_INVALID_PARAMETER = 87,
1289
1286 INVALID_PARAMETER = 87,
12901287 /// Overlapped operation aborted.
12911288 /// An overlapped operation was canceled due to the closure of the socket, or the execution of the SIO_FLUSH command in WSAIoctl.
1292 WSA_OPERATION_ABORTED = 995,
1293
1289 OPERATION_ABORTED = 995,
12941290 /// Overlapped I/O event object not in signaled state.
12951291 /// The application has tried to determine the status of an overlapped operation which is not yet completed.
12961292 /// Applications that use WSAGetOverlappedResult (with the fWait flag set to FALSE) in a polling mode to determine when an overlapped operation has completed, get this error code until the operation is complete.
1297 WSA_IO_INCOMPLETE = 996,
1298
1293 IO_INCOMPLETE = 996,
12991294 /// The application has initiated an overlapped operation that cannot be completed immediately.
13001295 /// A completion indication will be given later when the operation has been completed.
1301 WSA_IO_PENDING = 997,
1302
1296 IO_PENDING = 997,
13031297 /// Interrupted function call.
13041298 /// A blocking operation was interrupted by a call to WSACancelBlockingCall.
1305 WSAEINTR = 10004,
1306
1299 EINTR = 10004,
13071300 /// File handle is not valid.
13081301 /// The file handle supplied is not valid.
1309 WSAEBADF = 10009,
1310
1302 EBADF = 10009,
13111303 /// Permission denied.
13121304 /// An attempt was made to access a socket in a way forbidden by its access permissions.
13131305 /// An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO.BROADCAST).
13141306 /// Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4.0 with SP4 and later), another application, service, or kernel mode driver is bound to the same address with exclusive access.
13151307 /// Such exclusive access is a new feature of Windows NT 4.0 with SP4 and later, and is implemented by using the SO.EXCLUSIVEADDRUSE option.
1316 WSAEACCES = 10013,
1317
1308 EACCES = 10013,
13181309 /// Bad address.
13191310 /// The system detected an invalid pointer address in attempting to use a pointer argument of a call.
13201311 /// This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small.
13211312 /// For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).
1322 WSAEFAULT = 10014,
1323
1313 EFAULT = 10014,
13241314 /// Invalid argument.
13251315 /// Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function).
13261316 /// In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.
1327 WSAEINVAL = 10022,
1328
1317 EINVAL = 10022,
13291318 /// Too many open files.
13301319 /// Too many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process, or per thread.
1331 WSAEMFILE = 10024,
1332
1320 EMFILE = 10024,
13331321 /// Resource temporarily unavailable.
13341322 /// This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket.
13351323 /// It is a nonfatal error, and the operation should be retried later.
13361324 /// It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK.STREAM socket, since some time must elapse for the connection to be established.
1337 WSAEWOULDBLOCK = 10035,
1338
1325 EWOULDBLOCK = 10035,
13391326 /// Operation now in progress.
13401327 /// A blocking operation is currently executing.
13411328 /// Windows Sockets only allows a single blocking operation—per- task or thread—to be outstanding, and if any other function call is made (whether or not it references that or any other socket) the function fails with the WSAEINPROGRESS error.
1342 WSAEINPROGRESS = 10036,
1343
1329 EINPROGRESS = 10036,
13441330 /// Operation already in progress.
13451331 /// An operation was attempted on a nonblocking socket with an operation already in progress—that is, calling connect a second time on a nonblocking socket that is already connecting, or canceling an asynchronous request (WSAAsyncGetXbyY) that has already been canceled or completed.
1346 WSAEALREADY = 10037,
1347
1332 EALREADY = 10037,
13481333 /// Socket operation on nonsocket.
13491334 /// An operation was attempted on something that is not a socket.
13501335 /// Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.
1351 WSAENOTSOCK = 10038,
1352
1336 ENOTSOCK = 10038,
13531337 /// Destination address required.
13541338 /// A required address was omitted from an operation on a socket.
13551339 /// For example, this error is returned if sendto is called with the remote address of ADDR_ANY.
1356 WSAEDESTADDRREQ = 10039,
1357
1340 EDESTADDRREQ = 10039,
13581341 /// Message too long.
13591342 /// A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram was smaller than the datagram itself.
1360 WSAEMSGSIZE = 10040,
1361
1343 EMSGSIZE = 10040,
13621344 /// Protocol wrong type for socket.
13631345 /// A protocol was specified in the socket function call that does not support the semantics of the socket type requested.
13641346 /// For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK.STREAM.
1365 WSAEPROTOTYPE = 10041,
1366
1347 EPROTOTYPE = 10041,
13671348 /// Bad protocol option.
13681349 /// An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.
1369 WSAENOPROTOOPT = 10042,
1370
1350 ENOPROTOOPT = 10042,
13711351 /// Protocol not supported.
13721352 /// The requested protocol has not been configured into the system, or no implementation for it exists.
13731353 /// For example, a socket call requests a SOCK.DGRAM socket, but specifies a stream protocol.
1374 WSAEPROTONOSUPPORT = 10043,
1375
1354 EPROTONOSUPPORT = 10043,
13761355 /// Socket type not supported.
13771356 /// The support for the specified socket type does not exist in this address family.
13781357 /// For example, the optional type SOCK.RAW might be selected in a socket call, and the implementation does not support SOCK.RAW sockets at all.
1379 WSAESOCKTNOSUPPORT = 10044,
1380
1358 ESOCKTNOSUPPORT = 10044,
13811359 /// Operation not supported.
13821360 /// The attempted operation is not supported for the type of object referenced.
13831361 /// Usually this occurs when a socket descriptor to a socket that cannot support this operation is trying to accept a connection on a datagram socket.
1384 WSAEOPNOTSUPP = 10045,
1385
1362 EOPNOTSUPP = 10045,
13861363 /// Protocol family not supported.
13871364 /// The protocol family has not been configured into the system or no implementation for it exists.
13881365 /// This message has a slightly different meaning from WSAEAFNOSUPPORT.
13891366 /// However, it is interchangeable in most cases, and all Windows Sockets functions that return one of these messages also specify WSAEAFNOSUPPORT.
1390 WSAEPFNOSUPPORT = 10046,
1391
1367 EPFNOSUPPORT = 10046,
13921368 /// Address family not supported by protocol family.
13931369 /// An address incompatible with the requested protocol was used.
13941370 /// All sockets are created with an associated address family (that is, AF.INET for Internet Protocols) and a generic protocol type (that is, SOCK.STREAM).
13951371 /// This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.
1396 WSAEAFNOSUPPORT = 10047,
1397
1372 EAFNOSUPPORT = 10047,
13981373 /// Address already in use.
13991374 /// Typically, only one usage of each socket address (protocol/IP address/port) is permitted.
14001375 /// This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that was not closed properly, or one that is still in the process of closing.
......@@ -1402,115 +1377,91 @@ pub const WinsockError = enum(u16) {
14021377 /// Client applications usually need not call bind at all—connect chooses an unused port automatically.
14031378 /// When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed.
14041379 /// This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.
1405 WSAEADDRINUSE = 10048,
1406
1380 EADDRINUSE = 10048,
14071381 /// Cannot assign requested address.
14081382 /// The requested address is not valid in its context.
14091383 /// This normally results from an attempt to bind to an address that is not valid for the local computer.
14101384 /// This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the remote address or port is not valid for a remote computer (for example, address or port 0).
1411 WSAEADDRNOTAVAIL = 10049,
1412
1385 EADDRNOTAVAIL = 10049,
14131386 /// Network is down.
14141387 /// A socket operation encountered a dead network.
14151388 /// This could indicate a serious failure of the network system (that is, the protocol stack that the Windows Sockets DLL runs over), the network interface, or the local network itself.
1416 WSAENETDOWN = 10050,
1417
1389 ENETDOWN = 10050,
14181390 /// Network is unreachable.
14191391 /// A socket operation was attempted to an unreachable network.
14201392 /// This usually means the local software knows no route to reach the remote host.
1421 WSAENETUNREACH = 10051,
1422
1393 ENETUNREACH = 10051,
14231394 /// Network dropped connection on reset.
14241395 /// The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress.
14251396 /// It can also be returned by setsockopt if an attempt is made to set SO.KEEPALIVE on a connection that has already failed.
1426 WSAENETRESET = 10052,
1427
1397 ENETRESET = 10052,
14281398 /// Software caused connection abort.
14291399 /// An established connection was aborted by the software in your host computer, possibly due to a data transmission time-out or protocol error.
1430 WSAECONNABORTED = 10053,
1431
1400 ECONNABORTED = 10053,
14321401 /// Connection reset by peer.
14331402 /// An existing connection was forcibly closed by the remote host.
14341403 /// This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO.LINGER option on the remote socket).
14351404 /// This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress.
14361405 /// Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.
1437 WSAECONNRESET = 10054,
1438
1406 ECONNRESET = 10054,
14391407 /// No buffer space available.
14401408 /// An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.
1441 WSAENOBUFS = 10055,
1442
1409 ENOBUFS = 10055,
14431410 /// Socket is already connected.
14441411 /// A connect request was made on an already-connected socket.
14451412 /// Some implementations also return this error if sendto is called on a connected SOCK.DGRAM socket (for SOCK.STREAM sockets, the to parameter in sendto is ignored) although other implementations treat this as a legal occurrence.
1446 WSAEISCONN = 10056,
1447
1413 EISCONN = 10056,
14481414 /// Socket is not connected.
14491415 /// A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using sendto) no address was supplied.
14501416 /// Any other type of operation might also return this error—for example, setsockopt setting SO.KEEPALIVE if the connection has been reset.
1451 WSAENOTCONN = 10057,
1452
1417 ENOTCONN = 10057,
14531418 /// Cannot send after socket shutdown.
14541419 /// A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call.
14551420 /// By calling shutdown a partial close of a socket is requested, which is a signal that sending or receiving, or both have been discontinued.
1456 WSAESHUTDOWN = 10058,
1457
1421 ESHUTDOWN = 10058,
14581422 /// Too many references.
14591423 /// Too many references to some kernel object.
1460 WSAETOOMANYREFS = 10059,
1461
1424 ETOOMANYREFS = 10059,
14621425 /// Connection timed out.
14631426 /// A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.
1464 WSAETIMEDOUT = 10060,
1465
1427 ETIMEDOUT = 10060,
14661428 /// Connection refused.
14671429 /// No connection could be made because the target computer actively refused it.
14681430 /// This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.
1469 WSAECONNREFUSED = 10061,
1470
1431 ECONNREFUSED = 10061,
14711432 /// Cannot translate name.
14721433 /// Cannot translate a name.
1473 WSAELOOP = 10062,
1474
1434 ELOOP = 10062,
14751435 /// Name too long.
14761436 /// A name component or a name was too long.
1477 WSAENAMETOOLONG = 10063,
1478
1437 ENAMETOOLONG = 10063,
14791438 /// Host is down.
14801439 /// A socket operation failed because the destination host is down. A socket operation encountered a dead host.
14811440 /// Networking activity on the local host has not been initiated.
14821441 /// These conditions are more likely to be indicated by the error WSAETIMEDOUT.
1483 WSAEHOSTDOWN = 10064,
1484
1442 EHOSTDOWN = 10064,
14851443 /// No route to host.
14861444 /// A socket operation was attempted to an unreachable host. See WSAENETUNREACH.
1487 WSAEHOSTUNREACH = 10065,
1488
1445 EHOSTUNREACH = 10065,
14891446 /// Directory not empty.
14901447 /// Cannot remove a directory that is not empty.
1491 WSAENOTEMPTY = 10066,
1492
1448 ENOTEMPTY = 10066,
14931449 /// Too many processes.
14941450 /// A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously.
14951451 /// WSAStartup may fail with this error if the limit has been reached.
1496 WSAEPROCLIM = 10067,
1497
1452 EPROCLIM = 10067,
14981453 /// User quota exceeded.
14991454 /// Ran out of user quota.
1500 WSAEUSERS = 10068,
1501
1455 EUSERS = 10068,
15021456 /// Disk quota exceeded.
15031457 /// Ran out of disk quota.
1504 WSAEDQUOT = 10069,
1505
1458 EDQUOT = 10069,
15061459 /// Stale file handle reference.
15071460 /// The file handle reference is no longer available.
1508 WSAESTALE = 10070,
1509
1461 ESTALE = 10070,
15101462 /// Item is remote.
15111463 /// The item is not available locally.
1512 WSAEREMOTE = 10071,
1513
1464 EREMOTE = 10071,
15141465 /// Network subsystem is unavailable.
15151466 /// This error is returned by WSAStartup if the Windows Sockets implementation cannot function at this time because the underlying system it uses to provide network services is currently unavailable.
15161467 /// Users should check:
......@@ -1518,47 +1469,38 @@ pub const WinsockError = enum(u16) {
15181469 /// - That they are not trying to use more than one Windows Sockets implementation simultaneously.
15191470 /// - If there is more than one Winsock DLL on your system, be sure the first one in the path is appropriate for the network subsystem currently loaded.
15201471 /// - The Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.
1521 WSASYSNOTREADY = 10091,
1522
1472 SYSNOTREADY = 10091,
15231473 /// Winsock.dll version out of range.
15241474 /// The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application.
15251475 /// Check that no old Windows Sockets DLL files are being accessed.
1526 WSAVERNOTSUPPORTED = 10092,
1527
1476 VERNOTSUPPORTED = 10092,
15281477 /// Successful WSAStartup not yet performed.
15291478 /// Either the application has not called WSAStartup or WSAStartup failed.
15301479 /// The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.
1531 WSANOTINITIALISED = 10093,
1532
1480 NOTINITIALISED = 10093,
15331481 /// Graceful shutdown in progress.
15341482 /// Returned by WSARecv and WSARecvFrom to indicate that the remote party has initiated a graceful shutdown sequence.
1535 WSAEDISCON = 10101,
1536
1483 EDISCON = 10101,
15371484 /// No more results.
15381485 /// No more results can be returned by the WSALookupServiceNext function.
1539 WSAENOMORE = 10102,
1540
1486 ENOMORE = 10102,
15411487 /// Call has been canceled.
15421488 /// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.
1543 WSAECANCELLED = 10103,
1544
1489 ECANCELLED = 10103,
15451490 /// Procedure call table is invalid.
15461491 /// The service provider procedure call table is invalid.
15471492 /// A service provider returned a bogus procedure table to Ws2_32.dll.
15481493 /// This is usually caused by one or more of the function pointers being NULL.
1549 WSAEINVALIDPROCTABLE = 10104,
1550
1494 EINVALIDPROCTABLE = 10104,
15511495 /// Service provider is invalid.
15521496 /// The requested service provider is invalid.
15531497 /// This error is returned by the WSCGetProviderInfo and WSCGetProviderInfo32 functions if the protocol entry specified could not be found.
15541498 /// This error is also returned if the service provider returned a version number other than 2.0.
1555 WSAEINVALIDPROVIDER = 10105,
1556
1499 EINVALIDPROVIDER = 10105,
15571500 /// Service provider failed to initialize.
15581501 /// The requested service provider could not be loaded or initialized.
15591502 /// This error is returned if either a service provider's DLL could not be loaded (LoadLibrary failed) or the provider's WSPStartup or NSPStartup function failed.
1560 WSAEPROVIDERFAILEDINIT = 10106,
1561
1503 EPROVIDERFAILEDINIT = 10106,
15621504 /// System call failure.
15631505 /// A system call that should never fail has failed.
15641506 /// This is a generic error code, returned under various conditions.
......@@ -1566,157 +1508,120 @@ pub const WinsockError = enum(u16) {
15661508 /// For example, if a call to WaitForMultipleEvents fails or one of the registry functions fails trying to manipulate the protocol/namespace catalogs.
15671509 /// Returned when a provider does not return SUCCESS and does not provide an extended error code.
15681510 /// Can indicate a service provider implementation error.
1569 WSASYSCALLFAILURE = 10107,
1570
1511 SYSCALLFAILURE = 10107,
15711512 /// Service not found.
15721513 /// No such service is known. The service cannot be found in the specified name space.
1573 WSASERVICE_NOT_FOUND = 10108,
1574
1514 SERVICE_NOT_FOUND = 10108,
15751515 /// Class type not found.
15761516 /// The specified class was not found.
1577 WSATYPE_NOT_FOUND = 10109,
1578
1517 TYPE_NOT_FOUND = 10109,
15791518 /// No more results.
15801519 /// No more results can be returned by the WSALookupServiceNext function.
1581 WSA_E_NO_MORE = 10110,
1582
1520 E_NO_MORE = 10110,
15831521 /// Call was canceled.
15841522 /// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.
1585 WSA_E_CANCELLED = 10111,
1586
1523 E_CANCELLED = 10111,
15871524 /// Database query was refused.
15881525 /// A database query failed because it was actively refused.
1589 WSAEREFUSED = 10112,
1590
1526 EREFUSED = 10112,
15911527 /// Host not found.
15921528 /// No such host is known. The name is not an official host name or alias, or it cannot be found in the database(s) being queried.
15931529 /// This error may also be returned for protocol and service queries, and means that the specified name could not be found in the relevant database.
1594 WSAHOST_NOT_FOUND = 11001,
1595
1530 HOST_NOT_FOUND = 11001,
15961531 /// Nonauthoritative host not found.
15971532 /// This is usually a temporary error during host name resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful.
1598 WSATRY_AGAIN = 11002,
1599
1533 TRY_AGAIN = 11002,
16001534 /// This is a nonrecoverable error.
16011535 /// This indicates that some sort of nonrecoverable error occurred during a database lookup.
16021536 /// This may be because the database files (for example, BSD-compatible HOSTS, SERVICES, or PROTOCOLS files) could not be found, or a DNS request was returned by the server with a severe error.
1603 WSANO_RECOVERY = 11003,
1604
1537 NO_RECOVERY = 11003,
16051538 /// Valid name, no data record of requested type.
16061539 /// The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for.
16071540 /// The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server).
16081541 /// An MX record is returned but no A record—indicating the host itself exists, but is not directly reachable.
1609 WSANO_DATA = 11004,
1610
1542 NO_DATA = 11004,
16111543 /// QoS receivers.
16121544 /// At least one QoS reserve has arrived.
1613 WSA_QOS_RECEIVERS = 11005,
1614
1545 QOS_RECEIVERS = 11005,
16151546 /// QoS senders.
16161547 /// At least one QoS send path has arrived.
1617 WSA_QOS_SENDERS = 11006,
1618
1548 QOS_SENDERS = 11006,
16191549 /// No QoS senders.
16201550 /// There are no QoS senders.
1621 WSA_QOS_NO_SENDERS = 11007,
1622
1551 QOS_NO_SENDERS = 11007,
16231552 /// QoS no receivers.
16241553 /// There are no QoS receivers.
1625 WSA_QOS_NO_RECEIVERS = 11008,
1626
1554 QOS_NO_RECEIVERS = 11008,
16271555 /// QoS request confirmed.
16281556 /// The QoS reserve request has been confirmed.
1629 WSA_QOS_REQUEST_CONFIRMED = 11009,
1630
1557 QOS_REQUEST_CONFIRMED = 11009,
16311558 /// QoS admission error.
16321559 /// A QoS error occurred due to lack of resources.
1633 WSA_QOS_ADMISSION_FAILURE = 11010,
1634
1560 QOS_ADMISSION_FAILURE = 11010,
16351561 /// QoS policy failure.
16361562 /// The QoS request was rejected because the policy system couldn't allocate the requested resource within the existing policy.
1637 WSA_QOS_POLICY_FAILURE = 11011,
1638
1563 QOS_POLICY_FAILURE = 11011,
16391564 /// QoS bad style.
16401565 /// An unknown or conflicting QoS style was encountered.
1641 WSA_QOS_BAD_STYLE = 11012,
1642
1566 QOS_BAD_STYLE = 11012,
16431567 /// QoS bad object.
16441568 /// A problem was encountered with some part of the filterspec or the provider-specific buffer in general.
1645 WSA_QOS_BAD_OBJECT = 11013,
1646
1569 QOS_BAD_OBJECT = 11013,
16471570 /// QoS traffic control error.
16481571 /// An error with the underlying traffic control (TC) API as the generic QoS request was converted for local enforcement by the TC API.
16491572 /// This could be due to an out of memory error or to an internal QoS provider error.
1650 WSA_QOS_TRAFFIC_CTRL_ERROR = 11014,
1651
1573 QOS_TRAFFIC_CTRL_ERROR = 11014,
16521574 /// QoS generic error.
16531575 /// A general QoS error.
1654 WSA_QOS_GENERIC_ERROR = 11015,
1655
1576 QOS_GENERIC_ERROR = 11015,
16561577 /// QoS service type error.
16571578 /// An invalid or unrecognized service type was found in the QoS flowspec.
1658 WSA_QOS_ESERVICETYPE = 11016,
1659
1579 QOS_ESERVICETYPE = 11016,
16601580 /// QoS flowspec error.
16611581 /// An invalid or inconsistent flowspec was found in the QOS structure.
1662 WSA_QOS_EFLOWSPEC = 11017,
1663
1582 QOS_EFLOWSPEC = 11017,
16641583 /// Invalid QoS provider buffer.
16651584 /// An invalid QoS provider-specific buffer.
1666 WSA_QOS_EPROVSPECBUF = 11018,
1667
1585 QOS_EPROVSPECBUF = 11018,
16681586 /// Invalid QoS filter style.
16691587 /// An invalid QoS filter style was used.
1670 WSA_QOS_EFILTERSTYLE = 11019,
1671
1588 QOS_EFILTERSTYLE = 11019,
16721589 /// Invalid QoS filter type.
16731590 /// An invalid QoS filter type was used.
1674 WSA_QOS_EFILTERTYPE = 11020,
1675
1591 QOS_EFILTERTYPE = 11020,
16761592 /// Incorrect QoS filter count.
16771593 /// An incorrect number of QoS FILTERSPECs were specified in the FLOWDESCRIPTOR.
1678 WSA_QOS_EFILTERCOUNT = 11021,
1679
1594 QOS_EFILTERCOUNT = 11021,
16801595 /// Invalid QoS object length.
16811596 /// An object with an invalid ObjectLength field was specified in the QoS provider-specific buffer.
1682 WSA_QOS_EOBJLENGTH = 11022,
1683
1597 QOS_EOBJLENGTH = 11022,
16841598 /// Incorrect QoS flow count.
16851599 /// An incorrect number of flow descriptors was specified in the QoS structure.
1686 WSA_QOS_EFLOWCOUNT = 11023,
1687
1600 QOS_EFLOWCOUNT = 11023,
16881601 /// Unrecognized QoS object.
16891602 /// An unrecognized object was found in the QoS provider-specific buffer.
1690 WSA_QOS_EUNKOWNPSOBJ = 11024,
1691
1603 QOS_EUNKOWNPSOBJ = 11024,
16921604 /// Invalid QoS policy object.
16931605 /// An invalid policy object was found in the QoS provider-specific buffer.
1694 WSA_QOS_EPOLICYOBJ = 11025,
1695
1606 QOS_EPOLICYOBJ = 11025,
16961607 /// Invalid QoS flow descriptor.
16971608 /// An invalid QoS flow descriptor was found in the flow descriptor list.
1698 WSA_QOS_EFLOWDESC = 11026,
1699
1609 QOS_EFLOWDESC = 11026,
17001610 /// Invalid QoS provider-specific flowspec.
17011611 /// An invalid or inconsistent flowspec was found in the QoS provider-specific buffer.
1702 WSA_QOS_EPSFLOWSPEC = 11027,
1703
1612 QOS_EPSFLOWSPEC = 11027,
17041613 /// Invalid QoS provider-specific filterspec.
17051614 /// An invalid FILTERSPEC was found in the QoS provider-specific buffer.
1706 WSA_QOS_EPSFILTERSPEC = 11028,
1707
1615 QOS_EPSFILTERSPEC = 11028,
17081616 /// Invalid QoS shape discard mode object.
17091617 /// An invalid shape discard mode object was found in the QoS provider-specific buffer.
1710 WSA_QOS_ESDMODEOBJ = 11029,
1711
1618 QOS_ESDMODEOBJ = 11029,
17121619 /// Invalid QoS shaping rate object.
17131620 /// An invalid shaping rate object was found in the QoS provider-specific buffer.
1714 WSA_QOS_ESHAPERATEOBJ = 11030,
1715
1621 QOS_ESHAPERATEOBJ = 11030,
17161622 /// Reserved policy QoS element type.
17171623 /// A reserved policy element was found in the QoS provider-specific buffer.
1718 WSA_QOS_RESERVED_PETYPE = 11031,
1719
1624 QOS_RESERVED_PETYPE = 11031,
17201625 _,
17211626};
17221627
lib/std/posix.zig+111-229
......@@ -3290,33 +3290,6 @@ pub const SocketError = error{
32903290} || UnexpectedError;
32913291
32923292pub fn socket(domain: u32, socket_type: u32, protocol: u32) SocketError!socket_t {
3293 if (native_os == .windows) {
3294 // These flags are not actually part of the Windows API, instead they are converted here for compatibility
3295 const filtered_sock_type = socket_type & ~@as(u32, SOCK.NONBLOCK | SOCK.CLOEXEC);
3296 var flags: u32 = windows.ws2_32.WSA_FLAG_OVERLAPPED;
3297 if ((socket_type & SOCK.CLOEXEC) != 0) flags |= windows.ws2_32.WSA_FLAG_NO_HANDLE_INHERIT;
3298
3299 const rc = try windows.WSASocketW(
3300 @bitCast(domain),
3301 @bitCast(filtered_sock_type),
3302 @bitCast(protocol),
3303 null,
3304 0,
3305 flags,
3306 );
3307 errdefer windows.closesocket(rc) catch unreachable;
3308 if ((socket_type & SOCK.NONBLOCK) != 0) {
3309 var mode: c_ulong = 1; // nonblocking
3310 if (windows.ws2_32.SOCKET_ERROR == windows.ws2_32.ioctlsocket(rc, windows.ws2_32.FIONBIO, &mode)) {
3311 switch (windows.ws2_32.WSAGetLastError()) {
3312 // have not identified any error codes that should be handled yet
3313 else => unreachable,
3314 }
3315 }
3316 }
3317 return rc;
3318 }
3319
33203293 const have_sock_flags = !builtin.target.os.tag.isDarwin() and native_os != .haiku;
33213294 const filtered_sock_type = if (!have_sock_flags)
33223295 socket_type & ~@as(u32, SOCK.NONBLOCK | SOCK.CLOEXEC)
......@@ -3411,14 +3384,14 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {
34113384 .both => windows.ws2_32.SD_BOTH,
34123385 });
34133386 if (0 != result) switch (windows.ws2_32.WSAGetLastError()) {
3414 .WSAECONNABORTED => return error.ConnectionAborted,
3415 .WSAECONNRESET => return error.ConnectionResetByPeer,
3416 .WSAEINPROGRESS => return error.BlockingOperationInProgress,
3417 .WSAEINVAL => unreachable,
3418 .WSAENETDOWN => return error.NetworkDown,
3419 .WSAENOTCONN => return error.SocketUnconnected,
3420 .WSAENOTSOCK => unreachable,
3421 .WSANOTINITIALISED => unreachable,
3387 .ECONNABORTED => return error.ConnectionAborted,
3388 .ECONNRESET => return error.ConnectionResetByPeer,
3389 .EINPROGRESS => return error.BlockingOperationInProgress,
3390 .EINVAL => unreachable,
3391 .ENETDOWN => return error.NetworkDown,
3392 .ENOTCONN => return error.SocketUnconnected,
3393 .ENOTSOCK => unreachable,
3394 .NOTINITIALISED => unreachable,
34223395 else => |err| return windows.unexpectedWSAError(err),
34233396 };
34243397 } else {
......@@ -3440,70 +3413,17 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {
34403413}
34413414
34423415pub const BindError = error{
3443 /// The address is protected, and the user is not the superuser.
3444 /// For UNIX domain sockets: Search permission is denied on a component
3445 /// of the path prefix.
3446 AccessDenied,
3447
3448 /// The given address is already in use, or in the case of Internet domain sockets,
3449 /// The port number was specified as zero in the socket
3450 /// address structure, but, upon attempting to bind to an ephemeral port, it was
3451 /// determined that all port numbers in the ephemeral port range are currently in
3452 /// use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range ip(7).
3453 AddressInUse,
3454
3455 /// A nonexistent interface was requested or the requested address was not local.
3456 AddressNotAvailable,
3457
3458 /// The address is not valid for the address family of socket.
3459 AddressFamilyUnsupported,
3460
3461 /// Too many symbolic links were encountered in resolving addr.
34623416 SymLinkLoop,
3463
3464 /// addr is too long.
34653417 NameTooLong,
3466
3467 /// A component in the directory prefix of the socket pathname does not exist.
34683418 FileNotFound,
3469
3470 /// Insufficient kernel memory was available.
3471 SystemResources,
3472
3473 /// A component of the path prefix is not a directory.
34743419 NotDir,
3475
3476 /// The socket inode would reside on a read-only filesystem.
34773420 ReadOnlyFileSystem,
3421 AccessDenied,
3422} || std.Io.net.IpAddress.BindError;
34783423
3479 /// The network subsystem has failed.
3480 NetworkDown,
3481
3482 FileDescriptorNotASocket,
3483
3484 AlreadyBound,
3485} || UnexpectedError;
3486
3487/// addr is `*const T` where T is one of the sockaddr
34883424pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!void {
34893425 if (native_os == .windows) {
3490 const rc = windows.bind(sock, addr, len);
3491 if (rc == windows.ws2_32.SOCKET_ERROR) {
3492 switch (windows.ws2_32.WSAGetLastError()) {
3493 .WSANOTINITIALISED => unreachable, // not initialized WSA
3494 .WSAEACCES => return error.AccessDenied,
3495 .WSAEADDRINUSE => return error.AddressInUse,
3496 .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
3497 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
3498 .WSAEFAULT => unreachable, // invalid pointers
3499 .WSAEINVAL => return error.AlreadyBound,
3500 .WSAENOBUFS => return error.SystemResources,
3501 .WSAENETDOWN => return error.NetworkDown,
3502 else => |err| return windows.unexpectedWSAError(err),
3503 }
3504 unreachable;
3505 }
3506 return;
3426 @compileError("use std.Io instead");
35073427 } else {
35083428 const rc = system.bind(sock, addr, len);
35093429 switch (errno(rc)) {
......@@ -3514,7 +3434,7 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi
35143434 .INVAL => unreachable, // invalid parameters
35153435 .NOTSOCK => unreachable, // invalid `sockfd`
35163436 .AFNOSUPPORT => return error.AddressFamilyUnsupported,
3517 .ADDRNOTAVAIL => return error.AddressNotAvailable,
3437 .ADDRNOTAVAIL => return error.AddressUnavailable,
35183438 .FAULT => unreachable, // invalid `addr` pointer
35193439 .LOOP => return error.SymLinkLoop,
35203440 .NAMETOOLONG => return error.NameTooLong,
......@@ -3529,51 +3449,13 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi
35293449}
35303450
35313451pub const ListenError = error{
3532 /// Another socket is already listening on the same port.
3533 /// For Internet domain sockets, the socket referred to by sockfd had not previously
3534 /// been bound to an address and, upon attempting to bind it to an ephemeral port, it
3535 /// was determined that all port numbers in the ephemeral port range are currently in
3536 /// use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range in ip(7).
3537 AddressInUse,
3538
3539 /// The file descriptor sockfd does not refer to a socket.
35403452 FileDescriptorNotASocket,
3541
3542 /// The socket is not of a type that supports the listen() operation.
35433453 OperationNotSupported,
3544
3545 /// The network subsystem has failed.
3546 NetworkDown,
3547
3548 /// Ran out of system resources
3549 /// On Windows it can either run out of socket descriptors or buffer space
3550 SystemResources,
3551
3552 /// Already connected
3553 AlreadyConnected,
3554
3555 /// Socket has not been bound yet
3556 SocketNotBound,
3557} || UnexpectedError;
3454} || std.Io.net.IpAddress.ListenError || std.Io.net.UnixAddress.ListenError;
35583455
35593456pub fn listen(sock: socket_t, backlog: u31) ListenError!void {
35603457 if (native_os == .windows) {
3561 const rc = windows.listen(sock, backlog);
3562 if (rc == windows.ws2_32.SOCKET_ERROR) {
3563 switch (windows.ws2_32.WSAGetLastError()) {
3564 .WSANOTINITIALISED => unreachable, // not initialized WSA
3565 .WSAENETDOWN => return error.NetworkDown,
3566 .WSAEADDRINUSE => return error.AddressInUse,
3567 .WSAEISCONN => return error.AlreadyConnected,
3568 .WSAEINVAL => return error.SocketNotBound,
3569 .WSAEMFILE, .WSAENOBUFS => return error.SystemResources,
3570 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
3571 .WSAEOPNOTSUPP => return error.OperationNotSupported,
3572 .WSAEINPROGRESS => unreachable,
3573 else => |err| return windows.unexpectedWSAError(err),
3574 }
3575 }
3576 return;
3458 @compileError("use std.Io instead");
35773459 } else {
35783460 const rc = system.listen(sock, backlog);
35793461 switch (errno(rc)) {
......@@ -3630,16 +3512,16 @@ pub fn accept(
36303512 if (native_os == .windows) {
36313513 if (rc == windows.ws2_32.INVALID_SOCKET) {
36323514 switch (windows.ws2_32.WSAGetLastError()) {
3633 .WSANOTINITIALISED => unreachable, // not initialized WSA
3634 .WSAECONNRESET => return error.ConnectionResetByPeer,
3635 .WSAEFAULT => unreachable,
3636 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
3637 .WSAEINVAL => return error.SocketNotListening,
3638 .WSAEMFILE => return error.ProcessFdQuotaExceeded,
3639 .WSAENETDOWN => return error.NetworkDown,
3640 .WSAENOBUFS => return error.FileDescriptorNotASocket,
3641 .WSAEOPNOTSUPP => return error.OperationNotSupported,
3642 .WSAEWOULDBLOCK => return error.WouldBlock,
3515 .NOTINITIALISED => unreachable, // not initialized WSA
3516 .ECONNRESET => return error.ConnectionResetByPeer,
3517 .EFAULT => unreachable,
3518 .ENOTSOCK => return error.FileDescriptorNotASocket,
3519 .EINVAL => return error.SocketNotListening,
3520 .EMFILE => return error.ProcessFdQuotaExceeded,
3521 .ENETDOWN => return error.NetworkDown,
3522 .ENOBUFS => return error.FileDescriptorNotASocket,
3523 .EOPNOTSUPP => return error.OperationNotSupported,
3524 .EWOULDBLOCK => return error.WouldBlock,
36433525 else => |err| return windows.unexpectedWSAError(err),
36443526 }
36453527 } else {
......@@ -3706,9 +3588,9 @@ fn setSockFlags(sock: socket_t, flags: u32) !void {
37063588 var mode: c_ulong = 1;
37073589 if (windows.ws2_32.ioctlsocket(sock, windows.ws2_32.FIONBIO, &mode) == windows.ws2_32.SOCKET_ERROR) {
37083590 switch (windows.ws2_32.WSAGetLastError()) {
3709 .WSANOTINITIALISED => unreachable,
3710 .WSAENETDOWN => return error.NetworkDown,
3711 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
3591 .NOTINITIALISED => unreachable,
3592 .ENETDOWN => return error.NetworkDown,
3593 .ENOTSOCK => return error.FileDescriptorNotASocket,
37123594 // TODO: handle more errors
37133595 else => |err| return windows.unexpectedWSAError(err),
37143596 }
......@@ -3861,11 +3743,11 @@ pub fn getsockname(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
38613743 const rc = windows.getsockname(sock, addr, addrlen);
38623744 if (rc == windows.ws2_32.SOCKET_ERROR) {
38633745 switch (windows.ws2_32.WSAGetLastError()) {
3864 .WSANOTINITIALISED => unreachable,
3865 .WSAENETDOWN => return error.NetworkDown,
3866 .WSAEFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
3867 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
3868 .WSAEINVAL => return error.SocketNotBound,
3746 .NOTINITIALISED => unreachable,
3747 .ENETDOWN => return error.NetworkDown,
3748 .EFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
3749 .ENOTSOCK => return error.FileDescriptorNotASocket,
3750 .EINVAL => return error.SocketNotBound,
38693751 else => |err| return windows.unexpectedWSAError(err),
38703752 }
38713753 }
......@@ -3890,11 +3772,11 @@ pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
38903772 const rc = windows.getpeername(sock, addr, addrlen);
38913773 if (rc == windows.ws2_32.SOCKET_ERROR) {
38923774 switch (windows.ws2_32.WSAGetLastError()) {
3893 .WSANOTINITIALISED => unreachable,
3894 .WSAENETDOWN => return error.NetworkDown,
3895 .WSAEFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
3896 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
3897 .WSAEINVAL => return error.SocketNotBound,
3775 .NOTINITIALISED => unreachable,
3776 .ENETDOWN => return error.NetworkDown,
3777 .EFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
3778 .ENOTSOCK => return error.FileDescriptorNotASocket,
3779 .EINVAL => return error.SocketNotBound,
38983780 else => |err| return windows.unexpectedWSAError(err),
38993781 }
39003782 }
......@@ -3932,7 +3814,7 @@ pub const ConnectError = error{
39323814 /// address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers
39333815 /// in the ephemeral port range are currently in use. See the discussion of
39343816 /// /proc/sys/net/ipv4/ip_local_port_range in ip(7).
3935 AddressNotAvailable,
3817 AddressUnavailable,
39363818
39373819 /// The passed address didn't have the correct address family in its sa_family field.
39383820 AddressFamilyUnsupported,
......@@ -3975,22 +3857,22 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne
39753857 const rc = windows.ws2_32.connect(sock, sock_addr, @intCast(len));
39763858 if (rc == 0) return;
39773859 switch (windows.ws2_32.WSAGetLastError()) {
3978 .WSAEADDRINUSE => return error.AddressInUse,
3979 .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
3980 .WSAECONNREFUSED => return error.ConnectionRefused,
3981 .WSAECONNRESET => return error.ConnectionResetByPeer,
3982 .WSAETIMEDOUT => return error.Timeout,
3983 .WSAEHOSTUNREACH, // TODO: should we return NetworkUnreachable in this case as well?
3984 .WSAENETUNREACH,
3860 .EADDRINUSE => return error.AddressInUse,
3861 .EADDRNOTAVAIL => return error.AddressUnavailable,
3862 .ECONNREFUSED => return error.ConnectionRefused,
3863 .ECONNRESET => return error.ConnectionResetByPeer,
3864 .ETIMEDOUT => return error.Timeout,
3865 .EHOSTUNREACH, // TODO: should we return NetworkUnreachable in this case as well?
3866 .ENETUNREACH,
39853867 => return error.NetworkUnreachable,
3986 .WSAEFAULT => unreachable,
3987 .WSAEINVAL => unreachable,
3988 .WSAEISCONN => return error.AlreadyConnected,
3989 .WSAENOTSOCK => unreachable,
3990 .WSAEWOULDBLOCK => return error.WouldBlock,
3991 .WSAEACCES => unreachable,
3992 .WSAENOBUFS => return error.SystemResources,
3993 .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
3868 .EFAULT => unreachable,
3869 .EINVAL => unreachable,
3870 .EISCONN => return error.AlreadyConnected,
3871 .ENOTSOCK => unreachable,
3872 .EWOULDBLOCK => return error.WouldBlock,
3873 .EACCES => unreachable,
3874 .ENOBUFS => return error.SystemResources,
3875 .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
39943876 else => |err| return windows.unexpectedWSAError(err),
39953877 }
39963878 return;
......@@ -4002,7 +3884,7 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne
40023884 .ACCES => return error.AccessDenied,
40033885 .PERM => return error.PermissionDenied,
40043886 .ADDRINUSE => return error.AddressInUse,
4005 .ADDRNOTAVAIL => return error.AddressNotAvailable,
3887 .ADDRNOTAVAIL => return error.AddressUnavailable,
40063888 .AFNOSUPPORT => return error.AddressFamilyUnsupported,
40073889 .AGAIN, .INPROGRESS => return error.WouldBlock,
40083890 .ALREADY => return error.ConnectionPending,
......@@ -4064,7 +3946,7 @@ pub fn getsockoptError(sockfd: fd_t) ConnectError!void {
40643946 .ACCES => return error.AccessDenied,
40653947 .PERM => return error.PermissionDenied,
40663948 .ADDRINUSE => return error.AddressInUse,
4067 .ADDRNOTAVAIL => return error.AddressNotAvailable,
3949 .ADDRNOTAVAIL => return error.AddressUnavailable,
40683950 .AFNOSUPPORT => return error.AddressFamilyUnsupported,
40693951 .AGAIN => return error.SystemResources,
40703952 .ALREADY => return error.ConnectionPending,
......@@ -5686,7 +5568,7 @@ pub const SendMsgError = SendError || error{
56865568
56875569 /// The socket is not connected (connection-oriented sockets only).
56885570 SocketUnconnected,
5689 AddressNotAvailable,
5571 AddressUnavailable,
56905572};
56915573
56925574pub fn sendmsg(
......@@ -5701,25 +5583,25 @@ pub fn sendmsg(
57015583 if (native_os == .windows) {
57025584 if (rc == windows.ws2_32.SOCKET_ERROR) {
57035585 switch (windows.ws2_32.WSAGetLastError()) {
5704 .WSAEACCES => return error.AccessDenied,
5705 .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
5706 .WSAECONNRESET => return error.ConnectionResetByPeer,
5707 .WSAEMSGSIZE => return error.MessageOversize,
5708 .WSAENOBUFS => return error.SystemResources,
5709 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
5710 .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
5711 .WSAEDESTADDRREQ => unreachable, // A destination address is required.
5712 .WSAEFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
5713 .WSAEHOSTUNREACH => return error.NetworkUnreachable,
5714 // TODO: WSAEINPROGRESS, WSAEINTR
5715 .WSAEINVAL => unreachable,
5716 .WSAENETDOWN => return error.NetworkDown,
5717 .WSAENETRESET => return error.ConnectionResetByPeer,
5718 .WSAENETUNREACH => return error.NetworkUnreachable,
5719 .WSAENOTCONN => return error.SocketUnconnected,
5720 .WSAESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
5721 .WSAEWOULDBLOCK => return error.WouldBlock,
5722 .WSANOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
5586 .EACCES => return error.AccessDenied,
5587 .EADDRNOTAVAIL => return error.AddressUnavailable,
5588 .ECONNRESET => return error.ConnectionResetByPeer,
5589 .EMSGSIZE => return error.MessageOversize,
5590 .ENOBUFS => return error.SystemResources,
5591 .ENOTSOCK => return error.FileDescriptorNotASocket,
5592 .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
5593 .EDESTADDRREQ => unreachable, // A destination address is required.
5594 .EFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
5595 .EHOSTUNREACH => return error.NetworkUnreachable,
5596 // TODO: EINPROGRESS, EINTR
5597 .EINVAL => unreachable,
5598 .ENETDOWN => return error.NetworkDown,
5599 .ENETRESET => return error.ConnectionResetByPeer,
5600 .ENETUNREACH => return error.NetworkUnreachable,
5601 .ENOTCONN => return error.SocketUnconnected,
5602 .ESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
5603 .EWOULDBLOCK => return error.WouldBlock,
5604 .NOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
57235605 else => |err| return windows.unexpectedWSAError(err),
57245606 }
57255607 } else {
......@@ -5804,25 +5686,25 @@ pub fn sendto(
58045686 if (native_os == .windows) {
58055687 switch (windows.sendto(sockfd, buf.ptr, buf.len, flags, dest_addr, addrlen)) {
58065688 windows.ws2_32.SOCKET_ERROR => switch (windows.ws2_32.WSAGetLastError()) {
5807 .WSAEACCES => return error.AccessDenied,
5808 .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
5809 .WSAECONNRESET => return error.ConnectionResetByPeer,
5810 .WSAEMSGSIZE => return error.MessageOversize,
5811 .WSAENOBUFS => return error.SystemResources,
5812 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
5813 .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,
5814 .WSAEDESTADDRREQ => unreachable, // A destination address is required.
5815 .WSAEFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
5816 .WSAEHOSTUNREACH => return error.NetworkUnreachable,
5817 // TODO: WSAEINPROGRESS, WSAEINTR
5818 .WSAEINVAL => unreachable,
5819 .WSAENETDOWN => return error.NetworkDown,
5820 .WSAENETRESET => return error.ConnectionResetByPeer,
5821 .WSAENETUNREACH => return error.NetworkUnreachable,
5822 .WSAENOTCONN => return error.SocketUnconnected,
5823 .WSAESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
5824 .WSAEWOULDBLOCK => return error.WouldBlock,
5825 .WSANOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
5689 .EACCES => return error.AccessDenied,
5690 .EADDRNOTAVAIL => return error.AddressUnavailable,
5691 .ECONNRESET => return error.ConnectionResetByPeer,
5692 .EMSGSIZE => return error.MessageOversize,
5693 .ENOBUFS => return error.SystemResources,
5694 .ENOTSOCK => return error.FileDescriptorNotASocket,
5695 .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
5696 .EDESTADDRREQ => unreachable, // A destination address is required.
5697 .EFAULT => unreachable, // The lpBuffers, lpTo, lpOverlapped, lpNumberOfBytesSent, or lpCompletionRoutine parameters are not part of the user address space, or the lpTo parameter is too small.
5698 .EHOSTUNREACH => return error.NetworkUnreachable,
5699 // TODO: EINPROGRESS, EINTR
5700 .EINVAL => unreachable,
5701 .ENETDOWN => return error.NetworkDown,
5702 .ENETRESET => return error.ConnectionResetByPeer,
5703 .ENETUNREACH => return error.NetworkUnreachable,
5704 .ENOTCONN => return error.SocketUnconnected,
5705 .ESHUTDOWN => unreachable, // The socket has been shut down; it is not possible to WSASendTo on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
5706 .EWOULDBLOCK => return error.WouldBlock,
5707 .NOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
58265708 else => |err| return windows.unexpectedWSAError(err),
58275709 },
58285710 else => |rc| return @intCast(rc),
......@@ -5896,7 +5778,7 @@ pub fn send(
58965778 error.FileNotFound => unreachable,
58975779 error.NotDir => unreachable,
58985780 error.NetworkUnreachable => unreachable,
5899 error.AddressNotAvailable => unreachable,
5781 error.AddressUnavailable => unreachable,
59005782 error.SocketUnconnected => unreachable,
59015783 error.UnreachableAddress => unreachable,
59025784 else => |e| return e,
......@@ -6007,9 +5889,9 @@ pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {
60075889 if (native_os == .windows) {
60085890 switch (windows.poll(fds.ptr, @intCast(fds.len), timeout)) {
60095891 windows.ws2_32.SOCKET_ERROR => switch (windows.ws2_32.WSAGetLastError()) {
6010 .WSANOTINITIALISED => unreachable,
6011 .WSAENETDOWN => return error.NetworkDown,
6012 .WSAENOBUFS => return error.SystemResources,
5892 .NOTINITIALISED => unreachable,
5893 .ENETDOWN => return error.NetworkDown,
5894 .ENOBUFS => return error.SystemResources,
60135895 // TODO: handle more errors
60145896 else => |err| return windows.unexpectedWSAError(err),
60155897 },
......@@ -6107,14 +5989,14 @@ pub fn recvfrom(
61075989 if (native_os == .windows) {
61085990 if (rc == windows.ws2_32.SOCKET_ERROR) {
61095991 switch (windows.ws2_32.WSAGetLastError()) {
6110 .WSANOTINITIALISED => unreachable,
6111 .WSAECONNRESET => return error.ConnectionResetByPeer,
6112 .WSAEINVAL => return error.SocketNotBound,
6113 .WSAEMSGSIZE => return error.MessageOversize,
6114 .WSAENETDOWN => return error.NetworkDown,
6115 .WSAENOTCONN => return error.SocketUnconnected,
6116 .WSAEWOULDBLOCK => return error.WouldBlock,
6117 .WSAETIMEDOUT => return error.Timeout,
5992 .NOTINITIALISED => unreachable,
5993 .ECONNRESET => return error.ConnectionResetByPeer,
5994 .EINVAL => return error.SocketNotBound,
5995 .EMSGSIZE => return error.MessageOversize,
5996 .ENETDOWN => return error.NetworkDown,
5997 .ENOTCONN => return error.SocketUnconnected,
5998 .EWOULDBLOCK => return error.WouldBlock,
5999 .ETIMEDOUT => return error.Timeout,
61186000 // TODO: handle more errors
61196001 else => |err| return windows.unexpectedWSAError(err),
61206002 }
......@@ -6220,11 +6102,11 @@ pub fn setsockopt(fd: socket_t, level: i32, optname: u32, opt: []const u8) SetSo
62206102 const rc = windows.ws2_32.setsockopt(fd, level, @intCast(optname), opt.ptr, @intCast(opt.len));
62216103 if (rc == windows.ws2_32.SOCKET_ERROR) {
62226104 switch (windows.ws2_32.WSAGetLastError()) {
6223 .WSANOTINITIALISED => unreachable,
6224 .WSAENETDOWN => return error.NetworkDown,
6225 .WSAEFAULT => unreachable,
6226 .WSAENOTSOCK => return error.FileDescriptorNotASocket,
6227 .WSAEINVAL => return error.SocketNotBound,
6105 .NOTINITIALISED => unreachable,
6106 .ENETDOWN => return error.NetworkDown,
6107 .EFAULT => unreachable,
6108 .ENOTSOCK => return error.FileDescriptorNotASocket,
6109 .EINVAL => return error.SocketNotBound,
62286110 else => |err| return windows.unexpectedWSAError(err),
62296111 }
62306112 }
lib/std/posix/test.zig-19
......@@ -520,25 +520,6 @@ test "getrlimit and setrlimit" {
520520 }
521521}
522522
523test "shutdown socket" {
524 if (native_os == .wasi)
525 return error.SkipZigTest;
526 if (native_os == .windows) {
527 _ = try std.os.windows.WSAStartup(2, 2);
528 }
529 defer {
530 if (native_os == .windows) {
531 std.os.windows.WSACleanup() catch unreachable;
532 }
533 }
534 const sock = try posix.socket(posix.AF.INET, posix.SOCK.STREAM, 0);
535 posix.shutdown(sock, .both) catch |err| switch (err) {
536 error.SocketUnconnected => {},
537 else => |e| return e,
538 };
539 std.posix.close(sock);
540}
541
542523test "sigrtmin/max" {
543524 if (native_os == .wasi or native_os == .windows or native_os == .macos) {
544525 return error.SkipZigTest;