Debian Codegraph @

runtime/msg.c

raw
1 /* msg.c
2 * The msg object. Implementation of all msg-related functions
3 *
4 * File begun on 2007-07-13 by RGerhards (extracted from syslogd.c)
5 * This file is under development and has not yet arrived at being fully
6 * self-contained and a real object. So far, it is mostly an excerpt
7 * of the "old" message code without any modifications. However, it
8 * helps to have things at the right place one we go to the meat of it.
9 *
10 * Copyright 2007-2026 Rainer Gerhards and Adiscon GmbH.
11 *
12 * This file is part of the rsyslog runtime library.
13 *
14 * The rsyslog runtime library is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * The rsyslog runtime library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Lesser General Public License for more details.
23 *
24 * You should have received a copy of the GNU Lesser General Public License
25 * along with the rsyslog runtime library. If not, see <http://www.gnu.org/licenses/>.
26 *
27 * A copy of the GPL can be found in the file "COPYING" in this distribution.
28 * A copy of the LGPL can be found in the file "COPYING.LESSER" in this distribution.
29 */
30 #include "config.h"
31 #include <stdio.h>
32 #include <stdarg.h>
33 #include <stdlib.h>
34 #define SYSLOG_NAMES
35 #include <string.h>
36 #include <assert.h>
37 #include <ctype.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #ifdef HAVE_SYSINFO_UPTIME
41 #include <sys/sysinfo.h>
42 #endif
43 #include <netdb.h>
44 #include <libestr.h>
45 #include <json.h>
46 #ifdef HAVE_MALLOC_H
47 #include <malloc.h>
48 #endif
49 #ifdef USE_LIBUUID
50 #include <uuid/uuid.h>
51 #endif
52 #include <errno.h>
53 #include "rsyslog.h"
54 #include "srUtils.h"
55 #include "stringbuf.h"
56 #include "template.h"
57 #include "msg.h"
58 #include "datetime.h"
59 #include "glbl.h"
60 #include "regexp.h"
61 #include "atomic.h"
62 #include "unicode-helper.h"
63 #include "ruleset.h"
64 #include "prop.h"
65 #include "net.h"
66 #include "var.h"
67 #include "rsconf.h"
68 #include "parserif.h"
69 #include "errmsg.h"
70
71 #define DEV_DEBUG 0 /* set to 1 to enable very verbose developer debugging messages */
72
73 /* TODO: move the global variable root to the config object - had no time to to it
74 * right now before vacation -- rgerhards, 2013-07-22
75 */
76 static pthread_mutex_t glblVars_lock;
77 struct json_object *global_var_root = NULL;
78
79 /* static data */
80 DEFobjStaticHelpers;
81 DEFobjCurrIf(datetime) DEFobjCurrIf(glbl) DEFobjCurrIf(regexp) DEFobjCurrIf(prop) DEFobjCurrIf(net) DEFobjCurrIf(var)
82
83 static const char *one_digit[10] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
84
85 static const char *two_digits[100] = {
86 "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16",
87 "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33",
88 "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50",
89 "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67",
90 "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84",
91 "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99"};
92
93 static const char *wdayNames[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
94
95 /* Table of days in a year, needed for getYearDay */
96 static const char *daysInYear[366] = {
97 "001", "002", "003", "004", "005", "006", "007", "008", "009", "010", "011", "012", "013", "014", "015", "016",
98 "017", "018", "019", "020", "021", "022", "023", "024", "025", "026", "027", "028", "029", "030", "031", "032",
99 "033", "034", "035", "036", "037", "038", "039", "040", "041", "042", "043", "044", "045", "046", "047", "048",
100 "049", "050", "051", "052", "053", "054", "055", "056", "057", "058", "059", "060", "061", "062", "063", "064",
101 "065", "066", "067", "068", "069", "070", "071", "072", "073", "074", "075", "076", "077", "078", "079", "080",
102 "081", "082", "083", "084", "085", "086", "087", "088", "089", "090", "091", "092", "093", "094", "095", "096",
103 "097", "098", "099", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112",
104 "113", "114", "115", "116", "117", "118", "119", "120", "121", "122", "123", "124", "125", "126", "127", "128",
105 "129", "130", "131", "132", "133", "134", "135", "136", "137", "138", "139", "140", "141", "142", "143", "144",
106 "145", "146", "147", "148", "149", "150", "151", "152", "153", "154", "155", "156", "157", "158", "159", "160",
107 "161", "162", "163", "164", "165", "166", "167", "168", "169", "170", "171", "172", "173", "174", "175", "176",
108 "177", "178", "179", "180", "181", "182", "183", "184", "185", "186", "187", "188", "189", "190", "191", "192",
109 "193", "194", "195", "196", "197", "198", "199", "200", "201", "202", "203", "204", "205", "206", "207", "208",
110 "209", "210", "211", "212", "213", "214", "215", "216", "217", "218", "219", "220", "221", "222", "223", "224",
111 "225", "226", "227", "228", "229", "230", "231", "232", "233", "234", "235", "236", "237", "238", "239", "240",
112 "241", "242", "243", "244", "245", "246", "247", "248", "249", "250", "251", "252", "253", "254", "255", "256",
113 "257", "258", "259", "260", "261", "262", "263", "264", "265", "266", "267", "268", "269", "270", "271", "272",
114 "273", "274", "275", "276", "277", "278", "279", "280", "281", "282", "283", "284", "285", "286", "287", "288",
115 "289", "290", "291", "292", "293", "294", "295", "296", "297", "298", "299", "300", "301", "302", "303", "304",
116 "305", "306", "307", "308", "309", "310", "311", "312", "313", "314", "315", "316", "317", "318", "319", "320",
117 "321", "322", "323", "324", "325", "326", "327", "328", "329", "330", "331", "332", "333", "334", "335", "336",
118 "337", "338", "339", "340", "341", "342", "343", "344", "345", "346", "347", "348", "349", "350", "351", "352",
119 "353", "354", "355", "356", "357", "358", "359", "360", "361", "362", "363", "364", "365", "366"};
120
121 /* The following is a table of supported years. This permits us
122 * to avoid dynamic memory allocation. Note that the time-based
123 * algos need to be upgraded after the year 2099 in any case.
124 * Quite honestly, I don't expect that this is a real problem ;)
125 */
126 static const char *years[] = {
127 "1967", "1968", "1969", "1970", "1971", "1972", "1973", "1974", "1975", "1976", "1977", "1978", "1979", "1980",
128 "1981", "1982", "1983", "1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991", "1992", "1993", "1994",
129 "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008",
130 "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022",
131 "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030", "2031", "2032", "2033", "2034", "2035", "2036",
132 "2037", "2038", "2039", "2040", "2041", "2042", "2043", "2044", "2045", "2046", "2047", "2048", "2049", "2050",
133 "2051", "2052", "2053", "2054", "2055", "2056", "2057", "2058", "2059", "2060", "2061", "2062", "2063", "2064",
134 "2065", "2066", "2067", "2068", "2069", "2070", "2071", "2072", "2073", "2074", "2075", "2076", "2077", "2078",
135 "2079", "2080", "2081", "2082", "2083", "2084", "2085", "2086", "2087", "2088", "2089", "2090", "2091", "2092",
136 "2093", "2094", "2095", "2096", "2097", "2098", "2099"};
137
138 static struct {
139 uchar *pszName;
140 } syslog_pri_names[200] = {
141 {UCHAR_CONSTANT("0")}, {UCHAR_CONSTANT("1")}, {UCHAR_CONSTANT("2")}, {UCHAR_CONSTANT("3")},
142 {UCHAR_CONSTANT("4")}, {UCHAR_CONSTANT("5")}, {UCHAR_CONSTANT("6")}, {UCHAR_CONSTANT("7")},
143 {UCHAR_CONSTANT("8")}, {UCHAR_CONSTANT("9")}, {UCHAR_CONSTANT("10")}, {UCHAR_CONSTANT("11")},
144 {UCHAR_CONSTANT("12")}, {UCHAR_CONSTANT("13")}, {UCHAR_CONSTANT("14")}, {UCHAR_CONSTANT("15")},
145 {UCHAR_CONSTANT("16")}, {UCHAR_CONSTANT("17")}, {UCHAR_CONSTANT("18")}, {UCHAR_CONSTANT("19")},
146 {UCHAR_CONSTANT("20")}, {UCHAR_CONSTANT("21")}, {UCHAR_CONSTANT("22")}, {UCHAR_CONSTANT("23")},
147 {UCHAR_CONSTANT("24")}, {UCHAR_CONSTANT("25")}, {UCHAR_CONSTANT("26")}, {UCHAR_CONSTANT("27")},
148 {UCHAR_CONSTANT("28")}, {UCHAR_CONSTANT("29")}, {UCHAR_CONSTANT("30")}, {UCHAR_CONSTANT("31")},
149 {UCHAR_CONSTANT("32")}, {UCHAR_CONSTANT("33")}, {UCHAR_CONSTANT("34")}, {UCHAR_CONSTANT("35")},
150 {UCHAR_CONSTANT("36")}, {UCHAR_CONSTANT("37")}, {UCHAR_CONSTANT("38")}, {UCHAR_CONSTANT("39")},
151 {UCHAR_CONSTANT("40")}, {UCHAR_CONSTANT("41")}, {UCHAR_CONSTANT("42")}, {UCHAR_CONSTANT("43")},
152 {UCHAR_CONSTANT("44")}, {UCHAR_CONSTANT("45")}, {UCHAR_CONSTANT("46")}, {UCHAR_CONSTANT("47")},
153 {UCHAR_CONSTANT("48")}, {UCHAR_CONSTANT("49")}, {UCHAR_CONSTANT("50")}, {UCHAR_CONSTANT("51")},
154 {UCHAR_CONSTANT("52")}, {UCHAR_CONSTANT("53")}, {UCHAR_CONSTANT("54")}, {UCHAR_CONSTANT("55")},
155 {UCHAR_CONSTANT("56")}, {UCHAR_CONSTANT("57")}, {UCHAR_CONSTANT("58")}, {UCHAR_CONSTANT("59")},
156 {UCHAR_CONSTANT("60")}, {UCHAR_CONSTANT("61")}, {UCHAR_CONSTANT("62")}, {UCHAR_CONSTANT("63")},
157 {UCHAR_CONSTANT("64")}, {UCHAR_CONSTANT("65")}, {UCHAR_CONSTANT("66")}, {UCHAR_CONSTANT("67")},
158 {UCHAR_CONSTANT("68")}, {UCHAR_CONSTANT("69")}, {UCHAR_CONSTANT("70")}, {UCHAR_CONSTANT("71")},
159 {UCHAR_CONSTANT("72")}, {UCHAR_CONSTANT("73")}, {UCHAR_CONSTANT("74")}, {UCHAR_CONSTANT("75")},
160 {UCHAR_CONSTANT("76")}, {UCHAR_CONSTANT("77")}, {UCHAR_CONSTANT("78")}, {UCHAR_CONSTANT("79")},
161 {UCHAR_CONSTANT("80")}, {UCHAR_CONSTANT("81")}, {UCHAR_CONSTANT("82")}, {UCHAR_CONSTANT("83")},
162 {UCHAR_CONSTANT("84")}, {UCHAR_CONSTANT("85")}, {UCHAR_CONSTANT("86")}, {UCHAR_CONSTANT("87")},
163 {UCHAR_CONSTANT("88")}, {UCHAR_CONSTANT("89")}, {UCHAR_CONSTANT("90")}, {UCHAR_CONSTANT("91")},
164 {UCHAR_CONSTANT("92")}, {UCHAR_CONSTANT("93")}, {UCHAR_CONSTANT("94")}, {UCHAR_CONSTANT("95")},
165 {UCHAR_CONSTANT("96")}, {UCHAR_CONSTANT("97")}, {UCHAR_CONSTANT("98")}, {UCHAR_CONSTANT("99")},
166 {UCHAR_CONSTANT("100")}, {UCHAR_CONSTANT("101")}, {UCHAR_CONSTANT("102")}, {UCHAR_CONSTANT("103")},
167 {UCHAR_CONSTANT("104")}, {UCHAR_CONSTANT("105")}, {UCHAR_CONSTANT("106")}, {UCHAR_CONSTANT("107")},
168 {UCHAR_CONSTANT("108")}, {UCHAR_CONSTANT("109")}, {UCHAR_CONSTANT("110")}, {UCHAR_CONSTANT("111")},
169 {UCHAR_CONSTANT("112")}, {UCHAR_CONSTANT("113")}, {UCHAR_CONSTANT("114")}, {UCHAR_CONSTANT("115")},
170 {UCHAR_CONSTANT("116")}, {UCHAR_CONSTANT("117")}, {UCHAR_CONSTANT("118")}, {UCHAR_CONSTANT("119")},
171 {UCHAR_CONSTANT("120")}, {UCHAR_CONSTANT("121")}, {UCHAR_CONSTANT("122")}, {UCHAR_CONSTANT("123")},
172 {UCHAR_CONSTANT("124")}, {UCHAR_CONSTANT("125")}, {UCHAR_CONSTANT("126")}, {UCHAR_CONSTANT("127")},
173 {UCHAR_CONSTANT("128")}, {UCHAR_CONSTANT("129")}, {UCHAR_CONSTANT("130")}, {UCHAR_CONSTANT("131")},
174 {UCHAR_CONSTANT("132")}, {UCHAR_CONSTANT("133")}, {UCHAR_CONSTANT("134")}, {UCHAR_CONSTANT("135")},
175 {UCHAR_CONSTANT("136")}, {UCHAR_CONSTANT("137")}, {UCHAR_CONSTANT("138")}, {UCHAR_CONSTANT("139")},
176 {UCHAR_CONSTANT("140")}, {UCHAR_CONSTANT("141")}, {UCHAR_CONSTANT("142")}, {UCHAR_CONSTANT("143")},
177 {UCHAR_CONSTANT("144")}, {UCHAR_CONSTANT("145")}, {UCHAR_CONSTANT("146")}, {UCHAR_CONSTANT("147")},
178 {UCHAR_CONSTANT("148")}, {UCHAR_CONSTANT("149")}, {UCHAR_CONSTANT("150")}, {UCHAR_CONSTANT("151")},
179 {UCHAR_CONSTANT("152")}, {UCHAR_CONSTANT("153")}, {UCHAR_CONSTANT("154")}, {UCHAR_CONSTANT("155")},
180 {UCHAR_CONSTANT("156")}, {UCHAR_CONSTANT("157")}, {UCHAR_CONSTANT("158")}, {UCHAR_CONSTANT("159")},
181 {UCHAR_CONSTANT("160")}, {UCHAR_CONSTANT("161")}, {UCHAR_CONSTANT("162")}, {UCHAR_CONSTANT("163")},
182 {UCHAR_CONSTANT("164")}, {UCHAR_CONSTANT("165")}, {UCHAR_CONSTANT("166")}, {UCHAR_CONSTANT("167")},
183 {UCHAR_CONSTANT("168")}, {UCHAR_CONSTANT("169")}, {UCHAR_CONSTANT("170")}, {UCHAR_CONSTANT("171")},
184 {UCHAR_CONSTANT("172")}, {UCHAR_CONSTANT("173")}, {UCHAR_CONSTANT("174")}, {UCHAR_CONSTANT("175")},
185 {UCHAR_CONSTANT("176")}, {UCHAR_CONSTANT("177")}, {UCHAR_CONSTANT("178")}, {UCHAR_CONSTANT("179")},
186 {UCHAR_CONSTANT("180")}, {UCHAR_CONSTANT("181")}, {UCHAR_CONSTANT("182")}, {UCHAR_CONSTANT("183")},
187 {UCHAR_CONSTANT("184")}, {UCHAR_CONSTANT("185")}, {UCHAR_CONSTANT("186")}, {UCHAR_CONSTANT("187")},
188 {UCHAR_CONSTANT("188")}, {UCHAR_CONSTANT("189")}, {UCHAR_CONSTANT("190")}, {UCHAR_CONSTANT("191")},
189 {UCHAR_CONSTANT("192")}, {UCHAR_CONSTANT("193")}, {UCHAR_CONSTANT("194")}, {UCHAR_CONSTANT("195")},
190 {UCHAR_CONSTANT("196")}, {UCHAR_CONSTANT("197")}, {UCHAR_CONSTANT("198")}, {UCHAR_CONSTANT("199")}};
191 static char hexdigit[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
192
193 #if defined(_AIX)
194 /* AIXPORT : replace facility names with aso and caa only for AIX */
195 static const char *syslog_fac_names[LOG_NFACILITIES] = {
196 "kern", "user", "mail", "daemon", "auth", "syslog", "lpr", "news", "uucp",
197 "cron", "authpriv", "ftp", "aso", "audit", "alert", "caa", "local0", "local1",
198 "local2", "local3", "local4", "local5", "local6", "local7", "invld"};
199 /* length of the facility names string (for optimizatiions) */
200 static short len_syslog_fac_names[LOG_NFACILITIES] = {4, 4, 4, 6, 4, 6, 3, 4, 4, 4, 8, 3, 3,
201 5, 5, 3, 6, 6, 6, 6, 6, 6, 6, 6, 5};
202
203 #else
204 /*syslog facility names (as of RFC5424) */
205 static const char *syslog_fac_names[LOG_NFACILITIES] = {
206 "kern", "user", "mail", "daemon", "auth", "syslog", "lpr", "news", "uucp",
207 "cron", "authpriv", "ftp", "ntp", "audit", "alert", "clock", "local0", "local1",
208 "local2", "local3", "local4", "local5", "local6", "local7", "invld"};
209 /* length of the facility names string (for optimizatiions) */
210 static short len_syslog_fac_names[LOG_NFACILITIES] = {4, 4, 4, 6, 4, 6, 3, 4, 4, 4, 8, 3, 3,
211 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 5};
212 #endif
213
214 /* table of severity names (in numerical order)*/
215 static const char *syslog_severity_names[8] = {"emerg", "alert", "crit", "err", "warning", "notice", "info", "debug"};
216 static short len_syslog_severity_names[8] = {5, 5, 4, 3, 7, 6, 4, 5};
217
218 /* numerical values as string - this is the most efficient approach to convert severity
219 * and facility values to a numerical string... -- rgerhars, 2009-06-17
220 */
221
222 static const char *syslog_number_names[LOG_NFACILITIES] = {"0", "1", "2", "3", "4", "5", "6", "7", "8",
223 "9", "10", "11", "12", "13", "14", "15", "16", "17",
224 "18", "19", "20", "21", "22", "23", "24"};
225
226 /* global variables */
227 #if defined(HAVE_MALLOC_TRIM) && !defined(HAVE_ATOMIC_BUILTINS)
228 static pthread_mutex_t mutTrimCtr; /* mutex to handle malloc trim */
229 #endif
230
231 /* some forward declarations */
232 static int getAPPNAMELen(smsg_t *const pM, sbool bLockMutex);
233 static rsRetVal jsonPathFindParent(
234 struct json_object *jroot, uchar *name, uchar *leaf, struct json_object **parent, int bCreate);
235 static uchar *jsonPathGetLeaf(uchar *name, int lenName);
236 static json_bool jsonVarExtract(struct json_object *root, const char *key, struct json_object **value);
237 void getRawMsgAfterPRI(smsg_t *const pM, uchar **pBuf, int *piLen);
238
239
240 /* the locking and unlocking implementations: */
241 void MsgLock(smsg_t *pThis) {
242 #if DEV_DEBUG == 1
243 dbgprintf("MsgLock(0x%lx)\n", (unsigned long)pThis);
244 #endif
245 pthread_mutex_lock(&pThis->mut);
246 }
247 void MsgUnlock(smsg_t *pThis) {
248 #if DEV_DEBUG == 1
249 dbgprintf("MsgUnlock(0x%lx)\n", (unsigned long)pThis);
250 #endif
251 pthread_mutex_unlock(&pThis->mut);
252 }
253
254
255 /* set RcvFromIP name in msg object WITHOUT calling AddRef.
256 * rgerhards, 2013-01-22
257 */
258 static inline void MsgSetRcvFromIPWithoutAddRef(smsg_t *pThis, prop_t *new) {
259 if (pThis->pRcvFromIP != NULL) prop.Destruct(&pThis->pRcvFromIP);
260 pThis->pRcvFromIP = new;
261 }
262
263 static inline void MsgSetRcvFromPortWithoutAddRef(smsg_t *pThis, prop_t *new) {
264 if (pThis->pRcvFromPort != NULL) prop.Destruct(&pThis->pRcvFromPort);
265 pThis->pRcvFromPort = new;
266 }
267
268
269 /* set RcvFrom name in msg object WITHOUT calling AddRef.
270 * rgerhards, 2013-01-22
271 */
272 static void MsgSetRcvFromWithoutAddRef(smsg_t *pThis, prop_t *new) {
273 assert(pThis != NULL);
274
275 if (pThis->msgFlags & NEEDS_DNSRESOL) {
276 if (pThis->rcvFrom.pfrominet != NULL) free(pThis->rcvFrom.pfrominet);
277 pThis->msgFlags &= ~NEEDS_DNSRESOL;
278 } else {
279 if (pThis->rcvFrom.pRcvFrom != NULL) prop.Destruct(&pThis->rcvFrom.pRcvFrom);
280 }
281 pThis->rcvFrom.pRcvFrom = new;
282 }
283
284
285 /* rgerhards 2012-04-18: set associated ruleset (by ruleset name)
286 * pRuleset pointer inside msg is updated. If ruleset cannot be found,
287 * no update is done and an error message emitted.
288 */
289 static void ATTR_NONNULL() MsgSetRulesetByName(smsg_t *const pMsg, cstr_t *const rulesetName) {
290 uchar *const rs_name = rsCStrGetSzStrNoNULL(rulesetName);
291 const rsRetVal localRet = rulesetGetRuleset(runConf, &(pMsg->pRuleset), rs_name);
292
293 if (localRet != RS_RET_OK) {
294 LogError(0, localRet,
295 "msg: ruleset '%s' could not be found and could not "
296 "be assigned to message object. This possibly leads to the message "
297 "being processed incorrectly. We cannot do anything against this, but "
298 "wanted to let you know.",
299 rs_name);
300 }
301 }
302
303 /* do a DNS reverse resolution, if not already done, reflect status
304 * rgerhards, 2009-11-16
305 */
306 static rsRetVal resolveDNS(smsg_t *const pMsg) {
307 rsRetVal localRet;
308 prop_t *propFromHost = NULL;
309 prop_t *ip;
310 prop_t *localName;
311 prop_t *port = NULL;
312 char portbuf[8];
313 uint16_t pnum;
314 DEFiRet;
315
316 MsgLock(pMsg);
317 CHKiRet(objUse(net, CORE_COMPONENT));
318 if (pMsg->msgFlags & NEEDS_DNSRESOL) {
319 if (pMsg->msgFlags & PRESERVE_CASE) {
320 localRet = net.cvthname(pMsg->rcvFrom.pfrominet, NULL, &localName, &ip);
321 } else {
322 localRet = net.cvthname(pMsg->rcvFrom.pfrominet, &localName, NULL, &ip);
323 }
324 if (localRet == RS_RET_OK) {
325 /* we pass down the props, so no need for AddRef */
326 MsgSetRcvFromWithoutAddRef(pMsg, localName);
327 MsgSetRcvFromIPWithoutAddRef(pMsg, ip);
328
329 if (pMsg->pRcvFromPort == NULL) {
330 if (pMsg->rcvFrom.pfrominet->ss_family == AF_INET)
331 pnum = ntohs(((struct sockaddr_in *)pMsg->rcvFrom.pfrominet)->sin_port);
332 else if (pMsg->rcvFrom.pfrominet->ss_family == AF_INET6)
333 pnum = ntohs(((struct sockaddr_in6 *)pMsg->rcvFrom.pfrominet)->sin6_port);
334 else
335 pnum = 0;
336 snprintf(portbuf, sizeof(portbuf), "%u", pnum);
337 CHKiRet(prop.CreateStringProp(&port, (uchar *)portbuf, strlen(portbuf)));
338 MsgSetRcvFromPortWithoutAddRef(pMsg, port);
339 port = NULL;
340 }
341 }
342 }
343 finalize_it:
344 if (iRet != RS_RET_OK) {
345 /* best we can do: remove property */
346 MsgSetRcvFromStr(pMsg, UCHAR_CONSTANT(""), 0, &propFromHost);
347 prop.Destruct(&propFromHost);
348 }
349 MsgUnlock(pMsg);
350 if (propFromHost != NULL) prop.Destruct(&propFromHost);
351 if (port != NULL) prop.Destruct(&port);
352 RETiRet;
353 }
354
355
356 void getInputName(const smsg_t *const pM, uchar **ppsz, int *const plen) {
357 if (pM == NULL || pM->pInputName == NULL) {
358 *ppsz = UCHAR_CONSTANT("");
359 *plen = 0;
360 } else {
361 prop.GetString(pM->pInputName, ppsz, plen);
362 }
363 }
364
365
366 static uchar *getRcvFromIP(smsg_t *const pM) {
367 uchar *psz;
368 int len;
369 if (pM == NULL) {
370 psz = UCHAR_CONSTANT("");
371 } else {
372 resolveDNS(pM); /* make sure we have a resolved entry */
373 if (pM->pRcvFromIP == NULL)
374 psz = UCHAR_CONSTANT("");
375 else
376 prop.GetString(pM->pRcvFromIP, &psz, &len);
377 }
378 return psz;
379 }
380
381 static uchar *getRcvFromPort(smsg_t *const pM) {
382 uchar *psz;
383 int len;
384 if (pM == NULL) {
385 psz = UCHAR_CONSTANT("");
386 } else {
387 resolveDNS(pM);
388 if (pM->pRcvFromPort == NULL)
389 psz = UCHAR_CONSTANT("");
390 else
391 prop.GetString(pM->pRcvFromPort, &psz, &len);
392 }
393 return psz;
394 }
395
396
397 /* map a property name (string) to a property ID */
398 rsRetVal propNameToID(const uchar *const pName, propid_t *const pPropID) {
399 DEFiRet;
400
401 /* sometimes there are aliases to the original MonitoWare
402 * property names. These come after || in the ifs below. */
403 if (!strcasecmp((char *)pName, "msg")) {
404 *pPropID = PROP_MSG;
405 } else if (!strcasecmp((char *)pName, "timestamp") || !strcasecmp((char *)pName, "timereported")) {
406 *pPropID = PROP_TIMESTAMP;
407 } else if (!strcasecmp((char *)pName, "hostname") || !strcasecmp((char *)pName, "source")) {
408 *pPropID = PROP_HOSTNAME;
409 } else if (!strcasecmp((char *)pName, "syslogtag")) {
410 *pPropID = PROP_SYSLOGTAG;
411 } else if (!strcasecmp((char *)pName, "rawmsg")) {
412 *pPropID = PROP_RAWMSG;
413 } else if (!strcasecmp((char *)pName, "rawmsg-after-pri")) {
414 *pPropID = PROP_RAWMSG_AFTER_PRI;
415 } else if (!strcasecmp((char *)pName, "inputname")) {
416 *pPropID = PROP_INPUTNAME;
417 } else if (!strcasecmp((char *)pName, "fromhost")) {
418 *pPropID = PROP_FROMHOST;
419 } else if (!strcasecmp((char *)pName, "fromhost-ip")) {
420 *pPropID = PROP_FROMHOST_IP;
421 } else if (!strcasecmp((char *)pName, "fromhost-port")) {
422 *pPropID = PROP_FROMHOST_PORT;
423 } else if (!strcasecmp((char *)pName, "pri")) {
424 *pPropID = PROP_PRI;
425 } else if (!strcasecmp((char *)pName, "pri-text")) {
426 *pPropID = PROP_PRI_TEXT;
427 } else if (!strcasecmp((char *)pName, "iut")) {
428 *pPropID = PROP_IUT;
429 } else if (!strcasecmp((char *)pName, "syslogfacility")) {
430 *pPropID = PROP_SYSLOGFACILITY;
431 } else if (!strcasecmp((char *)pName, "syslogfacility-text")) {
432 *pPropID = PROP_SYSLOGFACILITY_TEXT;
433 } else if (!strcasecmp((char *)pName, "syslogseverity") || !strcasecmp((char *)pName, "syslogpriority")) {
434 *pPropID = PROP_SYSLOGSEVERITY;
435 } else if (!strcasecmp((char *)pName, "syslogseverity-text") || !strcasecmp((char *)pName, "syslogpriority-text")) {
436 *pPropID = PROP_SYSLOGSEVERITY_TEXT;
437 } else if (!strcasecmp((char *)pName, "timegenerated")) {
438 *pPropID = PROP_TIMEGENERATED;
439 } else if (!strcasecmp((char *)pName, "programname")) {
440 *pPropID = PROP_PROGRAMNAME;
441 } else if (!strcasecmp((char *)pName, "protocol-version")) {
442 *pPropID = PROP_PROTOCOL_VERSION;
443 } else if (!strcasecmp((char *)pName, "structured-data")) {
444 *pPropID = PROP_STRUCTURED_DATA;
445 } else if (!strcasecmp((char *)pName, "app-name")) {
446 *pPropID = PROP_APP_NAME;
447 } else if (!strcasecmp((char *)pName, "procid")) {
448 *pPropID = PROP_PROCID;
449 } else if (!strcasecmp((char *)pName, "msgid")) {
450 *pPropID = PROP_MSGID;
451 } else if (!strcasecmp((char *)pName, "jsonmesg")) {
452 *pPropID = PROP_JSONMESG;
453 } else if (!strcasecmp((char *)pName, "parsesuccess")) {
454 *pPropID = PROP_PARSESUCCESS;
455 #ifdef USE_LIBUUID
456 } else if (!strcasecmp((char *)pName, "uuid")) {
457 *pPropID = PROP_UUID;
458 #endif
459 /* here start system properties (those, that do not relate to the message itself */
460 } else if (!strcasecmp((char *)pName, "$NOW")) {
461 *pPropID = PROP_SYS_NOW;
462 } else if (!strcasecmp((char *)pName, "$YEAR")) {
463 *pPropID = PROP_SYS_YEAR;
464 } else if (!strcasecmp((char *)pName, "$MONTH")) {
465 *pPropID = PROP_SYS_MONTH;
466 } else if (!strcasecmp((char *)pName, "$DAY")) {
467 *pPropID = PROP_SYS_DAY;
468 } else if (!strcasecmp((char *)pName, "$HOUR")) {
469 *pPropID = PROP_SYS_HOUR;
470 } else if (!strcasecmp((char *)pName, "$HHOUR")) {
471 *pPropID = PROP_SYS_HHOUR;
472 } else if (!strcasecmp((char *)pName, "$QHOUR")) {
473 *pPropID = PROP_SYS_QHOUR;
474 } else if (!strcasecmp((char *)pName, "$MINUTE")) {
475 *pPropID = PROP_SYS_MINUTE;
476 } else if (!strcasecmp((char *)pName, "$WDAY")) {
477 *pPropID = PROP_SYS_WDAY;
478 } else if (!strcasecmp((char *)pName, "$now-utc")) {
479 *pPropID = PROP_SYS_NOW_UTC;
480 } else if (!strcasecmp((char *)pName, "$year-utc")) {
481 *pPropID = PROP_SYS_YEAR_UTC;
482 } else if (!strcasecmp((char *)pName, "$month-utc")) {
483 *pPropID = PROP_SYS_MONTH_UTC;
484 } else if (!strcasecmp((char *)pName, "$day-utc")) {
485 *pPropID = PROP_SYS_DAY_UTC;
486 } else if (!strcasecmp((char *)pName, "$hour-utc")) {
487 *pPropID = PROP_SYS_HOUR_UTC;
488 } else if (!strcasecmp((char *)pName, "$hhour-utc")) {
489 *pPropID = PROP_SYS_HHOUR_UTC;
490 } else if (!strcasecmp((char *)pName, "$qhour-utc")) {
491 *pPropID = PROP_SYS_QHOUR_UTC;
492 } else if (!strcasecmp((char *)pName, "$minute-utc")) {
493 *pPropID = PROP_SYS_MINUTE_UTC;
494 } else if (!strcasecmp((char *)pName, "$wday-utc")) {
495 *pPropID = PROP_SYS_WDAY_UTC;
496 } else if (!strcasecmp((char *)pName, "$now-unixtimestamp")) {
497 *pPropID = PROP_SYS_NOW_UXTIMESTAMP;
498 } else if (!strcasecmp((char *)pName, "$MYHOSTNAME")) {
499 *pPropID = PROP_SYS_MYHOSTNAME;
500 } else if (!strcasecmp((char *)pName, "$!all-json")) {
501 *pPropID = PROP_CEE_ALL_JSON;
502 } else if (!strcasecmp((char *)pName, "$!all-json-plain")) {
503 *pPropID = PROP_CEE_ALL_JSON_PLAIN;
504 } else if (!strcasecmp((char *)pName, "$BOM")) {
505 *pPropID = PROP_SYS_BOM;
506 } else if (!strcasecmp((char *)pName, "$UPTIME")) {
507 *pPropID = PROP_SYS_UPTIME;
508 } else if (!strncmp((char *)pName, "$!", 2) || pName[0] == '!') {
509 *pPropID = PROP_CEE;
510 } else if (!strncmp((char *)pName, "$.", 2) || pName[0] == '.') {
511 *pPropID = PROP_LOCAL_VAR;
512 } else if (!strncmp((char *)pName, "$/", 2) || pName[0] == '/') {
513 *pPropID = PROP_GLOBAL_VAR;
514 } else {
515 DBGPRINTF("PROP_INVALID for name '%s'\n", pName);
516 *pPropID = PROP_INVALID;
517 iRet = RS_RET_VAR_NOT_FOUND;
518 }
519
520 RETiRet;
521 }
522
523
524 /* map a property ID to a name string (useful for displaying) */
525 uchar *propIDToName(propid_t propID) {
526 switch (propID) {
527 case PROP_MSG:
528 return UCHAR_CONSTANT("msg");
529 case PROP_TIMESTAMP:
530 return UCHAR_CONSTANT("timestamp");
531 case PROP_HOSTNAME:
532 return UCHAR_CONSTANT("hostname");
533 case PROP_SYSLOGTAG:
534 return UCHAR_CONSTANT("syslogtag");
535 case PROP_RAWMSG:
536 return UCHAR_CONSTANT("rawmsg");
537 case PROP_RAWMSG_AFTER_PRI:
538 return UCHAR_CONSTANT("rawmsg-after-pri");
539 case PROP_INPUTNAME:
540 return UCHAR_CONSTANT("inputname");
541 case PROP_FROMHOST:
542 return UCHAR_CONSTANT("fromhost");
543 case PROP_FROMHOST_IP:
544 return UCHAR_CONSTANT("fromhost-ip");
545 case PROP_FROMHOST_PORT:
546 return UCHAR_CONSTANT("fromhost-port");
547 case PROP_PRI:
548 return UCHAR_CONSTANT("pri");
549 case PROP_PRI_TEXT:
550 return UCHAR_CONSTANT("pri-text");
551 case PROP_IUT:
552 return UCHAR_CONSTANT("iut");
553 case PROP_SYSLOGFACILITY:
554 return UCHAR_CONSTANT("syslogfacility");
555 case PROP_SYSLOGFACILITY_TEXT:
556 return UCHAR_CONSTANT("syslogfacility-text");
557 case PROP_SYSLOGSEVERITY:
558 return UCHAR_CONSTANT("syslogseverity");
559 case PROP_SYSLOGSEVERITY_TEXT:
560 return UCHAR_CONSTANT("syslogseverity-text");
561 case PROP_TIMEGENERATED:
562 return UCHAR_CONSTANT("timegenerated");
563 case PROP_PROGRAMNAME:
564 return UCHAR_CONSTANT("programname");
565 case PROP_PROTOCOL_VERSION:
566 return UCHAR_CONSTANT("protocol-version");
567 case PROP_STRUCTURED_DATA:
568 return UCHAR_CONSTANT("structured-data");
569 case PROP_APP_NAME:
570 return UCHAR_CONSTANT("app-name");
571 case PROP_PROCID:
572 return UCHAR_CONSTANT("procid");
573 case PROP_MSGID:
574 return UCHAR_CONSTANT("msgid");
575 case PROP_JSONMESG:
576 return UCHAR_CONSTANT("jsonmesg");
577 case PROP_PARSESUCCESS:
578 return UCHAR_CONSTANT("parsesuccess");
579 #ifdef USE_LIBUUID
580 case PROP_UUID:
581 return UCHAR_CONSTANT("uuid");
582 #endif
583 case PROP_SYS_NOW:
584 return UCHAR_CONSTANT("$NOW");
585 case PROP_SYS_YEAR:
586 return UCHAR_CONSTANT("$YEAR");
587 case PROP_SYS_MONTH:
588 return UCHAR_CONSTANT("$MONTH");
589 case PROP_SYS_DAY:
590 return UCHAR_CONSTANT("$DAY");
591 case PROP_SYS_HOUR:
592 return UCHAR_CONSTANT("$HOUR");
593 case PROP_SYS_HHOUR:
594 return UCHAR_CONSTANT("$HHOUR");
595 case PROP_SYS_QHOUR:
596 return UCHAR_CONSTANT("$QHOUR");
597 case PROP_SYS_MINUTE:
598 return UCHAR_CONSTANT("$MINUTE");
599 case PROP_SYS_NOW_UTC:
600 return UCHAR_CONSTANT("$NOW-UTC");
601 case PROP_SYS_YEAR_UTC:
602 return UCHAR_CONSTANT("$YEAR-UTC");
603 case PROP_SYS_MONTH_UTC:
604 return UCHAR_CONSTANT("$MONTH-UTC");
605 case PROP_SYS_DAY_UTC:
606 return UCHAR_CONSTANT("$DAY-UTC");
607 case PROP_SYS_HOUR_UTC:
608 return UCHAR_CONSTANT("$HOUR-UTC");
609 case PROP_SYS_HHOUR_UTC:
610 return UCHAR_CONSTANT("$HHOUR-UTC");
611 case PROP_SYS_QHOUR_UTC:
612 return UCHAR_CONSTANT("$QHOUR-UTC");
613 case PROP_SYS_MINUTE_UTC:
614 return UCHAR_CONSTANT("$MINUTE-UTC");
615 case PROP_SYS_WDAY:
616 return UCHAR_CONSTANT("$WDAY");
617 case PROP_SYS_WDAY_UTC:
618 return UCHAR_CONSTANT("$WDAY-UTC");
619 case PROP_SYS_NOW_UXTIMESTAMP:
620 return UCHAR_CONSTANT("$NOW-UNIXTIMESTAMP");
621 case PROP_SYS_MYHOSTNAME:
622 return UCHAR_CONSTANT("$MYHOSTNAME");
623 case PROP_CEE_ALL_JSON:
624 return UCHAR_CONSTANT("$!all-json");
625 case PROP_CEE_ALL_JSON_PLAIN:
626 return UCHAR_CONSTANT("$!all-json-plain");
627 case PROP_SYS_BOM:
628 return UCHAR_CONSTANT("$BOM");
629 case PROP_SYS_UPTIME:
630 return UCHAR_CONSTANT("$UPTIME");
631 case PROP_CEE:
632 return UCHAR_CONSTANT("*CEE-based property*");
633 case PROP_LOCAL_VAR:
634 return UCHAR_CONSTANT("*LOCAL_VARIABLE*");
635 case PROP_GLOBAL_VAR:
636 return UCHAR_CONSTANT("*GLOBAL_VARIABLE*");
637 default:
638 return UCHAR_CONSTANT("*invalid property id*");
639 }
640 }
641
642
643 /* This is common code for all Constructors. It is defined in an
644 * inline'able function so that we can save a function call in the
645 * actual constructors (otherwise, the msgConstruct would need
646 * to call msgConstructWithTime(), which would require a
647 * function call). Now, both can use this inline function. This
648 * enables us to be optimal, but still have the code just once.
649 * the new object or NULL if no such object could be allocated.
650 * An object constructed via this function should only be destroyed
651 * via "msgDestruct()". This constructor does not query system time
652 * itself but rather uses a user-supplied value. This enables the caller
653 * to do some tricks to save processing time (done, for example, in the
654 * udp input).
655 * NOTE: this constructor does NOT call calloc(), as we have many bytes
656 * inside the structure which do not need to be cleared. bzero() will
657 * heavily thrash the cache, so we do the init manually (which also
658 * is the right thing to do with pointers, as they are not neccessarily
659 * a binary 0 on all machines [but today almost always...]).
660 * rgerhards, 2008-10-06
661 */
662 static rsRetVal msgBaseConstruct(smsg_t **ppThis) {
663 DEFiRet;
664 smsg_t *pM;
665
666 assert(ppThis != NULL);
667 CHKmalloc(pM = malloc(sizeof(smsg_t)));
668 objConstructSetObjInfo(pM); /* initialize object helper entities */
669
670 /* initialize members in ORDER they appear in structure (think "cache line"!) */
671 pM->flowCtlType = 0;
672 pM->bParseSuccess = 0;
673 pM->iRefCount = 1;
674 pM->iSeverity = LOG_DEBUG;
675 pM->iFacility = LOG_INVLD;
676 pM->iLenPROGNAME = -1;
677 pM->offAfterPRI = 0;
678 pM->offMSG = -1;
679 pM->iProtocolVersion = 0;
680 pM->msgFlags = 0;
681 pM->iLenRawMsg = 0;
682 pM->iLenMSG = 0;
683 pM->iLenTAG = 0;
684 pM->iLenHOSTNAME = 0;
685 pM->pszRawMsg = NULL;
686 pM->pszHOSTNAME = NULL;
687 pM->pszRcvdAt3164 = NULL;
688 pM->pszRcvdAt3339 = NULL;
689 pM->pszRcvdAt_MySQL = NULL;
690 pM->pszRcvdAt_PgSQL = NULL;
691 pM->pszTIMESTAMP3164 = NULL;
692 pM->pszTIMESTAMP3339 = NULL;
693 pM->pszTIMESTAMP_MySQL = NULL;
694 pM->pszTIMESTAMP_PgSQL = NULL;
695 pM->pszStrucData = NULL;
696 pM->lenStrucData = 0;
697 pM->pCSAPPNAME = NULL;
698 pM->pCSPROCID = NULL;
699 pM->pCSMSGID = NULL;
700 pM->pInputName = NULL;
701 pM->pRcvFromIP = NULL;
702 pM->pRcvFromPort = NULL;
703 pM->rcvFrom.pRcvFrom = NULL;
704 pM->pRuleset = NULL;
705 pM->json = NULL;
706 pM->localvars = NULL;
707 pM->dfltTZ[0] = '\0';
708 memset(&pM->tRcvdAt, 0, sizeof(pM->tRcvdAt));
709 memset(&pM->tTIMESTAMP, 0, sizeof(pM->tTIMESTAMP));
710 pM->TAG.pszTAG = NULL;
711 pM->pszTimestamp3164[0] = '\0';
712 pM->pszTimestamp3339[0] = '\0';
713 pM->pszTIMESTAMP_SecFrac[0] = '\0';
714 pM->pszRcvdAt_SecFrac[0] = '\0';
715 pM->pszTIMESTAMP_Unix[0] = '\0';
716 pM->pszRcvdAt_Unix[0] = '\0';
717 pM->pszUUID = NULL;
718 pthread_mutex_init(&pM->mut, NULL);
719
720 #if DEV_DEBUG == 1
721 dbgprintf("msgConstruct\t0x%x, ref 1\n", (int)pM);
722 #endif
723
724 *ppThis = pM;
725
726 finalize_it:
727 RETiRet;
728 }
729
730
731 /* "Constructor" for a msg "object". Returns a pointer to
732 * the new object or NULL if no such object could be allocated.
733 * An object constructed via this function should only be destroyed
734 * via "msgDestruct()". This constructor does not query system time
735 * itself but rather uses a user-supplied value. This enables the caller
736 * to do some tricks to save processing time (done, for example, in the
737 * udp input).
738 * rgerhards, 2008-10-06
739 */
740 rsRetVal msgConstructWithTime(smsg_t **ppThis, const struct syslogTime *stTime, const time_t ttGenTime) {
741 DEFiRet;
742
743 CHKiRet(msgBaseConstruct(ppThis));
744 (*ppThis)->ttGenTime = ttGenTime;
745 memcpy(&(*ppThis)->tRcvdAt, stTime, sizeof(struct syslogTime));
746 memcpy(&(*ppThis)->tTIMESTAMP, stTime, sizeof(struct syslogTime));
747
748 finalize_it:
749 RETiRet;
750 }
751
752
753 /* "Constructor" for a msg "object". Returns a pointer to
754 * the new object or NULL if no such object could be allocated.
755 * An object constructed via this function should only be destroyed
756 * via "msgDestruct()". This constructor, for historical reasons,
757 * also sets the two timestamps to the current time.
758 */
759 rsRetVal msgConstruct(smsg_t **ppThis) {
760 DEFiRet;
761
762 CHKiRet(msgBaseConstruct(ppThis));
763 /* we initialize both timestamps to contain the current time, so that they
764 * are consistent. Also, this saves us from doing any further time calls just
765 * to obtain a timestamp. The memcpy() should not really make a difference,
766 * especially as I think there is no codepath currently where it would not be
767 * required (after I have cleaned up the pathes ;)). -- rgerhards, 2008-10-02
768 */
769 datetime.getCurrTime(&((*ppThis)->tRcvdAt), &((*ppThis)->ttGenTime), TIME_IN_LOCALTIME);
770 memcpy(&(*ppThis)->tTIMESTAMP, &(*ppThis)->tRcvdAt, sizeof(struct syslogTime));
771
772 finalize_it:
773 RETiRet;
774 }
775
776
777 /* Special msg constructor, to be used when an object is deserialized.
778 * we do only the base init as we know the properties will be set in
779 * any case by the deserializer. We still do the "inexpensive" inits
780 * just to be on the safe side. The whole process needs to be
781 * refactored together with the msg serialization subsystem.
782 */
783 rsRetVal msgConstructForDeserializer(smsg_t **ppThis) {
784 return msgBaseConstruct(ppThis);
785 }
786
787
788 /* some free handlers for (slightly) complicated cases... All of them may be called
789 * with an empty element.
790 */
791 static inline void freeTAG(smsg_t *pThis) {
792 if (pThis->iLenTAG >= CONF_TAG_BUFSIZE) free(pThis->TAG.pszTAG);
793 }
794 static inline void freeHOSTNAME(smsg_t *pThis) {
795 if (pThis->iLenHOSTNAME >= CONF_HOSTNAME_BUFSIZE) free(pThis->pszHOSTNAME);
796 }
797
798
799 rsRetVal msgDestruct(smsg_t **ppThis) {
800 DEFiRet;
801 smsg_t *pThis;
802 int currRefCount;
803 #ifdef HAVE_MALLOC_TRIM
804 int currCnt;
805 #endif
806 CODESTARTobjDestruct(msg);
807 #if DEV_DEBUG == 1
808 dbgprintf(
809 "msgDestruct\t0x%lx, "
810 "Ref now: %d\n",
811 (unsigned long)pThis, pThis->iRefCount - 1);
812 #endif
813 #ifdef HAVE_ATOMIC_BUILTINS
814 currRefCount = ATOMIC_DEC_AND_FETCH(&pThis->iRefCount, NULL);
815 #else
816 MsgLock(pThis);
817 currRefCount = --pThis->iRefCount;
818 #endif
819 if (currRefCount == 0) {
820 #if DEV_DEBUG == 1
821 dbgprintf("msgDestruct\t0x%lx, RefCount now 0, doing DESTROY\n", (unsigned long)pThis);
822 #endif
823 if (pThis->pszRawMsg != pThis->szRawMsg) free(pThis->pszRawMsg);
824 freeTAG(pThis);
825 freeHOSTNAME(pThis);
826 if (pThis->pInputName != NULL) prop.Destruct(&pThis->pInputName);
827 if ((pThis->msgFlags & NEEDS_DNSRESOL) == 0) {
828 if (pThis->rcvFrom.pRcvFrom != NULL) prop.Destruct(&pThis->rcvFrom.pRcvFrom);
829 } else {
830 free(pThis->rcvFrom.pfrominet);
831 }
832 if (pThis->pRcvFromIP != NULL) prop.Destruct(&pThis->pRcvFromIP);
833 if (pThis->pRcvFromPort != NULL) prop.Destruct(&pThis->pRcvFromPort);
834 free(pThis->pszRcvdAt3164);
835 free(pThis->pszRcvdAt3339);
836 free(pThis->pszRcvdAt_MySQL);
837 free(pThis->pszRcvdAt_PgSQL);
838 free(pThis->pszTIMESTAMP_MySQL);
839 free(pThis->pszTIMESTAMP_PgSQL);
840 free(pThis->pszStrucData);
841 if (pThis->iLenPROGNAME >= CONF_PROGNAME_BUFSIZE) free(pThis->PROGNAME.ptr);
842 if (pThis->pCSAPPNAME != NULL) rsCStrDestruct(&pThis->pCSAPPNAME);
843 if (pThis->pCSPROCID != NULL) rsCStrDestruct(&pThis->pCSPROCID);
844 if (pThis->pCSMSGID != NULL) rsCStrDestruct(&pThis->pCSMSGID);
845 if (pThis->json != NULL) json_object_put(pThis->json);
846 if (pThis->localvars != NULL) json_object_put(pThis->localvars);
847 if (pThis->pszUUID != NULL) free(pThis->pszUUID);
848 #ifndef HAVE_ATOMIC_BUILTINS
849 MsgUnlock(pThis);
850 #endif
851 pthread_mutex_destroy(&pThis->mut);
852 /* now we need to do our own optimization. Testing has shown that at least the glibc
853 * malloc() subsystem returns memory to the OS far too late in our case. So we need
854 * to help it a bit, by calling malloc_trim(), which will tell the alloc subsystem
855 * to consolidate and return to the OS. We keep 128K for our use, as a safeguard
856 * to too-frequent reallocs. But more importantly, we call this hook only every
857 * 100,000 messages (which is an approximation, as we do not work with atomic
858 * operations on the counter. --- rgerhards, 2009-06-22.
859 */
860 #ifdef HAVE_MALLOC_TRIM
861 { /* standard C requires a new block for a new variable definition!
862 * To simplify matters, we use modulo arithmetic and live with the fact
863 * that we trim too often when the counter wraps.
864 */
865 static unsigned iTrimCtr = 1;
866 currCnt = ATOMIC_INC_AND_FETCH_unsigned(&iTrimCtr, &mutTrimCtr);
867 if (currCnt % 100000 == 0) {
868 malloc_trim(128 * 1024);
869 }
870 }
871 #endif
872 } else {
873 #ifndef HAVE_ATOMIC_BUILTINS
874 MsgUnlock(pThis);
875 #endif
876 pThis = NULL; /* tell framework not to destructing the object! */
877 }
878 ENDobjDestruct
879 (msg)
880 /* The macros below are used in MsgDup(). I use macros
881 * to keep the fuction code somewhat more readyble. It is my
882 * replacement for inline functions in CPP
883 */
884 #define tmpCOPYSZ(name) \
885 if (pOld->psz##name != NULL) { \
886 if ((pNew->psz##name = srUtilStrDup(pOld->psz##name, pOld->iLen##name)) == NULL) { \
887 msgDestruct(&pNew); \
888 return NULL; \
889 } \
890 pNew->iLen##name = pOld->iLen##name; \
891 }
892
893 /* copy the CStr objects.
894 * if the old value is NULL, we do not need to do anything because we
895 * initialized the new value to NULL via calloc().
896 */
897 #define tmpCOPYCSTR(name) \
898 if (pOld->pCS##name != NULL) { \
899 if (rsCStrConstructFromCStr(&(pNew->pCS##name), pOld->pCS##name) != RS_RET_OK) { \
900 msgDestruct(&pNew); \
901 return NULL; \
902 } \
903 cstrFinalize(pNew->pCS##name); \
904 }
905
906 /* Constructs a message object by duplicating another one.
907 * Returns NULL if duplication failed. We do not need to lock the
908 * message object here, because a fully-created msg object is never
909 * allowed to be manipulated. For this, MsgDup() must be used, so MsgDup()
910 * can never run into a situation where the message object is being
911 * modified while its content is copied - it's forbidden by definition.
912 * rgerhards, 2007-07-10
913 */
914 smsg_t *MsgDup(smsg_t *pOld) {
915 smsg_t *pNew;
916 rsRetVal localRet;
917
918 assert(pOld != NULL);
919
920 if (msgConstructWithTime(&pNew, &pOld->tTIMESTAMP, pOld->ttGenTime) != RS_RET_OK) {
921 return NULL;
922 }
923
924 /* now copy the message properties */
925 pNew->iRefCount = 1;
926 pNew->iSeverity = pOld->iSeverity;
927 pNew->iFacility = pOld->iFacility;
928 pNew->msgFlags = pOld->msgFlags;
929 pNew->iProtocolVersion = pOld->iProtocolVersion;
930 pNew->tRcvdAt = pOld->tRcvdAt;
931 pNew->offMSG = pOld->offMSG;
932 pNew->iLenRawMsg = pOld->iLenRawMsg;
933 pNew->iLenMSG = pOld->iLenMSG;
934 pNew->iLenTAG = pOld->iLenTAG;
935 pNew->iLenHOSTNAME = pOld->iLenHOSTNAME;
936 if ((pOld->msgFlags & NEEDS_DNSRESOL)) {
937 localRet = msgSetFromSockinfo(pNew, pOld->rcvFrom.pfrominet);
938 if (localRet != RS_RET_OK) {
939 /* if something fails, we accept loss of this property, it is
940 * better than losing the whole message.
941 */
942 pNew->msgFlags &= ~NEEDS_DNSRESOL;
943 pNew->rcvFrom.pRcvFrom = NULL; /* make sure no dangling values */
944 }
945 } else {
946 if (pOld->rcvFrom.pRcvFrom != NULL) {
947 pNew->rcvFrom.pRcvFrom = pOld->rcvFrom.pRcvFrom;
948 prop.AddRef(pNew->rcvFrom.pRcvFrom);
949 }
950 }
951 if (pOld->pRcvFromIP != NULL) {
952 pNew->pRcvFromIP = pOld->pRcvFromIP;
953 prop.AddRef(pNew->pRcvFromIP);
954 }
955 if (pOld->pRcvFromPort != NULL) {
956 pNew->pRcvFromPort = pOld->pRcvFromPort;
957 prop.AddRef(pNew->pRcvFromPort);
958 }
959 if (pOld->pInputName != NULL) {
960 pNew->pInputName = pOld->pInputName;
961 prop.AddRef(pNew->pInputName);
962 }
963 if (pOld->iLenTAG > 0) {
964 if (pOld->iLenTAG < CONF_TAG_BUFSIZE) {
965 memcpy(pNew->TAG.szBuf, pOld->TAG.szBuf, pOld->iLenTAG + 1);
966 } else {
967 if ((pNew->TAG.pszTAG = srUtilStrDup(pOld->TAG.pszTAG, pOld->iLenTAG)) == NULL) {
968 msgDestruct(&pNew);
969 return NULL;
970 }
971 pNew->iLenTAG = pOld->iLenTAG;
972 }
973 }
974 if (pOld->pszRawMsg == pOld->szRawMsg) {
975 memcpy(pNew->szRawMsg, pOld->szRawMsg, pOld->iLenRawMsg + 1);
976 pNew->pszRawMsg = pNew->szRawMsg;
977 } else {
978 tmpCOPYSZ(RawMsg);
979 }
980 if (pOld->pszHOSTNAME == NULL) {
981 pNew->pszHOSTNAME = NULL;
982 } else {
983 if (pOld->iLenHOSTNAME < CONF_HOSTNAME_BUFSIZE) {
984 memcpy(pNew->szHOSTNAME, pOld->szHOSTNAME, pOld->iLenHOSTNAME + 1);
985 pNew->pszHOSTNAME = pNew->szHOSTNAME;
986 } else {
987 tmpCOPYSZ(HOSTNAME);
988 }
989 }
990 if (pOld->pszStrucData == NULL) {
991 pNew->pszStrucData = NULL;
992 } else {
993 pNew->pszStrucData = (uchar *)strdup((char *)pOld->pszStrucData);
994 pNew->lenStrucData = pOld->lenStrucData;
995 }
996
997 tmpCOPYCSTR(APPNAME);
998 tmpCOPYCSTR(PROCID);
999 tmpCOPYCSTR(MSGID);
1000
1001 if (pOld->json != NULL) pNew->json = jsonDeepCopy(pOld->json);
1002 if (pOld->localvars != NULL) pNew->localvars = jsonDeepCopy(pOld->localvars);
1003
1004 /* we do not copy all other cache properties, as we do not even know
1005 * if they are needed once again. So we let them re-create if needed.
1006 */
1007
1008 return pNew;
1009 }
1010 #undef tmpCOPYSZ
1011 #undef tmpCOPYCSTR
1012
1013 /* Return a textual representation of @json.
1014 *
1015 * The pointer is owned by @json; do NOT free it.
1016 * To keep the string beyond the next mutation, serialization call,
1017 * or destruction of @json, make a copy (e.g., strdup()).
1018 */
1019 static const char *jsonToString(struct json_object *const json) {
1020 if (!json) {
1021 return NULL;
1022 }
1023
1024 if (json_object_get_type(json) == json_type_string) {
1025 /* Direct pointer to internal string storage.
1026 * - Stable across repeated json_object_get_string() calls.
1027 * - Invalidated once the object is modified or fjson_object_put().
1028 */
1029 return json_object_get_string(json);
1030 }
1031
1032 /* Non-string types serialize into json->_pb.
1033 * - json->_pb is reset/overwritten on every serialization or mutation.
1034 * - The returned pointer becomes invalid immediately after that.
1035 */
1036 return json_object_to_json_string_ext(json, glblJsonFormatOpt);
1037 }
1038
1039 /* This method serializes a message object. That means the whole
1040 * object is modified into text form. That text form is suitable for
1041 * later reconstruction of the object by calling MsgDeSerialize().
1042 * The most common use case for this method is the creation of an
1043 * on-disk representation of the message object.
1044 * We do not serialize the cache properties. We re-create them when needed.
1045 * This saves us a lot of memory. Performance is no concern, as serializing
1046 * is a so slow operation that recration of the caches does not count. Also,
1047 * we do not serialize --currently none--, as this is only a helper variable
1048 * during msg construction - and never again used later.
1049 * rgerhards, 2008-01-03
1050 */
1051 static rsRetVal MsgSerialize(smsg_t *pThis, strm_t *pStrm) {
1052 uchar *psz;
1053 int len;
1054 DEFiRet;
1055
1056 assert(pThis != NULL);
1057 assert(pStrm != NULL);
1058
1059 /* then serialize elements */
1060 CHKiRet(obj.BeginSerialize(pStrm, (obj_t *)pThis));
1061 objSerializeSCALAR(pStrm, iProtocolVersion, SHORT);
1062 objSerializeSCALAR(pStrm, iSeverity, SHORT);
1063 objSerializeSCALAR(pStrm, iFacility, SHORT);
1064 objSerializeSCALAR(pStrm, msgFlags, INT);
1065 objSerializeSCALAR(pStrm, ttGenTime, INT);
1066 objSerializeSCALAR(pStrm, tRcvdAt, SYSLOGTIME);
1067 objSerializeSCALAR(pStrm, tTIMESTAMP, SYSLOGTIME);
1068
1069 CHKiRet(obj.SerializeProp(pStrm, UCHAR_CONSTANT("pszTAG"), PROPTYPE_PSZ,
1070 (void *)((pThis->iLenTAG < CONF_TAG_BUFSIZE) ? pThis->TAG.szBuf : pThis->TAG.pszTAG)));
1071
1072 objSerializePTR(pStrm, pszRawMsg, PSZ);
1073 objSerializePTR(pStrm, pszHOSTNAME, PSZ);
1074 getInputName(pThis, &psz, &len);
1075 CHKiRet(obj.SerializeProp(pStrm, UCHAR_CONSTANT("pszInputName"), PROPTYPE_PSZ, (void *)psz));
1076 psz = getRcvFrom(pThis);
1077 CHKiRet(obj.SerializeProp(pStrm, UCHAR_CONSTANT("pszRcvFrom"), PROPTYPE_PSZ, (void *)psz));
1078 psz = getRcvFromIP(pThis);
1079 CHKiRet(obj.SerializeProp(pStrm, UCHAR_CONSTANT("pszRcvFromIP"), PROPTYPE_PSZ, (void *)psz));
1080 psz = pThis->pszStrucData;
1081 CHKiRet(obj.SerializeProp(pStrm, UCHAR_CONSTANT("pszStrucData"), PROPTYPE_PSZ, (void *)psz));
1082 if (pThis->json != NULL) {
1083 MsgLock(pThis);
1084 psz = (uchar *)jsonToString(pThis->json);
1085 MsgUnlock(pThis);
1086 CHKiRet(obj.SerializeProp(pStrm, UCHAR_CONSTANT("json"), PROPTYPE_PSZ, (void *)psz));
1087 }
1088 if (pThis->localvars != NULL) {
1089 MsgLock(pThis);
1090 psz = (uchar *)jsonToString(pThis->localvars);
1091 MsgUnlock(pThis);
1092 CHKiRet(obj.SerializeProp(pStrm, UCHAR_CONSTANT("localvars"), PROPTYPE_PSZ, (void *)psz));
1093 }
1094
1095 objSerializePTR(pStrm, pCSAPPNAME, CSTR);
1096 objSerializePTR(pStrm, pCSPROCID, CSTR);
1097 objSerializePTR(pStrm, pCSMSGID, CSTR);
1098
1099 objSerializePTR(pStrm, pszUUID, PSZ);
1100
1101 if (pThis->pRuleset != NULL) {
1102 CHKiRet(obj.SerializeProp(pStrm, UCHAR_CONSTANT("pszRuleset"), PROPTYPE_PSZ, rulesetGetName(pThis->pRuleset)));
1103 }
1104
1105 /* offset must be serialized after pszRawMsg, because we need that to obtain the correct
1106 * MSG size.
1107 */
1108 objSerializeSCALAR(pStrm, offMSG, INT);
1109
1110 CHKiRet(obj.EndSerialize(pStrm));
1111
1112 finalize_it:
1113 RETiRet;
1114 }
1115
1116
1117 /* This is a helper for MsgDeserialize that re-inits the var object. This
1118 * whole construct should be replaced, var is really ready to be retired.
1119 * But as an interim help during refactoring let's introduce this function
1120 * here (and thus NOT as method of var object!). -- rgerhads, 2012-11-06
1121 */
1122 static void reinitVar(var_t *pVar) {
1123 rsCStrDestruct(&pVar->pcsName); /* no longer needed */
1124 if (pVar->varType == VARTYPE_STR) {
1125 rsCStrDestruct(&pVar->val.pStr);
1126 }
1127 memset(&pVar->val, 0, sizeof(pVar->val));
1128 pVar->varType = VARTYPE_NONE;
1129 }
1130 /* deserialize the message again
1131 * we deserialize the properties in the same order that we serialized them. Except
1132 * for some checks to cover downlevel version, we do not need to do all these
1133 * CPU intense name checkings.
1134 */
1135 #define isProp(name) !rsCStrSzStrCmp(pVar->pcsName, (uchar *)name, sizeof(name) - 1)
1136 rsRetVal MsgDeserialize(smsg_t *const pMsg, strm_t *pStrm) {
1137 prop_t *myProp;
1138 prop_t *propRcvFrom = NULL;
1139 prop_t *propRcvFromIP = NULL;
1140 struct json_tokener *tokener;
1141 var_t *pVar = NULL;
1142 DEFiRet;
1143
1144 ISOBJ_TYPE_assert(pStrm, strm);
1145
1146 CHKiRet(var.Construct(&pVar));
1147 CHKiRet(var.ConstructFinalize(pVar));
1148
1149 CHKiRet(objDeserializeProperty(pVar, pStrm));
1150 if (isProp("iProtocolVersion")) {
1151 setProtocolVersion(pMsg, pVar->val.num);
1152 reinitVar(pVar);
1153 CHKiRet(objDeserializeProperty(pVar, pStrm));
1154 }
1155 if (isProp("iSeverity")) {
1156 pMsg->iSeverity = pVar->val.num;
1157 reinitVar(pVar);
1158 CHKiRet(objDeserializeProperty(pVar, pStrm));
1159 }
1160 if (isProp("iFacility")) {
1161 pMsg->iFacility = pVar->val.num;
1162 reinitVar(pVar);
1163 CHKiRet(objDeserializeProperty(pVar, pStrm));
1164 }
1165 if (isProp("msgFlags")) {
1166 pMsg->msgFlags = pVar->val.num;
1167 reinitVar(pVar);
1168 CHKiRet(objDeserializeProperty(pVar, pStrm));
1169 }
1170 if (isProp("ttGenTime")) {
1171 pMsg->ttGenTime = pVar->val.num;
1172 reinitVar(pVar);
1173 CHKiRet(objDeserializeProperty(pVar, pStrm));
1174 }
1175 if (isProp("tRcvdAt")) {
1176 memcpy(&pMsg->tRcvdAt, &pVar->val.vSyslogTime, sizeof(struct syslogTime));
1177 reinitVar(pVar);
1178 CHKiRet(objDeserializeProperty(pVar, pStrm));
1179 }
1180 if (isProp("tTIMESTAMP")) {
1181 memcpy(&pMsg->tTIMESTAMP, &pVar->val.vSyslogTime, sizeof(struct syslogTime));
1182 reinitVar(pVar);
1183 CHKiRet(objDeserializeProperty(pVar, pStrm));
1184 }
1185 if (isProp("pszTAG")) {
1186 MsgSetTAG(pMsg, rsCStrGetSzStrNoNULL(pVar->val.pStr), cstrLen(pVar->val.pStr));
1187 reinitVar(pVar);
1188 CHKiRet(objDeserializeProperty(pVar, pStrm));
1189 }
1190 if (isProp("pszRawMsg")) {
1191 MsgSetRawMsg(pMsg, (char *)rsCStrGetSzStrNoNULL(pVar->val.pStr), cstrLen(pVar->val.pStr));
1192 reinitVar(pVar);
1193 CHKiRet(objDeserializeProperty(pVar, pStrm));
1194 }
1195 if (isProp("pszHOSTNAME")) {
1196 MsgSetHOSTNAME(pMsg, rsCStrGetSzStrNoNULL(pVar->val.pStr), rsCStrLen(pVar->val.pStr));
1197 reinitVar(pVar);
1198 CHKiRet(objDeserializeProperty(pVar, pStrm));
1199 }
1200 if (isProp("pszInputName")) {
1201 /* we need to create a property */
1202 CHKiRet(prop.Construct(&myProp));
1203 CHKiRet(prop.SetString(myProp, rsCStrGetSzStrNoNULL(pVar->val.pStr), rsCStrLen(pVar->val.pStr)));
1204 CHKiRet(prop.ConstructFinalize(myProp));
1205 MsgSetInputName(pMsg, myProp);
1206 prop.Destruct(&myProp);
1207 reinitVar(pVar);
1208 CHKiRet(objDeserializeProperty(pVar, pStrm));
1209 }
1210 if (isProp("pszRcvFrom")) {
1211 MsgSetRcvFromStr(pMsg, rsCStrGetSzStrNoNULL(pVar->val.pStr), rsCStrLen(pVar->val.pStr), &propRcvFrom);
1212 prop.Destruct(&propRcvFrom);
1213 reinitVar(pVar);
1214 CHKiRet(objDeserializeProperty(pVar, pStrm));
1215 }
1216 if (isProp("pszRcvFromIP")) {
1217 MsgSetRcvFromIPStr(pMsg, rsCStrGetSzStrNoNULL(pVar->val.pStr), rsCStrLen(pVar->val.pStr), &propRcvFromIP);
1218 prop.Destruct(&propRcvFromIP);
1219 reinitVar(pVar);
1220 CHKiRet(objDeserializeProperty(pVar, pStrm));
1221 }
1222 if (isProp("pszStrucData")) {
1223 MsgSetStructuredData(pMsg, (char *)rsCStrGetSzStrNoNULL(pVar->val.pStr));
1224 reinitVar(pVar);
1225 CHKiRet(objDeserializeProperty(pVar, pStrm));
1226 }
1227 if (isProp("json")) {
1228 tokener = json_tokener_new();
1229 pMsg->json =
1230 json_tokener_parse_ex(tokener, (char *)rsCStrGetSzStrNoNULL(pVar->val.pStr), cstrLen(pVar->val.pStr));
1231 json_tokener_free(tokener);
1232 reinitVar(pVar);
1233 CHKiRet(objDeserializeProperty(pVar, pStrm));
1234 }
1235 if (isProp("localvars")) {
1236 tokener = json_tokener_new();
1237 pMsg->localvars =
1238 json_tokener_parse_ex(tokener, (char *)rsCStrGetSzStrNoNULL(pVar->val.pStr), cstrLen(pVar->val.pStr));
1239 json_tokener_free(tokener);
1240 reinitVar(pVar);
1241 CHKiRet(objDeserializeProperty(pVar, pStrm));
1242 }
1243 if (isProp("pCSAPPNAME")) {
1244 MsgSetAPPNAME(pMsg, (char *)rsCStrGetSzStrNoNULL(pVar->val.pStr));
1245 reinitVar(pVar);
1246 CHKiRet(objDeserializeProperty(pVar, pStrm));
1247 }
1248 if (isProp("pCSPROCID")) {
1249 MsgSetPROCID(pMsg, (char *)rsCStrGetSzStrNoNULL(pVar->val.pStr));
1250 reinitVar(pVar);
1251 CHKiRet(objDeserializeProperty(pVar, pStrm));
1252 }
1253 if (isProp("pCSMSGID")) {
1254 MsgSetMSGID(pMsg, (char *)rsCStrGetSzStrNoNULL(pVar->val.pStr));
1255 reinitVar(pVar);
1256 CHKiRet(objDeserializeProperty(pVar, pStrm));
1257 }
1258 if (isProp("pszUUID")) {
1259 pMsg->pszUUID = ustrdup(rsCStrGetSzStrNoNULL(pVar->val.pStr));
1260 reinitVar(pVar);
1261 CHKiRet(objDeserializeProperty(pVar, pStrm));
1262 }
1263 if (isProp("pszRuleset")) {
1264 MsgSetRulesetByName(pMsg, pVar->val.pStr);
1265 reinitVar(pVar);
1266 CHKiRet(objDeserializeProperty(pVar, pStrm));
1267 }
1268 /* "offMSG" must always be our last field, so we use this as an
1269 * indicator if the sequence is correct. This is a bit questionable,
1270 * but on the other hand it works decently AND we will probably replace
1271 * the whole persisted format soon in any case. -- rgerhards, 2012-11-06
1272 */
1273 if (!isProp("offMSG")) {
1274 DBGPRINTF("error property: %s\n", rsCStrGetSzStrNoNULL(pVar->pcsName));
1275 ABORT_FINALIZE(RS_RET_DS_PROP_SEQ_ERR);
1276 }
1277 MsgSetMSGoffs(pMsg, pVar->val.num);
1278 finalize_it:
1279 if (pVar != NULL) var.Destruct(&pVar);
1280 if (Debug && iRet != RS_RET_OK) {
1281 dbgprintf("MsgDeserialize error %d\n", iRet);
1282 }
1283 RETiRet;
1284 }
1285 #undef isProp
1286
1287
1288 /* Increment reference count - see description of the "msg"
1289 * structure for details. As a convenience to developers,
1290 * this method returns the msg pointer that is passed to it.
1291 * It is recommended that it is called as follows:
1292 *
1293 * pSecondMsgPointer = MsgAddRef(pOrgMsgPointer);
1294 */
1295 smsg_t *MsgAddRef(smsg_t *const pM) {
1296 assert(pM != NULL);
1297 #ifdef HAVE_ATOMIC_BUILTINS
1298 ATOMIC_INC(&pM->iRefCount, NULL);
1299 #else
1300 MsgLock(pM);
1301 pM->iRefCount++;
1302 MsgUnlock(pM);
1303 #endif
1304 #if DEV_DEBUG == 1
1305 dbgprintf("MsgAddRef\t0x%x done, Ref now: %d\n", (int)pM, pM->iRefCount);
1306 #endif
1307 return (pM);
1308 }
1309
1310
1311 /* This functions tries to acquire the PROCID from TAG. Its primary use is
1312 * when a legacy syslog message has been received and should be forwarded as
1313 * syslog-protocol (or the PROCID is requested for any other reason).
1314 * In legacy syslog, the PROCID is considered to be the character sequence
1315 * between the first [ and the first ]. This usually are digits only, but we
1316 * do not check that. However, if there is no closing ], we do not assume we
1317 * can obtain a PROCID. Take in mind that not every legacy syslog message
1318 * actually has a PROCID.
1319 * rgerhards, 2005-11-24
1320 * THIS MUST be called with the message lock locked.
1321 */
1322 static rsRetVal acquirePROCIDFromTAG(smsg_t *const pM) {
1323 register int i;
1324 uchar *pszTag;
1325 DEFiRet;
1326
1327 assert(pM != NULL);
1328
1329 if (pM->pCSPROCID != NULL) return RS_RET_OK; /* we are already done ;) */
1330
1331 if (msgGetProtocolVersion(pM) != 0) return RS_RET_OK; /* we can only emulate if we have legacy format */
1332
1333 pszTag = (uchar *)((pM->iLenTAG < CONF_TAG_BUFSIZE) ? pM->TAG.szBuf : pM->TAG.pszTAG);
1334
1335 /* find first '['... */
1336 i = 0;
1337 while ((i < pM->iLenTAG) && (pszTag[i] != '[')) ++i;
1338 if (!(i < pM->iLenTAG)) return RS_RET_OK; /* no [, so can not emulate... */
1339
1340 ++i; /* skip '[' */
1341
1342 /* now obtain the PROCID string... */
1343 CHKiRet(cstrConstruct(&pM->pCSPROCID));
1344 while ((i < pM->iLenTAG) && (pszTag[i] != ']')) {
1345 CHKiRet(cstrAppendChar(pM->pCSPROCID, pszTag[i]));
1346 ++i;
1347 }
1348
1349 if (!(i < pM->iLenTAG)) {
1350 /* oops... it looked like we had a PROCID, but now it has
1351 * turned out this is not true. In this case, we need to free
1352 * the buffer and simply return. Note that this is NOT an error
1353 * case!
1354 */
1355 cstrDestruct(&pM->pCSPROCID);
1356 FINALIZE;
1357 }
1358
1359 /* OK, finally we could obtain a PROCID. So let's use it ;) */
1360 cstrFinalize(pM->pCSPROCID);
1361
1362 finalize_it:
1363 RETiRet;
1364 }
1365
1366
1367 /* Parse and set the "programname" for a given MSG object. Programname
1368 * is a BSD concept, it is the tag without any instance-specific information.
1369 * Precisely, the programname is terminated by either (whichever occurs first):
1370 * - end of tag
1371 * - nonprintable character
1372 * - ':'
1373 * - '['
1374 * - '/'
1375 * The above definition has been taken from the FreeBSD syslogd sources.
1376 *
1377 * The program name is not parsed by default, because it is infrequently-used.
1378 * IMPORTANT: A locked message object must be provided, else a crash will occur.
1379 * rgerhards, 2005-10-19
1380 */
1381 static rsRetVal acquireProgramName(smsg_t *const pM) {
1382 int i;
1383 uchar *pszTag, *pszProgName;
1384 DEFiRet;
1385
1386 assert(pM != NULL);
1387 pszTag = (uchar *)((pM->iLenTAG < CONF_TAG_BUFSIZE) ? pM->TAG.szBuf : pM->TAG.pszTAG);
1388 for (i = 0; (i < pM->iLenTAG) && isprint((int)pszTag[i]) && (pszTag[i] != '\0') && (pszTag[i] != ':') &&
1389 (pszTag[i] != '[') && (runConf->globals.parser.bPermitSlashInProgramname || (pszTag[i] != '/'));
1390 ++i); /* just search end of PROGNAME */
1391 if (i < CONF_PROGNAME_BUFSIZE) {
1392 pszProgName = pM->PROGNAME.szBuf;
1393 } else {
1394 CHKmalloc(pM->PROGNAME.ptr = malloc(i + 1));
1395 pszProgName = pM->PROGNAME.ptr;
1396 }
1397 memcpy((char *)pszProgName, (char *)pszTag, i);
1398 pszProgName[i] = '\0';
1399 pM->iLenPROGNAME = i;
1400 finalize_it:
1401 RETiRet;
1402 }
1403
1404
1405 /* Access methods - dumb & easy, not a comment for each ;)
1406 */
1407 void setProtocolVersion(smsg_t *const pM, int iNewVersion) {
1408 assert(pM != NULL);
1409 if (iNewVersion != 0 && iNewVersion != 1) {
1410 dbgprintf("Tried to set unsupported protocol version %d - changed to 0.\n", iNewVersion);
1411 iNewVersion = 0;
1412 }
1413 pM->iProtocolVersion = iNewVersion;
1414 }
1415
1416 /* note: string is taken from constant pool, do NOT free */
1417 static const char *getProtocolVersionString(smsg_t *const pM) {
1418 assert(pM != NULL);
1419 return (pM->iProtocolVersion ? "1" : "0");
1420 }
1421
1422 void msgSetPRI(smsg_t *const __restrict__ pMsg, syslog_pri_t pri) {
1423 if (pri > LOG_MAXPRI) pri = LOG_PRI_INVLD;
1424 pMsg->iFacility = pri2fac(pri), pMsg->iSeverity = pri2sev(pri);
1425 }
1426
1427 #ifdef USE_LIBUUID
1428 /* note: libuuid seems not to be thread-safe, so we need
1429 * to get some safeguards in place.
1430 */
1431 static pthread_mutex_t mutUUID = PTHREAD_MUTEX_INITIALIZER;
1432
1433 static void call_uuid_generate(uuid_t uuid) {
1434 pthread_mutex_lock(&mutUUID);
1435 pthread_cleanup_push(mutexCancelCleanup, &mutUUID);
1436 uuid_generate(uuid);
1437 pthread_cleanup_pop(1);
1438 }
1439
1440 static void msgSetUUID(smsg_t *const pM) {
1441 size_t lenRes = sizeof(uuid_t) * 2 + 1;
1442 char hex_char[] = "0123456789ABCDEF";
1443 unsigned int byte_nbr;
1444 uuid_t uuid;
1445
1446 dbgprintf("[MsgSetUUID] START, lenRes %llu\n", (long long unsigned)lenRes);
1447 assert(pM != NULL);
1448
1449 if ((pM->pszUUID = (uchar *)malloc(lenRes)) == NULL) {
1450 pM->pszUUID = (uchar *)"";
1451 } else {
1452 call_uuid_generate(uuid);
1453 for (byte_nbr = 0; byte_nbr < sizeof(uuid_t); byte_nbr++) {
1454 pM->pszUUID[byte_nbr * 2 + 0] = hex_char[uuid[byte_nbr] >> 4];
1455 pM->pszUUID[byte_nbr * 2 + 1] = hex_char[uuid[byte_nbr] & 15];
1456 }
1457
1458 pM->pszUUID[lenRes - 1] = '\0';
1459 dbgprintf("[MsgSetUUID] UUID : %s LEN: %d \n", pM->pszUUID, (int)lenRes);
1460 }
1461 dbgprintf("[MsgSetUUID] END\n");
1462 }
1463
1464 static void getUUID(smsg_t *const pM, uchar **pBuf, int *piLen) {
1465 dbgprintf("[getUUID] START\n");
1466 if (pM == NULL) {
1467 dbgprintf("[getUUID] pM is NULL\n");
1468 *pBuf = UCHAR_CONSTANT("");
1469 *piLen = 0;
1470 } else {
1471 if (pM->pszUUID == NULL) {
1472 dbgprintf("[getUUID] pM->pszUUID is NULL\n");
1473 MsgLock(pM);
1474 /* re-query, things may have changed in the mean time... */
1475 if (pM->pszUUID == NULL) msgSetUUID(pM);
1476 MsgUnlock(pM);
1477 } else { /* UUID already there we reuse it */
1478 dbgprintf("[getUUID] pM->pszUUID already exists\n");
1479 }
1480 *pBuf = pM->pszUUID;
1481 *piLen = sizeof(uuid_t) * 2;
1482 }
1483 dbgprintf("[getUUID] END\n");
1484 }
1485 #endif
1486
1487 int ATTR_NONNULL() getRawMsgLen(const smsg_t *const pMsg) {
1488 return (pMsg->pszRawMsg == NULL) ? 0 : pMsg->iLenRawMsg;
1489 }
1490
1491 void getRawMsg(const smsg_t *const pM, uchar **pBuf, int *piLen) {
1492 if (pM == NULL) {
1493 *pBuf = UCHAR_CONSTANT("");
1494 *piLen = 0;
1495 } else {
1496 if (pM->pszRawMsg == NULL) {
1497 *pBuf = UCHAR_CONSTANT("");
1498 *piLen = 0;
1499 } else {
1500 *pBuf = pM->pszRawMsg;
1501 *piLen = pM->iLenRawMsg;
1502 }
1503 }
1504 }
1505
1506 void getRawMsgAfterPRI(smsg_t *const pM, uchar **pBuf, int *piLen) {
1507 if (pM == NULL) {
1508 *pBuf = UCHAR_CONSTANT("");
1509 *piLen = 0;
1510 } else {
1511 if (pM->pszRawMsg == NULL) {
1512 *pBuf = UCHAR_CONSTANT("");
1513 *piLen = 0;
1514 } else {
1515 /* unfortunately, pM->offAfterPRI seems NOT to be
1516 * correct/consistent in all cases. imuxsock and imudp
1517 * seem to have other values than imptcp. Testbench
1518 * covers some of that. As a work-around, we caluculate
1519 * the value ourselfes here. -- rgerhards, 2015-10-09
1520 */
1521 size_t offAfterPRI = 0;
1522 if (pM->pszRawMsg[0] == '<') { /* do we have a PRI? */
1523 if (pM->pszRawMsg[2] == '>')
1524 offAfterPRI = 3;
1525 else if (pM->pszRawMsg[3] == '>')
1526 offAfterPRI = 4;
1527 else if (pM->pszRawMsg[4] == '>')
1528 offAfterPRI = 5;
1529 }
1530 *pBuf = pM->pszRawMsg + offAfterPRI;
1531 *piLen = pM->iLenRawMsg - offAfterPRI;
1532 }
1533 }
1534 }
1535
1536
1537 /* note: setMSGLen() is only for friends who really know what they
1538 * do. Setting an invalid length can be desasterous!
1539 */
1540 void setMSGLen(smsg_t *const pM, int lenMsg) {
1541 pM->iLenMSG = lenMsg;
1542 }
1543
1544 int getMSGLen(smsg_t *const pM) {
1545 return ((pM == NULL) ? 0 : pM->iLenMSG);
1546 }
1547
1548 uchar *getMSG(smsg_t *const pM) {
1549 uchar *ret;
1550 if (pM == NULL)
1551 ret = UCHAR_CONSTANT("");
1552 else {
1553 if (pM->iLenMSG == 0)
1554 ret = UCHAR_CONSTANT("");
1555 else
1556 ret = pM->pszRawMsg + pM->offMSG;
1557 }
1558 return ret;
1559 }
1560
1561
1562 /* Get PRI value as integer */
1563 int getPRIi(const smsg_t *const pM) {
1564 syslog_pri_t pri = (pM->iFacility << 3) + (pM->iSeverity);
1565 if (pri > 191) pri = LOG_PRI_INVLD;
1566 return pri;
1567 }
1568
1569
1570 /* Get PRI value in text form
1571 */
1572 const char *getPRI(smsg_t *const pM) {
1573 /* PRI is a number in the range 0..191. Thus, we use a simple lookup table to obtain the
1574 * string value. It looks a bit clumpsy here in code ;)
1575 */
1576 int iPRI;
1577
1578 if (pM == NULL) return "";
1579
1580 iPRI = getPRIi(pM);
1581 return (iPRI > 191) ? "invld" : (char *)syslog_pri_names[iPRI].pszName;
1582 }
1583
1584
1585 static const char *formatISOWeekOrYear(enum tplFormatTypes eFmt, struct syslogTime *pTm) {
1586 if (pTm->year >= 1970 && pTm->year <= 2099) {
1587 int isoWeekYear;
1588 int isoWeek;
1589
1590 isoWeek = getISOWeek(pTm, &isoWeekYear);
1591
1592 if (eFmt == tplFmtISOWeek) {
1593 return two_digits[isoWeek];
1594 } else {
1595 return years[isoWeekYear - 1967];
1596 }
1597 } else {
1598 return "YEAR OUT OF RANGE(1970-2099)";
1599 }
1600 }
1601
1602 const char *getTimeReported(smsg_t *const pM, enum tplFormatTypes eFmt) {
1603 if (pM == NULL) return "";
1604
1605 switch (eFmt) {
1606 case tplFmtDefault:
1607 case tplFmtRFC3164Date:
1608 case tplFmtRFC3164BuggyDate:
1609 MsgLock(pM);
1610 if (pM->pszTIMESTAMP3164 == NULL) {
1611 pM->pszTIMESTAMP3164 = pM->pszTimestamp3164;
1612 datetime.formatTimestamp3164(&pM->tTIMESTAMP, pM->pszTIMESTAMP3164, (eFmt == tplFmtRFC3164BuggyDate));
1613 }
1614 MsgUnlock(pM);
1615 return (pM->pszTIMESTAMP3164);
1616 case tplFmtMySQLDate:
1617 MsgLock(pM);
1618 if (pM->pszTIMESTAMP_MySQL == NULL) {
1619 if ((pM->pszTIMESTAMP_MySQL = malloc(15)) == NULL) {
1620 MsgUnlock(pM);
1621 return "";
1622 }
1623 datetime.formatTimestampToMySQL(&pM->tTIMESTAMP, pM->pszTIMESTAMP_MySQL);
1624 }
1625 MsgUnlock(pM);
1626 return (pM->pszTIMESTAMP_MySQL);
1627 case tplFmtPgSQLDate:
1628 MsgLock(pM);
1629 if (pM->pszTIMESTAMP_PgSQL == NULL) {
1630 if ((pM->pszTIMESTAMP_PgSQL = malloc(21)) == NULL) {
1631 MsgUnlock(pM);
1632 return "";
1633 }
1634 datetime.formatTimestampToPgSQL(&pM->tTIMESTAMP, pM->pszTIMESTAMP_PgSQL);
1635 }
1636 MsgUnlock(pM);
1637 return (pM->pszTIMESTAMP_PgSQL);
1638 case tplFmtRFC3339Date:
1639 MsgLock(pM);
1640 if (pM->pszTIMESTAMP3339 == NULL) {
1641 pM->pszTIMESTAMP3339 = pM->pszTimestamp3339;
1642 datetime.formatTimestamp3339(&pM->tTIMESTAMP, pM->pszTIMESTAMP3339);
1643 }
1644 MsgUnlock(pM);
1645 return (pM->pszTIMESTAMP3339);
1646 case tplFmtUnixDate:
1647 MsgLock(pM);
1648 if (pM->pszTIMESTAMP_Unix[0] == '\0') {
1649 datetime.formatTimestampUnix(&pM->tTIMESTAMP, pM->pszTIMESTAMP_Unix);
1650 }
1651 MsgUnlock(pM);
1652 return (pM->pszTIMESTAMP_Unix);
1653 case tplFmtSecFrac:
1654 if (pM->pszTIMESTAMP_SecFrac[0] == '\0') {
1655 MsgLock(pM);
1656 /* re-check, may have changed while we did not hold lock */
1657 if (pM->pszTIMESTAMP_SecFrac[0] == '\0') {
1658 datetime.formatTimestampSecFrac(&pM->tTIMESTAMP, pM->pszTIMESTAMP_SecFrac);
1659 }
1660 MsgUnlock(pM);
1661 }
1662 return (pM->pszTIMESTAMP_SecFrac);
1663 case tplFmtWDayName:
1664 return wdayNames[getWeekdayNbr(&pM->tTIMESTAMP)];
1665 case tplFmtWDay:
1666 return one_digit[getWeekdayNbr(&pM->tTIMESTAMP)];
1667 case tplFmtMonth:
1668 return two_digits[(int)pM->tTIMESTAMP.month];
1669 case tplFmtYear:
1670 if (pM->tTIMESTAMP.year >= 1967 && pM->tTIMESTAMP.year <= 2099)
1671 return years[pM->tTIMESTAMP.year - 1967];
1672 else
1673 return "YEAR OUT OF RANGE(1967-2099)";
1674 case tplFmtDay:
1675 return two_digits[(int)pM->tTIMESTAMP.day];
1676 case tplFmtHour:
1677 return two_digits[(int)pM->tTIMESTAMP.hour];
1678 case tplFmtMinute:
1679 return two_digits[(int)pM->tTIMESTAMP.minute];
1680 case tplFmtSecond:
1681 return two_digits[(int)pM->tTIMESTAMP.second];
1682 case tplFmtTZOffsHour:
1683 return two_digits[(int)pM->tTIMESTAMP.OffsetHour];
1684 case tplFmtTZOffsMin:
1685 return two_digits[(int)pM->tTIMESTAMP.OffsetMinute];
1686 case tplFmtTZOffsDirection:
1687 return (pM->tTIMESTAMP.OffsetMode == '+') ? "+" : "-";
1688 case tplFmtOrdinal:
1689 return daysInYear[getOrdinal(&pM->tTIMESTAMP)];
1690 case tplFmtWeek:
1691 return two_digits[getWeek(&pM->tTIMESTAMP)];
1692 case tplFmtISOWeek:
1693 case tplFmtISOWeekYear:
1694 return formatISOWeekOrYear(eFmt, &pM->tTIMESTAMP);
1695 default:
1696 return "INVALID eFmt OPTION!";
1697 }
1698 }
1699
1700
1701 static const char *getTimeUTC(struct syslogTime *const __restrict__ pTmIn,
1702 const enum tplFormatTypes eFmt,
1703 unsigned short *const __restrict__ pbMustBeFreed) {
1704 struct syslogTime tUTC;
1705 char *retbuf = NULL;
1706
1707 timeConvertToUTC(pTmIn, &tUTC);
1708 struct syslogTime *const pTm = &tUTC;
1709
1710 switch (eFmt) {
1711 case tplFmtDefault:
1712 if ((retbuf = malloc(16)) != NULL) {
1713 datetime.formatTimestamp3164(pTm, retbuf, 0);
1714 }
1715 break;
1716 case tplFmtMySQLDate:
1717 if ((retbuf = malloc(15)) != NULL) {
1718 datetime.formatTimestampToMySQL(pTm, retbuf);
1719 }
1720 break;
1721 case tplFmtPgSQLDate:
1722 if ((retbuf = malloc(21)) != NULL) {
1723 datetime.formatTimestampToPgSQL(pTm, retbuf);
1724 }
1725 break;
1726 case tplFmtRFC3164Date:
1727 case tplFmtRFC3164BuggyDate:
1728 if ((retbuf = malloc(16)) != NULL) {
1729 datetime.formatTimestamp3164(pTm, retbuf, (eFmt == tplFmtRFC3164BuggyDate));
1730 }
1731 break;
1732 case tplFmtRFC3339Date:
1733 if ((retbuf = malloc(33)) != NULL) {
1734 datetime.formatTimestamp3339(pTm, retbuf);
1735 }
1736 break;
1737 case tplFmtUnixDate:
1738 if ((retbuf = malloc(12)) != NULL) {
1739 datetime.formatTimestampUnix(pTm, retbuf);
1740 }
1741 break;
1742 case tplFmtSecFrac:
1743 if ((retbuf = malloc(7)) != NULL) {
1744 datetime.formatTimestampSecFrac(pTm, retbuf);
1745 }
1746 break;
1747 case tplFmtWDayName:
1748 retbuf = strdup(wdayNames[getWeekdayNbr(pTm)]);
1749 break;
1750 case tplFmtWDay:
1751 retbuf = strdup(one_digit[getWeekdayNbr(pTm)]);
1752 break;
1753 case tplFmtMonth:
1754 retbuf = strdup(two_digits[(int)pTm->month]);
1755 break;
1756 case tplFmtYear:
1757 if (pTm->year >= 1967 && pTm->year <= 2099)
1758 retbuf = strdup(years[pTm->year - 1967]);
1759 else
1760 retbuf = strdup("YEAR OUT OF RANGE(1967-2099)");
1761 break;
1762 case tplFmtDay:
1763 retbuf = strdup(two_digits[(int)pTm->day]);
1764 break;
1765 case tplFmtHour:
1766 retbuf = strdup(two_digits[(int)pTm->hour]);
1767 break;
1768 case tplFmtMinute:
1769 retbuf = strdup(two_digits[(int)pTm->minute]);
1770 break;
1771 case tplFmtSecond:
1772 retbuf = strdup(two_digits[(int)pTm->second]);
1773 break;
1774 case tplFmtTZOffsHour:
1775 retbuf = strdup(two_digits[(int)pTm->OffsetHour]);
1776 break;
1777 case tplFmtTZOffsMin:
1778 retbuf = strdup(two_digits[(int)pTm->OffsetMinute]);
1779 break;
1780 case tplFmtTZOffsDirection:
1781 retbuf = strdup((pTm->OffsetMode == '+') ? "+" : "-");
1782 break;
1783 case tplFmtOrdinal:
1784 retbuf = strdup(daysInYear[getOrdinal(pTm)]);
1785 break;
1786 case tplFmtWeek:
1787 retbuf = strdup(two_digits[getWeek(pTm)]);
1788 break;
1789 case tplFmtISOWeek:
1790 case tplFmtISOWeekYear:
1791 retbuf = strdup(formatISOWeekOrYear(eFmt, pTm));
1792 break;
1793 default:
1794 // Required to prevent compiler warning C4062 (unhandled enum value).
1795 // Unhandled eFmt values are correctly managed by the subsequent if(retbuf == NULL) check.
1796 break;
1797 }
1798
1799 if (retbuf == NULL) {
1800 retbuf = (char *)"internal error: invalid eFmt option or malloc problem";
1801 *pbMustBeFreed = 0;
1802 } else {
1803 *pbMustBeFreed = 1;
1804 }
1805 return retbuf;
1806 }
1807
1808 static const char *getTimeGenerated(smsg_t *const __restrict__ pM, const enum tplFormatTypes eFmt) {
1809 struct syslogTime *const pTm = &pM->tRcvdAt;
1810 if (pM == NULL) return "";
1811
1812 switch (eFmt) {
1813 case tplFmtDefault:
1814 MsgLock(pM);
1815 if (pM->pszRcvdAt3164 == NULL) {
1816 if ((pM->pszRcvdAt3164 = malloc(16)) == NULL) {
1817 MsgUnlock(pM);
1818 return "";
1819 }
1820 datetime.formatTimestamp3164(pTm, pM->pszRcvdAt3164, 0);
1821 }
1822 MsgUnlock(pM);
1823 return (pM->pszRcvdAt3164);
1824 case tplFmtMySQLDate:
1825 MsgLock(pM);
1826 if (pM->pszRcvdAt_MySQL == NULL) {
1827 if ((pM->pszRcvdAt_MySQL = malloc(15)) == NULL) {
1828 MsgUnlock(pM);
1829 return "";
1830 }
1831 datetime.formatTimestampToMySQL(pTm, pM->pszRcvdAt_MySQL);
1832 }
1833 MsgUnlock(pM);
1834 return (pM->pszRcvdAt_MySQL);
1835 case tplFmtPgSQLDate:
1836 MsgLock(pM);
1837 if (pM->pszRcvdAt_PgSQL == NULL) {
1838 if ((pM->pszRcvdAt_PgSQL = malloc(21)) == NULL) {
1839 MsgUnlock(pM);
1840 return "";
1841 }
1842 datetime.formatTimestampToPgSQL(pTm, pM->pszRcvdAt_PgSQL);
1843 }
1844 MsgUnlock(pM);
1845 return (pM->pszRcvdAt_PgSQL);
1846 case tplFmtRFC3164Date:
1847 case tplFmtRFC3164BuggyDate:
1848 MsgLock(pM);
1849 if (pM->pszRcvdAt3164 == NULL) {
1850 if ((pM->pszRcvdAt3164 = malloc(16)) == NULL) {
1851 MsgUnlock(pM);
1852 return "";
1853 }
1854 datetime.formatTimestamp3164(pTm, pM->pszRcvdAt3164, (eFmt == tplFmtRFC3164BuggyDate));
1855 }
1856 MsgUnlock(pM);
1857 return (pM->pszRcvdAt3164);
1858 case tplFmtRFC3339Date:
1859 MsgLock(pM);
1860 if (pM->pszRcvdAt3339 == NULL) {
1861 if ((pM->pszRcvdAt3339 = malloc(33)) == NULL) {
1862 MsgUnlock(pM);
1863 return "";
1864 }
1865 datetime.formatTimestamp3339(pTm, pM->pszRcvdAt3339);
1866 }
1867 MsgUnlock(pM);
1868 return (pM->pszRcvdAt3339);
1869 case tplFmtUnixDate:
1870 MsgLock(pM);
1871 if (pM->pszRcvdAt_Unix[0] == '\0') {
1872 datetime.formatTimestampUnix(pTm, pM->pszRcvdAt_Unix);
1873 }
1874 MsgUnlock(pM);
1875 return (pM->pszRcvdAt_Unix);
1876 case tplFmtSecFrac:
1877 if (pM->pszRcvdAt_SecFrac[0] == '\0') {
1878 MsgLock(pM);
1879 /* re-check, may have changed while we did not hold lock */
1880 if (pM->pszRcvdAt_SecFrac[0] == '\0') {
1881 datetime.formatTimestampSecFrac(pTm, pM->pszRcvdAt_SecFrac);
1882 }
1883 MsgUnlock(pM);
1884 }
1885 return (pM->pszRcvdAt_SecFrac);
1886 case tplFmtWDayName:
1887 return wdayNames[getWeekdayNbr(pTm)];
1888 case tplFmtWDay:
1889 return one_digit[getWeekdayNbr(pTm)];
1890 case tplFmtMonth:
1891 return two_digits[(int)pTm->month];
1892 case tplFmtYear:
1893 if (pTm->year >= 1967 && pTm->year <= 2099)
1894 return years[pTm->year - 1967];
1895 else
1896 return "YEAR OUT OF RANGE(1967-2099)";
1897 case tplFmtDay:
1898 return two_digits[(int)pTm->day];
1899 case tplFmtHour:
1900 return two_digits[(int)pTm->hour];
1901 case tplFmtMinute:
1902 return two_digits[(int)pTm->minute];
1903 case tplFmtSecond:
1904 return two_digits[(int)pTm->second];
1905 case tplFmtTZOffsHour:
1906 return two_digits[(int)pTm->OffsetHour];
1907 case tplFmtTZOffsMin:
1908 return two_digits[(int)pTm->OffsetMinute];
1909 case tplFmtTZOffsDirection:
1910 return (pTm->OffsetMode == '+') ? "+" : "-";
1911 case tplFmtOrdinal:
1912 return daysInYear[getOrdinal(pTm)];
1913 case tplFmtWeek:
1914 return two_digits[getWeek(pTm)];
1915 case tplFmtISOWeek:
1916 case tplFmtISOWeekYear:
1917 return formatISOWeekOrYear(eFmt, pTm);
1918 default:
1919 return "INVALID eFmt OPTION!";
1920 }
1921 }
1922
1923
1924 static const char *getSeverity(smsg_t *const pM) {
1925 const char *name = NULL;
1926
1927 if (pM == NULL) return "";
1928
1929 if (pM->iSeverity > 7) {
1930 name = "invld";
1931 } else {
1932 name = syslog_number_names[pM->iSeverity];
1933 }
1934
1935 return name;
1936 }
1937
1938
1939 static const char *getSeverityStr(smsg_t *const pM) {
1940 const char *name = NULL;
1941
1942 if (pM == NULL) return "";
1943
1944 if (pM->iSeverity > 7) {
1945 name = "invld";
1946 } else {
1947 name = syslog_severity_names[pM->iSeverity];
1948 }
1949
1950 return name;
1951 }
1952
1953 static const char *getFacility(smsg_t *const pM) {
1954 const char *name = NULL;
1955
1956 if (pM == NULL) return "";
1957
1958 if (pM->iFacility > 23) {
1959 name = "invld";
1960 } else {
1961 name = syslog_number_names[pM->iFacility];
1962 }
1963
1964 return name;
1965 }
1966
1967 static const char *getFacilityStr(smsg_t *const pM) {
1968 const char *name = NULL;
1969
1970 if (pM == NULL) return "";
1971
1972 if (pM->iFacility > 23) {
1973 name = "invld";
1974 } else {
1975 name = syslog_fac_names[pM->iFacility];
1976 }
1977
1978 return name;
1979 }
1980
1981
1982 /* set flow control state (if not called, the default - NO_DELAY - is used)
1983 * This needs no locking because it is only done while the object is
1984 * not fully constructed (which also means you must not call this
1985 * method after the msg has been handed over to a queue).
1986 * rgerhards, 2008-03-14
1987 */
1988 rsRetVal MsgSetFlowControlType(smsg_t *const pMsg, flowControl_t eFlowCtl) {
1989 DEFiRet;
1990 assert(pMsg != NULL);
1991 assert(eFlowCtl == eFLOWCTL_NO_DELAY || eFlowCtl == eFLOWCTL_LIGHT_DELAY || eFlowCtl == eFLOWCTL_FULL_DELAY);
1992
1993 pMsg->flowCtlType = eFlowCtl;
1994
1995 RETiRet;
1996 }
1997
1998 /* set offset after which PRI in raw msg starts
1999 * rgerhards, 2009-06-16
2000 */
2001 rsRetVal MsgSetAfterPRIOffs(smsg_t *const pMsg, int offs) {
2002 assert(pMsg != NULL);
2003 pMsg->offAfterPRI = offs;
2004 return RS_RET_OK;
2005 }
2006
2007
2008 /* rgerhards 2004-11-24: set APP-NAME in msg object
2009 * This is not locked, because it either is called during message
2010 * construction (where we need no locking) or later as part of a function
2011 * which already obtained the lock. So in general, this function here must
2012 * only be called when it it safe to do so without it aquiring a lock.
2013 */
2014 rsRetVal ATTR_NONNULL(1, 2) MsgSetAPPNAME(smsg_t *__restrict__ const pMsg, const char *pszAPPNAME) {
2015 DEFiRet;
2016 assert(pMsg != NULL);
2017 if (pszAPPNAME[0] == '\0') {
2018 pszAPPNAME = "-"; /* RFC5424 NIL value */
2019 }
2020 if (pMsg->pCSAPPNAME == NULL) {
2021 /* we need to obtain the object first */
2022 CHKiRet(rsCStrConstruct(&pMsg->pCSAPPNAME));
2023 }
2024 /* if we reach this point, we have the object */
2025 CHKiRet(rsCStrSetSzStr(pMsg->pCSAPPNAME, (uchar *)pszAPPNAME));
2026 cstrFinalize(pMsg->pCSAPPNAME);
2027
2028 finalize_it:
2029 RETiRet;
2030 }
2031
2032
2033 /* rgerhards 2004-11-24: set PROCID in msg object
2034 */
2035 rsRetVal MsgSetPROCID(smsg_t *__restrict__ const pMsg, const char *pszPROCID) {
2036 DEFiRet;
2037 ISOBJ_TYPE_assert(pMsg, msg);
2038 if (pMsg->pCSPROCID == NULL) {
2039 /* we need to obtain the object first */
2040 CHKiRet(cstrConstruct(&pMsg->pCSPROCID));
2041 }
2042 /* if we reach this point, we have the object */
2043 CHKiRet(rsCStrSetSzStr(pMsg->pCSPROCID, (uchar *)pszPROCID));
2044 cstrFinalize(pMsg->pCSPROCID);
2045
2046 finalize_it:
2047 RETiRet;
2048 }
2049
2050
2051 /* check if we have a procid, and, if not, try to acquire/emulate it.
2052 * This must be called WITHOUT the message lock being held.
2053 * rgerhards, 2009-06-26
2054 */
2055 static void preparePROCID(smsg_t *const pM, sbool bLockMutex) {
2056 if (pM->pCSPROCID == NULL) {
2057 if (bLockMutex == LOCK_MUTEX) MsgLock(pM);
2058 /* re-query, things may have changed in the mean time... */
2059 if (pM->pCSPROCID == NULL) acquirePROCIDFromTAG(pM);
2060 if (bLockMutex == LOCK_MUTEX) MsgUnlock(pM);
2061 }
2062 }
2063
2064
2065 #if 0
2066 /* rgerhards, 2005-11-24
2067 */
2068 static int getPROCIDLen(smsg_t *pM, sbool bLockMutex)
2069 {
2070 assert(pM != NULL);
2071 preparePROCID(pM, bLockMutex);
2072 return (pM->pCSPROCID == NULL) ? 1 : rsCStrLen(pM->pCSPROCID);
2073 }
2074 #endif
2075
2076
2077 /* rgerhards, 2005-11-24
2078 */
2079 char *getPROCID(smsg_t *const pM, sbool bLockMutex) {
2080 uchar *pszRet;
2081
2082 ISOBJ_TYPE_assert(pM, msg);
2083 if (bLockMutex == LOCK_MUTEX) MsgLock(pM);
2084 preparePROCID(pM, MUTEX_ALREADY_LOCKED);
2085 if (pM->pCSPROCID == NULL)
2086 pszRet = UCHAR_CONSTANT("-");
2087 else
2088 pszRet = rsCStrGetSzStrNoNULL(pM->pCSPROCID);
2089 if (bLockMutex == LOCK_MUTEX) MsgUnlock(pM);
2090 return (char *)pszRet;
2091 }
2092
2093
2094 /* rgerhards 2004-11-24: set MSGID in msg object
2095 */
2096 rsRetVal MsgSetMSGID(smsg_t *const pMsg, const char *pszMSGID) {
2097 DEFiRet;
2098 ISOBJ_TYPE_assert(pMsg, msg);
2099 if (pMsg->pCSMSGID == NULL) {
2100 /* we need to obtain the object first */
2101 CHKiRet(rsCStrConstruct(&pMsg->pCSMSGID));
2102 }
2103 /* if we reach this point, we have the object */
2104 CHKiRet(rsCStrSetSzStr(pMsg->pCSMSGID, (uchar *)pszMSGID));
2105 cstrFinalize(pMsg->pCSMSGID);
2106
2107 finalize_it:
2108 RETiRet;
2109 }
2110
2111
2112 /* Return state of last parser. If it had success, "OK" is returned, else
2113 * "FAIL". All from the constant pool.
2114 */
2115 static const char *getParseSuccess(smsg_t *const pM) {
2116 return (pM->bParseSuccess) ? "OK" : "FAIL";
2117 }
2118
2119
2120 /* al, 2011-07-26: LockMsg to avoid race conditions
2121 */
2122 static const char *getMSGID(smsg_t *const pM) {
2123 if (pM->pCSMSGID == NULL) {
2124 return "-";
2125 } else {
2126 MsgLock(pM);
2127 char *pszreturn = (char *)rsCStrGetSzStrNoNULL(pM->pCSMSGID);
2128 MsgUnlock(pM);
2129 return pszreturn;
2130 }
2131 }
2132
2133 /* rgerhards 2012-03-15: set parser success (an integer, acutally bool)
2134 */
2135 void MsgSetParseSuccess(smsg_t *const pMsg, int bSuccess) {
2136 assert(pMsg != NULL);
2137 pMsg->bParseSuccess = bSuccess;
2138 }
2139
2140
2141 /* return full message as a json string */
2142 const uchar *msgGetJSONMESG(smsg_t *__restrict__ const pMsg) {
2143 struct json_object *json;
2144 struct json_object *jval;
2145 uchar *pRes; /* result pointer */
2146 rs_size_t bufLen = -1; /* length of string or -1, if not known */
2147
2148 json = json_object_new_object();
2149
2150 jval = json_object_new_string((char *)getMSG(pMsg));
2151 json_object_object_add(json, "msg", jval);
2152
2153 getRawMsg(pMsg, &pRes, &bufLen);
2154 jval = json_object_new_string((char *)pRes);
2155 json_object_object_add(json, "rawmsg", jval);
2156
2157 pRes = (uchar *)getTimeReported(pMsg, tplFmtRFC3339Date);
2158 jval = json_object_new_string((char *)pRes);
2159 json_object_object_add(json, "timereported", jval);
2160
2161 jval = json_object_new_string(getHOSTNAME(pMsg));
2162 json_object_object_add(json, "hostname", jval);
2163
2164 getTAG(pMsg, &pRes, &bufLen, LOCK_MUTEX);
2165 jval = json_object_new_string((char *)pRes);
2166 json_object_object_add(json, "syslogtag", jval);
2167
2168 getInputName(pMsg, &pRes, &bufLen);
2169 jval = json_object_new_string((char *)pRes);
2170 json_object_object_add(json, "inputname", jval);
2171
2172 jval = json_object_new_string((char *)getRcvFrom(pMsg));
2173 json_object_object_add(json, "fromhost", jval);
2174
2175 jval = json_object_new_string((char *)getRcvFromIP(pMsg));
2176 json_object_object_add(json, "fromhost-ip", jval);
2177
2178 jval = json_object_new_string((char *)getRcvFromPort(pMsg));
2179 json_object_object_add(json, "fromhost-port", jval);
2180
2181 jval = json_object_new_string(getPRI(pMsg));
2182 json_object_object_add(json, "pri", jval);
2183
2184 jval = json_object_new_string(getFacility(pMsg));
2185 json_object_object_add(json, "syslogfacility", jval);
2186
2187 jval = json_object_new_string(getSeverity(pMsg));
2188 json_object_object_add(json, "syslogseverity", jval);
2189
2190 pRes = (uchar *)getTimeGenerated(pMsg, tplFmtRFC3339Date);
2191 jval = json_object_new_string((char *)pRes);
2192 json_object_object_add(json, "timegenerated", jval);
2193
2194 jval = json_object_new_string((char *)getProgramName(pMsg, LOCK_MUTEX));
2195 json_object_object_add(json, "programname", jval);
2196
2197 jval = json_object_new_string(getProtocolVersionString(pMsg));
2198 json_object_object_add(json, "protocol-version", jval);
2199
2200 MsgGetStructuredData(pMsg, &pRes, &bufLen);
2201 jval = json_object_new_string((char *)pRes);
2202 json_object_object_add(json, "structured-data", jval);
2203
2204 jval = json_object_new_string(getAPPNAME(pMsg, LOCK_MUTEX));
2205 json_object_object_add(json, "app-name", jval);
2206
2207 jval = json_object_new_string(getPROCID(pMsg, LOCK_MUTEX));
2208 json_object_object_add(json, "procid", jval);
2209
2210 jval = json_object_new_string(getMSGID(pMsg));
2211 json_object_object_add(json, "msgid", jval);
2212
2213 #ifdef USE_LIBUUID
2214 if (pMsg->pszUUID == NULL) {
2215 jval = NULL;
2216 } else {
2217 getUUID(pMsg, &pRes, &bufLen);
2218 jval = json_object_new_string((char *)pRes);
2219 }
2220 json_object_object_add(json, "uuid", jval);
2221 #endif
2222
2223 json_object_object_add(json, "$!", json_object_get(pMsg->json));
2224
2225 pRes = (uchar *)strdup(jsonToString(json));
2226 json_object_put(json);
2227 return pRes;
2228 }
2229
2230 /* rgerhards 2009-06-12: set associated ruleset
2231 */
2232 void MsgSetRuleset(smsg_t *const pMsg, ruleset_t *pRuleset) {
2233 assert(pMsg != NULL);
2234 pMsg->pRuleset = pRuleset;
2235 }
2236
2237
2238 /* set TAG in msg object
2239 * (rewritten 2009-06-18 rgerhards)
2240 */
2241 void MsgSetTAG(smsg_t *__restrict__ const pMsg, const uchar *pszBuf, const size_t lenBuf) {
2242 uchar *pBuf;
2243 assert(pMsg != NULL);
2244
2245 freeTAG(pMsg);
2246
2247 pMsg->iLenTAG = lenBuf;
2248 if (pMsg->iLenTAG < CONF_TAG_BUFSIZE) {
2249 /* small enough: use fixed buffer (faster!) */
2250 pBuf = pMsg->TAG.szBuf;
2251 } else {
2252 if ((pBuf = (uchar *)malloc(pMsg->iLenTAG + 1)) == NULL) {
2253 /* truncate message, better than completely loosing it... */
2254 pBuf = pMsg->TAG.szBuf;
2255 pMsg->iLenTAG = CONF_TAG_BUFSIZE - 1;
2256 } else {
2257 pMsg->TAG.pszTAG = pBuf;
2258 }
2259 }
2260
2261 memcpy(pBuf, pszBuf, pMsg->iLenTAG);
2262 pBuf[pMsg->iLenTAG] = '\0'; /* this also works with truncation! */
2263 }
2264
2265
2266 /* This function tries to emulate the TAG if none is
2267 * set. Its primary purpose is to provide an old-style TAG
2268 * when a syslog-protocol message has been received. Then,
2269 * the tag is APP-NAME "[" PROCID "]". The function first checks
2270 * if there is a TAG and, if not, if it can emulate it.
2271 * rgerhards, 2005-11-24
2272 */
2273 static void ATTR_NONNULL(1) tryEmulateTAG(smsg_t *const pM, const sbool bLockMutex) {
2274 size_t lenTAG;
2275 uchar bufTAG[CONF_TAG_MAXSIZE];
2276 assert(pM != NULL);
2277
2278 if (bLockMutex == LOCK_MUTEX) MsgLock(pM);
2279 if (pM->iLenTAG > 0) {
2280 if (bLockMutex == LOCK_MUTEX) MsgUnlock(pM);
2281 return; /* done, no need to emulate */
2282 }
2283
2284 if (msgGetProtocolVersion(pM) == 1) {
2285 if (!strcmp(getPROCID(pM, MUTEX_ALREADY_LOCKED), "-")) {
2286 /* no process ID, use APP-NAME only */
2287 MsgSetTAG(pM, (uchar *)getAPPNAME(pM, MUTEX_ALREADY_LOCKED), getAPPNAMELen(pM, MUTEX_ALREADY_LOCKED));
2288 } else {
2289 /* now we can try to emulate */
2290 lenTAG = snprintf((char *)bufTAG, CONF_TAG_MAXSIZE, "%s[%s]", getAPPNAME(pM, MUTEX_ALREADY_LOCKED),
2291 getPROCID(pM, MUTEX_ALREADY_LOCKED));
2292 bufTAG[sizeof(bufTAG) - 1] = '\0'; /* just to make sure... */
2293 MsgSetTAG(pM, bufTAG, lenTAG);
2294 }
2295 /* Signal change in TAG for acquireProgramName */
2296 pM->iLenPROGNAME = -1;
2297 }
2298 if (bLockMutex == LOCK_MUTEX) MsgUnlock(pM);
2299 }
2300
2301
2302 void ATTR_NONNULL(2, 3) getTAG(smsg_t *const pM, uchar **const ppBuf, int *const piLen, const sbool bLockMutex) {
2303 if (bLockMutex == LOCK_MUTEX) MsgLock(pM);
2304
2305 if (pM == NULL) {
2306 *ppBuf = UCHAR_CONSTANT("");
2307 *piLen = 0;
2308 } else {
2309 if (pM->iLenTAG == 0) tryEmulateTAG(pM, MUTEX_ALREADY_LOCKED);
2310 if (pM->iLenTAG == 0) {
2311 *ppBuf = UCHAR_CONSTANT("");
2312 *piLen = 0;
2313 } else {
2314 *ppBuf = (pM->iLenTAG < CONF_TAG_BUFSIZE) ? pM->TAG.szBuf : pM->TAG.pszTAG;
2315 *piLen = pM->iLenTAG;
2316 }
2317 }
2318
2319 if (bLockMutex == LOCK_MUTEX) MsgUnlock(pM);
2320 }
2321
2322
2323 int getHOSTNAMELen(smsg_t *const pM) {
2324 if (pM == NULL)
2325 return 0;
2326 else if (pM->pszHOSTNAME == NULL) {
2327 resolveDNS(pM);
2328 if (pM->rcvFrom.pRcvFrom == NULL)
2329 return 0;
2330 else
2331 return prop.GetStringLen(pM->rcvFrom.pRcvFrom);
2332 } else
2333 return pM->iLenHOSTNAME;
2334 }
2335
2336
2337 const char *getHOSTNAME(smsg_t *const pM) {
2338 if (pM == NULL)
2339 return "";
2340 else if (pM->pszHOSTNAME == NULL) {
2341 resolveDNS(pM);
2342 if (pM->rcvFrom.pRcvFrom == NULL) {
2343 return "";
2344 } else {
2345 uchar *psz;
2346 int len;
2347 prop.GetString(pM->rcvFrom.pRcvFrom, &psz, &len);
2348 return (char *)psz;
2349 }
2350 } else {
2351 return (char *)pM->pszHOSTNAME;
2352 }
2353 }
2354
2355
2356 uchar *getRcvFrom(smsg_t *const pM) {
2357 uchar *psz;
2358 int len;
2359
2360 if (pM == NULL) {
2361 psz = UCHAR_CONSTANT("");
2362 } else {
2363 resolveDNS(pM);
2364 if (pM->rcvFrom.pRcvFrom == NULL)
2365 psz = UCHAR_CONSTANT("");
2366 else
2367 prop.GetString(pM->rcvFrom.pRcvFrom, &psz, &len);
2368 }
2369 return psz;
2370 }
2371
2372
2373 /* rgerhards 2004-11-24: set STRUCTURED DATA in msg object
2374 */
2375 rsRetVal MsgSetStructuredData(smsg_t *const pMsg, const char *pszStrucData) {
2376 DEFiRet;
2377 ISOBJ_TYPE_assert(pMsg, msg);
2378 free(pMsg->pszStrucData);
2379 CHKmalloc(pMsg->pszStrucData = (uchar *)strdup(pszStrucData));
2380 pMsg->lenStrucData = strlen(pszStrucData);
2381 finalize_it:
2382 RETiRet;
2383 }
2384
2385
2386 /* get the "STRUCTURED-DATA" as sz string, including length */
2387 void MsgGetStructuredData(smsg_t *const pM, uchar **pBuf, rs_size_t *len) {
2388 MsgLock(pM);
2389 if (pM->pszStrucData == NULL) {
2390 *pBuf = UCHAR_CONSTANT("-"), *len = 1;
2391 } else {
2392 *pBuf = pM->pszStrucData, *len = pM->lenStrucData;
2393 }
2394 MsgUnlock(pM);
2395 }
2396
2397 /* get the "programname" as sz string
2398 * rgerhards, 2005-10-19
2399 */
2400 uchar *ATTR_NONNULL(1) getProgramName(smsg_t *const pM, const sbool bLockMutex) {
2401 if (bLockMutex == LOCK_MUTEX) {
2402 MsgLock(pM);
2403 }
2404
2405 if (pM->iLenPROGNAME == -1) {
2406 if (pM->iLenTAG == 0) {
2407 uchar *pRes;
2408 rs_size_t bufLen = -1;
2409 getTAG(pM, &pRes, &bufLen, MUTEX_ALREADY_LOCKED);
2410 }
2411 acquireProgramName(pM);
2412 }
2413
2414 if (bLockMutex == LOCK_MUTEX) {
2415 MsgUnlock(pM);
2416 }
2417 return (pM->iLenPROGNAME < CONF_PROGNAME_BUFSIZE) ? pM->PROGNAME.szBuf : pM->PROGNAME.ptr;
2418 }
2419
2420
2421 /* check if we have a APPNAME, and, if not, try to acquire/emulate it.
2422 * rgerhards, 2009-06-26
2423 */
2424 static void ATTR_NONNULL(1) prepareAPPNAME(smsg_t *const pM, const sbool bLockMutex) {
2425 if (pM->pCSAPPNAME == NULL) {
2426 if (bLockMutex == LOCK_MUTEX) MsgLock(pM);
2427
2428 /* re-query as things might have changed during locking */
2429 if (pM->pCSAPPNAME == NULL) {
2430 if (msgGetProtocolVersion(pM) == 0) {
2431 /* only then it makes sense to emulate */
2432 MsgSetAPPNAME(pM, (char *)getProgramName(pM, MUTEX_ALREADY_LOCKED));
2433 }
2434 }
2435
2436 if (bLockMutex == LOCK_MUTEX) MsgUnlock(pM);
2437 }
2438 }
2439
2440 /* rgerhards, 2005-11-24
2441 */
2442 char *getAPPNAME(smsg_t *const pM, const sbool bLockMutex) {
2443 uchar *pszRet;
2444
2445 assert(pM != NULL);
2446 if (bLockMutex == LOCK_MUTEX) MsgLock(pM);
2447 prepareAPPNAME(pM, MUTEX_ALREADY_LOCKED);
2448 if (pM->pCSAPPNAME == NULL)
2449 pszRet = UCHAR_CONSTANT("");
2450 else
2451 pszRet = rsCStrGetSzStrNoNULL(pM->pCSAPPNAME);
2452 if (bLockMutex == LOCK_MUTEX) MsgUnlock(pM);
2453 return (char *)pszRet;
2454 }
2455
2456 /* rgerhards, 2005-11-24
2457 */
2458 static int getAPPNAMELen(smsg_t *const pM, const sbool bLockMutex) {
2459 assert(pM != NULL);
2460 prepareAPPNAME(pM, bLockMutex);
2461 return (pM->pCSAPPNAME == NULL) ? 0 : rsCStrLen(pM->pCSAPPNAME);
2462 }
2463
2464 /* rgerhards 2008-09-10: set pszInputName in msg object. This calls AddRef()
2465 * on the property, because this must be done in all current cases and there
2466 * is no case expected where this may not be necessary.
2467 * rgerhards, 2009-06-16
2468 */
2469 void MsgSetInputName(smsg_t *pThis, prop_t *inputName) {
2470 assert(pThis != NULL);
2471
2472 prop.AddRef(inputName);
2473 if (pThis->pInputName != NULL) prop.Destruct(&pThis->pInputName);
2474 pThis->pInputName = inputName;
2475 }
2476
2477 /* Set default TZ. Note that at most 7 chars are set, as we would
2478 * otherwise overrun our buffer!
2479 */
2480 void MsgSetDfltTZ(smsg_t *pThis, char *tz) {
2481 strncpy(pThis->dfltTZ, tz, 7);
2482 pThis->dfltTZ[7] = '\0'; /* ensure 0-Term in case of overflow! */
2483 }
2484
2485
2486 /* Set the pfrominet socket store, so that we can obtain the peer at some
2487 * later time. Note that we do not check if pRcvFrom is already set, so this
2488 * function must only be called during message creation.
2489 * NOTE: msgFlags is NOT set. While this is somewhat a violation of layers,
2490 * it is done because it gains us some performance. So the caller must make
2491 * sure the message flags are properly maintained. For all current callers,
2492 * this is always the case and without extra effort required.
2493 * rgerhards, 2009-11-17
2494 */
2495 rsRetVal msgSetFromSockinfo(smsg_t *pThis, struct sockaddr_storage *sa) {
2496 DEFiRet;
2497 assert(pThis->rcvFrom.pRcvFrom == NULL);
2498
2499 CHKmalloc(pThis->rcvFrom.pfrominet = malloc(sizeof(struct sockaddr_storage)));
2500 memcpy(pThis->rcvFrom.pfrominet, sa, sizeof(struct sockaddr_storage));
2501
2502 finalize_it:
2503 RETiRet;
2504 }
2505
2506 /* rgerhards 2008-09-10: set RcvFrom name in msg object. This calls AddRef()
2507 * on the property, because this must be done in all current cases and there
2508 * is no case expected where this may not be necessary.
2509 * rgerhards, 2009-06-30
2510 */
2511 void MsgSetRcvFrom(smsg_t *pThis, prop_t *new) {
2512 prop.AddRef(new);
2513 MsgSetRcvFromWithoutAddRef(pThis, new);
2514 }
2515
2516
2517 /* This is used to set the property via a string. This function should not be
2518 * called if there is a reliable way for a caller to make sure that the
2519 * same name can be used across multiple messages. However, if it can not
2520 * ensure that, calling this function is the second best thing, because it
2521 * will re-use the previously created property if it contained the same
2522 * name (but it works only for the immediate previous).
2523 * rgerhards, 2009-06-31
2524 */
2525 void MsgSetRcvFromStr(smsg_t *const pThis, const uchar *psz, const int len, prop_t **ppProp) {
2526 assert(pThis != NULL);
2527 assert(ppProp != NULL);
2528
2529 prop.CreateOrReuseStringProp(ppProp, psz, len);
2530 MsgSetRcvFrom(pThis, *ppProp);
2531 }
2532
2533
2534 /* set RcvFromIP name in msg object. This calls AddRef()
2535 * on the property, because this must be done in all current cases and there
2536 * is no case expected where this may not be necessary.
2537 * rgerhards, 2009-06-30
2538 */
2539 rsRetVal MsgSetRcvFromIP(smsg_t *pThis, prop_t *new) {
2540 assert(pThis != NULL);
2541
2542 prop.AddRef(new);
2543 MsgSetRcvFromIPWithoutAddRef(pThis, new);
2544 return RS_RET_OK;
2545 }
2546
2547
2548 /* This is used to set the property via a string. This function should not be
2549 * called if there is a reliable way for a caller to make sure that the
2550 * same name can be used across multiple messages. However, if it can not
2551 * ensure that, calling this function is the second best thing, because it
2552 * will re-use the previously created property if it contained the same
2553 * name (but it works only for the immediate previous).
2554 * rgerhards, 2009-06-31
2555 */
2556 rsRetVal MsgSetRcvFromIPStr(smsg_t *const pThis, const uchar *psz, const int len, prop_t **ppProp) {
2557 DEFiRet;
2558 assert(pThis != NULL);
2559
2560 CHKiRet(prop.CreateOrReuseStringProp(ppProp, psz, len));
2561 MsgSetRcvFromIP(pThis, *ppProp);
2562
2563 finalize_it:
2564 RETiRet;
2565 }
2566
2567 rsRetVal MsgSetRcvFromPort(smsg_t *pThis, prop_t *new) {
2568 assert(pThis != NULL);
2569
2570 prop.AddRef(new);
2571 MsgSetRcvFromPortWithoutAddRef(pThis, new);
2572 return RS_RET_OK;
2573 }
2574
2575 rsRetVal MsgSetRcvFromPortStr(smsg_t *const pThis, const uchar *psz, const int len, prop_t **ppProp) {
2576 DEFiRet;
2577 assert(pThis != NULL);
2578
2579 CHKiRet(prop.CreateOrReuseStringProp(ppProp, psz, len));
2580 MsgSetRcvFromPort(pThis, *ppProp);
2581
2582 finalize_it:
2583 RETiRet;
2584 }
2585
2586
2587 /* rgerhards 2004-11-09: set HOSTNAME in msg object
2588 * rgerhards, 2007-06-21:
2589 * Does not return anything. If an error occurs, the hostname is
2590 * simply not set. I have changed this behaviour. The only problem
2591 * we can run into is memory shortage. If we have such, it is better
2592 * to loose the hostname than the full message. So we silently ignore
2593 * that problem and hope that memory will be available the next time
2594 * we need it. The rest of the code already knows how to handle an
2595 * unset HOSTNAME.
2596 */
2597 void MsgSetHOSTNAME(smsg_t *pThis, const uchar *pszHOSTNAME, const int lenHOSTNAME) {
2598 assert(pThis != NULL);
2599
2600 freeHOSTNAME(pThis);
2601
2602 pThis->iLenHOSTNAME = lenHOSTNAME;
2603 if (pThis->iLenHOSTNAME < CONF_HOSTNAME_BUFSIZE) {
2604 /* small enough: use fixed buffer (faster!) */
2605 pThis->pszHOSTNAME = pThis->szHOSTNAME;
2606 } else if ((pThis->pszHOSTNAME = (uchar *)malloc(pThis->iLenHOSTNAME + 1)) == NULL) {
2607 /* truncate message, better than completely loosing it... */
2608 pThis->pszHOSTNAME = pThis->szHOSTNAME;
2609 pThis->iLenHOSTNAME = CONF_HOSTNAME_BUFSIZE - 1;
2610 }
2611
2612 memcpy(pThis->pszHOSTNAME, pszHOSTNAME, pThis->iLenHOSTNAME);
2613 pThis->pszHOSTNAME[pThis->iLenHOSTNAME] = '\0'; /* this also works with truncation! */
2614 }
2615
2616
2617 /* set the offset of the MSG part into the raw msg buffer
2618 * Note that the offset may be higher than the length of the raw message
2619 * (exactly by one). This can happen if we have a message that does not
2620 * contain any MSG part.
2621 */
2622 void MsgSetMSGoffs(smsg_t *const pMsg, int offs) {
2623 ISOBJ_TYPE_assert(pMsg, msg);
2624 pMsg->offMSG = offs;
2625 if (offs > pMsg->iLenRawMsg) {
2626 assert((int)offs - 1 == pMsg->iLenRawMsg);
2627 pMsg->iLenMSG = 0;
2628 } else {
2629 pMsg->iLenMSG = pMsg->iLenRawMsg - offs;
2630 }
2631 }
2632
2633
2634 /* replace the MSG part of a message. The update actually takes place inside
2635 * rawmsg.
2636 * There are two cases: either the new message will be larger than the new msg
2637 * or it will be less than or equal. If it is less than or equal, we can utilize
2638 * the previous message buffer. If it is larger, we can utilize the smsg_t-included
2639 * message buffer if it fits in there. If this is not the case, we need to alloc
2640 * a new, larger, chunk and copy over the data to it. Note that this function is
2641 * (hopefully) relatively seldom being called, so some performance impact is
2642 * uncritical. In any case, pszMSG is copied, so if it was dynamically allocated,
2643 * the caller is responsible for freeing it.
2644 * rgerhards, 2009-06-23
2645 */
2646 rsRetVal MsgReplaceMSG(smsg_t *pThis, const uchar *pszMSG, int lenMSG) {
2647 int lenNew;
2648 uchar *bufNew;
2649 DEFiRet;
2650 ISOBJ_TYPE_assert(pThis, msg);
2651 assert(pszMSG != NULL);
2652
2653 lenNew = pThis->iLenRawMsg + lenMSG - pThis->iLenMSG;
2654 if (lenMSG > pThis->iLenMSG && lenNew >= CONF_RAWMSG_BUFSIZE) {
2655 /* we have lost our "bet" and need to alloc a new buffer ;) */
2656 CHKmalloc(bufNew = malloc(lenNew + 1));
2657 memcpy(bufNew, pThis->pszRawMsg, pThis->offMSG);
2658 if (pThis->pszRawMsg != pThis->szRawMsg) free(pThis->pszRawMsg);
2659 pThis->pszRawMsg = bufNew;
2660 }
2661
2662 if (lenMSG > 0) memcpy(pThis->pszRawMsg + pThis->offMSG, pszMSG, lenMSG);
2663 pThis->pszRawMsg[lenNew] = '\0'; /* this also works with truncation! */
2664 pThis->iLenRawMsg = lenNew;
2665 pThis->iLenMSG = lenMSG;
2666
2667 finalize_it:
2668 RETiRet;
2669 }
2670
2671 /* truncate the (raw) message to configured max size.
2672 * The function makes sure that the stored rawmsg remains
2673 * properly terminated by '\0'.
2674 */
2675 void ATTR_NONNULL() MsgTruncateToMaxSize(smsg_t *const pThis) {
2676 ISOBJ_TYPE_assert(pThis, msg);
2677 const int maxMsgSize = glblGetMaxLine(runConf);
2678 assert(pThis->iLenRawMsg > maxMsgSize);
2679
2680 const int deltaSize = pThis->iLenRawMsg - maxMsgSize;
2681 pThis->pszRawMsg[maxMsgSize] = '\0';
2682 pThis->iLenRawMsg = maxMsgSize;
2683 if (pThis->iLenMSG < deltaSize) {
2684 pThis->iLenMSG = 0;
2685 } else {
2686 pThis->iLenMSG -= deltaSize;
2687 }
2688 }
2689
2690 /* set raw message in message object. Size of message is provided.
2691 * The function makes sure that the stored rawmsg is properly
2692 * terminated by '\0'. When a message is replaced, we try to keep
2693 * the existing MSG offset valid so that modules modifying only the
2694 * raw text do not need to recompute it.
2695 * rgerhards, 2009-06-16
2696 */
2697 void ATTR_NONNULL() MsgSetRawMsg(smsg_t *const pThis, const char *const pszRawMsg, const size_t lenMsg) {
2698 ISOBJ_TYPE_assert(pThis, msg);
2699 int deltaSize;
2700 if (pThis->pszRawMsg != pThis->szRawMsg) free(pThis->pszRawMsg);
2701
2702 deltaSize = (int)lenMsg - pThis->iLenRawMsg; /* value < 0 in truncation case! */
2703 pThis->iLenRawMsg = lenMsg;
2704 if (pThis->iLenRawMsg < CONF_RAWMSG_BUFSIZE) {
2705 /* small enough: use fixed buffer (faster!) */
2706 pThis->pszRawMsg = pThis->szRawMsg;
2707 } else if ((pThis->pszRawMsg = (uchar *)malloc(pThis->iLenRawMsg + 1)) == NULL) {
2708 /* truncate message, better than completely loosing it... */
2709 pThis->pszRawMsg = pThis->szRawMsg;
2710 pThis->iLenRawMsg = CONF_RAWMSG_BUFSIZE - 1;
2711 }
2712
2713 memcpy(pThis->pszRawMsg, pszRawMsg, pThis->iLenRawMsg);
2714 pThis->pszRawMsg[pThis->iLenRawMsg] = '\0'; /* this also works with truncation! */
2715 /*
2716 * Update cached MSG length. When offMSG already points into the
2717 * message (e.g. after initial parsing) adjusting iLenMSG avoids the
2718 * need for a costly re-parse in modules like mmexternal which may
2719 * replace the raw message text.
2720 */
2721 if (pThis->iLenRawMsg > pThis->offMSG)
2722 pThis->iLenMSG += deltaSize;
2723 else
2724 pThis->iLenMSG = 0;
2725 }
2726
2727
2728 /* set raw message in message object. Size of message is not provided. This
2729 * function should only be used when it is unavoidable (and over time we should
2730 * try to remove it altogether).
2731 * rgerhards, 2009-06-16
2732 */
2733 void MsgSetRawMsgWOSize(smsg_t *const pMsg, char *pszRawMsg) {
2734 MsgSetRawMsg(pMsg, pszRawMsg, strlen(pszRawMsg));
2735 }
2736
2737
2738 /* create textual representation of facility and severity.
2739 * The variable pRes must point to a user-supplied buffer of
2740 * at least 20 characters.
2741 */
2742 static uchar *textpri(const smsg_t *const __restrict__ pMsg) {
2743 int lenfac = len_syslog_fac_names[pMsg->iFacility];
2744 int lensev = len_syslog_severity_names[pMsg->iSeverity];
2745 int totlen = lenfac + 1 + lensev + 1;
2746 char *pRes = malloc(totlen);
2747 if (pRes != NULL) {
2748 memcpy(pRes, syslog_fac_names[pMsg->iFacility], lenfac);
2749 pRes[lenfac] = '.';
2750 memcpy(pRes + lenfac + 1, syslog_severity_names[pMsg->iSeverity], lensev + 1 /* for \0! */);
2751 }
2752 return (uchar *)pRes;
2753 }
2754
2755
2756 /* This function returns the current date in different
2757 * variants. It is used to construct the $NOW series of
2758 * system properties. The returned buffer must be freed
2759 * by the caller when no longer needed. If the function
2760 * can not allocate memory, it returns a NULL pointer.
2761 * Added 2007-07-10 rgerhards
2762 */
2763 typedef enum ENOWType {
2764 NOW_NOW,
2765 NOW_YEAR,
2766 NOW_MONTH,
2767 NOW_DAY,
2768 NOW_HOUR,
2769 NOW_HHOUR,
2770 NOW_QHOUR,
2771 NOW_MINUTE,
2772 NOW_WDAY
2773 } eNOWType;
2774 #define tmpBUFSIZE 16 /* size of formatting buffer */
2775 static uchar *getNOW(eNOWType eNow, struct syslogTime *t, const int inUTC) {
2776 uchar *pBuf;
2777 struct syslogTime tt;
2778
2779 if ((pBuf = (uchar *)malloc(tmpBUFSIZE)) == NULL) {
2780 return NULL;
2781 }
2782
2783 if (t == NULL) { /* can happen if called via script engine */
2784 datetime.getCurrTime(&tt, NULL, inUTC);
2785 t = &tt;
2786 }
2787
2788 if (t->year == 0 || t->inUTC != inUTC) { /* not yet set! */
2789 datetime.getCurrTime(t, NULL, inUTC);
2790 }
2791
2792 switch (eNow) {
2793 case NOW_NOW:
2794 memcpy(pBuf, two_digits[t->year / 100], 2);
2795 memcpy(pBuf + 2, two_digits[t->year % 100], 2);
2796 pBuf[4] = '-';
2797 memcpy(pBuf + 5, two_digits[(int)t->month], 2);
2798 pBuf[7] = '-';
2799 memcpy(pBuf + 8, two_digits[(int)t->day], 3);
2800 break;
2801 case NOW_YEAR:
2802 memcpy(pBuf, two_digits[t->year / 100], 2);
2803 memcpy(pBuf + 2, two_digits[t->year % 100], 3);
2804 break;
2805 case NOW_MONTH:
2806 memcpy(pBuf, two_digits[(int)t->month], 3);
2807 break;
2808 case NOW_DAY:
2809 memcpy(pBuf, two_digits[(int)t->day], 3);
2810 break;
2811 case NOW_HOUR:
2812 memcpy(pBuf, two_digits[(int)t->hour], 3);
2813 break;
2814 case NOW_HHOUR:
2815 memcpy(pBuf, two_digits[t->minute / 30], 3);
2816 break;
2817 case NOW_QHOUR:
2818 memcpy(pBuf, two_digits[t->minute / 15], 3);
2819 break;
2820 case NOW_MINUTE:
2821 memcpy(pBuf, two_digits[(int)t->minute], 3);
2822 break;
2823 case NOW_WDAY:
2824 memcpy(pBuf, one_digit[(int)t->wday], 2);
2825 break;
2826 default:
2827 // We need to satisfy compiler which does not properly handle enum
2828 break;
2829 }
2830
2831 return (pBuf);
2832 }
2833 #undef tmpBUFSIZE /* clean up */
2834
2835
2836 /* helper function to obtain correct JSON root and mutex depending on
2837 * property type (essentially based on the property id. If a non-json
2838 * property id is given the function errors out.
2839 * Note well: jroot points to a pointer to a (ptr to a) json object.
2840 * This is necessary because the caller needs a pointer to where the
2841 * json object pointer is stored, that in turn is necessary because
2842 * while the address of the actual pointer stays stable, the actual
2843 * content is volatile until the caller has locked the variable tree,
2844 * which we DO NOT do to keep calling semantics simple.
2845 */
2846 static rsRetVal ATTR_NONNULL() getJSONRootAndMutex(smsg_t *const pMsg,
2847 const propid_t id,
2848 struct json_object ***const jroot,
2849 pthread_mutex_t **const mut) {
2850 DEFiRet;
2851 assert(jroot != NULL); /* asserts also help static analyzer! */
2852 assert(mut != NULL);
2853 assert(*mut == NULL); /* caller shall have initialized this one! */
2854 assert(id == PROP_CEE || id == PROP_LOCAL_VAR || id == PROP_GLOBAL_VAR);
2855
2856 if (id == PROP_CEE) {
2857 *mut = &pMsg->mut;
2858 *jroot = &pMsg->json;
2859 } else if (id == PROP_LOCAL_VAR) {
2860 *mut = &pMsg->mut;
2861 *jroot = &pMsg->localvars;
2862 } else if (id == PROP_GLOBAL_VAR) {
2863 *mut = &glblVars_lock;
2864 *jroot = &global_var_root;
2865 } else {
2866 LogError(0, RS_RET_NON_JSON_PROP,
2867 "internal error: "
2868 "getJSONRootAndMutex; invalid property id %d",
2869 id);
2870 iRet = RS_RET_NON_JSON_PROP;
2871 }
2872
2873 RETiRet;
2874 }
2875
2876 /* basically same function, but does not use property id, but the the
2877 * variable name type indicator (char after starting $, e.g. $!myvar --> CEE)
2878 */
2879 static rsRetVal ATTR_NONNULL() getJSONRootAndMutexByVarChar(smsg_t *const pMsg,
2880 const char c,
2881 struct json_object ***const jroot,
2882 pthread_mutex_t **const mut) {
2883 DEFiRet;
2884 propid_t id;
2885 assert(c == '!' || c == '.' || c == '/');
2886
2887 switch (c) {
2888 case '!':
2889 id = PROP_CEE;
2890 break;
2891 case '.':
2892 id = PROP_LOCAL_VAR;
2893 break;
2894 case '/':
2895 id = PROP_GLOBAL_VAR;
2896 break;
2897 default:
2898 LogError(0, RS_RET_NON_JSON_PROP,
2899 "internal error: "
2900 "getJSONRootAndMutex; invalid indicator char %c(%2.2x)",
2901 c, c);
2902 ABORT_FINALIZE(RS_RET_NON_JSON_PROP);
2903 break;
2904 }
2905 iRet = getJSONRootAndMutex(pMsg, id, jroot, mut);
2906
2907 finalize_it:
2908 RETiRet;
2909 }
2910
2911
2912 /* Get a JSON-Property as string value (used for various types of JSON-based vars) */
2913 rsRetVal getJSONPropVal(
2914 smsg_t *const pMsg, msgPropDescr_t *pProp, uchar **pRes, rs_size_t *buflen, unsigned short *pbMustBeFreed) {
2915 uchar *leaf;
2916 struct json_object **jroot;
2917 struct json_object *parent;
2918 struct json_object *field;
2919 pthread_mutex_t *mut = NULL;
2920 DEFiRet;
2921
2922 *pRes = NULL;
2923 CHKiRet(getJSONRootAndMutex(pMsg, pProp->id, &jroot, &mut));
2924 pthread_mutex_lock(mut);
2925
2926 if (*jroot == NULL) FINALIZE;
2927
2928 if (!strcmp((char *)pProp->name, "!")) {
2929 field = *jroot;
2930 } else {
2931 leaf = jsonPathGetLeaf(pProp->name, pProp->nameLen);
2932 CHKiRet(jsonPathFindParent(*jroot, pProp->name, leaf, &parent, 0));
2933 if (jsonVarExtract(parent, (char *)leaf, &field) == FALSE) field = NULL;
2934 }
2935 if (field != NULL) {
2936 *pRes = (uchar *)strdup(jsonToString(field));
2937 *buflen = (int)ustrlen(*pRes);
2938 *pbMustBeFreed = 1;
2939 }
2940
2941 finalize_it:
2942 if (mut != NULL) pthread_mutex_unlock(mut);
2943 if (*pRes == NULL) {
2944 /* could not find any value, so set it to empty */
2945 *pRes = (unsigned char *)"";
2946 *pbMustBeFreed = 0;
2947 }
2948 RETiRet;
2949 }
2950
2951
2952 /* Get a JSON-based-variable as native json object, except
2953 * when it is string type, in which case a string is returned.
2954 * This is an optimization to not use JSON when not strictly
2955 * necessary. This in turn is helpful, as calling json-c is
2956 * *very* expensive due to our need for locking and deep
2957 * copies.
2958 * The caller needs to check pjson and pcstr: one of them
2959 * is non-NULL and contains the return value. Note that
2960 * the caller is responsible for freeing the string pointer
2961 * it if is being returned.
2962 */
2963 rsRetVal msgGetJSONPropJSONorString(smsg_t *const pMsg,
2964 msgPropDescr_t *pProp,
2965 struct json_object **pjson,
2966 uchar **pcstr) {
2967 struct json_object **jroot;
2968 uchar *leaf;
2969 struct json_object *parent;
2970 pthread_mutex_t *mut = NULL;
2971 DEFiRet;
2972
2973 *pjson = NULL, *pcstr = NULL;
2974
2975 CHKiRet(getJSONRootAndMutex(pMsg, pProp->id, &jroot, &mut));
2976 pthread_mutex_lock(mut);
2977 if (!strcmp((char *)pProp->name, "!")) {
2978 *pjson = *jroot;
2979 FINALIZE;
2980 }
2981 if (*jroot == NULL) {
2982 ABORT_FINALIZE(RS_RET_NOT_FOUND);
2983 }
2984 leaf = jsonPathGetLeaf(pProp->name, pProp->nameLen);
2985 CHKiRet(jsonPathFindParent(*jroot, pProp->name, leaf, &parent, 0));
2986 if (jsonVarExtract(parent, (char *)leaf, pjson) == FALSE) {
2987 ABORT_FINALIZE(RS_RET_NOT_FOUND);
2988 }
2989 if (*pjson == NULL) {
2990 /* we had a NULL json object and represent this as empty string */
2991 *pcstr = (uchar *)strdup("");
2992 } else {
2993 if (json_object_get_type(*pjson) == json_type_string) {
2994 *pcstr = (uchar *)strdup(jsonToString(*pjson));
2995 *pjson = NULL;
2996 }
2997 }
2998
2999 finalize_it:
3000 /* we need a deep copy, as another thread may modify the object */
3001 if (*pjson != NULL) *pjson = jsonDeepCopy(*pjson);
3002 if (mut != NULL) pthread_mutex_unlock(mut);
3003 RETiRet;
3004 }
3005
3006
3007 /* Get a JSON-based-variable as native json object */
3008 rsRetVal msgGetJSONPropJSON(smsg_t *const pMsg, msgPropDescr_t *pProp, struct json_object **pjson) {
3009 struct json_object **jroot;
3010 uchar *leaf;
3011 struct json_object *parent;
3012 pthread_mutex_t *mut = NULL;
3013 DEFiRet;
3014
3015 *pjson = NULL;
3016
3017 CHKiRet(getJSONRootAndMutex(pMsg, pProp->id, &jroot, &mut));
3018 pthread_mutex_lock(mut);
3019
3020 if (!strcmp((char *)pProp->name, "!")) {
3021 *pjson = *jroot;
3022 FINALIZE;
3023 }
3024 leaf = jsonPathGetLeaf(pProp->name, pProp->nameLen);
3025 CHKiRet(jsonPathFindParent(*jroot, pProp->name, leaf, &parent, 0));
3026 if (jsonVarExtract(parent, (char *)leaf, pjson) == FALSE) {
3027 ABORT_FINALIZE(RS_RET_NOT_FOUND);
3028 }
3029
3030 finalize_it:
3031 /* we need a deep copy, as another thread may modify the object */
3032 if (*pjson != NULL) *pjson = jsonDeepCopy(*pjson);
3033 if (mut != NULL) pthread_mutex_unlock(mut);
3034 RETiRet;
3035 }
3036
3037
3038 /* Helper for jsonAddVal(), to be called onces we know there are actually
3039 * json escapes inside the string. If so, this function takes over.
3040 * Splitting the functions permits us to make some performance optimizations.
3041 * For further details, see jsonAddVal().
3042 */
3043 static rsRetVal ATTR_NONNULL(1, 4) jsonAddVal_escaped(uchar *const pSrc,
3044 const unsigned buflen,
3045 const unsigned len_none_escaped_head,
3046 es_str_t **dst,
3047 const int escapeAll) {
3048 unsigned char c;
3049 es_size_t i;
3050 char numbuf[4];
3051 unsigned ni;
3052 unsigned char nc;
3053 int j;
3054 uchar wrkbuf[100000];
3055 size_t dst_realloc_size;
3056 size_t dst_size;
3057 uchar *dst_base;
3058 uchar *dst_w;
3059 uchar *newbuf;
3060 DEFiRet;
3061
3062 assert(len_none_escaped_head <= buflen);
3063 /* first copy over unescaped head string */
3064 if (len_none_escaped_head + 10 > sizeof(wrkbuf)) {
3065 dst_size = 2 * len_none_escaped_head;
3066 CHKmalloc(dst_base = malloc(dst_size));
3067 } else {
3068 dst_size = sizeof(wrkbuf);
3069 dst_base = wrkbuf;
3070 }
3071 dst_realloc_size = dst_size - 10; /* some buffer for escaping */
3072 dst_w = dst_base;
3073 memcpy(dst_w, pSrc, len_none_escaped_head);
3074 dst_w += len_none_escaped_head;
3075
3076 /* now do the escaping */
3077 for (i = len_none_escaped_head; i < buflen; ++i) {
3078 const size_t dst_offset = dst_w - dst_base;
3079 if (dst_offset >= dst_realloc_size) {
3080 const size_t new_size = 2 * dst_size;
3081 if (dst_base == wrkbuf) {
3082 CHKmalloc(newbuf = malloc(new_size));
3083 memcpy(newbuf, dst_base, dst_offset);
3084 } else {
3085 CHKmalloc(newbuf = realloc(dst_base, new_size));
3086 }
3087 dst_size = new_size;
3088 dst_realloc_size = new_size - 10; /* some buffer for escaping */
3089 dst_base = newbuf;
3090 dst_w = dst_base + dst_offset;
3091 }
3092 c = pSrc[i];
3093 if ((c >= 0x30 && c <= 0x5b) || (c >= 0x23 && c <= 0x2e) || (c >= 0x5d /* && c <= 0x10FFFF*/) || c == 0x20 ||
3094 c == 0x21) {
3095 /* no need to escape */
3096 *dst_w++ = c;
3097 } else {
3098 /* we must escape, try RFC4627-defined special sequences first */
3099 switch (c) {
3100 case '\0':
3101 *dst_w++ = '\\';
3102 *dst_w++ = 'u';
3103 *dst_w++ = '0';
3104 *dst_w++ = '0';
3105 *dst_w++ = '0';
3106 *dst_w++ = '0';
3107 break;
3108 case '\"':
3109 *dst_w++ = '\\';
3110 *dst_w++ = '"';
3111 break;
3112 case '/':
3113 *dst_w++ = '\\';
3114 *dst_w++ = '/';
3115 break;
3116 case '\\':
3117 if (escapeAll == RSFALSE) {
3118 ni = i + 1;
3119 if (ni <= buflen) {
3120 nc = pSrc[ni];
3121
3122 /* Attempt to not double encode */
3123 if (nc == '"' || nc == '/' || nc == '\\' || nc == 'b' || nc == 'f' || nc == 'n' ||
3124 nc == 'r' || nc == 't' || nc == 'u') {
3125 *dst_w++ = c;
3126 *dst_w++ = nc;
3127 i = ni;
3128 break;
3129 }
3130 }
3131 }
3132 *dst_w++ = '\\';
3133 *dst_w++ = '\\';
3134 break;
3135 case '\010':
3136 *dst_w++ = '\\';
3137 *dst_w++ = 'b';
3138 break;
3139 case '\014':
3140 *dst_w++ = '\\';
3141 *dst_w++ = 'f';
3142 break;
3143 case '\n':
3144 *dst_w++ = '\\';
3145 *dst_w++ = 'n';
3146 break;
3147 case '\r':
3148 *dst_w++ = '\\';
3149 *dst_w++ = 'r';
3150 break;
3151 case '\t':
3152 *dst_w++ = '\\';
3153 *dst_w++ = 't';
3154 break;
3155 default:
3156 /* TODO : proper Unicode encoding (see header comment) */
3157 for (j = 0; j < 4; ++j) {
3158 numbuf[3 - j] = hexdigit[c % 16];
3159 c = c / 16;
3160 }
3161 *dst_w++ = '\\';
3162 *dst_w++ = 'u';
3163 *dst_w++ = numbuf[0];
3164 *dst_w++ = numbuf[1];
3165 *dst_w++ = numbuf[2];
3166 *dst_w++ = numbuf[3];
3167 break;
3168 }
3169 }
3170 }
3171 if (*dst == NULL) {
3172 *dst = es_newStrFromBuf((char *)dst_base, dst_w - dst_base);
3173 } else {
3174 es_addBuf(dst, (const char *)dst_base, dst_w - dst_base);
3175 }
3176 finalize_it:
3177 if (dst_base != wrkbuf) {
3178 free(dst_base);
3179 }
3180 RETiRet;
3181 }
3182
3183
3184 /* Encode a JSON value and add it to provided string. Note that
3185 * the string object may be NULL. In this case, it is created
3186 * if and only if escaping is needed. if escapeAll is false, previously
3187 * escaped strings are left as is
3188 */
3189 static rsRetVal ATTR_NONNULL(1, 3)
3190 jsonAddVal(uchar *const pSrc, const unsigned buflen, es_str_t **dst, const int escapeAll) {
3191 es_size_t i;
3192 DEFiRet;
3193
3194 for (i = 0; i < buflen; ++i) {
3195 const uchar c = pSrc[i];
3196 if (!((c >= 0x30 && c <= 0x5b) || (c >= 0x23 && c <= 0x2e) || (c >= 0x5d /* && c <= 0x10FFFF*/) || c == 0x20 ||
3197 c == 0x21)) {
3198 iRet = jsonAddVal_escaped(pSrc, buflen, i, dst, escapeAll);
3199 FINALIZE;
3200 }
3201 }
3202 if (*dst != NULL) {
3203 es_addBuf(dst, (const char *)pSrc, buflen);
3204 }
3205 finalize_it:
3206 RETiRet;
3207 }
3208
3209
3210 /* encode a property in JSON escaped format. This is a helper
3211 * to MsgGetProp. It needs to update all provided parameters.
3212 * For performance reasons, we begin to copy the string only
3213 * when we recognice that we actually need to do some escaping.
3214 * rgerhards, 2012-03-16
3215 */
3216 static rsRetVal jsonEncode(uchar **ppRes, unsigned short *pbMustBeFreed, int *pBufLen, int escapeAll) {
3217 unsigned buflen;
3218 uchar *pSrc;
3219 es_str_t *dst = NULL;
3220 DEFiRet;
3221
3222 pSrc = *ppRes;
3223 buflen = (*pBufLen == -1) ? (int)ustrlen(pSrc) : *pBufLen;
3224 CHKiRet(jsonAddVal(pSrc, buflen, &dst, escapeAll));
3225
3226 if (dst != NULL) {
3227 /* we updated the string and need to replace the
3228 * previous data.
3229 */
3230 if (*pbMustBeFreed) free(*ppRes);
3231 CHKmalloc(*ppRes = (uchar *)es_str2cstr(dst, NULL));
3232 *pbMustBeFreed = 1;
3233 *pBufLen = -1;
3234 es_deleteStr(dst);
3235 }
3236
3237 finalize_it:
3238 RETiRet;
3239 }
3240
3241
3242 /* Format a property as JSON field, that means
3243 * "name"="value"
3244 * where value is JSON-escaped (here we assume that the name
3245 * only contains characters from the valid character set).
3246 * Note: this function duplicates code from jsonEncode().
3247 * TODO: these two functions should be combined, at least if
3248 * that makes any sense from a performance PoV - definitely
3249 * something to consider at a later stage. rgerhards, 2012-04-19
3250 */
3251 static rsRetVal ATTR_NONNULL() jsonField(const struct templateEntry *const pTpe,
3252 uchar **const ppRes,
3253 unsigned short *const pbMustBeFreed,
3254 int *const pBufLen,
3255 int escapeAll) {
3256 unsigned buflen;
3257 uchar *pSrc;
3258 es_str_t *dst = NULL;
3259 int is_numeric = 1;
3260 DEFiRet;
3261
3262 pSrc = *ppRes;
3263 buflen = (*pBufLen == -1) ? (int)ustrlen(pSrc) : *pBufLen;
3264 dbgprintf("jsonEncode: datatype: %u, onEmpty: %u val %*s\n", (unsigned)pTpe->data.field.options.dataType,
3265 (unsigned)pTpe->data.field.options.onEmpty, buflen, pSrc);
3266 if (buflen == 0) {
3267 if (pTpe->data.field.options.onEmpty == TPE_DATAEMPTY_SKIP) {
3268 FINALIZE;
3269 }
3270 is_numeric = 0;
3271 } else if (pTpe->data.field.options.dataType == TPE_DATATYPE_NUMBER) {
3272 /* trim whitespace for numeric checks */
3273 while (buflen > 0 && isspace((int)*pSrc)) {
3274 ++pSrc;
3275 --buflen;
3276 }
3277 while (buflen > 0 && isspace((int)pSrc[buflen - 1])) --buflen;
3278
3279 if (pTpe->data.field.options.bOmitIfZero && buflen == 1 && pSrc[0] == '0') {
3280 *pBufLen = 0;
3281 FINALIZE;
3282 }
3283 }
3284 /* we hope we have only few escapes... */
3285 dst = es_newStr(buflen + pTpe->lenFieldName + 15);
3286 es_addChar(&dst, '"');
3287 es_addBuf(&dst, (char *)pTpe->fieldName, pTpe->lenFieldName);
3288 es_addBufConstcstr(&dst, "\":");
3289 if (buflen == 0 && pTpe->data.field.options.onEmpty == TPE_DATAEMPTY_NULL) {
3290 es_addBufConstcstr(&dst, "null");
3291 } else {
3292 if (pTpe->data.field.options.dataType == TPE_DATATYPE_AUTO) {
3293 for (unsigned i = 0; i < buflen; ++i) {
3294 if (pSrc[i] < '0' || pSrc[i] > '9') {
3295 is_numeric = 0;
3296 break;
3297 }
3298 }
3299 if (!is_numeric) {
3300 es_addChar(&dst, '"');
3301 }
3302 CHKiRet(jsonAddVal(pSrc, buflen, &dst, escapeAll));
3303 if (!is_numeric) {
3304 es_addChar(&dst, '"');
3305 }
3306 } else if (pTpe->data.field.options.dataType == TPE_DATATYPE_STRING) {
3307 es_addChar(&dst, '"');
3308 CHKiRet(jsonAddVal(pSrc, buflen, &dst, escapeAll));
3309 es_addChar(&dst, '"');
3310 } else if (pTpe->data.field.options.dataType == TPE_DATATYPE_NUMBER) {
3311 if (buflen == 0) {
3312 es_addChar(&dst, '0');
3313 } else {
3314 CHKiRet(jsonAddVal(pSrc, buflen, &dst, escapeAll));
3315 }
3316 } else if (pTpe->data.field.options.dataType == TPE_DATATYPE_BOOL) {
3317 if (buflen == 1 && *pSrc == '0') {
3318 es_addBufConstcstr(&dst, "false");
3319 } else {
3320 es_addBufConstcstr(&dst, "true");
3321 }
3322 }
3323 }
3324
3325 if (*pbMustBeFreed) free(*ppRes);
3326 /* we know we do not have \0 chars - so the size does not change */
3327 *pBufLen = es_strlen(dst);
3328 CHKmalloc(*ppRes = (uchar *)es_str2cstr(dst, NULL));
3329 *pbMustBeFreed = 1;
3330 es_deleteStr(dst);
3331
3332 finalize_it:
3333 RETiRet;
3334 }
3335
3336
3337 /* This function returns a string-representation of the
3338 * requested message property. This is a generic function used
3339 * to abstract properties so that these can be easier
3340 * queried. Returns NULL if property could not be found.
3341 * Actually, this function is a big if..elseif. What it does
3342 * is simply to map property names (from MonitorWare) to the
3343 * message object data fields.
3344 *
3345 * In case we need string forms of propertis we do not
3346 * yet have in string form, we do a memory allocation that
3347 * is sufficiently large (in all cases). Once the string
3348 * form has been obtained, it is saved until the Msg object
3349 * is finally destroyed. This is so that we save the processing
3350 * time in the (likely) case that this property is requested
3351 * again. It also saves us a lot of dynamic memory management
3352 * issues in the upper layers, because we so can guarantee that
3353 * the buffer will remain static AND available during the lifetime
3354 * of the object. Please note that both the max size allocation as
3355 * well as keeping things in memory might like look like a
3356 * waste of memory (some might say it actually is...) - we
3357 * deliberately accept this because performance is more important
3358 * to us ;)
3359 * rgerhards 2004-11-18
3360 * Parameter "bMustBeFreed" is set by this function. It tells the
3361 * caller whether or not the string returned must be freed by the
3362 * caller itself. It is is 0, the caller MUST NOT free it. If it is
3363 * 1, the caller MUST free it. Handling this wrongly leads to either
3364 * a memory leak of a program abort (do to double-frees or frees on
3365 * the constant memory pool). So be careful to do it right.
3366 * rgerhards 2004-11-23
3367 * regular expression support contributed by Andres Riancho merged
3368 * on 2005-09-13
3369 * changed so that it now an be called without a template entry (NULL).
3370 * In this case, only the (unmodified) property is returned. This will
3371 * be used in selector line processing.
3372 * rgerhards 2005-09-15
3373 */
3374 /* a quick helper to save some writing: */
3375 #define RET_OUT_OF_MEMORY \
3376 { \
3377 *pbMustBeFreed = 0; \
3378 *pPropLen = sizeof("**OUT OF MEMORY**") - 1; \
3379 return (UCHAR_CONSTANT("**OUT OF MEMORY**")); \
3380 }
3381
3382 /**
3383 * \brief Helper function to generate a string property from a source buffer.
3384 *
3385 * This function allocates a new buffer, copies the content from the source,
3386 * null-terminates it, and manages the memory of the previous result string.
3387 *
3388 * \param[in,out] ppRes Pointer to the result string pointer. The old string is freed if *pbMustBeFreed is set.
3389 * The new string is assigned to *ppRes.
3390 * \param[in,out] pbMustBeFreed Pointer to the boolean flag indicating if *ppRes must be freed.
3391 * Updated to 1 (true) upon successful allocation.
3392 * \param[out] pBufLen Pointer to store the length of the new string.
3393 * \param[in] pSrc Pointer to the source buffer to copy from.
3394 * \param[in] len Length of the data to copy.
3395 *
3396 * \return rsRetVal RS_RET_OK on success, RS_RET_OUT_OF_MEMORY on allocation failure.
3397 */
3398 static rsRetVal msgPropStrGen(
3399 uchar **ppRes, unsigned short *pbMustBeFreed, rs_size_t *pBufLen, const uchar *pSrc, size_t len) {
3400 uchar *pBuf = NULL;
3401 DEFiRet;
3402
3403 CHKmalloc(pBuf = malloc(len + 1));
3404
3405 memcpy(pBuf, pSrc, len);
3406 pBuf[len] = '\0';
3407
3408 if (*pbMustBeFreed == 1) free(*ppRes);
3409 *ppRes = pBuf;
3410 *pbMustBeFreed = 1;
3411 *pBufLen = (rs_size_t)len;
3412
3413 finalize_it:
3414 if (iRet != RS_RET_OK) {
3415 free(pBuf);
3416 }
3417 RETiRet;
3418 }
3419
3420 uchar *MsgGetProp(smsg_t *__restrict__ const pMsg,
3421 struct templateEntry *__restrict__ const pTpe,
3422 msgPropDescr_t *pProp,
3423 rs_size_t *__restrict__ const pPropLen,
3424 unsigned short *__restrict__ const pbMustBeFreed,
3425 struct syslogTime *const ttNow) {
3426 uchar *pRes; /* result pointer */
3427 rs_size_t bufLen = -1; /* length of string or -1, if not known */
3428 uchar *pBufStart;
3429 uchar *pBuf;
3430 int iLen;
3431 short iOffs;
3432 enum tplFormatTypes datefmt;
3433 int bDateInUTC;
3434
3435 assert(pMsg != NULL);
3436 assert(pbMustBeFreed != NULL);
3437
3438 #ifdef FEATURE_REGEXP
3439 /* Variables necessary for regular expression matching */
3440 size_t nmatch = 10;
3441 regmatch_t pmatch[10];
3442 #endif
3443
3444 *pbMustBeFreed = 0;
3445
3446 switch (pProp->id) {
3447 case PROP_MSG:
3448 pRes = getMSG(pMsg);
3449 bufLen = getMSGLen(pMsg);
3450 break;
3451 case PROP_TIMESTAMP:
3452 if (pTpe != NULL) {
3453 datefmt = pTpe->data.field.eDateFormat;
3454 bDateInUTC = pTpe->data.field.options.bDateInUTC;
3455 } else {
3456 datefmt = tplFmtDefault;
3457 bDateInUTC = 0;
3458 }
3459 if (bDateInUTC) {
3460 pRes = (uchar *)getTimeUTC(&pMsg->tTIMESTAMP, datefmt, pbMustBeFreed);
3461 } else {
3462 pRes = (uchar *)getTimeReported(pMsg, datefmt);
3463 }
3464 break;
3465 case PROP_HOSTNAME:
3466 pRes = (uchar *)getHOSTNAME(pMsg);
3467 bufLen = getHOSTNAMELen(pMsg);
3468 break;
3469 case PROP_SYSLOGTAG:
3470 getTAG(pMsg, &pRes, &bufLen, LOCK_MUTEX);
3471 break;
3472 case PROP_RAWMSG:
3473 getRawMsg(pMsg, &pRes, &bufLen);
3474 break;
3475 case PROP_RAWMSG_AFTER_PRI:
3476 getRawMsgAfterPRI(pMsg, &pRes, &bufLen);
3477 break;
3478 case PROP_INPUTNAME:
3479 getInputName(pMsg, &pRes, &bufLen);
3480 break;
3481 case PROP_FROMHOST:
3482 pRes = getRcvFrom(pMsg);
3483 break;
3484 case PROP_FROMHOST_IP:
3485 pRes = getRcvFromIP(pMsg);
3486 break;
3487 case PROP_FROMHOST_PORT:
3488 pRes = getRcvFromPort(pMsg);
3489 break;
3490 case PROP_PRI:
3491 pRes = (uchar *)getPRI(pMsg);
3492 break;
3493 case PROP_PRI_TEXT:
3494 pRes = textpri(pMsg);
3495 if (pRes == NULL) RET_OUT_OF_MEMORY;
3496 *pbMustBeFreed = 1;
3497 break;
3498 case PROP_IUT:
3499 pRes = UCHAR_CONSTANT("1"); /* always 1 for syslog messages (a MonitorWare thing;)) */
3500 bufLen = 1;
3501 break;
3502 case PROP_SYSLOGFACILITY:
3503 pRes = (uchar *)getFacility(pMsg);
3504 break;
3505 case PROP_SYSLOGFACILITY_TEXT:
3506 pRes = (uchar *)getFacilityStr(pMsg);
3507 break;
3508 case PROP_SYSLOGSEVERITY:
3509 pRes = (uchar *)getSeverity(pMsg);
3510 break;
3511 case PROP_SYSLOGSEVERITY_TEXT:
3512 pRes = (uchar *)getSeverityStr(pMsg);
3513 break;
3514 case PROP_TIMEGENERATED:
3515 if (pTpe != NULL) {
3516 datefmt = pTpe->data.field.eDateFormat;
3517 bDateInUTC = pTpe->data.field.options.bDateInUTC;
3518 } else {
3519 datefmt = tplFmtDefault;
3520 bDateInUTC = 0;
3521 }
3522 if (bDateInUTC) {
3523 pRes = (uchar *)getTimeUTC(&pMsg->tRcvdAt, datefmt, pbMustBeFreed);
3524 } else {
3525 pRes = (uchar *)getTimeGenerated(pMsg, datefmt);
3526 }
3527 break;
3528 case PROP_PROGRAMNAME:
3529 pRes = getProgramName(pMsg, LOCK_MUTEX);
3530 break;
3531 case PROP_PROTOCOL_VERSION:
3532 pRes = (uchar *)getProtocolVersionString(pMsg);
3533 break;
3534 case PROP_STRUCTURED_DATA:
3535 MsgGetStructuredData(pMsg, &pRes, &bufLen);
3536 break;
3537 case PROP_APP_NAME:
3538 pRes = (uchar *)getAPPNAME(pMsg, LOCK_MUTEX);
3539 break;
3540 case PROP_PROCID:
3541 pRes = (uchar *)getPROCID(pMsg, LOCK_MUTEX);
3542 break;
3543 case PROP_MSGID:
3544 pRes = (uchar *)getMSGID(pMsg);
3545 break;
3546 case PROP_JSONMESG:
3547 pRes = (uchar *)msgGetJSONMESG(pMsg);
3548 *pbMustBeFreed = 1;
3549 break;
3550 #ifdef USE_LIBUUID
3551 case PROP_UUID:
3552 getUUID(pMsg, &pRes, &bufLen);
3553 break;
3554 #endif
3555 case PROP_PARSESUCCESS:
3556 pRes = (uchar *)getParseSuccess(pMsg);
3557 break;
3558 case PROP_SYS_NOW:
3559 if ((pRes = getNOW(NOW_NOW, ttNow, TIME_IN_LOCALTIME)) == NULL) {
3560 RET_OUT_OF_MEMORY;
3561 } else {
3562 *pbMustBeFreed = 1;
3563 bufLen = 10;
3564 }
3565 break;
3566 case PROP_SYS_YEAR:
3567 if ((pRes = getNOW(NOW_YEAR, ttNow, TIME_IN_LOCALTIME)) == NULL) {
3568 RET_OUT_OF_MEMORY;
3569 } else {
3570 *pbMustBeFreed = 1;
3571 bufLen = 4;
3572 }
3573 break;
3574 case PROP_SYS_MONTH:
3575 if ((pRes = getNOW(NOW_MONTH, ttNow, TIME_IN_LOCALTIME)) == NULL) {
3576 RET_OUT_OF_MEMORY;
3577 } else {
3578 *pbMustBeFreed = 1;
3579 bufLen = 2;
3580 }
3581 break;
3582 case PROP_SYS_DAY:
3583 if ((pRes = getNOW(NOW_DAY, ttNow, TIME_IN_LOCALTIME)) == NULL) {
3584 RET_OUT_OF_MEMORY;
3585 } else {
3586 *pbMustBeFreed = 1;
3587 bufLen = 2;
3588 }
3589 break;
3590 case PROP_SYS_HOUR:
3591 if ((pRes = getNOW(NOW_HOUR, ttNow, TIME_IN_LOCALTIME)) == NULL) {
3592 RET_OUT_OF_MEMORY;
3593 } else {
3594 *pbMustBeFreed = 1;
3595 bufLen = 2;
3596 }
3597 break;
3598 case PROP_SYS_HHOUR:
3599 if ((pRes = getNOW(NOW_HHOUR, ttNow, TIME_IN_LOCALTIME)) == NULL) {
3600 RET_OUT_OF_MEMORY;
3601 } else {
3602 *pbMustBeFreed = 1;
3603 bufLen = 2;
3604 }
3605 break;
3606 case PROP_SYS_QHOUR:
3607 if ((pRes = getNOW(NOW_QHOUR, ttNow, TIME_IN_LOCALTIME)) == NULL) {
3608 RET_OUT_OF_MEMORY;
3609 } else {
3610 *pbMustBeFreed = 1;
3611 bufLen = 2;
3612 }
3613 break;
3614 case PROP_SYS_MINUTE:
3615 if ((pRes = getNOW(NOW_MINUTE, ttNow, TIME_IN_LOCALTIME)) == NULL) {
3616 RET_OUT_OF_MEMORY;
3617 } else {
3618 *pbMustBeFreed = 1;
3619 bufLen = 2;
3620 }
3621 break;
3622 case PROP_SYS_NOW_UTC:
3623 if ((pRes = getNOW(NOW_NOW, ttNow, TIME_IN_UTC)) == NULL) {
3624 RET_OUT_OF_MEMORY;
3625 } else {
3626 *pbMustBeFreed = 1;
3627 bufLen = 10;
3628 }
3629 break;
3630 case PROP_SYS_YEAR_UTC:
3631 if ((pRes = getNOW(NOW_YEAR, ttNow, TIME_IN_UTC)) == NULL) {
3632 RET_OUT_OF_MEMORY;
3633 } else {
3634 *pbMustBeFreed = 1;
3635 bufLen = 4;
3636 }
3637 break;
3638 case PROP_SYS_MONTH_UTC:
3639 if ((pRes = getNOW(NOW_MONTH, ttNow, TIME_IN_UTC)) == NULL) {
3640 RET_OUT_OF_MEMORY;
3641 } else {
3642 *pbMustBeFreed = 1;
3643 bufLen = 2;
3644 }
3645 break;
3646 case PROP_SYS_DAY_UTC:
3647 if ((pRes = getNOW(NOW_DAY, ttNow, TIME_IN_UTC)) == NULL) {
3648 RET_OUT_OF_MEMORY;
3649 } else {
3650 *pbMustBeFreed = 1;
3651 bufLen = 2;
3652 }
3653 break;
3654 case PROP_SYS_HOUR_UTC:
3655 if ((pRes = getNOW(NOW_HOUR, ttNow, TIME_IN_UTC)) == NULL) {
3656 RET_OUT_OF_MEMORY;
3657 } else {
3658 *pbMustBeFreed = 1;
3659 bufLen = 2;
3660 }
3661 break;
3662 case PROP_SYS_HHOUR_UTC:
3663 if ((pRes = getNOW(NOW_HHOUR, ttNow, TIME_IN_UTC)) == NULL) {
3664 RET_OUT_OF_MEMORY;
3665 } else {
3666 *pbMustBeFreed = 1;
3667 bufLen = 2;
3668 }
3669 break;
3670 case PROP_SYS_QHOUR_UTC:
3671 if ((pRes = getNOW(NOW_QHOUR, ttNow, TIME_IN_UTC)) == NULL) {
3672 RET_OUT_OF_MEMORY;
3673 } else {
3674 *pbMustBeFreed = 1;
3675 bufLen = 2;
3676 }
3677 break;
3678 case PROP_SYS_MINUTE_UTC:
3679 if ((pRes = getNOW(NOW_MINUTE, ttNow, TIME_IN_UTC)) == NULL) {
3680 RET_OUT_OF_MEMORY;
3681 } else {
3682 *pbMustBeFreed = 1;
3683 bufLen = 2;
3684 }
3685 break;
3686 case PROP_SYS_WDAY:
3687 if ((pRes = getNOW(NOW_WDAY, ttNow, TIME_IN_LOCALTIME)) == NULL) {
3688 RET_OUT_OF_MEMORY;
3689 } else {
3690 *pbMustBeFreed = 1;
3691 bufLen = 1;
3692 }
3693 break;
3694 case PROP_SYS_WDAY_UTC:
3695 if ((pRes = getNOW(NOW_WDAY, ttNow, TIME_IN_UTC)) == NULL) {
3696 RET_OUT_OF_MEMORY;
3697 } else {
3698 *pbMustBeFreed = 1;
3699 bufLen = 1;
3700 }
3701 break;
3702 case PROP_SYS_NOW_UXTIMESTAMP:
3703 if ((pRes = malloc(16)) == NULL) {
3704 RET_OUT_OF_MEMORY;
3705 } else {
3706 snprintf((char *)pRes, 16 - 1, "%lld", (long long)getTime(NULL));
3707 pRes[16 - 1] = '\0';
3708 *pbMustBeFreed = 1;
3709 bufLen = -1;
3710 }
3711 break;
3712 case PROP_SYS_MYHOSTNAME:
3713 pRes = glbl.GetLocalHostName();
3714 break;
3715 case PROP_CEE_ALL_JSON:
3716 case PROP_CEE_ALL_JSON_PLAIN:
3717 if (pMsg->json == NULL) {
3718 pRes = (uchar *)"{}";
3719 bufLen = 2;
3720 *pbMustBeFreed = 0;
3721 } else {
3722 const char *jstr;
3723 MsgLock(pMsg);
3724 int jflag = 0;
3725 if (pProp->id == PROP_CEE_ALL_JSON) {
3726 jflag = JSON_C_TO_STRING_SPACED;
3727 } else if (pProp->id == PROP_CEE_ALL_JSON_PLAIN) {
3728 jflag = JSON_C_TO_STRING_PLAIN;
3729 }
3730 jstr = json_object_to_json_string_ext(pMsg->json, jflag);
3731 MsgUnlock(pMsg);
3732 if (jstr == NULL) {
3733 RET_OUT_OF_MEMORY;
3734 }
3735 pRes = (uchar *)strdup(jstr);
3736 if (pRes == NULL) {
3737 RET_OUT_OF_MEMORY;
3738 }
3739 *pbMustBeFreed = 1;
3740 }
3741 break;
3742 case PROP_CEE:
3743 case PROP_LOCAL_VAR:
3744 case PROP_GLOBAL_VAR:
3745 getJSONPropVal(pMsg, pProp, &pRes, &bufLen, pbMustBeFreed);
3746 break;
3747 case PROP_SYS_BOM:
3748 pRes = (uchar *)"\xEF\xBB\xBF";
3749 *pbMustBeFreed = 0;
3750 break;
3751 case PROP_SYS_UPTIME:
3752 #ifndef HAVE_SYSINFO_UPTIME
3753 /* An alternative on some systems (eg Solaris) is to scan
3754 * /var/adm/utmpx for last boot time.
3755 */
3756 pRes = (uchar *)"UPTIME NOT available on this system";
3757 *pbMustBeFreed = 0;
3758
3759 #elif defined(__FreeBSD__)
3760
3761 {
3762 struct timespec tp;
3763
3764 if ((pRes = (uchar *)malloc(32)) == NULL) {
3765 RET_OUT_OF_MEMORY;
3766 }
3767
3768 if (clock_gettime(CLOCK_UPTIME, &tp) == -1) {
3769 free(pRes);
3770 *pPropLen = sizeof("**SYSCALL FAILED**") - 1;
3771 return (UCHAR_CONSTANT("**SYSCALL FAILED**"));
3772 }
3773
3774 *pbMustBeFreed = 1;
3775
3776 snprintf((char *)pRes, 32, "%ld", tp.tv_sec);
3777 }
3778
3779 #else
3780
3781 {
3782 struct sysinfo s_info;
3783
3784 if ((pRes = (uchar *)malloc(32)) == NULL) {
3785 RET_OUT_OF_MEMORY;
3786 }
3787
3788 if (sysinfo(&s_info) < 0) {
3789 free(pRes);
3790 *pPropLen = sizeof("**SYSCALL FAILED**") - 1;
3791 return (UCHAR_CONSTANT("**SYSCALL FAILED**"));
3792 }
3793
3794 *pbMustBeFreed = 1;
3795
3796 snprintf((char *)pRes, 32, "%ld", s_info.uptime);
3797 }
3798 #endif
3799 break;
3800 default:
3801 /* there is no point in continuing, we may even otherwise render the
3802 * error message unreadable. rgerhards, 2007-07-10
3803 */
3804 dbgprintf("invalid property id: '%d'\n", pProp->id);
3805 *pbMustBeFreed = 0;
3806 *pPropLen = sizeof("**INVALID PROPERTY NAME**") - 1;
3807 return UCHAR_CONSTANT("**INVALID PROPERTY NAME**");
3808 }
3809
3810 /* If we did not receive a template pointer, we are already done... */
3811 if (pTpe == NULL || !pTpe->bComplexProcessing) {
3812 *pPropLen = (bufLen == -1) ? (int)ustrlen(pRes) : bufLen;
3813 return pRes;
3814 }
3815
3816 /* Now check if we need to make "temporary" transformations (these
3817 * are transformations that do not go back into the message -
3818 * memory must be allocated for them!).
3819 */
3820
3821 /* substring extraction */
3822 /* first we check if we need to extract by field number
3823 * rgerhards, 2005-12-22
3824 */
3825 if (pTpe->data.field.has_fields == 1) {
3826 size_t iCurrFld;
3827 uchar *pFld;
3828 uchar *pFldEnd;
3829 /* first, skip to the field in question. The field separator
3830 * is always one character and is stored in the template entry.
3831 */
3832 iCurrFld = 1;
3833 pFld = pRes;
3834 while (*pFld && iCurrFld < pTpe->data.field.iFieldNr) {
3835 /* skip fields until the requested field or end of string is found */
3836 while (*pFld && (uchar)*pFld != pTpe->data.field.field_delim) ++pFld; /* skip to field terminator */
3837 if (*pFld == pTpe->data.field.field_delim) {
3838 ++pFld; /* eat it */
3839 #ifdef STRICT_GPLV3
3840 if (pTpe->data.field.field_expand != 0) {
3841 while (*pFld == pTpe->data.field.field_delim) {
3842 ++pFld;
3843 }
3844 }
3845 #endif
3846 ++iCurrFld;
3847 }
3848 }
3849 dbgprintf("field requested %d, field found %d\n", pTpe->data.field.iFieldNr, (int)iCurrFld);
3850
3851 if (iCurrFld == pTpe->data.field.iFieldNr) {
3852 /* field found, now extract it */
3853 /* first of all, we need to find the end */
3854 pFldEnd = pFld;
3855 while (*pFldEnd && *pFldEnd != pTpe->data.field.field_delim) ++pFldEnd;
3856 --pFldEnd; /* we are already at the delimiter - so we need to
3857 * step back a little not to copy it as part of the field. */
3858 /* we got our end pointer, now do the copy */
3859 /* TODO: code copied from below, this is a candidate for a separate function */
3860 iLen = pFldEnd - pFld + 1; /* the +1 is for an actual char, NOT \0! */
3861 if (msgPropStrGen(&pRes, pbMustBeFreed, &bufLen, pFld, iLen) != RS_RET_OK) {
3862 if (*pbMustBeFreed == 1) {
3863 free(pRes);
3864 *pbMustBeFreed = 0;
3865 }
3866 RET_OUT_OF_MEMORY;
3867 }
3868 } else {
3869 /* field not found, return error */
3870 if (*pbMustBeFreed == 1) free(pRes);
3871 *pbMustBeFreed = 0;
3872 *pPropLen = sizeof("**FIELD NOT FOUND**") - 1;
3873 return UCHAR_CONSTANT("**FIELD NOT FOUND**");
3874 }
3875 #ifdef FEATURE_REGEXP
3876 } else {
3877 /* Check for regular expressions */
3878 if (pTpe->data.field.has_regex != 0) {
3879 if (pTpe->data.field.has_regex == 2) {
3880 /* Could not compile regex before! */
3881 if (*pbMustBeFreed == 1) {
3882 free(pRes);
3883 *pbMustBeFreed = 0;
3884 }
3885 *pPropLen = sizeof("**NO MATCH** **BAD REGULAR EXPRESSION**") - 1;
3886 return UCHAR_CONSTANT("**NO MATCH** **BAD REGULAR EXPRESSION**");
3887 }
3888
3889 dbgprintf("string to match for regex is: %s\n", pRes);
3890
3891 if (objUse(regexp, LM_REGEXP_FILENAME) == RS_RET_OK) {
3892 short iTry = 0;
3893 uchar bFound = 0;
3894 iOffs = 0;
3895 /* first see if we find a match, iterating through the series of
3896 * potential matches over the string.
3897 */
3898 while (!bFound) {
3899 int iREstat;
3900 iREstat = regexp.regexec(&pTpe->data.field.re, (char *)(pRes + iOffs), nmatch, pmatch, 0);
3901 dbgprintf("regexec return is %d\n", iREstat);
3902 if (iREstat == 0) {
3903 if (pmatch[0].rm_so == -1) {
3904 dbgprintf(
3905 "oops ... start offset of successful "
3906 "regexec is -1\n");
3907 break;
3908 }
3909 if (iTry == pTpe->data.field.iMatchToUse) {
3910 bFound = 1;
3911 } else {
3912 dbgprintf(
3913 "regex found at offset %d, new offset %d, "
3914 "tries %d\n",
3915 iOffs, (int)(iOffs + pmatch[0].rm_eo), iTry);
3916 iOffs += pmatch[0].rm_eo;
3917 ++iTry;
3918 }
3919 } else {
3920 break;
3921 }
3922 }
3923 dbgprintf("regex: end search, found %d\n", bFound);
3924 if (!bFound) {
3925 /* we got no match! */
3926 if (pTpe->data.field.nomatchAction != TPL_REGEX_NOMATCH_USE_WHOLE_FIELD) {
3927 if (*pbMustBeFreed == 1) {
3928 free(pRes);
3929 *pbMustBeFreed = 0;
3930 }
3931 if (pTpe->data.field.nomatchAction == TPL_REGEX_NOMATCH_USE_DFLTSTR) {
3932 bufLen = sizeof("**NO MATCH**") - 1;
3933 pRes = UCHAR_CONSTANT("**NO MATCH**");
3934 } else if (pTpe->data.field.nomatchAction == TPL_REGEX_NOMATCH_USE_ZERO) {
3935 bufLen = 1;
3936 pRes = UCHAR_CONSTANT("0");
3937 } else {
3938 bufLen = 0;
3939 pRes = UCHAR_CONSTANT("");
3940 }
3941 }
3942 } else {
3943 /* Match- but did it match the one we wanted? */
3944 /* we got no match! */
3945 if (pmatch[pTpe->data.field.iSubMatchToUse].rm_so == -1) {
3946 if (pTpe->data.field.nomatchAction != TPL_REGEX_NOMATCH_USE_WHOLE_FIELD) {
3947 if (*pbMustBeFreed == 1) {
3948 free(pRes);
3949 *pbMustBeFreed = 0;
3950 }
3951 if (pTpe->data.field.nomatchAction == TPL_REGEX_NOMATCH_USE_DFLTSTR) {
3952 bufLen = sizeof("**NO MATCH**") - 1;
3953 pRes = UCHAR_CONSTANT("**NO MATCH**");
3954 } else if (pTpe->data.field.nomatchAction == TPL_REGEX_NOMATCH_USE_ZERO) {
3955 bufLen = 1;
3956 pRes = UCHAR_CONSTANT("0");
3957 } else {
3958 bufLen = 0;
3959 pRes = UCHAR_CONSTANT("");
3960 }
3961 }
3962 }
3963 /* OK, we have a usable match - we now need to malloc pB */
3964 int iLenBuf;
3965
3966 iLenBuf =
3967 pmatch[pTpe->data.field.iSubMatchToUse].rm_eo - pmatch[pTpe->data.field.iSubMatchToUse].rm_so;
3968
3969 if (msgPropStrGen(&pRes, pbMustBeFreed, &bufLen,
3970 pRes + iOffs + pmatch[pTpe->data.field.iSubMatchToUse].rm_so,
3971 iLenBuf) != RS_RET_OK) {
3972 if (*pbMustBeFreed == 1) {
3973 free(pRes);
3974 *pbMustBeFreed = 0;
3975 }
3976 RET_OUT_OF_MEMORY;
3977 }
3978 }
3979 } else {
3980 /* we could not load regular expression support. This is quite unexpected at
3981 * this stage of processing (after all, the config parser found it), but so
3982 * it is. We return an error in that case. -- rgerhards, 2008-03-07
3983 */
3984 dbgprintf("could not get regexp object pointer, so regexp can not be evaluated\n");
3985 if (*pbMustBeFreed == 1) {
3986 free(pRes);
3987 *pbMustBeFreed = 0;
3988 }
3989 *pPropLen = sizeof("***REGEXP NOT AVAILABLE***") - 1;
3990 return UCHAR_CONSTANT("***REGEXP NOT AVAILABLE***");
3991 }
3992 }
3993 #endif /* #ifdef FEATURE_REGEXP */
3994 }
3995
3996 if (pTpe->data.field.iFromPos != 0 || pTpe->data.field.iToPos != 0) {
3997 /* we need to obtain a private copy */
3998 int iFrom, iTo;
3999 uchar *pSb;
4000 iFrom = pTpe->data.field.iFromPos;
4001 iTo = pTpe->data.field.iToPos;
4002 if (bufLen == -1) bufLen = ustrlen(pRes);
4003 if (pTpe->data.field.options.bFromPosEndRelative) {
4004 iFrom = (bufLen < iFrom) ? 0 : bufLen - iFrom;
4005 iTo = (bufLen < iTo) ? 0 : bufLen - iTo;
4006 } else {
4007 /* need to zero-base to and from (they are 1-based!) */
4008 if (iFrom > 0) --iFrom;
4009 if (iTo > 0) {
4010 --iTo;
4011 } else if (iTo < 0) {
4012 /* note: we ADD negative value, 0-based (-1)! */
4013 iTo = bufLen - 1 + iTo;
4014 if (iTo < 0) {
4015 iTo = 0;
4016 }
4017 }
4018 }
4019 if (iFrom >= bufLen) {
4020 DBGPRINTF("msgGetProp: iFrom %d >= buflen %d, returning empty string\n", iFrom, bufLen);
4021 if (*pbMustBeFreed == 1) free(pRes);
4022 pRes = (uchar *)"";
4023 *pbMustBeFreed = 0;
4024 bufLen = 0;
4025 } else if (iFrom == 0 && iTo >= bufLen && pTpe->data.field.options.bFixedWidth == 0) {
4026 /* in this case, the requested string is a superset of what we already have,
4027 * so there is no need to do any processing. This is a frequent case for size-limited
4028 * fields like TAG in the default forwarding template (so it is a useful optimization
4029 * to check for this condition ;)). -- rgerhards, 2009-07-09
4030 */
4031 ; /*DO NOTHING*/
4032 } else {
4033 if (iTo >= bufLen) /* iTo is very large, if no to-position is set in the template! */
4034 if (pTpe->data.field.options.bFixedWidth == 0) iTo = bufLen - 1;
4035
4036 iLen = iTo - iFrom + 1; /* the +1 is for an actual char, NOT \0! */
4037 pBufStart = pBuf = malloc(iLen + 1);
4038 if (pBuf == NULL) {
4039 if (*pbMustBeFreed == 1) free(pRes);
4040 RET_OUT_OF_MEMORY;
4041 }
4042 pSb = pRes;
4043 if (iFrom) {
4044 /* skip to the start of the substring (can't do pointer arithmetic
4045 * because the whole string might be smaller!!)
4046 */
4047 while (*pSb && iFrom) {
4048 --iFrom;
4049 ++pSb;
4050 }
4051 }
4052 /* OK, we are at the begin - now let's copy... */
4053 bufLen = iLen;
4054 while (iLen) {
4055 if (*pSb) {
4056 *pBuf++ = *pSb;
4057 ++pSb;
4058 } else {
4059 *pBuf++ = ' ';
4060 }
4061 --iLen;
4062 }
4063 *pBuf = '\0';
4064 bufLen -= iLen; /* subtract remaining length if the string was smaller! */
4065 if (*pbMustBeFreed == 1) free(pRes);
4066 pRes = pBufStart;
4067 *pbMustBeFreed = 1;
4068 }
4069 }
4070
4071 /* now check if we need to do our "SP if first char is non-space" hack logic */
4072 if (*pRes && pTpe->data.field.options.bSPIffNo1stSP) {
4073 /* here, we always destruct the buffer and return a new one */
4074 uchar cFirst = *pRes; /* save first char */
4075 if (*pbMustBeFreed == 1) free(pRes);
4076 pRes = (cFirst == ' ') ? UCHAR_CONSTANT("") : UCHAR_CONSTANT(" ");
4077 bufLen = (cFirst == ' ') ? 0 : 1;
4078 *pbMustBeFreed = 0;
4079 }
4080
4081 if (*pRes) {
4082 /* case conversations (should go after substring, because so we are able to
4083 * work on the smallest possible buffer).
4084 */
4085 if (pTpe->data.field.eCaseConv != tplCaseConvNo) {
4086 /* we need to obtain a private copy */
4087 if (bufLen == -1) bufLen = ustrlen(pRes);
4088 uchar *pBStart;
4089 uchar *pB;
4090 uchar *pSrc;
4091 pBStart = pB = malloc(bufLen + 1);
4092 if (pB == NULL) {
4093 if (*pbMustBeFreed == 1) free(pRes);
4094 RET_OUT_OF_MEMORY;
4095 }
4096 pSrc = pRes;
4097 while (*pSrc) {
4098 *pB++ = (pTpe->data.field.eCaseConv == tplCaseConvUpper) ? (uchar)toupper((int)*pSrc)
4099 : (uchar)tolower((int)*pSrc);
4100 /* currently only these two exist */
4101 ++pSrc;
4102 }
4103 *pB = '\0';
4104 if (*pbMustBeFreed == 1) free(pRes);
4105 pRes = pBStart;
4106 *pbMustBeFreed = 1;
4107 }
4108
4109 /* now do control character dropping/escaping/replacement
4110 * Only one of these can be used. If multiple options are given, the
4111 * result is random (though currently there obviously is an order of
4112 * preferrence, see code below. But this is NOT guaranteed.
4113 * RGerhards, 2006-11-17
4114 * We must copy the strings if we modify them, because they may either
4115 * point to static memory or may point into the message object, in which
4116 * case we would actually modify the original property (which of course
4117 * is wrong).
4118 * This was found and fixed by varmojefkoj on 2007-09-11
4119 */
4120 if (pTpe->data.field.options.bDropCC) {
4121 int iLenBuf = 0;
4122 uchar *pSrc = pRes;
4123 uchar *pDstStart;
4124 uchar *pDst;
4125 uchar bDropped = 0;
4126
4127 while (*pSrc) {
4128 if (!iscntrl((int)*pSrc++))
4129 iLenBuf++;
4130 else
4131 bDropped = 1;
4132 }
4133
4134 if (bDropped) {
4135 pDst = pDstStart = malloc(iLenBuf + 1);
4136 if (pDst == NULL) {
4137 if (*pbMustBeFreed == 1) free(pRes);
4138 RET_OUT_OF_MEMORY;
4139 }
4140 for (pSrc = pRes; *pSrc; pSrc++) {
4141 if (!iscntrl((int)*pSrc)) *pDst++ = *pSrc;
4142 }
4143 *pDst = '\0';
4144 if (*pbMustBeFreed == 1) free(pRes);
4145 pRes = pDstStart;
4146 bufLen = iLenBuf;
4147 *pbMustBeFreed = 1;
4148 }
4149 } else if (pTpe->data.field.options.bSpaceCC) {
4150 uchar *pSrc;
4151 uchar *pDstStart;
4152 uchar *pDst;
4153
4154 if (*pbMustBeFreed == 1) {
4155 /* in this case, we already work on dynamic
4156 * memory, so there is no need to copy it - we can
4157 * modify it in-place without any harm. This is a
4158 * performance optiomization.
4159 */
4160 for (pDst = pRes; *pDst; pDst++) {
4161 if (iscntrl((int)*pDst)) *pDst = ' ';
4162 }
4163 } else {
4164 if (bufLen == -1) bufLen = ustrlen(pRes);
4165 pDst = pDstStart = malloc(bufLen + 1);
4166 if (pDst == NULL) {
4167 if (*pbMustBeFreed == 1) free(pRes);
4168 RET_OUT_OF_MEMORY;
4169 }
4170 for (pSrc = pRes; *pSrc; pSrc++) {
4171 if (iscntrl((int)*pSrc))
4172 *pDst++ = ' ';
4173 else
4174 *pDst++ = *pSrc;
4175 }
4176 *pDst = '\0';
4177 pRes = pDstStart;
4178 *pbMustBeFreed = 1;
4179 }
4180 } else if (pTpe->data.field.options.bEscapeCC) {
4181 /* we must first count how many control charactes are
4182 * present, because we need this to compute the new string
4183 * buffer length. While doing so, we also compute the string
4184 * length.
4185 */
4186 int iNumCC = 0;
4187 int iLenBuf = 0;
4188 uchar *pSrc;
4189 uchar *pB;
4190
4191 for (pB = pRes; *pB; ++pB) {
4192 ++iLenBuf;
4193 if (iscntrl((int)*pB)) ++iNumCC;
4194 }
4195
4196 if (iNumCC > 0) { /* if 0, there is nothing to escape, so we are done */
4197 /* OK, let's do the escaping... */
4198 uchar *pBStart;
4199 uchar szCCEsc[8]; /* buffer for escape sequence */
4200 int i;
4201
4202 iLenBuf += iNumCC * 4;
4203 pBStart = pB = malloc(iLenBuf + 1);
4204 if (pB == NULL) {
4205 if (*pbMustBeFreed == 1) free(pRes);
4206 RET_OUT_OF_MEMORY;
4207 }
4208 for (pSrc = pRes; *pSrc; pSrc++) {
4209 if (iscntrl((int)*pSrc)) {
4210 snprintf((char *)szCCEsc, sizeof(szCCEsc), "#%3.3d", *pSrc);
4211 for (i = 0; i < 4; ++i) *pB++ = szCCEsc[i];
4212 } else {
4213 *pB++ = *pSrc;
4214 }
4215 }
4216 *pB = '\0';
4217 if (*pbMustBeFreed == 1) free(pRes);
4218 pRes = pBStart;
4219 bufLen = -1;
4220 *pbMustBeFreed = 1;
4221 }
4222 }
4223 }
4224
4225 /* Take care of spurious characters to make the property safe
4226 * for a path definition
4227 */
4228 if (pTpe->data.field.options.bSecPathDrop || pTpe->data.field.options.bSecPathReplace) {
4229 if (pTpe->data.field.options.bSecPathDrop) {
4230 int iLenBuf = 0;
4231 uchar *pSrc = pRes;
4232 uchar *pDstStart;
4233 uchar *pDst;
4234 uchar bDropped = 0;
4235
4236 while (*pSrc) {
4237 if (*pSrc++ != '/')
4238 iLenBuf++;
4239 else
4240 bDropped = 1;
4241 }
4242
4243 if (bDropped) {
4244 pDst = pDstStart = malloc(iLenBuf + 1);
4245 if (pDst == NULL) {
4246 if (*pbMustBeFreed == 1) free(pRes);
4247 RET_OUT_OF_MEMORY;
4248 }
4249 for (pSrc = pRes; *pSrc; pSrc++) {
4250 if (*pSrc != '/') *pDst++ = *pSrc;
4251 }
4252 *pDst = '\0';
4253 if (*pbMustBeFreed == 1) free(pRes);
4254 pRes = pDstStart;
4255 bufLen = -1; /* TODO: can we do better? */
4256 *pbMustBeFreed = 1;
4257 }
4258 } else {
4259 uchar *pSrc;
4260 uchar *pDstStart;
4261 uchar *pDst;
4262
4263 if (*pbMustBeFreed == 1) {
4264 /* here, again, we can modify the string as we already obtained
4265 * a private buffer. As we do not change the size of that buffer,
4266 * in-place modification is possible. This is a performance
4267 * enhancement.
4268 */
4269 for (pDst = pRes; *pDst; pDst++) {
4270 if (*pDst == '/') *pDst++ = '_';
4271 }
4272 } else {
4273 if (bufLen == -1) bufLen = ustrlen(pRes);
4274 pDst = pDstStart = malloc(bufLen + 1);
4275 if (pDst == NULL) {
4276 if (*pbMustBeFreed == 1) free(pRes);
4277 RET_OUT_OF_MEMORY;
4278 }
4279 for (pSrc = pRes; *pSrc; pSrc++) {
4280 if (*pSrc == '/')
4281 *pDst++ = '_';
4282 else
4283 *pDst++ = *pSrc;
4284 }
4285 *pDst = '\0';
4286 /* we must NOT check if it needs to be freed, because we have done
4287 * this in the if above. So if we come to hear, the pSrc string needs
4288 * not to be freed (and we do not need to care about it).
4289 */
4290 pRes = pDstStart;
4291 *pbMustBeFreed = 1;
4292 }
4293 }
4294
4295 /* check for "." and ".." (note the parenthesis in the if condition!) */
4296 if (*pRes == '\0') {
4297 if (*pbMustBeFreed == 1) free(pRes);
4298 pRes = UCHAR_CONSTANT("_");
4299 bufLen = 1;
4300 *pbMustBeFreed = 0;
4301 } else if ((*pRes == '.') && (*(pRes + 1) == '\0' || (*(pRes + 1) == '.' && *(pRes + 2) == '\0'))) {
4302 uchar *pTmp = pRes;
4303
4304 if (*(pRes + 1) == '\0')
4305 pRes = UCHAR_CONSTANT("_");
4306 else
4307 pRes = UCHAR_CONSTANT("_.");
4308 ;
4309 if (*pbMustBeFreed == 1) free(pTmp);
4310 *pbMustBeFreed = 0;
4311 }
4312 }
4313
4314 /* Now drop last LF if present (pls note that this must not be done
4315 * if bEscapeCC was set)!
4316 */
4317 if (pTpe->data.field.options.bDropLastLF && !pTpe->data.field.options.bEscapeCC) {
4318 int iLn;
4319 uchar *pB;
4320 if (bufLen == -1) bufLen = ustrlen(pRes);
4321 iLn = bufLen;
4322 if (iLn > 0 && *(pRes + iLn - 1) == '\n') {
4323 /* we have a LF! */
4324 /* check if we need to obtain a private copy */
4325 if (*pbMustBeFreed == 0) {
4326 /* ok, original copy, need a private one */
4327 pB = malloc(iLn + 1);
4328 if (pB == NULL) {
4329 RET_OUT_OF_MEMORY;
4330 }
4331 memcpy(pB, pRes, iLn - 1);
4332 pRes = pB;
4333 *pbMustBeFreed = 1;
4334 }
4335 *(pRes + iLn - 1) = '\0'; /* drop LF ;) */
4336 --bufLen;
4337 }
4338 }
4339
4340 /* Now everything is squased as much as possible and more or less ready to
4341 * go. This is the perfect place to compress any remaining spaces, if so
4342 * instructed by the user/config.
4343 */
4344 if (pTpe->data.field.options.bCompressSP) {
4345 int needCompress = 0;
4346 int hadSP = 0;
4347 uchar *pB;
4348 if (*pbMustBeFreed == 0) {
4349 for (pB = pRes; *pB && needCompress == 0; ++pB) {
4350 if (*pB == ' ') {
4351 if (hadSP) {
4352 uchar *const tmp = ustrdup(pRes);
4353 if (tmp == NULL)
4354 /* better not compress than
4355 * loose message. */
4356 break;
4357 *pbMustBeFreed = 1;
4358 pRes = tmp;
4359 needCompress = 1;
4360 } else {
4361 hadSP = 1;
4362 }
4363 }
4364 }
4365 } else {
4366 /* If we can modify the buffer in any case, we
4367 * do NOT check if we actually need to compress,
4368 * but "just do it" - that's the quickest way
4369 * to get it done.
4370 */
4371 needCompress = 1;
4372 }
4373 if (needCompress) {
4374 hadSP = 0;
4375 uchar *pDst = pRes;
4376 int needCopy = 0;
4377 for (pB = pRes; *pB; ++pB) {
4378 if (*pB == ' ') {
4379 if (hadSP) {
4380 needCopy = 1;
4381 } else {
4382 hadSP = 1;
4383 if (needCopy) *pDst = *pB;
4384 ++pDst;
4385 }
4386 } else {
4387 hadSP = 0;
4388 if (needCopy) *pDst = *pB;
4389 ++pDst;
4390 }
4391 }
4392 *pDst = '\0';
4393 bufLen = pDst - pRes;
4394 }
4395 }
4396
4397 /* finally, we need to check if the property should be formatted in CSV or JSON.
4398 * For CSV we use RFC 4180, and always use double quotes. As of this writing,
4399 * this should be the last action carried out on the property, but in the
4400 * future there may be reasons to change that. -- rgerhards, 2009-04-02
4401 */
4402 if (pTpe->data.field.options.bCSV) {
4403 /* we need to obtain a private copy, as we need to at least add the double quotes */
4404 int iBufLen;
4405 uchar *pBStart;
4406 uchar *pDst;
4407 uchar *pSrc;
4408 if (bufLen == -1) bufLen = ustrlen(pRes);
4409 iBufLen = bufLen;
4410 /* the malloc may be optimized, we currently use the worst case... */
4411 pBStart = pDst = malloc(2 * iBufLen + 3);
4412 if (pDst == NULL) {
4413 if (*pbMustBeFreed == 1) free(pRes);
4414 RET_OUT_OF_MEMORY;
4415 }
4416 pSrc = pRes;
4417 *pDst++ = '"'; /* starting quote */
4418 while (*pSrc) {
4419 if (*pSrc == '"') *pDst++ = '"'; /* need to add double double quote (see RFC4180) */
4420 *pDst++ = *pSrc++;
4421 }
4422 *pDst++ = '"'; /* ending quote */
4423 *pDst = '\0';
4424 if (*pbMustBeFreed == 1) free(pRes);
4425 pRes = pBStart;
4426 bufLen = -1;
4427 *pbMustBeFreed = 1;
4428 } else if (pTpe->data.field.options.bJSON) {
4429 jsonEncode(&pRes, pbMustBeFreed, &bufLen, RSTRUE);
4430 } else if (pTpe->data.field.options.bJSONf) {
4431 jsonField(pTpe, &pRes, pbMustBeFreed, &bufLen, RSTRUE);
4432 } else if (pTpe->data.field.options.bJSONr) {
4433 jsonEncode(&pRes, pbMustBeFreed, &bufLen, RSFALSE);
4434 } else if (pTpe->data.field.options.bJSONfr) {
4435 jsonField(pTpe, &pRes, pbMustBeFreed, &bufLen, RSFALSE);
4436 }
4437
4438 *pPropLen = (bufLen == -1) ? (int)ustrlen(pRes) : bufLen;
4439
4440 return (pRes);
4441 }
4442
4443 /* Set a single property based on the JSON object provided. The
4444 * property name is extracted from the JSON object.
4445 */
4446 static rsRetVal msgSetPropViaJSON(smsg_t *__restrict__ const pMsg,
4447 const char *name,
4448 struct json_object *json,
4449 int sharedReference) {
4450 const char *psz;
4451 int val;
4452 prop_t *propFromHost = NULL;
4453 prop_t *propRcvFromIP = NULL;
4454 int bNeedFree = 1;
4455 DEFiRet;
4456
4457 /* note: jsonToString() manages the memory of the returned
4458 * string. So we MUST NOT free it!
4459 */
4460 dbgprintf("DDDD: msgSetPropViaJSON key: '%s'\n", name);
4461 if (!strcmp(name, "rawmsg")) {
4462 psz = jsonToString(json);
4463 MsgSetRawMsg(pMsg, psz, strlen(psz));
4464 } else if (!strcmp(name, "msg")) {
4465 psz = jsonToString(json);
4466 MsgReplaceMSG(pMsg, (const uchar *)psz, strlen(psz));
4467 } else if (!strcmp(name, "syslogtag")) {
4468 psz = jsonToString(json);
4469 MsgSetTAG(pMsg, (const uchar *)psz, strlen(psz));
4470 } else if (!strcmp(name, "pri")) {
4471 val = json_object_get_int(json);
4472 msgSetPRI(pMsg, val);
4473 } else if (!strcmp(name, "syslogfacility")) {
4474 val = json_object_get_int(json);
4475 if (val >= 0 && val <= 24)
4476 pMsg->iFacility = val;
4477 else
4478 DBGPRINTF("mmexternal: invalid fac %d requested -- ignored\n", val);
4479 } else if (!strcmp(name, "syslogseverity")) {
4480 val = json_object_get_int(json);
4481 if (val >= 0 && val <= 7)
4482 pMsg->iSeverity = val;
4483 else
4484 DBGPRINTF("mmexternal: invalid fac %d requested -- ignored\n", val);
4485 } else if (!strcmp(name, "procid")) {
4486 psz = jsonToString(json);
4487 MsgSetPROCID(pMsg, psz);
4488 } else if (!strcmp(name, "msgid")) {
4489 psz = jsonToString(json);
4490 MsgSetMSGID(pMsg, psz);
4491 } else if (!strcmp(name, "structured-data")) {
4492 psz = jsonToString(json);
4493 MsgSetStructuredData(pMsg, psz);
4494 } else if (!strcmp(name, "hostname") || !strcmp(name, "source")) {
4495 psz = jsonToString(json);
4496 MsgSetHOSTNAME(pMsg, (const uchar *)psz, strlen(psz));
4497 } else if (!strcmp(name, "fromhost")) {
4498 psz = jsonToString(json);
4499 MsgSetRcvFromStr(pMsg, (const uchar *)psz, strlen(psz), &propFromHost);
4500 prop.Destruct(&propFromHost);
4501 } else if (!strcmp(name, "fromhost-ip")) {
4502 psz = jsonToString(json);
4503 MsgSetRcvFromIPStr(pMsg, (const uchar *)psz, strlen(psz), &propRcvFromIP);
4504 prop.Destruct(&propRcvFromIP);
4505 } else if (!strcmp(name, "$!")) {
4506 /* msgAddJSON expects that it can keep the object without incremeting
4507 * the json reference count. So we MUST NOT free (_put) the object in
4508 * this case. -- rgerhards, 2018-09-14
4509 */
4510 bNeedFree = 0;
4511 msgAddJSON(pMsg, (uchar *)"!", json, 0, sharedReference);
4512 } else {
4513 /* we ignore unknown properties */
4514 DBGPRINTF("msgSetPropViaJSON: unkonwn property ignored: %s\n", name);
4515 }
4516
4517 if (bNeedFree) {
4518 json_object_put(json);
4519 }
4520
4521 RETiRet;
4522 }
4523
4524
4525 /* set message properties based on JSON string. This function does it all,
4526 * including parsing the JSON string. If an error is detected, the operation
4527 * is aborted at the time of error. Any modifications made before the
4528 * error ocurs are still PERSISTED.
4529 * This function is meant to support the external message modifiction module
4530 * interface. As such, replacing properties is expressively permited. Note that
4531 * properties which were derived from the message during parsing are NOT
4532 * updated if the underlying (raw)msg property is changed.
4533 */
4534 rsRetVal MsgSetPropsViaJSON(smsg_t *__restrict__ const pMsg, const uchar *__restrict__ const jsonstr) {
4535 struct json_tokener *tokener = NULL;
4536 struct json_object *json;
4537 const char *errMsg;
4538 DEFiRet;
4539
4540 DBGPRINTF("DDDDDD: JSON string for message mod: '%s'\n", jsonstr);
4541 if (!strcmp((char *)jsonstr, "{}")) /* shortcut for a common case */
4542 FINALIZE;
4543
4544 tokener = json_tokener_new();
4545
4546 json = json_tokener_parse_ex(tokener, (char *)jsonstr, ustrlen(jsonstr));
4547 if (Debug) {
4548 errMsg = NULL;
4549 if (json == NULL) {
4550 enum json_tokener_error err;
4551
4552 err = tokener->err;
4553 if (err != json_tokener_continue)
4554 errMsg = json_tokener_error_desc(err);
4555 else
4556 errMsg = "Unterminated input";
4557 } else if (!json_object_is_type(json, json_type_object))
4558 errMsg = "JSON value is not an object";
4559 if (errMsg != NULL) {
4560 DBGPRINTF("MsgSetPropsViaJSON: Error parsing JSON '%s': %s\n", jsonstr, errMsg);
4561 }
4562 }
4563 if (json == NULL || !json_object_is_type(json, json_type_object)) {
4564 ABORT_FINALIZE(RS_RET_JSON_UNUSABLE);
4565 }
4566 MsgSetPropsViaJSON_Object(pMsg, json);
4567
4568 finalize_it:
4569 if (tokener != NULL) json_tokener_free(tokener);
4570 RETiRet;
4571 }
4572
4573
4574 /* Used by MsgSetPropsViaJSON to set properties.
4575 * The same as MsgSetPropsViaJSON only that a json object is given and not a string
4576 */
4577 rsRetVal MsgSetPropsViaJSON_Object(smsg_t *__restrict__ const pMsg, struct json_object *json) {
4578 DEFiRet;
4579 if (json == NULL || !json_object_is_type(json, json_type_object)) {
4580 DBGPRINTF("MsgSetPropsViaJSON_Object: json NULL or not object type\n");
4581 ABORT_FINALIZE(RS_RET_JSON_UNUSABLE);
4582 }
4583 struct json_object_iterator it = json_object_iter_begin(json);
4584 struct json_object_iterator itEnd = json_object_iter_end(json);
4585 while (!json_object_iter_equal(&it, &itEnd)) {
4586 struct json_object *child = json_object_iter_peek_value(&it);
4587 json_object_get(child);
4588 msgSetPropViaJSON(pMsg, json_object_iter_peek_name(&it), child, 0);
4589 json_object_iter_next(&it);
4590 }
4591 json_object_put(json);
4592
4593 finalize_it:
4594 RETiRet;
4595 }
4596
4597
4598 /* get the severity - this is an entry point that
4599 * satisfies the base object class getSeverity semantics.
4600 * rgerhards, 2008-01-14
4601 */
4602 rsRetVal MsgGetSeverity(smsg_t *const pMsg, int *piSeverity) {
4603 *piSeverity = pMsg->iSeverity;
4604 return RS_RET_OK;
4605 }
4606
4607
4608 static uchar *jsonPathGetLeaf(uchar *name, int lenName) {
4609 int i;
4610 for (i = lenName; i >= 0; --i)
4611 if (i == 0) {
4612 if (name[0] == '!' || name[0] == '.' || name[0] == '/') break;
4613 } else {
4614 if (name[i] == '!') break;
4615 }
4616 if (name[i] == '!' || name[i] == '.' || name[i] == '/') ++i;
4617 return name + i;
4618 }
4619
4620 static json_bool jsonVarExtract(struct json_object *root, const char *key, struct json_object **value) {
4621 char namebuf[MAX_VARIABLE_NAME_LEN];
4622 int key_len = strlen(key);
4623 char *array_idx_start = strstr(key, "[");
4624 char *array_idx_end = NULL;
4625 char *array_idx_num_end_discovered = NULL;
4626 struct json_object *arr = NULL;
4627 if (array_idx_start != NULL) {
4628 array_idx_end = strstr(array_idx_start, "]");
4629 }
4630 if (array_idx_end != NULL && (array_idx_end - key + 1) == key_len) {
4631 errno = 0;
4632 int idx = (int)strtol(array_idx_start + 1, &array_idx_num_end_discovered, 10);
4633 if (errno == 0 && array_idx_num_end_discovered == array_idx_end) {
4634 memcpy(namebuf, key, array_idx_start - key);
4635 namebuf[array_idx_start - key] = '\0';
4636 json_bool found_obj = json_object_object_get_ex(root, namebuf, &arr);
4637 if (found_obj && json_object_is_type(arr, json_type_array)) {
4638 int len = json_object_array_length(arr);
4639 if (len > idx) {
4640 *value = json_object_array_get_idx(arr, idx);
4641 if (*value != NULL) return TRUE;
4642 }
4643 return FALSE;
4644 }
4645 }
4646 }
4647 return json_object_object_get_ex(root, key, value);
4648 }
4649
4650
4651 static rsRetVal jsonPathFindNext(
4652 struct json_object *root, uchar *namestart, uchar **name, uchar *leaf, struct json_object **found, int bCreate) {
4653 uchar namebuf[MAX_VARIABLE_NAME_LEN];
4654 struct json_object *json;
4655 size_t i;
4656 uchar *p = *name;
4657 DEFiRet;
4658
4659 if (*p == '!' || (*name == namestart && (*p == '.' || *p == '/'))) ++p;
4660 for (i = 0;
4661 *p && !(p == namestart && (*p == '.' || *p == '/')) && *p != '!' && p != leaf && i < sizeof(namebuf) - 1;
4662 ++i, ++p)
4663 namebuf[i] = *p;
4664 if (i > 0) {
4665 namebuf[i] = '\0';
4666 if (jsonVarExtract(root, (char *)namebuf, &json) == FALSE) {
4667 json = NULL;
4668 }
4669 } else
4670 json = root;
4671 if (json == NULL) {
4672 if (!bCreate) {
4673 ABORT_FINALIZE(RS_RET_JNAME_INVALID);
4674 } else {
4675 if (json_object_get_type(root) != json_type_object) {
4676 DBGPRINTF(
4677 "jsonPathFindNext with bCreate: not a container in json path, "
4678 "name is '%s'\n",
4679 namestart);
4680 ABORT_FINALIZE(RS_RET_INVLD_SETOP);
4681 }
4682 json = json_object_new_object();
4683 json_object_object_add(root, (char *)namebuf, json);
4684 }
4685 }
4686
4687 *name = p;
4688 *found = json;
4689 finalize_it:
4690 RETiRet;
4691 }
4692
4693 static rsRetVal jsonPathFindParent(
4694 struct json_object *jroot, uchar *name, uchar *leaf, struct json_object **parent, const int bCreate) {
4695 uchar *namestart;
4696 DEFiRet;
4697 namestart = name;
4698 *parent = jroot;
4699 while (name < leaf - 1) {
4700 CHKiRet(jsonPathFindNext(*parent, namestart, &name, leaf, parent, bCreate));
4701 }
4702 if (*parent == NULL) ABORT_FINALIZE(RS_RET_NOT_FOUND);
4703 finalize_it:
4704 RETiRet;
4705 }
4706
4707 static rsRetVal jsonMerge(struct json_object *existing, struct json_object *json) {
4708 DEFiRet;
4709
4710 struct json_object_iterator it = json_object_iter_begin(json);
4711 struct json_object_iterator itEnd = json_object_iter_end(json);
4712 while (!json_object_iter_equal(&it, &itEnd)) {
4713 json_object_object_add(existing, json_object_iter_peek_name(&it),
4714 json_object_get(json_object_iter_peek_value(&it)));
4715 json_object_iter_next(&it);
4716 }
4717 /* note: json-c does ref counting. We added all descandants refcounts
4718 * in the loop above. So when we now free(_put) the root object, only
4719 * root gets freed().
4720 */
4721 json_object_put(json);
4722 RETiRet;
4723 }
4724
4725 /* find a JSON structure element (field or container doesn't matter). */
4726 rsRetVal jsonFind(smsg_t *const pMsg, msgPropDescr_t *pProp, struct json_object **jsonres) {
4727 uchar *leaf;
4728 struct json_object *parent;
4729 struct json_object *field;
4730 struct json_object **jroot = NULL;
4731 pthread_mutex_t *mut = NULL;
4732 DEFiRet;
4733
4734 CHKiRet(getJSONRootAndMutex(pMsg, pProp->id, &jroot, &mut));
4735 pthread_mutex_lock(mut);
4736
4737 if (*jroot == NULL) {
4738 field = NULL;
4739 FINALIZE;
4740 }
4741
4742 if (!strcmp((char *)pProp->name, "!")) {
4743 field = *jroot;
4744 } else if (!strcmp((char *)pProp->name, ".")) {
4745 field = *jroot;
4746 } else {
4747 leaf = jsonPathGetLeaf(pProp->name, pProp->nameLen);
4748 CHKiRet(jsonPathFindParent(*jroot, pProp->name, leaf, &parent, 0));
4749 if (jsonVarExtract(parent, (char *)leaf, &field) == FALSE) field = NULL;
4750 }
4751 *jsonres = field;
4752
4753 finalize_it:
4754 if (mut != NULL) pthread_mutex_unlock(mut);
4755 RETiRet;
4756 }
4757
4758 /* check if JSON variable exists (works on terminal var and container) */
4759 rsRetVal ATTR_NONNULL() msgCheckVarExists(smsg_t *const pMsg, msgPropDescr_t *pProp) {
4760 struct json_object *jsonres = NULL;
4761 DEFiRet;
4762
4763 CHKiRet(jsonFind(pMsg, pProp, &jsonres));
4764 if (jsonres == NULL) {
4765 iRet = RS_RET_NOT_FOUND;
4766 }
4767
4768 finalize_it:
4769 RETiRet;
4770 }
4771
4772 rsRetVal msgAddJSON(smsg_t *const pM, uchar *name, struct json_object *json, int force_reset, int sharedReference) {
4773 /* TODO: error checks! This is a quick&dirty PoC! */
4774 struct json_object **jroot;
4775 struct json_object *parent, *leafnode;
4776 struct json_object *given = NULL;
4777 uchar *leaf;
4778 pthread_mutex_t *mut = NULL;
4779 DEFiRet;
4780
4781 CHKiRet(getJSONRootAndMutexByVarChar(pM, name[0], &jroot, &mut));
4782 pthread_mutex_lock(mut);
4783
4784 if (name[0] == '/') { /* globl var special handling */
4785 if (sharedReference) {
4786 given = json;
4787 json = jsonDeepCopy(json);
4788 json_object_put(given);
4789 }
4790 }
4791
4792 if (name[1] == '\0') { /* full tree? */
4793 if (*jroot == NULL)
4794 *jroot = json;
4795 else
4796 CHKiRet(jsonMerge(*jroot, json));
4797 } else {
4798 if (*jroot == NULL) {
4799 /* now we need a root obj */
4800 *jroot = json_object_new_object();
4801 }
4802 leaf = jsonPathGetLeaf(name, ustrlen(name));
4803 iRet = jsonPathFindParent(*jroot, name, leaf, &parent, 1);
4804 if (unlikely(iRet != RS_RET_OK)) {
4805 json_object_put(json);
4806 FINALIZE;
4807 }
4808 if (json_object_get_type(parent) != json_type_object) {
4809 DBGPRINTF(
4810 "msgAddJSON: not a container in json path,"
4811 "name is '%s'\n",
4812 name);
4813 json_object_put(json);
4814 ABORT_FINALIZE(RS_RET_INVLD_SETOP);
4815 }
4816 if (jsonVarExtract(parent, (char *)leaf, &leafnode) == FALSE) leafnode = NULL;
4817 /* json-c code indicates we can simply replace a
4818 * json type. Unfortunaltely, this is not documented
4819 * as part of the interface spec. We still use it,
4820 * because it speeds up processing. If it does not work
4821 * at some point, use
4822 * json_object_object_del(parent, (char*)leaf);
4823 * before adding. rgerhards, 2012-09-17
4824 */
4825 if (force_reset || (leafnode == NULL)) {
4826 json_object_object_add(parent, (char *)leaf, json);
4827 } else {
4828 if (json_object_get_type(json) == json_type_object) {
4829 CHKiRet(jsonMerge(*jroot, json));
4830 } else {
4831 /* TODO: improve the code below, however, the current
4832 * state is not really bad */
4833 if (json_object_get_type(leafnode) == json_type_object) {
4834 DBGPRINTF(
4835 "msgAddJSON: trying to update a container "
4836 "node with a leaf, name is %s - "
4837 "forbidden",
4838 name);
4839 json_object_put(json);
4840 ABORT_FINALIZE(RS_RET_INVLD_SETOP);
4841 }
4842 json_object_object_add(parent, (char *)leaf, json);
4843 }
4844 }
4845 }
4846
4847 finalize_it:
4848 if (mut != NULL) pthread_mutex_unlock(mut);
4849 RETiRet;
4850 }
4851
4852
4853 rsRetVal msgDelJSON(smsg_t *const pM, uchar *name) {
4854 struct json_object **jroot;
4855 struct json_object *parent, *leafnode;
4856 uchar *leaf;
4857 pthread_mutex_t *mut = NULL;
4858 DEFiRet;
4859
4860 CHKiRet(getJSONRootAndMutexByVarChar(pM, name[0], &jroot, &mut));
4861 pthread_mutex_lock(mut);
4862
4863 if (*jroot == NULL) {
4864 DBGPRINTF("msgDelJSONVar; jroot empty in unset for property %s\n", name);
4865 FINALIZE;
4866 }
4867
4868 if (name[1] == '\0') {
4869 /* full tree! Strange, but I think we should permit this. After all,
4870 * we trust rsyslog.conf to be written by the admin.
4871 */
4872 DBGPRINTF("unsetting JSON root object\n");
4873 json_object_put(*jroot);
4874 *jroot = NULL;
4875 } else {
4876 leaf = jsonPathGetLeaf(name, ustrlen(name));
4877 CHKiRet(jsonPathFindParent(*jroot, name, leaf, &parent, 0));
4878 if (jsonVarExtract(parent, (char *)leaf, &leafnode) == FALSE) leafnode = NULL;
4879 if (leafnode == NULL) {
4880 DBGPRINTF("unset JSON: could not find '%s'\n", name);
4881 ABORT_FINALIZE(RS_RET_JNAME_NOTFOUND);
4882 } else {
4883 DBGPRINTF(
4884 "deleting JSON value path '%s', "
4885 "leaf '%s', type %d\n",
4886 name, leaf, json_object_get_type(leafnode));
4887 json_object_object_del(parent, (char *)leaf);
4888 }
4889 }
4890
4891 finalize_it:
4892 if (mut != NULL) pthread_mutex_unlock(mut);
4893 RETiRet;
4894 }
4895
4896 /* add Metadata to the message. This is stored in a special JSON
4897 * container. Note that only string types are currently supported,
4898 * what should pose absolutely no problem with the string-ish nature
4899 * of rsyslog metadata.
4900 * added 2015-01-09 rgerhards
4901 */
4902 rsRetVal msgAddMetadata(smsg_t *const __restrict__ pMsg,
4903 uchar *const __restrict__ metaname,
4904 uchar *const __restrict__ metaval) {
4905 DEFiRet;
4906 struct json_object *const json = json_object_new_object();
4907 CHKmalloc(json);
4908 struct json_object *const jval = json_object_new_string((char *)metaval);
4909 if (jval == NULL) {
4910 json_object_put(json);
4911 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
4912 }
4913 json_object_object_add(json, (const char *const)metaname, jval);
4914 iRet = msgAddJSON(pMsg, (uchar *)"!metadata", json, 0, 0);
4915 finalize_it:
4916 RETiRet;
4917 }
4918
4919 rsRetVal msgAddMultiMetadata(smsg_t *const __restrict__ pMsg,
4920 const uchar **__restrict__ metaname,
4921 const uchar **__restrict__ metaval,
4922 const int count) {
4923 DEFiRet;
4924 int i = 0;
4925 struct json_object *const json = json_object_new_object();
4926 CHKmalloc(json);
4927 for (i = 0; i < count; i++) {
4928 struct json_object *const jval = json_object_new_string((char *)metaval[i]);
4929 if (jval == NULL) {
4930 json_object_put(json);
4931 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
4932 }
4933 json_object_object_add(json, (const char *const)metaname[i], jval);
4934 }
4935 iRet = msgAddJSON(pMsg, (uchar *)"!metadata", json, 0, 0);
4936 finalize_it:
4937 RETiRet;
4938 }
4939
4940 struct json_object *jsonDeepCopy(struct json_object *src) {
4941 struct json_object *dst = NULL, *json;
4942 int arrayLen, i;
4943
4944 if (src == NULL) goto done;
4945
4946 switch (json_object_get_type(src)) {
4947 case json_type_boolean:
4948 dst = json_object_new_boolean(json_object_get_boolean(src));
4949 break;
4950 case json_type_double:
4951 dst = json_object_new_double(json_object_get_double(src));
4952 break;
4953 case json_type_int:
4954 dst = json_object_new_int64(json_object_get_int64(src));
4955 break;
4956 case json_type_string:
4957 dst = json_object_new_string(jsonToString(src));
4958 break;
4959 case json_type_object:
4960 dst = json_object_new_object();
4961 struct json_object_iterator it = json_object_iter_begin(src);
4962 struct json_object_iterator itEnd = json_object_iter_end(src);
4963 while (!json_object_iter_equal(&it, &itEnd)) {
4964 json = jsonDeepCopy(json_object_iter_peek_value(&it));
4965 json_object_object_add(dst, json_object_iter_peek_name(&it), json);
4966 json_object_iter_next(&it);
4967 }
4968 break;
4969 case json_type_array:
4970 arrayLen = json_object_array_length(src);
4971 dst = json_object_new_array();
4972 for (i = 0; i < arrayLen; ++i) {
4973 json = json_object_array_get_idx(src, i);
4974 json = jsonDeepCopy(json);
4975 json_object_array_add(dst, json);
4976 }
4977 break;
4978 case json_type_null:
4979 default:
4980 DBGPRINTF("jsonDeepCopy(): error unknown type %d\n", json_object_get_type(src));
4981 dst = NULL;
4982 break;
4983 }
4984 done:
4985 return dst;
4986 }
4987
4988
4989 rsRetVal msgSetJSONFromVar(smsg_t *const pMsg, uchar *varname, struct svar *v, int force_reset) {
4990 struct json_object *json = NULL;
4991 char *cstr;
4992 DEFiRet;
4993 switch (v->datatype) {
4994 case 'S': /* string */
4995 CHKmalloc(cstr = es_str2cstr(v->d.estr, NULL));
4996 json = json_object_new_string(cstr);
4997 free(cstr);
4998 break;
4999 case 'N': /* number (integer) */
5000 json = json_object_new_int64(v->d.n);
5001 break;
5002 case 'J': /* native JSON */
5003 json = jsonDeepCopy(v->d.json);
5004 break;
5005 default:
5006 DBGPRINTF("msgSetJSONFromVar: unsupported datatype %c\n", v->datatype);
5007 ABORT_FINALIZE(RS_RET_ERR);
5008 }
5009
5010 msgAddJSON(pMsg, varname, json, force_reset, 0);
5011 finalize_it:
5012 RETiRet;
5013 }
5014
5015 rsRetVal MsgAddToStructuredData(smsg_t *const pMsg, uchar *toadd, rs_size_t len) {
5016 uchar *newptr;
5017 rs_size_t newlen;
5018 int empty;
5019 DEFiRet;
5020 empty = pMsg->pszStrucData == NULL || pMsg->pszStrucData[0] == '-';
5021 newlen = (empty) ? len : pMsg->lenStrucData + len;
5022 CHKmalloc(newptr = (uchar *)realloc(pMsg->pszStrucData, newlen + 1));
5023 if (empty) {
5024 memcpy(newptr, toadd, len);
5025 } else {
5026 memcpy(newptr + pMsg->lenStrucData, toadd, len);
5027 }
5028 pMsg->pszStrucData = newptr;
5029 pMsg->pszStrucData[newlen] = '\0';
5030 pMsg->lenStrucData = newlen;
5031 finalize_it:
5032 RETiRet;
5033 }
5034
5035
5036 /* Fill a message propert description. Space must already be alloced
5037 * by the caller. This is for efficiency, as we expect this to happen
5038 * as part of a larger structure alloc.
5039 * Note that CEE/LOCAL_VAR properties can come in either as
5040 * "$!xx"/"$.xx" or "!xx"/".xx" - we will unify them here.
5041 */
5042 rsRetVal msgPropDescrFill(msgPropDescr_t *pProp, uchar *name, int nameLen) {
5043 propid_t id;
5044 int offs;
5045 DEFiRet;
5046 if (propNameToID(name, &id) != RS_RET_OK) {
5047 parser_errmsg("invalid property '%s'", name);
5048 /* now try to find some common error causes */
5049 if (!strcasecmp((char *)name, "myhostname"))
5050 parser_errmsg(
5051 "did you mean '$myhostname' instead of '%s'? "
5052 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5053 name);
5054 else if (!strcasecmp((char *)name, "bom"))
5055 parser_errmsg(
5056 "did you mean '$bom' instead of '%s'?"
5057 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5058 name);
5059 else if (!strcasecmp((char *)name, "now"))
5060 parser_errmsg(
5061 "did you mean '$now' instead of '%s'?"
5062 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5063 name);
5064 else if (!strcasecmp((char *)name, "year"))
5065 parser_errmsg(
5066 "did you mean '$year' instead of '%s'?"
5067 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5068 name);
5069 else if (!strcasecmp((char *)name, "month"))
5070 parser_errmsg(
5071 "did you mean '$month' instead of '%s'?"
5072 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5073 name);
5074 else if (!strcasecmp((char *)name, "day"))
5075 parser_errmsg(
5076 "did you mean '$day' instead of '%s'?"
5077 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5078 name);
5079 else if (!strcasecmp((char *)name, "hour"))
5080 parser_errmsg(
5081 "did you mean '$hour' instead of '%s'?"
5082 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5083 name);
5084 else if (!strcasecmp((char *)name, "hhour"))
5085 parser_errmsg(
5086 "did you mean '$hhour' instead of '%s'?"
5087 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5088 name);
5089 else if (!strcasecmp((char *)name, "qhour"))
5090 parser_errmsg(
5091 "did you mean '$qhour' instead of '%s'?"
5092 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5093 name);
5094 else if (!strcasecmp((char *)name, "minute"))
5095 parser_errmsg(
5096 "did you mean '$minute' instead of '%s'?"
5097 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5098 name);
5099 else if (!strcasecmp((char *)name, "now-utc"))
5100 parser_errmsg(
5101 "did you mean '$now-utc' instead of '%s'?"
5102 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5103 name);
5104 else if (!strcasecmp((char *)name, "year-utc"))
5105 parser_errmsg(
5106 "did you mean '$year-utc' instead of '%s'?"
5107 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5108 name);
5109 else if (!strcasecmp((char *)name, "month-utc"))
5110 parser_errmsg(
5111 "did you mean '$month-utc' instead of '%s'?"
5112 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5113 name);
5114 else if (!strcasecmp((char *)name, "day-utc"))
5115 parser_errmsg(
5116 "did you mean '$day-utc' instead of '%s'?"
5117 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5118 name);
5119 else if (!strcasecmp((char *)name, "hour-utc"))
5120 parser_errmsg(
5121 "did you mean '$hour-utc' instead of '%s'?"
5122 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5123 name);
5124 else if (!strcasecmp((char *)name, "hhour-utc"))
5125 parser_errmsg(
5126 "did you mean '$hhour-utc' instead of '%s'?"
5127 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5128 name);
5129 else if (!strcasecmp((char *)name, "qhour-utc"))
5130 parser_errmsg(
5131 "did you mean '$qhour-utc' instead of '%s'?"
5132 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5133 name);
5134 else if (!strcasecmp((char *)name, "minute-utc"))
5135 parser_errmsg(
5136 "did you mean '$minute-utc' instead of '%s'?"
5137 "See also: https://www.rsyslog.com/rsyslog-info-1/",
5138 name);
5139 ABORT_FINALIZE(RS_RET_INVLD_PROP);
5140 }
5141 if (id == PROP_CEE || id == PROP_LOCAL_VAR || id == PROP_GLOBAL_VAR) {
5142 /* in these cases, we need the field name for later processing */
5143 /* normalize name: remove $ if present */
5144 offs = (name[0] == '$') ? 1 : 0;
5145 pProp->name = ustrdup(name + offs);
5146 pProp->nameLen = nameLen - offs;
5147 /* we patch the root name, so that support functions do not need to
5148 * check for different root chars. */
5149 pProp->name[0] = '!';
5150 }
5151 pProp->id = id;
5152 finalize_it:
5153 RETiRet;
5154 }
5155
5156 void msgPropDescrDestruct(msgPropDescr_t *pProp) {
5157 if (pProp != NULL) {
5158 if (pProp->id == PROP_CEE || pProp->id == PROP_LOCAL_VAR || pProp->id == PROP_GLOBAL_VAR) free(pProp->name);
5159 }
5160 }
5161
5162
5163 /* dummy */
5164 static rsRetVal msgQueryInterface(interface_t __attribute__((unused)) * i) {
5165 return RS_RET_NOT_IMPLEMENTED;
5166 }
5167
5168 /* Initialize the message class. Must be called as the very first method
5169 * before anything else is called inside this class.
5170 * rgerhards, 2008-01-04
5171 */
5172 BEGINObjClassInit(msg, 1, OBJ_IS_CORE_MODULE)
5173 pthread_mutex_init(&glblVars_lock, NULL);
5174
5175 /* request objects we use */
5176 CHKiRet(objUse(datetime, CORE_COMPONENT));
5177 CHKiRet(objUse(glbl, CORE_COMPONENT));
5178 CHKiRet(objUse(prop, CORE_COMPONENT));
5179 CHKiRet(objUse(var, CORE_COMPONENT));
5180
5181 /* set our own handlers */
5182 OBJSetMethodHandler(objMethod_SERIALIZE, MsgSerialize);
5183 /* some more inits */
5184 #ifdef HAVE_MALLOC_TRIM
5185 INIT_ATOMIC_HELPER_MUT(mutTrimCtr);
5186 #endif
5187 ENDObjClassInit(msg)