~ubuntu-branches/ubuntu/lucid/rsyslog/lucid

« back to all changes in this revision

Viewing changes to omfwd.c

  • Committer: Bazaar Package Importer
  • Author(s): Michael Biebl
  • Date: 2007-10-19 17:21:49 UTC
  • Revision ID: james.westby@ubuntu.com-20071019172149-ie6ej2xve33mxiu7
Tags: upstream-1.19.10
ImportĀ upstreamĀ versionĀ 1.19.10

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* omfwd.c
 
2
 * This is the implementation of the build-in forwarding output module.
 
3
 *
 
4
 * NOTE: read comments in module-template.h to understand how this file
 
5
 *       works!
 
6
 *
 
7
 * File begun on 2007-07-20 by RGerhards (extracted from syslogd.c)
 
8
 * This file is under development and has not yet arrived at being fully
 
9
 * self-contained and a real object. So far, it is mostly an excerpt
 
10
 * of the "old" message code without any modifications. However, it
 
11
 * helps to have things at the right place one we go to the meat of it.
 
12
 *
 
13
 * Copyright 2007 Rainer Gerhards and Adiscon GmbH.
 
14
 *
 
15
 * This program is free software; you can redistribute it and/or
 
16
 * modify it under the terms of the GNU General Public License
 
17
 * as published by the Free Software Foundation; either version 2
 
18
 * of the License, or (at your option) any later version.
 
19
 *
 
20
 * This program is distributed in the hope that it will be useful,
 
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
23
 * GNU General Public License for more details.
 
24
 *
 
25
 * You should have received a copy of the GNU General Public License
 
26
 * along with this program; if not, write to the Free Software
 
27
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
28
 *
 
29
 * A copy of the GPL can be found in the file "COPYING" in this distribution.
 
30
 */
 
31
#include "config.h"
 
32
#ifdef SYSLOG_INET
 
33
#include "rsyslog.h"
 
34
#include <stdio.h>
 
35
#include <stdarg.h>
 
36
#include <stdlib.h>
 
37
#include <string.h>
 
38
#include <time.h>
 
39
#include <netinet/in.h>
 
40
#include <netdb.h>
 
41
#include <fnmatch.h>
 
42
#include <assert.h>
 
43
#include <errno.h>
 
44
#include <ctype.h>
 
45
#include <unistd.h>
 
46
#ifdef USE_PTHREADS
 
47
#include <pthread.h>
 
48
#else
 
49
#include <fcntl.h>
 
50
#endif
 
51
#include "syslogd.h"
 
52
#include "syslogd-types.h"
 
53
#include "srUtils.h"
 
54
#include "net.h"
 
55
#include "omfwd.h"
 
56
#include "template.h"
 
57
#include "msg.h"
 
58
#include "tcpsyslog.h"
 
59
#include "module-template.h"
 
60
 
 
61
#ifdef SYSLOG_INET
 
62
//#define INET_SUSPEND_TIME 60          /* equal to 1 minute 
 
63
#define INET_SUSPEND_TIME 2             /* equal to 1 minute 
 
64
                                         * rgerhards, 2005-07-26: This was 3 minutes. As the
 
65
                                         * same timer is used for tcp based syslog, we have
 
66
                                         * reduced it. However, it might actually be worth
 
67
                                         * thinking about a buffered tcp sender, which would be 
 
68
                                         * a much better alternative. When that happens, this
 
69
                                         * time here can be re-adjusted to 3 minutes (or,
 
70
                                         * even better, made configurable).
 
71
                                         */
 
72
#define INET_RETRY_MAX 30               /* maximum of retries for gethostbyname() */
 
73
        /* was 10, changed to 30 because we reduced INET_SUSPEND_TIME by one third. So
 
74
         * this "fixes" some of implications of it (see comment on INET_SUSPEND_TIME).
 
75
         * rgerhards, 2005-07-26
 
76
         */
 
77
#endif
 
78
 
 
79
/* internal structures
 
80
 */
 
81
DEF_OMOD_STATIC_DATA
 
82
 
 
83
typedef struct _instanceData {
 
84
        char    f_hname[MAXHOSTNAMELEN+1];
 
85
        short   sock;                   /* file descriptor */
 
86
        enum { /* TODO: we shoud revisit these definitions */
 
87
                eDestFORW,
 
88
                eDestFORW_SUSP,
 
89
                eDestFORW_UNKN
 
90
        } eDestState;
 
91
        int iRtryCnt;
 
92
        struct addrinfo *f_addr;
 
93
        int compressionLevel; /* 0 - no compression, else level for zlib */
 
94
        char *port;
 
95
        int protocol;
 
96
        TCPFRAMINGMODE tcp_framing;
 
97
#       define  FORW_UDP 0
 
98
#       define  FORW_TCP 1
 
99
        /* following fields for TCP-based delivery */
 
100
        enum TCPSendStatus {
 
101
                TCP_SEND_NOTCONNECTED = 0,
 
102
                TCP_SEND_CONNECTING = 1,
 
103
                TCP_SEND_READY = 2
 
104
        } status;
 
105
        char *savedMsg;
 
106
        int savedMsgLen; /* length of savedMsg in octets */
 
107
        time_t  ttSuspend;      /* time selector was suspended */
 
108
#       ifdef USE_PTHREADS
 
109
        pthread_mutex_t mtxTCPSend;
 
110
#       endif
 
111
} instanceData;
 
112
 
 
113
 
 
114
BEGINcreateInstance
 
115
CODESTARTcreateInstance
 
116
ENDcreateInstance
 
117
 
 
118
 
 
119
BEGINisCompatibleWithFeature
 
120
CODESTARTisCompatibleWithFeature
 
121
        if(eFeat == sFEATURERepeatedMsgReduction)
 
122
                iRet = RS_RET_OK;
 
123
ENDisCompatibleWithFeature
 
124
 
 
125
 
 
126
BEGINfreeInstance
 
127
CODESTARTfreeInstance
 
128
        switch (pData->eDestState) {
 
129
                case eDestFORW:
 
130
                case eDestFORW_SUSP:
 
131
                        freeaddrinfo(pData->f_addr);
 
132
                        /* fall through */
 
133
                case eDestFORW_UNKN:
 
134
                        if(pData->port != NULL)
 
135
                                free(pData->port);
 
136
                        break;
 
137
        }
 
138
#       ifdef USE_PTHREADS
 
139
        /* delete any mutex objects, if present */
 
140
        if(pData->protocol == FORW_TCP) {
 
141
                pthread_mutex_destroy(&pData->mtxTCPSend);
 
142
        }
 
143
#       endif
 
144
ENDfreeInstance
 
145
 
 
146
 
 
147
BEGINdbgPrintInstInfo
 
148
CODESTARTdbgPrintInstInfo
 
149
        printf("%s", pData->f_hname);
 
150
ENDdbgPrintInstInfo
 
151
 
 
152
/* CODE FOR SENDING TCP MESSAGES */
 
153
 
 
154
/* get send status
 
155
 * rgerhards, 2005-10-24
 
156
 */
 
157
static void TCPSendSetStatus(instanceData *pData, enum TCPSendStatus iNewState)
 
158
{
 
159
        assert(pData != NULL);
 
160
        assert(pData->protocol == FORW_TCP);
 
161
        assert(   (iNewState == TCP_SEND_NOTCONNECTED)
 
162
               || (iNewState == TCP_SEND_CONNECTING)
 
163
               || (iNewState == TCP_SEND_READY));
 
164
 
 
165
        /* there can potentially be a race condition, so guard by mutex */
 
166
#       ifdef   USE_PTHREADS
 
167
                pthread_mutex_lock(&pData->mtxTCPSend);
 
168
#       endif
 
169
        pData->status = iNewState;
 
170
#       ifdef   USE_PTHREADS
 
171
                pthread_mutex_unlock(&pData->mtxTCPSend);
 
172
#       endif
 
173
}
 
174
 
 
175
 
 
176
/* set send status
 
177
 * rgerhards, 2005-10-24
 
178
 */
 
179
static enum TCPSendStatus TCPSendGetStatus(instanceData *pData)
 
180
{
 
181
        enum TCPSendStatus eState;
 
182
        assert(pData != NULL);
 
183
        assert(pData->protocol == FORW_TCP);
 
184
 
 
185
        /* there can potentially be a race condition, so guard by mutex */
 
186
#       ifdef   USE_PTHREADS
 
187
                pthread_mutex_lock(&pData->mtxTCPSend);
 
188
#       endif
 
189
        eState = pData->status;
 
190
#       ifdef   USE_PTHREADS
 
191
                pthread_mutex_unlock(&pData->mtxTCPSend);
 
192
#       endif
 
193
 
 
194
        return eState;
 
195
}
 
196
 
 
197
 
 
198
/* Initialize TCP sockets (for sender)
 
199
 * This is done once per selector line, if not yet initialized.
 
200
 */
 
201
static int TCPSendCreateSocket(instanceData *pData, struct addrinfo *addrDest)
 
202
{
 
203
        int fd;
 
204
        struct addrinfo *r; 
 
205
        
 
206
        assert(pData != NULL);
 
207
        
 
208
        r = addrDest;
 
209
 
 
210
        while(r != NULL) {
 
211
                fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
 
212
                if (fd != -1) {
 
213
                        /* We can not allow the TCP sender to block syslogd, at least
 
214
                         * not in a single-threaded design. That would cause rsyslogd to
 
215
                         * loose input messages - which obviously also would affect
 
216
                         * other selector lines, too. So we do set it to non-blocking and 
 
217
                         * handle the situation ourselfs (by discarding messages). IF we run
 
218
                         * dual-threaded, however, the situation is different: in this case,
 
219
                         * the receivers and the selector line processing are only loosely
 
220
                         * coupled via a memory buffer. Now, I think, we can afford the extra
 
221
                         * wait time. Thus, we enable blocking mode for TCP if we compile with
 
222
                         * pthreads.
 
223
                         * rgerhards, 2005-10-25
 
224
                         */
 
225
#       ifndef USE_PTHREADS
 
226
                        /* set to nonblocking - rgerhards 2005-07-20 */
 
227
                        fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
 
228
#       endif           
 
229
                        if (connect (fd, r->ai_addr, r->ai_addrlen) != 0) {
 
230
                                if(errno == EINPROGRESS) {
 
231
                                        /* this is normal - will complete during select */
 
232
                                        TCPSendSetStatus(pData, TCP_SEND_CONNECTING);
 
233
                                        return fd;
 
234
                                } else {
 
235
                                        char errStr[1024];
 
236
                                        dbgprintf("create tcp connection failed, reason %s",
 
237
                                                strerror_r(errno, errStr, sizeof(errStr)));
 
238
                                }
 
239
 
 
240
                        }
 
241
                        else {
 
242
                                TCPSendSetStatus(pData, TCP_SEND_READY);
 
243
                                return fd;
 
244
                        }
 
245
                        close(fd);
 
246
                }
 
247
                else {
 
248
                        char errStr[1024];
 
249
                        dbgprintf("couldn't create send socket, reason %s", strerror_r(errno, errStr, sizeof(errStr)));
 
250
                }               
 
251
                r = r->ai_next;
 
252
        }
 
253
 
 
254
        dbgprintf("no working socket could be obtained");
 
255
 
 
256
        return -1;
 
257
}
 
258
 
 
259
/* Sends a TCP message. It is first checked if the
 
260
 * session is open and, if not, it is opened. Then the send
 
261
 * is tried. If it fails, one silent re-try is made. If the send
 
262
 * fails again, an error status (-1) is returned. If all goes well,
 
263
 * 0 is returned. The TCP session is NOT torn down.
 
264
 * For now, EAGAIN is ignored (causing message loss) - but it is
 
265
 * hard to do something intelligent in this case. With this
 
266
 * implementation here, we can not block and/or defer. Things are
 
267
 * probably a bit better when we move to liblogging. The alternative
 
268
 * would be to enhance the current select server with buffering and
 
269
 * write descriptors. This seems not justified, given the expected
 
270
 * short life span of this code (and the unlikeliness of this event).
 
271
 * rgerhards 2005-07-06
 
272
 * This function is now expected to stay. Libloging won't be used for
 
273
 * that purpose. I have added the param "len", because it is known by the
 
274
 * caller and so safes us some time. Also, it MUST be given because there
 
275
 * may be NULs inside msg so that we can not rely on strlen(). Please note
 
276
 * that the restrictions outlined above do not existin in multi-threaded
 
277
 * mode, which we assume will now be most often used. So there is no
 
278
 * real issue with the potential message loss in single-threaded builds.
 
279
 * rgerhards, 2006-11-30
 
280
 * 
 
281
 * In order to support compressed messages via TCP, we must support an
 
282
 * octet-counting based framing (LF may be part of the compressed message).
 
283
 * We are now supporting the same mode that is available in IETF I-D
 
284
 * syslog-transport-tls-05 (current at the time of this writing). This also
 
285
 * eases things when we go ahead and implement that framing. I have now made
 
286
 * available two cases where this framing is used: either by explitely
 
287
 * specifying it in the config file or implicitely when sending a compressed
 
288
 * message. In the later case, compressed and uncompressed messages within
 
289
 * the same session have different framings. If it is explicitely set to
 
290
 * octet-counting, only this framing mode is used within the session.
 
291
 * rgerhards, 2006-12-07
 
292
 */
 
293
static int TCPSend(instanceData *pData, char *msg, size_t len)
 
294
{
 
295
        int retry = 0;
 
296
        int done = 0;
 
297
        int bIsCompressed;
 
298
        int lenSend;
 
299
        char *buf = NULL;       /* if this is non-NULL, it MUST be freed before return! */
 
300
        enum TCPSendStatus eState;
 
301
        TCPFRAMINGMODE framingToUse;
 
302
 
 
303
        assert(pData != NULL);
 
304
        assert(msg != NULL);
 
305
        assert(len > 0);
 
306
 
 
307
        bIsCompressed = *msg == 'z';    /* cache this, so that we can modify the message buffer */
 
308
        /* select framing for this record. If we have a compressed record, we always need to
 
309
         * use octet counting because the data potentially contains all control characters
 
310
         * including LF.
 
311
         */
 
312
        framingToUse = bIsCompressed ? TCP_FRAMING_OCTET_COUNTING : pData->tcp_framing;
 
313
 
 
314
        do { /* try to send message */
 
315
                if(pData->sock <= 0) {
 
316
                        /* we need to open the socket first */
 
317
                        if((pData->sock = TCPSendCreateSocket(pData, pData->f_addr)) <= 0) {
 
318
                                return -1;
 
319
                        }
 
320
                }
 
321
 
 
322
                eState = TCPSendGetStatus(pData); /* cache info */
 
323
 
 
324
                if(eState == TCP_SEND_CONNECTING) {
 
325
                        /* In this case, we save the buffer. If we have a
 
326
                         * system with few messages, that hopefully prevents
 
327
                         * message loss at all. However, we make no further attempts,
 
328
                         * just the first message is saved. So we only try this
 
329
                         * if there is not yet a saved message present.
 
330
                         * rgerhards 2005-07-20
 
331
                         */
 
332
                        if(pData->savedMsg == NULL) {
 
333
                                pData->savedMsg = malloc(len * sizeof(char));
 
334
                                if(pData->savedMsg == NULL)
 
335
                                        return 0; /* nothing we can do... */
 
336
                                memcpy(pData->savedMsg, msg, len);
 
337
                                pData->savedMsgLen = len;
 
338
                        }
 
339
                        return 0;
 
340
                } else if(eState != TCP_SEND_READY)
 
341
                        /* This here is debatable. For the time being, we
 
342
                         * accept the loss of a single message (e.g. during
 
343
                         * connection setup in favour of not messing with
 
344
                         * wait time and timeouts. The reason is that such
 
345
                         * things might otherwise cost us considerable message
 
346
                         * loss on the receiving side (even at a timeout set
 
347
                         * to just 1 second).  - rgerhards 2005-07-20
 
348
                         */
 
349
                        return 0;
 
350
 
 
351
                /* now check if we need to add a line terminator. We need to
 
352
                 * copy the string in memory in this case, this is probably
 
353
                 * quicker than using writev and definitely quicker than doing
 
354
                 * two socket calls.
 
355
                 * rgerhards 2005-07-22
 
356
                 *//*
 
357
                 * Some messages already contain a \n character at the end
 
358
                 * of the message. We append one only if we there is not
 
359
                 * already one. This seems the best fit, though this also
 
360
                 * means the message does not arrive unaltered at the final
 
361
                 * destination. But in the spirit of legacy syslog, this is
 
362
                 * probably the best to do...
 
363
                 * rgerhards 2005-07-20
 
364
                 */
 
365
 
 
366
                /* Build frame based on selected framing */
 
367
                if(framingToUse == TCP_FRAMING_OCTET_STUFFING) {
 
368
                        if((*(msg+len-1) != '\n')) {
 
369
                                if(buf != NULL)
 
370
                                        free(buf);
 
371
                                /* in the malloc below, we need to add 2 to the length. The
 
372
                                 * reason is that we a) add one character and b) len does
 
373
                                 * not take care of the '\0' byte. Up until today, it was just
 
374
                                 * +1 , which caused rsyslogd to sometimes dump core.
 
375
                                 * I have added this comment so that the logic is not accidently
 
376
                                 * changed again. rgerhards, 2005-10-25
 
377
                                 */
 
378
                                if((buf = malloc((len + 2) * sizeof(char))) == NULL) {
 
379
                                        /* extreme mem shortage, try to solve
 
380
                                         * as good as we can. No point in calling
 
381
                                         * any alarms, they might as well run out
 
382
                                         * of memory (the risk is very high, so we
 
383
                                         * do NOT risk that). If we have a message of
 
384
                                         * more than 1 byte (what I guess), we simply
 
385
                                         * overwrite the last character.
 
386
                                         * rgerhards 2005-07-22
 
387
                                         */
 
388
                                        if(len > 1) {
 
389
                                                *(msg+len-1) = '\n';
 
390
                                        } else {
 
391
                                                /* we simply can not do anything in
 
392
                                                 * this case (its an error anyhow...).
 
393
                                                 */
 
394
                                        }
 
395
                                } else {
 
396
                                        /* we got memory, so we can copy the message */
 
397
                                        memcpy(buf, msg, len); /* do not copy '\0' */
 
398
                                        *(buf+len) = '\n';
 
399
                                        *(buf+len+1) = '\0';
 
400
                                        msg = buf; /* use new one */
 
401
                                        ++len; /* care for the \n */
 
402
                                }
 
403
                        }
 
404
                } else {
 
405
                        /* Octect-Counting
 
406
                         * In this case, we need to always allocate a buffer. This is because
 
407
                         * we need to put a header in front of the message text
 
408
                         */
 
409
                        char szLenBuf[16];
 
410
                        int iLenBuf;
 
411
 
 
412
                        /* important: the printf-mask is "%d<sp>" because there must be a
 
413
                         * space after the len!
 
414
                         *//* The chairs of the IETF syslog-sec WG have announced that it is
 
415
                         * consensus to do the octet count on the SYSLOG-MSG part only. I am
 
416
                         * now changing the code to reflect this. Hopefully, it will not change
 
417
                         * once again (there can no compatibility layer programmed for this).
 
418
                         * To be on the save side, I just comment the code out. I mark these
 
419
                         * comments with "IETF20061218".
 
420
                         * rgerhards, 2006-12-19
 
421
                         */
 
422
                        iLenBuf = snprintf(szLenBuf, sizeof(szLenBuf)/sizeof(char), "%d ", (int) len);
 
423
                        /* IETF20061218 iLenBuf =
 
424
                          snprintf(szLenBuf, sizeof(szLenBuf)/sizeof(char), "%d ", len + iLenBuf);*/
 
425
 
 
426
                        if((buf = malloc((len + iLenBuf) * sizeof(char))) == NULL) {
 
427
                                /* we are out of memory. This is an extreme situation. We do not
 
428
                                 * call any alarm handlers because they most likely run out of mem,
 
429
                                 * too. We are brave enough to call debug output, though. Other than
 
430
                                 * that, there is nothing left to do. We can not sent the message (as
 
431
                                 * in case of the other framing, because the message is incomplete.
 
432
                                 * We could, however, send two chunks (header and text separate), but
 
433
                                 * that would cause a lot of complexity in the code. So we think it
 
434
                                 * is appropriate enough to just make sure we do not crash in this
 
435
                                 * very unlikely case. For this, it is justified just to loose
 
436
                                 * the message. Rgerhards, 2006-12-07
 
437
                                 */
 
438
                                 dbgprintf("Error: out of memory when building TCP octet-counted "
 
439
                                         "frame. Message is lost, trying to continue.\n");
 
440
                                return 0;
 
441
                        }
 
442
 
 
443
                         memcpy(buf, szLenBuf, iLenBuf); /* header */
 
444
                         memcpy(buf + iLenBuf, msg, len); /* message */
 
445
                         len += iLenBuf;        /* new message size */
 
446
                         msg = buf;     /* set message buffer */
 
447
                }
 
448
 
 
449
                /* frame building complete, on to actual sending */
 
450
 
 
451
                lenSend = send(pData->sock, msg, len, 0);
 
452
                dbgprintf("TCP sent %d bytes, requested %d, msg: '%s'\n", lenSend, len,
 
453
                        bIsCompressed ? "***compressed***" : msg);
 
454
                if((unsigned)lenSend == len) {
 
455
                        /* all well */
 
456
                        if(buf != NULL) {
 
457
                                free(buf);
 
458
                        }
 
459
                        return 0;
 
460
                } else if(lenSend != -1) {
 
461
                        /* no real error, could "just" not send everything... 
 
462
                         * For the time being, we ignore this...
 
463
                         * rgerhards, 2005-10-25
 
464
                         */
 
465
                        dbgprintf("message not completely (tcp)send, ignoring %d\n", lenSend);
 
466
#                       if USE_PTHREADS
 
467
                        usleep(1000); /* experimental - might be benefitial in this situation */
 
468
#                       endif
 
469
                        if(buf != NULL)
 
470
                                free(buf);
 
471
                        return 0;
 
472
                }
 
473
 
 
474
                switch(errno) {
 
475
                case EMSGSIZE:
 
476
                        dbgprintf("message not (tcp)send, too large\n");
 
477
                        /* This is not a real error, so it is not flagged as one */
 
478
                        if(buf != NULL)
 
479
                                free(buf);
 
480
                        return 0;
 
481
                        break;
 
482
                case EINPROGRESS:
 
483
                case EAGAIN:
 
484
                        dbgprintf("message not (tcp)send, would block\n");
 
485
#                       if USE_PTHREADS
 
486
                        usleep(1000); /* experimental - might be benefitial in this situation */
 
487
#                       endif
 
488
                        /* we loose this message, but that's better than loosing
 
489
                         * all ;)
 
490
                         */
 
491
                        /* This is not a real error, so it is not flagged as one */
 
492
                        if(buf != NULL)
 
493
                                free(buf);
 
494
                        return 0;
 
495
                        break;
 
496
                default:
 
497
                        dbgprintf("message not (tcp)send");
 
498
                        break;
 
499
                }
 
500
        
 
501
                if(retry == 0) {
 
502
                        ++retry;
 
503
                        /* try to recover */
 
504
                        close(pData->sock);
 
505
                        TCPSendSetStatus(pData, TCP_SEND_NOTCONNECTED);
 
506
                        pData->sock = -1;
 
507
                } else {
 
508
                        if(buf != NULL)
 
509
                                free(buf);
 
510
                        return -1;
 
511
                }
 
512
        } while(!done); /* warning: do ... while() */
 
513
        /*NOT REACHED*/
 
514
 
 
515
        if(buf != NULL)
 
516
                free(buf);
 
517
        return -1; /* only to avoid compiler warning! */
 
518
}
 
519
 
 
520
 
 
521
/* get the syslog forward port from selector_t. The passed in
 
522
 * struct must be one that is setup for forwarding.
 
523
 * rgerhards, 2007-06-28
 
524
 * We may change the implementation to try to lookup the port
 
525
 * if it is unspecified. So far, we use the IANA default auf 514.
 
526
 */
 
527
static char *getFwdSyslogPt(instanceData *pData)
 
528
{
 
529
        assert(pData != NULL);
 
530
        if(pData->port == NULL)
 
531
                return("514");
 
532
        else
 
533
                return(pData->port);
 
534
}
 
535
 
 
536
 
 
537
/* try to resume connection if it is not ready
 
538
 * rgerhards, 2007-08-02
 
539
 */
 
540
static rsRetVal doTryResume(instanceData *pData)
 
541
{
 
542
        DEFiRet;
 
543
        struct addrinfo *res;
 
544
        struct addrinfo hints;
 
545
        unsigned e;
 
546
 
 
547
        switch (pData->eDestState) {
 
548
        case eDestFORW_SUSP:
 
549
                iRet = RS_RET_OK; /* the actual check happens during doAction() only */
 
550
                pData->eDestState = eDestFORW;
 
551
                break;
 
552
                
 
553
        case eDestFORW_UNKN:
 
554
                /* The remote address is not yet known and needs to be obtained */
 
555
                dbgprintf(" %s\n", pData->f_hname);
 
556
                memset(&hints, 0, sizeof(hints));
 
557
                /* port must be numeric, because config file syntax requests this */
 
558
                /* TODO: this code is a duplicate from cfline() - we should later create
 
559
                 * a common function.
 
560
                 */
 
561
                hints.ai_flags = AI_NUMERICSERV;
 
562
                hints.ai_family = family;
 
563
                hints.ai_socktype = pData->protocol == FORW_UDP ? SOCK_DGRAM : SOCK_STREAM;
 
564
                if((e = getaddrinfo(pData->f_hname,
 
565
                                    getFwdSyslogPt(pData), &hints, &res)) == 0) {
 
566
                        dbgprintf("%s found, resuming.\n", pData->f_hname);
 
567
                        pData->f_addr = res;
 
568
                        pData->iRtryCnt = 0;
 
569
                        pData->eDestState = eDestFORW;
 
570
                } else {
 
571
                        iRet = RS_RET_SUSPENDED;
 
572
                }
 
573
                break;
 
574
        case eDestFORW:
 
575
                /* rgerhards, 2007-09-11: this can not happen, but I've included it to
 
576
                 * a) make the compiler happy, b) detect any logic errors */
 
577
                assert(0);
 
578
                break;
 
579
        }
 
580
 
 
581
        return iRet;
 
582
}
 
583
 
 
584
 
 
585
BEGINtryResume
 
586
CODESTARTtryResume
 
587
        iRet = doTryResume(pData);
 
588
ENDtryResume
 
589
 
 
590
BEGINdoAction
 
591
        char *psz; /* temporary buffering */
 
592
        register unsigned l;
 
593
        struct addrinfo *r;
 
594
        int i;
 
595
        unsigned lsent = 0;
 
596
        int bSendSuccess;
 
597
CODESTARTdoAction
 
598
        switch (pData->eDestState) {
 
599
        case eDestFORW_SUSP:
 
600
                dbgprintf("internal error in omfwd.c, eDestFORW_SUSP in doAction()!\n");
 
601
                iRet = RS_RET_SUSPENDED;
 
602
                break;
 
603
                
 
604
        case eDestFORW_UNKN:
 
605
                dbgprintf("doAction eDestFORW_UNKN\n");
 
606
                iRet = doTryResume(pData);
 
607
                break;
 
608
 
 
609
        case eDestFORW:
 
610
                dbgprintf(" %s:%s/%s\n", pData->f_hname, getFwdSyslogPt(pData),
 
611
                         pData->protocol == FORW_UDP ? "udp" : "tcp");
 
612
                if ( 0) // TODO: think about this strcmp(getHOSTNAME(f->f_pMsg), LocalHostName) && NoHops )
 
613
                /* what we need to do is get the hostname as an additonal string (during parseSe..). Then,
 
614
                 * we can compare that string to LocalHostName. That way, we do not need to access the
 
615
                 * msgobject, and everything is clean. The question remains, though, if that functionality
 
616
                 * here actually makes sense or not. If we really need it, it might make more sense to compare
 
617
                 * the target IP address to the IP addresses of the local machene - that is a far better way of
 
618
                 * handling things than to relay on the error-prone hostname property.
 
619
                 * rgerhards, 2007-07-27
 
620
                 */
 
621
                        dbgprintf("Not sending message to remote.\n");
 
622
                else {
 
623
                        pData->ttSuspend = time(NULL);
 
624
                        psz = (char*) ppString[0];
 
625
                        l = strlen((char*) psz);
 
626
                        if (l > MAXLINE)
 
627
                                l = MAXLINE;
 
628
 
 
629
#                       ifdef   USE_NETZIP
 
630
                        /* Check if we should compress and, if so, do it. We also
 
631
                         * check if the message is large enough to justify compression.
 
632
                         * The smaller the message, the less likely is a gain in compression.
 
633
                         * To save CPU cycles, we do not try to compress very small messages.
 
634
                         * What "very small" means needs to be configured. Currently, it is
 
635
                         * hard-coded but this may be changed to a config parameter.
 
636
                         * rgerhards, 2006-11-30
 
637
                         */
 
638
                        if(pData->compressionLevel && (l > MIN_SIZE_FOR_COMPRESS)) {
 
639
                                Bytef out[MAXLINE+MAXLINE/100+12] = "z";
 
640
                                uLongf destLen = sizeof(out) / sizeof(Bytef);
 
641
                                uLong srcLen = l;
 
642
                                int ret;
 
643
                                ret = compress2((Bytef*) out+1, &destLen, (Bytef*) psz,
 
644
                                                srcLen, pData->compressionLevel);
 
645
                                dbgprintf("Compressing message, length was %d now %d, return state  %d.\n",
 
646
                                        l, (int) destLen, ret);
 
647
                                if(ret != Z_OK) {
 
648
                                        /* if we fail, we complain, but only in debug mode
 
649
                                         * Otherwise, we are silent. In any case, we ignore the
 
650
                                         * failed compression and just sent the uncompressed
 
651
                                         * data, which is still valid. So this is probably the
 
652
                                         * best course of action.
 
653
                                         * rgerhards, 2006-11-30
 
654
                                         */
 
655
                                        dbgprintf("Compression failed, sending uncompressed message\n");
 
656
                                } else if(destLen+1 < l) {
 
657
                                        /* only use compression if there is a gain in using it! */
 
658
                                        dbgprintf("there is gain in compression, so we do it\n");
 
659
                                        psz = (char*) out;
 
660
                                        l = destLen + 1; /* take care for the "z" at message start! */
 
661
                                }
 
662
                                ++destLen;
 
663
                        }
 
664
#                       endif
 
665
 
 
666
                        if(pData->protocol == FORW_UDP) {
 
667
                                /* forward via UDP */
 
668
                                if(finet != NULL) {
 
669
                                        /* we need to track if we have success sending to the remote
 
670
                                         * peer. Success is indicated by at least one sendto() call
 
671
                                         * succeeding. We track this be bSendSuccess. We can not simply
 
672
                                         * rely on lsent, as a call might initially work, but a later
 
673
                                         * call fails. Then, lsent has the error status, even though
 
674
                                         * the sendto() succeeded.
 
675
                                         * rgerhards, 2007-06-22
 
676
                                         */
 
677
                                        bSendSuccess = FALSE;
 
678
                                        for (r = pData->f_addr; r; r = r->ai_next) {
 
679
                                                for (i = 0; i < *finet; i++) {
 
680
                                                       lsent = sendto(finet[i+1], psz, l, 0,
 
681
                                                                      r->ai_addr, r->ai_addrlen);
 
682
                                                        if (lsent == l) {
 
683
                                                                bSendSuccess = TRUE;
 
684
                                                                break;
 
685
                                                        } else {
 
686
                                                                int eno = errno;
 
687
                                                                char errStr[1024];
 
688
                                                                dbgprintf("sendto() error: %d = %s.\n",
 
689
                                                                        eno, strerror_r(eno, errStr, sizeof(errStr)));
 
690
                                                        }
 
691
                                                }
 
692
                                                if (lsent == l && !send_to_all)
 
693
                                                       break;
 
694
                                        }
 
695
                                        /* finished looping */
 
696
                                        if (bSendSuccess == FALSE) {
 
697
                                                dbgprintf("error forwarding via udp, suspending\n");
 
698
                                                iRet = RS_RET_SUSPENDED;
 
699
                                        }
 
700
                                }
 
701
                        } else {
 
702
                                /* forward via TCP */
 
703
                                if(TCPSend(pData, psz, l) != 0) {
 
704
                                        /* error! */
 
705
                                        dbgprintf("error forwarding via tcp, suspending\n");
 
706
                                        iRet = RS_RET_SUSPENDED;
 
707
                                }
 
708
                        }
 
709
                }
 
710
                break;
 
711
        }
 
712
ENDdoAction
 
713
 
 
714
 
 
715
BEGINparseSelectorAct
 
716
        uchar *q;
 
717
        int i;
 
718
        int error;
 
719
        int bErr;
 
720
        struct addrinfo hints, *res;
 
721
CODESTARTparseSelectorAct
 
722
CODE_STD_STRING_REQUESTparseSelectorAct(1)
 
723
        if(*p == '@') {
 
724
                if((iRet = createInstance(&pData)) != RS_RET_OK)
 
725
                        goto finalize_it;
 
726
                ++p; /* eat '@' */
 
727
                if(*p == '@') { /* indicator for TCP! */
 
728
                        pData->protocol = FORW_TCP;
 
729
                        ++p; /* eat this '@', too */
 
730
                        /* in this case, we also need a mutex... */
 
731
#                       ifdef USE_PTHREADS
 
732
                        pthread_mutex_init(&pData->mtxTCPSend, 0);
 
733
#                       endif
 
734
                } else {
 
735
                        pData->protocol = FORW_UDP;
 
736
                }
 
737
                /* we are now after the protocol indicator. Now check if we should
 
738
                 * use compression. We begin to use a new option format for this:
 
739
                 * @(option,option)host:port
 
740
                 * The first option defined is "z[0..9]" where the digit indicates
 
741
                 * the compression level. If it is not given, 9 (best compression) is
 
742
                 * assumed. An example action statement might be:
 
743
                 * @@(z5,o)127.0.0.1:1400  
 
744
                 * Which means send via TCP with medium (5) compresion (z) to the local
 
745
                 * host on port 1400. The '0' option means that octet-couting (as in
 
746
                 * IETF I-D syslog-transport-tls) is to be used for framing (this option
 
747
                 * applies to TCP-based syslog only and is ignored when specified with UDP).
 
748
                 * That is not yet implemented.
 
749
                 * rgerhards, 2006-12-07
 
750
                 */
 
751
                if(*p == '(') {
 
752
                        /* at this position, it *must* be an option indicator */
 
753
                        do {
 
754
                                ++p; /* eat '(' or ',' (depending on when called) */
 
755
                                /* check options */
 
756
                                if(*p == 'z') { /* compression */
 
757
#                                       ifdef USE_NETZIP
 
758
                                        ++p; /* eat */
 
759
                                        if(isdigit((int) *p)) {
 
760
                                                int iLevel;
 
761
                                                iLevel = *p - '0';
 
762
                                                ++p; /* eat */
 
763
                                                pData->compressionLevel = iLevel;
 
764
                                        } else {
 
765
                                                logerrorInt("Invalid compression level '%c' specified in "
 
766
                                                         "forwardig action - NOT turning on compression.",
 
767
                                                         *p);
 
768
                                        }
 
769
#                                       else
 
770
                                        logerror("Compression requested, but rsyslogd is not compiled "
 
771
                                                 "with compression support - request ignored.");
 
772
#                                       endif /* #ifdef USE_NETZIP */
 
773
                                } else if(*p == 'o') { /* octet-couting based TCP framing? */
 
774
                                        ++p; /* eat */
 
775
                                        /* no further options settable */
 
776
                                        pData->tcp_framing = TCP_FRAMING_OCTET_COUNTING;
 
777
                                } else { /* invalid option! Just skip it... */
 
778
                                        logerrorInt("Invalid option %c in forwarding action - ignoring.", *p);
 
779
                                        ++p; /* eat invalid option */
 
780
                                }
 
781
                                /* the option processing is done. We now do a generic skip
 
782
                                 * to either the next option or the end of the option
 
783
                                 * block.
 
784
                                 */
 
785
                                while(*p && *p != ')' && *p != ',')
 
786
                                        ++p;    /* just skip it */
 
787
                        } while(*p && *p == ','); /* Attention: do.. while() */
 
788
                        if(*p == ')')
 
789
                                ++p; /* eat terminator, on to next */
 
790
                        else
 
791
                                /* we probably have end of string - leave it for the rest
 
792
                                 * of the code to handle it (but warn the user)
 
793
                                 */
 
794
                                logerror("Option block not terminated in forwarding action.");
 
795
                }
 
796
                /* extract the host first (we do a trick - we replace the ';' or ':' with a '\0')
 
797
                 * now skip to port and then template name. rgerhards 2005-07-06
 
798
                 */
 
799
                for(q = p ; *p && *p != ';' && *p != ':' ; ++p)
 
800
                        /* JUST SKIP */;
 
801
 
 
802
                pData->port = NULL;
 
803
                if(*p == ':') { /* process port */
 
804
                        uchar * tmp;
 
805
 
 
806
                        *p = '\0'; /* trick to obtain hostname (later)! */
 
807
                        tmp = ++p;
 
808
                        for(i=0 ; *p && isdigit((int) *p) ; ++p, ++i)
 
809
                                /* SKIP AND COUNT */;
 
810
                        pData->port = malloc(i + 1);
 
811
                        if(pData->port == NULL) {
 
812
                                logerror("Could not get memory to store syslog forwarding port, "
 
813
                                         "using default port, results may not be what you intend\n");
 
814
                                /* we leave f_forw.port set to NULL, this is then handled by
 
815
                                 * getFwdSyslogPt().
 
816
                                 */
 
817
                        } else {
 
818
                                memcpy(pData->port, tmp, i);
 
819
                                *(pData->port + i) = '\0';
 
820
                        }
 
821
                }
 
822
                
 
823
                /* now skip to template */
 
824
                bErr = 0;
 
825
                while(*p && *p != ';') {
 
826
                        if(*p && *p != ';' && !isspace((int) *p)) {
 
827
                                if(bErr == 0) { /* only 1 error msg! */
 
828
                                        bErr = 1;
 
829
                                        errno = 0;
 
830
                                        logerror("invalid selector line (port), probably not doing "
 
831
                                                 "what was intended");
 
832
                                }
 
833
                        }
 
834
                        ++p;
 
835
                }
 
836
        
 
837
                /* TODO: make this if go away! */
 
838
                if(*p == ';') {
 
839
                        *p = '\0'; /* trick to obtain hostname (later)! */
 
840
                        strcpy(pData->f_hname, (char*) q);
 
841
                        *p = ';';
 
842
                } else
 
843
                        strcpy(pData->f_hname, (char*) q);
 
844
 
 
845
                /* process template */
 
846
                if((iRet = cflineParseTemplateName(&p, *ppOMSR, 0, OMSR_NO_RQD_TPL_OPTS, (uchar*) " StdFwdFmt"))
 
847
                   != RS_RET_OK)
 
848
                        goto finalize_it;
 
849
 
 
850
                /* first set the pData->eDestState */
 
851
                memset(&hints, 0, sizeof(hints));
 
852
                /* port must be numeric, because config file syntax requests this */
 
853
                hints.ai_flags = AI_NUMERICSERV;
 
854
                hints.ai_family = family;
 
855
                hints.ai_socktype = pData->protocol == FORW_UDP ? SOCK_DGRAM : SOCK_STREAM;
 
856
                if( (error = getaddrinfo(pData->f_hname, getFwdSyslogPt(pData), &hints, &res)) != 0) {
 
857
                        pData->eDestState = eDestFORW_UNKN;
 
858
                        pData->iRtryCnt = INET_RETRY_MAX;
 
859
                        pData->ttSuspend = time(NULL);
 
860
                } else {
 
861
                        pData->eDestState = eDestFORW;
 
862
                        pData->f_addr = res;
 
863
                }
 
864
 
 
865
                /*
 
866
                 * Otherwise the host might be unknown due to an
 
867
                 * inaccessible nameserver (perhaps on the same
 
868
                 * host). We try to get the ip number later, like
 
869
                 * FORW_SUSP.
 
870
                 */
 
871
        } else {
 
872
                iRet = RS_RET_CONFLINE_UNPROCESSED;
 
873
        }
 
874
 
 
875
        /* TODO: do we need to call freeInstance if we failed - this is a general question for
 
876
         * all output modules. I'll address it lates as the interface evolves. rgerhards, 2007-07-25
 
877
         */
 
878
CODE_STD_FINALIZERparseSelectorAct
 
879
ENDparseSelectorAct
 
880
 
 
881
 
 
882
BEGINneedUDPSocket
 
883
CODESTARTneedUDPSocket
 
884
        iRet = RS_RET_TRUE;
 
885
ENDneedUDPSocket
 
886
 
 
887
 
 
888
BEGINonSelectReadyWrite
 
889
CODESTARTonSelectReadyWrite
 
890
        dbgprintf("tcp send socket %d ready for writing.\n", pData->sock);
 
891
        TCPSendSetStatus(pData, TCP_SEND_READY);
 
892
        /* Send stored message (if any) */
 
893
        if(pData->savedMsg != NULL) {
 
894
                if(TCPSend(pData, pData->savedMsg,
 
895
                           pData->savedMsgLen) != 0) {
 
896
                        /* error! */
 
897
                        pData->eDestState = eDestFORW_SUSP;
 
898
                        errno = 0;
 
899
                        logerror("error forwarding via tcp, suspending...");
 
900
                }
 
901
                free(pData->savedMsg);
 
902
                pData->savedMsg = NULL;
 
903
        }
 
904
ENDonSelectReadyWrite
 
905
 
 
906
 
 
907
BEGINgetWriteFDForSelect
 
908
CODESTARTgetWriteFDForSelect
 
909
        if(   (pData->eDestState == eDestFORW)
 
910
           && (pData->protocol == FORW_TCP)
 
911
           && TCPSendGetStatus(pData) == TCP_SEND_CONNECTING) {
 
912
                *fd = pData->sock;
 
913
                iRet = RS_RET_OK;
 
914
        }
 
915
ENDgetWriteFDForSelect
 
916
 
 
917
 
 
918
BEGINqueryEtryPt
 
919
CODESTARTqueryEtryPt
 
920
CODEqueryEtryPt_STD_OMOD_QUERIES
 
921
ENDqueryEtryPt
 
922
 
 
923
 
 
924
BEGINmodInit(Fwd)
 
925
CODESTARTmodInit
 
926
        *ipIFVersProvided = 1; /* so far, we only support the initial definition */
 
927
CODEmodInit_QueryRegCFSLineHdlr
 
928
ENDmodInit
 
929
 
 
930
#endif /* #ifdef SYSLOG_INET */
 
931
/*
 
932
 * vi:set ai:
 
933
 */