buspass_server.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. #!/usr/bin/perl -Tw
  2. #
  3. # Copyright (c) 2019 Clementine Computing LLC.
  4. #
  5. # This file is part of PopuFare.
  6. #
  7. # PopuFare is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # PopuFare is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with PopuFare. If not, see <https://www.gnu.org/licenses/>.
  19. #
  20. require 5.002;
  21. use strict;
  22. use Socket;
  23. use Switch;
  24. use Carp;
  25. use DBI;
  26. use FileHandle;
  27. use Fcntl;
  28. use Compress::Zlib;
  29. use POSIX;
  30. #my $database_path = 'DBI:mysql:busdb';
  31. my $database_path = 'DBI:SQLite:dbname=../bus.sqlite';
  32. my $database_user = '';
  33. my $database_pass = '';
  34. my $bind_ip = '127.0.0.1';
  35. my $bind_port = 7277;
  36. #----------------------------------------------Ugly exception handling logic using closures and anonymous functions----
  37. #-------------------------------------------This is in there to deal with the fact that CreditCall uses the die("error")
  38. #-------------------------------------------function instead of returning an error message in many cases...
  39. # This utility function returns the passed string sans any leading or trailing whitespace.
  40. #
  41. sub strip_whitespace
  42. {
  43. my $str = shift; #grab our first parameter
  44. $str =~ s/^\s+//; #strip leading whitespace
  45. $str =~ s/\s+$//; #strip trailing whitespace
  46. return $str; #return the improved string
  47. }
  48. # This function takes two coderef parameters, the second of which is usually an explicit call to the
  49. # 'catch' function which itself takes a coderef parameter. This allows the code employing this suite of
  50. # functions to look somewhat like a conventional exception handling mechanism:
  51. #
  52. # try
  53. # {
  54. # do_something_that_might_die();
  55. # }
  56. # catch
  57. # {
  58. # my $errmsg = $_;
  59. # log_the_error_message($errmsg);
  60. # perform_some_cleanup();
  61. # };
  62. #
  63. # DO NOT FORGET THAT LAST SEMICOLON, EVERYTHING GOES TO HELL IF YOU DO!
  64. #
  65. sub try(&$)
  66. {
  67. my ($attempt, $handler) = @_;
  68. eval
  69. {
  70. &$attempt;
  71. };
  72. if($@)
  73. {
  74. do_catch($handler);
  75. }
  76. }
  77. # This function strips off the whitespace from the exception message reported by die()
  78. # and places the result into the default variable such that the code in the catch block can
  79. # just examine $_ to figure out what the cause of the error is, or to display or log
  80. # the error message.
  81. #
  82. sub do_catch(&$)
  83. {
  84. my ($handler) = @_;
  85. local $_ = strip_whitespace($@);
  86. &$handler;
  87. }
  88. # This just takes an explicit coderef and returns it unharmed. The only
  89. # purpose of this is so the try/catch structure looks pretty and familiar.
  90. #
  91. sub catch(&) {$_[0]}
  92. #--------------------------------------------------------------------------------------------------------------------
  93. #my $DebugMode = 1;
  94. my $DebugMode = 0;
  95. # This function only executes the passed code reference if the global variable $DebugMode is non-zero.
  96. # The reason for this is that any calculation (like a FooBar::ComplexObject->toString call) will not be
  97. # performed if we are not in debug mode, sort of like a very limited form of lazy evaluation.
  98. #
  99. sub ifdebug(&@)
  100. {
  101. my ($cmd) = @_;
  102. &$cmd() if($DebugMode);
  103. }
  104. sub ServerReply
  105. {
  106. my $client_query = $_[0];
  107. chomp($client_query);
  108. my $response = "";
  109. my $hangup_flag=0;
  110. #Turning this on will use FLUSH instead of ZFLUSH, which is much slower
  111. my $do_legacy_flush = 0;
  112. switch ($client_query)
  113. {
  114. case /^QUERY\t[0-9][0-9]*$/
  115. {
  116. my $sequence_number = $client_query;
  117. $sequence_number =~ s/^QUERY\t//;
  118. my $dbh = DBI->connect($database_path, $database_user, $database_pass)
  119. or die "Couldn't connect to database: " . DBI->errstr;
  120. #A query to check for the validity of the queried sequence number
  121. my $seqcheck = $dbh->prepare('SELECT seq_num FROM active_rider_table WHERE seq_num = ?') or die "Couldn't prepare statement: " . $dbh->errstr;
  122. #Prepare to send records
  123. my $sth = $dbh->prepare('SELECT deleted, seq_num, logical_card_id, mag_token, rfid_token, rule_name, rule_param FROM active_rider_table a1 WHERE seq_num = ' .
  124. '(SELECT MAX(seq_num) FROM active_rider_table a2 WHERE a1.logical_card_id= a2.logical_card_id) AND seq_num > ? ORDER BY seq_num ASC')
  125. or die "Couldn't prepare statement: " . $dbh->errstr;
  126. $seqcheck->execute($sequence_number);
  127. #Check if the client is on the same page as us
  128. #if not, tell them to flush everything and send it all again
  129. my $flushdata = 0;
  130. if ($sequence_number == 0)
  131. {
  132. $flushdata = 1;
  133. $sth->execute($sequence_number) # Execute the query
  134. or die "Couldn't execute statement: " . $sth->errstr;
  135. }
  136. elsif (!$seqcheck->fetchrow_array())
  137. {
  138. $sth->execute(0) # Get everything
  139. or die "Couldn't execute statement: " . $sth->errstr;
  140. $flushdata = 1;
  141. }
  142. else
  143. {
  144. $sth->execute($sequence_number) # Execute the query
  145. or die "Couldn't execute statement: " . $sth->errstr;
  146. }
  147. # Read the matching records and print them out
  148. # $data[0] = deleted
  149. # $data[1] = seq_num
  150. # $data[2] = logical_card_id
  151. # $data[3] = mag_token
  152. # $data[4] = rfid_token
  153. # $data[5] = rule_name
  154. # $data[6] = rule_param
  155. my @data ;
  156. #If we are doing a flush
  157. if($flushdata)
  158. {
  159. if($do_legacy_flush)
  160. {
  161. $response .= "FLUSH\n" if $flushdata;
  162. while (@data = $sth->fetchrow_array())
  163. {
  164. if (!$data[0])
  165. {
  166. $data[3] = "" unless defined $data[3]; #populate any NULL mag_token with ""
  167. $data[4] = "" unless defined $data[4]; #populate any NULL rfid_token with ""
  168. $data[6] = "" unless defined $data[6]; #populate any NULL rule_param with ""
  169. $response .= "UPDATE\t$data[1]\t$data[2]\t$data[3]\t$data[4]\t$data[5]\t$data[6]\n";
  170. }
  171. }
  172. $response .= "FLUSHDONE\n" if $flushdata;
  173. }
  174. else
  175. {
  176. my $z = deflateInit( -Level => Z_BEST_COMPRESSION ) or die "Cannot create a deflation stream\n";
  177. my $size = 0;
  178. my $dat = "";
  179. my ($zout, $stat);
  180. my $cmpdat;
  181. while (@data = $sth->fetchrow_array())
  182. {
  183. if (!$data[0])
  184. {
  185. $data[3] = "" unless defined $data[3]; #populate any NULL mag_token with ""
  186. $data[4] = "" unless defined $data[4]; #populate any NULL rfid_token with ""
  187. $data[6] = "" unless defined $data[6]; #populate any NULL rule_param with ""
  188. $dat .= "UPDATE\t$data[1]\t$data[2]\t$data[3]\t$data[4]\t$data[5]\t$data[6]\n";
  189. }
  190. }
  191. ($zout, $stat) = $z->deflate($dat);
  192. $stat == Z_OK or die "deflation failed...";
  193. $cmpdat = $zout;
  194. ($zout, $stat) = $z->flush();
  195. $stat == Z_OK or die "deflation failed...";
  196. $cmpdat .= $zout;
  197. $size = $z->total_out();
  198. $response .= "ZFLUSH\t$size\n";
  199. $response .= $cmpdat;
  200. $response .= "ZFLUSHDONE\n";
  201. #Set the "HANG-UP" flag to make the server hang up on a client who has just done a ZFLUSH
  202. #so that the client will start a fresh server session with its shiny new database
  203. $hangup_flag = 1;
  204. }
  205. }
  206. else
  207. {
  208. while (@data = $sth->fetchrow_array())
  209. {
  210. if ($data[0])
  211. {
  212. $response .= "DELETE\t$data[1]\t$data[2]\n";
  213. } else
  214. {
  215. $data[3] = "" unless defined $data[3]; #populate any NULL mag_token with ""
  216. $data[4] = "" unless defined $data[4]; #populate any NULL rfid_token with ""
  217. $data[6] = "" unless defined $data[6]; #populate any NULL rule_param with ""
  218. $response .= "UPDATE\t$data[1]\t$data[2]\t$data[3]\t$data[4]\t$data[5]\t$data[6]\n";
  219. }
  220. }
  221. }
  222. $seqcheck->finish;
  223. $sth->finish;
  224. $dbh->disconnect;
  225. }
  226. else
  227. {
  228. $response = "ERROR\n" . $client_query;
  229. }
  230. }
  231. if($response eq "")
  232. {
  233. $response .= "NOP\n";
  234. }
  235. return ($response, $hangup_flag);
  236. }
  237. sub handle_client()
  238. {
  239. close SERVER;
  240. CLIENT->autoflush(1);
  241. my $linebuffer;
  242. while($linebuffer = <CLIENT>)
  243. {
  244. ## DEBUG
  245. print "## buspass: $linebuffer\n";
  246. my ($reply, $hangup_flag) = ServerReply($linebuffer);
  247. print CLIENT $reply;
  248. if($hangup_flag)
  249. {
  250. sleep(60);
  251. shutdown(CLIENT, 2);
  252. close CLIENT;
  253. return 0;
  254. }
  255. } #while data from client
  256. close CLIENT;
  257. }
  258. my $waitedpid = 0;
  259. my $sigreceived = 0;
  260. sub REAPER
  261. {
  262. while (($waitedpid = waitpid(-1, WNOHANG))>0) { }
  263. $SIG{CHLD} = \&REAPER; # loathe sysV
  264. $sigreceived = 1;
  265. }
  266. sub spawn
  267. {
  268. my $coderef = shift; #grab the first parameter
  269. unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') #verify that it consists of a non-null block of executable perl code
  270. {
  271. confess "usage: spawn CODEREF"; #complain if this is not the case
  272. }
  273. my $pid;
  274. if (!defined($pid = fork)) #attempt a fork, remembering the returned PID value
  275. {
  276. close CLIENT;
  277. return; #failed to fork, we'd better close the client
  278. }
  279. elsif ($pid) #If the returned process ID is non-zero, that indicates that we are the parent process
  280. {
  281. return; # i'm the parent
  282. }
  283. else #otherwise, if the returned process ID is 0, that means we're the child process
  284. {
  285. exit &$coderef(); #in which case, we want to execute the child handler that was passed in, and then
  286. #exit this (child) process when we've finished our conversation(s) with the
  287. #other (client) end of the socket.
  288. }
  289. }
  290. #----------------------------------------------------------------------
  291. # Local network settings for Inter-Process communication.
  292. #----------------------------------------------------------------------
  293. my $proto = getprotobyname('tcp');
  294. my $addr = sockaddr_in( $bind_port ,inet_aton($bind_ip));;
  295. #----------------------------------------------------------------------
  296. my $max_retries = 10; #Maximum number of address-binding retries before we give up.
  297. my $retry_count = $max_retries; #number of retries left...
  298. my $retry_delay = 3; #number of seconds to wait between retries at binding to our designated IPC address
  299. my $got_network = 0; #flag to let us know that we can quit retrying once we have gotten a valid listening socket
  300. while( ($retry_count > 0) && (!$got_network) )
  301. {
  302. try #Try and allocate a socket, bind it to our IPC address, and set it to listen for connections
  303. {
  304. socket(SERVER,PF_INET,SOCK_STREAM,$proto) || die "socket: $!";
  305. setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1);
  306. bind (SERVER, $addr) || die "bind: $!";
  307. listen(SERVER,5) || die "listen: $!";
  308. $got_network = 1;
  309. }
  310. catch #If that didn't work for some reason, log the error, clean up, and prepair to retry
  311. {
  312. my $errmsg = $_; #Remember the error message
  313. close(SERVER); #Clean up the server socket if it needs it
  314. #Decrement our remaining retry counter
  315. $retry_count = $retry_count - 1;
  316. #Log the message to our debug log
  317. print "Failed to allocate socket, will retry $retry_count times: $errmsg\n";
  318. #Wait a reasonable period before trying again
  319. sleep $retry_delay;
  320. };
  321. }
  322. if($got_network) #If we met with success binding to the network, report it
  323. {
  324. my $logmsg = "Socket setup successful. Listening for clients at $bind_ip:$bind_port\n";
  325. print $logmsg;
  326. }
  327. else #If we ran out of patience and gave up, report that as well and exit
  328. {
  329. my $errmsg = "Could not allocate and bind listening socket at $bind_ip:$bind_port after $max_retries attempts.\n";
  330. die $errmsg;
  331. }
  332. # Set up our signal handler which will clean up defunct child processes and let the main
  333. # accept() loop know that the reason accept returned was due to a signal, not a legit connection.
  334. $SIG{CHLD} = \&REAPER;
  335. #This for loop is efficient, but confusting, so I'll break it down by clause
  336. #
  337. # The first clause ($sigreceived = 0) clears the signal received flag that will be set if the
  338. # accept() call was interrupted by a signal. This clause runs once before the first run of the loop
  339. #
  340. # The second clause is the test clause, it will process the contents of the loop if EITHER
  341. # accept() has returned (presumably generating a valid file handle for the CLIENT end of the
  342. # socket, OR the signal received flag is set (thus accept would have returned early without
  343. # having actually accepted a connection.
  344. #
  345. # The third clause (the 'incrementer') is run after each time the body is executed, before the
  346. # test clause is executed again (deciding whether to run the body or drop out... This test
  347. # clause will close the parent process' copy of the CLIENT file handle since (see body below)
  348. # after the body executes, all communication with the socket referred to by that file handle
  349. # will be carried out by the spawned child process. This frees the parent's copy of the CLIENT
  350. # file handle to be used again in the parent process for the next accepted incoming connection.
  351. for ( $sigreceived = 0; accept(CLIENT,SERVER) || $sigreceived; $sigreceived = 0, close CLIENT)
  352. {
  353. next if $sigreceived; #If we were interrupted by a signal, there is no real client, just go back and try to accept a new one
  354. print "connection received.\n"; #Print a diagnostic message confirming that we have made a connection
  355. spawn sub {handle_client();}; #fork() off a child process that will handle communication with the socket pointed to by the CLIENT file handle
  356. }