3 * Copyright 2004--2006, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
28 #include "talk/base/unixfilesystem.h"
37 #include <Carbon/Carbon.h>
38 #include <IOKit/IOCFBundle.h>
39 #include <sys/statvfs.h>
40 #include "talk/base/macutils.h"
43 #if defined(POSIX) && !defined(OSX)
44 #include <sys/types.h>
46 #include <sys/statfs.h>
47 #elif !defined(__native_client__)
48 #include <sys/statvfs.h>
49 #endif // !defined(__native_client__)
53 #endif // POSIX && !OSX
60 #if defined(__native_client__) && !defined(__GLIBC__)
61 #include <sys/syslimits.h>
64 #include "talk/base/fileutils.h"
65 #include "talk/base/pathutils.h"
66 #include "talk/base/stream.h"
67 #include "talk/base/stringutils.h"
71 #if !defined(ANDROID) && !defined(IOS)
72 char* UnixFilesystem::app_temp_path_ = NULL;
74 char* UnixFilesystem::provided_app_data_folder_ = NULL;
75 char* UnixFilesystem::provided_app_temp_folder_ = NULL;
77 void UnixFilesystem::SetAppDataFolder(const std::string& folder) {
78 delete [] provided_app_data_folder_;
79 provided_app_data_folder_ = CopyString(folder);
82 void UnixFilesystem::SetAppTempFolder(const std::string& folder) {
83 delete [] provided_app_temp_folder_;
84 provided_app_temp_folder_ = CopyString(folder);
88 bool UnixFilesystem::CreateFolder(const Pathname &path, mode_t mode) {
89 std::string pathname(path.pathname());
90 int len = pathname.length();
91 if ((len == 0) || (pathname[len - 1] != '/'))
95 int res = ::stat(pathname.c_str(), &st);
97 // Something exists at this location, check if it is a directory
98 return S_ISDIR(st.st_mode) != 0;
99 } else if (errno != ENOENT) {
104 // Directory doesn't exist, look up one directory level
107 } while ((len > 0) && (pathname[len - 1] != '/'));
109 if (!CreateFolder(Pathname(pathname.substr(0, len)), mode)) {
113 LOG(LS_INFO) << "Creating folder: " << pathname;
114 return (0 == ::mkdir(pathname.c_str(), mode));
117 bool UnixFilesystem::CreateFolder(const Pathname &path) {
118 return CreateFolder(path, 0755);
121 FileStream *UnixFilesystem::OpenFile(const Pathname &filename,
122 const std::string &mode) {
123 FileStream *fs = new FileStream();
124 if (fs && !fs->Open(filename.pathname().c_str(), mode.c_str(), NULL)) {
131 bool UnixFilesystem::CreatePrivateFile(const Pathname &filename) {
132 int fd = open(filename.pathname().c_str(),
133 O_RDWR | O_CREAT | O_EXCL,
136 LOG_ERR(LS_ERROR) << "open() failed.";
139 // Don't need to keep the file descriptor.
141 LOG_ERR(LS_ERROR) << "close() failed.";
147 bool UnixFilesystem::DeleteFile(const Pathname &filename) {
148 LOG(LS_INFO) << "Deleting file:" << filename.pathname();
150 if (!IsFile(filename)) {
151 ASSERT(IsFile(filename));
154 return ::unlink(filename.pathname().c_str()) == 0;
157 bool UnixFilesystem::DeleteEmptyFolder(const Pathname &folder) {
158 LOG(LS_INFO) << "Deleting folder" << folder.pathname();
160 if (!IsFolder(folder)) {
161 ASSERT(IsFolder(folder));
164 std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
165 return ::rmdir(no_slash.c_str()) == 0;
168 bool UnixFilesystem::GetTemporaryFolder(Pathname &pathname, bool create,
169 const std::string *append) {
172 if (0 != FSFindFolder(kOnAppropriateDisk, kTemporaryFolderType,
175 unsigned char buffer[NAME_MAX+1];
176 if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
178 pathname.SetPathname(reinterpret_cast<char*>(buffer), "");
179 #elif defined(ANDROID) || defined(IOS)
180 ASSERT(provided_app_temp_folder_ != NULL);
181 pathname.SetPathname(provided_app_temp_folder_, "");
182 #else // !OSX && !ANDROID
183 if (const char* tmpdir = getenv("TMPDIR")) {
184 pathname.SetPathname(tmpdir, "");
185 } else if (const char* tmp = getenv("TMP")) {
186 pathname.SetPathname(tmp, "");
189 pathname.SetPathname(P_tmpdir, "");
191 pathname.SetPathname("/tmp/", "");
194 #endif // !OSX && !ANDROID
196 ASSERT(!append->empty());
197 pathname.AppendFolder(*append);
199 return !create || CreateFolder(pathname);
202 std::string UnixFilesystem::TempFilename(const Pathname &dir,
203 const std::string &prefix) {
204 int len = dir.pathname().size() + prefix.size() + 2 + 6;
205 char *tempname = new char[len];
207 snprintf(tempname, len, "%s/%sXXXXXX", dir.pathname().c_str(),
209 int fd = ::mkstemp(tempname);
212 std::string ret(tempname);
218 bool UnixFilesystem::MoveFile(const Pathname &old_path,
219 const Pathname &new_path) {
220 if (!IsFile(old_path)) {
221 ASSERT(IsFile(old_path));
224 LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
225 << " to " << new_path.pathname();
226 if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
229 if (!CopyFile(old_path, new_path))
231 if (!DeleteFile(old_path))
237 bool UnixFilesystem::MoveFolder(const Pathname &old_path,
238 const Pathname &new_path) {
239 if (!IsFolder(old_path)) {
240 ASSERT(IsFolder(old_path));
243 LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
244 << " to " << new_path.pathname();
245 if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
248 if (!CopyFolder(old_path, new_path))
250 if (!DeleteFolderAndContents(old_path))
256 bool UnixFilesystem::IsFolder(const Pathname &path) {
258 if (stat(path.pathname().c_str(), &st) < 0)
260 return S_ISDIR(st.st_mode);
263 bool UnixFilesystem::CopyFile(const Pathname &old_path,
264 const Pathname &new_path) {
265 LOG(LS_VERBOSE) << "Copying " << old_path.pathname()
266 << " to " << new_path.pathname();
270 StreamInterface *source = OpenFile(old_path, "rb");
274 StreamInterface *dest = OpenFile(new_path, "wb");
280 while (source->Read(buf, sizeof(buf), &len, NULL) == SR_SUCCESS)
281 dest->Write(buf, len, NULL, NULL);
288 bool UnixFilesystem::IsTemporaryPath(const Pathname& pathname) {
289 #if defined(ANDROID) || defined(IOS)
290 ASSERT(provided_app_temp_folder_ != NULL);
293 const char* const kTempPrefixes[] = {
294 #if defined(ANDROID) || defined(IOS)
295 provided_app_temp_folder_,
297 "/tmp/", "/var/tmp/",
299 "/private/tmp/", "/private/var/tmp/", "/private/var/folders/",
301 #endif // ANDROID || IOS
303 for (size_t i = 0; i < ARRAY_SIZE(kTempPrefixes); ++i) {
304 if (0 == strncmp(pathname.pathname().c_str(), kTempPrefixes[i],
305 strlen(kTempPrefixes[i])))
311 bool UnixFilesystem::IsFile(const Pathname& pathname) {
313 int res = ::stat(pathname.pathname().c_str(), &st);
314 // Treat symlinks, named pipes, etc. all as files.
315 return res == 0 && !S_ISDIR(st.st_mode);
318 bool UnixFilesystem::IsAbsent(const Pathname& pathname) {
320 int res = ::stat(pathname.pathname().c_str(), &st);
321 // Note: we specifically maintain ENOTDIR as an error, because that implies
322 // that you could not call CreateFolder(pathname).
323 return res != 0 && ENOENT == errno;
326 bool UnixFilesystem::GetFileSize(const Pathname& pathname, size_t *size) {
328 if (::stat(pathname.pathname().c_str(), &st) != 0)
334 bool UnixFilesystem::GetFileTime(const Pathname& path, FileTimeType which,
337 if (::stat(path.pathname().c_str(), &st) != 0)
355 bool UnixFilesystem::GetAppPathname(Pathname* path) {
357 ProcessSerialNumber psn = { 0, kCurrentProcess };
358 CFDictionaryRef procinfo = ProcessInformationCopyDictionary(&psn,
359 kProcessDictionaryIncludeAllInformationMask);
360 if (NULL == procinfo)
362 CFStringRef cfpath = (CFStringRef) CFDictionaryGetValue(procinfo,
363 kIOBundleExecutableKey);
365 bool success = ToUtf8(cfpath, &path8);
368 path->SetPathname(path8);
370 #elif defined(__native_client__)
373 char buffer[NAME_MAX+1];
374 size_t len = readlink("/proc/self/exe", buffer, ARRAY_SIZE(buffer) - 1);
378 path->SetPathname(buffer);
383 bool UnixFilesystem::GetAppDataFolder(Pathname* path, bool per_user) {
384 ASSERT(!organization_name_.empty());
385 ASSERT(!application_name_.empty());
387 // First get the base directory for app data.
390 // Use ~/Library/Application Support/<orgname>/<appname>/
392 if (0 != FSFindFolder(kUserDomain, kApplicationSupportFolderType,
395 unsigned char buffer[NAME_MAX+1];
396 if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
398 path->SetPathname(reinterpret_cast<char*>(buffer), "");
403 #elif defined(ANDROID) || defined(IOS) // && !OSX
404 ASSERT(provided_app_data_folder_ != NULL);
405 path->SetPathname(provided_app_data_folder_, "");
406 #elif defined(LINUX) // && !OSX && !defined(ANDROID) && !defined(IOS)
408 // We follow the recommendations in
409 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
410 // It specifies separate directories for data and config files, but
411 // GetAppDataFolder() does not distinguish. We just return the config dir
413 const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
414 if (xdg_config_home) {
415 path->SetPathname(xdg_config_home, "");
417 // XDG says to default to $HOME/.config. We also support falling back to
418 // other synonyms for HOME if for some reason it is not defined.
420 if (const char* home = getenv("HOME")) {
422 } else if (const char* dotdir = getenv("DOTDIR")) {
424 } else if (passwd* pw = getpwuid(geteuid())) {
425 homedir = pw->pw_dir;
429 path->SetPathname(homedir, "");
430 path->AppendFolder(".config");
433 // XDG does not define a standard directory for writable global data. Let's
435 path->SetPathname("/var/cache/", "");
437 #endif // !OSX && !defined(ANDROID) && !defined(LINUX)
439 // Now add on a sub-path for our app.
440 #if defined(OSX) || defined(ANDROID) || defined(IOS)
441 path->AppendFolder(organization_name_);
442 path->AppendFolder(application_name_);
444 // XDG says to use a single directory level, so we concatenate the org and app
445 // name with a hyphen. We also do the Linuxy thing and convert to all
446 // lowercase with no spaces.
447 std::string subdir(organization_name_);
449 subdir.append(application_name_);
450 replace_substrs(" ", 1, "", 0, &subdir);
451 std::transform(subdir.begin(), subdir.end(), subdir.begin(), ::tolower);
452 path->AppendFolder(subdir);
454 if (!CreateFolder(*path, 0700)) {
457 #if !defined(__native_client__)
458 // If the folder already exists, it may have the wrong mode or be owned by
459 // someone else, both of which are security problems. Setting the mode
460 // avoids both issues since it will fail if the path is not owned by us.
461 if (0 != ::chmod(path->pathname().c_str(), 0700)) {
462 LOG_ERR(LS_ERROR) << "Can't set mode on " << path;
469 bool UnixFilesystem::GetAppTempFolder(Pathname* path) {
470 #if defined(ANDROID) || defined(IOS)
471 ASSERT(provided_app_temp_folder_ != NULL);
472 path->SetPathname(provided_app_temp_folder_);
475 ASSERT(!application_name_.empty());
476 // TODO: Consider whether we are worried about thread safety.
477 if (app_temp_path_ != NULL && strlen(app_temp_path_) > 0) {
478 path->SetPathname(app_temp_path_);
482 // Create a random directory as /tmp/<appname>-<pid>-<timestamp>
484 sprintfn(buffer, ARRAY_SIZE(buffer), "-%d-%d",
485 static_cast<int>(getpid()),
486 static_cast<int>(time(0)));
487 std::string folder(application_name_);
488 folder.append(buffer);
489 if (!GetTemporaryFolder(*path, true, &folder))
492 delete [] app_temp_path_;
493 app_temp_path_ = CopyString(path->pathname());
494 // TODO: atexit(DeleteFolderAndContents(app_temp_path_));
499 bool UnixFilesystem::GetDiskFreeSpace(const Pathname& path, int64 *freebytes) {
500 #ifdef __native_client__
502 #else // __native_client__
503 ASSERT(NULL != freebytes);
504 // TODO: Consider making relative paths absolute using cwd.
505 // TODO: When popping off a symlink, push back on the components of the
506 // symlink, so we don't jump out of the target disk inadvertently.
507 Pathname existing_path(path.folder(), "");
508 while (!existing_path.folder().empty() && IsAbsent(existing_path)) {
509 existing_path.SetFolder(existing_path.parent_folder());
513 memset(&vfs, 0, sizeof(vfs));
514 if (0 != statfs(existing_path.pathname().c_str(), &vfs))
518 memset(&vfs, 0, sizeof(vfs));
519 if (0 != statvfs(existing_path.pathname().c_str(), &vfs))
522 #if defined(LINUX) || defined(ANDROID)
523 *freebytes = static_cast<int64>(vfs.f_bsize) * vfs.f_bavail;
525 *freebytes = static_cast<int64>(vfs.f_frsize) * vfs.f_bavail;
529 #endif // !__native_client__
532 Pathname UnixFilesystem::GetCurrentDirectory() {
534 char buffer[PATH_MAX];
535 char *path = getcwd(buffer, PATH_MAX);
538 LOG_ERR(LS_ERROR) << "getcwd() failed";
539 return cwd; // returns empty pathname
541 cwd.SetFolder(std::string(path));
546 char* UnixFilesystem::CopyString(const std::string& str) {
547 size_t size = str.length() + 1;
549 char* buf = new char[size];
554 strcpyn(buf, size, str.c_str());
558 } // namespace talk_base
560 #if defined(__native_client__)
561 extern "C" int __attribute__((weak))
562 link(const char* oldpath, const char* newpath) {