forked from lsyncd/lsyncd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lsyncd.c
2912 lines (2371 loc) · 49.9 KB
/
lsyncd.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
/*
| lsyncd.c Live (Mirror) Syncing Demon
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| This is Lsyncd's core.
|
| It contains as minimal as possible glues to the operating system needed
| for Lsyncd's operation. All high-level logic is coded (when feasable)
| into lsyncd.lua
|
| This code assumes you have a 100 character wide display to view it (when tabstop is 4)
|
| License: GPLv2 (see COPYING) or any later version
| Authors: Axel Kittenberger <[email protected]>
|
*/
#include "lsyncd.h"
#define SYSLOG_NAMES 1
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <syslog.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#define LUA_USE_APICHECK 1
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
/*
| The Lua part of Lsyncd
*/
extern const char runner_out[];
extern size_t runner_size;
extern const char defaults_out[];
extern size_t defaults_size;
/*
| Makes sure there is one file system monitor.
*/
#ifndef WITH_INOTIFY
#ifndef WITH_FSEVENTS
# error "needing at least one notification system. please rerun cmake"
#endif
#endif
/*
| All monitors supported by this Lsyncd.
*/
static char *monitors[] = {
#ifdef WITH_INOTIFY
"inotify",
#endif
#ifdef WITH_FSEVENTS
"fsevents",
#endif
NULL,
};
/**
| Configuration parameters that matter to the core
*/
struct settings settings = {
.log_file = NULL,
.log_syslog = false,
.log_ident = NULL,
.log_facility = LOG_USER,
.log_level = LOG_NOTICE,
.nodaemon = false,
};
/*
| True when Lsyncd daemonized itself.
*/
static bool is_daemon = false;
/*
| The config file loaded by Lsyncd.
*/
char * lsyncd_config_file = NULL;
/*
| False after first time Lsyncd started up.
|
| Configuration error messages are thus written to
| stdout/stderr only on first start.
|
| All other resets (HUP or monitor OVERFLOW) run with 'insist'
| implictly turned on and thus Lsyncd does not failing on a non
| responding target.
*/
static bool first_time = true;
/*
| Set by TERM or HUP signal handler
| telling Lsyncd should end or reset ASAP.
*/
volatile sig_atomic_t hup = 0;
volatile sig_atomic_t term = 0;
volatile sig_atomic_t sigcode = 0;
int pidfile_fd = 0;
/*
| The kernel's clock ticks per second.
*/
static long clocks_per_sec;
/**
* signal handler
*/
void
sig_child(int sig) {
// nothing
}
/**
* signal handler
*/
void
sig_handler( int sig )
{
switch( sig )
{
case SIGTERM:
case SIGINT:
term = 1;
sigcode = sig;
return;
case SIGHUP:
hup = 1;
return;
}
}
/*
| Non glibc builds need a real tms structure for the times( ) call
*/
#ifdef __GLIBC__
static struct tms * dummy_tms = NULL;
#else
static struct tms _dummy_tms;
static struct tms * dummy_tms = &_dummy_tms;
#endif
/*
| Returns the absolute path of a path.
|
| This is a wrapper to various C-Library differences.
*/
char *
get_realpath( const char * rpath )
{
// uses c-library to get the absolute path
#ifdef __GLIBC__
// in case of GLIBC the task is easy.
return realpath( rpath, NULL );
#else
# warning having to use old style realpath()
// otherwise less so and requires PATH_MAX limit
char buf[ PATH_MAX] ;
char *asw = realpath( rpath, buf );
if( !asw )
{ return NULL; }
return s_strdup( asw );
#endif
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
( Logging )
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/*
| A logging category
*/
struct logcat
{
char *name;
int priority;
};
/*
| A table of all enabled logging categories.
| Sorted by first letter for faster access.
*/
static struct logcat *
logcats[ 26 ] = { 0, };
/*
| Returns a positive priority if category is configured to be logged or -1.
*/
extern int
check_logcat( const char *name )
{
struct logcat *lc;
if( name[ 0 ] < 'A' || name[ 0 ] > 'Z')
{ return 99; }
lc = logcats[ name[ 0 ] - 'A' ];
if( !lc )
{ return 99; }
while( lc->name )
{
if( !strcmp( lc->name, name ) )
{ return lc->priority; }
lc++;
}
return 99;
}
/*
| Adds a logging category
|
| Returns true if OK.
*/
static bool
add_logcat( const char *name, int priority )
{
struct logcat *lc;
if( !strcmp( "all", name ) )
{
settings.log_level = 99;
return true;
}
if( !strcmp( "scarce", name ) )
{
settings.log_level = LOG_WARNING;
return true;
}
// categories must start with a capital letter.
if( name[ 0 ] < 'A' || name[ 0 ] > 'Z' )
{
return false;
}
if( !logcats[ name[ 0 ]- 'A' ] )
{
// an empty capital letter
lc = logcats[name[0]-'A'] = s_calloc(2, sizeof(struct logcat));
}
else
{
// length of letter list
int ll = 0;
// counts list length
for( lc = logcats[name[0]-'A']; lc->name; lc++ )
{ ll++; }
// enlarges list
logcats[ name[ 0 ] - 'A'] =
s_realloc(
logcats[ name[ 0 ]-'A' ],
( ll + 2 ) * sizeof( struct logcat )
);
// goes to the list end
for( lc = logcats[ name[ 0 ] - 'A']; lc->name; lc++ )
{
if( !strcmp( name, lc->name ) )
{
// already there
return true;
}
}
}
lc->name = s_strdup( name );
lc->priority = priority;
// terminates the list
lc[ 1 ].name = NULL;
return true;
}
/*
| Logs a string.
|
| Do not call this directly, but the macro logstring( )
| defined in lsyncd.h
*/
extern void
logstring0(
int priority, // the priority of the log message
const char * cat, // the category
const char * message // the log message
)
{
if( first_time )
{
// lsyncd is in it's intial configuration phase.
// thus just print to normal stdout/stderr.
if( priority >= LOG_ERR )
{
fprintf( stderr, "%s: %s\n", cat, message);
}
else
{
printf( "%s: %s\n", cat, message );
}
return;
}
// writes on console if not daemonized
if( !is_daemon )
{
char ct[ 255 ];
// gets current timestamp hour:minute:second
time_t mtime;
time( &mtime );
strftime( ct, sizeof( ct ), "%T", localtime( &mtime ) );
FILE * flog = priority <= LOG_ERR ? stderr : stdout;
fprintf(
flog,
"%s %s: %s\n",
ct, cat, message
);
}
// writes to file if configured so
if( settings.log_file )
{
FILE * flog = fopen( settings.log_file, "a" );
char * ct;
time_t mtime;
// gets current timestamp day-time-year
time( &mtime );
ct = ctime( &mtime );
// cuts trailing linefeed
ct[ strlen( ct ) - 1] = 0;
if( flog == NULL )
{
fprintf(
stderr,
"Cannot open logfile [%s]!\n",
settings.log_file
);
exit( -1 );
}
fprintf(
flog,
"%s %s: %s\n",
ct, cat, message
);
fclose( flog );
}
// sends to syslog if configured so
if( settings.log_syslog )
{
syslog( priority, "%s, %s", cat, message );
}
return;
}
/*
| Lets the core print logmessages comfortably as formated string.
| This uses the lua_State for it easy string buffers only.
*/
extern void
printlogf0(lua_State *L,
int priority,
const char *cat,
const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
lua_pushvfstring(L, fmt, ap);
va_end(ap);
logstring0(priority, cat, luaL_checkstring(L, -1));
lua_pop(L, 1);
return;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
( Simple memory management )
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// FIXME call the Lua garbace collector in case of out of memory
/*
| "Secured" calloc
*/
extern void *
s_calloc( size_t nmemb, size_t size )
{
void * r = calloc( nmemb, size );
if( r == NULL )
{
logstring0(
LOG_ERR,
"Error",
"Out of memory!"
);
exit( -1 );
}
return r;
}
/*
| "Secured" malloc
*/
extern void *
s_malloc( size_t size )
{
void * r = malloc( size );
if( r == NULL )
{
logstring0(
LOG_ERR,
"Error",
"Out of memory!"
);
exit( -1 );
}
return r;
}
/*
| "Secured" realloc
*/
extern void *
s_realloc( void * ptr, size_t size )
{
void * r = realloc( ptr, size );
if( r == NULL )
{
logstring0(
LOG_ERR,
"Error",
"Out of memory!"
);
exit( -1 );
}
return r;
}
/*
| "Secured" strdup
*/
extern char *
s_strdup( const char *src )
{
char *s = strdup( src );
if( s == NULL )
{
logstring0(
LOG_ERR,
"Error",
"Out of memory!"
);
exit( -1 );
}
return s;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
( Pipes Management )
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/*
| A child process gets text piped through stdin
*/
struct pipemsg
{
char * text; // message to send
int tlen; // length of text
int pos; // position in message
};
/*
| Called by the core whenever a pipe becomes
| writeable again
*/
static void
pipe_writey(
lua_State * L,
struct observance * observance
)
{
int fd = observance->fd;
struct pipemsg *pm = (struct pipemsg * ) observance->extra;
int len = write(
fd,
pm->text + pm->pos,
pm->tlen - pm->pos
);
pm->pos += len;
if( len < 0 )
{
logstring( "Normal", "broken pipe." );
nonobserve_fd( fd );
}
else if( pm->pos >= pm->tlen )
{
logstring( "Exec", "finished pipe." );
nonobserve_fd(fd);
}
}
/*
| Called when cleaning up a pipe.
*/
static void
pipe_tidy( struct observance * observance )
{
struct pipemsg *pm = ( struct pipemsg * ) observance->extra;
close( observance->fd );
free( pm->text );
free( pm );
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
( Helper Routines )
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/*
| Dummy variable of which it's address is used as
| the cores index in the lua registry to
| the lua runners function table in the lua registry.
*/
static int runner;
/*
| Dummy variable of which it's address is used as
| the cores index n the lua registry to
| the lua runners error handler.
*/
static int callError;
/*
| Sets the close-on-exit flag of a file descriptor.
*/
extern void
close_exec_fd( int fd )
{
int flags;
flags = fcntl( fd, F_GETFD );
if( flags == -1 )
{
logstring( "Error", "cannot get descriptor flags!" );
exit( -1 );
}
flags |= FD_CLOEXEC;
if( fcntl( fd, F_SETFD, flags ) == -1 )
{
logstring( "Error", "cannot set descripptor flags!" );
exit( -1 );
}
}
/*
| Sets the non-blocking flag of a file descriptor.
*/
extern void
non_block_fd( int fd )
{
int flags;
flags = fcntl( fd, F_GETFL );
if( flags == -1 )
{
logstring( "Error", "cannot get status flags!" );
exit( -1 );
}
flags |= O_NONBLOCK;
if( fcntl( fd, F_SETFL, flags ) == -1 )
{
logstring( "Error", "cannot set status flags!" );
exit( -1 );
}
}
/*
| Writes a pid file.
*/
static void
write_pidfile
(
lua_State *L,
const char *pidfile
)
{
pidfile_fd = open( pidfile, O_CREAT | O_RDWR, 0644 );
fcntl( pidfile_fd, F_SETFD, FD_CLOEXEC );
char buf[ 127 ];
if( pidfile_fd < 0 )
{
printlogf(
L, "Error",
"Cannot create pidfile; '%s'",
pidfile
);
exit( -1 );
}
int rc = lockf( pidfile_fd, F_TLOCK, 0 );
if( rc < 0 )
{
printlogf(
L, "Error",
"Cannot lock pidfile; '%s'",
pidfile
);
exit( -1 );
}
snprintf( buf, sizeof( buf ), "%i\n", getpid( ) );
write( pidfile_fd, buf, strlen( buf ) );
//fclose( f );
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
( Observances )
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/*
| List of file descriptor watches.
*/
static struct observance * observances = NULL;
static int observances_len = 0;
static int observances_size = 0;
/*
| List of file descriptors to not observe.
|
| While working for the oberver lists, it may
| not be altered, thus nonobserve stores the
| delayed removals.
*/
static int * nonobservances = NULL;
static int nonobservances_len = 0;
static int nonobservances_size = 0;
/*
| True while the observances list is being handled.
*/
static bool observance_action = false;
/*
| Core watches a filedescriptor to become ready,
| one of read_ready or write_ready may be zero
*/
extern void
observe_fd(
int fd,
void ( * ready ) (lua_State *, struct observance * ),
void ( * writey ) (lua_State *, struct observance * ),
void ( * tidy ) (struct observance * ),
void *extra
)
{
int pos;
// looks if the fd is already there as pos or
// stores the position to insert the new fd in pos
for( pos = 0; pos < observances_len; pos++)
{
if( fd <= observances[ pos ].fd )
{ break; }
}
if( pos < observances_len && observances[ pos ].fd == fd )
{
// just updates an existing observance
logstring( "Masterloop", "updating fd observance" );
observances[ pos ].ready = ready;
observances[ pos ].writey = writey;
observances[ pos ].tidy = tidy;
observances[ pos ].extra = extra;
return;
}
if( observance_action )
{
// FIXME
logstring(
"Error",
"New observances in ready/writey handlers not yet supported"
);
exit( -1 );
}
if( !tidy )
{
logstring(
"Error",
"internal, tidy() in observe_fd() must not be NULL."
);
exit( -1 );
}
if( observances_len + 1 > observances_size )
{
observances_size = observances_len + 1;
observances = s_realloc(
observances,
observances_size * sizeof( struct observance )
);
}
memmove(
observances + pos + 1,
observances + pos,
(observances_len - pos) * sizeof(struct observance)
);
observances_len++;
observances[ pos ].fd = fd;
observances[ pos ].ready = ready;
observances[ pos ].writey = writey;
observances[ pos ].tidy = tidy;
observances[ pos ].extra = extra;
}
/*
| Makes the core no longer watch a filedescriptor.
*/
extern void
nonobserve_fd( int fd )
{
int pos;
if( observance_action )
{
// this function is called through a ready/writey handler
// while the core works through the observance list, thus
// it does not alter the list, but stores this actions
// on a stack
nonobservances_len++;
if( nonobservances_len > nonobservances_size )
{
nonobservances_size = nonobservances_len;
nonobservances = s_realloc(
nonobservances,
nonobservances_size * sizeof( int )
);
}
nonobservances[ nonobservances_len - 1 ] = fd;
return;
}
// looks for the fd
for( pos = 0; pos < observances_len; pos++ )
{
if( observances[ pos ].fd == fd )
{ break; }
}
if( pos >= observances_len )
{
logstring(
"Error",
"internal fail, not observance file descriptor in nonobserve"
);
exit( -1 );
}
// tidies up the observance
observances[ pos ].tidy( observances + pos );
// and moves the list down
memmove(
observances + pos,
observances + pos + 1,
(observances_len - pos) * sizeof( struct observance )
);
observances_len--;
}
/*
| A user observance became read-ready.
*/
static void
user_obs_ready(
lua_State * L,
struct observance * obs
)
{
int fd = obs->fd;
// pushes the ready table on table
lua_pushlightuserdata( L, ( void * ) user_obs_ready );
lua_gettable( L, LUA_REGISTRYINDEX );
// pushes the error handler
lua_pushlightuserdata( L, (void *) &callError );
lua_gettable( L, LUA_REGISTRYINDEX );
// pushes the user func
lua_pushnumber( L, fd );
lua_gettable( L, -3 );
// gives the ufunc the fd
lua_pushnumber( L, fd );
// calls the user function
if( lua_pcall( L, 1, 0, -3 ) )
{
exit( -1 );
}
lua_pop( L, 2 );
}
/*
| A user observance became write-ready
*/
static void
user_obs_writey(
lua_State * L,
struct observance * obs
)
{
int fd = obs->fd;
// pushes the writey table on table
lua_pushlightuserdata( L, (void *) user_obs_writey );
lua_gettable( L, LUA_REGISTRYINDEX );
// pushes the error handler
lua_pushlightuserdata(L, (void *) &callError);
lua_gettable( L, LUA_REGISTRYINDEX );
// pushes the user func
lua_pushnumber( L, fd );
lua_gettable( L, -3 );
// gives the user func the fd
lua_pushnumber( L, fd );
// calls the user function
if( lua_pcall( L, 1, 0, -3 ) )
{
exit(-1);
}
lua_pop( L, 2 );
}
/*
| Tidies up a user observance
| FIXME - give the user a chance to do something in that case!
*/
static void
user_obs_tidy( struct observance *obs )
{
close( obs->fd );
}
/******************************.
* Library calls for the runner *
'******************************/
static void daemonize( lua_State *L, const char *pidfile );
int l_stackdump( lua_State* L );
/*
| Logs a message.
|
| Params on Lua stack:
|
| 1: loglevel of massage
| 2: the string to log
*/
static int
l_log( lua_State *L )
{
const char * cat; // log category
const char * message; // log message
int priority; // log priority
cat = luaL_checkstring( L, 1 );
priority = check_logcat( cat );