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