1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/misc/CheckAccessDeleted.cc
13 #include <unordered_set>
14 #include "zypp/base/LogTools.h"
15 #include "zypp/base/String.h"
16 #include "zypp/base/Gettext.h"
17 #include "zypp/base/Exception.h"
19 #include "zypp/PathInfo.h"
20 #include "zypp/ExternalProgram.h"
21 #include "zypp/base/Regex.h"
22 #include "zypp/base/IOStream.h"
23 #include "zypp/base/InputStream.h"
25 #include "zypp/misc/CheckAccessDeleted.h"
29 #undef ZYPP_BASE_LOGGER_LOGGROUP
30 #define ZYPP_BASE_LOGGER_LOGGROUP "zypp::misc"
32 ///////////////////////////////////////////////////////////////////
34 { /////////////////////////////////////////////////////////////////
36 ///////////////////////////////////////////////////////////////////
38 { /////////////////////////////////////////////////////////////////
40 // lsof output lines are a sequence of NUL terminated fields,
41 // where the 1st char determines the fields type.
43 // (pcuL) pid command userid loginname
44 // (ftkn).filedescriptor type linkcount filename
46 /////////////////////////////////////////////////////////////////
48 /** lsof output line + files extracted so far for this PID */
49 typedef std::pair<std::string,std::unordered_set<std::string>> CacheEntry;
51 /** Add \c cache to \c data if the process is accessing deleted files.
52 * \c pid string in \c cache is the proc line \c (pcuLR), \c files
53 * are already in place. Always clear the \c cache.files!
55 inline void addDataIf( std::vector<CheckAccessDeleted::ProcInfo> & data_r, const CacheEntry & cache_r )
57 const auto & filelist( cache_r.second );
59 if ( filelist.empty() )
62 // at least one file access so keep it:
63 data_r.push_back( CheckAccessDeleted::ProcInfo() );
64 CheckAccessDeleted::ProcInfo & pinfo( data_r.back() );
65 pinfo.files.insert( pinfo.files.begin(), filelist.begin(), filelist.end() );
67 const std::string & pline( cache_r.first );
68 std::string commandname; // pinfo.command if still needed...
69 for_( ch, pline.begin(), pline.end() )
77 pinfo.ppid = &*(ch+1);
80 pinfo.puid = &*(ch+1);
83 pinfo.login = &*(ch+1);
86 if ( pinfo.command.empty() )
87 commandname = &*(ch+1);
90 if ( *ch == '\n' ) break; // end of data
91 do { ++ch; } while ( *ch != '\0' ); // skip to next field
94 if ( pinfo.command.empty() )
96 // the lsof command name might be truncated, so we prefer /proc/<pid>/exe
97 pinfo.command = filesystem::readlink( Pathname("/proc")/pinfo.pid/"exe" ).basename();
98 if ( pinfo.command.empty() )
99 pinfo.command = std::move(commandname);
104 /** Add file to cache if it refers to a deleted executable or library file:
105 * - Either the link count \c(k) is \c 0, or no link cout is present.
106 * - The type \c (t) is set to \c REG or \c DEL
107 * - The filedescriptor \c (f) is set to \c txt, \c mem or \c DEL
109 inline void addCacheIf( CacheEntry & cache_r, const std::string & line_r, bool verbose_r )
115 for_( ch, line_r.c_str(), ch+line_r.size() )
120 if ( *(ch+1) != '0' ) // skip non-zero link counts
133 if ( *ch == '\n' ) break; // end of data
134 do { ++ch; } while ( *ch != '\0' ); // skip to next field
137 if ( !t || !f || !n )
138 return; // wrong filedescriptor/type/name
140 if ( !( ( *t == 'R' && *(t+1) == 'E' && *(t+2) == 'G' && *(t+3) == '\0' )
141 || ( *t == 'D' && *(t+1) == 'E' && *(t+2) == 'L' && *(t+3) == '\0' ) ) )
142 return; // wrong type
144 if ( !( ( *f == 'm' && *(f+1) == 'e' && *(f+2) == 'm' && *(f+3) == '\0' )
145 || ( *f == 't' && *(f+1) == 'x' && *(f+2) == 't' && *(f+3) == '\0' )
146 || ( *f == 'D' && *(f+1) == 'E' && *(f+2) == 'L' && *(f+3) == '\0' )
147 || ( *f == 'l' && *(f+1) == 't' && *(f+2) == 'x' && *(f+3) == '\0' ) ) )
148 return; // wrong filedescriptor type
150 if ( str::contains( n, "(stat: Permission denied)" ) )
151 return; // Avoid reporting false positive due to insufficient permission.
155 if ( ! ( str::contains( n, "/lib" ) || str::contains( n, "bin/" ) ) )
156 return; // Try to avoid reporting false positive unless verbose.
159 if ( *f == 'm' || *f == 'D' ) // skip some wellknown nonlibrary memorymapped files
161 static const char * black[] = {
166 for_( it, arrayBegin( black ), arrayEnd( black ) )
168 if ( str::hasPrefix( n, *it ) )
172 // Add if no duplicate
173 cache_r.second.insert( n );
176 /////////////////////////////////////////////////////////////////
177 /// \class FilterRunsInLXC
178 /// \brief Functor guessing whether \a PID is running in a container.
180 /// Asumme a using different \c pid/mnt namespace than \c self.
181 /////////////////////////////////////////////////////////////////
182 struct FilterRunsInLXC
184 bool operator()( pid_t pid_r ) const
185 { return( nsIno( pid_r, "pid" ) != pidNS || nsIno( pid_r, "mnt" ) != mntNS ); }
188 : pidNS( nsIno( "self", "pid" ) )
189 , mntNS( nsIno( "self", "mnt" ) )
192 static inline ino_t nsIno( const std::string & pid_r, const std::string & ns_r )
193 { return PathInfo("/proc/"+pid_r+"/ns/"+ns_r).ino(); }
195 static inline ino_t nsIno( pid_t pid_r, const std::string & ns_r )
196 { return nsIno( asString(pid_r), ns_r ); }
202 /////////////////////////////////////////////////////////////////
204 ///////////////////////////////////////////////////////////////////
206 CheckAccessDeleted::size_type CheckAccessDeleted::check( bool verbose_r )
210 static const char* argv[] =
212 "lsof", "-n", "-FpcuLRftkn0", NULL
214 ExternalProgram prog( argv, ExternalProgram::Discard_Stderr );
216 // cachemap: PID => (deleted files)
217 // NOTE: omit PIDs running in a (lxc/docker) container
218 std::map<pid_t,CacheEntry> cachemap;
220 FilterRunsInLXC runsInLXC;
221 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
223 // NOTE: line contains '\0' separeated fields!
224 if ( line[0] == 'p' )
226 str::strtonum( line.c_str()+1, cachepid ); // line is "p<PID>\0...."
227 if ( !runsInLXC( cachepid ) )
228 cachemap[cachepid].first.swap( line );
230 cachepid = 0; // ignore this pid
234 addCacheIf( cachemap[cachepid], line, verbose_r );
238 int ret = prog.close();
243 ZYPP_THROW( Exception(_("Please install package 'lsof' first.") ) );
245 Exception err( str::form("Executing 'lsof' failed (%d).", ret) );
246 err.remember( prog.execError() );
250 std::vector<ProcInfo> data;
251 for ( const auto & cached : cachemap )
253 addDataIf( data, cached.second );
259 std::string CheckAccessDeleted::findService( pid_t pid_r )
262 p.pid = str::numstring( pid_r );
266 ///////////////////////////////////////////////////////////////////
268 { /////////////////////////////////////////////////////////////////
269 /////////////////////////////////////////////////////////////////
271 ///////////////////////////////////////////////////////////////////
273 std::string CheckAccessDeleted::ProcInfo::service() const
275 static const str::regex rx( "[0-9]+:name=systemd:/system.slice/(.*/)?(.*).service$" );
278 iostr::simpleParseFile( InputStream( Pathname("/proc")/pid/"cgroup" ),
279 [&]( int num_r, std::string line_r )->bool
281 if ( str::regex_match( line_r, what, rx ) )
284 return false; // stop after match
291 /******************************************************************
293 ** FUNCTION NAME : operator<<
294 ** FUNCTION TYPE : std::ostream &
296 std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted & obj )
298 return dumpRange( str << "CheckAccessDeleted ",
303 /******************************************************************
305 ** FUNCTION NAME : operator<<
306 ** FUNCTION TYPE : std::ostream &
308 std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted::ProcInfo & obj )
310 if ( obj.pid.empty() )
311 return str << "<NoProc>";
313 return dumpRangeLine( str << obj.command
323 /////////////////////////////////////////////////////////////////
325 ///////////////////////////////////////////////////////////////////