Repository navigation
Expand file tree
/
Copy pathnet.zig
More file actions
1842 lines (1635 loc) · 62.3 KB
/
Copy pathnet.zig
File metadata and controls
1842 lines (1635 loc) · 62.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const net = @This();
const mem = std.mem;
const os = std.os;
const fs = std.fs;
const io = std.io;
const native_endian = builtin.target.cpu.arch.endian();
// Windows 10 added support for unix sockets in build 17063, redstone 4 is the
// first release to support them.
pub const has_unix_sockets = @hasDecl(os.sockaddr, "un") and
(builtin.target.os.tag != .windows or
builtin.os.version_range.windows.isAtLeast(.win10_rs4) orelse false);
pub const Address = extern union {
any: os.sockaddr,
in: Ip4Address,
in6: Ip6Address,
un: if (has_unix_sockets) os.sockaddr.un else void,
/// Parse the given IP address string into an Address value.
/// It is recommended to use `resolveIp` instead, to handle
/// IPv6 link-local unix addresses.
pub fn parseIp(name: []const u8, port: u16) !Address {
if (parseIp4(name, port)) |ip4| return ip4 else |err| switch (err) {
error.Overflow,
error.InvalidEnd,
error.InvalidCharacter,
error.Incomplete,
error.NonCanonical,
=> {},
}
if (parseIp6(name, port)) |ip6| return ip6 else |err| switch (err) {
error.Overflow,
error.InvalidEnd,
error.InvalidCharacter,
error.Incomplete,
error.InvalidIpv4Mapping,
=> {},
}
return error.InvalidIPAddressFormat;
}
pub fn resolveIp(name: []const u8, port: u16) !Address {
if (parseIp4(name, port)) |ip4| return ip4 else |err| switch (err) {
error.Overflow,
error.InvalidEnd,
error.InvalidCharacter,
error.Incomplete,
error.NonCanonical,
=> {},
}
if (resolveIp6(name, port)) |ip6| return ip6 else |err| switch (err) {
error.Overflow,
error.InvalidEnd,
error.InvalidCharacter,
error.Incomplete,
error.InvalidIpv4Mapping,
=> {},
else => return err,
}
return error.InvalidIPAddressFormat;
}
pub fn parseExpectingFamily(name: []const u8, family: os.sa_family_t, port: u16) !Address {
switch (family) {
os.AF.INET => return parseIp4(name, port),
os.AF.INET6 => return parseIp6(name, port),
os.AF.UNSPEC => return parseIp(name, port),
else => unreachable,
}
}
pub fn parseIp6(buf: []const u8, port: u16) !Address {
return Address{ .in6 = try Ip6Address.parse(buf, port) };
}
pub fn resolveIp6(buf: []const u8, port: u16) !Address {
return Address{ .in6 = try Ip6Address.resolve(buf, port) };
}
pub fn parseIp4(buf: []const u8, port: u16) !Address {
return Address{ .in = try Ip4Address.parse(buf, port) };
}
pub fn initIp4(addr: [4]u8, port: u16) Address {
return Address{ .in = Ip4Address.init(addr, port) };
}
pub
8000
fn initIp6(addr: [16]u8, port: u16, flowinfo: u32, scope_id: u32) Address {
return Address{ .in6 = Ip6Address.init(addr, port, flowinfo, scope_id) };
}
pub fn initUnix(path: []const u8) !Address {
var sock_addr = os.sockaddr.un{
.family = os.AF.UNIX,
.path = undefined,
};
// this enables us to have the proper length of the socket in getOsSockLen
mem.set(u8, &sock_addr.path, 0);
if (path.len > sock_addr.path.len) return error.NameTooLong;
mem.copy(u8, &sock_addr.path, path);
return Address{ .un = sock_addr };
}
/// Returns the port in native endian.
/// Asserts that the address is ip4 or ip6.
pub fn getPort(self: Address) u16 {
return switch (self.any.family) {
os.AF.INET => self.in.getPort(),
os.AF.INET6 => self.in6.getPort(),
else => unreachable,
};
}
/// `port` is native-endian.
/// Asserts that the address is ip4 or ip6.
pub fn setPort(self: *Address, port: u16) void {
switch (self.any.family) {
os.AF.INET => self.in.setPort(port),
os.AF.INET6 => self.in6.setPort(port),
else => unreachable,
}
}
/// Asserts that `addr` is an IP address.
/// This function will read past the end of the pointer, with a size depending
/// on the address family.
pub fn initPosix(addr: *align(4) const os.sockaddr) Address {
switch (addr.family) {
os.AF.INET => return Address{ .in = Ip4Address{ .sa = @ptrCast(*const os.sockaddr.in, addr).* } },
os.AF.INET6 => return Address{ .in6 = Ip6Address{ .sa = @ptrCast(*const os.sockaddr.in6, addr).* } },
else => unreachable,
}
}
pub fn format(
self: Address,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: anytype,
) !void {
switch (self.any.family) {
os.AF.INET => try self.in.format(fmt, options, out_stream),
os.AF.INET6 => try self.in6.format(fmt, options, out_stream),
os.AF.UNIX => {
if (!has_unix_sockets) {
unreachable;
}
try std.fmt.format(out_stream, "{s}", .{std.mem.sliceTo(&self.un.path, 0)});
},
else => unreachable,
}
}
pub fn eql(a: Address, b: Address) bool {
const a_bytes = @ptrCast([*]const u8, &a.any)[0..a.getOsSockLen()];
const b_bytes = @ptrCast([*]const u8, &b.any)[0..b.getOsSockLen()];
return mem.eql(u8, a_bytes, b_bytes);
}
pub fn getOsSockLen(self: Address) os.socklen_t {
switch (self.any.family) {
os.AF.INET => return self.in.getOsSockLen(),
os.AF.INET6 => return self.in6.getOsSockLen(),
os.AF.UNIX => {
if (!has_unix_sockets) {
unreachable;
}
const path_len = std.mem.len(std.meta.assumeSentinel(&self.un.path, 0));
return @intCast(os.socklen_t, @sizeOf(os.sockaddr.un) - self.un.path.len + path_len);
},
else => unreachable,
}
}
};
pub const Ip4Address = extern struct {
sa: os.sockaddr.in,
pub fn parse(buf: []const u8, port: u16) !Ip4Address {
var result = Ip4Address{
.sa = .{
.port = mem.nativeToBig(u16, port),
.addr = undefined,
},
};
const out_ptr = mem.asBytes(&result.sa.addr);
var x: u8 = 0;
var index: u8 = 0;
var saw_any_digits = false;
var has_zero_prefix = false;
for (buf) |c| {
if (c == '.') {
if (!saw_any_digits) {
return error.InvalidCharacter;
}
if (index == 3) {
return error.InvalidEnd;
}
out_ptr[index] = x;
index += 1;
x = 0;
saw_any_digits = false;
has_zero_prefix = false;
} else if (c >= '0' and c <= '9') {
if (c == '0' and !saw_any_digits) {
has_zero_prefix = true;
} else if (has_zero_prefix) {
return error.NonCanonical;
}
saw_any_digits = true;
x = try std.math.mul(u8, x, 10);
x = try std.math.add(u8, x, c - '0');
} else {
return error.InvalidCharacter;
}
}
if (index == 3 and saw_any_digits) {
out_ptr[index] = x;
return result;
}
return error.Incomplete;
}
pub fn resolveIp(name: []const u8, port: u16) !Ip4Address {
if (parse(name, port)) |ip4| return ip4 else |err| switch (err) {
error.Overflow,
error.InvalidEnd,
error.InvalidCharacter,
error.Incomplete,
=> {},
}
return error.InvalidIPAddressFormat;
}
pub fn init(addr: [4]u8, port: u16) Ip4Address {
return Ip4Address{
.sa = os.sockaddr.in{
.port = mem.nativeToBig(u16, port),
.addr = @ptrCast(*align(1) const u32, &addr).*,
},
};
}
/// Returns the port in native endian.
/// Asserts that the address is ip4 or ip6.
pub fn getPort(self: Ip4Address) u16 {
return mem.bigToNative(u16, self.sa.port);
}
/// `port` is native-endian.
/// Asserts that the address is ip4 or ip6.
pub fn setPort(self: *Ip4Address, port: u16) void {
self.sa.port = mem.nativeToBig(u16, port);
}
pub fn format(
self: Ip4Address,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: anytype,
) !void {
_ = fmt;
_ = options;
const bytes = @ptrCast(*const [4]u8, &self.sa.addr);
try std.fmt.format(out_stream, "{}.{}.{}.{}:{}", .{
bytes[0],
bytes[1],
bytes[2],
bytes[3],
self.getPort(),
});
}
pub fn getOsSockLen(self: Ip4Address) os.socklen_t {
_ = self;
return @sizeOf(os.sockaddr.in);
}
};
pub const Ip6Address = extern struct {
sa: os.sockaddr.in6,
/// Parse a given IPv6 address string into an Address.
/// Assumes the Scope ID of the address is fully numeric.
/// For non-numeric addresses, see `resolveIp6`.
pub fn parse(buf: []const u8, port: u16) !Ip6Address {
var result = Ip6Address{
.sa = os.sockaddr.in6{
.scope_id = 0,
.port = mem.nativeToBig(u16, port),
.flowinfo = 0,
.addr = undefined,
},
};
var ip_slice = result.sa.addr[0..];
var tail: [16]u8 = undefined;
var x: u16 = 0;
var saw_any_digits = false;
var index: u8 = 0;
var scope_id = false;
var abbrv = false;
for (buf) |c, i| {
if (scope_id) {
if (c >= '0' and c <= '9') {
const digit = c - '0';
if (@mulWithOverflow(u32, result.sa.scope_id, 10, &result.sa.scope_id)) {
return error.Overflow;
}
if (@addWithOverflow(u32, result.sa.scope_id, digit, &result.sa.scope_id)) {
return error.Overflow;
}
} else {
return error.InvalidCharacter;
}
} else if (c == ':') {
if (!saw_any_digits) {
if (abbrv) return error.InvalidCharacter; // ':::'
if (i != 0) abbrv = true;
mem.set(u8, ip_slice[index..], 0);
ip_slice = tail[0..];
index = 0;
continue;
}
if (index == 14) {
return error.InvalidEnd;
}
ip_slice[index] = @truncate(u8, x >> 8);
index += 1;
ip_slice[index] = @truncate(u8, x);
index += 1;
x = 0;
saw_any_digits = false;
} else if (c == '%') {
if (!saw_any_digits) {
return error.InvalidCharacter;
}
scope_id = true;
saw_any_digits = false;
} else if (c == '.') {
if (!abbrv or ip_slice[0] != 0xff or ip_slice[1] != 0xff) {
// must start with '::ffff:'
return error.InvalidIpv4Mapping;
}
const start_index = mem.lastIndexOfScalar(u8, buf[0..i], ':').? + 1;
const addr = (Ip4Address.parse(buf[start_index..], 0) c
10000
atch {
return error.InvalidIpv4Mapping;
}).sa.addr;
ip_slice = result.sa.addr[0..];
ip_slice[10] = 0xff;
ip_slice[11] = 0xff;
const ptr = mem.sliceAsBytes(@as(*const [1]u32, &addr)[0..]);
ip_slice[12] = ptr[0];
ip_slice[13] = ptr[1];
ip_slice[14] = ptr[2];
ip_slice[15] = ptr[3];
return result;
} else {
const digit = try std.fmt.charToDigit(c, 16);
if (@mulWithOverflow(u16, x, 16, &x)) {
return error.Overflow;
}
if (@addWithOverflow(u16, x, digit, &x)) {
return error.Overflow;
}
saw_any_digits = true;
}
}
if (!saw_any_digits and !abbrv) {
return error.Incomplete;
}
if (index == 14) {
ip_slice[14] = @truncate(u8, x >> 8);
ip_slice[15] = @truncate(u8, x);
return result;
} else {
ip_slice[index] = @truncate(u8, x >> 8);
index += 1;
ip_slice[index] = @truncate(u8, x);
index += 1;
mem.copy(u8, result.sa.addr[16 - index ..], ip_slice[0..index]);
return result;
}
}
pub fn resolve(buf: []const u8, port: u16) !Ip6Address {
// TODO: Unify the implementations of resolveIp6 and parseIp6.
var result = Ip6Address{
.sa = os.sockaddr.in6{
.scope_id = 0,
.port = mem.nativeToBig(u16, port),
.flowinfo = 0,
.addr = undefined,
},
};
var ip_slice = result.sa.addr[0..];
var tail: [16]u8 = undefined;
var x: u16 = 0;
var saw_any_digits = false;
var index: u8 = 0;
var abbrv = false;
var scope_id = false;
var scope_id_value: [os.IFNAMESIZE - 1]u8 = undefined;
var scope_id_index: usize = 0;
for (buf) |c, i| {
if (scope_id) {
// Handling of percent-encoding should be for an URI library.
if ((c >= '0' and c <= '9') or
(c >= 'A' and c <= 'Z') or
(c >= 'a' and c <= 'z') or
(c == '-') or (c == '.') or (c == '_') or (c == '~'))
{
if (scope_id_index >= scope_id_value.len) {
return error.Overflow;
}
scope_id_value[scope_id_index] = c;
scope_id_index += 1;
} else {
return error.InvalidCharacter;
}
} else if (c == ':') {
if (!saw_any_digits) {
if (abbrv) return error.InvalidCharacter; // ':::'
if (i != 0) abbrv = true;
mem.set(u8, ip_slice[index..], 0);
ip_slice = tail[0..];
index = 0;
continue;
}
if (index == 14) {
return error.InvalidEnd;
}
ip_slice[index] = @truncate(u8, x >> 8);
index += 1;
ip_slice[index] = @truncate(u8, x);
index += 1;
x = 0;
saw_any_digits = false;
} else if (c == '%') {
if (!saw_any_digits) {
return error.InvalidCharacter;
}
scope_id = true;
saw_any_digits = false;
} else if (c == '.') {
if (!abbrv or ip_slice[0] != 0xff or ip_slice[1] != 0xff) {
// must start with '::ffff:'
return error.InvalidIpv4Mapping;
}
const start_index = mem.lastIndexOfScalar(u8, buf[0..i], ':').? + 1;
const addr = (Ip4Address.parse(buf[start_index..], 0) catch {
return error.InvalidIpv4Mapping;
}).sa.addr;
ip_slice = result.sa.addr[0..];
ip_slice[10] = 0xff;
ip_slice[11] = 0xff;
const ptr = mem.sliceAsBytes(@as(*const [1]u32, &addr)[0..]);
ip_slice[12] = ptr[0];
ip_slice[13] = ptr[1];
ip_slice[14] = ptr[2];
ip_slice[15] = ptr[3];
return result;
} else {
const digit = try std.fmt.charToDigit(c, 16);
if (@mulWithOverflow(u16, x, 16, &x)) {
return error.Overflow;
}
if (@addWithOverflow(u16, x, digit, &x)) {
return error.Overflow;
}
saw_any_digits = true;
}
}
if (!saw_any_digits and !abbrv) {
return error.Incomplete;
}
if (scope_id and scope_id_index == 0) {
return error.Incomplete;
}
var resolved_scope_id: u32 = 0;
if (scope_id_index > 0) {
const scope_id_str = scope_id_value[0..scope_id_index];
resolved_scope_id = std.fmt.parseInt(u32, scope_id_str, 10) catch |err| blk: {
if (err != error.InvalidCharacter) return err;
break :blk try if_nametoindex(scope_id_str);
};
}
result.sa.scope_id = resolved_scope_id;
if (index == 14) {
ip_slice[14] = @truncate(u8, x >> 8);
ip_slice[15] = @truncate(u8, x);
return result;
} else {
ip_slice[index] = @truncate(u8, x >> 8);
index += 1;
ip_slice[index] = @truncate(u8, x);
index += 1;
mem.copy(u8, result.sa.addr[16 - index ..], ip_slice[0..index]);
return result;
}
}
pub fn init(addr: [16]u8, port: u16, flowinfo: u32, scope_id: u32) Ip6Address {
return Ip6Address{
.sa = os.sockaddr.in6{
.addr = addr,
.port = mem.nativeToBig(u16, port),
.flowinfo = flowinfo,
.scope_id = scope_id,
},
};
}
/// Returns the port in native endian.
/// Asserts that the address is ip4 or ip6.
pub fn getPort(self: Ip6Address) u16 {
return mem.bigToNative(u16, self.sa.port);
}
/// `port` is native-endian.
/// Asserts that the address is ip4 or ip6.
pub fn setPort(self: *Ip6Address, port: u16) void {
self.sa.port = mem.nativeToBig(u16, port);
}
pub fn format(
self: Ip6Address,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: anytype,
) !void {
_ = fmt;
_ = options;
const port = mem.bigToNative(u16, self.sa.port);
if (mem.eql(u8, self.sa.addr[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) {
try std.fmt.format(out_stream, "[::ffff:{}.{}.{}.{}]:{}", .{
self.sa.addr[12],
self.sa.addr[13],
self.sa.addr[14],
self.sa.addr[15],
port,
});
return;
}
const big_endian_parts = @ptrCast(*align(1) const [8]u16, &self.sa.addr);
const native_endian_parts = switch (native_endian) {
.Big => big_endian_parts.*,
.Little => blk: {
var buf: [8]u16 = undefined;
for (big_endian_parts) |part, i| {
buf[i] = mem.bigToNative(u16, part);
}
break :blk buf;
},
};
try out_stream.writeAll("[");
var i: usize = 0;
var abbrv = false;
while (i < native_endian_parts.len) : (i += 1) {
if (native_endian_parts[i] == 0) {
if (!abbrv) {
try out_stream.writeAll(if (i == 0) "::" else ":");
abbrv = true;
}
continue;
}
try std.fmt.format(out_stream, "{x}", .{native_endian_parts[i]});
if (i != native_endian_parts.len - 1) {
try out_stream.writeAll(":");
}
}
try std.fmt.format(out_stream, "]:{}", .{port});
}
pub fn getOsSockLen(self: Ip6Address) os.socklen_t {
_ = self;
return @sizeOf(os.sockaddr.in6);
}
};
pub fn connectUnixSocket(path: []const u8) !Stream {
const opt_non_block = if (std.io.is_async) os.SOCK.NONBLOCK else 0;
const sockfd = try os.socket(
os.AF.UNIX,
os.SOCK.STREAM | os.SOCK.CLOEXEC | opt_non_block,
0,
);
errdefer os.closeSocket(sockfd);
var addr = try std.net.Address.initUnix(path);
if (std.io.is_async) {
const loop = std.event.Loop.instance orelse return error.WouldBlock;
try loop.connect(sockfd, &addr.any, addr.getOsSockLen());
} else {
try os.connect(sockfd, &addr.any, addr.getOsSockLen());
}
return Stream{
.handle = sockfd,
};
}
fn if_nametoindex(name: []const u8) !u32 {
if (builtin.target.os.tag == .linux) {
var ifr: os.ifreq = undefined;
var sockfd = try os.socket(os.AF.UNIX, os.SOCK.DGRAM | os.SOCK.CLOEXEC, 0);
defer os.closeSocket(sockfd);
std.mem.copy(u8, &ifr.ifrn.name, name);
ifr.ifrn.name[name.len] = 0;
// TODO investigate if this needs to be integrated with evented I/O.
try os.ioctl_SIOCGIFINDEX(sockfd, &ifr);
return @bitCast(u32, ifr.ifru.ivalue);
}
if (comptime builtin.target.os.tag.isDarwin()) {
if (name.len >= os.IFNAMESIZE)
return error.NameTooLong;
var if_name: [os.IFNAMESIZE:0]u8 = undefined;
std.mem.copy(u8, &if_name, name);
if_name[name.len] = 0;
const if_slice = if_name[0..name.len :0];
const index = os.system.if_nametoindex(if_slice);
if (index == 0)
return error.InterfaceNotFound;
return @bitCast(u32, index);
}
@compileError("std.net.if_nametoindex unimplemented for this OS");
}
pub const AddressList = struct {
arena: std.heap.ArenaAllocator,
addrs: []Address,
canon_name: ?[]u8,
pub fn deinit(self: *AddressList) void {
// Here we copy the arena allocator into stack memory, because
// otherwise it would destroy itself while it was still working.
var arena = self.arena;
arena.deinit();
// self is destroyed
}
};
/// All memory allocated with `allocator` will be freed before this function returns.
pub fn tcpConnectToHost(allocator: mem.Allocator, name: []const u8, port: u16) !Stream {
const list = try getAddressList(allocator, name, port);
defer list.deinit();
if (list.addrs.len == 0) return error.UnknownHostName;
for (list.addrs) |addr| {
return tcpConnectToAddress(addr) catch |err| switch (err) {
error.ConnectionRefused => {
continue;
},
else => return err,
};
}
return std.os.ConnectError.ConnectionRefused;
}
pub fn tcpConnectToAddress(address: Address) !Stream {
const nonblock = if (std.io.is_async) os.SOCK.NONBLOCK else 0;
const sock_flags = os.SOCK.STREAM | nonblock |
(if (builtin.target.os.tag == .windows) 0 else os.SOCK.CLOEXEC);
const sockfd = try os.socket(address.any.family, sock_flags, os.IPPROTO.TCP);
errdefer os.closeSocket(sockfd);
if (std.io.is_async) {
const loop = std.event.Loop.instance orelse return error.WouldBlock;
try loop.connect(sockfd, &address.any, address.getOsSockLen());
} else {
try os.connect(sockfd, &address.any, address.getOsSockLen());
}
return Stream{ .handle = sockfd };
}
/// Call `AddressList.deinit` on the result.
pub fn getAddressList(allocator: mem.Allocator, name: []const u8, port: u16) !*AddressList {
const result = blk: {
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();
const result = try arena.allocator().create(AddressList);
result.* = AddressList{
.arena = arena,
.addrs = undefined,
.canon_name = null,
};
break :blk result;
};
const arena = result.arena.allocator();
errdefer result.arena.deinit();
if (builtin.target.os.tag == .windows or builtin.link_libc) {
const name_c = try std.cstr.addNullByte(allocator, name);
defer allocator.free(name_c);
const port_c = try std.fmt.allocPrintZ(allocator, "{}", .{port});
defer allocator.free(port_c);
const sys = if (builtin.target.os.tag == .windows) os.windows.ws2_32 else os.system;
const hints = os.addrinfo{
.flags = sys.AI.NUMERICSERV,
.family = os.AF.UNSPEC,
.socktype = os.SOCK.STREAM,
.protocol = os.IPPROTO.TCP,
.canonname = null,
.addr = null,
.addrlen = 0,
.next = null,
};
var res: *os.addrinfo = undefined;
const rc = sys.getaddrinfo(name_c.ptr, port_c.ptr, &hints, &res);
if (builtin.target.os.tag == .windows) switch (@intToEnum(os.windows.ws2_32.WinsockError, @intCast(u16, rc))) {
@intToEnum(os.windows.ws2_32.WinsockError, 0) => {},
.WSATRY_AGAIN => return error.TemporaryNameServerFailure,
.WSANO_RECOVERY => return error.NameServerFailure,
.WSAEAFNOSUPPORT => return error.AddressFamilyNotSupported,
.WSA_NOT_ENOUGH_MEMORY => return error.OutOfMemory,
.WSAHOST_NOT_FOUND => return error.UnknownHostName,
.WSATYPE_NOT_FOUND => return error.ServiceUnavailable,
.WSAEINVAL => unreachable,
.WSAESOCKTNOSUPPORT => unreachable,
else => |err| return os.windows.unexpectedWSAError(err),
} else switch (rc) {
@intToEnum(sys.EAI, 0) => {},
.ADDRFAMILY => return error.HostLacksNetworkAddresses,
.AGAIN => return error.TemporaryNameServerFailure,
.BADFLAGS => unreachable, // Invalid hints
.FAIL => return error.NameServerFailure,
.FAMILY => return error.AddressFamilyNotSupported,
.MEMORY => return error.OutOfMemory,
.NODATA => return error.HostLacksNetworkAddresses,
.NONAME => return error.UnknownHostName,
.SERVICE => return error.ServiceUnavailable,
.SOCKTYPE => unreachable, // Invalid socket type requested in hints
.SYSTEM => switch (os.errno(-1)) {
else => |e| return os.unexpectedErrno(e),
},
else => unreachable,
}
defer sys.freeaddrinfo(res);
const addr_count = blk: {
var count: usize = 0;
var it: ?*os.addrinfo = res;
while (it) |info| : (it = info.next) {
if (info.addr != null) {
count += 1;
}
}
break :blk count;
};
result.addrs = try arena.alloc(Address, addr_count);
var it: ?*os.addrinfo = res;
var i: usize = 0;
while (it) |info| : (it = info.next) {
const addr = info.addr orelse continue;
result.addrs[i] = Address.initPosix(@alignCast(4, addr));
if (info.canonname) |n| {
if (result.canon_name == null) {
result.canon_name = try arena.dupe(u8, mem.sliceTo(n, 0));
}
}
i += 1;
}
return result;
}
if (builtin.target.os.tag == .linux) {
const flags = std.c.AI.NUMERICSERV;
const family = os.AF.UNSPEC;
var lookup_addrs = std.ArrayList(LookupAddr).init(allocator);
defer lookup_addrs.deinit();
var canon = std.ArrayList(u8).init(arena);
defer canon.deinit();
try linuxLookupName(&lookup_addrs, &canon, name, family, flags, port);
result.addrs = try arena.alloc(Address, lookup_addrs.items.len);
if (canon.items.len != 0) {
result.canon_name = canon.toOwnedSlice();
}
for (lookup_addrs.items) |lookup_addr, i| {
result.addrs[i] = lookup_addr.addr;
assert(result.addrs[i].getPort() == port);
}
return result;
}
@compileError("std.net.getAddressList unimplemented for this OS");
}
const LookupAddr = struct {
addr: Address,
sortkey: i32 = 0,
};
const DAS_USABLE = 0x40000000;
const DAS_MATCHINGSCOPE = 0x20000000;
const DAS_MATCHINGLABEL = 0x10000000;
const DAS_PREC_SHIFT = 20;
const DAS_SCOPE_SHIFT = 16;
const DAS_PREFIX_SHIFT = 8;
const DAS_ORDER_SHIFT = 0;
fn linuxLookupName(
addrs: *std.ArrayList(LookupAddr),
canon: *std.ArrayList(u8),
opt_name: ?[]const u8,
family: os.sa_family_t,
flags: u32,
port: u16,
) !void {
if (opt_name) |name| {
// reject empty name and check len so it fits into temp bufs
canon.items.len = 0;
try canon.appendSlice(name);
if (Address.parseExpectingFamily(name, family, port)) |addr| {
try addrs.append(LookupAddr{ .addr = addr });
} else |name_err| if ((flags & std.c.AI.NUMERICHOST) != 0) {
return name_err;
} else {
try linuxLookupNameFromHosts(addrs, canon, name, family, port);
if (addrs.items.len == 0) {
try linuxLookupNameFromDnsSearch(addrs, canon, name, family, port);
}
if (addrs.items.len == 0) {
// RFC 6761 Section 6.3
// Name resolution APIs and libraries SHOULD recognize localhost
// names as special and SHOULD always return the IP loopback address
// for address queries and negative responses for all other query
// types.
// Check for equal to "localhost" or ends in ".localhost"
if (mem.endsWith(u8, name, "localhost") and (name.len == "localhost".len or na
A897
me[name.len - "localhost".len] == '.')) {
try addrs.append(LookupAddr{ .addr = .{ .in = Ip4Address.parse("127.0.0.1", port) catch unreachable } });
try addrs.append(LookupAddr{ .addr = .{ .in6 = Ip6Address.parse("::1", port) catch unreachable } });
return;
}
}
}
} else {
try canon.resize(0);
try linuxLookupNameFromNull(addrs, family, flags, port);
}
if (addrs.items.len == 0) return error.UnknownHostName;
// No further processing is needed if there are fewer than 2
// results or if there are only IPv4 results.
if (addrs.items.len == 1 or family == os.AF.INET) return;
const all_ip4 = for (addrs.items) |addr| {
if (addr.addr.any.family != os.AF.INET) break false;
} else true;
if (all_ip4) return;
// The following implements a subset of RFC 3484/6724 destination
// address selection by generating a single 31-bit sort key for
// each address. Rules 3, 4, and 7 are omitted for having
// excessive runtime and code size cost and dubious benefit.
// So far the label/precedence table cannot be customized.
// This implementation is ported from musl libc.
// A more idiomatic "ziggy" implementation would be welcome.
for (addrs.items) |*addr, i| {
var key: i32 = 0;
var sa6: os.sockaddr.in6 = undefined;
@memset(@ptrCast([*]u8, &sa6), 0, @sizeOf(os.sockaddr.in6));
var da6 = os.sockaddr.in6{
.family = os.AF.INET6,
.scope_id = addr.addr.in6.sa.scope_id,
.port = 65535,
.flowinfo = 0,
.addr = [1]u8{0} ** 16,
};
var sa4: os.sockaddr.in = undefined;
@memset(@ptrCast([*]u8, &sa4), 0, @sizeOf(os.sockaddr.in));
var da4 = os.sockaddr.in{
.family = os.AF.INET,
.port = 65535,
.addr = 0,
.zero = [1]u8{0} ** 8,
};
var sa: *align(4) os.sockaddr = undefined;
var da: *align(4) os.sockaddr = undefined;
var salen: os.socklen_t = undefined;
var dalen: os.socklen_t = undefined;
if (addr.addr.any.family == os.AF.INET6) {
mem.copy(u8, &da6.addr, &addr.addr.in6.sa.addr);
da = @ptrCast(*os.sockaddr, &da6);
dalen = @sizeOf(os.sockaddr.in6);
sa = @ptrCast(*os.sockaddr, &sa6);
salen = @sizeOf(os.sockaddr.in6);
} else {
mem.copy(u8, &sa6.addr, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff");
mem.copy(u8, &da6.addr, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff");
mem.writeIntNative(u32, da6.addr[12..], addr.addr.in.sa.addr);
da4.addr = addr.addr.in.sa.addr;
da = @ptrCast(*os.sockaddr, &da4);
dalen = @sizeOf(os.sockaddr.in);
sa = @ptrCast(*os.sockaddr, &sa4);
salen = @sizeOf(os.sockaddr.in);
}
const dpolicy = policyOf(da6.addr);
const dscope: i32 = scopeOf(da6.addr);
const dlabel = dpolicy.label;
const dprec: i32 = dpolicy.prec;
const MAXADDRS = 3;
var prefixlen: i32 = 0;
const sock_flags = os.SOCK.DGRAM | os.SOCK.CLOEXEC;
if (os.socket(addr.addr.any.family, sock_flags, os.IPPROTO.UDP)) |fd| syscalls: {
defer os.closeSocket(fd);
os.connect(fd, da, dalen) catch break :syscalls;
key |= DAS_USABLE;
os.getsockname(fd, sa, &salen) catch break :syscalls;
if (addr.addr.any.family == os.AF.INET) {
// TODO sa6.addr[12..16] should return *[4]u8, making this cast unnecessary.
mem.writeIntNative(u32, @ptrCast(*[4]u8, &sa6.addr[12]), sa4.addr);
}
if (dscope == @as(i32, scopeOf(sa6.addr))) key |= DAS_MATCHINGSCOPE;
if (dlabel == labelOf(sa6.addr)) key |= DAS_MATCHINGLABEL;
prefixlen = prefixMatch(sa6.addr, da6.addr);
} else |_| {}
key |= dprec << DAS_PREC_SHIFT;
key |= (15 - dscope) << DAS_SCOPE_SHIFT;
key |= prefixlen << DAS_PREFIX_SHIFT;
key |= (MAXADDRS - @intCast(i32, i)) << DAS_ORDER_SHIFT;
addr.sortkey = key;
}
std.sort.sort(LookupAddr, addrs.items, {}, addrCmpLessThan);
}
const Policy = struct {
addr: [16]u8,
len: u8,
mask: u8,
prec: u8,
label: u8,
};
const defined_policies = [_]Policy{
Policy{
.addr = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01".*,
.len = 15,
.mask = 0xff,
.prec = 50,
.label = 0,
},
Policy{
.addr = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00".*,
.len = 11,
.mask = 0xff,
.prec = 35,
.label = 4,
},