1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "sandboxed_api/util/temp_file.h"
16
17 #include <unistd.h>
18
19 #include <cerrno>
20 #include <string>
21 #include <utility>
22
23 #include "absl/status/status.h"
24 #include "absl/status/statusor.h"
25 #include "absl/strings/str_cat.h"
26 #include "absl/strings/string_view.h"
27 #include "sandboxed_api/util/status_macros.h"
28
29 namespace sapi {
30
31 namespace {
32 constexpr absl::string_view kMktempSuffix = "XXXXXX";
33 } // namespace
34
CreateNamedTempFile(absl::string_view prefix)35 absl::StatusOr<std::pair<std::string, int>> CreateNamedTempFile(
36 absl::string_view prefix) {
37 std::string name_template = absl::StrCat(prefix, kMktempSuffix);
38 int fd = mkstemp(&name_template[0]);
39 if (fd < 0) {
40 return absl::ErrnoToStatus(errno, "mkstemp()");
41 }
42 return std::pair<std::string, int>{std::move(name_template), fd};
43 }
44
CreateNamedTempFileAndClose(absl::string_view prefix)45 absl::StatusOr<std::string> CreateNamedTempFileAndClose(
46 absl::string_view prefix) {
47 SAPI_ASSIGN_OR_RETURN(auto result, CreateNamedTempFile(prefix));
48 close(result.second);
49 return std::move(result.first);
50 }
51
CreateTempDir(absl::string_view prefix)52 absl::StatusOr<std::string> CreateTempDir(absl::string_view prefix) {
53 std::string name_template = absl::StrCat(prefix, kMktempSuffix);
54 if (mkdtemp(&name_template[0]) == nullptr) {
55 return absl::ErrnoToStatus(errno, "mkdtemp()");
56 }
57 return name_template;
58 }
59
60 } // namespace sapi
61