gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/sentry/socket/control/control_test.go (about) 1 // Copyright 2020 The gVisor Authors. 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 control provides internal representations of socket control 16 // messages. 17 package control 18 19 import ( 20 "testing" 21 22 "github.com/google/go-cmp/cmp" 23 "gvisor.dev/gvisor/pkg/abi/linux" 24 "gvisor.dev/gvisor/pkg/binary" 25 "gvisor.dev/gvisor/pkg/errors/linuxerr" 26 "gvisor.dev/gvisor/pkg/hostarch" 27 "gvisor.dev/gvisor/pkg/sentry/socket" 28 ) 29 30 func TestParse(t *testing.T) { 31 // Craft the control message to parse. 32 length := linux.SizeOfControlMessageHeader + linux.SizeOfTimeval 33 hdr := linux.ControlMessageHeader{ 34 Length: uint64(length), 35 Level: linux.SOL_SOCKET, 36 Type: linux.SO_TIMESTAMP, 37 } 38 buf := make([]byte, 0, length) 39 buf = binary.Marshal(buf, hostarch.ByteOrder, &hdr) 40 ts := linux.Timeval{ 41 Sec: 2401, 42 Usec: 343, 43 } 44 buf = binary.Marshal(buf, hostarch.ByteOrder, &ts) 45 46 cmsg, err := Parse(nil, nil, buf, 8 /* width */) 47 if err != nil { 48 t.Fatalf("Parse(_, _, %+v, _): %v", cmsg, err) 49 } 50 51 want := socket.ControlMessages{ 52 IP: socket.IPControlMessages{ 53 HasTimestamp: true, 54 Timestamp: ts.ToTime(), 55 }, 56 } 57 if diff := cmp.Diff(want, cmsg); diff != "" { 58 t.Errorf("unexpected message parsed, (-want, +got):\n%s", diff) 59 } 60 } 61 62 func TestParseRightsNegativeLength(t *testing.T) { 63 // Craft the control message to parse. 64 length := uint64(linux.SizeOfControlMessageHeader) + 128 65 hdr := linux.ControlMessageHeader{ 66 Length: uint64(0xffffffff8f000000), 67 Level: linux.SOL_SOCKET, 68 Type: linux.SCM_RIGHTS, 69 } 70 hdrBuf := make([]byte, 0, length) 71 hdrBuf = binary.Marshal(hdrBuf, hostarch.ByteOrder, &hdr) 72 73 buf := make([]byte, length) 74 copy(buf, hdrBuf) 75 cmsg, err := Parse(nil, nil, buf, 8 /* width */) 76 if err != linuxerr.EINVAL { 77 t.Fatalf("Parse(_, _, %+v, _): %v", cmsg, err) 78 } 79 80 }