Implement mkdtemp()
[libi2ncommon] / src / filefunc.cpp
1 /*
2 The software in this package is distributed under the GNU General
3 Public License version 2 (with a special exception described below).
4
5 A copy of GNU General Public License (GPL) is included in this distribution,
6 in the file COPYING.GPL.
7
8 As a special exception, if other files instantiate templates or use macros
9 or inline functions from this file, or you compile this file and link it
10 with other works to produce a work based on this file, this file
11 does not by itself cause the resulting work to be covered
12 by the GNU General Public License.
13
14 However the source code for this file must still be made available
15 in accordance with section (3) of the GNU General Public License.
16
17 This exception does not invalidate any other reasons why a work based
18 on this file might be covered by the GNU General Public License.
19 */
20 /***************************************************************************
21                           escape.cpp  -  escaping of strings
22                              -------------------
23     begin                : Sun Nov 14 1999
24     copyright            : (C) 1999 by Intra2net AG
25  ***************************************************************************/
26
27 #include <list>
28 #include <string>
29 #include <fstream>
30 #include <sstream>
31 #include <iostream>
32 #include <stdexcept>
33
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <dirent.h>
37 #include <pwd.h>
38 #include <grp.h>
39 #include <unistd.h>
40 #include <errno.h>
41 #include <string.h>
42
43 #include <boost/scoped_array.hpp>
44 #include "filefunc.hxx"
45 #include "stringfunc.hxx"
46
47
48 namespace I2n
49 {
50
51 using namespace std;
52
53 /*
54 ** implementation of Stat
55 */
56
57 Stat::Stat()
58 : Valid(false)
59 {
60    clear();
61 } // eo Stat::Stat()
62
63
64 Stat::Stat(const std::string& path, bool follow_links)
65 {
66     stat(path,follow_links);
67 } // eo Stat::Stat(const std::string&,bool)
68
69
70 Stat::~Stat()
71 {
72 } // eo Stat::~Stat()
73
74
75 /**
76  * @brief updates the internal data.
77  *
78  * In other words: stat()'s the file again.
79  */
80 void Stat::recheck()
81 {
82     if (! Path.empty())
83     {
84         // pass a copy of Path: otherwise clear() would leave an empty reference
85         stat(string(Path), FollowLinks);
86     }
87 } // eo Stat::recheck()
88
89
90 /**
91  * @brief calls stat() or lstat() to get the information for the given path
92  *  and stores that information.
93  * @param path the path which should be checked
94  * @param follow_links determine if (symbalic) links should be followed.
95  */
96 void Stat::stat(const std::string& path, bool follow_links)
97 {
98     clear();
99     Path= path;
100     FollowLinks= follow_links;
101     struct stat stat_info;
102     int res;
103     res = ( follow_links ? ::stat(path.c_str(), &stat_info) : ::lstat(path.c_str(), &stat_info) );
104     if ( 0 == res )
105     {
106         Device = stat_info.st_dev;
107         Inode  = stat_info.st_ino;
108         Mode   = (stat_info.st_mode & ~(S_IFMT));
109         NumLinks = stat_info.st_nlink;
110         Uid    = stat_info.st_uid;
111         Gid    = stat_info.st_gid;
112         DeviceType = stat_info.st_rdev;
113         Size   = stat_info.st_size;
114         Atime  = stat_info.st_atime;
115         Mtime  = stat_info.st_mtime;
116         Ctime  = stat_info.st_atime;
117
118         IsLink=          S_ISLNK( stat_info.st_mode );
119         IsRegular=       S_ISREG( stat_info.st_mode );
120         IsDirectory=     S_ISDIR( stat_info.st_mode );
121         IsCharacterDevice= S_ISCHR( stat_info.st_mode );
122         IsBlockDevice=   S_ISBLK( stat_info.st_mode );
123         IsFifo=          S_ISFIFO( stat_info.st_mode );
124         IsSocket=        S_ISSOCK( stat_info.st_mode );
125     }
126     Valid = (0 == res);
127 } // eo Stat::stat(const std::string&,bool)
128
129
130 /**
131  * @brief clears the internal data.
132  */
133 void Stat::clear()
134 {
135     Path.clear();
136     Valid= false;
137
138     Device = 0;
139     Inode  = 0;
140     Mode   = 0;
141     NumLinks = 0;
142     Uid    = 0;
143     Gid    = 0;
144     DeviceType = 0;
145     Size   = 0;
146     Atime  = 0;
147     Mtime  = 0;
148     Ctime  = 0;
149
150     IsLink= false;
151     IsRegular= false;
152     IsDirectory= false;
153     IsCharacterDevice= false;
154     IsBlockDevice= false;
155     IsFifo= false;
156     IsSocket= false;
157 } // eo Stat::clear()
158
159
160 /**
161  * @brief checks if another instance describes the same file.
162  * @param rhs the other instance.
163  * @return @a true iff the other instance describes the same file.
164  * @note
165  * The "same file" means that the files are located on the same device and use the same inode.
166  * They might still have two different directory entries (different paths)!
167  */
168 bool Stat::is_same_as(const Stat& rhs)
169 {
170     return Valid and rhs.Valid
171         and ( Device == rhs.Device)
172         and ( Inode == rhs.Inode);
173 } // eo Stat::is_same_as(const Stat& rhs);
174
175
176 /**
177  * @brief checks if this and the other instance describe the same device.
178  * @param rhs the other instance.
179  * @return @a true if we and the other instance describe a device and the same device.
180  *
181  * "Same device" means that the devices have the same type and the same major and minor id.
182  */
183 bool Stat::is_same_device_as(const Stat& rhs)
184 {
185     return is_device() and rhs.is_device()
186         and ( IsBlockDevice == rhs.IsBlockDevice )
187         and ( IsCharacterDevice == rhs.IsCharacterDevice )
188         and ( DeviceType == rhs.DeviceType);
189 } // eo Stat::is_same_device_as(const Stat&)
190
191 /**
192  * @brief check existence of a path.
193  * @param path path which should be tested.
194  * @return @a true iff path exists.
195  */
196 bool path_exists(const std::string& path)
197 {
198     struct stat stat_info;
199     int res = ::stat(path.c_str(), &stat_info);
200     if (res) return false;
201     return true;
202 } // eo path_exists(const std::string&)
203
204 /**
205  * @brief check existence of a regular file.
206  * @param path path which should be tested.
207  * @return @a true if path exists and is a regular file (or a link pointing to a regular file).
208  * @note this checks for regular files; not for the pure exitsnace of a path; use pathExists() for that.
209  * @see pathExists
210  */
211 bool file_exists(const std::string& path)
212 {
213     struct stat stat_info;
214     int res = ::stat(path.c_str(), &stat_info);
215     if (res) return false;
216     return S_ISREG(stat_info.st_mode);
217 } // eo file_exists(const std::string&)
218
219 // TODO: Use Stat class
220 /**
221  * Get size of file
222  * @param name filename to get size for
223  * @return file size or -1 if file does not exist
224  */
225 long file_size (const string &name)
226 {
227     long iReturn = -1;
228
229     struct stat statbuff;
230
231     if (lstat(name.c_str(), &statbuff) < 0)
232         return -1;
233
234     if (!S_ISREG(statbuff.st_mode))
235         return -1;
236
237     iReturn=statbuff.st_size;
238
239     return iReturn;
240 }
241
242 /**
243  * @brief tests the last modification time stamp of a path.
244  * @param path path which should be tested.
245  * @return the last modification time or 0 if the path doen't exist.
246  */
247 time_t file_mtime(const std::string& path)
248 {
249     struct stat stat_info;
250     int res = ::stat(path.c_str(), &stat_info);
251     if (res) return 0;
252     return stat_info.st_mtime;
253 } // eo file_mtime(const std::string&)
254
255
256 /**
257  * @brief reads the contents of a directory.
258  * @param path the path to the directory whose contents should be read.
259  * @param[out] result the resulting list of names.
260  * @param include_dot_names determines if dot-files should be included in the list.
261  * @return @a true if reading the directory was succesful, @a false on error.
262  */
263 bool get_dir(
264     const std::string& path,
265     std::vector< std::string >& result,
266     bool include_dot_names )
267 {
268     DIR* dir = ::opendir( path.c_str());
269     if (!dir)
270     {
271         return false;
272     }
273     struct dirent *entry;
274     while ( NULL != (entry = ::readdir(dir)) )
275     {
276         std::string name( entry->d_name );
277         if (! include_dot_names && (name[0] == '.') )
278         {
279             continue;
280         }
281         result.push_back( name );
282     }
283     ::closedir(dir);
284     return true;
285 } // eo get_dir(const std::string&,std::vector< std::string >&,bool)
286
287
288 /**
289  * @brief reads the contents of a directory
290  * @param path the path to the directory whose contents should be read.
291  * @param include_dot_names determines if dot-files should be included in the list.
292  * @return the list of names (empty on error).
293  */
294 std::vector< std::string > get_dir(const std::string& path, bool include_dot_names )
295 {
296     std::vector< std::string > result;
297     get_dir(path,result,include_dot_names);
298     return result;
299 } // eo get_dir(const std::string&,bool)
300
301
302
303 /**
304  * @brief removes a file from a filesystem.
305  * @param path path to the file.
306  * @return @a true iff the unlink was successful.
307  */
308 bool unlink( const std::string& path )
309 {
310     int res = ::unlink( path.c_str() );
311     return (res == 0);
312 } // eo unlink(const std::string&)
313
314
315
316 /**
317  * @brief creates a symbolic link named @a link_name to @a target.
318  * @param target the target the link should point to.
319  * @param link_name the name of the link.
320  * @param force if @a true, the (file or link) @a link_name is removed if it exists.
321  * @return @a true iff the symlink was successfully created.
322  */
323 bool symlink(const std::string& target, const std::string& link_name, bool force)
324 {
325     int res= -1;
326     if (target.empty() or link_name.empty() or target == link_name)
327     {
328         // no, we don't do this!
329         return false;
330     }
331     std::string n_target;
332     if (target[0] == '/') // absolute target?
333     {
334         n_target= target;
335     }
336     else // relative target
337     {
338         // for stat'ing: prepend dir of link_name:
339         n_target= dirname(link_name)+"/"+ target;
340     }
341     Stat target_stat(n_target, false);
342     Stat link_name_stat(link_name, false);
343     if (target_stat.exists() && link_name_stat.exists())
344     {
345         if (link_name_stat.is_same_as(target_stat)
346             or link_name_stat.is_same_device_as(target_stat) )
347         {
348             return false;
349         }
350         //TODO: more consistency checks?!
351     }
352     if (link_name_stat.exists())
353     {
354         // the link name already exists.
355         if (force)
356         {
357             // "force" as given, so try to remove the link_name:
358             unlink(link_name);
359             // update the stat:
360             link_name_stat.recheck();
361         }
362     }
363     if (link_name_stat.exists())
364     {
365         // well, if the link_name still exists; we cannot create that link:
366         errno = EEXIST;
367         return false;
368     }
369     res= ::symlink(target.c_str(), link_name.c_str());
370     return (0 == res);
371 } // eo symlink(const std::string&,const std::string&,bool)
372
373
374
375 /**
376  * @brief reads the target of a symbolic link.
377  * @param path path to the symbolic link
378  * @return the target of the link or an empty string on error.
379  */
380 std::string read_link(const std::string& path)
381 {
382     errno= 0;
383     Stat stat(path,false);
384     if (!stat || !stat.is_link())
385     {
386         return std::string();
387     }
388     int buffer_size= PATH_MAX+1 + 128;
389     boost::scoped_array<char> buffer_ptr( new char[buffer_size] );
390     int res= ::readlink( path.c_str(), buffer_ptr.get(), buffer_size-1 );
391     if (res >= 0)
392     {
393         return std::string( buffer_ptr.get(), res );
394     }
395     return std::string();
396 } // eo read_link(const std::string&)
397
398
399
400 /**
401  * @brief returns content of a file as string.
402  *
403  * A simple (q'n'd) function for retrieving content of a file as string.<br>
404  * Also able to read special (but regular) files which don't provide a size when stat'ed
405  * (like files in the /proc filesystem).
406  *
407  * @param path path to the file.
408  * @return the content of the file as string (empty if file could be opened).
409  */
410 std::string read_file(const std::string& path)
411 {
412     Stat stat(path);
413     if (!stat.is_reg())
414     {
415         return std::string();
416     }
417     std::ifstream f( path.c_str(), std::ios::in | std::ios::binary );
418     std::string result;
419     if (f.is_open())
420     {
421         // NOTE: there are cases where we don't know the correct size (/proc files...)
422         // therefore we only use the size for reserving space if we know it, but don't
423         // use it when reading the file!
424         if (stat.size() > 0)
425         {
426             // if we know the size, we reserve enough space.
427             result.reserve( stat.size() );
428         }
429         char buffer[2048];
430         while (f.good())
431         {
432             f.read(buffer, sizeof(buffer));
433             result.append(buffer, f.gcount());
434         }
435     }
436     return result;
437 } // eo read_file(const std::string&)
438
439
440 /**
441  * @brief writes a string to a file.
442  * @param path path to the file
443  * @param data the data which should be written into the file
444  * @return @a true if the data was written to the file.
445  *
446  * A simple (q'n'd) function for writing a string to a file.
447  */
448 bool write_file(const std::string& path, const std::string& data)
449 {
450     std::ofstream f( path.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
451     if (f.good())
452     {
453         f.write( data.data(), data.size() );
454         return f.good();
455     }
456     else
457     {
458         return false;
459     }
460 } // eo write_file(const std::string&,const std::string&)
461
462
463 /**
464  * Copy file in 4k blocks from source to target.
465  * Overwrites the target if it already exists.
466  *
467  * On error the target file gets removed.
468  *
469  * @param src source file
470  * @param dest target file
471  * @return true if all is ok, false on error
472  */
473 bool copy_file(const std::string& src, const std::string& dest)
474 {
475     std::ifstream input( src.c_str(), std::ios::in | std::ios::binary );
476     if (!input)
477         return false;
478
479     std::ofstream output( dest.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
480     if (!output)
481         return false;
482
483     // Out of disc space?
484     if (!copy_stream(input,output))
485     {
486         output.close();
487         unlink(dest);
488         return false;
489     }
490
491     return true;
492 }
493
494 /**
495  * Copy streams in 4k blocks.
496  *
497  * @param is source stream
498  * @param os target stream
499  * @return true if all is ok, false on error
500  */
501 bool copy_stream(std::istream& is, std::ostream& os)
502 {
503    if (!is)
504       return false;
505
506    if (!os)
507       return false;
508
509    char buffer[4096];
510    while (is.good())
511    {
512       is.read(buffer, sizeof(buffer));
513       os.write(buffer, is.gcount());
514
515       // Can't write?
516       if (!os.good())
517          return false;
518    }
519
520    return true;
521 }
522
523 /**
524  * @brief returns the filename part of a path (last component)
525  * @param path the path.
526  * @return the last component of the path.
527  */
528 std::string basename(const std::string& path)
529 {
530     std::string::size_type pos= path.rfind('/');
531     if (pos != std::string::npos)
532     {
533         return path.substr(pos+1);
534     }
535     return path;
536 } // eo basename(const std::string&)
537
538
539 /**
540  * @brief returns the directory part of a path.
541  * @param path the path.
542  * @return the directory part of the path.
543  */
544 std::string dirname(const std::string& path)
545 {
546     std::string::size_type pos= path.rfind('/');
547     if (pos != std::string::npos)
548     {
549         std::string result(path,0,pos);
550         if (result.empty())
551         {
552             return ".";
553         }
554         return result;
555     }
556     return ".";
557 } // eo dirname(const std::string&)
558
559
560 /**
561  * @brief normalizes a path.
562  *
563  * This method removes empty and "." elements.
564  * It also resolves ".." parts by removing previous path elements if possible.
565  * Leading ".." elements are preserved when a relative path was given; else they are removed.
566  * Trailing slashes are removed.
567  *
568  * @param path the path which should be normalized.
569  * @return the normalized path.
570  */
571
572 std::string normalize_path(const std::string& path)
573 {
574     if (path.empty())
575     {
576         return std::string();
577     }
578     // remember if the given path was absolute since this information vanishes when
579     // we split the path (since we split with omitting empty parts...)
580     bool is_absolute= (path[0]=='/');
581     std::list< std::string >  parts;
582     std::list< std::string >  result_parts;
583     
584     split_string(path,parts,"/",true);
585     
586     for(std::list< std::string >::const_iterator it_parts= parts.begin();
587         it_parts != parts.end();
588         ++it_parts)
589     {
590         std::string part(*it_parts); //convenience..
591         if (part == std::string(".") )
592         {
593             // single dot is "current path"; ignore!
594             continue;
595         }
596         if (part == std::string("..") )
597         {
598             // double dot is "one part back"
599             if (result_parts.empty())
600             {
601                 if (is_absolute)
602                 {
603                     // ignore since we cannot move behind / on absolute paths...
604                 }
605                 else
606                 {
607                     // on relative path, we need to store the "..":
608                     result_parts.push_back(part);
609                 }
610             }
611             else if (result_parts.back() == std::string("..") )
612             {
613                 // if last element was already "..", we need to store the new one again...
614                 // (PS: no need for "absolute" check; this can only be the case on relative path)
615                 result_parts.push_back(part);
616             }
617             else
618             {
619                 // remove last element.
620                 result_parts.pop_back();
621             }
622             continue;
623         }
624         result_parts.push_back(part);
625     }
626     std::string result;
627     if (is_absolute)
628     {
629         result= "/";
630     }
631     result+= join_string(result_parts,"/");
632     return result;
633 } // eo normalize_path(const std::string&)
634
635
636 /**
637  * @brief calls fsync on a given directory to sync all it's metadata
638  * @param path the path of the directory.
639  * @return true if successful
640  */
641 bool dirsync(const std::string& path)
642 {
643     // sync the directory the file is in
644     DIR* dir=opendir(path.c_str());
645     if (dir == NULL)
646         return false;
647
648     int ret=fsync(dirfd(dir));
649
650     closedir(dir);
651
652     return (ret==0);
653 }
654
655 /**
656  * @brief changes the file(/path) mode.
657  * @param path the path to change the mode for.
658  * @param mode the new file mode.
659  * @return @a true iff the file mode was sucessfully changed.
660  */
661 bool chmod(const std::string& path, int mode)
662 {
663     int res= ::chmod(path.c_str(), mode);
664     return (res==0);
665 } // eo chmod(const std::string&,int)
666
667
668 /**
669  * @brief changed the owner of a file(/path)
670  * @param path the path to change the owner for.
671  * @param user the new file owner.
672  * @param group the new file group.
673  * @return @a true iff the file owner was succesfully changed.
674  *
675  * @note
676  * the validity of user and group within the system is not checked.
677  * This is intentional since this way we can use id's which are not assigned.
678  */
679 bool chown(const std::string& path, const I2n::User& user, const I2n::Group& group)
680 {
681     uid_t uid= user.Uid;
682     if (uid<0) return false;
683     gid_t gid= group.Gid;
684     if (gid<0) gid= user.Gid;
685     if (gid<0) return false;
686     int res= ::chown( path.c_str(), uid, gid);
687     return (res==0);
688 } // eo chown(const std::string&,const User&,const Group&)
689
690 /**
691  * Recursive delete of files and directories
692  * @param path File or directory to delete
693  * @param error Will contain the error if the return value is false
694  * @return true on success, false otherwise
695  */
696 bool recursive_delete(const std::string &path, std::string *error)
697 {
698     bool rtn = true;
699
700     try {
701         struct stat my_stat;
702         if (stat(path.c_str(), &my_stat) != 0) {
703             throw runtime_error("can't stat " + path);
704         }
705
706         if (S_ISDIR(my_stat.st_mode)) {
707             DIR *dir = opendir(path.c_str());
708             if (!dir) {
709                 throw runtime_error("can't open directory " + path);
710             }
711
712             struct dirent *entry;
713             while ((entry = readdir(dir))) {
714                 string filename = entry->d_name;
715                 if (filename == "." || filename == "..") {
716                     continue;
717                 }
718
719                 // Delete subdir or file.
720                 rtn = recursive_delete(path + "/" + filename, error);
721                 if (rtn == false) {
722                     break;
723                 }
724             }
725
726             closedir(dir);
727             if (rmdir(path.c_str()) != 0) {
728                 throw runtime_error("can't remove directory " + path);
729             }
730         } else {
731             if (unlink(path.c_str()) != 0) {
732                 throw runtime_error("can't unlink " + path);
733             }
734         }
735     } catch (exception &e) {
736         if (error) {
737             ostringstream out;
738             out << e.what() << " (" << strerror(errno) << ")";
739             *error = out.str();
740         }
741         rtn = false;
742     } catch (...) {
743         if (error) {
744             ostringstream out;
745             out << "unknown error (" << strerror(errno) << ")";
746             *error = out.str();
747         }
748         rtn = false;
749     }
750
751     return rtn;
752 } // eo recursive_delete(const std::string&,std::string*)
753
754 /**
755     Create a unique temporary directory from path_template.
756     @param Path template. The last six characters must be XXXXXX.
757     @return Name of new directory or empty string on error.
758 */
759 std::string mkdtemp(const std::string &path_template)
760 {
761     boost::scoped_array<char> buf( new char[path_template.size()+1] );
762     path_template.copy(buf.get(), path_template.size());
763     buf[path_template.size()]=0;
764
765     char *unique_dir = ::mkdtemp(buf.get());
766     if (!unique_dir)
767         return "";
768
769     // Scoped pointer is still valid
770     return std::string(unique_dir);
771 }
772
773
774 } // eo namespace I2n