core/smn_filesystem.cpp
author Scott Ehlert <ds@alliedmods.net>
Fri Mar 21 04:26:53 2008 +0000 (2008-03-21)
changeset 1944 17984feecafd
parent 1914 0751a6430f15
child 1947 e73a1e51833b
permissions -rw-r--r--
Merged crash fix (amb1539) from 1.0.1 branch
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2007 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <sys/stat.h>
    33 #include "sm_globals.h"
    34 #include "HandleSys.h"
    35 #include "LibrarySys.h"
    36 #include "sm_stringutil.h"
    37 #include "Logger.h"
    38 #include "PluginSys.h"
    39 #include "sourcemm_api.h"
    40 #include "ForwardSys.h"
    41 
    42 SH_DECL_HOOK1_void(IVEngineServer, LogPrint, SH_NOATTRIB, false, const char *);
    43 
    44 HandleType_t g_FileType;
    45 HandleType_t g_DirType;
    46 IChangeableForward *g_pLogHook = NULL;
    47 
    48 class FileNatives : 
    49 	public SMGlobalClass,
    50 	public IHandleTypeDispatch,
    51 	public IPluginsListener
    52 {
    53 public:
    54 	FileNatives()
    55 	{
    56 		m_bIsLoggingHooked = false;
    57 	}
    58 	virtual void OnSourceModAllInitialized()
    59 	{
    60 		g_FileType = g_HandleSys.CreateType("File", this, 0, NULL, NULL, g_pCoreIdent, NULL);
    61 		g_DirType = g_HandleSys.CreateType("Directory", this, 0, NULL, NULL, g_pCoreIdent, NULL);
    62 		g_pLogHook = g_Forwards.CreateForwardEx(NULL, ET_Hook, 1, NULL, Param_String);
    63 		g_PluginSys.AddPluginsListener(this);
    64 	}
    65 	virtual void OnSourceModShutdown()
    66 	{
    67 		g_PluginSys.RemovePluginsListener(this);
    68 		if (m_bIsLoggingHooked)
    69 		{
    70 			SH_REMOVE_HOOK_MEMFUNC(IVEngineServer, LogPrint, engine, this, &FileNatives::LogPrint, false);
    71 			m_bIsLoggingHooked = false;
    72 		}
    73 		g_Forwards.ReleaseForward(g_pLogHook);
    74 		g_HandleSys.RemoveType(g_DirType, g_pCoreIdent);
    75 		g_HandleSys.RemoveType(g_FileType, g_pCoreIdent);
    76 		g_DirType = 0;
    77 		g_FileType = 0;
    78 	}
    79 	virtual void OnHandleDestroy(HandleType_t type, void *object)
    80 	{
    81 		if (type == g_FileType)
    82 		{
    83 			FILE *fp = (FILE *)object;
    84 			fclose(fp);
    85 		}
    86 		else if (type == g_DirType)
    87 		{
    88 			IDirectory *pDir = (IDirectory *)object;
    89 			g_LibSys.CloseDirectory(pDir);
    90 		}
    91 	}
    92 	virtual void OnPluginDestroyed(IPlugin *plugin)
    93 	{
    94 		if (m_bIsLoggingHooked && g_pLogHook->GetFunctionCount() == 0)
    95 		{
    96 			SH_REMOVE_HOOK_MEMFUNC(IVEngineServer, LogPrint, engine, this, &FileNatives::LogPrint, false);
    97 			m_bIsLoggingHooked = false;
    98 		}
    99 	}
   100 	virtual void AddLogHook(IPluginFunction *pFunc)
   101 	{
   102 		if (!m_bIsLoggingHooked)
   103 		{
   104 			SH_ADD_HOOK_MEMFUNC(IVEngineServer, LogPrint, engine, this, &FileNatives::LogPrint, false);
   105 			m_bIsLoggingHooked = true;
   106 		}
   107 
   108 		g_pLogHook->AddFunction(pFunc);
   109 	}
   110 	virtual void RemoveLogHook(IPluginFunction *pFunc)
   111 	{
   112 		g_pLogHook->RemoveFunction(pFunc);
   113 
   114 		if (m_bIsLoggingHooked && g_pLogHook->GetFunctionCount() == 0)
   115 		{
   116 			SH_REMOVE_HOOK_MEMFUNC(IVEngineServer, LogPrint, engine, this, &FileNatives::LogPrint, false);
   117 			m_bIsLoggingHooked = false;
   118 		}
   119 	}
   120 	virtual void LogPrint(const char *msg)
   121 	{
   122 		cell_t result;
   123 
   124 		result = 0;
   125 
   126 		g_in_game_log_hook = true;
   127 		g_pLogHook->PushString(msg);
   128 		g_pLogHook->Execute(&result);
   129 		g_in_game_log_hook = false;
   130 
   131 		if (result >= Pl_Handled)
   132 		{
   133 			RETURN_META(MRES_SUPERCEDE);
   134 		}
   135 	}
   136 private:
   137 	bool m_bIsLoggingHooked;
   138 } s_FileNatives;
   139 
   140 static cell_t sm_OpenDirectory(IPluginContext *pContext, const cell_t *params)
   141 {
   142 	char *path;
   143 	int err;
   144 	if ((err=pContext->LocalToString(params[1], &path)) != SP_ERROR_NONE)
   145 	{
   146 		pContext->ThrowNativeErrorEx(err, NULL);
   147 		return 0;
   148 	}
   149 
   150 	char realpath[PLATFORM_MAX_PATH];
   151 	g_SourceMod.BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path);
   152 
   153 	IDirectory *pDir = g_LibSys.OpenDirectory(realpath);
   154 	if (!pDir)
   155 	{
   156 		return 0;
   157 	}
   158 
   159 	return g_HandleSys.CreateHandle(g_DirType, pDir, pContext->GetIdentity(), g_pCoreIdent, NULL);
   160 }
   161 
   162 static cell_t sm_ReadDirEntry(IPluginContext *pContext, const cell_t *params)
   163 {
   164 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   165 	IDirectory *pDir;
   166 	HandleError herr;
   167 	HandleSecurity sec;
   168 	int err;
   169 
   170 	sec.pOwner = NULL;
   171 	sec.pIdentity = g_pCoreIdent;
   172 
   173 	if ((herr=g_HandleSys.ReadHandle(hndl, g_DirType, &sec, (void **)&pDir))
   174 		!= HandleError_None)
   175 	{
   176 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   177 	}
   178 
   179 	if (!pDir->MoreFiles())
   180 	{
   181 		return false;
   182 	}
   183 
   184 	cell_t *filetype;
   185 	if ((err=pContext->LocalToPhysAddr(params[4], &filetype)) != SP_ERROR_NONE)
   186 	{
   187 		pContext->ThrowNativeErrorEx(err, NULL);
   188 		return 0;
   189 	}
   190 
   191 	if (pDir->IsEntryDirectory())
   192 	{
   193 		*filetype = 1;
   194 	} else if (pDir->IsEntryFile()) {
   195 		*filetype = 2;
   196 	} else {
   197 		*filetype = 0;
   198 	}
   199 
   200 	const char *path = pDir->GetEntryName();
   201 	if ((err=pContext->StringToLocalUTF8(params[2], params[3], path, NULL))
   202 		!= SP_ERROR_NONE)
   203 	{
   204 		pContext->ThrowNativeErrorEx(err, NULL);
   205 		return 0;
   206 	}
   207 
   208 	pDir->NextEntry();
   209 
   210 	return true;
   211 }
   212 
   213 static cell_t sm_OpenFile(IPluginContext *pContext, const cell_t *params)
   214 {
   215 	char *name, *mode;
   216 	int err;
   217 	if ((err=pContext->LocalToString(params[1], &name)) != SP_ERROR_NONE)
   218 	{
   219 		pContext->ThrowNativeErrorEx(err, NULL);
   220 		return 0;
   221 	}
   222 	if ((err=pContext->LocalToString(params[2], &mode)) != SP_ERROR_NONE)
   223 	{
   224 		pContext->ThrowNativeErrorEx(err, NULL);
   225 		return 0;
   226 	}
   227 
   228 	char realpath[PLATFORM_MAX_PATH];
   229 	g_SourceMod.BuildPath(Path_Game, realpath, sizeof(realpath), "%s", name);
   230 
   231 	FILE *pFile = fopen(realpath, mode);
   232 	if (!pFile)
   233 	{
   234 		return 0;
   235 	}
   236 
   237 	return g_HandleSys.CreateHandle(g_FileType, pFile, pContext->GetIdentity(), g_pCoreIdent, NULL);
   238 }
   239 
   240 static cell_t sm_DeleteFile(IPluginContext *pContext, const cell_t *params)
   241 {
   242 	char *name;
   243 	int err;
   244 	if ((err=pContext->LocalToString(params[1], &name)) != SP_ERROR_NONE)
   245 	{
   246 		pContext->ThrowNativeErrorEx(err, NULL);
   247 		return 0;
   248 	}
   249 
   250 	char realpath[PLATFORM_MAX_PATH];
   251 	g_SourceMod.BuildPath(Path_Game, realpath, sizeof(realpath), "%s", name);
   252 
   253 	return (unlink(realpath)) ? 0 : 1;
   254 }
   255 
   256 static cell_t sm_ReadFileLine(IPluginContext *pContext, const cell_t *params)
   257 {
   258 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   259 	HandleError herr;
   260 	HandleSecurity sec;
   261 	FILE *pFile;
   262 	int err;
   263 
   264 	sec.pOwner = NULL;
   265 	sec.pIdentity = g_pCoreIdent;
   266 
   267 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   268 		!= HandleError_None)
   269 	{
   270 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   271 	}
   272 
   273 	char *buf;
   274 	if ((err=pContext->LocalToString(params[2], &buf)) != SP_ERROR_NONE)
   275 	{
   276 		pContext->ThrowNativeErrorEx(err, NULL);
   277 		return 0;
   278 	}
   279 
   280 	if (fgets(buf, params[3], pFile) == NULL)
   281 	{
   282 		return 0;
   283 	}
   284 
   285 	return 1;
   286 }
   287 
   288 static cell_t sm_IsEndOfFile(IPluginContext *pContext, const cell_t *params)
   289 {
   290 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   291 	HandleError herr;
   292 	HandleSecurity sec;
   293 	FILE *pFile;
   294 
   295 	sec.pOwner = NULL;
   296 	sec.pIdentity = g_pCoreIdent;
   297 
   298 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   299 		!= HandleError_None)
   300 	{
   301 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   302 	}
   303 
   304 	return (feof(pFile)) ? 1 : 0;
   305 }
   306 
   307 static cell_t sm_FileSeek(IPluginContext *pContext, const cell_t *params)
   308 {
   309 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   310 	HandleError herr;
   311 	HandleSecurity sec;
   312 	FILE *pFile;
   313 
   314 	sec.pOwner = NULL;
   315 	sec.pIdentity = g_pCoreIdent;
   316 
   317 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   318 		!= HandleError_None)
   319 	{
   320 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   321 	}
   322 
   323 	fseek(pFile, params[2], params[3]);
   324 	
   325 	return 1;
   326 }
   327 
   328 static cell_t sm_FilePosition(IPluginContext *pContext, const cell_t *params)
   329 {
   330 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   331 	HandleError herr;
   332 	HandleSecurity sec;
   333 	FILE *pFile;
   334 
   335 	sec.pOwner = NULL;
   336 	sec.pIdentity = g_pCoreIdent;
   337 
   338 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   339 		!= HandleError_None)
   340 	{
   341 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   342 	}
   343 
   344 	return ftell(pFile);
   345 }
   346 
   347 static cell_t sm_FileExists(IPluginContext *pContext, const cell_t *params)
   348 {
   349 	char *name;
   350 	int err;
   351 	if ((err=pContext->LocalToString(params[1], &name)) != SP_ERROR_NONE)
   352 	{
   353 		pContext->ThrowNativeErrorEx(err, NULL);
   354 		return 0;
   355 	}
   356 
   357 	if (params[0] >= 2 && params[2] == 1)
   358 	{
   359 		return basefilesystem->FileExists(name) ? 1 : 0;
   360 	}
   361 
   362 	char realpath[PLATFORM_MAX_PATH];
   363 	g_SourceMod.BuildPath(Path_Game, realpath, sizeof(realpath), "%s", name);
   364 #ifdef PLATFORM_WINDOWS
   365 	struct _stat s;
   366 	if (_stat(realpath, &s) != 0)
   367 	{
   368 		return 0;
   369 	}
   370 	if (s.st_mode & S_IFREG)
   371 	{
   372 		return 1;
   373 	}
   374 	return 0;
   375 #elif defined PLATFORM_POSIX
   376 	struct stat s;
   377 	if (stat(realpath, &s) != 0)
   378 	{
   379 		return 0;
   380 	}
   381 	if (S_ISREG(s.st_mode))
   382 	{
   383 		return 1;
   384 	}
   385 	return 0;
   386 #endif
   387 }
   388 
   389 static cell_t sm_RenameFile(IPluginContext *pContext, const cell_t *params)
   390 {
   391 	char *newpath, *oldpath;
   392 	int err;
   393 	if ((err=pContext->LocalToString(params[1], &newpath)) != SP_ERROR_NONE)
   394 	{
   395 		pContext->ThrowNativeErrorEx(err, NULL);
   396 		return 0;
   397 	}
   398 	if ((err=pContext->LocalToString(params[2], &oldpath)) != SP_ERROR_NONE)
   399 	{
   400 		pContext->ThrowNativeErrorEx(err, NULL);
   401 		return 0;
   402 	}
   403 
   404 	char new_realpath[PLATFORM_MAX_PATH];
   405 	g_SourceMod.BuildPath(Path_Game, new_realpath, sizeof(new_realpath), "%s", newpath);
   406 	char old_realpath[PLATFORM_MAX_PATH];
   407 	g_SourceMod.BuildPath(Path_Game, old_realpath, sizeof(old_realpath), "%s", oldpath);
   408 
   409 #ifdef PLATFORM_WINDOWS
   410 	return (MoveFileA(old_realpath, new_realpath)) ? 1 : 0;
   411 #elif defined PLATFORM_POSIX
   412 	return (rename(old_realpath, new_realpath)) ? 0 : 1;
   413 #endif
   414 }
   415 
   416 static cell_t sm_DirExists(IPluginContext *pContext, const cell_t *params)
   417 {
   418 	char *name;
   419 	int err;
   420 	if ((err=pContext->LocalToString(params[1], &name)) != SP_ERROR_NONE)
   421 	{
   422 		pContext->ThrowNativeErrorEx(err, NULL);
   423 		return 0;
   424 	}
   425 
   426 	char realpath[PLATFORM_MAX_PATH];
   427 	g_SourceMod.BuildPath(Path_Game, realpath, sizeof(realpath), "%s", name);
   428 #ifdef PLATFORM_WINDOWS
   429 	struct _stat s;
   430 	if (_stat(realpath, &s) != 0)
   431 	{
   432 		return 0;
   433 	}
   434 	if (s.st_mode & S_IFDIR)
   435 	{
   436 		return 1;
   437 	}
   438 	return 0;
   439 #elif defined PLATFORM_POSIX
   440 	struct stat s;
   441 	if (stat(realpath, &s) != 0)
   442 	{
   443 		return 0;
   444 	}
   445 	if (S_ISDIR(s.st_mode))
   446 	{
   447 		return 1;
   448 	}
   449 	return 0;
   450 #endif
   451 }
   452 
   453 static cell_t sm_FileSize(IPluginContext *pContext, const cell_t *params)
   454 {
   455 	char *name;
   456 	int err;
   457 	if ((err=pContext->LocalToString(params[1], &name)) != SP_ERROR_NONE)
   458 	{
   459 		pContext->ThrowNativeErrorEx(err, NULL);
   460 		return -1;
   461 	}
   462 
   463 	char realpath[PLATFORM_MAX_PATH];
   464 	g_SourceMod.BuildPath(Path_Game, realpath, sizeof(realpath), "%s", name);
   465 #ifdef PLATFORM_WINDOWS
   466 	struct _stat s;
   467 	if (_stat(realpath, &s) != 0)
   468 	{
   469 		return -1;
   470 	}
   471 	if (s.st_mode & S_IFREG)
   472 	{
   473 		return static_cast<cell_t>(s.st_size);
   474 	}
   475 	return -1;
   476 #elif defined PLATFORM_POSIX
   477 	struct stat s;
   478 	if (stat(realpath, &s) != 0)
   479 	{
   480 		return -1;
   481 	}
   482 	if (S_ISREG(s.st_mode))
   483 	{
   484 		return static_cast<cell_t>(s.st_size);
   485 	}
   486 	return -1;
   487 #endif
   488 }
   489 
   490 static cell_t sm_RemoveDir(IPluginContext *pContext, const cell_t *params)
   491 {
   492 	char *name;
   493 	int err;
   494 	if ((err=pContext->LocalToString(params[1], &name)) != SP_ERROR_NONE)
   495 	{
   496 		pContext->ThrowNativeErrorEx(err, NULL);
   497 		return 0;
   498 	}
   499 
   500 	char realpath[PLATFORM_MAX_PATH];
   501 	g_SourceMod.BuildPath(Path_Game, realpath, sizeof(realpath), "%s", name);
   502 
   503 	return (rmdir(realpath)) ? 0 : 1;
   504 }
   505 
   506 static cell_t sm_WriteFileLine(IPluginContext *pContext, const cell_t *params)
   507 {
   508 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   509 	HandleError herr;
   510 	HandleSecurity sec;
   511 	FILE *pFile;
   512 
   513 	sec.pOwner = NULL;
   514 	sec.pIdentity = g_pCoreIdent;
   515 
   516 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   517 		!= HandleError_None)
   518 	{
   519 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   520 	}
   521 
   522 	char *fmt;
   523 	int err;
   524 	if ((err=pContext->LocalToString(params[2], &fmt)) != SP_ERROR_NONE)
   525 	{
   526 		pContext->ThrowNativeErrorEx(err, NULL);
   527 		return 0;
   528 	}
   529 
   530 	char buffer[2048];
   531 	int arg = 3;
   532 	atcprintf(buffer, sizeof(buffer), fmt, pContext, params, &arg);
   533 	fprintf(pFile, "%s\n", buffer);
   534 
   535 	return 1;
   536 }
   537 
   538 static cell_t sm_FlushFile(IPluginContext *pContext, const cell_t *params)
   539 {
   540 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   541 	HandleError herr;
   542 	HandleSecurity sec;
   543 	FILE *pFile;
   544 
   545 	sec.pOwner = NULL;
   546 	sec.pIdentity = g_pCoreIdent;
   547 
   548 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   549 		!= HandleError_None)
   550 	{
   551 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   552 	}
   553 
   554 	return (fflush(pFile) == 0) ? 1 : 0;
   555 }
   556 
   557 static cell_t sm_BuildPath(IPluginContext *pContext, const cell_t *params)
   558 {
   559 	char path[PLATFORM_MAX_PATH], *fmt, *buffer;
   560 	int arg = 5;
   561 	pContext->LocalToString(params[2], &buffer);
   562 	pContext->LocalToString(params[4], &fmt);
   563 
   564 	atcprintf(path, sizeof(path), fmt, pContext, params, &arg);
   565 
   566 	return g_SourceMod.BuildPath(Path_SM_Rel, buffer, params[3], "%s", path);
   567 }
   568 
   569 static cell_t sm_LogToGame(IPluginContext *pContext, const cell_t *params)
   570 {
   571 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   572 
   573 	char buffer[1024];
   574 	size_t len = g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
   575 
   576 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   577 	{
   578 		return 0;
   579 	}
   580 
   581 	if (len >= sizeof(buffer)-2)
   582 	{
   583 		buffer[1022] = '\n';
   584 		buffer[1023] = '\0';
   585 	} else {
   586 		buffer[len++] = '\n';
   587 		buffer[len] = '\0';
   588 	}
   589 
   590 	Engine_LogPrintWrapper(buffer);
   591 
   592 	return 1;
   593 }
   594 
   595 static cell_t sm_LogMessage(IPluginContext *pContext, const cell_t *params)
   596 {
   597 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   598 
   599 	char buffer[1024];
   600 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
   601 
   602 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   603 	{
   604 		return 0;
   605 	}
   606 
   607 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   608 	g_Logger.LogMessage("[%s] %s", pPlugin->GetFilename(), buffer);
   609 
   610 	return 1;
   611 }
   612 
   613 static cell_t sm_LogError(IPluginContext *pContext, const cell_t *params)
   614 {
   615 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   616 
   617 	char buffer[1024];
   618 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
   619 
   620 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   621 	{
   622 		return 0;
   623 	}
   624 
   625 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   626 	g_Logger.LogError("[%s] %s", pPlugin->GetFilename(), buffer);
   627 
   628 	return 1;
   629 }
   630 
   631 static cell_t sm_GetFileTime(IPluginContext *pContext, const cell_t *params)
   632 {
   633 	char *name;
   634 	int err;
   635 	if ((err=pContext->LocalToString(params[1], &name)) != SP_ERROR_NONE)
   636 	{
   637 		pContext->ThrowNativeErrorEx(err, NULL);
   638 		return 0;
   639 	}
   640 
   641 	time_t time_val;
   642 	char realpath[PLATFORM_MAX_PATH];
   643 	g_SourceMod.BuildPath(Path_Game, realpath, sizeof(realpath), "%s", name);
   644 
   645 	if (!g_LibSys.FileTime(realpath, (FileTimeType)params[2], &time_val))
   646 	{
   647 		return -1;
   648 	}
   649 
   650 	return (cell_t)time_val;
   651 }
   652 
   653 static cell_t sm_LogToOpenFile(IPluginContext *pContext, const cell_t *params)
   654 {
   655 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   656 	HandleError herr;
   657 	HandleSecurity sec;
   658 	FILE *pFile;
   659 
   660 	sec.pOwner = NULL;
   661 	sec.pIdentity = g_pCoreIdent;
   662 
   663 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   664 		!= HandleError_None)
   665 	{
   666 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   667 	}
   668 
   669 	char buffer[2048];
   670 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   671 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
   672 
   673 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   674 	{
   675 		return 0;
   676 	}
   677 
   678 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   679 	g_Logger.LogToOpenFile(pFile, "[%s] %s", pPlugin->GetFilename(), buffer);
   680 
   681 	return 1;
   682 }
   683 
   684 static cell_t sm_LogToOpenFileEx(IPluginContext *pContext, const cell_t *params)
   685 {
   686 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   687 	HandleError herr;
   688 	HandleSecurity sec;
   689 	FILE *pFile;
   690 
   691 	sec.pOwner = NULL;
   692 	sec.pIdentity = g_pCoreIdent;
   693 
   694 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   695 		!= HandleError_None)
   696 	{
   697 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   698 	}
   699 
   700 	char buffer[2048];
   701 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   702 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
   703 
   704 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   705 	{
   706 		return 0;
   707 	}
   708 
   709 	g_Logger.LogToOpenFile(pFile, "%s", buffer);
   710 
   711 	return 1;
   712 }
   713 
   714 static cell_t sm_ReadFile(IPluginContext *pContext, const cell_t *params)
   715 {
   716 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   717 	HandleError herr;
   718 	HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
   719 	FILE *pFile;
   720 	size_t read = 0;
   721 
   722 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   723 		!= HandleError_None)
   724 	{
   725 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   726 	}
   727 
   728 	if (params[4] != 1 && params[4] != 2 && params[4] != 4)
   729 	{
   730 		return pContext->ThrowNativeError("Invalid size specifier (%d is not 1, 2, or 4)", params[4]);
   731 	}
   732 
   733 	cell_t *data;
   734 	pContext->LocalToPhysAddr(params[2], &data);
   735 
   736 	if (params[4] == 4)
   737 	{
   738 		read = fread(data, sizeof(cell_t), params[3], pFile);
   739 	}
   740 	else if (params[4] == 2)
   741 	{
   742 		int16_t val;
   743 		for (cell_t i = 0; i < params[3]; i++)
   744 		{
   745 			if (fread(&val, sizeof(int16_t), 1, pFile) != 1)
   746 			{
   747 				break;
   748 			}
   749 			data[read++] = val;
   750 		}
   751 	}
   752 	else if (params[4] == 1)
   753 	{
   754 		int8_t val;
   755 		for (cell_t i = 0; i < params[3]; i++)
   756 		{
   757 			if (fread(&val, sizeof(int8_t), 1, pFile) != 1)
   758 			{
   759 				break;
   760 			}
   761 			data[read++] = val;
   762 		}
   763 	}
   764 
   765 	if (read != (size_t)params[3] && ferror(pFile) != 0)
   766 	{
   767 		return -1;
   768 	}
   769 
   770 	return read;
   771 }
   772 
   773 static cell_t sm_ReadFileString(IPluginContext *pContext, const cell_t *params)
   774 {
   775 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   776 	HandleError herr;
   777 	HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
   778 	FILE *pFile;
   779 	cell_t num_read = 0;
   780 
   781 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   782 		!= HandleError_None)
   783 	{
   784 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   785 	}
   786 
   787 	char *buffer;
   788 	pContext->LocalToString(params[2], &buffer);
   789 
   790 	char val;
   791 	while (1)
   792 	{
   793 		/* If we're in stop mode, break as soon as the buffer is full. */
   794 		if (params[4] && (params[3] == 0 || num_read >= params[3] - 1))
   795 		{
   796 			break;
   797 		}
   798 		if (fread(&val, sizeof(val), 1, pFile) != 1)
   799 		{
   800 			if (ferror(pFile))
   801 			{
   802 				return -1;
   803 			}
   804 			break;
   805 		}
   806 		if (val == '\0')
   807 		{
   808 			break;
   809 		}
   810 		if (params[3] > 0 && num_read < params[3] - 1)
   811 		{
   812 			buffer[num_read++] = val;
   813 		}
   814 	}
   815 
   816 	if (params[3] > 0)
   817 	{
   818 		buffer[num_read] = '\0';
   819 	}
   820 
   821 	return num_read;
   822 }
   823 
   824 static cell_t sm_WriteFile(IPluginContext *pContext, const cell_t *params)
   825 {
   826 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   827 	HandleError herr;
   828 	HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
   829 	FILE *pFile;
   830 
   831 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   832 		!= HandleError_None)
   833 	{
   834 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   835 	}
   836 
   837 	cell_t *data;
   838 	pContext->LocalToPhysAddr(params[2], &data);
   839 
   840 	if (params[4] != 1 && params[4] != 2 && params[4] != 4)
   841 	{
   842 		return pContext->ThrowNativeError("Invalid size specifier (%d is not 1, 2, or 4)", params[4]);
   843 	}
   844 
   845 	/* :NOTE: This really isn't compatible with big endian but we will never have to worry about that. */
   846 
   847 	if (params[4] == 4)
   848 	{
   849 		if (fwrite(data, sizeof(cell_t), params[3], pFile) != (size_t)params[3])
   850 		{
   851 			return 0;
   852 		}
   853 	}
   854 	else if (params[4] == 2)
   855 	{
   856 		for (cell_t i = 0; i < params[3]; i++)
   857 		{
   858 			if (fwrite(&data[i], sizeof(int16_t), 1, pFile) != 1)
   859 			{
   860 				return 0;
   861 			}
   862 		}
   863 	}
   864 	else if (params[4] == 1)
   865 	{
   866 		for (cell_t i = 0; i < params[3]; i++)
   867 		{
   868 			if (fwrite(&data[i], sizeof(int8_t), 1, pFile) != 1)
   869 			{
   870 				return 0;
   871 			}
   872 		}
   873 	}
   874 
   875 	return 1;
   876 }
   877 
   878 static cell_t sm_WriteFileString(IPluginContext *pContext, const cell_t *params)
   879 {
   880 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   881 	HandleError herr;
   882 	HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
   883 	FILE *pFile;
   884 
   885 	if ((herr=g_HandleSys.ReadHandle(hndl, g_FileType, &sec, (void **)&pFile))
   886 		!= HandleError_None)
   887 	{
   888 		return pContext->ThrowNativeError("Invalid file handle %x (error %d)", hndl, herr);
   889 	}
   890 
   891 	char *buffer;
   892 	pContext->LocalToString(params[2], &buffer);
   893 
   894 	size_t len = strlen(buffer);
   895 
   896 	if (params[3])
   897 	{
   898 		len++;
   899 	}
   900 
   901 	return (fwrite(buffer, sizeof(char), len, pFile) == len) ? 1 : 0;
   902 }
   903 
   904 static cell_t sm_AddGameLogHook(IPluginContext *pContext, const cell_t *params)
   905 {
   906 	IPluginFunction *pFunction;
   907 
   908 	if ((pFunction=pContext->GetFunctionById(params[1])) == NULL)
   909 	{
   910 		return pContext->ThrowNativeError("Function id %x is invalid", params[1]);
   911 	}
   912 
   913 	s_FileNatives.AddLogHook(pFunction);
   914 	
   915 	return 1;
   916 }
   917 
   918 static cell_t sm_RemoveGameLogHook(IPluginContext *pContext, const cell_t *params)
   919 {
   920 	IPluginFunction *pFunction;
   921 
   922 	if ((pFunction=pContext->GetFunctionById(params[1])) == NULL)
   923 	{
   924 		return pContext->ThrowNativeError("Function id %x is invalid", params[1]);
   925 	}
   926 
   927 	s_FileNatives.RemoveLogHook(pFunction);
   928 
   929 	return 1;
   930 }
   931 
   932 REGISTER_NATIVES(filesystem)
   933 {
   934 	{"OpenDirectory",			sm_OpenDirectory},
   935 	{"ReadDirEntry",			sm_ReadDirEntry},
   936 	{"OpenFile",				sm_OpenFile},
   937 	{"DeleteFile",				sm_DeleteFile},
   938 	{"ReadFileLine",			sm_ReadFileLine},
   939 	{"IsEndOfFile",				sm_IsEndOfFile},
   940 	{"FileSeek",				sm_FileSeek},
   941 	{"FilePosition",			sm_FilePosition},
   942 	{"FileExists",				sm_FileExists},
   943 	{"RenameFile",				sm_RenameFile},
   944 	{"DirExists",				sm_DirExists},
   945 	{"FileSize",				sm_FileSize},
   946 	{"RemoveDir",				sm_RemoveDir},
   947 	{"WriteFileLine",			sm_WriteFileLine},
   948 	{"BuildPath",				sm_BuildPath},
   949 	{"LogToGame",				sm_LogToGame},
   950 	{"LogMessage",				sm_LogMessage},
   951 	{"LogError",				sm_LogError},
   952 	{"FlushFile",				sm_FlushFile},
   953 	{"GetFileTime",				sm_GetFileTime},
   954 	{"LogToOpenFile",			sm_LogToOpenFile},
   955 	{"LogToOpenFileEx",			sm_LogToOpenFileEx},
   956 	{"ReadFile",				sm_ReadFile},
   957 	{"ReadFileString",			sm_ReadFileString},
   958 	{"WriteFile",				sm_WriteFile},
   959 	{"WriteFileString",			sm_WriteFileString},
   960 	{"AddGameLogHook",			sm_AddGameLogHook},
   961 	{"RemoveGameLogHook",		sm_RemoveGameLogHook},
   962 	{NULL,						NULL},
   963 };