core/GameDataFetcher.cpp
author David Anderson <dvander@alliedmods.net>
Wed Feb 25 20:25:20 2009 -0500 (2009-02-25)
changeset 2613 46c76edb0875
parent 2484 2c3479db5956
child 2488 f7f1bbcc85e4
permissions -rw-r--r--
Removed tag sourcemod-1.1.1
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 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 "GameDataFetcher.h"
    33 #include "bitbuf.h"
    34 
    35 #ifdef PLATFORM_WINDOWS
    36 #include <winsock2.h>
    37 #else
    38 #include <unistd.h>
    39 #include <sys/types.h>
    40 #include <sys/socket.h>
    41 #include <netinet/in.h>
    42 #include <netdb.h>
    43 #include <arpa/inet.h>
    44 
    45 #define INVALID_SOCKET		-1
    46 #define closesocket 		close
    47 #define WSAGetLastError()	errno
    48 #endif
    49 
    50 #include "sh_vector.h"
    51 #include "sh_string.h"
    52 #include "sm_version.h"
    53 
    54 #ifdef ORANGEBOX_BUILD
    55 #include "convar_sm_ob.h"
    56 #else
    57 #include "convar_sm.h"
    58 #endif
    59 
    60 #include "sourcemm_api.h"
    61 #include "time.h"
    62 #include "TimerSys.h"
    63 #include "compat_wrappers.h"
    64 #include "sm_stringutil.h"
    65 #include "md5.h"
    66 #include "frame_hooks.h"
    67 
    68 #define QUERY_MAX_LENGTH 1024
    69 
    70 static BuildMD5ableBuffer g_MD5Builder;
    71 static FetcherThread g_FetchThread;
    72 
    73 static FILE *logfile = NULL;
    74 
    75 bool g_disableGameDataUpdate = false;
    76 
    77 /**
    78  * Note on this.  If we issue a reload and changelevel, my srcds.exe will emit 
    79  *   Assertion Failed: !m_bServiceStarted
    80  * on quit.  This seems like a non-issue, because before we just terminated the 
    81  * server anyway.  If anyone notices and files a bug, we can look into it further.
    82  */
    83 bool g_restartAfterUpdate = false;
    84 
    85 static bool was_level_started = false;
    86 static int g_serverPort = 6500;
    87 static char g_serverAddress[100] = "smupdate.alliedmods.net";
    88 
    89 static void _ForceRestart(void *data)
    90 {
    91 	char cmd[300];
    92 	g_Logger.LogMessage("Automatically restarting SourceMod after a successful gamedata update.");
    93 	UTIL_Format(cmd, sizeof(cmd), "meta unload %d\n", g_PLID);
    94 	engine->ServerCommand(cmd);
    95 	UTIL_Format(cmd, sizeof(cmd), "changelevel \"%s\"\n", STRING(gpGlobals->mapname));
    96 	engine->ServerCommand(cmd);
    97 	UTIL_Format(cmd, sizeof(cmd), "echo SourceMod restarted after gamedata update.\n");
    98 	engine->ServerCommand(cmd);
    99 }
   100 
   101 static void ForceRestart()
   102 {
   103 	FrameAction action;
   104 
   105 	action.action = _ForceRestart;
   106 	action.data = NULL;
   107 	AddFrameAction(action);
   108 }
   109 
   110 void FetcherThread::RunThread(IThreadHandle *pHandle)
   111 {
   112 	char lock_path[PLATFORM_MAX_PATH];
   113 	g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp");
   114 	g_LibSys.CreateFolder(lock_path);
   115 
   116 	g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
   117 
   118 	char log_path[PLATFORM_MAX_PATH];
   119 	g_SourceMod.BuildPath(Path_SM, log_path, sizeof(log_path), "logs/gamedata");
   120 
   121 	g_LibSys.CreateFolder(log_path);
   122 
   123 	time_t t;
   124 	GetAdjustedTime(&t);
   125 	tm *curtime = localtime(&t);
   126 
   127 	g_SourceMod.BuildPath(Path_SM,
   128 						  log_path,
   129 						  sizeof(log_path),
   130 						  "logs/gamedata/L%04d%02d%02d.log",
   131 						  curtime->tm_year + 1900,
   132 						  curtime->tm_mon + 1,
   133 						  curtime->tm_mday);
   134 
   135 	logfile = fopen(log_path, "at");
   136 
   137 	if (!logfile)
   138 	{
   139 		/* :( */
   140 		return;
   141 	}
   142 
   143 	//Create a blank lock file
   144 	FILE *fp = fopen(lock_path, "w");
   145 	if (fp)
   146 	{
   147 		fclose(fp);
   148 	}
   149 
   150 	char query[QUERY_MAX_LENGTH];
   151 
   152 	/* Check for updated gamedata files */
   153 	int len = BuildGameDataQuery(query, QUERY_MAX_LENGTH);
   154 
   155 	if (len == 0)
   156 	{
   157 		g_Logger.LogToFileOnly(logfile, "Could not build gamedata query!");
   158 		fclose(logfile);
   159 		unlink(lock_path);
   160 		return;
   161 	}
   162 
   163 	/* We check this late so we have the MD5 sums available.  This may change in the future. */
   164 	if (g_disableGameDataUpdate)
   165 	{
   166 		g_Logger.LogToFileOnly(logfile, "Skipping gamedata fetcher (DisableAutoUpdate set)");
   167 		fclose(logfile);
   168 		unlink(lock_path);
   169 		return;
   170 	}
   171 
   172 	/* Create a new socket for this connection */
   173 	int socketDescriptor = ConnectSocket();
   174 
   175 	if (socketDescriptor == INVALID_SOCKET)
   176 	{
   177 		fclose(logfile);
   178 		unlink(lock_path);
   179 		return;
   180 	}
   181 
   182 	int sent = SendData(socketDescriptor, query, len);
   183 
   184 IF_DEBUG_SPEW
   185 	g_Logger.LogToFileOnly(logfile, "Sent gamedata query");
   186 ENDIF_DEBUG_SPEW
   187 
   188 	if (sent == 0)
   189 	{
   190 IF_DEBUG_SPEW
   191 		g_Logger.LogToFileOnly(logfile, "Failed to send gamedata query data to remote host");
   192 ENDIF_DEBUG_SPEW
   193 
   194 		closesocket(socketDescriptor);
   195 		fclose(logfile);
   196 		unlink(lock_path);
   197 		return;
   198 	}
   199 
   200 	ProcessGameDataQuery(socketDescriptor);
   201 
   202 	/* And we're done! */
   203 	closesocket(socketDescriptor);
   204 	fclose(logfile);
   205 	unlink(lock_path);
   206 }
   207 
   208 void FetcherThread::OnTerminate(IThreadHandle *pHandle, bool cancel)
   209 {
   210 	g_blockGameDataLoad = false;
   211 
   212 	if (cancel)
   213 	{
   214 		return;
   215 	}
   216 
   217 	if (wasSuccess)
   218 	{
   219 		HandleUpdateStatus(updateStatus, build);
   220 
   221 		if (needsRestart)
   222 		{
   223 			if (g_restartAfterUpdate)
   224 			{
   225 				if (was_level_started)
   226 				{
   227 					ForceRestart();
   228 				}
   229 			}
   230 			else
   231 			{
   232 				g_Logger.LogMessage("Your gamedata files have been updated, please restart your server.");
   233 			}
   234 		}
   235 	}
   236 	else if (!g_disableGameDataUpdate)
   237 	{
   238 		g_Logger.LogError("An error occurred in the gamedata fetcher, see your gamedata log files for more information.");
   239 	}
   240 }
   241 
   242 int FetcherThread::BuildGameDataQuery(char *buffer, int maxlen)
   243 {
   244 	char gamedata_path[PLATFORM_MAX_PATH];
   245 	g_SourceMod.BuildPath(Path_SM, gamedata_path, sizeof(gamedata_path), "gamedata");
   246 
   247 	IDirectory *dir = g_LibSys.OpenDirectory(gamedata_path);
   248 
   249 	if (dir == NULL)
   250 	{
   251 		return 0;
   252 	}
   253 
   254 	bf_write Writer = bf_write("GameDataQuery", buffer, maxlen);
   255 
   256 	Writer.WriteByte('A'); //Generic Header char
   257 	Writer.WriteByte('G'); //G for gamedata query, or green, like my hat.
   258 
   259 	short build[4] = { SVN_FILE_VERSION };
   260 
   261 	Writer.WriteBytes(&build[0], 8);
   262 
   263 	Writer.WriteByte(0); // Initialize the file counter - Index 10
   264 
   265 	while (dir->MoreFiles())
   266 	{
   267 		if (dir->IsEntryFile())
   268 		{
   269 			const char *name = dir->GetEntryName();
   270 			size_t len = strlen(name);
   271 			if (len >= 4 && strcmp(&name[len-4], ".txt") == 0)
   272 			{
   273 				MD5 md5;
   274 				SMCError err;
   275 				SMCStates states;
   276 				unsigned char raw[16];
   277 				char file[PLATFORM_MAX_PATH];
   278 
   279 				g_LibSys.PathFormat(file, sizeof(file), "%s/%s", gamedata_path, name);
   280 
   281 				g_MD5Builder.checksum = &md5;
   282 				if ((err = g_TextParser.ParseFile_SMC(file, &g_MD5Builder, &states)) == SMCError_Okay)
   283 				{
   284 					md5.raw_digest(raw);
   285 					(uint8_t)buffer[10]++; //Increment the file counter
   286 					Writer.WriteBytes(raw, 16);
   287 
   288 					FileData *data = new FileData();
   289 					data->filename = new SourceHook::String(file);
   290 					md5.hex_digest(data->checksum);
   291 					filenames.push_back(data);
   292 
   293 IF_DEBUG_SPEW
   294 					g_Logger.LogToFileOnly(logfile, "Parsed file: %s as %s", file, data->checksum);
   295 ENDIF_DEBUG_SPEW
   296 
   297 				}
   298 				else
   299 				{
   300 IF_DEBUG_SPEW
   301 					const char *error = g_TextParser.GetSMCErrorString(err);
   302 					g_Logger.LogToFileOnly(logfile, "Parsing of file %s failed: %s", file, error);
   303 ENDIF_DEBUG_SPEW
   304 				}
   305 			}
   306 		}
   307 		dir->NextEntry();
   308 	}
   309 
   310 	return Writer.GetNumBytesWritten();
   311 }
   312 
   313 int FetcherThread::ConnectSocket()
   314 {
   315 #if defined PLATFORM_WINDOWS
   316 	WSADATA wsaData;
   317 	WSAStartup(0x0101, &wsaData);
   318 #endif
   319 
   320 	struct protoent *ptrp;
   321 	
   322 	if ((ptrp = getprotobyname("tcp")) == NULL) 
   323 	{
   324 		g_Logger.LogToFileOnly(logfile, "Error: Failed to find TCP protocol");
   325 		return INVALID_SOCKET;
   326 	}
   327 
   328 	int socketDescriptor = socket(AF_INET, SOCK_STREAM, ptrp->p_proto);
   329 
   330 	if (socketDescriptor == INVALID_SOCKET)
   331 	{
   332 		char error[255];
   333 		g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
   334 		g_Logger.LogToFileOnly(logfile, "Error: Failed to create socket: %s", error);
   335 		closesocket(socketDescriptor);
   336 		return INVALID_SOCKET;
   337 	}
   338 
   339 	struct hostent *he;
   340 	struct sockaddr_in local_addr;
   341 
   342 	local_addr.sin_family = AF_INET;
   343 	local_addr.sin_port = htons((u_short)g_serverPort);
   344 
   345 	he = gethostbyname(g_serverAddress);
   346 
   347 	if (!he)
   348 	{
   349 		if ((local_addr.sin_addr.s_addr = inet_addr(g_serverAddress)) == INADDR_NONE)
   350 		{
   351 			g_Logger.LogToFileOnly(logfile, "Couldn't locate address: %s", g_serverAddress);
   352 			closesocket(socketDescriptor);
   353 			return INVALID_SOCKET;
   354 		}
   355 	} 
   356 	else 
   357 	{
   358 		memcpy(&local_addr.sin_addr, (struct in_addr *)he->h_addr, he->h_length);
   359 	}
   360 
   361 	if (connect(socketDescriptor, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0)
   362 	{
   363 		char error[255];
   364 		g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
   365 		g_Logger.LogToFileOnly(logfile, "Couldn't connect to %s: %s", g_serverAddress, error);
   366 		closesocket(socketDescriptor);
   367 		return INVALID_SOCKET;
   368 	}
   369 
   370 	return socketDescriptor;
   371 }
   372 
   373 void FetcherThread::ProcessGameDataQuery(int socketDescriptor)
   374 {
   375 	char buffer[50];
   376 
   377 IF_DEBUG_SPEW
   378 	g_Logger.LogToFileOnly(logfile, "Waiting for reply!");
   379 ENDIF_DEBUG_SPEW
   380 
   381 	//Read in the header bytes
   382 	int returnLen = RecvData(socketDescriptor, buffer, 12);
   383 
   384 
   385 	if (returnLen == 0)
   386 	{
   387 		char error[255];
   388 		g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
   389 		g_Logger.LogToFileOnly(logfile, "Did not receive reply: %s", error);
   390 		return;
   391 	}
   392 
   393 IF_DEBUG_SPEW
   394 	g_Logger.LogToFileOnly(logfile, "Received Header!");
   395 ENDIF_DEBUG_SPEW
   396 
   397 	bf_read Reader = bf_read("GameDataQuery", buffer, 12);
   398 
   399 	if (Reader.ReadByte() != 'A' || Reader.ReadByte() != 'G')
   400 	{
   401 IF_DEBUG_SPEW
   402 		g_Logger.LogToFileOnly(logfile, "Unknown Query Response");
   403 ENDIF_DEBUG_SPEW
   404 		return;
   405 	}
   406 
   407 	updateStatus = (UpdateStatus)Reader.ReadByte();
   408 
   409 	build[0] = Reader.ReadShort();
   410 	build[1] = Reader.ReadShort();
   411 	build[2] = Reader.ReadShort();
   412 	build[3] = Reader.ReadShort();
   413 
   414 IF_DEBUG_SPEW
   415 	g_Logger.LogToFileOnly(logfile,
   416 						   "Update Status: %i - Latest %i.%i.%i.%i",
   417 						   updateStatus,
   418 						   build[0],
   419 						   build[1],
   420 						   build[2],
   421 						   build[3]);
   422 ENDIF_DEBUG_SPEW
   423 
   424 	int changedFiles = Reader.ReadByte();
   425 
   426 IF_DEBUG_SPEW
   427 	g_Logger.LogToFileOnly(logfile, "Files to download: %i", changedFiles);
   428 ENDIF_DEBUG_SPEW
   429 
   430 	for (int i=0; i<changedFiles; i++)
   431 	{
   432 		//Read in the file index and byte count
   433 		returnLen = RecvData(socketDescriptor, buffer, 5);
   434 
   435 		if (returnLen == 0)
   436 		{
   437 			/* Timeout or fail? */
   438 			return;
   439 		}
   440 
   441 		Reader.StartReading(buffer, 5);
   442 
   443 		int index = Reader.ReadByte();
   444 		int tempLen = Reader.ReadUBitLong(32);
   445 
   446 IF_DEBUG_SPEW
   447 		g_Logger.LogToFileOnly(logfile, "File index %i and length %i", index, tempLen);
   448 ENDIF_DEBUG_SPEW
   449 
   450 		void *memPtr;
   451 		memtable->CreateMem(tempLen+1, &memPtr);
   452 
   453 		//Read the contents of our file into the memtable
   454 		returnLen = RecvData(socketDescriptor, (char *)memPtr, tempLen);
   455 
   456 IF_DEBUG_SPEW
   457 		g_Logger.LogToFileOnly(logfile, "Received %i bytes", returnLen);
   458 ENDIF_DEBUG_SPEW
   459 
   460 		if (returnLen == 0)
   461 		{
   462 			/* Timeout or fail? */
   463 			return;
   464 		}
   465 
   466 		((unsigned char *)memPtr)[tempLen] = '\0';
   467 
   468 		FileData *data = filenames.at(index);
   469 		const char *filename;
   470 		if (data != NULL)
   471 		{
   472 			filename = data->filename->c_str();
   473 
   474 			FILE *fp = fopen(filename, "w");
   475 
   476 			if (fp)
   477 			{
   478 				fprintf(fp, "%s", (const char *)memPtr);
   479 				fclose(fp);
   480 			}
   481 			else
   482 			{
   483 				g_Logger.LogToFileOnly(logfile, "Failed to open file \"%s\" for writing", filename);
   484 			}
   485 		}
   486 		else
   487 		{
   488 			filename = "";
   489 		}
   490 
   491 		memtable->Reset();
   492 
   493 		g_Logger.LogToFileOnly(logfile, "Updated file: %s", filename);
   494 	}
   495 
   496 IF_DEBUG_SPEW
   497 	g_Logger.LogToFileOnly(logfile, "File Downloads Completed!");
   498 ENDIF_DEBUG_SPEW
   499 
   500 	needsRestart = false;
   501 
   502 	if (changedFiles > 0)
   503 	{
   504 		needsRestart = true;
   505 	}
   506 
   507 	//Read changed file count
   508 	returnLen = RecvData(socketDescriptor, buffer, 1);
   509 
   510 	if (returnLen == 0)
   511 	{
   512 		char error[255];
   513 		g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
   514 		g_Logger.LogToFileOnly(logfile, "Did not receive count reply: %s", error);
   515 		return;
   516 	}
   517 
   518 	Reader.StartReading(buffer, 1);
   519 
   520 	changedFiles = Reader.ReadByte();
   521 
   522 	if (changedFiles < 1)
   523 	{
   524 IF_DEBUG_SPEW
   525 		g_Logger.LogToFileOnly(logfile, "No unknown files. We're all done");
   526 ENDIF_DEBUG_SPEW
   527 		return;
   528 	}
   529 
   530 	char *changedFileIndexes = new char[changedFiles];
   531 
   532 IF_DEBUG_SPEW
   533 	g_Logger.LogToFileOnly(logfile, "%i files were unknown", changedFiles);
   534 ENDIF_DEBUG_SPEW
   535 
   536 	returnLen = RecvData(socketDescriptor, changedFileIndexes, changedFiles);
   537 
   538 	if (returnLen == 0)
   539 	{
   540 		char error[255];
   541 		g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
   542 		g_Logger.LogToFileOnly(logfile, "Did not receive list reply: %s", error);
   543 		return;
   544 	}
   545 
   546 	Reader.StartReading(changedFileIndexes, changedFiles);
   547 
   548 	for (int i=0; i<changedFiles; i++)
   549 	{
   550 		int index = Reader.ReadByte();
   551 		char fileName[30];
   552 
   553 		FileData *data = filenames.at(index);
   554 		const char* pathname;
   555 		if (data != NULL)
   556 		{
   557 			pathname = data->filename->c_str();
   558 		}
   559 		else
   560 		{
   561 			pathname = "";
   562 		}
   563 
   564 		g_LibSys.GetFileFromPath(fileName, sizeof(fileName), pathname);
   565 IF_DEBUG_SPEW
   566 		g_Logger.LogToFileOnly(logfile, "Unknown File %i : %s", index, fileName);
   567 ENDIF_DEBUG_SPEW
   568 	}
   569 
   570 	delete [] changedFileIndexes;
   571 
   572 	wasSuccess = true;
   573 }
   574 
   575 int FetcherThread::RecvData(int socketDescriptor, char *buffer, int len)
   576 {
   577 	fd_set fds;
   578 	struct timeval tv;
   579 
   580 	/* Create a 10 Second Timeout */
   581 	tv.tv_sec = 10;
   582 	tv.tv_usec = 0;
   583 
   584 	int bytesReceivedTotal = 0;
   585 
   586 	while (bytesReceivedTotal < len)
   587 	{
   588 		/* Add our socket to a socket set */
   589 		FD_ZERO(&fds);
   590 		FD_SET(socketDescriptor, &fds);
   591 
   592 		/* Wait max of 10 seconds for recv to become available */
   593 		select(socketDescriptor+1, &fds, NULL, NULL, &tv);
   594 
   595 		int bytesReceived = 0;
   596 
   597 		/* Is there a limit on how much we can receive? Some site said 1024 bytes, which will be well short of a file */
   598 		if (FD_ISSET(socketDescriptor, &fds))
   599 		{
   600 			bytesReceived = recv(socketDescriptor, buffer+bytesReceivedTotal, len-bytesReceivedTotal, 0);
   601 		}
   602 
   603 		if (bytesReceived == 0 || bytesReceived == -1)
   604 		{
   605 			return 0;
   606 		}
   607 
   608 		bytesReceivedTotal += bytesReceived;
   609 	}
   610 
   611 	return bytesReceivedTotal;	
   612 }
   613 
   614 int FetcherThread::SendData(int socketDescriptor, char *buffer, int len)
   615 {
   616 	fd_set fds;
   617 	struct timeval tv;
   618 
   619 	tv.tv_sec = 10;
   620 	tv.tv_usec = 0;
   621 
   622 	int sentBytesTotal = 0;
   623 
   624 	while (sentBytesTotal < len)
   625 	{
   626 		FD_ZERO(&fds);
   627 		FD_SET(socketDescriptor, &fds);
   628 
   629 		select(socketDescriptor+1, NULL, &fds, NULL, &tv);
   630 
   631 		int sentBytes = 0;
   632 
   633 		if (FD_ISSET(socketDescriptor, &fds))
   634 		{
   635 			sentBytes = send(socketDescriptor, buffer+sentBytesTotal, len-sentBytesTotal, 0);
   636 		}
   637 
   638 		if (sentBytes == 0 || sentBytes == -1)
   639 		{
   640 			return 0;
   641 		}		
   642 
   643 		sentBytesTotal += sentBytes;
   644 	}
   645 
   646 	return sentBytesTotal;
   647 }
   648 
   649 void FetcherThread::HandleUpdateStatus(UpdateStatus status, short version[4])
   650 {
   651 	switch (status)
   652 	{
   653 		case Update_Unknown:
   654 		case Update_Current:
   655 		{
   656 			break;
   657 		}
   658 
   659 		case Update_NewBuild:
   660 		{
   661 			break;
   662 		}
   663 
   664 		case Update_MinorAvailable:
   665 		{
   666 			g_Logger.LogMessage("SourceMod Update: A new release of SourceMod is now available from sourcemod.net");
   667 			g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
   668 			break;
   669 		}
   670 
   671 		case Update_MajorAvailable:
   672 		{
   673 			g_Logger.LogMessage("SourceMod Update: An major release of SourceMod is now available from sourcemod.net");
   674 			g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
   675 			break;
   676 		}
   677 
   678 		case Update_CriticalAvailable:
   679 		{
   680 			g_Logger.LogError("SourceMod Update: A critical SourceMod release is available from sourcemod.net. It is strongly recommended that you update!");
   681 			g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
   682 			break;
   683 		}
   684 	}
   685 }
   686 
   687 bool g_blockGameDataLoad = false;
   688 static IThreadHandle *fetch_thread_hndl;
   689 
   690 class InitFetch : public SMGlobalClass
   691 {
   692 public:
   693 	void OnSourceModAllInitialized_Post()
   694 	{
   695 		char lock_path[PLATFORM_MAX_PATH];
   696 		g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
   697 
   698 		if (g_LibSys.IsPathFile(lock_path) && g_LibSys.PathExists(lock_path))
   699 		{
   700 			g_Logger.LogError("sourcemod/data/temp/gamedata.lock file detected. This is most likely due to a crash during GameData updating - Blocking GameData loading");
   701 			g_Logger.LogError("If this error persists delete the file manually");
   702 			g_blockGameDataLoad = true;
   703 		}
   704 
   705 		ThreadParams fetchThreadParams = ThreadParams();
   706 		fetchThreadParams.prio = ThreadPrio_Low;
   707 		fetch_thread_hndl = g_pThreader->MakeThread(&g_FetchThread, &fetchThreadParams);
   708 	}
   709 
   710 	void OnSourceModShutdown()
   711 	{
   712 		fetch_thread_hndl->WaitForThread();
   713 		fetch_thread_hndl->DestroyThis();
   714 	}
   715 
   716 	void OnSourceModLevelActivated()
   717 	{
   718 		was_level_started = true;
   719 
   720 		if (g_restartAfterUpdate && 
   721 			g_FetchThread.wasSuccess && 
   722 			g_FetchThread.needsRestart)
   723 		{
   724 			ForceRestart();
   725 		}
   726 	}
   727 
   728 	void OnSourceModLevelEnd()
   729 	{
   730 		was_level_started = false;
   731 	}
   732 
   733 	ConfigResult OnSourceModConfigChanged(const char *key, 
   734 		const char *value, 
   735 		ConfigSource source,
   736 		char *error, 
   737 		size_t maxlength)
   738 	{
   739 		if (strcasecmp(key, "DisableAutoUpdate") == 0)
   740 		{
   741 			if (strcasecmp(value, "yes") == 0)
   742 			{
   743 				g_disableGameDataUpdate = true;
   744 				return ConfigResult_Accept;
   745 			}
   746 			else if (strcasecmp(value, "no") == 0)
   747 			{
   748 				g_disableGameDataUpdate = false;
   749 				return ConfigResult_Accept;
   750 			}
   751 
   752 			return ConfigResult_Reject;
   753 		}
   754 
   755 		if (strcasecmp(key, "ForceRestartAfterUpdate") == 0)
   756 		{
   757 			if (strcasecmp(value, "yes") == 0)
   758 			{
   759 				g_restartAfterUpdate = true;
   760 				return ConfigResult_Accept;
   761 			}
   762 			else if (strcasecmp(value, "no") == 0)
   763 			{
   764 				g_restartAfterUpdate = false;
   765 				return ConfigResult_Accept;
   766 			}
   767 
   768 			return ConfigResult_Reject;
   769 		}
   770 
   771 		if (strcasecmp(key, "AutoUpdateServer") == 0)
   772 		{
   773 			UTIL_Format(g_serverAddress, sizeof(g_serverAddress), "%s", value);
   774 
   775 			return ConfigResult_Accept;
   776 		}
   777 
   778 		if (strcasecmp(key, "AutoUpdatePort") == 0)
   779 		{
   780 			int port = atoi(value);
   781 
   782 			if (!port)
   783 			{
   784 				return ConfigResult_Reject;
   785 			}
   786 
   787 			g_serverPort = port;
   788 
   789 			return ConfigResult_Accept;
   790 		}
   791 
   792 		return ConfigResult_Ignore;
   793 	}
   794 } g_InitFetch;
   795 
   796 BuildMD5ableBuffer::BuildMD5ableBuffer()
   797 {
   798 	stringTable = new BaseStringTable(2048);
   799 }
   800 
   801 BuildMD5ableBuffer::~BuildMD5ableBuffer()
   802 {
   803 	delete stringTable;
   804 }
   805 
   806 void BuildMD5ableBuffer::ReadSMC_ParseStart()
   807 {
   808 	stringTable->Reset();
   809 }
   810 
   811 SMCResult BuildMD5ableBuffer::ReadSMC_KeyValue(const SMCStates *states,
   812 											   const char *key,
   813 											   const char *value)
   814 {
   815 	stringTable->AddString(key);
   816 	stringTable->AddString(value);
   817 
   818 	return SMCResult_Continue;
   819 }
   820 
   821 SMCResult BuildMD5ableBuffer::ReadSMC_NewSection(const SMCStates *states, const char *name)
   822 {
   823 	stringTable->AddString(name);
   824 
   825 	return SMCResult_Continue;
   826 }
   827 
   828 void BuildMD5ableBuffer::ReadSMC_ParseEnd(bool halted, bool failed)
   829 {
   830 	if (halted || failed)
   831 	{
   832 		return;
   833 	}
   834 
   835 	void *data = stringTable->GetMemTable()->GetAddress(0);
   836 
   837 	if (data != NULL)
   838 	{
   839 		checksum->update((unsigned char *)data, stringTable->GetMemTable()->GetActualMemUsed());
   840 	}
   841 
   842 	checksum->finalize();
   843 }
   844 
   845 CON_COMMAND(sm_gamedata_md5, "Checks the MD5 sum for a given gamedata file")
   846 {
   847 #if !defined ORANGEBOX_BUILD
   848 	CCommand args;
   849 #endif
   850 
   851 	if (args.ArgC() < 2)
   852 	{
   853 		g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
   854 		return;
   855 	}
   856 
   857 	const char *file = args.Arg(1);
   858 	if (!file || file[0] == '\0')
   859 	{
   860 		g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
   861 		return;
   862 	}
   863 
   864 	SourceHook::CVector<FileData *>::iterator iter = g_FetchThread.filenames.begin();
   865 
   866 	FileData *curData;
   867 
   868 	while (iter != g_FetchThread.filenames.end())
   869 	{
   870 		curData = (*iter);
   871 
   872 		char fileName[30];
   873 
   874 		g_LibSys.GetFileFromPath(fileName, sizeof(fileName), curData->filename->c_str());
   875 
   876 		if (strcmpi(fileName, file) == 0)
   877 		{
   878 			g_SMAPI->ConPrintf("MD5 Sum: %s\n", curData->checksum);
   879 			return;
   880 		}
   881 
   882 		iter++;
   883 	}
   884 
   885 	g_SMAPI->ConPrint("File not found!\n");
   886 }
   887 
   888 FetcherThread::~FetcherThread()
   889 {
   890 	SourceHook::CVector<FileData *>::iterator iter = filenames.begin();
   891 
   892 	FileData *curData;
   893 
   894 	while (iter != filenames.end())
   895 	{
   896 		curData = (*iter);
   897 		delete curData->filename;
   898 		delete curData;
   899 		iter = filenames.erase(iter);
   900 	}
   901 }
   902 
   903 FetcherThread::FetcherThread() 
   904 {
   905 	memtable = new BaseMemTable(4096);
   906 	wasSuccess = false;
   907 	needsRestart = false;
   908 }
   909