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