You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

531 lines
16 KiB

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