示例#1
0
ERRORCODE_T AbsolutizeAndSimplifyPathname(
    const char *pPathname,const char *pBaseDirectory,char **ppResolved)
{
  ERRORCODE_T ErrorCode;
  char *pLongPathname;


  DEBUGLOG_Printf5("AbsolutizeAndSimplifyPathname(%p(%s),%p(%s),%p)",
      pPathname,pPathname,pBaseDirectory,pBaseDirectory,ppResolved);
  DEBUGLOG_LogIn();

  /* Parameter checking. */
  if ( (pPathname==NULL) || (ppResolved==NULL) )
    ErrorCode=ERRORCODE_NULLPARAMETER;
  else
  {
    /* Check if the relative pathname is actually absolute. */
    if (*pPathname==DIRECTORY_SEPARATOR_CHAR)
    {
      /* Relative pathname is actually an absolute pathname. Only
          canonicalize the "relative" pathname. */
      *ppResolved=canonicalize_file_name(pPathname);
      if (*ppResolved==NULL)
        ErrorCode=ERRORCODE_SYSTEMFAILURE;
      else
        ErrorCode=ERRORCODE_SUCCESS;
    }
    else
    {
      /* Got a relative pathname. Make sure base is absolute. */
      if (pBaseDirectory==NULL)
          ErrorCode=ERRORCODE_NULLPARAMETER;
      else
      {
        /* Make sure the base pathname is absolute. */
        if (*pBaseDirectory!=DIRECTORY_SEPARATOR_CHAR)
          ErrorCode=ERRORCODE_INVALIDDATA;
        else
        {
          /* Combine directory and relative path. */
          if (asprintf(&pLongPathname,"%s/%s",pBaseDirectory,pPathname)==-1)
          {
            *ppResolved=NULL;
            ErrorCode=ERRORCODE_SYSTEMFAILURE;
          }
          else
          {
            *ppResolved=canonicalize_file_name(pLongPathname);
            free((char*)pLongPathname);
            ErrorCode=ERRORCODE_SUCCESS;
          }
        }
      }
    }
  }

  DEBUGLOG_LogOut();
  return(ErrorCode);
}
示例#2
0
bool SyscallPolicy::hasPermissionForPath(const char* path, Permission permission) const
{
    // The root directory policy needs to be set because it is the
    // ultimate fallback when rewinding directories.
    ASSERT(m_directoryPermission.contains("/"));

    if (permission == NotAllowed)
        return false;

    char* basePath = strdup(path);
    char* canonicalPath = canonicalize_file_name(basePath);

    while (canonicalPath) {
        struct stat pathStat;
        if (stat(canonicalPath, &pathStat) == -1) {
            free(basePath);
            free(canonicalPath);
            return false;
        }

        if (S_ISDIR(pathStat.st_mode))
            break;

        PermissionMap::const_iterator policy = m_filePermission.find(String(canonicalPath));
        if (policy != m_filePermission.end()) {
            free(basePath);
            free(canonicalPath);
            return (permission & policy->value) == permission;
        }

        // If not a directory neither a file with a policy defined,
        // we set canonicalPath to zero to force a rewind to the parent
        // directory.
        free(canonicalPath);
        canonicalPath = 0;
    }

    while (!canonicalPath) {
        char* currentBaseDirectory = dirname(basePath);
        canonicalPath = canonicalize_file_name(currentBaseDirectory);
    }

    PermissionMap::const_iterator policy = m_directoryPermission.find(String(canonicalPath));
    while (policy == m_directoryPermission.end()) {
        char* currentBaseDirectory = dirname(canonicalPath);
        policy = m_directoryPermission.find(String(currentBaseDirectory));
    }

    free(basePath);
    free(canonicalPath);

    if ((permission & policy->value) == permission)
        return true;

    // Don't warn if the file doesn't exist at all.
    if (!access(path, F_OK) || errno != ENOENT)
        fprintf(stderr, "Blocked impermissible %s access to %s\n", SyscallPolicy::permissionToString(permission), path);
    return false;
}
示例#3
0
文件: delta.c 项目: RoadRunnr/systemd
static int equivalent(const char *a, const char *b) {
        _cleanup_free_ char *x = NULL, *y = NULL;

        x = canonicalize_file_name(a);
        if (!x)
                return -errno;

        y = canonicalize_file_name(b);
        if (!y)
                return -errno;

        return path_equal(x, y);
}
示例#4
0
static void eval_link(char *pid, char *link_rel, enum field field, char **ptr,
    char *format_str, struct obstack *mem_pool)
{
    char *link_file, *link;
    
    /* path to the link file like. /proc/{pid}/{link_rel} */
    link_file = proc_pid_file(pid, link_rel, mem_pool);

    /* It's okay to use canonicalize_file_name instead of readlink on linux
     * for the cwd symlink, since on linux the links we care about will never
     * be relative links (cwd, exec) 
     * Doing this because readlink works on static buffers */
    link = canonicalize_file_name(link_file);

    /* we no longer need need the path to the link file */
    obstack_free(mem_pool, link_file);

    if (link == NULL)
        return;

    /* copy the path onto our obstack, set the value (somewhere in pts)
     * and free the results of canonicalize_file_name */
    obstack_printf(mem_pool, link);
    obstack_1grow(mem_pool, '\0');

    *ptr = (char *) obstack_finish(mem_pool);
    free(link);

    /* enable whatever field we successfuly retrived */
    field_enable(format_str, field);
}
示例#5
0
static void set_game_filename(const char *name)
{
  n_free(game_filename);
  game_filename = 0;

#if defined(_GNU_SOURCE)
  game_filename = canonicalize_file_name(name);
#else
#if defined(_BSD_SOURCE) || defined(_XOPEN_SOURCE)
  game_filename = (char *) n_malloc(PATH_MAX);
  if(!realpath(name, game_filename)) {
    n_free(game_filename);
    game_filename = 0;
  }
#else
#ifdef __DJGPP__
  game_filename = (char *) n_malloc(FILENAME_MAX);
  _fixpath(name, game_filename);
#endif
#endif
#endif

  if(!game_filename)
    game_filename = n_strdup(name);
}
示例#6
0
文件: relink.c 项目: 2ion/scripts
int main(int argc, char **argv) {
    struct stat buf;
    char *tpath;
    if (argc != 3) {
        fprintf(stderr, "Too few arguments. Usage: relink <symlink> <new-target>\n");
        return EXIT_FAILURE;
    }
    if (lstat(argv[1], &buf) != 0) {
        fprintf(stderr, "Can not read file: %s\n", argv[1]);
        return EXIT_FAILURE;
    }
    if (access(argv[2], F_OK) != 0) {
        fprintf(stderr, "Can not symlink to a non-existent file: %s\n", argv[2]);
        return EXIT_FAILURE;
    }
    if (S_ISLNK(buf.st_mode) == 0) {
        fprintf(stderr, "Can not relink a non-symlink: %s\n", argv[1]);
        return EXIT_FAILURE;
    }
    if (unlink(argv[1]) != 0) {
        fprintf(stderr, "Could not unlink symlink: %s\n", argv[1]);
        return EXIT_FAILURE;
    }
    if ((tpath = canonicalize_file_name(argv[2])) == NULL) {
        fprintf(stderr, "canonicalize_file_name() failed\n");
        return EXIT_FAILURE;
    }
    if (symlink(argv[2], tpath) != 0) {
        fprintf(stderr, "symlink() failed\n");
        free(tpath);
        return EXIT_FAILURE;
    }
    free(tpath);
    return EXIT_SUCCESS;
}
示例#7
0
/* Return the canonical name of DIR in malloc'd storage.  */
static char *
get_name (char const *dir)
{
  char *result;
  if (REPLACE_OPEN_DIRECTORY || !HAVE_CANONICALIZE_FILE_NAME)
    {
      /* The function canonicalize_file_name has not yet been ported
         to mingw, with all its drive letter and backslash quirks.
         Fortunately, getcwd is reliable in this case, but we ensure
         we can get back to where we started before using it.  Treat
         "." as a special case, as it is frequently encountered.  */
      char *cwd = getcwd (NULL, 0);
      int saved_errno;
      if (dir[0] == '.' && dir[1] == '\0')
        return cwd;
      if (chdir (cwd))
        return NULL;
      result = chdir (dir) ? NULL : getcwd (NULL, 0);
      saved_errno = errno;
      if (chdir (cwd))
        abort ();
      free (cwd);
      errno = saved_errno;
    }
  else
    {
      /* Avoid changing the directory.  */
      result = canonicalize_file_name (dir);
    }
  return result;
}
示例#8
0
int verify_file(const char *filename) {
  char *buffer = malloc(100);
  char *canonicalized_filename = malloc(100);

  /* 
    This function canonicalizes all user input. Ensure that this is used, followed by white list validation and then processing of the file.
    In this case, it will strip all the ../ characters or resolve the soft link and reveal the actual path that is used.
  */
  canonicalized_filename = canonicalize_file_name(filename);
  printf("%s\n", canonicalized_filename);

  /*
    Do validation here... before the file is actually opened. Maybe stuff like, the file needs to be opened must exist in a specific directory.
    That would result in a failed attempt to open /etc/passwd.
  */
  FILE *fd = fopen(filename, "r");
  if (fd == NULL) {
    printf("File cannot be opened\n");
  }
  else {
    fread(buffer, 2, 100, fd);
    printf("%s\n",buffer);
  }
  return 0;
}
示例#9
0
void DynamoModelLoader::load(char* srcpath) {
    int status;
    char *path;

    path = canonicalize_file_name(srcpath);
    QString model_name = QString(path);
    model_name.remove(MODEL_SOURCE_SUFFIX);

    if (model_name.isNull() || model_name.isEmpty())
        return;

    if (model_makefile_path.isNull() || model_makefile_path.isEmpty()) {
        ERROR_MSG("invalid model makefile name\n");
        return;
    }

    QString cmd = QString("cd %1; %2 %3 %4%5") .arg(getcwd(NULL, 0)) .arg(
                      MAKE_CMD_PREFIX) .arg(model_makefile_path) .arg(model_name) .arg(
                      MODEL_SUFFIX);

    QString module_name = QString("%1%2") .arg(model_name) .arg(MODEL_SUFFIX);

    DEBUG_MSG("about to compile model with command %s\n", cmd.toLatin1().constData());
    status = CmdLine::getInstance()->execute(cmd.toStdString());

    if (status != 0) {
        ERROR_MSG("build process error\n");
        return;
    }

    Plugin::Manager::getInstance()->load(module_name.toLatin1());

    if (path != NULL)
        free(path);
}
示例#10
0
static void scan_playlist(struct uade_config *uc)
{
  struct playlist_iterator pli;
  char *songfile;
  struct uade_state state = {.config = *uc};

  playlist_iterator(&pli, &uade_playlist);

  while (1) {
    songfile = playlist_iterator_get(&pli);
    if (songfile == NULL)
      break;

    if (!uade_is_our_file(songfile, 1, &state))
      continue;

    songfile = canonicalize_file_name(songfile);

    if (songfile)
      printf("%s\n", songfile);

    free(songfile);
    songfile = NULL;
  }
}
示例#11
0
static char *
guess_efi_drive (const char *orig_path)
{
  char *canon;
  char *ptr;
  canon = canonicalize_file_name (orig_path);
  if (!canon)
    return NULL;
  ptr = strrchr (orig_path, '/');
  if (ptr)
    ptr++;
  else
    ptr = canon;
  if ((ptr[0] == 's' || ptr[0] == 'h') && ptr[1] == 'd')
    {
      int num = ptr[2] - 'a';
      free (canon);
      return xasprintf ("hd%d", num);
    }
  if (ptr[0] == 'f' && ptr[1] == 'd')
    {
      int num = atoi (ptr + 2);
      free (canon);
      return xasprintf ("fd%d", num);
    }
  free (canon);
  return NULL;
}
示例#12
0
/* Sets the original and the current installation prefix of this module.
   Relocation simply replaces a pathname starting with the original prefix
   by the corresponding pathname with the current prefix instead.  Both
   prefixes should be directory names without trailing slash (i.e. use ""
   instead of "/").  */
static char *
set_orig_prefix (const char *orig_prefix_arg)
{
      char *memory;
//	  printf ("orig_prefix_arg: %s\n", orig_prefix_arg);
	  if (!orig_prefix_arg) {
		orig_prefix = NULL;
		orig_prefix_len = 0;
		return NULL;
	  }
	  if (orig_prefix)
		  free (orig_prefix);

	  memory = canonicalize_file_name (orig_prefix_arg);
//	  printf ("memory: %s\n", memory);
//	  memory = (char *) malloc (orig_prefix_len + 1);
      if (!memory) {
	  	set_werrno;
		orig_prefix = NULL;
		orig_prefix_len = 0;
		return NULL;
      }
	  win2unixpath (memory);
//	  win2posixpath (orig_prefix_arg, memory);
	  orig_prefix = memory;
	  orig_prefix_len = strlen (orig_prefix);
//	  printf ("orig_prefix: %s\n", orig_prefix);
	  if (ISDIRSEP (orig_prefix[orig_prefix_len-1])) {
	  	orig_prefix[orig_prefix_len-1] = '\0';
	  	orig_prefix_len--;
	  }
//	  printf ("orig_prefix: %s\n", orig_prefix);
//	  printf ("orig_prefix_len: %d\n", orig_prefix_len);
	  return orig_prefix;
}
void SeccompFiltersWebProcessEfl::platformInitialize()
{
    // TODO: We should block all the syscalls and whitelist
    // what we need + trap what should be handled by the broker.
    addRule("open", Trap);
    addRule("openat", Trap);
    addRule("creat", Trap);

    // Needed by Eeze on NetworkStateNotifierEfl.
    m_policy.addDirectoryPermission(ASCIILiteral("/sys/bus"), SyscallPolicy::Read);
    m_policy.addDirectoryPermission(ASCIILiteral("/sys/class"), SyscallPolicy::Read);
    m_policy.addDirectoryPermission(ASCIILiteral("/sys/devices"), SyscallPolicy::Read);
    m_policy.addFilePermission(ASCIILiteral("/etc/udev/udev.conf"), SyscallPolicy::Read);

    // Place where the theme and icons are installed.
    char* dataDir = canonicalize_file_name(DATA_DIR);
    if (dataDir) {
        m_policy.addDirectoryPermission(String::fromUTF8(dataDir), SyscallPolicy::Read);
        free(dataDir);
    }

#if USE(GSTREAMER)
    // Video playback requires access to the root of the user cache dir which
    // is not right. We need to check with these directories on gstreamer
    // can be configured.
    char* homeDir = getenv("HOME");
    if (homeDir)
        m_policy.addDirectoryPermission(String::fromUTF8(homeDir) + "/.cache", SyscallPolicy::ReadAndWrite);
#endif

    SeccompBroker::launchProcess(this, m_policy);
}
示例#14
0
static char *
guess_baremetal_drive (const char *orig_path)
{
  char *canon;
  char *ptr;
  canon = canonicalize_file_name (orig_path);
  if (!canon)
    return NULL;
  ptr = strrchr (orig_path, '/');
  if (ptr)
    ptr++;
  else
    ptr = canon;
  if (ptr[0] == 'h' && ptr[1] == 'd')
    {
      int num = ptr[2] - 'a';
      free (canon);
      return xasprintf ("ata%d", num);
    }
  if (ptr[0] == 's' && ptr[1] == 'd')
    {
      int num = ptr[2] - 'a';
      free (canon);
      return xasprintf ("ahci%d", num);
    }
  free (canon);
  return NULL;
}
示例#15
0
char *
tr_sys_path_resolve (const char  * path,
                     tr_error   ** error)
{
  char * ret = NULL;
  char * tmp = NULL;

  assert (path != NULL);

#if defined (HAVE_CANONICALIZE_FILE_NAME)

  ret = canonicalize_file_name (path);

#endif

#if defined (_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200809L

  /* Better safe than sorry: realpath () officially supports NULL as destination
     starting off POSIX.1-2008. */

  if (ret == NULL)
    ret = realpath (path, NULL);

#endif

  if (ret == NULL)
    {
      tmp = tr_new (char, PATH_MAX);
      ret = realpath (path, tmp);
      if (ret != NULL)
        ret = tr_strdup (ret);
    }
示例#16
0
char *devt_to_devpath(dev_t dev)
{
	char device[46];

	sprintf(device, "/sys/dev/block/%d:%d/device", major(dev), minor(dev));
	return canonicalize_file_name(device);
}
示例#17
0
int cmd_cd(tok_t arg[])
{
    char* path = canonicalize_file_name(arg[0]);
    int ret = chdir(path);
    free(path);
    return ret;
    //return chdir(arg[0]);
}
示例#18
0
char *
SBCanonicalizePath(const char* mypath)
{	
	DBG("SBCanonicalizePath? %s\n", mypath);
	char *p = canonicalize_file_name(mypath);	
	DBG("SBCanonicalizePath! %s-> %s\n", mypath, s.c_str());
	return p;
}
示例#19
0
文件: ult_src.c 项目: Shivox/man-db
static char *find_include (const char *name, const char *path,
			   const char *include)
{
	char *ret;
	char *dirname;
	char *temp_file;

	/* Restore the original path from before ult_softlink() etc., in
	 * case it went outside the mantree.
	 */
	ret = xasprintf ("%s/%s", path, include);

	/* If the original path from above doesn't exist, try to create new
	 * path as if the "include" was relative to the current man page.
	 */
	if (access (ret, F_OK) == 0)
		return ret;

	dirname = dir_name (name);
	temp_file = xasprintf ("%s/%s", dirname, include);
	free (dirname);

	if (access (temp_file, F_OK) == 0) {
		/* Just plain include. */
		free (ret);
		ret = canonicalize_file_name (temp_file);
	} else {
		/* Try globbing - the file suffix might be missing. */
		char *temp_file_asterisk = xasprintf ("%s*", temp_file);
		char **candidate_files = expand_path (temp_file_asterisk);
		int i;

		free (temp_file_asterisk);
		if (access (candidate_files[0], F_OK) == 0) {
			free (ret);
			ret = canonicalize_file_name (candidate_files[0]);
		}
		for (i = 0; candidate_files[i]; i++)
			free (candidate_files[i]);
		free (candidate_files);
	}
	free (temp_file);

	return ret;
}
示例#20
0
static int directory_load(module_t *Module, const char *FileName) {
	struct stat Stat;
	stat(FileName, &Stat);
	if (S_ISDIR(Stat.st_mode)) {
		module_setup(Module, canonicalize_file_name(FileName), (module_importer)directory_import);
	} else {
		return 0;
	};
};
void SeccompFiltersWebProcessEfl::platformInitialize()
{
    // TODO: We should block all the syscalls and whitelist
    // what we need + trap what should be handled by the broker.
    addRule("open", Trap);
    addRule("openat", Trap);
    addRule("creat", Trap);

    // Needed by Eeze on NetworkStateNotifierEfl.
    m_policy.addDirectoryPermission(ASCIILiteral("/sys/bus"), SyscallPolicy::Read);
    m_policy.addDirectoryPermission(ASCIILiteral("/sys/class"), SyscallPolicy::Read);
    m_policy.addDirectoryPermission(ASCIILiteral("/sys/devices"), SyscallPolicy::Read);
    m_policy.addFilePermission(ASCIILiteral("/etc/udev/udev.conf"), SyscallPolicy::Read);

#ifdef SOURCE_DIR
    // Developers using build-webkit --efl expect some libraries to be loaded
    // from the build root directory and they also need access to layout test
    // files. The constant is defined only when jhbuild is detected, which is
    // an indication of a development build.
    char* sourceDir = canonicalize_file_name(SOURCE_DIR);
    if (sourceDir) {
        m_policy.addDirectoryPermission(String::fromUTF8(sourceDir), SyscallPolicy::ReadAndWrite);
        free(sourceDir);
    }
#endif

    // Place where the theme and icons are installed.
    char* dataDir = canonicalize_file_name(DATA_DIR);
    if (dataDir) {
        m_policy.addDirectoryPermission(String::fromUTF8(dataDir), SyscallPolicy::Read);
        free(dataDir);
    }

#if USE(GSTREAMER)
    // Video playback requires access to the root of the user cache dir which
    // is not right. We need to check with these directories on gstreamer
    // can be configured.
    char* homeDir = getenv("HOME");
    if (homeDir)
        m_policy.addDirectoryPermission(String::fromUTF8(homeDir) + "/.cache", SyscallPolicy::ReadAndWrite);
#endif

    SeccompBroker::launchProcess(this, m_policy);
}
示例#22
0
struct sys_dev *find_driver_devices(const char *bus, const char *driver)
{
	/* search sysfs for devices driven by 'driver' */
	char path[292];
	char link[256];
	char *c;
	DIR *driver_dir;
	struct dirent *de;
	struct sys_dev *head = NULL;
	struct sys_dev *list = NULL;

	sprintf(path, "/sys/bus/%s/drivers/%s", bus, driver);
	driver_dir = opendir(path);
	if (!driver_dir)
		return NULL;
	for (de = readdir(driver_dir); de; de = readdir(driver_dir)) {
		int n;

		/* is 'de' a device? check that the 'subsystem' link exists and
		 * that its target matches 'bus'
		 */
		sprintf(path, "/sys/bus/%s/drivers/%s/%s/subsystem",
			bus, driver, de->d_name);
		n = readlink(path, link, sizeof(link));
		if (n < 0 || n >= (int)sizeof(link))
			continue;
		link[n] = '\0';
		c = strrchr(link, '/');
		if (!c)
			continue;
		if (strncmp(bus, c+1, strlen(bus)) != 0)
			continue;

		/* start / add list entry */
		if (!head) {
			head = malloc(sizeof(*head));
			list = head;
		} else {
			list->next = malloc(sizeof(*head));
			list = list->next;
		}

		if (!list) {
			free_sys_dev(&head);
			break;
		}

		/* generate canonical path name for the device */
		sprintf(path, "/sys/bus/%s/drivers/%s/%s",
			bus, driver, de->d_name);
		list->path = canonicalize_file_name(path);
		list->next = NULL;
	}
	closedir(driver_dir);
	return head;
}
示例#23
0
static inline char *getdev(char *path, char *ent) {
        char *a, *b, *ret;
        
        asprintf(&a,"%s/%s",path,ent);
        b = canonicalize_file_name(a);
        ret = strdup(basename(b));
        free(b);
        free(a);
        return ret;
}
示例#24
0
static String canonicalizeFileName(const String& path)
{
    char* canonicalizedPath = canonicalize_file_name(path.utf8().data());
    if (canonicalizedPath) {
        String result = String::fromUTF8(canonicalizedPath);
        free(canonicalizedPath);
        return result;
    }
    return path;
}
示例#25
0
文件: journalctl.c 项目: adsr/systemd
static int add_matches(sd_journal *j, char **args) {
        char **i;
        int r;

        assert(j);

        STRV_FOREACH(i, args) {

                if (streq(*i, "+"))
                        r = sd_journal_add_disjunction(j);
                else if (path_is_absolute(*i)) {
                        char *p;
                        const char *path;
                        struct stat st;

                        p = canonicalize_file_name(*i);
                        path = p ? p : *i;

                        if (stat(path, &st) < 0)  {
                                free(p);
                                log_error("Couldn't stat file: %m");
                                return -errno;
                        }

                        if (S_ISREG(st.st_mode) && (0111 & st.st_mode)) {
                                char *t;

                                t = strappend("_EXE=", path);
                                if (!t) {
                                        free(p);
                                        log_error("Out of memory");
                                        return -ENOMEM;
                                }

                                r = sd_journal_add_match(j, t, 0);
                                free(t);
                        } else {
                                free(p);
                                log_error("File is not a regular file or is not executable: %s", *i);
                                return -EINVAL;
                        }

                        free(p);
                } else
                        r = sd_journal_add_match(j, *i, 0);

                if (r < 0) {
                        log_error("Failed to add match '%s': %s", *i, strerror(-r));
                        return r;
                }
        }

        return 0;
}
示例#26
0
static int get_sriov_function(const char *device_link,
                              struct pci_config_address **bdf)
{
    char *config_address = NULL;
    char *device_path = NULL;
    char errbuf[64];
    int ret = SRIOV_ERROR;

    VIR_DEBUG("Attempting to resolve device path from device link '%s'",
              device_link);

    if (!virFileExists(device_link)) {

        VIR_DEBUG("SR IOV function link '%s' does not exist", device_link);
        /* Not an SR IOV device, not an error, either. */
        ret = SRIOV_NOT_FOUND;

        goto out;

    }

    device_path = canonicalize_file_name (device_link);
    if (device_path == NULL) {
        memset(errbuf, '\0', sizeof(errbuf));
        VIR_ERROR(_("Failed to resolve device link '%s': '%s'"), device_link,
                  virStrerror(errno, errbuf, sizeof(errbuf)));
        goto out;
    }

    VIR_DEBUG("SR IOV device path is '%s'", device_path);
    config_address = basename(device_path);
    if (VIR_ALLOC(*bdf) != 0) {
        VIR_ERROR0(_("Failed to allocate memory for PCI device name"));
        goto out;
    }

    if (parse_pci_config_address(config_address, *bdf) != 0) {
        VIR_ERROR(_("Failed to parse PCI config address '%s'"), config_address);
        goto out;
    }

    VIR_DEBUG("SR IOV function %.4x:%.2x:%.2x.%.1x",
              (*bdf)->domain,
              (*bdf)->bus,
              (*bdf)->slot,
              (*bdf)->function);

    ret = SRIOV_FOUND;

out:
    VIR_FREE(device_path);
    return ret;
}
示例#27
0
/******************************************
 * Return canonical version of name in a malloc'd buffer.
 * This code is high risk.
 */
const char *FileName::canonicalName(const char *name)
{
#if __linux__
    // Lovely glibc extension to do it for us
    return canonicalize_file_name(name);
#elif POSIX
  #if _POSIX_VERSION >= 200809L || defined (__linux__)
    // NULL destination buffer is allowed and preferred
    return realpath(name, NULL);
  #else
    char *cname = NULL;
    #if PATH_MAX
        /* PATH_MAX must be defined as a constant in <limits.h>,
         * otherwise using it is unsafe due to TOCTOU
         */
        size_t path_max = (size_t)PATH_MAX;
        if (path_max > 0)
        {
            /* Need to add one to PATH_MAX because of realpath() buffer overflow bug:
             * http://isec.pl/vulnerabilities/isec-0011-wu-ftpd.txt
             */
            cname = (char *)malloc(path_max + 1);
            if (cname == NULL)
                return NULL;
        }
    #endif
    return realpath(name, cname);
  #endif
#elif _WIN32
    /* Apparently, there is no good way to do this on Windows.
     * GetFullPathName isn't it, but use it anyway.
     */
    DWORD result = GetFullPathName(name, 0, NULL, NULL);
    if (result)
    {
        char *buf = (char *)malloc(result);
        result = GetFullPathName(name, result, buf, NULL);
        if (result == 0)
        {
            ::free(buf);
            return NULL;
        }
        return buf;
    }
    return NULL;
#else
    assert(0);
    return NULL;
#endif
}
示例#28
0
gdb::unique_xmalloc_ptr<char>
gdb_realpath (const char *filename)
{
/* On most hosts, we rely on canonicalize_file_name to compute
   the FILENAME's realpath.

   But the situation is slightly more complex on Windows, due to some
   versions of GCC which were reported to generate paths where
   backlashes (the directory separator) were doubled.  For instance:
      c:\\some\\double\\slashes\\dir
   ... instead of ...
      c:\some\double\slashes\dir
   Those double-slashes were getting in the way when comparing paths,
   for instance when trying to insert a breakpoint as follow:
      (gdb) b c:/some/double/slashes/dir/foo.c:4
      No source file named c:/some/double/slashes/dir/foo.c:4.
      (gdb) b c:\some\double\slashes\dir\foo.c:4
      No source file named c:\some\double\slashes\dir\foo.c:4.
   To prevent this from happening, we need this function to always
   strip those extra backslashes.  While canonicalize_file_name does
   perform this simplification, it only works when the path is valid.
   Since the simplification would be useful even if the path is not
   valid (one can always set a breakpoint on a file, even if the file
   does not exist locally), we rely instead on GetFullPathName to
   perform the canonicalization.  */

#if defined (_WIN32)
  {
    char buf[MAX_PATH];
    DWORD len = GetFullPathName (filename, MAX_PATH, buf, NULL);

    /* The file system is case-insensitive but case-preserving.
       So it is important we do not lowercase the path.  Otherwise,
       we might not be able to display the original casing in a given
       path.  */
    if (len > 0 && len < MAX_PATH)
      return gdb::unique_xmalloc_ptr<char> (xstrdup (buf));
  }
#else
  {
    char *rp = canonicalize_file_name (filename);

    if (rp != NULL)
      return gdb::unique_xmalloc_ptr<char> (rp);
  }
#endif

  /* This system is a lost cause, just dup the buffer.  */
  return gdb::unique_xmalloc_ptr<char> (xstrdup (filename));
}
示例#29
0
void
_gl_register_fd (int fd, const char *filename)
{
  struct stat statbuf;

  ensure_dirs_slot (fd);
  if (fd < dirs_allocated
      && fstat (fd, &statbuf) >= 0 && S_ISDIR (statbuf.st_mode))
    {
      dirs[fd].name = canonicalize_file_name (filename);
      if (dirs[fd].name == NULL)
	dirs[fd].saved_errno = errno;
    }
}
int main (int argc, char *argv[]) {
    char *path;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s command\n", argv[0]);
        exit(2);
    }

    if ((path = canonicalize_file_name(argv[1])) == NULL) {
        perror("canonicalize_file_name");
        exit(1);
    }

    printf("%s\n", path);

    return 0;
}