billing_server.pl 25 KB

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