billing_server.pl 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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 Date::Calc qw(:all);
  27. use FileHandle;
  28. use Fcntl;
  29. use Digest::MD5 qw(md5 md5_hex md5_base64);
  30. use POSIX;
  31. use Data::Dumper;
  32. #use OrgDB;
  33. my $ORG = "ORG";
  34. #my $database_path = 'DBI:mysql:busdb';
  35. my $database_path = 'DBI:SQLite:dbname=../bus.sqlite';
  36. my $database_user = '';
  37. my $database_pass = '';
  38. my $bind_ip = '127.0.0.1';
  39. my $bind_port = 2455;
  40. #my $logfile = '/home/bus/log/billing_log.log';
  41. my $logfile = './billing_log.log';
  42. sub unix_to_readable_time {
  43. my $unix_time = shift;
  44. my @a = localtime($unix_time);
  45. return sprintf('%d-%02d-%02d %02d:%02d:%02d', (1900+$a[5]), (1+$a[4]), $a[3], $a[2], $a[1], $a[0]);
  46. }
  47. #----------------------------------------------Ugly exception handling logic using closures and anonymous functions----
  48. #-------------------------------------------This is in there to deal with the fact that CreditCall uses the die("error")
  49. #-------------------------------------------function instead of returning an error message in many cases...
  50. # This utility function returns the passed string sans any leading or trailing whitespace.
  51. #
  52. sub strip_whitespace
  53. {
  54. my $str = shift; #grab our first parameter
  55. $str =~ s/^\s+//; #strip leading whitespace
  56. $str =~ s/\s+$//; #strip trailing whitespace
  57. return $str; #return the improved string
  58. }
  59. # This function takes two coderef parameters, the second of which is usually an explicit call to the
  60. # 'catch' function which itself takes a coderef parameter. This allows the code employing this suite of
  61. # functions to look somewhat like a conventional exception handling mechanism:
  62. #
  63. # try
  64. # {
  65. # do_something_that_might_die();
  66. # }
  67. # catch
  68. # {
  69. # my $errmsg = $_;
  70. # log_the_error_message($errmsg);
  71. # perform_some_cleanup();
  72. # };
  73. #
  74. # DO NOT FORGET THAT LAST SEMICOLON, EVERYTHING GOES TO HELL IF YOU DO!
  75. #
  76. sub try(&$)
  77. {
  78. my ($attempt, $handler) = @_;
  79. eval
  80. {
  81. &$attempt;
  82. };
  83. if($@)
  84. {
  85. do_catch($handler);
  86. }
  87. }
  88. # This function strips off the whitespace from the exception message reported by die()
  89. # and places the result into the default variable such that the code in the catch block can
  90. # just examine $_ to figure out what the cause of the error is, or to display or log
  91. # the error message.
  92. #
  93. sub do_catch(&$)
  94. {
  95. my ($handler) = @_;
  96. local $_ = strip_whitespace($@);
  97. &$handler;
  98. }
  99. # This just takes an explicit coderef and returns it unharmed. The only
  100. # purpose of this is so the try/catch structure looks pretty and familiar.
  101. #
  102. sub catch(&) {$_[0]}
  103. #--------------------------------------------------------------------------------------------------------------------
  104. #my $DebugMode = 1;
  105. my $DebugMode = 0;
  106. # This function only executes the passed code reference if the global variable $DebugMode is non-zero.
  107. # The reason for this is that any calculation (like a FooBar::ComplexObject->toString call) will not be
  108. # performed if we are not in debug mode, sort of like a very limited form of lazy evaluation.
  109. #
  110. sub ifdebug(&@)
  111. {
  112. my ($cmd) = @_;
  113. &$cmd() if($DebugMode);
  114. }
  115. sub ExpirePass {
  116. my $dbh = shift;
  117. my $cardid = shift;
  118. my $dummy_passid = shift;
  119. my $ride_time = shift;
  120. my @oldrow = @_;
  121. local $dbh->{RaiseError};
  122. local $dbh->{PrintError};
  123. $dbh->{RaiseError} = 1;
  124. $dbh->{PrintError} = 1;
  125. $dbh->begin_work;
  126. # get passes to expire for a cardid
  127. my $query = $dbh->prepare("select p.user_pass_id, p.queue_order, p.rule, p.nrides_remain, p.nday_expiration, rc.ruleclass
  128. from user_pass p, rule_class rc
  129. where p.logical_card_id = ? and p.active = 1 and p.expired = 0 and
  130. ( ( rc.ruleclass = 'NDAY' and p.nday_expiration < now() ) or
  131. ( rc.ruleclass = 'NRIDE' and p.nrides_remain <= 0 ) or
  132. ( rc.rulename = 'PREACTIVE' ) ) ");
  133. $query->execute($cardid);
  134. if ($query->rows == 0) { $dbh->commit; return; }
  135. my $href = $query->fetchrow_hashref;
  136. my $passid = $href->{'user_pass_id'};
  137. my $current_q_num = $href->{'queue_order'};
  138. # expire old pass
  139. my $audit_pass_id = audit_user_pass_start($dbh, $passid, "billing_server: ExpirePass: deactivating and expiring pass");
  140. $query = $dbh->prepare("update user_pass set active = 0, expired = 1, deactivated = now() where user_pass_id = ?");
  141. $query->execute($passid);
  142. audit_user_pass_end($dbh, $passid, $audit_pass_id);
  143. # activate new pass
  144. $query = $dbh->prepare("select p.user_pass_id, p.rule, p.nday_orig, p.nday_expiration, p.nrides_orig, p.queue_order, rc.ruleclass
  145. from user_pass p, rule_class rc
  146. where p.logical_card_id = ?
  147. and p.expired = 0 and p.rule = rc.rulename
  148. and p.queue_order = ( select min(t.queue_order)
  149. from user_pass t
  150. where t.logical_card_id = ?
  151. and t.queue_order > ?
  152. and t.expired = 0) ");
  153. $query->execute($cardid, $cardid, $current_q_num);
  154. # no passes left, put in reject rule, finish transaction
  155. if ($query->rows == 0) {
  156. $query = $dbh->prepare("lock tables active_rider_table write");
  157. $query->execute();
  158. $query = $dbh->prepare("insert into active_rider_table (logical_card_id, rfid_token, mag_token, rule_name, rule_param, deleted, notes)
  159. values (?,?,?,?,?,?,?)");
  160. $query->execute($cardid, @oldrow[1,2], $ORG . '-REJECT', 'reject', 0, $oldrow[7]);
  161. $dbh->commit;
  162. $query = $dbh->prepare("unlock tables");
  163. $query->execute();
  164. return;
  165. }
  166. # else make new pass active and update art with new pass
  167. $href = $query->fetchrow_hashref;
  168. my $pass_param = '';
  169. if ($href->{'ruleclass'} eq 'NRIDE') {
  170. $pass_param = $href->{'nrides_orig'};
  171. } elsif ($href->{'ruleclass'} eq 'NDAY') {
  172. $pass_param = $href->{'nday_orig'};
  173. $pass_param .= " " . $href->{'nday_expiration'} if $href->{'nday_expiration'};
  174. }
  175. $audit_pass_id = audit_user_pass_start($dbh, $href->{'user_pass_id'}, "billing_server: ExpirePass: activating pass");
  176. $query = $dbh->prepare("update user_pass set active = 1, activated = ? where user_pass_id = ?");
  177. $query->execute($ride_time, $href->{'user_pass_id'} );
  178. audit_user_pass_end($dbh, $href->{'user_pass_id'}, $audit_pass_id);
  179. $query = $dbh->prepare("lock tables active_rider_table write");
  180. $query->execute();
  181. $query = $dbh->prepare("insert into active_rider_table (logical_card_id, rfid_token, mag_token, rule_name, rule_param, deleted, notes)
  182. values (?,?,?,?,?,?,?)");
  183. $query->execute($cardid, @oldrow[1,2], $href->{'rule'}, $pass_param, 0, $oldrow[7]);
  184. $dbh->commit;
  185. $query = $dbh->prepare("unlock tables");
  186. $query->execute();
  187. }
  188. sub AdvanceRiderPass {
  189. my $dbh = shift;
  190. my $logical_card_id = shift;
  191. my $billing_cksum = shift;
  192. my $billing_ride_time = shift;
  193. my $billing_action = shift;
  194. my $billing_rule = shift;
  195. local $dbh->{RaiseError};
  196. local $dbh->{PrintError};
  197. $dbh->{RaiseError} = 1;
  198. $dbh->{PrintError} = 1;
  199. $dbh->begin_work;
  200. my $sth_find = $dbh->prepare('SELECT active_rider_table.logical_card_id, active_rider_table.rfid_token,
  201. active_rider_table.mag_token, active_rider_table.rule_name,
  202. active_rider_table.rule_param, active_rider_table.deleted,
  203. active_rider_table.parent_entity, active_rider_table.notes,
  204. active_rider_table.seq_num
  205. FROM active_rider_table
  206. WHERE logical_card_id = ?
  207. AND NOT(deleted)
  208. AND seq_num = (SELECT max(seq_num) FROM active_rider_table WHERE logical_card_id = ?) ');
  209. $sth_find->execute($logical_card_id, $logical_card_id);
  210. if ($sth_find->rows != 1) { $dbh->commit; return; }
  211. #@oldrow:
  212. #0. logical_card_id
  213. #1. rfid_token
  214. #2. mag_token
  215. #3. rule_name
  216. #4. rule_param
  217. #5. deleted
  218. #6. parent_entity
  219. #7. notes
  220. #8. seq_num
  221. my @oldrow = $sth_find->fetchrow_array();
  222. my $sth_pass = $dbh->prepare("select p.user_pass_id, p.nrides_remain, p.nday_orig, p.nday_expiration, p.rule
  223. from user_pass p, user_card c
  224. where p.logical_card_id = ?
  225. and c.logical_card_id = p.logical_card_id
  226. and c.active = 1
  227. and p.active = 1
  228. and p.expired = 0
  229. and p.activated <= ?");
  230. $sth_pass->execute($logical_card_id, $billing_ride_time);
  231. if ($sth_pass->rows != 1) {
  232. if (uc($billing_action) ne "REJECT") {
  233. my $sth = $dbh->prepare("insert into diagnostic_log (loglvl, message)
  234. values ('warning', concat('billing_server: logical_card_id ', ?, ', billing_cksum ', ?, ', art seq_num ', ?, ', dropping billing entry: no matching pass entry') ) ");
  235. $sth->execute($logical_card_id, $billing_cksum, $oldrow[8]);
  236. }
  237. $dbh->commit;
  238. return;
  239. }
  240. my $pass = $sth_pass->fetchrow_hashref;
  241. my $t = $dbh->prepare("select ruleclass from rule_class where rulename = ?");
  242. $t->execute($pass->{'rule'});
  243. my $rule_class = 'OTHER';
  244. if ($t->rows == 1) {
  245. $rule_class = $t->fetchrow_hashref->{'ruleclass'};
  246. } elsif ($t->rows < 1) {
  247. my $sth = $dbh->prepare("insert into diagnostic_log (loglvl, message)
  248. values ('warning', concat('billing_server: logical_card_id ', ?, ', billing_cksum ', ?, ', art seq_num ', ?, ', no rule class found, dropping billing entry') ) ");
  249. $sth->execute($logical_card_id, $billing_cksum, $oldrow[8]);
  250. $dbh->commit;
  251. return;
  252. } else {
  253. my $sth = $dbh->prepare("insert into diagnostic_log (loglvl, message)
  254. values ('warning', concat('billing_server: logical_card_id ', ?, ', billing_cksum ', ?, ', art seq_num ', ?, ', multiple rule classes found, dropping billing entry') ) ");
  255. $sth->execute($logical_card_id, $billing_cksum, $oldrow[8]);
  256. $dbh->commit;
  257. return;
  258. }
  259. if (uc($billing_action) eq "REJECT") {
  260. # bus not sync'd?
  261. $dbh->commit;
  262. } elsif ($oldrow[3] ne $pass->{'rule'}) {
  263. # raise warning?
  264. my $sth = $dbh->prepare("insert into diagnostic_log (loglvl, message)
  265. values ('warning', concat('billing_server: logical_card_id ',?,', billing_cksum ',?,', art seq_num ',?,', rule mismatch(1): art rule \"',?,'\" != user_pass_id ',?,' rule \"',?,'\"') )");
  266. $sth->execute($logical_card_id, $billing_cksum, $oldrow[8], $oldrow[3], $pass->{'user_pass_id'}, $pass->{'rule'});
  267. $dbh->commit;
  268. } elsif ($billing_rule ne $pass->{'rule'}) {
  269. # bus got out of sync with art? give user this pass at the risk to prevent against
  270. # decrementing an nride when an nday (or something else) was reported
  271. my $sth = $dbh->prepare("insert into diagnostic_log (loglvl, message)
  272. values ('warning', concat('billing_server: logical_card_id ',?,', billing_cksum ',?,', art seq_num ',?,', rule mismatch(2): billing rule \"',?,'\" != user_pass_id ',?,' rule \"',?,'\"' ) )");
  273. $sth->execute($logical_card_id, $billing_cksum, $oldrow[8], $billing_rule, $pass->{'user_pass_id'}, $pass->{'rule'});
  274. $dbh->commit;
  275. } elsif ( $rule_class eq 'NRIDE') {
  276. my $cur_rides = (($pass->{'nrides_remain'} > 0) ? ($pass->{'nrides_remain'}-1) : 0 );
  277. $oldrow[4] = $cur_rides;
  278. my $audit_pass_id = audit_user_pass_start($dbh, $pass->{'user_pass_id'}, "billing_server: AdvanceRiderPass: updating nride");
  279. my $q = $dbh->prepare('update user_pass set nrides_remain = ?, lastused = ? where user_pass_id = ?');
  280. $q->execute($cur_rides, $billing_ride_time, $pass->{'user_pass_id'});
  281. audit_user_pass_end($dbh, $pass->{'user_pass_id'}, $audit_pass_id);
  282. # expire passes will take care of it if #rides == 0
  283. if ($cur_rides>0) {
  284. $q = $dbh->prepare("lock tables active_rider_table write");
  285. $q->execute();
  286. $q = $dbh->prepare('insert into active_rider_table (logical_card_id, rfid_token, mag_token, rule_name, rule_param, deleted, parent_entity, notes)
  287. values (?, ?, ?,?, ?, ?, ?, ?)');
  288. $q->execute(@oldrow[0..7]);
  289. }
  290. $dbh->commit;
  291. if ($cur_rides>0) { $q = $dbh->prepare("unlock tables"); $q->execute(); }
  292. } elsif ($rule_class eq 'NDAY') {
  293. # update user_pass with expiration and update active_rider_table with new param
  294. if (!$pass->{'nday_expiration'}) {
  295. my $audit_pass_id = audit_user_pass_start($dbh, $pass->{'user_pass_id'}, "billing_server: AdvanceRiderPass: updating nday");
  296. my $q = $dbh->prepare("update user_pass
  297. set nday_expiration = addtime( adddate(convert(date(?), datetime), nday_orig), '2:30'), firstused = ?, lastused = ?
  298. where user_pass_id = ?");
  299. $q->execute($billing_ride_time, $billing_ride_time, $billing_ride_time, $pass->{'user_pass_id'});
  300. audit_user_pass_end($dbh, $pass->{'user_pass_id'}, $audit_pass_id);
  301. $oldrow[4] = $pass->{'nday_orig'} . " " . join('-', Add_Delta_Days(Today, $pass->{'nday_orig'} )) . " 2:30:00";
  302. $q = $dbh->prepare("lock tables active_rider_table write"); $q->execute();
  303. my $sth_new_expires = $dbh->prepare('INSERT INTO active_rider_table (logical_card_id, rfid_token, mag_token, rule_name, rule_param, deleted, parent_entity, notes)
  304. VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
  305. $sth_new_expires->execute(@oldrow[0..7]);
  306. $dbh->commit;
  307. $q = $dbh->prepare("unlock tables");
  308. $q->execute();
  309. } else { # else just update last used
  310. my $audit_pass_id = audit_user_pass_start($dbh, $pass->{'user_pass_id'}, "billing_server: AdvanceRiderPass: updating nday (lastused only)");
  311. my $q = $dbh->prepare("update user_pass set lastused = ? where user_pass_id = ? and (lastused is null or lastused < ?)");
  312. $q->execute($billing_ride_time, $pass->{'user_pass_id'}, $billing_ride_time);
  313. audit_user_pass_end($dbh, $pass->{'user_pass_id'}, $audit_pass_id);
  314. $dbh->commit;
  315. }
  316. } else {
  317. # domain card, do nothing
  318. my $audit_pass_id = audit_user_pass_start($dbh, $pass->{'user_pass_id'}, "billing_server: AdvanceRiderPass: updating domain (lastused only)");
  319. my $q = $dbh->prepare("update user_pass set lastused = ? where user_pass_id = ? and (lastused is null or lastused < ?)");
  320. $q->execute($billing_ride_time, $pass->{'user_pass_id'}, $billing_ride_time);
  321. audit_user_pass_end($dbh, $pass->{'user_pass_id'}, $audit_pass_id);
  322. $dbh->commit;
  323. }
  324. ExpirePass( $dbh, $logical_card_id, $pass->{'user_pass_id'}, $billing_ride_time, @oldrow );
  325. }
  326. sub ServerReply
  327. {
  328. my $client_query = $_[0];
  329. $/="\n";
  330. chomp($client_query);
  331. my $response = "";
  332. my $client_query_md5 = md5_hex($client_query);
  333. my $dbh = DBI->connect($database_path, $database_user, $database_pass)
  334. or die "Couldn't connect to database: " . DBI->errstr;
  335. my $sth ;
  336. my $loglvl ;
  337. my $message ;
  338. my $logmsg ;
  339. if ($client_query =~ m/^[\s\x00]*$/)
  340. {
  341. $logmsg .= "Ignoring spurious blank line.\n";
  342. $response .= "IGN\t" . $client_query_md5 . "\n";
  343. }
  344. elsif ($client_query =~ m/^\!/) #error
  345. {
  346. $loglvl = "error";
  347. $message = $client_query;
  348. $message =~ s/^.//;
  349. try {
  350. $sth = $dbh->prepare('INSERT IGNORE INTO diagnostic_log (loglvl, message) VALUES (?, ?)')
  351. or die "Couldn't prepare statement: " . $dbh->errstr;
  352. $sth->execute($loglvl, $message) # Execute the query
  353. or die "Couldn't execute statement: " . $sth->errstr;
  354. }
  355. catch {
  356. $logmsg .= $_ . "\n";
  357. $response .= "IGN\t" . $client_query_md5 . "\n";
  358. };
  359. if ($sth->rows < 1) {
  360. $response .= "DUP\t" . $client_query_md5 . "\n";
  361. } else {
  362. $response .= "ACK\t" . $client_query_md5 . "\n";
  363. }
  364. }
  365. elsif ($client_query =~ m/^\*/) #warning
  366. {
  367. $loglvl = "warning";
  368. $message = $client_query;
  369. $message =~ s/^.//;
  370. try {
  371. $sth = $dbh->prepare('INSERT IGNORE INTO diagnostic_log (loglvl, message) VALUES (?, ?)')
  372. or die "Couldn't prepare statement: " . $dbh->errstr;
  373. $sth->execute($loglvl, $message) # Execute the query
  374. or die "Couldn't execute statement: " . $sth->errstr;
  375. }
  376. catch {
  377. $logmsg .= $_ . "\n";
  378. $response .= "IGN\t" . $client_query_md5 . "\n";
  379. };
  380. if ($sth->rows < 1) {
  381. $response .= "DUP\t" . $client_query_md5 . "\n";
  382. } else {
  383. $response .= "ACK\t" . $client_query_md5 . "\n";
  384. }
  385. }
  386. elsif ($client_query =~ m/^\#/) #debug
  387. {
  388. $loglvl = "debug";
  389. $message = $client_query;
  390. $message =~ s/^.//;
  391. try {
  392. $sth = $dbh->prepare('INSERT IGNORE INTO diagnostic_log (loglvl, message) VALUES (?, ?)')
  393. or die "Couldn't prepare statement: " . $dbh->errstr;
  394. $sth->execute($loglvl, $message) # Execute the query
  395. or die "Couldn't execute statement: " . $sth->errstr;
  396. }
  397. catch {
  398. $logmsg .= $_ . "\n";
  399. $response .= "IGN\t" . $client_query_md5 . "\n";
  400. };
  401. if ($sth->rows < 1) {
  402. $response .= "DUP\t" . $client_query_md5 . "\n";
  403. } else {
  404. $response .= "ACK\t" . $client_query_md5 . "\n";
  405. }
  406. }
  407. elsif ($client_query =~ m/^(?:[^\t]*\t)+[^\t]*/) #look for a list of optionally blank tab-delimited fields
  408. {
  409. my @client_values = split(/[\t]/, $client_query, -1); #the -1 keeps split from trimming trailing blank fields
  410. #0. equip_num
  411. #1. driver
  412. #2. paddle
  413. #3. route
  414. #4. trip
  415. #5. stop
  416. #6. ride_time
  417. #7. latitude
  418. #8. longitude
  419. #9. action
  420. #10. rule
  421. #11. ruleparam
  422. #12. reason
  423. #13. credential
  424. #14. logical_card_id
  425. #15. cash_value
  426. #16. stop_name
  427. #17. (unused by DB) usec
  428. my $duplicate_billing_entry=0;
  429. try {
  430. #$sth = $dbh->prepare('select count(*) num from billing_log where ride_time = FROM_UNIXTIME(?) and conf_checksum = ?') or die "Couldn't prepare statement: " . $dbh->errstr;
  431. $sth = $dbh->prepare('select count(*) num from billing_log where ride_time = datetime(?, "unixepoch") and conf_checksum = ?') or die "Couldn't prepare statement: " . $dbh->errstr;
  432. $sth->execute($client_values[6], $client_query_md5) or die "Couldn't execute statement: " . $sth->errstr;
  433. $duplicate_billing_entry=1 if ($sth->fetchrow_arrayref->[0] > 0);
  434. if (!$duplicate_billing_entry) {
  435. #$sth = $dbh->prepare('REPLACE INTO billing_log (conf_checksum, equip_num, driver, paddle, route, trip, stop, ride_time, latitude, longitude, action, rule, ruleparam, reason, credential, logical_card_id, cash_value, stop_name) VALUES (?, ?, ?, ?, ?, ?, ?, FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
  436. $sth = $dbh->prepare('REPLACE INTO billing_log (conf_checksum, equip_num, driver, paddle, route, trip, stop, ride_time, latitude, longitude, action, rule, ruleparam, reason, credential, logical_card_id, cash_value, stop_name) VALUES (?, ?, ?, ?, ?, ?, ?, datetime(?, "unixepoch"), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
  437. or die "Couldn't prepare statement: " . $dbh->errstr;
  438. $sth->execute($client_query_md5, @client_values[0..16]) # Execute the query
  439. or die "Couldn't execute statement: " . $sth->errstr;
  440. }
  441. }
  442. catch {
  443. $logmsg .= $_ . "\n";
  444. $response .= "IGN\t" . $client_query_md5 . "\n";
  445. };
  446. if ($duplicate_billing_entry)
  447. {
  448. $response .= "DUP\t" . $client_query_md5 . "\n";
  449. } elsif ($sth->rows == 1) #if the billing log update was sucessful and wasn't a duplicate
  450. {
  451. AdvanceRiderPass($dbh, $client_values[14], $client_query_md5, unix_to_readable_time($client_values[6]), $client_values[9], $client_values[10]);
  452. $response .= "ACK\t" . $client_query_md5 . "\n";
  453. }
  454. #elsif ($sth->rows > 1)
  455. #{
  456. # $response .= "DUP\t" . $client_query_md5 . "\n";
  457. #}
  458. else
  459. {
  460. $logmsg .= "Error inserting $client_query_md5 $client_query into billing_log\n" ;
  461. }
  462. }
  463. else
  464. {
  465. $logmsg .= "Malformed log entry \"$client_query\".\n";
  466. $response .= "IGN\t" . $client_query_md5 . "\n";
  467. }
  468. print $logmsg if $logmsg;
  469. return $response;
  470. }
  471. sub handle_client()
  472. {
  473. close SERVER;
  474. CLIENT->autoflush(1);
  475. my $linebuffer;
  476. while($linebuffer = <CLIENT>)
  477. {
  478. ## DEBUG
  479. print "## billing: $linebuffer\n";
  480. open LOGFH, ">>$logfile";
  481. print LOGFH $linebuffer;
  482. close LOGFH;
  483. print CLIENT ServerReply($linebuffer);
  484. } #while data from client
  485. close CLIENT;
  486. }
  487. my $waitedpid = 0;
  488. my $sigreceived = 0;
  489. sub REAPER
  490. {
  491. while (($waitedpid = waitpid(-1, WNOHANG))>0) { }
  492. $SIG{CHLD} = \&REAPER; # loathe sysV
  493. $sigreceived = 1;
  494. }
  495. sub spawn
  496. {
  497. my $coderef = shift; #grab the first parameter
  498. unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') #verify that it consists of a non-null block of executable perl code
  499. {
  500. confess "usage: spawn CODEREF"; #complain if this is not the case
  501. }
  502. my $pid;
  503. if (!defined($pid = fork)) #attempt a fork, remembering the returned PID value
  504. {
  505. close CLIENT;
  506. return; #failed to fork, we'd better close the client
  507. }
  508. elsif ($pid) #If the returned process ID is non-zero, that indicates that we are the parent process
  509. {
  510. return; # i'm the parent
  511. }
  512. else #otherwise, if the returned process ID is 0, that means we're the child process
  513. {
  514. exit &$coderef(); #in which case, we want to execute the child handler that was passed in, and then
  515. #exit this (child) process when we've finished our conversation(s) with the
  516. #other (client) end of the socket.
  517. }
  518. }
  519. #----------------------------------------------------------------------
  520. # Local network settings for Inter-Process communication.
  521. #----------------------------------------------------------------------
  522. my $proto = getprotobyname('tcp');
  523. my $addr = sockaddr_in( $bind_port ,inet_aton($bind_ip));;
  524. #----------------------------------------------------------------------
  525. my $max_retries = 10; #Maximum number of address-binding retries before we give up.
  526. my $retry_count = $max_retries; #number of retries left...
  527. my $retry_delay = 3; #number of seconds to wait between retries at binding to our designated IPC address
  528. my $got_network = 0; #flag to let us know that we can quit retrying once we have gotten a valid listening socket
  529. while( ($retry_count > 0) && (!$got_network) )
  530. {
  531. try #Try and allocate a socket, bind it to our IPC address, and set it to listen for connections
  532. {
  533. socket(SERVER,PF_INET,SOCK_STREAM,$proto) || die "socket: $!";
  534. setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1);
  535. bind (SERVER, $addr) || die "bind: $!";
  536. listen(SERVER,5) || die "listen: $!";
  537. $got_network = 1;
  538. }
  539. catch #If that didn't work for some reason, log the error, clean up, and prepair to retry
  540. {
  541. my $errmsg = $_; #Remember the error message
  542. close(SERVER); #Clean up the server socket if it needs it
  543. #Decrement our remaining retry counter
  544. $retry_count = $retry_count - 1;
  545. #Log the message to our debug log
  546. print "Failed to allocate socket, will retry $retry_count times: $errmsg\n";
  547. #Wait a reasonable period before trying again
  548. sleep $retry_delay;
  549. };
  550. }
  551. if($got_network) #If we met with success binding to the network, report it
  552. {
  553. my $logmsg = "Socket setup successful. Listening for clients at $bind_ip:$bind_port\n";
  554. print $logmsg;
  555. }
  556. else #If we ran out of patience and gave up, report that as well and exit
  557. {
  558. my $errmsg = "Could not allocate and bind listening socket at $bind_ip:$bind_port after $max_retries attempts.\n";
  559. die $errmsg;
  560. }
  561. # Set up our signal handler which will clean up defunct child processes and let the main
  562. # accept() loop know that the reason accept returned was due to a signal, not a legit connection.
  563. $SIG{CHLD} = \&REAPER;
  564. #This for loop is efficient, but confusting, so I'll break it down by clause
  565. #
  566. # The first clause ($sigreceived = 0) clears the signal received flag that will be set if the
  567. # accept() call was interrupted by a signal. This clause runs once before the first run of the loop
  568. #
  569. # The second clause is the test clause, it will process the contents of the loop if EITHER
  570. # accept() has returned (presumably generating a valid file handle for the CLIENT end of the
  571. # socket, OR the signal received flag is set (thus accept would have returned early without
  572. # having actually accepted a connection.
  573. #
  574. # The third clause (the 'incrementer') is run after each time the body is executed, before the
  575. # test clause is executed again (deciding whether to run the body or drop out... This test
  576. # clause will close the parent process' copy of the CLIENT file handle since (see body below)
  577. # after the body executes, all communication with the socket referred to by that file handle
  578. # will be carried out by the spawned child process. This frees the parent's copy of the CLIENT
  579. # file handle to be used again in the parent process for the next accepted incoming connection.
  580. for ( $sigreceived = 0; accept(CLIENT,SERVER) || $sigreceived; $sigreceived = 0, close CLIENT)
  581. {
  582. 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
  583. print "connection received.\n"; #Print a diagnostic message confirming that we have made a connection
  584. spawn sub {handle_client();}; #fork() off a child process that will handle communication with the socket pointed to by the CLIENT file handle
  585. }