instructions for suid install
[Biblio-RFID.git] / scripts / RFID-JSONP-server.pl
1 #!/usr/bin/perl
2
3 =head1 NAME
4
5 RFID-JSONP-server - simpliest possible JSONP server which provides local web interface to RFID readers
6
7 =head1 USAGE
8
9   ./scripts/RFID-JSONP-server.pl [--debug] [--listen=127.0.0.1:9000] [--reader=filter]
10
11 =cut
12
13 use strict;
14 use warnings;
15
16 use Data::Dump qw/dump/;
17
18 use JSON::XS;
19 use IO::Socket::INET;
20 use LWP::UserAgent;
21 use URI;
22
23 my $debug = 1;
24 my $listen = '127.0.0.1:9000';
25 $listen = ':9000';
26 my $reader;
27 my $koha_url = 'http://ffzg.koha-dev.rot13.org:8080';
28 # internal URL so we can find local address of machine and vmware NAT
29 my $rfid_url = 'http://rfid.koha-dev.vbz.ffzg.hr';
30
31 use Getopt::Long;
32
33 GetOptions(
34         'debug!'    => \$debug,
35         'listen=s', => \$listen,
36         'reader=s', => \$reader,
37         'koha=s',       => \$koha_url,
38 ) || die $!;
39
40 our $rfid_sid_cache;
41
42 sub rfid_borrower {
43         my $hash = shift;
44         if ( my $json = $rfid_sid_cache->{ $hash->{sid} } ) {
45                 return $json;
46         }
47         my $ua = LWP::UserAgent->new;
48         my $url = URI->new( $koha_url . '/cgi-bin/koha/ffzg/rfid/borrower.pl');
49         $url->query_form(
50                   RFID_SID => $hash->{sid}
51                 , OIB => $hash->{OIB}
52                 , JMBAG => $hash->{JMBAG}
53         );
54         warn "GET ",$url->as_string;
55         my $response = $ua->get($url);
56         if ( $response->is_success ) {
57                 my $json = decode_json $response->decoded_content;
58                 $rfid_sid_cache->{ $hash->{sid} } = $json;
59                 return $json;
60         } else {
61                 warn "ERROR ", $response->status_line;
62         }
63 }
64
65 use lib 'lib';
66 use Biblio::RFID::RFID501;
67 use Biblio::RFID::Reader;
68 my $rfid = Biblio::RFID::Reader->new( shift @ARGV );
69 $rfid->debug( $debug );
70
71 my $index_html;
72 {
73         local $/ = undef;
74         $index_html = <DATA>;
75         $index_html =~ s{http://koha.example.com:8080}{$koha_url}sg;
76 }
77
78 my $server_url;
79
80 sub http_server {
81
82         my $server = IO::Socket::INET->new(
83                 Proto     => 'tcp',
84                 LocalAddr => $listen,
85                 Listen    => SOMAXCONN,
86                 Reuse     => 1
87         );
88                                                                   
89         die "can't setup server: $!" unless $server;
90
91         $server_url = 'http://' . $listen;
92         print "Server $0 ready at $server_url\n";
93
94         while (my $client = $server->accept()) {
95                 $client->autoflush(1);
96                 my $request = <$client>;
97
98                 warn "WEB << $request\n" if $debug;
99                 my $path;
100
101                 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
102                         my $method = $1;
103                         my $param;
104                         if ( $method =~ s{\?(.+)}{} ) {
105                                 foreach my $p ( split(/[&;]/, $1) ) {
106                                         my ($n,$v) = split(/=/, $p, 2);
107                                         $param->{$n} = $v;
108                                 }
109                                 warn "WEB << param: ",dump( $param ) if $debug;
110                         }
111                         $path = $method;
112
113                         if ( $path eq '/' ) {
114                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n$index_html";
115                         } elsif ( $path =~ m{^/(examples/.+)} ) {
116                                 $path = $1; # FIXME prefix with dir for installation
117                                 my $size = -s $path;
118                                 warn "static $path $size bytes\n";
119                                 my $content_type = 'text/plain';
120                                 $content_type = 'application/javascript' if $path =~ /\.js/;
121                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: $content_type\r\nContent-Length: $size\r\n\r\n";
122                                 {
123                                         local $/ = undef;
124                                         open(my $fh, '<', $path) || die "can't open $path: $!";
125                                         while(<$fh>) {
126                                                 print $client $_;
127                                         }
128                                         close($fh);
129                                 }
130                         } elsif ( $method =~ m{/scan} ) {
131                                 my @tags = $rfid->tags;
132                                 my $json = { time => time() };
133                                 foreach my $tag ( @tags ) {
134                                         my $hash = $rfid->to_hash( $tag );
135                                         $hash->{sid}  = $tag;
136                                         if ( $hash->{tag_type} eq 'SmartX' ) {
137                                                 my $borrower = rfid_borrower $hash;
138                                                 if ( exists $borrower->{error} ) {
139                                                         warn "ERROR ", dump($borrower);
140                                                 } else {
141                                                         $hash->{borrower} = $borrower->{borrower};
142                                                 }
143                                         } else {
144                                                 $hash->{security} = uc unpack 'H*', $rfid->afi( $tag );
145                                         }
146                                         push @{ $json->{tags} }, $hash;
147                                 };
148                                 warn "#### ", encode_json($json);
149                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
150                                         $param->{callback}, "(", encode_json($json), ")\r\n";
151                         } elsif ( $method =~ m{/program} ) {
152
153                                 my $status = 501; # Not implementd
154
155                                 foreach my $p ( keys %$param ) {
156                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
157                                         my $tag = $1;
158                                         my $content = Biblio::RFID::RFID501->from_hash({ content => $param->{$p} });
159                                         $content    = Biblio::RFID::RFID501->blank if $param->{$p} eq 'blank';
160                                         $status = 302;
161
162                                         warn "PROGRAM $tag $content\n";
163                                         $rfid->write_blocks( $tag => $content );
164                                         $rfid->write_afi(    $tag => chr( $param->{$p} =~ /^130/ ? 0xDA : 0xD7 ) );
165                                 }
166
167                                 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
168
169                         } elsif ( $method =~ m{/secure(.js)} ) {
170
171                                 my $json = $1;
172
173                                 my $status = 501; # Not implementd
174
175                                 foreach my $p ( keys %$param ) {
176                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
177                                         my $tag = $1;
178                                         my $data = $param->{$p};
179                                         $status = 302;
180
181                                         warn "SECURE $tag $data\n";
182                                         $rfid->write_afi( $tag => hex($data) );
183                                 }
184
185                                 if ( $json ) {
186                                         print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
187                                                 $param->{callback}, "({ ok: 1 })\r\n";
188                                 } else {
189                                         print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
190                                 }
191
192                         } else {
193                                 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
194                         }
195                 } else {
196                         print $client "HTTP/1.0 500 No method\r\n\r\n";
197                 }
198                 close $client;
199         }
200
201         die "server died";
202 }
203
204 sub rfid_register {
205         my $ip;
206
207         foreach ( split(/\n/, `ip addr` ) ) {
208                 if ( /^\d:\s(\w+):\s/ ) {
209                         $ip->{last} = $1;
210                 } elsif ( /^\s+inet\s((\d+)\.(\d+)\.(\d+)\.(\d+))\/(\d+)/ ) {
211                         $ip->{ $ip->{last} } = $1;
212                 } else {
213                         warn "# SKIP [$_]\n";
214                 }
215
216         }
217
218         my $ua = LWP::UserAgent->new;
219         my $url = URI->new( $rfid_url . '/register.pl');
220         $url->query_form(
221                 local_ip => $ip->{eth0},
222         );
223         warn "GET ",$url->as_string;
224         my $response = $ua->get($url);
225         if ( $response->is_success ) {
226                 warn "# ", $response->decoded_content;
227                 my $json = decode_json $response->decoded_content;
228                 warn "REGISTER: ",dump($json);
229                 return $json;
230         } else {
231                 warn "ERROR ", $response->status_line;
232         }
233 }
234
235 rfid_register;
236 http_server;
237
238 __DATA__
239 <html>
240 <head>
241 <title>RFID JSONP</title>
242 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
243 <style type="text/css">
244 .status {
245         background: #ff8;
246 }
247
248 .da {
249         background: #fcc;
250 }
251
252 .d7 {
253         background: #cfc;
254 }
255
256 label[for=pull-reader] {
257         position: absolute;
258         top: 1em;
259         right: 1em;
260         background: #eee;
261 }
262
263 </style>
264 <script type="text/javascript">
265
266 // mock console
267 if(!window.console) {
268         window.console = new function() {
269                 this.info = function(str) {};
270                 this.debug = function(str) {};
271         };
272 }
273
274
275 function got_visible_tags(data,textStatus) {
276         var html = 'No tags in range';
277         if ( data.tags ) {
278                 html = '<ul class="tags">';
279                 $.each(data.tags, function(i,tag) {
280                         console.debug( i, tag );
281                         html += '<li><tt class="' + tag.security + '">' + tag.sid;
282                         var content = tag.content || tag.borrower.cardnumber;
283
284                         if ( content ) {
285                                 html += ' <a href="http://koha.example.com:8080/cgi-bin/koha/';
286                                 if ( tag.type == 1 ) { // book
287                                         html += 'catalogue/search.pl?q=';
288                                 } else {
289                                         html += 'members/member.pl?member=';
290                                 }
291                                 html += content + '" title="lookup in Koha" target="koha-lookup">' + content + '</a>';
292                                 html += '</tt>';
293 /*
294                                 html += '<form method=get action=program style="display:inline">'
295                                         + '<input type=hidden name='+tag.sid+' value="blank">'
296                                         + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
297                                         + '</form>'
298                                 ;
299 */
300                         } else {
301                                 html += '</tt>';
302                                 html += ' <form method=get action=program style="display:inline">'
303                                         + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
304                                         + '<input type=text name='+tag.sid+' size=12>'
305                                         + '<input type=submit value="Program">'
306                                         + '</form>'
307                                 ;
308                         }
309                 });
310                 html += '</ul>';
311         }
312
313         var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
314
315         html = '<div class=status>'
316                 + textStatus
317                 + ' &#' + arrows[ data.time % arrows.length ] + ';'
318                 + '</div>'
319                 + html
320                 ;
321         $('#tags').html( html );
322         window.setTimeout(function(){
323                 scan_tags();
324         },200); // re-scan every 200ms
325 };
326
327 function scan_tags() {
328         console.info('scan_tags');
329         if ( $('input#pull-reader').attr('checked') )
330                 $.getJSON("/scan?callback=?", got_visible_tags);
331 }
332
333 $(document).ready(function() {
334                 $('input#pull-reader').click( function() {
335                         scan_tags();
336                 });
337                 $('input#pull-reader').attr('checked', true); // force check on load
338
339                 $('div#tags').click( function() {
340                         $('input#pull-reader').attr('checked', false);
341                 } );
342
343                 scan_tags();
344 });
345 </script>
346 </head>
347 <body>
348
349 <h1>RFID tags in range</h1>
350
351 <label for=pull-reader>
352 <input id=pull-reader type=checkbox checked=1>
353 active
354 </label>
355
356 <div id="tags">
357 RFID reader not found or driver program not started.
358 </div>
359
360 </body>
361 </html>