-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
zmeventnotification.pl
executable file
·3933 lines (3429 loc) · 133 KB
/
zmeventnotification.pl
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
#!/usr/bin/perl -T
#
# ==========================================================================
#
# THIS SCRIPT MUST BE RUN WITH SUDO OR STARTED VIA ZMDC.PL
#
# ZoneMinder Realtime Notification System
#
# A light weight event notification daemon
# Uses shared memory to detect new events (polls SHM)
# Also opens a websocket connection at a configurable port
# so events can be reported
# Any client can connect to this web socket and handle it further
# for example, send it out via APNS/GCM or any other mechanism
#
# This is a much faster and low overhead method compared to zmfilter
# as there is no DB overhead nor SQL searches for event matches
# ~ PP
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# ==========================================================================
use strict;
use warnings;
use bytes;
use POSIX ':sys_wait_h';
use Time::HiRes qw/gettimeofday/;
use Time::Seconds;
use Symbol qw(qualify_to_ref);
use IO::Select;
use ZoneMinder;
use POSIX;
use DBI;
use version;
$ENV{PATH} = '/bin:/usr/bin';
$ENV{SHELL} = '/bin/sh' if exists $ENV{SHELL};
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
####################################
my $app_version = '6.1.29';
####################################
if (@ARGV and ($ARGV[0] eq '--version')) {
# do this before any log init etc.
print ("$app_version\n");
exit(0);
}
if ( !try_use('JSON') ) {
if ( !try_use('JSON::XS') ) {
Fatal('JSON or JSON::XS missing');
exit(-1);
}
}
# debugging only.
#use Data::Dumper;
# ==========================================================================
#
# These are app defaults
# Note that you really should not have to to change these values.
# It is better you change them inside the ini file.
# These values are used ONLY if the server cannot find its ini file
# The only one you may want to change is DEFAULT_CONFIG_FILE to point
# to your custom ini file if you don't use --config. The rest should
# go into that config file.
# ==========================================================================
# configuration constants
use constant {
DEFAULT_CONFIG_FILE => '/etc/zm/zmeventnotification.ini',
DEFAULT_PORT => 9000,
DEFAULT_ADDRESS => '[::]',
DEFAULT_AUTH_ENABLE => 'yes',
DEFAULT_AUTH_TIMEOUT => 20,
DEFAULT_FCM_ENABLE => 'yes',
DEFAULT_USE_FCMV1 => 'yes',
DEFAULT_REPLACE_PUSH_MSGS => 'no',
DEFAULT_MQTT_ENABLE => 'no',
DEFAULT_MQTT_SERVER => '127.0.0.1',
DEFAULT_MQTT_TOPIC => 'zoneminder',
DEFAULT_MQTT_TICK_INTERVAL => 15,
DEFAULT_MQTT_RETAIN => 'no',
DEFAULT_FCM_TOKEN_FILE => '/var/lib/zmeventnotification/push/tokens.txt',
DEFAULT_USE_API_PUSH => 'no',
DEFAULT_BASE_DATA_PATH => '/var/lib/zmeventnotification',
DEFAULT_SSL_ENABLE => 'yes',
DEFAULT_CUSTOMIZE_VERBOSE => 'no',
DEFAULT_CUSTOMIZE_EVENT_CHECK_INTERVAL => 5,
DEFAULT_CUSTOMIZE_ES_DEBUG_LEVEL => 5,
DEFAULT_CUSTOMIZE_MONITOR_RELOAD_INTERVAL => 300,
DEFAULT_CUSTOMIZE_READ_ALARM_CAUSE => 'no',
DEFAULT_CUSTOMIZE_TAG_ALARM_EVENT_ID => 'no',
DEFAULT_CUSTOMIZE_USE_CUSTOM_NOTIFICATION_SOUND => 'no',
DEFAULT_CUSTOMIZE_INCLUDE_PICTURE => 'no',
DEFAULT_USE_HOOKS => 'no',
DEFAULT_HOOK_KEEP_FRAME_MATCH_TYPE => 'yes',
DEFAULT_HOOK_USE_HOOK_DESCRIPTION => 'no',
DEFAULT_HOOK_STORE_FRAME_IN_ZM => 'no',
DEFAULT_RESTART_INTERVAL => 7200,
DEFAULT_EVENT_START_NOTIFY_ON_HOOK_FAIL => 'none',
DEFAULT_EVENT_START_NOTIFY_ON_HOOK_SUCCESS => 'none',
DEFAULT_EVENT_END_NOTIFY_ON_HOOK_FAIL => 'none',
DEFAULT_EVENT_END_NOTIFY_ON_HOOK_SUCCESS => 'none',
DEFAULT_EVENT_END_NOTIFY_IF_START_SUCCESS => 'yes',
DEFAULT_SEND_EVENT_START_NOTIFICATION => 'yes',
DEFAULT_SEND_EVENT_END_NOTIFICATION => 'no',
DEFAULT_USE_ESCONTROL_INTERFACE => 'no',
DEFAULT_ESCONTROL_INTERFACE_FILE =>
'/var/lib/zmeventnotification/misc/escontrol_interface.dat',
DEFAULT_FCM_DATE_FORMAT => '%I:%M %p, %d-%b',
DEFAULT_FCM_ANDROID_PRIORITY=>'high',
DEFAULT_FCM_LOG_RAW_MESSAGE=>'no',
DEFAULT_FCM_LOG_MESSAGE_ID=>'NONE',
DEFAULT_MAX_FCM_PER_MONTH_PER_TOKEN => 8000,
DEFAULT_FCM_V1_KEY => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJnZW5lcmF0b3IiOiJab25lTWluZGVyIEluYyIsImlhdCI6MTY0MTAxODg0OCwiY2xpZW50Ijoiem1uaW5qYSJ9.ThaCp6WOlAHWrNUcXLcMB3yMWUI16AR0nePjufXcWEA',
DEFAULT_FCM_V1_URL => 'https://us-central1-zoneminder-ninja.cloudfunctions.net/send_push',
DEFAULT_MAX_PARALLEL_HOOKS => 0,
};
# connection state
use constant {
PENDING_AUTH => 1,
VALID_CONNECTION => 2,
INVALID_CONNECTION => 3,
PENDING_DELETE => 4,
};
# connection types
use constant {
FCM => 1000,
MQTT => 1001,
WEB => 1002
};
# child fork states
use constant {
ACTIVE => 100,
EXITED => 101
};
# escontrol notification states
use constant {
ESCONTROL_FORCE_NOTIFY => 1,
ESCONTROL_DEFAULT_NOTIFY => 0,
ESCONTROL_FORCE_MUTE => -1,
};
my $es_terminate = 0;
my $child_forks = 0; # Global tracker of active children
my $parallel_hooks = 0; # Global tracker for active hooks
my $total_forks = 0; # Global tracker of all forks since start
# Declare options.
my $help;
my $version;
my $config_file;
my $config_file_present;
my $check_config;
my $use_escontrol_interface;
my $escontrol_interface_password;
my $escontrol_interface_file;
my $port;
my $address;
my $auth_enabled;
my $auth_timeout;
my $use_mqtt;
my $mqtt_server;
my $mqtt_topic;
my $mqtt_username;
my $mqtt_password;
my $mqtt_tls_ca;
my $mqtt_tls_cert;
my $mqtt_tls_key;
my $mqtt_tls_insecure;
my $mqtt_tick_interval;
my $mqtt_retain;
my $mqtt_last_tick_time = time();
my $use_fcm;
my $use_fcmv1;
my $replace_push_messages;
my $use_api_push;
my $api_push_script;
my $token_file;
my $fcm_date_format;
my $fcm_android_priority;
my $fcm_android_ttl;
my $fcm_log_raw_message;
my $fcm_log_message_id;
my $fcm_v1_key;
my $fcm_v1_url;
my $ssl_enabled;
my $ssl_cert_file;
my $ssl_key_file;
my $console_logs;
my $es_debug_level;
my $event_check_interval;
my $monitor_reload_interval;
my $read_alarm_cause;
my $tag_alarm_event_id;
my $use_custom_notification_sound;
my $send_event_end_notification;
my $send_event_start_notification;
my $use_hooks;
my $event_start_hook;
my $event_end_hook;
my $event_start_hook_notify_userscript;
my $event_end_hook_notify_userscript;
my $event_start_notify_on_hook_fail;
my $event_start_notify_on_hook_success;
my %event_start_notify_on_hook_fail;
my %event_start_notify_on_hook_success;
my $event_end_notify_on_hook_fail;
my $event_end_notify_on_hook_success;
my %event_end_notify_on_hook_fail;
my %event_end_notify_on_hook_success;
my $event_end_notify_if_start_success;
my $use_hook_description;
my $keep_frame_match_type;
my $skip_monitors;
my %skip_monitors;
my $hook_skip_monitors;
my %hook_skip_monitors;
my $hook_pass_image_path;
my $es_rules_file;
my %es_rules;
my $picture_url;
my $include_picture;
my $picture_portal_username;
my $picture_portal_password;
my $secrets;
my $secrets_filename;
my $base_data_path;
my $restart_interval;
my $prefix = "PARENT:";
my $pcnt = 0;
my %fcm_tokens_map;
my $max_parallel_hooks= 0;
my %monitors = ();
my %active_events = ();
my $monitor_reload_time = 0;
my $es_start_time = time();
my $apns_feedback_time = 0;
my $proxy_reach_time = 0;
my @events = ();
my @active_connections = ();
my $wss;
my $zmdc_active = 0;
my $is_timepeice = 1;
# admin interface options
my %escontrol_interface_settings = ( notifications => {} );
my $dummyEventTest = 0
; # if on, will generate dummy events. Not in config for a reason. Only dev testing
my $dummyEventInterval = 20; # timespan to generate events in seconds
my $dummyEventTimeLastSent = time();
# This part makes sure we have the right core deps. See later for optional deps
# for testing only
#use lib qw(/home/pp/fiddle/perl-Net-WebSocket-Server/lib);
my $dbh = zmDbConnect(1); # adding 1 disconnects old connection
logInit();
logSetSignal();
#$SIG{CHLD} = \&chld_sig_handler;
$SIG{CHLD} ='IGNORE';
$SIG{INT} = \&shutdown_sig_handler;
$SIG{TERM} = \&shutdown_sig_handler;
$SIG{ABRT} = \&shutdown_sig_handler;
$SIG{HUP} = \&logrot;
if ( !try_use('Net::WebSocket::Server') ) {
Fatal('Net::WebSocket::Server missing');
}
Info("Running on WebSocket library version:$Net::WebSocket::Server::VERSION");
if (version->parse($Net::WebSocket::Server::VERSION) < version->parse('0.004000')) {
Warning("You are using an old version of Net::WebSocket::Server which can cause lockups. Please upgrade. For more information please see https://zmeventnotification.readthedocs.io/en/latest/guides/es_faq.html#the-es-randomly-hangs");
}
if ( !try_use('IO::Socket::SSL') ) { Fatal('IO::Socket::SSL missing'); }
if ( !try_use('IO::Handle') ) { Fatal('IO::Handle'); }
if ( !try_use('Config::IniFiles') ) { Fatal('Config::Inifiles missing'); }
if ( !try_use('Getopt::Long') ) { Fatal('Getopt::Long missing'); }
if ( !try_use('File::Basename') ) { Fatal('File::Basename missing'); }
if ( !try_use('File::Spec') ) { Fatal('File::Spec missing'); }
if ( !try_use('URI::Escape') ) { Fatal('URI::Escape missing'); }
if ( !try_use('Storable') ) { Fatal('Storable missing'); }
if ( !try_use('Time::Piece') ) {
Error(
'rules: Time::Piece module missing. Dates will not work in es rules json');
$is_timepeice = 0;
}
#
use constant USAGE => <<'USAGE';
Usage: zmeventnotification.pl [OPTION]...
--help Print this page.
--version Print version.
--config=FILE Read options from configuration file (default: /etc/zm/zmeventnotification.ini).
Any CLI options used below will override config settings.
--check-config Print configuration and exit.
USAGE
GetOptions(
'help' => \$help,
'version' => \$version,
'config=s' => \$config_file,
'check-config' => \$check_config,
'debug' => \$console_logs
);
if ($version) {
print($app_version);
exit(0);
}
exit( print(USAGE) ) if $help;
# Read options from a configuration file. If --config is specified, try to
# read it and fail if it can't be read. Otherwise, try the default
# configuration path, and if it doesn't exist, take all the default values by
# loading a blank Config::IniFiles object.
if ( !$config_file ) {
$config_file = DEFAULT_CONFIG_FILE;
$config_file_present = -e $config_file;
} else {
if ( !-e $config_file ) {
Fatal("$config_file does not exist!");
}
$config_file_present = 1;
}
my $config;
if ($config_file_present) {
Info("using config file: $config_file");
$config = Config::IniFiles->new( -file => $config_file );
unless ($config) {
Fatal( "Encountered errors while reading $config_file:\n"
. join( "\n", @Config::IniFiles::errors ) );
}
} else {
$config = Config::IniFiles->new;
Info('No config file found, using inbuilt defaults');
}
$secrets_filename = config_get_val( $config, 'general', 'secrets' );
if ($secrets_filename) {
Info("using secrets file: $secrets_filename");
$secrets = Config::IniFiles->new( -file => $secrets_filename );
unless ($secrets) {
Fatal(join("\n", "Encountered errors while reading $secrets_filename:",
@Config::IniFiles::errors));
}
}
$escontrol_interface_file =
config_get_val( $config, 'general', 'escontrol_interface_file',
DEFAULT_ESCONTROL_INTERFACE_FILE );
$use_escontrol_interface =
config_get_val( $config, 'general', 'use_escontrol_interface',
DEFAULT_USE_ESCONTROL_INTERFACE );
$escontrol_interface_password =
config_get_val( $config, 'general', 'escontrol_interface_password' )
if $use_escontrol_interface;
# secrets need to be loaded before admin
# Do this BEFORE any config_get_val
loadEsControlSettings();
# This will not load parameters in the .ini files
loadEsConfigSettings();
my %ssl_push_opts = ();
if ( $ssl_enabled && ( !$ssl_cert_file || !$ssl_key_file ) ) {
Fatal('SSL is enabled, but key or certificate file is missing');
}
my $notId = 1;
if ($hook_pass_image_path) {
if ( !try_use('ZoneMinder::Event') ) {
Fatal(
'ZoneMinder::Event missing, you may be using an old version. Please turn off hook_pass_image_path in your config'
);
}
}
sub check_for_duplicate_token {
my %token_duplicates = ();
foreach (@active_connections) {
$token_duplicates{$_->{token}}++ if $_->{token};
}
foreach (keys %token_duplicates) {
Debug('...'.substr($_,-10).' occurs: '.$token_duplicates{$_}.' times', 2) if $token_duplicates{$_} > 1;
}
}
sub shutdown_sig_handler {
$es_terminate = 1;
Debug(1, 'Received request to shutdown, please wait');
}
sub chld_sig_handler {
my $saved_status = $!;
Debug(1, 'Child signal handler invoked');
# Wait for a child to terminate
while ((my $cpid = waitpid(-1, WNOHANG)) > 0) {
#$pids_to_reap{$cpid} = { status=>$?, stopped=>time() };
} # end while waitpid
$SIG{CHLD} = \&chld_sig_handler;
$! = $saved_status;
}
# this is just a wrapper around Config::IniFiles val
# older versions don't support a default parameter
sub config_get_val {
my ( $config, $sect, $parm, $def ) = @_;
my $val = $config->val( $sect, $parm );
my $final_val = defined($val) ? $val : $def;
if ($final_val) {
my $first_char = substr( $final_val, 0, 1 );
#Info ("Parsing $final_val with X${fc}X");
if ($first_char eq '!') {
my $token = substr($final_val, 1);
Debug(2, 'Got secret token !' . $token);
Fatal('No secret file found') if !$secrets;
my $secret_val = $secrets->val('secrets', $token);
Fatal('Token:'.$token.' not found in secret file') if !$secret_val;
#Info ('replacing with:'.$secret_val);
$final_val = $secret_val;
}
}
#Info("ESCONTROL_INTERFACE checking override for $parm");
if ( exists $escontrol_interface_settings{$parm} ) {
Debug(
"ESCONTROL_INTERFACE overrides key: $parm with "
. $escontrol_interface_settings{$parm},
2
);
$final_val = $escontrol_interface_settings{$parm};
}
return $final_val if !defined($final_val);
# compatibility hack, lets use yes/no in config to maintain
# parity with hook config
if ( lc($final_val) eq 'yes' ) { $final_val = 1; }
elsif ( lc($final_val) eq 'no' ) { $final_val = 0; }
# now search for substitutions
my @matches = ( $final_val =~ /\{\{(.*?)\}\}/g );
foreach my $token (@matches) {
# check if token exists in either general or its own section
# other-section substitution not supported
my $val = $config->val( 'general', $token );
$val = $config->val( $sect, $token ) if !$val;
Debug(2, "config string substitution: {{$token}} is '$val'");
$final_val =~ s/\{\{$token\}\}/$val/g;
}
return trim($final_val);
}
# Loads all the ini file settings and populates variables
sub loadEsConfigSettings {
$restart_interval = config_get_val( $config, 'general', 'restart_interval',
DEFAULT_RESTART_INTERVAL );
if ( !$restart_interval ) {
Debug(1, 'ES will not be restarted as interval is specified as 0');
} else {
Debug(1, "ES will be restarted at $restart_interval seconds");
}
$skip_monitors = config_get_val($config, 'general', 'skip_monitors');
%skip_monitors = map { $_ => !undef } split(',', $skip_monitors);
# If an option set a value, leave it. If there's a value in the config, use
# it. Otherwise, use a default value if it's available.
$base_data_path = config_get_val( $config, 'general', 'base_data_path',
DEFAULT_BASE_DATA_PATH );
$port = config_get_val( $config, 'network', 'port', DEFAULT_PORT );
$address = config_get_val( $config, 'network', 'address', DEFAULT_ADDRESS );
$auth_enabled =
config_get_val( $config, 'auth', 'enable', DEFAULT_AUTH_ENABLE );
$auth_timeout =
config_get_val( $config, 'auth', 'timeout', DEFAULT_AUTH_TIMEOUT );
$use_mqtt = config_get_val( $config, 'mqtt', 'enable', DEFAULT_MQTT_ENABLE );
$mqtt_server =
config_get_val( $config, 'mqtt', 'server', DEFAULT_MQTT_SERVER );
$mqtt_topic = config_get_val( $config, 'mqtt', 'topic', DEFAULT_MQTT_TOPIC );
$mqtt_username = config_get_val( $config, 'mqtt', 'username' );
$mqtt_password = config_get_val( $config, 'mqtt', 'password' );
$mqtt_tls_ca = config_get_val( $config, 'mqtt', 'tls_ca' );
$mqtt_tls_cert = config_get_val( $config, 'mqtt', 'tls_cert' );
$mqtt_tls_key = config_get_val( $config, 'mqtt', 'tls_key' );
$mqtt_tls_insecure = config_get_val( $config, 'mqtt', 'tls_insecure' );
$mqtt_tick_interval =
config_get_val( $config, 'mqtt', 'tick_interval',
DEFAULT_MQTT_TICK_INTERVAL );
$mqtt_retain =
config_get_val( $config, 'mqtt', 'retain', DEFAULT_MQTT_RETAIN );
$use_fcm = config_get_val( $config, 'fcm', 'enable', DEFAULT_FCM_ENABLE );
$use_fcmv1 = config_get_val( $config, 'fcm', 'use_fcmv1', DEFAULT_USE_FCMV1 );
$replace_push_messages = config_get_val( $config, 'fcm', 'replace_push_messages', DEFAULT_REPLACE_PUSH_MSGS );
$fcm_date_format =
config_get_val( $config, 'fcm', 'date_format', DEFAULT_FCM_DATE_FORMAT );
$fcm_android_priority =
config_get_val( $config, 'fcm', 'fcm_android_priority', DEFAULT_FCM_ANDROID_PRIORITY );
$fcm_android_ttl =
config_get_val( $config, 'fcm', 'fcm_android_ttl');
$use_api_push =
config_get_val( $config, 'push', 'use_api_push', DEFAULT_USE_API_PUSH );
if ($use_api_push) {
$api_push_script = config_get_val( $config, 'push', 'api_push_script' );
Error('You have API push enabled, but no script to handle API pushes')
if !$api_push_script;
}
$token_file =
config_get_val( $config, 'fcm', 'token_file', DEFAULT_FCM_TOKEN_FILE );
$fcm_log_raw_message=
config_get_val( $config, 'fcm', 'fcm_log_raw_message', DEFAULT_FCM_LOG_RAW_MESSAGE );
$fcm_log_message_id=
config_get_val( $config, 'fcm', 'fcm_log_message_id', DEFAULT_FCM_LOG_MESSAGE_ID );
$fcm_v1_key=
config_get_val( $config, 'fcm', 'fcm_v1_key', DEFAULT_FCM_V1_KEY );
$fcm_v1_url=
config_get_val( $config, 'fcm', 'fcm_v1_url', DEFAULT_FCM_V1_URL );
$ssl_enabled = config_get_val( $config, 'ssl', 'enable', DEFAULT_SSL_ENABLE );
$ssl_cert_file = config_get_val( $config, 'ssl', 'cert' );
$ssl_key_file = config_get_val( $config, 'ssl', 'key' );
$console_logs = config_get_val( $config, 'customize', 'console_logs',
DEFAULT_CUSTOMIZE_VERBOSE ) if (!$console_logs);
$es_debug_level = config_get_val( $config, 'customize', 'es_debug_level',
DEFAULT_CUSTOMIZE_ES_DEBUG_LEVEL );
$event_check_interval =
config_get_val( $config, 'customize', 'event_check_interval',
DEFAULT_CUSTOMIZE_EVENT_CHECK_INTERVAL );
$monitor_reload_interval =
config_get_val( $config, 'customize', 'monitor_reload_interval',
DEFAULT_CUSTOMIZE_MONITOR_RELOAD_INTERVAL );
$read_alarm_cause =
config_get_val( $config, 'customize', 'read_alarm_cause',
DEFAULT_CUSTOMIZE_READ_ALARM_CAUSE );
$tag_alarm_event_id =
config_get_val( $config, 'customize', 'tag_alarm_event_id',
DEFAULT_CUSTOMIZE_TAG_ALARM_EVENT_ID );
$use_custom_notification_sound = config_get_val(
$config, 'customize',
'use_custom_notification_sound',
DEFAULT_CUSTOMIZE_USE_CUSTOM_NOTIFICATION_SOUND
);
$picture_url = config_get_val( $config, 'customize', 'picture_url' );
$include_picture = config_get_val( $config, 'customize', 'include_picture',
DEFAULT_CUSTOMIZE_INCLUDE_PICTURE );
$picture_portal_username =
config_get_val( $config, 'customize', 'picture_portal_username' );
$picture_portal_password =
config_get_val( $config, 'customize', 'picture_portal_password' );
$send_event_end_notification =
config_get_val( $config, 'customize', 'send_event_end_notification',
DEFAULT_SEND_EVENT_END_NOTIFICATION );
$send_event_start_notification =
config_get_val( $config, 'customize', 'send_event_start_notification',
DEFAULT_SEND_EVENT_START_NOTIFICATION );
$use_hooks =
config_get_val( $config, 'customize', 'use_hooks', DEFAULT_USE_HOOKS );
$es_rules_file = config_get_val( $config, 'customize', 'es_rules' );
if ($es_rules_file) {
my $hr;
my $fh;
Debug(2, "rules: Loading es rules json: $es_rules_file");
if (open($fh, '<', $es_rules_file)) {
my $data = do { local $/ = undef; <$fh> };
eval { $hr = decode_json($data); };
if ($@) {
Error("rules: Failed decoding es rules: $@");
} else {
%es_rules = %$hr;
#print Dumper(\%es_rules);
}
close($fh);
} else {
Error("rules: Could not open $es_rules_file: $!");
}
} # if es_rules
$event_start_hook = config_get_val( $config, 'hook', 'event_start_hook' );
$event_start_hook_notify_userscript =
config_get_val( $config, 'hook', 'event_start_hook_notify_userscript' );
$event_end_hook_notify_userscript =
config_get_val( $config, 'hook', 'event_end_hook_notify_userscript' );
# backward compatibility
$event_start_hook = config_get_val( $config, 'hook', 'hook_script' )
if !$event_start_hook;
$event_end_hook = config_get_val( $config, 'hook', 'event_end_hook' );
$event_start_notify_on_hook_fail = config_get_val(
$config, 'hook',
'event_start_notify_on_hook_fail',
DEFAULT_EVENT_START_NOTIFY_ON_HOOK_FAIL
);
$event_start_notify_on_hook_success = config_get_val(
$config, 'hook',
'event_start_notify_on_hook_success',
DEFAULT_EVENT_START_NOTIFY_ON_HOOK_SUCCESS
);
$event_end_notify_on_hook_fail = config_get_val(
$config, 'hook',
'event_end_notify_on_hook_fail',
DEFAULT_EVENT_END_NOTIFY_ON_HOOK_FAIL
);
$event_end_notify_on_hook_success = config_get_val(
$config, 'hook',
'event_end_notify_on_hook_success',
DEFAULT_EVENT_END_NOTIFY_ON_HOOK_SUCCESS
);
$max_parallel_hooks = config_get_val(
$config, 'hook',
'max_parallel_hooks',
DEFAULT_MAX_PARALLEL_HOOKS
);
# get channels and convert to hash
%event_start_notify_on_hook_fail = map { $_ => 1 }
split( /\s*,\s*/, lc($event_start_notify_on_hook_fail) );
%event_start_notify_on_hook_success = map { $_ => 1 }
split( /\s*,\s*/, lc($event_start_notify_on_hook_success) );
%event_end_notify_on_hook_fail =
map { $_ => 1 } split( /\s*,\s*/, lc($event_end_notify_on_hook_fail) );
%event_end_notify_on_hook_success = map { $_ => 1 }
split( /\s*,\s*/, lc($event_end_notify_on_hook_success) );
$event_end_notify_if_start_success = config_get_val(
$config, 'hook',
'event_end_notify_if_start_success',
DEFAULT_EVENT_END_NOTIFY_IF_START_SUCCESS
);
$use_hook_description =
config_get_val( $config, 'hook', 'use_hook_description',
DEFAULT_HOOK_USE_HOOK_DESCRIPTION );
$keep_frame_match_type =
config_get_val( $config, 'hook', 'keep_frame_match_type',
DEFAULT_HOOK_KEEP_FRAME_MATCH_TYPE );
$hook_skip_monitors = config_get_val( $config, 'hook', 'hook_skip_monitors' );
%hook_skip_monitors = map { $_ => !undef } split( ',', $hook_skip_monitors ) if $hook_skip_monitors;
$hook_pass_image_path = config_get_val( $config, 'hook', 'hook_pass_image_path' );
}
# helper routines to print config status in help
sub yes_or_no {
return $_[0] ? 'yes' : 'no';
}
sub default_or_custom {
return $_[0] eq $_[1] ? 'default' : 'custom';
}
sub value_or_undefined {
return defined($_[0]) ? $_[0] : '(undefined)';
#return $_[0] || '(undefined)';
}
sub present_or_not {
return $_[0] ? '(defined)' : '(undefined)';
}
sub print_config {
my $abs_config_file = File::Spec->rel2abs($config_file);
print(
<<"EOF"
${\(
$config_file_present ?
"Configuration (read $abs_config_file)" :
"Default configuration ($abs_config_file doesn't exist)"
)}:
Secrets file.......................... ${\(value_or_undefined($secrets_filename))}
Base data path........................ ${\(value_or_undefined($base_data_path))}
Restart interval (secs)............... ${\(value_or_undefined($restart_interval))}
Use admin interface .................. ${\(yes_or_no($use_escontrol_interface))}
Admin interface password.............. ${\(present_or_not($escontrol_interface_password))}
Admin interface persistence file ..... ${\(value_or_undefined($escontrol_interface_file))}
Port ................................. ${\(value_or_undefined($port))}
Address .............................. ${\(value_or_undefined($address))}
Event check interval ................. ${\(value_or_undefined($event_check_interval))}
Monitor reload interval .............. ${\(value_or_undefined($monitor_reload_interval))}
Skipped monitors...................... ${\(value_or_undefined($skip_monitors))}
Auth enabled ......................... ${\(yes_or_no($auth_enabled))}
Auth timeout ......................... ${\(value_or_undefined($auth_timeout))}
Use API Push.......................... ${\(yes_or_no($use_api_push))}
API Push Script....................... ${\(value_or_undefined($api_push_script))}
Use FCM .............................. ${\(yes_or_no($use_fcm))}
Use FCM V1 APIs....................... ${\(yes_or_no($use_fcmv1))}
FCM Date Format....................... ${\(value_or_undefined($fcm_date_format))}
Only show latest FCMv1 message........ ${\(yes_or_no($replace_push_messages))}
Android FCM push priority............. ${\(value_or_undefined($fcm_android_priority))}
Android FCM push ttl.................. ${\(value_or_undefined($fcm_android_ttl))}
Log FCM message ID.................... ${\(value_or_undefined($fcm_log_message_id))}
Log RAW FCM Messages.................. ${\(yes_or_no($fcm_log_raw_message))}
FCM V1 URL............................ ${\(value_or_undefined($fcm_v1_url))}
FCM V1 Key............................ ${\(default_or_custom($fcm_v1_key, DEFAULT_FCM_V1_KEY))}
Token file ........................... ${\(value_or_undefined($token_file))}
Use MQTT ............................. ${\(yes_or_no($use_mqtt))}
MQTT Server .......................... ${\(value_or_undefined($mqtt_server))}
MQTT Topic ........................... ${\(value_or_undefined($mqtt_topic))}
MQTT Username ........................ ${\(value_or_undefined($mqtt_username))}
MQTT Password ........................ ${\(present_or_not($mqtt_password))}
MQTT Retain .......................... ${\(yes_or_no($mqtt_retain))}
MQTT Tick Interval ................... ${\(value_or_undefined($mqtt_tick_interval))}
MQTT TLS CA .......................... ${\(value_or_undefined($mqtt_tls_ca))}
MQTT TLS Cert ........................ ${\(value_or_undefined($mqtt_tls_cert))}
MQTT TLS Key ......................... ${\(value_or_undefined($mqtt_tls_key))}
MQTT TLS Insecure .................... ${\(yes_or_no($mqtt_tls_insecure))}
SSL enabled .......................... ${\(yes_or_no($ssl_enabled))}
SSL cert file ........................ ${\(value_or_undefined($ssl_cert_file))}
SSL key file ......................... ${\(value_or_undefined($ssl_key_file))}
Verbose .............................. ${\(yes_or_no($console_logs))}
ES Debug level........................ ${\(value_or_undefined($es_debug_level))}
Read alarm cause ..................... ${\(yes_or_no($read_alarm_cause))}
Tag alarm event id ................... ${\(yes_or_no($tag_alarm_event_id))}
Use custom notification sound ........ ${\(yes_or_no($use_custom_notification_sound))}
Send event start notification......... ${\(yes_or_no($send_event_start_notification))}
Send event end notification........... ${\(yes_or_no($send_event_end_notification))}
Monitor rules JSON file............... ${\(value_or_undefined($es_rules_file))}
Use Hooks............................. ${\(yes_or_no($use_hooks))}
Max Parallel Hooks.................... ${\(value_or_undefined($max_parallel_hooks))}
Hook Script on Event Start ........... ${\(value_or_undefined($event_start_hook))}
User Script on Event Start............ ${\(value_or_undefined($event_start_hook_notify_userscript))}
Hook Script on Event End.............. ${\(value_or_undefined($event_end_hook))}
User Script on Event End.............. ${\(value_or_undefined($event_end_hook_notify_userscript))}
Hook Skipped monitors................. ${\(value_or_undefined($hook_skip_monitors))}
Notify on Event Start (hook success).. ${\(value_or_undefined($event_start_notify_on_hook_success))}
Notify on Event Start (hook fail)..... ${\(value_or_undefined($event_start_notify_on_hook_fail))}
Notify on Event End (hook success).... ${\(value_or_undefined($event_end_notify_on_hook_success))}
Notify on Event End (hook fail)....... ${\(value_or_undefined($event_end_notify_on_hook_fail))}
Notify End only if Start success...... ${\(yes_or_no($event_end_notify_if_start_success))}
Use Hook Description.................. ${\(yes_or_no($use_hook_description))}
Keep frame match type................. ${\(yes_or_no($keep_frame_match_type))}
Store Frame in ZM..................... ${\(yes_or_no($hook_pass_image_path))}
Picture URL .......................... ${\(value_or_undefined($picture_url))}
Include picture....................... ${\(yes_or_no($include_picture))}
Picture username ..................... ${\(value_or_undefined($picture_portal_username))}
Picture password ..................... ${\(present_or_not($picture_portal_password))}
EOF
);
}
exit(print_config()) if $check_config;
print_config() if $console_logs;
ZoneMinder::Logger::logTermLevel(DEBUG1) if $console_logs;
# Lets now load all the optional dependent libraries in a failsafe way
# Fetch whatever options are available from CLI arguments.
if ($use_fcm) {
if ( !try_use('LWP::UserAgent')
|| !try_use('URI::URL')
|| !try_use('LWP::Protocol::https') )
{
Fatal(
'FCM push mode needs LWP::Protocol::https, LWP::UserAgent and URI::URL perl packages installed'
);
} else {
Info('Push enabled via FCM');
Debug(2, "fcmv1: --> FCM V1 APIs: $use_fcmv1");
Debug(1, "fcmv1:--> Your FCM messages will be LOGGED at pliablepixel's server because your fcm_log_raw_message in zmeventnotification.ini is yes. Please turn it off, if you don't want it to!") if $fcm_log_raw_message;
}
} else {
Info('FCM disabled.');
}
if ($use_api_push) {
Info("Pushes will be sent through APIs and will use $api_push_script");
}
if ($use_mqtt) {
if (!try_use('Net::MQTT::Simple')) {
Fatal('Net::MQTT::Simple missing');
exit(-1);
}
if (defined $mqtt_tls_ca && !try_use('Net::MQTT::Simple::SSL')) {
Fatal('Net::MQTT::Simple:SSL missing');
exit(-1);
}
Info('MQTT Enabled');
} else {
Info('MQTT Disabled');
}
sub Usage {
print("This daemon is not meant to be invoked from command line\n");
exit(-1);
}
sub logrot {
logReinit();
Debug(1, 'log rotate HUP handler processed, logs re-inited');
}
# https://docstore.mik.ua/orelly/perl4/cook/ch07_24.htm
sub sysreadline(*;$) {
my ( $handle, $timeout ) = @_;
$handle = qualify_to_ref( $handle, caller() );
my $infinitely_patient = ( @_ == 1 || $timeout < 0 );
my $start_time = time();
my $selector = IO::Select->new();
$selector->add($handle);
my $line = "";
SLEEP:
until ( at_eol($line) ) {
unless ($infinitely_patient) {
return $line if time() > ( $start_time + $timeout );
}
# sleep only 1 second before checking again
next SLEEP unless $selector->can_read(1.0);
INPUT_READY:
while ( $selector->can_read(0.0) ) {
my $was_blocking = $handle->blocking(0);
CHAR: while ( sysread( $handle, my $nextbyte, 1 ) ) {
$line .= $nextbyte;
last CHAR if $nextbyte eq "\n";
}
$handle->blocking($was_blocking);
# if incomplete line, keep trying
next SLEEP unless at_eol($line);
last INPUT_READY;
}
}
return $line;
}
sub at_eol($) { $_[0] =~ /\n\z/ }
# Main entry point
#
Info("|------- Starting ES version: $app_version ---------|");
Debug(2, "Started with: perl:" . $^X . " and command:" . $0);
my $zmdc_status = `zmdc.pl status zmeventnotification.pl`;
if (index($zmdc_status, 'running since') != -1) {
$zmdc_active = 1;
Debug(1, 'ES invoked via ZMDC. Will exit when needed and have zmdc restart it');
} else {
Debug(1, 'ES invoked manually. Will handle restarts ourselves');
}
Warning(
'WARNING: SSL is disabled, which means all traffic will be unencrypted')
unless $ssl_enabled;
pipe( READER, WRITER ) || die "pipe failed: $!";
WRITER->autoflush(1);
my ( $rin, $rout ) = ('');
vec( $rin, fileno(READER), 1 ) = 1;
Debug(2, 'Parent<--Child pipe ready');
if ($use_fcm) {
my $dir = dirname($token_file);
if ( !-d $dir ) {
Debug(1, "Creating $dir to store FCM tokens");
mkdir $dir;
}
}
Info("Event Notification daemon v $app_version starting");
loadPredefinedConnections();
initSocketServer();
Info("Event Notification daemon exiting");
exit();
# left and right trim
sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };
# Try to load a perl module
# and if it is not available
# generate a log
sub try_use {
my $module = shift;
eval("use $module");
return ( $@ ? 0 : 1 );
}
# splits JSON string from detection title string
sub parseDetectResults {
my $results = shift;
my ($txt, $jsonstring) = $results ? split('--SPLIT--', $results) : ('','[]');
#ensure defined results so quiet warnings
$txt = '' if !$txt;
$jsonstring = '[]' if !$jsonstring;
Debug(2, "parse of hook:$txt and $jsonstring from $results");
return ($txt, $jsonstring);
}
sub saveEsControlSettings {