Debian Codegraph @

runtime/ruleset.c

raw
1 /* ruleset.c - rsyslog's ruleset object
2 *
3 * We have a two-way structure of linked lists: one config-specifc linked list
4 * (conf->rulesets.llRulesets) hold alls rule sets that we know. Included in each
5 * list is a list of rules (which contain a list of actions, but that's
6 * a different story).
7 *
8 * Usually, only a single rule set is executed. However, there exist some
9 * situations where all rules must be iterated over, for example on HUP. Thus,
10 * we also provide interfaces to do that.
11 *
12 * Module begun 2009-06-10 by Rainer Gerhards
13 *
14 * Copyright 2009-2025 Rainer Gerhards and Adiscon GmbH.
15 *
16 * This file is part of the rsyslog runtime library.
17 *
18 * Licensed under the Apache License, Version 2.0 (the "License");
19 * you may not use this file except in compliance with the License.
20 * You may obtain a copy of the License at
21 *
22 * http://www.apache.org/licenses/LICENSE-2.0
23 * -or-
24 * see COPYING.ASL20 in the source distribution
25 *
26 * Unless required by applicable law or agreed to in writing, software
27 * distributed under the License is distributed on an "AS IS" BASIS,
28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 * See the License for the specific language governing permissions and
30 * limitations under the License.
31 */
32 #include "config.h"
33 #include <stdlib.h>
34 #include <assert.h>
35 #include <ctype.h>
36
37 #include "rsyslog.h"
38 #include "obj.h"
39 #include "cfsysline.h"
40 #include "msg.h"
41 #include "ruleset.h"
42 #include "errmsg.h"
43 #include "parser.h"
44 #include "batch.h"
45 #include "unicode-helper.h"
46 #include "rsconf.h"
47 #include "action.h"
48 #include "rainerscript.h"
49 #include "srUtils.h"
50 #include "modules.h"
51 #include "wti.h"
52 #include "dirty.h" /* for main ruleset queue creation */
53
54
55 /* static data */
56 DEFobjStaticHelpers;
57 DEFobjCurrIf(parser)
58
59 /* tables for interfacing with the v6 config system (as far as we need to) */
60 static struct cnfparamdescr rspdescr[] = {{"name", eCmdHdlrString, CNFPARAM_REQUIRED},
61 {"parser", eCmdHdlrArray, 0}};
62 static struct cnfparamblk rspblk = {CNFPARAMBLK_VERSION, sizeof(rspdescr) / sizeof(struct cnfparamdescr), rspdescr};
63
64 /* forward definitions */
65 static rsRetVal processBatch(batch_t *pBatch, wti_t *pWti);
66 static rsRetVal scriptExec(struct cnfstmt *root, smsg_t *pMsg, wti_t *pWti);
67
68
69 /* ---------- linked-list key handling functions (ruleset) ---------- */
70
71 /* destructor for linked list keys.
72 */
73 rsRetVal rulesetKeyDestruct(void __attribute__((unused)) * pData) {
74 free(pData);
75 return RS_RET_OK;
76 }
77 /* ---------- END linked-list key handling functions (ruleset) ---------- */
78
79
80 /* iterate over all actions in a script (stmt subtree) */
81 static void scriptIterateAllActions(struct cnfstmt *root, rsRetVal (*pFunc)(void *, void *), void *pParam) {
82 struct cnfstmt *stmt;
83 for (stmt = root; stmt != NULL; stmt = stmt->next) {
84 switch (stmt->nodetype) {
85 case S_NOP:
86 case S_STOP:
87 case S_SET:
88 case S_UNSET:
89 case S_CALL_INDIRECT:
90 case S_CALL: /* call does not need to do anything - done in called ruleset! */
91 break;
92 case S_ACT:
93 DBGPRINTF("iterateAllActions calling into action %p\n", stmt->d.act);
94 pFunc(stmt->d.act, pParam);
95 break;
96 case S_IF:
97 if (stmt->d.s_if.t_then != NULL) scriptIterateAllActions(stmt->d.s_if.t_then, pFunc, pParam);
98 if (stmt->d.s_if.t_else != NULL) scriptIterateAllActions(stmt->d.s_if.t_else, pFunc, pParam);
99 break;
100 case S_FOREACH:
101 if (stmt->d.s_foreach.body != NULL) scriptIterateAllActions(stmt->d.s_foreach.body, pFunc, pParam);
102 break;
103 case S_PRIFILT:
104 if (stmt->d.s_prifilt.t_then != NULL) scriptIterateAllActions(stmt->d.s_prifilt.t_then, pFunc, pParam);
105 if (stmt->d.s_prifilt.t_else != NULL) scriptIterateAllActions(stmt->d.s_prifilt.t_else, pFunc, pParam);
106 break;
107 case S_PROPFILT:
108 scriptIterateAllActions(stmt->d.s_propfilt.t_then, pFunc, pParam);
109 break;
110 case S_RELOAD_LOOKUP_TABLE: /* this is a NOP */
111 break;
112 default:
113 dbgprintf("error: unknown stmt type %u during iterateAll\n", (unsigned)stmt->nodetype);
114 #ifndef NDEBUG
115 fprintf(stderr, "error: unknown stmt type %u during iterateAll\n", (unsigned)stmt->nodetype);
116 #endif
117 assert(0); /* abort under debugging */
118 break;
119 }
120 }
121 }
122
123 /* driver to iterate over all of this ruleset actions */
124 typedef struct iterateAllActions_s {
125 rsRetVal (*pFunc)(void *, void *);
126 void *pParam;
127 } iterateAllActions_t;
128 /* driver to iterate over all actions */
129 DEFFUNC_llExecFunc(doIterateAllActions) {
130 DEFiRet;
131 ruleset_t *pThis = (ruleset_t *)pData;
132 iterateAllActions_t *pMyParam = (iterateAllActions_t *)pParam;
133 scriptIterateAllActions(pThis->root, pMyParam->pFunc, pMyParam->pParam);
134 RETiRet;
135 }
136 /* iterate over ALL actions present in the WHOLE system.
137 * this is often needed, for example when HUP processing
138 * must be done or a shutdown is pending.
139 */
140 static rsRetVal iterateAllActions(rsconf_t *conf, rsRetVal (*pFunc)(void *, void *), void *pParam) {
141 iterateAllActions_t params;
142 DEFiRet;
143 assert(pFunc != NULL);
144
145 params.pFunc = pFunc;
146 params.pParam = pParam;
147 CHKiRet(llExecFunc(&(conf->rulesets.llRulesets), doIterateAllActions, &params));
148
149 finalize_it:
150 RETiRet;
151 }
152
153 /* driver to iterate over all rulesets */
154 DEFFUNC_llExecFunc(doActivateRulesetQueues) {
155 DEFiRet;
156 ruleset_t *pThis = (ruleset_t *)pData;
157 dbgprintf("Activating Ruleset Queue[%p] for Ruleset %s\n", pThis->pQueue, pThis->pszName);
158 if (pThis->pQueue != NULL) startMainQueue(runConf, pThis->pQueue);
159 RETiRet;
160 }
161 /* activate all ruleset queues */
162 rsRetVal activateRulesetQueues(void) {
163 llExecFunc(&(runConf->rulesets.llRulesets), doActivateRulesetQueues, NULL);
164 return RS_RET_OK;
165 }
166
167
168 static rsRetVal execAct(struct cnfstmt *stmt, smsg_t *pMsg, wti_t *pWti) {
169 DEFiRet;
170 if (actionIsDisabled(stmt->d.act)) {
171 DBGPRINTF("action %d died, do NOT execute\n", stmt->d.act->iActionNbr);
172 FINALIZE;
173 }
174
175 DBGPRINTF("executing action %d\n", stmt->d.act->iActionNbr);
176 stmt->d.act->submitToActQ(stmt->d.act, pWti, pMsg);
177 if (iRet != RS_RET_DISCARDMSG) {
178 /* note: we ignore the error code here, as we do NEVER want to
179 * stop script execution due to action return code
180 */
181 iRet = RS_RET_OK;
182 }
183 finalize_it:
184 RETiRet;
185 }
186
187 static rsRetVal ATTR_NONNULL()
188 execSet(const struct cnfstmt *const stmt, smsg_t *const pMsg, wti_t *const __restrict__ pWti) {
189 struct svar result;
190 DEFiRet;
191 cnfexprEval(stmt->d.s_set.expr, &result, pMsg, pWti);
192 msgSetJSONFromVar(pMsg, stmt->d.s_set.varname, &result, stmt->d.s_set.force_reset);
193 varDelete(&result);
194 RETiRet;
195 }
196
197 static rsRetVal execUnset(struct cnfstmt *stmt, smsg_t *pMsg) {
198 DEFiRet;
199 msgDelJSON(pMsg, stmt->d.s_unset.varname);
200 RETiRet;
201 }
202
203 static rsRetVal execCallIndirect(struct cnfstmt *const __restrict__ stmt,
204 smsg_t *pMsg,
205 wti_t *const __restrict__ pWti) {
206 ruleset_t *pRuleset;
207 struct svar result;
208 int bMustFree; /* dummy parameter */
209 DEFiRet;
210
211 assert(stmt->d.s_call_ind.expr != NULL);
212
213 cnfexprEval(stmt->d.s_call_ind.expr, &result, pMsg, pWti);
214 uchar *const rsName = (uchar *)var2CString(&result, &bMustFree);
215 const rsRetVal localRet = rulesetGetRuleset(runConf, &pRuleset, rsName);
216 if (localRet != RS_RET_OK) {
217 /* in that case, we accept that a NOP will "survive" */
218 LogError(0, RS_RET_RULESET_NOT_FOUND,
219 "error: CALL_INDIRECT: "
220 "ruleset '%s' cannot be found, treating as NOP\n",
221 rsName);
222 FINALIZE;
223 }
224 DBGPRINTF("CALL_INDIRECT obtained ruleset ptr %p for ruleset '%s' [hasQueue:%d]\n", pRuleset, rsName,
225 rulesetHasQueue(pRuleset));
226 if (rulesetHasQueue(pRuleset)) {
227 CHKmalloc(pMsg = MsgDup((smsg_t *)pMsg));
228 DBGPRINTF("CALL_INDIRECT: forwarding message to async ruleset %p\n", pRuleset->pQueue);
229 MsgSetFlowControlType(pMsg, eFLOWCTL_NO_DELAY);
230 MsgSetRuleset(pMsg, pRuleset);
231 /* Note: we intentionally use submitMsg2() here, as we process messages
232 * that were already run through the rate-limiter.
233 */
234 submitMsg2(pMsg);
235 } else {
236 CHKiRet(scriptExec(pRuleset->root, pMsg, pWti));
237 }
238 finalize_it:
239 varDelete(&result);
240 free(rsName);
241 RETiRet;
242 }
243
244 static rsRetVal execCall(struct cnfstmt *stmt, smsg_t *pMsg, wti_t *pWti) {
245 DEFiRet;
246 if (stmt->d.s_call.ruleset == NULL) {
247 CHKiRet(scriptExec(stmt->d.s_call.stmt, pMsg, pWti));
248 } else {
249 CHKmalloc(pMsg = MsgDup((smsg_t *)pMsg));
250 DBGPRINTF("CALL: forwarding message to async ruleset %p\n", stmt->d.s_call.ruleset->pQueue);
251 MsgSetFlowControlType(pMsg, eFLOWCTL_NO_DELAY);
252 MsgSetRuleset(pMsg, stmt->d.s_call.ruleset);
253 /* Note: we intentionally use submitMsg2() here, as we process messages
254 * that were already run through the rate-limiter.
255 */
256 submitMsg2(pMsg);
257 }
258 finalize_it:
259 RETiRet;
260 }
261
262 static rsRetVal execIf(struct cnfstmt *const stmt, smsg_t *const pMsg, wti_t *const pWti) {
263 sbool bRet;
264 DEFiRet;
265 bRet = cnfexprEvalBool(stmt->d.s_if.expr, pMsg, pWti);
266 DBGPRINTF("if condition result is %d\n", bRet);
267 if (bRet) {
268 if (stmt->d.s_if.t_then != NULL) CHKiRet(scriptExec(stmt->d.s_if.t_then, pMsg, pWti));
269 } else {
270 if (stmt->d.s_if.t_else != NULL) CHKiRet(scriptExec(stmt->d.s_if.t_else, pMsg, pWti));
271 }
272 finalize_it:
273 RETiRet;
274 }
275
276 static rsRetVal invokeForeachBodyWith(struct cnfstmt *stmt, json_object *o, smsg_t *pMsg, wti_t *pWti) {
277 struct svar v;
278 v.datatype = 'J';
279 v.d.json = o;
280 DEFiRet;
281 CHKiRet(msgSetJSONFromVar(pMsg, (uchar *)stmt->d.s_foreach.iter->var, &v, 1));
282 CHKiRet(scriptExec(stmt->d.s_foreach.body, pMsg, pWti));
283 finalize_it:
284 RETiRet;
285 }
286
287 static rsRetVal callForeachArray(struct cnfstmt *stmt, json_object *arr, smsg_t *pMsg, wti_t *pWti) {
288 DEFiRet;
289 int len = json_object_array_length(arr);
290 json_object *curr;
291 for (int i = 0; i < len; i++) {
292 curr = json_object_array_get_idx(arr, i);
293 CHKiRet(invokeForeachBodyWith(stmt, curr, pMsg, pWti));
294 }
295 finalize_it:
296 RETiRet;
297 }
298
299
300 static rsRetVal callForeachObject(struct cnfstmt *stmt, json_object *arr, smsg_t *pMsg, wti_t *pWti) {
301 json_object *entry = NULL;
302 json_object *key = NULL;
303 const char **keys = NULL;
304 json_object *curr = NULL;
305 const char **curr_key;
306 struct json_object_iterator it;
307 struct json_object_iterator itEnd;
308 DEFiRet;
309
310 int len = json_object_object_length(arr);
311 CHKmalloc(keys = calloc(len, sizeof(char *)));
312 curr_key = keys;
313 it = json_object_iter_begin(arr);
314 itEnd = json_object_iter_end(arr);
315 while (!json_object_iter_equal(&it, &itEnd)) {
316 *curr_key = json_object_iter_peek_name(&it);
317 curr_key++;
318 json_object_iter_next(&it);
319 }
320 CHKmalloc(entry = json_object_new_object());
321 for (int i = 0; i < len; i++) {
322 if (json_object_object_get_ex(arr, keys[i], &curr)) {
323 CHKmalloc(key = json_object_new_string(keys[i]));
324 json_object_object_add(entry, "key", key);
325 key = NULL;
326 json_object_object_add(entry, "value", json_object_get(curr));
327 CHKiRet(invokeForeachBodyWith(stmt, entry, pMsg, pWti));
328 }
329 }
330 finalize_it:
331 if (keys != NULL) free(keys);
332 if (entry != NULL) json_object_put(entry);
333 /* "fix" Coverity scan issue CID 185393: key currently can NOT be NULL
334 * However, instead of just removing the
335 * if (key != NULL) json_object_put(key);
336 * we put an assertion in its place.
337 */
338 assert(key == NULL);
339
340 RETiRet;
341 }
342
343 static rsRetVal ATTR_NONNULL() execForeach(struct cnfstmt *const stmt, smsg_t *const pMsg, wti_t *const pWti) {
344 json_object *arr = NULL;
345 DEFiRet;
346
347 /* arr can either be an array or an associative-array (obj) */
348 arr = cnfexprEvalCollection(stmt->d.s_foreach.iter->collection, pMsg, pWti);
349
350 if (arr == NULL) {
351 DBGPRINTF("foreach loop skipped, as object to iterate upon is empty\n");
352 FINALIZE;
353 } else if (json_object_is_type(arr, json_type_array) && json_object_array_length(arr) > 0) {
354 CHKiRet(callForeachArray(stmt, arr, pMsg, pWti));
355 } else if (json_object_is_type(arr, json_type_object) && json_object_object_length(arr) > 0) {
356 CHKiRet(callForeachObject(stmt, arr, pMsg, pWti));
357 } else {
358 DBGPRINTF("foreach loop skipped, as object to iterate upon is empty or is not an array\n");
359 FINALIZE;
360 }
361 CHKiRet(msgDelJSON(pMsg, (uchar *)stmt->d.s_foreach.iter->var));
362
363 finalize_it:
364 if (arr != NULL) json_object_put(arr);
365
366 RETiRet;
367 }
368
369 static rsRetVal execPRIFILT(struct cnfstmt *stmt, smsg_t *pMsg, wti_t *pWti) {
370 int bRet;
371 DEFiRet;
372 if ((stmt->d.s_prifilt.pmask[pMsg->iFacility] == TABLE_NOPRI) ||
373 ((stmt->d.s_prifilt.pmask[pMsg->iFacility] & (1 << pMsg->iSeverity)) == 0))
374 bRet = 0;
375 else
376 bRet = 1;
377
378 DBGPRINTF("PRIFILT condition result is %d\n", bRet);
379 if (bRet) {
380 if (stmt->d.s_prifilt.t_then != NULL) CHKiRet(scriptExec(stmt->d.s_prifilt.t_then, pMsg, pWti));
381 } else {
382 if (stmt->d.s_prifilt.t_else != NULL) CHKiRet(scriptExec(stmt->d.s_prifilt.t_else, pMsg, pWti));
383 }
384 finalize_it:
385 RETiRet;
386 }
387
388
389 /* helper to execPROPFILT(), as the evaluation itself is quite lengthy */
390 static int evalPROPFILT(struct cnfstmt *stmt, smsg_t *pMsg) {
391 unsigned short pbMustBeFreed;
392 uchar *pszPropVal;
393 int bRet = 0;
394 rs_size_t propLen;
395
396 if (stmt->d.s_propfilt.prop.id == PROP_INVALID) goto done;
397
398 pszPropVal = MsgGetProp(pMsg, NULL, &stmt->d.s_propfilt.prop, &propLen, &pbMustBeFreed, NULL);
399
400 /* Now do the compares (short list currently ;)) */
401 switch (stmt->d.s_propfilt.operation) {
402 case FIOP_CONTAINS:
403 if (rsCStrLocateInSzStr(stmt->d.s_propfilt.pCSCompValue, (uchar *)pszPropVal) != -1) bRet = 1;
404 break;
405 case FIOP_ISEMPTY:
406 if (propLen == 0) bRet = 1; /* process message! */
407 break;
408 case FIOP_ISEQUAL:
409 if (rsCStrSzStrCmp(stmt->d.s_propfilt.pCSCompValue, pszPropVal, propLen) == 0)
410 bRet = 1; /* process message! */
411 break;
412 case FIOP_STARTSWITH:
413 if (rsCStrSzStrStartsWithCStr(stmt->d.s_propfilt.pCSCompValue, pszPropVal, propLen) == 0)
414 bRet = 1; /* process message! */
415 break;
416 case FIOP_ENDSWITH:
417 if (rsCStrSzStrEndsWithCStr(stmt->d.s_propfilt.pCSCompValue, pszPropVal, propLen) == 0)
418 bRet = 1; /* process message! */
419 break;
420 case FIOP_REGEX:
421 if (rsCStrSzStrMatchRegex(stmt->d.s_propfilt.pCSCompValue, (unsigned char *)pszPropVal, 0,
422 &stmt->d.s_propfilt.regex_cache) == RS_RET_OK)
423 bRet = 1;
424 break;
425 case FIOP_EREREGEX:
426 if (rsCStrSzStrMatchRegex(stmt->d.s_propfilt.pCSCompValue, (unsigned char *)pszPropVal, 1,
427 &stmt->d.s_propfilt.regex_cache) == RS_RET_OK)
428 bRet = 1;
429 break;
430 case FIOP_NOP:
431 default:
432 /* here, it handles NOP (for performance reasons) */
433 assert(stmt->d.s_propfilt.operation == FIOP_NOP);
434 bRet = 1; /* as good as any other default ;) */
435 break;
436 }
437
438 /* now check if the value must be negated */
439 if (stmt->d.s_propfilt.isNegated) bRet = (bRet == 1) ? 0 : 1;
440
441 if (Debug) {
442 if (stmt->d.s_propfilt.prop.id == PROP_CEE) {
443 DBGPRINTF("Filter: check for CEE property '%s' (value '%s') ", stmt->d.s_propfilt.prop.name, pszPropVal);
444 } else if (stmt->d.s_propfilt.prop.id == PROP_LOCAL_VAR) {
445 DBGPRINTF("Filter: check for local var '%s' (value '%s') ", stmt->d.s_propfilt.prop.name, pszPropVal);
446 } else if (stmt->d.s_propfilt.prop.id == PROP_GLOBAL_VAR) {
447 DBGPRINTF("Filter: check for global var '%s' (value '%s') ", stmt->d.s_propfilt.prop.name, pszPropVal);
448 } else {
449 DBGPRINTF("Filter: check for property '%s' (value '%s') ", propIDToName(stmt->d.s_propfilt.prop.id),
450 pszPropVal);
451 }
452 if (stmt->d.s_propfilt.isNegated) DBGPRINTF("NOT ");
453 if (stmt->d.s_propfilt.operation == FIOP_ISEMPTY) {
454 DBGPRINTF("%s : %s\n", getFIOPName(stmt->d.s_propfilt.operation), bRet ? "TRUE" : "FALSE");
455 } else {
456 DBGPRINTF("%s '%s': %s\n", getFIOPName(stmt->d.s_propfilt.operation),
457 rsCStrGetSzStrNoNULL(stmt->d.s_propfilt.pCSCompValue), bRet ? "TRUE" : "FALSE");
458 }
459 }
460
461 /* cleanup */
462 if (pbMustBeFreed) free(pszPropVal);
463 done:
464 return bRet;
465 }
466
467 static rsRetVal execPROPFILT(struct cnfstmt *stmt, smsg_t *pMsg, wti_t *pWti) {
468 sbool bRet;
469 DEFiRet;
470
471 bRet = evalPROPFILT(stmt, pMsg);
472 DBGPRINTF("PROPFILT condition result is %d\n", bRet);
473 if (bRet) CHKiRet(scriptExec(stmt->d.s_propfilt.t_then, pMsg, pWti));
474 finalize_it:
475 RETiRet;
476 }
477
478 static rsRetVal ATTR_NONNULL() execReloadLookupTable(struct cnfstmt *stmt) {
479 assert(stmt != NULL);
480 lookup_ref_t *t;
481 DEFiRet;
482 t = stmt->d.s_reload_lookup_table.table;
483 if (t == NULL) {
484 ABORT_FINALIZE(RS_RET_NONE);
485 }
486
487 iRet = lookupReload(t, stmt->d.s_reload_lookup_table.stub_value);
488 /* Note that reload dispatched above is performed asynchronously,
489 on a different thread. So rsRetVal it returns means it was triggered
490 successfully, and not that it was reloaded successfully. */
491
492 finalize_it:
493 RETiRet;
494 }
495
496 /* The rainerscript execution engine. It is debatable if that would be better
497 * contained in grammer/rainerscript.c, HOWEVER, that file focusses primarily
498 * on the parsing and object creation part. So as an actual executor, it is
499 * better suited here.
500 * rgerhards, 2012-09-04
501 */
502 static rsRetVal ATTR_NONNULL(2, 3) scriptExec(struct cnfstmt *const root, smsg_t *const pMsg, wti_t *const pWti) {
503 struct cnfstmt *stmt;
504 DEFiRet;
505
506 for (stmt = root; stmt != NULL; stmt = stmt->next) {
507 if (*pWti->pbShutdownImmediate) {
508 DBGPRINTF(
509 "scriptExec: ShutdownImmediate set, "
510 "force terminating\n");
511 ABORT_FINALIZE(RS_RET_FORCE_TERM);
512 }
513 if (Debug) {
514 cnfstmtPrintOnly(stmt, 2, 0);
515 }
516 switch (stmt->nodetype) {
517 case S_NOP:
518 break;
519 case S_STOP:
520 ABORT_FINALIZE(RS_RET_DISCARDMSG);
521 break;
522 case S_ACT:
523 CHKiRet(execAct(stmt, pMsg, pWti));
524 break;
525 case S_SET:
526 CHKiRet(execSet(stmt, pMsg, pWti));
527 break;
528 case S_UNSET:
529 CHKiRet(execUnset(stmt, pMsg));
530 break;
531 case S_CALL:
532 CHKiRet(execCall(stmt, pMsg, pWti));
533 break;
534 case S_CALL_INDIRECT:
535 CHKiRet(execCallIndirect(stmt, pMsg, pWti));
536 break;
537 case S_IF:
538 CHKiRet(execIf(stmt, pMsg, pWti));
539 break;
540 case S_FOREACH:
541 CHKiRet(execForeach(stmt, pMsg, pWti));
542 break;
543 case S_PRIFILT:
544 CHKiRet(execPRIFILT(stmt, pMsg, pWti));
545 break;
546 case S_PROPFILT:
547 CHKiRet(execPROPFILT(stmt, pMsg, pWti));
548 break;
549 case S_RELOAD_LOOKUP_TABLE:
550 CHKiRet(execReloadLookupTable(stmt));
551 break;
552 default:
553 dbgprintf("error: unknown stmt type %u during exec\n", (unsigned)stmt->nodetype);
554 break;
555 }
556 }
557 finalize_it:
558 RETiRet;
559 }
560
561
562 /* Process (consume) a batch of messages. Calls the actions configured.
563 * This is called by MAIN queues.
564 */
565 static rsRetVal processBatch(batch_t *pBatch, wti_t *pWti) {
566 int i;
567 smsg_t *pMsg;
568 ruleset_t *pRuleset;
569 rsRetVal localRet;
570 DEFiRet;
571
572 DBGPRINTF("processBATCH: batch of %d elements must be processed\n", pBatch->nElem);
573
574 wtiResetExecState(pWti, pBatch);
575
576 /* execution phase */
577 for (i = 0; i < batchNumMsgs(pBatch) && !*(pWti->pbShutdownImmediate); ++i) {
578 pMsg = pBatch->pElem[i].pMsg;
579 DBGPRINTF("processBATCH: next msg %d: %.128s\n", i, pMsg->pszRawMsg);
580 pRuleset = (pMsg->pRuleset == NULL) ? runConf->rulesets.pDflt : pMsg->pRuleset;
581 localRet = scriptExec(pRuleset->root, pMsg, pWti);
582 /* the most important case here is that processing may be aborted
583 * due to pbShutdownImmediate, in which case we MUST NOT flag this
584 * message as committed. If we would do so, the message would
585 * potentially be lost.
586 */
587 if (localRet == RS_RET_OK)
588 batchSetElemState(pBatch, i, BATCH_STATE_COMM);
589 else if (localRet == RS_RET_SUSPENDED)
590 --i;
591 }
592
593 /* commit phase */
594 DBGPRINTF(
595 "END batch execution phase, entering to commit phase "
596 "[processed %d of %d messages]\n",
597 i, batchNumMsgs(pBatch));
598 actionCommitAllDirect(pWti);
599
600 DBGPRINTF("processBATCH: batch of %d elements has been processed\n", pBatch->nElem);
601 RETiRet;
602 }
603
604
605 /* return the ruleset-assigned parser list. NULL means use the default
606 * parser list.
607 * rgerhards, 2009-11-04
608 */
609 static parserList_t *GetParserList(rsconf_t *conf, smsg_t *pMsg) {
610 return (pMsg->pRuleset == NULL) ? conf->rulesets.pDflt->pParserLst : pMsg->pRuleset->pParserLst;
611 }
612
613
614 /* Add a script block to the current ruleset */
615 static void ATTR_NONNULL(1) addScript(ruleset_t *const pThis, struct cnfstmt *const script) {
616 if (script == NULL) /* happens for include() */
617 return;
618 if (pThis->last == NULL)
619 pThis->root = pThis->last = script;
620 else {
621 pThis->last->next = script;
622 pThis->last = script;
623 }
624 }
625
626
627 /* set name for ruleset */
628 static rsRetVal rulesetSetName(ruleset_t *pThis, uchar *pszName) {
629 DEFiRet;
630 free(pThis->pszName);
631 CHKmalloc(pThis->pszName = ustrdup(pszName));
632
633 finalize_it:
634 RETiRet;
635 }
636
637
638 /* get current ruleset
639 * We use a non-standard calling interface, as nothing can go wrong and it
640 * is really much more natural to return the pointer directly.
641 */
642 static ruleset_t *GetCurrent(rsconf_t *conf) {
643 return conf->rulesets.pCurr;
644 }
645
646
647 /* get main queue associated with ruleset. If no ruleset-specifc main queue
648 * is set, the primary main message queue is returned.
649 * We use a non-standard calling interface, as nothing can go wrong and it
650 * is really much more natural to return the pointer directly.
651 */
652 static qqueue_t *GetRulesetQueue(ruleset_t *pThis) {
653 ISOBJ_TYPE_assert(pThis, ruleset);
654 return (pThis->pQueue == NULL) ? runConf->pMsgQueue : pThis->pQueue;
655 }
656
657
658 /* Find the ruleset with the given name and return a pointer to its object.
659 */
660 rsRetVal rulesetGetRuleset(rsconf_t *conf, ruleset_t **ppRuleset, uchar *pszName) {
661 DEFiRet;
662 assert(ppRuleset != NULL);
663 assert(pszName != NULL);
664
665 CHKiRet(llFind(&(conf->rulesets.llRulesets), pszName, (void *)ppRuleset));
666
667 finalize_it:
668 RETiRet;
669 }
670
671
672 /* Set a new default rule set. If the default can not be found, no change happens.
673 */
674 static rsRetVal SetDefaultRuleset(rsconf_t *conf, uchar *pszName) {
675 ruleset_t *pRuleset;
676 DEFiRet;
677 assert(pszName != NULL);
678
679 CHKiRet(rulesetGetRuleset(conf, &pRuleset, pszName));
680 conf->rulesets.pDflt = pRuleset;
681 DBGPRINTF("default rule set changed to %p: '%s'\n", pRuleset, pszName);
682
683 finalize_it:
684 RETiRet;
685 }
686
687
688 /* Set a new current rule set. If the ruleset can not be found, no change happens */
689 static rsRetVal SetCurrRuleset(rsconf_t *conf, uchar *pszName) {
690 ruleset_t *pRuleset;
691 DEFiRet;
692 assert(pszName != NULL);
693
694 CHKiRet(rulesetGetRuleset(conf, &pRuleset, pszName));
695 conf->rulesets.pCurr = pRuleset;
696 DBGPRINTF("current rule set changed to %p: '%s'\n", pRuleset, pszName);
697
698 finalize_it:
699 RETiRet;
700 }
701
702
703 /* Standard-Constructor
704 */
705 BEGINobjConstruct(ruleset) /* be sure to specify the object type also in END macro! */
706 pThis->root = NULL;
707 pThis->last = NULL;
708 ENDobjConstruct(ruleset)
709
710
711 /* ConstructionFinalizer
712 * This also adds the rule set to the list of all known rulesets.
713 */
714 static rsRetVal rulesetConstructFinalize(rsconf_t *conf, ruleset_t *pThis) {
715 uchar *keyName;
716 DEFiRet;
717 ISOBJ_TYPE_assert(pThis, ruleset);
718
719 /* we must duplicate our name, as the key destructer would also
720 * free it, resulting in a double-free. It's also cleaner to have
721 * two separate copies.
722 */
723 CHKmalloc(keyName = ustrdup(pThis->pszName));
724 CHKiRet(llAppend(&(conf->rulesets.llRulesets), keyName, pThis));
725
726 /* and also the default, if so far none has been set */
727 if (conf->rulesets.pDflt == NULL) conf->rulesets.pDflt = pThis;
728
729 finalize_it:
730 RETiRet;
731 }
732
733
734 /* destructor for the ruleset object */
735 BEGINobjDestruct(ruleset) /* be sure to specify the object type also in END and CODESTART macros! */
736 CODESTARTobjDestruct(ruleset);
737 DBGPRINTF("destructing ruleset %p, name %p\n", pThis, pThis->pszName);
738 if (pThis->pQueue != NULL) {
739 qqueueDestruct(&pThis->pQueue);
740 }
741 if (pThis->pParserLst != NULL) {
742 parser.DestructParserList(&pThis->pParserLst);
743 }
744 free(pThis->pszName);
745 ENDobjDestruct(ruleset)
746
747
748 /* helper for Destructor, shut down queue workers */
749 DEFFUNC_llExecFunc(doShutdownQueueWorkers) {
750 DEFiRet;
751 ruleset_t *const pThis = (ruleset_t *)pData;
752 DBGPRINTF("shutting down queue workers for ruleset %p, name %s, queue %p\n", pThis, pThis->pszName, pThis->pQueue);
753 ISOBJ_TYPE_assert(pThis, ruleset);
754 if (pThis->pQueue != NULL) {
755 qqueueShutdownWorkers(pThis->pQueue);
756 }
757 RETiRet;
758 }
759 /* helper for Destructor, shut down actions (cnfstmt's in general) */
760 DEFFUNC_llExecFunc(doDestructCnfStmt) {
761 DEFiRet;
762 ruleset_t *const pThis = (ruleset_t *)pData;
763 DBGPRINTF("shutting down actions and conf stmts for ruleset %p, name %s\n", pThis, pThis->pszName);
764 ISOBJ_TYPE_assert(pThis, ruleset);
765 cnfstmtDestructLst(pThis->root);
766 RETiRet;
767 }
768 /* destruct ALL rule sets that reside in the system. This must
769 * be callable before unloading this module as the module may
770 * not be unloaded before unload of the actions is required. This is
771 * kind of a left-over from previous logic and may be optimized one
772 * everything runs stable again. -- rgerhards, 2009-06-10
773 */
774 static rsRetVal destructAllActions(rsconf_t *conf) {
775 DEFiRet;
776
777 DBGPRINTF("rulesetDestructAllActions\n");
778 /* we first need to stop all queue workers, else we
779 * may run into trouble with "call" statements calling
780 * into then-destroyed rulesets.
781 * see: https://github.com/rsyslog/rsyslog/issues/1122
782 */
783 DBGPRINTF("destructAllActions: queue shutdown\n");
784 llExecFunc(&(conf->rulesets.llRulesets), doShutdownQueueWorkers, NULL);
785 DBGPRINTF("destructAllActions: action and conf stmt shutdown\n");
786 llExecFunc(&(conf->rulesets.llRulesets), doDestructCnfStmt, NULL);
787
788 CHKiRet(llDestroy(&(conf->rulesets.llRulesets)));
789 CHKiRet(llInit(&(conf->rulesets.llRulesets), rulesetDestructForLinkedList, rulesetKeyDestruct,
790 (int (*)(void *, void *))strcasecmp));
791 conf->rulesets.pDflt = NULL;
792
793 finalize_it:
794 RETiRet;
795 }
796
797 /* this is a special destructor for the linkedList class. LinkedList does NOT
798 * provide a pointer to the pointer, but rather the raw pointer itself. So we
799 * must map this, otherwise the destructor will abort.
800 */
801 rsRetVal rulesetDestructForLinkedList(void *pData) {
802 ruleset_t *pThis = (ruleset_t *)pData;
803 return rulesetDestruct(&pThis);
804 }
805
806 /* debugprint for the ruleset object */
807 BEGINobjDebugPrint(ruleset) /* be sure to specify the object type also in END and CODESTART macros! */
808 CODESTARTobjDebugPrint(ruleset);
809 dbgoprint((obj_t *)pThis, "rsyslog ruleset %s:\n", pThis->pszName);
810 cnfstmtPrint(pThis->root, 0);
811 dbgoprint((obj_t *)pThis, "ruleset %s assigned parser list:\n", pThis->pszName);
812 printParserList(pThis->pParserLst);
813 ENDobjDebugPrint(ruleset)
814
815
816 /* helper for debugPrintAll(), prints a single ruleset */
817 DEFFUNC_llExecFunc(doDebugPrintAll) {
818 return rulesetDebugPrint((ruleset_t *)pData);
819 }
820 /* debug print all rulesets
821 */
822 static rsRetVal debugPrintAll(rsconf_t *conf) {
823 DEFiRet;
824 dbgprintf("All Rulesets:\n");
825 llExecFunc(&(conf->rulesets.llRulesets), doDebugPrintAll, NULL);
826 dbgprintf("End of Rulesets.\n");
827 RETiRet;
828 }
829
830 struct cnfstmt *removeNOPs(struct cnfstmt *root);
831 static void rulesetOptimize(ruleset_t *pRuleset) {
832 if (Debug) {
833 dbgprintf("ruleset '%s' before optimization:\n", pRuleset->pszName);
834 rulesetDebugPrint((ruleset_t *)pRuleset);
835 }
836 pRuleset->root = cnfstmtOptimize(pRuleset->root);
837 if (Debug) {
838 dbgprintf("ruleset '%s' after optimization:\n", pRuleset->pszName);
839 rulesetDebugPrint((ruleset_t *)pRuleset);
840 }
841 }
842
843 /* helper for rulsetOptimizeAll(), optimizes a single ruleset */
844 DEFFUNC_llExecFunc(doRulesetOptimizeAll) {
845 rulesetOptimize((ruleset_t *)pData);
846 return RS_RET_OK;
847 }
848 /* optimize all rulesets
849 */
850 rsRetVal rulesetOptimizeAll(rsconf_t *conf) {
851 DEFiRet;
852 dbgprintf("begin ruleset optimization phase\n");
853 llExecFunc(&(conf->rulesets.llRulesets), doRulesetOptimizeAll, NULL);
854 dbgprintf("ruleset optimization phase finished.\n");
855 RETiRet;
856 }
857
858
859 /* Create a ruleset-specific "main" queue for this ruleset. If one is already
860 * defined, an error message is emitted but nothing else is done.
861 * Note: we use the main message queue parameters for queue creation and access
862 * syslogd.c directly to obtain these. This is far from being perfect, but
863 * considered acceptable for the time being.
864 * rgerhards, 2009-10-27
865 */
866 static rsRetVal doRulesetCreateQueue(rsconf_t *conf, int *pNewVal) {
867 uchar *rsname;
868 DEFiRet;
869
870 if (conf->rulesets.pCurr == NULL) {
871 LogError(0, RS_RET_NO_CURR_RULESET,
872 "error: currently no specific ruleset specified, thus a "
873 "queue can not be added to it");
874 ABORT_FINALIZE(RS_RET_NO_CURR_RULESET);
875 }
876
877 if (conf->rulesets.pCurr->pQueue != NULL) {
878 LogError(0, RS_RET_RULES_QUEUE_EXISTS,
879 "error: ruleset already has a main queue, can not "
880 "add another one");
881 ABORT_FINALIZE(RS_RET_RULES_QUEUE_EXISTS);
882 }
883
884 if (pNewVal == 0) FINALIZE; /* if it is turned off, we do not need to change anything ;) */
885
886 rsname = (conf->rulesets.pCurr->pszName == NULL) ? (uchar *)"[ruleset]" : conf->rulesets.pCurr->pszName;
887 DBGPRINTF("adding a ruleset-specific \"main\" queue for ruleset '%s'\n", rsname);
888 CHKiRet(createMainQueue(&conf->rulesets.pCurr->pQueue, rsname, NULL));
889
890 finalize_it:
891 RETiRet;
892 }
893
894 static rsRetVal rulesetCreateQueue(void __attribute__((unused)) * pVal, int *pNewVal) {
895 return doRulesetCreateQueue(ourConf, pNewVal);
896 }
897
898 /* Add a ruleset specific parser to the ruleset. Note that adding the first
899 * parser automatically disables the default parsers. If they are needed as well,
900 * the must be added via explicit config directives.
901 * Note: this is the only spot in the code that requires the parser object. In order
902 * to solve some class init bootstrap sequence problems, we get the object handle here
903 * instead of during module initialization. Note that objUse() is capable of being
904 * called multiple times.
905 * rgerhards, 2009-11-04
906 */
907 static rsRetVal doRulesetAddParser(ruleset_t *pRuleset, uchar *pName) {
908 parser_t *pParser;
909 DEFiRet;
910
911 CHKiRet(objUse(parser, CORE_COMPONENT));
912 iRet = parser.FindParser(loadConf->parsers.pParsLstRoot, &pParser, pName);
913 if (iRet == RS_RET_PARSER_NOT_FOUND) {
914 LogError(0, RS_RET_PARSER_NOT_FOUND,
915 "error: parser '%s' unknown at this time "
916 "(maybe defined too late in rsyslog.conf?)",
917 pName);
918 ABORT_FINALIZE(RS_RET_NO_CURR_RULESET);
919 } else if (iRet != RS_RET_OK) {
920 LogError(0, iRet, "error trying to find parser '%s'\n", pName);
921 FINALIZE;
922 }
923
924 CHKiRet(parser.AddParserToList(&pRuleset->pParserLst, pParser));
925
926 DBGPRINTF("added parser '%s' to ruleset '%s'\n", pName, pRuleset->pszName);
927
928 finalize_it:
929 free(pName); /* no longer needed */
930
931 RETiRet;
932 }
933
934 static rsRetVal rulesetAddParser(void __attribute__((unused)) * pVal, uchar *pName) {
935 return doRulesetAddParser(loadConf->rulesets.pCurr, pName);
936 }
937
938
939 /* Process ruleset() objects */
940 rsRetVal rulesetProcessCnf(struct cnfobj *o) {
941 struct cnfparamvals *pvals;
942 rsRetVal localRet;
943 uchar *rsName = NULL;
944 uchar *parserName;
945 int nameIdx, parserIdx;
946 ruleset_t *pRuleset;
947 struct cnfarray *ar;
948 int i;
949 int qtype;
950 uchar *rsname;
951 DEFiRet;
952
953 pvals = nvlstGetParams(o->nvlst, &rspblk, NULL);
954 if (pvals == NULL) {
955 ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
956 }
957 DBGPRINTF("ruleset param blk after rulesetProcessCnf:\n");
958 cnfparamsPrint(&rspblk, pvals);
959 nameIdx = cnfparamGetIdx(&rspblk, "name");
960 rsName = (uchar *)es_str2cstr(pvals[nameIdx].val.d.estr, NULL);
961
962 localRet = rulesetGetRuleset(loadConf, &pRuleset, rsName);
963 if (localRet == RS_RET_OK) {
964 LogError(0, RS_RET_RULESET_EXISTS, "error: ruleset '%s' specified more than once", rsName);
965 cnfstmtDestructLst(o->script);
966 ABORT_FINALIZE(RS_RET_RULESET_EXISTS);
967 } else if (localRet != RS_RET_NOT_FOUND) {
968 ABORT_FINALIZE(localRet);
969 }
970
971 CHKiRet(rulesetConstruct(&pRuleset));
972 if ((localRet = rulesetSetName(pRuleset, rsName)) != RS_RET_OK) {
973 rulesetDestruct(&pRuleset);
974 ABORT_FINALIZE(localRet);
975 }
976 if ((localRet = rulesetConstructFinalize(loadConf, pRuleset)) != RS_RET_OK) {
977 rulesetDestruct(&pRuleset);
978 ABORT_FINALIZE(localRet);
979 }
980 addScript(pRuleset, o->script);
981
982 /* we have only two params, so we do NOT do the usual param loop */
983 parserIdx = cnfparamGetIdx(&rspblk, "parser");
984 if (parserIdx != -1 && pvals[parserIdx].bUsed) {
985 ar = pvals[parserIdx].val.d.ar;
986 for (i = 0; i < ar->nmemb; ++i) {
987 parserName = (uchar *)es_str2cstr(ar->arr[i], NULL);
988 doRulesetAddParser(pRuleset, parserName);
989 /* note parserName is freed in doRulesetAddParser()! */
990 }
991 }
992
993 /* pick up ruleset queue parameters */
994 if (queueCnfParamsSet(o->nvlst)) {
995 if (pRuleset->pszName == NULL) {
996 rsname = (uchar *)"[ruleset]";
997 qtype = pRuleset->pQueue->qType;
998 } else {
999 rsname = pRuleset->pszName;
1000 qtype = 3;
1001 }
1002 DBGPRINTF("adding a ruleset-specific \"main\" queue for ruleset '%s', mode %d\n", rsname, qtype);
1003 CHKiRet(createMainQueue(&pRuleset->pQueue, rsname, o->nvlst));
1004 }
1005
1006 finalize_it:
1007 free(rsName);
1008 cnfparamvalsDestruct(pvals, &rspblk);
1009 RETiRet;
1010 }
1011
1012
1013 /* queryInterface function
1014 * rgerhards, 2008-02-21
1015 */
1016 BEGINobjQueryInterface(ruleset)
1017 CODESTARTobjQueryInterface(ruleset);
1018 if (pIf->ifVersion != rulesetCURR_IF_VERSION) { /* check for current version, increment on each change */
1019 ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED);
1020 }
1021
1022 /* ok, we have the right interface, so let's fill it
1023 * Please note that we may also do some backwards-compatibility
1024 * work here (if we can support an older interface version - that,
1025 * of course, also affects the "if" above).
1026 */
1027 pIf->Construct = rulesetConstruct;
1028 pIf->ConstructFinalize = rulesetConstructFinalize;
1029 pIf->Destruct = rulesetDestruct;
1030 pIf->DebugPrint = rulesetDebugPrint;
1031
1032 pIf->IterateAllActions = iterateAllActions;
1033 pIf->DestructAllActions = destructAllActions;
1034 pIf->AddScript = addScript;
1035 pIf->ProcessBatch = processBatch;
1036 pIf->SetName = rulesetSetName;
1037 pIf->DebugPrintAll = debugPrintAll;
1038 pIf->GetCurrent = GetCurrent;
1039 pIf->GetRuleset = rulesetGetRuleset;
1040 pIf->SetDefaultRuleset = SetDefaultRuleset;
1041 pIf->SetCurrRuleset = SetCurrRuleset;
1042 pIf->GetRulesetQueue = GetRulesetQueue;
1043 pIf->GetParserList = GetParserList;
1044 finalize_it:
1045 ENDobjQueryInterface(ruleset)
1046
1047
1048 /* Exit the ruleset class.
1049 * rgerhards, 2009-04-06
1050 */
1051 BEGINObjClassExit(ruleset, OBJ_IS_CORE_MODULE) /* class, version */
1052 objRelease(parser, CORE_COMPONENT);
1053 ENDObjClassExit(ruleset)
1054
1055
1056 /* Initialize the ruleset class. Must be called as the very first method
1057 * before anything else is called inside this class.
1058 * rgerhards, 2008-02-19
1059 */
1060 BEGINObjClassInit(ruleset, 1, OBJ_IS_CORE_MODULE) /* class, version */
1061 /* request objects we use */
1062
1063 /* set our own handlers */
1064 OBJSetMethodHandler(objMethod_DEBUGPRINT, rulesetDebugPrint);
1065 OBJSetMethodHandler(objMethod_CONSTRUCTION_FINALIZER, rulesetConstructFinalize);
1066
1067 /* config file handlers */
1068 CHKiRet(regCfSysLineHdlr((uchar *)"rulesetparser", 0, eCmdHdlrGetWord, rulesetAddParser, NULL, NULL));
1069 CHKiRet(regCfSysLineHdlr((uchar *)"rulesetcreatemainqueue", 0, eCmdHdlrBinary, rulesetCreateQueue, NULL, NULL));
1070 ENDObjClassInit(ruleset)