libzypp  15.28.6
CheckAccessDeleted.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
12 #include <iostream>
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"
18 
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 
27 
28 using std::endl;
29 
30 #undef ZYPP_BASE_LOGGER_LOGGROUP
31 #define ZYPP_BASE_LOGGER_LOGGROUP "zypp::misc"
32 
34 namespace zypp
35 {
36 
38  namespace
39  {
40  //
41  // lsof output lines are a sequence of NUL terminated fields,
42  // where the 1st char determines the fields type.
43  //
44  // (pcuL) pid command userid loginname
45  // (ftkn).filedescriptor type linkcount filename
46  //
48 
50  typedef std::pair<std::string,std::unordered_set<std::string>> CacheEntry;
51 
56  inline void addDataIf( std::vector<CheckAccessDeleted::ProcInfo> & data_r, const CacheEntry & cache_r )
57  {
58  const auto & filelist( cache_r.second );
59 
60  if ( filelist.empty() )
61  return;
62 
63  // at least one file access so keep it:
64  data_r.push_back( CheckAccessDeleted::ProcInfo() );
65  CheckAccessDeleted::ProcInfo & pinfo( data_r.back() );
66  pinfo.files.insert( pinfo.files.begin(), filelist.begin(), filelist.end() );
67 
68  const std::string & pline( cache_r.first );
69  for_( ch, pline.begin(), pline.end() )
70  {
71  switch ( *ch )
72  {
73  case 'p':
74  pinfo.pid = &*(ch+1);
75  break;
76  case 'R':
77  pinfo.ppid = &*(ch+1);
78  break;
79  case 'u':
80  pinfo.puid = &*(ch+1);
81  break;
82  case 'L':
83  pinfo.login = &*(ch+1);
84  break;
85  case 'c':
86  pinfo.command = &*(ch+1);
87  break;
88  }
89  if ( *ch == '\n' ) break; // end of data
90  do { ++ch; } while ( *ch != '\0' ); // skip to next field
91  }
92 
93  if ( pinfo.command.size() == 15 )
94  {
95  // the command name might be truncated, so we check against /proc/<pid>/exe
96  Pathname command( filesystem::readlink( Pathname("/proc")/pinfo.pid/"exe" ) );
97  if ( ! command.empty() )
98  pinfo.command = command.basename();
99  }
100  //MIL << " Take " << pinfo << endl;
101  }
102 
103 
109  inline void addCacheIf( CacheEntry & cache_r, const std::string & line_r, bool verbose_r )
110  {
111  const char * f = 0;
112  const char * t = 0;
113  const char * n = 0;
114 
115  for_( ch, line_r.c_str(), ch+line_r.size() )
116  {
117  switch ( *ch )
118  {
119  case 'k':
120  if ( *(ch+1) != '0' ) // skip non-zero link counts
121  return;
122  break;
123  case 'f':
124  f = ch+1;
125  break;
126  case 't':
127  t = ch+1;
128  break;
129  case 'n':
130  n = ch+1;
131  break;
132  }
133  if ( *ch == '\n' ) break; // end of data
134  do { ++ch; } while ( *ch != '\0' ); // skip to next field
135  }
136 
137  if ( !t || !f || !n )
138  return; // wrong filedescriptor/type/name
139 
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
143 
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
149 
150  if ( str::contains( n, "(stat: Permission denied)" ) )
151  return; // Avoid reporting false positive due to insufficient permission.
152 
153  if ( ! verbose_r )
154  {
155  if ( ! ( str::contains( n, "/lib" ) || str::contains( n, "bin/" ) ) )
156  return; // Try to avoid reporting false positive unless verbose.
157  }
158 
159  if ( *f == 'm' || *f == 'D' ) // skip some wellknown nonlibrary memorymapped files
160  {
161  static const char * black[] = {
162  "/SYSV"
163  , "/var/run/"
164  , "/dev/"
165  };
166  for_( it, arrayBegin( black ), arrayEnd( black ) )
167  {
168  if ( str::hasPrefix( n, *it ) )
169  return;
170  }
171  }
172  // Add if no duplicate
173  cache_r.second.insert( n );
174  }
175 
182  struct FilterRunsInLXC
183  {
184  bool operator()( pid_t pid_r ) const
185  { return( nsIno( pid_r, "pid" ) != pidNS ); }
186 
187  FilterRunsInLXC()
188  : pidNS( nsIno( "self", "pid" ) )
189  {}
190 
191  static inline ino_t nsIno( const std::string & pid_r, const std::string & ns_r )
192  { return PathInfo("/proc/"+pid_r+"/ns/"+ns_r).ino(); }
193 
194  static inline ino_t nsIno( pid_t pid_r, const std::string & ns_r )
195  { return nsIno( asString(pid_r), ns_r ); }
196 
197  ino_t pidNS;
198  };
199 
205  bool lsofNoOptKi()
206  {
207  using target::rpm::librpmDb;
208  // RpmDb access is blocked while the Target is not initialized.
209  // Launching the Target just for this query would be an overkill.
210  struct TmpUnblock {
211  TmpUnblock()
212  : _wasBlocked( librpmDb::isBlocked() )
213  { if ( _wasBlocked ) librpmDb::unblockAccess(); }
214  ~TmpUnblock()
215  { if ( _wasBlocked ) librpmDb::blockAccess(); }
216  private:
217  bool _wasBlocked;
218  } tmpUnblock;
219 
220  librpmDb::db_const_iterator it;
221  return( it.findPackage( "lsof" ) && it->tag_edition() < Edition("4.90") && !it->tag_provides().count( Capability("backported-option-Ki") ) );
222  }
223 
225  } // namespace
227 
229  {
230  _data.clear();
231 
232  static const char* argv[] = { "lsof", "-n", "-FpcuLRftkn0", "-K", "i", NULL };
233  if ( lsofNoOptKi() )
234  argv[3] = NULL;
236 
237  // cachemap: PID => (deleted files)
238  // NOTE: omit PIDs running in a (lxc/docker) container
239  std::map<pid_t,CacheEntry> cachemap;
240  pid_t cachepid = 0;
241  FilterRunsInLXC runsInLXC;
242  for( std::string line = prog.receiveLine(); ! line.empty(); line = prog.receiveLine() )
243  {
244  // NOTE: line contains '\0' separeated fields!
245  if ( line[0] == 'p' )
246  {
247  str::strtonum( line.c_str()+1, cachepid ); // line is "p<PID>\0...."
248  if ( !runsInLXC( cachepid ) )
249  cachemap[cachepid].first.swap( line );
250  else
251  cachepid = 0; // ignore this pid
252  }
253  else if ( cachepid )
254  {
255  addCacheIf( cachemap[cachepid], line, verbose_r );
256  }
257  }
258 
259  int ret = prog.close();
260  if ( ret != 0 )
261  {
262  if ( ret == 129 )
263  {
264  ZYPP_THROW( Exception(_("Please install package 'lsof' first.") ) );
265  }
266  Exception err( str::form("Executing 'lsof' failed (%d).", ret) );
267  err.remember( prog.execError() );
268  ZYPP_THROW( err );
269  }
270 
271  std::vector<ProcInfo> data;
272  for ( const auto & cached : cachemap )
273  {
274  addDataIf( data, cached.second );
275  }
276  _data.swap( data );
277  return _data.size();
278  }
279 
280  std::string CheckAccessDeleted::findService( pid_t pid_r )
281  {
282  ProcInfo p;
283  p.pid = str::numstring( pid_r );
284  return p.service();
285  }
286 
288  namespace
289  {
290  } // namespace
293 
295  {
296  static const str::regex rx( "[0-9]+:name=systemd:/system.slice/(.*/)?(.*).service$" );
297  str::smatch what;
298  std::string ret;
299  iostr::simpleParseFile( InputStream( Pathname("/proc")/pid/"cgroup" ),
300  [&]( int num_r, std::string line_r )->bool
301  {
302  if ( str::regex_match( line_r, what, rx ) )
303  {
304  ret = what[2];
305  return false; // stop after match
306  }
307  return true;
308  } );
309  return ret;
310  }
311 
312  /******************************************************************
313  **
314  ** FUNCTION NAME : operator<<
315  ** FUNCTION TYPE : std::ostream &
316  */
317  std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted & obj )
318  {
319  return dumpRange( str << "CheckAccessDeleted ",
320  obj.begin(),
321  obj.end() );
322  }
323 
324  /******************************************************************
325  **
326  ** FUNCTION NAME : operator<<
327  ** FUNCTION TYPE : std::ostream &
328  */
329  std::ostream & operator<<( std::ostream & str, const CheckAccessDeleted::ProcInfo & obj )
330  {
331  if ( obj.pid.empty() )
332  return str << "<NoProc>";
333 
334  return dumpRangeLine( str << obj.command
335  << '<' << obj.pid
336  << '|' << obj.ppid
337  << '|' << obj.puid
338  << '|' << obj.login
339  << '>',
340  obj.files.begin(),
341  obj.files.end() );
342  }
343 
345 } // namespace zypp
std::string asString(const Patch::Category &obj)
Definition: Patch.cc:117
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:973
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:321
Regular expression.
Definition: Regex.h:86
int readlink(const Pathname &symlink_r, Pathname &target_r)
Like 'readlink'.
Definition: PathInfo.cc:856
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:89
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 ...
TInt strtonum(const C_Str &str)
Parsing numbers from string.
Definition: String.h:403
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:304
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:1036
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.