metamod/mplugin.cpp
author darope
Thu Nov 11 23:21:08 2004 +0000 (2004-11-11)
changeset 246 962d2947c6d6
parent 245 e2e3739f6ccd
child 247 2b1bf332bf41
permissions -rw-r--r--
Merged with B-work for release 1.17.3
     1 // vi: set ts=4 sw=4 :
     2 // vim: set tw=75 :
     3 
     4 // mplugin.cpp - functions for individual plugin (class MPlugin)
     5 
     6 /*
     7  * Copyright (c) 2001-2003 Will Day <[email protected]>
     8  *
     9  *    This file is part of Metamod.
    10  *
    11  *    Metamod is free software; you can redistribute it and/or modify it
    12  *    under the terms of the GNU General Public License as published by the
    13  *    Free Software Foundation; either version 2 of the License, or (at
    14  *    your option) any later version.
    15  *
    16  *    Metamod is distributed in the hope that it will be useful, but
    17  *    WITHOUT ANY WARRANTY; without even the implied warranty of
    18  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    19  *    General Public License for more details.
    20  *
    21  *    You should have received a copy of the GNU General Public License
    22  *    along with Metamod; if not, write to the Free Software Foundation,
    23  *    Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    24  *
    25  *    In addition, as a special exception, the author gives permission to
    26  *    link the code of this program with the Half-Life Game Engine ("HL
    27  *    Engine") and Modified Game Libraries ("MODs") developed by Valve,
    28  *    L.L.C ("Valve").  You must obey the GNU General Public License in all
    29  *    respects for all of the code used other than the HL Engine and MODs
    30  *    from Valve.  If you modify this file, you may extend this exception
    31  *    to your version of the file, but you are not obligated to do so.  If
    32  *    you do not wish to do so, delete this exception statement from your
    33  *    version.
    34  *
    35  */
    36 
    37 #include <errno.h>				// errno, etc
    38 #include <malloc.h>				// malloc, etc
    39 #include <sys/types.h>			// stat
    40 #include <sys/stat.h>			// stat
    41 
    42 #include <extdll.h>				// always
    43 
    44 #include "mplugin.h"			// me
    45 #include "metamod.h"			// GameDLL, etc
    46 #include "mreg.h"				// MRegCmdList::show(int), etc
    47 #include "mhook.h"				// class MHook
    48 #include "h_export.h"			// GIVE_ENGINE_FUNCTIONS_FN, etc
    49 #include "dllapi.h"				// FN_GAMEINIT, etc
    50 #include "support_meta.h"		// full_gamedir_path,
    51 #include "types_meta.h"			// mBOOL
    52 #include "log_meta.h"			// logging functions, etc
    53 #include "osdep.h"				// win32 snprintf, is_absolute_path,
    54 
    55 
    56 // Parse a line from plugins.ini into a plugin.
    57 // meta_errno values:
    58 //  - ME_COMMENT	ignored commented line
    59 //  - ME_FORMAT		invalid line format
    60 //  - ME_OSNOTSUP	plugin is not for this OS
    61 mBOOL MPlugin::ini_parseline(char *line) {
    62 	char *token;
    63 	char *ptr_token;
    64 	char *cp;
    65 
    66 	// skip whitespace at start of line
    67 	while(*line==' ' || *line=='\t' ) line++;
    68 
    69 	// remove whitespace at end of line
    70 	cp = line + strlen(line) -1;
    71 	while(*cp==' ' || *cp=='\t') *cp--='\0';
    72 
    73 	// skip empty lines
    74 	if(line[0]=='\0') {
    75 		META_DEBUG(7, ("ini: Ignoring empty line: %s", line));
    76 		RETURN_ERRNO(mFALSE, ME_BLANK);
    77 	}
    78 
    79 	if(line[0]=='#' || line[0]==';' || strstr(line, "//")==line) {
    80 		META_DEBUG(7, ("ini: Ignoring commented line: %s", line));
    81 		RETURN_ERRNO(mFALSE, ME_COMMENT);
    82 	}
    83 
    84 	// grab platform ("win32" or "linux")
    85 	token=strtok_r(line, " \t", &ptr_token);
    86 	if(!token)
    87 		RETURN_ERRNO(mFALSE, ME_FORMAT);
    88 	if(strcasecmp(token, PLATFORM) == 0) {
    89 		pfspecific=0;
    90 	} else if(strcasecmp(token, PLATFORM_SPC) == 0) {
    91 		pfspecific=1;
    92 	} else {
    93 		// plugin is not for this OS
    94 		META_DEBUG(7, ("ini: Ignoring entry for %s", token));
    95 		RETURN_ERRNO(mFALSE, ME_OSNOTSUP);
    96 	}
    97 
    98 	// grab filename
    99 	token=strtok_r(NULL, " \t\r\n", &ptr_token);
   100 	if(!token)
   101 		RETURN_ERRNO(mFALSE, ME_FORMAT);
   102 	STRNCPY(filename, token, sizeof(filename));
   103 	normalize_pathname(filename);
   104 	// Store name of just the actual _file_, without dir components.
   105 	cp=strrchr(filename, '/');
   106 	if(cp)
   107 		file=cp+1;
   108 	else
   109 		file=filename;
   110 
   111 	// Grab description.
   112 	// Just get the the rest of the line, minus line-termination.
   113 	token=strtok_r(NULL, "\n\r", &ptr_token);
   114 	if(token) {
   115 		token=token+strspn(token, " \t");			// skip whitespace
   116 		STRNCPY(desc, token, sizeof(desc));
   117 	}
   118 	else {
   119 		// If no description is specified, temporarily use plugin file,
   120 		// until plugin can be queried, and desc replaced with info->name.
   121 		snprintf(desc, sizeof(desc), "<%s>", file);
   122 	}
   123 
   124 	// Make full pathname (from gamedir if relative, remove "..",
   125 	// backslashes, etc).
   126 	full_gamedir_path(filename, pathname);
   127 
   128 	source=PS_INI;
   129 	status=PL_VALID;
   130 	return(mTRUE);
   131 }
   132 
   133 // Parse a line from console "load" command into a plugin.
   134 // meta_errno values:
   135 //  - ME_FORMAT		invalid line format
   136 mBOOL MPlugin::cmd_parseline(const char *line) {
   137 	char buf[NAME_MAX + PATH_MAX + MAX_DESC_LEN];
   138 	char *token;
   139 	char *ptr_token;
   140 	char *cp;
   141 
   142 	STRNCPY(buf, line, sizeof(buf));
   143 
   144 	// remove "load"
   145 	token=strtok_r(buf, " \t", &ptr_token);
   146 	if(!token)
   147 		RETURN_ERRNO(mFALSE, ME_FORMAT);
   148 
   149 	// grab filename
   150 	token=strtok_r(NULL, " \t", &ptr_token);
   151 	if(!token)
   152 		RETURN_ERRNO(mFALSE, ME_FORMAT);
   153 	STRNCPY(filename, token, sizeof(filename));
   154 	normalize_pathname(filename);
   155 	// store name of just the actual _file_, without dir components
   156 	cp=strrchr(filename, '/');
   157 	if(cp)
   158 		file=cp+1;
   159 	else
   160 		file=filename;
   161 
   162 	// Grab description.
   163 	// Specify no delimiter chars, as we just want the rest of the line.
   164 	token=strtok_r(NULL, "", &ptr_token);
   165 	if(token) {
   166 		token=token+strspn(token, " \t");			// skip whitespace
   167 		STRNCPY(desc, token, sizeof(desc));
   168 	}
   169 	else {
   170 		// if no description is specified, temporarily use plugin file,
   171 		// until plugin can be queried, and desc replaced with info->name.
   172 		snprintf(desc, sizeof(desc), "<%s>", file);
   173 	}
   174 
   175 	// Make full pathname (from gamedir if relative, remove "..",
   176 	// backslashes, etc).
   177 	full_gamedir_path(filename, pathname);
   178 
   179 	source=PS_CMD;
   180 	status=PL_VALID;
   181 	return(mTRUE);
   182 }
   183 
   184 // Make sure this plugin has the necessary minimal information.
   185 // meta_errno values:
   186 //  - ME_ARGUMENT	missing necessary fields in plugin
   187 mBOOL MPlugin::check_input(void) {
   188 	// doublecheck our input/state
   189 	if(status < PL_VALID) {
   190 		META_ERROR("dll: Tried to operate on plugin[%d] with a non-valid status (%d)", index, str_status());
   191 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   192 	}
   193 	if(!file || !file[0]) {
   194 		META_ERROR("dll: Tried to operate on plugin[%d] with an empty file", 
   195 				index);
   196 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   197 	}
   198 	if(!filename[0]) {
   199 		META_ERROR("dll: Tried to operate on plugin[%d] with an empty filename",
   200 				index);
   201 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   202 	}
   203 	if(!pathname[0]) {
   204 		META_ERROR("dll: Tried to operate on plugin[%d] with an empty pathname",
   205 				index);
   206 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   207 	}
   208 	if(!desc[0]) {
   209 		// if no description is specified, temporarily use plugin file,
   210 		// until plugin can be queried, and desc replaced with info->name.
   211 		snprintf(desc, sizeof(desc), "<%s>", file);
   212 	}
   213 	return(mTRUE);
   214 }
   215 
   216 // Try to resolve a plugin's filename as a (possibly partial) path to an
   217 // actual filename on disk, to facilitate easier console load-command
   218 // arguments.  Uses resolve_dirs, resolve_prefix, and resolve_suffix below.  
   219 // Example paths that it tries:
   220 //    filename
   221 //    Gamedir/filename.dll, Gamedir/filename.so
   222 //    Gamedir/filename_i386.so
   223 //    Gamedir/dlls/mm_filename_i386.so
   224 //    Gamedir/dlls/filename_mm_i386.so
   225 //    Gamedir/dlls/filename_MM_i386.so
   226 // meta_errno values:
   227 //  - ME_NOTFOUND	couldn't find a matching file for the partial name
   228 //  - errno's from check_input()
   229 mBOOL MPlugin::resolve(void) {
   230 	char *found;
   231 	char *cp;
   232 	int len;
   233 	if(!check_input()) {
   234 		// details logged, meta_errno set in check_input()
   235 		return(mFALSE);
   236 	}
   237 	if(is_absolute_path(filename))
   238 		found=resolve_prefix(filename);
   239 	else
   240 		found=resolve_dirs(filename);
   241 
   242 	if(!found) {
   243 		META_DEBUG(2, ("Couldn't resolve '%s' to file", filename));
   244 		RETURN_ERRNO(mFALSE, ME_NOTFOUND);
   245 	}
   246 	META_DEBUG(2, ("Resolved '%s' to file '%s'", filename, found));
   247 	// store pathname: the resolved path (should be absolute)
   248 	STRNCPY(pathname, found, sizeof(pathname));
   249 	// store file: the name of the file (without dir)
   250 	cp=strrchr(pathname, '/');
   251 	if(cp)
   252 		file=cp+1;
   253 	else
   254 		file=pathname;
   255 	// store pathname: the gamedir relative path, or an absolute path
   256 	len=strlen(GameDLL.gamedir);
   257 	if(strncasecmp(pathname, GameDLL.gamedir, len) == 0)
   258 		STRNCPY(filename, pathname+len+1, sizeof(filename));
   259 	else
   260 		STRNCPY(filename, pathname, sizeof(filename));
   261 
   262 	return(mTRUE);
   263 }
   264 
   265 // For the given path, tries to find file in several possible 
   266 // directories.
   267 // Try:
   268 //     GAMEDIR/filename
   269 //     GAMEDIR/dlls/filename
   270 // meta_errno values:
   271 //  - none
   272 char *MPlugin::resolve_dirs(char *path) {
   273 	struct stat st;
   274 	static char buf[PATH_MAX];
   275 	char *found;
   276 
   277 	snprintf(buf, sizeof(buf), "%s/%s", GameDLL.gamedir, path);
   278 	// try this path
   279 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   280 		return(buf);
   281 	// try other file prefixes in this path
   282 	if((found=resolve_prefix(buf)))
   283 		return(found);
   284 
   285 	snprintf(buf, sizeof(buf), "%s/dlls/%s", GameDLL.gamedir, path);
   286 	// try this path
   287 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   288 		return(buf);
   289 	// try other file prefixes for this path
   290 	if((found=resolve_prefix(buf)))
   291 		return(found);
   292 
   293 	return(NULL);
   294 }
   295 
   296 // For the given path, tries several possible filename prefixes.
   297 // Try:
   298 //     dir/mm_file
   299 //     dir/file
   300 // meta_errno values:
   301 //  - none
   302 char *MPlugin::resolve_prefix(char *path) {
   303 	struct stat st;
   304 	char *cp, *fname;
   305 	char dname[PATH_MAX];
   306 	static char buf[PATH_MAX];
   307 	char *found;
   308 
   309 	// try "mm_" prefix FIRST.
   310 	// split into dirname and filename
   311 	STRNCPY(dname, path, sizeof(dname));
   312 	cp=strrchr(dname, '/');
   313 	if(cp) {
   314 		*cp='\0';
   315 		fname=cp+1;
   316 		snprintf(buf, sizeof(buf), "%s/mm_%s", dname, fname);
   317 	}
   318 	else {
   319 		// no directory in given path
   320 		snprintf(buf, sizeof(buf), "mm_%s", path);
   321 	}
   322 	// try this path
   323 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   324 		return(buf);
   325 	// try other suffixes for this path
   326 	if((found=resolve_suffix(buf)))
   327 		return(found);
   328 
   329 	// try other suffixes for the original path
   330 	if((found=resolve_suffix(path)))
   331 		return(found);
   332 
   333 	return(NULL);
   334 }
   335 
   336 // For the given path, tries several different filename suffixes.
   337 // Try:
   338 //     path
   339 //     path_mm
   340 //     path_MM
   341 //     path.so (linux), path.dll (win32)
   342 //     path_i386.so, path_i486.so, etc (if linux)
   343 // meta_errno values:
   344 //  - none
   345 char *MPlugin::resolve_suffix(char *path) {
   346 	struct stat st;
   347 	static char buf[PATH_MAX];
   348 	char *found;
   349 
   350 	// Hmm, recursion.
   351 	if(!strstr(path, "_mm")) {
   352 		char *tmpbuf;
   353 		snprintf(buf, sizeof(buf), "%s_mm", path);
   354 		tmpbuf=strdup(buf);
   355 		found=resolve_suffix(tmpbuf);
   356 		free(tmpbuf);
   357 		if(found) return(found);
   358 	}
   359 	if(!strstr(path, "_MM")) {
   360 		char *tmpbuf;
   361 		snprintf(buf, sizeof(buf), "%s_MM", path);
   362 		tmpbuf=strdup(buf);
   363 		found=resolve_suffix(tmpbuf);
   364 		free(tmpbuf);
   365 		if(found) return(found);
   366 	}
   367 
   368 #ifdef _WIN32
   369 	snprintf(buf, sizeof(buf), "%s.dll", path);
   370 #elif defined(linux)
   371 	snprintf(buf, sizeof(buf), "%s.so", path);
   372 #else
   373 #error "OS unrecognized"
   374 #endif /* _WIN32 */
   375 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   376 		return(buf);
   377 
   378 #ifdef linux
   379 	snprintf(buf, sizeof(buf), "%s_i386.so", path);
   380 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   381 		return(buf);
   382 	snprintf(buf, sizeof(buf), "%s_i486.so", path);
   383 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   384 		return(buf);
   385 	snprintf(buf, sizeof(buf), "%s_i586.so", path);
   386 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   387 		return(buf);
   388 	snprintf(buf, sizeof(buf), "%s_i686.so", path);
   389 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   390 		return(buf);
   391 	snprintf(buf, sizeof(buf), "%s_amd64.so", path);
   392 	if(stat(buf, &st) == 0 && S_ISREG(st.st_mode))
   393 		return(buf);
   394 #endif /* linux */
   395 
   396 	return(NULL);
   397 }
   398 
   399 
   400 // Check if a passed string starts with a known platform postfix.
   401 // It does not check beyond the period in order to work for both
   402 // Linux and Win32.
   403 static mBOOL is_platform_postfix(char* pf)
   404 {
   405 	if ( NULL == pf ) return mFALSE;
   406 
   407 	if ( 0 == strncmp(pf, "_i386.", 6) ) return mTRUE;
   408 	if ( 0 == strncmp(pf, "_i486.", 6) ) return mTRUE;
   409 	if ( 0 == strncmp(pf, "_i586.", 6) ) return mTRUE;
   410 	if ( 0 == strncmp(pf, "_i686.", 6) ) return mTRUE;
   411 	if ( 0 == strncmp(pf, "_amd64.", 7) ) return mTRUE;
   412 
   413 	return mFALSE;
   414 }
   415 
   416 
   417 // Check if a given plugin is the same but possibly for a
   418 // different platform. A match is considered to be found if
   419 // 1.  the filename without the path is the same, or
   420 // 2a. for an attached plugin the logtag is the same, or
   421 // 2b. the description is the same, or
   422 // 3.  a significant part of the filename is the same.
   423 // A significant part of a plugin name is currently defined to:
   424 //  the part up to a known platform postfix as determined by 
   425 //  the is_platform_postfix() function (see above), or
   426 //  the part up to the last dot, if one exists.
   427 // meta_errno values:
   428 //  - none
   429 mBOOL MPlugin::platform_match(MPlugin* other) {
   430 	char *end, *other_end;
   431 	int prefixlen;
   432 
   433 	if(status == PL_EMPTY || other->status == PL_EMPTY) return mFALSE;
   434 
   435 	if(strcmp(file, other->file) == 0) return mTRUE;
   436 
   437 	if(status >= PL_OPENED && other->status >= PL_OPENED &&
   438        strcmp(info->logtag, other->info->logtag) == 0 ) return mTRUE;
   439 	if(*desc != '\0' && strcasecmp(desc,other->desc) == 0) return mTRUE;
   440 
   441 	end=strrchr(file, '_');
   442 	if(end == NULL || !is_platform_postfix(end)) end=strrchr(file, '.');
   443 	other_end=strrchr(other->file, '_');
   444 	if(other_end == NULL || !is_platform_postfix(other_end)) other_end=strrchr(other->file, '.');
   445 
   446 	if(end == NULL || other_end == NULL) return mFALSE;
   447 
   448 	prefixlen=end-file;
   449 	if((other_end-other->file) != prefixlen) return mFALSE;
   450 
   451 	if(strncmp(file,other->file, prefixlen) == 0) return mTRUE;
   452 
   453 	return mFALSE;
   454 }
   455 
   456 
   457 // Load a plugin; query, check allowed time, attach.
   458 // meta_errno values:
   459 //  - ME_ARGUMENT	missing necessary fields in plugin
   460 //  - ME_ALREADY	this plugin already loaded
   461 //  - ME_BADREQ		plugin not marked for load
   462 //  - ME_DELAYED	load request is delayed (till changelevel?)
   463 //  - ME_NOTALLOWED	plugin not loadable after startup
   464 //  - errno's from query()
   465 //  - errno's from attach()
   466 //  - errno's from check_input()
   467 mBOOL MPlugin::load(PLUG_LOADTIME now) {
   468 	if(!check_input()) {
   469 		// details logged, meta_errno set in check_input()
   470 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   471 	}
   472 	if(status >= PL_RUNNING) {
   473 		META_ERROR("dll: Not loading plugin '%s'; already loaded (status=%s)", 
   474 				desc, str_status());
   475 		RETURN_ERRNO(mFALSE, ME_ALREADY);
   476 	}
   477 	if(action != PA_LOAD && action != PA_ATTACH) {
   478 		META_ERROR("dll: Not loading plugin '%s'; not marked for load (action=%s)", desc, str_action());
   479 		RETURN_ERRNO(mFALSE, ME_BADREQ);
   480 	}
   481 
   482 	if(status != PL_OPENED) {
   483 		// query plugin; open file and get info about it
   484 		if(!query()) {
   485 			META_ERROR("dll: Skipping plugin '%s'; couldn't query", desc);
   486 			if(meta_errno != ME_DLOPEN) {
   487 				if(DLCLOSE(handle) != 0) {
   488 					META_ERROR("dll: Couldn't close plugin file '%s': %s", 
   489 							file, DLERROR());
   490 				}
   491 				else
   492 					handle=NULL;
   493 			}
   494 			status=PL_BADFILE;
   495 			// meta_errno should be already set in query()
   496 			return(mFALSE);
   497 		}
   498 		status=PL_OPENED;
   499 	}
   500 
   501 	// are we allowed to attach this plugin at this time?
   502 	if(info->loadable < now) {
   503 		if(info->loadable > PT_STARTUP) {
   504 			// will try to attach again at next opportunity
   505 			META_DEBUG(2, ("dll: Delaying load plugin '%s'; can't attach now: allowed=%s; now=%s", 
   506 						desc, str_loadable(), str_loadtime(now, SL_SIMPLE)));
   507 			RETURN_ERRNO(mFALSE, ME_DELAYED);
   508 		}
   509 		else {
   510 			META_DEBUG(2, ("dll: Failed load plugin '%s'; can't attach now: allowed=%s; now=%s", 
   511 						desc, str_loadable(), str_loadtime(now, SL_SIMPLE)));
   512 			// don't try to attach again later
   513 			action=PA_NONE;
   514 			RETURN_ERRNO(mFALSE, ME_NOTALLOWED);
   515 		}
   516 	}
   517 
   518 	// attach plugin; get function tables
   519 	if(attach(now) != mTRUE) {
   520 		META_ERROR("dll: Failed to attach plugin '%s'", desc);
   521 		// Note we don't dlclose() here, since we're returning PL_FAILED,
   522 		// which implies that it's been dlopened and queried successfully.
   523 		// Doing so causes crashes, because things like "meta list" try to
   524 		// look at *info, which is in the DLL memory space and unaccessible
   525 		// (segfault) after dlclosed.
   526 		status=PL_FAILED;
   527 		// meta_errno should be already set in attach()
   528 		return(mFALSE);
   529 	}
   530 	status=PL_RUNNING;
   531 	action=PA_NONE;
   532 
   533 	// If not loading at server startup, then need to call plugin's
   534 	// GameInit, since we've passed that.
   535 	if(now != PT_STARTUP) {
   536 		FN_GAMEINIT pfn_gameinit=NULL;
   537 		if(dllapi_table && (pfn_gameinit=dllapi_table->pfnGameInit))
   538 			pfn_gameinit();
   539 	}
   540 	// If loading during map, then I'd like to call plugin's
   541 	// ServerActivate, since we've passed that.  However, I'm not sure what
   542 	// arguments to give it...  So, we'll just have to say for the
   543 	// moment that plugins that are loadable during a map can't need to
   544 	// hook ServerActivate.
   545 
   546 	META_LOG("dll: Loaded plugin '%s': %s v%s %s, %s", desc, info->name, 
   547 			info->version, info->date, info->author);
   548 	return(mTRUE);
   549 }
   550 
   551 // Query a plugin:
   552 //  - dlopen() the file, store the handle
   553 //  - dlsym() and call:
   554 //	    Meta_Init (if present) - tell dll it'll be used as a metamod plugin
   555 //	    GiveFnptrsToDll - give engine function ptrs 
   556 //	    Meta_Query - say "hi" and get info about plugin
   557 // meta_errno values:
   558 //  - ME_DLOPEN		dlopen/loadlibrary failed; see dlerror() for details
   559 //  - ME_DLMISSING	couldn't find a query() or giveFuncs() in plugin
   560 //  - ME_DLERROR	plugin query() returned error
   561 //  - ME_NULLDATA	info struct from query() was null
   562 mBOOL MPlugin::query(void) {
   563 	META_INIT_FN pfn_init;
   564 	GIVE_ENGINE_FUNCTIONS_FN pfn_give_engfuncs;
   565 	META_QUERY_FN pfn_query;
   566 
   567 	// open the plugin DLL
   568 	if(!(handle=DLOPEN(pathname))) {
   569 		META_ERROR("dll: Failed query plugin '%s'; Couldn't open file '%s': %s",
   570 				desc, pathname, DLERROR());
   571 		RETURN_ERRNO(mFALSE, ME_DLOPEN);
   572 	}
   573 
   574 	// First, we check to see if they have a Meta_Query.  We would normally
   575 	// dlsym this just prior to calling it, after having called
   576 	// GiveFnptrsToDll, but things like standalone-DLL bots do all their
   577 	// startup in GiveFnptrsToDll, and trying to load them as metamod
   578 	// plugins creates all sorts of crashes.  So, we do a trivial check
   579 	// first to see if the DLL looks like a metamod plugin before
   580 	// proceeding with the normal order.  Note that we still have to call 
   581 	// GiveFnptrsToDll before Meta_Query, because the latter typically uses 
   582 	// engine functions like AlertMessage, which have to be passed along via 
   583 	// GiveFnptrsToDll.
   584 	pfn_query = (META_QUERY_FN) DLSYM(handle, "Meta_Query");
   585 	if(!pfn_query) {
   586 		META_ERROR("dll: Failed query plugin '%s'; Couldn't find Meta_Query(): %s", desc, DLERROR());
   587 		// caller will dlclose()
   588 		RETURN_ERRNO(mFALSE, ME_DLMISSING);
   589 	}
   590 
   591 	// Call Meta_Init, if present.  This is an optional plugin routine to
   592 	// allow plugin to do any special initializing or other processing
   593 	// prior to the standard query/attach procedure.  
   594 	//
   595 	// In particular, this should allow for DLL's that can operate as both
   596 	// a standalone dll AND a metamod plugin.  This routine has to be
   597 	// called _before_ GiveFnptrsToDll, since the dll will usually do all
   598 	// its startup processing in GiveFn, and has to know at that point
   599 	// whether it needs to do just mm plugin startup, or all the extra
   600 	// startup needed for a standalone DLL.
   601 	//
   602 	// This passes nothing and returns nothing, and the routine in the
   603 	// plugin can NOT use any Engine functions, as they haven't been
   604 	// provided yet (done next, in GiveFnptrsToDll).
   605 	pfn_init = (META_INIT_FN) DLSYM(handle, "Meta_Init");
   606 	if(pfn_init) {
   607 		pfn_init();
   608 		META_DEBUG(6, ("dll: Plugin '%s': Called Meta_Init()", desc));
   609 	}
   610 	else {
   611 		META_DEBUG(5, ("dll: no Meta_Init present in plugin '%s'", desc));
   612 		// don't return; not an error
   613 	}
   614 	
   615 	// pass on engine function table and globals to plugin
   616 	if(!(pfn_give_engfuncs = (GIVE_ENGINE_FUNCTIONS_FN) DLSYM(handle, "GiveFnptrsToDll"))) {
   617 		// META_ERROR("dll: Couldn't find GiveFnptrsToDll() in plugin '%s': %s", desc, DLERROR());
   618 		META_ERROR("dll: Failed query plugin '%s'; Couldn't find GiveFnptrsToDll(): %s", desc, DLERROR());
   619 		// caller will dlclose()
   620 		RETURN_ERRNO(mFALSE, ME_DLMISSING);
   621 	}
   622 	pfn_give_engfuncs(Engine.pl_funcs, Engine.globals);
   623 	META_DEBUG(6, ("dll: Plugin '%s': Called GiveFnptrsToDll()", desc));
   624 
   625 	// Call plugin's Meta_Query(), to pass our meta interface version, and get
   626 	// plugin's info structure.
   627 	meta_errno=ME_NOERROR;
   628 	info=NULL;
   629 	// Make a copy of the meta_util function table for each plugin, for the
   630 	// same reason.
   631 	memcpy(&mutil_funcs, &MetaUtilFunctions, sizeof(mutil_funcs));
   632 
   633 	if(pfn_query(META_INTERFACE_VERSION, &info, &mutil_funcs) != TRUE) {
   634 		META_ERROR("dll: Failed query plugin '%s'; Meta_Query returned error", 
   635 				desc);
   636 		meta_errno=ME_DLERROR;
   637 	}
   638 	else {
   639 		META_DEBUG(6, ("dll: Plugin '%s': Called Meta_Query() successfully", 
   640 					desc));
   641 	}
   642 
   643 	// Check for interface differences...  Generally, a difference in major
   644 	// version will be incompatible, and a plugin that expects a later
   645 	// minor version will be incompatible (it's expecting things that this
   646 	// Metamod won't be supplying).  Plugins that use an older minor
   647 	// version will still work, as backward-compability within major
   648 	// version is expected (forward-compatibility is not).
   649 	//
   650 	// Note, this check is done regardless of whether meta_query returns an
   651 	// error.
   652 	if(info && !FStrEq(info->ifvers, META_INTERFACE_VERSION)) {
   653 		int mmajor=0, mminor=0, pmajor=0, pminor=0;
   654 		META_DEBUG(3, ("dll: Note: Plugin '%s' interface version didn't match; expected %s, found %s", desc, META_INTERFACE_VERSION, info->ifvers));
   655 		sscanf(META_INTERFACE_VERSION, "%d:%d", &mmajor, &mminor);
   656 		sscanf(info->ifvers, "%d:%d", &pmajor, &pminor);
   657 		// If plugin has later interface version, it's incompatible 
   658 		// (update metamod).
   659 		if(pmajor > mmajor || (pmajor==mmajor && pminor > mminor)) {
   660 			META_ERROR("dll: Plugin '%s' requires a newer version of Metamod (Metamod needs at least interface %s not the current %s)", desc, info->ifvers, META_INTERFACE_VERSION);
   661 			meta_errno=ME_IFVERSION;
   662 		}
   663 		// If plugin has older major interface version, it's incompatible
   664 		// (update plugin).
   665 		else if(pmajor < mmajor) {
   666 			META_ERROR("dll: Plugin '%s' is out of date and incompatible with this version of Metamod; please find a newer version of the plugin (plugin needs at least interface %s not the current %s)", desc, META_INTERFACE_VERSION, info->ifvers);
   667 			meta_errno=ME_IFVERSION;
   668 		}
   669 		// Plugin has identical major, with older minor.  This is supposed to be
   670 		// backwards compatible, so we warn, but we still accept it.
   671 		else if(pmajor==mmajor && pminor < mminor)
   672 			META_LOG("dll: Note: plugin '%s' is using an older interface version (%s), not the latest interface version (%s); there might be an updated version of the plugin", desc, info->ifvers, META_INTERFACE_VERSION);
   673 		else
   674 			META_LOG("dll: Plugin '%s': unexpected version comparision; metavers=%s, mmajor=%d, mminor=%d; plugvers=%s, pmajor=%d, pminor=%d", 
   675 					desc, META_INTERFACE_VERSION, mmajor, mminor, info->ifvers, pmajor, pminor);
   676 	}
   677 
   678 	if(meta_errno == ME_IFVERSION) {
   679 		META_ERROR("dll: Rejected plugin '%s' due to interface version incompatibility (mm=%s, pl=%s)", desc, META_INTERFACE_VERSION, info->ifvers);
   680 		// meta_errno is set already above
   681 		// caller will dlclose()
   682 		return(mFALSE);
   683 	}
   684 	else if(meta_errno != ME_NOERROR)
   685 		// some other error, already logged
   686 		return(mFALSE);
   687 
   688 	if(!info) {
   689 		META_ERROR("dll: Failed query plugin '%s'; Empty info structure", desc);
   690 		// caller will dlclose()
   691 		RETURN_ERRNO(mFALSE, ME_NULLRESULT);
   692 	}
   693 	// Replace temporary desc with plugin's internal name.
   694 	if(desc[0] == '<')
   695 		STRNCPY(desc, info->name, sizeof(desc));
   696 	META_DEBUG(6, ("dll: Plugin '%s': Query successful", desc));
   697 	return(mTRUE);
   698 }
   699 
   700 // Attach a plugin:
   701 //	- dlsym() and call:
   702 //	    Meta_Attach - get table of api tables, give meta_globals
   703 //  - if provided by plugin, call various "Get" function pointers, 
   704 //    and store resulting function tables:
   705 //		GetEntityAPI			(std)
   706 //		GetEntityAPI2			(std sdk2)
   707 //		GetNewDLLFunctions		(std sdk2)
   708 //
   709 //		GetEntityAPI_Post		(meta)
   710 //		GetEntityAPI2_Post		(meta)
   711 //		GetNewDLLFunctions_Post	(meta)
   712 //
   713 //		GetEngineFunctions		(meta)
   714 //		GetEngineFunctions_Post	(meta)
   715 // meta_errno values:
   716 //  - ME_DLMISSING	couldn't find meta_attach() in plugin
   717 //  - ME_DLERROR	plugin attach() returned error
   718 //  - ME_NOMEM		failed malloc
   719 mBOOL MPlugin::attach(PLUG_LOADTIME now) {
   720 	int ret;
   721 	int iface_vers;
   722 
   723 	META_ATTACH_FN pfn_attach;
   724 	META_FUNCTIONS meta_table;
   725 
   726 	// Make copy of gameDLL's function tables for each plugin, so we don't
   727 	// risk the plugins screwing with the tables everyone uses.
   728 	if(GameDLL.funcs.dllapi_table && !gamedll_funcs.dllapi_table) {
   729 		gamedll_funcs.dllapi_table = (DLL_FUNCTIONS *) malloc(sizeof(DLL_FUNCTIONS));
   730 		if(!gamedll_funcs.dllapi_table) {
   731 			META_ERROR("dll: Failed attach plugin '%s': Failed malloc() for dllapi_table");
   732 			RETURN_ERRNO(mFALSE, ME_NOMEM);
   733 		}
   734 		memcpy(gamedll_funcs.dllapi_table, GameDLL.funcs.dllapi_table, 
   735 				sizeof(DLL_FUNCTIONS));
   736 	}
   737 	if(GameDLL.funcs.newapi_table && !gamedll_funcs.newapi_table) {
   738 		gamedll_funcs.newapi_table = (NEW_DLL_FUNCTIONS *) malloc(sizeof(NEW_DLL_FUNCTIONS));
   739 		if(!gamedll_funcs.newapi_table) {
   740 			META_ERROR("dll: Failed attach plugin '%s': Failed malloc() for newapi_table");
   741 			RETURN_ERRNO(mFALSE, ME_NOMEM);
   742 		}
   743 		memcpy(gamedll_funcs.newapi_table, GameDLL.funcs.newapi_table, 
   744 				sizeof(NEW_DLL_FUNCTIONS));
   745 	}
   746 	if(!(pfn_attach = (META_ATTACH_FN) DLSYM(handle, "Meta_Attach"))) {
   747 		META_ERROR("dll: Failed attach plugin '%s': Couldn't find Meta_Attach(): %s", desc, DLERROR());
   748 		// caller will dlclose()
   749 		RETURN_ERRNO(mFALSE, ME_DLMISSING);
   750 	}
   751 
   752 	memset(&meta_table, 0, sizeof(meta_table));
   753 	// get table of function tables,
   754 	// give public meta globals
   755 	ret=pfn_attach(now, &meta_table, &PublicMetaGlobals, &gamedll_funcs);
   756 	if(ret != TRUE) {
   757 		META_ERROR("dll: Failed attach plugin '%s': Error from Meta_Attach(): %d", desc, ret);
   758 		// caller will dlclose()
   759 		RETURN_ERRNO(mFALSE, ME_DLERROR);
   760 	}
   761 	META_DEBUG(6, ("dll: Plugin '%s': Called Meta_Attach() successfully", desc));
   762 
   763 	// Rather than duplicate code, we use another ugly macro.  Again,
   764 	// a function isn't an option since we have varying types.
   765 #define GET_FUNC_TABLE_FROM_PLUGIN(pfnGetFuncs, STR_GetFuncs, struct_field, API_TYPE, TABLE_TYPE, vers_pass, vers_int, vers_want) \
   766 	if(meta_table.pfnGetFuncs) { \
   767 		struct_field = (TABLE_TYPE*) calloc(1, sizeof(TABLE_TYPE)); \
   768 		if(meta_table.pfnGetFuncs(struct_field, vers_pass)) { \
   769 			META_DEBUG(3, ("dll: Plugin '%s': Found %s", desc, STR_GetFuncs)); \
   770 		} \
   771 		else { \
   772 			META_ERROR("dll: Failure calling %s in plugin '%s'", STR_GetFuncs, desc); \
   773 			if(vers_int != vers_want) \
   774 				META_ERROR("dll: Interface version didn't match; expected %d, found %d", vers_want, vers_int); \
   775 		} \
   776 	} \
   777 	else { \
   778 		META_DEBUG(5, ("dll: Plugin '%s': No %s", desc, STR_GetFuncs)); \
   779 		struct_field=NULL; \
   780 	}
   781 
   782 	// Look for API-NEW interface in plugin.  We do this before API2/API, because
   783 	// that's what the engine appears to do..
   784 	// But we only do this if the gamedll provides these, so that we don't
   785 	// give a plugin the idea that we'll call them, when in fact we won't
   786 	// (since we don't export them to the engine when the gamedll doesn't
   787 	// provide them).
   788 	if(GameDLL.funcs.newapi_table) {
   789 		iface_vers=NEW_DLL_FUNCTIONS_VERSION;
   790 		GET_FUNC_TABLE_FROM_PLUGIN(pfnGetNewDLLFunctions, 
   791 				"GetNewDLLFunctions", newapi_table, 
   792 				NEW_DLL_FUNCTIONS_FN, NEW_DLL_FUNCTIONS,
   793 				&iface_vers, iface_vers, NEW_DLL_FUNCTIONS_VERSION);
   794 		iface_vers=NEW_DLL_FUNCTIONS_VERSION;
   795 		GET_FUNC_TABLE_FROM_PLUGIN(pfnGetNewDLLFunctions_Post, 
   796 				"GetNewDLLFunctions_Post", newapi_post_table, 
   797 				NEW_DLL_FUNCTIONS_FN, NEW_DLL_FUNCTIONS,
   798 				&iface_vers, iface_vers, NEW_DLL_FUNCTIONS_VERSION);
   799 	}
   800 
   801 	// Look for API2 interface in plugin; preferred over API-1.
   802 	iface_vers=INTERFACE_VERSION;
   803 	GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEntityAPI2, 
   804 			"GetEntityAPI2", dllapi_table, 
   805 			APIFUNCTION2, DLL_FUNCTIONS,
   806 			&iface_vers, iface_vers, INTERFACE_VERSION);
   807 	iface_vers=INTERFACE_VERSION;
   808 	GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEntityAPI2_Post, 
   809 			"GetEntityAPI2_Post", dllapi_post_table, 
   810 			APIFUNCTION2, DLL_FUNCTIONS,
   811 			&iface_vers, iface_vers, INTERFACE_VERSION);
   812 
   813 	// Look for old-style API in plugin, if API2 interface wasn't found.
   814 	if(!dllapi_table && !dllapi_post_table) {
   815 		GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEntityAPI, 
   816 				"GetEntityAPI", dllapi_table, 
   817 				APIFUNCTION, DLL_FUNCTIONS,
   818 				INTERFACE_VERSION, INTERFACE_VERSION, INTERFACE_VERSION);
   819 		GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEntityAPI_Post, 
   820 				"GetEntityAPI_Post", dllapi_post_table, 
   821 				APIFUNCTION, DLL_FUNCTIONS,
   822 				INTERFACE_VERSION, INTERFACE_VERSION, INTERFACE_VERSION);
   823 	}
   824 
   825 	// Look for Engine interface.
   826 	iface_vers=ENGINE_INTERFACE_VERSION;
   827 	GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEngineFunctions, 
   828 			"GetEngineFunctions", engine_table, 
   829 			GET_ENGINE_FUNCTIONS_FN, enginefuncs_t,
   830 			&iface_vers, iface_vers, ENGINE_INTERFACE_VERSION);
   831 	iface_vers=ENGINE_INTERFACE_VERSION;
   832 	GET_FUNC_TABLE_FROM_PLUGIN(pfnGetEngineFunctions_Post, 
   833 			"GetEngineFunctions_Post", engine_post_table, 
   834 			GET_ENGINE_FUNCTIONS_FN, enginefuncs_t,
   835 			&iface_vers, iface_vers, ENGINE_INTERFACE_VERSION);
   836 
   837 	if(!dllapi_table && !dllapi_post_table 
   838 		&& !newapi_table && !newapi_post_table
   839 		&& !engine_table && !engine_post_table)
   840 	{
   841 		META_LOG("dll: Plugin '%s' isn't catching _any_ functions ??", desc);
   842 	}
   843 
   844 	time_loaded=time(NULL);
   845 	return(mTRUE);
   846 }
   847 
   848 // Unload a plugin.  Check time, detach.
   849 // meta_errno values:
   850 //  - ME_ARGUMENT	missing necessary fields in plugin
   851 //  - ME_ALREADY	this plugin already unloaded
   852 //  - ME_BADREQ		plugin not marked for unload
   853 //  - ME_DELAYED	unload request is delayed (till changelevel?)
   854 //  - ME_NOTALLOWED	plugin not unloadable after startup
   855 //  - errno's from check_input()
   856 mBOOL MPlugin::unload(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) {
   857 	if(!check_input()) {
   858 		// details logged, meta_errno set in check_input()
   859 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   860 	}
   861 	if(status < PL_RUNNING) {
   862 		META_ERROR("dll: Not unloading plugin '%s'; already unloaded (status=%s)", desc, str_status());
   863 		RETURN_ERRNO(mFALSE, ME_ALREADY);
   864 	}
   865 	if(action != PA_UNLOAD && action != PA_RELOAD) {
   866 		META_ERROR("dll: Not unloading plugin '%s'; not marked for unload (action=%s)", desc, str_action());
   867 		RETURN_ERRNO(mFALSE, ME_BADREQ);
   868 	}
   869 
   870 	// Are we allowed to detach this plugin at this time?
   871 	// If forcing unload, we disregard when plugin wants to be unloaded.
   872 	if(info->unloadable < now) {
   873 		if(reason == PNL_CMD_FORCED) {
   874 			META_DEBUG(2, ("dll: Forced unload plugin '%s' overriding allowed times: allowed=%s; now=%s", desc, str_unloadable(), str_loadtime(now, SL_SIMPLE)));
   875 		}
   876 		else {
   877 			if(info->unloadable > PT_STARTUP) {
   878 				META_DEBUG(2, ("dll: Delaying unload plugin '%s'; can't detach now: allowed=%s; now=%s", desc, str_unloadable(), str_loadtime(now, SL_SIMPLE)));
   879 				// caller should give message to user
   880 				// try to unload again at next opportunity
   881 				RETURN_ERRNO(mFALSE, ME_DELAYED);
   882 			}
   883 			else {
   884 				META_DEBUG(2, ("dll: Failed unload plugin '%s'; can't detach now: allowed=%s; now=%s", desc, str_unloadable(), str_loadtime(now, SL_SIMPLE)));
   885 				// don't try to unload again later
   886 				action=PA_NONE;
   887 				RETURN_ERRNO(mFALSE, ME_NOTALLOWED);
   888 			}
   889 		}
   890 	}
   891 
   892 	// If unloading during map, then I'd like to call plugin's
   893 	// ServerDeactivate.  However, I don't want to do this until I start
   894 	// calling ServerActivate when loading during map, since the SDK
   895 	// indicates these two routines should match call for call.
   896 
   897 	// detach plugin
   898 	if(!detach(now, reason)) {
   899 		if(reason == PNL_CMD_FORCED) {
   900 			META_DEBUG(2, ("dll: Forced unload plugin '%s' overriding failed detach"));
   901 		}
   902 		else {
   903 			META_ERROR("dll: Failed to detach plugin '%s'; ", desc);
   904 			// meta_errno should be already set in detach()
   905 			return(mFALSE);
   906 		}
   907 	}
   908 
   909 	// successful detach, or forced unload
   910 
   911 	// Unmark registered commands for this plugin (by index number).
   912 	RegCmds->disable(index);
   913 	// Unmark registered cvars for this plugin (by index number).
   914 	RegCvars->disable(index);
   915 
   916 #ifdef UNFINISHED
   917 	// Remove all requested hooks from this plugin (by index number).
   918 	Hooks->remove_all(info);
   919 #endif /* UNFINISHED */
   920 
   921 	// Close the file.  Note: after this, attempts to reference any memory
   922 	// locations in the file will produce a segfault.
   923 	if(DLCLOSE(handle) != 0) {
   924 		META_ERROR("dll: Couldn't close plugin file '%s': %s", file, DLERROR());
   925 		status=PL_FAILED;
   926 		RETURN_ERRNO(mFALSE, ME_DLERROR);
   927 	}
   928 	handle=NULL;
   929 
   930 	if(action==PA_UNLOAD) {
   931 		status=PL_EMPTY;
   932 		clear();
   933 	}
   934 	else if(action==PA_RELOAD) {
   935 		status=PL_VALID;
   936 		action=PA_LOAD;
   937 	}
   938 	META_LOG("dll: Unloaded plugin '%s' for reason '%s'", desc, str_reason(reason));
   939 	return(mTRUE);
   940 }
   941 
   942 // Inform plugin we're going to unload it.
   943 // meta_errno values:
   944 //  - ME_DLMISSING	couldn't find meta_detach() in plugin
   945 //  - ME_DLERROR	plugin detach() returned error
   946 mBOOL MPlugin::detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) {
   947 	int ret;
   948 	META_DETACH_FN pfn_detach;
   949 
   950 	if(!(pfn_detach = (META_DETACH_FN) DLSYM(handle, "Meta_Detach"))) {
   951 		META_ERROR("dll: Error detach plugin '%s': Couldn't find Meta_detach(): %s", desc, DLERROR());
   952 		// caller will dlclose()
   953 		RETURN_ERRNO(mFALSE, ME_DLMISSING);
   954 	}
   955 
   956 	ret=pfn_detach(now, reason);
   957 	if(ret != TRUE) {
   958 		META_ERROR("dll: Failed detach plugin '%s': Error from Meta_Detach(): %d", desc, ret);
   959 		RETURN_ERRNO(mFALSE, ME_DLERROR);
   960 	}
   961 	META_DEBUG(6, ("dll: Plugin '%s': Called Meta_Detach() successfully", desc));
   962 	return(mTRUE);
   963 }
   964 
   965 // Reload a plugin; unload and load again.
   966 // meta_errno values:
   967 //  - ME_NOTALLOWED	plugin not loadable after startup
   968 //  - errno's from check_input()
   969 //  - errno's from unload()
   970 //  - errno's from load()
   971 mBOOL MPlugin::reload(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) {
   972 	if(!check_input()) {
   973 		// details logged, meta_errno set in check_input()
   974 		RETURN_ERRNO(mFALSE, ME_ARGUMENT);
   975 	}
   976 	// Are we allowed to load this plugin at this time?
   977 	// If we cannot load the plugin after unloading it, we keep it.
   978 	if(info->loadable < now) {
   979 		if(info->loadable > PT_STARTUP) {
   980 			META_DEBUG(2, ("dll: Delaying reload plugin '%s'; would not be able to reattach now: allowed=%s; now=%s", desc, str_loadable(), str_loadtime(now, SL_SIMPLE)));
   981 			// caller should give message to user
   982 			// try to reload again at next opportunity
   983 			RETURN_ERRNO(mFALSE, ME_DELAYED);
   984 		}
   985 		else {
   986 			META_DEBUG(2, ("dll: Failed reload plugin '%s'; would not be able to reattach now: allowed=%s; now=%s", desc, str_loadable(), str_loadtime(now, SL_SIMPLE)));
   987 			// don't try to reload again later
   988 			action=PA_NONE;
   989 			RETURN_ERRNO(mFALSE, ME_NOTALLOWED);
   990 		}
   991 	}
   992 
   993 	if(!unload(now, reason)) {
   994 		META_ERROR("dll: Failed to unload plugin '%s' for reloading", desc);
   995 		// meta_errno should be set already in unload()
   996 		return(mFALSE);
   997 	}
   998 	if(!load(now)) {
   999 		META_ERROR("dll: Failed to reload plugin '%s' after unloading", desc);
  1000 		// meta_errno should be set already in load()
  1001 		return(mFALSE);
  1002 	}
  1003 	return(mTRUE);
  1004 }
  1005 
  1006 // Pause a plugin; temporarily disabled for API routines.
  1007 // meta_errno values:
  1008 //  - ME_ALREADY	this plugin already paused
  1009 //  - ME_BADREQ		can't pause; not running
  1010 //  - ME_NOTALLOWED	plugin doesn't want to be paused
  1011 mBOOL MPlugin::pause(void) {
  1012 	if(status == PL_PAUSED) {
  1013 		META_ERROR("Not pausing plugin '%s'; already paused", desc);
  1014 		RETURN_ERRNO(mFALSE, ME_ALREADY);
  1015 	}
  1016 	if(status != PL_RUNNING) {
  1017 		META_ERROR("Cannot pause plugin '%s'; not currently running (status=%s)", desc, str_status());
  1018 		RETURN_ERRNO(mFALSE, ME_BADREQ);
  1019 	}
  1020 
  1021 	// are we allowed to pause this plugin?
  1022 	if(info->unloadable < PT_ANYPAUSE) {
  1023 		META_ERROR("Cannot pause plugin '%s'; not allowed by plugin (allowed=%s)", desc, str_unloadable());
  1024 		action=PA_NONE;
  1025 		RETURN_ERRNO(mFALSE, ME_NOTALLOWED);
  1026 	}
  1027 
  1028 	status=PL_PAUSED;
  1029 	META_LOG("Paused plugin '%s'", desc);
  1030 	return(mTRUE);
  1031 }
  1032 
  1033 // Unpause a plugin.
  1034 // meta_errno values:
  1035 //  - ME_BADREQ		can't unpause; not paused
  1036 mBOOL MPlugin::unpause(void) {
  1037 	if(status != PL_PAUSED) {
  1038 		META_ERROR("Cannot unpause plugin '%s'; not currently paused (status=%s)", desc, str_status());
  1039 		RETURN_ERRNO(mFALSE, ME_BADREQ);
  1040 	}
  1041 	status=PL_RUNNING;
  1042 	META_LOG("Unpaused plugin '%s'", desc);
  1043 	return(mTRUE);
  1044 }
  1045 
  1046 // Retry pending action, presumably from a previous failure.
  1047 // meta_errno values:
  1048 //  - ME_BADREQ		no pending action
  1049 //  - errno's from load()
  1050 //  - errno's from unload()
  1051 //  - errno's from reload()
  1052 mBOOL MPlugin::retry(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) {
  1053 	if(action==PA_LOAD)
  1054 		return(load(now));
  1055 	else if(action==PA_ATTACH)
  1056 		return(load(now));
  1057 	else if(action==PA_UNLOAD)
  1058 		return(unload(now, reason));
  1059 	else if(action==PA_RELOAD)
  1060 		return(reload(now, reason));
  1061 	else {
  1062 		META_ERROR("No pending action to retry for plugin '%s'; (status=%s, action=%s)", desc, str_status(), str_action());
  1063 		RETURN_ERRNO(mFALSE, ME_BADREQ);
  1064 	}
  1065 }
  1066 
  1067 // Clear a plugin (it failed a previous action and should be
  1068 // removed from the list, or it's being unloaded).
  1069 // meta_errno values:
  1070 //  - ME_BADREQ		not marked for clearing
  1071 //  - ME_DLERROR	failed to dlclose
  1072 mBOOL MPlugin::clear(void) {
  1073 	if(status != PL_FAILED && status != PL_BADFILE
  1074 			&& status != PL_EMPTY && status != PL_OPENED) {
  1075 		META_ERROR("Cannot clear plugin '%s'; not marked as failed, empty, or open (status=%s)", desc, str_status());
  1076 		RETURN_ERRNO(mFALSE, ME_BADREQ);
  1077 	}
  1078 	// If file is open, close the file.  Note: after this, attempts to
  1079 	// reference any memory locations in the file will produce a segfault.
  1080 	if(handle && DLCLOSE(handle) != 0) {
  1081 		META_ERROR("dll: Couldn't close plugin file '%s': %s", file, DLERROR());
  1082 		status=PL_FAILED;
  1083 		RETURN_ERRNO(mFALSE, ME_DLERROR);
  1084 	}
  1085 	handle=NULL;
  1086 
  1087 	if(gamedll_funcs.dllapi_table) free(gamedll_funcs.dllapi_table);
  1088 	if(gamedll_funcs.newapi_table) free(gamedll_funcs.newapi_table);
  1089 	if(dllapi_table) free(dllapi_table);
  1090 	if(dllapi_post_table) free(dllapi_post_table);
  1091 	if(newapi_table) free(newapi_table);
  1092 	if(newapi_post_table) free(newapi_post_table);
  1093 	if(engine_table) free(engine_table);
  1094 	if(engine_post_table) free(engine_post_table);
  1095 
  1096 	status=PL_EMPTY;
  1097 	action=PA_NULL;
  1098 	handle=NULL;
  1099 	info=NULL;
  1100 	time_loaded=0;
  1101 	dllapi_table=NULL;
  1102 	dllapi_post_table=NULL;
  1103 	newapi_table=NULL;
  1104 	newapi_post_table=NULL;
  1105 	engine_table=NULL;
  1106 	engine_post_table=NULL;
  1107 	gamedll_funcs.dllapi_table = NULL;
  1108 	gamedll_funcs.newapi_table = NULL;
  1109 	return(mTRUE);
  1110 }
  1111 
  1112 // List information about plugin to console.
  1113 void MPlugin::show(void) {
  1114 	char *cp, *tstr;
  1115 	int n, width;
  1116 	width=13;
  1117 	META_CONS("%*s: %s", width, "name", info ? info->name : "(nil)");
  1118 	META_CONS("%*s: %s", width, "desc", desc);
  1119 	META_CONS("%*s: %s", width, "status", str_status());
  1120 	META_CONS("%*s: %s", width, "action", str_action());
  1121 	META_CONS("%*s: %s", width, "filename", filename);
  1122 	META_CONS("%*s: %s", width, "file", file);
  1123 	META_CONS("%*s: %s", width, "pathname", pathname);
  1124 	META_CONS("%*s: %d", width, "index", index);
  1125 	META_CONS("%*s: %s", width, "source", str_source());
  1126 	META_CONS("%*s: %s", width, "loadable", str_loadable(SL_ALLOWED));
  1127 	META_CONS("%*s: %s", width, "unloadable", str_unloadable(SL_ALLOWED));
  1128 	META_CONS("%*s: %s", width, "version", info ? info->version : "(nil)");
  1129 	META_CONS("%*s: %s", width, "date", info ? info->date : "(nil)");
  1130 	META_CONS("%*s: %s", width, "author", info ? info->author : "(nil)");
  1131 	META_CONS("%*s: %s", width, "url", info ? info->url : "(nil)");
  1132 	META_CONS("%*s: %s", width, "logtag", info ? info->logtag : "(nil)");
  1133 	// ctime() includes newline at EOL
  1134 	tstr=ctime(&time_loaded);
  1135 	if((cp=strchr(tstr, '\n')))
  1136 		*cp='\0';
  1137 	META_CONS("%*s: %s", width, "last loaded", tstr);
  1138 	// XXX show file time ?
  1139 
  1140 	if(dllapi_table) {
  1141 		META_CONS("DLLAPI functions:");
  1142 		SHOW_DEF_DLLAPI(dllapi_table, "   ", "");
  1143 		META_CONS("%d functions (dllapi)", n);
  1144 	}
  1145 	else
  1146 		META_CONS("No DLLAPI functions.");
  1147 	if(dllapi_post_table) {
  1148 		META_CONS("DLLAPI-Post functions:");
  1149 		SHOW_DEF_DLLAPI(dllapi_post_table, "   ", "_Post");
  1150 		META_CONS("%d functions (dllapi post)", n);
  1151 	}
  1152 	else
  1153 		META_CONS("No DLLAPI-Post functions.");
  1154 
  1155 	if(newapi_table) {
  1156 		META_CONS("NEWAPI functions:");
  1157 		SHOW_DEF_NEWAPI(newapi_table, "   ", "");
  1158 		META_CONS("%d functions (newapi)", n);
  1159 	}
  1160 	else
  1161 		META_CONS("No NEWAPI functions.");
  1162 	if(newapi_post_table) {
  1163 		META_CONS("NEWAPI-Post functions:");
  1164 		SHOW_DEF_NEWAPI(newapi_post_table, "   ", "_Post");
  1165 		META_CONS("%d functions (newapi post)", n);
  1166 	}
  1167 	else
  1168 		META_CONS("No NEWAPI-Post functions.");
  1169 
  1170 	if(engine_table) {
  1171 		META_CONS("Engine functions:");
  1172 		SHOW_DEF_ENGINE(engine_table, "   ", "");
  1173 		META_CONS("%d functions (engine)", n);
  1174 	}
  1175 	else
  1176 		META_CONS("No Engine functions.");
  1177 	if(engine_post_table) {
  1178 		META_CONS("Engine-Post functions:");
  1179 		SHOW_DEF_ENGINE(engine_post_table, "   ", "_Post");
  1180 		META_CONS("%d functions (engine post)", n);
  1181 	}
  1182 	else
  1183 		META_CONS("No Engine-Post functions.");
  1184 	RegCmds->show(index);
  1185 	RegCvars->show(index);
  1186 }
  1187 
  1188 // Check whether the file on disk looks like it's been updated since we
  1189 // last loaded the plugin.
  1190 // meta_errno values:
  1191 //  - ME_NOFILE		couldn't find file
  1192 //  - ME_NOERROR	no error; false indicates file not newer
  1193 mBOOL MPlugin::newer_file(void) {
  1194 	struct stat st;
  1195 	time_t file_time;
  1196 
  1197 	if(stat(pathname, &st) != 0)
  1198 		RETURN_ERRNO(mFALSE, ME_NOFILE);
  1199 	file_time=max(st.st_ctime, st.st_mtime);
  1200 	META_DEBUG(5, ("newer_file? file=%s; load=%d, file=%d; ctime=%d, mtime=%d",
  1201 				file, time_loaded, file_time, st.st_ctime, st.st_mtime));
  1202 	if(file_time > time_loaded)
  1203 		return(mTRUE);
  1204 	else
  1205 		RETURN_ERRNO(mFALSE, ME_NOERROR);
  1206 }
  1207 
  1208 // Return a string describing status of plugin.
  1209 // SIMPLE is the default.
  1210 // SHOW is max 4 chars, for "show" output.
  1211 // meta_errno values:
  1212 //  - none
  1213 char *MPlugin::str_status(STR_STATUS fmt) {
  1214 	switch(status) {
  1215 		case PL_EMPTY:
  1216 			if(fmt==ST_SHOW) return("empt");
  1217 			else return("empty");
  1218 		case PL_VALID:
  1219 			if(fmt==ST_SHOW) return("info");
  1220 			else return("valid");
  1221 		case PL_BADFILE:
  1222 			if(fmt==ST_SHOW) return("badf");
  1223 			else return("badfile");
  1224 		case PL_OPENED:
  1225 			if(fmt==ST_SHOW) return("open");
  1226 			else return("opened");
  1227 		case PL_FAILED:
  1228 			if(fmt==ST_SHOW) return("fail");
  1229 			else return("failed");
  1230 		case PL_RUNNING:
  1231 			if(fmt==ST_SHOW) return("RUN");
  1232 			else return("running");
  1233 		case PL_PAUSED:
  1234 			if(fmt==ST_SHOW) return("PAUS");
  1235 			else return("paused");
  1236 		default:
  1237 			if(fmt==ST_SHOW) return(UTIL_VarArgs("UNK%d", status));
  1238 			return(UTIL_VarArgs("unknown (%d)", status));
  1239 	}
  1240 }
  1241 
  1242 // Return a string (one word) describing requested action for plugin.
  1243 // SIMPLE is the default.
  1244 // SHOW is max 4 chars, for "show" output.
  1245 // meta_errno values:
  1246 //  - none
  1247 char *MPlugin::str_action(STR_ACTION fmt) {
  1248 	switch(action) {
  1249 		case PA_NULL:
  1250 			if(fmt==SA_SHOW) return("NULL");
  1251 			else return("null");
  1252 		case PA_NONE:
  1253 			if(fmt==SA_SHOW) return(" -  ");
  1254 			else return("none");
  1255 		case PA_KEEP:
  1256 			if(fmt==SA_SHOW) return("keep");
  1257 			else return("keep");
  1258 		case PA_LOAD:
  1259 			if(fmt==SA_SHOW) return("load");
  1260 			else return("load");
  1261 		case PA_ATTACH:
  1262 			if(fmt==SA_SHOW) return("atch");
  1263 			else return("attach");
  1264 		case PA_UNLOAD:
  1265 			if(fmt==SA_SHOW) return("unld");
  1266 			else return("unload");
  1267 		case PA_RELOAD:
  1268 			if(fmt==SA_SHOW) return("relo");
  1269 			else return("reload");
  1270 		default:
  1271 			if(fmt==SA_SHOW) return(UTIL_VarArgs("UNK%d", action));
  1272 			else return(UTIL_VarArgs("unknown (%d)", action));
  1273 	}
  1274 }
  1275 
  1276 // Return a string describing given plugin loadtime.
  1277 // SIMPLE is the default.
  1278 // SHOW is max 3 chars, for "show" output.
  1279 // ALLOWED is in terms of when it's allowed to load/unload.
  1280 // NOW is to describe current situation of load/unload attempt.
  1281 // meta_errno values:
  1282 //  - none
  1283 char *MPlugin::str_loadtime(PLUG_LOADTIME ptime, STR_LOADTIME fmt) {
  1284 	switch(ptime) {
  1285 		case PT_NEVER:
  1286 			if(fmt==SL_SHOW) return("Never");
  1287 			else return("never");
  1288 		case PT_STARTUP:
  1289 			if(fmt==SL_SHOW) return("Start");
  1290 			else if(fmt==SL_ALLOWED) return("at server startup");
  1291 			else if(fmt==SL_NOW) return("during server startup");
  1292 			else return("startup");
  1293 		case PT_CHANGELEVEL:
  1294 			if(fmt==SL_SHOW) return("Chlvl");
  1295 			else if(fmt==SL_ALLOWED) return("at changelevel");
  1296 			else if(fmt==SL_NOW) return("during changelevel");
  1297 			else return("changelevel");
  1298 		case PT_ANYTIME:
  1299 			if(fmt==SL_SHOW) return("ANY");
  1300 			else if(fmt==SL_ALLOWED) return("at any time");
  1301 			else if(fmt==SL_NOW) return("during map");
  1302 			else return("anytime");
  1303 		case PT_ANYPAUSE:
  1304 			if(fmt==SL_SHOW) return("Pause");
  1305 			else if(fmt==SL_ALLOWED) return("at any time, and pausable");
  1306 			else if(fmt==SL_NOW) return("for requested pause");
  1307 			else return("pausable");
  1308 		default:
  1309 			if(fmt==SL_SHOW) return(UTIL_VarArgs("UNK-%d", ptime));
  1310 			else return(UTIL_VarArgs("unknown (%d)", ptime));
  1311 	}
  1312 }
  1313 
  1314 // Return a string describing why a plugin is to be unloaded.
  1315 // meta_errno values:
  1316 //  - none
  1317 char *MPlugin::str_reason(PL_UNLOAD_REASON preason) {
  1318 	switch(preason) {
  1319 		case PNL_NULL:
  1320 			return("null");
  1321 		case PNL_INI_DELETED:
  1322 			return("deleted from ini file");
  1323 		case PNL_FILE_NEWER:
  1324 			return("file on disk is newer");
  1325 		case PNL_COMMAND:
  1326 			return("server command");
  1327 		case PNL_CMD_FORCED:
  1328 			return("forced by server command");
  1329 		default:
  1330 			return(UTIL_VarArgs("unknown (%d)", preason));
  1331 	}
  1332 }
  1333 
  1334 // Return a string describing how the plugin was loaded.
  1335 // meta_errno values:
  1336 //  - none
  1337 char *MPlugin::str_source(STR_SOURCE fmt) {
  1338 	switch(source) {
  1339 		case PS_INI:
  1340 			if(fmt==SO_SHOW) return("ini");
  1341 			else return("ini file");
  1342 		case PS_CMD:
  1343 			if(fmt==SO_SHOW) return("cmd");
  1344 			else return("console command");
  1345 		default:
  1346 			if(fmt==SO_SHOW) return(UTIL_VarArgs("UNK%d", source));
  1347 			else return(UTIL_VarArgs("unknown (%d)", source));
  1348 	}
  1349 }