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 #ifdef ORANGEBOX_BUILD
55 #include "convar_sm_ob.h"
57 #include "convar_sm.h"
60 #include "sourcemm_api.h"
63 #include "compat_wrappers.h"
64 #include "sm_stringutil.h"
66 #include "frame_hooks.h"
68 #define QUERY_MAX_LENGTH 1024
70 static BuildMD5ableBuffer g_MD5Builder;
71 static FetcherThread g_FetchThread;
73 static FILE *logfile = NULL;
75 bool g_disableGameDataUpdate = false;
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.
83 bool g_restartAfterUpdate = false;
85 static bool was_level_started = false;
86 static int g_serverPort = 6500;
87 static char g_serverAddress[100] = "smupdate.alliedmods.net";
89 static void _ForceRestart(void *data)
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);
101 static void ForceRestart()
105 action.action = _ForceRestart;
107 AddFrameAction(action);
110 void FetcherThread::RunThread(IThreadHandle *pHandle)
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);
116 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
118 char log_path[PLATFORM_MAX_PATH];
119 g_SourceMod.BuildPath(Path_SM, log_path, sizeof(log_path), "logs/gamedata");
121 g_LibSys.CreateFolder(log_path);
125 tm *curtime = localtime(&t);
127 g_SourceMod.BuildPath(Path_SM, log_path, sizeof(log_path), "logs/gamedata/L%02d%02d.log", curtime->tm_mon + 1, curtime->tm_mday);
129 logfile = fopen(log_path, "a");
137 //Create a blank lock file
138 FILE *fp = fopen(lock_path, "w");
144 char query[QUERY_MAX_LENGTH];
146 /* Check for updated gamedata files */
147 int len = BuildGameDataQuery(query, QUERY_MAX_LENGTH);
151 g_Logger.LogToFileOnly(logfile, "Could not build gamedata query!");
157 /* We check this late so we have the MD5 sums available. This may change in the future. */
158 if (g_disableGameDataUpdate)
160 g_Logger.LogToFileOnly(logfile, "Skipping gamedata fetcher (DisableAutoUpdate set)");
166 /* Create a new socket for this connection */
167 int socketDescriptor = ConnectSocket();
169 if (socketDescriptor == INVALID_SOCKET)
176 int sent = SendData(socketDescriptor, query, len);
179 g_Logger.LogToFileOnly(logfile, "Sent gamedata query");
185 g_Logger.LogToFileOnly(logfile, "Failed to send gamedata query data to remote host");
188 closesocket(socketDescriptor);
194 ProcessGameDataQuery(socketDescriptor);
196 /* And we're done! */
197 closesocket(socketDescriptor);
202 void FetcherThread::OnTerminate(IThreadHandle *pHandle, bool cancel)
204 g_blockGameDataLoad = false;
213 HandleUpdateStatus(updateStatus, build);
217 if (g_restartAfterUpdate)
219 if (was_level_started)
226 g_Logger.LogMessage("Your gamedata files have been updated, please restart your server.");
230 else if (!g_disableGameDataUpdate)
232 g_Logger.LogError("An error occurred in the gamedata fetcher, see your gamedata log files for more information.");
236 int FetcherThread::BuildGameDataQuery(char *buffer, int maxlen)
238 char gamedata_path[PLATFORM_MAX_PATH];
239 g_SourceMod.BuildPath(Path_SM, gamedata_path, sizeof(gamedata_path), "gamedata");
241 IDirectory *dir = g_LibSys.OpenDirectory(gamedata_path);
248 bf_write Writer = bf_write("GameDataQuery", buffer, maxlen);
250 Writer.WriteByte('A'); //Generic Header char
251 Writer.WriteByte('G'); //G for gamedata query, or green, like my hat.
253 short build[4] = { SVN_FILE_VERSION };
255 Writer.WriteBytes(&build[0], 8);
257 Writer.WriteByte(0); // Initialize the file counter - Index 10
259 while (dir->MoreFiles())
261 if (dir->IsEntryFile())
263 const char *name = dir->GetEntryName();
264 size_t len = strlen(name);
265 if (len >= 4 && strcmp(&name[len-4], ".txt") == 0)
270 unsigned char raw[16];
271 char file[PLATFORM_MAX_PATH];
273 g_LibSys.PathFormat(file, sizeof(file), "%s/%s", gamedata_path, name);
275 g_MD5Builder.checksum = &md5;
276 if ((err = g_TextParser.ParseFile_SMC(file, &g_MD5Builder, &states)) == SMCError_Okay)
279 (uint8_t)buffer[10]++; //Increment the file counter
280 Writer.WriteBytes(raw, 16);
282 FileData *data = new FileData();
283 data->filename = new SourceHook::String(file);
284 md5.hex_digest(data->checksum);
285 filenames.push_back(data);
288 g_Logger.LogToFileOnly(logfile, "Parsed file: %s as %s", file, data->checksum);
295 const char *error = g_TextParser.GetSMCErrorString(err);
296 g_Logger.LogToFileOnly(logfile, "Parsing of file %s failed: %s", file, error);
304 return Writer.GetNumBytesWritten();
307 int FetcherThread::ConnectSocket()
309 #if defined PLATFORM_WINDOWS
311 WSAStartup(0x0101, &wsaData);
314 struct protoent *ptrp;
316 if ((ptrp = getprotobyname("tcp")) == NULL)
318 g_Logger.LogToFileOnly(logfile, "Error: Failed to find TCP protocol");
319 return INVALID_SOCKET;
322 int socketDescriptor = socket(AF_INET, SOCK_STREAM, ptrp->p_proto);
324 if (socketDescriptor == INVALID_SOCKET)
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;
334 struct sockaddr_in local_addr;
336 local_addr.sin_family = AF_INET;
337 local_addr.sin_port = htons((u_short)g_serverPort);
339 he = gethostbyname(g_serverAddress);
343 if ((local_addr.sin_addr.s_addr = inet_addr(g_serverAddress)) == INADDR_NONE)
345 g_Logger.LogToFileOnly(logfile, "Couldn't locate address: %s", g_serverAddress);
346 closesocket(socketDescriptor);
347 return INVALID_SOCKET;
352 memcpy(&local_addr.sin_addr, (struct in_addr *)he->h_addr, he->h_length);
355 if (connect(socketDescriptor, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0)
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;
364 return socketDescriptor;
367 void FetcherThread::ProcessGameDataQuery(int socketDescriptor)
372 g_Logger.LogToFileOnly(logfile, "Waiting for reply!");
375 //Read in the header bytes
376 int returnLen = RecvData(socketDescriptor, buffer, 12);
382 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
383 g_Logger.LogToFileOnly(logfile, "Did not receive reply: %s", error);
388 g_Logger.LogToFileOnly(logfile, "Received Header!");
391 bf_read Reader = bf_read("GameDataQuery", buffer, 12);
393 if (Reader.ReadByte() != 'A' || Reader.ReadByte() != 'G')
396 g_Logger.LogToFileOnly(logfile, "Unknown Query Response");
401 updateStatus = (UpdateStatus)Reader.ReadByte();
403 build[0] = Reader.ReadShort();
404 build[1] = Reader.ReadShort();
405 build[2] = Reader.ReadShort();
406 build[3] = Reader.ReadShort();
409 g_Logger.LogToFileOnly(logfile,
410 "Update Status: %i - Latest %i.%i.%i.%i",
418 int changedFiles = Reader.ReadByte();
421 g_Logger.LogToFileOnly(logfile, "Files to download: %i", changedFiles);
424 for (int i=0; i<changedFiles; i++)
426 //Read in the file index and byte count
427 returnLen = RecvData(socketDescriptor, buffer, 5);
431 /* Timeout or fail? */
435 Reader.StartReading(buffer, 5);
437 int index = Reader.ReadByte();
438 int tempLen = Reader.ReadUBitLong(32);
441 g_Logger.LogToFileOnly(logfile, "File index %i and length %i", index, tempLen);
445 memtable->CreateMem(tempLen+1, &memPtr);
447 //Read the contents of our file into the memtable
448 returnLen = RecvData(socketDescriptor, (char *)memPtr, tempLen);
451 g_Logger.LogToFileOnly(logfile, "Received %i bytes", returnLen);
456 /* Timeout or fail? */
460 ((unsigned char *)memPtr)[tempLen] = '\0';
462 FileData *data = filenames.at(index);
463 const char *filename;
466 filename = data->filename->c_str();
468 FILE *fp = fopen(filename, "w");
472 fprintf(fp, "%s", (const char *)memPtr);
477 g_Logger.LogToFileOnly(logfile, "Failed to open file \"%s\" for writing", filename);
487 g_Logger.LogToFileOnly(logfile, "Updated file: %s", filename);
491 g_Logger.LogToFileOnly(logfile, "File Downloads Completed!");
494 needsRestart = false;
496 if (changedFiles > 0)
501 //Read changed file count
502 returnLen = RecvData(socketDescriptor, buffer, 1);
507 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
508 g_Logger.LogToFileOnly(logfile, "Did not receive count reply: %s", error);
512 Reader.StartReading(buffer, 1);
514 changedFiles = Reader.ReadByte();
516 if (changedFiles < 1)
519 g_Logger.LogToFileOnly(logfile, "No unknown files. We're all done");
524 char *changedFileIndexes = new char[changedFiles];
527 g_Logger.LogToFileOnly(logfile, "%i files were unknown", changedFiles);
530 returnLen = RecvData(socketDescriptor, changedFileIndexes, changedFiles);
535 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
536 g_Logger.LogToFileOnly(logfile, "Did not receive list reply: %s", error);
540 Reader.StartReading(changedFileIndexes, changedFiles);
542 for (int i=0; i<changedFiles; i++)
544 int index = Reader.ReadByte();
547 FileData *data = filenames.at(index);
548 const char* pathname;
551 pathname = data->filename->c_str();
558 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), pathname);
560 g_Logger.LogToFileOnly(logfile, "Unknown File %i : %s", index, fileName);
564 delete [] changedFileIndexes;
569 int FetcherThread::RecvData(int socketDescriptor, char *buffer, int len)
574 /* Create a 10 Second Timeout */
578 int bytesReceivedTotal = 0;
580 while (bytesReceivedTotal < len)
582 /* Add our socket to a socket set */
584 FD_SET(socketDescriptor, &fds);
586 /* Wait max of 10 seconds for recv to become available */
587 select(socketDescriptor+1, &fds, NULL, NULL, &tv);
589 int bytesReceived = 0;
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))
594 bytesReceived = recv(socketDescriptor, buffer+bytesReceivedTotal, len-bytesReceivedTotal, 0);
597 if (bytesReceived == 0 || bytesReceived == -1)
602 bytesReceivedTotal += bytesReceived;
605 return bytesReceivedTotal;
608 int FetcherThread::SendData(int socketDescriptor, char *buffer, int len)
616 int sentBytesTotal = 0;
618 while (sentBytesTotal < len)
621 FD_SET(socketDescriptor, &fds);
623 select(socketDescriptor+1, NULL, &fds, NULL, &tv);
627 if (FD_ISSET(socketDescriptor, &fds))
629 sentBytes = send(socketDescriptor, buffer+sentBytesTotal, len-sentBytesTotal, 0);
632 if (sentBytes == 0 || sentBytes == -1)
637 sentBytesTotal += sentBytes;
640 return sentBytesTotal;
643 void FetcherThread::HandleUpdateStatus(UpdateStatus status, short version[4])
653 case Update_NewBuild:
658 case Update_MinorAvailable:
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]);
665 case Update_MajorAvailable:
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]);
672 case Update_CriticalAvailable:
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]);
681 bool g_blockGameDataLoad = false;
682 static IThreadHandle *fetch_thread_hndl;
684 class InitFetch : public SMGlobalClass
687 void OnSourceModAllInitialized_Post()
689 char lock_path[PLATFORM_MAX_PATH];
690 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
692 if (g_LibSys.IsPathFile(lock_path) && g_LibSys.PathExists(lock_path))
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;
699 ThreadParams fetchThreadParams = ThreadParams();
700 fetchThreadParams.prio = ThreadPrio_Low;
701 fetch_thread_hndl = g_pThreader->MakeThread(&g_FetchThread, &fetchThreadParams);
704 void OnSourceModShutdown()
706 fetch_thread_hndl->WaitForThread();
707 fetch_thread_hndl->DestroyThis();
710 void OnSourceModLevelActivated()
712 was_level_started = true;
714 if (g_restartAfterUpdate &&
715 g_FetchThread.wasSuccess &&
716 g_FetchThread.needsRestart)
722 void OnSourceModLevelEnd()
724 was_level_started = false;
727 ConfigResult OnSourceModConfigChanged(const char *key,
733 if (strcasecmp(key, "DisableAutoUpdate") == 0)
735 if (strcasecmp(value, "yes") == 0)
737 g_disableGameDataUpdate = true;
738 return ConfigResult_Accept;
740 else if (strcasecmp(value, "no") == 0)
742 g_disableGameDataUpdate = false;
743 return ConfigResult_Accept;
746 return ConfigResult_Reject;
749 if (strcasecmp(key, "ForceRestartAfterUpdate") == 0)
751 if (strcasecmp(value, "yes") == 0)
753 g_restartAfterUpdate = true;
754 return ConfigResult_Accept;
756 else if (strcasecmp(value, "no") == 0)
758 g_restartAfterUpdate = false;
759 return ConfigResult_Accept;
762 return ConfigResult_Reject;
765 if (strcasecmp(key, "AutoUpdateServer") == 0)
767 UTIL_Format(g_serverAddress, sizeof(g_serverAddress), "%s", value);
769 return ConfigResult_Accept;
772 if (strcasecmp(key, "AutoUpdatePort") == 0)
774 int port = atoi(value);
778 return ConfigResult_Reject;
783 return ConfigResult_Accept;
786 return ConfigResult_Ignore;
790 BuildMD5ableBuffer::BuildMD5ableBuffer()
792 stringTable = new BaseStringTable(2048);
795 BuildMD5ableBuffer::~BuildMD5ableBuffer()
800 void BuildMD5ableBuffer::ReadSMC_ParseStart()
802 stringTable->Reset();
805 SMCResult BuildMD5ableBuffer::ReadSMC_KeyValue(const SMCStates *states,
809 stringTable->AddString(key);
810 stringTable->AddString(value);
812 return SMCResult_Continue;
815 SMCResult BuildMD5ableBuffer::ReadSMC_NewSection(const SMCStates *states, const char *name)
817 stringTable->AddString(name);
819 return SMCResult_Continue;
822 void BuildMD5ableBuffer::ReadSMC_ParseEnd(bool halted, bool failed)
824 if (halted || failed)
829 void *data = stringTable->GetMemTable()->GetAddress(0);
833 checksum->update((unsigned char *)data, stringTable->GetMemTable()->GetActualMemUsed());
836 checksum->finalize();
839 CON_COMMAND(sm_gamedata_md5, "Checks the MD5 sum for a given gamedata file")
841 #if !defined ORANGEBOX_BUILD
847 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
851 const char *file = args.Arg(1);
852 if (!file || file[0] == '\0')
854 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
858 SourceHook::CVector<FileData *>::iterator iter = g_FetchThread.filenames.begin();
862 while (iter != g_FetchThread.filenames.end())
868 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), curData->filename->c_str());
870 if (strcmpi(fileName, file) == 0)
872 g_SMAPI->ConPrintf("MD5 Sum: %s\n", curData->checksum);
879 g_SMAPI->ConPrint("File not found!\n");
882 FetcherThread::~FetcherThread()
884 SourceHook::CVector<FileData *>::iterator iter = filenames.begin();
888 while (iter != filenames.end())
891 delete curData->filename;
893 iter = filenames.erase(iter);
897 FetcherThread::FetcherThread()
899 memtable = new BaseMemTable(4096);
901 needsRestart = false;