1 /***************************************************************************
2 * Copyright (C) 2008 by Intra2net AG - Thomas Jarosch *
3 * thomas.jarosch@intra2net.com *
4 * http://www.intra2net.com *
5 ***************************************************************************/
14 #include "daemonfunc.hpp"
15 #include "stringfunc.hxx"
16 #include "filefunc.hxx"
27 * Fork into the background.
35 throw runtime_error("fork() failed");
42 // pid==0 -> child process: continue
46 * Drop root privileges
47 * @param username User to become. Don't change user if empty
48 * @param group Group to become. Don't change group if empty
49 * @param get_group_from_user Get group GID from user information if group is empty.
50 * @return true if all is fine, false otherwise
52 bool drop_root_privileges(const std::string &username,
53 const std::string &group, bool get_group_from_user)
57 Group my_group(group);
58 if (!my_group.is_valid())
61 if (setgid((my_group.Gid)))
65 if (!username.empty())
67 User my_user(username);
68 if (!my_user.is_valid())
71 if (get_group_from_user && group.empty())
73 if (setgid((my_user.Gid)))
77 if (setuid(my_user.Uid))
85 * @brief determine the pids for a given program
86 * @param[in] name name (or full path) of the binary
87 * @param[out] result the pids associated with the name.
88 * @return @a true if the function performed without errors.
90 * Walk though the /proc/\<pid\>'s and search for the name.
92 * @note Since this function uses /proc, it's system specific. Currently:
95 * @todo check cmdline and stat in /proc/\<pid\> dir for the searched name.
97 bool pid_of(const std::string& name, std::vector< pid_t >& result)
99 std::vector< std::string > entries;
100 std::vector< pid_t > fuzz1_result;
101 std::vector< pid_t > fuzz2_result;
103 if (!get_dir("/proc", entries)) return false;
104 for (std::vector< std::string >::const_iterator it= entries.begin();
109 if (! string_to<pid_t>(*it, pid)) continue;
110 std::string base_path= std::string("/proc/") + *it;
111 std::string exe_path= base_path + "/exe";
112 I2n::Stat stat(exe_path, false);
113 if (not stat or not stat.is_link()) continue;
114 std::string real_exe= read_link(exe_path);
115 if (real_exe == name)
117 result.push_back( pid );
121 std::string proc_stat= read_file( base_path + "/stat");
122 if (proc_stat.empty()) continue; // process vanished
124 //TODO some more fuzz tests here?! (cmdline, stat(us))
126 if (basename(real_exe) == name)
128 fuzz2_result.push_back(pid);
134 result.swap(fuzz1_result);
138 result.swap(fuzz2_result);
141 } // eo pidOf(const std::string&,std::vector< pid_t >&)