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>
48 #include <sys/statvfs.h>
53 #endif // POSIX && !OSX
60 #include "talk/base/fileutils.h"
61 #include "talk/base/pathutils.h"
62 #include "talk/base/stream.h"
63 #include "talk/base/stringutils.h"
67 #if !defined(ANDROID) && !defined(IOS)
68 char* UnixFilesystem::app_temp_path_ = NULL;
70 char* UnixFilesystem::provided_app_data_folder_ = NULL;
71 char* UnixFilesystem::provided_app_temp_folder_ = NULL;
73 void UnixFilesystem::SetAppDataFolder(const std::string& folder) {
74 delete [] provided_app_data_folder_;
75 provided_app_data_folder_ = CopyString(folder);
78 void UnixFilesystem::SetAppTempFolder(const std::string& folder) {
79 delete [] provided_app_temp_folder_;
80 provided_app_temp_folder_ = CopyString(folder);
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] != '/'))
91 int res = ::stat(pathname.c_str(), &st);
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) {
100 // Directory doesn't exist, look up one directory level
103 } while ((len > 0) && (pathname[len - 1] != '/'));
105 if (!CreateFolder(Pathname(pathname.substr(0, len)), mode)) {
109 LOG(LS_INFO) << "Creating folder: " << pathname;
110 return (0 == ::mkdir(pathname.c_str(), mode));
113 bool UnixFilesystem::CreateFolder(const Pathname &path) {
114 return CreateFolder(path, 0755);
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)) {
127 bool UnixFilesystem::CreatePrivateFile(const Pathname &filename) {
128 int fd = open(filename.pathname().c_str(),
129 O_RDWR | O_CREAT | O_EXCL,
132 LOG_ERR(LS_ERROR) << "open() failed.";
135 // Don't need to keep the file descriptor.
137 LOG_ERR(LS_ERROR) << "close() failed.";
143 bool UnixFilesystem::DeleteFile(const Pathname &filename) {
144 LOG(LS_INFO) << "Deleting file:" << filename.pathname();
146 if (!IsFile(filename)) {
147 ASSERT(IsFile(filename));
150 return ::unlink(filename.pathname().c_str()) == 0;
153 bool UnixFilesystem::DeleteEmptyFolder(const Pathname &folder) {
154 LOG(LS_INFO) << "Deleting folder" << folder.pathname();
156 if (!IsFolder(folder)) {
157 ASSERT(IsFolder(folder));
160 std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
161 return ::rmdir(no_slash.c_str()) == 0;
164 bool UnixFilesystem::GetTemporaryFolder(Pathname &pathname, bool create,
165 const std::string *append) {
168 if (0 != FSFindFolder(kOnAppropriateDisk, kTemporaryFolderType,
171 unsigned char buffer[NAME_MAX+1];
172 if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
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, "");
185 pathname.SetPathname(P_tmpdir, "");
187 pathname.SetPathname("/tmp/", "");
190 #endif // !OSX && !ANDROID
192 ASSERT(!append->empty());
193 pathname.AppendFolder(*append);
195 return !create || CreateFolder(pathname);
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];
203 snprintf(tempname, len, "%s/%sXXXXXX", dir.pathname().c_str(),
205 int fd = ::mkstemp(tempname);
208 std::string ret(tempname);
214 bool UnixFilesystem::MoveFile(const Pathname &old_path,
215 const Pathname &new_path) {
216 if (!IsFile(old_path)) {
217 ASSERT(IsFile(old_path));
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) {
225 if (!CopyFile(old_path, new_path))
227 if (!DeleteFile(old_path))
233 bool UnixFilesystem::MoveFolder(const Pathname &old_path,
234 const Pathname &new_path) {
235 if (!IsFolder(old_path)) {
236 ASSERT(IsFolder(old_path));
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) {
244 if (!CopyFolder(old_path, new_path))
246 if (!DeleteFolderAndContents(old_path))
252 bool UnixFilesystem::IsFolder(const Pathname &path) {
254 if (stat(path.pathname().c_str(), &st) < 0)
256 return S_ISDIR(st.st_mode);
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();
266 StreamInterface *source = OpenFile(old_path, "rb");
270 StreamInterface *dest = OpenFile(new_path, "wb");
276 while (source->Read(buf, sizeof(buf), &len, NULL) == SR_SUCCESS)
277 dest->Write(buf, len, NULL, NULL);
284 bool UnixFilesystem::IsTemporaryPath(const Pathname& pathname) {
285 #if defined(ANDROID) || defined(IOS)
286 ASSERT(provided_app_temp_folder_ != NULL);
289 const char* const kTempPrefixes[] = {
290 #if defined(ANDROID) || defined(IOS)
291 provided_app_temp_folder_,
293 "/tmp/", "/var/tmp/",
295 "/private/tmp/", "/private/var/tmp/", "/private/var/folders/",
297 #endif // ANDROID || IOS
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])))
307 bool UnixFilesystem::IsFile(const Pathname& pathname) {
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);
314 bool UnixFilesystem::IsAbsent(const Pathname& pathname) {
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;
322 bool UnixFilesystem::GetFileSize(const Pathname& pathname, size_t *size) {
324 if (::stat(pathname.pathname().c_str(), &st) != 0)
330 bool UnixFilesystem::GetFileTime(const Pathname& path, FileTimeType which,
333 if (::stat(path.pathname().c_str(), &st) != 0)
351 bool UnixFilesystem::GetAppPathname(Pathname* path) {
353 ProcessSerialNumber psn = { 0, kCurrentProcess };
354 CFDictionaryRef procinfo = ProcessInformationCopyDictionary(&psn,
355 kProcessDictionaryIncludeAllInformationMask);
356 if (NULL == procinfo)
358 CFStringRef cfpath = (CFStringRef) CFDictionaryGetValue(procinfo,
359 kIOBundleExecutableKey);
361 bool success = ToUtf8(cfpath, &path8);
364 path->SetPathname(path8);
367 char buffer[NAME_MAX+1];
368 size_t len = readlink("/proc/self/exe", buffer, ARRAY_SIZE(buffer) - 1);
372 path->SetPathname(buffer);
377 bool UnixFilesystem::GetAppDataFolder(Pathname* path, bool per_user) {
378 ASSERT(!organization_name_.empty());
379 ASSERT(!application_name_.empty());
381 // First get the base directory for app data.
384 // Use ~/Library/Application Support/<orgname>/<appname>/
386 if (0 != FSFindFolder(kUserDomain, kApplicationSupportFolderType,
389 unsigned char buffer[NAME_MAX+1];
390 if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
392 path->SetPathname(reinterpret_cast<char*>(buffer), "");
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)
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
407 const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
408 if (xdg_config_home) {
409 path->SetPathname(xdg_config_home, "");
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.
414 if (const char* home = getenv("HOME")) {
416 } else if (const char* dotdir = getenv("DOTDIR")) {
418 } else if (passwd* pw = getpwuid(geteuid())) {
419 homedir = pw->pw_dir;
423 path->SetPathname(homedir, "");
424 path->AppendFolder(".config");
427 // XDG does not define a standard directory for writable global data. Let's
429 path->SetPathname("/var/cache/", "");
431 #endif // !OSX && !defined(ANDROID) && !defined(LINUX)
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_);
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_);
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);
448 if (!CreateFolder(*path, 0700)) {
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;
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_);
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_);
474 // Create a random directory as /tmp/<appname>-<pid>-<timestamp>
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))
484 delete [] app_temp_path_;
485 app_temp_path_ = CopyString(path->pathname());
486 // TODO: atexit(DeleteFolderAndContents(app_temp_path_));
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());
502 memset(&vfs, 0, sizeof(vfs));
503 if (0 != statfs(existing_path.pathname().c_str(), &vfs))
507 memset(&vfs, 0, sizeof(vfs));
508 if (0 != statvfs(existing_path.pathname().c_str(), &vfs))
511 #if defined(LINUX) || defined(ANDROID)
512 *freebytes = static_cast<int64>(vfs.f_bsize) * vfs.f_bavail;
514 *freebytes = static_cast<int64>(vfs.f_frsize) * vfs.f_bavail;
520 Pathname UnixFilesystem::GetCurrentDirectory() {
522 char buffer[PATH_MAX];
523 char *path = getcwd(buffer, PATH_MAX);
526 LOG_ERR(LS_ERROR) << "getcwd() failed";
527 return cwd; // returns empty pathname
529 cwd.SetFolder(std::string(path));
534 char* UnixFilesystem::CopyString(const std::string& str) {
535 size_t size = str.length() + 1;
537 char* buf = new char[size];
542 strcpyn(buf, size, str.c_str());
546 } // namespace talk_base