Source

love-mount / src / modules / filesystem / physfs / Filesystem.cpp

Full commit
  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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
/**
* Copyright (c) 2006-2011 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
*    claim that you wrote the original software. If you use this software
*    in a product, an acknowledgment in the product documentation would be
*    appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
*    misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/

#include <common/config.h>

#include <iostream>

#include <common/utf8.h>
#include <common/b64.h>

#include "Filesystem.h"

#include "globbing.h"

namespace love
{
namespace filesystem
{
namespace physfs
{

	Filesystem::Filesystem()
		: open_count(0), buffer(0), isInited(false), release(false), releaseSet(false), mountsRestricted(false)
	{
	}

	Filesystem::~Filesystem()
	{
		if(isInited)
		{
			isInited = false;
			PHYSFS_deinit();
		}
	}

	const char * Filesystem::getName() const
	{
		return "love.filesystem.physfs";
	}

	void Filesystem::init(const char * arg0)
	{
		if(!PHYSFS_init(arg0))
			throw Exception(PHYSFS_getLastError());
		isInited = true;
	}

	void Filesystem::setRelease(bool release)
	{
		if (releaseSet)
			return;
		this->release = release;
		releaseSet = true;
	}

	bool Filesystem::setIdentity( const char * ident )
	{
		if(!isInited)
			return false;

		// Store the save directory.
		save_identity = std::string(ident);

		// Generate the relative path to the game save folder.
		save_path_relative = std::string(LOVE_APPDATA_PREFIX LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR) + save_identity;

		// Generate the full path to the game save folder.
		save_path_full = std::string(getAppdataDirectory()) + std::string(LOVE_PATH_SEPARATOR);
		if (release)
			save_path_full += std::string(LOVE_APPDATA_PREFIX) + save_identity;
		else
			save_path_full += save_path_relative;

		// We now have something like:
		// save_identity: game
		// save_path_relative: ./LOVE/game
		// save_path_full: C:\Documents and Settings\user\Application Data/LOVE/game

		// Try to add the save directory to the search path.
		// (No error on fail, it means that the path doesn't exist).
		PHYSFS_addToSearchPath(save_path_full.c_str(), 0);

		return true;
	}

	bool Filesystem::setSource(const char * source)
	{
		if(!isInited)
			return false;

		// Check whether directory is already set.
		if(!game_source.empty())
			return false;

		// Add the directory.
		if(!PHYSFS_addToSearchPath(source, 1))
			return false;

		// Save the game source.
		game_source = std::string(source);

		return true;
	}

	bool Filesystem::setupWriteDirectory()
	{
		if(!isInited)
			return false;

		// These must all be set.
		if(save_identity.empty() || save_path_full.empty() || save_path_relative.empty())
			return false;

		// Set the appdata folder as writable directory.
		// (We must create the save folder before mounting it).
		if(!PHYSFS_setWriteDir(getAppdataDirectory()))
			return false;

		// Create the save folder. (We're now "at" %APPDATA%).
		bool success = false;
		if (release)
			success = mkdir(save_identity.c_str());
		else
			success = mkdir(save_path_relative.c_str());

		if(!success)
		{
			PHYSFS_setWriteDir(0); // Clear the write directory in case of error.
			return false;
		}

		// Set the final write directory.
		if(!PHYSFS_setWriteDir(save_path_full.c_str()))
			return false;

		// Add the directory. (Will not be readded if already present).
		if(!PHYSFS_addToSearchPath(save_path_full.c_str(), 0))
		{
			PHYSFS_setWriteDir(0); // Clear the write directory in case of error.
			return false;
		}

		return true;
	}

	File * Filesystem::newFile(const char *filename)
	{
		return new File(filename);
	}

	FileData * Filesystem::newFileData(void * data, int size, const char * filename)
	{
		FileData * fd = new FileData(size, std::string(filename));

		// Copy the data into FileData.
		memcpy(fd->getData(), data, size);

		return fd;
	}

	FileData * Filesystem::newFileData(const char * b64, const char * filename)
	{
		int size = strlen(b64);
		int outsize = 0;
		char * dst = b64_decode(b64, size, outsize);
		FileData * fd = new FileData(outsize, std::string(filename));

		// Copy the data into FileData.
		memcpy(fd->getData(), dst, outsize);
		delete [] dst;

		return fd;
	}

	const char * Filesystem::getWorkingDirectory()
	{
		if(cwd.empty())
		{
#ifdef LOVE_WINDOWS

			WCHAR w_cwd[LOVE_MAX_PATH];
			_wgetcwd(w_cwd, LOVE_MAX_PATH);
			cwd = to_utf8(w_cwd);
			replace_char(cwd, '\\', '/');
#else
			char * cwd_char = new char[LOVE_MAX_PATH];

			if(getcwd(cwd_char, LOVE_MAX_PATH))
				cwd = cwd_char; // if getcwd fails, cwd_char (and thus cwd) will still be empty

			delete [] cwd_char;
#endif
		}

		return cwd.c_str();
	}

	const char * Filesystem::getUserDirectory()
	{
		return PHYSFS_getUserDir();
	}

	const char * Filesystem::getAppdataDirectory()
	{
#ifdef LOVE_WINDOWS
		if(appdata.empty())
		{
			wchar_t * w_appdata = _wgetenv(TEXT("APPDATA"));
			appdata = to_utf8(w_appdata);
			replace_char(appdata, '\\', '/');
		}
		return appdata.c_str();
#elif defined(LOVE_MACOSX)
		if(appdata.empty())
		{
			std::string udir = getUserDirectory();
			udir.append("/Library/Application Support");
			appdata = udir;
		}
		return appdata.c_str();
#elif defined(LOVE_LINUX)
		if(appdata.empty())
		{
			char * xdgdatahome = getenv("XDG_DATA_HOME");
			if (!xdgdatahome)
				appdata = std::string(getUserDirectory()) + "/.local/share/";
			else
				appdata = xdgdatahome;
		}
		return appdata.c_str();
#else
		return getUserDirectory();
#endif
	}


	const char * Filesystem::getSaveDirectory()
	{
		return save_path_full.c_str();
	}

	bool Filesystem::exists(const char * file)
	{
		if(PHYSFS_exists(file))
			return true;
		return false;
	}

	bool Filesystem::isDirectory(const char * file)
	{
		if(PHYSFS_isDirectory(file))
			return true;
		return false;
	}

	bool Filesystem::isFile(const char * file)
	{
		return exists(file) && !isDirectory(file);
	}

	bool Filesystem::mkdir(const char * file)
	{
		if(PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
			return false;

		if(!PHYSFS_mkdir(file))
			return false;
		return true;
	}

	bool Filesystem::remove(const char * file)
	{
		if(PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
			return false;

		if(!PHYSFS_delete(file))
			return false;
		return true;
	}

	int Filesystem::read(lua_State * L)
	{
		// The file to read from. The file must either be created
		// on-the-fly, or passed as a parameter.
		File * file;

        if(lua_isstring(L, 1))
		{
			// Create the file.
			file = newFile(lua_tostring(L, 1));
		}
		else
			return luaL_error(L, "Expected filename.");

		// Optionally, the caller can specify whether to read
		// the whole file, or just a part of it.
		int count = luaL_optint(L, 2, file->getSize());

		// Read the data.
		Data * data = file->read(count);

		// Error check.
		if(data == 0)
			return luaL_error(L, "File could not be read.");

		// Close and delete the file, if we created it.
		// (I.e. if the first parameter is a string).
		if(lua_isstring(L, 1))
			file->release();

		// Push the string.
		lua_pushlstring(L, (char*)data->getData(), data->getSize());

		// Push the size.
		lua_pushinteger(L, data->getSize());

		// Lua has a copy now, so we can free it.
		data->release();

		return 2;
	}

	int Filesystem::write(lua_State * L)
	{
		// The file to write to. The file must either be created
		// on-the-fly, or passed as a parameter.
		File * file;

		// We know for sure that we need a second parameter, so
		// let's check that first.
		if(lua_isnoneornil(L, 2))
			return luaL_error(L, "Second argument needed.");

		if(lua_isstring(L, 1))
		{
			// Create the file.
			file = newFile(lua_tostring(L, 1));
		}
		else
			return luaL_error(L, "Expected filename.");

		// Get the current mode of the file.
		File::Mode mode = file->getMode();

		if(mode == File::CLOSED)
		{
			// It should be possible to use append mode, but
			// normal File::Mode::Write is the default.
			int mode = luaL_optint(L, 4, File::WRITE);

			// Open the file.
			if(!file->open((File::Mode)mode))
				return luaL_error(L, "Could not open file.");
		}

		size_t length = 0;
		const char * input;
		if(lua_isstring(L, 2)) {
			input = lua_tolstring(L, 2, &length);
		} else if (luax_istype(L, 2, DATA_T)) {
			love::Data * data = luax_totype<love::Data>(L, 2, "Data", DATA_T);
			length = data->getSize();
			input = (char *)data->getData();
		} else {
			return luaL_error(L, "Expected string or data for argument #2.");
		}

		// Get how much we should write. Length of string default.
		length = luaL_optint(L, 3, length);

		// Write the data.
		bool success = file->write(input, length);

		// Close and delete the file, if we created
		// it in this function.
		if(lua_isstring(L, 1))
		{
			// Kill the file if "we" created it.
			file->close();
			file->release();
		}

		if(!success)
			return luaL_error(L, "Data could not be written.");

		lua_pushboolean(L, success);
		return 1;
	}

	int Filesystem::enumerate(lua_State * L)
	{
		int n = lua_gettop(L);

		if( n != 1 )
			return luaL_error(L, "Function requires a single parameter.");

		int type = lua_type(L, 1);

		if(type != LUA_TSTRING)
			return luaL_error(L, "Function requires parameter of type string.");

		const char * dir = lua_tostring(L, 1);
		char **rc = PHYSFS_enumerateFiles(dir);
		char **i;
		int index = 1;

		lua_newtable(L);

		for (i = rc; *i != 0; i++)
		{
			lua_pushinteger(L, index);
			lua_pushstring(L, *i);
			lua_settable(L, -3);
			index++;
		}

		PHYSFS_freeList(rc);

		return 1;
	}

	int Filesystem::find(lua_State * L)
	{
		const char* dir = luaL_checkstring(L, 1);
		const char* wildcard = luaL_checkstring(L, 2);
		int caseSensitive = 0;

		if (lua_gettop(L) == 3)
		{
			// why luaL doesn't have luaL_optboolean()?!
			if (lua_type(L, 3) != LUA_TBOOLEAN)
				return luaL_error(L, "bad argument #3 to 'enumerate', expected boolean");

			caseSensitive = lua_toboolean(L, 3);
		}

		char **rc;
		char **i;
		int index = 1;

		rc = PHYSFSEXT_enumerateFilesWildcard(dir, wildcard, caseSensitive);

		lua_newtable(L);

		for (i = rc; *i != 0; i++)
		{
			lua_pushinteger(L, index);
			lua_pushstring(L, *i);
			lua_settable(L, -3);
			index++;
		}

		PHYSFS_freeList(rc);

		return 1;
	}

	int Filesystem::lines(lua_State * L)
	{
		File * file;

		if(lua_isstring(L, 1))
		{
			file = newFile(lua_tostring(L, 1));
			if(!file->open(File::READ))
				return luaL_error(L, "Could not open file %s.\n", lua_tostring(L, 1));
			lua_pop(L, 1);

			luax_newtype(L, "File", FILESYSTEM_FILE_T, file, false);
			lua_pushnumber(L, 1); // 1 = autoclose.
		}
		else
			return luaL_error(L, "Expected filename.");

		// Reset the file position.
		if(!file->seek(0))
			return luaL_error(L, "File does not appear to be open.\n");

		lua_pushcclosure(L, lines_i, 2);
		return 1;
	}

	int Filesystem::lines_i(lua_State * L)
	{
		// We're using a 1k buffer.
		const static int bufsize = 8;
		static char buf[bufsize];

		File * file = luax_checktype<File>(L, lua_upvalueindex(1), "File", FILESYSTEM_FILE_T);
		int close = (int)lua_tointeger(L, lua_upvalueindex(2));

		// Find the next newline.
		// pos must be at the start of the line we're trying to find.
		int pos = file->tell();
		int newline = -1;
		int totalread = 0;

		while(!file->eof())
		{
			int current = file->tell();
			int read = file->read(buf, bufsize);
			totalread += read;

			if(read < 0)
				return luaL_error(L, "Readline failed!");

			for(int i = 0;i<read;i++)
			{
				if(buf[i] == '\n')
				{
					newline = current+i;
					break;
				}
			}

			if(newline > 0)
				break;
		}

		// Special case for the last "line".
		if(newline <= 0 && file->eof() && totalread > 0)
			newline = pos + totalread;

		// We've got a newline.
		if(newline > 0)
		{
			// Ok, we've got a line.
			int linesize = (newline-pos);

			// Allocate memory for the string.
			char * str = new char[linesize];

			// Read it.
			file->seek(pos);
			if(file->read(str, linesize) == -1)
				return luaL_error(L, "Read error.");

			if(str[linesize-1]=='\r')
				linesize -= 1;

			lua_pushlstring(L, str, linesize);

			// Free the memory. Lua has a copy now.
			delete[] str;

			// Set the beginning of the next line.
			if(!file->eof())
				file->seek(newline+1);
	
			return 1;
		}

		if(close)
		{
			file->close();
			file->release();
		}

		return 0;
	}

	int Filesystem::load(lua_State * L)
	{
		// Need only one arg.
		luax_assert_argc(L, 1, 1);

		// Must be string.
		if(!lua_isstring(L, -1))
			return luaL_error(L, "The argument must be a string.");

		std::string filename = lua_tostring(L, -1);

		// The file must exist.
		if(!exists(filename.c_str()))
			return luaL_error(L, "File %s does not exist.", filename.c_str());

		// Create the file.
		File * file = newFile(filename.c_str());

		// Get the data from the file.
		Data * data = file->read();

		int status = luaL_loadbuffer(L, (const char *)data->getData(), data->getSize(), ("@" + filename).c_str());

		data->release();
		file->release();

		// Load the chunk, but don't run it.
		switch (status)
		{
		case LUA_ERRMEM:
			return luaL_error(L, "Memory allocation error: %s\n", lua_tostring(L, -1));
		case LUA_ERRSYNTAX:
			return luaL_error(L, "Syntax error: %s\n", lua_tostring(L, -1));
		default: // success
			return 1;
		}
	}

	int Filesystem::getLastModified(lua_State * L)
	{
		const char * filename = luaL_checkstring(L, 1);
		PHYSFS_sint64 time = PHYSFS_getLastModTime(filename);
		if (time == -1)
		{
			lua_pushnil(L);
			lua_pushstring(L, "Could not determine file modification date.");
			return 2;
		}
		lua_pushnumber(L, static_cast<lua_Number>(time));
		return 1;
	}

	std::string Filesystem::dirname(const char* path)
	{
		std::string temp;
		int pos;
		// empty filename is the root dir (/)
		if (path[0] == 0 || path == "/")
			return std::string();

		temp = path;
		pos = temp.rfind("/");

		// a file in root directory?
		if (pos == std::string::npos)
			return std::string();

		// cut the directory part and return it
		return temp.substr(0, pos);
	}

	std::string Filesystem::basename(const char* path)
	{
		std::string temp;
		int pos;
		// empty filename is the root dir (/)
		if (path[0] == 0 || path == "/")
			return std::string();

		temp = path;
		pos = temp.rfind("/");

		// a file in root directory?
		if (pos == std::string::npos)
			return std::string(path);

		// cut the directory part and return it
		return temp.substr(pos+1);
	}

	bool Filesystem::isInRestrictedArchivePath(const std::string& path) {
		std::string dir = dirname(path.c_str());
		while (1)
		{
			if (restrictedArchivePaths.find(dir) != restrictedArchivePaths.end())
			{
				// path is correct, accept this archive
				return true;
			}

			if (dir == "")
			{
				// we went all the way to the root dir and the path wasn't
				// accepted by restrictedArchivePaths, archive pointed by
				// path is not allowed to be mounted!
				return false;
			}
			else
			{
				// remove last path component and continue the validation
				dir = dirname(dir.c_str());
			}
		}
	}



	bool Filesystem::mount(const char * path, const char * mpoint)
	{
		std::string rpath, archive;
		archive = path;

		// a single archive can only be mounted once at a time
		if (mountedArchives.find(archive) != mountedArchives.end())
			throw Exception("Archive '%s' already mounted.", path);

		// check if the path exists in the virtual filesystem
		if (!exists(path))
			throw Exception("Archive '%s' not found.", path);

		// check if the path points to a file
		if (!isFile(path))
			throw Exception("Path '%s' doesn't point to a file.", path);

		// to prevent hacks, the path can not contain '..' chars
		if (archive.find("..") != std::string::npos)
			throw Exception("Two dots (..) are illegal in a path to archive");

		// remove leading slash if present
		if (archive.size() && archive[0] == '/')
			archive = archive.substr(1);

		// check if the path is inside a restricted archive dir
		if (mountsRestricted && !isInRestrictedArchivePath(archive))
			throw Exception("Archive '%s' is not in restricted archive path", archive.c_str());

		// Add the directory.
		rpath = std::string(PHYSFS_getRealDir(archive.c_str())) + PHYSFS_getDirSeparator() + archive;
		if (!PHYSFS_mount(rpath.c_str(), mpoint, 0))
			throw Exception("Failed to mount '%s': %s", rpath.c_str(), PHYSFS_getLastError());

		if (mountsRestricted)
		{
			// mark this archive as mounted
			mountedArchives.insert(archive);
		}

		return true;
	}

	bool Filesystem::umount(const char * path)
	{
		std::string archive = path;

		// remove leading slash if present
		if (archive.size() && archive[0] == '/')
			archive = archive.substr(1);

		// check if path is mounted
		if (mountedArchives.find(archive) == mountedArchives.end())
			throw Exception("Archive '%s' not mounted", archive.c_str());

		std::string rpath = std::string(PHYSFS_getRealDir(archive.c_str())) + PHYSFS_getDirSeparator() + archive;
		// attempt to umount given archive
		if (!PHYSFS_removeFromSearchPath(rpath.c_str()))
			throw Exception("Failed to umount '%s': %s", rpath.c_str(), PHYSFS_getLastError());

		// remove archive from mount list
		mountedArchives.erase(archive);

		return true;
	}

	int Filesystem::restrictArchivePaths(lua_State * L) {
		int type;
		std::string path;

		if (mountsRestricted)
			return luaL_error(L, "can't change archive paths at runtime");

		mountsRestricted = true;

		type = lua_type(L, 1);
		if (type == LUA_TNIL)
			return 0;
		else if (type != LUA_TTABLE)
			return luaL_error(L, "invalid argument");

		lua_pushnil(L);  /* first key */
		while (lua_next(L, 1) != 0) {
			/* uses 'key' (at index -2) and 'value' (at index -1) */
			path = lua_tostring(L, -1);

			// fix the path
			if (path[path.size()-1] == '/')
			{
				// remove trailing slash
				path = path.substr(0, path.size() - 1);
			}
			else if (path.size() && path[0] == '/')
			{
				// remove leading slash
				path = path.substr(1);
			}

			// add path
			restrictedArchivePaths.insert(path);

			/* removes 'value'; keeps 'key' for next iteration */
			lua_pop(L, 1);
		}

		return 0;
	}


} // physfs
} // filesystem
} // love