我目前正在用C语言编写一个基于UNIX套接字的HTTP服务器,我即将实现GET请求中检查所请求文件的部分,以确保它具有适当的权限。
在我对HTTP服务器有所了解之前,我设置了一个Apache服务器,我的理解是HTTP服务器只有一个目录可以找到所请求的文件。我不知道这是因为服务器在某种程度上没有目录之外的权限,或者它是否实际验证了路径以确保它在目录中。
现在我要自己实现这个,我不知道如何妥善处理这个问题。 C中是否有一个函数可以让我确定一个路径是否在给定目录中(例如foo/bar/../../baz
内是foo/
)?
在python中,我会使用os.path.relpath
并检查结果是否以..
开头,以确保路径不在给定目录之外。
例如,如果目录是/foo/bar/htdocs
,并且给定的路径是index.html/../../passwords.txt
,我想要../passwords.txt
,所以我可以从前导{ {1}}该文件位于..
目录之外。
答案 0 :(得分:1)
你会惊讶于Python的I / O功能或多或少直接映射到POSIX可以做什么。 :)
换句话说,查看realpath()
。
当POSIX具有函数的更具描述性的名称时,它非常棒,包含了额外的字母! :)
答案 1 :(得分:0)
How to get the absolute path for a given relative path programmatically in Linux?
#include <stdlib.h>
#include <stdio.h>
int main()
{
char resolved_path[100];
realpath("../../", resolved_path);
printf("\n%s\n",resolved_path);
return 0;
}
你可以试试。同样的ser(放松)在那里回答。
答案 2 :(得分:0)
它的工作方式更简单:一旦服务器收到请求,它只查看其htdoc(静态内容)目录以检查所请求的资源是否存在:
char *htdoc = "/opt/server/htdoc"; // here a sub-directory of the server program
char *request = "GET /index.html"; // the client request
char *req_path = strchr(request, ' ') + 1; // the URI path
char filepath[512]; // build the file-system path
snprintf(filepath, sizeof(filepath) - 1, "%s/%s", htdos, req_path);
FILE *f = fopen(filepath, "r"); // try to open the file
...
请注意,此代码不安全,因为它不会通过包含“../”模式(以及其他技巧)来检查请求是否在文件系统中冒险。您还应该使用stat()
来确保该文件是常规文件,并且服务器有权读取它。
答案 3 :(得分:0)
作为一个简单(但不完整)的解决方案,我刚刚决定编写一些代码来检查任何..
的文件路径。
int is_valid_fname(char *fname) {
char *it = fname;
while(TRUE) {
if (strncmp(it, "..", 2) == 0) {
return FALSE;
}
it = strchr(it, '/');
if (it == NULL) break;
it++;
}
return TRUE;
}