blob: a787b4752c7e959890a71af5c9fcdb67bd169296 [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"
nisseede5da42017-01-12 05:15:36 -080048#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000049#include "webrtc/base/fileutils.h"
50#include "webrtc/base/pathutils.h"
51#include "webrtc/base/stream.h"
52#include "webrtc/base/stringutils.h"
53
kthelgasond5472242016-09-09 03:19:48 -070054#if defined(WEBRTC_MAC)
55// Defined in applefilesystem.mm. No header file to discourage use
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000056// elsewhere; other places should use GetApp{Data,Temp}Folder() in
57// this file. Don't copy/paste. I mean it.
kthelgasond5472242016-09-09 03:19:48 -070058char* AppleDataDirectory();
59char* AppleTempDirectory();
60void AppleAppName(rtc::Pathname* path);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000061#endif
62
63namespace rtc {
64
erikchen2ca8d5c2016-10-05 16:04:33 -070065#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066char* UnixFilesystem::app_temp_path_ = NULL;
67#else
68char* UnixFilesystem::provided_app_data_folder_ = NULL;
69char* UnixFilesystem::provided_app_temp_folder_ = NULL;
70
71void UnixFilesystem::SetAppDataFolder(const std::string& folder) {
72 delete [] provided_app_data_folder_;
73 provided_app_data_folder_ = CopyString(folder);
74}
75
76void UnixFilesystem::SetAppTempFolder(const std::string& folder) {
77 delete [] provided_app_temp_folder_;
78 provided_app_temp_folder_ = CopyString(folder);
79}
80#endif
81
82UnixFilesystem::UnixFilesystem() {
erikchen2ca8d5c2016-10-05 16:04:33 -070083#if defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000084 if (!provided_app_data_folder_)
kthelgasond5472242016-09-09 03:19:48 -070085 provided_app_data_folder_ = AppleDataDirectory();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000086 if (!provided_app_temp_folder_)
kthelgasond5472242016-09-09 03:19:48 -070087 provided_app_temp_folder_ = AppleTempDirectory();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088#endif
89}
90
91UnixFilesystem::~UnixFilesystem() {}
92
93bool UnixFilesystem::CreateFolder(const Pathname &path, mode_t mode) {
94 std::string pathname(path.pathname());
95 int len = pathname.length();
96 if ((len == 0) || (pathname[len - 1] != '/'))
97 return false;
98
99 struct stat st;
100 int res = ::stat(pathname.c_str(), &st);
101 if (res == 0) {
102 // Something exists at this location, check if it is a directory
103 return S_ISDIR(st.st_mode) != 0;
104 } else if (errno != ENOENT) {
105 // Unexpected error
106 return false;
107 }
108
109 // Directory doesn't exist, look up one directory level
110 do {
111 --len;
112 } while ((len > 0) && (pathname[len - 1] != '/'));
113
114 if (!CreateFolder(Pathname(pathname.substr(0, len)), mode)) {
115 return false;
116 }
117
118 LOG(LS_INFO) << "Creating folder: " << pathname;
119 return (0 == ::mkdir(pathname.c_str(), mode));
120}
121
122bool UnixFilesystem::CreateFolder(const Pathname &path) {
123 return CreateFolder(path, 0755);
124}
125
126FileStream *UnixFilesystem::OpenFile(const Pathname &filename,
127 const std::string &mode) {
128 FileStream *fs = new FileStream();
129 if (fs && !fs->Open(filename.pathname().c_str(), mode.c_str(), NULL)) {
130 delete fs;
131 fs = NULL;
132 }
133 return fs;
134}
135
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136bool UnixFilesystem::DeleteFile(const Pathname &filename) {
137 LOG(LS_INFO) << "Deleting file:" << filename.pathname();
138
139 if (!IsFile(filename)) {
nisseede5da42017-01-12 05:15:36 -0800140 RTC_DCHECK(IsFile(filename));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141 return false;
142 }
143 return ::unlink(filename.pathname().c_str()) == 0;
144}
145
146bool UnixFilesystem::DeleteEmptyFolder(const Pathname &folder) {
147 LOG(LS_INFO) << "Deleting folder" << folder.pathname();
148
149 if (!IsFolder(folder)) {
nisseede5da42017-01-12 05:15:36 -0800150 RTC_DCHECK(IsFolder(folder));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000151 return false;
152 }
153 std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
154 return ::rmdir(no_slash.c_str()) == 0;
155}
156
157bool UnixFilesystem::GetTemporaryFolder(Pathname &pathname, bool create,
158 const std::string *append) {
erikchen2ca8d5c2016-10-05 16:04:33 -0700159#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
nisseede5da42017-01-12 05:15:36 -0800160 RTC_DCHECK(provided_app_temp_folder_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000161 pathname.SetPathname(provided_app_temp_folder_, "");
kthelgasond5472242016-09-09 03:19:48 -0700162#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000163 if (const char* tmpdir = getenv("TMPDIR")) {
164 pathname.SetPathname(tmpdir, "");
165 } else if (const char* tmp = getenv("TMP")) {
166 pathname.SetPathname(tmp, "");
167 } else {
168#ifdef P_tmpdir
169 pathname.SetPathname(P_tmpdir, "");
170#else // !P_tmpdir
171 pathname.SetPathname("/tmp/", "");
172#endif // !P_tmpdir
173 }
kthelgasond5472242016-09-09 03:19:48 -0700174#endif // defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175 if (append) {
nisseede5da42017-01-12 05:15:36 -0800176 RTC_DCHECK(!append->empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177 pathname.AppendFolder(*append);
178 }
179 return !create || CreateFolder(pathname);
180}
181
182std::string UnixFilesystem::TempFilename(const Pathname &dir,
183 const std::string &prefix) {
184 int len = dir.pathname().size() + prefix.size() + 2 + 6;
185 char *tempname = new char[len];
186
187 snprintf(tempname, len, "%s/%sXXXXXX", dir.pathname().c_str(),
188 prefix.c_str());
189 int fd = ::mkstemp(tempname);
190 if (fd != -1)
191 ::close(fd);
192 std::string ret(tempname);
193 delete[] tempname;
194
195 return ret;
196}
197
198bool UnixFilesystem::MoveFile(const Pathname &old_path,
199 const Pathname &new_path) {
200 if (!IsFile(old_path)) {
nisseede5da42017-01-12 05:15:36 -0800201 RTC_DCHECK(IsFile(old_path));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000202 return false;
203 }
204 LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
205 << " to " << new_path.pathname();
206 if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
207 if (errno != EXDEV)
208 return false;
209 if (!CopyFile(old_path, new_path))
210 return false;
211 if (!DeleteFile(old_path))
212 return false;
213 }
214 return true;
215}
216
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000217bool UnixFilesystem::IsFolder(const Pathname &path) {
218 struct stat st;
219 if (stat(path.pathname().c_str(), &st) < 0)
220 return false;
221 return S_ISDIR(st.st_mode);
222}
223
224bool UnixFilesystem::CopyFile(const Pathname &old_path,
225 const Pathname &new_path) {
226 LOG(LS_VERBOSE) << "Copying " << old_path.pathname()
227 << " to " << new_path.pathname();
228 char buf[256];
229 size_t len;
230
231 StreamInterface *source = OpenFile(old_path, "rb");
232 if (!source)
233 return false;
234
235 StreamInterface *dest = OpenFile(new_path, "wb");
236 if (!dest) {
237 delete source;
238 return false;
239 }
240
241 while (source->Read(buf, sizeof(buf), &len, NULL) == SR_SUCCESS)
242 dest->Write(buf, len, NULL, NULL);
243
244 delete source;
245 delete dest;
246 return true;
247}
248
249bool UnixFilesystem::IsTemporaryPath(const Pathname& pathname) {
erikchen2ca8d5c2016-10-05 16:04:33 -0700250#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
nisseede5da42017-01-12 05:15:36 -0800251 RTC_DCHECK(provided_app_temp_folder_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252#endif
253
254 const char* const kTempPrefixes[] = {
erikchen2ca8d5c2016-10-05 16:04:33 -0700255#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256 provided_app_temp_folder_,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000257#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
258 "/private/tmp/", "/private/var/tmp/", "/private/var/folders/",
259#endif // WEBRTC_MAC && !defined(WEBRTC_IOS)
erikchen2ca8d5c2016-10-05 16:04:33 -0700260#else
261 "/tmp/", "/var/tmp/",
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262#endif // WEBRTC_ANDROID || WEBRTC_IOS
263 };
tfarina5237aaf2015-11-10 23:44:30 -0800264 for (size_t i = 0; i < arraysize(kTempPrefixes); ++i) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265 if (0 == strncmp(pathname.pathname().c_str(), kTempPrefixes[i],
266 strlen(kTempPrefixes[i])))
267 return true;
268 }
269 return false;
270}
271
272bool UnixFilesystem::IsFile(const Pathname& pathname) {
273 struct stat st;
274 int res = ::stat(pathname.pathname().c_str(), &st);
275 // Treat symlinks, named pipes, etc. all as files.
276 return res == 0 && !S_ISDIR(st.st_mode);
277}
278
279bool UnixFilesystem::IsAbsent(const Pathname& pathname) {
280 struct stat st;
281 int res = ::stat(pathname.pathname().c_str(), &st);
282 // Note: we specifically maintain ENOTDIR as an error, because that implies
283 // that you could not call CreateFolder(pathname).
284 return res != 0 && ENOENT == errno;
285}
286
287bool UnixFilesystem::GetFileSize(const Pathname& pathname, size_t *size) {
288 struct stat st;
289 if (::stat(pathname.pathname().c_str(), &st) != 0)
290 return false;
291 *size = st.st_size;
292 return true;
293}
294
295bool UnixFilesystem::GetFileTime(const Pathname& path, FileTimeType which,
296 time_t* time) {
297 struct stat st;
298 if (::stat(path.pathname().c_str(), &st) != 0)
299 return false;
300 switch (which) {
301 case FTT_CREATED:
302 *time = st.st_ctime;
303 break;
304 case FTT_MODIFIED:
305 *time = st.st_mtime;
306 break;
307 case FTT_ACCESSED:
308 *time = st.st_atime;
309 break;
310 default:
311 return false;
312 }
313 return true;
314}
315
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316bool UnixFilesystem::GetAppDataFolder(Pathname* path, bool per_user) {
erikchen2ca8d5c2016-10-05 16:04:33 -0700317 // On macOS and iOS, there is no requirement that the path contains the
318 // organization.
319#if !defined(WEBRTC_MAC)
nisseede5da42017-01-12 05:15:36 -0800320 RTC_DCHECK(!organization_name_.empty());
erikchen2ca8d5c2016-10-05 16:04:33 -0700321#endif
nisseede5da42017-01-12 05:15:36 -0800322 RTC_DCHECK(!application_name_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323
324 // First get the base directory for app data.
erikchen2ca8d5c2016-10-05 16:04:33 -0700325#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
nisseede5da42017-01-12 05:15:36 -0800326 RTC_DCHECK(provided_app_data_folder_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000327 path->SetPathname(provided_app_data_folder_, "");
erikchen2ca8d5c2016-10-05 16:04:33 -0700328#elif defined(WEBRTC_LINUX) // && !WEBRTC_MAC && !WEBRTC_ANDROID
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000329 if (per_user) {
330 // We follow the recommendations in
331 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
332 // It specifies separate directories for data and config files, but
333 // GetAppDataFolder() does not distinguish. We just return the config dir
334 // path.
335 const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
336 if (xdg_config_home) {
337 path->SetPathname(xdg_config_home, "");
338 } else {
339 // XDG says to default to $HOME/.config. We also support falling back to
340 // other synonyms for HOME if for some reason it is not defined.
341 const char* homedir;
342 if (const char* home = getenv("HOME")) {
343 homedir = home;
344 } else if (const char* dotdir = getenv("DOTDIR")) {
345 homedir = dotdir;
346 } else if (passwd* pw = getpwuid(geteuid())) {
347 homedir = pw->pw_dir;
348 } else {
349 return false;
350 }
351 path->SetPathname(homedir, "");
352 path->AppendFolder(".config");
353 }
354 } else {
355 // XDG does not define a standard directory for writable global data. Let's
356 // just use this.
357 path->SetPathname("/var/cache/", "");
358 }
359#endif // !WEBRTC_MAC && !WEBRTC_LINUX
360
361 // Now add on a sub-path for our app.
362#if defined(WEBRTC_MAC) || defined(WEBRTC_ANDROID)
363 path->AppendFolder(organization_name_);
364 path->AppendFolder(application_name_);
365#elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
366 // XDG says to use a single directory level, so we concatenate the org and app
367 // name with a hyphen. We also do the Linuxy thing and convert to all
368 // lowercase with no spaces.
369 std::string subdir(organization_name_);
370 subdir.append("-");
371 subdir.append(application_name_);
372 replace_substrs(" ", 1, "", 0, &subdir);
373 std::transform(subdir.begin(), subdir.end(), subdir.begin(), ::tolower);
374 path->AppendFolder(subdir);
375#endif
376 if (!CreateFolder(*path, 0700)) {
377 return false;
378 }
379#if !defined(__native_client__)
380 // If the folder already exists, it may have the wrong mode or be owned by
381 // someone else, both of which are security problems. Setting the mode
382 // avoids both issues since it will fail if the path is not owned by us.
383 if (0 != ::chmod(path->pathname().c_str(), 0700)) {
384 LOG_ERR(LS_ERROR) << "Can't set mode on " << path;
385 return false;
386 }
387#endif
388 return true;
389}
390
391bool UnixFilesystem::GetAppTempFolder(Pathname* path) {
erikchen2ca8d5c2016-10-05 16:04:33 -0700392#if defined(WEBRTC_ANDROID) || defined(WEBRTC_MAC)
nisseede5da42017-01-12 05:15:36 -0800393 RTC_DCHECK(provided_app_temp_folder_ != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000394 path->SetPathname(provided_app_temp_folder_);
395 return true;
396#else
nisseede5da42017-01-12 05:15:36 -0800397 RTC_DCHECK(!application_name_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000398 // TODO: Consider whether we are worried about thread safety.
399 if (app_temp_path_ != NULL && strlen(app_temp_path_) > 0) {
400 path->SetPathname(app_temp_path_);
401 return true;
402 }
403
404 // Create a random directory as /tmp/<appname>-<pid>-<timestamp>
405 char buffer[128];
tfarina5237aaf2015-11-10 23:44:30 -0800406 sprintfn(buffer, arraysize(buffer), "-%d-%d",
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000407 static_cast<int>(getpid()),
408 static_cast<int>(time(0)));
409 std::string folder(application_name_);
410 folder.append(buffer);
411 if (!GetTemporaryFolder(*path, true, &folder))
412 return false;
413
414 delete [] app_temp_path_;
415 app_temp_path_ = CopyString(path->pathname());
416 // TODO: atexit(DeleteFolderAndContents(app_temp_path_));
417 return true;
418#endif
419}
420
Peter Boström0c4e06b2015-10-07 12:23:21 +0200421bool UnixFilesystem::GetDiskFreeSpace(const Pathname& path,
422 int64_t* freebytes) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000423#ifdef __native_client__
424 return false;
425#else // __native_client__
nisseede5da42017-01-12 05:15:36 -0800426 RTC_DCHECK(NULL != freebytes);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000427 // TODO: Consider making relative paths absolute using cwd.
428 // TODO: When popping off a symlink, push back on the components of the
429 // symlink, so we don't jump out of the target disk inadvertently.
430 Pathname existing_path(path.folder(), "");
431 while (!existing_path.folder().empty() && IsAbsent(existing_path)) {
432 existing_path.SetFolder(existing_path.parent_folder());
433 }
434#if defined(WEBRTC_ANDROID)
435 struct statfs vfs;
436 memset(&vfs, 0, sizeof(vfs));
437 if (0 != statfs(existing_path.pathname().c_str(), &vfs))
438 return false;
439#else
440 struct statvfs vfs;
441 memset(&vfs, 0, sizeof(vfs));
442 if (0 != statvfs(existing_path.pathname().c_str(), &vfs))
443 return false;
444#endif // WEBRTC_ANDROID
445#if defined(WEBRTC_LINUX)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200446 *freebytes = static_cast<int64_t>(vfs.f_bsize) * vfs.f_bavail;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447#elif defined(WEBRTC_MAC)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200448 *freebytes = static_cast<int64_t>(vfs.f_frsize) * vfs.f_bavail;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000449#endif
450
451 return true;
452#endif // !__native_client__
453}
454
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000455char* UnixFilesystem::CopyString(const std::string& str) {
456 size_t size = str.length() + 1;
457
458 char* buf = new char[size];
459 if (!buf) {
460 return NULL;
461 }
462
463 strcpyn(buf, size, str.c_str());
464 return buf;
465}
466
467} // namespace rtc
468
469#if defined(__native_client__)
470extern "C" int __attribute__((weak))
471link(const char* oldpath, const char* newpath) {
472 errno = EACCES;
473 return -1;
474}
475#endif