ridelogic_buspassd 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 Getopt::Long qw(:config no_ignore_case);
  30. use POSIX;
  31. use RideLogic;
  32. my $database_path = 'DBI:mysql:busdb';
  33. my $database_user = '';
  34. my $database_pass = '';
  35. my $bind_ip = '127.0.0.1';
  36. my $bind_port = 7277;
  37. my $DebugMode = 0;
  38. # This function only executes the passed code reference if the global variable $DebugMode is non-zero.
  39. # The reason for this is that any calculation (like a FooBar::ComplexObject->toString call) will not be
  40. # performed if we are not in debug mode, sort of like a very limited form of lazy evaluation.
  41. #
  42. sub ifdebug(&@)
  43. {
  44. my ($cmd) = @_;
  45. &$cmd() if($DebugMode);
  46. }
  47. sub ServerReply
  48. {
  49. my $client_query = $_[0];
  50. chomp($client_query);
  51. my $response = "";
  52. my $hangup_flag=0;
  53. #Turning this on will use FLUSH instead of ZFLUSH, which is much slower
  54. my $do_legacy_flush = 0;
  55. switch ($client_query)
  56. {
  57. case /^QUERY\t[0-9][0-9]*$/
  58. {
  59. my $sequence_number = $client_query;
  60. $sequence_number =~ s/^QUERY\t//;
  61. my $dbh = DBI->connect($database_path, $database_user, $database_pass)
  62. or die "Couldn't connect to database: " . DBI->errstr;
  63. #A query to check for the validity of the queried sequence number
  64. my $seqcheck = $dbh->prepare('SELECT seq_num FROM active_rider_table WHERE seq_num = ?') or die "Couldn't prepare statement: " . $dbh->errstr;
  65. #Prepare to send records
  66. 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 = ' .
  67. '(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')
  68. or die "Couldn't prepare statement: " . $dbh->errstr;
  69. $seqcheck->execute($sequence_number);
  70. #Check if the client is on the same page as us
  71. #if not, tell them to flush everything and send it all again
  72. my $flushdata = 0;
  73. if ($sequence_number == 0)
  74. {
  75. $flushdata = 1;
  76. $sth->execute($sequence_number) # Execute the query
  77. or die "Couldn't execute statement: " . $sth->errstr;
  78. }
  79. elsif (!$seqcheck->fetchrow_array())
  80. {
  81. $sth->execute(0) # Get everything
  82. or die "Couldn't execute statement: " . $sth->errstr;
  83. $flushdata = 1;
  84. }
  85. else
  86. {
  87. $sth->execute($sequence_number) # Execute the query
  88. or die "Couldn't execute statement: " . $sth->errstr;
  89. }
  90. # Read the matching records and print them out
  91. # $data[0] = deleted
  92. # $data[1] = seq_num
  93. # $data[2] = logical_card_id
  94. # $data[3] = mag_token
  95. # $data[4] = rfid_token
  96. # $data[5] = rule_name
  97. # $data[6] = rule_param
  98. my @data ;
  99. #If we are doing a flush
  100. if($flushdata)
  101. {
  102. if($do_legacy_flush)
  103. {
  104. $response .= "FLUSH\n" if $flushdata;
  105. while (@data = $sth->fetchrow_array())
  106. {
  107. if (!$data[0])
  108. {
  109. $data[3] = "" unless defined $data[3]; #populate any NULL mag_token with ""
  110. $data[4] = "" unless defined $data[4]; #populate any NULL rfid_token with ""
  111. $data[6] = "" unless defined $data[6]; #populate any NULL rule_param with ""
  112. $response .= "UPDATE\t$data[1]\t$data[2]\t$data[3]\t$data[4]\t$data[5]\t$data[6]\n";
  113. }
  114. }
  115. $response .= "FLUSHDONE\n" if $flushdata;
  116. }
  117. else
  118. {
  119. my $z = deflateInit( -Level => Z_BEST_COMPRESSION ) or die "Cannot create a deflation stream\n";
  120. my $size = 0;
  121. my $dat = "";
  122. my ($zout, $stat);
  123. my $cmpdat;
  124. while (@data = $sth->fetchrow_array())
  125. {
  126. if (!$data[0])
  127. {
  128. $data[3] = "" unless defined $data[3]; #populate any NULL mag_token with ""
  129. $data[4] = "" unless defined $data[4]; #populate any NULL rfid_token with ""
  130. $data[6] = "" unless defined $data[6]; #populate any NULL rule_param with ""
  131. $dat .= "UPDATE\t$data[1]\t$data[2]\t$data[3]\t$data[4]\t$data[5]\t$data[6]\n";
  132. }
  133. }
  134. ($zout, $stat) = $z->deflate($dat);
  135. $stat == Z_OK or die "deflation failed...";
  136. $cmpdat = $zout;
  137. ($zout, $stat) = $z->flush();
  138. $stat == Z_OK or die "deflation failed...";
  139. $cmpdat .= $zout;
  140. $size = $z->total_out();
  141. $response .= "ZFLUSH\t$size\n";
  142. $response .= $cmpdat;
  143. $response .= "ZFLUSHDONE\n";
  144. #Set the "HANG-UP" flag to make the server hang up on a client who has just done a ZFLUSH
  145. #so that the client will start a fresh server session with its shiny new database
  146. $hangup_flag = 1;
  147. }
  148. }
  149. else
  150. {
  151. while (@data = $sth->fetchrow_array())
  152. {
  153. if ($data[0])
  154. {
  155. $response .= "DELETE\t$data[1]\t$data[2]\n";
  156. } else
  157. {
  158. $data[3] = "" unless defined $data[3]; #populate any NULL mag_token with ""
  159. $data[4] = "" unless defined $data[4]; #populate any NULL rfid_token with ""
  160. $data[6] = "" unless defined $data[6]; #populate any NULL rule_param with ""
  161. $response .= "UPDATE\t$data[1]\t$data[2]\t$data[3]\t$data[4]\t$data[5]\t$data[6]\n";
  162. }
  163. }
  164. }
  165. $seqcheck->finish;
  166. $sth->finish;
  167. $dbh->disconnect;
  168. }
  169. else
  170. {
  171. $response = "ERROR\n" . $client_query;
  172. }
  173. }
  174. if($response eq "")
  175. {
  176. $response .= "NOP\n";
  177. }
  178. return ($response, $hangup_flag);
  179. }
  180. sub handle_client()
  181. {
  182. close SERVER;
  183. CLIENT->autoflush(1);
  184. my $linebuffer;
  185. while($linebuffer = <CLIENT>)
  186. {
  187. my ($reply, $hangup_flag) = ServerReply($linebuffer);
  188. print CLIENT $reply;
  189. if($hangup_flag)
  190. {
  191. sleep(60);
  192. shutdown(CLIENT, 2);
  193. close CLIENT;
  194. return 0;
  195. }
  196. } #while data from client
  197. close CLIENT;
  198. }
  199. my $waitedpid = 0;
  200. my $sigreceived = 0;
  201. sub REAPER
  202. {
  203. while (($waitedpid = waitpid(-1, WNOHANG))>0) { }
  204. $SIG{CHLD} = \&REAPER; # loathe sysV
  205. $sigreceived = 1;
  206. }
  207. sub spawn
  208. {
  209. my $coderef = shift; #grab the first parameter
  210. unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') #verify that it consists of a non-null block of executable perl code
  211. {
  212. confess "usage: spawn CODEREF"; #complain if this is not the case
  213. }
  214. my $pid;
  215. if (!defined($pid = fork)) #attempt a fork, remembering the returned PID value
  216. {
  217. close CLIENT;
  218. return; #failed to fork, we'd better close the client
  219. }
  220. elsif ($pid) #If the returned process ID is non-zero, that indicates that we are the parent process
  221. {
  222. return; # i'm the parent
  223. }
  224. else #otherwise, if the returned process ID is 0, that means we're the child process
  225. {
  226. exit &$coderef(); #in which case, we want to execute the child handler that was passed in, and then
  227. #exit this (child) process when we've finished our conversation(s) with the
  228. #other (client) end of the socket.
  229. }
  230. }
  231. sub show_help_and_exit {
  232. print "usage:\n";
  233. print " [-i] interactive, do not daemonize\n";
  234. print " [-c cfg] use cfg as config file (default to " . $RideLogic::RIDELOGIC_DAEMON_CONF . ") \n";
  235. print " [-h] show help (this screen)\n";
  236. exit;
  237. }
  238. #----------------------------------------------------------------------
  239. #
  240. #----------------------------------------------------------------------
  241. my $daemonize = 1;
  242. my $interactive = 0;
  243. my $show_help = 0;
  244. my $cfg_file = $RideLogic::RIDELOGIC_DAEMON_CONF;
  245. GetOptions(
  246. 'i|interactive' => \$interactive,
  247. 'c|config=s' => \$cfg_file,
  248. 'h|help' => \$show_help );
  249. show_help_and_exit() if ($show_help);
  250. $daemonize=0 if ($interactive);
  251. #----------------------------------------------------------------------
  252. # Local network settings for Inter-Process communication.
  253. #----------------------------------------------------------------------
  254. my $proto = getprotobyname('tcp');
  255. my $addr = sockaddr_in( $bind_port ,inet_aton($bind_ip));;
  256. #----------------------------------------------------------------------
  257. my $max_retries = 10; #Maximum number of address-binding retries before we give up.
  258. my $retry_count = $max_retries; #number of retries left...
  259. my $retry_delay = 3; #number of seconds to wait between retries at binding to our designated IPC address
  260. my $got_network = 0; #flag to let us know that we can quit retrying once we have gotten a valid listening socket
  261. my %CFG_VAR;
  262. read_config($cfg_file, \%CFG_VAR) if ($cfg_file);
  263. my $logfile = ($CFG_VAR{"RIDELOGIC_DAEMON_LOG_DIR"} || $RideLogic::RIDELOGIC_DAEMON_LOG_DIR) . "/ridelogic_buspassd.log";
  264. my $pidfile = ($CFG_VAR{"RIDELOGIC_DAEMON_PID_DIR"} || $RideLogic::RIDELOGIC_DAEMON_PID_DIR) . "/ridelogic_buspassd.pid";
  265. daemonize($logfile, $pidfile) if ($daemonize);
  266. # set our pipes to be piping hot
  267. $|=1;
  268. while( ($retry_count > 0) && (!$got_network) )
  269. {
  270. try #Try and allocate a socket, bind it to our IPC address, and set it to listen for connections
  271. {
  272. socket(SERVER,PF_INET,SOCK_STREAM,$proto) || die "socket: $!";
  273. setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1);
  274. bind (SERVER, $addr) || die "bind: $!";
  275. listen(SERVER,5) || die "listen: $!";
  276. $got_network = 1;
  277. }
  278. catch #If that didn't work for some reason, log the error, clean up, and prepair to retry
  279. {
  280. my $errmsg = $_; #Remember the error message
  281. close(SERVER); #Clean up the server socket if it needs it
  282. #Decrement our remaining retry counter
  283. $retry_count = $retry_count - 1;
  284. #Log the message to our debug log
  285. print "Failed to allocate socket, will retry $retry_count times: $errmsg\n";
  286. #Wait a reasonable period before trying again
  287. sleep $retry_delay;
  288. };
  289. }
  290. if($got_network) #If we met with success binding to the network, report it
  291. {
  292. my $logmsg = "Socket setup successful. Listening for clients at $bind_ip:$bind_port\n";
  293. print $logmsg;
  294. }
  295. else #If we ran out of patience and gave up, report that as well and exit
  296. {
  297. my $errmsg = "Could not allocate and bind listening socket at $bind_ip:$bind_port after $max_retries attempts.\n";
  298. die $errmsg;
  299. }
  300. # Set up our signal handler which will clean up defunct child processes and let the main
  301. # accept() loop know that the reason accept returned was due to a signal, not a legit connection.
  302. $SIG{CHLD} = \&REAPER;
  303. #This for loop is efficient, but confusting, so I'll break it down by clause
  304. #
  305. # The first clause ($sigreceived = 0) clears the signal received flag that will be set if the
  306. # accept() call was interrupted by a signal. This clause runs once before the first run of the loop
  307. #
  308. # The second clause is the test clause, it will process the contents of the loop if EITHER
  309. # accept() has returned (presumably generating a valid file handle for the CLIENT end of the
  310. # socket, OR the signal received flag is set (thus accept would have returned early without
  311. # having actually accepted a connection.
  312. #
  313. # The third clause (the 'incrementer') is run after each time the body is executed, before the
  314. # test clause is executed again (deciding whether to run the body or drop out... This test
  315. # clause will close the parent process' copy of the CLIENT file handle since (see body below)
  316. # after the body executes, all communication with the socket referred to by that file handle
  317. # will be carried out by the spawned child process. This frees the parent's copy of the CLIENT
  318. # file handle to be used again in the parent process for the next accepted incoming connection.
  319. for ( $sigreceived = 0; accept(CLIENT,SERVER) || $sigreceived; $sigreceived = 0, close CLIENT)
  320. {
  321. 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
  322. print "connection received.\n"; #Print a diagnostic message confirming that we have made a connection
  323. spawn sub {handle_client();}; #fork() off a child process that will handle communication with the socket pointed to by the CLIENT file handle
  324. }