libzypp  17.6.2
CheckAccessDeleted.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
12 #include <iostream>
13 #include <fstream>
14 #include <unordered_set>
15 #include <iterator>
16 #include <stdio.h>
17 #include "zypp/base/LogTools.h"
18 #include "zypp/base/String.h"
19 #include "zypp/base/Gettext.h"
20 #include "zypp/base/Exception.h"
21 
22 #include "zypp/PathInfo.h"
23 #include "zypp/ExternalProgram.h"
24 #include "zypp/base/Regex.h"
25 #include "zypp/base/IOStream.h"
26 #include "zypp/base/InputStream.h"
28 
30 
31 using std::endl;
32 
33 #undef ZYPP_BASE_LOGGER_LOGGROUP
34 #define ZYPP_BASE_LOGGER_LOGGROUP "zypp::misc"
35 
37 namespace zypp
38 {
39 
41  namespace
42  {
43  //
44  // lsof output lines are a sequence of NUL terminated fields,
45  // where the 1st char determines the fields type.
46  //
47  // (pcuL) pid command userid loginname
48  // (ftkn).filedescriptor type linkcount filename
49  //
51 
53  typedef std::pair<std::string,std::unordered_set<std::string>> CacheEntry;
54 
61  struct FilterRunsInLXC
62  {
63  bool operator()( pid_t pid_r ) const
64  { return( nsIno( pid_r, "pid" ) != pidNS ); }
65 
66  FilterRunsInLXC()
67  : pidNS( nsIno( "self", "pid" ) )
68  {}
69 
70  static inline ino_t nsIno( const std::string & pid_r, const std::string & ns_r )
71  { return PathInfo("/proc/"+pid_r+"/ns/"+ns_r).ino(); }
72 
73  static inline ino_t nsIno( pid_t pid_r, const std::string & ns_r )
74  { return nsIno( asString(pid_r), ns_r ); }
75 
76  ino_t pidNS;
77  };
78 
82  bool lsofNoOptKi()
83  {
84  using target::rpm::librpmDb;
85  // RpmDb access is blocked while the Target is not initialized.
86  // Launching the Target just for this query would be an overkill.
87  struct TmpUnblock {
88  TmpUnblock()
89  : _wasBlocked( librpmDb::isBlocked() )
90  { if ( _wasBlocked ) librpmDb::unblockAccess(); }
91  ~TmpUnblock()
92  { if ( _wasBlocked ) librpmDb::blockAccess(); }
93  private:
94  bool _wasBlocked;
95  } tmpUnblock;
96 
97  librpmDb::db_const_iterator it;
98  return( it.findPackage( "lsof" ) && it->tag_edition() < Edition("4.90") );
99  }
100 
101  } //namespace
103 
105  {
106  public:
108 
109  bool addDataIf( const CacheEntry & cache_r, std::vector<std::string> *debMap = nullptr );
110  void addCacheIf( CacheEntry & cache_r, const std::string & line_r, std::vector<std::string> *debMap = nullptr );
111 
112  std::map<pid_t,CacheEntry> filterInput( externalprogram::ExternalDataSource &source );
113  CheckAccessDeleted::size_type createProcInfo( const std::map<pid_t,CacheEntry> &in );
114 
115  std::vector<CheckAccessDeleted::ProcInfo> _data;
116  bool _fromLsofFileMode = false; // Set if we currently process data from a debug file
117  bool _verbose = false;
118 
119  std::map<pid_t,std::vector<std::string>> debugMap; //will contain all used lsof files after filtering
121  };
122 
124  {
125  Impl *myClone = new Impl( *this );
126  return myClone;
127  }
128 
133  inline bool CheckAccessDeleted::Impl::addDataIf( const CacheEntry & cache_r, std::vector<std::string> *debMap )
134  {
135  const auto & filelist( cache_r.second );
136 
137  if ( filelist.empty() )
138  return false;
139 
140  // at least one file access so keep it:
141  _data.push_back( CheckAccessDeleted::ProcInfo() );
142  CheckAccessDeleted::ProcInfo & pinfo( _data.back() );
143  pinfo.files.insert( pinfo.files.begin(), filelist.begin(), filelist.end() );
144 
145  const std::string & pline( cache_r.first );
146  std::string commandname; // pinfo.command if still needed...
147  std::ostringstream pLineStr; //rewrite the first line in debug cache
148  for_( ch, pline.begin(), pline.end() )
149  {
150  switch ( *ch )
151  {
152  case 'p':
153  pinfo.pid = &*(ch+1);
154  if ( debMap )
155  pLineStr <<&*(ch)<<'\0';
156  break;
157  case 'R':
158  pinfo.ppid = &*(ch+1);
159  if ( debMap )
160  pLineStr <<&*(ch)<<'\0';
161  break;
162  case 'u':
163  pinfo.puid = &*(ch+1);
164  if ( debMap )
165  pLineStr <<&*(ch)<<'\0';
166  break;
167  case 'L':
168  pinfo.login = &*(ch+1);
169  if ( debMap )
170  pLineStr <<&*(ch)<<'\0';
171  break;
172  case 'c':
173  if ( pinfo.command.empty() ) {
174  commandname = &*(ch+1);
175  // the lsof command name might be truncated, so we prefer /proc/<pid>/exe
176  if (!_fromLsofFileMode)
177  pinfo.command = filesystem::readlink( Pathname("/proc")/pinfo.pid/"exe" ).basename();
178  if ( pinfo.command.empty() )
179  pinfo.command = std::move(commandname);
180  if ( debMap )
181  pLineStr <<'c'<<pinfo.command<<'\0';
182  }
183  break;
184  }
185  if ( *ch == '\n' ) break; // end of data
186  do { ++ch; } while ( *ch != '\0' ); // skip to next field
187  }
188 
189  //replace the data in the debug cache as well
190  if ( debMap ) {
191  pLineStr<<endl;
192  debMap->front() = pLineStr.str();
193  }
194 
195  //entry was added
196  return true;
197  }
198 
199 
205  inline void CheckAccessDeleted::Impl::addCacheIf( CacheEntry & cache_r, const std::string & line_r, std::vector<std::string> *debMap )
206  {
207  const char * f = 0;
208  const char * t = 0;
209  const char * n = 0;
210 
211  for_( ch, line_r.c_str(), ch+line_r.size() )
212  {
213  switch ( *ch )
214  {
215  case 'k':
216  if ( *(ch+1) != '0' ) // skip non-zero link counts
217  return;
218  break;
219  case 'f':
220  f = ch+1;
221  break;
222  case 't':
223  t = ch+1;
224  break;
225  case 'n':
226  n = ch+1;
227  break;
228  }
229  if ( *ch == '\n' ) break; // end of data
230  do { ++ch; } while ( *ch != '\0' ); // skip to next field
231  }
232 
233  if ( !t || !f || !n )
234  return; // wrong filedescriptor/type/name
235 
236  if ( !( ( *t == 'R' && *(t+1) == 'E' && *(t+2) == 'G' && *(t+3) == '\0' )
237  || ( *t == 'D' && *(t+1) == 'E' && *(t+2) == 'L' && *(t+3) == '\0' ) ) )
238  return; // wrong type
239 
240  if ( !( ( *f == 'm' && *(f+1) == 'e' && *(f+2) == 'm' && *(f+3) == '\0' )
241  || ( *f == 't' && *(f+1) == 'x' && *(f+2) == 't' && *(f+3) == '\0' )
242  || ( *f == 'D' && *(f+1) == 'E' && *(f+2) == 'L' && *(f+3) == '\0' )
243  || ( *f == 'l' && *(f+1) == 't' && *(f+2) == 'x' && *(f+3) == '\0' ) ) )
244  return; // wrong filedescriptor type
245 
246  if ( str::contains( n, "(stat: Permission denied)" ) )
247  return; // Avoid reporting false positive due to insufficient permission.
248 
249  if ( ! _verbose )
250  {
251  if ( ! ( str::contains( n, "/lib" ) || str::contains( n, "bin/" ) ) )
252  return; // Try to avoid reporting false positive unless verbose.
253  }
254 
255  if ( *f == 'm' || *f == 'D' ) // skip some wellknown nonlibrary memorymapped files
256  {
257  static const char * black[] = {
258  "/SYSV"
259  , "/var/"
260  , "/dev/"
261  , "/tmp/"
262  , "/proc/"
263  };
264  for_( it, arrayBegin( black ), arrayEnd( black ) )
265  {
266  if ( str::hasPrefix( n, *it ) )
267  return;
268  }
269  }
270  // Add if no duplicate
271  if ( debMap && cache_r.second.find(n) == cache_r.second.end() ) {
272  debMap->push_back(line_r);
273  }
274  cache_r.second.insert( n );
275  }
276 
278  : _pimpl(new Impl)
279  {
280  if ( doCheck_r ) check();
281  }
282 
283  CheckAccessDeleted::size_type CheckAccessDeleted::check( const Pathname &lsofOutput_r, bool verbose_r )
284  {
285  _pimpl->_verbose = verbose_r;
286  _pimpl->_fromLsofFileMode = true;
287 
288  FILE *inFile = fopen( lsofOutput_r.c_str(), "r" );
289  if ( !inFile ) {
290  ZYPP_THROW( Exception( str::Format("Opening input file %1% failed.") % lsofOutput_r.c_str() ) );
291  }
292 
293  //inFile is closed by ExternalDataSource
294  externalprogram::ExternalDataSource inSource( inFile, nullptr );
295  auto cache = _pimpl->filterInput( inSource );
296  return _pimpl->createProcInfo( cache );
297  }
298 
300  {
301  // cachemap: PID => (deleted files)
302  // NOTE: omit PIDs running in a (lxc/docker) container
303  std::map<pid_t,CacheEntry> cachemap;
304 
305  bool debugEnabled = !_debugFile.empty();
306 
307  pid_t cachepid = 0;
308  FilterRunsInLXC runsInLXC;
309  for( std::string line = source.receiveLine(); ! line.empty(); line = source.receiveLine() )
310  {
311  // NOTE: line contains '\0' separeated fields!
312  if ( line[0] == 'p' )
313  {
314  str::strtonum( line.c_str()+1, cachepid ); // line is "p<PID>\0...."
315  if ( _fromLsofFileMode || !runsInLXC( cachepid ) ) {
316  if ( debugEnabled ) {
317  auto &pidMad = debugMap[cachepid];
318  if ( pidMad.empty() )
319  debugMap[cachepid].push_back( line );
320  else
321  debugMap[cachepid].front() = line;
322  }
323  cachemap[cachepid].first.swap( line );
324  } else {
325  cachepid = 0; // ignore this pid
326  }
327  }
328  else if ( cachepid )
329  {
330  auto &dbgMap = debugMap[cachepid];
331  addCacheIf( cachemap[cachepid], line, debugEnabled ? &dbgMap : nullptr);
332  }
333  }
334  return cachemap;
335  }
336 
338  {
339  static const char* argv[] = { "lsof", "-n", "-FpcuLRftkn0", "-K", "i", NULL };
340  if ( lsofNoOptKi() )
341  argv[3] = NULL;
342 
343  _pimpl->_verbose = verbose_r;
344  _pimpl->_fromLsofFileMode = false;
345 
347  std::map<pid_t,CacheEntry> cachemap = _pimpl->filterInput( prog );
348 
349  int ret = prog.close();
350  if ( ret != 0 )
351  {
352  if ( ret == 129 )
353  {
354  ZYPP_THROW( Exception(_("Please install package 'lsof' first.") ) );
355  }
356  Exception err( str::Format("Executing 'lsof' failed (%1%).") % ret );
357  err.remember( prog.execError() );
358  ZYPP_THROW( err );
359  }
360 
361  return _pimpl->createProcInfo( cachemap );
362  }
363 
365  {
366  std::ofstream debugFileOut;
367  bool debugEnabled = false;
368  if ( !_debugFile.empty() ) {
369  debugFileOut.open( _debugFile.c_str() );
370  debugEnabled = debugFileOut.is_open();
371 
372  if ( !debugEnabled ) {
373  ERR<<"Unable to open debug file: "<<_debugFile<<endl;
374  }
375  }
376 
377  _data.clear();
378  for ( const auto &cached : in )
379  {
380  if (!debugEnabled)
381  addDataIf( cached.second);
382  else {
383  std::vector<std::string> *mapPtr = nullptr;
384 
385  auto dbgInfo = debugMap.find(cached.first);
386  if ( dbgInfo != debugMap.end() )
387  mapPtr = &(dbgInfo->second);
388 
389  if( !addDataIf( cached.second, mapPtr ) )
390  continue;
391 
392  for ( const std::string &dbgLine: dbgInfo->second ) {
393  debugFileOut.write( dbgLine.c_str(), dbgLine.length() );
394  }
395  }
396  }
397  return _data.size();
398  }
399 
401  {
402  return _pimpl->_data.empty();
403  }
404 
406  {
407  return _pimpl->_data.size();
408  }
409 
411  {
412  return _pimpl->_data.begin();
413  }
414 
416  {
417  return _pimpl->_data.end();
418  }
419 
421  {
422  _pimpl->_debugFile = filename_r;
423  }
424 
425  std::string CheckAccessDeleted::findService( pid_t pid_r )
426  {
427  ProcInfo p;
428  p.pid = str::numstring( pid_r );
429  return p.service();
430  }
431 
433  {
434  static const str::regex rx( "[0-9]+:name=systemd:/system.slice/(.*/)?(.*).service$" );
435  str::smatch what;
436  std::string ret;
437  iostr::simpleParseFile( InputStream( Pathname("/proc")/pid/"cgroup" ),
438  [&]( int num_r, std::string line_r )->bool
439  {
440  if ( str::regex_match( line_r, what, rx ) )
441  {
442  ret = what[2];
443  return false; // stop after match
444  }
445  return true;
446  } );
447  return ret;
448  }
449 
450  /******************************************************************
451  **
452  ** FUNCTION NAME : operator<<
453  ** FUNCTION TYPE : std::ostream &
454  */
455  std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted & obj )
456  {
457  return dumpRange( str << "CheckAccessDeleted ",
458  obj.begin(),
459  obj.end() );
460  }
461 
462  /******************************************************************
463  **
464  ** FUNCTION NAME : operator<<
465  ** FUNCTION TYPE : std::ostream &
466  */
467  std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted::ProcInfo & obj )
468  {
469  if ( obj.pid.empty() )
470  return str << "<NoProc>";
471 
472  return dumpRangeLine( str << obj.command
473  << '<' << obj.pid
474  << '|' << obj.ppid
475  << '|' << obj.puid
476  << '|' << obj.login
477  << '>',
478  obj.files.begin(),
479  obj.files.end() );
480  }
481 
483 } // namespace zypp
bool addDataIf(const CacheEntry &cache_r, std::vector< std::string > *debMap=nullptr)
Add cache to data if the process is accessing deleted files.
Interface to gettext.
Data about one running process accessing deleted files.
Bidirectional stream to external data.
bool contains(const C_Str &str_r, const C_Str &val_r)
Locate substring case sensitive.
Definition: String.h:948
std::map< pid_t, CacheEntry > filterInput(externalprogram::ExternalDataSource &source)
std::string asString(const DefaultIntegral< Tp, TInitial > &obj)
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:392
Regular expression.
Definition: Regex.h:86
std::map< pid_t, std::vector< std::string > > debugMap
int readlink(const Pathname &symlink_r, Pathname &target_r)
Like &#39;readlink&#39;.
Definition: PathInfo.cc:877
void setDebugOutputFile(const Pathname &filename_r)
Writes all filtered process entries that make it into the final set into a file specified by filename...
std::ostream & dumpRange(std::ostream &str, TIterator begin, TIterator end, const std::string &intro="{", const std::string &pfx="\ ", const std::string &sep="\ ", const std::string &sfx="\, const std::string &extro="}")
Print range defined by iterators (multiline style).
Definition: LogTools.h:91
const char * c_str() const
String representation.
Definition: Pathname.h:109
std::string command
process command name
String related utilities and Regular expression matching.
Helper to create and pass std::istream.
Definition: InputStream.h:56
#define for_(IT, BEG, END)
Convenient for-loops using iterator.
Definition: Easy.h:27
Convenient building of std::string with boost::format.
Definition: String.h:251
std::ostream & operator<<(std::ostream &str, const CheckAccessDeleted &obj)
#define ERR
Definition: Logger.h:66
void remember(const Exception &old_r)
Store an other Exception as history.
Definition: Exception.cc:105
CheckAccessDeleted::Impl * clone() const
bool empty() const
Test for an empty path.
Definition: Pathname.h:113
size_type check(bool verbose_r=false)
Check for running processes which access deleted executables or libraries.
RWCOW_pointer< Impl > _pimpl
const_iterator begin() const
int simpleParseFile(std::istream &str_r, ParseFlags flags_r, function< bool(int, std::string)> consume_r)
Simple lineparser optionally trimming and skipping comments.
Definition: IOStream.cc:124
const std::string & execError() const
Some detail telling why the execution failed, if it failed.
Execute a program and give access to its io An object of this class encapsulates the execution of an ...
std::list< PublicKeyData > _data
Definition: KeyRing.cc:138
std::vector< CheckAccessDeleted::ProcInfo > _data
TInt strtonum(const C_Str &str)
Parsing numbers from string.
Definition: String.h:387
std::string puid
process user ID
const_iterator end() const
#define _(MSG)
Definition: Gettext.h:29
std::string receiveLine()
Read one line from the input stream.
std::string numstring(char n, int w=0)
Definition: String.h:288
CheckAccessDeleted::size_type createProcInfo(const std::map< pid_t, CacheEntry > &in)
int close()
Wait for the progamm to complete.
#define arrayEnd(A)
Definition: Easy.h:42
#define arrayBegin(A)
Simple C-array iterator.
Definition: Easy.h:40
Regular expression match result.
Definition: Regex.h:145
Base class for Exception.
Definition: Exception.h:145
Check for running processes which access deleted executables or libraries.
CheckAccessDeleted(bool doCheck_r=true)
Default ctor performs check immediately.
std::ostream & dumpRangeLine(std::ostream &str, TIterator begin, TIterator end)
Print range defined by iterators (single line style).
Definition: LogTools.h:114
ino_t pidNS
bool regex_match(const std::string &s, smatch &matches, const regex &regex)
regex ZYPP_STR_REGEX regex ZYPP_STR_REGEX
Definition: Regex.h:70
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:1
bool hasPrefix(const C_Str &str_r, const C_Str &prefix_r)
Return whether str_r has prefix prefix_r.
Definition: String.h:1011
std::vector< ProcInfo >::const_iterator const_iterator
std::string login
process login name
void addCacheIf(CacheEntry &cache_r, const std::string &line_r, std::vector< std::string > *debMap=nullptr)
Add file to cache if it refers to a deleted executable or library file:
std::vector< std::string > files
list of deleted executables or libraries accessed
std::string ppid
parent process ID
std::string service() const
Guess if command was started by a systemd service script.
static std::string findService(pid_t pid_r)
Guess if pid was started by a systemd service script.