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