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");...@@ -4,6 +4,7 @@ const builtin = @import("builtin");
4const native_os = builtin.os.tag;4const native_os = builtin.os.tag;
5const is_windows = native_os == .windows;5const is_windows = native_os == .windows;
6const windows = std.os.windows;6const windows = std.os.windows;
7const ws2_32 = std.os.windows.ws2_32;
78
8const std = @import("../std.zig");9const std = @import("../std.zig");
9const Io = std.Io;10const Io = std.Io;
...@@ -24,6 +25,7 @@ threads: std.ArrayListUnmanaged(std.Thread),...@@ -24,6 +25,7 @@ threads: std.ArrayListUnmanaged(std.Thread),
24stack_size: usize,25stack_size: usize,
25cpu_count: std.Thread.CpuCountError!usize,26cpu_count: std.Thread.CpuCountError!usize,
26concurrent_count: usize,27concurrent_count: usize,
28wsa: if (is_windows) Wsa else struct {} = .{},
2729
28threadlocal var current_closure: ?*Closure = null;30threadlocal var current_closure: ?*Closure = null;
2931
...@@ -105,6 +107,9 @@ pub fn deinit(t: *Threaded) void {...@@ -105,6 +107,9 @@ pub fn deinit(t: *Threaded) void {
105 const gpa = t.allocator;107 const gpa = t.allocator;
106 t.join();108 t.join();
107 t.threads.deinit(gpa);109 t.threads.deinit(gpa);
110 if (is_windows and t.wsa.status == .initialized) {
111 if (ws2_32.WSACleanup() != 0) recoverableOsBugDetected();
112 }
108 t.* = undefined;113 t.* = undefined;
109}114}
110115
...@@ -234,7 +239,7 @@ pub fn io(t: *Threaded) Io {...@@ -234,7 +239,7 @@ pub fn io(t: *Threaded) Io {
234 },239 },
235240
236 .netListenIp = switch (builtin.os.tag) {241 .netListenIp = switch (builtin.os.tag) {
237 .windows => @panic("TODO"),242 .windows => netListenIpWindows,
238 else => netListenIpPosix,243 else => netListenIpPosix,
239 },244 },
240 .netListenUnix = netListenUnix,245 .netListenUnix = netListenUnix,
...@@ -2797,6 +2802,116 @@ fn netListenIpPosix(...@@ -2797,6 +2802,116 @@ fn netListenIpPosix(
2797 };2802 };
2798}2803}
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
2800fn netListenUnix(2915fn netListenUnix(
2801 userdata: ?*anyopaque,2916 userdata: ?*anyopaque,
2802 address: *const net.UnixAddress,2917 address: *const net.UnixAddress,
...@@ -2971,7 +3086,7 @@ fn setSocketOption(t: *Threaded, fd: posix.fd_t, level: i32, opt_name: u32, opti...@@ -2971,7 +3086,7 @@ fn setSocketOption(t: *Threaded, fd: posix.fd_t, level: i32, opt_name: u32, opti
2971 .CANCELED => return error.Canceled,3086 .CANCELED => return error.Canceled,
29723087
2973 .BADF => |err| return errnoBug(err), // File descriptor used after closed.3088 .BADF => |err| return errnoBug(err), // File descriptor used after closed.
2974 .NOTSOCK => |err| return errnoBug(err), // always a race condition3089 .NOTSOCK => |err| return errnoBug(err),
2975 .INVAL => |err| return errnoBug(err),3090 .INVAL => |err| return errnoBug(err),
2976 .FAULT => |err| return errnoBug(err),3091 .FAULT => |err| return errnoBug(err),
2977 else => |err| return posix.unexpectedErrno(err),3092 else => |err| return posix.unexpectedErrno(err),
...@@ -2979,6 +3094,27 @@ fn setSocketOption(t: *Threaded, fd: posix.fd_t, level: i32, opt_name: u32, opti...@@ -2979,6 +3094,27 @@ fn setSocketOption(t: *Threaded, fd: posix.fd_t, level: i32, opt_name: u32, opti
2979 }3094 }
2980}3095}
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
2982fn netConnectIpPosix(3118fn netConnectIpPosix(
2983 userdata: ?*anyopaque,3119 userdata: ?*anyopaque,
2984 address: *const IpAddress,3120 address: *const IpAddress,
...@@ -3263,25 +3399,31 @@ fn netSendOne(...@@ -3263,25 +3399,31 @@ fn netSendOne(
3263 try t.checkCancel();3399 try t.checkCancel();
3264 const rc = posix.system.sendmsg(handle, &msg, flags);3400 const rc = posix.system.sendmsg(handle, &msg, flags);
3265 if (is_windows) {3401 if (is_windows) {
3266 if (rc == windows.ws2_32.SOCKET_ERROR) {3402 if (rc == ws2_32.SOCKET_ERROR) {
3267 switch (windows.ws2_32.WSAGetLastError()) {3403 switch (ws2_32.WSAGetLastError()) {
3268 .WSAEACCES => return error.AccessDenied,3404 .EINTR => continue,
3269 .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,3405 .ECANCELLED, .E_CANCELLED => return error.Canceled,
3270 .WSAECONNRESET => return error.ConnectionResetByPeer,3406 .NOTINITIALISED => {
3271 .WSAEMSGSIZE => return error.MessageOversize,3407 try initializeWsa(t);
3272 .WSAENOBUFS => return error.SystemResources,3408 continue;
3273 .WSAENOTSOCK => return error.FileDescriptorNotASocket,3409 },
3274 .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,3410 .EACCES => return error.AccessDenied,
3275 .WSAEDESTADDRREQ => unreachable, // A destination address is required.3411 .EADDRNOTAVAIL => return error.AddressUnavailable,
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.3412 .ECONNRESET => return error.ConnectionResetByPeer,
3277 .WSAEHOSTUNREACH => return error.NetworkUnreachable,3413 .EMSGSIZE => return error.MessageOversize,
3278 .WSAEINVAL => unreachable,3414 .ENOBUFS => return error.SystemResources,
3279 .WSAENETDOWN => return error.NetworkDown,3415 .ENOTSOCK => return error.FileDescriptorNotASocket,
3280 .WSAENETRESET => return error.ConnectionResetByPeer,3416 .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
3281 .WSAENETUNREACH => return error.NetworkUnreachable,3417 .EDESTADDRREQ => unreachable, // A destination address is required.
3282 .WSAENOTCONN => return error.SocketUnconnected,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.
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.3419 .EHOSTUNREACH => return error.NetworkUnreachable,
3284 .WSANOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.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.
3285 else => |err| return windows.unexpectedWSAError(err),3427 else => |err| return windows.unexpectedWSAError(err),
3286 }3428 }
3287 } else {3429 } else {
...@@ -3613,7 +3755,7 @@ fn netClose(userdata: ?*anyopaque, handle: net.Socket.Handle) void {...@@ -3613,7 +3755,7 @@ fn netClose(userdata: ?*anyopaque, handle: net.Socket.Handle) void {
3613 const t: *Threaded = @ptrCast(@alignCast(userdata));3755 const t: *Threaded = @ptrCast(@alignCast(userdata));
3614 _ = t;3756 _ = t;
3615 switch (native_os) {3757 switch (native_os) {
3616 .windows => windows.closesocket(handle) catch recoverableOsBugDetected(),3758 .windows => closeSocketWindows(handle) catch recoverableOsBugDetected(),
3617 else => posix.close(handle),3759 else => posix.close(handle),
3618 }3760 }
3619}3761}
...@@ -3664,7 +3806,7 @@ fn netInterfaceNameResolve(...@@ -3664,7 +3806,7 @@ fn netInterfaceNameResolve(
36643806
3665 if (native_os == .windows) {3807 if (native_os == .windows) {
3666 try t.checkCancel();3808 try t.checkCancel();
3667 const index = windows.ws2_32.if_nametoindex(&name.bytes);3809 const index = ws2_32.if_nametoindex(&name.bytes);
3668 if (index == 0) return error.InterfaceNotFound;3810 if (index == 0) return error.InterfaceNotFound;
3669 return .{ .index = index };3811 return .{ .index = index };
3670 }3812 }
...@@ -3881,6 +4023,13 @@ const UnixAddress = extern union {...@@ -3881,6 +4023,13 @@ const UnixAddress = extern union {
3881 un: posix.sockaddr.un,4023 un: posix.sockaddr.un,
3882};4024};
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
3884fn posixAddressFamily(a: *const IpAddress) posix.sa_family_t {4033fn posixAddressFamily(a: *const IpAddress) posix.sa_family_t {
3885 return switch (a.*) {4034 return switch (a.*) {
3886 .ip4 => posix.AF.INET,4035 .ip4 => posix.AF.INET,
...@@ -3896,6 +4045,14 @@ fn addressFromPosix(posix_address: *const PosixAddress) IpAddress {...@@ -3896,6 +4045,14 @@ fn addressFromPosix(posix_address: *const PosixAddress) IpAddress {
3896 };4045 };
3897}4046}
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
3899fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_t {4056fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_t {
3900 return switch (a.*) {4057 return switch (a.*) {
3901 .ip4 => |ip4| {4058 .ip4 => |ip4| {
...@@ -3909,6 +4066,19 @@ fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_t {...@@ -3909,6 +4066,19 @@ fn addressToPosix(a: *const IpAddress, storage: *PosixAddress) posix.socklen_t {
3909 };4066 };
3910}4067}
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
3912fn addressUnixToPosix(a: *const net.UnixAddress, storage: *UnixAddress) posix.socklen_t {4082fn addressUnixToPosix(a: *const net.UnixAddress, storage: *UnixAddress) posix.socklen_t {
3913 @memcpy(storage.un.path[0..a.path.len], a.path);4083 @memcpy(storage.un.path[0..a.path.len], a.path);
3914 storage.un.family = posix.AF.UNIX;4084 storage.un.family = posix.AF.UNIX;
...@@ -3932,6 +4102,22 @@ fn address6FromPosix(in6: *const posix.sockaddr.in6) net.Ip6Address {...@@ -3932,6 +4102,22 @@ fn address6FromPosix(in6: *const posix.sockaddr.in6) net.Ip6Address {
3932 };4102 };
3933}4103}
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
3935fn address4ToPosix(a: net.Ip4Address) posix.sockaddr.in {4121fn address4ToPosix(a: net.Ip4Address) posix.sockaddr.in {
3936 return .{4122 return .{
3937 .port = std.mem.nativeToBig(u16, a.port),4123 .port = std.mem.nativeToBig(u16, a.port),
...@@ -3955,6 +4141,13 @@ fn errnoBug(err: posix.E) Io.UnexpectedError {...@@ -3955,6 +4141,13 @@ fn errnoBug(err: posix.E) Io.UnexpectedError {
3955 }4141 }
3956}4142}
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
3958fn posixSocketMode(mode: net.Socket.Mode) u32 {4151fn posixSocketMode(mode: net.Socket.Mode) u32 {
3959 return switch (mode) {4152 return switch (mode) {
3960 .stream => posix.SOCK.STREAM,4153 .stream => posix.SOCK.STREAM,
...@@ -4814,3 +5007,59 @@ pub const ResetEvent = enum(u32) {...@@ -4814,3 +5007,59 @@ pub const ResetEvent = enum(u32) {
4814 @atomicStore(ResetEvent, re, .unset, .monotonic);5007 @atomicStore(ResetEvent, re, .unset, .monotonic);
4815 }5008 }
4816};5009};
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...@@ -1574,131 +1574,11 @@ pub fn GetFileAttributesW(lpFileName: [*:0]const u16) GetFileAttributesError!DWO
1574 return rc;1574 return rc;
1575}1575}
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
1693pub fn accept(s: ws2_32.SOCKET, name: ?*ws2_32.sockaddr, namelen: ?*ws2_32.socklen_t) ws2_32.SOCKET {1577pub fn accept(s: ws2_32.SOCKET, name: ?*ws2_32.sockaddr, namelen: ?*ws2_32.socklen_t) ws2_32.SOCKET {
1694 assert((name == null) == (namelen == null));1578 assert((name == null) == (namelen == null));
1695 return ws2_32.accept(s, name, @as(?*i32, @ptrCast(namelen)));1579 return ws2_32.accept(s, name, @as(?*i32, @ptrCast(namelen)));
1696}1580}
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
1702pub fn getpeername(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 {1582pub fn getpeername(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 {
1703 return ws2_32.getpeername(s, name, @as(*i32, @ptrCast(namelen)));1583 return ws2_32.getpeername(s, name, @as(*i32, @ptrCast(namelen)));
1704}1584}
...@@ -2816,38 +2696,6 @@ inline fn MAKELANGID(p: c_ushort, s: c_ushort) LANGID {...@@ -2816,38 +2696,6 @@ inline fn MAKELANGID(p: c_ushort, s: c_ushort) LANGID {
2816 return (s << 10) | p;2696 return (s << 10) | p;
2817}2697}
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
2851/// Call this when you made a windows DLL call or something that does SetLastError2699/// Call this when you made a windows DLL call or something that does SetLastError
2852/// and you get an unexpected error.2700/// and you get an unexpected error.
2853pub fn unexpectedError(err: Win32Error) UnexpectedError {2701pub fn unexpectedError(err: Win32Error) UnexpectedError {
lib/std/os/windows/test.zig-25
...@@ -237,28 +237,3 @@ test "removeDotDirs" {...@@ -237,28 +237,3 @@ test "removeDotDirs" {
237 try testRemoveDotDirs("a\\b\\..\\", "a\\");237 try testRemoveDotDirs("a\\b\\..\\", "a\\");
238 try testRemoveDotDirs("a\\b\\..\\c", "a\\c");238 try testRemoveDotDirs("a\\b\\..\\c", "a\\c");
239}239}
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 {...@@ -1271,130 +1271,105 @@ pub const timeval = extern struct {
1271 usec: LONG,1271 usec: LONG,
1272};1272};
12731273
1274// https://docs.microsoft.com/en-au/windows/win32/winsock/windows-sockets-error-codes-21274/// https://docs.microsoft.com/en-au/windows/win32/winsock/windows-sockets-error-codes-2
1275pub const WinsockError = enum(u16) {1275pub const WinsockError = enum(u16) {
1276 /// Specified event object handle is invalid.1276 /// Specified event object handle is invalid.
1277 /// An application attempts to use an event object, but the specified handle is not valid.1277 /// An application attempts to use an event object, but the specified handle is not valid.
1278 WSA_INVALID_HANDLE = 6,1278 INVALID_HANDLE = 6,
1279
1280 /// Insufficient memory available.1279 /// Insufficient memory available.
1281 /// An application used a Windows Sockets function that directly maps to a Windows function.1280 /// An application used a Windows Sockets function that directly maps to a Windows function.
1282 /// The Windows function is indicating a lack of required memory resources.1281 /// The Windows function is indicating a lack of required memory resources.
1283 WSA_NOT_ENOUGH_MEMORY = 8,1282 NOT_ENOUGH_MEMORY = 8,
1284
1285 /// One or more parameters are invalid.1283 /// One or more parameters are invalid.
1286 /// An application used a Windows Sockets function which directly maps to a Windows function.1284 /// An application used a Windows Sockets function which directly maps to a Windows function.
1287 /// The Windows function is indicating a problem with one or more parameters.1285 /// The Windows function is indicating a problem with one or more parameters.
1288 WSA_INVALID_PARAMETER = 87,1286 INVALID_PARAMETER = 87,
1289
1290 /// Overlapped operation aborted.1287 /// Overlapped operation aborted.
1291 /// An overlapped operation was canceled due to the closure of the socket, or the execution of the SIO_FLUSH command in WSAIoctl.1288 /// 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,1289 OPERATION_ABORTED = 995,
1293
1294 /// Overlapped I/O event object not in signaled state.1290 /// Overlapped I/O event object not in signaled state.
1295 /// The application has tried to determine the status of an overlapped operation which is not yet completed.1291 /// The application has tried to determine the status of an overlapped operation which is not yet completed.
1296 /// 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.1292 /// 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,1293 IO_INCOMPLETE = 996,
1298
1299 /// The application has initiated an overlapped operation that cannot be completed immediately.1294 /// The application has initiated an overlapped operation that cannot be completed immediately.
1300 /// A completion indication will be given later when the operation has been completed.1295 /// A completion indication will be given later when the operation has been completed.
1301 WSA_IO_PENDING = 997,1296 IO_PENDING = 997,
1302
1303 /// Interrupted function call.1297 /// Interrupted function call.
1304 /// A blocking operation was interrupted by a call to WSACancelBlockingCall.1298 /// A blocking operation was interrupted by a call to WSACancelBlockingCall.
1305 WSAEINTR = 10004,1299 EINTR = 10004,
1306
1307 /// File handle is not valid.1300 /// File handle is not valid.
1308 /// The file handle supplied is not valid.1301 /// The file handle supplied is not valid.
1309 WSAEBADF = 10009,1302 EBADF = 10009,
1310
1311 /// Permission denied.1303 /// Permission denied.
1312 /// An attempt was made to access a socket in a way forbidden by its access permissions.1304 /// An attempt was made to access a socket in a way forbidden by its access permissions.
1313 /// An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO.BROADCAST).1305 /// An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO.BROADCAST).
1314 /// 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.1306 /// 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.
1315 /// 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.1307 /// 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,1308 EACCES = 10013,
1317
1318 /// Bad address.1309 /// Bad address.
1319 /// The system detected an invalid pointer address in attempting to use a pointer argument of a call.1310 /// The system detected an invalid pointer address in attempting to use a pointer argument of a call.
1320 /// This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small.1311 /// This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small.
1321 /// For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).1312 /// For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).
1322 WSAEFAULT = 10014,1313 EFAULT = 10014,
1323
1324 /// Invalid argument.1314 /// Invalid argument.
1325 /// Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function).1315 /// Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function).
1326 /// In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.1316 /// 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,1317 EINVAL = 10022,
1328
1329 /// Too many open files.1318 /// Too many open files.
1330 /// Too many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process, or per thread.1319 /// 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,1320 EMFILE = 10024,
1332
1333 /// Resource temporarily unavailable.1321 /// Resource temporarily unavailable.
1334 /// 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.1322 /// 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.
1335 /// It is a nonfatal error, and the operation should be retried later.1323 /// It is a nonfatal error, and the operation should be retried later.
1336 /// 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.1324 /// 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,1325 EWOULDBLOCK = 10035,
1338
1339 /// Operation now in progress.1326 /// Operation now in progress.
1340 /// A blocking operation is currently executing.1327 /// A blocking operation is currently executing.
1341 /// 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.1328 /// 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,1329 EINPROGRESS = 10036,
1343
1344 /// Operation already in progress.1330 /// Operation already in progress.
1345 /// 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.1331 /// 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,1332 EALREADY = 10037,
1347
1348 /// Socket operation on nonsocket.1333 /// Socket operation on nonsocket.
1349 /// An operation was attempted on something that is not a socket.1334 /// An operation was attempted on something that is not a socket.
1350 /// Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.1335 /// 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,1336 ENOTSOCK = 10038,
1352
1353 /// Destination address required.1337 /// Destination address required.
1354 /// A required address was omitted from an operation on a socket.1338 /// A required address was omitted from an operation on a socket.
1355 /// For example, this error is returned if sendto is called with the remote address of ADDR_ANY.1339 /// For example, this error is returned if sendto is called with the remote address of ADDR_ANY.
1356 WSAEDESTADDRREQ = 10039,1340 EDESTADDRREQ = 10039,
1357
1358 /// Message too long.1341 /// Message too long.
1359 /// 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.1342 /// 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,1343 EMSGSIZE = 10040,
1361
1362 /// Protocol wrong type for socket.1344 /// Protocol wrong type for socket.
1363 /// A protocol was specified in the socket function call that does not support the semantics of the socket type requested.1345 /// A protocol was specified in the socket function call that does not support the semantics of the socket type requested.
1364 /// For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK.STREAM.1346 /// For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK.STREAM.
1365 WSAEPROTOTYPE = 10041,1347 EPROTOTYPE = 10041,
1366
1367 /// Bad protocol option.1348 /// Bad protocol option.
1368 /// An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.1349 /// An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.
1369 WSAENOPROTOOPT = 10042,1350 ENOPROTOOPT = 10042,
1370
1371 /// Protocol not supported.1351 /// Protocol not supported.
1372 /// The requested protocol has not been configured into the system, or no implementation for it exists.1352 /// The requested protocol has not been configured into the system, or no implementation for it exists.
1373 /// For example, a socket call requests a SOCK.DGRAM socket, but specifies a stream protocol.1353 /// For example, a socket call requests a SOCK.DGRAM socket, but specifies a stream protocol.
1374 WSAEPROTONOSUPPORT = 10043,1354 EPROTONOSUPPORT = 10043,
1375
1376 /// Socket type not supported.1355 /// Socket type not supported.
1377 /// The support for the specified socket type does not exist in this address family.1356 /// The support for the specified socket type does not exist in this address family.
1378 /// 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.1357 /// 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,1358 ESOCKTNOSUPPORT = 10044,
1380
1381 /// Operation not supported.1359 /// Operation not supported.
1382 /// The attempted operation is not supported for the type of object referenced.1360 /// The attempted operation is not supported for the type of object referenced.
1383 /// 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.1361 /// 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,1362 EOPNOTSUPP = 10045,
1385
1386 /// Protocol family not supported.1363 /// Protocol family not supported.
1387 /// The protocol family has not been configured into the system or no implementation for it exists.1364 /// The protocol family has not been configured into the system or no implementation for it exists.
1388 /// This message has a slightly different meaning from WSAEAFNOSUPPORT.1365 /// This message has a slightly different meaning from WSAEAFNOSUPPORT.
1389 /// However, it is interchangeable in most cases, and all Windows Sockets functions that return one of these messages also specify WSAEAFNOSUPPORT.1366 /// However, it is interchangeable in most cases, and all Windows Sockets functions that return one of these messages also specify WSAEAFNOSUPPORT.
1390 WSAEPFNOSUPPORT = 10046,1367 EPFNOSUPPORT = 10046,
1391
1392 /// Address family not supported by protocol family.1368 /// Address family not supported by protocol family.
1393 /// An address incompatible with the requested protocol was used.1369 /// An address incompatible with the requested protocol was used.
1394 /// 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).1370 /// 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).
1395 /// 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.1371 /// 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,1372 EAFNOSUPPORT = 10047,
1397
1398 /// Address already in use.1373 /// Address already in use.
1399 /// Typically, only one usage of each socket address (protocol/IP address/port) is permitted.1374 /// Typically, only one usage of each socket address (protocol/IP address/port) is permitted.
1400 /// 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.1375 /// 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) {...@@ -1402,115 +1377,91 @@ pub const WinsockError = enum(u16) {
1402 /// Client applications usually need not call bind at all—connect chooses an unused port automatically.1377 /// Client applications usually need not call bind at all—connect chooses an unused port automatically.
1403 /// When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed.1378 /// When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed.
1404 /// This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.1379 /// This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.
1405 WSAEADDRINUSE = 10048,1380 EADDRINUSE = 10048,
1406
1407 /// Cannot assign requested address.1381 /// Cannot assign requested address.
1408 /// The requested address is not valid in its context.1382 /// The requested address is not valid in its context.
1409 /// This normally results from an attempt to bind to an address that is not valid for the local computer.1383 /// This normally results from an attempt to bind to an address that is not valid for the local computer.
1410 /// 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).1384 /// 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,1385 EADDRNOTAVAIL = 10049,
1412
1413 /// Network is down.1386 /// Network is down.
1414 /// A socket operation encountered a dead network.1387 /// A socket operation encountered a dead network.
1415 /// 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.1388 /// 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,1389 ENETDOWN = 10050,
1417
1418 /// Network is unreachable.1390 /// Network is unreachable.
1419 /// A socket operation was attempted to an unreachable network.1391 /// A socket operation was attempted to an unreachable network.
1420 /// This usually means the local software knows no route to reach the remote host.1392 /// This usually means the local software knows no route to reach the remote host.
1421 WSAENETUNREACH = 10051,1393 ENETUNREACH = 10051,
1422
1423 /// Network dropped connection on reset.1394 /// Network dropped connection on reset.
1424 /// The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress.1395 /// The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress.
1425 /// It can also be returned by setsockopt if an attempt is made to set SO.KEEPALIVE on a connection that has already failed.1396 /// 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,1397 ENETRESET = 10052,
1427
1428 /// Software caused connection abort.1398 /// Software caused connection abort.
1429 /// An established connection was aborted by the software in your host computer, possibly due to a data transmission time-out or protocol error.1399 /// 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,1400 ECONNABORTED = 10053,
1431
1432 /// Connection reset by peer.1401 /// Connection reset by peer.
1433 /// An existing connection was forcibly closed by the remote host.1402 /// An existing connection was forcibly closed by the remote host.
1434 /// 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).1403 /// 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).
1435 /// 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.1404 /// 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.
1436 /// Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.1405 /// Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.
1437 WSAECONNRESET = 10054,1406 ECONNRESET = 10054,
1438
1439 /// No buffer space available.1407 /// No buffer space available.
1440 /// An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.1408 /// 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,1409 ENOBUFS = 10055,
1442
1443 /// Socket is already connected.1410 /// Socket is already connected.
1444 /// A connect request was made on an already-connected socket.1411 /// A connect request was made on an already-connected socket.
1445 /// 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.1412 /// 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,1413 EISCONN = 10056,
1447
1448 /// Socket is not connected.1414 /// Socket is not connected.
1449 /// 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.1415 /// 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.
1450 /// Any other type of operation might also return this error—for example, setsockopt setting SO.KEEPALIVE if the connection has been reset.1416 /// 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,1417 ENOTCONN = 10057,
1452
1453 /// Cannot send after socket shutdown.1418 /// Cannot send after socket shutdown.
1454 /// 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.1419 /// 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.
1455 /// By calling shutdown a partial close of a socket is requested, which is a signal that sending or receiving, or both have been discontinued.1420 /// 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,1421 ESHUTDOWN = 10058,
1457
1458 /// Too many references.1422 /// Too many references.
1459 /// Too many references to some kernel object.1423 /// Too many references to some kernel object.
1460 WSAETOOMANYREFS = 10059,1424 ETOOMANYREFS = 10059,
1461
1462 /// Connection timed out.1425 /// Connection timed out.
1463 /// 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.1426 /// 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,1427 ETIMEDOUT = 10060,
1465
1466 /// Connection refused.1428 /// Connection refused.
1467 /// No connection could be made because the target computer actively refused it.1429 /// No connection could be made because the target computer actively refused it.
1468 /// 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.1430 /// 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,1431 ECONNREFUSED = 10061,
1470
1471 /// Cannot translate name.1432 /// Cannot translate name.
1472 /// Cannot translate a name.1433 /// Cannot translate a name.
1473 WSAELOOP = 10062,1434 ELOOP = 10062,
1474
1475 /// Name too long.1435 /// Name too long.
1476 /// A name component or a name was too long.1436 /// A name component or a name was too long.
1477 WSAENAMETOOLONG = 10063,1437 ENAMETOOLONG = 10063,
1478
1479 /// Host is down.1438 /// Host is down.
1480 /// A socket operation failed because the destination host is down. A socket operation encountered a dead host.1439 /// A socket operation failed because the destination host is down. A socket operation encountered a dead host.
1481 /// Networking activity on the local host has not been initiated.1440 /// Networking activity on the local host has not been initiated.
1482 /// These conditions are more likely to be indicated by the error WSAETIMEDOUT.1441 /// These conditions are more likely to be indicated by the error WSAETIMEDOUT.
1483 WSAEHOSTDOWN = 10064,1442 EHOSTDOWN = 10064,
1484
1485 /// No route to host.1443 /// No route to host.
1486 /// A socket operation was attempted to an unreachable host. See WSAENETUNREACH.1444 /// A socket operation was attempted to an unreachable host. See WSAENETUNREACH.
1487 WSAEHOSTUNREACH = 10065,1445 EHOSTUNREACH = 10065,
1488
1489 /// Directory not empty.1446 /// Directory not empty.
1490 /// Cannot remove a directory that is not empty.1447 /// Cannot remove a directory that is not empty.
1491 WSAENOTEMPTY = 10066,1448 ENOTEMPTY = 10066,
1492
1493 /// Too many processes.1449 /// Too many processes.
1494 /// A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously.1450 /// A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously.
1495 /// WSAStartup may fail with this error if the limit has been reached.1451 /// WSAStartup may fail with this error if the limit has been reached.
1496 WSAEPROCLIM = 10067,1452 EPROCLIM = 10067,
1497
1498 /// User quota exceeded.1453 /// User quota exceeded.
1499 /// Ran out of user quota.1454 /// Ran out of user quota.
1500 WSAEUSERS = 10068,1455 EUSERS = 10068,
1501
1502 /// Disk quota exceeded.1456 /// Disk quota exceeded.
1503 /// Ran out of disk quota.1457 /// Ran out of disk quota.
1504 WSAEDQUOT = 10069,1458 EDQUOT = 10069,
1505
1506 /// Stale file handle reference.1459 /// Stale file handle reference.
1507 /// The file handle reference is no longer available.1460 /// The file handle reference is no longer available.
1508 WSAESTALE = 10070,1461 ESTALE = 10070,
1509
1510 /// Item is remote.1462 /// Item is remote.
1511 /// The item is not available locally.1463 /// The item is not available locally.
1512 WSAEREMOTE = 10071,1464 EREMOTE = 10071,
1513
1514 /// Network subsystem is unavailable.1465 /// Network subsystem is unavailable.
1515 /// 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.1466 /// 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.
1516 /// Users should check:1467 /// Users should check:
...@@ -1518,47 +1469,38 @@ pub const WinsockError = enum(u16) {...@@ -1518,47 +1469,38 @@ pub const WinsockError = enum(u16) {
1518 /// - That they are not trying to use more than one Windows Sockets implementation simultaneously.1469 /// - That they are not trying to use more than one Windows Sockets implementation simultaneously.
1519 /// - 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.1470 /// - 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.
1520 /// - The Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.1471 /// - The Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.
1521 WSASYSNOTREADY = 10091,1472 SYSNOTREADY = 10091,
1522
1523 /// Winsock.dll version out of range.1473 /// Winsock.dll version out of range.
1524 /// The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application.1474 /// The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application.
1525 /// Check that no old Windows Sockets DLL files are being accessed.1475 /// Check that no old Windows Sockets DLL files are being accessed.
1526 WSAVERNOTSUPPORTED = 10092,1476 VERNOTSUPPORTED = 10092,
1527
1528 /// Successful WSAStartup not yet performed.1477 /// Successful WSAStartup not yet performed.
1529 /// Either the application has not called WSAStartup or WSAStartup failed.1478 /// Either the application has not called WSAStartup or WSAStartup failed.
1530 /// 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.1479 /// 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,1480 NOTINITIALISED = 10093,
1532
1533 /// Graceful shutdown in progress.1481 /// Graceful shutdown in progress.
1534 /// Returned by WSARecv and WSARecvFrom to indicate that the remote party has initiated a graceful shutdown sequence.1482 /// Returned by WSARecv and WSARecvFrom to indicate that the remote party has initiated a graceful shutdown sequence.
1535 WSAEDISCON = 10101,1483 EDISCON = 10101,
1536
1537 /// No more results.1484 /// No more results.
1538 /// No more results can be returned by the WSALookupServiceNext function.1485 /// No more results can be returned by the WSALookupServiceNext function.
1539 WSAENOMORE = 10102,1486 ENOMORE = 10102,
1540
1541 /// Call has been canceled.1487 /// Call has been canceled.
1542 /// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.1488 /// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.
1543 WSAECANCELLED = 10103,1489 ECANCELLED = 10103,
1544
1545 /// Procedure call table is invalid.1490 /// Procedure call table is invalid.
1546 /// The service provider procedure call table is invalid.1491 /// The service provider procedure call table is invalid.
1547 /// A service provider returned a bogus procedure table to Ws2_32.dll.1492 /// A service provider returned a bogus procedure table to Ws2_32.dll.
1548 /// This is usually caused by one or more of the function pointers being NULL.1493 /// This is usually caused by one or more of the function pointers being NULL.
1549 WSAEINVALIDPROCTABLE = 10104,1494 EINVALIDPROCTABLE = 10104,
1550
1551 /// Service provider is invalid.1495 /// Service provider is invalid.
1552 /// The requested service provider is invalid.1496 /// The requested service provider is invalid.
1553 /// This error is returned by the WSCGetProviderInfo and WSCGetProviderInfo32 functions if the protocol entry specified could not be found.1497 /// This error is returned by the WSCGetProviderInfo and WSCGetProviderInfo32 functions if the protocol entry specified could not be found.
1554 /// This error is also returned if the service provider returned a version number other than 2.0.1498 /// This error is also returned if the service provider returned a version number other than 2.0.
1555 WSAEINVALIDPROVIDER = 10105,1499 EINVALIDPROVIDER = 10105,
1556
1557 /// Service provider failed to initialize.1500 /// Service provider failed to initialize.
1558 /// The requested service provider could not be loaded or initialized.1501 /// The requested service provider could not be loaded or initialized.
1559 /// 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.1502 /// 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,1503 EPROVIDERFAILEDINIT = 10106,
1561
1562 /// System call failure.1504 /// System call failure.
1563 /// A system call that should never fail has failed.1505 /// A system call that should never fail has failed.
1564 /// This is a generic error code, returned under various conditions.1506 /// This is a generic error code, returned under various conditions.
...@@ -1566,157 +1508,120 @@ pub const WinsockError = enum(u16) {...@@ -1566,157 +1508,120 @@ pub const WinsockError = enum(u16) {
1566 /// For example, if a call to WaitForMultipleEvents fails or one of the registry functions fails trying to manipulate the protocol/namespace catalogs.1508 /// For example, if a call to WaitForMultipleEvents fails or one of the registry functions fails trying to manipulate the protocol/namespace catalogs.
1567 /// Returned when a provider does not return SUCCESS and does not provide an extended error code.1509 /// Returned when a provider does not return SUCCESS and does not provide an extended error code.
1568 /// Can indicate a service provider implementation error.1510 /// Can indicate a service provider implementation error.
1569 WSASYSCALLFAILURE = 10107,1511 SYSCALLFAILURE = 10107,
1570
1571 /// Service not found.1512 /// Service not found.
1572 /// No such service is known. The service cannot be found in the specified name space.1513 /// No such service is known. The service cannot be found in the specified name space.
1573 WSASERVICE_NOT_FOUND = 10108,1514 SERVICE_NOT_FOUND = 10108,
1574
1575 /// Class type not found.1515 /// Class type not found.
1576 /// The specified class was not found.1516 /// The specified class was not found.
1577 WSATYPE_NOT_FOUND = 10109,1517 TYPE_NOT_FOUND = 10109,
1578
1579 /// No more results.1518 /// No more results.
1580 /// No more results can be returned by the WSALookupServiceNext function.1519 /// No more results can be returned by the WSALookupServiceNext function.
1581 WSA_E_NO_MORE = 10110,1520 E_NO_MORE = 10110,
1582
1583 /// Call was canceled.1521 /// Call was canceled.
1584 /// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.1522 /// A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.
1585 WSA_E_CANCELLED = 10111,1523 E_CANCELLED = 10111,
1586
1587 /// Database query was refused.1524 /// Database query was refused.
1588 /// A database query failed because it was actively refused.1525 /// A database query failed because it was actively refused.
1589 WSAEREFUSED = 10112,1526 EREFUSED = 10112,
1590
1591 /// Host not found.1527 /// Host not found.
1592 /// 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.1528 /// 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.
1593 /// 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.1529 /// 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,1530 HOST_NOT_FOUND = 11001,
1595
1596 /// Nonauthoritative host not found.1531 /// Nonauthoritative host not found.
1597 /// 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.1532 /// 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,1533 TRY_AGAIN = 11002,
1599
1600 /// This is a nonrecoverable error.1534 /// This is a nonrecoverable error.
1601 /// This indicates that some sort of nonrecoverable error occurred during a database lookup.1535 /// This indicates that some sort of nonrecoverable error occurred during a database lookup.
1602 /// 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.1536 /// 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,1537 NO_RECOVERY = 11003,
1604
1605 /// Valid name, no data record of requested type.1538 /// Valid name, no data record of requested type.
1606 /// The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for.1539 /// The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for.
1607 /// The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server).1540 /// The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server).
1608 /// An MX record is returned but no A record—indicating the host itself exists, but is not directly reachable.1541 /// An MX record is returned but no A record—indicating the host itself exists, but is not directly reachable.
1609 WSANO_DATA = 11004,1542 NO_DATA = 11004,
1610
1611 /// QoS receivers.1543 /// QoS receivers.
1612 /// At least one QoS reserve has arrived.1544 /// At least one QoS reserve has arrived.
1613 WSA_QOS_RECEIVERS = 11005,1545 QOS_RECEIVERS = 11005,
1614
1615 /// QoS senders.1546 /// QoS senders.
1616 /// At least one QoS send path has arrived.1547 /// At least one QoS send path has arrived.
1617 WSA_QOS_SENDERS = 11006,1548 QOS_SENDERS = 11006,
1618
1619 /// No QoS senders.1549 /// No QoS senders.
1620 /// There are no QoS senders.1550 /// There are no QoS senders.
1621 WSA_QOS_NO_SENDERS = 11007,1551 QOS_NO_SENDERS = 11007,
1622
1623 /// QoS no receivers.1552 /// QoS no receivers.
1624 /// There are no QoS receivers.1553 /// There are no QoS receivers.
1625 WSA_QOS_NO_RECEIVERS = 11008,1554 QOS_NO_RECEIVERS = 11008,
1626
1627 /// QoS request confirmed.1555 /// QoS request confirmed.
1628 /// The QoS reserve request has been confirmed.1556 /// The QoS reserve request has been confirmed.
1629 WSA_QOS_REQUEST_CONFIRMED = 11009,1557 QOS_REQUEST_CONFIRMED = 11009,
1630
1631 /// QoS admission error.1558 /// QoS admission error.
1632 /// A QoS error occurred due to lack of resources.1559 /// A QoS error occurred due to lack of resources.
1633 WSA_QOS_ADMISSION_FAILURE = 11010,1560 QOS_ADMISSION_FAILURE = 11010,
1634
1635 /// QoS policy failure.1561 /// QoS policy failure.
1636 /// The QoS request was rejected because the policy system couldn't allocate the requested resource within the existing policy.1562 /// 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,1563 QOS_POLICY_FAILURE = 11011,
1638
1639 /// QoS bad style.1564 /// QoS bad style.
1640 /// An unknown or conflicting QoS style was encountered.1565 /// An unknown or conflicting QoS style was encountered.
1641 WSA_QOS_BAD_STYLE = 11012,1566 QOS_BAD_STYLE = 11012,
1642
1643 /// QoS bad object.1567 /// QoS bad object.
1644 /// A problem was encountered with some part of the filterspec or the provider-specific buffer in general.1568 /// A problem was encountered with some part of the filterspec or the provider-specific buffer in general.
1645 WSA_QOS_BAD_OBJECT = 11013,1569 QOS_BAD_OBJECT = 11013,
1646
1647 /// QoS traffic control error.1570 /// QoS traffic control error.
1648 /// An error with the underlying traffic control (TC) API as the generic QoS request was converted for local enforcement by the TC API.1571 /// An error with the underlying traffic control (TC) API as the generic QoS request was converted for local enforcement by the TC API.
1649 /// This could be due to an out of memory error or to an internal QoS provider error.1572 /// This could be due to an out of memory error or to an internal QoS provider error.
1650 WSA_QOS_TRAFFIC_CTRL_ERROR = 11014,1573 QOS_TRAFFIC_CTRL_ERROR = 11014,
1651
1652 /// QoS generic error.1574 /// QoS generic error.
1653 /// A general QoS error.1575 /// A general QoS error.
1654 WSA_QOS_GENERIC_ERROR = 11015,1576 QOS_GENERIC_ERROR = 11015,
1655
1656 /// QoS service type error.1577 /// QoS service type error.
1657 /// An invalid or unrecognized service type was found in the QoS flowspec.1578 /// An invalid or unrecognized service type was found in the QoS flowspec.
1658 WSA_QOS_ESERVICETYPE = 11016,1579 QOS_ESERVICETYPE = 11016,
1659
1660 /// QoS flowspec error.1580 /// QoS flowspec error.
1661 /// An invalid or inconsistent flowspec was found in the QOS structure.1581 /// An invalid or inconsistent flowspec was found in the QOS structure.
1662 WSA_QOS_EFLOWSPEC = 11017,1582 QOS_EFLOWSPEC = 11017,
1663
1664 /// Invalid QoS provider buffer.1583 /// Invalid QoS provider buffer.
1665 /// An invalid QoS provider-specific buffer.1584 /// An invalid QoS provider-specific buffer.
1666 WSA_QOS_EPROVSPECBUF = 11018,1585 QOS_EPROVSPECBUF = 11018,
1667
1668 /// Invalid QoS filter style.1586 /// Invalid QoS filter style.
1669 /// An invalid QoS filter style was used.1587 /// An invalid QoS filter style was used.
1670 WSA_QOS_EFILTERSTYLE = 11019,1588 QOS_EFILTERSTYLE = 11019,
1671
1672 /// Invalid QoS filter type.1589 /// Invalid QoS filter type.
1673 /// An invalid QoS filter type was used.1590 /// An invalid QoS filter type was used.
1674 WSA_QOS_EFILTERTYPE = 11020,1591 QOS_EFILTERTYPE = 11020,
1675
1676 /// Incorrect QoS filter count.1592 /// Incorrect QoS filter count.
1677 /// An incorrect number of QoS FILTERSPECs were specified in the FLOWDESCRIPTOR.1593 /// An incorrect number of QoS FILTERSPECs were specified in the FLOWDESCRIPTOR.
1678 WSA_QOS_EFILTERCOUNT = 11021,1594 QOS_EFILTERCOUNT = 11021,
1679
1680 /// Invalid QoS object length.1595 /// Invalid QoS object length.
1681 /// An object with an invalid ObjectLength field was specified in the QoS provider-specific buffer.1596 /// An object with an invalid ObjectLength field was specified in the QoS provider-specific buffer.
1682 WSA_QOS_EOBJLENGTH = 11022,1597 QOS_EOBJLENGTH = 11022,
1683
1684 /// Incorrect QoS flow count.1598 /// Incorrect QoS flow count.
1685 /// An incorrect number of flow descriptors was specified in the QoS structure.1599 /// An incorrect number of flow descriptors was specified in the QoS structure.
1686 WSA_QOS_EFLOWCOUNT = 11023,1600 QOS_EFLOWCOUNT = 11023,
1687
1688 /// Unrecognized QoS object.1601 /// Unrecognized QoS object.
1689 /// An unrecognized object was found in the QoS provider-specific buffer.1602 /// An unrecognized object was found in the QoS provider-specific buffer.
1690 WSA_QOS_EUNKOWNPSOBJ = 11024,1603 QOS_EUNKOWNPSOBJ = 11024,
1691
1692 /// Invalid QoS policy object.1604 /// Invalid QoS policy object.
1693 /// An invalid policy object was found in the QoS provider-specific buffer.1605 /// An invalid policy object was found in the QoS provider-specific buffer.
1694 WSA_QOS_EPOLICYOBJ = 11025,1606 QOS_EPOLICYOBJ = 11025,
1695
1696 /// Invalid QoS flow descriptor.1607 /// Invalid QoS flow descriptor.
1697 /// An invalid QoS flow descriptor was found in the flow descriptor list.1608 /// An invalid QoS flow descriptor was found in the flow descriptor list.
1698 WSA_QOS_EFLOWDESC = 11026,1609 QOS_EFLOWDESC = 11026,
1699
1700 /// Invalid QoS provider-specific flowspec.1610 /// Invalid QoS provider-specific flowspec.
1701 /// An invalid or inconsistent flowspec was found in the QoS provider-specific buffer.1611 /// An invalid or inconsistent flowspec was found in the QoS provider-specific buffer.
1702 WSA_QOS_EPSFLOWSPEC = 11027,1612 QOS_EPSFLOWSPEC = 11027,
1703
1704 /// Invalid QoS provider-specific filterspec.1613 /// Invalid QoS provider-specific filterspec.
1705 /// An invalid FILTERSPEC was found in the QoS provider-specific buffer.1614 /// An invalid FILTERSPEC was found in the QoS provider-specific buffer.
1706 WSA_QOS_EPSFILTERSPEC = 11028,1615 QOS_EPSFILTERSPEC = 11028,
1707
1708 /// Invalid QoS shape discard mode object.1616 /// Invalid QoS shape discard mode object.
1709 /// An invalid shape discard mode object was found in the QoS provider-specific buffer.1617 /// An invalid shape discard mode object was found in the QoS provider-specific buffer.
1710 WSA_QOS_ESDMODEOBJ = 11029,1618 QOS_ESDMODEOBJ = 11029,
1711
1712 /// Invalid QoS shaping rate object.1619 /// Invalid QoS shaping rate object.
1713 /// An invalid shaping rate object was found in the QoS provider-specific buffer.1620 /// An invalid shaping rate object was found in the QoS provider-specific buffer.
1714 WSA_QOS_ESHAPERATEOBJ = 11030,1621 QOS_ESHAPERATEOBJ = 11030,
1715
1716 /// Reserved policy QoS element type.1622 /// Reserved policy QoS element type.
1717 /// A reserved policy element was found in the QoS provider-specific buffer.1623 /// A reserved policy element was found in the QoS provider-specific buffer.
1718 WSA_QOS_RESERVED_PETYPE = 11031,1624 QOS_RESERVED_PETYPE = 11031,
1719
1720 _,1625 _,
1721};1626};
17221627
lib/std/posix.zig+111-229
...@@ -3290,33 +3290,6 @@ pub const SocketError = error{...@@ -3290,33 +3290,6 @@ pub const SocketError = error{
3290} || UnexpectedError;3290} || UnexpectedError;
32913291
3292pub fn socket(domain: u32, socket_type: u32, protocol: u32) SocketError!socket_t {3292pub 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
3320 const have_sock_flags = !builtin.target.os.tag.isDarwin() and native_os != .haiku;3293 const have_sock_flags = !builtin.target.os.tag.isDarwin() and native_os != .haiku;
3321 const filtered_sock_type = if (!have_sock_flags)3294 const filtered_sock_type = if (!have_sock_flags)
3322 socket_type & ~@as(u32, SOCK.NONBLOCK | SOCK.CLOEXEC)3295 socket_type & ~@as(u32, SOCK.NONBLOCK | SOCK.CLOEXEC)
...@@ -3411,14 +3384,14 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {...@@ -3411,14 +3384,14 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {
3411 .both => windows.ws2_32.SD_BOTH,3384 .both => windows.ws2_32.SD_BOTH,
3412 });3385 });
3413 if (0 != result) switch (windows.ws2_32.WSAGetLastError()) {3386 if (0 != result) switch (windows.ws2_32.WSAGetLastError()) {
3414 .WSAECONNABORTED => return error.ConnectionAborted,3387 .ECONNABORTED => return error.ConnectionAborted,
3415 .WSAECONNRESET => return error.ConnectionResetByPeer,3388 .ECONNRESET => return error.ConnectionResetByPeer,
3416 .WSAEINPROGRESS => return error.BlockingOperationInProgress,3389 .EINPROGRESS => return error.BlockingOperationInProgress,
3417 .WSAEINVAL => unreachable,3390 .EINVAL => unreachable,
3418 .WSAENETDOWN => return error.NetworkDown,3391 .ENETDOWN => return error.NetworkDown,
3419 .WSAENOTCONN => return error.SocketUnconnected,3392 .ENOTCONN => return error.SocketUnconnected,
3420 .WSAENOTSOCK => unreachable,3393 .ENOTSOCK => unreachable,
3421 .WSANOTINITIALISED => unreachable,3394 .NOTINITIALISED => unreachable,
3422 else => |err| return windows.unexpectedWSAError(err),3395 else => |err| return windows.unexpectedWSAError(err),
3423 };3396 };
3424 } else {3397 } else {
...@@ -3440,70 +3413,17 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {...@@ -3440,70 +3413,17 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {
3440}3413}
34413414
3442pub const BindError = error{3415pub 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.
3462 SymLinkLoop,3416 SymLinkLoop,
3463
3464 /// addr is too long.
3465 NameTooLong,3417 NameTooLong,
3466
3467 /// A component in the directory prefix of the socket pathname does not exist.
3468 FileNotFound,3418 FileNotFound,
3469
3470 /// Insufficient kernel memory was available.
3471 SystemResources,
3472
3473 /// A component of the path prefix is not a directory.
3474 NotDir,3419 NotDir,
3475
3476 /// The socket inode would reside on a read-only filesystem.
3477 ReadOnlyFileSystem,3420 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
3488pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!void {3424pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!void {
3489 if (native_os == .windows) {3425 if (native_os == .windows) {
3490 const rc = windows.bind(sock, addr, len);3426 @compileError("use std.Io instead");
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;
3507 } else {3427 } else {
3508 const rc = system.bind(sock, addr, len);3428 const rc = system.bind(sock, addr, len);
3509 switch (errno(rc)) {3429 switch (errno(rc)) {
...@@ -3514,7 +3434,7 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi...@@ -3514,7 +3434,7 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi
3514 .INVAL => unreachable, // invalid parameters3434 .INVAL => unreachable, // invalid parameters
3515 .NOTSOCK => unreachable, // invalid `sockfd`3435 .NOTSOCK => unreachable, // invalid `sockfd`
3516 .AFNOSUPPORT => return error.AddressFamilyUnsupported,3436 .AFNOSUPPORT => return error.AddressFamilyUnsupported,
3517 .ADDRNOTAVAIL => return error.AddressNotAvailable,3437 .ADDRNOTAVAIL => return error.AddressUnavailable,
3518 .FAULT => unreachable, // invalid `addr` pointer3438 .FAULT => unreachable, // invalid `addr` pointer
3519 .LOOP => return error.SymLinkLoop,3439 .LOOP => return error.SymLinkLoop,
3520 .NAMETOOLONG => return error.NameTooLong,3440 .NAMETOOLONG => return error.NameTooLong,
...@@ -3529,51 +3449,13 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi...@@ -3529,51 +3449,13 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi
3529}3449}
35303450
3531pub const ListenError = error{3451pub 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.
3540 FileDescriptorNotASocket,3452 FileDescriptorNotASocket,
3541
3542 /// The socket is not of a type that supports the listen() operation.
3543 OperationNotSupported,3453 OperationNotSupported,
35443454} || std.Io.net.IpAddress.ListenError || std.Io.net.UnixAddress.ListenError;
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;
35583455
3559pub fn listen(sock: socket_t, backlog: u31) ListenError!void {3456pub fn listen(sock: socket_t, backlog: u31) ListenError!void {
3560 if (native_os == .windows) {3457 if (native_os == .windows) {
3561 const rc = windows.listen(sock, backlog);3458 @compileError("use std.Io instead");
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;
3577 } else {3459 } else {
3578 const rc = system.listen(sock, backlog);3460 const rc = system.listen(sock, backlog);
3579 switch (errno(rc)) {3461 switch (errno(rc)) {
...@@ -3630,16 +3512,16 @@ pub fn accept(...@@ -3630,16 +3512,16 @@ pub fn accept(
3630 if (native_os == .windows) {3512 if (native_os == .windows) {
3631 if (rc == windows.ws2_32.INVALID_SOCKET) {3513 if (rc == windows.ws2_32.INVALID_SOCKET) {
3632 switch (windows.ws2_32.WSAGetLastError()) {3514 switch (windows.ws2_32.WSAGetLastError()) {
3633 .WSANOTINITIALISED => unreachable, // not initialized WSA3515 .NOTINITIALISED => unreachable, // not initialized WSA
3634 .WSAECONNRESET => return error.ConnectionResetByPeer,3516 .ECONNRESET => return error.ConnectionResetByPeer,
3635 .WSAEFAULT => unreachable,3517 .EFAULT => unreachable,
3636 .WSAENOTSOCK => return error.FileDescriptorNotASocket,3518 .ENOTSOCK => return error.FileDescriptorNotASocket,
3637 .WSAEINVAL => return error.SocketNotListening,3519 .EINVAL => return error.SocketNotListening,
3638 .WSAEMFILE => return error.ProcessFdQuotaExceeded,3520 .EMFILE => return error.ProcessFdQuotaExceeded,
3639 .WSAENETDOWN => return error.NetworkDown,3521 .ENETDOWN => return error.NetworkDown,
3640 .WSAENOBUFS => return error.FileDescriptorNotASocket,3522 .ENOBUFS => return error.FileDescriptorNotASocket,
3641 .WSAEOPNOTSUPP => return error.OperationNotSupported,3523 .EOPNOTSUPP => return error.OperationNotSupported,
3642 .WSAEWOULDBLOCK => return error.WouldBlock,3524 .EWOULDBLOCK => return error.WouldBlock,
3643 else => |err| return windows.unexpectedWSAError(err),3525 else => |err| return windows.unexpectedWSAError(err),
3644 }3526 }
3645 } else {3527 } else {
...@@ -3706,9 +3588,9 @@ fn setSockFlags(sock: socket_t, flags: u32) !void {...@@ -3706,9 +3588,9 @@ fn setSockFlags(sock: socket_t, flags: u32) !void {
3706 var mode: c_ulong = 1;3588 var mode: c_ulong = 1;
3707 if (windows.ws2_32.ioctlsocket(sock, windows.ws2_32.FIONBIO, &mode) == windows.ws2_32.SOCKET_ERROR) {3589 if (windows.ws2_32.ioctlsocket(sock, windows.ws2_32.FIONBIO, &mode) == windows.ws2_32.SOCKET_ERROR) {
3708 switch (windows.ws2_32.WSAGetLastError()) {3590 switch (windows.ws2_32.WSAGetLastError()) {
3709 .WSANOTINITIALISED => unreachable,3591 .NOTINITIALISED => unreachable,
3710 .WSAENETDOWN => return error.NetworkDown,3592 .ENETDOWN => return error.NetworkDown,
3711 .WSAENOTSOCK => return error.FileDescriptorNotASocket,3593 .ENOTSOCK => return error.FileDescriptorNotASocket,
3712 // TODO: handle more errors3594 // TODO: handle more errors
3713 else => |err| return windows.unexpectedWSAError(err),3595 else => |err| return windows.unexpectedWSAError(err),
3714 }3596 }
...@@ -3861,11 +3743,11 @@ pub fn getsockname(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock...@@ -3861,11 +3743,11 @@ pub fn getsockname(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
3861 const rc = windows.getsockname(sock, addr, addrlen);3743 const rc = windows.getsockname(sock, addr, addrlen);
3862 if (rc == windows.ws2_32.SOCKET_ERROR) {3744 if (rc == windows.ws2_32.SOCKET_ERROR) {
3863 switch (windows.ws2_32.WSAGetLastError()) {3745 switch (windows.ws2_32.WSAGetLastError()) {
3864 .WSANOTINITIALISED => unreachable,3746 .NOTINITIALISED => unreachable,
3865 .WSAENETDOWN => return error.NetworkDown,3747 .ENETDOWN => return error.NetworkDown,
3866 .WSAEFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value3748 .EFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
3867 .WSAENOTSOCK => return error.FileDescriptorNotASocket,3749 .ENOTSOCK => return error.FileDescriptorNotASocket,
3868 .WSAEINVAL => return error.SocketNotBound,3750 .EINVAL => return error.SocketNotBound,
3869 else => |err| return windows.unexpectedWSAError(err),3751 else => |err| return windows.unexpectedWSAError(err),
3870 }3752 }
3871 }3753 }
...@@ -3890,11 +3772,11 @@ pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock...@@ -3890,11 +3772,11 @@ pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
3890 const rc = windows.getpeername(sock, addr, addrlen);3772 const rc = windows.getpeername(sock, addr, addrlen);
3891 if (rc == windows.ws2_32.SOCKET_ERROR) {3773 if (rc == windows.ws2_32.SOCKET_ERROR) {
3892 switch (windows.ws2_32.WSAGetLastError()) {3774 switch (windows.ws2_32.WSAGetLastError()) {
3893 .WSANOTINITIALISED => unreachable,3775 .NOTINITIALISED => unreachable,
3894 .WSAENETDOWN => return error.NetworkDown,3776 .ENETDOWN => return error.NetworkDown,
3895 .WSAEFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value3777 .EFAULT => unreachable, // addr or addrlen have invalid pointers or addrlen points to an incorrect value
3896 .WSAENOTSOCK => return error.FileDescriptorNotASocket,3778 .ENOTSOCK => return error.FileDescriptorNotASocket,
3897 .WSAEINVAL => return error.SocketNotBound,3779 .EINVAL => return error.SocketNotBound,
3898 else => |err| return windows.unexpectedWSAError(err),3780 else => |err| return windows.unexpectedWSAError(err),
3899 }3781 }
3900 }3782 }
...@@ -3932,7 +3814,7 @@ pub const ConnectError = error{...@@ -3932,7 +3814,7 @@ pub const ConnectError = error{
3932 /// address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers3814 /// address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers
3933 /// in the ephemeral port range are currently in use. See the discussion of3815 /// in the ephemeral port range are currently in use. See the discussion of
3934 /// /proc/sys/net/ipv4/ip_local_port_range in ip(7).3816 /// /proc/sys/net/ipv4/ip_local_port_range in ip(7).
3935 AddressNotAvailable,3817 AddressUnavailable,
39363818
3937 /// The passed address didn't have the correct address family in its sa_family field.3819 /// The passed address didn't have the correct address family in its sa_family field.
3938 AddressFamilyUnsupported,3820 AddressFamilyUnsupported,
...@@ -3975,22 +3857,22 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne...@@ -3975,22 +3857,22 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne
3975 const rc = windows.ws2_32.connect(sock, sock_addr, @intCast(len));3857 const rc = windows.ws2_32.connect(sock, sock_addr, @intCast(len));
3976 if (rc == 0) return;3858 if (rc == 0) return;
3977 switch (windows.ws2_32.WSAGetLastError()) {3859 switch (windows.ws2_32.WSAGetLastError()) {
3978 .WSAEADDRINUSE => return error.AddressInUse,3860 .EADDRINUSE => return error.AddressInUse,
3979 .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,3861 .EADDRNOTAVAIL => return error.AddressUnavailable,
3980 .WSAECONNREFUSED => return error.ConnectionRefused,3862 .ECONNREFUSED => return error.ConnectionRefused,
3981 .WSAECONNRESET => return error.ConnectionResetByPeer,3863 .ECONNRESET => return error.ConnectionResetByPeer,
3982 .WSAETIMEDOUT => return error.Timeout,3864 .ETIMEDOUT => return error.Timeout,
3983 .WSAEHOSTUNREACH, // TODO: should we return NetworkUnreachable in this case as well?3865 .EHOSTUNREACH, // TODO: should we return NetworkUnreachable in this case as well?
3984 .WSAENETUNREACH,3866 .ENETUNREACH,
3985 => return error.NetworkUnreachable,3867 => return error.NetworkUnreachable,
3986 .WSAEFAULT => unreachable,3868 .EFAULT => unreachable,
3987 .WSAEINVAL => unreachable,3869 .EINVAL => unreachable,
3988 .WSAEISCONN => return error.AlreadyConnected,3870 .EISCONN => return error.AlreadyConnected,
3989 .WSAENOTSOCK => unreachable,3871 .ENOTSOCK => unreachable,
3990 .WSAEWOULDBLOCK => return error.WouldBlock,3872 .EWOULDBLOCK => return error.WouldBlock,
3991 .WSAEACCES => unreachable,3873 .EACCES => unreachable,
3992 .WSAENOBUFS => return error.SystemResources,3874 .ENOBUFS => return error.SystemResources,
3993 .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,3875 .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
3994 else => |err| return windows.unexpectedWSAError(err),3876 else => |err| return windows.unexpectedWSAError(err),
3995 }3877 }
3996 return;3878 return;
...@@ -4002,7 +3884,7 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne...@@ -4002,7 +3884,7 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne
4002 .ACCES => return error.AccessDenied,3884 .ACCES => return error.AccessDenied,
4003 .PERM => return error.PermissionDenied,3885 .PERM => return error.PermissionDenied,
4004 .ADDRINUSE => return error.AddressInUse,3886 .ADDRINUSE => return error.AddressInUse,
4005 .ADDRNOTAVAIL => return error.AddressNotAvailable,3887 .ADDRNOTAVAIL => return error.AddressUnavailable,
4006 .AFNOSUPPORT => return error.AddressFamilyUnsupported,3888 .AFNOSUPPORT => return error.AddressFamilyUnsupported,
4007 .AGAIN, .INPROGRESS => return error.WouldBlock,3889 .AGAIN, .INPROGRESS => return error.WouldBlock,
4008 .ALREADY => return error.ConnectionPending,3890 .ALREADY => return error.ConnectionPending,
...@@ -4064,7 +3946,7 @@ pub fn getsockoptError(sockfd: fd_t) ConnectError!void {...@@ -4064,7 +3946,7 @@ pub fn getsockoptError(sockfd: fd_t) ConnectError!void {
4064 .ACCES => return error.AccessDenied,3946 .ACCES => return error.AccessDenied,
4065 .PERM => return error.PermissionDenied,3947 .PERM => return error.PermissionDenied,
4066 .ADDRINUSE => return error.AddressInUse,3948 .ADDRINUSE => return error.AddressInUse,
4067 .ADDRNOTAVAIL => return error.AddressNotAvailable,3949 .ADDRNOTAVAIL => return error.AddressUnavailable,
4068 .AFNOSUPPORT => return error.AddressFamilyUnsupported,3950 .AFNOSUPPORT => return error.AddressFamilyUnsupported,
4069 .AGAIN => return error.SystemResources,3951 .AGAIN => return error.SystemResources,
4070 .ALREADY => return error.ConnectionPending,3952 .ALREADY => return error.ConnectionPending,
...@@ -5686,7 +5568,7 @@ pub const SendMsgError = SendError || error{...@@ -5686,7 +5568,7 @@ pub const SendMsgError = SendError || error{
56865568
5687 /// The socket is not connected (connection-oriented sockets only).5569 /// The socket is not connected (connection-oriented sockets only).
5688 SocketUnconnected,5570 SocketUnconnected,
5689 AddressNotAvailable,5571 AddressUnavailable,
5690};5572};
56915573
5692pub fn sendmsg(5574pub fn sendmsg(
...@@ -5701,25 +5583,25 @@ pub fn sendmsg(...@@ -5701,25 +5583,25 @@ pub fn sendmsg(
5701 if (native_os == .windows) {5583 if (native_os == .windows) {
5702 if (rc == windows.ws2_32.SOCKET_ERROR) {5584 if (rc == windows.ws2_32.SOCKET_ERROR) {
5703 switch (windows.ws2_32.WSAGetLastError()) {5585 switch (windows.ws2_32.WSAGetLastError()) {
5704 .WSAEACCES => return error.AccessDenied,5586 .EACCES => return error.AccessDenied,
5705 .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,5587 .EADDRNOTAVAIL => return error.AddressUnavailable,
5706 .WSAECONNRESET => return error.ConnectionResetByPeer,5588 .ECONNRESET => return error.ConnectionResetByPeer,
5707 .WSAEMSGSIZE => return error.MessageOversize,5589 .EMSGSIZE => return error.MessageOversize,
5708 .WSAENOBUFS => return error.SystemResources,5590 .ENOBUFS => return error.SystemResources,
5709 .WSAENOTSOCK => return error.FileDescriptorNotASocket,5591 .ENOTSOCK => return error.FileDescriptorNotASocket,
5710 .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,5592 .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
5711 .WSAEDESTADDRREQ => unreachable, // A destination address is required.5593 .EDESTADDRREQ => 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.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.
5713 .WSAEHOSTUNREACH => return error.NetworkUnreachable,5595 .EHOSTUNREACH => return error.NetworkUnreachable,
5714 // TODO: WSAEINPROGRESS, WSAEINTR5596 // TODO: EINPROGRESS, EINTR
5715 .WSAEINVAL => unreachable,5597 .EINVAL => unreachable,
5716 .WSAENETDOWN => return error.NetworkDown,5598 .ENETDOWN => return error.NetworkDown,
5717 .WSAENETRESET => return error.ConnectionResetByPeer,5599 .ENETRESET => return error.ConnectionResetByPeer,
5718 .WSAENETUNREACH => return error.NetworkUnreachable,5600 .ENETUNREACH => return error.NetworkUnreachable,
5719 .WSAENOTCONN => return error.SocketUnconnected,5601 .ENOTCONN => 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.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.
5721 .WSAEWOULDBLOCK => return error.WouldBlock,5603 .EWOULDBLOCK => return error.WouldBlock,
5722 .WSANOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.5604 .NOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
5723 else => |err| return windows.unexpectedWSAError(err),5605 else => |err| return windows.unexpectedWSAError(err),
5724 }5606 }
5725 } else {5607 } else {
...@@ -5804,25 +5686,25 @@ pub fn sendto(...@@ -5804,25 +5686,25 @@ pub fn sendto(
5804 if (native_os == .windows) {5686 if (native_os == .windows) {
5805 switch (windows.sendto(sockfd, buf.ptr, buf.len, flags, dest_addr, addrlen)) {5687 switch (windows.sendto(sockfd, buf.ptr, buf.len, flags, dest_addr, addrlen)) {
5806 windows.ws2_32.SOCKET_ERROR => switch (windows.ws2_32.WSAGetLastError()) {5688 windows.ws2_32.SOCKET_ERROR => switch (windows.ws2_32.WSAGetLastError()) {
5807 .WSAEACCES => return error.AccessDenied,5689 .EACCES => return error.AccessDenied,
5808 .WSAEADDRNOTAVAIL => return error.AddressNotAvailable,5690 .EADDRNOTAVAIL => return error.AddressUnavailable,
5809 .WSAECONNRESET => return error.ConnectionResetByPeer,5691 .ECONNRESET => return error.ConnectionResetByPeer,
5810 .WSAEMSGSIZE => return error.MessageOversize,5692 .EMSGSIZE => return error.MessageOversize,
5811 .WSAENOBUFS => return error.SystemResources,5693 .ENOBUFS => return error.SystemResources,
5812 .WSAENOTSOCK => return error.FileDescriptorNotASocket,5694 .ENOTSOCK => return error.FileDescriptorNotASocket,
5813 .WSAEAFNOSUPPORT => return error.AddressFamilyUnsupported,5695 .EAFNOSUPPORT => return error.AddressFamilyUnsupported,
5814 .WSAEDESTADDRREQ => unreachable, // A destination address is required.5696 .EDESTADDRREQ => 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.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.
5816 .WSAEHOSTUNREACH => return error.NetworkUnreachable,5698 .EHOSTUNREACH => return error.NetworkUnreachable,
5817 // TODO: WSAEINPROGRESS, WSAEINTR5699 // TODO: EINPROGRESS, EINTR
5818 .WSAEINVAL => unreachable,5700 .EINVAL => unreachable,
5819 .WSAENETDOWN => return error.NetworkDown,5701 .ENETDOWN => return error.NetworkDown,
5820 .WSAENETRESET => return error.ConnectionResetByPeer,5702 .ENETRESET => return error.ConnectionResetByPeer,
5821 .WSAENETUNREACH => return error.NetworkUnreachable,5703 .ENETUNREACH => return error.NetworkUnreachable,
5822 .WSAENOTCONN => return error.SocketUnconnected,5704 .ENOTCONN => 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.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.
5824 .WSAEWOULDBLOCK => return error.WouldBlock,5706 .EWOULDBLOCK => return error.WouldBlock,
5825 .WSANOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.5707 .NOTINITIALISED => unreachable, // A successful WSAStartup call must occur before using this function.
5826 else => |err| return windows.unexpectedWSAError(err),5708 else => |err| return windows.unexpectedWSAError(err),
5827 },5709 },
5828 else => |rc| return @intCast(rc),5710 else => |rc| return @intCast(rc),
...@@ -5896,7 +5778,7 @@ pub fn send(...@@ -5896,7 +5778,7 @@ pub fn send(
5896 error.FileNotFound => unreachable,5778 error.FileNotFound => unreachable,
5897 error.NotDir => unreachable,5779 error.NotDir => unreachable,
5898 error.NetworkUnreachable => unreachable,5780 error.NetworkUnreachable => unreachable,
5899 error.AddressNotAvailable => unreachable,5781 error.AddressUnavailable => unreachable,
5900 error.SocketUnconnected => unreachable,5782 error.SocketUnconnected => unreachable,
5901 error.UnreachableAddress => unreachable,5783 error.UnreachableAddress => unreachable,
5902 else => |e| return e,5784 else => |e| return e,
...@@ -6007,9 +5889,9 @@ pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {...@@ -6007,9 +5889,9 @@ pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {
6007 if (native_os == .windows) {5889 if (native_os == .windows) {
6008 switch (windows.poll(fds.ptr, @intCast(fds.len), timeout)) {5890 switch (windows.poll(fds.ptr, @intCast(fds.len), timeout)) {
6009 windows.ws2_32.SOCKET_ERROR => switch (windows.ws2_32.WSAGetLastError()) {5891 windows.ws2_32.SOCKET_ERROR => switch (windows.ws2_32.WSAGetLastError()) {
6010 .WSANOTINITIALISED => unreachable,5892 .NOTINITIALISED => unreachable,
6011 .WSAENETDOWN => return error.NetworkDown,5893 .ENETDOWN => return error.NetworkDown,
6012 .WSAENOBUFS => return error.SystemResources,5894 .ENOBUFS => return error.SystemResources,
6013 // TODO: handle more errors5895 // TODO: handle more errors
6014 else => |err| return windows.unexpectedWSAError(err),5896 else => |err| return windows.unexpectedWSAError(err),
6015 },5897 },
...@@ -6107,14 +5989,14 @@ pub fn recvfrom(...@@ -6107,14 +5989,14 @@ pub fn recvfrom(
6107 if (native_os == .windows) {5989 if (native_os == .windows) {
6108 if (rc == windows.ws2_32.SOCKET_ERROR) {5990 if (rc == windows.ws2_32.SOCKET_ERROR) {
6109 switch (windows.ws2_32.WSAGetLastError()) {5991 switch (windows.ws2_32.WSAGetLastError()) {
6110 .WSANOTINITIALISED => unreachable,5992 .NOTINITIALISED => unreachable,
6111 .WSAECONNRESET => return error.ConnectionResetByPeer,5993 .ECONNRESET => return error.ConnectionResetByPeer,
6112 .WSAEINVAL => return error.SocketNotBound,5994 .EINVAL => return error.SocketNotBound,
6113 .WSAEMSGSIZE => return error.MessageOversize,5995 .EMSGSIZE => return error.MessageOversize,
6114 .WSAENETDOWN => return error.NetworkDown,5996 .ENETDOWN => return error.NetworkDown,
6115 .WSAENOTCONN => return error.SocketUnconnected,5997 .ENOTCONN => return error.SocketUnconnected,
6116 .WSAEWOULDBLOCK => return error.WouldBlock,5998 .EWOULDBLOCK => return error.WouldBlock,
6117 .WSAETIMEDOUT => return error.Timeout,5999 .ETIMEDOUT => return error.Timeout,
6118 // TODO: handle more errors6000 // TODO: handle more errors
6119 else => |err| return windows.unexpectedWSAError(err),6001 else => |err| return windows.unexpectedWSAError(err),
6120 }6002 }
...@@ -6220,11 +6102,11 @@ pub fn setsockopt(fd: socket_t, level: i32, optname: u32, opt: []const u8) SetSo...@@ -6220,11 +6102,11 @@ pub fn setsockopt(fd: socket_t, level: i32, optname: u32, opt: []const u8) SetSo
6220 const rc = windows.ws2_32.setsockopt(fd, level, @intCast(optname), opt.ptr, @intCast(opt.len));6102 const rc = windows.ws2_32.setsockopt(fd, level, @intCast(optname), opt.ptr, @intCast(opt.len));
6221 if (rc == windows.ws2_32.SOCKET_ERROR) {6103 if (rc == windows.ws2_32.SOCKET_ERROR) {
6222 switch (windows.ws2_32.WSAGetLastError()) {6104 switch (windows.ws2_32.WSAGetLastError()) {
6223 .WSANOTINITIALISED => unreachable,6105 .NOTINITIALISED => unreachable,
6224 .WSAENETDOWN => return error.NetworkDown,6106 .ENETDOWN => return error.NetworkDown,
6225 .WSAEFAULT => unreachable,6107 .EFAULT => unreachable,
6226 .WSAENOTSOCK => return error.FileDescriptorNotASocket,6108 .ENOTSOCK => return error.FileDescriptorNotASocket,
6227 .WSAEINVAL => return error.SocketNotBound,6109 .EINVAL => return error.SocketNotBound,
6228 else => |err| return windows.unexpectedWSAError(err),6110 else => |err| return windows.unexpectedWSAError(err),
6229 }6111 }
6230 }6112 }
lib/std/posix/test.zig-19
...@@ -520,25 +520,6 @@ test "getrlimit and setrlimit" {...@@ -520,25 +520,6 @@ test "getrlimit and setrlimit" {
520 }520 }
521}521}
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
542test "sigrtmin/max" {523test "sigrtmin/max" {
543 if (native_os == .wasi or native_os == .windows or native_os == .macos) {524 if (native_os == .wasi or native_os == .windows or native_os == .macos) {
544 return error.SkipZigTest;525 return error.SkipZigTest;