Merge from sourcemod-1.1 branch.
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
32 #include "GameDataFetcher.h"
35 #ifdef PLATFORM_WINDOWS
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
43 #include <arpa/inet.h>
45 #define INVALID_SOCKET -1
46 #define closesocket close
47 #define WSAGetLastError() errno
50 #include "sh_vector.h"
51 #include "sh_string.h"
52 #include "sm_version.h"
54 #if SOURCE_ENGINE == SE_LEFT4DEAD
55 #include "convar_sm_l4d.h"
56 #elif SOURCE_ENGINE == SE_ORANGEBOX
57 #include "convar_sm_ob.h"
59 #include "convar_sm.h"
62 #include "sourcemm_api.h"
65 #include "compat_wrappers.h"
66 #include "sm_stringutil.h"
68 #include "frame_hooks.h"
70 #define QUERY_MAX_LENGTH 1024
72 static BuildMD5ableBuffer g_MD5Builder;
73 static FetcherThread g_FetchThread;
75 static FILE *logfile = NULL;
77 bool g_disableGameDataUpdate = false;
80 * Note on this. If we issue a reload and changelevel, my srcds.exe will emit
81 * Assertion Failed: !m_bServiceStarted
82 * on quit. This seems like a non-issue, because before we just terminated the
83 * server anyway. If anyone notices and files a bug, we can look into it further.
85 bool g_restartAfterUpdate = false;
87 static bool was_level_started = false;
88 static int g_serverPort = 6500;
89 static char g_serverAddress[100] = "smupdate.alliedmods.net";
91 static void _ForceRestart(void *data)
94 g_Logger.LogMessage("Automatically restarting SourceMod after a successful gamedata update.");
95 UTIL_Format(cmd, sizeof(cmd), "meta unload %d\n", g_PLID);
96 engine->ServerCommand(cmd);
97 UTIL_Format(cmd, sizeof(cmd), "changelevel \"%s\"\n", STRING(gpGlobals->mapname));
98 engine->ServerCommand(cmd);
99 UTIL_Format(cmd, sizeof(cmd), "echo SourceMod restarted after gamedata update.\n");
100 engine->ServerCommand(cmd);
103 static void ForceRestart()
107 action.action = _ForceRestart;
109 AddFrameAction(action);
112 void FetcherThread::RunThread(IThreadHandle *pHandle)
114 char lock_path[PLATFORM_MAX_PATH];
115 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp");
116 g_LibSys.CreateFolder(lock_path);
118 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
120 char log_path[PLATFORM_MAX_PATH];
121 g_SourceMod.BuildPath(Path_SM, log_path, sizeof(log_path), "logs/gamedata");
123 g_LibSys.CreateFolder(log_path);
127 tm *curtime = localtime(&t);
129 g_SourceMod.BuildPath(Path_SM,
132 "logs/gamedata/L%04d%02d%02d.log",
133 curtime->tm_year + 1900,
137 logfile = fopen(log_path, "at");
145 //Create a blank lock file
146 FILE *fp = fopen(lock_path, "w");
152 char query[QUERY_MAX_LENGTH];
154 /* Check for updated gamedata files */
155 int len = BuildGameDataQuery(query, QUERY_MAX_LENGTH);
159 g_Logger.LogToFileOnly(logfile, "Could not build gamedata query!");
165 /* We check this late so we have the MD5 sums available. This may change in the future. */
166 if (g_disableGameDataUpdate)
168 g_Logger.LogToFileOnly(logfile, "Skipping gamedata fetcher (DisableAutoUpdate set)");
174 /* Create a new socket for this connection */
175 int socketDescriptor = ConnectSocket();
177 if (socketDescriptor == INVALID_SOCKET)
184 int sent = SendData(socketDescriptor, query, len);
187 g_Logger.LogToFileOnly(logfile, "Sent gamedata query");
193 g_Logger.LogToFileOnly(logfile, "Failed to send gamedata query data to remote host");
196 closesocket(socketDescriptor);
202 ProcessGameDataQuery(socketDescriptor);
204 /* And we're done! */
205 closesocket(socketDescriptor);
210 void FetcherThread::OnTerminate(IThreadHandle *pHandle, bool cancel)
212 g_blockGameDataLoad = false;
221 HandleUpdateStatus(updateStatus, build);
225 if (g_restartAfterUpdate)
227 if (was_level_started)
234 g_Logger.LogMessage("Your gamedata files have been updated, please restart your server.");
238 else if (!g_disableGameDataUpdate)
240 g_Logger.LogError("An error occurred in the gamedata fetcher, see your gamedata log files for more information.");
244 int FetcherThread::BuildGameDataQuery(char *buffer, int maxlen)
246 char gamedata_path[PLATFORM_MAX_PATH];
247 g_SourceMod.BuildPath(Path_SM, gamedata_path, sizeof(gamedata_path), "gamedata");
249 IDirectory *dir = g_LibSys.OpenDirectory(gamedata_path);
256 bf_write Writer = bf_write("GameDataQuery", buffer, maxlen);
258 Writer.WriteByte('A'); //Generic Header char
259 Writer.WriteByte('G'); //G for gamedata query, or green, like my hat.
261 short build[4] = { SVN_FILE_VERSION };
263 Writer.WriteBytes(&build[0], 8);
265 Writer.WriteByte(0); // Initialize the file counter - Index 10
267 while (dir->MoreFiles())
269 if (dir->IsEntryFile())
271 const char *name = dir->GetEntryName();
272 size_t len = strlen(name);
273 if (len >= 4 && strcmp(&name[len-4], ".txt") == 0)
278 unsigned char raw[16];
279 char file[PLATFORM_MAX_PATH];
281 g_LibSys.PathFormat(file, sizeof(file), "%s/%s", gamedata_path, name);
283 g_MD5Builder.checksum = &md5;
284 if ((err = g_TextParser.ParseFile_SMC(file, &g_MD5Builder, &states)) == SMCError_Okay)
287 (uint8_t)buffer[10]++; //Increment the file counter
288 Writer.WriteBytes(raw, 16);
290 FileData *data = new FileData();
291 data->filename = new SourceHook::String(file);
292 md5.hex_digest(data->checksum);
293 filenames.push_back(data);
296 g_Logger.LogToFileOnly(logfile, "Parsed file: %s as %s", file, data->checksum);
303 const char *error = g_TextParser.GetSMCErrorString(err);
304 g_Logger.LogToFileOnly(logfile, "Parsing of file %s failed: %s", file, error);
312 return Writer.GetNumBytesWritten();
315 int FetcherThread::ConnectSocket()
317 #if defined PLATFORM_WINDOWS
319 WSAStartup(0x0101, &wsaData);
322 struct protoent *ptrp;
324 if ((ptrp = getprotobyname("tcp")) == NULL)
326 g_Logger.LogToFileOnly(logfile, "Error: Failed to find TCP protocol");
327 return INVALID_SOCKET;
330 int socketDescriptor = socket(AF_INET, SOCK_STREAM, ptrp->p_proto);
332 if (socketDescriptor == INVALID_SOCKET)
335 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
336 g_Logger.LogToFileOnly(logfile, "Error: Failed to create socket: %s", error);
337 closesocket(socketDescriptor);
338 return INVALID_SOCKET;
342 struct sockaddr_in local_addr;
344 local_addr.sin_family = AF_INET;
345 local_addr.sin_port = htons((u_short)g_serverPort);
347 he = gethostbyname(g_serverAddress);
351 if ((local_addr.sin_addr.s_addr = inet_addr(g_serverAddress)) == INADDR_NONE)
353 g_Logger.LogToFileOnly(logfile, "Couldn't locate address: %s", g_serverAddress);
354 closesocket(socketDescriptor);
355 return INVALID_SOCKET;
360 memcpy(&local_addr.sin_addr, (struct in_addr *)he->h_addr, he->h_length);
363 if (connect(socketDescriptor, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0)
366 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
367 g_Logger.LogToFileOnly(logfile, "Couldn't connect to %s: %s", g_serverAddress, error);
368 closesocket(socketDescriptor);
369 return INVALID_SOCKET;
372 return socketDescriptor;
375 void FetcherThread::ProcessGameDataQuery(int socketDescriptor)
380 g_Logger.LogToFileOnly(logfile, "Waiting for reply!");
383 //Read in the header bytes
384 int returnLen = RecvData(socketDescriptor, buffer, 12);
390 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
391 g_Logger.LogToFileOnly(logfile, "Did not receive reply: %s", error);
396 g_Logger.LogToFileOnly(logfile, "Received Header!");
399 bf_read Reader = bf_read("GameDataQuery", buffer, 12);
401 if (Reader.ReadByte() != 'A' || Reader.ReadByte() != 'G')
404 g_Logger.LogToFileOnly(logfile, "Unknown Query Response");
409 updateStatus = (UpdateStatus)Reader.ReadByte();
411 build[0] = Reader.ReadShort();
412 build[1] = Reader.ReadShort();
413 build[2] = Reader.ReadShort();
414 build[3] = Reader.ReadShort();
417 g_Logger.LogToFileOnly(logfile,
418 "Update Status: %i - Latest %i.%i.%i.%i",
426 int changedFiles = Reader.ReadByte();
429 g_Logger.LogToFileOnly(logfile, "Files to download: %i", changedFiles);
432 for (int i=0; i<changedFiles; i++)
434 //Read in the file index and byte count
435 returnLen = RecvData(socketDescriptor, buffer, 5);
439 /* Timeout or fail? */
443 Reader.StartReading(buffer, 5);
445 int index = Reader.ReadByte();
446 int tempLen = Reader.ReadUBitLong(32);
449 g_Logger.LogToFileOnly(logfile, "File index %i and length %i", index, tempLen);
453 memtable->CreateMem(tempLen+1, &memPtr);
455 //Read the contents of our file into the memtable
456 returnLen = RecvData(socketDescriptor, (char *)memPtr, tempLen);
459 g_Logger.LogToFileOnly(logfile, "Received %i bytes", returnLen);
464 /* Timeout or fail? */
468 ((unsigned char *)memPtr)[tempLen] = '\0';
470 FileData *data = filenames.at(index);
471 const char *filename;
474 filename = data->filename->c_str();
476 FILE *fp = fopen(filename, "w");
480 fprintf(fp, "%s", (const char *)memPtr);
485 g_Logger.LogToFileOnly(logfile, "Failed to open file \"%s\" for writing", filename);
495 g_Logger.LogToFileOnly(logfile, "Updated file: %s", filename);
499 g_Logger.LogToFileOnly(logfile, "File Downloads Completed!");
502 needsRestart = false;
504 if (changedFiles > 0)
509 //Read changed file count
510 returnLen = RecvData(socketDescriptor, buffer, 1);
515 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
516 g_Logger.LogToFileOnly(logfile, "Did not receive count reply: %s", error);
520 Reader.StartReading(buffer, 1);
522 changedFiles = Reader.ReadByte();
524 if (changedFiles < 1)
527 g_Logger.LogToFileOnly(logfile, "No unknown files. We're all done");
532 char *changedFileIndexes = new char[changedFiles];
535 g_Logger.LogToFileOnly(logfile, "%i files were unknown", changedFiles);
538 returnLen = RecvData(socketDescriptor, changedFileIndexes, changedFiles);
543 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
544 g_Logger.LogToFileOnly(logfile, "Did not receive list reply: %s", error);
548 Reader.StartReading(changedFileIndexes, changedFiles);
550 for (int i=0; i<changedFiles; i++)
552 int index = Reader.ReadByte();
555 FileData *data = filenames.at(index);
556 const char* pathname;
559 pathname = data->filename->c_str();
566 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), pathname);
568 g_Logger.LogToFileOnly(logfile, "Unknown File %i : %s", index, fileName);
572 delete [] changedFileIndexes;
577 int FetcherThread::RecvData(int socketDescriptor, char *buffer, int len)
582 /* Create a 10 Second Timeout */
586 int bytesReceivedTotal = 0;
588 while (bytesReceivedTotal < len)
590 /* Add our socket to a socket set */
592 FD_SET(socketDescriptor, &fds);
594 /* Wait max of 10 seconds for recv to become available */
595 select(socketDescriptor+1, &fds, NULL, NULL, &tv);
597 int bytesReceived = 0;
599 /* Is there a limit on how much we can receive? Some site said 1024 bytes, which will be well short of a file */
600 if (FD_ISSET(socketDescriptor, &fds))
602 bytesReceived = recv(socketDescriptor, buffer+bytesReceivedTotal, len-bytesReceivedTotal, 0);
605 if (bytesReceived == 0 || bytesReceived == -1)
610 bytesReceivedTotal += bytesReceived;
613 return bytesReceivedTotal;
616 int FetcherThread::SendData(int socketDescriptor, char *buffer, int len)
624 int sentBytesTotal = 0;
626 while (sentBytesTotal < len)
629 FD_SET(socketDescriptor, &fds);
631 select(socketDescriptor+1, NULL, &fds, NULL, &tv);
635 if (FD_ISSET(socketDescriptor, &fds))
637 sentBytes = send(socketDescriptor, buffer+sentBytesTotal, len-sentBytesTotal, 0);
640 if (sentBytes == 0 || sentBytes == -1)
645 sentBytesTotal += sentBytes;
648 return sentBytesTotal;
651 void FetcherThread::HandleUpdateStatus(UpdateStatus status, short version[4])
661 case Update_NewBuild:
666 case Update_MinorAvailable:
668 g_Logger.LogMessage("SourceMod Update: A new release of SourceMod is now available from sourcemod.net");
669 g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
673 case Update_MajorAvailable:
675 g_Logger.LogMessage("SourceMod Update: An major release of SourceMod is now available from sourcemod.net");
676 g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
680 case Update_CriticalAvailable:
682 g_Logger.LogError("SourceMod Update: A critical SourceMod release is available from sourcemod.net. It is strongly recommended that you update!");
683 g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
689 bool g_blockGameDataLoad = false;
690 static IThreadHandle *fetch_thread_hndl;
692 class InitFetch : public SMGlobalClass
695 void OnSourceModAllInitialized_Post()
697 char lock_path[PLATFORM_MAX_PATH];
698 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
700 if (g_LibSys.IsPathFile(lock_path) && g_LibSys.PathExists(lock_path))
702 g_Logger.LogError("sourcemod/data/temp/gamedata.lock file detected. This is most likely due to a crash during GameData updating - Blocking GameData loading");
703 g_Logger.LogError("If this error persists delete the file manually");
704 g_blockGameDataLoad = true;
707 ThreadParams fetchThreadParams = ThreadParams();
708 fetchThreadParams.prio = ThreadPrio_Low;
709 fetch_thread_hndl = g_pThreader->MakeThread(&g_FetchThread, &fetchThreadParams);
712 void OnSourceModShutdown()
714 fetch_thread_hndl->WaitForThread();
715 fetch_thread_hndl->DestroyThis();
718 void OnSourceModLevelActivated()
720 was_level_started = true;
722 if (g_restartAfterUpdate &&
723 g_FetchThread.wasSuccess &&
724 g_FetchThread.needsRestart)
730 void OnSourceModLevelEnd()
732 was_level_started = false;
735 ConfigResult OnSourceModConfigChanged(const char *key,
741 if (strcasecmp(key, "DisableAutoUpdate") == 0)
743 if (strcasecmp(value, "yes") == 0)
745 g_disableGameDataUpdate = true;
746 return ConfigResult_Accept;
748 else if (strcasecmp(value, "no") == 0)
750 g_disableGameDataUpdate = false;
751 return ConfigResult_Accept;
754 return ConfigResult_Reject;
757 if (strcasecmp(key, "ForceRestartAfterUpdate") == 0)
759 if (strcasecmp(value, "yes") == 0)
761 g_restartAfterUpdate = true;
762 return ConfigResult_Accept;
764 else if (strcasecmp(value, "no") == 0)
766 g_restartAfterUpdate = false;
767 return ConfigResult_Accept;
770 return ConfigResult_Reject;
773 if (strcasecmp(key, "AutoUpdateServer") == 0)
775 UTIL_Format(g_serverAddress, sizeof(g_serverAddress), "%s", value);
777 return ConfigResult_Accept;
780 if (strcasecmp(key, "AutoUpdatePort") == 0)
782 int port = atoi(value);
786 return ConfigResult_Reject;
791 return ConfigResult_Accept;
794 return ConfigResult_Ignore;
798 BuildMD5ableBuffer::BuildMD5ableBuffer()
800 stringTable = new BaseStringTable(2048);
803 BuildMD5ableBuffer::~BuildMD5ableBuffer()
808 void BuildMD5ableBuffer::ReadSMC_ParseStart()
810 stringTable->Reset();
813 SMCResult BuildMD5ableBuffer::ReadSMC_KeyValue(const SMCStates *states,
817 stringTable->AddString(key);
818 stringTable->AddString(value);
820 return SMCResult_Continue;
823 SMCResult BuildMD5ableBuffer::ReadSMC_NewSection(const SMCStates *states, const char *name)
825 stringTable->AddString(name);
827 return SMCResult_Continue;
830 void BuildMD5ableBuffer::ReadSMC_ParseEnd(bool halted, bool failed)
832 if (halted || failed)
837 void *data = stringTable->GetMemTable()->GetAddress(0);
841 checksum->update((unsigned char *)data, stringTable->GetMemTable()->GetActualMemUsed());
844 checksum->finalize();
847 CON_COMMAND(sm_gamedata_md5, "Checks the MD5 sum for a given gamedata file")
849 #if SOURCE_ENGINE == SE_EPISODEONE
855 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
859 const char *file = args.Arg(1);
860 if (!file || file[0] == '\0')
862 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
866 SourceHook::CVector<FileData *>::iterator iter = g_FetchThread.filenames.begin();
870 while (iter != g_FetchThread.filenames.end())
876 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), curData->filename->c_str());
878 if (strcmpi(fileName, file) == 0)
880 g_SMAPI->ConPrintf("MD5 Sum: %s\n", curData->checksum);
887 g_SMAPI->ConPrint("File not found!\n");
890 FetcherThread::~FetcherThread()
892 SourceHook::CVector<FileData *>::iterator iter = filenames.begin();
896 while (iter != filenames.end())
899 delete curData->filename;
901 iter = filenames.erase(iter);
905 FetcherThread::FetcherThread()
907 memtable = new BaseMemTable(4096);
909 needsRestart = false;