blob: a756ae515e21f0bddfc172e8117952b42cab6dde [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)
kthelgasond5472242016-09-09 03:19:48 -070020#include <CoreServices/CoreServices.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
kthelgasond5472242016-09-09 03:19:48 -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.
kthelgasond5472242016-09-09 03:19:48 -070057char* AppleDataDirectory();
58char* AppleTempDirectory();
59void AppleAppName(rtc::Pathname* path);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060#endif
61
62namespace rtc {
63
erikchen2ca8d5c2016-10-05 16:04:33 -070064#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065char* 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() {
erikchen2ca8d5c2016-10-05 16:04:33 -070082#if defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000083 if (!provided_app_data_folder_)
kthelgasond5472242016-09-09 03:19:48 -070084 provided_app_data_folder_ = AppleDataDirectory();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085 if (!provided_app_temp_folder_)
kthelgasond5472242016-09-09 03:19:48 -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) {
erikchen2ca8d5c2016-10-05 16:04:33 -0700174#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175 ASSERT(provided_app_temp_folder_ != NULL);
176 pathname.SetPathname(provided_app_temp_folder_, "");
kthelgasond5472242016-09-09 03:19:48 -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 }
kthelgasond5472242016-09-09 03:19:48 -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) {
erikchen2ca8d5c2016-10-05 16:04:33 -0700284#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000285 ASSERT(provided_app_temp_folder_ != NULL);
286#endif
287
288 const char* const kTempPrefixes[] = {
erikchen2ca8d5c2016-10-05 16:04:33 -0700289#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290 provided_app_temp_folder_,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
292 "/private/tmp/", "/private/var/tmp/", "/private/var/folders/",
293#endif // WEBRTC_MAC && !defined(WEBRTC_IOS)
erikchen2ca8d5c2016-10-05 16:04:33 -0700294#else
295 "/tmp/", "/var/tmp/",
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000296#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) {
kthelgasond5472242016-09-09 03:19:48 -0700351#if defined(__native_client__)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352 return false;
kthelgasond5472242016-09-09 03:19:48 -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) {
erikchen2ca8d5c2016-10-05 16:04:33 -0700368 // On macOS and iOS, there is no requirement that the path contains the
369 // organization.
370#if !defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000371 ASSERT(!organization_name_.empty());
erikchen2ca8d5c2016-10-05 16:04:33 -0700372#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000373 ASSERT(!application_name_.empty());
374
375 // First get the base directory for app data.
erikchen2ca8d5c2016-10-05 16:04:33 -0700376#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000377 ASSERT(provided_app_data_folder_ != NULL);
378 path->SetPathname(provided_app_data_folder_, "");
erikchen2ca8d5c2016-10-05 16:04:33 -0700379#elif defined(WEBRTC_LINUX) // && !WEBRTC_MAC && !WEBRTC_ANDROID
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000380 if (per_user) {
381 // We follow the recommendations in
382 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
383 // It specifies separate directories for data and config files, but
384 // GetAppDataFolder() does not distinguish. We just return the config dir
385 // path.
386 const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
387 if (xdg_config_home) {
388 path->SetPathname(xdg_config_home, "");
389 } else {
390 // XDG says to default to $HOME/.config. We also support falling back to
391 // other synonyms for HOME if for some reason it is not defined.
392 const char* homedir;
393 if (const char* home = getenv("HOME")) {
394 homedir = home;
395 } else if (const char* dotdir = getenv("DOTDIR")) {
396 homedir = dotdir;
397 } else if (passwd* pw = getpwuid(geteuid())) {
398 homedir = pw->pw_dir;
399 } else {
400 return false;
401 }
402 path->SetPathname(homedir, "");
403 path->AppendFolder(".config");
404 }
405 } else {
406 // XDG does not define a standard directory for writable global data. Let's
407 // just use this.
408 path->SetPathname("/var/cache/", "");
409 }
410#endif // !WEBRTC_MAC && !WEBRTC_LINUX
411
412 // Now add on a sub-path for our app.
413#if defined(WEBRTC_MAC) || defined(WEBRTC_ANDROID)
414 path->AppendFolder(organization_name_);
415 path->AppendFolder(application_name_);
416#elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
417 // XDG says to use a single directory level, so we concatenate the org and app
418 // name with a hyphen. We also do the Linuxy thing and convert to all
419 // lowercase with no spaces.
420 std::string subdir(organization_name_);
421 subdir.append("-");
422 subdir.append(application_name_);
423 replace_substrs(" ", 1, "", 0, &subdir);
424 std::transform(subdir.begin(), subdir.end(), subdir.begin(), ::tolower);
425 path->AppendFolder(subdir);
426#endif
427 if (!CreateFolder(*path, 0700)) {
428 return false;
429 }
430#if !defined(__native_client__)
431 // If the folder already exists, it may have the wrong mode or be owned by
432 // someone else, both of which are security problems. Setting the mode
433 // avoids both issues since it will fail if the path is not owned by us.
434 if (0 != ::chmod(path->pathname().c_str(), 0700)) {
435 LOG_ERR(LS_ERROR) << "Can't set mode on " << path;
436 return false;
437 }
438#endif
439 return true;
440}
441
442bool UnixFilesystem::GetAppTempFolder(Pathname* path) {
erikchen2ca8d5c2016-10-05 16:04:33 -0700443#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000444 ASSERT(provided_app_temp_folder_ != NULL);
445 path->SetPathname(provided_app_temp_folder_);
446 return true;
447#else
448 ASSERT(!application_name_.empty());
449 // TODO: Consider whether we are worried about thread safety.
450 if (app_temp_path_ != NULL && strlen(app_temp_path_) > 0) {
451 path->SetPathname(app_temp_path_);
452 return true;
453 }
454
455 // Create a random directory as /tmp/<appname>-<pid>-<timestamp>
456 char buffer[128];
tfarina5237aaf2015-11-10 23:44:30 -0800457 sprintfn(buffer, arraysize(buffer), "-%d-%d",
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000458 static_cast<int>(getpid()),
459 static_cast<int>(time(0)));
460 std::string folder(application_name_);
461 folder.append(buffer);
462 if (!GetTemporaryFolder(*path, true, &folder))
463 return false;
464
465 delete [] app_temp_path_;
466 app_temp_path_ = CopyString(path->pathname());
467 // TODO: atexit(DeleteFolderAndContents(app_temp_path_));
468 return true;
469#endif
470}
471
Peter Boström0c4e06b2015-10-07 12:23:21 +0200472bool UnixFilesystem::GetDiskFreeSpace(const Pathname& path,
473 int64_t* freebytes) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000474#ifdef __native_client__
475 return false;
476#else // __native_client__
477 ASSERT(NULL != freebytes);
478 // TODO: Consider making relative paths absolute using cwd.
479 // TODO: When popping off a symlink, push back on the components of the
480 // symlink, so we don't jump out of the target disk inadvertently.
481 Pathname existing_path(path.folder(), "");
482 while (!existing_path.folder().empty() && IsAbsent(existing_path)) {
483 existing_path.SetFolder(existing_path.parent_folder());
484 }
485#if defined(WEBRTC_ANDROID)
486 struct statfs vfs;
487 memset(&vfs, 0, sizeof(vfs));
488 if (0 != statfs(existing_path.pathname().c_str(), &vfs))
489 return false;
490#else
491 struct statvfs vfs;
492 memset(&vfs, 0, sizeof(vfs));
493 if (0 != statvfs(existing_path.pathname().c_str(), &vfs))
494 return false;
495#endif // WEBRTC_ANDROID
496#if defined(WEBRTC_LINUX)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200497 *freebytes = static_cast<int64_t>(vfs.f_bsize) * vfs.f_bavail;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000498#elif defined(WEBRTC_MAC)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200499 *freebytes = static_cast<int64_t>(vfs.f_frsize) * vfs.f_bavail;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000500#endif
501
502 return true;
503#endif // !__native_client__
504}
505
506Pathname UnixFilesystem::GetCurrentDirectory() {
507 Pathname cwd;
508 char buffer[PATH_MAX];
509 char *path = getcwd(buffer, PATH_MAX);
510
511 if (!path) {
512 LOG_ERR(LS_ERROR) << "getcwd() failed";
513 return cwd; // returns empty pathname
514 }
515 cwd.SetFolder(std::string(path));
516
517 return cwd;
518}
519
520char* UnixFilesystem::CopyString(const std::string& str) {
521 size_t size = str.length() + 1;
522
523 char* buf = new char[size];
524 if (!buf) {
525 return NULL;
526 }
527
528 strcpyn(buf, size, str.c_str());
529 return buf;
530}
531
532} // namespace rtc
533
534#if defined(__native_client__)
535extern "C" int __attribute__((weak))
536link(const char* oldpath, const char* newpath) {
537 errno = EACCES;
538 return -1;
539}
540#endif