blob: b7a720ecf1bed1715dad40c6fc63016f215999a9 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/base/unixfilesystem.h"
12
13#include <errno.h>
14#include <fcntl.h>
15#include <stdlib.h>
16#include <sys/stat.h>
17#include <unistd.h>
18
19#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
kthelgasona90879b2016-09-08 03:34:40 -070020#include <CoreFoundation/CoreFoundation.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#include <IOKit/IOCFBundle.h>
22#include <sys/statvfs.h>
23#include "webrtc/base/macutils.h"
24#endif // WEBRTC_MAC && !defined(WEBRTC_IOS)
25
26#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
27#include <sys/types.h>
28#if defined(WEBRTC_ANDROID)
29#include <sys/statfs.h>
30#elif !defined(__native_client__)
31#include <sys/statvfs.h>
32#endif // !defined(__native_client__)
33#include <limits.h>
34#include <pwd.h>
35#include <stdio.h>
36#endif // WEBRTC_POSIX && !WEBRTC_MAC || WEBRTC_IOS
37
38#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
39#include <ctype.h>
40#include <algorithm>
41#endif
42
43#if defined(__native_client__) && !defined(__GLIBC__)
44#include <sys/syslimits.h>
45#endif
46
tfarina5237aaf2015-11-10 23:44:30 -080047#include "webrtc/base/arraysize.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000048#include "webrtc/base/fileutils.h"
49#include "webrtc/base/pathutils.h"
50#include "webrtc/base/stream.h"
51#include "webrtc/base/stringutils.h"
52
kthelgasona90879b2016-09-08 03:34:40 -070053#if defined(WEBRTC_MAC)
54// Defined in applefilesystem.mm. No header file to discourage use
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055// elsewhere; other places should use GetApp{Data,Temp}Folder() in
56// this file. Don't copy/paste. I mean it.
kthelgasona90879b2016-09-08 03:34:40 -070057char* AppleDataDirectory();
58char* AppleTempDirectory();
59void AppleAppName(rtc::Pathname* path);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060#endif
61
62namespace rtc {
63
64#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
65char* UnixFilesystem::app_temp_path_ = NULL;
66#else
67char* UnixFilesystem::provided_app_data_folder_ = NULL;
68char* UnixFilesystem::provided_app_temp_folder_ = NULL;
69
70void UnixFilesystem::SetAppDataFolder(const std::string& folder) {
71 delete [] provided_app_data_folder_;
72 provided_app_data_folder_ = CopyString(folder);
73}
74
75void UnixFilesystem::SetAppTempFolder(const std::string& folder) {
76 delete [] provided_app_temp_folder_;
77 provided_app_temp_folder_ = CopyString(folder);
78}
79#endif
80
81UnixFilesystem::UnixFilesystem() {
82#if defined(WEBRTC_IOS)
83 if (!provided_app_data_folder_)
kthelgasona90879b2016-09-08 03:34:40 -070084 provided_app_data_folder_ = AppleDataDirectory();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085 if (!provided_app_temp_folder_)
kthelgasona90879b2016-09-08 03:34:40 -070086 provided_app_temp_folder_ = AppleTempDirectory();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000087#endif
88}
89
90UnixFilesystem::~UnixFilesystem() {}
91
92bool UnixFilesystem::CreateFolder(const Pathname &path, mode_t mode) {
93 std::string pathname(path.pathname());
94 int len = pathname.length();
95 if ((len == 0) || (pathname[len - 1] != '/'))
96 return false;
97
98 struct stat st;
99 int res = ::stat(pathname.c_str(), &st);
100 if (res == 0) {
101 // Something exists at this location, check if it is a directory
102 return S_ISDIR(st.st_mode) != 0;
103 } else if (errno != ENOENT) {
104 // Unexpected error
105 return false;
106 }
107
108 // Directory doesn't exist, look up one directory level
109 do {
110 --len;
111 } while ((len > 0) && (pathname[len - 1] != '/'));
112
113 if (!CreateFolder(Pathname(pathname.substr(0, len)), mode)) {
114 return false;
115 }
116
117 LOG(LS_INFO) << "Creating folder: " << pathname;
118 return (0 == ::mkdir(pathname.c_str(), mode));
119}
120
121bool UnixFilesystem::CreateFolder(const Pathname &path) {
122 return CreateFolder(path, 0755);
123}
124
125FileStream *UnixFilesystem::OpenFile(const Pathname &filename,
126 const std::string &mode) {
127 FileStream *fs = new FileStream();
128 if (fs && !fs->Open(filename.pathname().c_str(), mode.c_str(), NULL)) {
129 delete fs;
130 fs = NULL;
131 }
132 return fs;
133}
134
135bool UnixFilesystem::CreatePrivateFile(const Pathname &filename) {
136 int fd = open(filename.pathname().c_str(),
137 O_RDWR | O_CREAT | O_EXCL,
138 S_IRUSR | S_IWUSR);
139 if (fd < 0) {
140 LOG_ERR(LS_ERROR) << "open() failed.";
141 return false;
142 }
143 // Don't need to keep the file descriptor.
144 if (close(fd) < 0) {
145 LOG_ERR(LS_ERROR) << "close() failed.";
146 // Continue.
147 }
148 return true;
149}
150
151bool UnixFilesystem::DeleteFile(const Pathname &filename) {
152 LOG(LS_INFO) << "Deleting file:" << filename.pathname();
153
154 if (!IsFile(filename)) {
155 ASSERT(IsFile(filename));
156 return false;
157 }
158 return ::unlink(filename.pathname().c_str()) == 0;
159}
160
161bool UnixFilesystem::DeleteEmptyFolder(const Pathname &folder) {
162 LOG(LS_INFO) << "Deleting folder" << folder.pathname();
163
164 if (!IsFolder(folder)) {
165 ASSERT(IsFolder(folder));
166 return false;
167 }
168 std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
169 return ::rmdir(no_slash.c_str()) == 0;
170}
171
172bool UnixFilesystem::GetTemporaryFolder(Pathname &pathname, bool create,
173 const std::string *append) {
kthelgasona90879b2016-09-08 03:34:40 -0700174#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175 ASSERT(provided_app_temp_folder_ != NULL);
176 pathname.SetPathname(provided_app_temp_folder_, "");
kthelgasona90879b2016-09-08 03:34:40 -0700177#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178 if (const char* tmpdir = getenv("TMPDIR")) {
179 pathname.SetPathname(tmpdir, "");
180 } else if (const char* tmp = getenv("TMP")) {
181 pathname.SetPathname(tmp, "");
182 } else {
183#ifdef P_tmpdir
184 pathname.SetPathname(P_tmpdir, "");
185#else // !P_tmpdir
186 pathname.SetPathname("/tmp/", "");
187#endif // !P_tmpdir
188 }
kthelgasona90879b2016-09-08 03:34:40 -0700189#endif // defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190 if (append) {
191 ASSERT(!append->empty());
192 pathname.AppendFolder(*append);
193 }
194 return !create || CreateFolder(pathname);
195}
196
197std::string UnixFilesystem::TempFilename(const Pathname &dir,
198 const std::string &prefix) {
199 int len = dir.pathname().size() + prefix.size() + 2 + 6;
200 char *tempname = new char[len];
201
202 snprintf(tempname, len, "%s/%sXXXXXX", dir.pathname().c_str(),
203 prefix.c_str());
204 int fd = ::mkstemp(tempname);
205 if (fd != -1)
206 ::close(fd);
207 std::string ret(tempname);
208 delete[] tempname;
209
210 return ret;
211}
212
213bool UnixFilesystem::MoveFile(const Pathname &old_path,
214 const Pathname &new_path) {
215 if (!IsFile(old_path)) {
216 ASSERT(IsFile(old_path));
217 return false;
218 }
219 LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
220 << " to " << new_path.pathname();
221 if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
222 if (errno != EXDEV)
223 return false;
224 if (!CopyFile(old_path, new_path))
225 return false;
226 if (!DeleteFile(old_path))
227 return false;
228 }
229 return true;
230}
231
232bool UnixFilesystem::MoveFolder(const Pathname &old_path,
233 const Pathname &new_path) {
234 if (!IsFolder(old_path)) {
235 ASSERT(IsFolder(old_path));
236 return false;
237 }
238 LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
239 << " to " << new_path.pathname();
240 if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
241 if (errno != EXDEV)
242 return false;
243 if (!CopyFolder(old_path, new_path))
244 return false;
245 if (!DeleteFolderAndContents(old_path))
246 return false;
247 }
248 return true;
249}
250
251bool UnixFilesystem::IsFolder(const Pathname &path) {
252 struct stat st;
253 if (stat(path.pathname().c_str(), &st) < 0)
254 return false;
255 return S_ISDIR(st.st_mode);
256}
257
258bool UnixFilesystem::CopyFile(const Pathname &old_path,
259 const Pathname &new_path) {
260 LOG(LS_VERBOSE) << "Copying " << old_path.pathname()
261 << " to " << new_path.pathname();
262 char buf[256];
263 size_t len;
264
265 StreamInterface *source = OpenFile(old_path, "rb");
266 if (!source)
267 return false;
268
269 StreamInterface *dest = OpenFile(new_path, "wb");
270 if (!dest) {
271 delete source;
272 return false;
273 }
274
275 while (source->Read(buf, sizeof(buf), &len, NULL) == SR_SUCCESS)
276 dest->Write(buf, len, NULL, NULL);
277
278 delete source;
279 delete dest;
280 return true;
281}
282
283bool UnixFilesystem::IsTemporaryPath(const Pathname& pathname) {
284#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
285 ASSERT(provided_app_temp_folder_ != NULL);
286#endif
287
288 const char* const kTempPrefixes[] = {
289#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
290 provided_app_temp_folder_,
291#else
292 "/tmp/", "/var/tmp/",
293#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
294 "/private/tmp/", "/private/var/tmp/", "/private/var/folders/",
295#endif // WEBRTC_MAC && !defined(WEBRTC_IOS)
296#endif // WEBRTC_ANDROID || WEBRTC_IOS
297 };
tfarina5237aaf2015-11-10 23:44:30 -0800298 for (size_t i = 0; i < arraysize(kTempPrefixes); ++i) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299 if (0 == strncmp(pathname.pathname().c_str(), kTempPrefixes[i],
300 strlen(kTempPrefixes[i])))
301 return true;
302 }
303 return false;
304}
305
306bool UnixFilesystem::IsFile(const Pathname& pathname) {
307 struct stat st;
308 int res = ::stat(pathname.pathname().c_str(), &st);
309 // Treat symlinks, named pipes, etc. all as files.
310 return res == 0 && !S_ISDIR(st.st_mode);
311}
312
313bool UnixFilesystem::IsAbsent(const Pathname& pathname) {
314 struct stat st;
315 int res = ::stat(pathname.pathname().c_str(), &st);
316 // Note: we specifically maintain ENOTDIR as an error, because that implies
317 // that you could not call CreateFolder(pathname).
318 return res != 0 && ENOENT == errno;
319}
320
321bool UnixFilesystem::GetFileSize(const Pathname& pathname, size_t *size) {
322 struct stat st;
323 if (::stat(pathname.pathname().c_str(), &st) != 0)
324 return false;
325 *size = st.st_size;
326 return true;
327}
328
329bool UnixFilesystem::GetFileTime(const Pathname& path, FileTimeType which,
330 time_t* time) {
331 struct stat st;
332 if (::stat(path.pathname().c_str(), &st) != 0)
333 return false;
334 switch (which) {
335 case FTT_CREATED:
336 *time = st.st_ctime;
337 break;
338 case FTT_MODIFIED:
339 *time = st.st_mtime;
340 break;
341 case FTT_ACCESSED:
342 *time = st.st_atime;
343 break;
344 default:
345 return false;
346 }
347 return true;
348}
349
350bool UnixFilesystem::GetAppPathname(Pathname* path) {
kthelgasona90879b2016-09-08 03:34:40 -0700351#if defined(__native_client__)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352 return false;
kthelgasona90879b2016-09-08 03:34:40 -0700353#elif defined(WEBRTC_MAC)
354 AppleAppName(path);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355 return true;
356#else // WEBRTC_MAC && !defined(WEBRTC_IOS)
357 char buffer[PATH_MAX + 2];
tfarina5237aaf2015-11-10 23:44:30 -0800358 ssize_t len = readlink("/proc/self/exe", buffer, arraysize(buffer) - 1);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000359 if ((len <= 0) || (len == PATH_MAX + 1))
360 return false;
361 buffer[len] = '\0';
362 path->SetPathname(buffer);
363 return true;
364#endif // WEBRTC_MAC && !defined(WEBRTC_IOS)
365}
366
367bool UnixFilesystem::GetAppDataFolder(Pathname* path, bool per_user) {
368 ASSERT(!organization_name_.empty());
369 ASSERT(!application_name_.empty());
370
371 // First get the base directory for app data.
372#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
373 if (per_user) {
374 // Use ~/Library/Application Support/<orgname>/<appname>/
375 FSRef fr;
376 if (0 != FSFindFolder(kUserDomain, kApplicationSupportFolderType,
377 kCreateFolder, &fr))
378 return false;
379 unsigned char buffer[NAME_MAX+1];
tfarina5237aaf2015-11-10 23:44:30 -0800380 if (0 != FSRefMakePath(&fr, buffer, arraysize(buffer)))
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000381 return false;
382 path->SetPathname(reinterpret_cast<char*>(buffer), "");
383 } else {
384 // TODO
385 return false;
386 }
387#elif defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) // && !WEBRTC_MAC || WEBRTC_IOS
388 ASSERT(provided_app_data_folder_ != NULL);
389 path->SetPathname(provided_app_data_folder_, "");
390#elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) // && !WEBRTC_MAC && !WEBRTC_IOS && !WEBRTC_ANDROID
391 if (per_user) {
392 // We follow the recommendations in
393 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
394 // It specifies separate directories for data and config files, but
395 // GetAppDataFolder() does not distinguish. We just return the config dir
396 // path.
397 const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
398 if (xdg_config_home) {
399 path->SetPathname(xdg_config_home, "");
400 } else {
401 // XDG says to default to $HOME/.config. We also support falling back to
402 // other synonyms for HOME if for some reason it is not defined.
403 const char* homedir;
404 if (const char* home = getenv("HOME")) {
405 homedir = home;
406 } else if (const char* dotdir = getenv("DOTDIR")) {
407 homedir = dotdir;
408 } else if (passwd* pw = getpwuid(geteuid())) {
409 homedir = pw->pw_dir;
410 } else {
411 return false;
412 }
413 path->SetPathname(homedir, "");
414 path->AppendFolder(".config");
415 }
416 } else {
417 // XDG does not define a standard directory for writable global data. Let's
418 // just use this.
419 path->SetPathname("/var/cache/", "");
420 }
421#endif // !WEBRTC_MAC && !WEBRTC_LINUX
422
423 // Now add on a sub-path for our app.
424#if defined(WEBRTC_MAC) || defined(WEBRTC_ANDROID)
425 path->AppendFolder(organization_name_);
426 path->AppendFolder(application_name_);
427#elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
428 // XDG says to use a single directory level, so we concatenate the org and app
429 // name with a hyphen. We also do the Linuxy thing and convert to all
430 // lowercase with no spaces.
431 std::string subdir(organization_name_);
432 subdir.append("-");
433 subdir.append(application_name_);
434 replace_substrs(" ", 1, "", 0, &subdir);
435 std::transform(subdir.begin(), subdir.end(), subdir.begin(), ::tolower);
436 path->AppendFolder(subdir);
437#endif
438 if (!CreateFolder(*path, 0700)) {
439 return false;
440 }
441#if !defined(__native_client__)
442 // If the folder already exists, it may have the wrong mode or be owned by
443 // someone else, both of which are security problems. Setting the mode
444 // avoids both issues since it will fail if the path is not owned by us.
445 if (0 != ::chmod(path->pathname().c_str(), 0700)) {
446 LOG_ERR(LS_ERROR) << "Can't set mode on " << path;
447 return false;
448 }
449#endif
450 return true;
451}
452
453bool UnixFilesystem::GetAppTempFolder(Pathname* path) {
454#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
455 ASSERT(provided_app_temp_folder_ != NULL);
456 path->SetPathname(provided_app_temp_folder_);
457 return true;
458#else
459 ASSERT(!application_name_.empty());
460 // TODO: Consider whether we are worried about thread safety.
461 if (app_temp_path_ != NULL && strlen(app_temp_path_) > 0) {
462 path->SetPathname(app_temp_path_);
463 return true;
464 }
465
466 // Create a random directory as /tmp/<appname>-<pid>-<timestamp>
467 char buffer[128];
tfarina5237aaf2015-11-10 23:44:30 -0800468 sprintfn(buffer, arraysize(buffer), "-%d-%d",
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000469 static_cast<int>(getpid()),
470 static_cast<int>(time(0)));
471 std::string folder(application_name_);
472 folder.append(buffer);
473 if (!GetTemporaryFolder(*path, true, &folder))
474 return false;
475
476 delete [] app_temp_path_;
477 app_temp_path_ = CopyString(path->pathname());
478 // TODO: atexit(DeleteFolderAndContents(app_temp_path_));
479 return true;
480#endif
481}
482
Peter Boström0c4e06b2015-10-07 12:23:21 +0200483bool UnixFilesystem::GetDiskFreeSpace(const Pathname& path,
484 int64_t* freebytes) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000485#ifdef __native_client__
486 return false;
487#else // __native_client__
488 ASSERT(NULL != freebytes);
489 // TODO: Consider making relative paths absolute using cwd.
490 // TODO: When popping off a symlink, push back on the components of the
491 // symlink, so we don't jump out of the target disk inadvertently.
492 Pathname existing_path(path.folder(), "");
493 while (!existing_path.folder().empty() && IsAbsent(existing_path)) {
494 existing_path.SetFolder(existing_path.parent_folder());
495 }
496#if defined(WEBRTC_ANDROID)
497 struct statfs vfs;
498 memset(&vfs, 0, sizeof(vfs));
499 if (0 != statfs(existing_path.pathname().c_str(), &vfs))
500 return false;
501#else
502 struct statvfs vfs;
503 memset(&vfs, 0, sizeof(vfs));
504 if (0 != statvfs(existing_path.pathname().c_str(), &vfs))
505 return false;
506#endif // WEBRTC_ANDROID
507#if defined(WEBRTC_LINUX)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200508 *freebytes = static_cast<int64_t>(vfs.f_bsize) * vfs.f_bavail;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000509#elif defined(WEBRTC_MAC)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200510 *freebytes = static_cast<int64_t>(vfs.f_frsize) * vfs.f_bavail;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000511#endif
512
513 return true;
514#endif // !__native_client__
515}
516
517Pathname UnixFilesystem::GetCurrentDirectory() {
518 Pathname cwd;
519 char buffer[PATH_MAX];
520 char *path = getcwd(buffer, PATH_MAX);
521
522 if (!path) {
523 LOG_ERR(LS_ERROR) << "getcwd() failed";
524 return cwd; // returns empty pathname
525 }
526 cwd.SetFolder(std::string(path));
527
528 return cwd;
529}
530
531char* UnixFilesystem::CopyString(const std::string& str) {
532 size_t size = str.length() + 1;
533
534 char* buf = new char[size];
535 if (!buf) {
536 return NULL;
537 }
538
539 strcpyn(buf, size, str.c_str());
540 return buf;
541}
542
543} // namespace rtc
544
545#if defined(__native_client__)
546extern "C" int __attribute__((weak))
547link(const char* oldpath, const char* newpath) {
548 errno = EACCES;
549 return -1;
550}
551#endif