github.com/nicocha30/gvisor-ligolo@v0.0.0-20230726075806-989fa2c0a413/runsc/console/console.go (about)

     1  // Copyright 2018 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 console contains utilities for working with pty consols in runsc.
    16  package console
    17  
    18  import (
    19  	"fmt"
    20  	"net"
    21  	"os"
    22  
    23  	"github.com/kr/pty"
    24  	"golang.org/x/sys/unix"
    25  )
    26  
    27  // NewWithSocket creates pty master/replica pair, sends the master FD over the
    28  // given socket, and returns the replica.
    29  func NewWithSocket(socketPath string) (*os.File, error) {
    30  	// Create a new pty master and replica.
    31  	ptyMaster, ptyReplica, err := pty.Open()
    32  	if err != nil {
    33  		return nil, fmt.Errorf("opening pty: %v", err)
    34  	}
    35  	defer ptyMaster.Close()
    36  
    37  	// Get a connection to the socket path.
    38  	conn, err := net.Dial("unix", socketPath)
    39  	if err != nil {
    40  		ptyReplica.Close()
    41  		return nil, fmt.Errorf("dialing socket %q: %v", socketPath, err)
    42  	}
    43  	defer conn.Close()
    44  	uc, ok := conn.(*net.UnixConn)
    45  	if !ok {
    46  		ptyReplica.Close()
    47  		return nil, fmt.Errorf("connection is not a UnixConn: %T", conn)
    48  	}
    49  	socket, err := uc.File()
    50  	if err != nil {
    51  		ptyReplica.Close()
    52  		return nil, fmt.Errorf("getting file for unix socket %v: %v", uc, err)
    53  	}
    54  	defer socket.Close()
    55  
    56  	// Send the master FD over the connection.
    57  	msg := unix.UnixRights(int(ptyMaster.Fd()))
    58  	if err := unix.Sendmsg(int(socket.Fd()), []byte("pty-master"), msg, nil, 0); err != nil {
    59  		ptyReplica.Close()
    60  		return nil, fmt.Errorf("sending console over unix socket %q: %v", socketPath, err)
    61  	}
    62  	return ptyReplica, nil
    63  }