Home | History | Annotate | Download | only in base
      1 /*
      2  * libjingle
      3  * Copyright 2004--2006, Google Inc.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions are met:
      7  *
      8  *  1. Redistributions of source code must retain the above copyright notice,
      9  *     this list of conditions and the following disclaimer.
     10  *  2. Redistributions in binary form must reproduce the above copyright notice,
     11  *     this list of conditions and the following disclaimer in the documentation
     12  *     and/or other materials provided with the distribution.
     13  *  3. The name of the author may not be used to endorse or promote products
     14  *     derived from this software without specific prior written permission.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
     17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     18  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
     19  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 #include "talk/base/unixfilesystem.h"
     29 
     30 #include <errno.h>
     31 #include <fcntl.h>
     32 #include <stdlib.h>
     33 #include <sys/stat.h>
     34 #include <unistd.h>
     35 
     36 #ifdef OSX
     37 #include <Carbon/Carbon.h>
     38 #include <IOKit/IOCFBundle.h>
     39 #include <sys/statvfs.h>
     40 #include "talk/base/macutils.h"
     41 #endif  // OSX
     42 
     43 #if defined(POSIX) && !defined(OSX)
     44 #include <sys/types.h>
     45 #ifdef ANDROID
     46 #include <sys/statfs.h>
     47 #else
     48 #include <sys/statvfs.h>
     49 #endif  // ANDROID
     50 #include <pwd.h>
     51 #include <stdio.h>
     52 #include <unistd.h>
     53 #endif  // POSIX && !OSX
     54 
     55 #ifdef LINUX
     56 #include <ctype.h>
     57 #include <algorithm>
     58 #endif
     59 
     60 #include "talk/base/fileutils.h"
     61 #include "talk/base/pathutils.h"
     62 #include "talk/base/stream.h"
     63 #include "talk/base/stringutils.h"
     64 
     65 namespace talk_base {
     66 
     67 #if !defined(ANDROID) && !defined(IOS)
     68 char* UnixFilesystem::app_temp_path_ = NULL;
     69 #else
     70 char* UnixFilesystem::provided_app_data_folder_ = NULL;
     71 char* UnixFilesystem::provided_app_temp_folder_ = NULL;
     72 
     73 void UnixFilesystem::SetAppDataFolder(const std::string& folder) {
     74   delete [] provided_app_data_folder_;
     75   provided_app_data_folder_ = CopyString(folder);
     76 }
     77 
     78 void UnixFilesystem::SetAppTempFolder(const std::string& folder) {
     79   delete [] provided_app_temp_folder_;
     80   provided_app_temp_folder_ = CopyString(folder);
     81 }
     82 #endif
     83 
     84 bool UnixFilesystem::CreateFolder(const Pathname &path, mode_t mode) {
     85   std::string pathname(path.pathname());
     86   int len = pathname.length();
     87   if ((len == 0) || (pathname[len - 1] != '/'))
     88     return false;
     89 
     90   struct stat st;
     91   int res = ::stat(pathname.c_str(), &st);
     92   if (res == 0) {
     93     // Something exists at this location, check if it is a directory
     94     return S_ISDIR(st.st_mode) != 0;
     95   } else if (errno != ENOENT) {
     96     // Unexpected error
     97     return false;
     98   }
     99 
    100   // Directory doesn't exist, look up one directory level
    101   do {
    102     --len;
    103   } while ((len > 0) && (pathname[len - 1] != '/'));
    104 
    105   if (!CreateFolder(Pathname(pathname.substr(0, len)), mode)) {
    106     return false;
    107   }
    108 
    109   LOG(LS_INFO) << "Creating folder: " << pathname;
    110   return (0 == ::mkdir(pathname.c_str(), mode));
    111 }
    112 
    113 bool UnixFilesystem::CreateFolder(const Pathname &path) {
    114   return CreateFolder(path, 0755);
    115 }
    116 
    117 FileStream *UnixFilesystem::OpenFile(const Pathname &filename,
    118                                      const std::string &mode) {
    119   FileStream *fs = new FileStream();
    120   if (fs && !fs->Open(filename.pathname().c_str(), mode.c_str(), NULL)) {
    121     delete fs;
    122     fs = NULL;
    123   }
    124   return fs;
    125 }
    126 
    127 bool UnixFilesystem::CreatePrivateFile(const Pathname &filename) {
    128   int fd = open(filename.pathname().c_str(),
    129                 O_RDWR | O_CREAT | O_EXCL,
    130                 S_IRUSR | S_IWUSR);
    131   if (fd < 0) {
    132     LOG_ERR(LS_ERROR) << "open() failed.";
    133     return false;
    134   }
    135   // Don't need to keep the file descriptor.
    136   if (close(fd) < 0) {
    137     LOG_ERR(LS_ERROR) << "close() failed.";
    138     // Continue.
    139   }
    140   return true;
    141 }
    142 
    143 bool UnixFilesystem::DeleteFile(const Pathname &filename) {
    144   LOG(LS_INFO) << "Deleting file:" << filename.pathname();
    145 
    146   if (!IsFile(filename)) {
    147     ASSERT(IsFile(filename));
    148     return false;
    149   }
    150   return ::unlink(filename.pathname().c_str()) == 0;
    151 }
    152 
    153 bool UnixFilesystem::DeleteEmptyFolder(const Pathname &folder) {
    154   LOG(LS_INFO) << "Deleting folder" << folder.pathname();
    155 
    156   if (!IsFolder(folder)) {
    157     ASSERT(IsFolder(folder));
    158     return false;
    159   }
    160   std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
    161   return ::rmdir(no_slash.c_str()) == 0;
    162 }
    163 
    164 bool UnixFilesystem::GetTemporaryFolder(Pathname &pathname, bool create,
    165                                         const std::string *append) {
    166 #ifdef OSX
    167   FSRef fr;
    168   if (0 != FSFindFolder(kOnAppropriateDisk, kTemporaryFolderType,
    169                         kCreateFolder, &fr))
    170     return false;
    171   unsigned char buffer[NAME_MAX+1];
    172   if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
    173     return false;
    174   pathname.SetPathname(reinterpret_cast<char*>(buffer), "");
    175 #elif defined(ANDROID) || defined(IOS)
    176   ASSERT(provided_app_temp_folder_ != NULL);
    177   pathname.SetPathname(provided_app_temp_folder_, "");
    178 #else  // !OSX && !ANDROID
    179   if (const char* tmpdir = getenv("TMPDIR")) {
    180     pathname.SetPathname(tmpdir, "");
    181   } else if (const char* tmp = getenv("TMP")) {
    182     pathname.SetPathname(tmp, "");
    183   } else {
    184 #ifdef P_tmpdir
    185     pathname.SetPathname(P_tmpdir, "");
    186 #else  // !P_tmpdir
    187     pathname.SetPathname("/tmp/", "");
    188 #endif  // !P_tmpdir
    189   }
    190 #endif  // !OSX && !ANDROID
    191   if (append) {
    192     ASSERT(!append->empty());
    193     pathname.AppendFolder(*append);
    194   }
    195   return !create || CreateFolder(pathname);
    196 }
    197 
    198 std::string UnixFilesystem::TempFilename(const Pathname &dir,
    199                                          const std::string &prefix) {
    200   int len = dir.pathname().size() + prefix.size() + 2 + 6;
    201   char *tempname = new char[len];
    202 
    203   snprintf(tempname, len, "%s/%sXXXXXX", dir.pathname().c_str(),
    204            prefix.c_str());
    205   int fd = ::mkstemp(tempname);
    206   if (fd != -1)
    207     ::close(fd);
    208   std::string ret(tempname);
    209   delete[] tempname;
    210 
    211   return ret;
    212 }
    213 
    214 bool UnixFilesystem::MoveFile(const Pathname &old_path,
    215                               const Pathname &new_path) {
    216   if (!IsFile(old_path)) {
    217     ASSERT(IsFile(old_path));
    218     return false;
    219   }
    220   LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
    221                   << " to " << new_path.pathname();
    222   if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
    223     if (errno != EXDEV)
    224       return false;
    225     if (!CopyFile(old_path, new_path))
    226       return false;
    227     if (!DeleteFile(old_path))
    228       return false;
    229   }
    230   return true;
    231 }
    232 
    233 bool UnixFilesystem::MoveFolder(const Pathname &old_path,
    234                                 const Pathname &new_path) {
    235   if (!IsFolder(old_path)) {
    236     ASSERT(IsFolder(old_path));
    237     return false;
    238   }
    239   LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
    240                   << " to " << new_path.pathname();
    241   if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
    242     if (errno != EXDEV)
    243       return false;
    244     if (!CopyFolder(old_path, new_path))
    245       return false;
    246     if (!DeleteFolderAndContents(old_path))
    247       return false;
    248   }
    249   return true;
    250 }
    251 
    252 bool UnixFilesystem::IsFolder(const Pathname &path) {
    253   struct stat st;
    254   if (stat(path.pathname().c_str(), &st) < 0)
    255     return false;
    256   return S_ISDIR(st.st_mode);
    257 }
    258 
    259 bool UnixFilesystem::CopyFile(const Pathname &old_path,
    260                               const Pathname &new_path) {
    261   LOG(LS_VERBOSE) << "Copying " << old_path.pathname()
    262                   << " to " << new_path.pathname();
    263   char buf[256];
    264   size_t len;
    265 
    266   StreamInterface *source = OpenFile(old_path, "rb");
    267   if (!source)
    268     return false;
    269 
    270   StreamInterface *dest = OpenFile(new_path, "wb");
    271   if (!dest) {
    272     delete source;
    273     return false;
    274   }
    275 
    276   while (source->Read(buf, sizeof(buf), &len, NULL) == SR_SUCCESS)
    277     dest->Write(buf, len, NULL, NULL);
    278 
    279   delete source;
    280   delete dest;
    281   return true;
    282 }
    283 
    284 bool UnixFilesystem::IsTemporaryPath(const Pathname& pathname) {
    285 #if defined(ANDROID) || defined(IOS)
    286   ASSERT(provided_app_temp_folder_ != NULL);
    287 #endif
    288 
    289   const char* const kTempPrefixes[] = {
    290 #if defined(ANDROID) || defined(IOS)
    291     provided_app_temp_folder_,
    292 #else
    293     "/tmp/", "/var/tmp/",
    294 #ifdef OSX
    295     "/private/tmp/", "/private/var/tmp/", "/private/var/folders/",
    296 #endif  // OSX
    297 #endif  // ANDROID || IOS
    298   };
    299   for (size_t i = 0; i < ARRAY_SIZE(kTempPrefixes); ++i) {
    300     if (0 == strncmp(pathname.pathname().c_str(), kTempPrefixes[i],
    301                      strlen(kTempPrefixes[i])))
    302       return true;
    303   }
    304   return false;
    305 }
    306 
    307 bool UnixFilesystem::IsFile(const Pathname& pathname) {
    308   struct stat st;
    309   int res = ::stat(pathname.pathname().c_str(), &st);
    310   // Treat symlinks, named pipes, etc. all as files.
    311   return res == 0 && !S_ISDIR(st.st_mode);
    312 }
    313 
    314 bool UnixFilesystem::IsAbsent(const Pathname& pathname) {
    315   struct stat st;
    316   int res = ::stat(pathname.pathname().c_str(), &st);
    317   // Note: we specifically maintain ENOTDIR as an error, because that implies
    318   // that you could not call CreateFolder(pathname).
    319   return res != 0 && ENOENT == errno;
    320 }
    321 
    322 bool UnixFilesystem::GetFileSize(const Pathname& pathname, size_t *size) {
    323   struct stat st;
    324   if (::stat(pathname.pathname().c_str(), &st) != 0)
    325     return false;
    326   *size = st.st_size;
    327   return true;
    328 }
    329 
    330 bool UnixFilesystem::GetFileTime(const Pathname& path, FileTimeType which,
    331                                  time_t* time) {
    332   struct stat st;
    333   if (::stat(path.pathname().c_str(), &st) != 0)
    334     return false;
    335   switch (which) {
    336   case FTT_CREATED:
    337     *time = st.st_ctime;
    338     break;
    339   case FTT_MODIFIED:
    340     *time = st.st_mtime;
    341     break;
    342   case FTT_ACCESSED:
    343     *time = st.st_atime;
    344     break;
    345   default:
    346     return false;
    347   }
    348   return true;
    349 }
    350 
    351 bool UnixFilesystem::GetAppPathname(Pathname* path) {
    352 #ifdef OSX
    353   ProcessSerialNumber psn = { 0, kCurrentProcess };
    354   CFDictionaryRef procinfo = ProcessInformationCopyDictionary(&psn,
    355       kProcessDictionaryIncludeAllInformationMask);
    356   if (NULL == procinfo)
    357     return false;
    358   CFStringRef cfpath = (CFStringRef) CFDictionaryGetValue(procinfo,
    359       kIOBundleExecutableKey);
    360   std::string path8;
    361   bool success = ToUtf8(cfpath, &path8);
    362   CFRelease(procinfo);
    363   if (success)
    364     path->SetPathname(path8);
    365   return success;
    366 #else  // OSX
    367   char buffer[NAME_MAX+1];
    368   size_t len = readlink("/proc/self/exe", buffer, ARRAY_SIZE(buffer) - 1);
    369   if (len <= 0)
    370     return false;
    371   buffer[len] = '\0';
    372   path->SetPathname(buffer);
    373   return true;
    374 #endif  // OSX
    375 }
    376 
    377 bool UnixFilesystem::GetAppDataFolder(Pathname* path, bool per_user) {
    378   ASSERT(!organization_name_.empty());
    379   ASSERT(!application_name_.empty());
    380 
    381   // First get the base directory for app data.
    382 #ifdef OSX
    383   if (per_user) {
    384     // Use ~/Library/Application Support/<orgname>/<appname>/
    385     FSRef fr;
    386     if (0 != FSFindFolder(kUserDomain, kApplicationSupportFolderType,
    387                           kCreateFolder, &fr))
    388       return false;
    389     unsigned char buffer[NAME_MAX+1];
    390     if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
    391       return false;
    392     path->SetPathname(reinterpret_cast<char*>(buffer), "");
    393   } else {
    394     // TODO
    395     return false;
    396   }
    397 #elif defined(ANDROID) || defined(IOS)  // && !OSX
    398   ASSERT(provided_app_data_folder_ != NULL);
    399   path->SetPathname(provided_app_data_folder_, "");
    400 #elif defined(LINUX)  // && !OSX && !defined(ANDROID) && !defined(IOS)
    401   if (per_user) {
    402     // We follow the recommendations in
    403     // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
    404     // It specifies separate directories for data and config files, but
    405     // GetAppDataFolder() does not distinguish. We just return the config dir
    406     // path.
    407     const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
    408     if (xdg_config_home) {
    409       path->SetPathname(xdg_config_home, "");
    410     } else {
    411       // XDG says to default to $HOME/.config. We also support falling back to
    412       // other synonyms for HOME if for some reason it is not defined.
    413       const char* homedir;
    414       if (const char* home = getenv("HOME")) {
    415         homedir = home;
    416       } else if (const char* dotdir = getenv("DOTDIR")) {
    417         homedir = dotdir;
    418       } else if (passwd* pw = getpwuid(geteuid())) {
    419         homedir = pw->pw_dir;
    420       } else {
    421         return false;
    422       }
    423       path->SetPathname(homedir, "");
    424       path->AppendFolder(".config");
    425     }
    426   } else {
    427     // XDG does not define a standard directory for writable global data. Let's
    428     // just use this.
    429     path->SetPathname("/var/cache/", "");
    430   }
    431 #endif  // !OSX && !defined(ANDROID) && !defined(LINUX)
    432 
    433   // Now add on a sub-path for our app.
    434 #if defined(OSX) || defined(ANDROID) || defined(IOS)
    435   path->AppendFolder(organization_name_);
    436   path->AppendFolder(application_name_);
    437 #elif defined(LINUX)
    438   // XDG says to use a single directory level, so we concatenate the org and app
    439   // name with a hyphen. We also do the Linuxy thing and convert to all
    440   // lowercase with no spaces.
    441   std::string subdir(organization_name_);
    442   subdir.append("-");
    443   subdir.append(application_name_);
    444   replace_substrs(" ", 1, "", 0, &subdir);
    445   std::transform(subdir.begin(), subdir.end(), subdir.begin(), ::tolower);
    446   path->AppendFolder(subdir);
    447 #endif
    448   if (!CreateFolder(*path, 0700)) {
    449     return false;
    450   }
    451   // If the folder already exists, it may have the wrong mode or be owned by
    452   // someone else, both of which are security problems. Setting the mode
    453   // avoids both issues since it will fail if the path is not owned by us.
    454   if (0 != ::chmod(path->pathname().c_str(), 0700)) {
    455     LOG_ERR(LS_ERROR) << "Can't set mode on " << path;
    456     return false;
    457   }
    458   return true;
    459 }
    460 
    461 bool UnixFilesystem::GetAppTempFolder(Pathname* path) {
    462 #if defined(ANDROID) || defined(IOS)
    463   ASSERT(provided_app_temp_folder_ != NULL);
    464   path->SetPathname(provided_app_temp_folder_);
    465   return true;
    466 #else
    467   ASSERT(!application_name_.empty());
    468   // TODO: Consider whether we are worried about thread safety.
    469   if (app_temp_path_ != NULL && strlen(app_temp_path_) > 0) {
    470     path->SetPathname(app_temp_path_);
    471     return true;
    472   }
    473 
    474   // Create a random directory as /tmp/<appname>-<pid>-<timestamp>
    475   char buffer[128];
    476   sprintfn(buffer, ARRAY_SIZE(buffer), "-%d-%d",
    477            static_cast<int>(getpid()),
    478            static_cast<int>(time(0)));
    479   std::string folder(application_name_);
    480   folder.append(buffer);
    481   if (!GetTemporaryFolder(*path, true, &folder))
    482     return false;
    483 
    484   delete [] app_temp_path_;
    485   app_temp_path_ = CopyString(path->pathname());
    486   // TODO: atexit(DeleteFolderAndContents(app_temp_path_));
    487   return true;
    488 #endif
    489 }
    490 
    491 bool UnixFilesystem::GetDiskFreeSpace(const Pathname& path, int64 *freebytes) {
    492   ASSERT(NULL != freebytes);
    493   // TODO: Consider making relative paths absolute using cwd.
    494   // TODO: When popping off a symlink, push back on the components of the
    495   // symlink, so we don't jump out of the target disk inadvertently.
    496   Pathname existing_path(path.folder(), "");
    497   while (!existing_path.folder().empty() && IsAbsent(existing_path)) {
    498     existing_path.SetFolder(existing_path.parent_folder());
    499   }
    500 #ifdef ANDROID
    501   struct statfs vfs;
    502   memset(&vfs, 0, sizeof(vfs));
    503   if (0 != statfs(existing_path.pathname().c_str(), &vfs))
    504     return false;
    505 #else
    506   struct statvfs vfs;
    507   memset(&vfs, 0, sizeof(vfs));
    508   if (0 != statvfs(existing_path.pathname().c_str(), &vfs))
    509     return false;
    510 #endif  // ANDROID
    511 #if defined(LINUX) || defined(ANDROID)
    512   *freebytes = static_cast<int64>(vfs.f_bsize) * vfs.f_bavail;
    513 #elif defined(OSX)
    514   *freebytes = static_cast<int64>(vfs.f_frsize) * vfs.f_bavail;
    515 #endif
    516 
    517   return true;
    518 }
    519 
    520 Pathname UnixFilesystem::GetCurrentDirectory() {
    521   Pathname cwd;
    522   char buffer[PATH_MAX];
    523   char *path = getcwd(buffer, PATH_MAX);
    524 
    525   if (!path) {
    526     LOG_ERR(LS_ERROR) << "getcwd() failed";
    527     return cwd;  // returns empty pathname
    528   }
    529   cwd.SetFolder(std::string(path));
    530 
    531   return cwd;
    532 }
    533 
    534 char* UnixFilesystem::CopyString(const std::string& str) {
    535   size_t size = str.length() + 1;
    536 
    537   char* buf = new char[size];
    538   if (!buf) {
    539     return NULL;
    540   }
    541 
    542   strcpyn(buf, size, str.c_str());
    543   return buf;
    544 }
    545 
    546 }  // namespace talk_base
    547