Debian Codegraph @

runtime/tcpclt.c

raw
1 /* tcpclt.c
2 *
3 * This is the implementation of TCP-based syslog clients (the counterpart
4 * of the tcpsrv class).
5 *
6 * Copyright 2007-2024 Adiscon GmbH.
7 *
8 * This file is part of rsyslog.
9 *
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 * http://www.apache.org/licenses/LICENSE-2.0
15 * -or-
16 * see COPYING.ASL20 in the source distribution
17 *
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
23 */
24 #include "config.h"
25 #include <stdio.h>
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <errno.h>
31 #include <assert.h>
32 #include <limits.h>
33 #include <netinet/in.h>
34 #include <netdb.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #if HAVE_FCNTL_H
38 #include <fcntl.h>
39 #endif
40 #include "rsyslog.h"
41 #include "dirty.h"
42 #include "syslogd-types.h"
43 #include "net.h"
44 #include "tcpclt.h"
45 #include "module-template.h"
46 #include "srUtils.h"
47
48 MODULE_TYPE_LIB
49 MODULE_TYPE_NOKEEP;
50
51 /* static data */
52 DEFobjStaticHelpers;
53
54 /* Initialize TCP sockets (for sender)
55 */
56 static int CreateSocket(struct addrinfo *addrDest) {
57 int fd;
58 struct addrinfo *r;
59
60 r = addrDest;
61
62 while (r != NULL) {
63 fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
64 if (fd != -1) {
65 /* We can not allow the TCP sender to block syslogd, at least
66 * not in a single-threaded design. That would cause rsyslogd to
67 * loose input messages - which obviously also would affect
68 * other selector lines, too. So we do set it to non-blocking and
69 * handle the situation ourselfs (by discarding messages). IF we run
70 * dual-threaded, however, the situation is different: in this case,
71 * the receivers and the selector line processing are only loosely
72 * coupled via a memory buffer. Now, I think, we can afford the extra
73 * wait time. Thus, we enable blocking mode for TCP if we compile with
74 * pthreads. -- rgerhards, 2005-10-25
75 * And now, we always run on multiple threads... -- rgerhards, 2007-12-20
76 */
77 if (connect(fd, r->ai_addr, r->ai_addrlen) != 0) {
78 if (errno == EINPROGRESS) {
79 /* this is normal - will complete later select */
80 return fd;
81 } else {
82 char errStr[1024];
83 dbgprintf("create tcp connection failed, reason %s", rs_strerror_r(errno, errStr, sizeof(errStr)));
84 }
85
86 } else {
87 return fd;
88 }
89 close(fd);
90 } else {
91 char errStr[1024];
92 dbgprintf("couldn't create send socket, reason %s", rs_strerror_r(errno, errStr, sizeof(errStr)));
93 }
94 r = r->ai_next;
95 }
96
97 dbgprintf("no working socket could be obtained");
98
99 return -1;
100 }
101
102
103 /* Build frame based on selected framing
104 * This function was created by pulling code from TCPSend()
105 * on 2007-12-27 by rgerhards. Older comments are still relevant.
106 *
107 * In order to support compressed messages via TCP, we must support an
108 * octet-counting based framing (LF may be part of the compressed message).
109 * We are now supporting the same mode that is available in IETF I-D
110 * syslog-transport-tls-05 (current at the time of this writing). This also
111 * eases things when we go ahead and implement that framing. I have now made
112 * available two cases where this framing is used: either by explitely
113 * specifying it in the config file or implicitely when sending a compressed
114 * message. In the later case, compressed and uncompressed messages within
115 * the same session have different framings. If it is explicitely set to
116 * octet-counting, only this framing mode is used within the session.
117 * rgerhards, 2006-12-07
118 */
119 static rsRetVal TCPSendBldFrame(tcpclt_t *pThis, char **pmsg, size_t *plen, int *pbMustBeFreed) {
120 DEFiRet;
121 TCPFRAMINGMODE framingToUse;
122 int bIsCompressed;
123 size_t len;
124 size_t frameSize;
125 char *msg;
126 char *buf = NULL; /* if this is non-NULL, it MUST be freed before return! */
127
128 assert(plen != NULL);
129 assert(pbMustBeFreed != NULL);
130 assert(pmsg != NULL);
131
132 msg = *pmsg;
133 len = *plen;
134 bIsCompressed = *msg == 'z'; /* cache this, so that we can modify the message buffer */
135 /* select framing for this record. If we have a compressed record, we always need to
136 * use octet counting because the data potentially contains all control characters
137 * including LF.
138 */
139 framingToUse = bIsCompressed ? TCP_FRAMING_OCTET_COUNTING : pThis->tcp_framing;
140
141 /* now check if we need to add a line terminator. We need to
142 * copy the string in memory in this case, this is probably
143 * quicker than using writev and definitely quicker than doing
144 * two socket calls.
145 * rgerhards 2005-07-22
146 *
147 * Some messages already contain a \n character at the end
148 * of the message. We append one only if we there is not
149 * already one. This seems the best fit, though this also
150 * means the message does not arrive unaltered at the final
151 * destination. But in the spirit of legacy syslog, this is
152 * probably the best to do...
153 * rgerhards 2005-07-20
154 */
155
156 /* Build frame based on selected framing */
157 if (framingToUse == TCP_FRAMING_OCTET_STUFFING) {
158 if ((*(msg + len - 1) != pThis->tcp_framingDelimiter)) {
159 if (len > SIZE_MAX - 2) {
160 LogError(0, RS_RET_OUT_OF_MEMORY,
161 "Error: TCP frame too large to append framing delimiter safely. Message is lost.");
162 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
163 }
164
165 /* in the malloc below, we need to add 2 to the length. The
166 * reason is that we a) add one character and b) len does
167 * not take care of the '\0' byte. Up until today, it was just
168 * +1 , which caused rsyslogd to sometimes dump core.
169 * I have added this comment so that the logic is not accidently
170 * changed again. rgerhards, 2005-10-25
171 */
172 if ((buf = malloc(len + 2)) == NULL) {
173 /* extreme mem shortage, try to solve
174 * as good as we can. No point in calling
175 * any alarms, they might as well run out
176 * of memory (the risk is very high, so we
177 * do NOT risk that). If we have a message of
178 * more than 1 byte (what I guess), we simply
179 * overwrite the last character.
180 * rgerhards 2005-07-22
181 */
182 if (len > 1) {
183 *(msg + len - 1) = pThis->tcp_framingDelimiter;
184 } else {
185 /* we simply can not do anything in
186 * this case (its an error anyhow...).
187 */
188 }
189 } else {
190 /* we got memory, so we can copy the message */
191 memcpy(buf, msg, len); /* do not copy '\0' */
192 *(buf + len) = pThis->tcp_framingDelimiter;
193 *(buf + len + 1) = '\0';
194 msg = buf; /* use new one */
195 ++len; /* care for the \n */
196 }
197 }
198 } else {
199 /* Octect-Counting
200 * In this case, we need to always allocate a buffer. This is because
201 * we need to put a header in front of the message text
202 */
203 char szLenBuf[16];
204 int iLenBuf;
205
206 /* important: the printf-mask is "%d<sp>" because there must be a
207 * space after the len!
208 *//* The chairs of the IETF syslog-sec WG have announced that it is
209 * consensus to do the octet count on the SYSLOG-MSG part only. I am
210 * now changing the code to reflect this. Hopefully, it will not change
211 * once again (there can no compatibility layer programmed for this).
212 * To be on the save side, I just comment the code out. I mark these
213 * comments with "IETF20061218".
214 * rgerhards, 2006-12-19
215 */
216 if (len > (size_t)INT_MAX) {
217 LogError(0, RS_RET_OUT_OF_MEMORY,
218 "Error: TCP frame too large for octet-counted framing header. Message is lost.");
219 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
220 }
221 iLenBuf = snprintf(szLenBuf, sizeof(szLenBuf), "%d ", (int)len);
222 /* IETF20061218 iLenBuf =
223 snprintf(szLenBuf, sizeof(szLenBuf), "%d ", len + iLenBuf);*/
224 if (iLenBuf < 0) {
225 ABORT_FINALIZE(RS_RET_ERR);
226 }
227 if (len > SIZE_MAX - (size_t)iLenBuf) {
228 LogError(0, RS_RET_OUT_OF_MEMORY,
229 "Error: TCP frame too large to prepend octet-counted header safely. Message is lost.");
230 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
231 }
232 frameSize = len + (size_t)iLenBuf;
233
234 if ((buf = malloc(frameSize)) == NULL) {
235 /* we are out of memory. This is an extreme situation. We do not
236 * call any alarm handlers because they most likely run out of mem,
237 * too. We are brave enough to call debug output, though. Other than
238 * that, there is nothing left to do. We can not sent the message (as
239 * in case of the other framing, because the message is incomplete.
240 * We could, however, send two chunks (header and text separate), but
241 * that would cause a lot of complexity in the code. So we think it
242 * is appropriate enough to just make sure we do not crash in this
243 * very unlikely case. For this, it is justified just to loose
244 * the message. Rgerhards, 2006-12-07
245 */
246 dbgprintf(
247 "Error: out of memory when building TCP octet-counted "
248 "frame. Message is lost, trying to continue.\n");
249 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
250 }
251
252 memcpy(buf, szLenBuf, iLenBuf); /* header */
253 memcpy(buf + iLenBuf, msg, len); /* message */
254 len = frameSize; /* new message size */
255 msg = buf; /* set message buffer */
256 }
257
258 /* frame building complete, on to actual sending */
259
260 *plen = len;
261 if (buf == NULL) {
262 /* msg not modified */
263 *pbMustBeFreed = 0;
264 } else {
265 *pmsg = msg;
266 *pbMustBeFreed = 1;
267 }
268
269 finalize_it:
270 RETiRet;
271 }
272
273
274 /* Sends a TCP message. It is first checked if the
275 * session is open and, if not, it is opened. Then the send
276 * is tried. If it fails, one silent re-try is made. If the send
277 * fails again, an error status (-1) is returned. If all goes well,
278 * 0 is returned. The TCP session is NOT torn down.
279 * For now, EAGAIN is ignored (causing message loss) - but it is
280 * hard to do something intelligent in this case. With this
281 * implementation here, we can not block and/or defer. Things are
282 * probably a bit better when we move to liblogging. The alternative
283 * would be to enhance the current select server with buffering and
284 * write descriptors. This seems not justified, given the expected
285 * short life span of this code (and the unlikeliness of this event).
286 * rgerhards 2005-07-06
287 * This function is now expected to stay. Libloging won't be used for
288 * that purpose. I have added the param "len", because it is known by the
289 * caller and so saves us some time. Also, it MUST be given because there
290 * may be NULs inside msg so that we can not rely on strlen(). Please note
291 * that the restrictions outlined above do not existin in multi-threaded
292 * mode, which we assume will now be most often used. So there is no
293 * real issue with the potential message loss in single-threaded builds.
294 * rgerhards, 2006-11-30
295 * I greatly restructured the function to be more generic and work
296 * with function pointers. So it now can be used with any type of transport,
297 * as long as it follows stream semantics. This was initially done to
298 * support plain TCP and GSS via common code.
299 */
300 static int Send(tcpclt_t *pThis, void *pData, char *msg, size_t len) {
301 DEFiRet;
302 int bDone = 0;
303 int retry = 0;
304 int bMsgMustBeFreed = 0; /* must msg be freed at end of function? 0 - no, 1 - yes */
305
306 ISOBJ_TYPE_assert(pThis, tcpclt);
307 assert(pData != NULL);
308 assert(msg != NULL);
309 assert(len > 0);
310
311 CHKiRet(TCPSendBldFrame(pThis, &msg, &len, &bMsgMustBeFreed));
312
313 while (!bDone) { /* loop is broken when send succeeds or error occurs */
314 CHKiRet(pThis->initFunc(pData));
315 iRet = pThis->sendFunc(pData, msg, len);
316
317 if (iRet == RS_RET_OK || iRet == RS_RET_DEFER_COMMIT || iRet == RS_RET_PREVIOUS_COMMITTED) {
318 /* we are done, we also use this as indication that the previous
319 * message was succesfully received (it's not always the case, but its at
320 * least our best shot at it -- rgerhards, 2008-03-12
321 * As of 2008-06-09, we have implemented an algorithm which detects connection
322 * loss quite good in some (common) scenarios. Thus, the probability of
323 * message duplication due to the code below has increased. We so now have
324 * a config setting, default off, that enables the user to request retransmits.
325 * However, if not requested, we do NOT need to do all the stuff needed for it.
326 */
327 if (pThis->bResendLastOnRecon == 1) {
328 if (pThis->prevMsg != NULL) free(pThis->prevMsg);
329 /* if we can not alloc a new buffer, we silently ignore it. The worst that
330 * happens is that we lose our message recovery buffer - anything else would
331 * be worse, so don't try anything ;) -- rgerhards, 2008-03-12
332 */
333 if ((pThis->prevMsg = malloc(len)) != NULL) {
334 memcpy(pThis->prevMsg, msg, len);
335 pThis->lenPrevMsg = len;
336 }
337 }
338
339 /* we are done with this record */
340 bDone = 1;
341 } else {
342 if (retry == 0) { /* OK, one retry */
343 ++retry;
344 CHKiRet(pThis->prepRetryFunc(pData)); /* try to recover */
345 /* now try to send our stored previous message (which most probably
346 * didn't make it. Note that if bResendLastOnRecon is 0, prevMsg will
347 * never become non-NULL, so the check below covers all cases.
348 */
349 if (pThis->prevMsg != NULL) {
350 CHKiRet(pThis->initFunc(pData));
351 CHKiRet(pThis->sendFunc(pData, pThis->prevMsg, pThis->lenPrevMsg));
352 }
353 } else {
354 /* OK, max number of retries reached, nothing we can do */
355 bDone = 1;
356 }
357 }
358 }
359
360 finalize_it:
361 if (bMsgMustBeFreed) free(msg);
362 RETiRet;
363 }
364
365
366 /* set functions */
367 static rsRetVal SetResendLastOnRecon(tcpclt_t *pThis, const int bResendLastOnRecon) {
368 pThis->bResendLastOnRecon = (short)bResendLastOnRecon;
369 return RS_RET_OK;
370 }
371 static rsRetVal SetSendInit(tcpclt_t *pThis, rsRetVal (*pCB)(void *)) {
372 DEFiRet;
373 pThis->initFunc = pCB;
374 RETiRet;
375 }
376 static rsRetVal SetSendPrepRetry(tcpclt_t *pThis, rsRetVal (*pCB)(void *)) {
377 DEFiRet;
378 pThis->prepRetryFunc = pCB;
379 RETiRet;
380 }
381 static rsRetVal SetSendFrame(tcpclt_t *pThis, rsRetVal (*pCB)(void *, char *, size_t)) {
382 DEFiRet;
383 pThis->sendFunc = pCB;
384 RETiRet;
385 }
386 static rsRetVal SetFraming(tcpclt_t *pThis, TCPFRAMINGMODE framing) {
387 DEFiRet;
388 pThis->tcp_framing = framing;
389 RETiRet;
390 }
391 static rsRetVal SetFramingDelimiter(tcpclt_t *pThis, uchar tcp_framingDelimiter) {
392 DEFiRet;
393 pThis->tcp_framingDelimiter = tcp_framingDelimiter;
394 RETiRet;
395 }
396
397 /* Standard-Constructor
398 */
399 BEGINobjConstruct(tcpclt) /* be sure to specify the object type also in END macro! */
400 pThis->tcp_framingDelimiter = '\n';
401 ENDobjConstruct(tcpclt)
402
403
404 /* ConstructionFinalizer
405 */
406 static rsRetVal tcpcltConstructFinalize(tcpclt_t __attribute__((unused)) * pThis) {
407 DEFiRet;
408 ISOBJ_TYPE_assert(pThis, tcpclt);
409
410 RETiRet;
411 }
412
413
414 /* destructor for the tcpclt object */
415 BEGINobjDestruct(tcpclt) /* be sure to specify the object type also in END and CODESTART macros! */
416 CODESTARTobjDestruct(tcpclt);
417 if (pThis->prevMsg != NULL) free(pThis->prevMsg);
418 ENDobjDestruct(tcpclt)
419
420
421 /* ------------------------------ handling the interface plumbing ------------------------------ */
422
423 /* queryInterface function
424 * rgerhards, 2008-03-12
425 */
426 BEGINobjQueryInterface(tcpclt)
427 CODESTARTobjQueryInterface(tcpclt);
428 if (pIf->ifVersion != tcpcltCURR_IF_VERSION) { /* check for current version, increment on each change */
429 ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED);
430 }
431
432 /* ok, we have the right interface, so let's fill it
433 * Please note that we may also do some backwards-compatibility
434 * work here (if we can support an older interface version - that,
435 * of course, also affects the "if" above).
436 */
437 pIf->Construct = tcpcltConstruct;
438 pIf->ConstructFinalize = tcpcltConstructFinalize;
439 pIf->Destruct = tcpcltDestruct;
440
441 pIf->CreateSocket = CreateSocket;
442 pIf->Send = Send;
443
444 /* set functions */
445 pIf->SetResendLastOnRecon = SetResendLastOnRecon;
446 pIf->SetSendInit = SetSendInit;
447 pIf->SetSendFrame = SetSendFrame;
448 pIf->SetSendPrepRetry = SetSendPrepRetry;
449 pIf->SetFraming = SetFraming;
450 pIf->SetFramingDelimiter = SetFramingDelimiter;
451
452 finalize_it:
453 ENDobjQueryInterface(tcpclt)
454
455
456 /* exit our class
457 * rgerhards, 2008-03-10
458 */
459 BEGINObjClassExit(tcpclt, OBJ_IS_LOADABLE_MODULE) /* CHANGE class also in END MACRO! */
460 CODESTARTObjClassExit(tcpclt);
461 /* release objects we no longer need */
462 ENDObjClassExit(tcpclt)
463
464
465 /* Initialize our class. Must be called as the very first method
466 * before anything else is called inside this class.
467 * rgerhards, 2008-02-29
468 */
469 BEGINObjClassInit(tcpclt, 1, OBJ_IS_LOADABLE_MODULE) /* class, version - CHANGE class also in END MACRO! */
470 /* request objects we use */
471
472 /* set our own handlers */
473 OBJSetMethodHandler(objMethod_CONSTRUCTION_FINALIZER, tcpcltConstructFinalize);
474 ENDObjClassInit(tcpclt)
475
476
477 /* --------------- here now comes the plumbing that makes as a library module --------------- */
478
479
480 BEGINmodExit
481 CODESTARTmodExit;
482 /* de-init in reverse order! */
483 tcpcltClassExit();
484 ENDmodExit
485
486
487 BEGINqueryEtryPt
488 CODESTARTqueryEtryPt;
489 CODEqueryEtryPt_STD_LIB_QUERIES;
490 ENDqueryEtryPt
491
492
493 BEGINmodInit()
494 CODESTARTmodInit;
495 *ipIFVersProvided = CURR_MOD_IF_VERSION; /* we only support the current interface specification */
496
497 /* Initialize all classes that are in our module - this includes ourselves */
498 CHKiRet(tcpcltClassInit(pModInfo)); /* must be done after tcps_sess, as we use it */
499 ENDmodInit