• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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)
20 #include <Carbon/Carbon.h>
21 #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 
47 #include "webrtc/base/arraysize.h"
48 #include "webrtc/base/fileutils.h"
49 #include "webrtc/base/pathutils.h"
50 #include "webrtc/base/stream.h"
51 #include "webrtc/base/stringutils.h"
52 
53 #if defined(WEBRTC_IOS)
54 // Defined in iosfilesystem.mm.  No header file to discourage use
55 // elsewhere; other places should use GetApp{Data,Temp}Folder() in
56 // this file.  Don't copy/paste.  I mean it.
57 char* IOSDataDirectory();
58 char* IOSTempDirectory();
59 void IOSAppName(rtc::Pathname* path);
60 #endif
61 
62 namespace rtc {
63 
64 #if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
65 char* UnixFilesystem::app_temp_path_ = NULL;
66 #else
67 char* UnixFilesystem::provided_app_data_folder_ = NULL;
68 char* UnixFilesystem::provided_app_temp_folder_ = NULL;
69 
70 void UnixFilesystem::SetAppDataFolder(const std::string& folder) {
71   delete [] provided_app_data_folder_;
72   provided_app_data_folder_ = CopyString(folder);
73 }
74 
75 void UnixFilesystem::SetAppTempFolder(const std::string& folder) {
76   delete [] provided_app_temp_folder_;
77   provided_app_temp_folder_ = CopyString(folder);
78 }
79 #endif
80 
UnixFilesystem()81 UnixFilesystem::UnixFilesystem() {
82 #if defined(WEBRTC_IOS)
83   if (!provided_app_data_folder_)
84     provided_app_data_folder_ = IOSDataDirectory();
85   if (!provided_app_temp_folder_)
86     provided_app_temp_folder_ = IOSTempDirectory();
87 #endif
88 }
89 
~UnixFilesystem()90 UnixFilesystem::~UnixFilesystem() {}
91 
CreateFolder(const Pathname & path,mode_t mode)92 bool 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 
CreateFolder(const Pathname & path)121 bool UnixFilesystem::CreateFolder(const Pathname &path) {
122   return CreateFolder(path, 0755);
123 }
124 
OpenFile(const Pathname & filename,const std::string & mode)125 FileStream *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 
CreatePrivateFile(const Pathname & filename)135 bool 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 
DeleteFile(const Pathname & filename)151 bool 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 
DeleteEmptyFolder(const Pathname & folder)161 bool 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 
GetTemporaryFolder(Pathname & pathname,bool create,const std::string * append)172 bool UnixFilesystem::GetTemporaryFolder(Pathname &pathname, bool create,
173                                         const std::string *append) {
174 #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
175   FSRef fr;
176   if (0 != FSFindFolder(kOnAppropriateDisk, kTemporaryFolderType,
177                         kCreateFolder, &fr))
178     return false;
179   unsigned char buffer[NAME_MAX+1];
180   if (0 != FSRefMakePath(&fr, buffer, arraysize(buffer)))
181     return false;
182   pathname.SetPathname(reinterpret_cast<char*>(buffer), "");
183 #elif defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
184   ASSERT(provided_app_temp_folder_ != NULL);
185   pathname.SetPathname(provided_app_temp_folder_, "");
186 #else  // !WEBRTC_MAC || WEBRTC_IOS && !WEBRTC_ANDROID
187   if (const char* tmpdir = getenv("TMPDIR")) {
188     pathname.SetPathname(tmpdir, "");
189   } else if (const char* tmp = getenv("TMP")) {
190     pathname.SetPathname(tmp, "");
191   } else {
192 #ifdef P_tmpdir
193     pathname.SetPathname(P_tmpdir, "");
194 #else  // !P_tmpdir
195     pathname.SetPathname("/tmp/", "");
196 #endif  // !P_tmpdir
197   }
198 #endif  // !WEBRTC_MAC || WEBRTC_IOS && !WEBRTC_ANDROID
199   if (append) {
200     ASSERT(!append->empty());
201     pathname.AppendFolder(*append);
202   }
203   return !create || CreateFolder(pathname);
204 }
205 
TempFilename(const Pathname & dir,const std::string & prefix)206 std::string UnixFilesystem::TempFilename(const Pathname &dir,
207                                          const std::string &prefix) {
208   int len = dir.pathname().size() + prefix.size() + 2 + 6;
209   char *tempname = new char[len];
210 
211   snprintf(tempname, len, "%s/%sXXXXXX", dir.pathname().c_str(),
212            prefix.c_str());
213   int fd = ::mkstemp(tempname);
214   if (fd != -1)
215     ::close(fd);
216   std::string ret(tempname);
217   delete[] tempname;
218 
219   return ret;
220 }
221 
MoveFile(const Pathname & old_path,const Pathname & new_path)222 bool UnixFilesystem::MoveFile(const Pathname &old_path,
223                               const Pathname &new_path) {
224   if (!IsFile(old_path)) {
225     ASSERT(IsFile(old_path));
226     return false;
227   }
228   LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
229                   << " to " << new_path.pathname();
230   if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
231     if (errno != EXDEV)
232       return false;
233     if (!CopyFile(old_path, new_path))
234       return false;
235     if (!DeleteFile(old_path))
236       return false;
237   }
238   return true;
239 }
240 
MoveFolder(const Pathname & old_path,const Pathname & new_path)241 bool UnixFilesystem::MoveFolder(const Pathname &old_path,
242                                 const Pathname &new_path) {
243   if (!IsFolder(old_path)) {
244     ASSERT(IsFolder(old_path));
245     return false;
246   }
247   LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
248                   << " to " << new_path.pathname();
249   if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
250     if (errno != EXDEV)
251       return false;
252     if (!CopyFolder(old_path, new_path))
253       return false;
254     if (!DeleteFolderAndContents(old_path))
255       return false;
256   }
257   return true;
258 }
259 
IsFolder(const Pathname & path)260 bool UnixFilesystem::IsFolder(const Pathname &path) {
261   struct stat st;
262   if (stat(path.pathname().c_str(), &st) < 0)
263     return false;
264   return S_ISDIR(st.st_mode);
265 }
266 
CopyFile(const Pathname & old_path,const Pathname & new_path)267 bool UnixFilesystem::CopyFile(const Pathname &old_path,
268                               const Pathname &new_path) {
269   LOG(LS_VERBOSE) << "Copying " << old_path.pathname()
270                   << " to " << new_path.pathname();
271   char buf[256];
272   size_t len;
273 
274   StreamInterface *source = OpenFile(old_path, "rb");
275   if (!source)
276     return false;
277 
278   StreamInterface *dest = OpenFile(new_path, "wb");
279   if (!dest) {
280     delete source;
281     return false;
282   }
283 
284   while (source->Read(buf, sizeof(buf), &len, NULL) == SR_SUCCESS)
285     dest->Write(buf, len, NULL, NULL);
286 
287   delete source;
288   delete dest;
289   return true;
290 }
291 
IsTemporaryPath(const Pathname & pathname)292 bool UnixFilesystem::IsTemporaryPath(const Pathname& pathname) {
293 #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
294   ASSERT(provided_app_temp_folder_ != NULL);
295 #endif
296 
297   const char* const kTempPrefixes[] = {
298 #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
299     provided_app_temp_folder_,
300 #else
301     "/tmp/", "/var/tmp/",
302 #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
303     "/private/tmp/", "/private/var/tmp/", "/private/var/folders/",
304 #endif  // WEBRTC_MAC && !defined(WEBRTC_IOS)
305 #endif  // WEBRTC_ANDROID || WEBRTC_IOS
306   };
307   for (size_t i = 0; i < arraysize(kTempPrefixes); ++i) {
308     if (0 == strncmp(pathname.pathname().c_str(), kTempPrefixes[i],
309                      strlen(kTempPrefixes[i])))
310       return true;
311   }
312   return false;
313 }
314 
IsFile(const Pathname & pathname)315 bool UnixFilesystem::IsFile(const Pathname& pathname) {
316   struct stat st;
317   int res = ::stat(pathname.pathname().c_str(), &st);
318   // Treat symlinks, named pipes, etc. all as files.
319   return res == 0 && !S_ISDIR(st.st_mode);
320 }
321 
IsAbsent(const Pathname & pathname)322 bool UnixFilesystem::IsAbsent(const Pathname& pathname) {
323   struct stat st;
324   int res = ::stat(pathname.pathname().c_str(), &st);
325   // Note: we specifically maintain ENOTDIR as an error, because that implies
326   // that you could not call CreateFolder(pathname).
327   return res != 0 && ENOENT == errno;
328 }
329 
GetFileSize(const Pathname & pathname,size_t * size)330 bool UnixFilesystem::GetFileSize(const Pathname& pathname, size_t *size) {
331   struct stat st;
332   if (::stat(pathname.pathname().c_str(), &st) != 0)
333     return false;
334   *size = st.st_size;
335   return true;
336 }
337 
GetFileTime(const Pathname & path,FileTimeType which,time_t * time)338 bool UnixFilesystem::GetFileTime(const Pathname& path, FileTimeType which,
339                                  time_t* time) {
340   struct stat st;
341   if (::stat(path.pathname().c_str(), &st) != 0)
342     return false;
343   switch (which) {
344   case FTT_CREATED:
345     *time = st.st_ctime;
346     break;
347   case FTT_MODIFIED:
348     *time = st.st_mtime;
349     break;
350   case FTT_ACCESSED:
351     *time = st.st_atime;
352     break;
353   default:
354     return false;
355   }
356   return true;
357 }
358 
GetAppPathname(Pathname * path)359 bool UnixFilesystem::GetAppPathname(Pathname* path) {
360 #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
361   ProcessSerialNumber psn = { 0, kCurrentProcess };
362   CFDictionaryRef procinfo = ProcessInformationCopyDictionary(&psn,
363       kProcessDictionaryIncludeAllInformationMask);
364   if (NULL == procinfo)
365     return false;
366   CFStringRef cfpath = (CFStringRef) CFDictionaryGetValue(procinfo,
367       kIOBundleExecutableKey);
368   std::string path8;
369   bool success = ToUtf8(cfpath, &path8);
370   CFRelease(procinfo);
371   if (success)
372     path->SetPathname(path8);
373   return success;
374 #elif defined(__native_client__)
375   return false;
376 #elif WEBRTC_IOS
377   IOSAppName(path);
378   return true;
379 #else  // WEBRTC_MAC && !defined(WEBRTC_IOS)
380   char buffer[PATH_MAX + 2];
381   ssize_t len = readlink("/proc/self/exe", buffer, arraysize(buffer) - 1);
382   if ((len <= 0) || (len == PATH_MAX + 1))
383     return false;
384   buffer[len] = '\0';
385   path->SetPathname(buffer);
386   return true;
387 #endif  // WEBRTC_MAC && !defined(WEBRTC_IOS)
388 }
389 
GetAppDataFolder(Pathname * path,bool per_user)390 bool UnixFilesystem::GetAppDataFolder(Pathname* path, bool per_user) {
391   ASSERT(!organization_name_.empty());
392   ASSERT(!application_name_.empty());
393 
394   // First get the base directory for app data.
395 #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
396   if (per_user) {
397     // Use ~/Library/Application Support/<orgname>/<appname>/
398     FSRef fr;
399     if (0 != FSFindFolder(kUserDomain, kApplicationSupportFolderType,
400                           kCreateFolder, &fr))
401       return false;
402     unsigned char buffer[NAME_MAX+1];
403     if (0 != FSRefMakePath(&fr, buffer, arraysize(buffer)))
404       return false;
405     path->SetPathname(reinterpret_cast<char*>(buffer), "");
406   } else {
407     // TODO
408     return false;
409   }
410 #elif defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)  // && !WEBRTC_MAC || WEBRTC_IOS
411   ASSERT(provided_app_data_folder_ != NULL);
412   path->SetPathname(provided_app_data_folder_, "");
413 #elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)  // && !WEBRTC_MAC && !WEBRTC_IOS && !WEBRTC_ANDROID
414   if (per_user) {
415     // We follow the recommendations in
416     // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
417     // It specifies separate directories for data and config files, but
418     // GetAppDataFolder() does not distinguish. We just return the config dir
419     // path.
420     const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
421     if (xdg_config_home) {
422       path->SetPathname(xdg_config_home, "");
423     } else {
424       // XDG says to default to $HOME/.config. We also support falling back to
425       // other synonyms for HOME if for some reason it is not defined.
426       const char* homedir;
427       if (const char* home = getenv("HOME")) {
428         homedir = home;
429       } else if (const char* dotdir = getenv("DOTDIR")) {
430         homedir = dotdir;
431       } else if (passwd* pw = getpwuid(geteuid())) {
432         homedir = pw->pw_dir;
433       } else {
434         return false;
435       }
436       path->SetPathname(homedir, "");
437       path->AppendFolder(".config");
438     }
439   } else {
440     // XDG does not define a standard directory for writable global data. Let's
441     // just use this.
442     path->SetPathname("/var/cache/", "");
443   }
444 #endif  // !WEBRTC_MAC && !WEBRTC_LINUX
445 
446   // Now add on a sub-path for our app.
447 #if defined(WEBRTC_MAC) || defined(WEBRTC_ANDROID)
448   path->AppendFolder(organization_name_);
449   path->AppendFolder(application_name_);
450 #elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
451   // XDG says to use a single directory level, so we concatenate the org and app
452   // name with a hyphen. We also do the Linuxy thing and convert to all
453   // lowercase with no spaces.
454   std::string subdir(organization_name_);
455   subdir.append("-");
456   subdir.append(application_name_);
457   replace_substrs(" ", 1, "", 0, &subdir);
458   std::transform(subdir.begin(), subdir.end(), subdir.begin(), ::tolower);
459   path->AppendFolder(subdir);
460 #endif
461   if (!CreateFolder(*path, 0700)) {
462     return false;
463   }
464 #if !defined(__native_client__)
465   // If the folder already exists, it may have the wrong mode or be owned by
466   // someone else, both of which are security problems. Setting the mode
467   // avoids both issues since it will fail if the path is not owned by us.
468   if (0 != ::chmod(path->pathname().c_str(), 0700)) {
469     LOG_ERR(LS_ERROR) << "Can't set mode on " << path;
470     return false;
471   }
472 #endif
473   return true;
474 }
475 
GetAppTempFolder(Pathname * path)476 bool UnixFilesystem::GetAppTempFolder(Pathname* path) {
477 #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
478   ASSERT(provided_app_temp_folder_ != NULL);
479   path->SetPathname(provided_app_temp_folder_);
480   return true;
481 #else
482   ASSERT(!application_name_.empty());
483   // TODO: Consider whether we are worried about thread safety.
484   if (app_temp_path_ != NULL && strlen(app_temp_path_) > 0) {
485     path->SetPathname(app_temp_path_);
486     return true;
487   }
488 
489   // Create a random directory as /tmp/<appname>-<pid>-<timestamp>
490   char buffer[128];
491   sprintfn(buffer, arraysize(buffer), "-%d-%d",
492            static_cast<int>(getpid()),
493            static_cast<int>(time(0)));
494   std::string folder(application_name_);
495   folder.append(buffer);
496   if (!GetTemporaryFolder(*path, true, &folder))
497     return false;
498 
499   delete [] app_temp_path_;
500   app_temp_path_ = CopyString(path->pathname());
501   // TODO: atexit(DeleteFolderAndContents(app_temp_path_));
502   return true;
503 #endif
504 }
505 
GetDiskFreeSpace(const Pathname & path,int64_t * freebytes)506 bool UnixFilesystem::GetDiskFreeSpace(const Pathname& path,
507                                       int64_t* freebytes) {
508 #ifdef __native_client__
509   return false;
510 #else  // __native_client__
511   ASSERT(NULL != freebytes);
512   // TODO: Consider making relative paths absolute using cwd.
513   // TODO: When popping off a symlink, push back on the components of the
514   // symlink, so we don't jump out of the target disk inadvertently.
515   Pathname existing_path(path.folder(), "");
516   while (!existing_path.folder().empty() && IsAbsent(existing_path)) {
517     existing_path.SetFolder(existing_path.parent_folder());
518   }
519 #if defined(WEBRTC_ANDROID)
520   struct statfs vfs;
521   memset(&vfs, 0, sizeof(vfs));
522   if (0 != statfs(existing_path.pathname().c_str(), &vfs))
523     return false;
524 #else
525   struct statvfs vfs;
526   memset(&vfs, 0, sizeof(vfs));
527   if (0 != statvfs(existing_path.pathname().c_str(), &vfs))
528     return false;
529 #endif  // WEBRTC_ANDROID
530 #if defined(WEBRTC_LINUX)
531   *freebytes = static_cast<int64_t>(vfs.f_bsize) * vfs.f_bavail;
532 #elif defined(WEBRTC_MAC)
533   *freebytes = static_cast<int64_t>(vfs.f_frsize) * vfs.f_bavail;
534 #endif
535 
536   return true;
537 #endif  // !__native_client__
538 }
539 
GetCurrentDirectory()540 Pathname UnixFilesystem::GetCurrentDirectory() {
541   Pathname cwd;
542   char buffer[PATH_MAX];
543   char *path = getcwd(buffer, PATH_MAX);
544 
545   if (!path) {
546     LOG_ERR(LS_ERROR) << "getcwd() failed";
547     return cwd;  // returns empty pathname
548   }
549   cwd.SetFolder(std::string(path));
550 
551   return cwd;
552 }
553 
CopyString(const std::string & str)554 char* UnixFilesystem::CopyString(const std::string& str) {
555   size_t size = str.length() + 1;
556 
557   char* buf = new char[size];
558   if (!buf) {
559     return NULL;
560   }
561 
562   strcpyn(buf, size, str.c_str());
563   return buf;
564 }
565 
566 }  // namespace rtc
567 
568 #if defined(__native_client__)
569 extern "C" int __attribute__((weak))
link(const char * oldpath,const char * newpath)570 link(const char* oldpath, const char* newpath) {
571   errno = EACCES;
572   return -1;
573 }
574 #endif
575