| ... | ... | @@ -11,11 +11,15 @@ const io = std.io; |
| 11 | 11 | const native_endian = builtin.target.cpu.arch.endian(); |
| 12 | 12 | const native_os = builtin.os.tag; |
| 13 | 13 | const windows = std.os.windows; |
| 14 | const Allocator = std.mem.Allocator; |
| 15 | const ArrayList = std.ArrayListUnmanaged; |
| 16 | const File = std.fs.File; |
| 14 | 17 | |
| 15 | 18 | // Windows 10 added support for unix sockets in build 17063, redstone 4 is the |
| 16 | 19 | // first release to support them. |
| 17 | 20 | pub const has_unix_sockets = switch (native_os) { |
| 18 | 21 | .windows => builtin.os.version_range.windows.isAtLeast(.win10_rs4) orelse false, |
| 22 | .wasi => false, |
| 19 | 23 | else => true, |
| 20 | 24 | }; |
| 21 | 25 | |
| ... | ... | @@ -719,7 +723,7 @@ pub fn connectUnixSocket(path: []const u8) !Stream { |
| 719 | 723 | ); |
| 720 | 724 | errdefer Stream.close(.{ .handle = sockfd }); |
| 721 | 725 | |
| 722 | | var addr = try std.net.Address.initUnix(path); |
| 726 | var addr = try Address.initUnix(path); |
| 723 | 727 | try posix.connect(sockfd, &addr.any, addr.getOsSockLen()); |
| 724 | 728 | |
| 725 | 729 | return .{ .handle = sockfd }; |
| ... | ... | @@ -787,7 +791,7 @@ pub const AddressList = struct { |
| 787 | 791 | pub const TcpConnectToHostError = GetAddressListError || TcpConnectToAddressError; |
| 788 | 792 | |
| 789 | 793 | /// All memory allocated with `allocator` will be freed before this function returns. |
| 790 | | pub fn tcpConnectToHost(allocator: mem.Allocator, name: []const u8, port: u16) TcpConnectToHostError!Stream { |
| 794 | pub fn tcpConnectToHost(allocator: Allocator, name: []const u8, port: u16) TcpConnectToHostError!Stream { |
| 791 | 795 | const list = try getAddressList(allocator, name, port); |
| 792 | 796 | defer list.deinit(); |
| 793 | 797 | |
| ... | ... | @@ -818,9 +822,9 @@ pub fn tcpConnectToAddress(address: Address) TcpConnectToAddressError!Stream { |
| 818 | 822 | return Stream{ .handle = sockfd }; |
| 819 | 823 | } |
| 820 | 824 | |
| 821 | | const GetAddressListError = std.mem.Allocator.Error || std.fs.File.OpenError || std.fs.File.ReadError || posix.SocketError || posix.BindError || posix.SetSockOptError || error{ |
| 822 | | // TODO: break this up into error sets from the various underlying functions |
| 823 | | |
| 825 | // TODO: Instead of having a massive error set, make the error set have categories, and then |
| 826 | // store the sub-error as a diagnostic value. |
| 827 | const GetAddressListError = Allocator.Error || File.OpenError || File.ReadError || posix.SocketError || posix.BindError || posix.SetSockOptError || error{ |
| 824 | 828 | TemporaryNameServerFailure, |
| 825 | 829 | NameServerFailure, |
| 826 | 830 | AddressFamilyNotSupported, |
| ... | ... | @@ -840,12 +844,13 @@ const GetAddressListError = std.mem.Allocator.Error || std.fs.File.OpenError || |
| 840 | 844 | |
| 841 | 845 | InterfaceNotFound, |
| 842 | 846 | FileSystem, |
| 847 | ResolveConfParseFailed, |
| 843 | 848 | }; |
| 844 | 849 | |
| 845 | 850 | /// Call `AddressList.deinit` on the result. |
| 846 | | pub fn getAddressList(allocator: mem.Allocator, name: []const u8, port: u16) GetAddressListError!*AddressList { |
| 851 | pub fn getAddressList(gpa: Allocator, name: []const u8, port: u16) GetAddressListError!*AddressList { |
| 847 | 852 | const result = blk: { |
| 848 | | var arena = std.heap.ArenaAllocator.init(allocator); |
| 853 | var arena = std.heap.ArenaAllocator.init(gpa); |
| 849 | 854 | errdefer arena.deinit(); |
| 850 | 855 | |
| 851 | 856 | const result = try arena.allocator().create(AddressList); |
| ... | ... | @@ -860,11 +865,11 @@ pub fn getAddressList(allocator: mem.Allocator, name: []const u8, port: u16) Get |
| 860 | 865 | errdefer result.deinit(); |
| 861 | 866 | |
| 862 | 867 | if (native_os == .windows) { |
| 863 | | const name_c = try allocator.dupeZ(u8, name); |
| 864 | | defer allocator.free(name_c); |
| 868 | const name_c = try gpa.dupeZ(u8, name); |
| 869 | defer gpa.free(name_c); |
| 865 | 870 | |
| 866 | | const port_c = try std.fmt.allocPrintSentinel(allocator, "{}", .{port}, 0); |
| 867 | | defer allocator.free(port_c); |
| 871 | const port_c = try std.fmt.allocPrintSentinel(gpa, "{d}", .{port}, 0); |
| 872 | defer gpa.free(port_c); |
| 868 | 873 | |
| 869 | 874 | const ws2_32 = windows.ws2_32; |
| 870 | 875 | const hints: posix.addrinfo = .{ |
| ... | ... | @@ -932,11 +937,11 @@ pub fn getAddressList(allocator: mem.Allocator, name: []const u8, port: u16) Get |
| 932 | 937 | } |
| 933 | 938 | |
| 934 | 939 | if (builtin.link_libc) { |
| 935 | | const name_c = try allocator.dupeZ(u8, name); |
| 936 | | defer allocator.free(name_c); |
| 940 | const name_c = try gpa.dupeZ(u8, name); |
| 941 | defer gpa.free(name_c); |
| 937 | 942 | |
| 938 | | const port_c = try std.fmt.allocPrintSentinel(allocator, "{}", .{port}, 0); |
| 939 | | defer allocator.free(port_c); |
| 943 | const port_c = try std.fmt.allocPrintSentinel(gpa, "{d}", .{port}, 0); |
| 944 | defer gpa.free(port_c); |
| 940 | 945 | |
| 941 | 946 | const hints: posix.addrinfo = .{ |
| 942 | 947 | .flags = .{ .NUMERICSERV = true }, |
| ... | ... | @@ -999,17 +1004,17 @@ pub fn getAddressList(allocator: mem.Allocator, name: []const u8, port: u16) Get |
| 999 | 1004 | |
| 1000 | 1005 | if (native_os == .linux) { |
| 1001 | 1006 | const family = posix.AF.UNSPEC; |
| 1002 | | var lookup_addrs = std.ArrayList(LookupAddr).init(allocator); |
| 1003 | | defer lookup_addrs.deinit(); |
| 1007 | var lookup_addrs: ArrayList(LookupAddr) = .empty; |
| 1008 | defer lookup_addrs.deinit(gpa); |
| 1004 | 1009 | |
| 1005 | | var canon = std.ArrayList(u8).init(arena); |
| 1006 | | defer canon.deinit(); |
| 1010 | var canon: ArrayList(u8) = .empty; |
| 1011 | defer canon.deinit(gpa); |
| 1007 | 1012 | |
| 1008 | | try linuxLookupName(&lookup_addrs, &canon, name, family, .{ .NUMERICSERV = true }, port); |
| 1013 | try linuxLookupName(gpa, &lookup_addrs, &canon, name, family, .{ .NUMERICSERV = true }, port); |
| 1009 | 1014 | |
| 1010 | 1015 | result.addrs = try arena.alloc(Address, lookup_addrs.items.len); |
| 1011 | 1016 | if (canon.items.len != 0) { |
| 1012 | | result.canon_name = try canon.toOwnedSlice(); |
| 1017 | result.canon_name = try arena.dupe(u8, canon.items); |
| 1013 | 1018 | } |
| 1014 | 1019 | |
| 1015 | 1020 | for (lookup_addrs.items, 0..) |lookup_addr, i| { |
| ... | ... | @@ -1036,8 +1041,9 @@ const DAS_PREFIX_SHIFT = 8; |
| 1036 | 1041 | const DAS_ORDER_SHIFT = 0; |
| 1037 | 1042 | |
| 1038 | 1043 | fn linuxLookupName( |
| 1039 | | addrs: *std.ArrayList(LookupAddr), |
| 1040 | | canon: *std.ArrayList(u8), |
| 1044 | gpa: Allocator, |
| 1045 | addrs: *ArrayList(LookupAddr), |
| 1046 | canon: *ArrayList(u8), |
| 1041 | 1047 | opt_name: ?[]const u8, |
| 1042 | 1048 | family: posix.sa_family_t, |
| 1043 | 1049 | flags: posix.AI, |
| ... | ... | @@ -1046,13 +1052,13 @@ fn linuxLookupName( |
| 1046 | 1052 | if (opt_name) |name| { |
| 1047 | 1053 | // reject empty name and check len so it fits into temp bufs |
| 1048 | 1054 | canon.items.len = 0; |
| 1049 | | try canon.appendSlice(name); |
| 1055 | try canon.appendSlice(gpa, name); |
| 1050 | 1056 | if (Address.parseExpectingFamily(name, family, port)) |addr| { |
| 1051 | | try addrs.append(LookupAddr{ .addr = addr }); |
| 1057 | try addrs.append(gpa, .{ .addr = addr }); |
| 1052 | 1058 | } else |name_err| if (flags.NUMERICHOST) { |
| 1053 | 1059 | return name_err; |
| 1054 | 1060 | } else { |
| 1055 | | try linuxLookupNameFromHosts(addrs, canon, name, family, port); |
| 1061 | try linuxLookupNameFromHosts(gpa, addrs, canon, name, family, port); |
| 1056 | 1062 | if (addrs.items.len == 0) { |
| 1057 | 1063 | // RFC 6761 Section 6.3.3 |
| 1058 | 1064 | // Name resolution APIs and libraries SHOULD recognize localhost |
| ... | ... | @@ -1063,17 +1069,18 @@ fn linuxLookupName( |
| 1063 | 1069 | // Check for equal to "localhost(.)" or ends in ".localhost(.)" |
| 1064 | 1070 | const localhost = if (name[name.len - 1] == '.') "localhost." else "localhost"; |
| 1065 | 1071 | if (mem.endsWith(u8, name, localhost) and (name.len == localhost.len or name[name.len - localhost.len] == '.')) { |
| 1066 | | try addrs.append(LookupAddr{ .addr = .{ .in = Ip4Address.parse("127.0.0.1", port) catch unreachable } }); |
| 1067 | | try addrs.append(LookupAddr{ .addr = .{ .in6 = Ip6Address.parse("::1", port) catch unreachable } }); |
| 1072 | try addrs.append(gpa, .{ .addr = .{ .in = Ip4Address.parse("127.0.0.1", port) catch unreachable } }); |
| 1073 | try addrs.append(gpa, .{ .addr = .{ .in6 = Ip6Address.parse("::1", port) catch unreachable } }); |
| 1068 | 1074 | return; |
| 1069 | 1075 | } |
| 1070 | 1076 | |
| 1071 | | try linuxLookupNameFromDnsSearch(addrs, canon, name, family, port); |
| 1077 | try linuxLookupNameFromDnsSearch(gpa, addrs, canon, name, family, port); |
| 1072 | 1078 | } |
| 1073 | 1079 | } |
| 1074 | 1080 | } else { |
| 1075 | | try canon.resize(0); |
| 1076 | | try linuxLookupNameFromNull(addrs, family, flags, port); |
| 1081 | try canon.resize(gpa, 0); |
| 1082 | try addrs.ensureUnusedCapacity(gpa, 2); |
| 1083 | linuxLookupNameFromNull(addrs, family, flags, port); |
| 1077 | 1084 | } |
| 1078 | 1085 | if (addrs.items.len == 0) return error.UnknownHostName; |
| 1079 | 1086 | |
| ... | ... | @@ -1279,39 +1286,40 @@ fn addrCmpLessThan(context: void, b: LookupAddr, a: LookupAddr) bool { |
| 1279 | 1286 | } |
| 1280 | 1287 | |
| 1281 | 1288 | fn linuxLookupNameFromNull( |
| 1282 | | addrs: *std.ArrayList(LookupAddr), |
| 1289 | addrs: *ArrayList(LookupAddr), |
| 1283 | 1290 | family: posix.sa_family_t, |
| 1284 | 1291 | flags: posix.AI, |
| 1285 | 1292 | port: u16, |
| 1286 | | ) !void { |
| 1293 | ) void { |
| 1287 | 1294 | if (flags.PASSIVE) { |
| 1288 | 1295 | if (family != posix.AF.INET6) { |
| 1289 | | (try addrs.addOne()).* = LookupAddr{ |
| 1296 | addrs.appendAssumeCapacity(.{ |
| 1290 | 1297 | .addr = Address.initIp4([1]u8{0} ** 4, port), |
| 1291 | | }; |
| 1298 | }); |
| 1292 | 1299 | } |
| 1293 | 1300 | if (family != posix.AF.INET) { |
| 1294 | | (try addrs.addOne()).* = LookupAddr{ |
| 1301 | addrs.appendAssumeCapacity(.{ |
| 1295 | 1302 | .addr = Address.initIp6([1]u8{0} ** 16, port, 0, 0), |
| 1296 | | }; |
| 1303 | }); |
| 1297 | 1304 | } |
| 1298 | 1305 | } else { |
| 1299 | 1306 | if (family != posix.AF.INET6) { |
| 1300 | | (try addrs.addOne()).* = LookupAddr{ |
| 1307 | addrs.appendAssumeCapacity(.{ |
| 1301 | 1308 | .addr = Address.initIp4([4]u8{ 127, 0, 0, 1 }, port), |
| 1302 | | }; |
| 1309 | }); |
| 1303 | 1310 | } |
| 1304 | 1311 | if (family != posix.AF.INET) { |
| 1305 | | (try addrs.addOne()).* = LookupAddr{ |
| 1312 | addrs.appendAssumeCapacity(.{ |
| 1306 | 1313 | .addr = Address.initIp6(([1]u8{0} ** 15) ++ [1]u8{1}, port, 0, 0), |
| 1307 | | }; |
| 1314 | }); |
| 1308 | 1315 | } |
| 1309 | 1316 | } |
| 1310 | 1317 | } |
| 1311 | 1318 | |
| 1312 | 1319 | fn linuxLookupNameFromHosts( |
| 1313 | | addrs: *std.ArrayList(LookupAddr), |
| 1314 | | canon: *std.ArrayList(u8), |
| 1320 | gpa: Allocator, |
| 1321 | addrs: *ArrayList(LookupAddr), |
| 1322 | canon: *ArrayList(u8), |
| 1315 | 1323 | name: []const u8, |
| 1316 | 1324 | family: posix.sa_family_t, |
| 1317 | 1325 | port: u16, |
| ... | ... | @@ -1325,18 +1333,36 @@ fn linuxLookupNameFromHosts( |
| 1325 | 1333 | }; |
| 1326 | 1334 | defer file.close(); |
| 1327 | 1335 | |
| 1328 | | var buffered_reader = std.io.bufferedReader(file.deprecatedReader()); |
| 1329 | | const reader = buffered_reader.reader(); |
| 1330 | 1336 | var line_buf: [512]u8 = undefined; |
| 1331 | | while (reader.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) { |
| 1332 | | error.StreamTooLong => blk: { |
| 1333 | | // Skip to the delimiter in the reader, to fix parsing |
| 1334 | | try reader.skipUntilDelimiterOrEof('\n'); |
| 1335 | | // Use the truncated line. A truncated comment or hostname will be handled correctly. |
| 1336 | | break :blk &line_buf; |
| 1337 | | }, |
| 1338 | | else => |e| return e, |
| 1339 | | }) |line| { |
| 1337 | var file_reader = file.reader(&line_buf); |
| 1338 | return parseHosts(gpa, addrs, canon, name, family, port, &file_reader.interface) catch |err| switch (err) { |
| 1339 | error.OutOfMemory => return error.OutOfMemory, |
| 1340 | error.ReadFailed => return file_reader.err.?, |
| 1341 | }; |
| 1342 | } |
| 1343 | |
| 1344 | fn parseHosts( |
| 1345 | gpa: Allocator, |
| 1346 | addrs: *ArrayList(LookupAddr), |
| 1347 | canon: *ArrayList(u8), |
| 1348 | name: []const u8, |
| 1349 | family: posix.sa_family_t, |
| 1350 | port: u16, |
| 1351 | br: *io.Reader, |
| 1352 | ) error{ OutOfMemory, ReadFailed }!void { |
| 1353 | while (true) { |
| 1354 | const line = br.takeDelimiterExclusive('\n') catch |err| switch (err) { |
| 1355 | error.StreamTooLong => { |
| 1356 | // Skip lines that are too long. |
| 1357 | _ = br.discardDelimiterInclusive('\n') catch |e| switch (e) { |
| 1358 | error.EndOfStream => break, |
| 1359 | error.ReadFailed => return error.ReadFailed, |
| 1360 | }; |
| 1361 | continue; |
| 1362 | }, |
| 1363 | error.ReadFailed => return error.ReadFailed, |
| 1364 | error.EndOfStream => break, |
| 1365 | }; |
| 1340 | 1366 | var split_it = mem.splitScalar(u8, line, '#'); |
| 1341 | 1367 | const no_comment_line = split_it.first(); |
| 1342 | 1368 | |
| ... | ... | @@ -1360,17 +1386,36 @@ fn linuxLookupNameFromHosts( |
| 1360 | 1386 | error.NonCanonical, |
| 1361 | 1387 | => continue, |
| 1362 | 1388 | }; |
| 1363 | | try addrs.append(LookupAddr{ .addr = addr }); |
| 1389 | try addrs.append(gpa, .{ .addr = addr }); |
| 1364 | 1390 | |
| 1365 | 1391 | // first name is canonical name |
| 1366 | 1392 | const name_text = first_name_text.?; |
| 1367 | 1393 | if (isValidHostName(name_text)) { |
| 1368 | 1394 | canon.items.len = 0; |
| 1369 | | try canon.appendSlice(name_text); |
| 1395 | try canon.appendSlice(gpa, name_text); |
| 1370 | 1396 | } |
| 1371 | 1397 | } |
| 1372 | 1398 | } |
| 1373 | 1399 | |
| 1400 | test parseHosts { |
| 1401 | if (builtin.os.tag == .wasi) { |
| 1402 | // TODO parsing addresses should not have OS dependencies |
| 1403 | return error.SkipZigTest; |
| 1404 | } |
| 1405 | var reader: std.io.Reader = .fixed( |
| 1406 | \\127.0.0.1 localhost |
| 1407 | \\::1 localhost |
| 1408 | \\127.0.0.2 abcd |
| 1409 | ); |
| 1410 | var addrs: ArrayList(LookupAddr) = .empty; |
| 1411 | defer addrs.deinit(std.testing.allocator); |
| 1412 | var canon: ArrayList(u8) = .empty; |
| 1413 | defer canon.deinit(std.testing.allocator); |
| 1414 | try parseHosts(std.testing.allocator, &addrs, &canon, "abcd", posix.AF.UNSPEC, 1234, &reader); |
| 1415 | try std.testing.expectEqual(1, addrs.items.len); |
| 1416 | try std.testing.expectFmt("127.0.0.2:1234", "{f}", .{addrs.items[0].addr}); |
| 1417 | } |
| 1418 | |
| 1374 | 1419 | pub fn isValidHostName(hostname: []const u8) bool { |
| 1375 | 1420 | if (hostname.len >= 254) return false; |
| 1376 | 1421 | if (!std.unicode.utf8ValidateSlice(hostname)) return false; |
| ... | ... | @@ -1384,14 +1429,15 @@ pub fn isValidHostName(hostname: []const u8) bool { |
| 1384 | 1429 | } |
| 1385 | 1430 | |
| 1386 | 1431 | fn linuxLookupNameFromDnsSearch( |
| 1387 | | addrs: *std.ArrayList(LookupAddr), |
| 1388 | | canon: *std.ArrayList(u8), |
| 1432 | gpa: Allocator, |
| 1433 | addrs: *ArrayList(LookupAddr), |
| 1434 | canon: *ArrayList(u8), |
| 1389 | 1435 | name: []const u8, |
| 1390 | 1436 | family: posix.sa_family_t, |
| 1391 | 1437 | port: u16, |
| 1392 | 1438 | ) !void { |
| 1393 | 1439 | var rc: ResolvConf = undefined; |
| 1394 | | try getResolvConf(addrs.allocator, &rc); |
| 1440 | rc.init(gpa) catch return error.ResolveConfParseFailed; |
| 1395 | 1441 | defer rc.deinit(); |
| 1396 | 1442 | |
| 1397 | 1443 | // Count dots, suppress search when >=ndots or name ends in |
| ... | ... | @@ -1416,37 +1462,40 @@ fn linuxLookupNameFromDnsSearch( |
| 1416 | 1462 | // provides the desired default canonical name (if the requested |
| 1417 | 1463 | // name is not a CNAME record) and serves as a buffer for passing |
| 1418 | 1464 | // the full requested name to name_from_dns. |
| 1419 | | try canon.resize(canon_name.len); |
| 1465 | try canon.resize(gpa, canon_name.len); |
| 1420 | 1466 | @memcpy(canon.items, canon_name); |
| 1421 | | try canon.append('.'); |
| 1467 | try canon.append(gpa, '.'); |
| 1422 | 1468 | |
| 1423 | 1469 | var tok_it = mem.tokenizeAny(u8, search, " \t"); |
| 1424 | 1470 | while (tok_it.next()) |tok| { |
| 1425 | 1471 | canon.shrinkRetainingCapacity(canon_name.len + 1); |
| 1426 | | try canon.appendSlice(tok); |
| 1427 | | try linuxLookupNameFromDns(addrs, canon, canon.items, family, rc, port); |
| 1472 | try canon.appendSlice(gpa, tok); |
| 1473 | try linuxLookupNameFromDns(gpa, addrs, canon, canon.items, family, rc, port); |
| 1428 | 1474 | if (addrs.items.len != 0) return; |
| 1429 | 1475 | } |
| 1430 | 1476 | |
| 1431 | 1477 | canon.shrinkRetainingCapacity(canon_name.len); |
| 1432 | | return linuxLookupNameFromDns(addrs, canon, name, family, rc, port); |
| 1478 | return linuxLookupNameFromDns(gpa, addrs, canon, name, family, rc, port); |
| 1433 | 1479 | } |
| 1434 | 1480 | |
| 1435 | 1481 | const dpc_ctx = struct { |
| 1436 | | addrs: *std.ArrayList(LookupAddr), |
| 1437 | | canon: *std.ArrayList(u8), |
| 1482 | gpa: Allocator, |
| 1483 | addrs: *ArrayList(LookupAddr), |
| 1484 | canon: *ArrayList(u8), |
| 1438 | 1485 | port: u16, |
| 1439 | 1486 | }; |
| 1440 | 1487 | |
| 1441 | 1488 | fn linuxLookupNameFromDns( |
| 1442 | | addrs: *std.ArrayList(LookupAddr), |
| 1443 | | canon: *std.ArrayList(u8), |
| 1489 | gpa: Allocator, |
| 1490 | addrs: *ArrayList(LookupAddr), |
| 1491 | canon: *ArrayList(u8), |
| 1444 | 1492 | name: []const u8, |
| 1445 | 1493 | family: posix.sa_family_t, |
| 1446 | 1494 | rc: ResolvConf, |
| 1447 | 1495 | port: u16, |
| 1448 | 1496 | ) !void { |
| 1449 | | const ctx = dpc_ctx{ |
| 1497 | const ctx: dpc_ctx = .{ |
| 1498 | .gpa = gpa, |
| 1450 | 1499 | .addrs = addrs, |
| 1451 | 1500 | .canon = canon, |
| 1452 | 1501 | .port = port, |
| ... | ... | @@ -1456,8 +1505,8 @@ fn linuxLookupNameFromDns( |
| 1456 | 1505 | rr: u8, |
| 1457 | 1506 | }; |
| 1458 | 1507 | const afrrs = [_]AfRr{ |
| 1459 | | AfRr{ .af = posix.AF.INET6, .rr = posix.RR.A }, |
| 1460 | | AfRr{ .af = posix.AF.INET, .rr = posix.RR.AAAA }, |
| 1508 | .{ .af = posix.AF.INET6, .rr = posix.RR.A }, |
| 1509 | .{ .af = posix.AF.INET, .rr = posix.RR.AAAA }, |
| 1461 | 1510 | }; |
| 1462 | 1511 | var qbuf: [2][280]u8 = undefined; |
| 1463 | 1512 | var abuf: [2][512]u8 = undefined; |
| ... | ... | @@ -1477,7 +1526,7 @@ fn linuxLookupNameFromDns( |
| 1477 | 1526 | ap[0].len = 0; |
| 1478 | 1527 | ap[1].len = 0; |
| 1479 | 1528 | |
| 1480 | | try resMSendRc(qp[0..nq], ap[0..nq], apbuf[0..nq], rc); |
| 1529 | try rc.resMSendRc(qp[0..nq], ap[0..nq], apbuf[0..nq]); |
| 1481 | 1530 | |
| 1482 | 1531 | var i: usize = 0; |
| 1483 | 1532 | while (i < nq) : (i += 1) { |
| ... | ... | @@ -1492,248 +1541,257 @@ fn linuxLookupNameFromDns( |
| 1492 | 1541 | } |
| 1493 | 1542 | |
| 1494 | 1543 | const ResolvConf = struct { |
| 1544 | gpa: Allocator, |
| 1495 | 1545 | attempts: u32, |
| 1496 | 1546 | ndots: u32, |
| 1497 | 1547 | timeout: u32, |
| 1498 | | search: std.ArrayList(u8), |
| 1499 | | ns: std.ArrayList(LookupAddr), |
| 1548 | search: ArrayList(u8), |
| 1549 | /// TODO there are actually only allowed to be maximum 3 nameservers, no need |
| 1550 | /// for an array list. |
| 1551 | ns: ArrayList(LookupAddr), |
| 1552 | |
| 1553 | /// Returns `error.StreamTooLong` if a line is longer than 512 bytes. |
| 1554 | /// TODO: https://github.com/ziglang/zig/issues/2765 and https://github.com/ziglang/zig/issues/2761 |
| 1555 | fn init(rc: *ResolvConf, gpa: Allocator) !void { |
| 1556 | rc.* = .{ |
| 1557 | .gpa = gpa, |
| 1558 | .ns = .empty, |
| 1559 | .search = .empty, |
| 1560 | .ndots = 1, |
| 1561 | .timeout = 5, |
| 1562 | .attempts = 2, |
| 1563 | }; |
| 1564 | errdefer rc.deinit(); |
| 1565 | |
| 1566 | const file = fs.openFileAbsoluteZ("/etc/resolv.conf", .{}) catch |err| switch (err) { |
| 1567 | error.FileNotFound, |
| 1568 | error.NotDir, |
| 1569 | error.AccessDenied, |
| 1570 | => return linuxLookupNameFromNumericUnspec(gpa, &rc.ns, "127.0.0.1", 53), |
| 1571 | else => |e| return e, |
| 1572 | }; |
| 1573 | defer file.close(); |
| 1500 | 1574 | |
| 1501 | | fn deinit(rc: *ResolvConf) void { |
| 1502 | | rc.ns.deinit(); |
| 1503 | | rc.search.deinit(); |
| 1504 | | rc.* = undefined; |
| 1575 | var line_buf: [512]u8 = undefined; |
| 1576 | var file_reader = file.reader(&line_buf); |
| 1577 | return parse(rc, &file_reader.interface) catch |err| switch (err) { |
| 1578 | error.ReadFailed => return file_reader.err.?, |
| 1579 | else => |e| return e, |
| 1580 | }; |
| 1505 | 1581 | } |
| 1506 | | }; |
| 1507 | | |
| 1508 | | /// Ignores lines longer than 512 bytes. |
| 1509 | | /// TODO: https://github.com/ziglang/zig/issues/2765 and https://github.com/ziglang/zig/issues/2761 |
| 1510 | | fn getResolvConf(allocator: mem.Allocator, rc: *ResolvConf) !void { |
| 1511 | | rc.* = ResolvConf{ |
| 1512 | | .ns = std.ArrayList(LookupAddr).init(allocator), |
| 1513 | | .search = std.ArrayList(u8).init(allocator), |
| 1514 | | .ndots = 1, |
| 1515 | | .timeout = 5, |
| 1516 | | .attempts = 2, |
| 1517 | | }; |
| 1518 | | errdefer rc.deinit(); |
| 1519 | 1582 | |
| 1520 | | const file = fs.openFileAbsoluteZ("/etc/resolv.conf", .{}) catch |err| switch (err) { |
| 1521 | | error.FileNotFound, |
| 1522 | | error.NotDir, |
| 1523 | | error.AccessDenied, |
| 1524 | | => return linuxLookupNameFromNumericUnspec(&rc.ns, "127.0.0.1", 53), |
| 1525 | | else => |e| return e, |
| 1526 | | }; |
| 1527 | | defer file.close(); |
| 1583 | const Directive = enum { options, nameserver, domain, search }; |
| 1584 | const Option = enum { ndots, attempts, timeout }; |
| 1528 | 1585 | |
| 1529 | | var buf_reader = std.io.bufferedReader(file.deprecatedReader()); |
| 1530 | | const stream = buf_reader.reader(); |
| 1531 | | var line_buf: [512]u8 = undefined; |
| 1532 | | while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) { |
| 1533 | | error.StreamTooLong => blk: { |
| 1534 | | // Skip to the delimiter in the stream, to fix parsing |
| 1535 | | try stream.skipUntilDelimiterOrEof('\n'); |
| 1536 | | // Give an empty line to the while loop, which will be skipped. |
| 1537 | | break :blk line_buf[0..0]; |
| 1538 | | }, |
| 1539 | | else => |e| return e, |
| 1540 | | }) |line| { |
| 1541 | | const no_comment_line = no_comment_line: { |
| 1542 | | var split = mem.splitScalar(u8, line, '#'); |
| 1543 | | break :no_comment_line split.first(); |
| 1544 | | }; |
| 1545 | | var line_it = mem.tokenizeAny(u8, no_comment_line, " \t"); |
| 1546 | | |
| 1547 | | const token = line_it.next() orelse continue; |
| 1548 | | if (mem.eql(u8, token, "options")) { |
| 1549 | | while (line_it.next()) |sub_tok| { |
| 1550 | | var colon_it = mem.splitScalar(u8, sub_tok, ':'); |
| 1551 | | const name = colon_it.first(); |
| 1552 | | const value_txt = colon_it.next() orelse continue; |
| 1553 | | const value = std.fmt.parseInt(u8, value_txt, 10) catch |err| switch (err) { |
| 1554 | | // TODO https://github.com/ziglang/zig/issues/11812 |
| 1555 | | error.Overflow => @as(u8, 255), |
| 1556 | | error.InvalidCharacter => continue, |
| 1557 | | }; |
| 1558 | | if (mem.eql(u8, name, "ndots")) { |
| 1559 | | rc.ndots = @min(value, 15); |
| 1560 | | } else if (mem.eql(u8, name, "attempts")) { |
| 1561 | | rc.attempts = @min(value, 10); |
| 1562 | | } else if (mem.eql(u8, name, "timeout")) { |
| 1563 | | rc.timeout = @min(value, 60); |
| 1564 | | } |
| 1586 | fn parse(rc: *ResolvConf, reader: *io.Reader) !void { |
| 1587 | const gpa = rc.gpa; |
| 1588 | while (reader.takeSentinel('\n')) |line_with_comment| { |
| 1589 | const line = line: { |
| 1590 | var split = mem.splitScalar(u8, line_with_comment, '#'); |
| 1591 | break :line split.first(); |
| 1592 | }; |
| 1593 | var line_it = mem.tokenizeAny(u8, line, " \t"); |
| 1594 | |
| 1595 | const token = line_it.next() orelse continue; |
| 1596 | switch (std.meta.stringToEnum(Directive, token) orelse continue) { |
| 1597 | .options => while (line_it.next()) |sub_tok| { |
| 1598 | var colon_it = mem.splitScalar(u8, sub_tok, ':'); |
| 1599 | const name = colon_it.first(); |
| 1600 | const value_txt = colon_it.next() orelse continue; |
| 1601 | const value = std.fmt.parseInt(u8, value_txt, 10) catch |err| switch (err) { |
| 1602 | error.Overflow => 255, |
| 1603 | error.InvalidCharacter => continue, |
| 1604 | }; |
| 1605 | switch (std.meta.stringToEnum(Option, name) orelse continue) { |
| 1606 | .ndots => rc.ndots = @min(value, 15), |
| 1607 | .attempts => rc.attempts = @min(value, 10), |
| 1608 | .timeout => rc.timeout = @min(value, 60), |
| 1609 | } |
| 1610 | }, |
| 1611 | .nameserver => { |
| 1612 | const ip_txt = line_it.next() orelse continue; |
| 1613 | try linuxLookupNameFromNumericUnspec(gpa, &rc.ns, ip_txt, 53); |
| 1614 | }, |
| 1615 | .domain, .search => { |
| 1616 | rc.search.items.len = 0; |
| 1617 | try rc.search.appendSlice(gpa, line_it.rest()); |
| 1618 | }, |
| 1565 | 1619 | } |
| 1566 | | } else if (mem.eql(u8, token, "nameserver")) { |
| 1567 | | const ip_txt = line_it.next() orelse continue; |
| 1568 | | try linuxLookupNameFromNumericUnspec(&rc.ns, ip_txt, 53); |
| 1569 | | } else if (mem.eql(u8, token, "domain") or mem.eql(u8, token, "search")) { |
| 1570 | | rc.search.items.len = 0; |
| 1571 | | try rc.search.appendSlice(line_it.rest()); |
| 1620 | } else |err| switch (err) { |
| 1621 | error.EndOfStream => if (reader.bufferedLen() != 0) return error.EndOfStream, |
| 1622 | else => |e| return e, |
| 1572 | 1623 | } |
| 1573 | | } |
| 1574 | 1624 | |
| 1575 | | if (rc.ns.items.len == 0) { |
| 1576 | | return linuxLookupNameFromNumericUnspec(&rc.ns, "127.0.0.1", 53); |
| 1625 | if (rc.ns.items.len == 0) { |
| 1626 | return linuxLookupNameFromNumericUnspec(gpa, &rc.ns, "127.0.0.1", 53); |
| 1627 | } |
| 1577 | 1628 | } |
| 1578 | | } |
| 1579 | 1629 | |
| 1580 | | fn linuxLookupNameFromNumericUnspec( |
| 1581 | | addrs: *std.ArrayList(LookupAddr), |
| 1582 | | name: []const u8, |
| 1583 | | port: u16, |
| 1584 | | ) !void { |
| 1585 | | const addr = try Address.resolveIp(name, port); |
| 1586 | | (try addrs.addOne()).* = LookupAddr{ .addr = addr }; |
| 1587 | | } |
| 1630 | fn resMSendRc( |
| 1631 | rc: ResolvConf, |
| 1632 | queries: []const []const u8, |
| 1633 | answers: [][]u8, |
| 1634 | answer_bufs: []const []u8, |
| 1635 | ) !void { |
| 1636 | const gpa = rc.gpa; |
| 1637 | const timeout = 1000 * rc.timeout; |
| 1638 | const attempts = rc.attempts; |
| 1588 | 1639 | |
| 1589 | | fn resMSendRc( |
| 1590 | | queries: []const []const u8, |
| 1591 | | answers: [][]u8, |
| 1592 | | answer_bufs: []const []u8, |
| 1593 | | rc: ResolvConf, |
| 1594 | | ) !void { |
| 1595 | | const timeout = 1000 * rc.timeout; |
| 1596 | | const attempts = rc.attempts; |
| 1640 | var sl: posix.socklen_t = @sizeOf(posix.sockaddr.in); |
| 1641 | var family: posix.sa_family_t = posix.AF.INET; |
| 1597 | 1642 | |
| 1598 | | var sl: posix.socklen_t = @sizeOf(posix.sockaddr.in); |
| 1599 | | var family: posix.sa_family_t = posix.AF.INET; |
| 1643 | var ns_list: ArrayList(Address) = .empty; |
| 1644 | defer ns_list.deinit(gpa); |
| 1600 | 1645 | |
| 1601 | | var ns_list = std.ArrayList(Address).init(rc.ns.allocator); |
| 1602 | | defer ns_list.deinit(); |
| 1646 | try ns_list.resize(gpa, rc.ns.items.len); |
| 1603 | 1647 | |
| 1604 | | try ns_list.resize(rc.ns.items.len); |
| 1605 | | const ns = ns_list.items; |
| 1606 | | |
| 1607 | | for (rc.ns.items, 0..) |iplit, i| { |
| 1608 | | ns[i] = iplit.addr; |
| 1609 | | assert(ns[i].getPort() == 53); |
| 1610 | | if (iplit.addr.any.family != posix.AF.INET) { |
| 1611 | | family = posix.AF.INET6; |
| 1648 | for (ns_list.items, rc.ns.items) |*ns, iplit| { |
| 1649 | ns.* = iplit.addr; |
| 1650 | assert(ns.getPort() == 53); |
| 1651 | if (iplit.addr.any.family != posix.AF.INET) { |
| 1652 | family = posix.AF.INET6; |
| 1653 | } |
| 1612 | 1654 | } |
| 1613 | | } |
| 1614 | 1655 | |
| 1615 | | const flags = posix.SOCK.DGRAM | posix.SOCK.CLOEXEC | posix.SOCK.NONBLOCK; |
| 1616 | | const fd = posix.socket(family, flags, 0) catch |err| switch (err) { |
| 1617 | | error.AddressFamilyNotSupported => blk: { |
| 1618 | | // Handle case where system lacks IPv6 support |
| 1619 | | if (family == posix.AF.INET6) { |
| 1620 | | family = posix.AF.INET; |
| 1621 | | break :blk try posix.socket(posix.AF.INET, flags, 0); |
| 1656 | const flags = posix.SOCK.DGRAM | posix.SOCK.CLOEXEC | posix.SOCK.NONBLOCK; |
| 1657 | const fd = posix.socket(family, flags, 0) catch |err| switch (err) { |
| 1658 | error.AddressFamilyNotSupported => blk: { |
| 1659 | // Handle case where system lacks IPv6 support |
| 1660 | if (family == posix.AF.INET6) { |
| 1661 | family = posix.AF.INET; |
| 1662 | break :blk try posix.socket(posix.AF.INET, flags, 0); |
| 1663 | } |
| 1664 | return err; |
| 1665 | }, |
| 1666 | else => |e| return e, |
| 1667 | }; |
| 1668 | defer Stream.close(.{ .handle = fd }); |
| 1669 | |
| 1670 | // Past this point, there are no errors. Each individual query will |
| 1671 | // yield either no reply (indicated by zero length) or an answer |
| 1672 | // packet which is up to the caller to interpret. |
| 1673 | |
| 1674 | // Convert any IPv4 addresses in a mixed environment to v4-mapped |
| 1675 | if (family == posix.AF.INET6) { |
| 1676 | try posix.setsockopt( |
| 1677 | fd, |
| 1678 | posix.SOL.IPV6, |
| 1679 | std.os.linux.IPV6.V6ONLY, |
| 1680 | &mem.toBytes(@as(c_int, 0)), |
| 1681 | ); |
| 1682 | for (ns_list.items) |*ns| { |
| 1683 | if (ns.any.family != posix.AF.INET) continue; |
| 1684 | mem.writeInt(u32, ns.in6.sa.addr[12..], ns.in.sa.addr, native_endian); |
| 1685 | ns.in6.sa.addr[0..12].* = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff".*; |
| 1686 | ns.any.family = posix.AF.INET6; |
| 1687 | ns.in6.sa.flowinfo = 0; |
| 1688 | ns.in6.sa.scope_id = 0; |
| 1622 | 1689 | } |
| 1623 | | return err; |
| 1624 | | }, |
| 1625 | | else => |e| return e, |
| 1626 | | }; |
| 1627 | | defer Stream.close(.{ .handle = fd }); |
| 1628 | | |
| 1629 | | // Past this point, there are no errors. Each individual query will |
| 1630 | | // yield either no reply (indicated by zero length) or an answer |
| 1631 | | // packet which is up to the caller to interpret. |
| 1632 | | |
| 1633 | | // Convert any IPv4 addresses in a mixed environment to v4-mapped |
| 1634 | | if (family == posix.AF.INET6) { |
| 1635 | | try posix.setsockopt( |
| 1636 | | fd, |
| 1637 | | posix.SOL.IPV6, |
| 1638 | | std.os.linux.IPV6.V6ONLY, |
| 1639 | | &mem.toBytes(@as(c_int, 0)), |
| 1640 | | ); |
| 1641 | | for (0..ns.len) |i| { |
| 1642 | | if (ns[i].any.family != posix.AF.INET) continue; |
| 1643 | | mem.writeInt(u32, ns[i].in6.sa.addr[12..], ns[i].in.sa.addr, native_endian); |
| 1644 | | ns[i].in6.sa.addr[0..12].* = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff".*; |
| 1645 | | ns[i].any.family = posix.AF.INET6; |
| 1646 | | ns[i].in6.sa.flowinfo = 0; |
| 1647 | | ns[i].in6.sa.scope_id = 0; |
| 1690 | sl = @sizeOf(posix.sockaddr.in6); |
| 1648 | 1691 | } |
| 1649 | | sl = @sizeOf(posix.sockaddr.in6); |
| 1650 | | } |
| 1651 | | |
| 1652 | | // Get local address and open/bind a socket |
| 1653 | | var sa: Address = undefined; |
| 1654 | | @memset(@as([*]u8, @ptrCast(&sa))[0..@sizeOf(Address)], 0); |
| 1655 | | sa.any.family = family; |
| 1656 | | try posix.bind(fd, &sa.any, sl); |
| 1657 | | |
| 1658 | | var pfd = [1]posix.pollfd{posix.pollfd{ |
| 1659 | | .fd = fd, |
| 1660 | | .events = posix.POLL.IN, |
| 1661 | | .revents = undefined, |
| 1662 | | }}; |
| 1663 | | const retry_interval = timeout / attempts; |
| 1664 | | var next: u32 = 0; |
| 1665 | | var t2: u64 = @bitCast(std.time.milliTimestamp()); |
| 1666 | | const t0 = t2; |
| 1667 | | var t1 = t2 - retry_interval; |
| 1668 | | |
| 1669 | | var servfail_retry: usize = undefined; |
| 1670 | | |
| 1671 | | outer: while (t2 - t0 < timeout) : (t2 = @as(u64, @bitCast(std.time.milliTimestamp()))) { |
| 1672 | | if (t2 - t1 >= retry_interval) { |
| 1673 | | // Query all configured nameservers in parallel |
| 1674 | | var i: usize = 0; |
| 1675 | | while (i < queries.len) : (i += 1) { |
| 1676 | | if (answers[i].len == 0) { |
| 1677 | | var j: usize = 0; |
| 1678 | | while (j < ns.len) : (j += 1) { |
| 1679 | | _ = posix.sendto(fd, queries[i], posix.MSG.NOSIGNAL, &ns[j].any, sl) catch undefined; |
| 1692 | |
| 1693 | // Get local address and open/bind a socket |
| 1694 | var sa: Address = undefined; |
| 1695 | @memset(@as([*]u8, @ptrCast(&sa))[0..@sizeOf(Address)], 0); |
| 1696 | sa.any.family = family; |
| 1697 | try posix.bind(fd, &sa.any, sl); |
| 1698 | |
| 1699 | var pfd = [1]posix.pollfd{posix.pollfd{ |
| 1700 | .fd = fd, |
| 1701 | .events = posix.POLL.IN, |
| 1702 | .revents = undefined, |
| 1703 | }}; |
| 1704 | const retry_interval = timeout / attempts; |
| 1705 | var next: u32 = 0; |
| 1706 | var t2: u64 = @bitCast(std.time.milliTimestamp()); |
| 1707 | const t0 = t2; |
| 1708 | var t1 = t2 - retry_interval; |
| 1709 | |
| 1710 | var servfail_retry: usize = undefined; |
| 1711 | |
| 1712 | outer: while (t2 - t0 < timeout) : (t2 = @as(u64, @bitCast(std.time.milliTimestamp()))) { |
| 1713 | if (t2 - t1 >= retry_interval) { |
| 1714 | // Query all configured nameservers in parallel |
| 1715 | var i: usize = 0; |
| 1716 | while (i < queries.len) : (i += 1) { |
| 1717 | if (answers[i].len == 0) { |
| 1718 | for (ns_list.items) |*ns| { |
| 1719 | _ = posix.sendto(fd, queries[i], posix.MSG.NOSIGNAL, &ns.any, sl) catch undefined; |
| 1720 | } |
| 1680 | 1721 | } |
| 1681 | 1722 | } |
| 1723 | t1 = t2; |
| 1724 | servfail_retry = 2 * queries.len; |
| 1682 | 1725 | } |
| 1683 | | t1 = t2; |
| 1684 | | servfail_retry = 2 * queries.len; |
| 1685 | | } |
| 1686 | 1726 | |
| 1687 | | // Wait for a response, or until time to retry |
| 1688 | | const clamped_timeout = @min(@as(u31, std.math.maxInt(u31)), t1 + retry_interval - t2); |
| 1689 | | const nevents = posix.poll(&pfd, clamped_timeout) catch 0; |
| 1690 | | if (nevents == 0) continue; |
| 1727 | // Wait for a response, or until time to retry |
| 1728 | const clamped_timeout = @min(@as(u31, std.math.maxInt(u31)), t1 + retry_interval - t2); |
| 1729 | const nevents = posix.poll(&pfd, clamped_timeout) catch 0; |
| 1730 | if (nevents == 0) continue; |
| 1731 | |
| 1732 | while (true) { |
| 1733 | var sl_copy = sl; |
| 1734 | const rlen = posix.recvfrom(fd, answer_bufs[next], 0, &sa.any, &sl_copy) catch break; |
| 1735 | |
| 1736 | // Ignore non-identifiable packets |
| 1737 | if (rlen < 4) continue; |
| 1738 | |
| 1739 | // Ignore replies from addresses we didn't send to |
| 1740 | const ns = for (ns_list.items) |*ns| { |
| 1741 | if (ns.eql(sa)) break ns; |
| 1742 | } else continue; |
| 1743 | |
| 1744 | // Find which query this answer goes with, if any |
| 1745 | var i: usize = next; |
| 1746 | while (i < queries.len and (answer_bufs[next][0] != queries[i][0] or |
| 1747 | answer_bufs[next][1] != queries[i][1])) : (i += 1) |
| 1748 | {} |
| 1749 | |
| 1750 | if (i == queries.len) continue; |
| 1751 | if (answers[i].len != 0) continue; |
| 1752 | |
| 1753 | // Only accept positive or negative responses; |
| 1754 | // retry immediately on server failure, and ignore |
| 1755 | // all other codes such as refusal. |
| 1756 | switch (answer_bufs[next][3] & 15) { |
| 1757 | 0, 3 => {}, |
| 1758 | 2 => if (servfail_retry != 0) { |
| 1759 | servfail_retry -= 1; |
| 1760 | _ = posix.sendto(fd, queries[i], posix.MSG.NOSIGNAL, &ns.any, sl) catch undefined; |
| 1761 | }, |
| 1762 | else => continue, |
| 1763 | } |
| 1691 | 1764 | |
| 1692 | | while (true) { |
| 1693 | | var sl_copy = sl; |
| 1694 | | const rlen = posix.recvfrom(fd, answer_bufs[next], 0, &sa.any, &sl_copy) catch break; |
| 1695 | | |
| 1696 | | // Ignore non-identifiable packets |
| 1697 | | if (rlen < 4) continue; |
| 1698 | | |
| 1699 | | // Ignore replies from addresses we didn't send to |
| 1700 | | var j: usize = 0; |
| 1701 | | while (j < ns.len and !ns[j].eql(sa)) : (j += 1) {} |
| 1702 | | if (j == ns.len) continue; |
| 1703 | | |
| 1704 | | // Find which query this answer goes with, if any |
| 1705 | | var i: usize = next; |
| 1706 | | while (i < queries.len and (answer_bufs[next][0] != queries[i][0] or |
| 1707 | | answer_bufs[next][1] != queries[i][1])) : (i += 1) |
| 1708 | | {} |
| 1709 | | |
| 1710 | | if (i == queries.len) continue; |
| 1711 | | if (answers[i].len != 0) continue; |
| 1712 | | |
| 1713 | | // Only accept positive or negative responses; |
| 1714 | | // retry immediately on server failure, and ignore |
| 1715 | | // all other codes such as refusal. |
| 1716 | | switch (answer_bufs[next][3] & 15) { |
| 1717 | | 0, 3 => {}, |
| 1718 | | 2 => if (servfail_retry != 0) { |
| 1719 | | servfail_retry -= 1; |
| 1720 | | _ = posix.sendto(fd, queries[i], posix.MSG.NOSIGNAL, &ns[j].any, sl) catch undefined; |
| 1721 | | }, |
| 1722 | | else => continue, |
| 1723 | | } |
| 1765 | // Store answer in the right slot, or update next |
| 1766 | // available temp slot if it's already in place. |
| 1767 | answers[i].len = rlen; |
| 1768 | if (i == next) { |
| 1769 | while (next < queries.len and answers[next].len != 0) : (next += 1) {} |
| 1770 | } else { |
| 1771 | @memcpy(answer_bufs[i][0..rlen], answer_bufs[next][0..rlen]); |
| 1772 | } |
| 1724 | 1773 | |
| 1725 | | // Store answer in the right slot, or update next |
| 1726 | | // available temp slot if it's already in place. |
| 1727 | | answers[i].len = rlen; |
| 1728 | | if (i == next) { |
| 1729 | | while (next < queries.len and answers[next].len != 0) : (next += 1) {} |
| 1730 | | } else { |
| 1731 | | @memcpy(answer_bufs[i][0..rlen], answer_bufs[next][0..rlen]); |
| 1774 | if (next == queries.len) break :outer; |
| 1732 | 1775 | } |
| 1733 | | |
| 1734 | | if (next == queries.len) break :outer; |
| 1735 | 1776 | } |
| 1736 | 1777 | } |
| 1778 | |
| 1779 | fn deinit(rc: *ResolvConf) void { |
| 1780 | const gpa = rc.gpa; |
| 1781 | rc.ns.deinit(gpa); |
| 1782 | rc.search.deinit(gpa); |
| 1783 | rc.* = undefined; |
| 1784 | } |
| 1785 | }; |
| 1786 | |
| 1787 | fn linuxLookupNameFromNumericUnspec( |
| 1788 | gpa: Allocator, |
| 1789 | addrs: *ArrayList(LookupAddr), |
| 1790 | name: []const u8, |
| 1791 | port: u16, |
| 1792 | ) !void { |
| 1793 | const addr = try Address.resolveIp(name, port); |
| 1794 | try addrs.append(gpa, .{ .addr = addr }); |
| 1737 | 1795 | } |
| 1738 | 1796 | |
| 1739 | 1797 | fn dnsParse( |
| ... | ... | @@ -1770,20 +1828,19 @@ fn dnsParse( |
| 1770 | 1828 | } |
| 1771 | 1829 | |
| 1772 | 1830 | fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8) !void { |
| 1831 | const gpa = ctx.gpa; |
| 1773 | 1832 | switch (rr) { |
| 1774 | 1833 | posix.RR.A => { |
| 1775 | 1834 | if (data.len != 4) return error.InvalidDnsARecord; |
| 1776 | | const new_addr = try ctx.addrs.addOne(); |
| 1777 | | new_addr.* = LookupAddr{ |
| 1835 | try ctx.addrs.append(gpa, .{ |
| 1778 | 1836 | .addr = Address.initIp4(data[0..4].*, ctx.port), |
| 1779 | | }; |
| 1837 | }); |
| 1780 | 1838 | }, |
| 1781 | 1839 | posix.RR.AAAA => { |
| 1782 | 1840 | if (data.len != 16) return error.InvalidDnsAAAARecord; |
| 1783 | | const new_addr = try ctx.addrs.addOne(); |
| 1784 | | new_addr.* = LookupAddr{ |
| 1841 | try ctx.addrs.append(gpa, .{ |
| 1785 | 1842 | .addr = Address.initIp6(data[0..16].*, ctx.port, 0, 0), |
| 1786 | | }; |
| 1843 | }); |
| 1787 | 1844 | }, |
| 1788 | 1845 | posix.RR.CNAME => { |
| 1789 | 1846 | var tmp: [256]u8 = undefined; |
| ... | ... | @@ -1792,7 +1849,7 @@ fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8) |
| 1792 | 1849 | const canon_name = mem.sliceTo(&tmp, 0); |
| 1793 | 1850 | if (isValidHostName(canon_name)) { |
| 1794 | 1851 | ctx.canon.items.len = 0; |
| 1795 | | try ctx.canon.appendSlice(canon_name); |
| 1852 | try ctx.canon.appendSlice(gpa, canon_name); |
| 1796 | 1853 | } |
| 1797 | 1854 | }, |
| 1798 | 1855 | else => return, |
| ... | ... | @@ -1802,7 +1859,12 @@ fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8) |
| 1802 | 1859 | pub const Stream = struct { |
| 1803 | 1860 | /// Underlying platform-defined type which may or may not be |
| 1804 | 1861 | /// interchangeable with a file system file descriptor. |
| 1805 | | handle: posix.socket_t, |
| 1862 | handle: Handle, |
| 1863 | |
| 1864 | pub const Handle = switch (native_os) { |
| 1865 | .windows => windows.ws2_32.SOCKET, |
| 1866 | else => posix.fd_t, |
| 1867 | }; |
| 1806 | 1868 | |
| 1807 | 1869 | pub fn close(s: Stream) void { |
| 1808 | 1870 | switch (native_os) { |
| ... | ... | @@ -1811,20 +1873,342 @@ pub const Stream = struct { |
| 1811 | 1873 | } |
| 1812 | 1874 | } |
| 1813 | 1875 | |
| 1814 | | pub const ReadError = posix.ReadError; |
| 1815 | | pub const WriteError = posix.WriteError; |
| 1876 | pub const ReadError = posix.ReadError || error{ |
| 1877 | SocketNotBound, |
| 1878 | MessageTooBig, |
| 1879 | NetworkSubsystemFailed, |
| 1880 | ConnectionResetByPeer, |
| 1881 | SocketNotConnected, |
| 1882 | }; |
| 1883 | |
| 1884 | pub const WriteError = posix.SendMsgError || error{ |
| 1885 | ConnectionResetByPeer, |
| 1886 | SocketNotBound, |
| 1887 | MessageTooBig, |
| 1888 | NetworkSubsystemFailed, |
| 1889 | SystemResources, |
| 1890 | SocketNotConnected, |
| 1891 | Unexpected, |
| 1892 | }; |
| 1893 | |
| 1894 | pub const Reader = switch (native_os) { |
| 1895 | .windows => struct { |
| 1896 | /// Use `interface` for portable code. |
| 1897 | interface_state: io.Reader, |
| 1898 | /// Use `getStream` for portable code. |
| 1899 | net_stream: Stream, |
| 1900 | /// Use `getError` for portable code. |
| 1901 | error_state: ?Error, |
| 1902 | |
| 1903 | pub const Error = ReadError; |
| 1904 | |
| 1905 | pub fn getStream(r: *const Reader) Stream { |
| 1906 | return r.stream; |
| 1907 | } |
| 1908 | |
| 1909 | pub fn getError(r: *const Reader) ?Error { |
| 1910 | return r.error_state; |
| 1911 | } |
| 1912 | |
| 1913 | pub fn interface(r: *Reader) *io.Reader { |
| 1914 | return &r.interface_state; |
| 1915 | } |
| 1916 | |
| 1917 | pub fn init(net_stream: Stream, buffer: []u8) Reader { |
| 1918 | return .{ |
| 1919 | .interface_state = .{ |
| 1920 | .vtable = &.{ .stream = stream }, |
| 1921 | .buffer = buffer, |
| 1922 | .seek = 0, |
| 1923 | .end = 0, |
| 1924 | }, |
| 1925 | .net_stream = net_stream, |
| 1926 | .error_state = null, |
| 1927 | }; |
| 1928 | } |
| 1929 | |
| 1930 | fn stream(io_r: *io.Reader, io_w: *io.Writer, limit: io.Limit) io.Reader.StreamError!usize { |
| 1931 | const r: *Reader = @alignCast(@fieldParentPtr("interface_state", io_r)); |
| 1932 | var iovecs: [max_buffers_len]windows.ws2_32.WSABUF = undefined; |
| 1933 | const bufs = try io_w.writableVectorWsa(&iovecs, limit); |
| 1934 | assert(bufs[0].len != 0); |
| 1935 | const n = streamBufs(r, bufs) catch |err| { |
| 1936 | r.error_state = err; |
| 1937 | return error.ReadFailed; |
| 1938 | }; |
| 1939 | if (n == 0) return error.EndOfStream; |
| 1940 | return n; |
| 1941 | } |
| 1942 | |
| 1943 | fn streamBufs(r: *Reader, bufs: []windows.ws2_32.WSABUF) Error!u32 { |
| 1944 | var n: u32 = undefined; |
| 1945 | var flags: u32 = 0; |
| 1946 | const rc = windows.ws2_32.WSARecvFrom(r.net_stream.handle, bufs.ptr, @intCast(bufs.len), &n, &flags, null, null, null, null); |
| 1947 | if (rc != 0) switch (windows.ws2_32.WSAGetLastError()) { |
| 1948 | .WSAECONNRESET => return error.ConnectionResetByPeer, |
| 1949 | .WSAEFAULT => unreachable, // a pointer is not completely contained in user address space. |
| 1950 | .WSAEINPROGRESS, .WSAEINTR => unreachable, // deprecated and removed in WSA 2.2 |
| 1951 | .WSAEINVAL => return error.SocketNotBound, |
| 1952 | .WSAEMSGSIZE => return error.MessageTooBig, |
| 1953 | .WSAENETDOWN => return error.NetworkSubsystemFailed, |
| 1954 | .WSAENETRESET => return error.ConnectionResetByPeer, |
| 1955 | .WSAENOTCONN => return error.SocketNotConnected, |
| 1956 | .WSAEWOULDBLOCK => return error.WouldBlock, |
| 1957 | .WSANOTINITIALISED => unreachable, // WSAStartup must be called before this function |
| 1958 | .WSA_IO_PENDING => unreachable, // not using overlapped I/O |
| 1959 | .WSA_OPERATION_ABORTED => unreachable, // not using overlapped I/O |
| 1960 | else => |err| return windows.unexpectedWSAError(err), |
| 1961 | }; |
| 1962 | return n; |
| 1963 | } |
| 1964 | }, |
| 1965 | else => struct { |
| 1966 | /// Use `getStream`, `interface`, and `getError` for portable code. |
| 1967 | file_reader: File.Reader, |
| 1968 | |
| 1969 | pub const Error = ReadError; |
| 1970 | |
| 1971 | pub fn interface(r: *Reader) *io.Reader { |
| 1972 | return &r.file_reader.interface; |
| 1973 | } |
| 1974 | |
| 1975 | pub fn init(net_stream: Stream, buffer: []u8) Reader { |
| 1976 | return .{ |
| 1977 | .file_reader = .{ |
| 1978 | .interface = File.Reader.initInterface(buffer), |
| 1979 | .file = .{ .handle = net_stream.handle }, |
| 1980 | .mode = .streaming, |
| 1981 | .seek_err = error.Unseekable, |
| 1982 | }, |
| 1983 | }; |
| 1984 | } |
| 1985 | |
| 1986 | pub fn getStream(r: *const Reader) Stream { |
| 1987 | return .{ .handle = r.file_reader.file.handle }; |
| 1988 | } |
| 1989 | |
| 1990 | pub fn getError(r: *const Reader) ?Error { |
| 1991 | return r.file_reader.err; |
| 1992 | } |
| 1993 | }, |
| 1994 | }; |
| 1995 | |
| 1996 | pub const Writer = switch (native_os) { |
| 1997 | .windows => struct { |
| 1998 | /// This field is present on all systems. |
| 1999 | interface: io.Writer, |
| 2000 | /// Use `getStream` for cross-platform support. |
| 2001 | stream: Stream, |
| 2002 | /// This field is present on all systems. |
| 2003 | err: ?Error = null, |
| 2004 | |
| 2005 | pub const Error = WriteError; |
| 2006 | |
| 2007 | pub fn init(stream: Stream, buffer: []u8) Writer { |
| 2008 | return .{ |
| 2009 | .stream = stream, |
| 2010 | .interface = .{ |
| 2011 | .vtable = &.{ .drain = drain }, |
| 2012 | .buffer = buffer, |
| 2013 | }, |
| 2014 | }; |
| 2015 | } |
| 2016 | |
| 2017 | pub fn getStream(w: *const Writer) Stream { |
| 2018 | return w.stream; |
| 2019 | } |
| 1816 | 2020 | |
| 1817 | | pub const Reader = io.GenericReader(Stream, ReadError, read); |
| 1818 | | pub const Writer = io.GenericWriter(Stream, WriteError, write); |
| 2021 | fn addWsaBuf(v: []windows.ws2_32.WSABUF, i: *u32, bytes: []const u8) void { |
| 2022 | const cap = std.math.maxInt(u32); |
| 2023 | var remaining = bytes; |
| 2024 | while (remaining.len > cap) { |
| 2025 | if (v.len - i.* == 0) return; |
| 2026 | v[i.*] = .{ .buf = @constCast(remaining.ptr), .len = cap }; |
| 2027 | i.* += 1; |
| 2028 | remaining = remaining[cap..]; |
| 2029 | } else { |
| 2030 | @branchHint(.likely); |
| 2031 | if (v.len - i.* == 0) return; |
| 2032 | v[i.*] = .{ .buf = @constCast(remaining.ptr), .len = @intCast(remaining.len) }; |
| 2033 | i.* += 1; |
| 2034 | } |
| 2035 | } |
| 1819 | 2036 | |
| 1820 | | pub fn reader(self: Stream) Reader { |
| 1821 | | return .{ .context = self }; |
| 2037 | fn drain(io_w: *io.Writer, data: []const []const u8, splat: usize) io.Writer.Error!usize { |
| 2038 | const w: *Writer = @alignCast(@fieldParentPtr("interface", io_w)); |
| 2039 | const buffered = io_w.buffered(); |
| 2040 | comptime assert(native_os == .windows); |
| 2041 | var iovecs: [max_buffers_len]windows.ws2_32.WSABUF = undefined; |
| 2042 | var len: u32 = 0; |
| 2043 | addWsaBuf(&iovecs, &len, buffered); |
| 2044 | for (data[0 .. data.len - 1]) |bytes| addWsaBuf(&iovecs, &len, bytes); |
| 2045 | const pattern = data[data.len - 1]; |
| 2046 | if (iovecs.len - len != 0) switch (splat) { |
| 2047 | 0 => {}, |
| 2048 | 1 => addWsaBuf(&iovecs, &len, pattern), |
| 2049 | else => switch (pattern.len) { |
| 2050 | 0 => {}, |
| 2051 | 1 => { |
| 2052 | const splat_buffer_candidate = io_w.buffer[io_w.end..]; |
| 2053 | var backup_buffer: [64]u8 = undefined; |
| 2054 | const splat_buffer = if (splat_buffer_candidate.len >= backup_buffer.len) |
| 2055 | splat_buffer_candidate |
| 2056 | else |
| 2057 | &backup_buffer; |
| 2058 | const memset_len = @min(splat_buffer.len, splat); |
| 2059 | const buf = splat_buffer[0..memset_len]; |
| 2060 | @memset(buf, pattern[0]); |
| 2061 | addWsaBuf(&iovecs, &len, buf); |
| 2062 | var remaining_splat = splat - buf.len; |
| 2063 | while (remaining_splat > splat_buffer.len and len < iovecs.len) { |
| 2064 | addWsaBuf(&iovecs, &len, splat_buffer); |
| 2065 | remaining_splat -= splat_buffer.len; |
| 2066 | } |
| 2067 | addWsaBuf(&iovecs, &len, splat_buffer[0..remaining_splat]); |
| 2068 | }, |
| 2069 | else => for (0..@min(splat, iovecs.len - len)) |_| { |
| 2070 | addWsaBuf(&iovecs, &len, pattern); |
| 2071 | }, |
| 2072 | }, |
| 2073 | }; |
| 2074 | const n = sendBufs(w.stream.handle, iovecs[0..len]) catch |err| { |
| 2075 | w.err = err; |
| 2076 | return error.WriteFailed; |
| 2077 | }; |
| 2078 | return io_w.consume(n); |
| 2079 | } |
| 2080 | |
| 2081 | fn sendBufs(handle: Stream.Handle, bufs: []windows.ws2_32.WSABUF) Error!u32 { |
| 2082 | var n: u32 = undefined; |
| 2083 | const rc = windows.ws2_32.WSASend(handle, bufs.ptr, @intCast(bufs.len), &n, 0, null, null); |
| 2084 | if (rc == windows.ws2_32.SOCKET_ERROR) switch (windows.ws2_32.WSAGetLastError()) { |
| 2085 | .WSAECONNABORTED => return error.ConnectionResetByPeer, |
| 2086 | .WSAECONNRESET => return error.ConnectionResetByPeer, |
| 2087 | .WSAEFAULT => unreachable, // a pointer is not completely contained in user address space. |
| 2088 | .WSAEINPROGRESS, .WSAEINTR => unreachable, // deprecated and removed in WSA 2.2 |
| 2089 | .WSAEINVAL => return error.SocketNotBound, |
| 2090 | .WSAEMSGSIZE => return error.MessageTooBig, |
| 2091 | .WSAENETDOWN => return error.NetworkSubsystemFailed, |
| 2092 | .WSAENETRESET => return error.ConnectionResetByPeer, |
| 2093 | .WSAENOBUFS => return error.SystemResources, |
| 2094 | .WSAENOTCONN => return error.SocketNotConnected, |
| 2095 | .WSAENOTSOCK => unreachable, // not a socket |
| 2096 | .WSAEOPNOTSUPP => unreachable, // only for message-oriented sockets |
| 2097 | .WSAESHUTDOWN => unreachable, // cannot send on a socket after write shutdown |
| 2098 | .WSAEWOULDBLOCK => return error.WouldBlock, |
| 2099 | .WSANOTINITIALISED => unreachable, // WSAStartup must be called before this function |
| 2100 | .WSA_IO_PENDING => unreachable, // not using overlapped I/O |
| 2101 | .WSA_OPERATION_ABORTED => unreachable, // not using overlapped I/O |
| 2102 | else => |err| return windows.unexpectedWSAError(err), |
| 2103 | }; |
| 2104 | return n; |
| 2105 | } |
| 2106 | }, |
| 2107 | else => struct { |
| 2108 | /// This field is present on all systems. |
| 2109 | interface: io.Writer, |
| 2110 | |
| 2111 | err: ?Error = null, |
| 2112 | file_writer: File.Writer, |
| 2113 | |
| 2114 | pub const Error = WriteError; |
| 2115 | |
| 2116 | pub fn init(stream: Stream, buffer: []u8) Writer { |
| 2117 | return .{ |
| 2118 | .interface = .{ |
| 2119 | .vtable = &.{ |
| 2120 | .drain = drain, |
| 2121 | .sendFile = sendFile, |
| 2122 | }, |
| 2123 | .buffer = buffer, |
| 2124 | }, |
| 2125 | .file_writer = .initMode(.{ .handle = stream.handle }, &.{}, .streaming), |
| 2126 | }; |
| 2127 | } |
| 2128 | |
| 2129 | pub fn getStream(w: *const Writer) Stream { |
| 2130 | return .{ .handle = w.file_writer.file.handle }; |
| 2131 | } |
| 2132 | |
| 2133 | fn addBuf(v: []posix.iovec_const, i: *@FieldType(posix.msghdr_const, "iovlen"), bytes: []const u8) void { |
| 2134 | // OS checks ptr addr before length so zero length vectors must be omitted. |
| 2135 | if (bytes.len == 0) return; |
| 2136 | if (v.len - i.* == 0) return; |
| 2137 | v[i.*] = .{ .base = bytes.ptr, .len = bytes.len }; |
| 2138 | i.* += 1; |
| 2139 | } |
| 2140 | |
| 2141 | fn drain(io_w: *io.Writer, data: []const []const u8, splat: usize) io.Writer.Error!usize { |
| 2142 | const w: *Writer = @alignCast(@fieldParentPtr("interface", io_w)); |
| 2143 | const buffered = io_w.buffered(); |
| 2144 | var iovecs: [max_buffers_len]posix.iovec_const = undefined; |
| 2145 | var msg: posix.msghdr_const = .{ |
| 2146 | .name = null, |
| 2147 | .namelen = 0, |
| 2148 | .iov = &iovecs, |
| 2149 | .iovlen = 0, |
| 2150 | .control = null, |
| 2151 | .controllen = 0, |
| 2152 | .flags = 0, |
| 2153 | }; |
| 2154 | addBuf(&iovecs, &msg.iovlen, buffered); |
| 2155 | for (data[0 .. data.len - 1]) |bytes| addBuf(&iovecs, &msg.iovlen, bytes); |
| 2156 | const pattern = data[data.len - 1]; |
| 2157 | if (iovecs.len - msg.iovlen != 0) switch (splat) { |
| 2158 | 0 => {}, |
| 2159 | 1 => addBuf(&iovecs, &msg.iovlen, pattern), |
| 2160 | else => switch (pattern.len) { |
| 2161 | 0 => {}, |
| 2162 | 1 => { |
| 2163 | const splat_buffer_candidate = io_w.buffer[io_w.end..]; |
| 2164 | var backup_buffer: [64]u8 = undefined; |
| 2165 | const splat_buffer = if (splat_buffer_candidate.len >= backup_buffer.len) |
| 2166 | splat_buffer_candidate |
| 2167 | else |
| 2168 | &backup_buffer; |
| 2169 | const memset_len = @min(splat_buffer.len, splat); |
| 2170 | const buf = splat_buffer[0..memset_len]; |
| 2171 | @memset(buf, pattern[0]); |
| 2172 | addBuf(&iovecs, &msg.iovlen, buf); |
| 2173 | var remaining_splat = splat - buf.len; |
| 2174 | while (remaining_splat > splat_buffer.len and iovecs.len - msg.iovlen != 0) { |
| 2175 | assert(buf.len == splat_buffer.len); |
| 2176 | addBuf(&iovecs, &msg.iovlen, splat_buffer); |
| 2177 | remaining_splat -= splat_buffer.len; |
| 2178 | } |
| 2179 | addBuf(&iovecs, &msg.iovlen, splat_buffer[0..remaining_splat]); |
| 2180 | }, |
| 2181 | else => for (0..@min(splat, iovecs.len - msg.iovlen)) |_| { |
| 2182 | addBuf(&iovecs, &msg.iovlen, pattern); |
| 2183 | }, |
| 2184 | }, |
| 2185 | }; |
| 2186 | const flags = posix.MSG.NOSIGNAL; |
| 2187 | return io_w.consume(posix.sendmsg(w.file_writer.file.handle, &msg, flags) catch |err| { |
| 2188 | w.err = err; |
| 2189 | return error.WriteFailed; |
| 2190 | }); |
| 2191 | } |
| 2192 | |
| 2193 | fn sendFile(io_w: *io.Writer, file_reader: *File.Reader, limit: io.Limit) io.Writer.FileError!usize { |
| 2194 | const w: *Writer = @alignCast(@fieldParentPtr("interface", io_w)); |
| 2195 | const n = try w.file_writer.interface.sendFileHeader(io_w.buffered(), file_reader, limit); |
| 2196 | return io_w.consume(n); |
| 2197 | } |
| 2198 | }, |
| 2199 | }; |
| 2200 | |
| 2201 | pub fn reader(stream: Stream, buffer: []u8) Reader { |
| 2202 | return .init(stream, buffer); |
| 1822 | 2203 | } |
| 1823 | 2204 | |
| 1824 | | pub fn writer(self: Stream) Writer { |
| 1825 | | return .{ .context = self }; |
| 2205 | pub fn writer(stream: Stream, buffer: []u8) Writer { |
| 2206 | return .init(stream, buffer); |
| 1826 | 2207 | } |
| 1827 | 2208 | |
| 2209 | const max_buffers_len = 8; |
| 2210 | |
| 2211 | /// Deprecated in favor of `Reader`. |
| 1828 | 2212 | pub fn read(self: Stream, buffer: []u8) ReadError!usize { |
| 1829 | 2213 | if (native_os == .windows) { |
| 1830 | 2214 | return windows.ReadFile(self.handle, buffer, null); |
| ... | ... | @@ -1833,10 +2217,10 @@ pub const Stream = struct { |
| 1833 | 2217 | return posix.read(self.handle, buffer); |
| 1834 | 2218 | } |
| 1835 | 2219 | |
| 2220 | /// Deprecated in favor of `Reader`. |
| 1836 | 2221 | pub fn readv(s: Stream, iovecs: []const posix.iovec) ReadError!usize { |
| 1837 | 2222 | if (native_os == .windows) { |
| 1838 | | // TODO improve this to use ReadFileScatter |
| 1839 | | if (iovecs.len == 0) return @as(usize, 0); |
| 2223 | if (iovecs.len == 0) return 0; |
| 1840 | 2224 | const first = iovecs[0]; |
| 1841 | 2225 | return windows.ReadFile(s.handle, first.base[0..first.len], null); |
| 1842 | 2226 | } |
| ... | ... | @@ -1844,18 +2228,7 @@ pub const Stream = struct { |
| 1844 | 2228 | return posix.readv(s.handle, iovecs); |
| 1845 | 2229 | } |
| 1846 | 2230 | |
| 1847 | | /// Returns the number of bytes read. If the number read is smaller than |
| 1848 | | /// `buffer.len`, it means the stream reached the end. Reaching the end of |
| 1849 | | /// a stream is not an error condition. |
| 1850 | | pub fn readAll(s: Stream, buffer: []u8) ReadError!usize { |
| 1851 | | return readAtLeast(s, buffer, buffer.len); |
| 1852 | | } |
| 1853 | | |
| 1854 | | /// Returns the number of bytes read, calling the underlying read function |
| 1855 | | /// the minimal number of times until the buffer has at least `len` bytes |
| 1856 | | /// filled. If the number read is less than `len` it means the stream |
| 1857 | | /// reached the end. Reaching the end of the stream is not an error |
| 1858 | | /// condition. |
| 2231 | /// Deprecated in favor of `Reader`. |
| 1859 | 2232 | pub fn readAtLeast(s: Stream, buffer: []u8, len: usize) ReadError!usize { |
| 1860 | 2233 | assert(len <= buffer.len); |
| 1861 | 2234 | var index: usize = 0; |
| ... | ... | @@ -1867,17 +2240,13 @@ pub const Stream = struct { |
| 1867 | 2240 | return index; |
| 1868 | 2241 | } |
| 1869 | 2242 | |
| 1870 | | /// TODO in evented I/O mode, this implementation incorrectly uses the event loop's |
| 1871 | | /// file system thread instead of non-blocking. It needs to be reworked to properly |
| 1872 | | /// use non-blocking I/O. |
| 2243 | /// Deprecated in favor of `Writer`. |
| 1873 | 2244 | pub fn write(self: Stream, buffer: []const u8) WriteError!usize { |
| 1874 | | if (native_os == .windows) { |
| 1875 | | return windows.WriteFile(self.handle, buffer, null); |
| 1876 | | } |
| 1877 | | |
| 1878 | | return posix.write(self.handle, buffer); |
| 2245 | var stream_writer = self.writer(&.{}); |
| 2246 | return stream_writer.interface.writeVec(&.{buffer}) catch return stream_writer.err.?; |
| 1879 | 2247 | } |
| 1880 | 2248 | |
| 2249 | /// Deprecated in favor of `Writer`. |
| 1881 | 2250 | pub fn writeAll(self: Stream, bytes: []const u8) WriteError!void { |
| 1882 | 2251 | var index: usize = 0; |
| 1883 | 2252 | while (index < bytes.len) { |
| ... | ... | @@ -1885,16 +2254,12 @@ pub const Stream = struct { |
| 1885 | 2254 | } |
| 1886 | 2255 | } |
| 1887 | 2256 | |
| 1888 | | /// See https://github.com/ziglang/zig/issues/7699 |
| 1889 | | /// See equivalent function: `std.fs.File.writev`. |
| 2257 | /// Deprecated in favor of `Writer`. |
| 1890 | 2258 | pub fn writev(self: Stream, iovecs: []const posix.iovec_const) WriteError!usize { |
| 1891 | | return posix.writev(self.handle, iovecs); |
| 2259 | return @errorCast(posix.writev(self.handle, iovecs)); |
| 1892 | 2260 | } |
| 1893 | 2261 | |
| 1894 | | /// The `iovecs` parameter is mutable because this function needs to mutate the fields in |
| 1895 | | /// order to handle partial writes from the underlying OS layer. |
| 1896 | | /// See https://github.com/ziglang/zig/issues/7699 |
| 1897 | | /// See equivalent function: `std.fs.File.writevAll`. |
| 2262 | /// Deprecated in favor of `Writer`. |
| 1898 | 2263 | pub fn writevAll(self: Stream, iovecs: []posix.iovec_const) WriteError!void { |
| 1899 | 2264 | if (iovecs.len == 0) return; |
| 1900 | 2265 | |
| ... | ... | @@ -1914,10 +2279,10 @@ pub const Stream = struct { |
| 1914 | 2279 | |
| 1915 | 2280 | pub const Server = struct { |
| 1916 | 2281 | listen_address: Address, |
| 1917 | | stream: std.net.Stream, |
| 2282 | stream: Stream, |
| 1918 | 2283 | |
| 1919 | 2284 | pub const Connection = struct { |
| 1920 | | stream: std.net.Stream, |
| 2285 | stream: Stream, |
| 1921 | 2286 | address: Address, |
| 1922 | 2287 | }; |
| 1923 | 2288 | |