NfsStorage.cxx 9.37 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2015 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/Domain.hxx"
28
#include "lib/nfs/Base.hxx"
29 30 31
#include "lib/nfs/Lease.hxx"
#include "lib/nfs/Connection.hxx"
#include "lib/nfs/Glue.hxx"
32
#include "fs/AllocatedPath.hxx"
33
#include "thread/Mutex.hxx"
34 35 36 37 38
#include "thread/Cond.hxx"
#include "event/Loop.hxx"
#include "event/Call.hxx"
#include "event/DeferredMonitor.hxx"
#include "event/TimeoutMonitor.hxx"
39 40
#include "util/Error.hxx"
#include "util/StringCompare.hxx"
41 42 43 44 45 46

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

47 48 49
#include <string>

#include <assert.h>
50 51 52
#include <sys/stat.h>
#include <fcntl.h>

53 54 55 56 57 58 59
class NfsStorage final
	: public Storage, NfsLease, DeferredMonitor, TimeoutMonitor {

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

60 61
	const std::string base;

62 63 64 65 66 67 68 69
	const std::string server, export_name;

	NfsConnection *connection;

	Mutex mutex;
	Cond cond;
	State state;
	Error last_error;
70 71

public:
72 73 74 75 76 77 78 79 80
	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();
	}
81

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

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

91 92
	StorageDirectoryReader *OpenDirectory(const char *uri_utf8,
					      Error &error) override;
93

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

96
	const char *MapToRelativeUTF8(const char *uri_utf8) const override;
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

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

		SetState(State::READY);
	}

	void OnNfsConnectionFailed(gcc_unused const Error &error) final {
		assert(state == State::CONNECTING);

		SetState(State::DELAY, error);
		TimeoutMonitor::ScheduleSeconds(60);
	}

	void OnNfsConnectionDisconnected(gcc_unused const Error &error) final {
		assert(state == State::READY);

		SetState(State::DELAY, error);
		TimeoutMonitor::ScheduleSeconds(5);
	}

	/* 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());

		const ScopeLock protect(mutex);
		state = _state;
		cond.broadcast();
	}

	void SetState(State _state, const Error &error) {
		assert(GetEventLoop().IsInside());

		const ScopeLock protect(mutex);
		state = _state;
150
		last_error.Clear();
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
		last_error.Set(error);
		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();
	}

	bool WaitConnected(Error &error) {
		const ScopeLock protect(mutex);

		while (true) {
			switch (state) {
			case State::INITIAL:
				/* schedule connect */
				mutex.unlock();
				DeferredMonitor::Schedule();
				mutex.lock();
181 182
				if (state == State::INITIAL)
					cond.wait(mutex);
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
				break;

			case State::CONNECTING:
			case State::READY:
				return true;

			case State::DELAY:
				assert(last_error.IsDefined());
				error.Set(last_error);
				return false;
			}
		}
	}

	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;
		}
	}
217 218
};

219
static std::string
220
UriToNfsPath(const char *_uri_utf8, Error &error)
221
{
222 223
	assert(_uri_utf8 != nullptr);

224
	/* libnfs paths must begin with a slash */
225 226
	std::string uri_utf8("/");
	uri_utf8.append(_uri_utf8);
227

228
	return AllocatedPath::FromUTF8(uri_utf8.c_str(), error).Steal();
229 230
}

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

236
	if (StringIsEmpty(uri_utf8))
237 238 239 240 241 242 243 244 245 246 247
		return base;

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

const char *
NfsStorage::MapToRelativeUTF8(const char *uri_utf8) const
{
	return PathTraitsUTF8::Relative(base.c_str(), uri_utf8);
}

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

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

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

public:
	NfsGetInfoOperation(NfsConnection &_connection, const char *_path,
270
			    StorageFileInfo &_info)
271 272 273 274 275
		:BlockingNfsOperation(_connection), path(_path), info(_info) {}

protected:
	bool Start(Error &_error) override {
		return connection.Stat(path, *this, _error);
276 277
	}

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

bool
NfsStorage::GetInfo(const char *uri_utf8, gcc_unused bool follow,
285
		    StorageFileInfo &info, Error &error)
286
{
287 288 289
	const std::string path = UriToNfsPath(uri_utf8, error);
	if (path.empty())
		return false;
290

291
	if (!WaitConnected(error))
292
		return false;
293 294 295

	NfsGetInfoOperation operation(*connection, path.c_str(), info);
	return operation.Run(error);
296 297 298 299 300 301 302 303 304 305 306
}

gcc_pure
static bool
SkipNameFS(const char *name)
{
	return name[0] == '.' &&
		(name[1] == 0 ||
		 (name[1] == '.' && name[2] == 0));
}

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

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

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

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

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

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

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

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

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

	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());
364 365

	const struct nfsdirent *ent;
366
	while ((ent = connection.ReadDirectory(dir)) != nullptr) {
367 368 369 370 371 372 373 374 375 376 377 378 379
		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);
	}
380
}
381

382 383 384 385 386 387
StorageDirectoryReader *
NfsStorage::OpenDirectory(const char *uri_utf8, Error &error)
{
	const std::string path = UriToNfsPath(uri_utf8, error);
	if (path.empty())
		return nullptr;
388

389 390 391 392 393 394 395 396
	if (!WaitConnected(error))
		return nullptr;

	NfsListDirectoryOperation operation(*connection, path.c_str());
	if (!operation.Run(error))
		return nullptr;

	return operation.ToReader();
397 398 399
}

static Storage *
400
CreateNfsStorageURI(EventLoop &event_loop, const char *base,
401
		    Error &error)
402 403 404 405 406 407 408 409 410 411 412 413 414 415
{
	if (memcmp(base, "nfs://", 6) != 0)
		return nullptr;

	const char *p = base + 6;

	const char *mount = strchr(p, '/');
	if (mount == nullptr) {
		error.Set(nfs_domain, "Malformed nfs:// URI");
		return nullptr;
	}

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

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

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

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