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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
#[cfg(windows)]
use std::borrow::Cow;
use std::
{
ffi::{CStr, OsStr, c_char},
fmt::{self, Debug, Display},
hash::{Hash, Hasher},
io::{self, ErrorKind},
mem,
path::Path,
slice
};
#[cfg(unix)]
use std::os::unix::{ffi::OsStrExt, net};
#[cfg(unix)]
use libc::{AF_UNIX, sa_family_t, sockaddr, sockaddr_storage, sockaddr_un, socklen_t};
#[cfg(windows)]
pub use windows_sys::Win32::Networking::WinSock::
{
AF_UNIX, SOCKADDR_STORAGE as sockaddr_storage, socklen_t, SOCKADDR as sockaddr,
SOCKADDR_UN as sockaddr_un, ADDRESS_FAMILY as sa_family_t
};
/// Offset of `.sun_path` in `sockaddr_un`.
///
/// This is not always identical to `mem::size_of::<sa_family_t>()`,
/// as there can be other fields before or after `.sun_family`.
fn path_offset() -> socklen_t
{
unsafe
{
let total_size = mem::size_of::<sockaddr_un>();
let name_size = mem::size_of_val(&mem::zeroed::<sockaddr_un>().sun_path);
(total_size - name_size) as socklen_t
}
}
const
fn as_u8(slice: &[c_char]) -> &[u8]
{
unsafe { &*(slice as *const[c_char] as *const[u8]) }
}
const
fn as_char(slice: &[u8]) -> &[c_char]
{
unsafe { &*(slice as *const[u8] as *const[c_char]) }
}
const TOO_LONG_DESC: &str = "address is too long";
/// A unix domain socket address.
///
/// # Differences from `std`'s `unix::net::SocketAddr`
///
/// This type fully supports Linux's abstract socket addresses,
/// and can be created by user code instead of just returned by `accept()`
/// and similar.
///
/// # Examples
///
/// Creating an abstract address (fails if the OS doesn't support them):
///
#[cfg_attr(any(target_os="linux", target_os="android"), doc="```")]
#[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```no_run")]
/// use uds_fork::UnixSocketAddr;
///
/// let addr = UnixSocketAddr::new("@abstract").unwrap();
/// assert!(addr.is_abstract());
/// assert_eq!(addr.to_string(), "@abstract");
/// ```
#[derive(Clone, Copy)]
pub struct UnixSocketAddr
{
addr: sockaddr_un,
/// How many bytes of addr are in use.
///
/// Must never be greater than `size_of::<sockaddr_un>()`.
///
/// On BSDs and macOS, `sockaddr_un` has a (non-standard) `.sun_len` field
/// that *could* be used to store the length instead, but doing that is
/// not a very good idea:
/// At least [NetBSD ignores it](http://mail-index.netbsd.org/tech-net/2006/10/11/0008.html)
/// so we would still need to pass a correctly set `socklen_t`,
/// in some cases by referece.
/// Because it's rarely used and some BSDs aren't afraid to break stuff,
/// it could even dissappear in the future.
/// The size this extra field is also rather minor compared to the size of
/// `sockaddr_un`, so the possible benefit is tiny.
len: socklen_t,
}
/// An enum representation of an unix socket address.
///
/// Useful for pattern matching an [`UnixSocketAddr`](struct.UnixSocketAddr.html)
/// via [`UnixSocketAddr.name()`](struct.UnixSocketAddr.html#method.name).
///
/// It cannot be used to bind or connect a socket directly as it
/// doesn't contain a `sockaddr_un`, but a `UnixSocketAddr` can be created
/// from it.
///
/// # Examples
///
/// Cleaning up pathname socket files after ourselves:
///
/// ```no_run
/// # use uds_fork::{UnixSocketAddr, AddrName};
/// let addr = UnixSocketAddr::from_path("/var/run/socket.sock").unwrap();
/// if let AddrName::Path(path) = addr.name() {
/// let _ = std::fs::remove_file(path);
/// }
/// ```
#[derive(Clone,Copy, PartialEq,Eq,Hash, Debug)]
pub enum AddrName<'a>
{
/// Unnamed / anonymous address.
Unnamed,
/// Regular file path based address.
///
/// Can be both relative and absolute.
Path(&'a Path),
/// Address in the abstract namespace.
Abstract(&'a [u8]),
}
impl<'a> From<&'a UnixSocketAddr> for AddrName<'a>
{
fn from(addr: &'a UnixSocketAddr) -> AddrName<'a>
{
let name_len = addr.len as isize - path_offset() as isize;
if addr.is_unnamed() == true
{
AddrName::Unnamed
}
else if addr.is_abstract() == true
{
let slice = &addr.addr.sun_path[1..name_len as usize];
AddrName::Abstract(as_u8(slice))
}
else
{
let mut slice = &addr.addr.sun_path[..name_len as usize];
// remove trailing NUL if present (and multiple NULs on OpenBSD)
while let Some(&0) = slice.last()
{
slice = &slice[..slice.len()-1];
}
#[cfg(unix)]
return
AddrName::Path(Path::new(OsStr::from_bytes(as_u8(slice))));
// sun_path is UTF-8
#[cfg(windows)]
{
//let utf8_valid = str::from_utf8(as_u8(slice)).unwrap();
return
AddrName::Path(Path::new(unsafe{ OsStr::from_encoded_bytes_unchecked(as_u8(slice)) } ))
}
}
}
}
pub type UnixSocketAddrRef<'a> = AddrName<'a>;
impl Debug for UnixSocketAddr
{
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result
{
#[derive(Debug)]
struct Unnamed;
#[derive(Debug)]
struct Path<'a>(&'a std::path::Path);
#[cfg(unix)]
#[derive(Debug)]
struct Abstract<'a>(&'a OsStr);
#[cfg(windows)]
#[derive(Debug)]
struct Abstract<'a>(Cow<'a, str>);
// doesn't live long enough if created inside match
let mut path_type = Path("".as_ref());
#[cfg(unix)]
let mut abstract_type = Abstract(OsStr::new(""));
#[cfg(windows)]
let mut abstract_type = Abstract(Cow::Borrowed(""));
let variant: &dyn Debug =
match self.into()
{
UnixSocketAddrRef::Unnamed =>
&Unnamed,
UnixSocketAddrRef::Path(path) =>
{
path_type.0 = path;
&path_type
},
UnixSocketAddrRef::Abstract(name) =>
{
#[cfg(unix)]
{
abstract_type.0 = OsStr::from_bytes(name);
}
#[cfg(windows)]
{
let utf8_valid = String::from_utf8_lossy(name);
abstract_type.0 = utf8_valid;
}
&abstract_type
},
};
fmtr.debug_tuple("UnixSocketAddr").field(variant).finish()
}
}
impl Display for UnixSocketAddr
{
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result
{
match self.into()
{
UnixSocketAddrRef::Unnamed =>
fmtr.write_str("unnamed"),
UnixSocketAddrRef::Path(path) =>
write!(fmtr, "{}", path.display()), // TODO check that display() doesn't print \n as-is
#[cfg(unix)]
UnixSocketAddrRef::Abstract(name) =>
{
write!(fmtr, "@{}", OsStr::from_bytes(name).to_string_lossy()) // FIXME escape to sane characters
}
#[cfg(windows)]
UnixSocketAddrRef::Abstract(name) =>
{
let utf8_valid = String::from_utf8_lossy(name);
write!(fmtr, "@{}", utf8_valid) // FIXME escape to sane characters
}
}
}
}
#[cfg(windows)]
impl UnixSocketAddr
{
/// Allows creating abstract, path or unspecified address based on an
/// user-supplied string.
///
/// A leading `'@'` or `'\0'` signifies an abstract address,
/// an empty slice is taken as the unnamed address, and anything else is a
/// path address.
/// If a relative path address starts with `@`, escape it by prepending
/// `"./"`.
/// To avoid surprises, abstract addresses will be detected regargsless of
/// wheither the OS supports them, and result in an error if it doesn't.
///
/// # Errors
///
/// * A path or abstract address is too long.
/// * A path address contains `'\0'`.
/// * An abstract name was supplied on an OS that doesn't support them.
///
/// # Examples
///
/// Abstract address:
///
/// ```
/// # use uds_fork::UnixSocketAddr;
/// if UnixSocketAddr::has_abstract_addresses() {
/// assert!(UnixSocketAddr::new("@abstract").unwrap().is_abstract());
/// assert!(UnixSocketAddr::new("\0abstract").unwrap().is_abstract());
/// } else {
/// assert!(UnixSocketAddr::new("@abstract").is_err());
/// assert!(UnixSocketAddr::new("\0abstract").is_err());
/// }
/// ```
///
/// Escaped path address:
///
/// ```
/// # use uds_fork::UnixSocketAddr;
/// assert!(UnixSocketAddr::new("./@path").unwrap().is_relative_path());
/// ```
///
/// Unnamed address:
///
#[cfg_attr(not(target_family="windows"), doc="```")]
#[cfg_attr(target_family="windows", doc="```no_run")]
/// # use uds_fork::UnixSocketAddr;
/// assert!(UnixSocketAddr::new("").unwrap().is_unnamed());
/// ```
pub
fn new<A: AsRef<[u8]>+?Sized>(addr: &A) -> Result<Self, io::Error>
{
fn parse(addr: &[u8]) -> Result<UnixSocketAddr, io::Error>
{
match addr.first()
{
Some(&b'@') | Some(&b'\0') =>
return
Err(
io::Error::new(
ErrorKind::AddrNotAvailable,
format!( "abstract unix domain socket addresses are not available on {}",
std::env::consts::OS)
)
),
Some(_) =>
{
let utf8_valid =
str::from_utf8(addr)
.map_err(|e| io::Error::new(ErrorKind::InvalidInput, e)
)?;
UnixSocketAddr::from_path(Path::new(utf8_valid))
},
None =>
return
Err(
io::Error::new(
ErrorKind::AddrNotAvailable,
format!( "unspecified unix domain socket addresses are not available on {}",
std::env::consts::OS)
)
),
}
}
return parse(addr.as_ref());
}
/// Allows creating abstract, path or unspecified address based on an
/// user-supplied string for Windows UTF-16 path.
///
/// A leading `'@'` or `'\0'` signifies an abstract address,
/// an empty slice is taken as the unnamed address, and anything else is a
/// path address. (Windows does not support abstract addresses)
/// If a relative path address starts with `@`, escape it by prepending
/// `"./"`.
/// To avoid surprises, abstract addresses will be detected regargsless of
/// wheither the OS supports them, and result in an error if it doesn't.
///
/// # Errors
///
/// * A path or abstract address is too long.
/// * A path address contains `'\0'`.
/// * An abstract name was supplied on an OS that doesn't support them.
pub
fn new_utf16<A: AsRef<[u16]>+?Sized>(addr_v: &A) -> Result<Self, io::Error>
{
use std::{ffi::OsString, os::windows::ffi::OsStringExt};
let addr = addr_v.as_ref();
let first =
if addr.len() > 0
{
Some(OsString::from_wide(&addr[0..1]))
}
else
{
None
};
match first.as_ref().map(|v| v.as_encoded_bytes())
{
Some(b"@") | Some(b"\0") =>
return
Err(
io::Error::new(
ErrorKind::AddrNotAvailable,
format!( "abstract unix domain socket addresses are not available on {}",
std::env::consts::OS)
)
),
Some(_) =>
{
let osstr = OsString::from_wide(addr);
return UnixSocketAddr::from_path(Path::new( &osstr ));
},
None =>
return
Err(
io::Error::new(
ErrorKind::AddrNotAvailable,
format!( "unspecified unix domain socket addresses are not available on {}",
std::env::consts::OS)
)
),
}
}
}
#[cfg(unix)]
impl UnixSocketAddr
{
/// Allows creating abstract, path or unspecified address based on an
/// user-supplied string.
///
/// A leading `'@'` or `'\0'` signifies an abstract address,
/// an empty slice is taken as the unnamed address, and anything else is a
/// path address.
/// If a relative path address starts with `@`, escape it by prepending
/// `"./"`.
/// To avoid surprises, abstract addresses will be detected regargsless of
/// wheither the OS supports them, and result in an error if it doesn't.
///
/// # Errors
///
/// * A path or abstract address is too long.
/// * A path address contains `'\0'`.
/// * An abstract name was supplied on an OS that doesn't support them.
///
/// # Examples
///
/// Abstract address:
///
/// ```
/// # use uds_fork::UnixSocketAddr;
/// if UnixSocketAddr::has_abstract_addresses() {
/// assert!(UnixSocketAddr::new("@abstract").unwrap().is_abstract());
/// assert!(UnixSocketAddr::new("\0abstract").unwrap().is_abstract());
/// } else {
/// assert!(UnixSocketAddr::new("@abstract").is_err());
/// assert!(UnixSocketAddr::new("\0abstract").is_err());
/// }
/// ```
///
/// Escaped path address:
///
/// ```
/// # use uds_fork::UnixSocketAddr;
/// assert!(UnixSocketAddr::new("./@path").unwrap().is_relative_path());
/// ```
///
/// Unnamed address:
///
/// ```
/// # use uds_fork::UnixSocketAddr;
/// assert!(UnixSocketAddr::new("").unwrap().is_unnamed());
/// ```
pub
fn new<A: AsRef<[u8]>+?Sized>(addr: &A) -> Result<Self, io::Error>
{
fn parse(addr: &[u8]) -> Result<UnixSocketAddr, io::Error>
{
match addr.first()
{
Some(&b'@') | Some(&b'\0') =>
UnixSocketAddr::from_abstract(&addr[1..]),
Some(_) =>
UnixSocketAddr::from_path(Path::new(OsStr::from_bytes(addr))),
None =>
Ok(UnixSocketAddr::new_unspecified()),
}
}
return parse(addr.as_ref());
}
}
impl UnixSocketAddr
{
/// Creates an unnamed address, which on Linux can be used for auto-bind.
///
/// Binding a socket to the unnamed address is different from not binding
/// at all:
///
/// On Linux doing so binds the socket to a random abstract address
/// determined by the OS.
///
/// # Examples
///
#[cfg_attr(any(target_os="linux", target_os="android"), doc="```")]
#[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```ignore")]
/// # use uds_fork::{UnixSocketAddr, UnixDatagramExt};
/// # use std::os::unix::net::UnixDatagram;
/// let addr = UnixSocketAddr::new_unspecified();
/// assert!(addr.is_unnamed());
/// let socket = UnixDatagram::unbound().unwrap();
/// socket.bind_to_unix_addr(&addr).unwrap();
/// assert!(socket.local_unix_addr().unwrap().is_abstract());
/// ```
pub
fn new_unspecified() -> Self
{
let mut addr: sockaddr_un = unsafe { mem::zeroed() };
addr.sun_family = AF_UNIX as sa_family_t;
return
UnixSocketAddr
{
len: path_offset(),
addr,
};
}
/// Returns the maximum size of pathname addresses supported by `UnixSocketAddr`.
///
/// Is the size of the underlying `sun_path` field, minus 1 if the OS
/// is known to either require a trailing NUL (`'\0'`) byte,
/// or supports longer paths that go past the end of `sun_path`.
///
/// These OSes are:
///
/// * OpenBSD: Enforces that `sun_path`` is NUL-terminated.
/// * macOS / iOS / anything else Apple: I haven't found a manpage,
/// but it supports longer paths.
/// * Illumos: [The manpage](https://illumos.org/man/3SOCKET/sockaddr_un)
/// says it must be NUL-terminated (and that it cannot be longer),
/// but when I tested on an older version, neither of these constraints seem to be the case.
/// * Solaris: Assumed to be identical to Illumos.
///
/// OSes that have been tested that they allow using the full `sun_path`
/// without NUL and no longer paths, and whose manpages don't state the opposite:
///
/// * [Linux](https://www.man7.org/linux/man-pages/man7/unix.7.html)
/// * [FreeBSD](https://man.freebsd.org/cgi/man.cgi?query=unix&sektion=4)
/// * [NetBSD](https://man.netbsd.org/unix.4)
/// * [Dragonfly BSD](https://man.dragonflybsd.org/?command=unix§ion=4)
pub
fn max_path_len() -> usize
{
let always_nul_terminate =
cfg!(any(
target_os="openbsd",
target_vendor="apple",
target_os="illumos",
target_os="solaris",
));
return
if always_nul_terminate == true
{
mem::size_of_val(&Self::new_unspecified().addr.sun_path) - 1
}
else
{
mem::size_of_val(&Self::new_unspecified().addr.sun_path)
};
}
/// Creates a pathname unix socket address.
///
/// # Errors
///
/// This function will return an error if the path is too long for the
/// underlying `sockaddr_un` type, or contains NUL (`'\0'`) bytes.
pub
fn from_path<P: AsRef<Path>+?Sized>(path: &P) -> Result<Self, io::Error>
{
fn from_path_inner(path: &[u8]) -> Result<UnixSocketAddr, io::Error>
{
let mut addr = UnixSocketAddr::new_unspecified();
let capacity = UnixSocketAddr::max_path_len();
if path.is_empty() == true
{
return Err(io::Error::new(ErrorKind::NotFound, "path is empty"));
}
else if path.len() > capacity
{
let message = "path is too long for an unix socket address";
return Err(io::Error::new(ErrorKind::InvalidInput, message));
}
else if path.iter().any(|&b| b == b'\0' ) == true
{
return Err(io::Error::new(ErrorKind::InvalidInput, "path cannot contain nul bytes"));
}
else
{
addr.addr.sun_path[..path.len()].copy_from_slice(as_char(path));
addr.len = path_offset() + path.len() as socklen_t;
if path.len() < capacity
{
addr.len += 1; // for increased portability
}
return Ok(addr);
}
}
#[cfg(unix)]
return from_path_inner(path.as_ref().as_os_str().as_bytes());
#[cfg(windows)]
return from_path_inner(path.as_ref().as_os_str().as_encoded_bytes());
}
/// Returns maximum size of abstract addesses supported by `UnixSocketAddr`.
///
/// Is the size of the underlying `sun_path` field minus 1 for the
/// leading `'\0'` byte.
///
/// This value is also returned on operating systems that doesn't support
/// abstract addresses.
pub
fn max_abstract_len() -> usize
{
mem::size_of_val(&Self::new_unspecified().addr.sun_path) - 1
}
/// Returns whether the operating system is known to support
/// abstract unix domain socket addresses.
///
/// Is `true` for Linux & Android, and `false` for all other OSes.
pub const
fn has_abstract_addresses() -> bool
{
cfg!(any(target_os="linux", target_os="android"))
}
/// Creates an abstract unix domain socket address.
///
/// Abstract addresses use a namespace separate from the file system,
/// that doesn't have directories (ie. is flat) or permissions.
/// The advandage of it is that the address disappear when the socket bound
/// to it is closed, which frees one from dealing with removing it when
/// shutting down cleanly.
///
/// They are a Linux-only feature though, and this function will fail
/// if abstract addresses are not supported.
///
/// # Errors
///
/// This function will return an error if the name is too long.
/// Call [`max_abstract_len()`](#method.max_abstract_len)
/// get the limit.
///
/// It will also fail on operating systems that don't support abstract
/// addresses. (ie. anything other than Linux and Android)
pub
fn from_abstract<N: AsRef<[u8]>+?Sized>(name: &N) -> Result<Self, io::Error>
{
fn from_abstract_inner(name: &[u8]) -> Result<UnixSocketAddr, io::Error>
{
let mut addr = UnixSocketAddr::new_unspecified();
if UnixSocketAddr::has_abstract_addresses() == false
{
return
Err(
io::Error::new(
ErrorKind::AddrNotAvailable,
format!( "abstract unix domain socket addresses are not available on {}",
std::env::consts::OS)
)
);
}
else if name.len() > UnixSocketAddr::max_abstract_len()
{
return
Err(io::Error::new(ErrorKind::InvalidInput, "abstract name is too long"));
}
else
{
addr.addr.sun_path[1..1+name.len()].copy_from_slice(as_char(name));
addr.len = path_offset() + 1 + name.len() as socklen_t;
return Ok(addr);
}
}
return from_abstract_inner(name.as_ref());
}
/// Tries to convert a `std::os::unix::net::SocketAddr` into an `UnixSocketAddr`.
///
/// This can fail (produce `None`) on Linux and Android
/// if the `std` `SocketAddr` represents an abstract address,
/// as it provides no method for viewing abstract addresses.
/// (other than parsing its `Debug` output, anyway.)
#[cfg(unix)]
pub
fn from_std(addr: net::SocketAddr) -> Option<Self>
{
return
if let Some(path) = addr.as_pathname()
{
Some(Self::from_path(path).expect("pathname addr cannot be converted"))
}
else if addr.is_unnamed()
{
Some(Self::new_unspecified())
}
else
{
None
};
}
/// Returns unnamed addres for empty strings, and path addresses otherwise.
///
/// # Errors
///
/// Returns ENAMETOOLONG if path (without the trailing `'\0'`) is too long
/// for `sockaddr_un.sun_path`.
pub
fn from_c_str(path: &CStr) -> Result<Self, io::Error>
{
let path = path.to_bytes();
let mut addr = Self::new_unspecified();
if path.is_empty()
{
return Ok(addr);
}
else if path.len() > mem::size_of_val(&addr.addr.sun_path)
{
let message = "path is too long for unix socket address";
return Err(io::Error::new(ErrorKind::InvalidInput, message));
}
else
{
addr.addr.sun_path[..path.len()].copy_from_slice(as_char(path));
addr.len = path_offset() + path.len() as socklen_t;
if path.len() < mem::size_of_val(&addr.addr.sun_path)
{
addr.len += 1;
}
return Ok(addr);
}
}
/// Checks whether the address is unnamed.
#[inline]
pub
fn is_unnamed(&self) -> bool
{
if Self::has_abstract_addresses()
{
return self.len <= path_offset();
}
else
{
// MacOS can apparently return non-empty addresses but with
// all-zeroes path for unnamed addresses.
return self.len <= path_offset() || self.addr.sun_path[0] as u8 == b'\0';
}
}
/// Checks whether the address is a name in the abstract namespace.
///
/// Always returns `false` on operating systems that don't support abstract
/// addresses.
pub
fn is_abstract(&self) -> bool
{
if Self::has_abstract_addresses() == true
{
return self.len > path_offset() && self.addr.sun_path[0] as u8 == b'\0';
}
else
{
return false;
}
}
/// Checks whether the address is a path that begins with '/'.
#[cfg(unix)]
#[inline]
pub
fn is_absolute_path(&self) -> bool
{
self.len > path_offset() && self.addr.sun_path[0] as u8 == b'/'
}
/// Checks whether the address is a path that begins with '/' or "C:\".
#[cfg(windows)]
#[inline]
pub
fn is_absolute_path(&self) -> bool
{
self.len > path_offset() &&
(
self.addr.sun_path[0] as u8 == b'/' ||
(self.addr.sun_path[0] as u8 as char).is_ascii_alphabetic() == true
)
}
/// Checks whether the address is a path that doesn't begin with '/'.
#[inline]
pub
fn is_relative_path(&self) -> bool
{
self.len > path_offset()
&& self.addr.sun_path[0] as u8 != b'\0'
&& self.addr.sun_path[0] as u8 != b'/'
}
/// Checks whether the address is a path.
#[inline]
pub
fn is_path(&self) -> bool
{
self.len > path_offset() && self.addr.sun_path[0] as u8 != b'\0'
}
/// Returns a view of the address that can be pattern matched
/// to the differnt types of addresses.
///
/// # Examples
///
/// ```
/// use uds_fork::{UnixSocketAddr, AddrName};
/// use std::path::Path;
///
/// assert_eq!(
/// UnixSocketAddr::new_unspecified().name(),
/// AddrName::Unnamed
/// );
/// assert_eq!(
/// UnixSocketAddr::from_path("/var/run/socket.sock").unwrap().name(),
/// AddrName::Path(Path::new("/var/run/socket.sock"))
/// );
/// if UnixSocketAddr::has_abstract_addresses() {
/// assert_eq!(
/// UnixSocketAddr::from_abstract("tcartsba").unwrap().name(),
/// AddrName::Abstract(b"tcartsba")
/// );
/// }
/// ```
pub
fn name(&self) -> AddrName<'_>
{
AddrName::from(self)
}
/// Returns the path of a path-based address.
pub
fn as_pathname(&self) -> Option<&Path>
{
let UnixSocketAddrRef::Path(path) = UnixSocketAddrRef::from(self)
else { return None };
return Some(path);
}
/// Returns the name of an address which is in the abstract namespace.
pub
fn as_abstract(&self) -> Option<&[u8]>
{
let UnixSocketAddrRef::Abstract(name) = UnixSocketAddrRef::from(self)
else {return None};
return Some(name);
}
/// Returns a view that can be pattern matched to the differnt types of
/// addresses.
///
/// # Examples
///
#[cfg_attr(any(target_os="linux", target_os="android"), doc="```")]
#[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```ignore")]
/// use uds_fork::{UnixDatagramExt, UnixSocketAddr, UnixSocketAddrRef};
/// use std::os::unix::net::UnixDatagram;
/// use tempfile::TempDir;
/// use std::path::Path;
///
/// let dir = tempfile::tempdir().unwrap();
/// let path = dir.path().join("dgram.socket");
///
/// let receiver = UnixDatagram::bind(&path).expect("create datagram socket");
/// assert_eq!(
/// receiver.local_unix_addr().unwrap().as_ref(),
/// UnixSocketAddrRef::Path(&path)
/// );
///
/// let sender = UnixDatagram::unbound().expect("create unbound datagram socket");
/// sender.send_to(b"I can't hear you", &path).expect("send");
///
/// let mut buf = [0; 100];
/// let (len, addr) = receiver.recv_from_unix_addr(&mut buf).unwrap();
/// assert_eq!(addr.as_ref(), UnixSocketAddrRef::Unnamed);
/// ```
pub
fn as_ref(&self) -> UnixSocketAddrRef<'_>
{
UnixSocketAddrRef::from(self)
}
/// Creates an address from a slice of bytes to place in `sun_path`.
///
/// This is a low-level but simple interface for creating addresses by
/// other unix socket wrappers without exposing any libc types.
/// The meaning of a slice can vary between operating systems.
///
/// `addr` should point to thes start of the "path" part of a socket
/// address, with length being the number of valid bytes of the path.
/// (Trailing NULs are not stripped by this function.)
///
/// # Errors
///
/// If the slice is longer than `sun_path`, an error of kind `Other` is
/// returned. No other validation of the bytes is performed.
///
/// # Examples
///
/// A normal path-based address
///
/// ```
/// # use std::path::Path;
/// # use uds_fork::UnixSocketAddr;
/// let addr = UnixSocketAddr::from_raw_bytes(b"/tmp/a.sock\0").unwrap();
/// assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/a.sock")));
/// assert_eq!(addr.as_raw_bytes(), b"/tmp/a.sock\0");
/// ```
///
/// On Linux:
///
#[cfg_attr(any(target_os="linux", target_os="android"), doc="```")]
#[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```no_run")]
/// # use uds_fork::UnixSocketAddr;
/// let addr = UnixSocketAddr::from_raw_bytes(b"\0a").unwrap();
/// assert_eq!(addr.as_abstract(), Some(&b"a"[..]));
/// assert_eq!(addr.as_raw_bytes(), b"\0a");
/// ```
///
/// Elsewhere:
///
#[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```")]
#[cfg_attr(any(target_os="linux", target_os="android"), doc="```no_run")]
/// # use uds_fork::UnixSocketAddr;
/// let addr = UnixSocketAddr::from_raw_bytes(b"\0a").unwrap();
/// assert!(addr.is_unnamed());
/// assert_eq!(addr.as_raw_bytes().len(), 2);
/// ```
///
/// A portable unnamed address:
///
/// ```
/// # use uds_fork::UnixSocketAddr;
/// let addr = UnixSocketAddr::from_raw_bytes(&[]).expect("not too long");
/// assert!(addr.is_unnamed());
/// assert!(addr.as_raw_bytes().is_empty());
/// ```
pub
fn from_raw_bytes(addr: &[u8]) -> Result<Self, io::Error>
{
if addr.len() <= Self::max_path_len()
{
let name = addr;
let mut addr = Self::default();
addr.addr.sun_path[..name.len()].copy_from_slice(as_char(name));
addr.len = path_offset() + name.len() as socklen_t;
return Ok(addr);
}
else
{
return Err(io::Error::new(ErrorKind::InvalidInput, TOO_LONG_DESC));
}
}
/// Returns a low-level view of the address without using any libc types.
///
/// The returned slice points to the start of `sun_addr` of the contained
/// `sockaddr_un`, and the length is the number of bytes of `sun_addr`
/// that were filled out by the OS. Any trailing NUL(s) will be preserved.
///
/// # Examples
///
/// A normal path-based address:
///
#[cfg_attr(any(target_vendor="apple", target_os="openbsd"), doc="```")]
#[cfg_attr(not(any(target_vendor="apple", target_os="openbsd")), doc="```ignore")]
/// # use std::path::Path;
/// # use std::os::unix::net::UnixDatagram;
/// # use uds_fork::{UnixSocketAddr, UnixDatagramExt};
/// let pathname = "/tmp/a_file";
/// let socket = UnixDatagram::bind(pathname).expect("create datagram socket");
/// # let _ = std::fs::remove_file(pathname);
/// let addr = socket.local_unix_addr().expect("get its address");
/// assert!(addr.as_raw_bytes().starts_with(pathname.as_bytes()));
/// assert!(addr.as_raw_bytes()[pathname.len()..].iter().all(|&b| b == b'\0' ));
/// assert_eq!(addr.as_pathname(), Some(Path::new(pathname)));
/// ```
///
/// Abstract address:
///
#[cfg_attr(any(target_os="linux", target_os="android"), doc="```")]
#[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```no_run")]
/// # use uds_fork::UnixSocketAddr;
/// let addr = UnixSocketAddr::new("@someone@").unwrap();
/// assert_eq!(addr.as_raw_bytes(), b"\0someone@");
/// ```
///
/// Unnamed address on macOS, OpenBSD and maybe others:
///
#[cfg_attr(any(target_vendor="apple", target_os="openbsd"), doc="```")]
#[cfg_attr(not(any(target_vendor="apple", target_os="openbsd")), doc="```ignore")]
/// # use std::os::unix::net::UnixDatagram;
/// # use uds_fork::{UnixSocketAddr, UnixDatagramExt};
/// let socket = UnixDatagram::unbound().expect("create datagram socket");
/// let addr = socket.local_unix_addr().expect("get its unbound address");
/// let bytes = addr.as_raw_bytes();
/// assert!(bytes.len() > 0);
/// assert!(bytes.iter().all(|&b| b == b'\0' ));
/// assert!(addr.is_unnamed());
/// ```
pub
fn as_raw_bytes(&self) -> &[u8]
{
as_u8(&self.addr.sun_path[..(self.len-path_offset()) as usize])
}
/// Prepares a `struct sockaddr*` and `socklen_t*` for passing to FFI
/// (such as `getsockname()`, `getpeername()`, or `accept()`),
/// and validate and normalize the produced address afterwards.
///
/// Validation:
///
/// * Check that the address family is `AF_UNIX`.
/// * Check that the address wasn't truncated (the `socklen_t` is too big).
///
/// Normalization:
///
/// * Ensure path addresses have a trailing NUL byte if there is space.
pub
fn new_from_ffi<R, F>(call: F) -> Result<(R, Self), io::Error>
where
F: FnOnce(&mut sockaddr, &mut socklen_t) -> Result<R, io::Error>
{
let mut addr = Self::new_unspecified();
let capacity = mem::size_of_val(&addr.addr) as socklen_t;
addr.len = capacity;
unsafe
{
let (addr_ptr, addr_len_ptr) = addr.as_raw_mut_general();
let ret = call(addr_ptr, addr_len_ptr)?;
if addr.addr.sun_family != AF_UNIX as sa_family_t
{
return Err(
io::Error::new(
ErrorKind::InvalidData,
"file descriptor did not correspond to a Unix socket" // identical to std's
)
);
}
if addr.is_abstract() == true
{
if addr.len > capacity
{
return Err(
io::Error::new(ErrorKind::InvalidData, "abstract name was too long")
);
}
}
else if addr.is_path() == true
{
if addr.len > capacity+1
{
return Err(io::Error::new(ErrorKind::InvalidData, "path was too long"));
// accept lengths one too big; assume the truncated byte was NUL
}
else
{
// normalize addr.len to include terminating NUL byte if possible
// and not be greater than capacity
if addr.len >= capacity
{
addr.len = capacity;
}
else if addr.addr.sun_path[(addr.len-1-path_offset()) as usize] != 0
{
addr.len += 1;
addr.addr.sun_path[(addr.len-1-path_offset()) as usize] = 0;
}
}
}
return Ok((ret, addr));
}
}
pub unsafe
fn from_ref(addr: &sockaddr, len: socklen_t) -> Result<Self, io::Error>
{
let mut copy = Self::new_unspecified();
if len < path_offset()
{
return Err(io::Error::new(ErrorKind::InvalidInput, "address length is too short"));
}
else if len > mem::size_of::<sockaddr_un>() as socklen_t
{
return Err(io::Error::new(ErrorKind::InvalidInput, TOO_LONG_DESC));
}
else if addr.sa_family != AF_UNIX as sa_family_t
{
return Err(io::Error::new(ErrorKind::InvalidData, "not an unix socket address"));
}
else
{
let addr = addr as *const sockaddr as *const sockaddr_un;
let sun_path_ptr = unsafe { (&*addr).sun_path.as_ptr() };
let path_len = (len - path_offset()) as usize;
let sun_path = unsafe { slice::from_raw_parts(sun_path_ptr, path_len) };
copy.addr.sun_path[..path_len].copy_from_slice(sun_path);
copy.len = len;
return Ok(copy);
}
}
/// Creates an `UnixSocketAddr` from a pointer to a generic [libc::sockaddr_storage] and
/// a length.
///
/// If len is == 0 or < [path_offset] an `unspecified` type is returned.
///
/// # Safety
///
/// * `len` must not be greater than the size of the memory `addr` points to.
/// * `addr` must point to valid memory if `len` is greater than zero, or be NULL.
pub unsafe
fn from_sockaddr_storage(addr: &sockaddr_storage, len: socklen_t) -> Result<Self, io::Error>
{
let mut copy = Self::new_unspecified();
if len < path_offset()
{
return Ok(copy);
}
else if len > mem::size_of::<sockaddr_un>() as socklen_t
{
return Err(io::Error::new(ErrorKind::InvalidInput, TOO_LONG_DESC));
}
else if addr.ss_family != AF_UNIX as sa_family_t
{
return Err(io::Error::new(ErrorKind::InvalidData, "not an unix socket address"));
}
else
{
let addr = addr as *const sockaddr_storage as *const sockaddr_un;
let sun_path_ptr = unsafe { (&*addr).sun_path.as_ptr() };
let path_len = (len - path_offset()) as usize;
let sun_path = unsafe { slice::from_raw_parts(sun_path_ptr, path_len) };
copy.addr.sun_path[..path_len].copy_from_slice(sun_path);
copy.len = len;
return Ok(copy);
}
}
/// Creates an `UnixSocketAddr` from a pointer to a generic `sockaddr` and
/// a length.
///
/// # Safety
///
/// * `len` must not be greater than the size of the memory `addr` points to.
/// * `addr` must point to valid memory if `len` is greater than zero, or be NULL.
pub unsafe
fn from_raw(addr: *const sockaddr, len: socklen_t) -> Result<Self, io::Error>
{
let mut copy = Self::new_unspecified();
if addr.is_null() == true && len == 0
{
return Ok(Self::new_unspecified());
}
else if addr.is_null() == true
{
return Err(io::Error::new(ErrorKind::InvalidInput, "addr is NULL"));
}
else if len < path_offset()
{
return Err(io::Error::new(ErrorKind::InvalidInput, "address length is too short"));
}
else if len > mem::size_of::<sockaddr_un>() as socklen_t
{
return Err(io::Error::new(ErrorKind::InvalidInput, TOO_LONG_DESC));
}
else if unsafe { (&*addr).sa_family } != AF_UNIX as sa_family_t
{
return Err(io::Error::new(ErrorKind::InvalidData, "not an unix socket address"));
}
else
{
let addr = addr as *const sockaddr_un;
let sun_path_ptr = unsafe { (&*addr).sun_path.as_ptr() };
let path_len = (len - path_offset()) as usize;
let sun_path = unsafe { slice::from_raw_parts(sun_path_ptr, path_len) };
copy.addr.sun_path[..path_len].copy_from_slice(sun_path);
copy.len = len;
return Ok(copy);
}
}
/// Creates an `UnixSocketAddr` without any validation.
///
/// # Safety
///
/// * `len` must be `<= size_of::<sockaddr_un>()`.
/// * `addr.sun_family` should be `AF_UNIX` or strange things might happen.
/// * `addr.sun_len`, if it exists, should be zero (but is probably ignored).
pub unsafe
fn from_raw_unchecked(addr: sockaddr_un, len: socklen_t) -> Self
{
Self{addr, len}
}
/// Splits the address into its inner, raw parts.
pub
fn into_raw(self) -> (sockaddr_un, socklen_t)
{
(self.addr, self.len)
}
/// Returns a general `sockaddr` reference to the address and its length.
///
/// Useful for passing to `bind()`, `connect()`, `sendto()` or other FFI.
///
/// Pathname addresses are not guaranteed to be NUL-terminated on most OSes:
/// Most paths will be NUL-terminated, but paths that just fit within `sockaddr_un.sun_len`
/// (iow their length is equal to `addr.sun_len[..].len()`) will not have one.
/// Therefore do not call `SUN_LEN()` on unknown addresses.
/// See [`max_path_len()`](#tymethod.max_path_len) for which OSes this affects.
pub
fn as_raw_general(&self) -> (&sockaddr, socklen_t)
{
// SAFETY: sockaddr is a super-type of sockaddr_un.
(unsafe { &*(&self.addr as *const sockaddr_un as *const sockaddr) }, self.len)
}
/// Returns a reference to the inner `struct sockaddr_un`, and length.
///
/// Pathname addresses are not guaranteed to be NUL-terminated on most OSes:
/// Most paths will be NUL-terminated, but paths that just fit within `sockaddr_un.sun_len`
/// (iow their length is equal to `addr.sun_len[..].len()`) will not have one.
/// Therefore do not call `SUN_LEN()` on unknown addresses.
/// See [`max_path_len()`](#tymethod.max_path_len) for which OSes this affects.
pub
fn as_raw(&self) -> (&sockaddr_un, socklen_t)
{
(&self.addr, self.len)
}
/// Returns mutable references to a general `struct sockaddr` and `socklen_t`.
///
/// If passing to `getpeername()`, `accept()` or similar, remember to set
/// the length to the capacity,
/// and consider using [`new_from_ffi()`](#method.new_from_ffi) instead.
///
/// Pathname addresses are not guaranteed to be NUL-terminated on most OSes:
/// Most paths will be NUL-terminated, but paths that just fit within `sockaddr_un.sun_len`
/// (iow their length is equal to `addr.sun_len[..].len()`) will not have one.
/// Therefore do not call `SUN_LEN()` on unknown addresses.
/// See [`max_path_len()`](#tymethod.max_path_len) for which OSes this affects.
///
/// # Safety
///
/// Assigning a value > `sizeof(struct sockaddr_un)` to the `socklen_t`
/// reference might lead to out-of-bounds reads later.
pub unsafe
fn as_raw_mut_general(&mut self) -> (&mut sockaddr, &mut socklen_t)
{
// SAFETY: sockaddr is a super-type of sockaddr_un.
(unsafe { &mut*(&mut self.addr as *mut sockaddr_un as *mut sockaddr) }, &mut self.len)
}
pub unsafe
fn as_raw_ptr_general(&self) -> (*const sockaddr, socklen_t)
{
// SAFETY: sockaddr is a super-type of sockaddr_un.
(&self.addr as *const sockaddr_un as *const sockaddr, self.len)
}
/// Returns mutable references to the inner `struct sockaddr_un` and length.
///
/// Pathname addresses are not guaranteed to be NUL-terminated on most OSes:
/// Most paths will be NUL-terminated, but paths that just fit within `sockaddr_un.sun_len`
/// (iow their length is equal to `addr.sun_len[..].len()`) will not have one.
/// Therefore do not call `SUN_LEN()` on unknown addresses.
/// See [`max_path_len()`](#tymethod.max_path_len) for which OSes this affects
///
/// # Safety
///
/// Assigning a value > `sizeof(struct sockaddr_un)` to the `socklen_t`
/// reference might lead to out-of-bounds reads later.
pub unsafe
fn as_raw_mut(&mut self) -> (&mut sockaddr_un, &mut socklen_t)
{
(&mut self.addr, &mut self.len)
}
}
impl Default for UnixSocketAddr
{
fn default() -> Self
{
Self::new_unspecified()
}
}
impl PartialEq for UnixSocketAddr
{
fn eq(&self, other: &Self) -> bool
{
self.as_ref() == other.as_ref()
}
}
impl Eq for UnixSocketAddr {}
impl Hash for UnixSocketAddr
{
fn hash<H: Hasher>(&self, hasher: &mut H)
{
self.as_ref().hash(hasher)
}
}
impl PartialEq<[u8]> for UnixSocketAddr
{
fn eq(&self, unescaped: &[u8]) -> bool
{
match (self.as_ref(), unescaped.first())
{
#[cfg(unix)]
(UnixSocketAddrRef::Path(path), Some(_)) =>
path.as_os_str().as_bytes() == unescaped,
#[cfg(windows)]
(UnixSocketAddrRef::Path(path), Some(_)) =>
path.as_os_str().as_encoded_bytes() == unescaped,
(UnixSocketAddrRef::Abstract(name), Some(b'\0')) =>
name == &unescaped[1..],
(UnixSocketAddrRef::Unnamed, None) =>
true,
(_, _) =>
false,
}
}
}
impl PartialEq<UnixSocketAddr> for [u8]
{
fn eq(&self, addr: &UnixSocketAddr) -> bool
{
addr == self
}
}