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,
130 "logs/gamedata/L%04d%02d%02d.log",
131 curtime->tm_year + 1900,
135 logfile = fopen(log_path, "at");
143 //Create a blank lock file
144 FILE *fp = fopen(lock_path, "w");
150 char query[QUERY_MAX_LENGTH];
152 /* Check for updated gamedata files */
153 int len = BuildGameDataQuery(query, QUERY_MAX_LENGTH);
157 g_Logger.LogToFileOnly(logfile, "Could not build gamedata query!");
163 /* We check this late so we have the MD5 sums available. This may change in the future. */
164 if (g_disableGameDataUpdate)
166 g_Logger.LogToFileOnly(logfile, "Skipping gamedata fetcher (DisableAutoUpdate set)");
172 /* Create a new socket for this connection */
173 int socketDescriptor = ConnectSocket();
175 if (socketDescriptor == INVALID_SOCKET)
182 int sent = SendData(socketDescriptor, query, len);
185 g_Logger.LogToFileOnly(logfile, "Sent gamedata query");
191 g_Logger.LogToFileOnly(logfile, "Failed to send gamedata query data to remote host");
194 closesocket(socketDescriptor);
200 ProcessGameDataQuery(socketDescriptor);
202 /* And we're done! */
203 closesocket(socketDescriptor);
208 void FetcherThread::OnTerminate(IThreadHandle *pHandle, bool cancel)
210 g_blockGameDataLoad = false;
219 HandleUpdateStatus(updateStatus, build);
223 if (g_restartAfterUpdate)
225 if (was_level_started)
232 g_Logger.LogMessage("Your gamedata files have been updated, please restart your server.");
236 else if (!g_disableGameDataUpdate)
238 g_Logger.LogError("An error occurred in the gamedata fetcher, see your gamedata log files for more information.");
242 int FetcherThread::BuildGameDataQuery(char *buffer, int maxlen)
244 char gamedata_path[PLATFORM_MAX_PATH];
245 g_SourceMod.BuildPath(Path_SM, gamedata_path, sizeof(gamedata_path), "gamedata");
247 IDirectory *dir = g_LibSys.OpenDirectory(gamedata_path);
254 bf_write Writer = bf_write("GameDataQuery", buffer, maxlen);
256 Writer.WriteByte('A'); //Generic Header char
257 Writer.WriteByte('G'); //G for gamedata query, or green, like my hat.
259 short build[4] = { SVN_FILE_VERSION };
261 Writer.WriteBytes(&build[0], 8);
263 Writer.WriteByte(0); // Initialize the file counter - Index 10
265 while (dir->MoreFiles())
267 if (dir->IsEntryFile())
269 const char *name = dir->GetEntryName();
270 size_t len = strlen(name);
271 if (len >= 4 && strcmp(&name[len-4], ".txt") == 0)
276 unsigned char raw[16];
277 char file[PLATFORM_MAX_PATH];
279 g_LibSys.PathFormat(file, sizeof(file), "%s/%s", gamedata_path, name);
281 g_MD5Builder.checksum = &md5;
282 if ((err = g_TextParser.ParseFile_SMC(file, &g_MD5Builder, &states)) == SMCError_Okay)
285 (uint8_t)buffer[10]++; //Increment the file counter
286 Writer.WriteBytes(raw, 16);
288 FileData *data = new FileData();
289 data->filename = new SourceHook::String(file);
290 md5.hex_digest(data->checksum);
291 filenames.push_back(data);
294 g_Logger.LogToFileOnly(logfile, "Parsed file: %s as %s", file, data->checksum);
301 const char *error = g_TextParser.GetSMCErrorString(err);
302 g_Logger.LogToFileOnly(logfile, "Parsing of file %s failed: %s", file, error);
310 return Writer.GetNumBytesWritten();
313 int FetcherThread::ConnectSocket()
315 #if defined PLATFORM_WINDOWS
317 WSAStartup(0x0101, &wsaData);
320 struct protoent *ptrp;
322 if ((ptrp = getprotobyname("tcp")) == NULL)
324 g_Logger.LogToFileOnly(logfile, "Error: Failed to find TCP protocol");
325 return INVALID_SOCKET;
328 int socketDescriptor = socket(AF_INET, SOCK_STREAM, ptrp->p_proto);
330 if (socketDescriptor == INVALID_SOCKET)
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;
340 struct sockaddr_in local_addr;
342 local_addr.sin_family = AF_INET;
343 local_addr.sin_port = htons((u_short)g_serverPort);
345 he = gethostbyname(g_serverAddress);
349 if ((local_addr.sin_addr.s_addr = inet_addr(g_serverAddress)) == INADDR_NONE)
351 g_Logger.LogToFileOnly(logfile, "Couldn't locate address: %s", g_serverAddress);
352 closesocket(socketDescriptor);
353 return INVALID_SOCKET;
358 memcpy(&local_addr.sin_addr, (struct in_addr *)he->h_addr, he->h_length);
361 if (connect(socketDescriptor, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0)
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;
370 return socketDescriptor;
373 void FetcherThread::ProcessGameDataQuery(int socketDescriptor)
378 g_Logger.LogToFileOnly(logfile, "Waiting for reply!");
381 //Read in the header bytes
382 int returnLen = RecvData(socketDescriptor, buffer, 12);
388 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
389 g_Logger.LogToFileOnly(logfile, "Did not receive reply: %s", error);
394 g_Logger.LogToFileOnly(logfile, "Received Header!");
397 bf_read Reader = bf_read("GameDataQuery", buffer, 12);
399 if (Reader.ReadByte() != 'A' || Reader.ReadByte() != 'G')
402 g_Logger.LogToFileOnly(logfile, "Unknown Query Response");
407 updateStatus = (UpdateStatus)Reader.ReadByte();
409 build[0] = Reader.ReadShort();
410 build[1] = Reader.ReadShort();
411 build[2] = Reader.ReadShort();
412 build[3] = Reader.ReadShort();
415 g_Logger.LogToFileOnly(logfile,
416 "Update Status: %i - Latest %i.%i.%i.%i",
424 int changedFiles = Reader.ReadByte();
427 g_Logger.LogToFileOnly(logfile, "Files to download: %i", changedFiles);
430 for (int i=0; i<changedFiles; i++)
432 //Read in the file index and byte count
433 returnLen = RecvData(socketDescriptor, buffer, 5);
437 /* Timeout or fail? */
441 Reader.StartReading(buffer, 5);
443 int index = Reader.ReadByte();
444 int tempLen = Reader.ReadUBitLong(32);
447 g_Logger.LogToFileOnly(logfile, "File index %i and length %i", index, tempLen);
451 memtable->CreateMem(tempLen+1, &memPtr);
453 //Read the contents of our file into the memtable
454 returnLen = RecvData(socketDescriptor, (char *)memPtr, tempLen);
457 g_Logger.LogToFileOnly(logfile, "Received %i bytes", returnLen);
462 /* Timeout or fail? */
466 ((unsigned char *)memPtr)[tempLen] = '\0';
468 FileData *data = filenames.at(index);
469 const char *filename;
472 filename = data->filename->c_str();
474 FILE *fp = fopen(filename, "w");
478 fprintf(fp, "%s", (const char *)memPtr);
483 g_Logger.LogToFileOnly(logfile, "Failed to open file \"%s\" for writing", filename);
493 g_Logger.LogToFileOnly(logfile, "Updated file: %s", filename);
497 g_Logger.LogToFileOnly(logfile, "File Downloads Completed!");
500 needsRestart = false;
502 if (changedFiles > 0)
507 //Read changed file count
508 returnLen = RecvData(socketDescriptor, buffer, 1);
513 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
514 g_Logger.LogToFileOnly(logfile, "Did not receive count reply: %s", error);
518 Reader.StartReading(buffer, 1);
520 changedFiles = Reader.ReadByte();
522 if (changedFiles < 1)
525 g_Logger.LogToFileOnly(logfile, "No unknown files. We're all done");
530 char *changedFileIndexes = new char[changedFiles];
533 g_Logger.LogToFileOnly(logfile, "%i files were unknown", changedFiles);
536 returnLen = RecvData(socketDescriptor, changedFileIndexes, changedFiles);
541 g_LibSys.GetPlatformErrorEx(WSAGetLastError(), error, sizeof(error));
542 g_Logger.LogToFileOnly(logfile, "Did not receive list reply: %s", error);
546 Reader.StartReading(changedFileIndexes, changedFiles);
548 for (int i=0; i<changedFiles; i++)
550 int index = Reader.ReadByte();
553 FileData *data = filenames.at(index);
554 const char* pathname;
557 pathname = data->filename->c_str();
564 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), pathname);
566 g_Logger.LogToFileOnly(logfile, "Unknown File %i : %s", index, fileName);
570 delete [] changedFileIndexes;
575 int FetcherThread::RecvData(int socketDescriptor, char *buffer, int len)
580 /* Create a 10 Second Timeout */
584 int bytesReceivedTotal = 0;
586 while (bytesReceivedTotal < len)
588 /* Add our socket to a socket set */
590 FD_SET(socketDescriptor, &fds);
592 /* Wait max of 10 seconds for recv to become available */
593 select(socketDescriptor+1, &fds, NULL, NULL, &tv);
595 int bytesReceived = 0;
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))
600 bytesReceived = recv(socketDescriptor, buffer+bytesReceivedTotal, len-bytesReceivedTotal, 0);
603 if (bytesReceived == 0 || bytesReceived == -1)
608 bytesReceivedTotal += bytesReceived;
611 return bytesReceivedTotal;
614 int FetcherThread::SendData(int socketDescriptor, char *buffer, int len)
622 int sentBytesTotal = 0;
624 while (sentBytesTotal < len)
627 FD_SET(socketDescriptor, &fds);
629 select(socketDescriptor+1, NULL, &fds, NULL, &tv);
633 if (FD_ISSET(socketDescriptor, &fds))
635 sentBytes = send(socketDescriptor, buffer+sentBytesTotal, len-sentBytesTotal, 0);
638 if (sentBytes == 0 || sentBytes == -1)
643 sentBytesTotal += sentBytes;
646 return sentBytesTotal;
649 void FetcherThread::HandleUpdateStatus(UpdateStatus status, short version[4])
659 case Update_NewBuild:
664 case Update_MinorAvailable:
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]);
671 case Update_MajorAvailable:
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]);
678 case Update_CriticalAvailable:
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]);
687 bool g_blockGameDataLoad = false;
688 static IThreadHandle *fetch_thread_hndl;
690 class InitFetch : public SMGlobalClass
693 void OnSourceModAllInitialized_Post()
695 char lock_path[PLATFORM_MAX_PATH];
696 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
698 if (g_LibSys.IsPathFile(lock_path) && g_LibSys.PathExists(lock_path))
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;
705 ThreadParams fetchThreadParams = ThreadParams();
706 fetchThreadParams.prio = ThreadPrio_Low;
707 fetch_thread_hndl = g_pThreader->MakeThread(&g_FetchThread, &fetchThreadParams);
710 void OnSourceModShutdown()
712 fetch_thread_hndl->WaitForThread();
713 fetch_thread_hndl->DestroyThis();
716 void OnSourceModLevelActivated()
718 was_level_started = true;
720 if (g_restartAfterUpdate &&
721 g_FetchThread.wasSuccess &&
722 g_FetchThread.needsRestart)
728 void OnSourceModLevelEnd()
730 was_level_started = false;
733 ConfigResult OnSourceModConfigChanged(const char *key,
739 if (strcasecmp(key, "DisableAutoUpdate") == 0)
741 if (strcasecmp(value, "yes") == 0)
743 g_disableGameDataUpdate = true;
744 return ConfigResult_Accept;
746 else if (strcasecmp(value, "no") == 0)
748 g_disableGameDataUpdate = false;
749 return ConfigResult_Accept;
752 return ConfigResult_Reject;
755 if (strcasecmp(key, "ForceRestartAfterUpdate") == 0)
757 if (strcasecmp(value, "yes") == 0)
759 g_restartAfterUpdate = true;
760 return ConfigResult_Accept;
762 else if (strcasecmp(value, "no") == 0)
764 g_restartAfterUpdate = false;
765 return ConfigResult_Accept;
768 return ConfigResult_Reject;
771 if (strcasecmp(key, "AutoUpdateServer") == 0)
773 UTIL_Format(g_serverAddress, sizeof(g_serverAddress), "%s", value);
775 return ConfigResult_Accept;
778 if (strcasecmp(key, "AutoUpdatePort") == 0)
780 int port = atoi(value);
784 return ConfigResult_Reject;
789 return ConfigResult_Accept;
792 return ConfigResult_Ignore;
796 BuildMD5ableBuffer::BuildMD5ableBuffer()
798 stringTable = new BaseStringTable(2048);
801 BuildMD5ableBuffer::~BuildMD5ableBuffer()
806 void BuildMD5ableBuffer::ReadSMC_ParseStart()
808 stringTable->Reset();
811 SMCResult BuildMD5ableBuffer::ReadSMC_KeyValue(const SMCStates *states,
815 stringTable->AddString(key);
816 stringTable->AddString(value);
818 return SMCResult_Continue;
821 SMCResult BuildMD5ableBuffer::ReadSMC_NewSection(const SMCStates *states, const char *name)
823 stringTable->AddString(name);
825 return SMCResult_Continue;
828 void BuildMD5ableBuffer::ReadSMC_ParseEnd(bool halted, bool failed)
830 if (halted || failed)
835 void *data = stringTable->GetMemTable()->GetAddress(0);
839 checksum->update((unsigned char *)data, stringTable->GetMemTable()->GetActualMemUsed());
842 checksum->finalize();
845 CON_COMMAND(sm_gamedata_md5, "Checks the MD5 sum for a given gamedata file")
847 #if !defined ORANGEBOX_BUILD
853 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
857 const char *file = args.Arg(1);
858 if (!file || file[0] == '\0')
860 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
864 SourceHook::CVector<FileData *>::iterator iter = g_FetchThread.filenames.begin();
868 while (iter != g_FetchThread.filenames.end())
874 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), curData->filename->c_str());
876 if (strcmpi(fileName, file) == 0)
878 g_SMAPI->ConPrintf("MD5 Sum: %s\n", curData->checksum);
885 g_SMAPI->ConPrint("File not found!\n");
888 FetcherThread::~FetcherThread()
890 SourceHook::CVector<FileData *>::iterator iter = filenames.begin();
894 while (iter != filenames.end())
897 delete curData->filename;
899 iter = filenames.erase(iter);
903 FetcherThread::FetcherThread()
905 memtable = new BaseMemTable(4096);
907 needsRestart = false;