2020-01-17 21:05:03 +08:00
|
|
|
// Copyright 2019 Google LLC
|
2019-03-19 00:21:48 +08:00
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
#include "sandboxed_api/sandbox2/util/temp_file.h"
|
|
|
|
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
#include <sys/types.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
|
|
|
|
#include <cstdlib>
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
#include "absl/strings/str_cat.h"
|
|
|
|
#include "sandboxed_api/sandbox2/util/fileops.h"
|
|
|
|
#include "sandboxed_api/sandbox2/util/strerror.h"
|
|
|
|
|
|
|
|
namespace sandbox2 {
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
constexpr absl::string_view kMktempSuffix = "XXXXXX";
|
|
|
|
} // namespace
|
|
|
|
|
2019-08-23 23:08:23 +08:00
|
|
|
sapi::StatusOr<std::pair<std::string, int>> CreateNamedTempFile(
|
2019-03-19 00:21:48 +08:00
|
|
|
absl::string_view prefix) {
|
|
|
|
std::string name_template = absl::StrCat(prefix, kMktempSuffix);
|
|
|
|
int fd = mkstemp(&name_template[0]);
|
|
|
|
if (fd < 0) {
|
2020-02-28 01:23:44 +08:00
|
|
|
return absl::UnknownError(absl::StrCat("mkstemp():", StrError(errno)));
|
2019-03-19 00:21:48 +08:00
|
|
|
}
|
|
|
|
return std::pair<std::string, int>{std::move(name_template), fd};
|
|
|
|
}
|
|
|
|
|
2019-08-23 23:08:23 +08:00
|
|
|
sapi::StatusOr<std::string> CreateNamedTempFileAndClose(
|
2019-03-26 22:54:02 +08:00
|
|
|
absl::string_view prefix) {
|
2019-03-19 00:21:48 +08:00
|
|
|
auto result_or = CreateNamedTempFile(prefix);
|
|
|
|
if (result_or.ok()) {
|
|
|
|
std::string path;
|
|
|
|
int fd;
|
2020-04-02 22:42:17 +08:00
|
|
|
std::tie(path, fd) = std::move(result_or).value();
|
2019-03-19 00:21:48 +08:00
|
|
|
close(fd);
|
|
|
|
return path;
|
|
|
|
}
|
|
|
|
return result_or.status();
|
|
|
|
}
|
|
|
|
|
2019-08-23 23:08:23 +08:00
|
|
|
sapi::StatusOr<std::string> CreateTempDir(absl::string_view prefix) {
|
2019-03-19 00:21:48 +08:00
|
|
|
std::string name_template = absl::StrCat(prefix, kMktempSuffix);
|
|
|
|
if (mkdtemp(&name_template[0]) == nullptr) {
|
2020-02-28 01:23:44 +08:00
|
|
|
return absl::UnknownError(absl::StrCat("mkdtemp():", StrError(errno)));
|
2019-03-19 00:21:48 +08:00
|
|
|
}
|
|
|
|
return name_template;
|
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace sandbox2
|