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