forked from ZoneMinder/zmeventnotification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zmeventnotification.pl
executable file
·3734 lines (3136 loc) · 112 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 bytes;
use POSIX ':sys_wait_h';
use Time::HiRes qw/gettimeofday/;
use Symbol qw(qualify_to_ref);
use IO::Select;
if ( !try_use('JSON') ) {
if ( !try_use('JSON::XS') ) {
Fatal('JSON or JSON::XS missing');
exit(-1);
}
}
# debugging only.
#use Data::Dumper;
# ==========================================================================
#
# Starting v1.0, configuration has moved to a separate file, please make sure
# you see README
#
# Starting v0.95, I've moved to FCM which means I no longer need to maintain
# my own push server. Plus this uses HTTP which is the new recommended
# way. Note that 0.95 will only work with zmNinja 1.2.510 and beyond
# Conversely, old versions of the event server will NOT work with zmNinja
# 1.2.510 and beyond, so make sure you upgrade both
#
# ==========================================================================
my $app_version = '5.16.0';
# ==========================================================================
#
# 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_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 => 2,
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_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'
};
# 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 $child_forks = 0; # Global tracker of active children
# 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 $fcm_api_key;
my $use_api_push;
my $api_push_script;
my $token_file;
my $fcm_date_format;
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 $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 $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:";
# admin interface options
my %escontrol_interface_settings = ( notifications => {} );
#default key. Please don't change this
use constant NINJA_API_KEY =>
'AAAApYcZ0mA:APA91bG71SfBuYIaWHJorjmBQB3cAN7OMT7bAxKuV3ByJ4JiIGumG6cQw0Bo6_fHGaWoo4Bl-SlCdxbivTv5Z-2XPf0m86wsebNIG15pyUHojzmRvJKySNwfAHs7sprTGsA_SIR_H43h';
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
if ( !try_use('Net::WebSocket::Server') ) {
Fatal('Net::WebSocket::Server missing');
}
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 ("threads")) {Fatal ("threads library/support missing");}
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,
);
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) {
printInfo("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;
printInfo('No config file found, using inbuilt defaults');
}
$secrets_filename = config_get_val( $config, 'general', 'secrets' );
if ($secrets_filename) {
printInfo("using secrets file: $secrets_filename");
$secrets = Config::IniFiles->new( -file => $secrets_filename );
unless ($secrets) {
Fatal( "Encountered errors while reading $secrets_filename:\n"
. join( "\n", @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 yoyr config'
);
}
}
# 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;
my $fc = substr( $final_val, 0, 1 );
#printInfo ("Parsing $final_val with X${fc}X");
if ( $fc eq '!' ) {
my $token = substr( $final_val, 1 );
printDebug( 'Got secret token !' . $token,2 );
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 );
#printInfo ('replacing with:'.$secret_val);
$final_val = $secret_val;
}
#printInfo("ESCONTROL_INTERFACE checking override for $parm");
if ( exists $escontrol_interface_settings{$parm} ) {
printDebug( "ESCONTROL_INTERFACE overrides key: $parm with "
. $escontrol_interface_settings{$parm},2 );
$final_val = $escontrol_interface_settings{$parm};
}
# 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 (@matches) {
my $token = $_;
# 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;
printDebug("config string substitution: {{$token}} is '$val'",3);
$final_val =~ s/\{\{$token\}\}/$val/g;
}
return $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 ) {
printDebug('ES will not be restarted as interval is specified as 0',1);
}
else {
printDebug("ES will be restarted at $restart_interval seconds",1);
}
$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 );
$fcm_api_key = config_get_val( $config, 'fcm', 'api_key', NINJA_API_KEY );
$fcm_date_format =
config_get_val( $config, 'fcm', 'date_format', DEFAULT_FCM_DATE_FORMAT );
$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 );
$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 );
$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 );
$use_hooks =
config_get_val( $config, 'customize', 'use_hooks', DEFAULT_USE_HOOKS );
$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
);
# 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 );
$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 value_or_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))}
FCM Date Format....................... ${\(value_or_undefined($fcm_date_format))}
FCM API key .......................... ${\(present_or_not($fcm_api_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 end notification............${\(yes_or_no($send_event_end_notification))}
Use Hooks............................. ${\(yes_or_no($use_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;
# 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 {
printInfo('Push enabled via FCM');
}
}
else {
printInfo('FCM disabled.');
}
if ($use_api_push) {
printInfo("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);
}
printInfo('MQTT Enabled');
}
else {
printInfo('MQTT Disabled');
}
# ==========================================================================
#
# Don't change anything below here
#
# ==========================================================================
use ZoneMinder;
use POSIX;
use DBI;
$ENV{PATH} = '/bin:/usr/bin';
$ENV{SHELL} = '/bin/sh' if exists $ENV{SHELL};
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
sub Usage {
print("This daemon is not meant to be invoked from command line\n");
exit(-1);
}
sub logrot {
logReinit();
printDebug('log rotate HUP handler processed, logs re-inited',1);
}
# 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/ }
sub REAPER {
# don't mess up return codes for back ticks
local ( $!, $? );
my $pid;
$pid = waitpid( -1, &WNOHANG );
if ( $pid == -1 ) { # no child waiting. Ignore it.
}
elsif ( WIFEXITED($?) ) {
printDebug("REAPER: acknowledged child $pid exiting\n",2);
}
else {
printDebug("REAPER: False alarm on $pid",2);
}
$SIG{CHLD} = \&REAPER; # install *after* calling waitpid
}
logInit();
logSetSignal();
$SIG{HUP} = \&logrot;
#$SIG{CHLD} = \&REAPER;
$SIG{CHLD} = "IGNORE";
#$SIG{CHLD} = 'DEFAULT';
my $dbh = zmDbConnect();
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 $wss;
my @events = ();
my @active_connections = ();
my $wss;
my $zmdc_active = 0;
# Main entry point
#
printInfo("|------- Starting ES version: $app_version ---------|");
printDebug( "Started with: perl:" . $^X . " and command:" . $0 ,1);
my $zmdc_status = `zmdc.pl status zmeventnotification.pl`;
if ( index( $zmdc_status, 'running since' ) != -1 ) {
$zmdc_active = 1;
printDebug(
'ES invoked via ZMDC. Will exit when needed and have zmdc restart it',1);
}
else {
printDebug('ES invoked manually. Will handle restarts ourselves',1);
}
printWarning(
'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;
printDebug('Parent<--Child pipe ready',2);
if ($use_fcm) {
my $dir = dirname($token_file);
if ( !-d $dir ) {
printDebug("Creating $dir to store FCM tokens",1);
mkdir $dir;
}
}
printInfo("Event Notification daemon v $app_version starting\n");
loadPredefinedConnections();
initSocketServer();
printInfo("Event Notification daemon exiting\n");
exit();
# 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 );
}
# ZM logger print and optionally console print
sub printDebug {
my $str = shift;
my $level = shift;
$level = $es_debug_level if not defined $level;
return if $es_debug_level < $level;
my $now = strftime( '%Y-%m-%d,%H:%M:%S', localtime );
$str = $prefix . ' ' . $str;
print( "CONSOLE DBG-$level:", $now, " ", $str, "\n" ) if $console_logs;
Debug($str);
}
sub printInfo {
my $str = shift;
my $now = strftime( '%Y-%m-%d,%H:%M:%S', localtime );
$str = $prefix . ' ' . $str;
print( 'CONSOLE INF:', $now, " ", $str, "\n" ) if $console_logs;
Info($str);
}
sub printWarning {
my $str = shift;
my $now = strftime( '%Y-%m-%d,%H:%M:%S', localtime );
$str = $prefix . ' ' . $str;
print( 'CONSOLE WAR:', $now, " ", $str, "\n" ) if $console_logs;
Warning($str);
}
sub printError {
my $str = shift;
my $now = strftime( '%Y-%m-%d,%H:%M:%S', localtime );
$str = $prefix . ' ' . $str;
print( 'CONSOLE ERR:', $now, " ", $str, "\n" ) if $console_logs;
Error($str);
}
# splits JSON string from detection title string
sub parseDetectResults {
my $results = shift;
my ( $txt, $jsonstring ) = split( '--SPLIT--', $results );
$jsonstring = '[]' if ( !$jsonstring );
printDebug("parse of hook:$txt and $jsonstring",2);
return ( $txt, $jsonstring );
}
sub saveEsControlSettings() {
if ( !$use_escontrol_interface ) {
printDebug('ESCONTROL_INTERFACE is disabled. Not saving control data',1);
}
return if ( !$use_escontrol_interface );
printDebug(
"ESCONTROL_INTERFACE: Saving admin interfaces to $escontrol_interface_file",1
);
store( \%escontrol_interface_settings, $escontrol_interface_file )
or Fatal("Error writing to $escontrol_interface_file: $!");
}
sub loadEsControlSettings() {
if ( !$use_escontrol_interface ) {
printDebug('ESCONTROL_INTERFACE is disabled. Not loading control data',1);
return;
}
printDebug(
"ESCONTROL_INTERFACE: Loading persistent admin interface settings from $escontrol_interface_file",1
);
if ( !-f $escontrol_interface_file ) {
printDebug(
'ESCONTROL_INTERFACE: admin interface file does not exist, creating...',1);
saveEsControlSettings();
}
else {
%escontrol_interface_settings = %{ retrieve($escontrol_interface_file) };
my $json = encode_json( \%escontrol_interface_settings );
printDebug("ESCONTROL_INTERFACE: Loaded parameters: $json",2);
}
}
# checks to see if notifications are muted or enabled for this monitor
sub getNotificationStatusEsControl {
my $id = shift;
if ( !exists $escontrol_interface_settings{notifications}{$id} ) {
printError(
"Hmm, Monitor:$id does not exist in control interface, treating it as force notify..."
);
return ESCONTROL_FORCE_NOTIFY;
}
else {
# printDebug( "ESCONTROL: Notification for Monitor:$id is "
# . $escontrol_interface_settings{notifications}{$id} );
return $escontrol_interface_settings{notifications}{$id};
}
}
sub populateEsControlNotification {
# we need to update notifications in admin interface
if ($use_escontrol_interface) {
my $found = 0;
foreach my $monitor ( values(%monitors) ) {
my $id = $monitor->{Id};
if ( !exists $escontrol_interface_settings{notifications}{$id} ) {
$escontrol_interface_settings{notifications}{$id} =
ESCONTROL_DEFAULT_NOTIFY;
$found = 1;