github.com/mutagen-io/mutagen@v0.18.0-rc1/pkg/ipc/ipc_posix.go (about)

     1  //go:build !windows
     2  
     3  package ipc
     4  
     5  import (
     6  	"context"
     7  	"fmt"
     8  	"net"
     9  	"os"
    10  )
    11  
    12  // DialContext attempts to establish an IPC connection, timing out if the
    13  // provided context expires.
    14  func DialContext(ctx context.Context, path string) (net.Conn, error) {
    15  	// Create a zero-valued dialer, which will have the same dialing behavior as
    16  	// the raw dialing functions.
    17  	dialer := &net.Dialer{}
    18  
    19  	// Perform dialing.
    20  	return dialer.DialContext(ctx, "unix", path)
    21  }
    22  
    23  // NewListener creates a new IPC listener.
    24  func NewListener(path string) (net.Listener, error) {
    25  	// Create the listener.
    26  	listener, err := net.Listen("unix", path)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	// Explicitly set socket permissions. Unfortunately we can't do this
    32  	// atomically on socket creation, but we can do it quickly.
    33  	if err := os.Chmod(path, 0600); err != nil {
    34  		listener.Close()
    35  		return nil, fmt.Errorf("unable to set socket permissions: %w", err)
    36  	}
    37  
    38  	// Success.
    39  	return listener, nil
    40  }