1 /***************************************************************************
2 * Copyright (C) 2008 by Intra2net AG - Thomas Jarosch *
3 * thomas.jarosch@intra2net.com *
4 * http://www.intra2net.com *
5 ***************************************************************************/
13 #include "daemonfunc.hxx"
14 #include "stringfunc.hxx"
15 #include "filefunc.hxx"
17 // TODO: Remove me once libi2ncommon is completly switched to I2n
28 * Fork into the background.
36 throw runtime_error("fork() failed");
43 // pid==0 -> child process: continue
47 * Drop root privileges
48 * @param username User to become. Don't change user if empty
49 * @param group Group to become. Don't change group if empty
51 void drop_root_privileges(const std::string &username,
52 const std::string &group)
56 if (setgid(daemon::lookup_gid(group))) {
57 throw runtime_error("Can't change to group " + group);
61 if (!username.empty()) {
62 if (setuid(daemon::lookup_uid(username))) {
63 throw runtime_error("Can't change to user " + username);
70 * @brief determine the pids for a given program
71 * @param[in] name name (or full path) of the binary
72 * @param[out] result the pids associated with the name.
73 * @return @a true if the function performed without errors.
75 * Walk though the /proc/\<pid\>'s and search for the name.
77 * @note Since this function uses /proc, it's system specific. Currently:
80 * @todo check cmdline and stat in /proc/\<pid\> dir for the searched name.
82 bool pid_of(const std::string& name, std::vector< pid_t >& result)
84 std::vector< std::string > entries;
85 std::vector< pid_t > fuzz1_result;
86 std::vector< pid_t > fuzz2_result;
88 if (!get_dir("/proc", entries)) return false;
89 for(std::vector< std::string >::const_iterator it= entries.begin();
94 if (! string_to<pid_t>(*it, pid)) continue;
95 std::string base_path= std::string("/proc/") + *it;
96 std::string exe_path= base_path + "/exe";
97 I2n::Stat stat(exe_path, false);
98 if (not stat or not stat.is_link()) continue;
99 std::string real_exe= read_link(exe_path);
100 if (real_exe == name)
102 result.push_back( pid );
106 std::string proc_stat= read_file( base_path + "/stat");
107 if (proc_stat.empty()) continue; // process vanished
109 //TODO some more fuzz tests here?! (cmdline, stat(us))
111 if (basename(real_exe) == name)
113 fuzz2_result.push_back(pid);
119 result.swap(fuzz1_result);
123 result.swap(fuzz2_result);
126 } // eo pidOf(const std::string&,std::vector< pid_t >&)