SandboxOpenedFiles.cpp (1981B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "SandboxOpenedFiles.h" 8 9 #include <errno.h> 10 #include <fcntl.h> 11 #include <unistd.h> 12 13 #include <utility> 14 15 #include "SandboxLogging.h" 16 17 namespace mozilla { 18 19 // The default move constructor almost works, but Atomic isn't 20 // move-constructable and the fd needs some special handling. 21 SandboxOpenedFile::SandboxOpenedFile(SandboxOpenedFile&& aMoved) 22 : mPath(std::move(aMoved.mPath)), 23 mMaybeFd(aMoved.TakeDesc()), 24 mDup(aMoved.mDup), 25 mExpectError(aMoved.mExpectError) {} 26 27 SandboxOpenedFile::SandboxOpenedFile(const char* aPath, Dup aDup) 28 : mPath(aPath), mDup(aDup == Dup::YES), mExpectError(false) { 29 MOZ_ASSERT(aPath[0] == '/', "path should be absolute"); 30 31 int fd = open(aPath, O_RDONLY | O_CLOEXEC); 32 if (fd < 0) { 33 mExpectError = true; 34 } 35 mMaybeFd = fd; 36 } 37 38 SandboxOpenedFile::SandboxOpenedFile(const char* aPath, Error) 39 : mPath(aPath), mMaybeFd(-1), mDup(false), mExpectError(true) {} 40 41 int SandboxOpenedFile::GetDesc() const { 42 int fd; 43 if (mDup) { 44 fd = mMaybeFd; 45 if (fd >= 0) { 46 fd = dup(fd); 47 if (fd < 0) { 48 SANDBOX_LOG_ERRNO("dup"); 49 } 50 } 51 } else { 52 fd = TakeDesc(); 53 } 54 if (fd < 0 && !mExpectError) { 55 SANDBOX_LOG("unexpected multiple open of file %s", Path()); 56 } 57 return fd; 58 } 59 60 SandboxOpenedFile::~SandboxOpenedFile() { 61 int fd = TakeDesc(); 62 if (fd >= 0) { 63 close(fd); 64 } 65 } 66 67 int SandboxOpenedFiles::GetDesc(const char* aPath) const { 68 for (const auto& file : mFiles) { 69 if (strcmp(file.Path(), aPath) == 0) { 70 return file.GetDesc(); 71 } 72 } 73 SANDBOX_LOG("attempt to open unexpected file %s", aPath); 74 return -1; 75 } 76 77 } // namespace mozilla