libzypp  16.22.5
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 "zypp/base/LogTools.h"
16 #include "zypp/base/String.h"
17 #include "zypp/base/Gettext.h"
18 #include "zypp/base/Exception.h"
19 
20 #include "zypp/PathInfo.h"
21 #include "zypp/ExternalProgram.h"
22 #include "zypp/base/Regex.h"
23 #include "zypp/base/IOStream.h"
24 #include "zypp/base/InputStream.h"
26 
28 
29 using std::endl;
30 
31 #undef ZYPP_BASE_LOGGER_LOGGROUP
32 #define ZYPP_BASE_LOGGER_LOGGROUP "zypp::misc"
33 
35 namespace zypp
36 {
37 
39  namespace
40  {
41  //
42  // lsof output lines are a sequence of NUL terminated fields,
43  // where the 1st char determines the fields type.
44  //
45  // (pcuL) pid command userid loginname
46  // (ftkn).filedescriptor type linkcount filename
47  //
49 
51  typedef std::pair<std::string,std::unordered_set<std::string>> CacheEntry;
52 
57  inline void addDataIf( std::vector<CheckAccessDeleted::ProcInfo> & data_r, const CacheEntry & cache_r )
58  {
59  const auto & filelist( cache_r.second );
60 
61  if ( filelist.empty() )
62  return;
63 
64  // at least one file access so keep it:
65  data_r.push_back( CheckAccessDeleted::ProcInfo() );
66  CheckAccessDeleted::ProcInfo & pinfo( data_r.back() );
67  pinfo.files.insert( pinfo.files.begin(), filelist.begin(), filelist.end() );
68 
69  const std::string & pline( cache_r.first );
70  std::string commandname; // pinfo.command if still needed...
71  for_( ch, pline.begin(), pline.end() )
72  {
73  switch ( *ch )
74  {
75  case 'p':
76  pinfo.pid = &*(ch+1);
77  break;
78  case 'R':
79  pinfo.ppid = &*(ch+1);
80  break;
81  case 'u':
82  pinfo.puid = &*(ch+1);
83  break;
84  case 'L':
85  pinfo.login = &*(ch+1);
86  break;
87  case 'c':
88  if ( pinfo.command.empty() )
89  commandname = &*(ch+1);
90  break;
91  }
92  if ( *ch == '\n' ) break; // end of data
93  do { ++ch; } while ( *ch != '\0' ); // skip to next field
94  }
95 
96  if ( pinfo.command.empty() )
97  {
98  // the lsof command name might be truncated, so we prefer /proc/<pid>/exe
99  pinfo.command = filesystem::readlink( Pathname("/proc")/pinfo.pid/"exe" ).basename();
100  if ( pinfo.command.empty() )
101  pinfo.command = std::move(commandname);
102  }
103  }
104 
105 
111  inline void addCacheIf( CacheEntry & cache_r, const std::string & line_r, bool verbose_r )
112  {
113  const char * f = 0;
114  const char * t = 0;
115  const char * n = 0;
116 
117  for_( ch, line_r.c_str(), ch+line_r.size() )
118  {
119  switch ( *ch )
120  {
121  case 'k':
122  if ( *(ch+1) != '0' ) // skip non-zero link counts
123  return;
124  break;
125  case 'f':
126  f = ch+1;
127  break;
128  case 't':
129  t = ch+1;
130  break;
131  case 'n':
132  n = ch+1;
133  break;
134  }
135  if ( *ch == '\n' ) break; // end of data
136  do { ++ch; } while ( *ch != '\0' ); // skip to next field
137  }
138 
139  if ( !t || !f || !n )
140  return; // wrong filedescriptor/type/name
141 
142  if ( !( ( *t == 'R' && *(t+1) == 'E' && *(t+2) == 'G' && *(t+3) == '\0' )
143  || ( *t == 'D' && *(t+1) == 'E' && *(t+2) == 'L' && *(t+3) == '\0' ) ) )
144  return; // wrong type
145 
146  if ( !( ( *f == 'm' && *(f+1) == 'e' && *(f+2) == 'm' && *(f+3) == '\0' )
147  || ( *f == 't' && *(f+1) == 'x' && *(f+2) == 't' && *(f+3) == '\0' )
148  || ( *f == 'D' && *(f+1) == 'E' && *(f+2) == 'L' && *(f+3) == '\0' )
149  || ( *f == 'l' && *(f+1) == 't' && *(f+2) == 'x' && *(f+3) == '\0' ) ) )
150  return; // wrong filedescriptor type
151 
152  if ( str::contains( n, "(stat: Permission denied)" ) )
153  return; // Avoid reporting false positive due to insufficient permission.
154 
155  if ( ! verbose_r )
156  {
157  if ( ! ( str::contains( n, "/lib" ) || str::contains( n, "bin/" ) ) )
158  return; // Try to avoid reporting false positive unless verbose.
159  }
160 
161  if ( *f == 'm' || *f == 'D' ) // skip some wellknown nonlibrary memorymapped files
162  {
163  static const char * black[] = {
164  "/SYSV"
165  , "/var/run/"
166  , "/var/lib/sss/"
167  , "/dev/"
168  , "/var/lib/gdm"
169  };
170  for_( it, arrayBegin( black ), arrayEnd( black ) )
171  {
172  if ( str::hasPrefix( n, *it ) )
173  return;
174  }
175  }
176  // Add if no duplicate
177  cache_r.second.insert( n );
178  }
179 
186  struct FilterRunsInLXC
187  {
188  bool operator()( pid_t pid_r ) const
189  { return( nsIno( pid_r, "pid" ) != pidNS ); }
190 
191  FilterRunsInLXC()
192  : pidNS( nsIno( "self", "pid" ) )
193  {}
194 
195  static inline ino_t nsIno( const std::string & pid_r, const std::string & ns_r )
196  { return PathInfo("/proc/"+pid_r+"/ns/"+ns_r).ino(); }
197 
198  static inline ino_t nsIno( pid_t pid_r, const std::string & ns_r )
199  { return nsIno( asString(pid_r), ns_r ); }
200 
201  ino_t pidNS;
202  };
203 
204 #if 0
205  void lsofdebug( const Pathname & file_r )
206  {
207  std::ifstream infile( file_r.c_str() );
208  USR << infile << endl;
209  std::vector<std::string> fields;
210  CacheEntry cache;
211  for( iostr::EachLine in( infile ); in; in.next() )
212  {
213  std::string field( *in );
214  if ( field[0] == 'f' || field[0] == 'p' )
215  {
216  if ( !fields.empty() )
217  {
218  // consume
219  std::string line( str::join( fields, "\n" ) );
220  for ( char & c : line )
221  { if ( c == '\n' ) c = '\0'; }
222  line.push_back( '\n' );
223 
224  size_t sze = cache.second.size();
225  addCacheIf( cache, line, false );
226  if ( sze != cache.second.size() )
227  USR << fields << endl;
228 
229  fields.clear();
230  }
231  if ( field[0] == 'p' )
232  continue;
233  fields.push_back( field );
234  }
235  else if ( !fields.empty() )
236  {
237  fields.push_back( field );
238  }
239  }
240  }
241 #endif
242 
248  bool lsofNoOptKi()
249  {
250  using target::rpm::librpmDb;
251  // RpmDb access is blocked while the Target is not initialized.
252  // Launching the Target just for this query would be an overkill.
253  struct TmpUnblock {
254  TmpUnblock()
255  : _wasBlocked( librpmDb::isBlocked() )
256  { if ( _wasBlocked ) librpmDb::unblockAccess(); }
257  ~TmpUnblock()
258  { if ( _wasBlocked ) librpmDb::blockAccess(); }
259  private:
260  bool _wasBlocked;
261  } tmpUnblock;
262 
263  librpmDb::db_const_iterator it;
264  return( it.findPackage( "lsof" ) && it->tag_edition() < Edition("4.90") && !it->tag_provides().count( Capability("backported-option-Ki") ) );
265  }
266 
268  } // namespace
270 
272  {
273  _data.clear();
274 
275  static const char* argv[] = { "lsof", "-n", "-FpcuLRftkn0", "-K", "i", NULL };
276  if ( lsofNoOptKi() )
277  argv[3] = NULL;
279 
280  // cachemap: PID => (deleted files)
281  // NOTE: omit PIDs running in a (lxc/docker) container
282  std::map<pid_t,CacheEntry> cachemap;
283  pid_t cachepid = 0;
284  FilterRunsInLXC runsInLXC;
285  for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
286  {
287  // NOTE: line contains '\0' separeated fields!
288  if ( line[0] == 'p' )
289  {
290  str::strtonum( line.c_str()+1, cachepid ); // line is "p<PID>\0...."
291  if ( !runsInLXC( cachepid ) )
292  cachemap[cachepid].first.swap( line );
293  else
294  cachepid = 0; // ignore this pid
295  }
296  else if ( cachepid )
297  {
298  addCacheIf( cachemap[cachepid], line, verbose_r );
299  }
300  }
301 
302  int ret = prog.close();
303  if ( ret != 0 )
304  {
305  if ( ret == 129 )
306  {
307  ZYPP_THROW( Exception(_("Please install package 'lsof' first.") ) );
308  }
309  Exception err( str::form("Executing 'lsof' failed (%d).", ret) );
310  err.remember( prog.execError() );
311  ZYPP_THROW( err );
312  }
313 
314  std::vector<ProcInfo> data;
315  for ( const auto & cached : cachemap )
316  {
317  addDataIf( data, cached.second );
318  }
319  _data.swap( data );
320  return _data.size();
321  }
322 
323  std::string CheckAccessDeleted::findService( pid_t pid_r )
324  {
325  ProcInfo p;
326  p.pid = str::numstring( pid_r );
327  return p.service();
328  }
329 
331  namespace
332  {
333  } // namespace
336 
338  {
339  static const str::regex rx( "[0-9]+:name=systemd:/system.slice/(.*/)?(.*).service$" );
340  str::smatch what;
341  std::string ret;
342  iostr::simpleParseFile( InputStream( Pathname("/proc")/pid/"cgroup" ),
343  [&]( int num_r, std::string line_r )->bool
344  {
345  if ( str::regex_match( line_r, what, rx ) )
346  {
347  ret = what[2];
348  return false; // stop after match
349  }
350  return true;
351  } );
352  return ret;
353  }
354 
355  /******************************************************************
356  **
357  ** FUNCTION NAME : operator<<
358  ** FUNCTION TYPE : std::ostream &
359  */
360  std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted & obj )
361  {
362  return dumpRange( str << "CheckAccessDeleted ",
363  obj.begin(),
364  obj.end() );
365  }
366 
367  /******************************************************************
368  **
369  ** FUNCTION NAME : operator<<
370  ** FUNCTION TYPE : std::ostream &
371  */
372  std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted::ProcInfo & obj )
373  {
374  if ( obj.pid.empty() )
375  return str << "<NoProc>";
376 
377  return dumpRangeLine( str << obj.command
378  << '<' << obj.pid
379  << '|' << obj.ppid
380  << '|' << obj.puid
381  << '|' << obj.login
382  << '>',
383  obj.files.begin(),
384  obj.files.end() );
385  }
386 
388 } // namespace zypp
Interface to gettext.
Data about one running process accessing deleted files.
bool contains(const C_Str &str_r, const C_Str &val_r)
Locate substring case sensitive.
Definition: String.h:974
std::string asString(const DefaultIntegral< Tp, TInitial > &obj)
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:350
Regular expression.
Definition: Regex.h:86
int readlink(const Pathname &symlink_r, Pathname &target_r)
Like 'readlink'.
Definition: PathInfo.cc:886
std::string join(TIterator begin, TIterator end, const C_Str &sep_r=" ")
Join strings using separator sep_r (defaults to BLANK).
Definition: String.h:759
std::vector< ProcInfo > _data
const std::string & execError() const
Some detail telling why the execution failed, if it failed.
std::string service() const
Guess if command was started by a systemd service script.
std::string command
process command name
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
std::ostream & operator<<(std::ostream &str, const CheckAccessDeleted &obj)
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
Definition: String.cc:36
void remember(const Exception &old_r)
Store an other Exception as history.
Definition: Exception.cc:105
size_type check(bool verbose_r=false)
Check for running processes which access deleted executables or libraries.
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
std::ostream & dumpRange(std::ostream &str, TIterator begin, TIterator end, const std::string &intro="{", const std::string &pfx="\n ", const std::string &sep="\n ", const std::string &sfx="\n", const std::string &extro="}")
Print range defined by iterators (multiline style).
Definition: LogTools.h:91
Execute a program and give access to its io An object of this class encapsulates the execution of an ...
#define USR
Definition: Logger.h:69
TInt strtonum(const C_Str &str)
Parsing numbers from string.
Definition: String.h:404
std::string puid
process user ID
#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:305
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:143
Check for running processes which access deleted executables or libraries.
const_iterator end() const
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
bool hasPrefix(const C_Str &str_r, const C_Str &prefix_r)
Return whether str_r has prefix prefix_r.
Definition: String.h:1037
const_iterator begin() const
std::string login
process login name
std::vector< std::string > files
list of deleted executables or libraries accessed
std::string ppid
parent process ID
static std::string findService(pid_t pid_r)
Guess if pid was started by a systemd service script.