1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/PathInfo.h
12 #ifndef ZYPP_PATHINFO_H
13 #define ZYPP_PATHINFO_H
17 #include <sys/types.h>
30 #include "zypp/Pathname.h"
31 #include "zypp/CheckSum.h"
32 #include "zypp/ByteCount.h"
34 ///////////////////////////////////////////////////////////////////
36 { /////////////////////////////////////////////////////////////////
40 ///////////////////////////////////////////////////////////////////
41 /** Types and functions for filesystem operations.
42 * \todo move zypp::filesystem stuff into separate header
43 * \todo Add tmpfile and tmpdir handling.
44 * \todo think about using Exceptions in zypp::filesystem
45 * \todo provide a readdir iterator; at least provide an interface
46 * using an insert_iterator to be independent from std::container.
49 { /////////////////////////////////////////////////////////////////
51 ///////////////////////////////////////////////////////////////////
52 /** File type information.
53 * \todo Think about an \ref g_EnumerationClass
57 FT_NOT_AVAIL = 0x00, // no typeinfo available
58 FT_NOT_EXIST = 0x01, // file does not exist
67 ///////////////////////////////////////////////////////////////////
69 /** \relates FileType Stram output. */
70 extern std::ostream & operator<<( std::ostream & str, FileType obj );
72 ///////////////////////////////////////////////////////////////////
74 ///////////////////////////////////////////////////////////////////
76 // CLASS NAME : StatMode
78 * @short Wrapper class for mode_t values as derived from ::stat
82 friend std::ostream & operator<<( std::ostream & str, const StatMode & obj );
85 /** Ctor taking mode_t value from ::stat. */
86 StatMode( const mode_t & mode_r = 0 )
92 /** \name Query FileType. */
94 FileType fileType() const;
96 bool isFile() const { return S_ISREG( _mode ); }
97 bool isDir () const { return S_ISDIR( _mode ); }
98 bool isLink() const { return S_ISLNK( _mode ); }
99 bool isChr() const { return S_ISCHR( _mode ); }
100 bool isBlk() const { return S_ISBLK( _mode ); }
101 bool isFifo() const { return S_ISFIFO( _mode ); }
102 bool isSock() const { return S_ISSOCK( _mode ); }
105 /** \name Query user permissions. */
107 bool isRUsr() const { return (_mode & S_IRUSR); }
108 bool isWUsr() const { return (_mode & S_IWUSR); }
109 bool isXUsr() const { return (_mode & S_IXUSR); }
111 /** Short for isRUsr().*/
112 bool isR() const { return isRUsr(); }
113 /** Short for isWUsr().*/
114 bool isW() const { return isWUsr(); }
115 /** Short for isXUsr().*/
116 bool isX() const { return isXUsr(); }
119 /** \name Query group permissions. */
121 bool isRGrp() const { return (_mode & S_IRGRP); }
122 bool isWGrp() const { return (_mode & S_IWGRP); }
123 bool isXGrp() const { return (_mode & S_IXGRP); }
126 /** \name Query others permissions. */
128 bool isROth() const { return (_mode & S_IROTH); }
129 bool isWOth() const { return (_mode & S_IWOTH); }
130 bool isXOth() const { return (_mode & S_IXOTH); }
133 /** \name Query special permissions. */
136 bool isUid() const { return (_mode & S_ISUID); }
138 bool isGid() const { return (_mode & S_ISGID); }
140 bool isVtx() const { return (_mode & S_ISVTX); }
143 /** \name Query permission */
145 /** Test for equal permission bits. */
146 bool isPerm ( mode_t m ) const { return (m == perm()); }
147 /** Test for set permission bits. */
148 bool hasPerm( mode_t m ) const { return (m == (m & perm())); }
151 /** \name Extract permission bits only. */
153 mode_t uperm() const { return (_mode & S_IRWXU); }
154 mode_t gperm() const { return (_mode & S_IRWXG); }
155 mode_t operm() const { return (_mode & S_IRWXO); }
156 mode_t perm() const { return (_mode & (S_IRWXU|S_IRWXG|S_IRWXO|S_ISUID|S_ISGID|S_ISVTX)); }
159 /** Return the mode_t value. */
160 mode_t st_mode() const { return _mode; }
165 ///////////////////////////////////////////////////////////////////
167 /** \relates StatMode Stream output. */
168 extern std::ostream & operator<<( std::ostream & str, const StatMode & obj );
170 ///////////////////////////////////////////////////////////////////
172 ///////////////////////////////////////////////////////////////////
174 // CLASS NAME : DevInoCache
175 /** Simple cache remembering device/inode to detect hardlinks.
178 * for ( all files ) {
179 * if ( trace.insert( file.device, file.inode ) ) {
180 * // 1st occurance of file
182 * // else: hardlink; already counted this device/inode
194 void clear() { _devino.clear(); }
196 /** Remember dev/ino.
197 * \Return <code>true</code> if it's inserted the first
198 * time, <code>false</code> if alredy present in cache
199 * (a hardlink to a previously remembered file).
201 bool insert( const dev_t & dev_r, const ino_t & ino_r ) {
202 return _devino[dev_r].insert( ino_r ).second;
206 std::map<dev_t,std::set<ino_t> > _devino;
208 ///////////////////////////////////////////////////////////////////
210 ///////////////////////////////////////////////////////////////////
212 // CLASS NAME : PathInfo
213 /** Wrapper class for ::stat/::lstat.
215 * \note All attribute quieries test for isExist(), and return \c false or
216 * \c 0, if stat was not successful.
218 * \note For convenience PathInfo is available as zypp::PathInfo too.
222 friend std::ostream & operator<<( std::ostream & str, const PathInfo & obj );
225 /** stat() or lstat() */
226 enum Mode { STAT, LSTAT };
229 /** \name Construct from Pathname.
230 * Default mode is \c STAT.
235 PathInfo( const Pathname & path, Mode initial = STAT );
237 PathInfo( const std::string & path, Mode initial = STAT );
239 PathInfo( const char * path, Mode initial = STAT );
245 /** Return current Pathname. */
246 const Pathname & path() const { return path_t; }
247 /** Return current Pathname as String. */
248 const std::string & asString() const { return path_t.asString(); }
249 /** Return current Pathname as C-string. */
250 const char * c_str() const { return path_t.asString().c_str(); }
251 /** Return current stat Mode. */
252 Mode mode() const { return mode_e; }
253 /** Return error returned from last stat/lstat call. */
254 int error() const { return error_i; }
256 /** Set a new Pathname. */
257 void setPath( const Pathname & path ) { if ( path != path_t ) error_i = -1; path_t = path; }
258 /** Set a new Mode . */
259 void setMode( Mode mode ) { if ( mode != mode_e ) error_i = -1; mode_e = mode; }
262 bool stat ( const Pathname & path ) { setPath( path ); setMode( STAT ); return operator()(); }
263 /** LSTAT \a path. */
264 bool lstat ( const Pathname & path ) { setPath( path ); setMode( LSTAT ); return operator()(); }
265 /** Restat \a path using current mode. */
266 bool operator()( const Pathname & path ) { setPath( path ); return operator()(); }
268 /** STAT current path. */
269 bool stat() { setMode( STAT ); return operator()(); }
270 /** LSTAT current path. */
271 bool lstat() { setMode( LSTAT ); return operator()(); }
272 /** Restat current path using current mode. */
277 /** Return whether valid stat info exists.
278 * That's usg. whether the file exist and you had permission to
281 bool isExist() const { return !error_i; }
283 /** \name Query StatMode attibutes.
284 * Combines \ref zypp::PathInfo::isExist and \ref zypp::filesystem::StatMode query.
287 FileType fileType() const;
289 bool isFile() const { return isExist() && S_ISREG( statbuf_C.st_mode ); }
290 bool isDir () const { return isExist() && S_ISDIR( statbuf_C.st_mode ); }
291 bool isLink() const { return isExist() && S_ISLNK( statbuf_C.st_mode ); }
292 bool isChr() const { return isExist() && S_ISCHR( statbuf_C.st_mode ); }
293 bool isBlk() const { return isExist() && S_ISBLK( statbuf_C.st_mode ); }
294 bool isFifo() const { return isExist() && S_ISFIFO( statbuf_C.st_mode ); }
295 bool isSock() const { return isExist() && S_ISSOCK( statbuf_C.st_mode ); }
298 bool isRUsr() const { return isExist() && (statbuf_C.st_mode & S_IRUSR); }
299 bool isWUsr() const { return isExist() && (statbuf_C.st_mode & S_IWUSR); }
300 bool isXUsr() const { return isExist() && (statbuf_C.st_mode & S_IXUSR); }
302 bool isR() const { return isRUsr(); }
303 bool isW() const { return isWUsr(); }
304 bool isX() const { return isXUsr(); }
306 bool isRGrp() const { return isExist() && (statbuf_C.st_mode & S_IRGRP); }
307 bool isWGrp() const { return isExist() && (statbuf_C.st_mode & S_IWGRP); }
308 bool isXGrp() const { return isExist() && (statbuf_C.st_mode & S_IXGRP); }
310 bool isROth() const { return isExist() && (statbuf_C.st_mode & S_IROTH); }
311 bool isWOth() const { return isExist() && (statbuf_C.st_mode & S_IWOTH); }
312 bool isXOth() const { return isExist() && (statbuf_C.st_mode & S_IXOTH); }
314 bool isUid() const { return isExist() && (statbuf_C.st_mode & S_ISUID); }
315 bool isGid() const { return isExist() && (statbuf_C.st_mode & S_ISGID); }
316 bool isVtx() const { return isExist() && (statbuf_C.st_mode & S_ISVTX); }
318 bool isPerm ( mode_t m ) const { return isExist() && (m == perm()); }
319 bool hasPerm( mode_t m ) const { return isExist() && (m == (m & perm())); }
321 mode_t uperm() const { return isExist() ? (statbuf_C.st_mode & S_IRWXU) : 0; }
322 mode_t gperm() const { return isExist() ? (statbuf_C.st_mode & S_IRWXG) : 0; }
323 mode_t operm() const { return isExist() ? (statbuf_C.st_mode & S_IRWXO) : 0; }
324 mode_t perm() const { return isExist() ? (statbuf_C.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO|S_ISUID|S_ISGID|S_ISVTX)) : 0; }
326 mode_t st_mode() const { return isExist() ? statbuf_C.st_mode : 0; }
329 /** Return st_mode() as filesystem::StatMode. */
330 StatMode asStatMode() const { return st_mode(); }
332 nlink_t nlink() const { return isExist() ? statbuf_C.st_nlink : 0; }
334 /** \name Owner and group */
336 uid_t owner() const { return isExist() ? statbuf_C.st_uid : 0; }
337 gid_t group() const { return isExist() ? statbuf_C.st_gid : 0; }
340 /** \name Permission according to current uid/gid. */
342 /** Returns current users permission (<tt>[0-7]</tt>)*/
343 mode_t userMay() const;
345 bool userMayR() const { return( userMay() & 04 ); }
346 bool userMayW() const { return( userMay() & 02 ); }
347 bool userMayX() const { return( userMay() & 01 ); }
349 bool userMayRW() const { return( (userMay() & 06) == 06 ); }
350 bool userMayRX() const { return( (userMay() & 05) == 05 ); }
351 bool userMayWX() const { return( (userMay() & 03) == 03 ); }
353 bool userMayRWX() const { return( userMay() == 07 ); }
356 /** \name Device and inode info. */
358 ino_t ino() const { return isExist() ? statbuf_C.st_ino : 0; }
359 dev_t dev() const { return isExist() ? statbuf_C.st_dev : 0; }
360 dev_t rdev() const { return isExist() ? statbuf_C.st_rdev : 0; }
362 unsigned int devMajor() const;
363 unsigned int devMinor() const;
366 /** \name Size info. */
368 off_t size() const { return isExist() ? statbuf_C.st_size : 0; }
369 unsigned long blksize() const { return isExist() ? statbuf_C.st_blksize : 0; }
370 unsigned long blocks() const { return isExist() ? statbuf_C.st_blocks : 0; }
373 /** \name Time stamps. */
375 time_t atime() const { return isExist() ? statbuf_C.st_atime : 0; } /* time of last access */
376 time_t mtime() const { return isExist() ? statbuf_C.st_mtime : 0; } /* time of last modification */
377 time_t ctime() const { return isExist() ? statbuf_C.st_ctime : 0; }
382 struct stat statbuf_C;
386 ///////////////////////////////////////////////////////////////////
388 /** \relates PathInfo Stream output. */
389 extern std::ostream & operator<<( std::ostream & str, const PathInfo & obj );
391 ///////////////////////////////////////////////////////////////////
393 ///////////////////////////////////////////////////////////////////
394 /** \name Directory related functions. */
397 * Like '::mkdir'. Attempt to create a new directory named path. mode
398 * specifies the permissions to use. It is modified by the process's
399 * umask in the usual way.
401 * @return 0 on success, errno on failure
403 int mkdir( const Pathname & path, unsigned mode = 0755 );
406 * Like 'mkdir -p'. No error if directory exists. Make parent directories
407 * as needed. mode specifies the permissions to use, if directories have to
408 * be created. It is modified by the process's umask in the usual way.
410 * @return 0 on success, errno on failure
412 int assert_dir( const Pathname & path, unsigned mode = 0755 );
415 * Like '::rmdir'. Delete a directory, which must be empty.
417 * @return 0 on success, errno on failure
419 int rmdir( const Pathname & path );
422 * Like 'rm -r DIR'. Delete a directory, recursively removing its contents.
424 * @return 0 on success, ENOTDIR if path is not a directory, otherwise the
425 * commands return value.
427 int recursive_rmdir( const Pathname & path );
430 * Like 'rm -r DIR/ *'. Delete directory contents, but keep the directory itself.
432 * @return 0 on success, ENOTDIR if path is not a directory, otherwise the
433 * commands return value.
435 int clean_dir( const Pathname & path );
438 * Like 'cp -a srcpath destpath'. Copy directory tree. srcpath/destpath must be
439 * directories. 'basename srcpath' must not exist in destpath.
441 * @return 0 on success, ENOTDIR if srcpath/destpath is not a directory, EEXIST if
442 * 'basename srcpath' exists in destpath, otherwise the commands return value.
444 int copy_dir( const Pathname & srcpath, const Pathname & destpath );
447 * Like 'cp -a srcpath/. destpath'. Copy the content of srcpath recursively
448 * into destpath. Both \p srcpath and \p destpath has to exists.
450 * @return 0 on success, ENOTDIR if srcpath/destpath is not a directory,
451 * EEXIST if srcpath and destpath are equal, otherwise the commands
454 int copy_dir_content( const Pathname & srcpath, const Pathname & destpath);
457 * Convenience returning <tt>StrMatcher( "[^.]*", Match::GLOB )</tt>
458 * \see \ref dirForEach
460 const StrMatcher & matchNoDots();
463 * Invoke callback function \a fnc_r for each entry in directory \a dir_r.
465 * If \a fnc_r is a \c NULL function \c 0 is returned immediately without even
466 * testing or accessing \a dir_r.
468 * Otherwise \c ::readdir is used to read the name of every entry in \a dir_r,
469 * omitting \c '.' and \c '..'. \a dir_r and the current entries name are passed
470 * as arguments to \a fnc_r. If \a fnc_r returns \c false processing is aborted.
472 * @return 0 on success, -1 if aborted by callback, errno > 0 on ::readdir failure.
474 int dirForEach( const Pathname & dir_r, function<bool(const Pathname &, const char *const)> fnc_r );
477 * \overload taking a \ref StrMatcher to filter the entries for which \a fnc_r is invoked.
479 * For convenience a \ref StrMatcher \ref matchNoDots is provided in this namespace.</tt>
482 * bool cbfnc( const Pathname & dir_r, const char *const str_r )
484 * D BG <*< " - " << dir_r/str_r << endl;
487 * // Print no-dot files in "/tmp" via callback
488 * filesystem::dirForEach( "/tmp", filesystem::matchNoDots(), cbfnc );
491 * filesystem::dirForEach( "/tmp", filesystem::matchNoDots(),
492 * [](const Pathname & dir_r, const std::string & str_r)->bool
494 * DBG << " - " << dir_r/str_r << endl;
499 int dirForEach( const Pathname & dir_r, const StrMatcher & matcher_r, function<bool(const Pathname &, const char *const)> fnc_r );
502 * Return content of directory via retlist. If dots is false
503 * entries starting with '.' are not reported. "." and ".."
504 * are never reported.
506 * Returns just the directory entries as string.
508 * @return 0 on success, errno on failure.
510 * \todo provide some readdirIterator.
513 int readdir( std::list<std::string> & retlist,
514 const Pathname & path, bool dots = true );
517 * Return content of directory via retlist. If dots is false
518 * entries starting with '.' are not reported. "." and ".."
519 * are never reported.
521 * Returns the directory entries prefixed with \a path.
523 * @return 0 on success, errno on failure.
525 * \todo provide some readdirIterator.
528 int readdir( std::list<Pathname> & retlist,
529 const Pathname & path, bool dots = true );
531 /** Listentry returned by readdir. */
535 DirEntry( const std::string & name_r = std::string(), FileType type_r = FT_NOT_AVAIL )
540 bool operator==( const DirEntry &rhs ) const;
543 inline std::ostream & operator<<( std::ostream & str, const DirEntry & obj )
544 { return str << '[' << obj.type << "] " << obj.name; }
546 /** Returned by readdir. */
547 typedef std::list<DirEntry> DirContent;
549 std::ostream & operator<<( std::ostream & str, const DirContent & obj );
552 * Return content of directory via retlist. If dots is false
553 * entries starting with '.' are not reported. "." and ".."
554 * are never reported.
556 * The type of individual directory entries is determined accoding to
557 * statmode (i.e. via stat or lstat).
559 * @return 0 on success, errno on failure.
561 int readdir( DirContent & retlist, const Pathname & path,
562 bool dots = true, PathInfo::Mode statmode = PathInfo::STAT );
565 * Check if the specified directory is empty.
566 * \param path The path of the directory to check.
567 * \return 0 if directory is empty, -1 if not, errno > 0 on failure.
569 int is_empty_dir(const Pathname & path);
573 ///////////////////////////////////////////////////////////////////
574 /** \name File related functions. */
577 * Create an empty file if it does not yet exist. Make parent directories
578 * as needed. mode specifies the permissions to use. It is modified by the
579 * process's umask in the usual way.
581 * @return 0 on success, errno on failure
583 int assert_file( const Pathname & path, unsigned mode = 0644 );
586 * Change file's modification and access times.
588 * \return 0 on success, errno on failure
591 int touch (const Pathname & path);
594 * Like '::unlink'. Delete a file (symbolic link, socket, fifo or device).
596 * @return 0 on success, errno on failure
598 int unlink( const Pathname & path );
601 * Like '::rename'. Renames a file, moving it between directories if required.
603 * @return 0 on success, errno on failure
605 int rename( const Pathname & oldpath, const Pathname & newpath );
607 /** Exchanges two files or directories.
609 * Most common use is when building a new config file (or dir)
610 * in a tempfile. After the job is done, configfile and tempfile
611 * are exchanged. This includes moving away the configfile in case
612 * the tempfile does not exist. Parent directories are created as
615 * \note Paths are exchanged using \c ::rename, so take care both paths
616 * are located on the same filesystem.
619 * Pathname configfile( "/etc/myconfig" );
620 * TmpFile newconfig( TmpFile::makeSibling( configfile ) );
621 * // now write the new config:
622 * std::ofstream o( newconfig.path().c_str() );
623 * o << "mew values << endl;
625 * // If everything is fine, exchange the files:
626 * exchange( newconfig.path(), configfile );
627 * // Now the old configfile is still available at newconfig.path()
628 * // until newconfig goes out of scope.
631 * @return 0 on success, errno on failure
633 int exchange( const Pathname & lpath, const Pathname & rpath );
636 * Like 'cp file dest'. Copy file to destination file.
638 * @return 0 on success, EINVAL if file is not a file, EISDIR if
639 * destiantion is a directory, otherwise the commands return value.
641 int copy( const Pathname & file, const Pathname & dest );
644 * Like '::symlink'. Creates a symbolic link named newpath which contains
645 * the string oldpath. If newpath exists it will not be overwritten.
647 * @return 0 on success, errno on failure.
649 int symlink( const Pathname & oldpath, const Pathname & newpath );
652 * Like '::link'. Creates a hard link named newpath to an existing file
653 * oldpath. If newpath exists it will not be overwritten.
655 * @return 0 on success, errno on failure.
657 int hardlink( const Pathname & oldpath, const Pathname & newpath );
660 * Create \a newpath as hardlink or copy of \a oldpath.
662 * @return 0 on success, errno on failure.
664 int hardlinkCopy( const Pathname & oldpath, const Pathname & newpath );
667 * Like '::readlink'. Return the contents of the symbolic link
668 * \a symlink_r via \a target_r.
670 * @return 0 on success, errno on failure.
672 int readlink( const Pathname & symlink_r, Pathname & target_r );
673 /** \overload Return an empty Pathname on error. */
674 inline Pathname readlink( const Pathname & symlink_r )
677 readlink( symlink_r, target );
682 * Recursively follows the symlink pointed to by \a path_r and returns
683 * the Pathname to the real file or directory pointed to by the link.
685 * There is a recursion limit of 256 iterations to protect against a cyclic
688 * @return Pathname of the file or directory pointed to by the given link
689 * if it is a valid link. If \a path_r is not a link, an exact copy of
690 * it is returned. If \a path_r is a broken or a cyclic link, an empty
691 * Pathname is returned and the event logged.
693 Pathname expandlink( const Pathname & path_r );
696 * Like 'cp file dest'. Copy file to dest dir.
698 * @return 0 on success, EINVAL if file is not a file, ENOTDIR if dest
699 * is no directory, otherwise the commands return value.
701 int copy_file2dir( const Pathname & file, const Pathname & dest );
704 ///////////////////////////////////////////////////////////////////
705 /** \name Digest computaion.
706 * \todo check cooperation with zypp::Digest
710 * Compute a files md5sum.
712 * @return the files md5sum on success, otherwise an empty string..
714 std::string md5sum( const Pathname & file );
717 * Compute a files sha1sum.
719 * @return the files sha1sum on success, otherwise an empty string..
721 std::string sha1sum( const Pathname & file );
725 * Compute a files checksum
727 * @return the files checksum on success, otherwise an empty string..
729 std::string checksum( const Pathname & file, const std::string &algorithm );
732 * check files checksum
734 * @return true if the checksum matchs
736 bool is_checksum( const Pathname & file, const CheckSum &checksum );
738 ///////////////////////////////////////////////////////////////////
739 /** \name Changing permissions. */
742 * Like '::chmod'. The mode of the file given by path is changed.
744 * @return 0 on success, errno on failure
746 int chmod( const Pathname & path, mode_t mode );
749 * Add the \c mode bits to the file given by path.
751 * @return 0 on success, errno on failure
753 int addmod( const Pathname & path, mode_t mode );
756 * Remove the \c mode bits from the file given by path.
758 * @return 0 on success, errno on failure
760 int delmod( const Pathname & path, mode_t mode );
763 ///////////////////////////////////////////////////////////////////
767 * Test whether a file is compressed (gzip/bzip2).
769 * @return ZT_GZ, ZT_BZ2 if file is compressed, otherwise ZT_NONE.
771 enum ZIP_TYPE { ZT_NONE, ZT_GZ, ZT_BZ2 };
773 ZIP_TYPE zipType( const Pathname & file );
776 * Erase whatever happens to be located at path (file or directory).
778 * @return 0 on success.
780 * \todo check cooperation with zypp::TmpFile and zypp::TmpDir
782 int erase( const Pathname & path );
785 * Report free disk space on a mounted file system.
787 * path is the path name of any file within the mounted filesystem.
789 * @return Free disk space or -1 on error.
791 ByteCount df( const Pathname & path );
794 * Get the current umask (file mode creation mask)
796 * @return The current umask
801 * Modify \c mode_r according to the current umask
802 * <tt>( mode_r & ~getUmask() )</tt>.
803 * \see \ref getUmask.
804 * @return The resulting permissions.
806 inline mode_t applyUmaskTo( mode_t mode_r )
807 { return mode_r & ~getUmask(); }
810 /////////////////////////////////////////////////////////////////
811 } // namespace filesystem
812 ///////////////////////////////////////////////////////////////////
814 /** Dragged into namespace zypp. */
815 using filesystem::PathInfo;
817 /////////////////////////////////////////////////////////////////
819 ///////////////////////////////////////////////////////////////////
820 #endif // ZYPP_PATHINFO_H