forked from ZoneMinder/zmeventnotification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzmeventnotification.pl
executable file
·1419 lines (1237 loc) · 50.1 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.
#
# ==========================================================================
#sudo perl -MCPAN -e "install Crypt::MySQL"
#sudo perl -MCPAN -e "install Net::WebSocket::Server"
#For pushProxy
#sudo perl -MCPAN -e "install LWP::Protocol::https"
#For iOS APNS:
#sudo perl -MCPAN -e "install Net::APNS::Persistent"
use File::Basename;
use strict;
use bytes;
my $app_version="0.93";
# ==========================================================================
#
# These are the elements you can edit to suit your installation
#
# ==========================================================================
use constant EVENT_NOTIFICATION_PORT=>9000; # port for Websockets connection
my $useSecure = 1; # make this 0 if you don't want SSL
# ignore if useSecure is 0
use constant SSL_CERT_FILE=>'/etc/apache2/ssl/zoneminder.crt'; # Change these to your certs/keys
use constant SSL_KEY_FILE=>'/etc/apache2/ssl/zoneminder.key';
# if you only want to enable websockets make both of these 0
my $usePushProxy = 1; # set this to 1 to use a remote push proxy for APNS that I have set up for zmNinja users
my $useMQTTServer = 1; # set this to 1 to publish events on a MQTT Server
my $usePushAPNSDirect = 0; # set this to 1 if you have an APNS SSL certificate/key pair
# the only way to have this is if you have an apple developer
# account
my $pushProxyURL = 'https://185.124.74.36:8801'; # This is my proxy URL. Don't change it unless you are hosting your on APNS AS
my $useCustomNotificationSound = 1; # set to 0 for default sound
# PUSH_TOKEN_FILE is needed for pushProxy mode as well as direct APNS mode
# change this to a directory and file of your choosing.
# This server will create the file if it does not exist
use constant PUSH_TOKEN_FILE=>'/etc/private/tokens.txt'; # MAKE SURE THIS DIRECTORY HAS WWW-DATA PERMISSIONS
my $printDebugToConsole = 0; # set this to OFF unless you are debugging. If 1, make sure its NOT running via zmdc
#
# -------- There seems to be an LWP perl bug that fails certifying self signed certs
# refer to https://bugs.launchpad.net/ubuntu/+source/libwww-perl/+bug/1408331
# you don't have to make it this drastic, you can also follow other tips in that thread to point to
# a mozilla cert. I haven't tried
my %ssl_push_opts = ( ssl_opts=>{verify_hostname => 0,SSL_verify_mode => 0,SSL_verifycn_scheme => 'none'} );
#----------- Start: Change these only if you have usePushAPNSDirect set to 1 ------------------
my $isSandbox = 1; # 1 or 0 depending on your APNS certificate
use constant APNS_CERT_FILE=>'/etc/private/apns-dev-cert.pem'; # only used if usePushAPNSDirect is enabled
use constant APNS_KEY_FILE=>'/etc/private/apns-dev-key.pem'; # only used if usePushAPNSDirect is enabled
use constant APNS_FEEDBACK_CHECK_INTERVAL => 3600; # only used if usePushAPNSDirect is enabled
#----------- End: only applies to usePushAPNSDirect = 1 --
use constant PUSH_CHECK_REACH_INTERVAL => 3600; # time in seconds to do a reachability test with push proxt
use constant SLEEP_DELAY=>5; # duration in seconds after which we will check for new events
use constant MONITOR_RELOAD_INTERVAL => 300;
use constant WEBSOCKET_AUTH_DELAY => 20; # max seconds by which authentication must be done
# These are needed for the remote push to work. Don't change these
use constant PUSHPROXY_APP_NAME => 'zmninjapro';
use constant PUSHPROXY_APP_ID => 'e10db4ac29d34243f66f15592328fecc';
use constant PENDING_WEBSOCKET => '1';
use constant INVALID_WEBSOCKET => '-1';
use constant INVALID_APNS => '-2';
use constant INVALID_AUTH => '-3';
use constant VALID_WEBSOCKET => '0';
my $alarmEventId = 1; # tags the event id along with the alarm - useful for correlation
# only for geeks though - most people won't give a damn. I do.
my $mqttServer = '127.0.0.1';
# This part makes sure we have the righ deps
if (!try_use ("Net::WebSocket::Server")) {Fatal ("Net::WebSocket::Server missing");exit (-1);}
if (!try_use ("IO::Socket::SSL")) {Fatal ("IO::Socket::SSL missing");exit (-1);}
if (!try_use ("Crypt::MySQL qw(password password41)")) {Fatal ("Crypt::MySQL missing");exit (-1);}
if (!try_use ("JSON"))
{
if (!try_use ("JSON::XS"))
{ Fatal ("JSON or JSON::XS missing");exit (-1);}
}
# Lets now load all the dependent libraries in a failsafe way
if ($usePushProxy)
{
if ($usePushAPNSDirect) # can't have both
{
$usePushAPNSDirect = 0;
Info ("Disabling direct push as push proxy is enabled");
}
if (!try_use ("LWP::UserAgent") || !try_use ("URI::URL") || !try_use("LWP::Protocol::https"))
{
Error ("Disabling PushProxy. PushProxy mode needs LWP::Protocol::https, LWP::UserAgent and URI::URL perl packages installed");
$usePushProxy = 0;
}
else
{
Info ("Push enabled via PushProxy");
}
}
else
{
Info ("Push Proxy disabled");
}
# These modules are needed only if DirectPush is enabled and PushProxy is disabled
if ($usePushAPNSDirect )
{
if (!try_use ("Net::APNS::Persistent") || !try_use ("Net::APNS::Feedback"))
{
Error ("Net::APNS::Feedback and/or Net::APNS::Persistent not present. Disabling direct APNS support");
$usePushAPNSDirect = 0;
}
else
{
Info ("direct APNS support loaded");
}
}
else
{
Info ("direct APNS disabled");
}
if ($useMQTTServer)
{
if (!try_use ("Net::MQTT::Simple")) {Fatal ("Net::MQTT::Simple missing");exit (-1);}
}
# ==========================================================================
#
# Don't change anything below here
#
# ==========================================================================
use lib '/usr/local/lib/x86_64-linux-gnu/perl5';
use ZoneMinder;
use POSIX;
use DBI;
$| = 1;
$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 );
}
logInit();
logSetSignal();
my $dbh = zmDbConnect();
my %monitors;
my $monitor_reload_time = 0;
my $apns_feedback_time = 0;
my $proxy_reach_time=0;
my $wss;
my @events=();
my @active_connections=();
my $alarm_header="";
my $alarm_mid="";
# MAIN
printdbg ("******You are running version: $app_version");
if ($usePushAPNSDirect || $usePushProxy)
{
my $dir = dirname(PUSH_TOKEN_FILE);
if ( ! -d $dir)
{
Info ("Creating $dir to store APNS tokens");
mkdir $dir;
}
}
Info( "Event Notification daemon v $app_version starting\n" );
loadTokens();
initSocketServer();
Info( "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);
}
# console print
sub printdbg
{
my $a = shift;
my $now = strftime('%Y-%m-%d,%H:%M:%S',localtime);
print($now," ",$a, "\n") if $printDebugToConsole;
}
# This function uses shared memory polling to check if
# ZM reported any new events. If it does find events
# then the details are packaged into the events array
# so they can be JSONified and sent out
sub checkEvents()
{
my $eventFound = 0;
if ( (time() - $monitor_reload_time) > MONITOR_RELOAD_INTERVAL )
{
my $len = scalar @active_connections;
Info ("Total event client connections: ".$len."\n");
my $ndx = 1;
foreach (@active_connections)
{
my $cip="(none)";
if (exists $_->{conn} )
{
$cip = $_->{conn}->ip();
}
Debug ("-->Connection $ndx: IP->".$cip." Token->:".$_->{token}." Plat:".$_->{platform}." Push:".$_->{pushstate});
printdbg ("-->Connection $ndx: IP->".$cip." Token->".$_->{token}." Plat:".$_->{platform}." Push:".$_->{pushstate});
$ndx++;
}
Info ("Reloading Monitors...\n");
foreach my $monitor (values(%monitors))
{
zmMemInvalidate( $monitor );
}
loadMonitors();
}
@events = ();
$alarm_header = "";
$alarm_mid="";
foreach my $monitor ( values(%monitors) )
{
my ( $state, $last_event )
= zmMemRead( $monitor,
[ "shared_data:state",
"shared_data:last_event"
]
);
Debug ("State for ".$monitor->{Name}." reported as:".$state);
if ($state == STATE_ALARM || $state == STATE_ALERT)
{
Debug ("state is STATE_ALARM or ALERT for ".$monitor->{Name});
if ( !defined($monitor->{LastEvent})
|| ($last_event != $monitor->{LastEvent}))
{
Info( "New event $last_event reported for ".$monitor->{Name}."\n");
$monitor->{LastState} = $state;
$monitor->{LastEvent} = $last_event;
my $name = $monitor->{Name};
my $mid = $monitor->{Id};
my $eid = $last_event;
Debug ("Creating event object for ".$monitor->{Name}." with $last_event");
push @events, {Name => $name, MonitorId => $mid, EventId => $last_event};
$alarm_header = "Alarms: " if (!$alarm_header);
$alarm_header = $alarm_header . $name ;
$alarm_mid = $alarm_mid.$mid.",";
$alarm_header = $alarm_header . " (".$last_event.") " if ($alarmEventId);
$alarm_header = $alarm_header . "," ;
$eventFound = 1;
}
}
}
chop($alarm_header) if ($alarm_header);
chop ($alarm_mid) if ($alarm_mid);
return ($eventFound);
}
# Refreshes list of monitors from DB
#
sub loadMonitors
{
Info( "Loading monitors\n" );
$monitor_reload_time = time();
my %new_monitors = ();
my $sql = "SELECT * FROM Monitors
WHERE find_in_set( Function, 'Modect,Mocord,Nodect' )".
( $Config{ZM_SERVER_ID} ? 'AND ServerId=?' : '' );
Debug ("SQL to be executed is :$sql");
my $sth = $dbh->prepare_cached( $sql )
or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute( $Config{ZM_SERVER_ID} ? $Config{ZM_SERVER_ID} : () )
or Fatal( "Can't execute: ".$sth->errstr() );
while( my $monitor = $sth->fetchrow_hashref() )
{
next if ( !zmMemVerify( $monitor ) ); # Check shared memory ok
if ( defined($monitors{$monitor->{Id}}->{LastState}) )
{
$monitor->{LastState} = $monitors{$monitor->{Id}}->{LastState};
}
else
{
$monitor->{LastState} = zmGetMonitorState( $monitor );
}
if ( defined($monitors{$monitor->{Id}}->{LastEvent}) )
{
$monitor->{LastEvent} = $monitors{$monitor->{Id}}->{LastEvent};
}
else
{
$monitor->{LastEvent} = zmGetLastEvent( $monitor );
}
$new_monitors{$monitor->{Id}} = $monitor;
}
%monitors = %new_monitors;
}
# Does a health check to make sure push proxy is reachable
sub testProxyURL
{
if ((time() - $proxy_reach_time) > PUSH_CHECK_REACH_INTERVAL)
{
Info ("Checking $pushProxyURL reachability...");
my $ua = LWP::UserAgent->new(%ssl_push_opts);
$ua->timeout(10);
$ua->env_proxy;
my $response = $ua->get($pushProxyURL);
if ($response->is_success)
{
Info ("PushProxy $pushProxyURL is reachable.");
}
else
{
Error ($response->status_line);
Error ("PushProxy $pushProxyURL is NOT reachable. Notifications will not work. Please reach out to the proxy owner if this error persists");
}
$proxy_reach_time = time();
}
}
# This function compares the password provided over websockets
# to the password stored in the ZM MYSQL DB
sub validateZM
{
my ($u,$p) = @_;
return 0 if ( $u eq "" || $p eq "");
my $sql = 'select Password from Users where Username=?';
my $sth = $dbh->prepare_cached($sql)
or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute( $u )
or Fatal( "Can't execute: ".$sth->errstr() );
if (my ($state) = $sth->fetchrow_hashref())
{
my $encryptedPassword = password41($p);
$sth->finish();
return $state->{Password} eq $encryptedPassword ? 1:0;
}
else
{
$sth->finish();
return 0;
}
}
# Passes on device token to the push proxy
sub registerOverPushProxy
{
my ($token) = shift;
my ($platform) = shift;
my $uri = $pushProxyURL."/api/v2/tokens";
my $json = '{"device":"'.$platform.'", "token":"'.$token.'", "channel":"default"}';
my $req = HTTP::Request->new ('POST', $uri);
$req->header( 'Content-Type' => 'application/json', 'X-AN-APP-NAME'=> PUSHPROXY_APP_NAME, 'X-AN-APP-KEY'=> PUSHPROXY_APP_ID
);
$req->content($json);
my $lwp = LWP::UserAgent->new(%ssl_push_opts);
my $res = $lwp->request( $req );
if ($res->is_success)
{
Info ("Pushproxy registration success ".$res->content);
}
else
{
Warning("Push Proxy Token registration Error:".$res->status_line);
}
}
# Sends a push notification to the remote proxy
sub sendOverPushProxy
{
my ($obj, $header, $mid, $str) = @_;
$obj->{badge}++;
my $uri = $pushProxyURL."/api/v2/push";
my $json;
# Not passing full JSON object - so that payload is limited for now
if ($obj->{platform} eq "ios")
{
if ($useCustomNotificationSound)
{
$json = encode_json ({
device=>$obj->{platform},
token=>$obj->{token},
alert=>$header,
sound=>'blop.caf',
custom=> { mid=>$mid},
badge=>$obj->{badge}
});
}
else
{
$json = encode_json ({
device=>$obj->{platform},
token=>$obj->{token},
alert=>$header,
sound=>'true',
custom=> { mid=>$mid},
badge=>$obj->{badge}
});
}
}
else # android
{
if ($useCustomNotificationSound)
{
$json = encode_json ({
device=>$obj->{platform},
token=>$obj->{token},
alert=>$header,
sound=>'blop',
extra=> { mid=>$mid}
});
}
else
{
$json = encode_json ({
device=>$obj->{platform},
token=>$obj->{token},
extra=> { mid=>$mid},
alert=>$header
});
}
}
#print "Sending:$json\n";
Debug ("Final JSON being sent is: $json");
my $req = HTTP::Request->new ('POST', $uri);
$req->header( 'Content-Type' => 'application/json', 'X-AN-APP-NAME'=> PUSHPROXY_APP_NAME, 'X-AN-APP-KEY'=> PUSHPROXY_APP_ID);
$req->content($json);
my $lwp = LWP::UserAgent->new(%ssl_push_opts);
my $res = $lwp->request( $req );
if ($res->is_success)
{
Info ("Pushproxy push message success ".$res->content);
}
else
{
Info("Push Proxy push message Error:".$res->status_line);
}
}
# Sends a push notification to the mqtt Broker
sub sendOverMQTTBroker
{
my ($header, $mid) = @_;
my $json;
$json = encode_json ({
monitor=> $mid,
name=>$header,
state => 'alarm',
});
Debug ("Final JSON being sent is: $json");
my $mqtt = Net::MQTT::Simple->new($mqttServer);
$mqtt->publish(join('/','zoneminder',$mid) => $json);
}
# This function is called when an alarm
# needs to be transmitted over APNS
# called only if direct APNS mode is enabled
sub sendOverAPNS
{
if (!$usePushAPNSDirect)
{
Info ("Rejecting APNS request as daemon has APNS disabled");
return;
}
my ($obj, $header, $mid, $str) = @_;
my (%hash) = %{$str};
my $apns = Net::APNS::Persistent->new({
sandbox => $isSandbox,
cert => APNS_CERT_FILE,
key => APNS_KEY_FILE
});
$obj->{badge}++;
$apns->queue_notification(
$obj->{token},
{
aps => {
alert => $header,
sound => 'default',
badge => $obj->{badge},
},
alarm_details => \%hash
});
$apns->send_queue;
$apns->disconnect;
}
# This function polls APNS Feedback
# to see if any entries need to be removed
# only applicable for direct apns mode
sub apnsFeedbackCheck
{
if ((time() - $apns_feedback_time) > APNS_FEEDBACK_CHECK_INTERVAL)
{
if ($usePushProxy)
{
Info ("Not checking APNS feedback in PushProxy Mode");
return;
}
if (!$usePushAPNSDirect)
{
Info ("Rejecting APNS Feedback request as daemon has APNS disabled");
return;
}
Info ("Checking APNS Feedback\n");
$apns_feedback_time = time();
my $apnsfb = Net::APNS::Feedback->new({
sandbox => $isSandbox,
cert => APNS_CERT_FILE,
key => APNS_KEY_FILE
});
my @feedback = $apnsfb->retrieve_feedback;
foreach (@feedback[0]->[0])
{
my $delete_token = $_->{token};
if ($delete_token != "")
{
deleteToken($delete_token);
foreach(@active_connections)
{
if ($_->{token} eq $delete_token)
{
printdbg ("FEEDBACK: marking $delete_token as INVALID_APNS with directAPNS= $usePushAPNSDirect");
$_->{pending} = INVALID_APNS;
Info ("Marking entry as invalid apns token: ". $delete_token."\n");
}
}
}
}
}
}
# This runs at each tick to purge connections
# that are inactive or have had an error
# This also closes any connection that has not provided
# credentials in the time configured after opening a socket
sub checkConnection
{
foreach (@active_connections)
{
my $curtime = time();
if ($_->{pending} == PENDING_WEBSOCKET)
{
# This takes care of purging connections that have not authenticated
if ($curtime - $_->{time} > WEBSOCKET_AUTH_DELAY)
{
# What happens if auth is not provided but device token is registered?
# It may still be a bogus token, so don't risk keeping connection stored
if (exists $_->{conn})
{
my $conn = $_->{conn};
Info ("Rejecting ".$conn->ip()." - authentication timeout");
printdbg ("Rejecting ".$conn->ip()." - authentication timeout marking as INVALID_AUTH");
$_->{pending} = INVALID_AUTH;
my $str = encode_json({event => 'auth', type=>'',status=>'Fail', reason => 'NOAUTH'});
eval {$_->{conn}->send_utf8($str);};
$_->{conn}->disconnect();
}
}
}
}
my $ac1 = scalar @active_connections;
printdbg ("Active connects before purge=$ac1");
@active_connections = grep { $_->{pending} != INVALID_AUTH } @active_connections;
$ac1 = scalar @active_connections;
printdbg ("Active connects after INVALID_AUTH purge=$ac1");
if ($usePushAPNSDirect || $usePushProxy)
{
#@active_connections = grep { $_->{'pending'} != INVALID_APNS || $_->{'token'} ne ''} @active_connections;
@active_connections = grep { $_->{'pending'} != INVALID_APNS} @active_connections;
$ac1 = scalar @active_connections;
printdbg ("Active connects after INVALID_APNS purge=$ac1");
}
}
# tokens can have : , so right split - this way I don't break existing token files
# http://stackoverflow.com/a/37870235/1361529
sub rsplit {
my $pattern = shift(@_); # Precompiled regex pattern (i.e. qr/pattern/)
my $expr = shift(@_); # String to split
my $limit = shift(@_); # Number of chunks to split into
map { scalar reverse($_) } reverse split(/$pattern/, scalar reverse($expr), $limit);
}
# This function is called whenever we receive a message from a client
sub checkMessage
{
my ($conn, $msg) = @_;
my $json_string;
eval {$json_string = decode_json($msg);};
if ($@)
{
Info ("Failed decoding json in checkMessage");
my $str = encode_json({event=> 'malformed', type=>'', status=>'Fail', reason=>'BADJSON'});
eval {$conn->send_utf8($str);};
return;
}
# This event type is when a command related to push notification is received
if (($json_string->{'event'} eq "push") && !$usePushAPNSDirect && !$usePushProxy)
{
my $str = encode_json({event=>'push', type=>'',status=>'Fail', reason => 'PUSHDISABLED'});
eval {$conn->send_utf8($str);};
return;
}
#-----------------------------------------------------------------------------------
# "push" event processing
#-----------------------------------------------------------------------------------
elsif (($json_string->{'event'} eq "push") && ($usePushAPNSDirect || $usePushProxy))
{
# sets the unread event count of events for a specific connection
# the server keeps a tab of # of events it pushes out per connection
# but won't know when the client has read them, so the client call tell the server
# using this message
if ($json_string->{'data'}->{'type'} eq "badge")
{
foreach (@active_connections)
{
if ((exists $_->{conn}) && ($_->{conn}->ip() eq $conn->ip()) &&
($_->{conn}->port() eq $conn->port()))
{
#print "Badge match, setting to 0\n";
$_->{badge} = $json_string->{'data'}->{'badge'};
}
}
return;
}
# This sub type is when a device token is registered
if ($json_string->{'data'}->{'type'} eq "token")
{
# a token must have a platform otherwise I don't know whether to use APNS or GCM
if (!$json_string->{'data'}->{'platform'})
{
my $str = encode_json({event=>'push', type=>'token',status=>'Fail', reason => 'MISSINGPLATFORM'});
eval {$conn->send_utf8($str);};
return;
}
foreach (@active_connections)
{
# this token already exists
if ($_->{token} eq $json_string->{'data'}->{'token'})
{
# if the token doesn't belong to the same connection
# then we have two connections owning the same token
# so we need to delete the old one. This can happen when you load
# the token from the persistent file and there is no connection
# and then the client is loaded
if ( (!exists $_->{conn}) || ($_->{conn}->ip() ne $conn->ip()
&& $_->{conn}->port() ne $conn->port()))
{
printdbg ("REGISTRATION: marking ".$_->{token}." as INVALID_APNS with directAPNS= $usePushAPNSDirect");
$_->{pending} = INVALID_APNS;
Info ("Duplicate token found, removing old data point");
}
else # token matches and connection matches, so it may be an update
{
$_->{token} = $json_string->{'data'}->{'token'};
$_->{platform} = $json_string->{'data'}->{'platform'};
if (exists($json_string->{'data'}->{'monlist'}))
{
$_->{monlist} = $json_string->{'data'}->{'monlist'};
}
else
{
$_->{monlist} = "-1";
}
if (exists($json_string->{'data'}->{'intlist'}))
{
$_->{intlist} = $json_string->{'data'}->{'intlist'};
}
else
{
$_->{intlist} = "-1";
}
$_->{pushstate} = $json_string->{'data'}->{'state'};
Info ("Storing token ...".substr($_->{token},-10).",monlist:".$_->{monlist}.",intlist:".$_->{intlist}.",pushstate:".$_->{pushstate}."\n");
my ($emonlist,$eintlist) = saveTokens($_->{token}, $_->{monlist}, $_->{intlist}, $_->{platform}, $_->{pushstate});
$_->{monlist} = $emonlist;
$_->{intlist} = $eintlist;
} # token and conn. matches
} # end of token matches
# The connection matches but the token does not
# this can happen if this is the first token registration after push notification registration
# response is received
elsif ( (exists $_->{conn}) && ($_->{conn}->ip() eq $conn->ip()) &&
($_->{conn}->port() eq $conn->port()))
{
$_->{token} = $json_string->{'data'}->{'token'};
$_->{platform} = $json_string->{'data'}->{'platform'};
$_->{monlist} = $json_string->{'data'}->{'monlist'};
$_->{intlist} = $json_string->{'data'}->{'intlist'};
if (exists($json_string->{'data'}->{'monlist'}))
{
$_->{monlist} = $json_string->{'data'}->{'monlist'};
}
else
{
$_->{monlist} = "-1";
}
if (exists($json_string->{'data'}->{'intlist'}))
{
$_->{intlist} = $json_string->{'data'}->{'intlist'};
}
else
{
$_->{intlist} = "-1";
}
$_->{pushstate} = $json_string->{'data'}->{'state'};
Info ("Storing token ...".substr($_->{token},-10).",monlist:".$_->{monlist}.",intlist:".$_->{intlist}.",pushstate:".$_->{pushstate}."\n");
my ($emonlist,$eintlist) = saveTokens($_->{token}, $_->{monlist}, $_->{intlist}, $_->{platform}, $_->{pushstate});
$_->{monlist} = $emonlist;
$_->{intlist} = $eintlist;
}
}
}
} # event = push
#-----------------------------------------------------------------------------------
# "control" event processing
#-----------------------------------------------------------------------------------
elsif (($json_string->{'event'} eq "control") )
{
if ($json_string->{'data'}->{'type'} eq "filter")
{
if (!$json_string->{'data'}->{'monlist'})
{
my $str = encode_json({event=>'control', type=>'filter',status=>'Fail', reason => 'MISSINGMONITORLIST'});
eval {$conn->send_utf8($str);};
return;
}
if (!$json_string->{'data'}->{'intlist'})
{
my $str = encode_json({event=>'control', type=>'filter',status=>'Fail', reason => 'MISSINGINTERVALLIST'});
eval {$conn->send_utf8($str);};
return;
}
my $monlist = $json_string->{'data'}->{'monlist'};
my $intlist = $json_string->{'data'}->{'intlist'};
#print ("CONTROL GOT: $monlist and $intlist\n");
foreach (@active_connections)
{
if ((exists $_->{conn}) && ($_->{conn}->ip() eq $conn->ip()) &&
($_->{conn}->port() eq $conn->port()))
{
$_->{monlist} = $monlist;
$_->{intlist} = $intlist;
Info ("Contrl: Storing token ...".substr($_->{token},-10).",monlist:".$_->{monlist}.",intlist:".$_->{intlist}.",pushstate:".$_->{pushstate}."\n");
saveTokens($_->{token}, $_->{monlist}, $_->{intlist}, $_->{platform}, $_->{pushstate});
}
}
}
if ($json_string->{'data'}->{'type'} eq "version")
{
foreach (@active_connections)
{
if ((exists $_->{conn}) && ($_->{conn}->ip() eq $conn->ip()) &&
($_->{conn}->port() eq $conn->port()))
{
my $str = encode_json({event=>'control',type=>'version', status=>'Success', reason => '', version => $app_version});
eval {$_->{conn}->send_utf8($str);};
}
}
}
} # event = control
#-----------------------------------------------------------------------------------
# "auth" event processing
#-----------------------------------------------------------------------------------
# This event type is when a command related to authorization is sent
elsif ($json_string->{'event'} eq "auth")
{
my $uname = $json_string->{'data'}->{'user'};
my $pwd = $json_string->{'data'}->{'password'};
return if ($uname eq "" || $pwd eq "");
foreach (@active_connections)
{
if ( (exists $_->{conn}) &&
($_->{conn}->ip() eq $conn->ip()) &&
($_->{conn}->port() eq $conn->port()) &&
($_->{pending}==PENDING_WEBSOCKET))
{
if (!validateZM($uname,$pwd))
{
# bad username or password, so reject and mark for deletion
my $str = encode_json({event=>'auth', type=>'', status=>'Fail', reason => 'BADAUTH'});
eval {$_->{conn}->send_utf8($str);};
Info("Bad authentication provided by ".$_->{conn}->ip());
printdbg("marking INVALID_AUTH Bad authentication provided by ".$_->{conn}->ip());
$_->{pending}=INVALID_AUTH;
}
else
{
# all good, connection auth was valid
$_->{pending}=VALID_WEBSOCKET;
$_->{token}='';
my $str = encode_json({event=>'auth', type=>'', status=>'Success', reason => '', version => $app_version});
eval {$_->{conn}->send_utf8($str);};
Info("Correct authentication provided by ".$_->{conn}->ip());
}
}
}
} # event = auth
else
{
my $str = encode_json({event=>$json_string->{'event'},type=>'', status=>'Fail', reason => 'NOTSUPPORTED'});
eval {$_->{conn}->send_utf8($str);};
}
}
# This loads APNS tokens stored in a conf file
# This ensures even if the daemon dies and
# restarts APNS tokens are maintained
# I also maintain monitor filter list
# so that APNS notifications will only be pushed
# for the monitors that are configured against
# that token
sub loadTokens
{
return if (!$usePushAPNSDirect && !$usePushProxy);
if ( ! -f PUSH_TOKEN_FILE)
{
open (my $foh, '>', PUSH_TOKEN_FILE);
Info ("Creating ".PUSH_TOKEN_FILE);
print $foh "";
close ($foh);
}
open (my $fh, '<', PUSH_TOKEN_FILE);
chomp( my @lines = <$fh>);
close ($fh);
printdbg ("Calling uniq from loadTokens");
my @uniquetokens = uniq(@lines);
open ($fh, '>', PUSH_TOKEN_FILE);
# This makes sure we rewrite the file with
# unique tokens
foreach(@uniquetokens)
{
next if ($_ eq "");
print $fh "$_\n";
my ($token, $monlist, $intlist, $platform, $pushstate) = rsplit(qr/:/, $_, 5); # split (":",$_);
#print "load: PUSHING $row\n";
push @active_connections, {
token => $token,
pending => VALID_WEBSOCKET,
time=>time(),
badge => 0,
monlist => $monlist,
intlist => $intlist,
last_sent=>{},
platform => $platform,
pushstate => $pushstate
};
}
close ($fh);
}
# This is called if the APNS feedback channel
# reports an invalid token. We also remove it from
# our token file