Merged revisions 4705-4906 via svnmerge from
[platform/upstream/libzypp.git] / zypp / PathInfo.h
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/PathInfo.h
10  *
11 */
12 #ifndef ZYPP_PATHINFO_H
13 #define ZYPP_PATHINFO_H
14
15 extern "C"
16 {
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21 #include <dirent.h>
22 }
23
24 #include <cerrno>
25 #include <iosfwd>
26 #include <list>
27 #include <set>
28 #include <map>
29
30 #include "zypp/Pathname.h"
31 #include "zypp/CheckSum.h"
32 #include "zypp/ByteCount.h"
33
34 ///////////////////////////////////////////////////////////////////
35 namespace zypp
36 { /////////////////////////////////////////////////////////////////
37
38   ///////////////////////////////////////////////////////////////////
39   /** Types and functions for filesystem operations.
40    * \todo move zypp::filesystem stuff into separate header
41    * \todo Add tmpfile and tmpdir handling.
42    * \todo think about using Exceptions in zypp::filesystem
43    * \todo provide a readdir iterator; at least provide an interface
44    * using an insert_iterator to be independent from std::container.
45   */
46   namespace filesystem
47   { /////////////////////////////////////////////////////////////////
48
49     ///////////////////////////////////////////////////////////////////
50     /** File type information.
51      * \todo Think about an \ref g_EnumerationClass
52     */
53     enum FileType
54       {
55         FT_NOT_AVAIL = 0x00, // no typeinfo available
56         FT_NOT_EXIST = 0x01, // file does not exist
57         FT_FILE      = 0x02,
58         FT_DIR       = 0x04,
59         FT_CHARDEV   = 0x08,
60         FT_BLOCKDEV  = 0x10,
61         FT_FIFO      = 0x20,
62         FT_LINK      = 0x40,
63         FT_SOCKET    = 0x80
64       };
65     ///////////////////////////////////////////////////////////////////
66
67     /** \relates FileType Stram output. */
68     extern std::ostream & operator<<( std::ostream & str, FileType obj );
69
70     ///////////////////////////////////////////////////////////////////
71
72     ///////////////////////////////////////////////////////////////////
73     //
74     //  CLASS NAME : StatMode
75     /**
76      * @short Wrapper class for mode_t values as derived from ::stat
77      **/
78     class StatMode
79     {
80       friend std::ostream & operator<<( std::ostream & str, const StatMode & obj );
81
82     public:
83       /** Ctor taking  mode_t value from ::stat. */
84       StatMode( const mode_t & mode_r = 0 )
85       : _mode( mode_r )
86       {}
87
88     public:
89
90       /** \name Query FileType. */
91       //@{
92       FileType fileType() const;
93
94       bool   isFile()  const { return S_ISREG( _mode ); }
95       bool   isDir ()  const { return S_ISDIR( _mode ); }
96       bool   isLink()  const { return S_ISLNK( _mode ); }
97       bool   isChr()   const { return S_ISCHR( _mode ); }
98       bool   isBlk()   const { return S_ISBLK( _mode ); }
99       bool   isFifo()  const { return S_ISFIFO( _mode ); }
100       bool   isSock()  const { return S_ISSOCK( _mode ); }
101       //@}
102
103       /** \name Query user permissions. */
104       //@{
105       bool   isRUsr()  const { return (_mode & S_IRUSR); }
106       bool   isWUsr()  const { return (_mode & S_IWUSR); }
107       bool   isXUsr()  const { return (_mode & S_IXUSR); }
108
109       /** Short for isRUsr().*/
110       bool   isR()     const { return isRUsr(); }
111       /** Short for isWUsr().*/
112       bool   isW()     const { return isWUsr(); }
113       /** Short for isXUsr().*/
114       bool   isX()     const { return isXUsr(); }
115       //@}
116
117       /** \name Query group permissions. */
118       //@{
119       bool   isRGrp()  const { return (_mode & S_IRGRP); }
120       bool   isWGrp()  const { return (_mode & S_IWGRP); }
121       bool   isXGrp()  const { return (_mode & S_IXGRP); }
122       //@}
123
124       /** \name Query others permissions. */
125       //@{
126       bool   isROth()  const { return (_mode & S_IROTH); }
127       bool   isWOth()  const { return (_mode & S_IWOTH); }
128       bool   isXOth()  const { return (_mode & S_IXOTH); }
129       //@}
130
131       /** \name Query special permissions. */
132       //@{
133       /** Set UID bit. */
134       bool   isUid()   const { return (_mode & S_ISUID); }
135       /** Set GID bit. */
136       bool   isGid()   const { return (_mode & S_ISGID); }
137       /** Sticky bit. */
138       bool   isVtx()   const { return (_mode & S_ISVTX); }
139       //@}
140
141       /** \name Query permission */
142       //@{
143       /** Test for equal permission bits. */
144       bool   isPerm ( mode_t m ) const { return (m == perm()); }
145       /** Test for set permission bits. */
146       bool   hasPerm( mode_t m ) const { return (m == (m & perm())); }
147       //@}
148
149       /** \name Extract permission bits only. */
150       //@{
151       mode_t uperm()   const { return (_mode & S_IRWXU); }
152       mode_t gperm()   const { return (_mode & S_IRWXG); }
153       mode_t operm()   const { return (_mode & S_IRWXO); }
154       mode_t perm()    const { return (_mode & (S_IRWXU|S_IRWXG|S_IRWXO|S_ISUID|S_ISGID|S_ISVTX)); }
155       //@}
156
157       /** Return the mode_t value. */
158       mode_t st_mode() const { return _mode; }
159
160     private:
161       mode_t _mode;
162     };
163     ///////////////////////////////////////////////////////////////////
164
165     /** \relates StatMode Stream output. */
166     extern std::ostream & operator<<( std::ostream & str, const StatMode & obj );
167
168     ///////////////////////////////////////////////////////////////////
169
170     ///////////////////////////////////////////////////////////////////
171     //
172     //  CLASS NAME : DevInoCache
173     /** Simple cache remembering device/inode to detect hardlinks.
174      * \code
175      *     DevInoCache trace;
176      *     for ( all files ) {
177      *       if ( trace.insert( file.device, file.inode ) ) {
178      *         // 1st occurance of file
179      *       }
180      *         // else: hardlink; already counted this device/inode
181      *       }
182      *     }
183      * \endcode
184      **/
185     class DevInoCache
186     {
187     public:
188       /** Ctor */
189       DevInoCache() {}
190
191       /** Clear cache. */
192       void clear() { _devino.clear(); }
193
194       /** Remember dev/ino.
195        * \Return <code>true</code> if it's inserted the first
196        * time, <code>false</code> if alredy present in cache
197        * (a hardlink to a previously remembered file).
198        **/
199       bool insert( const dev_t & dev_r, const ino_t & ino_r ) {
200         return _devino[dev_r].insert( ino_r ).second;
201       }
202
203     private:
204       std::map<dev_t,std::set<ino_t> > _devino;
205     };
206     ///////////////////////////////////////////////////////////////////
207
208     ///////////////////////////////////////////////////////////////////
209     //
210     //  CLASS NAME : PathInfo
211     /** Wrapper class for ::stat/::lstat.
212      *
213      * \note All attribute quieries test for isExist(), and return \c false or
214      * \c 0, if stat was not successful.
215      *
216      * \note For convenience PathInfo is available as zypp::PathInfo too.
217      **/
218     class PathInfo
219     {
220       friend std::ostream & operator<<( std::ostream & str, const PathInfo & obj );
221
222     public:
223       /** stat() or lstat() */
224       enum Mode { STAT, LSTAT };
225
226     public:
227       /** \name Construct from Pathname.
228        * Default mode is \c STAT.
229       */
230       //@{
231       PathInfo();
232       explicit
233       PathInfo( const Pathname & path, Mode initial = STAT );
234       explicit
235       PathInfo( const std::string & path, Mode initial = STAT );
236       explicit
237       PathInfo( const char * path, Mode initial = STAT );
238       //@}
239
240       /**Dtor */
241       ~PathInfo();
242
243       /** Return current Pathname. */
244       const Pathname &    path()     const { return path_t; }
245       /** Return current Pathname as String. */
246       const std::string & asString() const { return path_t.asString(); }
247       /** Return current stat Mode. */
248       Mode                mode()     const { return mode_e; }
249       /** Return error returned from last stat/lstat call. */
250       int                 error()    const { return error_i; }
251
252       /** Set a new Pathname. */
253       void setPath( const Pathname & path ) { if ( path != path_t ) error_i = -1; path_t = path; }
254       /** Set a new Mode . */
255       void setMode( Mode mode )             { if ( mode != mode_e ) error_i = -1; mode_e = mode; }
256
257       /** STAT \a path. */
258       bool stat      ( const Pathname & path ) { setPath( path ); setMode( STAT );  return operator()(); }
259       /** LSTAT \a path. */
260       bool lstat     ( const Pathname & path ) { setPath( path ); setMode( LSTAT ); return operator()(); }
261       /** Restat \a path using current mode. */
262       bool operator()( const Pathname & path ) { setPath( path ); return operator()(); }
263
264       /** STAT current path. */
265       bool stat()   { setMode( STAT );  return operator()(); }
266       /** LSTAT current path. */
267       bool lstat()  { setMode( LSTAT ); return operator()(); }
268       /** Restat current path using current mode. */
269       bool operator()();
270
271     public:
272
273       /** Return whether valid stat info exists.
274        * That's usg. whether the file exist and you had permission to
275        * stat it.
276       */
277       bool   isExist() const { return !error_i; }
278
279       /** \name Query StatMode attibutes.
280        * Combines \ref zypp::PathInfo::isExist and \ref zypp::filesystem::StatMode query.
281       */
282       //@{
283       FileType fileType() const;
284
285       bool   isFile()  const { return isExist() && S_ISREG( statbuf_C.st_mode ); }
286       bool   isDir ()  const { return isExist() && S_ISDIR( statbuf_C.st_mode ); }
287       bool   isLink()  const { return isExist() && S_ISLNK( statbuf_C.st_mode ); }
288       bool   isChr()   const { return isExist() && S_ISCHR( statbuf_C.st_mode ); }
289       bool   isBlk()   const { return isExist() && S_ISBLK( statbuf_C.st_mode ); }
290       bool   isFifo()  const { return isExist() && S_ISFIFO( statbuf_C.st_mode ); }
291       bool   isSock()  const { return isExist() && S_ISSOCK( statbuf_C.st_mode ); }
292
293       // permission
294       bool   isRUsr()  const { return isExist() && (statbuf_C.st_mode & S_IRUSR); }
295       bool   isWUsr()  const { return isExist() && (statbuf_C.st_mode & S_IWUSR); }
296       bool   isXUsr()  const { return isExist() && (statbuf_C.st_mode & S_IXUSR); }
297
298       bool   isR()     const { return isRUsr(); }
299       bool   isW()     const { return isWUsr(); }
300       bool   isX()     const { return isXUsr(); }
301
302       bool   isRGrp()  const { return isExist() && (statbuf_C.st_mode & S_IRGRP); }
303       bool   isWGrp()  const { return isExist() && (statbuf_C.st_mode & S_IWGRP); }
304       bool   isXGrp()  const { return isExist() && (statbuf_C.st_mode & S_IXGRP); }
305
306       bool   isROth()  const { return isExist() && (statbuf_C.st_mode & S_IROTH); }
307       bool   isWOth()  const { return isExist() && (statbuf_C.st_mode & S_IWOTH); }
308       bool   isXOth()  const { return isExist() && (statbuf_C.st_mode & S_IXOTH); }
309
310       bool   isUid()   const { return isExist() && (statbuf_C.st_mode & S_ISUID); }
311       bool   isGid()   const { return isExist() && (statbuf_C.st_mode & S_ISGID); }
312       bool   isVtx()   const { return isExist() && (statbuf_C.st_mode & S_ISVTX); }
313
314       bool   isPerm ( mode_t m ) const { return isExist() && (m == perm()); }
315       bool   hasPerm( mode_t m ) const { return isExist() && (m == (m & perm())); }
316
317       mode_t uperm()   const { return isExist() ? (statbuf_C.st_mode & S_IRWXU) : 0; }
318       mode_t gperm()   const { return isExist() ? (statbuf_C.st_mode & S_IRWXG) : 0; }
319       mode_t operm()   const { return isExist() ? (statbuf_C.st_mode & S_IRWXO) : 0; }
320       mode_t perm()    const { return isExist() ? (statbuf_C.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO|S_ISUID|S_ISGID|S_ISVTX)) : 0; }
321
322       mode_t st_mode() const { return isExist() ? statbuf_C.st_mode : 0; }
323       //@}
324
325       /** Return st_mode() as filesystem::StatMode. */
326       StatMode asStatMode() const { return st_mode(); }
327
328       nlink_t nlink()  const { return isExist() ? statbuf_C.st_nlink : 0; }
329
330       /** \name Owner and group */
331       //@{
332       uid_t  owner()   const { return isExist() ? statbuf_C.st_uid : 0; }
333       gid_t  group()   const { return isExist() ? statbuf_C.st_gid : 0; }
334       //@}
335
336       /** \name Permission according to current uid/gid. */
337       //@{
338       /** Returns current users permission (<tt>[0-7]</tt>)*/
339       mode_t userMay() const;
340
341       bool   userMayR() const { return( userMay() & 04 ); }
342       bool   userMayW() const { return( userMay() & 02 ); }
343       bool   userMayX() const { return( userMay() & 01 ); }
344
345       bool   userMayRW()  const { return( (userMay() & 06) == 06 ); }
346       bool   userMayRX()  const { return( (userMay() & 05) == 05 ); }
347       bool   userMayWX()  const { return( (userMay() & 03) == 03 ); }
348
349       bool   userMayRWX() const { return( userMay() == 07 ); }
350       //@}
351
352       /** \name Device and inode info. */
353       //@{
354       ino_t  ino()     const { return isExist() ? statbuf_C.st_ino  : 0; }
355       dev_t  dev()     const { return isExist() ? statbuf_C.st_dev  : 0; }
356       dev_t  rdev()    const { return isExist() ? statbuf_C.st_rdev : 0; }
357
358       unsigned int major() const;
359       unsigned int minor() const;
360       //@}
361
362       /** \name Size info. */
363       //@{
364       off_t         size()    const { return isExist() ? statbuf_C.st_size : 0; }
365       unsigned long blksize() const { return isExist() ? statbuf_C.st_blksize : 0; }
366       unsigned long blocks()  const { return isExist() ? statbuf_C.st_blocks  : 0; }
367       //@}
368
369       /** \name Time stamps. */
370       //@{
371       time_t atime()   const { return isExist() ? statbuf_C.st_atime : 0; } /* time of last access */
372       time_t mtime()   const { return isExist() ? statbuf_C.st_mtime : 0; } /* time of last modification */
373       time_t ctime()   const { return isExist() ? statbuf_C.st_ctime : 0; }
374       //@}
375
376     private:
377       Pathname    path_t;
378       struct stat statbuf_C;
379       Mode        mode_e;
380       int         error_i;
381     };
382     ///////////////////////////////////////////////////////////////////
383
384     /** \relates PathInfo Stream output. */
385     extern std::ostream & operator<<( std::ostream & str, const PathInfo & obj );
386
387     ///////////////////////////////////////////////////////////////////
388
389     ///////////////////////////////////////////////////////////////////
390     /** \name Directory related functions. */
391     //@{
392     /**
393      * Like '::mkdir'. Attempt to create a new directory named path. mode
394      * specifies the permissions to use. It is modified by the process's
395      * umask in the usual way.
396      *
397      * @return 0 on success, errno on failure
398      **/
399     int mkdir( const Pathname & path, unsigned mode = 0755 );
400
401     /**
402      * Like 'mkdir -p'. No error if directory exists. Make parent directories
403      * as needed. mode specifies the permissions to use, if directories have to
404      * be created. It is modified by the process's umask in the usual way.
405      *
406      * @return 0 on success, errno on failure
407      **/
408     int assert_dir( const Pathname & path, unsigned mode = 0755 );
409
410     /**
411      * Like '::rmdir'. Delete a directory, which must be empty.
412      *
413      * @return 0 on success, errno on failure
414      **/
415     int rmdir( const Pathname & path );
416
417     /**
418      * Like 'rm -r DIR'. Delete a directory, recursively removing its contents.
419      *
420      * @return 0 on success, ENOTDIR if path is not a directory, otherwise the
421      * commands return value.
422      **/
423     int recursive_rmdir( const Pathname & path );
424
425     /**
426      * Like 'rm -r DIR/ *'. Delete directory contents, but keep the directory itself.
427      *
428      * @return 0 on success, ENOTDIR if path is not a directory, otherwise the
429      * commands return value.
430      **/
431     int clean_dir( const Pathname & path );
432
433     /**
434      * Like 'cp -a srcpath destpath'. Copy directory tree. srcpath/destpath must be
435      * directories. 'basename srcpath' must not exist in destpath.
436      *
437      * @return 0 on success, ENOTDIR if srcpath/destpath is not a directory, EEXIST if
438      * 'basename srcpath' exists in destpath, otherwise the commands return value.
439      **/
440     int copy_dir( const Pathname & srcpath, const Pathname & destpath );
441
442     /**
443      * Like 'cp -a srcpath/. destpath'. Copy the content of srcpath recursively
444      * into destpath. Both \p srcpath and \p destpath has to exists.
445      *
446      * @return 0 on success, ENOTDIR if srcpath/destpath is not a directory,
447      * EEXIST if srcpath and destpath are equal, otherwise the commands
448      * return value.
449      */
450     int copy_dir_content( const Pathname & srcpath, const Pathname & destpath);
451
452     /**
453      * Return content of directory via retlist. If dots is false
454      * entries starting with '.' are not reported. "." and ".."
455      * are never reported.
456      *
457      * Returns just the directory entries as string.
458      *
459      * @return 0 on success, errno on failure.
460      *
461      * \todo provide some readdirIterator.
462      **/
463
464     int readdir( std::list<std::string> & retlist,
465                  const Pathname & path, bool dots = true );
466
467     /**
468      * Return content of directory via retlist. If dots is false
469      * entries starting with '.' are not reported. "." and ".."
470      * are never reported.
471      *
472      * Returns the directory entries prefixed with \a path.
473      *
474      * @return 0 on success, errno on failure.
475      *
476      * \todo provide some readdirIterator.
477      **/
478
479     int readdir( std::list<Pathname> & retlist,
480                  const Pathname & path, bool dots = true );
481
482     /** Listentry returned by readdir. */
483     struct DirEntry {
484       std::string name;
485       FileType    type;
486       DirEntry( const std::string & name_r = std::string(), FileType type_r = FT_NOT_AVAIL )
487       : name( name_r )
488       , type( type_r )
489       {}
490     };
491
492     /** Returned by readdir. */
493     typedef std::list<DirEntry> DirContent;
494
495     /**
496      * Return content of directory via retlist. If dots is false
497      * entries starting with '.' are not reported. "." and ".."
498      * are never reported.
499      *
500      * The type of individual directory entries is determined accoding to
501      * statmode (i.e. via stat or lstat).
502      *
503      * @return 0 on success, errno on failure.
504      **/
505     int readdir( DirContent & retlist, const Pathname & path,
506                  bool dots = true, PathInfo::Mode statmode = PathInfo::STAT );
507
508
509     /**
510      * Check if the specified directory is empty.
511      * \param path The path of the directory to check.
512      * \return 0 if directory is empty, -1 if not, errno > 0 on failure.
513      */
514     int is_empty_dir(const Pathname & path);
515
516     //@}
517
518     ///////////////////////////////////////////////////////////////////
519     /** \name File related functions. */
520     //@{
521     /**
522      * Like '::unlink'. Delete a file (symbolic link, socket, fifo or device).
523      *
524      * @return 0 on success, errno on failure
525      **/
526     int unlink( const Pathname & path );
527
528     /**
529      * Like '::rename'. Renames a file, moving it between directories if required.
530      *
531      * @return 0 on success, errno on failure
532      **/
533     int rename( const Pathname & oldpath, const Pathname & newpath );
534
535     /**
536      * Like 'cp file dest'. Copy file to destination file.
537      *
538      * @return 0 on success, EINVAL if file is not a file, EISDIR if
539      * destiantion is a directory, otherwise the commands return value.
540      **/
541     int copy( const Pathname & file, const Pathname & dest );
542
543     /**
544      * Like '::symlink'. Creates a symbolic link named newpath which contains
545      * the string oldpath. If newpath exists it will not be overwritten.
546      *
547      * @return 0 on success, errno on failure.
548      **/
549     int symlink( const Pathname & oldpath, const Pathname & newpath );
550
551     /**
552      * Like '::link'. Creates a hard link named newpath to an existing file
553      * oldpath. If newpath exists it will not be overwritten.
554      *
555      * @return 0 on success, errno on failure.
556      **/
557     int hardlink( const Pathname & oldpath, const Pathname & newpath );
558
559     /**
560      * Like 'cp file dest'. Copy file to dest dir.
561      *
562      * @return 0 on success, EINVAL if file is not a file, ENOTDIR if dest
563      * is no directory, otherwise the commands return value.
564      **/
565     int copy_file2dir( const Pathname & file, const Pathname & dest );
566     //@}
567
568     ///////////////////////////////////////////////////////////////////
569     /** \name Digest computaion.
570      * \todo check cooperation with zypp::Digest
571     */
572     //@{
573     /**
574      * Compute a files md5sum.
575      *
576      * @return the files md5sum on success, otherwise an empty string..
577      **/
578     std::string md5sum( const Pathname & file );
579
580     /**
581      * Compute a files sha1sum.
582      *
583      * @return the files sha1sum on success, otherwise an empty string..
584      **/
585     std::string sha1sum( const Pathname & file );
586     //@}
587
588     /**
589      * Compute a files checksum
590      *
591      * @return the files checksum on success, otherwise an empty string..
592      **/
593     std::string checksum( const Pathname & file, const std::string &algorithm );
594
595     /**
596      * check files checksum
597      *
598      * @return true if the checksum matchs
599      **/
600     bool is_checksum( const Pathname & file, const CheckSum &checksum );
601
602     ///////////////////////////////////////////////////////////////////
603     /** \name Changing permissions. */
604     //@{
605     /**
606      * Like '::chmod'. The mode of the file given by path is changed.
607      *
608      * @return 0 on success, errno on failure
609      **/
610     int chmod( const Pathname & path, mode_t mode );
611     //@}
612
613     ///////////////////////////////////////////////////////////////////
614     /** \name Misc. */
615     //@{
616     /**
617      * Test whether a file is compressed (gzip/bzip2).
618      *
619      * @return ZT_GZ, ZT_BZ2 if file is compressed, otherwise ZT_NONE.
620      **/
621     enum ZIP_TYPE { ZT_NONE, ZT_GZ, ZT_BZ2 };
622
623     ZIP_TYPE zipType( const Pathname & file );
624
625     /**
626      * Erase whatever happens to be located at path (file or directory).
627      *
628      * @return 0 on success.
629      *
630      * \todo check cooperation with zypp::TmpFile and zypp::TmpDir
631      **/
632     int erase( const Pathname & path );
633
634     /**
635      * Report free disk space on a mounted file system.
636      *
637      * path is the path name of any file within the mounted filesystem.
638      *
639      * @return Free disk space or -1 on error.
640      **/
641     ByteCount df( const Pathname & path );
642     //@}
643
644     /////////////////////////////////////////////////////////////////
645   } // namespace filesystem
646   ///////////////////////////////////////////////////////////////////
647
648   /** Dragged into namespace zypp. */
649   using filesystem::PathInfo;
650
651   /////////////////////////////////////////////////////////////////
652 } // namespace zypp
653 ///////////////////////////////////////////////////////////////////
654 #endif // ZYPP_PATHINFO_H