summaryrefslogtreecommitdiff
path: root/netfs/fuse/fuseApp.cpp
blob: 04602aae9494170ae931b1e252daaea9268b4be9 (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#include "fuseApp.h"
#include "cache.impl.h"
#include "fuseDirs.h"
#include "fuseFiles.h"
#include "fuseMappersImpl.h"
#include "lockHelpers.h"
#include <Glacier2/Router.h>
#include <boost/lexical_cast.hpp>
#include <compileTimeFormatter.h>
#include <cstring>
#include <defaultMapper.h>
#include <entCache.h>
#include <safeMapFind.h>
#include <slicer/slicer.h>
#include <uriParse.h>

namespace AdHoc {
	template class Cache<struct stat, std::string>;
	template class CallCacheable<struct stat, std::string>;
}

NetFS::FuseApp::FuseApp(Ice::StringSeq && a) : iceArgs(std::move(a)), sessionOpened(false), openHandleId(0) { }

NetFS::FuseApp::~FuseApp()
{
	for (const OpenDirs::value_type & of : openDirs) {
		// LCOV_EXCL_START
		try {
			of.second->remote->close();
		}
		catch (...) {
			// Can't do anything useful here
		}
		// LCOV_EXCL_STOP
	}
	for (const OpenFiles::value_type & of : openFiles) {
		// LCOV_EXCL_START
		try {
			of.second->remote->close();
		}
		catch (...) {
			// Can't do anything useful here
		}
		// LCOV_EXCL_STOP
	}
	if (volume) {
		try {
			volume->disconnect();
		}
		catch (...) {
			// Can't do anything useful here
		}
	}
	if (session) {
		try {
			session->destroy();
		}
		catch (...) {
			// Can't do anything useful here
		}
	}
	if (ic) {
		ic->destroy();
	}
}

void *
NetFS::FuseApp::init(struct fuse_conn_info *, struct fuse_config *)
{
	BOOST_ASSERT(!ic);
	ic = Ice::initialize(iceArgs);
	BOOST_ASSERT(ic);
	if (!iceArgs.empty()) {
		const auto & arg = iceArgs.front();
		if (arg.find("://") != std::string::npos) {
			fcr = configureFromUri(arg);
		}
		else if (auto colon = arg.find(':'); colon != std::string::npos) {
			fcr = configureFromFile(arg.substr(0, colon), arg.substr(colon + 1));
		}
	}
	if (!fcr->Mapper) {
		fcr->Mapper = std::make_shared<Mapping::DefaultMapper>();
	}
	BOOST_ASSERT(fcr);
	converter.mapper = fcr->Mapper;
	return this;
}

NetFS::Client::ResourcePtr
NetFS::FuseApp::configureFromFile(const std::filesystem::path & path, const std::string & resourceName)
{
	auto s = Slicer::FileDeserializerFactory::createNew(path.extension().string(), path);
	auto c = Slicer::DeserializeAnyWith<NetFS::Client::ConfigurationPtr>(s);
	return AdHoc::safeMapLookup<Client::ResourceNotFound>(c->Resources, resourceName);
}

AdHocFormatter(IceEndpointFmt, "%? -h %? -p %?");
NetFS::Client::ResourcePtr
NetFS::FuseApp::configureFromUri(const std::string & uriString)
{
	const AdHoc::Uri uri(uriString);

	auto r = std::make_shared<NetFS::Client::Resource>();
	r->ExportName = uri.path->string();
	r->Endpoints.emplace_back(IceEndpointFmt::get(uri.scheme, uri.host, uri.port ? *uri.port : 4000));
	if (uri.password) {
		r->AuthToken = *uri.password;
	}
	auto set = [&uri](const auto & param, auto & setting) {
		if (auto p = uri.query.find(param); p != uri.query.end()) {
			setting = boost::lexical_cast<std::remove_reference_t<decltype(setting)>>(p->second);
		}
	};
	auto setWith = [&uri](const auto & param, auto & setting, auto && f) {
		if (auto p = uri.query.find(param); p != uri.query.end()) {
			setting = f(p->second);
		}
	};
	set("async", r->Async);
	setWith("mapper", r->Mapper, [&set, &setWith](auto && m) -> NetFS::Mapping::MapperPtr {
		if (m == "hide") {
			return std::make_shared<NetFS::Client::HideUnknownMapperImpl>();
		}
		else if (m == "mask") {
			auto mi = std::make_shared<NetFS::Client::MaskUnknownMapperImpl>();
			set("mapper.unknownuser", mi->UnknownUser);
			set("mapper.unknowngroup", mi->UnknownGroup);
			setWith("mapper.usermask", mi->UserMask, Client::from_octal);
			setWith("mapper.groupmask", mi->GroupMask, Client::from_octal);
			return mi;
		}
		return {};
	});
	return r;
}

int
NetFS::FuseApp::opt_parse(void * data, const char * arg, int, struct fuse_args *)
{
	auto & iceArgs = *static_cast<Ice::StringSeq *>(data);
	if (strncmp(arg, "--Ice.", 6) == 0) {
		iceArgs.emplace_back(arg);
		return 0;
	}
	else if (strncmp(arg, "_netdev", 7) == 0) {
		return 0;
	}
	else if (arg[0] == '-') {
		return 1;
	}
	else if (iceArgs.empty() || strncmp(iceArgs.front().c_str(), "--Ice.", 6) == 0) {
		iceArgs.emplace(iceArgs.begin(), arg);
		return 0;
	}
	return 1;
}

void
NetFS::FuseApp::connectSession()
{
	if (!sessionOpened && ic->getDefaultRouter()) {
		Lock(_lock);
		auto router = Ice::checkedCast<Glacier2::RouterPrx>(ic->getDefaultRouter());
		session = router->createSession("", "");
		if (int acmTimeout = router->getACMTimeout() > 0) {
			Ice::ConnectionPtr conn = router->ice_getCachedConnection();
			conn->setACM(acmTimeout, IceUtil::None, Ice::ACMHeartbeat::HeartbeatAlways);
		}
		sessionOpened = true;
	}
}

void
NetFS::FuseApp::connectToService()
{
	if (!service) {
		Lock(_lock);
		auto proxyAddr = fcr->ServiceIdentity;
		for (const auto & ep : fcr->Endpoints) {
			proxyAddr += ":" + ep;
		}
		service = Ice::checkedCast<NetFS::ServicePrx>(ic->stringToProxy(proxyAddr));
		if (!service) {
			throw std::runtime_error("Invalid service proxy: " + proxyAddr);
		}
	}
}

void
NetFS::FuseApp::connectToVolume()
{
	if (!volume) {
		Lock(_lock);
		volume = service->connect(fcr->ExportName, fcr->AuthToken);
		if (!volume) {
			throw std::runtime_error("Invalid filesystem proxy");
		}
	}
}

void
NetFS::FuseApp::connectHandles()
{
	for (const OpenFiles::value_type & of : openFiles) {
		try {
			of.second->remote->ice_ping();
		}
		catch (const Ice::ObjectNotExistException &) {
			of.second->remote = volume->open(reqEnv(), of.second->path, of.second->flags & !O_CREAT);
		}
	}
	for (const OpenDirs::value_type & of : openDirs) {
		try {
			of.second->remote->ice_ping();
		}
		catch (const Ice::ObjectNotExistException &) {
			of.second->remote = volume->opendir(reqEnv(), of.second->path);
		}
	}
}

void
NetFS::FuseApp::verifyConnection()
{
	Lock(_lock);
	if (session) {
		try {
			session->ice_ping();
		}
		catch (const Ice::Exception &) {
			session = nullptr;
			sessionOpened = false;
		}
	}
	if (service) {
		try {
			service->ice_ping();
		}
		catch (const Ice::Exception &) {
			service = nullptr;
		}
	}
	if (volume) {
		try {
			volume->ice_ping();
		}
		catch (const Ice::Exception &) {
			volume = nullptr;
		}
	}
}

int
NetFS::FuseApp::onError(const std::exception & e) noexcept
{
	if (dynamic_cast<const Ice::SocketException *>(&e) || dynamic_cast<const Ice::TimeoutException *>(&e)) {
		log(LOG_ERR, e.what());
		try {
			verifyConnection();
			connectSession();
			connectToService();
			connectToVolume();
			connectHandles();
			return 0;
		}
		catch (...) {
			return -EIO;
		}
	}
	if (dynamic_cast<const Ice::RequestFailedException *>(&e)) {
		try {
			volume = nullptr;
			connectToVolume();
			connectHandles();
			return 0;
		}
		catch (...) {
			return -EIO;
		}
	}
	if (dynamic_cast<const NetFS::AuthError *>(&e)) {
		return -EPERM;
	}
	return FuseAppBase::onError(e);
}

void
NetFS::FuseApp::beforeOperation()
{
	connectSession();
	connectToService();
	connectToVolume();
}

NetFS::ReqEnv
NetFS::FuseApp::reqEnv()
{
	struct fuse_context * c = fuse_get_context();
	const auto t = converter.mapper->mapFileSystem(c->uid, c->gid);
	return {t.username, t.groupname};
}