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
49 #include "sh_vector.h"
50 #include "sh_string.h"
51 #include "sm_version.h"
53 #ifdef ORANGEBOX_BUILD
54 #include "convar_sm_ob.h"
56 #include "convar_sm.h"
59 #include "sourcemm_api.h"
62 #include "compat_wrappers.h"
63 #include "sm_stringutil.h"
65 #define QUERY_MAX_LENGTH 1024
67 BuildMD5ableBuffer g_MD5Builder;
68 FetcherThread g_FetchThread;
72 bool g_disableGameDataUpdate = false;
73 bool g_restartAfterUpdate = false;
75 int g_serverPort = 6500;
76 char g_serverAddress[100] = "hayate.alliedmods.net";
78 void FetcherThread::RunThread( IThreadHandle *pHandle )
80 char lock_path[PLATFORM_MAX_PATH];
81 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp");
82 g_LibSys.CreateFolder(lock_path);
84 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
86 g_Logger.LogMessage("Starting experimental gamedata update fetcher... please report problems to bugs.alliedmods.net");
88 char log_path[PLATFORM_MAX_PATH];
89 g_SourceMod.BuildPath(Path_SM, log_path, sizeof(log_path), "logs/gamedata");
91 g_LibSys.CreateFolder(log_path);
95 tm *curtime = localtime(&t);
97 g_SourceMod.BuildPath(Path_SM, log_path, sizeof(log_path), "logs/gamedata/L%02d%02d.log", curtime->tm_mon + 1, curtime->tm_mday);
99 logfile = fopen(log_path, "a");
103 g_Logger.LogError("Failed to create GameData log file");
107 //Create a blank lock file
108 FILE *fp = fopen(lock_path, "w");
114 /* Create a new socket for this connection */
115 int socketDescriptor = ConnectSocket();
117 if (socketDescriptor == INVALID_SOCKET)
124 char query[QUERY_MAX_LENGTH];
126 /* Check for updated gamedata files */
127 int len = BuildGameDataQuery(query, QUERY_MAX_LENGTH);
131 g_Logger.LogToOpenFile(logfile, "Query Writing failed");
133 closesocket(socketDescriptor);
139 if (g_disableGameDataUpdate)
141 g_Logger.LogMessage("Skipping GameData Query due to DisableAutoUpdate being set to true");
143 closesocket(socketDescriptor);
149 int sent = NonBlockingSend(socketDescriptor, query, len);
151 g_Logger.LogToOpenFile(logfile, "Sent Query!");
155 g_Logger.LogToOpenFile(logfile, "Failed to send data");
157 closesocket(socketDescriptor);
163 ProcessGameDataQuery(socketDescriptor);
165 /* And we're done! */
166 closesocket(socketDescriptor);
171 void FetcherThread::OnTerminate( IThreadHandle *pHandle, bool cancel )
173 g_blockGameDataLoad = false;
176 int FetcherThread::BuildGameDataQuery( char *buffer, int maxlen )
178 char gamedata_path[PLATFORM_MAX_PATH];
179 g_SourceMod.BuildPath(Path_SM, gamedata_path, sizeof(gamedata_path), "gamedata");
181 IDirectory *dir = g_LibSys.OpenDirectory(gamedata_path);
188 bf_write Writer = bf_write("GameDataQuery", buffer, maxlen);
190 Writer.WriteByte('A'); //Generic Header char
191 Writer.WriteByte('G'); //G for gamedata query, or green, like my hat.
193 short build[4] = { SVN_FILE_VERSION };
195 Writer.WriteBytes(&build[0], 8);
197 Writer.WriteByte(0); // Initialize the file counter - Index 10
199 while (dir->MoreFiles())
201 if (dir->IsEntryFile())
203 const char *name = dir->GetEntryName();
204 size_t len = strlen(name);
206 && strcmp(&name[len-4], ".txt") == 0)
208 char file[PLATFORM_MAX_PATH];
210 g_LibSys.PathFormat(file, sizeof(file), "%s/%s", gamedata_path, name);
213 if (g_TextParser.ParseFile_SMC(file, &g_MD5Builder, &states) == SMCError_Okay)
215 unsigned char *md5 = g_MD5Builder.GetMD5();
218 (uint8_t)buffer[10]++; //Increment the file counter
219 Writer.WriteBytes(md5, 16);
221 g_Logger.LogToOpenFile(logfile, "%s - \"%s\"", file, g_MD5Builder.GetMD5String());
223 FileData *data = new FileData();
224 data->filename = new SourceHook::String(file);
225 memcpy(data->checksum, g_MD5Builder.GetMD5String(), 33);
226 filenames.push_back(data);
230 g_Logger.LogToOpenFile(logfile, "%s no md5?", file);
235 g_Logger.LogToOpenFile(logfile, "%s failed!", file);
243 return Writer.GetNumBytesWritten();
246 int FetcherThread::ConnectSocket()
248 struct protoent *ptrp;
249 ptrp = getprotobyname("tcp");
253 WSAStartup(0x0101, &wsaData);
258 g_Logger.LogToOpenFile(logfile, "Failed to find TCP");
259 return INVALID_SOCKET;
262 int socketDescriptor = socket(AF_INET, SOCK_STREAM, ptrp->p_proto);
264 if (socketDescriptor == INVALID_SOCKET)
267 g_Logger.LogToOpenFile(logfile, "Failed to create a new socket");
268 closesocket(socketDescriptor);
269 return INVALID_SOCKET;
273 struct sockaddr_in local_addr;
275 local_addr.sin_family = AF_INET;
276 local_addr.sin_port = htons((u_short)g_serverPort);
278 he = gethostbyname(g_serverAddress);
282 if ((local_addr.sin_addr.s_addr = inet_addr(g_serverAddress)) == INADDR_NONE)
284 g_Logger.LogToOpenFile(logfile, "Couldnt locate address");
285 closesocket(socketDescriptor);
286 return INVALID_SOCKET;
291 memcpy(&local_addr.sin_addr, (struct in_addr *)he->h_addr, he->h_length);
294 if (connect(socketDescriptor, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0)
296 g_Logger.LogToOpenFile(logfile, "Couldn't connect");
297 closesocket(socketDescriptor);
298 return INVALID_SOCKET;
301 return socketDescriptor;
304 void FetcherThread::ProcessGameDataQuery(int socketDescriptor)
308 g_Logger.LogToOpenFile(logfile, "Waiting for reply!");
310 //Read in the header bytes
311 int returnLen = NonBlockingRecv(socketDescriptor, buffer, 12);
313 g_Logger.LogToOpenFile(logfile, "Recv Completed");
317 g_Logger.LogToOpenFile(logfile, ",but it failed.");
318 /* Timeout or fail? */
322 g_Logger.LogToOpenFile(logfile, "Received Header!");
324 bf_read Reader = bf_read("GameDataQuery", buffer, 12);
326 if (Reader.ReadByte() != 'A' || Reader.ReadByte() != 'G')
328 g_Logger.LogToOpenFile(logfile, "Invalid Query to handle");
332 UpdateStatus updateStatus = (UpdateStatus)Reader.ReadByte();
334 short build[4] = {0,0,0,0};
336 build[0] = Reader.ReadShort();
337 build[1] = Reader.ReadShort();
338 build[2] = Reader.ReadShort();
339 build[3] = Reader.ReadShort();
341 g_Logger.LogToOpenFile(logfile, "Update Status: %i - Latest %i.%i.%i.%i", updateStatus, build[0], build[1], build[2], build[3]);
343 HandleUpdateStatus(updateStatus, build);
345 int changedFiles = Reader.ReadByte();
347 g_Logger.LogToOpenFile(logfile, "Files to download: %i", changedFiles);
349 for (int i=0; i<changedFiles; i++)
351 //Read in the file index and byte count
352 returnLen = NonBlockingRecv(socketDescriptor, buffer, 5);
356 /* Timeout or fail? */
360 Reader.StartReading(buffer, 5);
362 int index = Reader.ReadByte();
363 int tempLen = Reader.ReadUBitLong(32);
365 g_Logger.LogToOpenFile(logfile, "File index %i and length %i", index, tempLen);
368 memtable->CreateMem(tempLen+1, &memPtr);
370 //Read the contents of our file into the memtable
371 returnLen = NonBlockingRecv(socketDescriptor, (char *)memPtr, tempLen);
373 g_Logger.LogToOpenFile(logfile, "Recieved %i bytes", returnLen);
377 /* Timeout or fail? */
381 ((unsigned char *)memPtr)[tempLen] = '\0';
383 FileData *data = filenames.at(index);
384 const char* filename;
387 filename = data->filename->c_str();
389 FILE *fp = fopen(filename, "w");
393 fprintf(fp, (const char *)memPtr);
404 g_Logger.LogToOpenFile(logfile, "Updated File %s", filename);
407 g_Logger.LogToOpenFile(logfile, "File Downloads Completed!");
409 bool needsRestart = false;
411 if (changedFiles > 0)
414 g_Logger.LogMessage("New GameData Files have been downloaded to your gamedata directory. Please restart your server for these to take effect");
417 //Read changed file count
418 returnLen = NonBlockingRecv(socketDescriptor, buffer, 1);
422 /* Timeout or fail? */
423 g_Logger.LogToOpenFile(logfile, "Failed to receive unknown count");
427 Reader.StartReading(buffer, 1);
429 changedFiles = Reader.ReadByte();
431 if (changedFiles == 0)
433 g_Logger.LogToOpenFile(logfile, "No unknown files. We're all done");
437 char *changedFileIndexes = new char[changedFiles];
439 g_Logger.LogToOpenFile(logfile, "%i Files were unknown", changedFiles);
441 returnLen = NonBlockingRecv(socketDescriptor, changedFileIndexes, changedFiles);
445 /* Timeout or fail? */
446 g_Logger.LogToOpenFile(logfile, "Failed to receive unknown list");
450 Reader.StartReading(changedFileIndexes, changedFiles);
452 for (int i=0; i<changedFiles; i++)
454 int index = Reader.ReadByte();
457 FileData *data = filenames.at(index);
458 const char* pathname;
461 pathname = data->filename->c_str();
468 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), pathname);
470 g_Logger.LogToOpenFile(logfile, "Unknown File %i : %s", index, fileName);
473 delete [] changedFileIndexes;
475 if (needsRestart && g_restartAfterUpdate)
477 g_Logger.LogMessage("Automatically restarting server after a successful gamedata update!");
478 engine->ServerCommand("quit\n");
482 int FetcherThread::NonBlockingRecv( int socketDescriptor, char *buffer, int len )
487 /* Create a 10 Second Timeout */
491 /* Add our socket to a socket set */
493 FD_SET(socketDescriptor, &fds);
495 /* Wait max of 10 seconds for recv to become available */
496 select(socketDescriptor+1, &fds, NULL, NULL, &tv);
498 int bytesReceived = 0;
500 /* Is there a limit on how much we can receive? Some site said 1024 bytes, which will be well short of a file */
501 if (FD_ISSET(socketDescriptor, &fds))
503 bytesReceived = recv(socketDescriptor, buffer, len, 0);
506 if (bytesReceived == 0 || bytesReceived == -1)
511 if (bytesReceived < len)
513 return bytesReceived + NonBlockingRecv(socketDescriptor, buffer+bytesReceived, len-bytesReceived);
516 return bytesReceived;
519 int FetcherThread::NonBlockingSend( int socketDescriptor, char *buffer, int len )
528 FD_SET(socketDescriptor, &fds);
530 select(socketDescriptor+1, NULL, &fds, NULL, &tv);
534 if (FD_ISSET(socketDescriptor, &fds))
536 sentBytes = send(socketDescriptor, buffer, len, 0);
539 if (sentBytes == 0 || sentBytes == -1)
546 return sentBytes + NonBlockingSend(socketDescriptor, buffer+sentBytes, len-sentBytes);
552 void FetcherThread::HandleUpdateStatus( UpdateStatus status, short version[4] )
562 case Update_NewBuild:
564 g_Logger.LogMessage("SourceMod Update: A new SVN build is available from sourcemod.net");
565 g_Logger.LogMessage("Current Version: %i.%i.%i.%i Available: %i.%i.%i.%i", version[0], version[1], version[2], version[3], version[0], version[1], version[2], version[3]);
569 case Update_MinorAvailable:
571 g_Logger.LogMessage("SourceMod Update: An incremental minor release of SourceMod is now available from sourcemod.net");
572 g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
576 case Update_MajorAvailable:
578 g_Logger.LogMessage("SourceMod Update: An major release of SourceMod is now available from sourcemod.net");
579 g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
583 case Update_CriticalAvailable:
585 g_Logger.LogError("SourceMod Update: A new critical release of SourceMod is now available from sourcemod.net. It is strongly recommended that you update");
586 g_Logger.LogMessage("Current Version: %i.%i.%i.%i Available: %i.%i.%i.%i", version[0], version[1], version[2], version[3], version[0], version[1], version[2], version[3]);
592 bool g_blockGameDataLoad = false;
594 class InitFetch : public SMGlobalClass
597 void OnSourceModAllInitialized_Post()
599 char lock_path[PLATFORM_MAX_PATH];
600 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
602 if (g_LibSys.IsPathFile(lock_path) && g_LibSys.PathExists(lock_path))
604 g_Logger.LogError("sourcemod/data/temp/gamedata.lock file detected. This is most likely due to a crash during GameData updating - Blocking GameData loading");
605 g_Logger.LogError("If this error persists delete the file manually");
606 g_blockGameDataLoad = true;
609 ThreadParams fetchThreadParams = ThreadParams();
610 fetchThreadParams.prio = ThreadPrio_Low;
611 g_pThreader->MakeThread(&g_FetchThread, &fetchThreadParams);
614 ConfigResult OnSourceModConfigChanged(const char *key,
620 if (strcmp(key, "DisableAutoUpdate") == 0)
622 if (strcmp(value, "yes") == 0)
624 g_disableGameDataUpdate = true;
625 return ConfigResult_Accept;
627 else if (strcmp(value, "no") == 0)
629 g_disableGameDataUpdate = false;
630 return ConfigResult_Accept;
633 return ConfigResult_Reject;
636 if (strcmp(key, "ForceRestartAfterUpdate") == 0)
638 if (strcmp(value, "yes") == 0)
640 g_restartAfterUpdate = true;
641 return ConfigResult_Accept;
643 else if (strcmp(value, "no") == 0)
645 g_restartAfterUpdate = false;
646 return ConfigResult_Accept;
649 return ConfigResult_Reject;
652 if (strcmp(key, "AutoUpdateServer") == 0)
654 UTIL_Format(g_serverAddress, sizeof(g_serverAddress), "%s", value);
656 return ConfigResult_Accept;
659 if (strcmp(key, "AutoUpdatePort") == 0)
661 int port = atoi(value);
665 return ConfigResult_Reject;
670 return ConfigResult_Accept;
673 return ConfigResult_Ignore;
677 CON_COMMAND(sm_gamedata_md5, "Checks the MD5 sum for a given gamedata file")
679 #if !defined ORANGEBOX_BUILD
685 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
689 const char *file = args.Arg(1);
690 if (!file || file[0] == '\0')
692 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
696 SourceHook::CVector<FileData *>::iterator iter = g_FetchThread.filenames.begin();
700 while (iter != g_FetchThread.filenames.end())
706 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), curData->filename->c_str());
708 if (strcmpi(fileName, file) == 0)
710 g_SMAPI->ConPrintf("MD5 Sum: %s\n", curData->checksum);
717 g_SMAPI->ConPrint("File not found!\n");