NfsStorage.cxx 9.4 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "config.h"
#include "NfsStorage.hxx"
#include "storage/StoragePlugin.hxx"
#include "storage/StorageInterface.hxx"
#include "storage/FileInfo.hxx"
25
#include "storage/MemoryDirectoryReader.hxx"
26
#include "lib/nfs/Blocking.hxx"
27
#include "lib/nfs/Base.hxx"
28 29 30
#include "lib/nfs/Lease.hxx"
#include "lib/nfs/Connection.hxx"
#include "lib/nfs/Glue.hxx"
31
#include "fs/AllocatedPath.hxx"
32
#include "thread/Mutex.hxx"
33 34 35
#include "thread/Cond.hxx"
#include "event/Loop.hxx"
#include "event/Call.hxx"
36
#include "event/DeferEvent.hxx"
37
#include "event/TimerEvent.hxx"
38
#include "util/StringCompare.hxx"
39 40 41 42 43 44

extern "C" {
#include <nfsc/libnfs.h>
#include <nfsc/libnfs-raw-nfs.h>
}

45 46 47
#include <string>

#include <assert.h>
48 49 50
#include <sys/stat.h>
#include <fcntl.h>

51
class NfsStorage final
52
	: public Storage, NfsLease {
53 54 55 56 57

	enum class State {
		INITIAL, CONNECTING, READY, DELAY,
	};

58 59
	const std::string base;

60 61 62 63
	const std::string server, export_name;

	NfsConnection *connection;

64
	DeferEvent defer_connect;
65 66
	TimerEvent reconnect_timer;

67 68
	Mutex mutex;
	Cond cond;
69
	State state = State::INITIAL;
70
	std::exception_ptr last_exception;
71 72

public:
73 74
	NfsStorage(EventLoop &_loop, const char *_base,
		   std::string &&_server, std::string &&_export_name)
75
		:base(_base),
76 77
		 server(std::move(_server)),
		 export_name(std::move(_export_name)),
78
		 defer_connect(_loop, BIND_THIS_METHOD(OnDeferredConnect)),
79
		 reconnect_timer(_loop, BIND_THIS_METHOD(OnReconnectTimer)) {
80
		nfs_init(_loop);
81
	}
82

83 84 85
	~NfsStorage() {
		BlockingCall(GetEventLoop(), [this](){ Disconnect(); });
		nfs_finish();
86 87 88
	}

	/* virtual methods from class Storage */
89
	StorageFileInfo GetInfo(const char *uri_utf8, bool follow) override;
90

91
	std::unique_ptr<StorageDirectoryReader> OpenDirectory(const char *uri_utf8) override;
92

93
	std::string MapUTF8(const char *uri_utf8) const noexcept override;
94

95
	const char *MapToRelativeUTF8(const char *uri_utf8) const noexcept override;
96 97

	/* virtual methods from NfsLease */
98
	void OnNfsConnectionReady() noexcept final {
99 100 101 102 103
		assert(state == State::CONNECTING);

		SetState(State::READY);
	}

104
	void OnNfsConnectionFailed(std::exception_ptr e) noexcept final {
105 106
		assert(state == State::CONNECTING);

107
		SetState(State::DELAY, std::move(e));
108
		reconnect_timer.Schedule(std::chrono::minutes(1));
109 110
	}

111
	void OnNfsConnectionDisconnected(std::exception_ptr e) noexcept final {
112 113
		assert(state == State::READY);

114
		SetState(State::DELAY, std::move(e));
115
		reconnect_timer.Schedule(std::chrono::seconds(5));
116 117
	}

118 119
	/* DeferEvent callback */
	void OnDeferredConnect() noexcept {
120 121 122 123
		if (state == State::INITIAL)
			Connect();
	}

124 125
	/* callback for #reconnect_timer */
	void OnReconnectTimer() {
126 127 128 129 130 131
		assert(state == State::DELAY);

		Connect();
	}

private:
132
	EventLoop &GetEventLoop() noexcept {
133
		return defer_connect.GetEventLoop();
134 135
	}

136
	void SetState(State _state) noexcept {
137 138
		assert(GetEventLoop().IsInside());

139
		const std::lock_guard<Mutex> protect(mutex);
140 141 142 143
		state = _state;
		cond.broadcast();
	}

144
	void SetState(State _state, std::exception_ptr &&e) noexcept {
145 146
		assert(GetEventLoop().IsInside());

147
		const std::lock_guard<Mutex> protect(mutex);
148
		state = _state;
149
		last_exception = std::move(e);
150 151 152
		cond.broadcast();
	}

153
	void Connect() noexcept {
154 155 156 157 158 159 160 161 162 163
		assert(state != State::READY);
		assert(GetEventLoop().IsInside());

		connection = &nfs_get_connection(server.c_str(),
						 export_name.c_str());
		connection->AddLease(*this);

		SetState(State::CONNECTING);
	}

164
	void EnsureConnected() noexcept {
165 166 167 168
		if (state != State::READY)
			Connect();
	}

169
	void WaitConnected() {
170
		const std::lock_guard<Mutex> protect(mutex);
171 172 173 174 175 176

		while (true) {
			switch (state) {
			case State::INITIAL:
				/* schedule connect */
				mutex.unlock();
177
				defer_connect.Schedule();
178
				mutex.lock();
179 180
				if (state == State::INITIAL)
					cond.wait(mutex);
181 182 183 184
				break;

			case State::CONNECTING:
			case State::READY:
185
				return;
186 187

			case State::DELAY:
188 189
				assert(last_exception);
				std::rethrow_exception(last_exception);
190 191 192 193
			}
		}
	}

194
	void Disconnect() noexcept {
195 196 197 198
		assert(GetEventLoop().IsInside());

		switch (state) {
		case State::INITIAL:
199
			defer_connect.Cancel();
200 201 202 203 204 205 206 207 208
			break;

		case State::CONNECTING:
		case State::READY:
			connection->RemoveLease(*this);
			SetState(State::INITIAL);
			break;

		case State::DELAY:
209
			reconnect_timer.Cancel();
210 211 212 213
			SetState(State::INITIAL);
			break;
		}
	}
214 215
};

216
static std::string
217
UriToNfsPath(const char *_uri_utf8)
218
{
219 220
	assert(_uri_utf8 != nullptr);

221
	/* libnfs paths must begin with a slash */
222 223
	std::string uri_utf8("/");
	uri_utf8.append(_uri_utf8);
224

225
	return AllocatedPath::FromUTF8Throw(uri_utf8.c_str()).Steal();
226 227
}

228
std::string
229
NfsStorage::MapUTF8(const char *uri_utf8) const noexcept
230 231 232
{
	assert(uri_utf8 != nullptr);

233
	if (StringIsEmpty(uri_utf8))
234 235 236 237 238 239
		return base;

	return PathTraitsUTF8::Build(base.c_str(), uri_utf8);
}

const char *
240
NfsStorage::MapToRelativeUTF8(const char *uri_utf8) const noexcept
241 242 243 244
{
	return PathTraitsUTF8::Relative(base.c_str(), uri_utf8);
}

245
static void
246
Copy(StorageFileInfo &info, const struct stat &st) noexcept
247 248
{
	if (S_ISREG(st.st_mode))
249
		info.type = StorageFileInfo::Type::REGULAR;
250
	else if (S_ISDIR(st.st_mode))
251
		info.type = StorageFileInfo::Type::DIRECTORY;
252
	else
253
		info.type = StorageFileInfo::Type::OTHER;
254 255

	info.size = st.st_size;
256
	info.mtime = std::chrono::system_clock::from_time_t(st.st_mtime);
257 258
	info.device = st.st_dev;
	info.inode = st.st_ino;
259 260
}

261 262
class NfsGetInfoOperation final : public BlockingNfsOperation {
	const char *const path;
263
	StorageFileInfo info;
264 265

public:
266 267 268 269 270 271
	NfsGetInfoOperation(NfsConnection &_connection, const char *_path)
		:BlockingNfsOperation(_connection), path(_path) {}

	const StorageFileInfo &GetInfo() const {
		return info;
	}
272 273

protected:
274 275
	void Start() override {
		connection.Stat(path, *this);
276 277
	}

278
	void HandleResult(gcc_unused unsigned status, void *data) noexcept override {
279 280 281
		Copy(info, *(const struct stat *)data);
	}
};
282

283 284
StorageFileInfo
NfsStorage::GetInfo(const char *uri_utf8, gcc_unused bool follow)
285
{
286
	const std::string path = UriToNfsPath(uri_utf8);
287

288
	WaitConnected();
289

290
	NfsGetInfoOperation operation(*connection, path.c_str());
291
	operation.Run();
292
	return operation.GetInfo();
293 294 295 296
}

gcc_pure
static bool
297
SkipNameFS(const char *name) noexcept
298 299 300 301 302 303
{
	return name[0] == '.' &&
		(name[1] == 0 ||
		 (name[1] == '.' && name[2] == 0));
}

304
static void
305
Copy(StorageFileInfo &info, const struct nfsdirent &ent)
306
{
307
	switch (ent.type) {
308
	case NF3REG:
309
		info.type = StorageFileInfo::Type::REGULAR;
310 311 312
		break;

	case NF3DIR:
313
		info.type = StorageFileInfo::Type::DIRECTORY;
314 315 316
		break;

	default:
317
		info.type = StorageFileInfo::Type::OTHER;
318 319 320
		break;
	}

321
	info.size = ent.size;
322
	info.mtime = std::chrono::system_clock::from_time_t(ent.mtime.tv_sec);
323
	info.device = 0;
324 325 326
	info.inode = ent.inode;
}

327 328
class NfsListDirectoryOperation final : public BlockingNfsOperation {
	const char *const path;
329

330 331 332 333 334 335 336
	MemoryStorageDirectoryReader::List entries;

public:
	NfsListDirectoryOperation(NfsConnection &_connection,
				  const char *_path)
		:BlockingNfsOperation(_connection), path(_path) {}

337 338
	std::unique_ptr<StorageDirectoryReader> ToReader() {
		return std::make_unique<MemoryStorageDirectoryReader>(std::move(entries));
339 340
	}

341
protected:
342 343
	void Start() override {
		connection.OpenDirectory(path, *this);
344 345
	}

346 347
	void HandleResult(gcc_unused unsigned status,
			  void *data) noexcept override {
348 349 350 351 352 353 354 355 356 357 358 359 360 361
		struct nfsdir *const dir = (struct nfsdir *)data;

		CollectEntries(dir);
		connection.CloseDirectory(dir);
	}

private:
	void CollectEntries(struct nfsdir *dir);
};

inline void
NfsListDirectoryOperation::CollectEntries(struct nfsdir *dir)
{
	assert(entries.empty());
362 363

	const struct nfsdirent *ent;
364
	while ((ent = connection.ReadDirectory(dir)) != nullptr) {
365 366 367 368 369 370 371 372 373 374 375 376 377
		const Path name_fs = Path::FromFS(ent->name);
		if (SkipNameFS(name_fs.c_str()))
			continue;

		std::string name_utf8 = name_fs.ToUTF8();
		if (name_utf8.empty())
			/* ignore files whose name cannot be converted
			   to UTF-8 */
			continue;

		entries.emplace_front(std::move(name_utf8));
		Copy(entries.front().info, *ent);
	}
378
}
379

380
std::unique_ptr<StorageDirectoryReader>
381
NfsStorage::OpenDirectory(const char *uri_utf8)
382
{
383
	const std::string path = UriToNfsPath(uri_utf8);
384

385
	WaitConnected();
386 387

	NfsListDirectoryOperation operation(*connection, path.c_str());
388
	operation.Run();
389 390

	return operation.ToReader();
391 392
}

393
static std::unique_ptr<Storage>
394
CreateNfsStorageURI(EventLoop &event_loop, const char *base)
395
{
396
	if (strncmp(base, "nfs://", 6) != 0)
397 398 399 400 401
		return nullptr;

	const char *p = base + 6;

	const char *mount = strchr(p, '/');
402 403
	if (mount == nullptr)
		throw std::runtime_error("Malformed nfs:// URI");
404 405 406

	const std::string server(p, mount);

407 408
	nfs_set_base(server.c_str(), mount);

409 410
	return std::make_unique<NfsStorage>(event_loop, base,
					    server.c_str(), mount);
411 412 413 414 415 416
}

const StoragePlugin nfs_storage_plugin = {
	"nfs",
	CreateNfsStorageURI,
};