github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/pkg/strace/epsocket.go (about) 1 // Copyright 2018 Google LLC. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package strace 16 17 import ( 18 "bytes" 19 "encoding/binary" 20 "strings" 21 22 "golang.org/x/sys/unix" 23 ) 24 25 // Address is a byte slice cast as a string that represents the address of a 26 // network node. Or, in the case of unix endpoints, it may represent a path. 27 type Address string 28 29 type FullAddress struct { 30 // Addr is the network address. 31 Addr Address 32 33 // Port is the transport port. 34 // 35 // This may not be used by all endpoint types. 36 Port uint16 37 } 38 39 // GetAddress reads an sockaddr struct from the given address and converts it 40 // to the FullAddress format. It supports AF_UNIX, AF_INET and AF_INET6 41 // addresses. 42 func GetAddress(t *Tracer, addr []byte) (FullAddress, error) { 43 r := bytes.NewBuffer(addr[:2]) 44 var fam uint16 45 if err := binary.Read(r, ByteOrder, &fam); err != nil { 46 return FullAddress{}, unix.EFAULT 47 } 48 49 // Get the rest of the fields based on the address family. 50 switch fam { 51 case unix.AF_UNIX: 52 path := addr[2:] 53 if len(path) > unix.PathMax { 54 return FullAddress{}, unix.EINVAL 55 } 56 // Drop the terminating NUL (if one exists) and everything after 57 // it for filesystem (non-abstract) addresses. 58 if len(path) > 0 && path[0] != 0 { 59 if n := bytes.IndexByte(path[1:], 0); n >= 0 { 60 path = path[:n+1] 61 } 62 } 63 return FullAddress{ 64 Addr: Address(path), 65 }, nil 66 67 case unix.AF_INET: 68 var a unix.RawSockaddrInet4 69 r = bytes.NewBuffer(addr) 70 if err := binary.Read(r, binary.BigEndian, &a); err != nil { 71 return FullAddress{}, unix.EFAULT 72 } 73 out := FullAddress{ 74 Addr: Address(a.Addr[:]), 75 Port: uint16(a.Port), 76 } 77 if out.Addr == "\x00\x00\x00\x00" { 78 out.Addr = "" 79 } 80 return out, nil 81 case unix.AF_INET6: 82 var a unix.RawSockaddrInet6 83 r = bytes.NewBuffer(addr) 84 if err := binary.Read(r, binary.BigEndian, &a); err != nil { 85 return FullAddress{}, unix.EFAULT 86 } 87 88 out := FullAddress{ 89 Addr: Address(a.Addr[:]), 90 Port: uint16(a.Port), 91 } 92 93 //if isLinkLocal(out.Addr) { 94 // out.NIC = NICID(a.Scope_id) 95 //} 96 97 if out.Addr == Address(strings.Repeat("\x00", 16)) { 98 out.Addr = "" 99 } 100 return out, nil 101 default: 102 103 return FullAddress{}, unix.ENOTSUP 104 } 105 }