Debian Codegraph @

runtime/tcpsrv.c

raw
1 /* tcpsrv.c
2 *
3 * Common code for plain TCP syslog based servers. This is currently being
4 * utilized by imtcp and imgssapi.
5 *
6 * NOTE: this is *not* a generic TCP server, but one for syslog servers. For
7 * generic stream servers, please use ./runtime/strmsrv.c!
8 *
9 * There are actually two classes within the tcpserver code: one is
10 * the tcpsrv itself, the other one is its sessions. This is a helper
11 * class to tcpsrv.
12 *
13 * The common code here calls upon specific functionality by using
14 * callbacks. The specialised input modules need to set the proper
15 * callbacks before the code is run. The tcpsrv then calls back
16 * into the specific input modules at the appropriate time.
17 *
18 * NOTE: read comments in module-template.h to understand how this file
19 * works!
20 *
21 * File begun on 2007-12-21 by RGerhards (extracted from syslogd.c[which was
22 * licensed under BSD at the time of the rsyslog fork])
23 *
24 * Copyright 2007-2025 Adiscon GmbH.
25 *
26 * This file is part of rsyslog.
27 *
28 * Licensed under the Apache License, Version 2.0 (the "License");
29 * you may not use this file except in compliance with the License.
30 * You may obtain a copy of the License at
31 *
32 * http://www.apache.org/licenses/LICENSE-2.0
33 * -or-
34 * see COPYING.ASL20 in the source distribution
35 *
36 * Unless required by applicable law or agreed to in writing, software
37 * distributed under the License is distributed on an "AS IS" BASIS,
38 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
39 * See the License for the specific language governing permissions and
40 * limitations under the License.
41 */
42 #include "config.h"
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <assert.h>
46 #include <string.h>
47 #include <errno.h>
48 #include <unistd.h>
49 #include <stdarg.h>
50 #include <ctype.h>
51 #include <limits.h>
52 #include <netinet/in.h>
53 #include <netdb.h>
54 #include <pthread.h>
55 #include <sys/types.h>
56 #include <signal.h>
57 #include <sys/socket.h>
58 #if HAVE_FCNTL_H
59 #include <fcntl.h>
60 #endif
61 #if !defined(ENABLE_IMTCP_EPOLL)
62 #include <sys/poll.h>
63 #endif
64 #include "rsyslog.h"
65 #include "dirty.h"
66 #include "cfsysline.h"
67 #include "module-template.h"
68 #include "net.h"
69 #include "srUtils.h"
70 #include "conf.h"
71 #include "tcpsrv.h"
72 #include "obj.h"
73 #include "glbl.h"
74 #include "netstrms.h"
75 #include "netstrm.h"
76 #include "errmsg.h"
77 #include "ruleset.h"
78 #include "ratelimit.h"
79 #include "unicode-helper.h"
80 #include "nsd_ptcp.h"
81
82
83 PRAGMA_IGNORE_Wswitch_enum MODULE_TYPE_LIB MODULE_TYPE_NOKEEP;
84
85 /* defines */
86 #define TCPSESS_MAX_DEFAULT 200 /* default for nbr of tcp sessions if no number is given */
87 #define TCPLSTN_MAX_DEFAULT 20 /* default for nbr of listeners */
88
89 /* static data */
90 DEFobjStaticHelpers;
91 DEFobjCurrIf(conf);
92 DEFobjCurrIf(glbl);
93 DEFobjCurrIf(ruleset);
94 DEFobjCurrIf(tcps_sess);
95 DEFobjCurrIf(net);
96 DEFobjCurrIf(netstrms);
97 DEFobjCurrIf(netstrm);
98 DEFobjCurrIf(prop);
99 DEFobjCurrIf(statsobj);
100 DEFobjCurrIf(regexp);
101
102 #define NSPOLL_MAX_EVENTS_PER_WAIT 128
103
104
105 static void enqueueWork(tcpsrv_io_descr_t *const pioDescr);
106
107 /* We check which event notification mechanism we have and use the best available one.
108 * We switch back from library-specific drivers, because event notification always works
109 * at the socket layer and is conceptually the same. As such, we can reduce code, code
110 * complexity, and a bit of runtime overhead by using a compile time selection and
111 * abstraction of the event notification mechanism.
112 * rgerhards, 2025-01-16
113 */
114 #if defined(ENABLE_IMTCP_EPOLL)
115
116 static rsRetVal ATTR_NONNULL() eventNotify_init(tcpsrv_t *const pThis) {
117 DEFiRet;
118 #if defined(ENABLE_IMTCP_EPOLL) && defined(EPOLL_CLOEXEC) && defined(HAVE_EPOLL_CREATE1)
119 DBGPRINTF("tcpsrv uses epoll_create1()\n");
120 pThis->evtdata.epoll.efd = epoll_create1(EPOLL_CLOEXEC);
121 if (pThis->evtdata.epoll.efd < 0 && errno == ENOSYS)
122 #endif
123 {
124 DBGPRINTF("tcpsrv uses epoll_create()\n");
125 pThis->evtdata.epoll.efd = epoll_create(100);
126 /* size is ignored in newer kernels, but 100 is not bad... */
127 }
128
129 if (pThis->evtdata.epoll.efd < 0) {
130 DBGPRINTF("epoll_create1() could not create fd\n");
131 ABORT_FINALIZE(RS_RET_IO_ERROR);
132 }
133 finalize_it:
134 RETiRet;
135 }
136
137
138 static rsRetVal ATTR_NONNULL() eventNotify_exit(tcpsrv_t *const pThis) {
139 DEFiRet;
140 close(pThis->evtdata.epoll.efd);
141 RETiRet;
142 }
143
144
145 /* Modify socket set */
146 static rsRetVal ATTR_NONNULL()
147 epoll_Ctl(tcpsrv_t *const pThis, tcpsrv_io_descr_t *const pioDescr, const int isLstn, const int op) {
148 DEFiRet;
149
150 const int id = pioDescr->id;
151 const int sock = pioDescr->sock;
152 assert(sock >= 0);
153
154 if (op == EPOLL_CTL_ADD) {
155 dbgprintf("adding epoll entry %d, socket %d\n", id, sock);
156 pioDescr->event.events = EPOLLIN | EPOLLET | EPOLLONESHOT;
157 pioDescr->event.data.ptr = (void *)pioDescr;
158 if (epoll_ctl(pThis->evtdata.epoll.efd, EPOLL_CTL_ADD, sock, &pioDescr->event) < 0) {
159 LogError(errno, RS_RET_ERR_EPOLL_CTL, "epoll_ctl failed on fd %d, isLstn %d\n", sock, isLstn);
160 }
161 } else if (op == EPOLL_CTL_DEL) {
162 dbgprintf("removing epoll entry %d, socket %d\n", id, sock);
163 if (epoll_ctl(pThis->evtdata.epoll.efd, EPOLL_CTL_DEL, sock, NULL) < 0) {
164 if (errno == EBADF || errno == ENOENT) {
165 /* already gone-away, everything is well */
166 DBGPRINTF("epoll_ctl: fd %d already removed, isLstn %d", sock, isLstn);
167 } else {
168 LogError(errno, RS_RET_ERR_EPOLL_CTL, "epoll_ctl failed on fd %d, isLstn %d\n", sock, isLstn);
169 ABORT_FINALIZE(RS_RET_ERR_EPOLL_CTL);
170 }
171 }
172 } else {
173 dbgprintf("program error: invalid NSDPOLL_mode %d - ignoring request\n", op);
174 ABORT_FINALIZE(RS_RET_ERR);
175 }
176
177 finalize_it:
178 DBGPRINTF("Done processing epoll entry %d, iRet %d\n", id, iRet);
179 RETiRet;
180 }
181
182
183 /* Wait for io to become ready. After the successful call, idRdy contains the
184 * id set by the caller for that i/o event, ppUsr is a pointer to a location
185 * where the user pointer shall be stored.
186 * numEntries contains the maximum number of entries on entry and the actual
187 * number of entries actually read on exit.
188 * rgerhards, 2009-11-18
189 */
190 static rsRetVal ATTR_NONNULL()
191 epoll_Wait(tcpsrv_t *const pThis, const int timeout, int *const numEntries, tcpsrv_io_descr_t *pWorkset[]) {
192 struct epoll_event event[NSPOLL_MAX_EVENTS_PER_WAIT];
193 int nfds;
194 int i;
195 DEFiRet;
196
197 assert(pWorkset != NULL);
198
199 if (*numEntries > NSPOLL_MAX_EVENTS_PER_WAIT) *numEntries = NSPOLL_MAX_EVENTS_PER_WAIT;
200 DBGPRINTF("doing epoll_wait for max %d events\n", *numEntries);
201 nfds = epoll_wait(pThis->evtdata.epoll.efd, event, *numEntries, timeout);
202 if (nfds == -1) {
203 if (errno == EINTR) {
204 ABORT_FINALIZE(RS_RET_EINTR);
205 } else {
206 DBGPRINTF("epoll_wait() returned with error code %d\n", errno);
207 ABORT_FINALIZE(RS_RET_ERR_EPOLL);
208 }
209 } else if (nfds == 0) {
210 ABORT_FINALIZE(RS_RET_TIMEOUT);
211 }
212
213 /* we got valid events, so tell the caller... */
214 DBGPRINTF("epoll_wait returned %d entries\n", nfds);
215 for (i = 0; i < nfds; ++i) {
216 pWorkset[i] = event[i].data.ptr;
217 /* default is no error, on error we terminate, so we need only to set in error case! */
218 if (event[i].events & EPOLLERR) {
219 ATOMIC_STORE_1_TO_INT(&pWorkset[i]->isInError, &pWorkset[i]->mut_isInError);
220 }
221 }
222 *numEntries = nfds;
223
224 finalize_it:
225 RETiRet;
226 }
227
228
229 #else /* no epoll, let's use poll() ------------------------------------------------------------ */
230 #define FDSET_INCREMENT 1024 /* increment for struct pollfds array allocation */
231
232
233 static rsRetVal ATTR_NONNULL() eventNotify_init(tcpsrv_t *const pThis ATTR_UNUSED) {
234 return RS_RET_OK;
235 }
236
237
238 static rsRetVal ATTR_NONNULL() eventNotify_exit(tcpsrv_t *const pThis) {
239 DEFiRet;
240 free(pThis->evtdata.poll.fds);
241 RETiRet;
242 }
243
244
245 /* Add a socket to the poll set */
246 static rsRetVal ATTR_NONNULL() poll_Add(tcpsrv_t *const pThis, netstrm_t *const pStrm, const nsdsel_waitOp_t waitOp) {
247 DEFiRet;
248 int sock;
249
250 CHKiRet(netstrm.GetSock(pStrm, &sock));
251
252 if (pThis->evtdata.poll.currfds == pThis->evtdata.poll.maxfds) {
253 struct pollfd *newfds;
254 CHKmalloc(newfds = realloc(pThis->evtdata.poll.fds,
255 sizeof(struct pollfd) * (pThis->evtdata.poll.maxfds + FDSET_INCREMENT)));
256 pThis->evtdata.poll.maxfds += FDSET_INCREMENT;
257 pThis->evtdata.poll.fds = newfds;
258 }
259
260 switch (waitOp) {
261 case NSDSEL_RD:
262 pThis->evtdata.poll.fds[pThis->evtdata.poll.currfds].events = POLLIN;
263 break;
264 case NSDSEL_WR:
265 pThis->evtdata.poll.fds[pThis->evtdata.poll.currfds].events = POLLOUT;
266 break;
267 case NSDSEL_RDWR:
268 pThis->evtdata.poll.fds[pThis->evtdata.poll.currfds].events = POLLIN | POLLOUT;
269 break;
270 default:
271 break;
272 }
273 pThis->evtdata.poll.fds[pThis->evtdata.poll.currfds].fd = sock;
274 ++pThis->evtdata.poll.currfds;
275
276 finalize_it:
277 RETiRet;
278 }
279
280
281 /* perform the poll() piNumReady returns how many descriptors are ready for IO
282 */
283 static rsRetVal ATTR_NONNULL() poll_Poll(tcpsrv_t *const pThis, int *const piNumReady) {
284 DEFiRet;
285
286 assert(piNumReady != NULL);
287
288 /* Output debug first*/
289 if (Debug) {
290 dbgprintf("calling poll, active fds (%d): ", pThis->evtdata.poll.currfds);
291 for (uint32_t i = 0; i <= pThis->evtdata.poll.currfds; ++i) dbgprintf("%d ", pThis->evtdata.poll.fds[i].fd);
292 dbgprintf("\n");
293 }
294 assert(pThis->evtdata.poll.currfds >= 1);
295
296 /* now do the select */
297 *piNumReady = poll(pThis->evtdata.poll.fds, pThis->evtdata.poll.currfds, -1);
298 if (*piNumReady < 0) {
299 if (errno == EINTR) {
300 DBGPRINTF("tcpsrv received EINTR\n");
301 } else {
302 LogMsg(errno, RS_RET_POLL_ERR, LOG_WARNING,
303 "ndssel_ptcp: poll system call failed, may cause further troubles");
304 }
305 *piNumReady = 0;
306 }
307
308 RETiRet;
309 }
310
311
312 /* check if a socket is ready for IO */
313 static rsRetVal ATTR_NONNULL()
314 poll_IsReady(tcpsrv_t *const pThis, netstrm_t *const pStrm, const nsdsel_waitOp_t waitOp, int *const pbIsReady) {
315 DEFiRet;
316 int sock;
317
318 CHKiRet(netstrm.GetSock(pStrm, &sock));
319
320 uint32_t idx;
321 for (idx = 0; idx < pThis->evtdata.poll.currfds; ++idx) {
322 if (pThis->evtdata.poll.fds[idx].fd == sock) break;
323 }
324 if (idx >= pThis->evtdata.poll.currfds) {
325 LogMsg(0, RS_RET_INTERNAL_ERROR, LOG_ERR, "ndssel_ptcp: could not find socket %d which should be present",
326 sock);
327 ABORT_FINALIZE(RS_RET_INTERNAL_ERROR);
328 }
329
330 const short revent = pThis->evtdata.poll.fds[idx].revents;
331 if (revent & POLLNVAL) {
332 DBGPRINTF("ndssel_ptcp: revent & POLLNVAL is TRUE, we had a race, ignoring, revent = %d", revent);
333 *pbIsReady = 0;
334 }
335 switch (waitOp) {
336 case NSDSEL_RD:
337 *pbIsReady = revent & POLLIN;
338 break;
339 case NSDSEL_WR:
340 *pbIsReady = revent & POLLOUT;
341 break;
342 case NSDSEL_RDWR:
343 *pbIsReady = revent & (POLLIN | POLLOUT);
344 break;
345 default:
346 break;
347 }
348
349 finalize_it:
350 RETiRet;
351 }
352
353 #endif /* event notification compile time selection */
354
355 static void freeLstnParams(tcpLstnParams_t *cnf_params) {
356 if (cnf_params == NULL) {
357 return;
358 }
359
360 if (cnf_params->pInputName != NULL) {
361 prop.Destruct(&cnf_params->pInputName);
362 }
363 free((void *)cnf_params->pszInputName);
364 free((void *)cnf_params->pszPort);
365 free((void *)cnf_params->pszAddr);
366 free((void *)cnf_params->pszLstnPortFileName);
367 free((void *)cnf_params->pszNetworkNamespace);
368 free((void *)cnf_params->pszStrmDrvrName);
369 free((void *)cnf_params->pszStartRegex);
370 free((void *)cnf_params->pszRatelimitName);
371 free(cnf_params);
372 }
373
374
375 /* add new listener port to listener port list
376 * rgerhards, 2009-05-21
377 */
378 static rsRetVal ATTR_NONNULL() addNewLstnPort(tcpsrv_t *const pThis, tcpLstnParams_t *const cnf_params) {
379 tcpLstnPortList_t *pEntry;
380 uchar statname[64];
381 DEFiRet;
382
383 ISOBJ_TYPE_assert(pThis, tcpsrv);
384
385 /* create entry */
386 CHKmalloc(pEntry = (tcpLstnPortList_t *)calloc(1, sizeof(tcpLstnPortList_t)));
387 pEntry->cnf_params = cnf_params;
388
389 strcpy((char *)pEntry->cnf_params->dfltTZ, (char *)pThis->dfltTZ);
390 pEntry->cnf_params->bSPFramingFix = pThis->bSPFramingFix;
391 pEntry->cnf_params->bPreserveCase = pThis->bPreserveCase;
392 pEntry->pSrv = pThis;
393
394 #ifdef FEATURE_REGEXP
395 if (cnf_params->pszStartRegex != NULL) {
396 if (glbl.GetMaxLine(runConf) > (INT_MAX - 1) / 2) {
397 LogError(0, RS_RET_ERR,
398 "imtcp: framing.delimiter.regex requires maxMessageSize <= %d to avoid session buffer overflow",
399 (INT_MAX - 1) / 2);
400 ABORT_FINALIZE(RS_RET_ERR);
401 }
402 const int errcode = regexp.regcomp(&pEntry->start_preg, (char *)cnf_params->pszStartRegex, REG_EXTENDED);
403 if (errcode != 0) {
404 char errbuff[512];
405 regexp.regerror(errcode, &pEntry->start_preg, errbuff, sizeof(errbuff));
406 LogError(0, RS_RET_ERR, "imtcp: error in framing.delimiter.regex expansion: %s", errbuff);
407 ABORT_FINALIZE(RS_RET_ERR);
408 }
409 pEntry->bHasStartRegex = 1;
410 }
411 #else
412 if (cnf_params->pszStartRegex != NULL) {
413 LogError(0, RS_RET_ERR, "imtcp: framing.delimiter.regex set, but regexp support not available");
414 ABORT_FINALIZE(RS_RET_ERR);
415 }
416 #endif
417
418 /* support statistics gathering */
419 if (pEntry->cnf_params->pszRatelimitName != NULL) {
420 CHKiRet(ratelimitNewFromConfig(&(pEntry->ratelimiter), runConf, (char *)pEntry->cnf_params->pszRatelimitName,
421 "tcpsrv", NULL));
422 } else {
423 CHKiRet(ratelimitNew(&(pEntry->ratelimiter), "tcpsrv", NULL));
424 ratelimitSetLinuxLike(pEntry->ratelimiter, pThis->ratelimitInterval, pThis->ratelimitBurst);
425 }
426 ratelimitSetThreadSafe(pEntry->ratelimiter);
427 CHKiRet(statsobj.Construct(&(pEntry->stats)));
428 snprintf((char *)statname, sizeof(statname), "%s(%s)", cnf_params->pszInputName, cnf_params->pszPort);
429 statname[sizeof(statname) - 1] = '\0'; /* just to be on the save side... */
430 CHKiRet(statsobj.SetName(pEntry->stats, statname));
431 CHKiRet(statsobj.SetOrigin(pEntry->stats, pThis->pszOrigin));
432 STATSCOUNTER_INIT(pEntry->ctrSubmit, pEntry->mutCtrSubmit);
433 CHKiRet(statsobj.AddCounter(pEntry->stats, UCHAR_CONSTANT("submitted"), ctrType_IntCtr, CTR_FLAG_RESETTABLE,
434 &(pEntry->ctrSubmit)));
435 CHKiRet(statsobj.ConstructFinalize(pEntry->stats));
436
437 /* all OK - add to list */
438 pEntry->pNext = pThis->pLstnPorts;
439 pThis->pLstnPorts = pEntry;
440
441 finalize_it:
442 if (iRet != RS_RET_OK) {
443 if (pEntry != NULL) {
444 if (pEntry->ratelimiter != NULL) {
445 ratelimitDestruct(pEntry->ratelimiter);
446 }
447 if (pEntry->stats != NULL) {
448 statsobj.Destruct(&pEntry->stats);
449 }
450 #ifdef FEATURE_REGEXP
451 if (pEntry->bHasStartRegex) {
452 regexp.regfree(&pEntry->start_preg);
453 }
454 #endif
455 free(pEntry);
456 }
457 }
458
459 RETiRet;
460 }
461
462
463 /* configure TCP listener settings.
464 * Note: pszPort is handed over to us - the caller MUST NOT free it!
465 * rgerhards, 2008-03-20
466 */
467 static rsRetVal ATTR_NONNULL() configureTCPListen(tcpsrv_t *const pThis, tcpLstnParams_t *const cnf_params) {
468 assert(cnf_params->pszPort != NULL);
469 int i;
470 sbool added = 0;
471 DEFiRet;
472
473 ISOBJ_TYPE_assert(pThis, tcpsrv);
474
475 /* extract port */
476 const uchar *pPort = cnf_params->pszPort;
477 i = 0;
478 while (isdigit((int)*pPort)) {
479 i = i * 10 + *pPort++ - '0';
480 }
481
482 if (i >= 0 && i <= 65535) {
483 CHKiRet(addNewLstnPort(pThis, cnf_params));
484 added = 1;
485 } else {
486 LogError(0, NO_ERRCODE, "Invalid TCP listen port %s - ignored.\n", cnf_params->pszPort);
487 }
488
489 finalize_it:
490 if (iRet != RS_RET_OK || !added) {
491 freeLstnParams(cnf_params);
492 }
493 RETiRet;
494 }
495
496
497 /* Initialize the session table
498 * returns 0 if OK, somewhat else otherwise
499 */
500 static rsRetVal ATTR_NONNULL() TCPSessTblInit(tcpsrv_t *const pThis) {
501 DEFiRet;
502
503 ISOBJ_TYPE_assert(pThis, tcpsrv);
504 assert(pThis->pSessions == NULL);
505
506 DBGPRINTF("Allocating buffer for %d TCP sessions.\n", pThis->iSessMax);
507 if ((pThis->pSessions = (tcps_sess_t **)calloc(pThis->iSessMax, sizeof(tcps_sess_t *))) == NULL) {
508 DBGPRINTF("Error: TCPSessInit() could not alloc memory for TCP session table.\n");
509 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
510 }
511
512 finalize_it:
513 RETiRet;
514 }
515
516
517 /* find a free spot in the session table. If the table
518 * is full, -1 is returned, else the index of the free
519 * entry (0 or higher).
520 */
521 static int ATTR_NONNULL() TCPSessTblFindFreeSpot(tcpsrv_t *const pThis) {
522 register int i;
523
524 ISOBJ_TYPE_assert(pThis, tcpsrv);
525
526 for (i = 0; i < pThis->iSessMax; ++i) {
527 if (pThis->pSessions[i] == NULL) break;
528 }
529
530 return ((i < pThis->iSessMax) ? i : -1);
531 }
532
533
534 #if !defined(ENABLE_IMTCP_EPOLL)
535 /* Get the next session index. Free session tables entries are
536 * skipped. This function is provided the index of the last
537 * session entry, or -1 if no previous entry was obtained. It
538 * returns the index of the next session or -1, if there is no
539 * further entry in the table. Please note that the initial call
540 * might as well return -1, if there is no session at all in the
541 * session table.
542 */
543 static int ATTR_NONNULL() TCPSessGetNxtSess(tcpsrv_t *pThis, const int iCurr) {
544 register int i;
545
546 ISOBJ_TYPE_assert(pThis, tcpsrv);
547 assert(pThis->pSessions != NULL);
548 for (i = iCurr + 1; i < pThis->iSessMax; ++i) {
549 if (pThis->pSessions[i] != NULL) break;
550 }
551
552 return ((i < pThis->iSessMax) ? i : -1);
553 }
554 #endif
555
556
557 /* De-Initialize TCP listener sockets.
558 * This function deinitializes everything, including freeing the
559 * session table. No TCP listen receive operations are permitted
560 * unless the subsystem is reinitialized.
561 * rgerhards, 2007-06-21
562 */
563 static void ATTR_NONNULL() deinit_tcp_listener(tcpsrv_t *const pThis) {
564 int i;
565 tcpLstnPortList_t *pEntry;
566 tcpLstnPortList_t *pDel;
567
568 ISOBJ_TYPE_assert(pThis, tcpsrv);
569
570 if (pThis->pSessions != NULL) {
571 #if !defined(ENABLE_IMTCP_EPOLL)
572 /* close all TCP connections! */
573 i = TCPSessGetNxtSess(pThis, -1);
574 while (i != -1) {
575 tcps_sess.Destruct(&pThis->pSessions[i]);
576 /* now get next... */
577 i = TCPSessGetNxtSess(pThis, i);
578 }
579 #endif
580
581 /* we are done with the session table - so get rid of it... */
582 free(pThis->pSessions);
583 pThis->pSessions = NULL; /* just to make sure... */
584 }
585
586 /* free list of tcp listen ports */
587 pEntry = pThis->pLstnPorts;
588 while (pEntry != NULL) {
589 #ifdef FEATURE_REGEXP
590 if (pEntry->bHasStartRegex) {
591 regexp.regfree(&pEntry->start_preg);
592 }
593 #endif
594 freeLstnParams(pEntry->cnf_params);
595 ratelimitDestruct(pEntry->ratelimiter);
596 statsobj.Destruct(&(pEntry->stats));
597 pDel = pEntry;
598 pEntry = pEntry->pNext;
599 free(pDel);
600 }
601
602 /* finally close our listen streams */
603 for (i = 0; i < pThis->iLstnCurr; ++i) {
604 netstrm.Destruct(pThis->ppLstn + i);
605 }
606 }
607
608
609 /* add a listen socket to our listen socket array. This is a callback
610 * invoked from the netstrm class. -- rgerhards, 2008-04-23
611 */
612 static rsRetVal ATTR_NONNULL() addTcpLstn(void *pUsr, netstrm_t *const pLstn) {
613 tcpLstnPortList_t *pPortList = (tcpLstnPortList_t *)pUsr;
614 tcpsrv_t *pThis = pPortList->pSrv;
615 DEFiRet;
616
617 ISOBJ_TYPE_assert(pThis, tcpsrv);
618 ISOBJ_TYPE_assert(pLstn, netstrm);
619
620 if (pThis->iLstnCurr >= pThis->iLstnMax) ABORT_FINALIZE(RS_RET_MAX_LSTN_REACHED);
621
622 pThis->ppLstn[pThis->iLstnCurr] = pLstn;
623 pThis->ppLstnPort[pThis->iLstnCurr] = pPortList;
624 ++pThis->iLstnCurr;
625
626 finalize_it:
627 RETiRet;
628 }
629
630
631 /* Initialize TCP listener socket for a single port
632 * Note: at this point, TLS vs. non-TLS does not matter; TLS params are
633 * set on connect!
634 * rgerhards, 2009-05-21
635 */
636 static rsRetVal ATTR_NONNULL() initTCPListener(tcpsrv_t *pThis, tcpLstnPortList_t *pPortEntry) {
637 DEFiRet;
638
639 ISOBJ_TYPE_assert(pThis, tcpsrv);
640 assert(pPortEntry != NULL);
641
642 CHKiRet(netstrm.LstnInit(pThis->pNS, (void *)pPortEntry, addTcpLstn, pThis->iSessMax, pPortEntry->cnf_params));
643
644 finalize_it:
645 RETiRet;
646 }
647
648
649 /* Initialize TCP sockets (for listener) and listens on them */
650 static rsRetVal ATTR_NONNULL() create_tcp_socket(tcpsrv_t *const pThis) {
651 DEFiRet;
652 rsRetVal localRet;
653 tcpLstnPortList_t *pEntry;
654
655 ISOBJ_TYPE_assert(pThis, tcpsrv);
656
657 /* init all configured ports */
658 pEntry = pThis->pLstnPorts;
659 while (pEntry != NULL) {
660 localRet = initTCPListener(pThis, pEntry);
661 if (localRet != RS_RET_OK) {
662 char *ns = pEntry->cnf_params->pszNetworkNamespace;
663
664 LogError(
665 0, localRet,
666 "Could not create tcp listener, ignoring port "
667 "%s bind-address %s%s%s.",
668 (pEntry->cnf_params->pszPort == NULL) ? "**UNSPECIFIED**" : (const char *)pEntry->cnf_params->pszPort,
669 (pEntry->cnf_params->pszAddr == NULL) ? "**UNSPECIFIED**" : (const char *)pEntry->cnf_params->pszAddr,
670 (ns == NULL) ? "" : " namespace ", (ns == NULL) ? "" : ns);
671 }
672 pEntry = pEntry->pNext;
673 }
674
675 /* OK, we had success. Now it is also time to
676 * initialize our connections
677 */
678 if (TCPSessTblInit(pThis) != 0) {
679 /* OK, we are in some trouble - we could not initialize the
680 * session table, so we can not continue. We need to free all
681 * we have assigned so far, because we can not really use it...
682 */
683 LogError(0, RS_RET_ERR,
684 "Could not initialize TCP session table, suspending TCP "
685 "message reception.");
686 ABORT_FINALIZE(RS_RET_ERR);
687 }
688
689 finalize_it:
690 RETiRet;
691 }
692
693
694 /* Accept new TCP connection; make entry in session table. If there
695 * is no more space left in the connection table, the new TCP
696 * connection is immediately dropped.
697 * ppSess has a pointer to the newly created session, if it succeeds.
698 * If it does not succeed, no session is created and ppSess is
699 * undefined. If the user has provided an OnSessAccept Callback,
700 * this one is executed immediately after creation of the
701 * session object, so that it can do its own initialization.
702 * rgerhards, 2008-03-02
703 */
704 static ATTR_NONNULL() rsRetVal SessAccept(tcpsrv_t *const pThis,
705 tcpLstnPortList_t *const pLstnInfo,
706 tcps_sess_t **ppSess,
707 int *const piSessIdx,
708 netstrm_t *pStrm,
709 char *const connInfo) {
710 DEFiRet;
711 tcps_sess_t *pSess = NULL;
712 netstrm_t *pNewStrm = NULL;
713 const tcpLstnParams_t *const cnf_params = pLstnInfo->cnf_params;
714 int iSess = -1;
715 struct sockaddr_storage *addr;
716 uchar *fromHostFQDN = NULL;
717 prop_t *fromHostIP = NULL;
718 prop_t *fromHostPort = NULL;
719 const char *fromHostNameStr = "(hostname unknown)";
720 const char *fromHostIPStr = "(IP unknown)";
721 const char *fromHostPortStr = "(port unknown)";
722
723 ISOBJ_TYPE_assert(pThis, tcpsrv);
724 assert(pLstnInfo != NULL);
725 assert(piSessIdx != NULL);
726
727 CHKiRet(netstrm.AcceptConnReq(pStrm, &pNewStrm, connInfo));
728
729 /* Add to session list */
730 iSess = TCPSessTblFindFreeSpot(pThis);
731 if (iSess == -1) {
732 errno = 0;
733 LogError(0, RS_RET_MAX_SESS_REACHED, "too many tcp sessions - dropping incoming request");
734 ABORT_FINALIZE(RS_RET_MAX_SESS_REACHED);
735 }
736
737 if (pThis->bUseKeepAlive) {
738 CHKiRet(netstrm.SetKeepAliveProbes(pNewStrm, pThis->iKeepAliveProbes));
739 CHKiRet(netstrm.SetKeepAliveTime(pNewStrm, pThis->iKeepAliveTime));
740 CHKiRet(netstrm.SetKeepAliveIntvl(pNewStrm, pThis->iKeepAliveIntvl));
741 CHKiRet(netstrm.EnableKeepAlive(pNewStrm));
742 }
743
744 /* we found a free spot and can construct our session object */
745 if (pThis->gnutlsPriorityString != NULL) {
746 CHKiRet(netstrm.SetGnutlsPriorityString(pNewStrm, pThis->gnutlsPriorityString));
747 }
748 CHKiRet(tcps_sess.Construct(&pSess));
749 CHKiRet(tcps_sess.SetTcpsrv(pSess, pThis));
750 CHKiRet(tcps_sess.SetLstnInfo(pSess, pLstnInfo));
751 if (pThis->OnMsgReceive != NULL) CHKiRet(tcps_sess.SetOnMsgReceive(pSess, pThis->OnMsgReceive));
752
753 /* get the host name */
754 CHKiRet(netstrm.GetRemoteHName(pNewStrm, &fromHostFQDN));
755 fromHostNameStr = szStrOrDefault(fromHostFQDN, "(hostname unknown)");
756 if (!cnf_params->bPreserveCase) {
757 /* preserve_case = off */
758 uchar *p;
759 for (p = fromHostFQDN; *p; p++) {
760 if (isupper((int)*p)) {
761 *p = tolower((int)*p);
762 }
763 }
764 }
765 CHKiRet(netstrm.GetRemoteIP(pNewStrm, &fromHostIP));
766 fromHostIPStr = propGetSzStrOrDefault(fromHostIP, "(IP unknown)");
767 CHKiRet(netstrm.GetRemAddr(pNewStrm, &addr));
768 char portbuf[8];
769 uint16_t port;
770 if (addr->ss_family == AF_INET)
771 port = ntohs(((struct sockaddr_in *)addr)->sin_port);
772 else if (addr->ss_family == AF_INET6)
773 port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
774 else
775 port = 0;
776 snprintf(portbuf, sizeof(portbuf), "%u", port);
777 CHKiRet(prop.Construct(&fromHostPort));
778 CHKiRet(prop.SetString(fromHostPort, (uchar *)portbuf, strlen(portbuf)));
779 CHKiRet(prop.ConstructFinalize(fromHostPort));
780 fromHostPortStr = propGetSzStrOrDefault(fromHostPort, "(port unknown)");
781 /* Here we check if a host is permitted to send us messages. If it isn't, we do not further
782 * process the message but log a warning (if we are configured to do this).
783 * rgerhards, 2005-09-26
784 */
785 if (!pThis->pIsPermittedHost((struct sockaddr *)addr, (char *)fromHostFQDN, pThis->pUsr, pSess->pUsr)) {
786 DBGPRINTF("%s is not an allowed sender\n", fromHostFQDN);
787 if (glbl.GetOptionDisallowWarning(runConf)) {
788 errno = 0;
789 LogError(0, RS_RET_HOST_NOT_PERMITTED,
790 "connection request from disallowed "
791 "sender %s (%s:%s) discarded",
792 fromHostNameStr, fromHostIPStr, fromHostPortStr);
793 }
794 ABORT_FINALIZE(RS_RET_HOST_NOT_PERMITTED);
795 }
796
797 /* OK, we have an allowed sender, so let's continue, what
798 * means we can finally fill in the session object.
799 */
800 CHKiRet(tcps_sess.SetHost(pSess, fromHostFQDN));
801 fromHostFQDN = NULL; /* we handed this string over */
802 fromHostNameStr = propGetSzStrOrDefault(pSess->fromHost, "(hostname unknown)");
803 CHKiRet(tcps_sess.SetHostIP(pSess, fromHostIP));
804 fromHostIPStr = propGetSzStrOrDefault(pSess->fromHostIP, "(IP unknown)");
805 fromHostIP = NULL;
806 CHKiRet(tcps_sess.SetHostPort(pSess, fromHostPort));
807 fromHostPortStr = propGetSzStrOrDefault(pSess->fromHostPort, "(port unknown)");
808 fromHostPort = NULL;
809 CHKiRet(tcps_sess.SetStrm(pSess, pNewStrm));
810 pNewStrm = NULL; /* prevent it from being freed in error handler, now done in tcps_sess! */
811 CHKiRet(tcps_sess.SetMsgIdx(pSess, 0));
812 CHKiRet(tcps_sess.ConstructFinalize(pSess));
813
814 /* check if we need to call our callback */
815 if (pThis->pOnSessAccept != NULL) {
816 CHKiRet(pThis->pOnSessAccept(pThis, pSess, connInfo));
817 }
818
819 *ppSess = pSess;
820 pThis->pSessions[iSess] = pSess;
821 *piSessIdx = iSess;
822 pSess = NULL; /* this is now also handed over */
823
824 if (pThis->bEmitMsgOnOpen) {
825 LogMsg(0, RS_RET_NO_ERRCODE, LOG_INFO, "imtcp: connection established with host: %s (%s:%s)", fromHostNameStr,
826 fromHostIPStr, fromHostPortStr);
827 }
828
829 finalize_it:
830 if (iRet != RS_RET_OK) {
831 if (iRet != RS_RET_HOST_NOT_PERMITTED && pThis->bEmitMsgOnOpen) {
832 LogError(0, NO_ERRCODE,
833 "imtcp: connection could not be "
834 "established with host: %s (%s:%s)",
835 fromHostNameStr, fromHostIPStr, fromHostPortStr);
836 }
837 if (pSess != NULL) tcps_sess.Destruct(&pSess);
838 if (pNewStrm != NULL) netstrm.Destruct(&pNewStrm);
839 if (fromHostIP != NULL) prop.Destruct(&fromHostIP);
840 if (fromHostPort != NULL) prop.Destruct(&fromHostPort);
841 free(fromHostFQDN);
842 }
843
844 RETiRet;
845 }
846
847
848 /**
849 * \brief Close a TCP session and release associated resources.
850 *
851 * Closes the session referenced by \p pioDescr, runs the module-specific
852 * close hook, and updates the event notification set. On EPOLL builds the
853 * I/O descriptor is heap-allocated and is freed here after best-effort
854 * removal from the epoll set.
855 *
856 * No locking is performed; callers are responsible for any required
857 * mutex handling before/after this call.
858 *
859 * \param[in] pThis Server instance.
860 * \param[in] pioDescr I/O descriptor for the session to close
861 * (pioDescr->ptrType == NSD_PTR_TYPE_SESS).
862 *
863 * \pre \p pioDescr and its \c pSess are valid.
864 * \post The session object is destroyed. On EPOLL builds, \p pioDescr is
865 * freed; on non-EPOLL builds, the session table entry is cleared.
866 * \post Callers must not access \p pioDescr or \c pSess after return.
867 *
868 * \note epoll removal is performed on a best-effort basis; teardown proceeds
869 * regardless of epoll_ctl outcome.
870 *
871 * \retval RS_RET_OK
872 */
873 static ATTR_NONNULL() rsRetVal closeSess(tcpsrv_t *const pThis, tcpsrv_io_descr_t *const pioDescr) {
874 DEFiRet;
875 assert(pioDescr->ptrType == NSD_PTR_TYPE_SESS);
876 tcps_sess_t *pSess = pioDescr->ptr.pSess;
877
878 #if defined(ENABLE_IMTCP_EPOLL)
879 /* note: we do not check the result of epoll_Ctl because we cannot do
880 * anything against a failure BUT we need to do the cleanup in any case.
881 */
882 epoll_Ctl(pThis, pioDescr, 0, EPOLL_CTL_DEL);
883 #endif
884 assert(pThis->pOnRegularClose != NULL);
885 pThis->pOnRegularClose(pSess);
886
887 tcps_sess.Destruct(&pSess);
888 pThis->pSessions[pioDescr->id] = NULL;
889 #if defined(ENABLE_IMTCP_EPOLL)
890 /* in epoll mode, pioDescr is dynamically allocated */
891 DESTROY_ATOMIC_HELPER_MUT(pioDescr->mut_isInError);
892 free(pioDescr);
893 #endif
894 RETiRet;
895 }
896
897
898 /**
899 * @brief Re-arm EPOLLONESHOT for this session’s descriptor.
900 *
901 * Uses EPOLL_CTL_MOD to (re)register the descriptor for the next I/O event,
902 * selecting EPOLLIN or EPOLLOUT from `pioDescr->ioDirection` and always
903 * enabling `EPOLLET | EPOLLONESHOT`. The epoll user data is set to the
904 * given `pioDescr` so the same descriptor is delivered on the next event.
905 *
906 * @pre `pioDescr` is valid; `pioDescr->sock` and
907 * `pioDescr->pSrv->evtdata.epoll.efd` refer to open fds.
908 * @pre `pioDescr->ioDirection` ∈ { `NSDSEL_RD`, `NSDSEL_WR` }.
909 * @pre Called by the thread that owns the descriptor (no concurrent epoll_ctl).
910 *
911 * @post On success, the descriptor is armed for the next edge-triggered event.
912 * On failure, the previous epoll registration remains unchanged.
913 *
914 * @param[in] pioDescr I/O descriptor to (re)arm.
915 * @retval RS_RET_OK on success.
916 * @retval RS_RET_ERR_EPOLL_CTL on epoll_ctl failure (error is logged).
917 *
918 * @note Compiled only when ENABLE_IMTCP_EPOLL is defined.
919 */
920 #if defined(ENABLE_IMTCP_EPOLL)
921 static ATTR_NONNULL() rsRetVal rearmIoEvent(tcpsrv_io_descr_t *const pioDescr) {
922 DEFiRet;
923
924 /* Debug-only invariants */
925 assert(pioDescr->ioDirection == NSDSEL_RD || pioDescr->ioDirection == NSDSEL_WR);
926 assert(pioDescr->pSrv != NULL && pioDescr->pSrv->evtdata.epoll.efd >= 0);
927 assert(pioDescr->sock >= 0);
928
929 const uint32_t waitIOEvent = (pioDescr->ioDirection == NSDSEL_WR) ? EPOLLOUT : EPOLLIN;
930 struct epoll_event event = {.events = waitIOEvent | EPOLLET | EPOLLONESHOT, .data = {.ptr = pioDescr}};
931 if (epoll_ctl(pioDescr->pSrv->evtdata.epoll.efd, EPOLL_CTL_MOD, pioDescr->sock, &event) < 0) {
932 LogError(errno, RS_RET_ERR_EPOLL_CTL, "epoll_ctl failed re-arm socket %d", pioDescr->sock);
933 ABORT_FINALIZE(RS_RET_ERR_EPOLL_CTL);
934 }
935
936 finalize_it:
937 RETiRet;
938 }
939 #endif
940
941
942 /**
943 * @brief Receive and dispatch data for a TCP session with starvation control and EPOLL re-arm.
944 *
945 * Flow:
946 * - Read via pThis->pRcvData(), forward to tcps_sess.DataRcvd().
947 * - Starvation: after `starvationMaxReads`, enqueue `pioDescr` (handoff) and return (no re-arm).
948 * - Would-block (RS_RET_RETRY): re-arm EPOLLONESHOT and return.
949 * - Close/error: exit the loop and close the session after unlocking.
950 *
951 * Locking:
952 * - If workQueue.numWrkr > 1, this function locks `pSess->mut` on entry and always unlocks
953 * before return (including close/error and starvation/handoff paths).
954 * - **Re-arm timing:** on the would-block path, `rearmIoEvent(pioDescr)` is called *before*
955 * unlocking `pSess->mut` to keep ownership until the EPOLL_CTL_MOD completes.
956 * - `closeSess()` is called *after* unlocking.
957 *
958 * Starvation accounting:
959 * - `read_calls` counts only successful reads (RS_RET_OK), so the cap reflects actual data
960 * consumption, not retries/closures/errors.
961 *
962 * @pre `pioDescr`, `pioDescr->ptr.pSess`, and `pioDescr->pSrv` are valid; I/O is non-blocking.
963 * @post On close paths, both `pioDescr` and `pSess` are invalid on return.
964 */
965 static rsRetVal ATTR_NONNULL(1)
966 doReceive(tcpsrv_io_descr_t *const pioDescr, tcpsrvWrkrData_t *const wrkrData ATTR_UNUSED) {
967 char buf[128 * 1024]; /* reception buffer - may hold a partial or multiple messages */
968 ssize_t iRcvd;
969 rsRetVal localRet;
970 DEFiRet;
971 int oserr = 0;
972 unsigned read_calls = 0;
973 tcps_sess_t *const pSess = pioDescr->ptr.pSess;
974 tcpsrv_t *const pThis = pioDescr->pSrv;
975 const unsigned maxReads = pThis->starvationMaxReads;
976
977 ISOBJ_TYPE_assert(pThis, tcpsrv);
978 const char *const peerIP = propGetSzStrOrDefault(pSess->fromHostIP, "(IP unknown)");
979 const char *const peerPort = propGetSzStrOrDefault(pSess->fromHostPort, "(port unknown)");
980 DBGPRINTF("netstream %p with new data from remote peer %s:%s\n", (pSess)->pStrm, peerIP, peerPort);
981
982 if (pThis->workQueue.numWrkr > 1) {
983 pthread_mutex_lock(&pSess->mut);
984 }
985
986 /* explicit state machine */
987 enum RecvState { RS_READING, RS_STARVATION, RS_DONE_REARM, RS_DONECLOSE, RS_DONE_HANDOFF };
988 enum RecvState state = RS_READING;
989
990 #if defined(ENABLE_IMTCP_EPOLL)
991 /* If we had EPOLLERR, log additional info; processing continues. */
992 if (ATOMIC_FETCH_32BIT(&pioDescr->isInError, &pioDescr->mut_isInError)) {
993 ATOMIC_STORE_0_TO_INT(&pioDescr->isInError, &pioDescr->mut_isInError);
994 int error = 0;
995 socklen_t len = sizeof(error);
996 const int sock = pioDescr->sock;
997 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) == 0) {
998 LogError(error, RS_RET_IO_ERROR, "epoll subsystem signaled EPOLLERR for stream %p, peer %s:%s",
999 (pSess)->pStrm, peerIP, peerPort);
1000 }
1001 }
1002 #endif
1003
1004 /* Sanity (debug builds): I/O direction must be valid. */
1005 assert(pioDescr->ioDirection == NSDSEL_RD || pioDescr->ioDirection == NSDSEL_WR);
1006
1007 /* Loop while in non-terminal states (positive check for readability). */
1008 while (state == RS_READING || state == RS_STARVATION) {
1009 switch (state) {
1010 case RS_READING:
1011 /* maxReads==0 is intentional and documented: it disables starvation protection. */
1012 while (state == RS_READING && (maxReads == 0 || read_calls < maxReads)) {
1013 iRet = pThis->pRcvData(pSess, buf, sizeof(buf), &iRcvd, &oserr, &pioDescr->ioDirection);
1014
1015 switch (iRet) {
1016 case RS_RET_CLOSED:
1017 if (pThis->bEmitMsgOnClose) {
1018 errno = 0;
1019 LogError(0, RS_RET_PEER_CLOSED_CONN,
1020 "Netstream session %p closed by remote peer %s:%s.", (pSess)->pStrm, peerIP,
1021 peerPort);
1022 }
1023 state = RS_DONECLOSE;
1024 break;
1025
1026 case RS_RET_RETRY:
1027 #if defined(ENABLE_IMTCP_EPOLL)
1028 if (pThis->workQueue.numWrkr > 1 && read_calls == 0) {
1029 STATSCOUNTER_ADD(wrkrData->ctrEmptyRead, wrkrData->mutCtrEmptyRead, 1);
1030 }
1031 #endif
1032 state = RS_DONE_REARM; /* would block → exit and re-arm */
1033 break;
1034
1035 case RS_RET_OK:
1036 /* Successful read counts toward starvation cap */
1037 if (pThis->workQueue.numWrkr > 1) {
1038 ++read_calls;
1039 }
1040 localRet = tcps_sess.DataRcvd(pSess, buf, iRcvd);
1041 if (localRet != RS_RET_OK && localRet != RS_RET_QUEUE_FULL) {
1042 LogError(oserr, localRet, "Tearing down TCP Session from %s:%s", peerIP, peerPort);
1043 state = RS_DONECLOSE;
1044 }
1045 break;
1046
1047 default:
1048 LogError(oserr, iRet, "netstream session %p from %s:%s will be closed due to error",
1049 pSess->pStrm, peerIP, peerPort);
1050 state = RS_DONECLOSE;
1051 break;
1052 }
1053 }
1054
1055 if (state == RS_READING) {
1056 state = RS_STARVATION; /* hit the read cap */
1057 }
1058 break;
1059
1060 case RS_STARVATION:
1061 dbgprintf("starvation avoidance triggered, ctr=%u, maxReads=%u\n", read_calls, maxReads);
1062 assert(pThis->workQueue.numWrkr > 1);
1063 #if defined(ENABLE_IMTCP_EPOLL)
1064 STATSCOUNTER_INC(wrkrData->ctrStarvation, wrkrData->mutCtrStarvation);
1065 #endif
1066 enqueueWork(pioDescr);
1067 state = RS_DONE_HANDOFF; /* queued behind existing work → exit, no re-arm */
1068 break;
1069
1070 default:
1071 assert(0 && "unhandled RecvState inside doReceive loop");
1072 state = RS_DONECLOSE;
1073 break;
1074 }
1075 }
1076
1077 /* Postcondition: we must have transitioned to a terminal state. */
1078 assert(state == RS_DONE_REARM || state == RS_DONECLOSE || state == RS_DONE_HANDOFF);
1079
1080 #if defined(ENABLE_IMTCP_EPOLL)
1081 if (pThis->workQueue.numWrkr > 1) {
1082 STATSCOUNTER_ADD(wrkrData->ctrRead, wrkrData->mutCtrRead, read_calls);
1083 }
1084 if (state == RS_DONE_REARM) {
1085 rearmIoEvent(pioDescr); /* re-arm while still holding pSess->mut */
1086 }
1087 #endif
1088
1089 if (pThis->workQueue.numWrkr > 1) {
1090 pthread_mutex_unlock(&pSess->mut);
1091 }
1092
1093 if (state == RS_DONECLOSE) {
1094 closeSess(pThis, pioDescr); /* also frees pioDescr in epoll builds */
1095 }
1096
1097 RETiRet;
1098 }
1099
1100
1101 /* This function processes a single incoming connection */
1102 static rsRetVal ATTR_NONNULL(1) doSingleAccept(tcpsrv_io_descr_t *const pioDescr) {
1103 tcps_sess_t *pNewSess = NULL;
1104 tcpsrv_io_descr_t *pDescrNew = NULL;
1105 const int idx = pioDescr->id;
1106 int iSess = -1;
1107 tcpsrv_t *const pThis = pioDescr->pSrv;
1108 char connInfo[TCPSRV_CONNINFO_SIZE] = "\0";
1109 DEFiRet;
1110
1111 DBGPRINTF("New connect on NSD %p.\n", pThis->ppLstn[idx]);
1112 iRet = SessAccept(pThis, pThis->ppLstnPort[idx], &pNewSess, &iSess, pThis->ppLstn[idx], connInfo);
1113 if (iRet == RS_RET_NO_MORE_DATA) {
1114 goto no_more_data;
1115 }
1116
1117 if (iRet == RS_RET_OK) {
1118 #if defined(ENABLE_IMTCP_EPOLL)
1119 /* pDescrNew is only dyn allocated in epoll mode! */
1120 CHKmalloc(pDescrNew = (tcpsrv_io_descr_t *)calloc(1, sizeof(tcpsrv_io_descr_t)));
1121 pDescrNew->pSrv = pThis;
1122 pDescrNew->id = iSess;
1123 pDescrNew->isInError = 0;
1124 INIT_ATOMIC_HELPER_MUT(pDescrNew->mut_isInError);
1125 pDescrNew->ptrType = NSD_PTR_TYPE_SESS;
1126 pDescrNew->ioDirection = NSDSEL_RD;
1127 CHKiRet(netstrm.GetSock(pNewSess->pStrm, &pDescrNew->sock));
1128 pDescrNew->ptr.pSess = pNewSess;
1129 CHKiRet(epoll_Ctl(pThis, pDescrNew, 0, EPOLL_CTL_ADD));
1130 #endif
1131
1132 DBGPRINTF("New session created with NSD %p.\n", pNewSess);
1133 } else {
1134 DBGPRINTF("tcpsrv: error %d during accept\n", iRet);
1135 }
1136
1137 #if defined(ENABLE_IMTCP_EPOLL)
1138 finalize_it:
1139 #endif
1140 if (iRet != RS_RET_OK) {
1141 const tcpLstnParams_t *cnf_params = pThis->ppLstnPort[idx]->cnf_params;
1142 LogError(0, iRet,
1143 "tcpsrv listener (inputname: '%s') failed "
1144 "to process incoming connection %s with error %d",
1145 (cnf_params->pszInputName == NULL) ? (uchar *)"*UNSET*" : cnf_params->pszInputName, connInfo, iRet);
1146 if (pDescrNew != NULL) {
1147 DESTROY_ATOMIC_HELPER_MUT(pDescrNew->mut_isInError);
1148 free(pDescrNew);
1149 }
1150 srSleep(0, 20000); /* Sleep 20ms */
1151 }
1152 no_more_data:
1153 RETiRet;
1154 }
1155
1156
1157 /* This function processes all pending accepts on this fd */
1158 static rsRetVal ATTR_NONNULL(1)
1159 doAccept(tcpsrv_io_descr_t *const pioDescr, tcpsrvWrkrData_t *const wrkrData ATTR_UNUSED) {
1160 DEFiRet;
1161 int bRun = 1;
1162 int nAccept = 0;
1163
1164 while (bRun) {
1165 iRet = doSingleAccept(pioDescr);
1166 if (iRet != RS_RET_OK) {
1167 bRun = 0;
1168 }
1169 ++nAccept;
1170 }
1171 #if defined(ENABLE_IMTCP_EPOLL)
1172 if (pioDescr->pSrv->workQueue.numWrkr > 1) {
1173 STATSCOUNTER_ADD(wrkrData->ctrAccept, wrkrData->mutCtrAccept, nAccept);
1174 }
1175 rearmIoEvent(pioDescr); /* listeners must ALWAYS be re-armed */
1176 #endif
1177
1178 RETiRet;
1179 }
1180
1181
1182 /* process a single workset item */
1183 static rsRetVal ATTR_NONNULL(1)
1184 processWorksetItem(tcpsrv_io_descr_t *const pioDescr, tcpsrvWrkrData_t *const wrkrData ATTR_UNUSED) {
1185 DEFiRet;
1186
1187 DBGPRINTF("tcpsrv: processing item %d, socket %d\n", pioDescr->id, pioDescr->sock);
1188 if (pioDescr->ptrType == NSD_PTR_TYPE_LSTN) {
1189 iRet = doAccept(pioDescr, wrkrData);
1190 } else {
1191 iRet = doReceive(pioDescr, wrkrData);
1192 }
1193
1194 RETiRet;
1195 }
1196
1197
1198 /* work queue functions */
1199
1200 static void ATTR_NONNULL() * wrkr(void *arg); /* forward-def of wrkr */
1201
1202 /**
1203 * @brief Start the worker thread pool for tcpsrv (best-effort, single-path cleanup).
1204 *
1205 * @details
1206 * This function allocates worker arrays, initializes synchronization primitives,
1207 * and spawns `workQueue.numWrkr` threads running `wrkr()`.
1208 *
1209 * ### Why all cleanup happens in `finalize_it`
1210 * This routine runs during initialization. If we fail here, the process is very
1211 * likely unable to run successfully anyway. To keep the code robust and
1212 * maintainable as more CHKiRet checks are added over time, we centralize **all**
1213 * rollback into the single `finalize_it` block:
1214 *
1215 * - guarantees a single, well-tested teardown path
1216 * - avoids fragile “partial cleanups” spread across multiple branches
1217 * - tolerates partial initialization (some threads created, some not; mutex/cond
1218 * initialized or not), destroying only what actually succeeded
1219 * - ignores secondary errors from pthread_*destroy/cancel/join — this is an
1220 * extreme error path and best-effort cleanup is sufficient
1221 *
1222 * ### Thread cancellation model
1223 * If any threads were created before failure, we call `pthread_cancel()` and then
1224 * `pthread_join()` on each. Worker threads block in `pthread_cond_wait()` which is
1225 * a POSIX cancellation point, so cancellation is reliable here.
1226 *
1227 * @param pThis Server instance (must have `workQueue.numWrkr > 1`).
1228 * @retval RS_RET_OK on success; error code on failure (resources cleaned up).
1229 */
1230 static rsRetVal ATTR_NONNULL() startWrkrPool(tcpsrv_t *const pThis) {
1231 DEFiRet;
1232 workQueue_t *const queue = &pThis->workQueue;
1233 int mut_initialized = 0;
1234 int cond_initialized = 0;
1235 unsigned created = 0;
1236
1237 assert(queue->numWrkr > 1);
1238
1239 /* Initialize queue state first. */
1240 queue->head = NULL;
1241 queue->tail = NULL;
1242
1243 /* Allocate arrays. */
1244 CHKmalloc(queue->wrkr_tids = calloc(queue->numWrkr, sizeof(pthread_t)));
1245 CHKmalloc(queue->wrkr_data = calloc(queue->numWrkr, sizeof(tcpsrvWrkrData_t)));
1246
1247 /* Init sync primitives. */
1248 if (pthread_mutex_init(&queue->mut, NULL) != 0) {
1249 ABORT_FINALIZE(RS_RET_ERR);
1250 }
1251 mut_initialized = 1;
1252
1253 if (pthread_cond_init(&queue->workRdy, NULL) != 0) {
1254 ABORT_FINALIZE(RS_RET_ERR);
1255 }
1256 cond_initialized = 1;
1257
1258 /* Spawn workers. */
1259 pThis->currWrkrs = 0;
1260 for (unsigned i = 0; i < queue->numWrkr; ++i) {
1261 if (pthread_create(&queue->wrkr_tids[i], &default_thread_attr, wrkr, pThis) != 0) {
1262 iRet = RS_RET_ERR;
1263 break;
1264 }
1265 ++created;
1266 }
1267
1268 finalize_it:
1269 if (iRet != RS_RET_OK) {
1270 /* Best-effort rollback in strict reverse order of construction. */
1271
1272 /* If any threads were created, cancel and join them. */
1273 if (created > 0) {
1274 for (unsigned i = 0; i < created; ++i) {
1275 (void)pthread_cancel(queue->wrkr_tids[i]); /* cond_wait is a cancellation point */
1276 }
1277 for (unsigned i = 0; i < created; ++i) {
1278 (void)pthread_join(queue->wrkr_tids[i], NULL);
1279 }
1280 }
1281
1282 /* Destroy sync primitives IFF they were successfully initialized. */
1283 if (cond_initialized) {
1284 (void)pthread_cond_destroy(&queue->workRdy);
1285 }
1286 if (mut_initialized) {
1287 (void)pthread_mutex_destroy(&queue->mut);
1288 }
1289
1290 /* Free arrays (they might be NULL if allocation failed early). */
1291 free(queue->wrkr_tids);
1292 free(queue->wrkr_data);
1293 queue->wrkr_tids = NULL;
1294 queue->wrkr_data = NULL;
1295 }
1296
1297 RETiRet;
1298 }
1299
1300 /**
1301 * @brief Safely stops the worker thread pool.
1302 *
1303 * This function can be called multiple times or in partial-init states.
1304 * It checks preconditions and only performs cleanup operations that are safe.
1305 */
1306 static void ATTR_NONNULL() stopWrkrPool(tcpsrv_t *const pThis) {
1307 workQueue_t *const queue = &pThis->workQueue;
1308
1309 /* Guard against being called when pool was never started or already stopped. */
1310 if (queue->numWrkr <= 1 || queue->wrkr_tids == NULL) {
1311 return;
1312 }
1313
1314 /* Signal all workers to wake and exit. */
1315 pthread_mutex_lock(&queue->mut);
1316 pthread_cond_broadcast(&queue->workRdy);
1317 pthread_mutex_unlock(&queue->mut);
1318
1319 /* Wait for all worker threads to finish. */
1320 for (unsigned i = 0; i < queue->numWrkr; i++) {
1321 pthread_join(queue->wrkr_tids[i], NULL);
1322 }
1323
1324 /* Free allocated resources. */
1325 free(queue->wrkr_tids);
1326 free(queue->wrkr_data);
1327
1328 /* Destroy synchronization primitives. */
1329 pthread_mutex_destroy(&queue->mut);
1330 pthread_cond_destroy(&queue->workRdy);
1331
1332 queue->wrkr_tids = NULL;
1333 queue->wrkr_data = NULL;
1334 }
1335
1336 static tcpsrv_io_descr_t ATTR_NONNULL() * dequeueWork(tcpsrv_t *pSrv) {
1337 workQueue_t *const queue = &pSrv->workQueue;
1338 tcpsrv_io_descr_t *pioDescr;
1339
1340 pthread_mutex_lock(&queue->mut);
1341 while ((queue->head == NULL) && !glbl.GetGlobalInputTermState()) {
1342 pthread_cond_wait(&queue->workRdy, &queue->mut);
1343 }
1344
1345 if (queue->head == NULL) {
1346 pioDescr = NULL;
1347 goto finalize_it;
1348 }
1349
1350 pioDescr = queue->head;
1351 queue->head = pioDescr->next;
1352 if (queue->head == NULL) {
1353 queue->tail = NULL;
1354 }
1355 finalize_it:
1356 pthread_mutex_unlock(&queue->mut);
1357 return pioDescr;
1358 }
1359
1360 /**
1361 * @brief Queue a ready I/O descriptor for worker processing (best-effort).
1362 *
1363 * Appends @p pioDescr to the work FIFO and signals one worker. Performs its
1364 * own locking; callers must not hold workQueue::mut. No epoll re-arm is done here.
1365 *
1366 * Intent:
1367 * - File-local helper for starvation/handoff paths.
1368 * - Best-effort, side-effect only; no return value. In debug builds you may assert
1369 * on obvious misuse, but callers do not recover here.
1370 *
1371 * Threading & Ownership:
1372 * - Thread-safe; may be called from the event loop or a worker.
1373 * - Stores a non-owning pointer; @p pioDescr must remain valid until a worker
1374 * dequeues it.
1375 *
1376 * Preconditions:
1377 * - @p pioDescr != NULL and @p pioDescr->pSrv != NULL.
1378 * - Multi-thread mode active (workQueue.numWrkr > 1).
1379 *
1380 * Postconditions:
1381 * - @p pioDescr is placed at the queue tail and one worker is signaled.
1382 */
1383 static void ATTR_NONNULL() enqueueWork(tcpsrv_io_descr_t *const pioDescr) {
1384 workQueue_t *const queue = &pioDescr->pSrv->workQueue;
1385
1386 pthread_mutex_lock(&queue->mut);
1387 pioDescr->next = NULL;
1388 if (queue->tail == NULL) {
1389 assert(queue->head == NULL);
1390 queue->head = pioDescr;
1391 } else {
1392 queue->tail->next = pioDescr;
1393 }
1394 queue->tail = pioDescr;
1395
1396 pthread_cond_signal(&queue->workRdy);
1397 pthread_mutex_unlock(&queue->mut);
1398 }
1399
1400 /* Worker thread function */
1401 static void ATTR_NONNULL() * wrkr(void *arg) {
1402 tcpsrv_t *const pThis = (tcpsrv_t *)arg;
1403 workQueue_t *const queue = &pThis->workQueue;
1404 tcpsrv_io_descr_t *pioDescr;
1405
1406 pthread_mutex_lock(&queue->mut);
1407 const int wrkrIdx = pThis->currWrkrs++;
1408 pthread_mutex_unlock(&queue->mut);
1409 int deinit_stats = 0;
1410 rsRetVal localRet;
1411
1412 tcpsrvWrkrData_t *const wrkrData = &(queue->wrkr_data[wrkrIdx]);
1413
1414 uchar shortThrdName[16];
1415 snprintf((char *)shortThrdName, sizeof(shortThrdName), "w%d/%s", wrkrIdx,
1416 (pThis->pszInputName == NULL) ? (uchar *)"tcpsrv" : pThis->pszInputName);
1417 uchar thrdName[32];
1418 snprintf((char *)thrdName, sizeof(thrdName), "w%d/%s", wrkrIdx,
1419 (pThis->pszInputName == NULL) ? (uchar *)"tcpsrv" : pThis->pszInputName);
1420 dbgSetThrdName(thrdName);
1421
1422 /* set thread name - we ignore if it fails, has no harsh consequences... */
1423 #if defined(HAVE_PRCTL) && defined(PR_SET_NAME)
1424 if (prctl(PR_SET_NAME, thrdName, 0, 0, 0) != 0) {
1425 DBGPRINTF("prctl failed, not setting thread name for '%s'\n", thrdName);
1426 }
1427 #elif defined(HAVE_PTHREAD_SETNAME_NP)
1428 #if defined(__APPLE__)
1429 /* The macOS variant takes only the thread name and returns an int. */
1430 int r = pthread_setname_np((char *)shortThrdName);
1431 if (r != 0) {
1432 DBGPRINTF("pthread_setname_np failed, not setting thread name for '%s'\n", shortThrdName);
1433 }
1434 #elif defined(__FreeBSD__)
1435 /* FreeBSD variant has a void return type. */
1436 pthread_setname_np(pthread_self(), (char *)shortThrdName);
1437 #elif defined(__NetBSD__)
1438 /* NetBSD variant takes a format string and returns an int. */
1439 int r = pthread_setname_np(pthread_self(), "%s", (void *)shortThrdName);
1440 if (r != 0) {
1441 DBGPRINTF("pthread_setname_np failed, not setting thread name for '%s'\n", shortThrdName);
1442 }
1443 #else
1444 /* The glibc variant takes thread ID and name, and returns an int. */
1445 int r = pthread_setname_np(pthread_self(), (char *)shortThrdName);
1446 if (r != 0) {
1447 DBGPRINTF("pthread_setname_np failed, not setting thread name for '%s'\n", shortThrdName);
1448 }
1449 #endif
1450 #endif
1451
1452 if ((localRet = statsobj.Construct(&wrkrData->stats)) == RS_RET_OK) {
1453 statsobj.SetName(wrkrData->stats, thrdName);
1454 statsobj.SetOrigin(wrkrData->stats, (uchar *)"imtcp");
1455
1456 STATSCOUNTER_INIT(wrkrData->ctrRuns, wrkrData->mutCtrRuns);
1457 statsobj.AddCounter(wrkrData->stats, UCHAR_CONSTANT("runs"), ctrType_IntCtr, CTR_FLAG_RESETTABLE,
1458 &(wrkrData->ctrRuns));
1459
1460 STATSCOUNTER_INIT(wrkrData->ctrRead, wrkrData->mutCtrRead);
1461 statsobj.AddCounter(wrkrData->stats, UCHAR_CONSTANT("read"), ctrType_IntCtr, CTR_FLAG_RESETTABLE,
1462 &(wrkrData->ctrRead));
1463
1464 STATSCOUNTER_INIT(wrkrData->ctrEmptyRead, wrkrData->mutCtrEmptyRead);
1465 statsobj.AddCounter(wrkrData->stats, UCHAR_CONSTANT("emptyread"), ctrType_IntCtr, CTR_FLAG_RESETTABLE,
1466 &(wrkrData->ctrEmptyRead));
1467
1468 STATSCOUNTER_INIT(wrkrData->ctrStarvation, wrkrData->mutCtrStarvation);
1469 statsobj.AddCounter(wrkrData->stats, UCHAR_CONSTANT("starvation_protect"), ctrType_IntCtr, CTR_FLAG_RESETTABLE,
1470 &(wrkrData->ctrStarvation));
1471
1472 STATSCOUNTER_INIT(wrkrData->ctrAccept, wrkrData->mutCtrAccept);
1473 statsobj.AddCounter(wrkrData->stats, UCHAR_CONSTANT("accept"), ctrType_IntCtr, CTR_FLAG_RESETTABLE,
1474 &(wrkrData->ctrAccept));
1475
1476 statsobj.ConstructFinalize(wrkrData->stats);
1477 deinit_stats = 1;
1478 } else {
1479 LogMsg(errno, localRet, LOG_WARNING,
1480 "tcpsrv worker %s could not create statistics "
1481 "counter. Thus, this worker does not provide them. Processing "
1482 "is otherwise unaffected",
1483 thrdName);
1484 }
1485
1486 /**** main loop ****/
1487 while (1) {
1488 pioDescr = dequeueWork(pThis);
1489 if (pioDescr == NULL) {
1490 break;
1491 }
1492
1493 /* note: we ignore the result as we cannot do anything against errors in any
1494 * case. Also, errors are reported inside processWorksetItem().
1495 */
1496 processWorksetItem(pioDescr, wrkrData);
1497 STATSCOUNTER_ADD(wrkrData->ctrRuns, wrkrData->mutCtrRuns, 1);
1498 }
1499
1500 /**** de-init ****/
1501 if (deinit_stats) {
1502 statsobj.Destruct(&wrkrData->stats);
1503 }
1504
1505 return NULL;
1506 }
1507
1508
1509 /* Process a workset, that is handle io. We become activated
1510 * from either poll or epoll handler. We split the workload
1511 * out to a pool of threads, but try to avoid context switches
1512 * as much as possible.
1513 */
1514 static rsRetVal ATTR_NONNULL() processWorkset(const int numEntries, tcpsrv_io_descr_t *const pioDescr[]) {
1515 int i;
1516 assert(numEntries > 0);
1517 const unsigned numWrkr = pioDescr[0]->pSrv->workQueue.numWrkr; /* pSrv is always the same! */
1518 DEFiRet;
1519
1520 DBGPRINTF("tcpsrv: ready to process %d event entries\n", numEntries);
1521
1522 for (i = 0; i < numEntries; ++i) {
1523 if (numWrkr == 1) {
1524 /* we process all on this thread, no need for context switch */
1525 processWorksetItem(pioDescr[i], NULL);
1526 } else {
1527 enqueueWork(pioDescr[i]);
1528 }
1529 }
1530 RETiRet;
1531 }
1532
1533
1534 #if !defined(ENABLE_IMTCP_EPOLL)
1535 /* This function is called to gather input.
1536 */
1537 PRAGMA_DIAGNOSTIC_PUSH
1538 PRAGMA_IGNORE_Wempty_body static ATTR_NONNULL() rsRetVal RunPoll(tcpsrv_t *const pThis) {
1539 DEFiRet;
1540 int nfds;
1541 int i;
1542 int iWorkset;
1543 int iTCPSess;
1544 int bIsReady;
1545 tcpsrv_io_descr_t *pWorkset[NSPOLL_MAX_EVENTS_PER_WAIT];
1546 tcpsrv_io_descr_t workset[NSPOLL_MAX_EVENTS_PER_WAIT];
1547 const int sizeWorkset = sizeof(workset) / sizeof(tcpsrv_io_descr_t);
1548 rsRetVal localRet;
1549
1550 ISOBJ_TYPE_assert(pThis, tcpsrv);
1551 DBGPRINTF("tcpsrv uses poll() [ex-select()] interface\n");
1552
1553 /* init the workset pointers, they will remain fixed */
1554 for (i = 0; i < sizeWorkset; ++i) {
1555 pWorkset[i] = workset + i;
1556 }
1557
1558 /* we init the fd set with "constant" data and only later on add the sessions.
1559 * Note: further optimization would be to keep the sessions as long as possible,
1560 * but this is currently not considered worth the effort as non-epoll platforms
1561 * become really rare. 2025-02-25 RGerhards
1562 */
1563 pThis->evtdata.poll.maxfds = FDSET_INCREMENT;
1564
1565 /* we need to alloc one pollfd more, because the list must be 0-terminated! */
1566 CHKmalloc(pThis->evtdata.poll.fds = calloc(FDSET_INCREMENT + 1, sizeof(struct pollfd)));
1567 /* Add the TCP listen sockets to the list of read descriptors. */
1568 for (i = 0; i < pThis->iLstnCurr; ++i) {
1569 CHKiRet(poll_Add(pThis, pThis->ppLstn[i], NSDSEL_RD));
1570 }
1571
1572 while (1) {
1573 pThis->evtdata.poll.currfds = pThis->iLstnCurr; /* listeners are "fixed" */
1574 /* do the sessions */
1575 iTCPSess = TCPSessGetNxtSess(pThis, -1);
1576 while (iTCPSess != -1) {
1577 /* TODO: access to pNsd is NOT really CLEAN, use method... */
1578 CHKiRet(poll_Add(pThis, pThis->pSessions[iTCPSess]->pStrm, NSDSEL_RD));
1579 DBGPRINTF("tcpsrv process session %d:\n", iTCPSess);
1580
1581 /* now get next... */
1582 iTCPSess = TCPSessGetNxtSess(pThis, iTCPSess);
1583 }
1584
1585 /* zero-out the last fd - space for it is always reserved! */
1586 assert(pThis->evtdata.poll.maxfds != pThis->evtdata.poll.currfds);
1587 pThis->evtdata.poll.fds[pThis->evtdata.poll.currfds].fd = 0;
1588 /* wait for io to become ready */
1589 CHKiRet(poll_Poll(pThis, &nfds));
1590 if (glbl.GetGlobalInputTermState() == 1) break; /* terminate input! */
1591
1592 iWorkset = 0;
1593 for (i = 0; i < pThis->iLstnCurr && nfds; ++i) {
1594 if (glbl.GetGlobalInputTermState() == 1) ABORT_FINALIZE(RS_RET_FORCE_TERM);
1595 CHKiRet(poll_IsReady(pThis, pThis->ppLstn[i], NSDSEL_RD, &bIsReady));
1596 if (bIsReady) {
1597 workset[iWorkset].pSrv = pThis;
1598 workset[iWorkset].ptrType = NSD_PTR_TYPE_LSTN;
1599 workset[iWorkset].id = i;
1600 workset[iWorkset].isInError = 0;
1601 workset[iWorkset].ioDirection = NSDSEL_RD; /* non-epoll: ensure sane default */
1602 CHKiRet(netstrm.GetSock(pThis->ppLstn[i], &(workset[iWorkset].sock)));
1603 workset[iWorkset].ptr.ppLstn = pThis->ppLstn;
1604 /* this is a flag to indicate listen sock */
1605 ++iWorkset;
1606 if (iWorkset >= (int)sizeWorkset) {
1607 processWorkset(iWorkset, pWorkset);
1608 iWorkset = 0;
1609 }
1610 --nfds; /* indicate we have processed one */
1611 }
1612 }
1613
1614 /* now check the sessions */
1615 iTCPSess = TCPSessGetNxtSess(pThis, -1);
1616 while (nfds && iTCPSess != -1) {
1617 if (glbl.GetGlobalInputTermState() == 1) ABORT_FINALIZE(RS_RET_FORCE_TERM);
1618 localRet = poll_IsReady(pThis, pThis->pSessions[iTCPSess]->pStrm, NSDSEL_RD, &bIsReady);
1619 if (bIsReady || localRet != RS_RET_OK) {
1620 workset[iWorkset].pSrv = pThis;
1621 workset[iWorkset].ptrType = NSD_PTR_TYPE_SESS;
1622 workset[iWorkset].id = iTCPSess;
1623 workset[iWorkset].isInError = 0;
1624 workset[iWorkset].ioDirection = NSDSEL_RD; /* non-epoll: ensure sane default */
1625 CHKiRet(netstrm.GetSock(pThis->pSessions[iTCPSess]->pStrm, &(workset[iWorkset].sock)));
1626 workset[iWorkset].ptr.pSess = pThis->pSessions[iTCPSess];
1627 ++iWorkset;
1628 if (iWorkset >= (int)sizeWorkset) {
1629 processWorkset(iWorkset, pWorkset);
1630 iWorkset = 0;
1631 }
1632 if (bIsReady) --nfds; /* indicate we have processed one */
1633 }
1634 iTCPSess = TCPSessGetNxtSess(pThis, iTCPSess);
1635 }
1636
1637 if (iWorkset > 0) {
1638 processWorkset(iWorkset, pWorkset);
1639 }
1640
1641 /* we need to copy back close descriptors */
1642 finalize_it: /* this is a very special case - this time only we do not exit the function,
1643 * because that would not help us either. So we simply retry it. Let's see
1644 * if that actually is a better idea. Exiting the loop wasn't we always
1645 * crashed, which made sense (the rest of the engine was not prepared for
1646 * that) -- rgerhards, 2008-05-19
1647 */
1648 continue; /* keep compiler happy, block end after label is non-standard */
1649 }
1650
1651 RETiRet;
1652 }
1653 PRAGMA_DIAGNOSTIC_POP
1654 #endif /* conditional exclude when epoll is available */
1655
1656
1657 #if defined(ENABLE_IMTCP_EPOLL)
1658 static rsRetVal ATTR_NONNULL() RunEpoll(tcpsrv_t *const pThis) {
1659 DEFiRet;
1660 int i;
1661 tcpsrv_io_descr_t *workset[NSPOLL_MAX_EVENTS_PER_WAIT];
1662 int numEntries;
1663 rsRetVal localRet;
1664
1665 DBGPRINTF("tcpsrv uses epoll() interface\n");
1666
1667 /* Add the TCP listen sockets to the list of sockets to monitor */
1668 for (i = 0; i < pThis->iLstnCurr; ++i) {
1669 DBGPRINTF("Trying to add listener %d, pUsr=%p\n", i, pThis->ppLstn);
1670 CHKmalloc(pThis->ppioDescrPtr[i] = (tcpsrv_io_descr_t *)calloc(1, sizeof(tcpsrv_io_descr_t)));
1671 pThis->ppioDescrPtr[i]->pSrv = pThis;
1672 pThis->ppioDescrPtr[i]->id = i;
1673 pThis->ppioDescrPtr[i]->isInError = 0;
1674 pThis->ppioDescrPtr[i]->ioDirection = NSDSEL_RD;
1675 INIT_ATOMIC_HELPER_MUT(pThis->ppioDescrPtr[i]->mut_isInError);
1676 CHKiRet(netstrm.GetSock(pThis->ppLstn[i], &(pThis->ppioDescrPtr[i]->sock)));
1677 pThis->ppioDescrPtr[i]->ptrType = NSD_PTR_TYPE_LSTN;
1678 pThis->ppioDescrPtr[i]->ptr.ppLstn = pThis->ppLstn;
1679 CHKiRet(epoll_Ctl(pThis, pThis->ppioDescrPtr[i], 1, EPOLL_CTL_ADD));
1680 DBGPRINTF("Added listener %d\n", i);
1681 }
1682
1683 while (glbl.GetGlobalInputTermState() == 0) {
1684 numEntries = sizeof(workset) / sizeof(tcpsrv_io_descr_t *);
1685 localRet = epoll_Wait(pThis, -1, &numEntries, workset);
1686 if (glbl.GetGlobalInputTermState() == 1) {
1687 break; /* terminate input! */
1688 }
1689
1690 /* check if we need to ignore the i/o ready state. We do this if we got an invalid
1691 * return state. Validly, this can happen for RS_RET_EINTR, for other cases it may
1692 * not be the right thing, but what is the right thing is really hard at this point...
1693 * Note: numEntries can be validly 0 in some rare cases (eg spurios wakeup).
1694 */
1695 if (localRet != RS_RET_OK || numEntries == 0) {
1696 continue;
1697 }
1698
1699 processWorkset(numEntries, workset);
1700 }
1701
1702 /* remove the tcp listen sockets from the epoll set */
1703 for (i = 0; i < pThis->iLstnCurr; ++i) {
1704 CHKiRet(epoll_Ctl(pThis, pThis->ppioDescrPtr[i], 1, EPOLL_CTL_DEL));
1705 DESTROY_ATOMIC_HELPER_MUT(pThis->ppioDescrPtr[i]->mut_isInError);
1706 free(pThis->ppioDescrPtr[i]);
1707 }
1708
1709 finalize_it:
1710 RETiRet;
1711 }
1712 #endif
1713
1714
1715 /* This function is called to gather input. It tries doing that via the epoll()
1716 * interface. If the driver does not support that, it falls back to calling its
1717 * select() equivalent.
1718 * rgerhards, 2009-11-18
1719 */
1720 static rsRetVal ATTR_NONNULL() Run(tcpsrv_t *const pThis) {
1721 DEFiRet;
1722 ISOBJ_TYPE_assert(pThis, tcpsrv);
1723
1724 if (pThis->iLstnCurr == 0) {
1725 dbgprintf("tcpsrv: no listeners at all (probably init error), terminating\n");
1726 FINALIZE;
1727 }
1728
1729 #if !defined(ENABLE_IMTCP_EPOLL)
1730 /* if we do not have epoll(), we need to run single-threaded */
1731 pThis->workQueue.numWrkr = 1;
1732 #endif
1733
1734 eventNotify_init(pThis);
1735 if (pThis->workQueue.numWrkr > 1) {
1736 iRet = startWrkrPool(pThis);
1737 if (iRet != RS_RET_OK) {
1738 LogError(errno, iRet,
1739 "tcpsrv could not start worker pool "
1740 "- now running single threaded '%s')",
1741 (pThis->pszInputName == NULL) ? (uchar *)"*UNSET*" : pThis->pszInputName);
1742 pThis->workQueue.numWrkr = 1;
1743 }
1744 }
1745 #if defined(ENABLE_IMTCP_EPOLL)
1746 iRet = RunEpoll(pThis);
1747 #else
1748 /* fall back to select */
1749 iRet = RunPoll(pThis);
1750 #endif
1751
1752 stopWrkrPool(pThis);
1753 eventNotify_exit(pThis);
1754
1755 finalize_it:
1756 RETiRet;
1757 }
1758
1759
1760 /* Standard-Constructor */
1761 BEGINobjConstruct(tcpsrv) /* be sure to specify the object type also in END macro! */
1762 pThis->iSessMax = TCPSESS_MAX_DEFAULT;
1763 pThis->iLstnMax = TCPLSTN_MAX_DEFAULT;
1764 pThis->addtlFrameDelim = TCPSRV_NO_ADDTL_DELIMITER;
1765 pThis->maxFrameSize = 200000;
1766 pThis->bDisableLFDelim = 0;
1767 pThis->discardTruncatedMsg = 0;
1768 pThis->OnMsgReceive = NULL;
1769 pThis->dfltTZ[0] = '\0';
1770 pThis->bSPFramingFix = 0;
1771 pThis->ratelimitInterval = 0;
1772 pThis->ratelimitBurst = 10000;
1773 pThis->bUseFlowControl = 1;
1774 pThis->pszDrvrName = NULL;
1775 pThis->bPreserveCase = 1; /* preserve case in fromhost; default to true. */
1776 pThis->iSynBacklog = 0; /* default: unset */
1777 pThis->DrvrTlsVerifyDepth = 0;
1778 pThis->DrvrTlsRevocationCheck = 0;
1779 ENDobjConstruct(tcpsrv)
1780
1781
1782 /* ConstructionFinalizer */
1783 static rsRetVal ATTR_NONNULL() tcpsrvConstructFinalize(tcpsrv_t *pThis) {
1784 DEFiRet;
1785 ISOBJ_TYPE_assert(pThis, tcpsrv);
1786
1787 /* prepare network stream subsystem */
1788 CHKiRet(netstrms.Construct(&pThis->pNS));
1789 CHKiRet(netstrms.SetSynBacklog(pThis->pNS, pThis->iSynBacklog));
1790 if (pThis->pszDrvrName != NULL) CHKiRet(netstrms.SetDrvrName(pThis->pNS, pThis->pszDrvrName));
1791 CHKiRet(netstrms.SetDrvrMode(pThis->pNS, pThis->iDrvrMode));
1792 CHKiRet(netstrms.SetDrvrCheckExtendedKeyUsage(pThis->pNS, pThis->DrvrChkExtendedKeyUsage));
1793 CHKiRet(netstrms.SetDrvrPrioritizeSAN(pThis->pNS, pThis->DrvrPrioritizeSan));
1794 CHKiRet(netstrms.SetDrvrTlsVerifyDepth(pThis->pNS, pThis->DrvrTlsVerifyDepth));
1795 CHKiRet(netstrms.SetDrvrTlsRevocationCheck(pThis->pNS, pThis->DrvrTlsRevocationCheck));
1796 if (pThis->pszDrvrAuthMode != NULL) CHKiRet(netstrms.SetDrvrAuthMode(pThis->pNS, pThis->pszDrvrAuthMode));
1797 /* Call SetDrvrPermitExpiredCerts required
1798 * when param is NULL default handling for ExpiredCerts is set! */
1799 CHKiRet(netstrms.SetDrvrPermitExpiredCerts(pThis->pNS, pThis->pszDrvrPermitExpiredCerts));
1800 CHKiRet(netstrms.SetDrvrTlsCAFile(pThis->pNS, pThis->pszDrvrCAFile));
1801 CHKiRet(netstrms.SetDrvrTlsCRLFile(pThis->pNS, pThis->pszDrvrCRLFile));
1802 CHKiRet(netstrms.SetDrvrTlsKeyFile(pThis->pNS, pThis->pszDrvrKeyFile));
1803 CHKiRet(netstrms.SetDrvrTlsCertFile(pThis->pNS, pThis->pszDrvrCertFile));
1804 if (pThis->pPermPeers != NULL) CHKiRet(netstrms.SetDrvrPermPeers(pThis->pNS, pThis->pPermPeers));
1805 if (pThis->gnutlsPriorityString != NULL)
1806 CHKiRet(netstrms.SetDrvrGnutlsPriorityString(pThis->pNS, pThis->gnutlsPriorityString));
1807 CHKiRet(netstrms.ConstructFinalize(pThis->pNS));
1808
1809 /* set up listeners */
1810 CHKmalloc(pThis->ppLstn = calloc(pThis->iLstnMax, sizeof(netstrm_t *)));
1811 CHKmalloc(pThis->ppLstnPort = calloc(pThis->iLstnMax, sizeof(tcpLstnPortList_t *)));
1812 CHKmalloc(pThis->ppioDescrPtr = calloc(pThis->iLstnMax, sizeof(tcpsrv_io_descr_t *)));
1813 iRet = pThis->OpenLstnSocks(pThis);
1814
1815 finalize_it:
1816 if (iRet != RS_RET_OK) {
1817 if (pThis->pNS != NULL) netstrms.Destruct(&pThis->pNS);
1818 free(pThis->ppLstn);
1819 pThis->ppLstn = NULL;
1820 free(pThis->ppLstnPort);
1821 pThis->ppLstnPort = NULL;
1822 free(pThis->ppioDescrPtr);
1823 pThis->ppioDescrPtr = NULL;
1824
1825 LogError(0, iRet, "tcpsrv could not create listener (inputname: '%s')",
1826 (pThis->pszInputName == NULL) ? (uchar *)"*UNSET*" : pThis->pszInputName);
1827 }
1828 RETiRet;
1829 }
1830
1831
1832 /* destructor for the tcpsrv object */
1833 BEGINobjDestruct(tcpsrv) /* be sure to specify the object type also in END and CODESTART macros! */
1834 CODESTARTobjDestruct(tcpsrv);
1835 if (pThis->OnDestruct != NULL) pThis->OnDestruct(pThis->pUsr);
1836
1837 stopWrkrPool(pThis);
1838
1839 deinit_tcp_listener(pThis);
1840
1841
1842 if (pThis->pNS != NULL) netstrms.Destruct(&pThis->pNS);
1843 free(pThis->pszDrvrName);
1844 free(pThis->pszDrvrAuthMode);
1845 free(pThis->pszDrvrPermitExpiredCerts);
1846 free(pThis->pszDrvrCAFile);
1847 free(pThis->pszDrvrCRLFile);
1848 free(pThis->pszDrvrKeyFile);
1849 free(pThis->pszDrvrCertFile);
1850 free(pThis->ppLstn);
1851 free(pThis->ppLstnPort);
1852 free(pThis->ppioDescrPtr);
1853 free(pThis->pszOrigin);
1854 ENDobjDestruct(tcpsrv)
1855
1856
1857 /* debugprint for the tcpsrv object */
1858 BEGINobjDebugPrint(tcpsrv) /* be sure to specify the object type also in END and CODESTART macros! */
1859 CODESTARTobjDebugPrint(tcpsrv);
1860 ENDobjDebugPrint(tcpsrv)
1861
1862 /* set functions */
1863 static rsRetVal ATTR_NONNULL(1)
1864 SetCBIsPermittedHost(tcpsrv_t *pThis, int (*pCB)(struct sockaddr *addr, char *fromHostFQDN, void *, void *)) {
1865 DEFiRet;
1866 pThis->pIsPermittedHost = pCB;
1867 RETiRet;
1868 }
1869
1870 static rsRetVal ATTR_NONNULL(1)
1871 SetCBRcvData(tcpsrv_t *pThis, rsRetVal (*pRcvData)(tcps_sess_t *, char *, size_t, ssize_t *, int *, unsigned *)) {
1872 DEFiRet;
1873 pThis->pRcvData = pRcvData;
1874 RETiRet;
1875 }
1876
1877 static rsRetVal ATTR_NONNULL(1) SetCBOnListenDeinit(tcpsrv_t *pThis, rsRetVal (*pCB)(void *)) {
1878 DEFiRet;
1879 pThis->pOnListenDeinit = pCB;
1880 RETiRet;
1881 }
1882
1883 static rsRetVal ATTR_NONNULL(1) SetCBOnSessAccept(tcpsrv_t *pThis, rsRetVal (*pCB)(tcpsrv_t *, tcps_sess_t *, char *)) {
1884 DEFiRet;
1885 pThis->pOnSessAccept = pCB;
1886 RETiRet;
1887 }
1888
1889 static rsRetVal ATTR_NONNULL(1) SetCBOnDestruct(tcpsrv_t *pThis, rsRetVal (*pCB)(void *)) {
1890 DEFiRet;
1891 pThis->OnDestruct = pCB;
1892 RETiRet;
1893 }
1894
1895 static rsRetVal ATTR_NONNULL(1) SetCBOnSessConstructFinalize(tcpsrv_t *pThis, rsRetVal (*pCB)(void *)) {
1896 DEFiRet;
1897 pThis->OnSessConstructFinalize = pCB;
1898 RETiRet;
1899 }
1900
1901 static rsRetVal ATTR_NONNULL(1) SetCBOnSessDestruct(tcpsrv_t *pThis, rsRetVal (*pCB)(void *)) {
1902 DEFiRet;
1903 pThis->pOnSessDestruct = pCB;
1904 RETiRet;
1905 }
1906
1907 static rsRetVal ATTR_NONNULL(1) SetCBOnRegularClose(tcpsrv_t *pThis, rsRetVal (*pCB)(tcps_sess_t *)) {
1908 DEFiRet;
1909 pThis->pOnRegularClose = pCB;
1910 RETiRet;
1911 }
1912
1913 static rsRetVal ATTR_NONNULL(1) SetCBOnErrClose(tcpsrv_t *pThis, rsRetVal (*pCB)(tcps_sess_t *)) {
1914 DEFiRet;
1915 pThis->pOnErrClose = pCB;
1916 RETiRet;
1917 }
1918
1919 static rsRetVal ATTR_NONNULL(1) SetCBOpenLstnSocks(tcpsrv_t *pThis, rsRetVal (*pCB)(tcpsrv_t *)) {
1920 DEFiRet;
1921 pThis->OpenLstnSocks = pCB;
1922 RETiRet;
1923 }
1924
1925 static rsRetVal ATTR_NONNULL(1) SetUsrP(tcpsrv_t *pThis, void *pUsr) {
1926 DEFiRet;
1927 pThis->pUsr = pUsr;
1928 RETiRet;
1929 }
1930
1931 static rsRetVal ATTR_NONNULL(1) SetKeepAlive(tcpsrv_t *pThis, const int iVal) {
1932 DEFiRet;
1933 DBGPRINTF("tcpsrv: keep-alive set to %d\n", iVal);
1934 pThis->bUseKeepAlive = iVal;
1935 RETiRet;
1936 }
1937
1938 static rsRetVal ATTR_NONNULL(1) SetKeepAliveIntvl(tcpsrv_t *pThis, const int iVal) {
1939 DEFiRet;
1940 DBGPRINTF("tcpsrv: keep-alive interval set to %d\n", iVal);
1941 pThis->iKeepAliveIntvl = iVal;
1942 RETiRet;
1943 }
1944
1945 static rsRetVal ATTR_NONNULL(1) SetKeepAliveProbes(tcpsrv_t *pThis, int iVal) {
1946 DEFiRet;
1947 DBGPRINTF("tcpsrv: keep-alive probes set to %d\n", iVal);
1948 pThis->iKeepAliveProbes = iVal;
1949 RETiRet;
1950 }
1951
1952 static rsRetVal ATTR_NONNULL(1) SetKeepAliveTime(tcpsrv_t *pThis, int iVal) {
1953 DEFiRet;
1954 DBGPRINTF("tcpsrv: keep-alive timeout set to %d\n", iVal);
1955 pThis->iKeepAliveTime = iVal;
1956 RETiRet;
1957 }
1958
1959 static rsRetVal ATTR_NONNULL(1) SetGnutlsPriorityString(tcpsrv_t *pThis, uchar *iVal) {
1960 DEFiRet;
1961 DBGPRINTF("tcpsrv: gnutlsPriorityString set to %s\n", (iVal == NULL) ? "(null)" : (const char *)iVal);
1962 pThis->gnutlsPriorityString = iVal;
1963 RETiRet;
1964 }
1965
1966
1967 static rsRetVal ATTR_NONNULL(1)
1968 SetOnMsgReceive(tcpsrv_t *pThis, rsRetVal (*OnMsgReceive)(tcps_sess_t *, uchar *, int)) {
1969 DEFiRet;
1970 assert(OnMsgReceive != NULL);
1971 pThis->OnMsgReceive = OnMsgReceive;
1972 RETiRet;
1973 }
1974
1975
1976 /* set enable/disable standard LF frame delimiter (use with care!)
1977 * -- rgerhards, 2010-01-03
1978 */
1979 static rsRetVal ATTR_NONNULL(1) SetbDisableLFDelim(tcpsrv_t *pThis, int bVal) {
1980 DEFiRet;
1981 ISOBJ_TYPE_assert(pThis, tcpsrv);
1982 pThis->bDisableLFDelim = bVal;
1983 RETiRet;
1984 }
1985
1986
1987 /* discard the truncated msg part
1988 * -- PascalWithopf, 2017-04-20
1989 */
1990 static rsRetVal ATTR_NONNULL(1) SetDiscardTruncatedMsg(tcpsrv_t *pThis, int discard) {
1991 DEFiRet;
1992 ISOBJ_TYPE_assert(pThis, tcpsrv);
1993 pThis->discardTruncatedMsg = discard;
1994 RETiRet;
1995 }
1996
1997
1998 /* Set additional framing to use (if any) -- rgerhards, 2008-12-10 */
1999 static rsRetVal ATTR_NONNULL(1) SetAddtlFrameDelim(tcpsrv_t *pThis, int iDelim) {
2000 DEFiRet;
2001 ISOBJ_TYPE_assert(pThis, tcpsrv);
2002 pThis->addtlFrameDelim = iDelim;
2003 RETiRet;
2004 }
2005
2006
2007 /* Set max frame size for octet counted -- PascalWithopf, 2017-04-20*/
2008 static rsRetVal ATTR_NONNULL(1) SetMaxFrameSize(tcpsrv_t *pThis, int maxFrameSize) {
2009 DEFiRet;
2010 ISOBJ_TYPE_assert(pThis, tcpsrv);
2011 pThis->maxFrameSize = maxFrameSize;
2012 RETiRet;
2013 }
2014
2015
2016 static rsRetVal ATTR_NONNULL(1) SetDfltTZ(tcpsrv_t *const pThis, uchar *const tz) {
2017 DEFiRet;
2018 ISOBJ_TYPE_assert(pThis, tcpsrv);
2019 strncpy((char *)pThis->dfltTZ, (char *)tz, sizeof(pThis->dfltTZ));
2020 pThis->dfltTZ[sizeof(pThis->dfltTZ) - 1] = '\0';
2021 RETiRet;
2022 }
2023
2024
2025 static rsRetVal ATTR_NONNULL(1) SetbSPFramingFix(tcpsrv_t *pThis, const sbool val) {
2026 DEFiRet;
2027 ISOBJ_TYPE_assert(pThis, tcpsrv);
2028 pThis->bSPFramingFix = val;
2029 RETiRet;
2030 }
2031
2032 static rsRetVal ATTR_NONNULL(1) SetOrigin(tcpsrv_t *pThis, uchar *origin) {
2033 DEFiRet;
2034 free(pThis->pszOrigin);
2035 pThis->pszOrigin = (origin == NULL) ? NULL : ustrdup(origin);
2036 RETiRet;
2037 }
2038
2039 /* Set the input name to use -- rgerhards, 2008-12-10 */
2040 static rsRetVal ATTR_NONNULL(1)
2041 SetInputName(tcpsrv_t *const pThis, tcpLstnParams_t *const cnf_params, const uchar *const name) {
2042 DEFiRet;
2043 ISOBJ_TYPE_assert(pThis, tcpsrv);
2044 if (name == NULL) {
2045 cnf_params->pszInputName = NULL;
2046 } else {
2047 CHKmalloc(cnf_params->pszInputName = ustrdup(name));
2048 pThis->pszInputName = cnf_params->pszInputName;
2049 }
2050
2051 /* we need to create a property */
2052 CHKiRet(prop.Construct(&cnf_params->pInputName));
2053 CHKiRet(prop.SetString(cnf_params->pInputName, cnf_params->pszInputName, ustrlen(cnf_params->pszInputName)));
2054 CHKiRet(prop.ConstructFinalize(cnf_params->pInputName));
2055 finalize_it:
2056 RETiRet;
2057 }
2058
2059 static rsRetVal SetNetworkNamespace(tcpsrv_t *pThis __attribute__((unused)),
2060 tcpLstnParams_t *const cnf_params,
2061 const char *const networkNamespace) {
2062 DEFiRet;
2063 ISOBJ_TYPE_assert(pThis, tcpsrv);
2064 free(cnf_params->pszNetworkNamespace);
2065 if (!networkNamespace || !*networkNamespace) {
2066 cnf_params->pszNetworkNamespace = NULL;
2067 } else {
2068 #ifdef HAVE_SETNS
2069 CHKmalloc(cnf_params->pszNetworkNamespace = strdup(networkNamespace));
2070 #else // ndef HAVE_SETNS
2071 LogError(0, RS_RET_VALUE_NOT_SUPPORTED, "Namespaces are not supported");
2072 ABORT_FINALIZE(RS_RET_VALUE_NOT_SUPPORTED);
2073 #endif // #else ndef HAVE_SETNS
2074 }
2075 finalize_it:
2076 RETiRet;
2077 }
2078
2079 /* Set the linux-like ratelimiter settings */
2080 static rsRetVal ATTR_NONNULL(1)
2081 SetLinuxLikeRatelimiters(tcpsrv_t *pThis, unsigned int ratelimitInterval, unsigned int ratelimitBurst) {
2082 DEFiRet;
2083 pThis->ratelimitInterval = ratelimitInterval;
2084 pThis->ratelimitBurst = ratelimitBurst;
2085 RETiRet;
2086 }
2087
2088
2089 /* Set connection open notification */
2090 static rsRetVal ATTR_NONNULL(1) SetNotificationOnRemoteOpen(tcpsrv_t *pThis, const int bNewVal) {
2091 pThis->bEmitMsgOnOpen = bNewVal;
2092 return RS_RET_OK;
2093 }
2094 /* Set connection close notification */
2095 static rsRetVal ATTR_NONNULL(1) SetNotificationOnRemoteClose(tcpsrv_t *pThis, const int bNewVal) {
2096 DEFiRet;
2097 pThis->bEmitMsgOnClose = bNewVal;
2098 RETiRet;
2099 }
2100
2101
2102 /* here follows a number of methods that shuffle authentication settings down
2103 * to the drivers. Drivers not supporting these settings may return an error
2104 * state.
2105 * -------------------------------------------------------------------------- */
2106
2107 /* set the driver mode -- rgerhards, 2008-04-30 */
2108 static rsRetVal ATTR_NONNULL(1) SetDrvrMode(tcpsrv_t *pThis, const int iMode) {
2109 DEFiRet;
2110 ISOBJ_TYPE_assert(pThis, tcpsrv);
2111 pThis->iDrvrMode = iMode;
2112 RETiRet;
2113 }
2114
2115 static rsRetVal ATTR_NONNULL(1) SetDrvrName(tcpsrv_t *pThis, uchar *const name) {
2116 DEFiRet;
2117 ISOBJ_TYPE_assert(pThis, tcpsrv);
2118 free(pThis->pszDrvrName);
2119 CHKmalloc(pThis->pszDrvrName = ustrdup(name));
2120 finalize_it:
2121 RETiRet;
2122 }
2123
2124 /* set the driver authentication mode -- rgerhards, 2008-05-19 */
2125 static rsRetVal ATTR_NONNULL(1) SetDrvrAuthMode(tcpsrv_t *pThis, uchar *const mode) {
2126 DEFiRet;
2127 ISOBJ_TYPE_assert(pThis, tcpsrv);
2128 CHKmalloc(pThis->pszDrvrAuthMode = ustrdup(mode));
2129 finalize_it:
2130 RETiRet;
2131 }
2132
2133 /* set the driver permitexpiredcerts mode -- alorbach, 2018-12-20
2134 */
2135 static rsRetVal ATTR_NONNULL(1) SetDrvrPermitExpiredCerts(tcpsrv_t *pThis, uchar *mode) {
2136 DEFiRet;
2137 ISOBJ_TYPE_assert(pThis, tcpsrv);
2138 if (mode != NULL) {
2139 CHKmalloc(pThis->pszDrvrPermitExpiredCerts = ustrdup(mode));
2140 }
2141 finalize_it:
2142 RETiRet;
2143 }
2144
2145 static rsRetVal ATTR_NONNULL(1) SetDrvrCAFile(tcpsrv_t *const pThis, uchar *const mode) {
2146 DEFiRet;
2147 ISOBJ_TYPE_assert(pThis, tcpsrv);
2148 if (mode != NULL) {
2149 CHKmalloc(pThis->pszDrvrCAFile = ustrdup(mode));
2150 }
2151 finalize_it:
2152 RETiRet;
2153 }
2154
2155 static rsRetVal ATTR_NONNULL(1) SetDrvrCRLFile(tcpsrv_t *const pThis, uchar *const mode) {
2156 DEFiRet;
2157 ISOBJ_TYPE_assert(pThis, tcpsrv);
2158 if (mode != NULL) {
2159 CHKmalloc(pThis->pszDrvrCRLFile = ustrdup(mode));
2160 }
2161 finalize_it:
2162 RETiRet;
2163 }
2164
2165 static rsRetVal ATTR_NONNULL(1) SetDrvrKeyFile(tcpsrv_t *pThis, uchar *mode) {
2166 DEFiRet;
2167 ISOBJ_TYPE_assert(pThis, tcpsrv);
2168 if (mode != NULL) {
2169 CHKmalloc(pThis->pszDrvrKeyFile = ustrdup(mode));
2170 }
2171 finalize_it:
2172 RETiRet;
2173 }
2174
2175 static rsRetVal ATTR_NONNULL(1) SetDrvrCertFile(tcpsrv_t *pThis, uchar *mode) {
2176 DEFiRet;
2177 ISOBJ_TYPE_assert(pThis, tcpsrv);
2178 if (mode != NULL) {
2179 CHKmalloc(pThis->pszDrvrCertFile = ustrdup(mode));
2180 }
2181 finalize_it:
2182 RETiRet;
2183 }
2184
2185
2186 /* set the driver's permitted peers -- rgerhards, 2008-05-19 */
2187 static rsRetVal ATTR_NONNULL(1) SetDrvrPermPeers(tcpsrv_t *pThis, permittedPeers_t *pPermPeers) {
2188 DEFiRet;
2189 ISOBJ_TYPE_assert(pThis, tcpsrv);
2190 pThis->pPermPeers = pPermPeers;
2191 RETiRet;
2192 }
2193
2194 /* set the driver cert extended key usage check setting -- jvymazal, 2019-08-16 */
2195 static rsRetVal ATTR_NONNULL(1) SetDrvrCheckExtendedKeyUsage(tcpsrv_t *pThis, int ChkExtendedKeyUsage) {
2196 DEFiRet;
2197 ISOBJ_TYPE_assert(pThis, tcpsrv);
2198 pThis->DrvrChkExtendedKeyUsage = ChkExtendedKeyUsage;
2199 RETiRet;
2200 }
2201
2202 /* set the driver name checking policy -- jvymazal, 2019-08-16 */
2203 static rsRetVal ATTR_NONNULL(1) SetDrvrPrioritizeSAN(tcpsrv_t *pThis, int prioritizeSan) {
2204 DEFiRet;
2205 ISOBJ_TYPE_assert(pThis, tcpsrv);
2206 pThis->DrvrPrioritizeSan = prioritizeSan;
2207 RETiRet;
2208 }
2209
2210 /* set the driver Set the driver tls verifyDepth -- alorbach, 2019-12-20 */
2211 static rsRetVal ATTR_NONNULL(1) SetDrvrTlsVerifyDepth(tcpsrv_t *pThis, int verifyDepth) {
2212 DEFiRet;
2213 ISOBJ_TYPE_assert(pThis, tcpsrv);
2214 pThis->DrvrTlsVerifyDepth = verifyDepth;
2215 RETiRet;
2216 }
2217
2218 static rsRetVal ATTR_NONNULL(1) SetDrvrTlsRevocationCheck(tcpsrv_t *pThis, int enabled) {
2219 DEFiRet;
2220 ISOBJ_TYPE_assert(pThis, tcpsrv);
2221 pThis->DrvrTlsRevocationCheck = (enabled != 0) ? 1 : 0;
2222 RETiRet;
2223 }
2224
2225
2226 /* End of methods to shuffle authentication settings to the driver.;
2227
2228 * -------------------------------------------------------------------------- */
2229
2230
2231 /* set max number of listeners
2232 * this must be called before ConstructFinalize, or it will have no effect!
2233 * rgerhards, 2009-08-17
2234 */
2235 static rsRetVal ATTR_NONNULL(1) SetLstnMax(tcpsrv_t *pThis, int iMax) {
2236 DEFiRet;
2237 ISOBJ_TYPE_assert(pThis, tcpsrv);
2238 pThis->iLstnMax = iMax;
2239 RETiRet;
2240 }
2241
2242
2243 /* set if flow control shall be supported
2244 */
2245 static rsRetVal ATTR_NONNULL(1) SetUseFlowControl(tcpsrv_t *pThis, int bUseFlowControl) {
2246 DEFiRet;
2247 ISOBJ_TYPE_assert(pThis, tcpsrv);
2248 pThis->bUseFlowControl = bUseFlowControl;
2249 RETiRet;
2250 }
2251
2252
2253 /* set max number of sessions
2254 * this must be called before ConstructFinalize, or it will have no effect!
2255 * rgerhards, 2009-04-09
2256 */
2257 static rsRetVal ATTR_NONNULL(1) SetSessMax(tcpsrv_t *pThis, int iMax) {
2258 DEFiRet;
2259 ISOBJ_TYPE_assert(pThis, tcpsrv);
2260 pThis->iSessMax = iMax;
2261 RETiRet;
2262 }
2263
2264
2265 static rsRetVal ATTR_NONNULL(1) SetPreserveCase(tcpsrv_t *pThis, int bPreserveCase) {
2266 DEFiRet;
2267 ISOBJ_TYPE_assert(pThis, tcpsrv);
2268 pThis->bPreserveCase = bPreserveCase;
2269 RETiRet;
2270 }
2271
2272
2273 static rsRetVal ATTR_NONNULL(1) SetSynBacklog(tcpsrv_t *pThis, const int iSynBacklog) {
2274 pThis->iSynBacklog = iSynBacklog;
2275 return RS_RET_OK;
2276 }
2277
2278
2279 static rsRetVal ATTR_NONNULL(1) SetStarvationMaxReads(tcpsrv_t *pThis, const unsigned int maxReads) {
2280 pThis->starvationMaxReads = maxReads;
2281 return RS_RET_OK;
2282 }
2283
2284
2285 static rsRetVal ATTR_NONNULL(1) SetNumWrkr(tcpsrv_t *pThis, const int numWrkr) {
2286 pThis->workQueue.numWrkr = numWrkr;
2287 return RS_RET_OK;
2288 }
2289
2290
2291 /* queryInterface function
2292 * rgerhards, 2008-02-29
2293 */
2294 BEGINobjQueryInterface(tcpsrv)
2295 CODESTARTobjQueryInterface(tcpsrv);
2296 if (pIf->ifVersion != tcpsrvCURR_IF_VERSION) { /* check for current version, increment on each change */
2297 ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED);
2298 }
2299
2300 /* ok, we have the right interface, so let's fill it
2301 * Please note that we may also do some backwards-compatibility
2302 * work here (if we can support an older interface version - that,
2303 * of course, also affects the "if" above).
2304 */
2305 pIf->DebugPrint = tcpsrvDebugPrint;
2306 pIf->Construct = tcpsrvConstruct;
2307 pIf->ConstructFinalize = tcpsrvConstructFinalize;
2308 pIf->Destruct = tcpsrvDestruct;
2309
2310 pIf->configureTCPListen = configureTCPListen;
2311 pIf->create_tcp_socket = create_tcp_socket;
2312 pIf->Run = Run;
2313
2314 pIf->SetNetworkNamespace = SetNetworkNamespace;
2315 pIf->SetKeepAlive = SetKeepAlive;
2316 pIf->SetKeepAliveIntvl = SetKeepAliveIntvl;
2317 pIf->SetKeepAliveProbes = SetKeepAliveProbes;
2318 pIf->SetKeepAliveTime = SetKeepAliveTime;
2319 pIf->SetGnutlsPriorityString = SetGnutlsPriorityString;
2320 pIf->SetUsrP = SetUsrP;
2321 pIf->SetInputName = SetInputName;
2322 pIf->SetOrigin = SetOrigin;
2323 pIf->SetDfltTZ = SetDfltTZ;
2324 pIf->SetbSPFramingFix = SetbSPFramingFix;
2325 pIf->SetAddtlFrameDelim = SetAddtlFrameDelim;
2326 pIf->SetMaxFrameSize = SetMaxFrameSize;
2327 pIf->SetbDisableLFDelim = SetbDisableLFDelim;
2328 pIf->SetDiscardTruncatedMsg = SetDiscardTruncatedMsg;
2329 pIf->SetSessMax = SetSessMax;
2330 pIf->SetUseFlowControl = SetUseFlowControl;
2331 pIf->SetLstnMax = SetLstnMax;
2332 pIf->SetDrvrMode = SetDrvrMode;
2333 pIf->SetDrvrAuthMode = SetDrvrAuthMode;
2334 pIf->SetDrvrPermitExpiredCerts = SetDrvrPermitExpiredCerts;
2335 pIf->SetDrvrCAFile = SetDrvrCAFile;
2336 pIf->SetDrvrCRLFile = SetDrvrCRLFile;
2337 pIf->SetDrvrKeyFile = SetDrvrKeyFile;
2338 pIf->SetDrvrCertFile = SetDrvrCertFile;
2339 pIf->SetDrvrName = SetDrvrName;
2340 pIf->SetDrvrPermPeers = SetDrvrPermPeers;
2341 pIf->SetCBIsPermittedHost = SetCBIsPermittedHost;
2342 pIf->SetCBOpenLstnSocks = SetCBOpenLstnSocks;
2343 pIf->SetCBRcvData = SetCBRcvData;
2344 pIf->SetCBOnListenDeinit = SetCBOnListenDeinit;
2345 pIf->SetCBOnSessAccept = SetCBOnSessAccept;
2346 pIf->SetCBOnSessConstructFinalize = SetCBOnSessConstructFinalize;
2347 pIf->SetCBOnSessDestruct = SetCBOnSessDestruct;
2348 pIf->SetCBOnDestruct = SetCBOnDestruct;
2349 pIf->SetCBOnRegularClose = SetCBOnRegularClose;
2350 pIf->SetCBOnErrClose = SetCBOnErrClose;
2351 pIf->SetOnMsgReceive = SetOnMsgReceive;
2352 pIf->SetLinuxLikeRatelimiters = SetLinuxLikeRatelimiters;
2353 pIf->SetNotificationOnRemoteClose = SetNotificationOnRemoteClose;
2354 pIf->SetNotificationOnRemoteOpen = SetNotificationOnRemoteOpen;
2355 pIf->SetPreserveCase = SetPreserveCase;
2356 pIf->SetDrvrCheckExtendedKeyUsage = SetDrvrCheckExtendedKeyUsage;
2357 pIf->SetDrvrPrioritizeSAN = SetDrvrPrioritizeSAN;
2358 pIf->SetDrvrTlsVerifyDepth = SetDrvrTlsVerifyDepth;
2359 pIf->SetDrvrTlsRevocationCheck = SetDrvrTlsRevocationCheck;
2360 pIf->SetSynBacklog = SetSynBacklog;
2361 pIf->SetNumWrkr = SetNumWrkr;
2362 pIf->SetStarvationMaxReads = SetStarvationMaxReads;
2363
2364 finalize_it:
2365 ENDobjQueryInterface(tcpsrv)
2366
2367
2368 /* exit our class
2369 * rgerhards, 2008-03-10
2370 */
2371 BEGINObjClassExit(tcpsrv, OBJ_IS_LOADABLE_MODULE) /* CHANGE class also in END MACRO! */
2372 CODESTARTObjClassExit(tcpsrv);
2373 /* release objects we no longer need */
2374 objRelease(tcps_sess, DONT_LOAD_LIB);
2375 objRelease(conf, CORE_COMPONENT);
2376 objRelease(prop, CORE_COMPONENT);
2377 objRelease(statsobj, CORE_COMPONENT);
2378 objRelease(ruleset, CORE_COMPONENT);
2379 objRelease(glbl, CORE_COMPONENT);
2380 objRelease(netstrms, DONT_LOAD_LIB);
2381 objRelease(netstrm, LM_NETSTRMS_FILENAME);
2382 objRelease(net, LM_NET_FILENAME);
2383 objRelease(regexp, LM_REGEXP_FILENAME);
2384 ENDObjClassExit(tcpsrv)
2385
2386
2387 /* Initialize our class. Must be called as the very first method
2388 * before anything else is called inside this class.
2389 * rgerhards, 2008-02-29
2390 */
2391 BEGINObjClassInit(tcpsrv, 1, OBJ_IS_LOADABLE_MODULE) /* class, version - CHANGE class also in END MACRO! */
2392 /* request objects we use */
2393 CHKiRet(objUse(net, LM_NET_FILENAME));
2394 CHKiRet(objUse(netstrms, LM_NETSTRMS_FILENAME));
2395 CHKiRet(objUse(netstrm, DONT_LOAD_LIB));
2396 CHKiRet(objUse(tcps_sess, DONT_LOAD_LIB));
2397 CHKiRet(objUse(conf, CORE_COMPONENT));
2398 CHKiRet(objUse(glbl, CORE_COMPONENT));
2399 CHKiRet(objUse(ruleset, CORE_COMPONENT));
2400 CHKiRet(objUse(statsobj, CORE_COMPONENT));
2401 CHKiRet(objUse(prop, CORE_COMPONENT));
2402 CHKiRet(objUse(regexp, LM_REGEXP_FILENAME));
2403
2404 /* set our own handlers */
2405 OBJSetMethodHandler(objMethod_DEBUGPRINT, tcpsrvDebugPrint);
2406 OBJSetMethodHandler(objMethod_CONSTRUCTION_FINALIZER, tcpsrvConstructFinalize);
2407 ENDObjClassInit(tcpsrv)
2408
2409
2410 /* --------------- here now comes the plumbing that makes as a library module --------------- */
2411
2412 BEGINmodExit
2413 CODESTARTmodExit;
2414 /* de-init in reverse order! */
2415 tcpsrvClassExit();
2416 tcps_sessClassExit();
2417 ENDmodExit
2418
2419
2420 BEGINqueryEtryPt
2421 CODESTARTqueryEtryPt;
2422 CODEqueryEtryPt_STD_LIB_QUERIES;
2423 ENDqueryEtryPt
2424
2425
2426 BEGINmodInit()
2427 CODESTARTmodInit;
2428 *ipIFVersProvided = CURR_MOD_IF_VERSION; /* we only support the current interface specification */
2429 /* Initialize all classes that are in our module - this includes ourselves */
2430 CHKiRet(tcps_sessClassInit(pModInfo));
2431 CHKiRet(tcpsrvClassInit(pModInfo)); /* must be done after tcps_sess, as we use it */
2432 ENDmodInit