github.com/kubiko/snapd@v0.0.0-20201013125620-d4f3094d9ddf/cmd/snap-confine/cookie-support.c (about)

     1  /*
     2   * Copyright (C) 2017 Canonical Ltd
     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 version 3 as
     6   * published by the Free Software Foundation.
     7   *
     8   * This program is distributed in the hope that it will be useful,
     9   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    10   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11   * GNU General Public License for more details.
    12   *
    13   * You should have received a copy of the GNU General Public License
    14   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15   *
    16   */
    17  
    18  #include "cookie-support.h"
    19  
    20  #include "../libsnap-confine-private/cleanup-funcs.h"
    21  #include "../libsnap-confine-private/string-utils.h"
    22  #include "../libsnap-confine-private/utils.h"
    23  
    24  #include "config.h"
    25  
    26  #include <errno.h>
    27  #include <fcntl.h>
    28  #include <string.h>
    29  #include <sys/types.h>
    30  #include <sys/stat.h>
    31  #include <unistd.h>
    32  
    33  #define SC_COOKIE_DIR "/var/lib/snapd/cookie"
    34  
    35  /**
    36   * Effective value of SC_COOKIE_DIR
    37   **/
    38  static const char *sc_cookie_dir = SC_COOKIE_DIR;
    39  
    40  char *sc_cookie_get_from_snapd(const char *snap_name, struct sc_error **errorp)
    41  {
    42  	char context_path[PATH_MAX] = { 0 };
    43  	struct sc_error *err = NULL;
    44  	char *context = NULL;
    45  
    46  	sc_must_snprintf(context_path, sizeof(context_path), "%s/snap.%s",
    47  			 sc_cookie_dir, snap_name);
    48  	int fd SC_CLEANUP(sc_cleanup_close) = -1;
    49  	fd = open(context_path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
    50  	if (fd < 0) {
    51  		err =
    52  		    sc_error_init_from_errno(errno,
    53  					     "warning: cannot open cookie file %s",
    54  					     context_path);
    55  		goto out;
    56  	}
    57  	// large enough buffer for opaque cookie string
    58  	char context_val[255] = { 0 };
    59  	ssize_t n = read(fd, context_val, sizeof(context_val) - 1);
    60  	if (n < 0) {
    61  		err =
    62  		    sc_error_init_from_errno(errno,
    63  					     "cannot read cookie file %s",
    64  					     context_path);
    65  		goto out;
    66  	}
    67  	context = strndup(context_val, n);
    68  	if (context == NULL) {
    69  		die("cannot duplicate snap cookie value");
    70  	}
    71  
    72   out:
    73  	sc_error_forward(errorp, err);
    74  	return context;
    75  }