2 * Temporary debug code to find processes locking internal cryptsetup devices.
3 * This code is intended to run only in debug mode.
5 * inspired by psmisc/fuser proc scanning code
11 #include <sys/types.h>
17 #include "libcryptsetup.h"
20 #define MAX_PATHNAME 1024
21 #define MAX_SHORTNAME 64
23 static int numeric_name(const char *name)
25 return (name[0] < '0' || name[0] > '9') ? 0 : 1;
28 static int check_pid(const pid_t pid, const char *dev_name, const char *short_dev_name)
30 char dirpath[MAX_SHORTNAME], fdpath[MAX_SHORTNAME], linkpath[MAX_PATHNAME];
32 struct dirent *direntry;
36 snprintf(dirpath, sizeof(dirpath), "/proc/%d/fd", pid);
38 if (!(dirp = opendir(dirpath)))
41 while ((direntry = readdir(dirp))) {
42 if (!numeric_name(direntry->d_name))
45 snprintf(fdpath, sizeof(fdpath), "/proc/%d/fd/%s", pid, direntry->d_name);
47 if ((len = readlink(fdpath, linkpath, MAX_PATHNAME-1)) < 0)
51 if (!strcmp(dev_name, linkpath)) {
56 if (!strcmp(short_dev_name, linkpath)) {
65 static int read_proc_info(const pid_t pid, pid_t *ppid, char *name, int max_size)
67 char path[MAX_SHORTNAME], info[max_size], c;
70 snprintf(path, sizeof(path), "/proc/%u/stat", pid);
71 if ((fd = open(path, O_RDONLY)) < 0)
74 if (read(fd, info, max_size) > 0 &&
75 sscanf(info, "%d %s %c %d", &xpid, name, &c, ppid) == 4)
86 static void report_proc(const pid_t pid, const char *dev_name)
88 char name[MAX_PATHNAME], name2[MAX_PATHNAME];
91 if (read_proc_info(pid, &ppid, name, MAX_PATHNAME) &&
92 read_proc_info(ppid, &ppid2, name2, MAX_PATHNAME))
93 log_dbg("WARNING: Process PID %u %s [PPID %u %s] spying on internal device %s.",
94 pid, name, ppid, name2, dev_name);
97 void debug_processes_using_device(const char *dm_name)
99 char short_dev_name[MAX_SHORTNAME], dev_name[MAX_PATHNAME];
101 struct dirent *proc_dentry;
105 if (crypt_get_debug_level() != CRYPT_LOG_DEBUG)
108 snprintf(dev_name, sizeof(dev_name), "/dev/mapper/%s", dm_name);
109 if (stat(dev_name, &st) || !S_ISBLK(st.st_mode))
111 snprintf(short_dev_name, sizeof(short_dev_name), "/dev/dm-%u", minor(st.st_rdev));
113 if (!(proc_dir = opendir("/proc")))
116 while ((proc_dentry = readdir(proc_dir))) {
117 if (!numeric_name(proc_dentry->d_name))
120 pid = atoi(proc_dentry->d_name);
121 switch(check_pid(pid, dev_name, short_dev_name)) {
122 case 1: report_proc(pid, dev_name);
124 case 2: report_proc(pid, short_dev_name);