aboutsummaryrefslogtreecommitdiffstats
path: root/liblfjail/fileutils.cc
blob: b73e05f0157c6e8348eb9865b2426a605fb64ac9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
 * This source code is released into the public domain.
 */

#include <iostream>
#include <print>
#include <string>

#include <sys/stat.h>

#include "context.hh"
#include "fileutils.hh"
#include "generic_error.hh"

namespace lfjail {

void ensure_dir(context const &ctx, std::string_view dir) {
	auto const cdir = std::string(dir);

	struct ::stat st{};
	if (auto const err = ::stat(cdir.c_str(), &st); err == 0) {
		if (!S_ISDIR(st.st_mode))
			throw generic_error("{}: already exists", dir);
		return;
	}

	if (errno != ENOENT)
		throw generic_error("{}: stat: {}",
				    dir, ::strerror(errno));

	if (auto const err = ::mkdir(cdir.c_str(), 0700); err != 0)
		throw generic_error("{}: mkdir: {}",
				    dir, ::strerror(errno));

	if (ctx.verbose)
		std::print(std::cerr, "{}: created {}\n",
			   getprogname(), dir);
}

} // namespace lfjail