]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_path.cxx
utf8ToLatin1: return original instead of crashing on non-UTF-8 input
[simgear.git] / simgear / misc / sg_path.cxx
1 // sg_path.cxx -- routines to abstract out path separator differences
2 //               between MacOS and the rest of the world
3 //
4 // Written by Curtis L. Olson, started April 1999.
5 //
6 // Copyright (C) 1999  Curtis L. Olson - http://www.flightgear.org/~curt
7 //
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Library General Public
10 // License as published by the Free Software Foundation; either
11 // version 2 of the License, or (at your option) any later version.
12 //
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // Library General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24
25 #include <simgear/compiler.h>
26
27 #include <simgear_config.h>
28 #include <simgear/debug/logstream.hxx>
29 #include <simgear/misc/strutils.hxx>
30 #include <stdio.h>
31 #include <sys/stat.h>
32 #include <errno.h>
33 #include <fstream>
34
35 #ifdef _WIN32
36 #  include <direct.h>
37 #endif
38 #include "sg_path.hxx"
39
40 #include <boost/algorithm/string/case_conv.hpp>
41
42 using std::string;
43 using simgear::strutils::starts_with;
44
45 /**
46  * define directory path separators
47  */
48
49 static const char sgDirPathSep = '/';
50 static const char sgDirPathSepBad = '\\';
51
52 #ifdef _WIN32
53 static const char sgSearchPathSep = ';';
54 #else
55 static const char sgSearchPathSep = ':';
56 #endif
57
58 #ifdef _WIN32
59 #include <ShlObj.h> // for CSIDL
60
61 static SGPath pathForCSIDL(int csidl, const SGPath& def)
62 {
63         typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
64         static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
65
66         // lazy open+resolve of shell32
67         if (!SHGetSpecialFolderPath) {
68                 HINSTANCE shellDll = ::LoadLibrary("shell32");
69                 SHGetSpecialFolderPath = (GetSpecialFolderPath) GetProcAddress(shellDll, "SHGetSpecialFolderPathA");
70         }
71
72         if (!SHGetSpecialFolderPath){
73                 return def;
74         }
75
76         char path[MAX_PATH];
77         if (SHGetSpecialFolderPath(0, path, csidl, false)) {
78                 return SGPath(path, def.getPermissionChecker());
79         }
80
81         return def;
82 }
83 #elif __APPLE__
84
85 // defined in CocoaHelpers.mm
86 SGPath appleSpecialFolder(int dirType, int domainMask, const SGPath& def);
87
88 #else
89 static SGPath getXDGDir( const std::string& name,
90                          const SGPath& def,
91                          const std::string& fallback )
92 {
93   // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
94
95   // $XDG_CONFIG_HOME defines the base directory relative to which user specific
96   // configuration files should be stored. If $XDG_CONFIG_HOME is either not set
97   // or empty, a default equal to $HOME/.config should be used.
98   const SGPath user_dirs = SGPath::fromEnv( "XDG_CONFIG_HOME",
99                                             SGPath::home() / ".config")
100                          / "user-dirs.dirs";
101
102   // Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
103   // homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an absolute
104   // path. No other format is supported.
105   const std::string XDG_ID = "XDG_" + name + "_DIR=\"";
106
107   std::ifstream user_dirs_file( user_dirs.c_str() );
108   std::string line;
109   while( std::getline(user_dirs_file, line).good() )
110   {
111     if( !starts_with(line, XDG_ID) || *line.rbegin() != '"' )
112       continue;
113
114     // Extract dir from XDG_<name>_DIR="<dir>"
115     line = line.substr(XDG_ID.length(), line.length() - XDG_ID.length() - 1 );
116
117     const std::string HOME = "$HOME";
118     if( starts_with(line, HOME) )
119       return SGPath::home(def)
120            / simgear::strutils::unescape(line.substr(HOME.length()));
121
122     return SGPath(line, def.getPermissionChecker());
123   }
124
125   if( def.isNull() )
126     return SGPath::home(def) / fallback;
127
128   return def;
129 }
130 #endif
131
132 // For windows, replace "\" by "/".
133 void
134 SGPath::fix()
135 {
136     string::size_type sz = path.size();
137     for ( string::size_type i = 0; i < sz; ++i ) {
138         if ( path[i] == sgDirPathSepBad ) {
139             path[i] = sgDirPathSep;
140         }
141     }
142     // drop trailing "/"
143     while ((sz>1)&&(path[sz-1]==sgDirPathSep))
144     {
145         path.resize(--sz);
146     }
147 }
148
149
150 // default constructor
151 SGPath::SGPath(PermissionChecker validator)
152     : path(""),
153     _permission_checker(validator),
154     _cached(false),
155     _rwCached(false),
156     _cacheEnabled(true)
157 {
158 }
159
160
161 // create a path based on "path"
162 SGPath::SGPath( const std::string& p, PermissionChecker validator )
163     : path(p),
164     _permission_checker(validator),
165     _cached(false),
166     _rwCached(false),
167     _cacheEnabled(true)
168 {
169     fix();
170 }
171
172 // create a path based on "path" and a "subpath"
173 SGPath::SGPath( const SGPath& p,
174                 const std::string& r,
175                 PermissionChecker validator )
176     : path(p.path),
177     _permission_checker(validator),
178     _cached(false),
179     _rwCached(false),
180     _cacheEnabled(p._cacheEnabled)
181 {
182     append(r);
183     fix();
184 }
185
186 SGPath::SGPath(const SGPath& p) :
187   path(p.path),
188   _permission_checker(p._permission_checker),
189   _cached(p._cached),
190   _rwCached(p._rwCached),
191   _cacheEnabled(p._cacheEnabled),
192   _canRead(p._canRead),
193   _canWrite(p._canWrite),
194   _exists(p._exists),
195   _isDir(p._isDir),
196   _isFile(p._isFile),
197   _modTime(p._modTime)
198 {
199 }
200
201 SGPath& SGPath::operator=(const SGPath& p)
202 {
203   path = p.path;
204   _permission_checker = p._permission_checker,
205   _cached = p._cached;
206   _rwCached = p._rwCached;
207   _cacheEnabled = p._cacheEnabled;
208   _canRead = p._canRead;
209   _canWrite = p._canWrite;
210   _exists = p._exists;
211   _isDir = p._isDir;
212   _isFile = p._isFile;
213   _modTime = p._modTime;
214   return *this;
215 }
216
217 // destructor
218 SGPath::~SGPath() {
219 }
220
221
222 // set path
223 void SGPath::set( const string& p ) {
224     path = p;
225     fix();
226     _cached = false;
227     _rwCached = false;
228 }
229
230 //------------------------------------------------------------------------------
231 void SGPath::setPermissionChecker(PermissionChecker validator)
232 {
233   _permission_checker = validator;
234   _rwCached = false;
235 }
236
237 //------------------------------------------------------------------------------
238 SGPath::PermissionChecker SGPath::getPermissionChecker() const
239 {
240   return _permission_checker;
241 }
242
243 //------------------------------------------------------------------------------
244 void SGPath::set_cached(bool cached)
245 {
246   _cacheEnabled = cached;
247 }
248
249 // append another piece to the existing path
250 void SGPath::append( const string& p ) {
251     if ( path.empty() ) {
252         path = p;
253     } else {
254     if ( p[0] != sgDirPathSep ) {
255         path += sgDirPathSep;
256     }
257         path += p;
258     }
259     fix();
260     _cached = false;
261     _rwCached = false;
262 }
263
264 //------------------------------------------------------------------------------
265 SGPath SGPath::operator/( const std::string& p ) const
266 {
267   SGPath ret = *this;
268   ret.append(p);
269   return ret;
270 }
271
272 //add a new path component to the existing path string
273 void SGPath::add( const string& p ) {
274     append( sgSearchPathSep+p );
275 }
276
277
278 // concatenate a string to the end of the path without inserting a
279 // path separator
280 void SGPath::concat( const string& p ) {
281     if ( path.empty() ) {
282         path = p;
283     } else {
284         path += p;
285     }
286     fix();
287     _cached = false;
288     _rwCached = false;
289 }
290
291
292 // Get the file part of the path (everything after the last path sep)
293 string SGPath::file() const
294 {
295     string::size_type index = path.rfind(sgDirPathSep);
296     if (index != string::npos) {
297         return path.substr(index + 1);
298     } else {
299         return path;
300     }
301 }
302   
303
304 // get the directory part of the path.
305 string SGPath::dir() const {
306     int index = path.rfind(sgDirPathSep);
307     if (index >= 0) {
308         return path.substr(0, index);
309     } else {
310         return "";
311     }
312 }
313
314 // get the base part of the path (everything but the extension.)
315 string SGPath::base() const
316 {
317     string::size_type index = path.rfind(".");
318     string::size_type lastSep = path.rfind(sgDirPathSep);
319     
320 // tolerate dots inside directory names
321     if ((lastSep != string::npos) && (index < lastSep)) {
322         return path;
323     }
324     
325     if (index != string::npos) {
326         return path.substr(0, index);
327     } else {
328         return path;
329     }
330 }
331
332 string SGPath::file_base() const
333 {
334     string::size_type index = path.rfind(sgDirPathSep);
335     if (index == string::npos) {
336         index = 0; // no separator in the name
337     } else {
338         ++index; // skip past the separator
339     }
340     
341     string::size_type firstDot = path.find(".", index);
342     if (firstDot == string::npos) {
343         return path.substr(index); // no extensions
344     }
345     
346     return path.substr(index, firstDot - index);
347 }
348
349 // get the extension (everything after the final ".")
350 // but make sure no "/" follows the "." character (otherwise it
351 // is has to be a directory name containing a ".").
352 string SGPath::extension() const {
353     int index = path.rfind(".");
354     if ((index >= 0)  && (path.find("/", index) == string::npos)) {
355         return path.substr(index + 1);
356     } else {
357         return "";
358     }
359 }
360
361 string SGPath::lower_extension() const {
362     return boost::to_lower_copy(extension());
363 }
364
365 string SGPath::complete_lower_extension() const
366 {
367     string::size_type index = path.rfind(sgDirPathSep);
368     if (index == string::npos) {
369         index = 0; // no separator in the name
370     } else {
371         ++index; // skip past the separator
372     }
373     
374     string::size_type firstDot = path.find(".", index);
375     if ((firstDot != string::npos)  && (path.find(sgDirPathSep, firstDot) == string::npos)) {
376         return boost::to_lower_copy(path.substr(firstDot + 1));
377     } else {
378         return "";
379     }
380 }
381
382 //------------------------------------------------------------------------------
383 void SGPath::validate() const
384 {
385   if (_cached && _cacheEnabled) {
386     return;
387   }
388
389   if (path.empty()) {
390           _exists = false;
391           return;
392   }
393
394 #ifdef _WIN32
395   struct _stat buf ;
396   bool remove_trailing = false;
397   string statPath(path);
398   if ((path.length() > 1) && (path.back() == '/')) {
399           statPath.pop_back();
400   }
401       
402   if (_stat(statPath.c_str(), &buf ) < 0) {
403     _exists = false;
404   } else {
405     _exists = true;
406     _isFile = ((S_IFREG & buf.st_mode ) !=0);
407     _isDir = ((S_IFDIR & buf.st_mode ) !=0);
408     _modTime = buf.st_mtime;
409   }
410
411 #else
412   struct stat buf ;
413
414   if (stat(path.c_str(), &buf ) < 0) {
415     _exists = false;
416   } else {
417     _exists = true;
418     _isFile = ((S_ISREG(buf.st_mode )) != 0);
419     _isDir = ((S_ISDIR(buf.st_mode )) != 0);
420     _modTime = buf.st_mtime;
421   }
422   
423 #endif
424   _cached = true;
425 }
426
427 //------------------------------------------------------------------------------
428 void SGPath::checkAccess() const
429 {
430   if( _rwCached && _cacheEnabled )
431     return;
432
433   if( _permission_checker )
434   {
435     Permissions p = _permission_checker(*this);
436     _canRead = p.read;
437     _canWrite = p.write;
438   }
439   else
440   {
441     _canRead = true;
442     _canWrite = true;
443   }
444
445   _rwCached = true;
446 }
447
448 bool SGPath::exists() const
449 {
450   validate();
451   return _exists;
452 }
453
454 //------------------------------------------------------------------------------
455 bool SGPath::canRead() const
456 {
457   checkAccess();
458   return _canRead;
459 }
460
461 //------------------------------------------------------------------------------
462 bool SGPath::canWrite() const
463 {
464   checkAccess();
465   return _canWrite;
466 }
467
468 bool SGPath::isDir() const
469 {
470   validate();
471   return _exists && _isDir;
472 }
473
474 bool SGPath::isFile() const
475 {
476   validate();
477   return _exists && _isFile;
478 }
479
480 #ifdef _WIN32
481 #  define sgMkDir(d,m)       _mkdir(d)
482 #else
483 #  define sgMkDir(d,m)       mkdir(d,m)
484 #endif
485
486
487 int SGPath::create_dir( mode_t mode ) {
488     string_list dirlist = sgPathSplit(dir());
489     if ( dirlist.empty() )
490         return -1;
491     string path = dirlist[0];
492     string_list path_elements = sgPathBranchSplit(path);
493     bool absolute = !path.empty() && path[0] == sgDirPathSep;
494
495     unsigned int i = 1;
496     SGPath dir(absolute ? string( 1, sgDirPathSep ) : "", _permission_checker);
497     dir.concat( path_elements[0] );
498 #ifdef _WIN32
499     if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
500         dir.append( path_elements[1] );
501         i = 2;
502     }
503 #endif
504     struct stat info;
505     int r;
506     for(; ( r = stat( dir.c_str(), &info ) ) == 0 && i < path_elements.size(); i++) {
507         dir.append(path_elements[i]);
508     }
509     if ( r == 0 ) {
510         return 0; // Directory already exists
511     }
512     for(;;)
513     {
514       if( !dir.canWrite() )
515       {
516         SG_LOG( SG_IO,
517                 SG_WARN, "Error creating directory: (" << dir.str() << ")" <<
518                                                   " reason: access denied" );
519         return -3;
520       }
521       else if( sgMkDir(dir.c_str(), mode) )
522       {
523         SG_LOG( SG_IO,
524                 SG_ALERT, "Error creating directory: (" << dir.str() << ")" );
525         return -2;
526       }
527
528       if( i >= path_elements.size() )
529         return  0;
530
531       dir.append(path_elements[i++]);
532     }
533
534     return 0;
535 }
536
537 string_list sgPathBranchSplit( const string &dirpath ) {
538     string_list path_elements;
539     string element, path = dirpath;
540     while ( ! path.empty() ) {
541         size_t p = path.find( sgDirPathSep );
542         if ( p != string::npos ) {
543             element = path.substr( 0, p );
544             path.erase( 0, p + 1 );
545         } else {
546             element = path;
547             path = "";
548         }
549         if ( ! element.empty() )
550             path_elements.push_back( element );
551     }
552     return path_elements;
553 }
554
555
556 string_list sgPathSplit( const string &search_path ) {
557     string tmp = search_path;
558     string_list result;
559     result.clear();
560
561     bool done = false;
562
563     while ( !done ) {
564         int index = tmp.find(sgSearchPathSep);
565         if (index >= 0) {
566             result.push_back( tmp.substr(0, index) );
567             tmp = tmp.substr( index + 1 );
568         } else {
569             if ( !tmp.empty() )
570                 result.push_back( tmp );
571             done = true;
572         }
573     }
574
575     return result;
576 }
577
578 bool SGPath::isAbsolute() const
579 {
580   if (path.empty()) {
581     return false;
582   }
583   
584 #ifdef _WIN32
585   // detect '[A-Za-z]:/'
586   if (path.size() > 2) {
587     if (isalpha(path[0]) && (path[1] == ':') && (path[2] == sgDirPathSep)) {
588       return true;
589     }
590   }
591 #endif
592   
593   return (path[0] == sgDirPathSep);
594 }
595
596 bool SGPath::isNull() const
597 {
598   return path.empty();
599 }
600
601 std::string SGPath::str_native() const
602 {
603 #ifdef _WIN32
604     std::string s = str();
605     std::string::size_type pos;
606     std::string nativeSeparator;
607     nativeSeparator = sgDirPathSepBad;
608
609     while( (pos=s.find( sgDirPathSep )) != std::string::npos ) {
610         s.replace( pos, 1, nativeSeparator );
611     }
612     return s;
613 #else
614     return str();
615 #endif
616 }
617
618 //------------------------------------------------------------------------------
619 bool SGPath::remove()
620 {
621   if( !canWrite() )
622   {
623     SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ")"
624                                                " reason: access denied" );
625     return false;
626   }
627
628   int err = ::unlink(c_str());
629   if( err )
630   {
631     SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << str() << ") "
632                                                " reason: " << strerror(errno) );
633     // TODO check if failed unlink can really change any of the cached values
634   }
635
636   _cached = false; // stat again if required
637   _rwCached = false;
638   return (err == 0);
639 }
640
641 time_t SGPath::modTime() const
642 {
643     validate();
644     return _modTime;
645 }
646
647 bool SGPath::operator==(const SGPath& other) const
648 {
649     return (path == other.path);
650 }
651
652 bool SGPath::operator!=(const SGPath& other) const
653 {
654     return (path != other.path);
655 }
656
657 //------------------------------------------------------------------------------
658 bool SGPath::rename(const SGPath& newName)
659 {
660   if( !canRead() || !canWrite() || !newName.canWrite() )
661   {
662     SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
663                                             " to " << newName.str() <<
664                                             " reason: access denied" );
665     return false;
666   }
667
668 #ifdef SG_WINDOWS
669         if (newName.exists()) {
670                 SGPath r(newName);
671                 if (!r.remove()) {
672                         return false;
673                 }
674         }
675 #endif
676   if( ::rename(c_str(), newName.c_str()) != 0 )
677   {
678     SG_LOG( SG_IO, SG_WARN, "rename failed: from " << str() <<
679                                             " to " << newName.str() <<
680                                             " reason: " << strerror(errno) );
681     return false;
682   }
683
684   path = newName.path;
685
686   // Do not remove permission checker (could happen for example if just using
687   // a std::string as new name)
688   if( newName._permission_checker )
689     _permission_checker = newName._permission_checker;
690
691   _cached = false;
692   _rwCached = false;
693
694   return true;
695 }
696
697 //------------------------------------------------------------------------------
698 SGPath SGPath::standardLocation(StandardLocation type, const SGPath& def)
699 {
700   switch(type)
701   {
702     case HOME:
703       return home(def);
704 #ifdef _WIN32
705     case DESKTOP:
706       return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
707     case DOWNLOADS:
708       // TODO use KnownFolders
709       // http://msdn.microsoft.com/en-us/library/bb776911%28v=vs.85%29.aspx
710       if( !def.isNull() )
711         return def;
712
713       return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
714     case DOCUMENTS:
715       return pathForCSIDL(CSIDL_MYDOCUMENTS, def);
716     case PICTURES:
717       return pathForCSIDL(CSIDL_MYPICTURES, def);
718 #elif __APPLE__
719       // since this is C++, we can't include NSPathUtilities.h to access the enum
720       // values, so hard-coding them here (they are stable, don't worry)
721     case DOWNLOADS:
722       return appleSpecialFolder(15, 1, def);
723     case DESKTOP:
724       return appleSpecialFolder(12, 1, def);
725     case DOCUMENTS:
726       return appleSpecialFolder(9, 1, def);
727     case PICTURES:
728       return appleSpecialFolder(19, 1, def);
729 #else
730     case DESKTOP:
731       return getXDGDir("DESKTOP", def, "Desktop");
732     case DOWNLOADS:
733       return getXDGDir("DOWNLOADS", def, "Downloads");
734     case DOCUMENTS:
735       return getXDGDir("DOCUMENTS", def, "Documents");
736     case PICTURES:
737       return getXDGDir("PICTURES", def, "Pictures");
738 #endif
739     default:
740       SG_LOG( SG_GENERAL,
741               SG_WARN,
742               "SGPath::standardLocation() unhandled type: " << type );
743       return def;
744   }
745 }
746
747 //------------------------------------------------------------------------------
748 SGPath SGPath::fromEnv(const char* name, const SGPath& def)
749 {
750   const char* val = getenv(name);
751   if( val && val[0] )
752     return SGPath(val, def._permission_checker);
753   return def;
754 }
755
756 #ifdef _WIN32
757 //------------------------------------------------------------------------------
758 SGPath SGPath::home(const SGPath& def)
759 {
760   // TODO
761   return def;
762 }
763 #else
764 //------------------------------------------------------------------------------
765 SGPath SGPath::home(const SGPath& def)
766 {
767   return fromEnv("HOME", def);
768 }
769 #endif
770
771 //------------------------------------------------------------------------------
772 SGPath SGPath::desktop(const SGPath& def)
773 {
774   return standardLocation(DESKTOP, def);
775 }
776
777 //------------------------------------------------------------------------------
778 SGPath SGPath::documents(const SGPath& def)
779 {
780   return standardLocation(DOCUMENTS, def);
781 }
782
783 //------------------------------------------------------------------------------
784 std::string SGPath::realpath() const
785 {
786 #if (defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050)
787     // Workaround for Mac OS 10.5. Somehow fgfs crashes on Mac at ::realpath. 
788     // This means relative paths cannot be used on Mac OS <= 10.5
789     return path;
790 #else
791   #if defined(_MSC_VER) /*for MS compilers */ || defined(_WIN32) /*needed for non MS windows compilers like MingW*/
792     // with absPath NULL, will allocate, and ignore length
793     char *buf = _fullpath( NULL, path.c_str(), _MAX_PATH );
794   #else
795     // POSIX
796     char* buf = ::realpath(path.c_str(), NULL);
797   #endif
798     if (!buf)
799     {
800         SG_LOG(SG_IO, SG_ALERT, "ERROR: The path '" << path << "' does not exist in the file system.");
801         return path;
802     }
803     std::string p(buf);
804     free(buf);
805     return p;
806 #endif
807 }