core/metamod_util.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Dec 10 00:59:50 2009 -0600 (2009-12-10)
changeset 689 4065ba5e9155
parent 658 8353605c1d97
child 705 a1001281dcb1
permissions -rw-r--r--
Rewrote user message caching code to always use IServerGameDLL::GetUserMessageInfo (bug 4117, r=dvander).

Games where the above function can crash are handled by detouring tier0's Error() function and jumping back to our own code. So in theory this should work on all games now.
     1 /**
     2  * vim: set ts=4 :
     3  * ======================================================
     4  * Metamod:Source
     5  * Copyright (C) 2004-2008 AlliedModders LLC and authors.
     6  * All rights reserved.
     7  * ======================================================
     8  *
     9  * This software is provided 'as-is', without any express or implied warranty.
    10  * In no event will the authors be held liable for any damages arising from 
    11  * the use of this software.
    12  * 
    13  * Permission is granted to anyone to use this software for any purpose, 
    14  * including commercial applications, and to alter it and redistribute it 
    15  * freely, subject to the following restrictions:
    16  *
    17  * 1. The origin of this software must not be misrepresented; you must not 
    18  * claim that you wrote the original software. If you use this software in a 
    19  * product, an acknowledgment in the product documentation would be 
    20  * appreciated but is not required.
    21  * 2. Altered source versions must be plainly marked as such, and must not be
    22  * misrepresented as being the original software.
    23  * 3. This notice may not be removed or altered from any source distribution.
    24  *
    25  * Version: $Id$
    26  */
    27 
    28 #include <ctype.h>
    29 #include <string.h>
    30 #include <stdio.h>
    31 #include "metamod_util.h"
    32 #include "metamod_oslink.h"
    33 
    34 /**
    35  * @brief Utility functions
    36  * @file util.cpp
    37  */
    38 
    39 const char *UTIL_GetExtension(const char *file)
    40 {
    41 	int len = strlen(file);
    42 	int i = 0;
    43 
    44 	for (i = len - 1; i >= 0; i--)
    45 	{
    46 		if (file[i] == '/' || file[i] == '\\')
    47 		{
    48 			return NULL;
    49 		}
    50 
    51 		if ((file[i] == '.') && (i != len - 1))
    52 		{
    53 			return (const char *)&(file[i + 1]);
    54 		}
    55 	}
    56 
    57 	return NULL;
    58 }
    59 
    60 void UTIL_TrimLeft(char *buffer)
    61 {
    62 	/* Let's think of this as our iterator */
    63 	char *i = buffer;
    64 
    65 	/* Make sure the buffer isn't null */
    66 	if (i && *i)
    67 	{
    68 		/* Add up number of whitespace characters */
    69 		while(isspace((unsigned char) *i))
    70 		{
    71 			i++;
    72 		}
    73 
    74 		/* If whitespace chars in buffer then adjust string so first non-whitespace char is at start of buffer */
    75 		if (i != buffer)
    76 		{
    77 			memmove(buffer, i, (strlen(i) + 1) * sizeof(char));
    78 		}
    79 	}
    80 }
    81 
    82 void UTIL_TrimRight(char *buffer)
    83 {
    84 	/* Make sure buffer isn't null */
    85 	if (buffer)
    86 	{
    87 		size_t len = strlen(buffer);
    88 
    89 		/* Loop through buffer backwards while replacing whitespace chars with null chars */
    90 		for (size_t i = len - 1; i >= 0; i--)
    91 		{
    92 			if (isspace((unsigned char) buffer[i]))
    93 			{
    94 				buffer[i] = '\0';
    95 			} else {
    96 				break;
    97 			}
    98 		}
    99 	}
   100 }
   101 
   102 bool UTIL_PathCmp(const char *path1, const char *path2)
   103 {
   104 	size_t pos1 = 0, pos2 = 0;
   105 
   106 	while (true)
   107 	{
   108 		if (path1[pos1] == '\0' || path2[pos2] == '\0')
   109 		{
   110 			return (path1[pos1] == path2[pos2]);
   111 		}
   112 
   113 		if (path1[pos1] == PATH_SEP_CHAR)
   114 		{
   115 			if (path2[pos2] != PATH_SEP_CHAR)
   116 			{
   117 				return false;
   118 			}
   119 
   120 			/* Look for extra path chars */
   121 			while (path1[++pos1])
   122 			{
   123 				if (path1[pos1] != PATH_SEP_CHAR)
   124 				{
   125 					break;
   126 				}
   127 			}
   128 			while (path2[++pos2])
   129 			{
   130 				if (path2[pos2] != PATH_SEP_CHAR)
   131 				{
   132 					break;
   133 				}
   134 			}
   135 			continue;
   136 		}
   137 
   138 		/* If we're at a different non-alphanumeric, the next character MUST match */
   139 		if ((((unsigned)path1[pos1] & 0x80) && path1[pos1] != path2[pos2])
   140 			||
   141 			!isalpha(path1[pos1]) && (path1[pos1] != path2[pos2])
   142 			)
   143 		{
   144 			return false;
   145 		}
   146 
   147 	#ifdef WIN32
   148 		if (toupper(path1[pos1]) != toupper(path2[pos2]))
   149 	#else
   150 		if (path1[pos1] != path2[pos2])
   151 	#endif
   152 		{
   153 			return false;
   154 		}
   155 
   156 		pos1++;
   157 		pos2++;
   158 	}
   159 }
   160 
   161 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
   162 {
   163 	va_list ap;
   164 
   165 	va_start(ap, fmt);
   166 	size_t len = vsnprintf(buffer, maxlength, fmt, ap);
   167 	va_end(ap);
   168 
   169 	if (len >= maxlength)
   170 	{
   171 		len = maxlength - 1;
   172 		buffer[len] = '\0';
   173 	}
   174 
   175 	return len;
   176 }
   177 
   178 size_t UTIL_FormatArgs(char *buffer, size_t maxlength, const char *fmt, va_list params)
   179 {
   180 	size_t len = vsnprintf(buffer, maxlength, fmt, params);
   181 
   182 	if (len >= maxlength)
   183 	{
   184 		len = maxlength - 1;
   185 		buffer[len] = '\0';
   186 	}
   187 
   188 	return len;
   189 }
   190 
   191 inline bool pathchar_isalpha(char a)
   192 {
   193 	return (((a & 1<<7) == 0) && isalpha(a));
   194 }
   195 
   196 inline bool pathchar_sep(char a)
   197 {
   198 #if defined WIN32
   199 	return (a == '/' || a == '\\');
   200 #elif defined __linux__
   201 	return (a == '/');
   202 #endif
   203 }
   204 
   205 inline bool pathstr_isabsolute(const char *str)
   206 {
   207 #if defined WIN32
   208 	return (pathchar_isalpha(str[0]) 
   209 		&& str[1] == ':' 
   210 		&& pathchar_sep(str[2]));
   211 #elif defined __linux__
   212 	return (str[0] == '/');
   213 #endif
   214 }
   215 
   216 inline bool pathchar_cmp(char a, char b)
   217 {
   218 #if defined WIN32
   219 	if (pathchar_isalpha(a) && pathchar_isalpha(b))
   220 	{
   221 		return (tolower(a) == tolower(b));
   222 	}
   223 	/* Either path separator is acceptable */
   224 	if (pathchar_sep(a))
   225 	{
   226 		return pathchar_sep(b);
   227 	}
   228 #endif
   229 	return (a == b);
   230 }
   231 
   232 /**
   233  * @brief Forms a relative path given two absolute paths.
   234  *
   235  * @param buffer		Buffer to store relative path in.
   236  * @param maxlength		Maximum length of the output buffer.
   237  * @param relTo			Destination folder to use as a working directory.
   238  *						Final folder name should not be pathchar-terminated.
   239  * @param relFrom		Source file or folder to use as a target.
   240  * @return				True on success, false on failure.
   241  */
   242 bool UTIL_Relatize(char buffer[],
   243 				   size_t maxlength,
   244 				   const char *relTo,
   245 				   const char *relFrom)
   246 {
   247 	/* We don't allow relative paths in here, force
   248 	 * the user to resolve these himself!
   249 	 */
   250 	if (!pathstr_isabsolute(relTo)
   251 		|| !pathstr_isabsolute(relFrom))
   252 	{
   253 		return false;
   254 	}
   255 
   256 #if defined WIN32
   257 	/* Relative paths across drives are not possible */
   258 	if (!pathchar_cmp(relTo[0], relFrom[0]))
   259 	{
   260 		return false;
   261 	}
   262 	/* Get rid of the drive and semicolon part */
   263 	relTo = &relTo[2];
   264 	relFrom = &relFrom[2];
   265 #endif
   266 
   267 	/* Eliminate the common root between the paths */
   268 	const char *rootTo = NULL;
   269 	const char *rootFrom = NULL;
   270 	while (*relTo != '\0' && *relFrom != '\0')
   271 	{
   272 		/* If we get to a new path sequence, start over */
   273 		if (pathchar_sep(*relTo)
   274 			&& pathchar_sep(*relFrom))
   275 		{
   276 			rootTo = relTo;
   277 			rootFrom = relFrom;
   278 		/* If the paths don't compare, stop looking for a common root */
   279 		} else if (!pathchar_cmp(*relTo, *relFrom)) {
   280 			break;
   281 		}
   282 		relTo++;
   283 		relFrom++;
   284 	}
   285 
   286 	/* NULLs shouldn't happen! */
   287 	if (rootTo == NULL
   288 		|| rootFrom == NULL)
   289 	{
   290 		return false;
   291 	}
   292 
   293 	size_t numLevels = 0;
   294 
   295 	/* The root case is special! 
   296 	 * Don't count anything from it.
   297 	 */
   298 	if (*(rootTo + 1) != '\0')
   299 	{
   300 		/* Search for how many levels we need to go up.
   301 	 	 * Since the root pointer points to a '/', we increment
   302 		 * the initial pointer by one.
   303 		 */
   304 		while (*rootTo != '\0')
   305 		{
   306 			if (pathchar_sep(*rootTo))
   307 			{
   308 				/* Check for an improper trailing slash,
   309 				 * just to be nice even though the user 
   310 				 * should NOT have done this!
   311 				 */
   312 				if (*(rootTo + 1) == '\0')
   313 				{
   314 					break;
   315 				}
   316 				numLevels++;
   317 			}
   318 			rootTo++;
   319 		}
   320 	}
   321 
   322 	/* Now build the new relative path. */
   323 	size_t len, total = 0;
   324 	while (numLevels--)
   325 	{
   326 		len = _snprintf(&buffer[total], maxlength - total, ".." PATH_SEP_STR);
   327 		if (len >= maxlength - total)
   328 		{
   329 			/* Not enough space in the buffer */
   330 			return false;
   331 		}
   332 		total += len;
   333 	}
   334 
   335 	/* Add the absolute path. */
   336 	len = _snprintf(&buffer[total], maxlength - total, "%s", &rootFrom[1]);
   337 	if (len >= maxlength - total)
   338 	{
   339 		return false;
   340 	}
   341 
   342 	return true;
   343 }
   344 
   345 bool UTIL_VerifySignature(const void *addr, const char *sig, size_t len)
   346 {
   347 	unsigned char *addr1 = (unsigned char *) addr;
   348 	unsigned char *addr2 = (unsigned char *) sig;
   349 
   350 	for (size_t i = 0; i < len; i++)
   351 	{
   352 		if (addr2[i] == '*')
   353 			continue;
   354 		if (addr1[i] != addr2[i])
   355 			return false;
   356 	}
   357 
   358 	return true;
   359 }