avls_server.pl 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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:SQLite:dbname=../bus.sqlite';
  31. my $database_user = '';
  32. my $database_pass = '';
  33. my $bind_ip = '127.0.0.1';
  34. my $bind_port = 2857;
  35. #----------------------------------------------Ugly exception handling logic using closures and anonymous functions----
  36. #-------------------------------------------This is in there to deal with the fact that CreditCall uses the die("error")
  37. #-------------------------------------------function instead of returning an error message in many cases...
  38. # This utility function returns the passed string sans any leading or trailing whitespace.
  39. #
  40. sub strip_whitespace
  41. {
  42. my $str = shift; #grab our first parameter
  43. $str =~ s/^\s+//; #strip leading whitespace
  44. $str =~ s/\s+$//; #strip trailing whitespace
  45. return $str; #return the improved string
  46. }
  47. # This function takes two coderef parameters, the second of which is usually an explicit call to the
  48. # 'catch' function which itself takes a coderef parameter. This allows the code employing this suite of
  49. # functions to look somewhat like a conventional exception handling mechanism:
  50. #
  51. # try
  52. # {
  53. # do_something_that_might_die();
  54. # }
  55. # catch
  56. # {
  57. # my $errmsg = $_;
  58. # log_the_error_message($errmsg);
  59. # perform_some_cleanup();
  60. # };
  61. #
  62. # DO NOT FORGET THAT LAST SEMICOLON, EVERYTHING GOES TO HELL IF YOU DO!
  63. #
  64. sub try(&$)
  65. {
  66. my ($attempt, $handler) = @_;
  67. eval
  68. {
  69. &$attempt;
  70. };
  71. if($@)
  72. {
  73. do_catch($handler);
  74. }
  75. }
  76. # This function strips off the whitespace from the exception message reported by die()
  77. # and places the result into the default variable such that the code in the catch block can
  78. # just examine $_ to figure out what the cause of the error is, or to display or log
  79. # the error message.
  80. #
  81. sub do_catch(&$)
  82. {
  83. my ($handler) = @_;
  84. local $_ = strip_whitespace($@);
  85. &$handler;
  86. }
  87. # This just takes an explicit coderef and returns it unharmed. The only
  88. # purpose of this is so the try/catch structure looks pretty and familiar.
  89. #
  90. sub catch(&) {$_[0]}
  91. #--------------------------------------------------------------------------------------------------------------------
  92. #my $DebugMode = 1;
  93. my $DebugMode = 0;
  94. # This function only executes the passed code reference if the global variable $DebugMode is non-zero.
  95. # The reason for this is that any calculation (like a FooBar::ComplexObject->toString call) will not be
  96. # performed if we are not in debug mode, sort of like a very limited form of lazy evaluation.
  97. #
  98. sub ifdebug(&@)
  99. {
  100. my ($cmd) = @_;
  101. &$cmd() if($DebugMode);
  102. }
  103. sub StoreAvls
  104. {
  105. my $client_query = $_[0];
  106. chomp($client_query);
  107. my $dbh = DBI->connect($database_path, $database_user, $database_pass)
  108. or die "Couldn't connect to database: " . DBI->errstr;
  109. #my $sth_avls = $dbh->prepare('INSERT INTO avls_data (equip_num, driver, paddle, route, trip, stop, chirp_time, latitude, longitude, heading, velocity) VALUES (?, ?, ?, ?, ?, ?, FROM_UNIXTIME(?), ?, ?, ?, ?)')
  110. my $sth_avls = $dbh->prepare('INSERT INTO avls_data (equip_num, driver, paddle, route, trip, stop, chirp_time, latitude, longitude, heading, velocity) VALUES (?, ?, ?, ?, ?, ?, datetime(?, "unixepoch"), ?, ?, ?, ?)')
  111. or die "Couldn't prepare statement: " . $dbh->errstr;
  112. #store avls data
  113. $sth_avls->execute(split("\t", $client_query)) # Execute the query
  114. or die "Couldn't execute statement: " . $sth_avls->errstr;
  115. $sth_avls->finish;
  116. $dbh->disconnect;
  117. }
  118. sub handle_client()
  119. {
  120. close SERVER;
  121. CLIENT->autoflush(1);
  122. my $linebuffer;
  123. while($linebuffer = <CLIENT>)
  124. {
  125. StoreAvls($linebuffer);
  126. } #while data from client
  127. close CLIENT;
  128. }
  129. my $waitedpid = 0;
  130. my $sigreceived = 0;
  131. sub REAPER
  132. {
  133. while (($waitedpid = waitpid(-1, WNOHANG))>0) { }
  134. $SIG{CHLD} = \&REAPER; # loathe sysV
  135. $sigreceived = 1;
  136. }
  137. sub spawn
  138. {
  139. my $coderef = shift; #grab the first parameter
  140. unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') #verify that it consists of a non-null block of executable perl code
  141. {
  142. confess "usage: spawn CODEREF"; #complain if this is not the case
  143. }
  144. my $pid;
  145. if (!defined($pid = fork)) #attempt a fork, remembering the returned PID value
  146. {
  147. close CLIENT;
  148. return; #failed to fork, we'd better close the client
  149. }
  150. elsif ($pid) #If the returned process ID is non-zero, that indicates that we are the parent process
  151. {
  152. return; # i'm the parent
  153. }
  154. else #otherwise, if the returned process ID is 0, that means we're the child process
  155. {
  156. exit &$coderef(); #in which case, we want to execute the child handler that was passed in, and then
  157. #exit this (child) process when we've finished our conversation(s) with the
  158. #other (client) end of the socket.
  159. }
  160. }
  161. #----------------------------------------------------------------------
  162. # Local network settings for Inter-Process communication.
  163. #----------------------------------------------------------------------
  164. my $proto = getprotobyname('tcp');
  165. my $addr = sockaddr_in( $bind_port ,inet_aton($bind_ip));;
  166. #----------------------------------------------------------------------
  167. my $max_retries = 10; #Maximum number of address-binding retries before we give up.
  168. my $retry_count = $max_retries; #number of retries left...
  169. my $retry_delay = 3; #number of seconds to wait between retries at binding to our designated IPC address
  170. my $got_network = 0; #flag to let us know that we can quit retrying once we have gotten a valid listening socket
  171. $|=1;
  172. while( ($retry_count > 0) && (!$got_network) )
  173. {
  174. try #Try and allocate a socket, bind it to our IPC address, and set it to listen for connections
  175. {
  176. socket(SERVER,PF_INET,SOCK_STREAM,$proto) || die "socket: $!";
  177. setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1);
  178. bind (SERVER, $addr) || die "bind: $!";
  179. listen(SERVER,5) || die "listen: $!";
  180. $got_network = 1;
  181. }
  182. catch #If that didn't work for some reason, log the error, clean up, and prepair to retry
  183. {
  184. my $errmsg = $_; #Remember the error message
  185. close(SERVER); #Clean up the server socket if it needs it
  186. #Decrement our remaining retry counter
  187. $retry_count = $retry_count - 1;
  188. #Log the message to our debug log
  189. print "Failed to allocate socket, will retry $retry_count times: $errmsg\n";
  190. #Wait a reasonable period before trying again
  191. sleep $retry_delay;
  192. };
  193. }
  194. if($got_network) #If we met with success binding to the network, report it
  195. {
  196. my $logmsg = "Socket setup successful. Listening for clients at $bind_ip:$bind_port\n";
  197. print $logmsg;
  198. }
  199. else #If we ran out of patience and gave up, report that as well and exit
  200. {
  201. my $errmsg = "Could not allocate and bind listening socket at $bind_ip:$bind_port after $max_retries attempts.\n";
  202. die $errmsg;
  203. }
  204. # Set up our signal handler which will clean up defunct child processes and let the main
  205. # accept() loop know that the reason accept returned was due to a signal, not a legit connection.
  206. $SIG{CHLD} = \&REAPER;
  207. #This for loop is efficient, but confusting, so I'll break it down by clause
  208. #
  209. # The first clause ($sigreceived = 0) clears the signal received flag that will be set if the
  210. # accept() call was interrupted by a signal. This clause runs once before the first run of the loop
  211. #
  212. # The second clause is the test clause, it will process the contents of the loop if EITHER
  213. # accept() has returned (presumably generating a valid file handle for the CLIENT end of the
  214. # socket, OR the signal received flag is set (thus accept would have returned early without
  215. # having actually accepted a connection.
  216. #
  217. # The third clause (the 'incrementer') is run after each time the body is executed, before the
  218. # test clause is executed again (deciding whether to run the body or drop out... This test
  219. # clause will close the parent process' copy of the CLIENT file handle since (see body below)
  220. # after the body executes, all communication with the socket referred to by that file handle
  221. # will be carried out by the spawned child process. This frees the parent's copy of the CLIENT
  222. # file handle to be used again in the parent process for the next accepted incoming connection.
  223. for ( $sigreceived = 0; accept(CLIENT,SERVER) || $sigreceived; $sigreceived = 0, close CLIENT)
  224. {
  225. 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
  226. print "connection received.\n"; #Print a diagnostic message confirming that we have made a connection
  227. spawn sub {handle_client();}; #fork() off a child process that will handle communication with the socket pointed to by the CLIENT file handle
  228. }