gpt4 book ai didi

c - C中如何将相对路径转换为绝对路径?

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:00 24 4
gpt4 key购买 nike

我正在尝试制作一个 suid 应用程序,它将只执行位于受限文件夹中的 ruby​​ 脚本。我曾尝试使用 realpath(3) 来执行此操作,但它仅返回路径的第一段。下面是我的代码...

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

#define SUEXEC_STR_LEN 2048
#define RUBY_APP "/usr/bin/ruby"
#define DIRECTORY_SEPARATOR "/"

static void safepath(const char *path_in, char * path_out, int outlen) {
realpath(path_in, path_out);
}

int main ( int argc, char *argv[] )
{
char cmd[SUEXEC_STR_LEN];
char path_out[SUEXEC_STR_LEN];
char path_in[SUEXEC_STR_LEN];

char *cp = &cmd[0];

strncpy(cp, RUBY_APP, SUEXEC_STR_LEN - 1);

strncpy(path_in, DIRECTORY_SEPARATOR, SUEXEC_STR_LEN - 1);
strncat(path_in,argv[1],SUEXEC_STR_LEN - 1);

safepath(path_in,path_out,SUEXEC_STR_LEN - 1);

printf("path_in=%s path_out=%s\n",path_in,path_out);

setuid( 0 );
// system( cmd );

return 0;
}

这是我得到的结果的一个例子

root@server01:/root/src# ./a.out foo/bar/../test
path_in=/foo/bar/../test path_out=/foo

这就是我想要的结果

root@server01:/root/src# ./a.out foo/bar/../test
path_in=/foo/bar/../test path_out=/foo/test

最佳答案

您应该检查 realpath() 的返回值。如其 man page 中所述,

RETURN VALUE
If there is no error, realpath() returns a pointer to the resolved_path.

Otherwise it returns a NULL pointer, and the contents of the array resolved_path are undefined. The global variable errno is set to indicate the error.

也在其手册页的错误部分,

ENOENT The named file does not exist.

因此,如果您的文件系统中确实没有/foo/testrealpath() 应该返回NULL 并且输出是未定义。

关于c - C中如何将相对路径转换为绝对路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22381647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com