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"
22 #include "zypp/misc/CheckAccessDeleted.h"
26 #undef ZYPP_BASE_LOGGER_LOGGROUP
27 #define ZYPP_BASE_LOGGER_LOGGROUP "zypp::misc"
29 ///////////////////////////////////////////////////////////////////
31 { /////////////////////////////////////////////////////////////////
33 ///////////////////////////////////////////////////////////////////
35 { /////////////////////////////////////////////////////////////////
37 // lsof output lines are a sequence of NUL terminated fields,
38 // where the 1st char determines the fiels type.
40 // (pcuL) pid command userid loginname
41 // (ftkn).filedescriptor type linkcount filename
43 /////////////////////////////////////////////////////////////////
45 /** lsof output line + files extracted so far for this PID */
46 typedef std::pair<std::string,std::unordered_set<std::string>> CacheEntry;
48 /** Add \c cache to \c data if the process is accessing deleted files.
49 * \c pid string in \c cache is the proc line \c (pcuLR), \c files
50 * are already in place. Always clear the \c cache.files!
52 inline void addDataIf( std::vector<CheckAccessDeleted::ProcInfo> & data_r, const CacheEntry & cache_r )
54 const auto & filelist( cache_r.second );
56 if ( filelist.empty() )
59 // at least one file access so keep it:
60 data_r.push_back( CheckAccessDeleted::ProcInfo() );
61 CheckAccessDeleted::ProcInfo & pinfo( data_r.back() );
62 pinfo.files.insert( pinfo.files.begin(), filelist.begin(), filelist.end() );
64 const std::string & pline( cache_r.first );
65 for_( ch, pline.begin(), pline.end() )
73 pinfo.ppid = &*(ch+1);
76 pinfo.puid = &*(ch+1);
79 pinfo.login = &*(ch+1);
82 pinfo.command = &*(ch+1);
85 if ( *ch == '\n' ) break; // end of data
86 do { ++ch; } while ( *ch != '\0' ); // skip to next field
89 if ( pinfo.command.size() == 15 )
91 // the command name might be truncated, so we check against /proc/<pid>/exe
92 Pathname command( filesystem::readlink( Pathname("/proc")/pinfo.pid/"exe" ) );
93 if ( ! command.empty() )
94 pinfo.command = command.basename();
96 //MIL << " Take " << pinfo << endl;
100 /** Add file to cache if it refers to a deleted executable or library file:
101 * - Either the link count \c(k) is \c 0, or no link cout is present.
102 * - The type \c (t) is set to \c REG or \c DEL
103 * - The filedescriptor \c (f) is set to \c txt, \c mem or \c DEL
105 inline void addCacheIf( CacheEntry & cache_r, const std::string & line_r, bool verbose_r )
111 for_( ch, line_r.c_str(), ch+line_r.size() )
116 if ( *(ch+1) != '0' ) // skip non-zero link counts
129 if ( *ch == '\n' ) break; // end of data
130 do { ++ch; } while ( *ch != '\0' ); // skip to next field
133 if ( !t || !f || !n )
134 return; // wrong filedescriptor/type/name
136 if ( !( ( *t == 'R' && *(t+1) == 'E' && *(t+2) == 'G' && *(t+3) == '\0' )
137 || ( *t == 'D' && *(t+1) == 'E' && *(t+2) == 'L' && *(t+3) == '\0' ) ) )
138 return; // wrong type
140 if ( !( ( *f == 'm' && *(f+1) == 'e' && *(f+2) == 'm' && *(f+3) == '\0' )
141 || ( *f == 't' && *(f+1) == 'x' && *(f+2) == 't' && *(f+3) == '\0' )
142 || ( *f == 'D' && *(f+1) == 'E' && *(f+2) == 'L' && *(f+3) == '\0' )
143 || ( *f == 'l' && *(f+1) == 't' && *(f+2) == 'x' && *(f+3) == '\0' ) ) )
144 return; // wrong filedescriptor type
146 if ( str::contains( n, "(stat: Permission denied)" ) )
147 return; // Avoid reporting false positive due to insufficient permission.
151 if ( ! ( str::contains( n, "/lib" ) || str::contains( n, "bin/" ) ) )
152 return; // Try to avoid reporting false positive unless verbose.
155 if ( *f == 'm' || *f == 'D' ) // skip some wellknown nonlibrary memorymapped files
157 static const char * black[] = {
162 for_( it, arrayBegin( black ), arrayEnd( black ) )
164 if ( str::hasPrefix( n, *it ) )
168 // Add if no duplicate
169 cache_r.second.insert( n );
172 /////////////////////////////////////////////////////////////////
173 /// \class FilterRunsInLXC
174 /// \brief Functor guessing whether \a PID is running in a container.
176 /// Asumme a using different \c pid/mnt namespace than \c self.
177 /////////////////////////////////////////////////////////////////
178 struct FilterRunsInLXC
180 bool operator()( pid_t pid_r ) const
181 { return( nsIno( pid_r, "pid" ) != pidNS || nsIno( pid_r, "mnt" ) != mntNS ); }
184 : pidNS( nsIno( "self", "pid" ) )
185 , mntNS( nsIno( "self", "mnt" ) )
188 static inline ino_t nsIno( const std::string & pid_r, const std::string & ns_r )
189 { return PathInfo("/proc/"+pid_r+"/ns/"+ns_r).ino(); }
191 static inline ino_t nsIno( pid_t pid_r, const std::string & ns_r )
192 { return nsIno( asString(pid_r), ns_r ); }
198 /////////////////////////////////////////////////////////////////
200 ///////////////////////////////////////////////////////////////////
202 CheckAccessDeleted::size_type CheckAccessDeleted::check( bool verbose_r )
206 static const char* argv[] =
208 "lsof", "-n", "-FpcuLRftkn0", NULL
210 ExternalProgram prog( argv, ExternalProgram::Discard_Stderr );
212 // cachemap: PID => (deleted files)
213 // NOTE: omit PIDs running in a (lxc/docker) container
214 std::map<pid_t,CacheEntry> cachemap;
216 FilterRunsInLXC runsInLXC;
217 for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
219 // NOTE: line contains '\0' separeated fields!
220 if ( line[0] == 'p' )
222 str::strtonum( line.c_str()+1, cachepid ); // line is "p<PID>\0...."
223 if ( !runsInLXC( cachepid ) )
224 cachemap[cachepid].first.swap( line );
226 cachepid = 0; // ignore this pid
230 addCacheIf( cachemap[cachepid], line, verbose_r );
234 int ret = prog.close();
239 ZYPP_THROW( Exception(_("Please install package 'lsof' first.") ) );
241 Exception err( str::form("Executing 'lsof' failed (%d).", ret) );
242 err.remember( prog.execError() );
246 std::vector<ProcInfo> data;
247 for ( const auto & cached : cachemap )
249 addDataIf( data, cached.second );
255 std::string CheckAccessDeleted::findService( const Pathname & command_r )
258 p.command = command_r.basename();
261 std::string CheckAccessDeleted::findService( const char * command_r )
262 { return findService( Pathname( command_r ) ); }
264 std::string CheckAccessDeleted::findService( const std::string & command_r )
265 { return findService( Pathname( command_r ) ); }
267 std::string CheckAccessDeleted::findService( pid_t pid_r )
268 { return findService( filesystem::readlink( Pathname("/proc")/str::numstring(pid_r)/"exe" ) ); }
270 ///////////////////////////////////////////////////////////////////
272 { /////////////////////////////////////////////////////////////////
273 /////////////////////////////////////////////////////////////////
275 ///////////////////////////////////////////////////////////////////
277 std::string CheckAccessDeleted::ProcInfo::service() const
279 if ( command.empty() )
280 return std::string();
281 // TODO: This needs to be implemented smarter... be carefull
282 // as we don't know whether the target is up.
284 static const Pathname initD( "/etc/init.d" );
285 { // init.d script with same name
286 PathInfo pi( initD/command );
287 if ( pi.isFile() && pi.isX() )
290 { // init.d script with name + 'd'
291 std::string alt( command+"d" );
292 PathInfo pi( initD/alt );
293 if ( pi.isFile() && pi.isX() )
296 if ( *command.rbegin() == 'd' )
297 { // init.d script with name - trailing'd'
298 std::string alt( command );
299 alt.erase( alt.size()-1 );
300 PathInfo pi( initD/alt );
302 if ( pi.isFile() && pi.isX() )
305 return std::string();
308 /******************************************************************
310 ** FUNCTION NAME : operator<<
311 ** FUNCTION TYPE : std::ostream &
313 std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted & obj )
315 return dumpRange( str << "CheckAccessDeleted ",
320 /******************************************************************
322 ** FUNCTION NAME : operator<<
323 ** FUNCTION TYPE : std::ostream &
325 std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted::ProcInfo & obj )
327 if ( obj.pid.empty() )
328 return str << "<NoProc>";
330 return dumpRangeLine( str << obj.command
340 /////////////////////////////////////////////////////////////////
342 ///////////////////////////////////////////////////////////////////