github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/supervisor/daemon/transport/transport_linux.go (about)

     1  /*
     2   * Copyright (C) 2020 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package transport
    19  
    20  import (
    21  	"fmt"
    22  	"net"
    23  	"os"
    24  	"strconv"
    25  
    26  	"github.com/rs/zerolog/log"
    27  )
    28  
    29  const sock = "/run/myst.sock"
    30  
    31  // Start starts a listener on a unix domain socket.
    32  // Conversation is handled by the handlerFunc.
    33  func Start(handle handlerFunc, options Options) error {
    34  	if err := os.RemoveAll(sock); err != nil {
    35  		return fmt.Errorf("could not remove sock: %w", err)
    36  	}
    37  	l, err := net.Listen("unix", sock)
    38  	if err != nil {
    39  		return fmt.Errorf("error listening: %w", err)
    40  	}
    41  	numUid, err := strconv.Atoi(options.Uid)
    42  	if err != nil {
    43  		return fmt.Errorf("failed to parse uid %s: %w", options.Uid, err)
    44  	}
    45  	if err := os.Chown(sock, numUid, -1); err != nil {
    46  		return fmt.Errorf("failed to chown supervisor socket to uid %s: %w", options.Uid, err)
    47  	}
    48  	if err := os.Chmod(sock, 0766); err != nil {
    49  		return fmt.Errorf("failed to chmod supervisor socket: %w", err)
    50  	}
    51  	defer func() {
    52  		if err := l.Close(); err != nil {
    53  			log.Err(err).Msg("Error closing listener")
    54  		}
    55  	}()
    56  	log.Info().Msg("Waiting for connections...")
    57  	for {
    58  		conn, err := l.Accept()
    59  		if err != nil {
    60  			return fmt.Errorf("accept error: %w", err)
    61  		}
    62  		go func() {
    63  			peer := conn.RemoteAddr().Network()
    64  			log.Debug().Msgf("Client connected: %s", peer)
    65  			handle(conn)
    66  			if err := conn.Close(); err != nil {
    67  				log.Err(err).Msgf("Error closing connection for: %v", peer)
    68  			}
    69  			log.Debug().Msgf("Client disconnected: %s", peer)
    70  		}()
    71  	}
    72  }