Debian Codegraph @

runtime/tcps_sess.c

raw
1 /* tcps_sess.c
2 *
3 * This implements a session of the tcpsrv object. For general
4 * comments, see header of tcpsrv.c.
5 *
6 * NOTE: read comments in module-template.h to understand how this file
7 * works!
8 *
9 * File begun on 2008-03-01 by RGerhards (extracted from tcpsrv.c, which
10 * based on the BSD-licensed syslogd.c)
11 *
12 * Copyright 2007-2026 Adiscon GmbH.
13 *
14 * This file is part of rsyslog.
15 *
16 * Licensed under the Apache License, Version 2.0 (the "License");
17 * you may not use this file except in compliance with the License.
18 * You may obtain a copy of the License at
19 *
20 * http://www.apache.org/licenses/LICENSE-2.0
21 * -or-
22 * see COPYING.ASL20 in the source distribution
23 *
24 * Unless required by applicable law or agreed to in writing, software
25 * distributed under the License is distributed on an "AS IS" BASIS,
26 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27 * See the License for the specific language governing permissions and
28 * limitations under the License.
29 */
30 #include "config.h"
31 #include <limits.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <assert.h>
35 #include <errno.h>
36 #include <ctype.h>
37
38 #include "rsyslog.h"
39 #include "dirty.h"
40 #include "unicode-helper.h"
41 #include "module-template.h"
42 #include "net.h"
43 #include "tcpsrv.h"
44 #include "tcps_sess.h"
45 #include "obj.h"
46 #include "errmsg.h"
47 #include "netstrm.h"
48 #include "template.h"
49 #include "wti.h"
50 #include "msg.h"
51 #include "datetime.h"
52 #include "prop.h"
53 #include "parser.h"
54 #include "ratelimit.h"
55 #include "debug.h"
56 #include "rsconf.h"
57
58 static rsRetVal ensurePerSourceKeyBuf(actWrkrIParams_t *param, size_t need) {
59 uchar *pNewBuf;
60 size_t iNewSize;
61 DEFiRet;
62
63 if (param->lenBuf >= need + 1) {
64 RETiRet;
65 }
66
67 iNewSize = ((need + 1) / 128 + 1) * 128;
68 CHKmalloc(pNewBuf = (uchar *)realloc(param->param, iNewSize));
69 param->param = pNewBuf;
70 param->lenBuf = iNewSize;
71
72 finalize_it:
73 RETiRet;
74 }
75
76
77 /* static data */
78 DEFobjStaticHelpers;
79 DEFobjCurrIf(glbl);
80 DEFobjCurrIf(netstrm);
81 DEFobjCurrIf(prop);
82 DEFobjCurrIf(datetime);
83 DEFobjCurrIf(regexp);
84 DEFobjCurrIf(parser)
85
86
87 /* forward definitions */
88 static rsRetVal Close(tcps_sess_t *pThis);
89
90
91 /* Standard-Constructor */
92 BEGINobjConstruct(tcps_sess) /* be sure to specify the object type also in END macro! */
93 size_t bufSize;
94
95 pThis->iMsg = 0; /* just make sure... */
96 pThis->iMaxLine = glbl.GetMaxLine(runConf);
97 pThis->inputState = eAtStrtFram; /* indicate frame header expected */
98 pThis->eFraming = TCP_FRAMING_OCTET_STUFFING; /* just make sure... */
99 pthread_mutex_init(&pThis->mut, NULL);
100 pThis->fromHost = NULL;
101 pThis->fromHostIP = NULL;
102 pThis->fromHostPort = NULL;
103 pThis->iCurrLine = 0;
104 pThis->pMsg_save = NULL;
105 pThis->tlsProbeBytes = 0;
106 pThis->tlsProbeDone = 0;
107 pThis->tlsMismatchWarned = 0;
108 memset(pThis->tlsProbeBuf, 0, sizeof(pThis->tlsProbeBuf));
109 wtiInitIParam(&pThis->perSourceKeyParam);
110 /* now allocate the message reception buffer */
111 bufSize = (size_t)pThis->iMaxLine + 1;
112 CHKmalloc(pThis->pMsg = (uchar *)malloc(bufSize));
113 finalize_it:
114 ENDobjConstruct(tcps_sess)
115
116
117 /* ConstructionFinalizer
118 */
119 static rsRetVal tcps_sessConstructFinalize(tcps_sess_t *pThis) {
120 DEFiRet;
121 ISOBJ_TYPE_assert(pThis, tcps_sess);
122 #ifdef FEATURE_REGEXP
123 if (pThis->pLstnInfo->bHasStartRegex) {
124 size_t regexBufSize;
125
126 if (pThis->iMaxLine > (INT_MAX - 1) / 2) {
127 LogError(0, RS_RET_ERR,
128 "imtcp: framing.delimiter.regex requires maxMessageSize <= %d to avoid session buffer overflow",
129 (INT_MAX - 1) / 2);
130 ABORT_FINALIZE(RS_RET_ERR);
131 }
132 regexBufSize = ((size_t)pThis->iMaxLine * 2) + 1;
133 /* in this case, we need a second buffer and a larger primary one */
134 CHKmalloc(pThis->pMsg = (uchar *)realloc(pThis->pMsg, regexBufSize));
135 CHKmalloc(pThis->pMsg_save = (uchar *)malloc(regexBufSize));
136 }
137 #endif
138 if (pThis->pSrv->OnSessConstructFinalize != NULL) {
139 CHKiRet(pThis->pSrv->OnSessConstructFinalize(&pThis->pUsr));
140 }
141
142 finalize_it:
143 RETiRet;
144 }
145
146
147 /* destructor for the tcps_sess object */
148 BEGINobjDestruct(tcps_sess) /* be sure to specify the object type also in END and CODESTART macros! */
149 CODESTARTobjDestruct(tcps_sess);
150 if (pThis->pStrm != NULL) netstrm.Destruct(&pThis->pStrm);
151
152 if (pThis->pSrv->pOnSessDestruct != NULL) {
153 pThis->pSrv->pOnSessDestruct(&pThis->pUsr);
154 }
155 pthread_mutex_destroy(&pThis->mut);
156 /* now destruct our own properties */
157 if (pThis->fromHost != NULL) CHKiRet(prop.Destruct(&pThis->fromHost));
158 if (pThis->fromHostIP != NULL) CHKiRet(prop.Destruct(&pThis->fromHostIP));
159 if (pThis->fromHostPort != NULL) CHKiRet(prop.Destruct(&pThis->fromHostPort));
160 free(pThis->perSourceKeyParam.param);
161 free(pThis->pMsg);
162 free(pThis->pMsg_save);
163 ENDobjDestruct(tcps_sess)
164
165
166 /* debugprint for the tcps_sess object */
167 BEGINobjDebugPrint(tcps_sess) /* be sure to specify the object type also in END and CODESTART macros! */
168 CODESTARTobjDebugPrint(tcps_sess);
169 ENDobjDebugPrint(tcps_sess)
170
171
172 /* set property functions */
173 /* set the hostname. Note that the caller *hands over* the string. That is,
174 * the caller no longer controls it once SetHost() has received it. Most importantly,
175 * the caller must not free it. -- rgerhards, 2008-04-24
176 */
177 static rsRetVal SetHost(tcps_sess_t *pThis, uchar *pszHost) {
178 DEFiRet;
179
180 ISOBJ_TYPE_assert(pThis, tcps_sess);
181
182 if (pThis->fromHost == NULL) CHKiRet(prop.Construct(&pThis->fromHost));
183
184 CHKiRet(prop.SetString(pThis->fromHost, pszHost, ustrlen(pszHost)));
185
186 finalize_it:
187 free(pszHost); /* we must free according to our (old) calling conventions */
188 RETiRet;
189 }
190
191 /* set the remote host's IP. Note that the caller *hands over* the property. That is,
192 * the caller no longer controls it once SetHostIP() has received it. Most importantly,
193 * the caller must not destruct it. -- rgerhards, 2008-05-16
194 */
195 static rsRetVal SetHostIP(tcps_sess_t *pThis, prop_t *ip) {
196 DEFiRet;
197 ISOBJ_TYPE_assert(pThis, tcps_sess);
198
199 if (pThis->fromHostIP != NULL) {
200 prop.Destruct(&pThis->fromHostIP);
201 }
202 pThis->fromHostIP = ip;
203 RETiRet;
204 }
205
206 static rsRetVal SetHostPort(tcps_sess_t *pThis, prop_t *port) {
207 DEFiRet;
208 ISOBJ_TYPE_assert(pThis, tcps_sess);
209
210 if (pThis->fromHostPort != NULL) {
211 prop.Destruct(&pThis->fromHostPort);
212 }
213 pThis->fromHostPort = port;
214 RETiRet;
215 }
216
217 static rsRetVal SetStrm(tcps_sess_t *pThis, netstrm_t *pStrm) {
218 DEFiRet;
219 ISOBJ_TYPE_assert(pThis, tcps_sess);
220 pThis->pStrm = pStrm;
221 RETiRet;
222 }
223
224
225 static inline int isLikelyTlsClientHello(const uchar buf[5]) {
226 if (buf[0] != 0x16) return 0; /* handshake record */
227 if (buf[1] != 0x03) return 0; /* TLS major version */
228 if (buf[2] > 0x04) return 0; /* accept TLS 1.0 - 1.3 */
229 const unsigned recordLen = ((unsigned)buf[3] << 8) | buf[4];
230 if (recordLen < 40 || recordLen > 16384) return 0; /* sanity */
231 return 1;
232 }
233
234 static ATTR_NONNULL() rsRetVal maybeDetectTlsClientHello(tcps_sess_t *pThis, const char *data, size_t len) {
235 DEFiRet;
236 if (pThis->tlsProbeDone) FINALIZE;
237
238 if (pThis->pSrv->pszOrigin == NULL || strcmp((const char *)pThis->pSrv->pszOrigin, "imtcp") != 0) {
239 pThis->tlsProbeDone = 1;
240 FINALIZE;
241 }
242
243 if (pThis->pSrv->iDrvrMode != 0) {
244 pThis->tlsProbeDone = 1;
245 FINALIZE;
246 }
247
248 while (len > 0 && pThis->tlsProbeBytes < sizeof(pThis->tlsProbeBuf)) {
249 pThis->tlsProbeBuf[pThis->tlsProbeBytes++] = (uchar)*data++;
250 --len;
251 }
252
253 if (pThis->tlsProbeBytes >= sizeof(pThis->tlsProbeBuf)) {
254 if (!pThis->tlsMismatchWarned && isLikelyTlsClientHello(pThis->tlsProbeBuf)) {
255 const char *const host = propGetSzStrOrDefault(pThis->fromHost, "(host unknown)");
256 const char *const ip = propGetSzStrOrDefault(pThis->fromHostIP, "(IP unknown)");
257 const char *const port = propGetSzStrOrDefault(pThis->fromHostPort, "(port unknown)");
258 LogError(0, RS_RET_SERVER_NO_TLS,
259 "imtcp: TLS handshake detected from %s (%s:%s) but listener is not TLS-enabled. "
260 "Enable TLS on this listener or disable TLS on the client. "
261 "See https://www.rsyslog.com/doc/faq/imtcp-tls-gibberish.html for troubleshooting.",
262 host, ip, port);
263 pThis->tlsMismatchWarned = 1;
264 ABORT_FINALIZE(RS_RET_SERVER_NO_TLS);
265 }
266 pThis->tlsProbeDone = 1;
267 }
268 finalize_it:
269 RETiRet;
270 }
271
272
273 static rsRetVal SetMsgIdx(tcps_sess_t *pThis, int idx) {
274 DEFiRet;
275 ISOBJ_TYPE_assert(pThis, tcps_sess);
276 pThis->iMsg = idx;
277 RETiRet;
278 }
279
280
281 /* set our parent, the tcpsrv object */
282 static rsRetVal SetTcpsrv(tcps_sess_t *pThis, tcpsrv_t *pSrv) {
283 DEFiRet;
284 ISOBJ_TYPE_assert(pThis, tcps_sess);
285 ISOBJ_TYPE_assert(pSrv, tcpsrv);
286 pThis->pSrv = pSrv;
287 RETiRet;
288 }
289
290
291 /* set our parent listener info*/
292 static rsRetVal SetLstnInfo(tcps_sess_t *pThis, tcpLstnPortList_t *pLstnInfo) {
293 DEFiRet;
294 ISOBJ_TYPE_assert(pThis, tcps_sess);
295 assert(pLstnInfo != NULL);
296 pThis->pLstnInfo = pLstnInfo;
297 /* set cached elements */
298 pThis->bSuppOctetFram = pLstnInfo->cnf_params->bSuppOctetFram;
299 pThis->bSPFramingFix = pLstnInfo->cnf_params->bSPFramingFix;
300 RETiRet;
301 }
302
303
304 static rsRetVal SetUsrP(tcps_sess_t *pThis, void *pUsr) {
305 DEFiRet;
306 pThis->pUsr = pUsr;
307 RETiRet;
308 }
309
310
311 static rsRetVal SetOnMsgReceive(tcps_sess_t *pThis, rsRetVal (*OnMsgReceive)(tcps_sess_t *, uchar *, int)) {
312 DEFiRet;
313 pThis->DoSubmitMessage = OnMsgReceive;
314 RETiRet;
315 }
316
317
318 /* This is a helper for submitting the message to the rsyslog core.
319 * It does some common processing, including resetting the various
320 * state variables to a "processed" state.
321 * Note that this function is also called if we had a buffer overflow
322 * due to a too-long message. So far, there is no indication this
323 * happened and it may be worth thinking about different handling
324 * of this case (what obviously would require a change to this
325 * function or some related code).
326 * rgerhards, 2009-04-23
327 */
328 static rsRetVal defaultDoSubmitMessage(tcps_sess_t *pThis,
329 struct syslogTime *stTime,
330 time_t ttGenTime,
331 multi_submit_t *pMultiSub) {
332 smsg_t *pMsg;
333 rsRetVal localRet;
334 DEFiRet;
335
336 ISOBJ_TYPE_assert(pThis, tcps_sess);
337 const tcpLstnParams_t *const cnf_params = pThis->pLstnInfo->cnf_params;
338
339 if (pThis->iMsg == 0) {
340 DBGPRINTF("discarding zero-sized message\n");
341 FINALIZE;
342 }
343
344 if (pThis->DoSubmitMessage != NULL) {
345 pThis->DoSubmitMessage(pThis, pThis->pMsg, pThis->iMsg);
346 FINALIZE;
347 }
348
349 /* we now create our own message object and submit it to the queue */
350 CHKiRet(msgConstructWithTime(&pMsg, stTime, ttGenTime));
351 MsgSetRawMsg(pMsg, (char *)pThis->pMsg, pThis->iMsg);
352 MsgSetInputName(pMsg, cnf_params->pInputName);
353 if (cnf_params->dfltTZ[0] != '\0') MsgSetDfltTZ(pMsg, (char *)cnf_params->dfltTZ);
354 MsgSetFlowControlType(pMsg, pThis->pSrv->bUseFlowControl ? eFLOWCTL_LIGHT_DELAY : eFLOWCTL_NO_DELAY);
355 pMsg->msgFlags = NEEDS_PARSING | PARSE_HOSTNAME;
356 MsgSetRcvFrom(pMsg, pThis->fromHost);
357 CHKiRet(MsgSetRcvFromIP(pMsg, pThis->fromHostIP));
358 CHKiRet(MsgSetRcvFromPort(pMsg, pThis->fromHostPort));
359 MsgSetRuleset(pMsg, cnf_params->pRuleset);
360
361 if (pThis->pLstnInfo->ratelimiter->pShared != NULL && pThis->pLstnInfo->ratelimiter->pShared->per_source_enabled) {
362 const char *per_source_key = NULL;
363 size_t per_source_key_len = 0;
364 if (pThis->pLstnInfo->ratelimiter->pShared->per_source_key_needs_parsing &&
365 (pMsg->msgFlags & NEEDS_PARSING) != 0) {
366 parser.ParseMsg(pMsg);
367 }
368 if (pThis->pLstnInfo->ratelimiter->pShared->per_source_key_mode == RL_PS_KEY_TPL) {
369 if (pThis->pLstnInfo->ratelimiter->pShared->per_source_key_tpl == NULL ||
370 pThis->pLstnInfo->ratelimiter->pShared->per_source_key_tpl_default) {
371 per_source_key = getHOSTNAME(pMsg);
372 per_source_key_len = getHOSTNAMELen(pMsg);
373 } else {
374 if (tplToString(pThis->pLstnInfo->ratelimiter->pShared->per_source_key_tpl, pMsg,
375 &pThis->perSourceKeyParam, NULL) == RS_RET_OK) {
376 per_source_key = (const char *)pThis->perSourceKeyParam.param;
377 per_source_key_len = pThis->perSourceKeyParam.lenStr;
378 }
379 }
380 } else {
381 uchar *pHost = NULL;
382 uchar *pPort = NULL;
383 int hostLen = 0;
384 int portLen = 0;
385
386 switch (pThis->pLstnInfo->ratelimiter->pShared->per_source_key_mode) {
387 case RL_PS_KEY_FROMHOST_IP:
388 if (pThis->fromHostIP != NULL) {
389 prop.GetString(pThis->fromHostIP, &pHost, &hostLen);
390 per_source_key = (const char *)pHost;
391 per_source_key_len = (size_t)hostLen;
392 }
393 break;
394 case RL_PS_KEY_FROMHOST:
395 if (pThis->fromHost != NULL) {
396 prop.GetString(pThis->fromHost, &pHost, &hostLen);
397 per_source_key = (const char *)pHost;
398 per_source_key_len = (size_t)hostLen;
399 }
400 break;
401 case RL_PS_KEY_FROMHOST_IP_PORT:
402 case RL_PS_KEY_FROMHOST_PORT:
403 if (pThis->fromHostPort != NULL) {
404 prop.GetString(pThis->fromHostPort, &pPort, &portLen);
405 }
406 if (pThis->pLstnInfo->ratelimiter->pShared->per_source_key_mode == RL_PS_KEY_FROMHOST_IP_PORT) {
407 if (pThis->fromHostIP != NULL) {
408 prop.GetString(pThis->fromHostIP, &pHost, &hostLen);
409 }
410 } else {
411 if (pThis->fromHost != NULL) {
412 prop.GetString(pThis->fromHost, &pHost, &hostLen);
413 }
414 }
415 if (pHost == NULL) {
416 pHost = (uchar *)"";
417 hostLen = 0;
418 }
419 if (pPort == NULL) {
420 pPort = (uchar *)"";
421 portLen = 0;
422 }
423 if (ensurePerSourceKeyBuf(&pThis->perSourceKeyParam, (size_t)hostLen + 1 + (size_t)portLen) ==
424 RS_RET_OK) {
425 memcpy(pThis->perSourceKeyParam.param, pHost, (size_t)hostLen);
426 pThis->perSourceKeyParam.param[hostLen] = ':';
427 memcpy(pThis->perSourceKeyParam.param + hostLen + 1, pPort, (size_t)portLen);
428 pThis->perSourceKeyParam.param[hostLen + 1 + portLen] = '\0';
429 pThis->perSourceKeyParam.lenStr = (size_t)hostLen + 1 + (size_t)portLen;
430 per_source_key = (const char *)pThis->perSourceKeyParam.param;
431 per_source_key_len = pThis->perSourceKeyParam.lenStr;
432 }
433 break;
434 case RL_PS_KEY_TPL:
435 default:
436 break;
437 }
438 }
439 localRet = ratelimitAddMsgPerSource(pThis->pLstnInfo->ratelimiter, pMultiSub, pMsg, per_source_key,
440 per_source_key_len, ttGenTime);
441 } else {
442 localRet = ratelimitAddMsg(pThis->pLstnInfo->ratelimiter, pMultiSub, pMsg);
443 }
444
445 if (localRet == RS_RET_OK) {
446 STATSCOUNTER_INC(pThis->pLstnInfo->ctrSubmit, pThis->pLstnInfo->mutCtrSubmit);
447 } else if (localRet == RS_RET_DISCARDMSG) {
448 DBGPRINTF("tcps_sess: message discarded by ratelimit helper\n");
449 iRet = RS_RET_OK;
450 } else {
451 DBGPRINTF("tcps_sess: ratelimit helper returned error %d, dropping message and continuing\n", localRet);
452 msgDestruct(&pMsg);
453 iRet = RS_RET_OK;
454 }
455
456 finalize_it:
457 /* reset status variables */
458 pThis->iMsg = 0;
459
460 RETiRet;
461 }
462
463
464 /* This should be called before a normal (non forced) close
465 * of a TCP session. This function checks if there is any unprocessed
466 * message left in the TCP stream. Such a message is probably a
467 * fragment. If everything goes well, we must be right at the
468 * beginning of a new frame without any data received from it. If
469 * not, there is some kind of a framing error. I think I remember that
470 * some legacy syslog/TCP implementations have non-LF terminated
471 * messages at the end of the stream. For now, we allow this behaviour.
472 * Later, it should probably become a configuration option.
473 * rgerhards, 2006-12-07
474 */
475 static rsRetVal PrepareClose(tcps_sess_t *pThis) {
476 struct syslogTime stTime;
477 time_t ttGenTime;
478 DEFiRet;
479
480 ISOBJ_TYPE_assert(pThis, tcps_sess);
481
482 if (pThis->inputState == eAtStrtFram) {
483 /* this is how it should be. There is no unprocessed
484 * data left and such we have nothing to do. For simplicity
485 * reasons, we immediately return in that case.
486 */
487 FINALIZE;
488 }
489
490 /* we have some data left! */
491 if (pThis->eFraming == TCP_FRAMING_OCTET_COUNTING) {
492 /* In this case, we have an invalid frame count and thus
493 * generate an error message and discard the frame.
494 */
495 LogError(0, NO_ERRCODE,
496 "Incomplete frame at end of stream in session %p - "
497 "ignoring extra data (a message may be lost).",
498 pThis->pStrm);
499 /* nothing more to do */
500 } else { /* here, we have traditional framing. Missing LF at the end
501 * of message may occur. As such, we process the message in
502 * this case.
503 */
504 DBGPRINTF("Extra data at end of stream in legacy syslog/tcp message - processing\n");
505 datetime.getCurrTime(&stTime, &ttGenTime, TIME_IN_LOCALTIME);
506 defaultDoSubmitMessage(pThis, &stTime, ttGenTime, NULL);
507 }
508
509 finalize_it:
510 RETiRet;
511 }
512
513
514 #ifdef FEATURE_REGEXP
515 static rsRetVal ATTR_NONNULL() processDataRcvd_regexFraming(tcps_sess_t *const __restrict__ pThis,
516 char **const buff,
517 struct syslogTime *const stTime,
518 const time_t ttGenTime,
519 multi_submit_t *const pMultiSub,
520 unsigned *const __restrict__ pnMsgs) {
521 DEFiRet;
522 const char c = **buff;
523
524 if (pThis->iMsg >= 2 * pThis->iMaxLine) {
525 LogError(0, RS_RET_OVERSIZE_MSG,
526 "imtcp: more then double max message size (%d) "
527 "received without finding frame terminator via regex - assuming "
528 "end of frame now.",
529 pThis->iMsg + 1);
530 defaultDoSubmitMessage(pThis, stTime, ttGenTime, pMultiSub);
531 ++(*pnMsgs);
532 pThis->iMsg = 0;
533 pThis->iCurrLine = 0;
534 }
535
536 pThis->pMsg[pThis->iMsg++] = c;
537 pThis->pMsg[pThis->iMsg] = '\0';
538
539
540 if (c == '\n') {
541 pThis->iCurrLine = pThis->iMsg;
542 } else {
543 const int isMatch =
544 !regexp.regexec(&pThis->pLstnInfo->start_preg, (char *)pThis->pMsg + pThis->iCurrLine, 0, NULL, 0);
545 if (pThis->iCurrLine > 0 && isMatch) {
546 DBGPRINTF("regex match (%d), framing line: %s\n", pThis->iCurrLine, pThis->pMsg);
547 const size_t len_save = pThis->iMsg - pThis->iCurrLine;
548 memmove(pThis->pMsg_save, pThis->pMsg + pThis->iCurrLine, len_save);
549 pThis->pMsg_save[len_save] = '\0';
550
551 pThis->iMsg = pThis->iCurrLine - 1; /* remove trailing LF */
552
553 defaultDoSubmitMessage(pThis, stTime, ttGenTime, pMultiSub);
554 ++(*pnMsgs);
555
556 memmove(pThis->pMsg, pThis->pMsg_save, len_save + 1);
557 pThis->iMsg = len_save;
558 pThis->iCurrLine = 0;
559 }
560 }
561
562 RETiRet;
563 }
564 #endif
565
566 /**
567 * @brief Close a TCP session and release session-owned properties.
568 *
569 * Tears down the network stream and frees per-session sender properties
570 * (hostname/IP). This does not flush pending data; callers should invoke
571 * PrepareClose() beforehand when needed. The netstrm close result is ignored
572 * because we are shutting down a session and there is no recovery path for a
573 * close failure.
574 */
575 static rsRetVal Close(tcps_sess_t *pThis) {
576 DEFiRet;
577
578 ISOBJ_TYPE_assert(pThis, tcps_sess);
579 netstrm.Destruct(&pThis->pStrm);
580 if (pThis->fromHost != NULL) {
581 prop.Destruct(&pThis->fromHost);
582 }
583 if (pThis->fromHostIP != NULL) prop.Destruct(&pThis->fromHostIP);
584
585 RETiRet;
586 }
587
588
589 /* process the data received. As TCP is stream based, we need to process the
590 * data inside a state machine. The actual data received is passed in byte-by-byte
591 * from DataRcvd, and this function here compiles messages from them and submits
592 * the end result to the queue. Introducing this function fixes a long-term bug ;)
593 * rgerhards, 2008-03-14
594 */
595 static rsRetVal ATTR_NONNULL(1) processDataRcvd(tcps_sess_t *pThis,
596 char **buff,
597 const int buffLen,
598 struct syslogTime *stTime,
599 const time_t ttGenTime,
600 multi_submit_t *pMultiSub,
601 unsigned *const __restrict__ pnMsgs) {
602 DEFiRet;
603 const char c = **buff;
604 const tcpLstnParams_t *const cnf_params = pThis->pLstnInfo->cnf_params;
605 ISOBJ_TYPE_assert(pThis, tcps_sess);
606
607 #ifdef FEATURE_REGEXP
608 if (pThis->pLstnInfo->bHasStartRegex) {
609 processDataRcvd_regexFraming(pThis, buff, stTime, ttGenTime, pMultiSub, pnMsgs);
610 FINALIZE;
611 }
612 #endif
613
614 if (pThis->inputState == eInMsgCheckMultiLine) {
615 if (c == '<') {
616 defaultDoSubmitMessage(pThis, stTime, ttGenTime, pMultiSub);
617 ++(*pnMsgs);
618 pThis->inputState = eAtStrtFram;
619 } else {
620 /* this was a continuation line, so we need to add the LF
621 * that we "missed" at the end of the previous packet.
622 */
623 if (pThis->iMsg < pThis->iMaxLine) {
624 *(pThis->pMsg + pThis->iMsg++) = '\n';
625 }
626 pThis->inputState = eInMsg;
627 }
628 }
629
630 if (pThis->inputState == eAtStrtFram) {
631 if (c >= '0' && c <= '9' && pThis->bSuppOctetFram) {
632 pThis->inputState = eInOctetCnt;
633 pThis->iOctetsRemain = 0;
634 pThis->eFraming = TCP_FRAMING_OCTET_COUNTING;
635 } else if (c == ' ' && pThis->bSPFramingFix) {
636 /* Cisco ASA very occasionally sends a SP after a LF, which
637 * thrashes framing if not taken special care of. Here,
638 * we permit space *in front of the next frame* and
639 * ignore it.
640 */
641 FINALIZE;
642 } else {
643 pThis->inputState = eInMsg;
644 pThis->eFraming = TCP_FRAMING_OCTET_STUFFING;
645 }
646 }
647
648 if (pThis->inputState == eInMsg) {
649 #if 0 // set to 1 for ultra-verbose
650 DBGPRINTF("DEBUG: processDataRcvd c=%c remain=%d\n",
651 c, pThis->iOctetsRemain);
652 #endif
653
654 if ((((c == '\n') && !pThis->pSrv->bDisableLFDelim) ||
655 ((pThis->pSrv->addtlFrameDelim != TCPSRV_NO_ADDTL_DELIMITER) && (c == pThis->pSrv->addtlFrameDelim))) &&
656 pThis->eFraming == TCP_FRAMING_OCTET_STUFFING) { /* record delimiter? */
657 if (cnf_params->bMultiLine) {
658 if (buffLen > 1) {
659 if (*(*buff + 1) == '<') {
660 defaultDoSubmitMessage(pThis, stTime, ttGenTime, pMultiSub);
661 ++(*pnMsgs);
662 pThis->inputState = eAtStrtFram;
663 } else {
664 if (pThis->iMsg < pThis->iMaxLine) {
665 *(pThis->pMsg + pThis->iMsg++) = c;
666 }
667 }
668 } else {
669 /* at end of buffer, check next packet */
670 pThis->inputState = eInMsgCheckMultiLine;
671 FINALIZE;
672 }
673 } else {
674 defaultDoSubmitMessage(pThis, stTime, ttGenTime, pMultiSub);
675 ++(*pnMsgs);
676 pThis->inputState = eAtStrtFram;
677 }
678 } else {
679 /* IMPORTANT: here we copy the actual frame content to the message - for BOTH framing modes!
680 * If we have a message that is larger than the max msg size, we truncate it. This is the best
681 * we can do in light of what the engine supports. -- rgerhards, 2008-03-14
682 */
683 if (pThis->iMsg < pThis->iMaxLine) {
684 *(pThis->pMsg + pThis->iMsg++) = c;
685 } else {
686 /* emergency, we now need to flush, no matter if we are at end of message or not... */
687 DBGPRINTF("error: message received is larger than max msg size, we %s it - c=%x\n",
688 pThis->pSrv->discardTruncatedMsg == 1 ? "truncate" : "split", c);
689 defaultDoSubmitMessage(pThis, stTime, ttGenTime, pMultiSub);
690 ++(*pnMsgs);
691 if (pThis->pSrv->discardTruncatedMsg == 1) {
692 if (pThis->eFraming == TCP_FRAMING_OCTET_COUNTING) {
693 pThis->iOctetsRemain--;
694 if (pThis->iOctetsRemain == 0) {
695 pThis->inputState = eAtStrtFram;
696 FINALIZE;
697 }
698 }
699 pThis->inputState = eInMsgTruncating;
700 FINALIZE;
701 }
702 }
703 }
704
705 if (pThis->eFraming == TCP_FRAMING_OCTET_COUNTING) {
706 /* do we need to find end-of-frame via octet counting? */
707 pThis->iOctetsRemain--;
708 if (pThis->iOctetsRemain < 1) {
709 /* we have end of frame! */
710 defaultDoSubmitMessage(pThis, stTime, ttGenTime, pMultiSub);
711 ++(*pnMsgs);
712 pThis->inputState = eAtStrtFram;
713 }
714 }
715 } else if (pThis->inputState == eInMsgTruncating) {
716 if (pThis->eFraming == TCP_FRAMING_OCTET_COUNTING) {
717 DBGPRINTF("DEBUG: TCP_FRAMING_OCTET_COUNTING eInMsgTruncating c=%c remain=%d\n", c, pThis->iOctetsRemain);
718
719 pThis->iOctetsRemain--;
720 if (pThis->iOctetsRemain < 1) {
721 pThis->inputState = eAtStrtFram;
722 }
723 } else {
724 if (((c == '\n') && !pThis->pSrv->bDisableLFDelim) ||
725 ((pThis->pSrv->addtlFrameDelim != TCPSRV_NO_ADDTL_DELIMITER) && (c == pThis->pSrv->addtlFrameDelim))) {
726 pThis->inputState = eAtStrtFram;
727 }
728 }
729 } else {
730 assert(pThis->inputState == eInOctetCnt);
731 if (c >= '0' && c <= '9') { /* isdigit() the faster way */
732 if (pThis->iOctetsRemain <= 200000000) {
733 pThis->iOctetsRemain = pThis->iOctetsRemain * 10 + c - '0';
734 }
735 if (pThis->iMsg < pThis->iMaxLine) {
736 *(pThis->pMsg + pThis->iMsg++) = c;
737 }
738 } else { /* done with the octet count, so this must be the SP terminator */
739 DBGPRINTF("TCP Message with octet-counter, size %d.\n", pThis->iOctetsRemain);
740 const char *const peerName = propGetSzStrOrDefault(pThis->fromHost, "(hostname unknown)");
741 const char *const peerIP = propGetSzStrOrDefault(pThis->fromHostIP, "(IP unknown)");
742 const char *const peerPort = propGetSzStrOrDefault(pThis->fromHostPort, "(port unknown)");
743 if (c != ' ') {
744 LogError(0, NO_ERRCODE,
745 "imtcp %s: Framing Error in received TCP message from "
746 "peer: (hostname) %s, (ip) %s, (port) %s: delimiter is not SP but has "
747 "ASCII value %d.",
748 cnf_params->pszInputName, peerName, peerIP, peerPort, c);
749 }
750 if (pThis->iOctetsRemain < 1) {
751 LogError(0, NO_ERRCODE,
752 "imtcp %s: Framing Error in received TCP message from "
753 "peer: (hostname) %s, (ip) %s, (port) %s: invalid octet count %d.",
754 cnf_params->pszInputName, peerName, peerIP, peerPort, pThis->iOctetsRemain);
755 pThis->eFraming = TCP_FRAMING_OCTET_STUFFING;
756 } else if (pThis->iOctetsRemain > pThis->iMaxLine) {
757 /* while we can not do anything against it, we can at least log an indication
758 * that something went wrong) -- rgerhards, 2008-03-14
759 */
760 LogError(0, NO_ERRCODE,
761 "imtcp %s: received oversize message from peer: "
762 "(hostname) %s, (ip) %s, (port) %s: size is %d bytes, max msg size "
763 "is %d, truncating...",
764 cnf_params->pszInputName, peerName, peerIP, peerPort, pThis->iOctetsRemain, pThis->iMaxLine);
765 }
766 if (pThis->iOctetsRemain > pThis->pSrv->maxFrameSize) {
767 LogError(0, NO_ERRCODE,
768 "imtcp %s: Framing Error in received TCP message from "
769 "peer: (hostname) %s, (ip) %s, (port) %s: frame too large: %d, change "
770 "to octet stuffing",
771 cnf_params->pszInputName, peerName, peerIP, peerPort, pThis->iOctetsRemain);
772 pThis->eFraming = TCP_FRAMING_OCTET_STUFFING;
773 } else {
774 pThis->iMsg = 0;
775 }
776 pThis->inputState = eInMsg;
777 }
778 }
779
780 finalize_it:
781 RETiRet;
782 }
783
784
785 /* Processes the data received via a TCP session. If there
786 * is no other way to handle it, data is discarded.
787 * Input parameter data is the data received, iLen is its
788 * len as returned from recv(). iLen must be 1 or more (that
789 * is errors must be handled by caller!). iTCPSess must be
790 * the index of the TCP session that received the data.
791 * rgerhards 2005-07-04
792 * And another change while generalizing. We now return either
793 * RS_RET_OK, which means the session should be kept open
794 * or anything else, which means it must be closed.
795 * rgerhards, 2008-03-01
796 * As a performance optimization, we pick up the timestamp here. Actually,
797 * this *is* the *correct* reception step for all the data we received, because
798 * we have just received a bunch of data! -- rgerhards, 2009-06-16
799 */
800 #define NUM_MULTISUB 1024
801 static rsRetVal DataRcvd(tcps_sess_t *pThis, char *pData, const size_t iLen) {
802 multi_submit_t multiSub;
803 smsg_t *pMsgs[NUM_MULTISUB];
804 struct syslogTime stTime;
805 time_t ttGenTime;
806 char *pEnd;
807 unsigned nMsgs = 0;
808 DEFiRet;
809
810 ISOBJ_TYPE_assert(pThis, tcps_sess);
811 assert(pData != NULL);
812 assert(iLen > 0);
813
814 CHKiRet(maybeDetectTlsClientHello(pThis, pData, iLen));
815
816 datetime.getCurrTime(&stTime, &ttGenTime, TIME_IN_LOCALTIME);
817 multiSub.ppMsgs = pMsgs;
818 multiSub.maxElem = NUM_MULTISUB;
819 multiSub.nElem = 0;
820
821 /* We now copy the message to the session buffer. */
822 pEnd = pData + iLen; /* this is one off, which is intentional */
823
824 while (pData < pEnd) {
825 CHKiRet(processDataRcvd(pThis, &pData, pEnd - pData, &stTime, ttGenTime, &multiSub, &nMsgs));
826 pData++;
827 }
828 iRet = multiSubmitFlush(&multiSub);
829
830 if (runConf->globals.senderKeepTrack) statsRecordSender(propGetSzStr(pThis->fromHost), nMsgs, ttGenTime);
831
832 finalize_it:
833 RETiRet;
834 }
835 #undef NUM_MULTISUB
836
837
838 /* queryInterface function
839 * rgerhards, 2008-02-29
840 */
841 BEGINobjQueryInterface(tcps_sess)
842 CODESTARTobjQueryInterface(tcps_sess);
843 if (pIf->ifVersion != tcps_sessCURR_IF_VERSION) { /* check for current version, increment on each change */
844 ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED);
845 }
846
847 /* ok, we have the right interface, so let's fill it
848 * Please note that we may also do some backwards-compatibility
849 * work here (if we can support an older interface version - that,
850 * of course, also affects the "if" above).
851 */
852 pIf->DebugPrint = tcps_sessDebugPrint;
853 pIf->Construct = tcps_sessConstruct;
854 pIf->ConstructFinalize = tcps_sessConstructFinalize;
855 pIf->Destruct = tcps_sessDestruct;
856
857 pIf->PrepareClose = PrepareClose;
858 pIf->Close = Close;
859 pIf->DataRcvd = DataRcvd;
860
861 pIf->SetUsrP = SetUsrP;
862 pIf->SetTcpsrv = SetTcpsrv;
863 pIf->SetLstnInfo = SetLstnInfo;
864 pIf->SetHost = SetHost;
865 pIf->SetHostIP = SetHostIP;
866 pIf->SetHostPort = SetHostPort;
867 pIf->SetStrm = SetStrm;
868 pIf->SetMsgIdx = SetMsgIdx;
869 pIf->SetOnMsgReceive = SetOnMsgReceive;
870 finalize_it:
871 ENDobjQueryInterface(tcps_sess)
872
873
874 /* exit our class
875 * rgerhards, 2008-03-10
876 */
877 BEGINObjClassExit(tcps_sess, OBJ_IS_LOADABLE_MODULE) /* CHANGE class also in END MACRO! */
878 CODESTARTObjClassExit(tcps_sess);
879 /* release objects we no longer need */
880 objRelease(netstrm, LM_NETSTRMS_FILENAME);
881 objRelease(datetime, CORE_COMPONENT);
882 objRelease(prop, CORE_COMPONENT);
883 objRelease(parser, CORE_COMPONENT);
884 objRelease(regexp, LM_REGEXP_FILENAME);
885 ENDObjClassExit(tcps_sess)
886
887
888 /* Initialize our class. Must be called as the very first method
889 * before anything else is called inside this class.
890 * rgerhards, 2008-02-29
891 */
892 BEGINObjClassInit(tcps_sess, 1, OBJ_IS_CORE_MODULE) /* class, version - CHANGE class also in END MACRO! */
893 /* request objects we use */
894 CHKiRet(objUse(netstrm, LM_NETSTRMS_FILENAME));
895 CHKiRet(objUse(datetime, CORE_COMPONENT));
896 CHKiRet(objUse(prop, CORE_COMPONENT));
897 CHKiRet(objUse(parser, CORE_COMPONENT));
898 CHKiRet(objUse(regexp, LM_REGEXP_FILENAME));
899
900 CHKiRet(objUse(glbl, CORE_COMPONENT));
901 objRelease(glbl, CORE_COMPONENT);
902
903 /* set our own handlers */
904 OBJSetMethodHandler(objMethod_DEBUGPRINT, tcps_sessDebugPrint);
905 OBJSetMethodHandler(objMethod_CONSTRUCTION_FINALIZER, tcps_sessConstructFinalize);
906 ENDObjClassInit(tcps_sess)
907
908 /* vim:set ai:
909 */