/
imfile.c
2729 lines (2455 loc) · 83.2 KB
/
imfile.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* imfile.c
*
* This is the input module for reading text file data. A text file is a
* non-binary file who's lines are delemited by the \n character.
*
* Work originally begun on 2008-02-01 by Rainer Gerhards
*
* Copyright 2008-2018 Adiscon GmbH.
*
* This file is part of rsyslog.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* -or-
* see COPYING.ASL20 in the source distribution
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <glob.h>
#include <poll.h>
#include <json.h>
#include <fnmatch.h>
#ifdef HAVE_SYS_INOTIFY_H
#include <sys/inotify.h>
#include <linux/types.h>
#endif
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#if defined(OS_SOLARIS) && defined (HAVE_PORT_SOURCE_FILE)
#include <port.h>
#include <sys/port.h>
#endif
#include "rsyslog.h" /* error codes etc... */
#include "dirty.h"
#include "cfsysline.h" /* access to config file objects */
#include "module-template.h" /* generic module interface code - very important, read it! */
#include "srUtils.h" /* some utility functions */
#include "msg.h"
#include "stream.h"
#include "errmsg.h"
#include "glbl.h"
#include "unicode-helper.h"
#include "prop.h"
#include "stringbuf.h"
#include "ruleset.h"
#include "ratelimit.h"
#include "srUtils.h"
#include "parserif.h"
#include <regex.h>
/* some platforms do not have large file support :( */
#ifndef O_LARGEFILE
# define O_LARGEFILE 0
#endif
#ifndef HAVE_LSEEK64
# define lseek64(fd, offset, whence) lseek(fd, offset, whence)
#endif
MODULE_TYPE_INPUT
MODULE_TYPE_NOKEEP
MODULE_CNFNAME("imfile")
/* defines */
#define FILE_ID_HASH_SIZE 20 /* max size of a file_id hash */
#define FILE_ID_SIZE 512 /* how many bytes are used for file-id? */
/* Module static data */
DEF_IMOD_STATIC_DATA /* must be present, starts static data */
DEFobjCurrIf(glbl)
DEFobjCurrIf(strm)
DEFobjCurrIf(prop)
DEFobjCurrIf(ruleset)
extern int rs_siphash(const uint8_t *in, const size_t inlen, const uint8_t *k,
uint8_t *out, const size_t outlen); /* see siphash.c */
static int bLegacyCnfModGlobalsPermitted;/* are legacy module-global config parameters permitted? */
#define NUM_MULTISUB 1024 /* default max number of submits */
#define DFLT_PollInterval 10
#define INIT_WDMAP_TAB_SIZE 1 /* default wdMap table size - is extended as needed, use 2^x value */
#define ADD_METADATA_UNSPECIFIED -1
/* If set to 1, fileTableDisplay will be compiled and used for debugging */
#define ULTRA_DEBUG 0
/* Setting GLOB_BRACE to ZERO which disables support for GLOB_BRACE if not available on current platform */
#ifndef GLOB_BRACE
#define GLOB_BRACE 0
#endif
static struct configSettings_s {
uchar *pszFileName;
uchar *pszFileTag;
uchar *pszStateFile;
uchar *pszBindRuleset;
int iPollInterval;
int iPersistStateInterval; /* how often if state file to be persisted? (default 0->never) */
int iFacility; /* local0 */
int iSeverity; /* notice, as of rfc 3164 */
int readMode; /* mode to use for ReadMultiLine call */
int64 maxLinesAtOnce; /* how many lines to process in a row? */
uint32_t trimLineOverBytes; /* 0: never trim line, positive number: trim line if over bytes */
} cs;
struct instanceConf_s {
uchar *pszFileName;
uchar *pszFileName_forOldStateFile; /* we unfortunately needs this to read old state files */
uchar *pszDirName;
uchar *pszFileBaseName;
uchar *pszTag;
size_t lenTag;
uchar *pszStateFile;
uchar *pszBindRuleset;
int nMultiSub;
int iPersistStateInterval;
int iFacility;
int iSeverity;
int readTimeout;
unsigned delay_perMsg;
sbool bRMStateOnDel;
uint8_t readMode;
uchar *startRegex;
uchar *endRegex;
regex_t start_preg; /* compiled version of startRegex */
regex_t end_preg; /* compiled version of endRegex */
sbool discardTruncatedMsg;
sbool msgDiscardingError;
sbool escapeLF;
sbool reopenOnTruncate;
sbool addCeeTag;
sbool addMetadata;
sbool freshStartTail;
sbool fileNotFoundError;
int maxLinesAtOnce;
uint32_t trimLineOverBytes;
ruleset_t *pBindRuleset; /* ruleset to bind listener to (use system default if unspecified) */
struct instanceConf_s *next;
};
/* file system objects */
typedef struct fs_edge_s fs_edge_t;
typedef struct fs_node_s fs_node_t;
typedef struct act_obj_s act_obj_t;
struct act_obj_s {
act_obj_t *prev;
act_obj_t *next;
fs_edge_t *edge; /* edge which this object belongs to */
char *name; /* full path name of active object */
char *basename; /* only basename */ //TODO: remove when refactoring rename support
char *source_name; /* if this object is target of a symlink, source_name is its name (else NULL) */
//char *statefile; /* base name of state file (for move operations) */
int wd;
#if defined(OS_SOLARIS) && defined (HAVE_PORT_SOURCE_FILE)
struct fileinfo *pfinf;
sbool bPortAssociated;
int is_deleted; /* debugging: entry deleted? */
#endif
time_t timeoutBase; /* what time to calculate the timeout against? */
/* file dynamic data */
int in_move; /* workaround for inotify move: if set, state file must not be deleted */
ino_t ino; /* current inode nbr */
strm_t *pStrm; /* its stream (NULL if not assigned) */
int nRecords; /**< How many records did we process before persisting the stream? */
ratelimit_t *ratelimiter;
multi_submit_t multiSub;
int is_symlink;
};
struct fs_edge_s {
fs_node_t *parent; /* node pointing to this edge */
fs_node_t *node; /* node this edge points to */
fs_edge_t *next;
uchar *name;
uchar *path;
act_obj_t *active;
int is_file;
int ninst; /* nbr of instances in instarr */
instanceConf_t **instarr;
};
struct fs_node_s {
fs_edge_t *edges; /* NULL in leaf nodes */
fs_node_t *root; /* node one level up (NULL for file system root) */
};
/* forward definitions */
static rsRetVal persistStrmState(act_obj_t *);
static rsRetVal resetConfigVariables(uchar __attribute__((unused)) *pp, void __attribute__((unused)) *pVal);
static rsRetVal ATTR_NONNULL(1) pollFile(act_obj_t *act);
static int ATTR_NONNULL() getBasename(uchar *const __restrict__ basen, uchar *const __restrict__ path);
static void ATTR_NONNULL() act_obj_unlink(act_obj_t *act);
static uchar * ATTR_NONNULL(1, 2) getStateFileName(const act_obj_t *, uchar *, const size_t);
static int ATTR_NONNULL() getFullStateFileName(const uchar *const, const char *const,
uchar *const pszout, const size_t ilenout);
#define OPMODE_POLLING 0
#define OPMODE_INOTIFY 1
#define OPMODE_FEN 2
/* config variables */
struct modConfData_s {
rsconf_t *pConf; /* our overall config object */
int iPollInterval; /* number of seconds to sleep when there was no file activity */
int readTimeout;
int timeoutGranularity; /* value in ms */
instanceConf_t *root, *tail;
fs_node_t *conf_tree;
uint8_t opMode;
sbool configSetViaV2Method;
sbool sortFiles;
sbool normalizePath; /* normalize file system pathes (all start with root dir) */
sbool haveReadTimeouts; /* use special processing if read timeouts exist */
sbool bHadFileData; /* actually a global variable:
1 - last call to pollFile() had data
0 - last call to pollFile() had NO data
Must be manually reset to 0 if desired. Helper for
polling mode.
*/
};
static modConfData_t *loadModConf = NULL;/* modConf ptr to use for the current load process */
static modConfData_t *runModConf = NULL;/* modConf ptr to use for the current load process */
#ifdef HAVE_INOTIFY_INIT
/* We need to map watch descriptors to our actual objects. Unfortunately, the
* inotify API does not provide us with any cookie, so a simple O(1) algorithm
* cannot be done (what a shame...). We assume that maintaining the array is much
* less often done than looking it up, so we keep the array sorted by watch descriptor
* and do a binary search on the wd we get back. This is at least O(log n), which
* is not too bad for the anticipated use case.
*/
struct wd_map_s {
int wd; /* ascending sort key */
act_obj_t *act; /* point to related active object */
};
typedef struct wd_map_s wd_map_t;
static wd_map_t *wdmap = NULL;
static int nWdmap;
static int allocMaxWdmap;
static int ino_fd; /* fd for inotify calls */
#endif /* #if HAVE_INOTIFY_INIT -------------------------------------------------- */
#if defined(OS_SOLARIS) && defined (HAVE_PORT_SOURCE_FILE)
struct fileinfo {
struct file_obj fobj;
int events;
int port;
};
static int glport; /* Static port handle for FEN api*/
#endif /* #if OS_SOLARIS -------------------------------------------------- */
static prop_t *pInputName = NULL;
/* there is only one global inputName for all messages generated by this input */
/* module-global parameters */
static struct cnfparamdescr modpdescr[] = {
{ "pollinginterval", eCmdHdlrPositiveInt, 0 },
{ "readtimeout", eCmdHdlrPositiveInt, 0 },
{ "timeoutgranularity", eCmdHdlrPositiveInt, 0 },
{ "sortfiles", eCmdHdlrBinary, 0 },
{ "normalizepath", eCmdHdlrBinary, 0 },
{ "mode", eCmdHdlrGetWord, 0 }
};
static struct cnfparamblk modpblk =
{ CNFPARAMBLK_VERSION,
sizeof(modpdescr)/sizeof(struct cnfparamdescr),
modpdescr
};
/* input instance parameters */
static struct cnfparamdescr inppdescr[] = {
{ "file", eCmdHdlrString, CNFPARAM_REQUIRED },
{ "tag", eCmdHdlrString, CNFPARAM_REQUIRED },
{ "severity", eCmdHdlrSeverity, 0 },
{ "facility", eCmdHdlrFacility, 0 },
{ "ruleset", eCmdHdlrString, 0 },
{ "readmode", eCmdHdlrInt, 0 },
{ "startmsg.regex", eCmdHdlrString, 0 },
{ "endmsg.regex", eCmdHdlrString, 0 },
{ "discardtruncatedmsg", eCmdHdlrBinary, 0 },
{ "msgdiscardingerror", eCmdHdlrBinary, 0 },
{ "escapelf", eCmdHdlrBinary, 0 },
{ "reopenontruncate", eCmdHdlrBinary, 0 },
{ "maxlinesatonce", eCmdHdlrInt, 0 },
{ "trimlineoverbytes", eCmdHdlrInt, 0 },
{ "maxsubmitatonce", eCmdHdlrInt, 0 },
{ "removestateondelete", eCmdHdlrBinary, 0 },
{ "persiststateinterval", eCmdHdlrInt, 0 },
{ "deletestateonfiledelete", eCmdHdlrBinary, 0 },
{ "delay.message", eCmdHdlrPositiveInt, 0 },
{ "addmetadata", eCmdHdlrBinary, 0 },
{ "addceetag", eCmdHdlrBinary, 0 },
{ "statefile", eCmdHdlrString, CNFPARAM_DEPRECATED },
{ "readtimeout", eCmdHdlrPositiveInt, 0 },
{ "freshstarttail", eCmdHdlrBinary, 0},
{ "filenotfounderror", eCmdHdlrBinary, 0}
};
static struct cnfparamblk inppblk =
{ CNFPARAMBLK_VERSION,
sizeof(inppdescr)/sizeof(struct cnfparamdescr),
inppdescr
};
#include "im-helper.h" /* must be included AFTER the type definitions! */
/* Support for "old cruft" state files will potentially become optional in the
* future (hopefully). To prepare so, we use conditional compilation with a
* fixed-true condition ;-) -- rgerhards, 2018-03-28
* reason: https://github.com/rsyslog/rsyslog/issues/2231#issuecomment-376862280
*/
#define ENABLE_V1_STATE_FILE_FORMAT_SUPPORT 1
#ifdef ENABLE_V1_STATE_FILE_FORMAT_SUPPORT
static uchar * ATTR_NONNULL(1, 2)
OLD_getStateFileName(const instanceConf_t *const inst,
uchar *const __restrict__ buf,
const size_t lenbuf)
{
DBGPRINTF("OLD_getStateFileName trying '%s'\n", inst->pszFileName_forOldStateFile);
snprintf((char*)buf, lenbuf - 1, "imfile-state:%s", inst->pszFileName_forOldStateFile);
buf[lenbuf-1] = '\0'; /* be on the safe side... */
uchar *p = buf;
for( ; *p ; ++p) {
if(*p == '/')
*p = '-';
}
return buf;
}
/* try to open an old-style state file for given file. If the state file does not
* exist or cannot be read, an error is returned.
*/
static rsRetVal ATTR_NONNULL(1)
OLD_openFileWithStateFile(act_obj_t *const act)
{
DEFiRet;
strm_t *psSF = NULL;
uchar pszSFNam[MAXFNAME];
size_t lenSFNam;
struct stat stat_buf;
uchar statefile[MAXFNAME];
const instanceConf_t *const inst = act->edge->instarr[0];// TODO: same file, multiple instances?
uchar *const statefn = OLD_getStateFileName(inst, statefile, sizeof(statefile));
DBGPRINTF("OLD_openFileWithStateFile: trying to open state for '%s', state file '%s'\n",
act->name, statefn);
/* Get full path and file name */
lenSFNam = getFullStateFileName(statefn, "", pszSFNam, sizeof(pszSFNam));
/* check if the file exists */
if(stat((char*) pszSFNam, &stat_buf) == -1) {
if(errno == ENOENT) {
DBGPRINTF("OLD_openFileWithStateFile: NO state file (%s) exists for '%s'\n",
pszSFNam, act->name);
ABORT_FINALIZE(RS_RET_FILE_NOT_FOUND);
} else {
char errStr[1024];
rs_strerror_r(errno, errStr, sizeof(errStr));
DBGPRINTF("OLD_openFileWithStateFile: error trying to access state "
"file for '%s':%s\n", act->name, errStr);
ABORT_FINALIZE(RS_RET_IO_ERROR);
}
}
/* If we reach this point, we have a state file */
DBGPRINTF("old state file found - instantiating from it\n");
CHKiRet(strm.Construct(&psSF));
CHKiRet(strm.SettOperationsMode(psSF, STREAMMODE_READ));
CHKiRet(strm.SetsType(psSF, STREAMTYPE_FILE_SINGLE));
CHKiRet(strm.SetFName(psSF, pszSFNam, lenSFNam));
CHKiRet(strm.SetFileNotFoundError(psSF, inst->fileNotFoundError));
CHKiRet(strm.ConstructFinalize(psSF));
/* read back in the object */
CHKiRet(obj.Deserialize(&act->pStrm, (uchar*) "strm", psSF, NULL, act));
free(act->pStrm->pszFName);
CHKmalloc(act->pStrm->pszFName = ustrdup(act->name));
strm.CheckFileChange(act->pStrm);
CHKiRet(strm.SeekCurrOffs(act->pStrm));
/* we now persist the new state file and delete the old one, so we will
* never have to deal with the old one. */
persistStrmState(act);
unlink((char*)pszSFNam);
finalize_it:
if(psSF != NULL)
strm.Destruct(&psSF);
RETiRet;
}
#endif /* #ifdef ENABLE_V1_STATE_FILE_FORMAT_SUPPORT */
#if 0 // Code we can potentially use for new functionality // TODO: use or remove
//TODO add a kind of portable asprintf:
static const char * ATTR_NONNULL()
gen_full_name(const char *const dirname, const char *const name)
{
const size_t len_full_name = strlen(dirname) + 1 + strlen(name) + 1;
char *const full_name = malloc(len_full_name);
if(full_name == NULL)
return NULL;
snprintf(full_name, len_full_name, "%s/%s", dirname, name);
return full_name;
}
#endif
#ifdef HAVE_INOTIFY_INIT
#if ULTRA_DEBUG == 1
static void
dbg_wdmapPrint(const char *msg)
{
int i;
DBGPRINTF("%s\n", msg);
for(i = 0 ; i < nWdmap ; ++i)
DBGPRINTF("wdmap[%d]: wd: %d, act %p, name: %s\n",
i, wdmap[i].wd, wdmap[i].act, wdmap[i].act->name);
}
#endif
static rsRetVal
wdmapInit(void)
{
DEFiRet;
free(wdmap);
CHKmalloc(wdmap = malloc(sizeof(wd_map_t) * INIT_WDMAP_TAB_SIZE));
allocMaxWdmap = INIT_WDMAP_TAB_SIZE;
nWdmap = 0;
finalize_it:
RETiRet;
}
/* note: we search backwards, as inotify tends to return increasing wd's */
static rsRetVal
wdmapAdd(int wd, act_obj_t *const act)
{
wd_map_t *newmap;
int newmapsize;
int i;
DEFiRet;
for(i = nWdmap-1 ; i >= 0 && wdmap[i].wd > wd ; --i)
; /* just scan */
if(i >= 0 && wdmap[i].wd == wd) {
LogError(0, RS_RET_INTERNAL_ERROR, "imfile: wd %d already in wdmap!", wd);
ABORT_FINALIZE(RS_RET_FILE_ALREADY_IN_TABLE);
}
++i;
/* i now points to the entry that is to be moved upwards (or end of map) */
if(nWdmap == allocMaxWdmap) {
newmapsize = 2 * allocMaxWdmap;
CHKmalloc(newmap = realloc(wdmap, sizeof(wd_map_t) * newmapsize));
// TODO: handle the error more intelligently? At all possible? -- 2013-10-15
wdmap = newmap;
allocMaxWdmap = newmapsize;
}
if(i < nWdmap) {
/* we need to shift to make room for new entry */
memmove(wdmap + i + 1, wdmap + i, sizeof(wd_map_t) * (nWdmap - i));
}
wdmap[i].wd = wd;
wdmap[i].act = act;
++nWdmap;
DBGPRINTF("add wdmap[%d]: wd %d, act obj %p, path %s\n", i, wd, act, act->name);
finalize_it:
RETiRet;
}
/* return wd or -1 on error */
static int
in_setupWatch(act_obj_t *const act, const int is_file)
{
int wd = -1;
if(runModConf->opMode != OPMODE_INOTIFY)
goto done;
wd = inotify_add_watch(ino_fd, act->name,
(is_file) ? IN_MODIFY|IN_DONT_FOLLOW : IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO);
if(wd < 0) {
if (errno == EACCES) { /* There is high probability of selinux denial on top-level paths */
DBGPRINTF("imfile: permission denied when adding watch for '%s'\n", act->name);
} else {
LogError(errno, RS_RET_IO_ERROR, "imfile: cannot watch object '%s'", act->name);
}
goto done;
}
wdmapAdd(wd, act);
DBGPRINTF("in_setupWatch: watch %d added for %s(object %p)\n", wd, act->name, act);
done: return wd;
}
/* compare function for bsearch() */
static int
wdmap_cmp(const void *k, const void *a)
{
int key = *((int*) k);
wd_map_t *etry = (wd_map_t*) a;
if(key < etry->wd)
return -1;
else if(key > etry->wd)
return 1;
else
return 0;
}
/* looks up a wdmap entry and returns it's index if found
* or -1 if not found.
*/
static wd_map_t *
wdmapLookup(int wd)
{
return bsearch(&wd, wdmap, nWdmap, sizeof(wd_map_t), wdmap_cmp);
}
static rsRetVal
wdmapDel(const int wd)
{
int i;
DEFiRet;
for(i = 0 ; i < nWdmap && wdmap[i].wd < wd ; ++i)
; /* just scan */
if(i == nWdmap || wdmap[i].wd != wd) {
DBGPRINTF("wd %d shall be deleted but not in wdmap!\n", wd);
FINALIZE;
}
if(i < nWdmap-1) {
/* we need to shift to delete it (see comment at wdmap definition) */
memmove(wdmap + i, wdmap + i + 1, sizeof(wd_map_t) * (nWdmap - i - 1));
}
--nWdmap;
DBGPRINTF("wd %d deleted, was idx %d\n", wd, i);
finalize_it:
RETiRet;
}
#endif // #ifdef HAVE_INOTIFY_INIT
#if defined(OS_SOLARIS) && defined (HAVE_PORT_SOURCE_FILE)
static void ATTR_NONNULL()
fen_setupWatch(act_obj_t *const act)
{
DBGPRINTF("fen_setupWatch: enter, opMode %d\n", runModConf->opMode);
if(runModConf->opMode != OPMODE_FEN)
goto done;
DBGPRINTF("fen_setupWatch: %s\n", act->name);
if(act->pfinf == NULL) {
act->pfinf = malloc(sizeof(struct fileinfo));
if (act->pfinf == NULL) {
LogError(errno, RS_RET_OUT_OF_MEMORY, "imfile: fen_setupWatch alloc memory "
"for fileinfo failed ");
goto done;
}
if ((act->pfinf->fobj.fo_name = strdup(act->name)) == NULL) {
LogError(errno, RS_RET_OUT_OF_MEMORY, "imfile: fen_setupWatch alloc memory "
"for strdup failed ");
free(act->pfinf);
act->pfinf = NULL;
goto done;
}
act->pfinf->events = FILE_MODIFIED;
act->pfinf->port = glport;
act->bPortAssociated = 0;
}
DBGPRINTF("fen_setupWatch: bPortAssociated %d\n", act->bPortAssociated);
if(act->bPortAssociated) {
goto done;
}
struct stat fileInfo;
const int r = stat(act->name, &fileInfo);
if(r == -1) { /* object gone away? */
DBGPRINTF("fen_setupWatch: file gone away, no watch: '%s'\n", act->name);
goto done;
}
/* note: FEN watch must be re-registered each time - this is what we do now */
act->pfinf->fobj.fo_atime = fileInfo.st_atim;
act->pfinf->fobj.fo_mtime = fileInfo.st_mtim;
act->pfinf->fobj.fo_ctime = fileInfo.st_ctim;
if(port_associate(glport, PORT_SOURCE_FILE, (uintptr_t)&(act->pfinf->fobj),
act->pfinf->events, (void *)act) == -1) {
LogError(errno, RS_RET_SYS_ERR, "fen_setupWatch: Failed to associate port for file "
": %s\n", act->pfinf->fobj.fo_name);
goto done;
} else {
/* Port successfull listening now*/
DBGPRINTF("fen_setupWatch: associated port for file %s\n", act->name);
act->bPortAssociated = 1;
}
DBGPRINTF("in_setupWatch: fen association added for %s\n", act->name);
done: return;
}
#else
static void ATTR_NONNULL()
fen_setupWatch(act_obj_t *const act __attribute__((unused)))
{
DBGPRINTF("fen_setupWatch: DUMMY CALLED - not on Solaris?\n");
}
#endif /* FEN */
static void
fs_node_print(const fs_node_t *const node, const int level)
{
fs_edge_t *chld;
act_obj_t *act;
dbgprintf("node print[%2.2d]: %p edges:\n", level, node);
for(chld = node->edges ; chld != NULL ; chld = chld->next) {
dbgprintf("node print[%2.2d]: child %p '%s' isFile %d, path: '%s'\n",
level, chld->node, chld->name, chld->is_file, chld->path);
for(int i = 0 ; i < chld->ninst ; ++i) {
dbgprintf("\tinst: %p\n", chld->instarr[i]);
}
for(act = chld->active ; act != NULL ; act = act->next) {
dbgprintf("\tact : %p\n", act);
dbgprintf("\tact : %p: name '%s', wd: %d\n",
act, act->name, act->wd);
}
}
for(chld = node->edges ; chld != NULL ; chld = chld->next) {
fs_node_print(chld->node, level+1);
}
}
/* add a new file system object if it not yet exists, ignore call
* if it already does.
*/
static rsRetVal ATTR_NONNULL(1,2)
act_obj_add(fs_edge_t *const edge, const char *const name, const int is_file,
const ino_t ino, const int is_symlink, const char *const source)
{
act_obj_t *act;
char basename[MAXFNAME];
DEFiRet;
DBGPRINTF("act_obj_add: edge %p, name '%s' (source '%s')\n", edge, name, source? source : "---");
for(act = edge->active ; act != NULL ; act = act->next) {
if(!strcmp(act->name, name)) {
if (!source || !act->source_name || !strcmp(act->source_name, source)) {
DBGPRINTF("active object '%s' already exists in '%s' - no need to add\n",
name, edge->path);
FINALIZE;
}
}
}
DBGPRINTF("add new active object '%s' in '%s'\n", name, edge->path);
CHKmalloc(act = calloc(sizeof(act_obj_t), 1));
CHKmalloc(act->name = strdup(name));
if (-1 == getBasename((uchar*)basename, (uchar*)name)) {
CHKmalloc(act->basename = strdup(name)); /* assume basename is same as name */
} else {
CHKmalloc(act->basename = strdup(basename));
}
act->edge = edge;
act->ino = ino;
act->is_symlink = is_symlink;
if (source) { /* we are target of symlink */
CHKmalloc(act->source_name = strdup(source));
} else {
act->source_name = NULL;
}
#ifdef HAVE_INOTIFY_INIT
act->wd = in_setupWatch(act, is_file);
#endif
fen_setupWatch(act);
if(is_file && !is_symlink) {
const instanceConf_t *const inst = edge->instarr[0];// TODO: same file, multiple instances?
CHKiRet(ratelimitNew(&act->ratelimiter, "imfile", name));
CHKmalloc(act->multiSub.ppMsgs = malloc(inst->nMultiSub * sizeof(smsg_t *)));
act->multiSub.maxElem = inst->nMultiSub;
act->multiSub.nElem = 0;
pollFile(act);
}
/* all well, add to active list */
if(edge->active != NULL) {
edge->active->prev = act;
}
act->next = edge->active;
edge->active = act;
finalize_it:
if(iRet != RS_RET_OK) {
if(act != NULL) {
free(act->name);
free(act);
}
}
RETiRet;
}
/* this walks an edges active list and detects and acts on any changes
* seen there. It does NOT detect newly appeared files, as they are not
* inside the active list!
*/
static void
detect_updates(fs_edge_t *const edge)
{
act_obj_t *act;
struct stat fileInfo;
int restart = 0;
for(act = edge->active ; act != NULL ; act = act->next) {
DBGPRINTF("detect_updates checking active obj '%s'\n", act->name);
const int r = lstat(act->name, &fileInfo);
if(r == -1) { /* object gone away? */
DBGPRINTF("object gone away, unlinking: '%s'\n", act->name);
act_obj_unlink(act);
restart = 1;
break;
} else if(fileInfo.st_ino != act->ino) {
DBGPRINTF("file '%s' inode changed from %llu to %llu, unlinking from "
"internal lists\n", act->name, (long long unsigned) act->ino,
(long long unsigned) fileInfo.st_ino);
if(act->pStrm != NULL) {
/* we do no need to re-set later, as act_obj_unlink
* will destroy the strm obj */
strmSet_checkRotation(act->pStrm, STRM_ROTATION_DO_NOT_CHECK);
}
act_obj_unlink(act);
restart = 1;
break;
}
}
if (restart) {
detect_updates(edge);
}
}
/* check if active files need to be processed. This is only needed in
* polling mode.
*/
static void ATTR_NONNULL()
poll_active_files(fs_edge_t *const edge)
{
if( runModConf->opMode != OPMODE_POLLING
|| !edge->is_file
|| glbl.GetGlobalInputTermState() != 0) {
return;
}
act_obj_t *act;
for(act = edge->active ; act != NULL ; act = act->next) {
fen_setupWatch(act);
DBGPRINTF("poll_active_files: polling '%s'\n", act->name);
pollFile(act);
}
}
static rsRetVal ATTR_NONNULL()
process_symlink(fs_edge_t *const chld, const char *symlink)
{
DEFiRet;
char *target;
CHKmalloc(target = realpath(symlink, NULL));
struct stat fileInfo;
if(lstat(target, &fileInfo) != 0) {
LogError(errno, RS_RET_ERR, "imfile: process_symlink: cannot stat file '%s' - ignored", target);
FINALIZE;
}
const int is_file = (S_ISREG(fileInfo.st_mode));
DBGPRINTF("process_symlink: found '%s', File: %d (config file: %d), symlink: %d\n",
target, is_file, chld->is_file, 0);
if (act_obj_add(chld, target, is_file, fileInfo.st_ino, 0, symlink) == RS_RET_OK) {
/* need to watch parent target as well for proper rotation support */
uint idx = ustrlen(chld->active->name) - ustrlen(chld->active->basename);
if (idx) { /* basename is different from name */
char parent[MAXFNAME];
idx--; /* move past trailing slash */
memcpy(parent, chld->active->name, idx);
parent[idx] = '\0';
if(lstat(parent, &fileInfo) != 0) {
LogError(errno, RS_RET_ERR,
"imfile: process_symlink: cannot stat directory '%s' - ignored", parent);
FINALIZE;
}
if (chld->parent->root->edges) {
DBGPRINTF("process_symlink: adding parent '%s' of target '%s'\n", parent, target);
act_obj_add(chld->parent->root->edges, parent, 0, fileInfo.st_ino, 0, NULL);
}
}
}
finalize_it:
free(target);
RETiRet;
}
static void ATTR_NONNULL()
poll_tree(fs_edge_t *const chld)
{
struct stat fileInfo;
glob_t files;
int need_globfree = 0;
int issymlink;
DBGPRINTF("poll_tree: chld %p, name '%s', path: %s\n", chld, chld->name, chld->path);
detect_updates(chld);
const int ret = glob((char*)chld->path, runModConf->sortFiles|GLOB_BRACE, NULL, &files);
need_globfree = 1;
DBGPRINTF("poll_tree: glob returned %d\n", ret);
if(ret == 0) {
DBGPRINTF("poll_tree: processing %d files\n", (int) files.gl_pathc);
for(unsigned i = 0 ; i < files.gl_pathc ; i++) {
if(glbl.GetGlobalInputTermState() != 0) {
goto done;
}
char *const file = files.gl_pathv[i];
if(lstat(file, &fileInfo) != 0) {
LogError(errno, RS_RET_ERR,
"imfile: poll_tree cannot stat file '%s' - ignored", file);
continue;
}
if (S_ISLNK(fileInfo.st_mode)) {
rsRetVal slink_ret = process_symlink(chld, file);
if (slink_ret != RS_RET_OK) {
continue;
}
issymlink = 1;
} else {
issymlink = 0;
}
const int is_file = (S_ISREG(fileInfo.st_mode) || issymlink);
DBGPRINTF("poll_tree: found '%s', File: %d (config file: %d), symlink: %d\n",
file, is_file, chld->is_file, issymlink);
if(!is_file && S_ISREG(fileInfo.st_mode)) {
LogMsg(0, RS_RET_ERR, LOG_WARNING,
"imfile: '%s' is neither a regular file, symlink, nor a "
"directory - ignored", file);
continue;
}
if(!issymlink && (chld->is_file != is_file)) {
LogMsg(0, RS_RET_ERR, LOG_WARNING,
"imfile: '%s' is %s but %s expected - ignored",
file, (is_file) ? "FILE" : "DIRECTORY",
(chld->is_file) ? "FILE" : "DIRECTORY");
continue;
}
act_obj_add(chld, file, is_file, fileInfo.st_ino, issymlink, NULL);
}
}
poll_active_files(chld);
done:
if(need_globfree) {
globfree(&files);
}
return;
}
#ifdef HAVE_INOTIFY_INIT // TODO: shouldn't we use that in polling as well?
static void ATTR_NONNULL()
poll_timeouts(fs_edge_t *const edge)
{
if(edge->is_file) {
act_obj_t *act;
for(act = edge->active ; act != NULL ; act = act->next) {
if(strmReadMultiLine_isTimedOut(act->pStrm)) {
DBGPRINTF("timeout occured on %s\n", act->name);
pollFile(act);
}
}
}
}
#endif
/* destruct a single act_obj object */
static void
act_obj_destroy(act_obj_t *const act, const int is_deleted)
{
uchar *statefn;
uchar statefile[MAXFNAME];
uchar toDel[MAXFNAME];
if(act == NULL)
return;
DBGPRINTF("act_obj_destroy: act %p '%s' (source '%s'), wd %d, pStrm %p, is_deleted %d, in_move %d\n",
act, act->name, act->source_name? act->source_name : "---", act->wd, act->pStrm, is_deleted,
act->in_move);
if(act->is_symlink && is_deleted) {
act_obj_t *target_act;
for(target_act = act->edge->active ; target_act != NULL ; target_act = target_act->next) {
if(target_act->source_name && !strcmp(target_act->source_name, act->name)) {
DBGPRINTF("act_obj_destroy: unlinking slink target %s of %s "
"symlink\n", target_act->name, act->name);
act_obj_unlink(target_act);
break;
}
}
}
if(act->pStrm != NULL) {
const instanceConf_t *const inst = act->edge->instarr[0];// TODO: same file, multiple instances?
pollFile(act); /* get any left-over data */
if(inst->bRMStateOnDel) {
statefn = getStateFileName(act, statefile, sizeof(statefile));
getFullStateFileName(statefn, "", toDel, sizeof(toDel)); // TODO: check!
statefn = toDel;
}
persistStrmState(act);
strm.Destruct(&act->pStrm);
/* we delete state file after destruct in case strm obj initiated a write */
if(is_deleted && !act->in_move && inst->bRMStateOnDel) {
DBGPRINTF("act_obj_destroy: deleting state file %s\n", statefn);
unlink((char*)statefn);
}
}
if(act->ratelimiter != NULL) {
ratelimitDestruct(act->ratelimiter);
}
#ifdef HAVE_INOTIFY_INIT
if(act->wd != -1) {
wdmapDel(act->wd);
}
#endif
#if defined(OS_SOLARIS) && defined (HAVE_PORT_SOURCE_FILE)
if(act->pfinf != NULL) {
free(act->pfinf->fobj.fo_name);
free(act->pfinf);
}
#endif
free(act->basename);
free(act->source_name);
free(act->multiSub.ppMsgs);
#if defined(OS_SOLARIS) && defined (HAVE_PORT_SOURCE_FILE)
act->is_deleted = 1;
#else
free(act->name);
free(act);
#endif
}
/* destroy complete act list starting at given node */
static void
act_obj_destroy_all(act_obj_t *act)
{
if(act == NULL)
return;
DBGPRINTF("act_obj_destroy_all: act %p '%s', wd %d, pStrm %p\n", act, act->name, act->wd, act->pStrm);
while(act != NULL) {
act_obj_t *const toDel = act;
act = act->next;
act_obj_destroy(toDel, 0);
}
}
#if 0
/* debug: find if ptr is still present in list */
static void
chk_active(const act_obj_t *act, const act_obj_t *const deleted)
{
while(act != NULL) {
DBGPRINTF("chk_active %p vs %p\n", act, deleted);
if(act->prev == deleted)
DBGPRINTF("chk_active %p prev points to %p\n", act, deleted);
if(act->next == deleted)