NfsStorage.cxx 9.34 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 36 37
#include "thread/Cond.hxx"
#include "event/Loop.hxx"
#include "event/Call.hxx"
#include "event/DeferredMonitor.hxx"
#include "event/TimeoutMonitor.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 52 53 54 55 56 57
class NfsStorage final
	: public Storage, NfsLease, DeferredMonitor, TimeoutMonitor {

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

58 59
	const std::string base;

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

	NfsConnection *connection;

	Mutex mutex;
	Cond cond;
	State state;
67
	std::exception_ptr last_exception;
68 69

public:
70 71 72 73 74 75 76 77 78
	NfsStorage(EventLoop &_loop, const char *_base,
		   std::string &&_server, std::string &&_export_name)
		:DeferredMonitor(_loop), TimeoutMonitor(_loop),
		 base(_base),
		 server(std::move(_server)),
		 export_name(std::move(_export_name)),
		 state(State::INITIAL) {
		nfs_init();
	}
79

80 81 82
	~NfsStorage() {
		BlockingCall(GetEventLoop(), [this](){ Disconnect(); });
		nfs_finish();
83 84 85
	}

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

88
	StorageDirectoryReader *OpenDirectory(const char *uri_utf8) override;
89

90
	std::string MapUTF8(const char *uri_utf8) const noexcept override;
91

92
	const char *MapToRelativeUTF8(const char *uri_utf8) const noexcept override;
93 94 95 96 97 98 99 100

	/* virtual methods from NfsLease */
	void OnNfsConnectionReady() final {
		assert(state == State::CONNECTING);

		SetState(State::READY);
	}

101
	void OnNfsConnectionFailed(std::exception_ptr e) final {
102 103
		assert(state == State::CONNECTING);

104
		SetState(State::DELAY, std::move(e));
105
		TimeoutMonitor::Schedule(std::chrono::minutes(1));
106 107
	}

108
	void OnNfsConnectionDisconnected(std::exception_ptr e) final {
109 110
		assert(state == State::READY);

111
		SetState(State::DELAY, std::move(e));
112
		TimeoutMonitor::Schedule(std::chrono::seconds(5));
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	}

	/* virtual methods from DeferredMonitor */
	void RunDeferred() final {
		if (state == State::INITIAL)
			Connect();
	}

	/* virtual methods from TimeoutMonitor */
	void OnTimeout() final {
		assert(state == State::DELAY);

		Connect();
	}

private:
	EventLoop &GetEventLoop() {
		return DeferredMonitor::GetEventLoop();
	}

	void SetState(State _state) {
		assert(GetEventLoop().IsInside());

136
		const std::lock_guard<Mutex> protect(mutex);
137 138 139 140
		state = _state;
		cond.broadcast();
	}

141
	void SetState(State _state, std::exception_ptr &&e) {
142 143
		assert(GetEventLoop().IsInside());

144
		const std::lock_guard<Mutex> protect(mutex);
145
		state = _state;
146
		last_exception = std::move(e);
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
		cond.broadcast();
	}

	void Connect() {
		assert(state != State::READY);
		assert(GetEventLoop().IsInside());

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

		SetState(State::CONNECTING);
	}

	void EnsureConnected() {
		if (state != State::READY)
			Connect();
	}

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

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

			case State::CONNECTING:
			case State::READY:
182
				return;
183 184

			case State::DELAY:
185 186
				assert(last_exception);
				std::rethrow_exception(last_exception);
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
			}
		}
	}

	void Disconnect() {
		assert(GetEventLoop().IsInside());

		switch (state) {
		case State::INITIAL:
			DeferredMonitor::Cancel();
			break;

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

		case State::DELAY:
			TimeoutMonitor::Cancel();
			SetState(State::INITIAL);
			break;
		}
	}
211 212
};

213
static std::string
214
UriToNfsPath(const char *_uri_utf8)
215
{
216 217
	assert(_uri_utf8 != nullptr);

218
	/* libnfs paths must begin with a slash */
219 220
	std::string uri_utf8("/");
	uri_utf8.append(_uri_utf8);
221

222 223 224 225
#ifdef _WIN32
	/* assume UTF-8 when accessing NFS from Windows */
	return uri_utf8;
#else
226
	return AllocatedPath::FromUTF8Throw(uri_utf8.c_str()).Steal();
227
#endif
228 229
}

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

235
	if (StringIsEmpty(uri_utf8))
236 237 238 239 240 241
		return base;

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

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

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

	info.size = st.st_size;
	info.mtime = st.st_mtime;
	info.device = st.st_dev;
	info.inode = st.st_ino;
261 262
}

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

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

	const StorageFileInfo &GetInfo() const {
		return info;
	}
274 275

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

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

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

290
	WaitConnected();
291

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

gcc_pure
static bool
299
SkipNameFS(PathTraitsFS::const_pointer_type name) noexcept
300 301 302 303 304 305
{
	return name[0] == '.' &&
		(name[1] == 0 ||
		 (name[1] == '.' && name[2] == 0));
}

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

	case NF3DIR:
315
		info.type = StorageFileInfo::Type::DIRECTORY;
316 317 318
		break;

	default:
319
		info.type = StorageFileInfo::Type::OTHER;
320 321 322
		break;
	}

323 324
	info.size = ent.size;
	info.mtime = ent.mtime.tv_sec;
325
	info.device = 0;
326 327 328
	info.inode = ent.inode;
}

329 330
class NfsListDirectoryOperation final : public BlockingNfsOperation {
	const char *const path;
331

332 333 334 335 336 337 338 339 340
	MemoryStorageDirectoryReader::List entries;

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

	StorageDirectoryReader *ToReader() {
		return new MemoryStorageDirectoryReader(std::move(entries));
341 342
	}

343
protected:
344 345
	void Start() override {
		connection.OpenDirectory(path, *this);
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
	}

	void HandleResult(gcc_unused unsigned status, void *data) override {
		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());
363 364

	const struct nfsdirent *ent;
365
	while ((ent = connection.ReadDirectory(dir)) != nullptr) {
366 367 368 369 370 371
#ifdef _WIN32
		/* assume UTF-8 when accessing NFS from Windows */
		const auto name_fs = AllocatedPath::FromUTF8Throw(ent->name);
		if (name_fs.IsNull())
			continue;
#else
372
		const Path name_fs = Path::FromFS(ent->name);
373
#endif
374 375 376 377 378 379 380 381 382 383 384 385
		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);
	}
386
}
387

388
StorageDirectoryReader *
389
NfsStorage::OpenDirectory(const char *uri_utf8)
390
{
391
	const std::string path = UriToNfsPath(uri_utf8);
392

393
	WaitConnected();
394 395

	NfsListDirectoryOperation operation(*connection, path.c_str());
396
	operation.Run();
397 398

	return operation.ToReader();
399 400 401
}

static Storage *
402
CreateNfsStorageURI(EventLoop &event_loop, const char *base)
403
{
404
	if (strncmp(base, "nfs://", 6) != 0)
405 406 407 408 409
		return nullptr;

	const char *p = base + 6;

	const char *mount = strchr(p, '/');
410 411
	if (mount == nullptr)
		throw std::runtime_error("Malformed nfs:// URI");
412 413 414

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

415 416
	nfs_set_base(server.c_str(), mount);

417
	return new NfsStorage(event_loop, base, server.c_str(), mount);
418 419 420 421 422 423
}

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