1/* 2 * Copyright (c) 2006 Cisco Systems, Inc. All rights reserved. 3 * 4 * This software is available to you under a choice of one of two 5 * licenses. You may choose to be licensed under the terms of the GNU 6 * General Public License (GPL) Version 2, available from the file 7 * COPYING in the main directory of this source tree, or the 8 * OpenIB.org BSD license below: 9 * 10 * Redistribution and use in source and binary forms, with or 11 * without modification, are permitted provided that the following 12 * conditions are met: 13 * 14 * - Redistributions of source code must retain the above 15 * copyright notice, this list of conditions and the following 16 * disclaimer. 17 * 18 * - Redistributions in binary form must reproduce the above 19 * copyright notice, this list of conditions and the following 20 * disclaimer in the documentation and/or other materials 21 * provided with the distribution. 22 * 23 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 24 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 25 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 26 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 27 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 28 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 29 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 30 * SOFTWARE. 31 */ 32 33#if HAVE_CONFIG_H 34# include <config.h> 35#endif /* HAVE_CONFIG_H */ 36 37#include <stdio.h> 38#include <stdlib.h> 39#include <unistd.h> 40#include <sys/types.h> 41#include <sys/stat.h> 42#include <fcntl.h> 43#include <string.h> 44 45#include <sys/sysctl.h> 46 47#include "ibverbs.h" 48 49static char *sysfs_path; 50 51const char *ibv_get_sysfs_path(void) 52{ 53 char *env = NULL; 54 55 if (sysfs_path) 56 return sysfs_path; 57 58 /* 59 * Only follow use path passed in through the calling user's 60 * environment if we're not running SUID. 61 */ 62 if (getuid() == geteuid()) 63 env = getenv("SYSFS_PATH"); 64 65 if (env) { 66 int len; 67 68 sysfs_path = strndup(env, IBV_SYSFS_PATH_MAX); 69 len = strlen(sysfs_path); 70 while (len > 0 && sysfs_path[len - 1] == '/') { 71 --len; 72 sysfs_path[len] = '\0'; 73 } 74 } else 75 sysfs_path = "/sys"; 76 77 return sysfs_path; 78} 79 80int ibv_read_sysfs_file(const char *dir, const char *file, 81 char *buf, size_t size) 82{ 83 char *path, *s; 84 int fd; 85 size_t len; 86 87 if (asprintf(&path, "%s/%s", dir, file) < 0) 88 return -1; 89 90 for (s = &path[0]; *s != '\0'; s++) 91 if (*s == '/') 92 *s = '.'; 93 94 len = size; 95 if (sysctlbyname(&path[1], buf, &len, NULL, 0) == -1) 96 return -1; 97 98 free(path); 99 100 if (len > 0 && buf[len - 1] == '\n') 101 buf[--len] = '\0'; 102 103 return len; 104} 105