1 /* modules.c
2  * This is the implementation of syslogd modules object.
3  * This object handles plug-ins and build-in modules of all kind.
4  *
5  * Modules are reference-counted. Anyone who access a module must call
6  * Use() before any function is accessed and Release() when he is done.
7  * When the reference count reaches 0, rsyslog unloads the module (that
8  * may be changed in the future to cache modules). Rsyslog does NOT
9  * unload modules with a reference count > 0, even if the unload
10  * method is called!
11  *
12  * File begun on 2007-07-22 by RGerhards
13  *
14  * Copyright 2007-2018 Rainer Gerhards and Adiscon GmbH.
15  *
16  * This file is part of the rsyslog runtime library.
17  *
18  * The rsyslog runtime library is free software: you can redistribute it and/or modify
19  * it under the terms of the GNU Lesser General Public License as published by
20  * the Free Software Foundation, either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * The rsyslog runtime library is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU Lesser General Public License for more details.
27  *
28  * You should have received a copy of the GNU Lesser General Public License
29  * along with the rsyslog runtime library.  If not, see <http://www.gnu.org/licenses/>.
30  *
31  * A copy of the GPL can be found in the file "COPYING" in this distribution.
32  * A copy of the LGPL can be found in the file "COPYING.LESSER" in this distribution.
33  */
34 #include "config.h"
35 #include <stdio.h>
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <time.h>
40 #include <assert.h>
41 #include <errno.h>
42 #include <pthread.h>
43 #ifdef	OS_BSD
44 #	include "libgen.h"
45 #endif
46 
47 #include <dlfcn.h> /* TODO: replace this with the libtools equivalent! */
48 
49 #include <unistd.h>
50 #include <sys/file.h>
51 
52 #include "rsyslog.h"
53 #include "rainerscript.h"
54 #include "cfsysline.h"
55 #include "rsconf.h"
56 #include "modules.h"
57 #include "errmsg.h"
58 #include "parser.h"
59 #include "strgen.h"
60 
61 /* static data */
62 DEFobjStaticHelpers
63 DEFobjCurrIf(strgen)
64 
65 static modInfo_t *pLoadedModules = NULL;	/* list of currently-loaded modules */
66 static modInfo_t *pLoadedModulesLast = NULL;	/* tail-pointer */
67 
68 /* already dlopen()-ed libs */
69 static struct dlhandle_s *pHandles = NULL;
70 
71 static uchar *pModDir;		/* directory where loadable modules are found */
72 
73 /* tables for interfacing with the v6 config system */
74 /* action (instance) parameters */
75 static struct cnfparamdescr actpdescr[] = {
76 	{ "load", eCmdHdlrGetWord, 1 }
77 };
78 static struct cnfparamblk pblk =
79 	{ CNFPARAMBLK_VERSION,
80 	  sizeof(actpdescr)/sizeof(struct cnfparamdescr),
81 	  actpdescr
82 	};
83 
84 
85 typedef rsRetVal (*pModInit_t)(int,int*, rsRetVal(**)(), rsRetVal(*)(), modInfo_t*);
86 
87 /* we provide a set of dummy functions for modules that do not support the
88  * some interfaces.
89  * On the commit feature: As the modules do not support it, they commit each message they
90  * receive, and as such the dummies can always return RS_RET_OK without causing
91  * harm. This simplifies things as in action processing we do not need to check
92  * if the transactional entry points exist.
93  */
94 static rsRetVal
dummyBeginTransaction(void * dummy)95 dummyBeginTransaction(__attribute__((unused)) void * dummy)
96 {
97 	return RS_RET_OK;
98 }
99 static rsRetVal
dummyEndTransaction(void * dummy)100 dummyEndTransaction(__attribute__((unused)) void * dummy)
101 {
102 	return RS_RET_OK;
103 }
104 static rsRetVal
dummyIsCompatibleWithFeature(syslogFeature eFeat)105 dummyIsCompatibleWithFeature(__attribute__((unused)) syslogFeature eFeat)
106 {
107 	return RS_RET_INCOMPATIBLE;
108 }
109 static rsRetVal
dummynewActInst(uchar * modName,struct nvlst * dummy1,void ** dummy2,omodStringRequest_t ** dummy3)110 dummynewActInst(uchar *modName, struct nvlst __attribute__((unused)) *dummy1,
111 		void __attribute__((unused)) **dummy2, omodStringRequest_t __attribute__((unused)) **dummy3)
112 {
113 	LogError(0, RS_RET_CONFOBJ_UNSUPPORTED, "config objects are not "
114 			"supported by module '%s' -- legacy config options "
115 			"MUST be used instead", modName);
116 	return RS_RET_CONFOBJ_UNSUPPORTED;
117 }
118 
119 #ifdef DEBUG
120 /* we add some home-grown support to track our users (and detect who does not free us). In
121  * the long term, this should probably be migrated into debug.c (TODO). -- rgerhards, 2008-03-11
122  */
123 
124 /* add a user to the current list of users (always at the root) */
125 static void
modUsrAdd(modInfo_t * pThis,const char * pszUsr)126 modUsrAdd(modInfo_t *pThis, const char *pszUsr)
127 {
128 	modUsr_t *pUsr;
129 
130 	if((pUsr = calloc(1, sizeof(modUsr_t))) == NULL)
131 		goto finalize_it;
132 
133 	if((pUsr->pszFile = strdup(pszUsr)) == NULL) {
134 		free(pUsr);
135 		goto finalize_it;
136 	}
137 
138 	if(pThis->pModUsrRoot != NULL) {
139 		pUsr->pNext = pThis->pModUsrRoot;
140 	}
141 	pThis->pModUsrRoot = pUsr;
142 
143 finalize_it:
144 	return;
145 }
146 
147 
148 /* remove a user from the current user list
149  * rgerhards, 2008-03-11
150  */
151 static void
modUsrDel(modInfo_t * pThis,const char * pszUsr)152 modUsrDel(modInfo_t *pThis, const char *pszUsr)
153 {
154 	modUsr_t *pUsr;
155 	modUsr_t *pPrev = NULL;
156 
157 	for(pUsr = pThis->pModUsrRoot ; pUsr != NULL ; pUsr = pUsr->pNext) {
158 		if(!strcmp(pUsr->pszFile, pszUsr))
159 			break;
160 		else
161 			pPrev = pUsr;
162 	}
163 
164 	if(pUsr == NULL) {
165 		dbgprintf("oops - tried to delete user %s from module %s and it wasn't registered as one...\n",
166 			  pszUsr, pThis->pszName);
167 	} else {
168 		if(pPrev == NULL) {
169 			/* This was at the root! */
170 			pThis->pModUsrRoot = pUsr->pNext;
171 		} else {
172 			pPrev->pNext = pUsr->pNext;
173 		}
174 		/* free ressources */
175 		free(pUsr->pszFile);
176 		free(pUsr);
177 		pUsr = NULL; /* just to make sure... */
178 	}
179 }
180 
181 
182 /* print a short list all all source files using the module in question
183  * rgerhards, 2008-03-11
184  */
185 static void
modUsrPrint(modInfo_t * pThis)186 modUsrPrint(modInfo_t *pThis)
187 {
188 	modUsr_t *pUsr;
189 
190 	for(pUsr = pThis->pModUsrRoot ; pUsr != NULL ; pUsr = pUsr->pNext) {
191 		dbgprintf("\tmodule %s is currently in use by file %s\n",
192 			  pThis->pszName, pUsr->pszFile);
193 	}
194 }
195 
196 
197 /* print all loaded modules and who is accessing them. This is primarily intended
198  * to be called at end of run to detect "module leaks" and who is causing them.
199  * rgerhards, 2008-03-11
200  */
201 static void
modUsrPrintAll(void)202 modUsrPrintAll(void)
203 {
204 	modInfo_t *pMod;
205 
206 	for(pMod = pLoadedModules ; pMod != NULL ; pMod = pMod->pNext) {
207 		dbgprintf("printing users of loadable module %s, refcount %u, ptr %p, type %d\n",
208 		pMod->pszName, pMod->uRefCnt, pMod, pMod->eType);
209 		modUsrPrint(pMod);
210 	}
211 }
212 
213 #endif /* #ifdef DEBUG */
214 
215 
216 /* Construct a new module object
217  */
moduleConstruct(modInfo_t ** pThis)218 static rsRetVal moduleConstruct(modInfo_t **pThis)
219 {
220 	modInfo_t *pNew;
221 
222 	if((pNew = calloc(1, sizeof(modInfo_t))) == NULL)
223 		return RS_RET_OUT_OF_MEMORY;
224 
225 	/* OK, we got the element, now initialize members that should
226 	 * not be zero-filled.
227 	 */
228 
229 	*pThis = pNew;
230 	return RS_RET_OK;
231 }
232 
233 
234 /* Destructs a module object. The object must not be linked to the
235  * linked list of modules. Please note that all other dependencies on this
236  * modules must have been removed before (e.g. CfSysLineHandlers!)
237  */
moduleDestruct(modInfo_t * pThis)238 static void moduleDestruct(modInfo_t *pThis)
239 {
240 	assert(pThis != NULL);
241 	free(pThis->pszName);
242 	free(pThis->cnfName);
243 	if(pThis->pModHdlr != NULL) {
244 #	ifdef	VALGRIND
245 		DBGPRINTF("moduleDestruct: compiled with valgrind, do "
246 			"not unload module\n");
247 #	else
248 		if(glblUnloadModules) {
249 			if(pThis->eKeepType == eMOD_NOKEEP) {
250 				dlclose(pThis->pModHdlr);
251 			}
252 		} else {
253 			DBGPRINTF("moduleDestruct: not unloading module "
254 				"due to user configuration\n");
255 		}
256 #	endif
257 	}
258 
259 	free(pThis);
260 }
261 
262 
263 /* This enables a module to query the core for specific features.
264  * rgerhards, 2009-04-22
265  */
queryCoreFeatureSupport(int * pBool,unsigned uFeat)266 static rsRetVal queryCoreFeatureSupport(int *pBool, unsigned uFeat)
267 {
268 	DEFiRet;
269 
270 	if(pBool == NULL)
271 		ABORT_FINALIZE(RS_RET_PARAM_ERROR);
272 
273 	*pBool = (uFeat & CORE_FEATURE_BATCHING) ? 1 : 0;
274 
275 finalize_it:
276 	RETiRet;
277 }
278 
279 
280 /* The following function is the queryEntryPoint for host-based entry points.
281  * Modules may call it to get access to core interface functions. Please note
282  * that utility functions can be accessed via shared libraries - at least this
283  * is my current shool of thinking.
284  * Please note that the implementation as a query interface allows to take
285  * care of plug-in interface version differences. -- rgerhards, 2007-07-31
286  * ... but often it better not to use a new interface. So we now add core
287  * functions here that a plugin may request. -- rgerhards, 2009-04-22
288  */
queryHostEtryPt(uchar * name,rsRetVal (** pEtryPoint)())289 static rsRetVal queryHostEtryPt(uchar *name, rsRetVal (**pEtryPoint)())
290 {
291 	DEFiRet;
292 
293 	if((name == NULL) || (pEtryPoint == NULL))
294 		ABORT_FINALIZE(RS_RET_PARAM_ERROR);
295 
296 	if(!strcmp((char*) name, "regCfSysLineHdlr")) {
297 		*pEtryPoint = regCfSysLineHdlr;
298 	} else if(!strcmp((char*) name, "objGetObjInterface")) {
299 		*pEtryPoint = objGetObjInterface;
300 	} else if(!strcmp((char*) name, "OMSRgetSupportedTplOpts")) {
301 		*pEtryPoint = OMSRgetSupportedTplOpts;
302 	} else if(!strcmp((char*) name, "queryCoreFeatureSupport")) {
303 		*pEtryPoint = queryCoreFeatureSupport;
304 	} else {
305 		*pEtryPoint = NULL; /* to  be on the safe side */
306 		ABORT_FINALIZE(RS_RET_ENTRY_POINT_NOT_FOUND);
307 	}
308 
309 finalize_it:
310 	RETiRet;
311 }
312 
313 
314 /* get the name of a module
315  */
316 uchar *
modGetName(modInfo_t * pThis)317 modGetName(modInfo_t *pThis)
318 {
319 	return((pThis->pszName == NULL) ? (uchar*) "" : pThis->pszName);
320 }
321 
322 
323 /* get the state-name of a module. The state name is its name
324  * together with a short description of the module state (which
325  * is pulled from the module itself.
326  * rgerhards, 2007-07-24
327  * TODO: the actual state name is not yet pulled
328  */
modGetStateName(modInfo_t * pThis)329 static uchar *modGetStateName(modInfo_t *pThis)
330 {
331 	return(modGetName(pThis));
332 }
333 
334 
335 /* Add a module to the loaded module linked list
336  */
ATTR_NONNULL()337 static void ATTR_NONNULL()
338 addModToGlblList(modInfo_t *const pThis)
339 {
340 	assert(pThis != NULL);
341 
342 	if(pLoadedModules == NULL) {
343 		pLoadedModules = pLoadedModulesLast = pThis;
344 	} else {
345 		/* there already exist entries */
346 		pThis->pPrev = pLoadedModulesLast;
347 		pLoadedModulesLast->pNext = pThis;
348 		pLoadedModulesLast = pThis;
349 	}
350 }
351 
352 
353 /* ready module for config processing. this includes checking if the module
354  * is already in the config, so this function may return errors. Returns a
355  * pointer to the last module inthe current config. That pointer needs to
356  * be passed to addModToCnfLst() when it is called later in the process.
357  */
358 rsRetVal
readyModForCnf(modInfo_t * pThis,cfgmodules_etry_t ** ppNew,cfgmodules_etry_t ** ppLast)359 readyModForCnf(modInfo_t *pThis, cfgmodules_etry_t **ppNew, cfgmodules_etry_t **ppLast)
360 {
361 	cfgmodules_etry_t *pNew = NULL;
362 	cfgmodules_etry_t *pLast;
363 	DEFiRet;
364 	assert(pThis != NULL);
365 
366 	if(loadConf == NULL) {
367 		FINALIZE; /* we are in an early init state */
368 	}
369 
370 	/* check for duplicates and, as a side-activity, identify last node */
371 	pLast = loadConf->modules.root;
372 	if(pLast != NULL) {
373 		while(1) { /* loop broken inside */
374 			if(pLast->pMod == pThis) {
375 				DBGPRINTF("module '%s' already in this config\n", modGetName(pThis));
376 				if(strncmp((char*)modGetName(pThis), "builtin:", sizeof("builtin:")-1)) {
377 					LogError(0, RS_RET_MODULE_ALREADY_IN_CONF,
378 					   "module '%s' already in this config, cannot be added\n", modGetName(pThis));
379 					ABORT_FINALIZE(RS_RET_MODULE_ALREADY_IN_CONF);
380 				}
381 				FINALIZE;
382 			}
383 			if(pLast->next == NULL)
384 				break;
385 			pLast = pLast->next;
386 		}
387 	}
388 
389 	/* if we reach this point, pLast is the tail pointer and this module is new
390 	 * inside the currently loaded config. So, iff it is an input module, let's
391 	 * pass it a pointer which it can populate with a pointer to its module conf.
392 	 */
393 
394 	CHKmalloc(pNew = malloc(sizeof(cfgmodules_etry_t)));
395 	pNew->canActivate = 1;
396 	pNew->next = NULL;
397 	pNew->pMod = pThis;
398 
399 	if(pThis->beginCnfLoad != NULL) {
400 		CHKiRet(pThis->beginCnfLoad(&pNew->modCnf, loadConf));
401 	}
402 
403 	*ppLast = pLast;
404 	*ppNew = pNew;
405 finalize_it:
406 	if(iRet != RS_RET_OK) {
407 		if(pNew != NULL)
408 			free(pNew);
409 	}
410 	RETiRet;
411 }
412 
413 
414 /* abort the creation of a module entry without adding it to the
415  * module list. Needed to prevent mem leaks.
416  */
417 static inline void
abortCnfUse(cfgmodules_etry_t ** pNew)418 abortCnfUse(cfgmodules_etry_t **pNew)
419 {
420 	if(pNew != NULL) {
421 		free(*pNew);
422 		*pNew = NULL;
423 	}
424 }
425 
426 
427 /* Add a module to the config module list for current loadConf.
428  * Requires last pointer obtained by readyModForCnf().
429  * The module pointer is handed over to this function. It is no
430  * longer available to caller one we are called.
431  */
432 rsRetVal ATTR_NONNULL(1)
addModToCnfList(cfgmodules_etry_t ** const pNew,cfgmodules_etry_t * const pLast)433 addModToCnfList(cfgmodules_etry_t **const pNew, cfgmodules_etry_t *const pLast)
434 {
435 	DEFiRet;
436 	assert(*pNew != NULL);
437 
438 	if(loadConf == NULL) {
439 		abortCnfUse(pNew);
440 		FINALIZE; /* we are in an early init state */
441 	}
442 
443 	if(pLast == NULL) {
444 		loadConf->modules.root = *pNew;
445 	} else {
446 		/* there already exist entries */
447 		pLast->next = *pNew;
448 	}
449 
450 finalize_it:
451 	*pNew = NULL;
452 	RETiRet;
453 }
454 
455 
456 /* Get the next module pointer - this is used to traverse the list.
457  * The function returns the next pointer or NULL, if there is no next one.
458  * The last object must be provided to the function. If NULL is provided,
459  * it starts at the root of the list. Even in this case, NULL may be
460  * returned - then, the list is empty.
461  * rgerhards, 2007-07-23
462  */
GetNxt(modInfo_t * pThis)463 static modInfo_t *GetNxt(modInfo_t *pThis)
464 {
465 	modInfo_t *pNew;
466 
467 	if(pThis == NULL)
468 		pNew = pLoadedModules;
469 	else
470 		pNew = pThis->pNext;
471 
472 	return(pNew);
473 }
474 
475 
476 /* this function is like GetNxt(), but it returns pointers to
477  * the configmodules entry, which than can be used to obtain the
478  * actual module pointer. Note that it returns those for
479  * modules of specific type only. Only modules from the provided
480  * config are returned. Note that processing speed could be improved,
481  * but this is really not relevant, as config file loading is not really
482  * something we are concerned about in regard to runtime.
483  */
484 static cfgmodules_etry_t
GetNxtCnfType(rsconf_t * cnf,cfgmodules_etry_t * node,eModType_t rqtdType)485 *GetNxtCnfType(rsconf_t *cnf, cfgmodules_etry_t *node, eModType_t rqtdType)
486 {
487 	if(node == NULL) { /* start at beginning of module list */
488 		node = cnf->modules.root;
489 	} else {
490 		node = node->next;
491 	}
492 
493 	if(rqtdType != eMOD_ANY) { /* if any, we already have the right one! */
494 		while(node != NULL && node->pMod->eType != rqtdType) {
495 			node = node->next;
496 		}
497 	}
498 
499 	return node;
500 }
501 
502 
503 /* Find a module with the given conf name and type. Returns NULL if none
504  * can be found, otherwise module found.
505  */
506 static modInfo_t *
FindWithCnfName(rsconf_t * cnf,uchar * name,eModType_t rqtdType)507 FindWithCnfName(rsconf_t *cnf, uchar *name, eModType_t rqtdType)
508 {
509 	cfgmodules_etry_t *node;
510 
511 	;
512 	for(  node = cnf->modules.root
513 	    ; node != NULL
514 	    ; node = node->next) {
515 		if(node->pMod->eType != rqtdType || node->pMod->cnfName == NULL)
516 			continue;
517 		if(!strcasecmp((char*)node->pMod->cnfName, (char*)name))
518 			break;
519 	}
520 
521 	return node == NULL ? NULL : node->pMod;
522 }
523 
524 
525 /* Prepare a module for unloading.
526  * This is currently a dummy, to be filled when we have a plug-in
527  * interface - rgerhards, 2007-08-09
528  * rgerhards, 2007-11-21:
529  * When this function is called, all instance-data must already have
530  * been destroyed. In the case of output modules, this happens when the
531  * rule set is being destroyed. When we implement other module types, we
532  * need to think how we handle it there (and if we have any instance data).
533  * rgerhards, 2008-03-10: reject unload request if the module has a reference
534  * count > 0.
535  */
536 static rsRetVal
modPrepareUnload(modInfo_t * pThis)537 modPrepareUnload(modInfo_t *pThis)
538 {
539 	DEFiRet;
540 	void *pModCookie;
541 
542 	assert(pThis != NULL);
543 
544 	if(pThis->uRefCnt > 0) {
545 		dbgprintf("rejecting unload of module '%s' because it has a refcount of %d\n",
546 			  pThis->pszName, pThis->uRefCnt);
547 		ABORT_FINALIZE(RS_RET_MODULE_STILL_REFERENCED);
548 	}
549 
550 	CHKiRet(pThis->modGetID(&pModCookie));
551 	pThis->modExit(); /* tell the module to get ready for unload */
552 	CHKiRet(unregCfSysLineHdlrs4Owner(pModCookie));
553 
554 finalize_it:
555 	RETiRet;
556 }
557 
558 
559 /* Add an already-loaded module to the module linked list. This function does
560  * everything needed to fully initialize the module.
561  */
562 static rsRetVal
doModInit(pModInit_t modInit,uchar * name,void * pModHdlr,modInfo_t ** pNewModule)563 doModInit(pModInit_t modInit, uchar *name, void *pModHdlr, modInfo_t **pNewModule)
564 {
565 	rsRetVal localRet;
566 	modInfo_t *pNew = NULL;
567 	uchar *pName;
568 	strgen_t *pStrgen; /* used for strgen modules */
569 	rsRetVal (*GetName)(uchar**);
570 	rsRetVal (*modGetType)(eModType_t *pType);
571 	rsRetVal (*modGetKeepType)(eModKeepType_t *pKeepType);
572 	struct dlhandle_s *pHandle = NULL;
573 	rsRetVal (*getModCnfName)(uchar **cnfName);
574 	uchar *cnfName;
575 	DEFiRet;
576 
577 	assert(modInit != NULL);
578 
579 	if((iRet = moduleConstruct(&pNew)) != RS_RET_OK) {
580 		pNew = NULL;
581 		FINALIZE;
582 	}
583 
584 	CHKiRet((*modInit)(CURR_MOD_IF_VERSION, &pNew->iIFVers, &pNew->modQueryEtryPt, queryHostEtryPt, pNew));
585 
586 	if(pNew->iIFVers != CURR_MOD_IF_VERSION) {
587 		ABORT_FINALIZE(RS_RET_MISSING_INTERFACE);
588 	}
589 
590 	/* We now poll the module to see what type it is. We do this only once as this
591 	 * can never change in the lifetime of an module. -- rgerhards, 2007-12-14
592 	 */
593 	CHKiRet((*pNew->modQueryEtryPt)((uchar*)"getType", &modGetType));
594 	CHKiRet((*modGetType)(&pNew->eType));
595 	CHKiRet((*pNew->modQueryEtryPt)((uchar*)"getKeepType", &modGetKeepType));
596 	CHKiRet((*modGetKeepType)(&pNew->eKeepType));
597 	dbgprintf("module %s of type %d being loaded (keepType=%d).\n", name, pNew->eType, pNew->eKeepType);
598 
599 	/* OK, we know we can successfully work with the module. So we now fill the
600 	 * rest of the data elements. First we load the interfaces common to all
601 	 * module types.
602 	 */
603 	CHKiRet((*pNew->modQueryEtryPt)((uchar*)"modGetID", &pNew->modGetID));
604 	CHKiRet((*pNew->modQueryEtryPt)((uchar*)"modExit", &pNew->modExit));
605 	localRet = (*pNew->modQueryEtryPt)((uchar*)"isCompatibleWithFeature", &pNew->isCompatibleWithFeature);
606 	if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND)
607 		pNew->isCompatibleWithFeature = dummyIsCompatibleWithFeature;
608 	else if(localRet != RS_RET_OK)
609 		ABORT_FINALIZE(localRet);
610 	localRet = (*pNew->modQueryEtryPt)((uchar*)"setModCnf", &pNew->setModCnf);
611 	if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND)
612 		pNew->setModCnf = NULL;
613 	else if(localRet != RS_RET_OK)
614 		ABORT_FINALIZE(localRet);
615 
616 	/* optional calls for new config system */
617 	localRet = (*pNew->modQueryEtryPt)((uchar*)"getModCnfName", &getModCnfName);
618 	if(localRet == RS_RET_OK) {
619 		if(getModCnfName(&cnfName) == RS_RET_OK)
620 			pNew->cnfName = (uchar*) strdup((char*)cnfName);
621 			  /**< we do not care if strdup() fails, we can accept that */
622 		else
623 			pNew->cnfName = NULL;
624 		dbgprintf("module config name is '%s'\n", cnfName);
625 	}
626 	localRet = (*pNew->modQueryEtryPt)((uchar*)"beginCnfLoad", &pNew->beginCnfLoad);
627 	if(localRet == RS_RET_OK) {
628 		dbgprintf("module %s supports rsyslog v6 config interface\n", name);
629 		CHKiRet((*pNew->modQueryEtryPt)((uchar*)"endCnfLoad", &pNew->endCnfLoad));
630 		CHKiRet((*pNew->modQueryEtryPt)((uchar*)"freeCnf", &pNew->freeCnf));
631 		CHKiRet((*pNew->modQueryEtryPt)((uchar*)"checkCnf", &pNew->checkCnf));
632 		CHKiRet((*pNew->modQueryEtryPt)((uchar*)"activateCnf", &pNew->activateCnf));
633 		localRet = (*pNew->modQueryEtryPt)((uchar*)"activateCnfPrePrivDrop", &pNew->activateCnfPrePrivDrop);
634 		if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND) {
635 			pNew->activateCnfPrePrivDrop = NULL;
636 		} else {
637 			CHKiRet(localRet);
638 		}
639 	} else if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND) {
640 		pNew->beginCnfLoad = NULL; /* flag as non-present */
641 	} else {
642 		ABORT_FINALIZE(localRet);
643 	}
644 	/* ... and now the module-specific interfaces */
645 	switch(pNew->eType) {
646 		case eMOD_IN:
647 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"runInput", &pNew->mod.im.runInput));
648 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"willRun", &pNew->mod.im.willRun));
649 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"afterRun", &pNew->mod.im.afterRun));
650 			pNew->mod.im.bCanRun = 0;
651 			localRet = (*pNew->modQueryEtryPt)((uchar*)"newInpInst", &pNew->mod.im.newInpInst);
652 			if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND) {
653 				pNew->mod.im.newInpInst = NULL;
654 			} else if(localRet != RS_RET_OK) {
655 				ABORT_FINALIZE(localRet);
656 			}
657 			localRet = (*pNew->modQueryEtryPt)((uchar*)"doHUP", &pNew->doHUP);
658 			if(localRet != RS_RET_OK && localRet != RS_RET_MODULE_ENTRY_POINT_NOT_FOUND)
659 				ABORT_FINALIZE(localRet);
660 
661 			break;
662 		case eMOD_OUT:
663 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"freeInstance", &pNew->freeInstance));
664 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"dbgPrintInstInfo", &pNew->dbgPrintInstInfo));
665 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"parseSelectorAct", &pNew->mod.om.parseSelectorAct));
666 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"tryResume", &pNew->tryResume));
667 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"createWrkrInstance",
668 				&pNew->mod.om.createWrkrInstance));
669 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"freeWrkrInstance",
670 				&pNew->mod.om.freeWrkrInstance));
671 
672 			/* try load optional interfaces */
673 			localRet = (*pNew->modQueryEtryPt)((uchar*)"doHUP", &pNew->doHUP);
674 			if(localRet != RS_RET_OK && localRet != RS_RET_MODULE_ENTRY_POINT_NOT_FOUND)
675 				ABORT_FINALIZE(localRet);
676 
677 			localRet = (*pNew->modQueryEtryPt)((uchar*)"doHUPWrkr", &pNew->doHUPWrkr);
678 			if(localRet != RS_RET_OK && localRet != RS_RET_MODULE_ENTRY_POINT_NOT_FOUND)
679 				ABORT_FINALIZE(localRet);
680 
681 			localRet = (*pNew->modQueryEtryPt)((uchar*)"SetShutdownImmdtPtr",
682 				&pNew->mod.om.SetShutdownImmdtPtr);
683 			if(localRet != RS_RET_OK && localRet != RS_RET_MODULE_ENTRY_POINT_NOT_FOUND)
684 				ABORT_FINALIZE(localRet);
685 
686 			pNew->mod.om.supportsTX = 1;
687 			localRet = (*pNew->modQueryEtryPt)((uchar*)"beginTransaction", &pNew->mod.om.beginTransaction);
688 			if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND) {
689 				pNew->mod.om.beginTransaction = dummyBeginTransaction;
690 				pNew->mod.om.supportsTX = 0;
691 			} else if(localRet != RS_RET_OK) {
692 				ABORT_FINALIZE(localRet);
693 			}
694 
695 			localRet = (*pNew->modQueryEtryPt)((uchar*)"doAction",
696 				   &pNew->mod.om.doAction);
697 			if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND) {
698 				pNew->mod.om.doAction = NULL;
699 			} else if(localRet != RS_RET_OK) {
700 				ABORT_FINALIZE(localRet);
701 			}
702 
703 			localRet = (*pNew->modQueryEtryPt)((uchar*)"commitTransaction",
704 				   &pNew->mod.om.commitTransaction);
705 			if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND) {
706 				pNew->mod.om.commitTransaction = NULL;
707 			} else if(localRet != RS_RET_OK) {
708 				ABORT_FINALIZE(localRet);
709 			}
710 
711 			if(pNew->mod.om.doAction == NULL && pNew->mod.om.commitTransaction == NULL) {
712 				LogError(0, RS_RET_INVLD_OMOD,
713 					"module %s does neither provide doAction() "
714 					"nor commitTransaction() interface - cannot "
715 					"load", name);
716 				ABORT_FINALIZE(RS_RET_INVLD_OMOD);
717 			}
718 
719 			if(pNew->mod.om.commitTransaction != NULL) {
720 				if(pNew->mod.om.doAction != NULL){
721 					LogError(0, RS_RET_INVLD_OMOD,
722 						"module %s provides both doAction() "
723 						"and commitTransaction() interface, using "
724 						"commitTransaction()", name);
725 					pNew->mod.om.doAction = NULL;
726 				}
727 				if(pNew->mod.om.beginTransaction == NULL){
728 					LogError(0, RS_RET_INVLD_OMOD,
729 						"module %s provides both commitTransaction() "
730 						"but does not provide beginTransaction() - "
731 						"cannot load", name);
732 					ABORT_FINALIZE(RS_RET_INVLD_OMOD);
733 				}
734 			}
735 
736 
737 			localRet = (*pNew->modQueryEtryPt)((uchar*)"endTransaction",
738 				   &pNew->mod.om.endTransaction);
739 			if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND) {
740 				pNew->mod.om.endTransaction = dummyEndTransaction;
741 			} else if(localRet != RS_RET_OK) {
742 				ABORT_FINALIZE(localRet);
743 			}
744 
745 			localRet = (*pNew->modQueryEtryPt)((uchar*)"newActInst", &pNew->mod.om.newActInst);
746 			if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND) {
747 				pNew->mod.om.newActInst = dummynewActInst;
748 			} else if(localRet != RS_RET_OK) {
749 				ABORT_FINALIZE(localRet);
750 			}
751 			break;
752 		case eMOD_LIB:
753 			break;
754 		case eMOD_PARSER:
755 			localRet = (*pNew->modQueryEtryPt)((uchar*)"parse2",
756 				   &pNew->mod.pm.parse2);
757 			if(localRet == RS_RET_OK) {
758 				pNew->mod.pm.parse = NULL;
759 				CHKiRet((*pNew->modQueryEtryPt)((uchar*)"newParserInst",
760 					&pNew->mod.pm.newParserInst));
761 				CHKiRet((*pNew->modQueryEtryPt)((uchar*)"freeParserInst",
762 					&pNew->mod.pm.freeParserInst));
763 			} else if(localRet == RS_RET_MODULE_ENTRY_POINT_NOT_FOUND) {
764 				pNew->mod.pm.parse2 = NULL;
765 				pNew->mod.pm.newParserInst = NULL;
766 				pNew->mod.pm.freeParserInst = NULL;
767 				CHKiRet((*pNew->modQueryEtryPt)((uchar*)"parse", &pNew->mod.pm.parse));
768 			} else {
769 				ABORT_FINALIZE(localRet);
770 			}
771 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"GetParserName", &GetName));
772 			CHKiRet(GetName(&pName));
773 			CHKiRet(parserConstructViaModAndName(pNew, pName, NULL));
774 			break;
775 		case eMOD_STRGEN:
776 			/* first, we need to obtain the strgen object. We could not do that during
777 			 * init as that would have caused class bootstrap issues which are not
778 			 * absolutely necessary. Note that we can call objUse() multiple times, it
779 			 * handles that.
780 			 */
781 			CHKiRet(objUse(strgen, CORE_COMPONENT));
782 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"strgen", &pNew->mod.sm.strgen));
783 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"GetName", &GetName));
784 			CHKiRet(GetName(&pName));
785 			CHKiRet(strgen.Construct(&pStrgen));
786 			CHKiRet(strgen.SetName(pStrgen, pName));
787 			CHKiRet(strgen.SetModPtr(pStrgen, pNew));
788 			CHKiRet(strgen.ConstructFinalize(pStrgen));
789 			break;
790 		case eMOD_FUNCTION:
791 			CHKiRet((*pNew->modQueryEtryPt)((uchar*)"getFunctArray", &pNew->mod.fm.getFunctArray));
792 			int version;
793 			struct scriptFunct *functArray;
794 			pNew->mod.fm.getFunctArray(&version, &functArray);
795 			dbgprintf("LLL: %s\n", functArray[0].fname);
796 			addMod2List(version, functArray);
797 			break;
798 		case eMOD_ANY: /* this is mostly to keep the compiler happy! */
799 			DBGPRINTF("PROGRAM ERROR: eMOD_ANY set as module type\n");
800 			assert(0);
801 			break;
802 	}
803 
804 	pNew->pszName = (uchar*) strdup((char*)name); /* we do not care if strdup() fails, we can accept that */
805 	pNew->pModHdlr = pModHdlr;
806 	if(pModHdlr == NULL) {
807 		pNew->eLinkType = eMOD_LINK_STATIC;
808 	} else {
809 		pNew->eLinkType = eMOD_LINK_DYNAMIC_LOADED;
810 
811 		/* if we need to keep the linked module, save it */
812 		if (pNew->eKeepType == eMOD_KEEP) {
813 			/* see if we have this one already */
814 			for (pHandle = pHandles; pHandle; pHandle = pHandle->next) {
815 				if (!strcmp((char *)name, (char *)pHandle->pszName))
816 					break;
817 			}
818 
819 			/* not found, create it */
820 			if (!pHandle) {
821 				if((pHandle = malloc(sizeof (*pHandle))) == NULL) {
822 					ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
823 				}
824 				if((pHandle->pszName = (uchar*) strdup((char*)name)) == NULL) {
825 					free(pHandle);
826 					ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
827 				}
828 				pHandle->pModHdlr = pModHdlr;
829 				pHandle->next = pHandles;
830 
831 				pHandles = pHandle;
832 			}
833 		}
834 	}
835 
836 	/* we initialized the structure, now let's add it to the linked list of modules */
837 	addModToGlblList(pNew);
838 	*pNewModule = pNew;
839 
840 finalize_it:
841 	if(iRet != RS_RET_OK) {
842 		if(pNew != NULL)
843 			moduleDestruct(pNew);
844 		*pNewModule = NULL;
845 	}
846 
847 	RETiRet;
848 }
849 
850 /* Print loaded modules. This is more or less a
851  * debug or test aid, but anyhow I think it's worth it...
852  * This only works if the dbgprintf() subsystem is initialized.
853  * TODO: update for new input modules!
854  */
modPrintList(void)855 static void modPrintList(void)
856 {
857 	modInfo_t *pMod;
858 
859 	pMod = GetNxt(NULL);
860 	while(pMod != NULL) {
861 		dbgprintf("Loaded Module: Name='%s', IFVersion=%d, ",
862 			(char*) modGetName(pMod), pMod->iIFVers);
863 		dbgprintf("type=");
864 		switch(pMod->eType) {
865 		case eMOD_OUT:
866 			dbgprintf("output");
867 			break;
868 		case eMOD_IN:
869 			dbgprintf("input");
870 			break;
871 		case eMOD_LIB:
872 			dbgprintf("library");
873 			break;
874 		case eMOD_PARSER:
875 			dbgprintf("parser");
876 			break;
877 		case eMOD_STRGEN:
878 			dbgprintf("strgen");
879 			break;
880 		case eMOD_FUNCTION:
881 			dbgprintf("function");
882 			break;
883 		case eMOD_ANY: /* this is mostly to keep the compiler happy! */
884 			DBGPRINTF("PROGRAM ERROR: eMOD_ANY set as module type\n");
885 			assert(0);
886 			break;
887 		}
888 		dbgprintf(" module.\n");
889 		dbgprintf("Entry points:\n");
890 		dbgprintf("\tqueryEtryPt:        0x%lx\n", (unsigned long) pMod->modQueryEtryPt);
891 		dbgprintf("\tdbgPrintInstInfo:   0x%lx\n", (unsigned long) pMod->dbgPrintInstInfo);
892 		dbgprintf("\tfreeInstance:       0x%lx\n", (unsigned long) pMod->freeInstance);
893 		dbgprintf("\tbeginCnfLoad:       0x%lx\n", (unsigned long) pMod->beginCnfLoad);
894 		dbgprintf("\tSetModCnf:          0x%lx\n", (unsigned long) pMod->setModCnf);
895 		dbgprintf("\tcheckCnf:           0x%lx\n", (unsigned long) pMod->checkCnf);
896 		dbgprintf("\tactivateCnfPrePrivDrop: 0x%lx\n", (unsigned long) pMod->activateCnfPrePrivDrop);
897 		dbgprintf("\tactivateCnf:        0x%lx\n", (unsigned long) pMod->activateCnf);
898 		dbgprintf("\tfreeCnf:            0x%lx\n", (unsigned long) pMod->freeCnf);
899 		switch(pMod->eType) {
900 		case eMOD_OUT:
901 			dbgprintf("Output Module Entry Points:\n");
902 			dbgprintf("\tdoAction:           %p\n", pMod->mod.om.doAction);
903 			dbgprintf("\tparseSelectorAct:   %p\n", pMod->mod.om.parseSelectorAct);
904 			dbgprintf("\tnewActInst:         %p\n", (pMod->mod.om.newActInst == dummynewActInst) ?
905 						NULL :  pMod->mod.om.newActInst);
906 			dbgprintf("\ttryResume:          %p\n", pMod->tryResume);
907 			dbgprintf("\tdoHUP:              %p\n", pMod->doHUP);
908 			dbgprintf("\tBeginTransaction:   %p\n", ((pMod->mod.om.beginTransaction ==
909 						dummyBeginTransaction) ? NULL :  pMod->mod.om.beginTransaction));
910 			dbgprintf("\tEndTransaction:     %p\n", ((pMod->mod.om.endTransaction ==
911 						dummyEndTransaction) ? NULL :  pMod->mod.om.endTransaction));
912 			break;
913 		case eMOD_IN:
914 			dbgprintf("Input Module Entry Points\n");
915 			dbgprintf("\trunInput:           0x%lx\n", (unsigned long) pMod->mod.im.runInput);
916 			dbgprintf("\twillRun:            0x%lx\n", (unsigned long) pMod->mod.im.willRun);
917 			dbgprintf("\tafterRun:           0x%lx\n", (unsigned long) pMod->mod.im.afterRun);
918 			break;
919 		case eMOD_LIB:
920 			break;
921 		case eMOD_PARSER:
922 			dbgprintf("Parser Module Entry Points\n");
923 			dbgprintf("\tparse:              0x%lx\n", (unsigned long) pMod->mod.pm.parse);
924 			break;
925 		case eMOD_STRGEN:
926 			dbgprintf("Strgen Module Entry Points\n");
927 			dbgprintf("\tstrgen:            0x%lx\n", (unsigned long) pMod->mod.sm.strgen);
928 			break;
929 		case eMOD_FUNCTION:
930 			dbgprintf("Function Module Entry Points\n");
931 			dbgprintf("\tgetFunctArray:     0x%lx\n", (unsigned long) pMod->mod.fm.getFunctArray);
932 			break;
933 		case eMOD_ANY: /* this is mostly to keep the compiler happy! */
934 			break;
935 		}
936 		dbgprintf("\n");
937 		pMod = GetNxt(pMod); /* done, go next */
938 	}
939 }
940 
941 
942 /* HUP all modules that support it - except for actions, which
943  * need (and have) specialised HUP handling.
944  */
945 void
modDoHUP(void)946 modDoHUP(void)
947 {
948 	modInfo_t *pMod;
949 
950 	pthread_mutex_lock(&mutObjGlobalOp);
951 	pMod = GetNxt(NULL);
952 	while(pMod != NULL) {
953 		if(pMod->eType != eMOD_OUT && pMod->doHUP != NULL) {
954 			DBGPRINTF("HUPing module %s\n", (char*) modGetName(pMod));
955 			pMod->doHUP(NULL);
956 		}
957 		pMod = GetNxt(pMod); /* done, go next */
958 	}
959 	pthread_mutex_unlock(&mutObjGlobalOp);
960 }
961 
962 
963 /* unlink and destroy a module. The caller must provide a pointer to the module
964  * itself as well as one to its immediate predecessor.
965  * rgerhards, 2008-02-26
966  */
967 static rsRetVal
modUnlinkAndDestroy(modInfo_t ** ppThis)968 modUnlinkAndDestroy(modInfo_t **ppThis)
969 {
970 	DEFiRet;
971 	modInfo_t *pThis;
972 
973 	assert(ppThis != NULL);
974 	pThis = *ppThis;
975 	assert(pThis != NULL);
976 
977 	pthread_mutex_lock(&mutObjGlobalOp);
978 
979 	/* first check if we are permitted to unload */
980 	if(pThis->eType == eMOD_LIB) {
981 		if(pThis->uRefCnt > 0) {
982 			dbgprintf("module %s NOT unloaded because it still has a refcount of %u\n",
983 				  pThis->pszName, pThis->uRefCnt);
984 			ABORT_FINALIZE(RS_RET_MODULE_STILL_REFERENCED);
985 		}
986 	}
987 
988 	/* we need to unlink the module before we can destruct it -- rgerhards, 2008-02-26 */
989 	if(pThis->pPrev == NULL) {
990 		/* module is root, so we need to set a new root */
991 		pLoadedModules = pThis->pNext;
992 	} else {
993 		pThis->pPrev->pNext = pThis->pNext;
994 	}
995 
996 	if(pThis->pNext == NULL) {
997 		pLoadedModulesLast = pThis->pPrev;
998 	} else {
999 		pThis->pNext->pPrev = pThis->pPrev;
1000 	}
1001 
1002 	/* finally, we are ready for the module to go away... */
1003 	dbgprintf("Unloading module %s\n", modGetName(pThis));
1004 	CHKiRet(modPrepareUnload(pThis));
1005 	*ppThis = pThis->pNext;
1006 
1007 	moduleDestruct(pThis);
1008 
1009 finalize_it:
1010 	pthread_mutex_unlock(&mutObjGlobalOp);
1011 	RETiRet;
1012 }
1013 
1014 
1015 /* unload all loaded modules of a specific type (use eMOD_ALL if you want to
1016  * unload all module types). The unload happens only if the module is no longer
1017  * referenced. So some modules may survive this call.
1018  * rgerhards, 2008-03-11
1019  */
1020 static rsRetVal
modUnloadAndDestructAll(eModLinkType_t modLinkTypesToUnload)1021 modUnloadAndDestructAll(eModLinkType_t modLinkTypesToUnload)
1022 {
1023 	DEFiRet;
1024 	modInfo_t *pModCurr; /* module currently being processed */
1025 
1026 	pModCurr = GetNxt(NULL);
1027 	while(pModCurr != NULL) {
1028 		if(modLinkTypesToUnload == eMOD_LINK_ALL || pModCurr->eLinkType == modLinkTypesToUnload) {
1029 			if(modUnlinkAndDestroy(&pModCurr) == RS_RET_MODULE_STILL_REFERENCED) {
1030 				pModCurr = GetNxt(pModCurr);
1031 			} else {
1032 				/* Note: if the module was successfully unloaded, it has updated the
1033 				 * pModCurr pointer to the next module. However, the unload process may
1034 				 * still have indirectly referenced the pointer list in a way that the
1035 				 * unloaded module is not aware of. So we restart the unload process
1036 				 * to make sure we do not fall into a trap (what we did ;)). The
1037 				 * performance toll is minimal. -- rgerhards, 2008-04-28
1038 				 */
1039 				pModCurr = GetNxt(NULL);
1040 			}
1041 		} else {
1042 			pModCurr = GetNxt(pModCurr);
1043 		}
1044 	}
1045 
1046 	RETiRet;
1047 }
1048 
1049 /* find module with given name in global list */
1050 static rsRetVal
findModule(uchar * pModName,int iModNameLen,modInfo_t ** pMod)1051 findModule(uchar *pModName, int iModNameLen, modInfo_t **pMod)
1052 {
1053 	modInfo_t *pModInfo;
1054 	uchar *pModNameCmp;
1055 	DEFiRet;
1056 
1057 	pModInfo = GetNxt(NULL);
1058 	while(pModInfo != NULL) {
1059 		if(!strncmp((char *) pModName, (char *) (pModNameCmp = modGetName(pModInfo)), iModNameLen) &&
1060 		   (!*(pModNameCmp + iModNameLen) || !strcmp((char *) pModNameCmp + iModNameLen, ".so"))) {
1061 			dbgprintf("Module '%s' found\n", pModName);
1062 			break;
1063 		}
1064 		pModInfo = GetNxt(pModInfo);
1065 	}
1066 	*pMod = pModInfo;
1067 	RETiRet;
1068 }
1069 
1070 
1071 /* load a module and initialize it, based on doModLoad() from conf.c
1072  * rgerhards, 2008-03-05
1073  * varmojfekoj added support for dynamically loadable modules on 2007-08-13
1074  * rgerhards, 2007-09-25: please note that the non-threadsafe function dlerror() is
1075  * called below. This is ok because modules are currently only loaded during
1076  * configuration file processing, which is executed on a single thread. Should we
1077  * change that design at any stage (what is unlikely), we need to find a
1078  * replacement.
1079  * rgerhards, 2011-04-27:
1080  * Parameter "bConfLoad" tells us if the load was triggered by a config handler, in
1081  * which case we need to tie the loaded module to the current config. If bConfLoad == 0,
1082  * the system loads a module for internal reasons, this is not directly tied to a
1083  * configuration. We could also think if it would be useful to add only certain types
1084  * of modules, but the current implementation at least looks simpler.
1085  * Note: pvals = NULL means legacy config system
1086  */
1087 static rsRetVal ATTR_NONNULL(1)
Load(uchar * const pModName,const sbool bConfLoad,struct nvlst * const lst)1088 Load(uchar *const pModName, const sbool bConfLoad, struct nvlst *const lst)
1089 {
1090 	size_t iPathLen, iModNameLen;
1091 	int bHasExtension;
1092 	void *pModHdlr;
1093 	pModInit_t pModInit;
1094 	modInfo_t *pModInfo;
1095 	cfgmodules_etry_t *pNew = NULL;
1096 	cfgmodules_etry_t *pLast = NULL;
1097 	uchar *pModDirCurr, *pModDirNext;
1098 	int iLoadCnt;
1099 	struct dlhandle_s *pHandle = NULL;
1100 	uchar pathBuf[PATH_MAX+1];
1101 	uchar *pPathBuf = pathBuf;
1102 	size_t lenPathBuf = sizeof(pathBuf);
1103 	rsRetVal localRet;
1104 	cstr_t *load_err_msg = NULL;
1105 	DEFiRet;
1106 
1107 	assert(pModName != NULL);
1108 	DBGPRINTF("Requested to load module '%s'\n", pModName);
1109 
1110 	iModNameLen = strlen((char*)pModName);
1111 	/* overhead for a full path is potentially 1 byte for a slash,
1112 	 * three bytes for ".so" and one byte for '\0'.
1113 	 */
1114 #	define PATHBUF_OVERHEAD 1 + iModNameLen + 3 + 1
1115 
1116 	pthread_mutex_lock(&mutObjGlobalOp);
1117 
1118 	if(iModNameLen > 3 && !strcmp((char *) pModName + iModNameLen - 3, ".so")) {
1119 		iModNameLen -= 3;
1120 		bHasExtension = RSTRUE;
1121 	} else
1122 		bHasExtension = RSFALSE;
1123 
1124 	CHKiRet(findModule(pModName, iModNameLen, &pModInfo));
1125 	if(pModInfo != NULL) {
1126 		DBGPRINTF("Module '%s' already loaded\n", pModName);
1127 		if(bConfLoad) {
1128 			localRet = readyModForCnf(pModInfo, &pNew, &pLast);
1129 			if(pModInfo->setModCnf != NULL && localRet == RS_RET_OK) {
1130 				if(!strncmp((char*)pModName, "builtin:", sizeof("builtin:")-1)) {
1131 					if(pModInfo->bSetModCnfCalled) {
1132 						LogError(0, RS_RET_DUP_PARAM,
1133 						    "parameters for built-in module %s already set - ignored\n",
1134 						    pModName);
1135 						ABORT_FINALIZE(RS_RET_DUP_PARAM);
1136 					} else {
1137 						/* for built-in moules, we need to call setModConf,
1138 						 * because there is no way to set parameters at load
1139 						 * time for obvious reasons...
1140 						 */
1141 						if(lst != NULL)
1142 							pModInfo->setModCnf(lst);
1143 						pModInfo->bSetModCnfCalled = 1;
1144 					}
1145 				} else {
1146 					/* regular modules need to be added to conf list (for
1147 					 * builtins, this happend during initial load).
1148 					 */
1149 					addModToCnfList(&pNew, pLast);
1150 				}
1151 			}
1152 		}
1153 		FINALIZE;
1154 	}
1155 
1156 	pModDirCurr = (uchar *)((pModDir == NULL) ? _PATH_MODDIR : (char *)pModDir);
1157 	pModDirNext = NULL;
1158 	pModHdlr    = NULL;
1159 	iLoadCnt    = 0;
1160 	do {	/* now build our load module name */
1161 		if(*pModName == '/' || *pModName == '.') {
1162 			if(lenPathBuf < PATHBUF_OVERHEAD) {
1163 				if(pPathBuf != pathBuf) /* already malloc()ed memory? */
1164 					free(pPathBuf);
1165 				/* we always alloc enough memory for everything we potentiall need to add */
1166 				lenPathBuf = PATHBUF_OVERHEAD;
1167 				CHKmalloc(pPathBuf = malloc(lenPathBuf));
1168 			}
1169 			*pPathBuf = '\0';	/* we do not need to append the path - its already in the module name */
1170 			iPathLen = 0;
1171 		} else {
1172 			*pPathBuf = '\0';
1173 
1174 			iPathLen = strlen((char *)pModDirCurr);
1175 			pModDirNext = (uchar *)strchr((char *)pModDirCurr, ':');
1176 			if(pModDirNext)
1177 				iPathLen = (size_t)(pModDirNext - pModDirCurr);
1178 
1179 			if(iPathLen == 0) {
1180 				if(pModDirNext) {
1181 					pModDirCurr = pModDirNext + 1;
1182 					continue;
1183 				}
1184 				break;
1185 			} else if(iPathLen > lenPathBuf - PATHBUF_OVERHEAD) {
1186 				if(pPathBuf != pathBuf) /* already malloc()ed memory? */
1187 					free(pPathBuf);
1188 				/* we always alloc enough memory for everything we potentiall need to add */
1189 				lenPathBuf = iPathLen + PATHBUF_OVERHEAD;
1190 				CHKmalloc(pPathBuf = malloc(lenPathBuf));
1191 			}
1192 
1193 			memcpy((char *) pPathBuf, (char *)pModDirCurr, iPathLen);
1194 			if((pPathBuf[iPathLen - 1] != '/')) {
1195 				/* we have space, made sure in previous check */
1196 				pPathBuf[iPathLen++] = '/';
1197 			}
1198 			pPathBuf[iPathLen] = '\0';
1199 
1200 			if(pModDirNext)
1201 				pModDirCurr = pModDirNext + 1;
1202 		}
1203 
1204 		/* ... add actual name ... */
1205 		strncat((char *) pPathBuf, (char *) pModName, lenPathBuf - iPathLen - 1);
1206 
1207 		/* now see if we have an extension and, if not, append ".so" */
1208 		if(!bHasExtension) {
1209 			/* we do not have an extension and so need to add ".so"
1210 			 * TODO: I guess this is highly importable, so we should change the
1211 			 * algo over time... -- rgerhards, 2008-03-05
1212 			 */
1213 			strncat((char *) pPathBuf, ".so", lenPathBuf - strlen((char*) pPathBuf) - 1);
1214 		}
1215 
1216 		/* complete load path constructed, so ... GO! */
1217 		dbgprintf("loading module '%s'\n", pPathBuf);
1218 
1219 		/* see if we have this one already */
1220 		for (pHandle = pHandles; pHandle; pHandle = pHandle->next) {
1221 			if (!strcmp((char *)pModName, (char *)pHandle->pszName)) {
1222 				pModHdlr = pHandle->pModHdlr;
1223 				break;
1224 			}
1225 		}
1226 
1227 		/* not found, try to dynamically link it */
1228 		if (!pModHdlr) {
1229 			pModHdlr = dlopen((char *) pPathBuf, RTLD_NOW);
1230 		}
1231 
1232 		if(pModHdlr == NULL) {
1233 			char errmsg[4096];
1234 			snprintf(errmsg, sizeof(errmsg), "%strying to load module %s: %s",
1235 				(load_err_msg == NULL) ? "" : "  ////////  ",
1236 				pPathBuf, dlerror());
1237 			if(load_err_msg == NULL) {
1238 				rsCStrConstructFromszStr(&load_err_msg, (uchar*)errmsg);
1239 			} else {
1240 				rsCStrAppendStr(load_err_msg, (uchar*)errmsg);
1241 			}
1242 		}
1243 
1244 		iLoadCnt++;
1245 
1246 	} while(pModHdlr == NULL && *pModName != '/' && pModDirNext);
1247 
1248 	if(load_err_msg != NULL) {
1249 		cstrFinalize(load_err_msg);
1250 	}
1251 
1252 	if(!pModHdlr) {
1253 		LogError(0, RS_RET_MODULE_LOAD_ERR_DLOPEN, "could not load module '%s', errors: %s", pModName,
1254 			(load_err_msg == NULL) ? "NONE SEEN???" : (const char*) cstrGetSzStrNoNULL(load_err_msg));
1255 		ABORT_FINALIZE(RS_RET_MODULE_LOAD_ERR_DLOPEN);
1256 	}
1257 	if(!(pModInit = (pModInit_t)dlsym(pModHdlr, "modInit"))) {
1258 		LogError(0, RS_RET_MODULE_LOAD_ERR_NO_INIT,
1259 			 	"could not load module '%s', dlsym: %s\n", pPathBuf, dlerror());
1260 		dlclose(pModHdlr);
1261 		ABORT_FINALIZE(RS_RET_MODULE_LOAD_ERR_NO_INIT);
1262 	}
1263 	if((iRet = doModInit(pModInit, (uchar*) pModName, pModHdlr, &pModInfo)) != RS_RET_OK) {
1264 		LogError(0, RS_RET_MODULE_LOAD_ERR_INIT_FAILED,
1265 			"could not load module '%s', rsyslog error %d\n", pPathBuf, iRet);
1266 		dlclose(pModHdlr);
1267 		ABORT_FINALIZE(RS_RET_MODULE_LOAD_ERR_INIT_FAILED);
1268 	}
1269 
1270 	if(bConfLoad) {
1271 		readyModForCnf(pModInfo, &pNew, &pLast);
1272 		if(pModInfo->setModCnf != NULL) {
1273 			if(lst != NULL) {
1274 				localRet = pModInfo->setModCnf(lst);
1275 				if(localRet != RS_RET_OK) {
1276 					LogError(0, localRet,
1277 						"module '%s', failed processing config parameters",
1278 						pPathBuf);
1279 					ABORT_FINALIZE(localRet);
1280 				}
1281 			}
1282 			pModInfo->bSetModCnfCalled = 1;
1283 		}
1284 		addModToCnfList(&pNew, pLast);
1285 	}
1286 
1287 finalize_it:
1288 	if(load_err_msg != NULL) {
1289 		cstrDestruct(&load_err_msg);
1290 	}
1291 	if(pPathBuf != pathBuf) /* used malloc()ed memory? */
1292 		free(pPathBuf);
1293 	if(iRet != RS_RET_OK)
1294 		abortCnfUse(&pNew);
1295 	free(pNew); /* is NULL again if properly consumed, else clean up */
1296 	pthread_mutex_unlock(&mutObjGlobalOp);
1297 	RETiRet;
1298 }
1299 
1300 
1301 /* the v6+ way of loading modules: process a "module(...)" directive.
1302  * rgerhards, 2012-06-20
1303  */
1304 rsRetVal
modulesProcessCnf(struct cnfobj * o)1305 modulesProcessCnf(struct cnfobj *o)
1306 {
1307 	struct cnfparamvals *pvals;
1308 	uchar *cnfModName = NULL;
1309 	int typeIdx;
1310 	DEFiRet;
1311 
1312 	pvals = nvlstGetParams(o->nvlst, &pblk, NULL);
1313 	if(pvals == NULL) {
1314 		ABORT_FINALIZE(RS_RET_ERR);
1315 	}
1316 	DBGPRINTF("modulesProcessCnf params:\n");
1317 	cnfparamsPrint(&pblk, pvals);
1318 	typeIdx = cnfparamGetIdx(&pblk, "load");
1319 	if(pvals[typeIdx].bUsed == 0) {
1320 		LogError(0, RS_RET_CONF_RQRD_PARAM_MISSING, "module type missing");
1321 		ABORT_FINALIZE(RS_RET_CONF_RQRD_PARAM_MISSING);
1322 	}
1323 
1324 	cnfModName = (uchar*)es_str2cstr(pvals[typeIdx].val.d.estr, NULL);
1325 	iRet = Load(cnfModName, 1, o->nvlst);
1326 
1327 finalize_it:
1328 	free(cnfModName);
1329 	cnfparamvalsDestruct(pvals, &pblk);
1330 	RETiRet;
1331 }
1332 
1333 
1334 /* set the default module load directory. A NULL value may be provided, in
1335  * which case any previous value is deleted but no new one set. The caller-provided
1336  * string is duplicated. If it needs to be freed, that's the caller's duty.
1337  * rgerhards, 2008-03-07
1338  */
1339 static rsRetVal
SetModDir(uchar * pszModDir)1340 SetModDir(uchar *pszModDir)
1341 {
1342 	DEFiRet;
1343 
1344 	dbgprintf("setting default module load directory '%s'\n", pszModDir);
1345 	if(pModDir != NULL) {
1346 		free(pModDir);
1347 	}
1348 
1349 	pModDir = (uchar*) strdup((char*)pszModDir);
1350 
1351 	RETiRet;
1352 }
1353 
1354 
1355 /* Reference-Counting object access: add 1 to the current reference count. Must be
1356  * called by anyone interested in using a module. -- rgerhards, 20080-03-10
1357  */
1358 static rsRetVal
Use(const char * srcFile,modInfo_t * pThis)1359 Use(const char *srcFile, modInfo_t *pThis)
1360 {
1361 	DEFiRet;
1362 
1363 	assert(pThis != NULL);
1364 	pThis->uRefCnt++;
1365 	dbgprintf("source file %s requested reference for module '%s', reference count now %u\n",
1366 		  srcFile, pThis->pszName, pThis->uRefCnt);
1367 
1368 #	ifdef DEBUG
1369 	modUsrAdd(pThis, srcFile);
1370 #	endif
1371 
1372 	RETiRet;
1373 
1374 }
1375 
1376 
1377 /* Reference-Counting object access: subract one from the current refcount. Must
1378  * by called by anyone who no longer needs a module. If count reaches 0, the
1379  * module is unloaded. -- rgerhards, 20080-03-10
1380  */
1381 static rsRetVal
Release(const char * srcFile,modInfo_t ** ppThis)1382 Release(const char *srcFile, modInfo_t **ppThis)
1383 {
1384 	DEFiRet;
1385 	modInfo_t *pThis;
1386 
1387 	assert(ppThis != NULL);
1388 	pThis = *ppThis;
1389 	assert(pThis != NULL);
1390 	if(pThis->uRefCnt == 0) {
1391 		/* oops, we are already at 0? */
1392 		dbgprintf("internal error: module '%s' already has a refcount of 0 (released by %s)!\n",
1393 			  pThis->pszName, srcFile);
1394 	} else {
1395 		--pThis->uRefCnt;
1396 		dbgprintf("file %s released module '%s', reference count now %u\n",
1397 			  srcFile, pThis->pszName, pThis->uRefCnt);
1398 #		ifdef DEBUG
1399 		modUsrDel(pThis, srcFile);
1400 		modUsrPrint(pThis);
1401 #		endif
1402 	}
1403 
1404 	if(pThis->uRefCnt == 0) {
1405 		/* we have a zero refcount, so we must unload the module */
1406 		dbgprintf("module '%s' has zero reference count, unloading...\n", pThis->pszName);
1407 		modUnlinkAndDestroy(&pThis);
1408 		/* we must NOT do a *ppThis = NULL, because ppThis now points into freed memory!
1409 		 * If in doubt, see obj.c::ReleaseObj() for how we are called.
1410 		 */
1411 	}
1412 
1413 	RETiRet;
1414 
1415 }
1416 
1417 
1418 /* exit our class
1419  * rgerhards, 2008-03-11
1420  */
1421 BEGINObjClassExit(module, OBJ_IS_LOADABLE_MODULE) /* CHANGE class also in END MACRO! */
1422 CODESTARTObjClassExit(module)
1423 	/* release objects we no longer need */
1424 	free(pModDir);
1425 #	ifdef DEBUG
1426 	modUsrPrintAll(); /* debug aid - TODO: integrate with debug.c, at least the settings! */
1427 #	endif
1428 ENDObjClassExit(module)
1429 
1430 
1431 /* queryInterface function
1432  * rgerhards, 2008-03-05
1433  */
1434 BEGINobjQueryInterface(module)
1435 CODESTARTobjQueryInterface(module)
1436 	if(pIf->ifVersion != moduleCURR_IF_VERSION) { /* check for current version, increment on each change */
1437 		ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED);
1438 	}
1439 
1440 	/* ok, we have the right interface, so let's fill it
1441 	 * Please note that we may also do some backwards-compatibility
1442 	 * work here (if we can support an older interface version - that,
1443 	 * of course, also affects the "if" above).
1444 	 */
1445 	pIf->GetNxt = GetNxt;
1446 	pIf->GetNxtCnfType = GetNxtCnfType;
1447 	pIf->GetName = modGetName;
1448 	pIf->GetStateName = modGetStateName;
1449 	pIf->PrintList = modPrintList;
1450 	pIf->FindWithCnfName = FindWithCnfName;
1451 	pIf->UnloadAndDestructAll = modUnloadAndDestructAll;
1452 	pIf->doModInit = doModInit;
1453 	pIf->SetModDir = SetModDir;
1454 	pIf->Load = Load;
1455 	pIf->Use = Use;
1456 	pIf->Release = Release;
1457 finalize_it:
1458 ENDobjQueryInterface(module)
1459 
1460 
1461 /* Initialize our class. Must be called as the very first method
1462  * before anything else is called inside this class.
1463  * rgerhards, 2008-03-05
1464  */
1465 BEGINAbstractObjClassInit(module, 1, OBJ_IS_CORE_MODULE) /* class, version - CHANGE class also in END MACRO! */
1466 	uchar *pModPath;
1467 
1468 	/* use any module load path specified in the environment */
1469 	if((pModPath = (uchar*) getenv("RSYSLOG_MODDIR")) != NULL) {
1470 		SetModDir(pModPath);
1471 	}
1472 
1473 	/* now check if another module path was set via the command line (-M)
1474 	 * if so, that overrides the environment. Please note that we must use
1475 	 * a global setting here because the command line parser can NOT call
1476 	 * into the module object, because it is not initialized at that point. So
1477 	 * instead a global setting is changed and we pick it up as soon as we
1478 	 * initialize -- rgerhards, 2008-04-04
1479 	 */
1480 	if(glblModPath != NULL) {
1481 		SetModDir(glblModPath);
1482 	}
1483 
1484 	/* request objects we use */
1485 ENDObjClassInit(module)
1486 
1487 /* vi:set ai:
1488  */
1489