在Debian系統中,readdir
函數用于讀取目錄的內容。為了提高使用readdir
函數時的安全性,可以采取以下措施:
realpath
函數來解析符號鏈接,防止用戶通過相對路徑或特殊字符(如../
)訪問到不應該訪問的目錄。#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <limits.h>
char *safe_realpath(const char *path) {
char *resolved_path = realpath(path, NULL);
if (resolved_path == NULL) {
perror("realpath");
return NULL;
}
return resolved_path;
}
readdir
后,檢查其返回值是否為NULL
,以確保沒有發生錯誤。DIR *dir = opendir("/path/to/directory");
if (dir == NULL) {
perror("opendir");
// Handle error appropriately
exit(EXIT_FAILURE);
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Process each entry
}
if (closedir(dir) == -1) {
perror("closedir");
// Handle error appropriately
}
opendir_r
(線程安全的版本)。以下是一個綜合了上述安全措施的示例代碼:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <limits.h>
#include <sys/stat.h>
#include <unistd.h>
char *safe_realpath(const char *path) {
char *resolved_path = realpath(path, NULL);
if (resolved_path == NULL) {
perror("realpath");
return NULL;
}
return resolved_path;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
char *dir_path = argv[1];
char *resolved_dir = safe_realpath(dir_path);
if (resolved_dir == NULL) {
return EXIT_FAILURE;
}
DIR *dir = opendir(resolved_dir);
if (dir == NULL) {
perror("opendir");
free(resolved_dir);
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Process each entry
printf("%s\n", entry->d_name);
}
if (closedir(dir) == -1) {
perror("closedir");
free(resolved_dir);
return EXIT_FAILURE;
}
free(resolved_dir);
return EXIT_SUCCESS;
}
通過這些措施,可以顯著提高使用readdir
函數時的安全性。