github.com/Lephar/snapd@v0.0.0-20210825215435-c7fba9cef4d2/usersession/userd/helpers.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2017 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package userd
    21  
    22  import (
    23  	"fmt"
    24  
    25  	"github.com/godbus/dbus"
    26  
    27  	"github.com/snapcore/snapd/sandbox/cgroup"
    28  )
    29  
    30  var snapFromSender = snapFromSenderImpl
    31  
    32  func snapFromSenderImpl(conn *dbus.Conn, sender dbus.Sender) (string, error) {
    33  	pid, err := connectionPid(conn, sender)
    34  	if err != nil {
    35  		return "", fmt.Errorf("cannot get connection pid: %v", err)
    36  	}
    37  	snap, err := cgroup.SnapNameFromPid(pid)
    38  	if err != nil {
    39  		return "", fmt.Errorf("cannot find snap for connection: %v", err)
    40  	}
    41  	// Check that the sender is still connected to the bus: if it
    42  	// has disconnected between the GetConnectionUnixProcessID
    43  	// call and when we poked around in /proc, then it is possible
    44  	// that the process ID was reused.
    45  	if !nameHasOwner(conn, sender) {
    46  		return "", fmt.Errorf("sender is no longer connected to the bus")
    47  	}
    48  	return snap, nil
    49  }
    50  
    51  func connectionPid(conn *dbus.Conn, sender dbus.Sender) (pid int, err error) {
    52  	call := conn.BusObject().Call("org.freedesktop.DBus.GetConnectionUnixProcessID", 0, sender)
    53  	if call.Err != nil {
    54  		return 0, call.Err
    55  	}
    56  	call.Store(&pid)
    57  	return pid, nil
    58  }
    59  
    60  func nameHasOwner(conn *dbus.Conn, sender dbus.Sender) bool {
    61  	call := conn.BusObject().Call("org.freedesktop.DBus.NameHasOwner", 0, sender)
    62  	if call.Err != nil {
    63  		return false
    64  	}
    65  	var hasOwner bool
    66  	call.Store(&hasOwner)
    67  	return hasOwner
    68  }