Initial Import of beta structs extension.
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"
64 #define QUERY_MAX_LENGTH 1024
66 BuildMD5ableBuffer g_MD5Builder;
67 FetcherThread g_FetchThread;
71 bool g_disableGameDataUpdate = false;
72 bool g_restartAfterUpdate = false;
74 void FetcherThread::RunThread( IThreadHandle *pHandle )
76 char lock_path[PLATFORM_MAX_PATH];
77 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp");
78 g_LibSys.CreateFolder(lock_path);
80 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
82 g_Logger.LogMessage("Starting experimental gamedata update fetcher... please report problems to bugs.alliedmods.net");
84 char log_path[PLATFORM_MAX_PATH];
85 g_SourceMod.BuildPath(Path_SM, log_path, sizeof(log_path), "logs/gamedata");
87 g_LibSys.CreateFolder(log_path);
91 tm *curtime = localtime(&t);
93 g_SourceMod.BuildPath(Path_SM, log_path, sizeof(log_path), "logs/gamedata/L%02d%02d.log", curtime->tm_mon + 1, curtime->tm_mday);
95 logfile = fopen(log_path, "a");
99 g_Logger.LogError("Failed to create GameData log file");
103 //Create a blank lock file
104 FILE *fp = fopen(lock_path, "w");
110 /* Create a new socket for this connection */
111 int socketDescriptor = ConnectSocket();
113 if (socketDescriptor == INVALID_SOCKET)
120 char query[QUERY_MAX_LENGTH];
122 /* Check for updated gamedata files */
123 int len = BuildGameDataQuery(query, QUERY_MAX_LENGTH);
127 g_Logger.LogToOpenFile(logfile, "Query Writing failed");
129 closesocket(socketDescriptor);
135 if (g_disableGameDataUpdate)
137 g_Logger.LogMessage("Skipping GameData Query due to DisableAutoUpdate being set to true");
139 closesocket(socketDescriptor);
145 int sent = NonBlockingSend(socketDescriptor, query, len);
147 g_Logger.LogToOpenFile(logfile, "Sent Query!");
151 g_Logger.LogToOpenFile(logfile, "Failed to send data");
153 closesocket(socketDescriptor);
159 ProcessGameDataQuery(socketDescriptor);
161 /* And we're done! */
162 closesocket(socketDescriptor);
167 void FetcherThread::OnTerminate( IThreadHandle *pHandle, bool cancel )
169 g_blockGameDataLoad = false;
172 int FetcherThread::BuildGameDataQuery( char *buffer, int maxlen )
174 char gamedata_path[PLATFORM_MAX_PATH];
175 g_SourceMod.BuildPath(Path_SM, gamedata_path, sizeof(gamedata_path), "gamedata");
177 IDirectory *dir = g_LibSys.OpenDirectory(gamedata_path);
184 bf_write Writer = bf_write("GameDataQuery", buffer, maxlen);
186 Writer.WriteByte('A'); //Generic Header char
187 Writer.WriteByte('G'); //G for gamedata query, or green, like my hat.
189 short build[4] = { SVN_FILE_VERSION };
191 Writer.WriteBytes(&build[0], 8);
193 Writer.WriteByte(0); // Initialize the file counter - Index 10
195 while (dir->MoreFiles())
197 if (dir->IsEntryFile())
199 const char *name = dir->GetEntryName();
200 size_t len = strlen(name);
202 && strcmp(&name[len-4], ".txt") == 0)
204 char file[PLATFORM_MAX_PATH];
206 g_LibSys.PathFormat(file, sizeof(file), "%s/%s", gamedata_path, name);
209 if (g_TextParser.ParseFile_SMC(file, &g_MD5Builder, &states) == SMCError_Okay)
211 unsigned char *md5 = g_MD5Builder.GetMD5();
214 (uint8_t)buffer[10]++; //Increment the file counter
215 Writer.WriteBytes(md5, 16);
217 g_Logger.LogToOpenFile(logfile, "%s - \"%s\"", file, g_MD5Builder.GetMD5String());
219 FileData *data = new FileData();
220 data->filename = new SourceHook::String(file);
221 memcpy(data->checksum, g_MD5Builder.GetMD5String(), 33);
222 filenames.push_back(data);
226 g_Logger.LogToOpenFile(logfile, "%s no md5?", file);
231 g_Logger.LogToOpenFile(logfile, "%s failed!", file);
239 return Writer.GetNumBytesWritten();
242 int FetcherThread::ConnectSocket()
244 struct protoent *ptrp;
245 ptrp = getprotobyname("tcp");
249 WSAStartup(0x0101, &wsaData);
254 g_Logger.LogToOpenFile(logfile, "Failed to find TCP");
255 return INVALID_SOCKET;
258 int socketDescriptor = socket(AF_INET, SOCK_STREAM, ptrp->p_proto);
260 if (socketDescriptor == INVALID_SOCKET)
263 g_Logger.LogToOpenFile(logfile, "Failed to create a new socket");
264 closesocket(socketDescriptor);
265 return INVALID_SOCKET;
269 struct sockaddr_in local_addr;
271 local_addr.sin_family = AF_INET;
272 local_addr.sin_port = htons((u_short)6500);
274 he = gethostbyname("hayate.alliedmods.net");
278 if ((local_addr.sin_addr.s_addr = inet_addr("hayate.alliedmods.net")) == INADDR_NONE)
280 g_Logger.LogToOpenFile(logfile, "Couldnt locate address");
281 closesocket(socketDescriptor);
282 return INVALID_SOCKET;
287 memcpy(&local_addr.sin_addr, (struct in_addr *)he->h_addr, he->h_length);
290 if (connect(socketDescriptor, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0)
292 g_Logger.LogToOpenFile(logfile, "Couldn't connect");
293 closesocket(socketDescriptor);
294 return INVALID_SOCKET;
297 return socketDescriptor;
300 void FetcherThread::ProcessGameDataQuery(int socketDescriptor)
304 g_Logger.LogToOpenFile(logfile, "Waiting for reply!");
306 //Read in the header bytes
307 int returnLen = NonBlockingRecv(socketDescriptor, buffer, 12);
309 g_Logger.LogToOpenFile(logfile, "Recv Completed");
313 g_Logger.LogToOpenFile(logfile, ",but it failed.");
314 /* Timeout or fail? */
318 g_Logger.LogToOpenFile(logfile, "Received Header!");
320 bf_read Reader = bf_read("GameDataQuery", buffer, 12);
322 if (Reader.ReadByte() != 'A' || Reader.ReadByte() != 'G')
324 g_Logger.LogToOpenFile(logfile, "Invalid Query to handle");
328 UpdateStatus updateStatus = (UpdateStatus)Reader.ReadByte();
330 short build[4] = {0,0,0,0};
332 build[0] = Reader.ReadShort();
333 build[1] = Reader.ReadShort();
334 build[2] = Reader.ReadShort();
335 build[3] = Reader.ReadShort();
337 g_Logger.LogToOpenFile(logfile, "Update Status: %i - Latest %i.%i.%i.%i", updateStatus, build[0], build[1], build[2], build[3]);
339 HandleUpdateStatus(updateStatus, build);
341 int changedFiles = Reader.ReadByte();
343 g_Logger.LogToOpenFile(logfile, "Files to download: %i", changedFiles);
345 for (int i=0; i<changedFiles; i++)
347 //Read in the file index and byte count
348 returnLen = NonBlockingRecv(socketDescriptor, buffer, 5);
352 /* Timeout or fail? */
356 Reader.StartReading(buffer, 5);
358 int index = Reader.ReadByte();
359 int tempLen = Reader.ReadUBitLong(32);
361 g_Logger.LogToOpenFile(logfile, "File index %i and length %i", index, tempLen);
364 memtable->CreateMem(tempLen+1, &memPtr);
366 //Read the contents of our file into the memtable
367 returnLen = NonBlockingRecv(socketDescriptor, (char *)memPtr, tempLen);
369 g_Logger.LogToOpenFile(logfile, "Recieved %i bytes", returnLen);
373 /* Timeout or fail? */
377 ((unsigned char *)memPtr)[tempLen] = '\0';
379 FileData *data = filenames.at(index);
380 const char* filename;
383 filename = data->filename->c_str();
385 FILE *fp = fopen(filename, "w");
389 fprintf(fp, (const char *)memPtr);
400 g_Logger.LogToOpenFile(logfile, "Updated File %s", filename);
403 g_Logger.LogToOpenFile(logfile, "File Downloads Completed!");
405 bool needsRestart = false;
407 if (changedFiles > 0)
410 g_Logger.LogMessage("New GameData Files have been downloaded to your gamedata directory. Please restart your server for these to take effect");
413 //Read changed file count
414 returnLen = NonBlockingRecv(socketDescriptor, buffer, 1);
418 /* Timeout or fail? */
419 g_Logger.LogToOpenFile(logfile, "Failed to receive unknown count");
423 Reader.StartReading(buffer, 1);
425 changedFiles = Reader.ReadByte();
427 if (changedFiles == 0)
429 g_Logger.LogToOpenFile(logfile, "No unknown files. We're all done");
433 char *changedFileIndexes = new char[changedFiles];
435 g_Logger.LogToOpenFile(logfile, "%i Files were unknown", changedFiles);
437 returnLen = NonBlockingRecv(socketDescriptor, changedFileIndexes, changedFiles);
441 /* Timeout or fail? */
442 g_Logger.LogToOpenFile(logfile, "Failed to receive unknown list");
446 Reader.StartReading(changedFileIndexes, changedFiles);
448 for (int i=0; i<changedFiles; i++)
450 int index = Reader.ReadByte();
453 FileData *data = filenames.at(index);
454 const char* pathname;
457 pathname = data->filename->c_str();
464 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), pathname);
466 g_Logger.LogToOpenFile(logfile, "Unknown File %i : %s", index, fileName);
469 delete [] changedFileIndexes;
471 if (needsRestart && g_restartAfterUpdate)
473 g_Logger.LogMessage("Automatically restarting server after a successful gamedata update!");
474 engine->ServerCommand("quit\n");
478 int FetcherThread::NonBlockingRecv( int socketDescriptor, char *buffer, int len )
483 /* Create a 10 Second Timeout */
487 /* Add our socket to a socket set */
489 FD_SET(socketDescriptor, &fds);
491 /* Wait max of 10 seconds for recv to become available */
492 select(socketDescriptor+1, &fds, NULL, NULL, &tv);
494 int bytesReceived = 0;
496 /* Is there a limit on how much we can receive? Some site said 1024 bytes, which will be well short of a file */
497 if (FD_ISSET(socketDescriptor, &fds))
499 bytesReceived = recv(socketDescriptor, buffer, len, 0);
502 if (bytesReceived == 0 || bytesReceived == -1)
507 if (bytesReceived < len)
509 return bytesReceived + NonBlockingRecv(socketDescriptor, buffer+bytesReceived, len-bytesReceived);
512 return bytesReceived;
515 int FetcherThread::NonBlockingSend( int socketDescriptor, char *buffer, int len )
524 FD_SET(socketDescriptor, &fds);
526 select(socketDescriptor+1, NULL, &fds, NULL, &tv);
530 if (FD_ISSET(socketDescriptor, &fds))
532 sentBytes = send(socketDescriptor, buffer, len, 0);
535 if (sentBytes == 0 || sentBytes == -1)
542 return sentBytes + NonBlockingSend(socketDescriptor, buffer+sentBytes, len-sentBytes);
548 void FetcherThread::HandleUpdateStatus( UpdateStatus status, short version[4] )
558 case Update_NewBuild:
560 g_Logger.LogMessage("SourceMod Update: A new SVN build is available from sourcemod.net");
561 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]);
565 case Update_MinorAvailable:
567 g_Logger.LogMessage("SourceMod Update: An incremental minor release of SourceMod is now available from sourcemod.net");
568 g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
572 case Update_MajorAvailable:
574 g_Logger.LogMessage("SourceMod Update: An major release of SourceMod is now available from sourcemod.net");
575 g_Logger.LogMessage("Current Version: %i.%i.%i Available: %i.%i.%i", version[0], version[1], version[2], version[0], version[1], version[2]);
579 case Update_CriticalAvailable:
581 g_Logger.LogError("SourceMod Update: A new critical release of SourceMod is now available from sourcemod.net. It is strongly recommended that you update");
582 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]);
588 bool g_blockGameDataLoad = false;
590 class InitFetch : public SMGlobalClass
593 void OnSourceModAllInitialized_Post()
595 char lock_path[PLATFORM_MAX_PATH];
596 g_SourceMod.BuildPath(Path_SM, lock_path, sizeof(lock_path), "data/temp/gamedata.lock");
598 if (g_LibSys.IsPathFile(lock_path) && g_LibSys.PathExists(lock_path))
600 g_Logger.LogError("sourcemod/data/temp/gamedata.lock file detected. This is most likely due to a crash during GameData updating - Blocking GameData loading");
601 g_Logger.LogError("If this error persists delete the file manually");
602 g_blockGameDataLoad = true;
605 ThreadParams fetchThreadParams = ThreadParams();
606 fetchThreadParams.prio = ThreadPrio_Low;
607 g_pThreader->MakeThread(&g_FetchThread, &fetchThreadParams);
610 ConfigResult OnSourceModConfigChanged(const char *key,
616 if (strcmp(key, "DisableAutoUpdate") == 0)
618 if (strcmp(value, "yes") == 0)
620 g_disableGameDataUpdate = true;
621 return ConfigResult_Accept;
623 else if (strcmp(value, "no") == 0)
625 g_disableGameDataUpdate = false;
626 return ConfigResult_Accept;
629 return ConfigResult_Reject;
632 if (strcmp(key, "ForceRestartAfterUpdate") == 0)
634 if (strcmp(value, "yes") == 0)
636 g_restartAfterUpdate = true;
637 return ConfigResult_Accept;
639 else if (strcmp(value, "no") == 0)
641 g_restartAfterUpdate = false;
642 return ConfigResult_Accept;
645 return ConfigResult_Reject;
648 return ConfigResult_Ignore;
652 CON_COMMAND(sm_gamedata_md5, "Checks the MD5 sum for a given gamedata file")
654 #if !defined ORANGEBOX_BUILD
660 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
664 const char *file = args.Arg(1);
665 if (!file || file[0] == '\0')
667 g_SMAPI->ConPrint("Usage: sm_gamedata_md5 <file>\n");
671 SourceHook::CVector<FileData *>::iterator iter = g_FetchThread.filenames.begin();
675 while (iter != g_FetchThread.filenames.end())
681 g_LibSys.GetFileFromPath(fileName, sizeof(fileName), curData->filename->c_str());
683 if (strcmpi(fileName, file) == 0)
685 g_SMAPI->ConPrintf("MD5 Sum: %s\n", curData->checksum);
692 g_SMAPI->ConPrint("File not found!\n");