ridelogic_versiond 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 Carp;
  24. use DBI;
  25. use FileHandle;
  26. use Fcntl;
  27. use Getopt::Long qw(:config no_ignore_case);
  28. use POSIX;
  29. use RideLogic;
  30. my $database_path = 'DBI:mysql:busdb';
  31. my $database_user = '';
  32. my $database_pass = '';
  33. my $bind_ip = '127.0.0.1';
  34. my $bind_port = 8377;
  35. my $DebugMode = 0;
  36. # This function only executes the passed code reference if the global variable $DebugMode is non-zero.
  37. # The reason for this is that any calculation (like a FooBar::ComplexObject->toString call) will not be
  38. # performed if we are not in debug mode, sort of like a very limited form of lazy evaluation.
  39. #
  40. sub ifdebug(&@)
  41. {
  42. my ($cmd) = @_;
  43. &$cmd() if($DebugMode);
  44. }
  45. sub CheckinServerReply
  46. {
  47. my $client_query = $_[0];
  48. my $dbh = DBI->connect($database_path, $database_user, $database_pass)
  49. or die "Couldn't connect to database: " . DBI->errstr;
  50. my $sth ;
  51. my $logmsg ;
  52. my $response = '';
  53. my @client_values = split(/[\t]/, $client_query, -1); #the -1 keeps split from trimming trailing blank fields
  54. #0. busunit_num (0 for Phase II)
  55. #1. equip_num (usually bogus for Phase I)
  56. #2. eth0_mac (Effectively a serial number of the SBC
  57. #3. cell_imei (Effectively a serial number of the Cell Modem)
  58. #4. cell_imsi (Effectively a serial number of the SIM card inserted in the modem)
  59. #5. version_strings (a concatenation of package versions)
  60. $client_values[0] =~ s/^[^0-9]*//; #Strip the leading '#' (and anything else non-numeric) from our string
  61. $sth = $dbh->prepare('INSERT INTO bus_checkin_log (busunit_num, equip_num, eth0_mac, cell_imei, cell_imsi, version_data) VALUES (?, ?, ?, ?, ?, ?)');
  62. # We explicitly chop this down to the 6 fields we want to insert, rather than passing @client_values as a parameter so
  63. #that if some foolish version string goes and contains a tab (this should never happen!) it will be trunctated instead
  64. #of the whole update being shitcanned because the array has too many data fields for the quiery...
  65. try
  66. {
  67. $sth->execute(@client_values[0..5]);
  68. $response .= "Thanks.\n";
  69. }
  70. catch
  71. {
  72. $logmsg .= $_ . "\n";
  73. $response .= "Server Side Error.\n";
  74. };
  75. print $logmsg if $logmsg;
  76. return $response;
  77. }
  78. sub ServerReply
  79. {
  80. my $client_query = $_[0];
  81. $/="\n";
  82. chomp($client_query);
  83. if ($client_query =~ m/^\#/) #A leading '#' signals a bus_checkin_log entry, rather than an package update checkin
  84. {
  85. return CheckinServerReply($client_query);
  86. }
  87. my $response = "";
  88. my $dbh = DBI->connect($database_path, $database_user, $database_pass)
  89. or die "Couldn't connect to database: " . DBI->errstr;
  90. my $sth ;
  91. my $logmsg ;
  92. $sth = $dbh->prepare('SELECT client_file, checksum, file_size, file_path, fileversion FROM update_level t1 WHERE (serial = (SELECT serial FROM update_level WHERE client_file = t1.client_file AND (equip_num = 0 OR equip_num = ?) ORDER BY equip_num DESC, serial DESC LIMIT 1)) ORDER BY client_file ASC');
  93. my @client_values = split(/[\t]/, $client_query, -1); #the -1 keeps split from trimming trailing blank fields
  94. #0. equip_num
  95. #1. filename=md5sum
  96. #2 ...
  97. my $i;
  98. my %filetable = ();
  99. for($i = 1; $i < @client_values; $i = $i + 1)
  100. {
  101. my ($client_file, $client_checksum) = split(/=/, $client_values[$i]);
  102. if($client_file && $client_checksum)
  103. {
  104. $filetable{$client_file} = $client_checksum;
  105. }
  106. }
  107. try
  108. {
  109. $sth->execute($client_values[0]) or die "Couldn't execute statement: " . $sth->errstr;
  110. }
  111. catch
  112. {
  113. $logmsg .= $_ . "\n";
  114. };
  115. while(my @data = $sth->fetchrow_array())
  116. {
  117. #0 client_file
  118. #1 checksum
  119. #2 file_size
  120. #3 file_path
  121. #4 fileversion
  122. if(defined $filetable{$data[0]} && $filetable{$data[0]} eq $data[1])
  123. {
  124. #do nothing, the client is up to date
  125. }
  126. else
  127. {
  128. $response .= "$data[0]\t$data[1]\t$data[2]\t$data[3]\t$data[4]\n";
  129. }
  130. }
  131. print $logmsg if $logmsg;
  132. return $response;
  133. }
  134. sub handle_client()
  135. {
  136. close SERVER;
  137. CLIENT->autoflush(1);
  138. my $linebuffer;
  139. while($linebuffer = <CLIENT>)
  140. {
  141. print CLIENT ServerReply($linebuffer);
  142. } #while data from client
  143. close CLIENT;
  144. }
  145. my $waitedpid = 0;
  146. my $sigreceived = 0;
  147. sub REAPER
  148. {
  149. while (($waitedpid = waitpid(-1, WNOHANG))>0) { }
  150. $SIG{CHLD} = \&REAPER; # loathe sysV
  151. $sigreceived = 1;
  152. }
  153. sub spawn
  154. {
  155. my $coderef = shift; #grab the first parameter
  156. unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') #verify that it consists of a non-null block of executable perl code
  157. {
  158. confess "usage: spawn CODEREF"; #complain if this is not the case
  159. }
  160. my $pid;
  161. if (!defined($pid = fork)) #attempt a fork, remembering the returned PID value
  162. {
  163. close CLIENT;
  164. return; #failed to fork, we'd better close the client
  165. }
  166. elsif ($pid) #If the returned process ID is non-zero, that indicates that we are the parent process
  167. {
  168. return; # i'm the parent
  169. }
  170. else #otherwise, if the returned process ID is 0, that means we're the child process
  171. {
  172. exit &$coderef(); #in which case, we want to execute the child handler that was passed in, and then
  173. #exit this (child) process when we've finished our conversation(s) with the
  174. #other (client) end of the socket.
  175. }
  176. }
  177. sub show_help_and_exit {
  178. print "usage:\n";
  179. print " [-i] interactive, do not daemonize\n";
  180. print " [-c cfg] use cfg as config file (default to " . $RideLogic::RIDELOGIC_DAEMON_CONF . ") \n";
  181. print " [-h] show help (this screen)\n";
  182. exit;
  183. }
  184. #----------------------------------------------------------------------
  185. #
  186. #----------------------------------------------------------------------
  187. my $daemonize = 1;
  188. my $interactive = 0;
  189. my $show_help = 0;
  190. my $cfg_file = $RideLogic::RIDELOGIC_DAEMON_CONF;
  191. GetOptions(
  192. 'i|interactive' => \$interactive,
  193. 'c|config=s' => \$cfg_file,
  194. 'h|help' => \$show_help );
  195. show_help_and_exit() if ($show_help);
  196. $daemonize=0 if ($interactive);
  197. #----------------------------------------------------------------------
  198. # Local network settings for Inter-Process communication.
  199. #----------------------------------------------------------------------
  200. my $proto = getprotobyname('tcp');
  201. my $addr = sockaddr_in( $bind_port ,inet_aton($bind_ip));;
  202. #----------------------------------------------------------------------
  203. my $max_retries = 10; #Maximum number of address-binding retries before we give up.
  204. my $retry_count = $max_retries; #number of retries left...
  205. my $retry_delay = 3; #number of seconds to wait between retries at binding to our designated IPC address
  206. my $got_network = 0; #flag to let us know that we can quit retrying once we have gotten a valid listening socket
  207. my %CFG_VAR;
  208. read_config($cfg_file, \%CFG_VAR) if ($cfg_file);
  209. my $logfile = ($CFG_VAR{"RIDELOGIC_DAEMON_LOG_DIR"} || $RideLogic::RIDELOGIC_DAEMON_LOG_DIR) . "/ridelogic_versiond.log";
  210. my $pidfile = ($CFG_VAR{"RIDELOGIC_DAEMON_PID_DIR"} || $RideLogic::RIDELOGIC_DAEMON_PID_DIR) . "/ridelogic_versiond.pid";
  211. daemonize($logfile, $pidfile) if ($daemonize);
  212. # set our pipes to be piping hot
  213. $|=1;
  214. while( ($retry_count > 0) && (!$got_network) )
  215. {
  216. try #Try and allocate a socket, bind it to our IPC address, and set it to listen for connections
  217. {
  218. socket(SERVER,PF_INET,SOCK_STREAM,$proto) || die "socket: $!";
  219. setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1);
  220. bind (SERVER, $addr) || die "bind: $!";
  221. listen(SERVER,5) || die "listen: $!";
  222. $got_network = 1;
  223. }
  224. catch #If that didn't work for some reason, log the error, clean up, and prepair to retry
  225. {
  226. my $errmsg = $_; #Remember the error message
  227. close(SERVER); #Clean up the server socket if it needs it
  228. #Decrement our remaining retry counter
  229. $retry_count = $retry_count - 1;
  230. #Log the message to our debug log
  231. print "Failed to allocate socket, will retry $retry_count times: $errmsg\n";
  232. #Wait a reasonable period before trying again
  233. sleep $retry_delay;
  234. };
  235. }
  236. if($got_network) #If we met with success binding to the network, report it
  237. {
  238. my $logmsg = "Socket setup successful. Listening for clients at $bind_ip:$bind_port\n";
  239. print $logmsg;
  240. }
  241. else #If we ran out of patience and gave up, report that as well and exit
  242. {
  243. my $errmsg = "Could not allocate and bind listening socket at $bind_ip:$bind_port after $max_retries attempts.\n";
  244. die $errmsg;
  245. }
  246. # Set up our signal handler which will clean up defunct child processes and let the main
  247. # accept() loop know that the reason accept returned was due to a signal, not a legit connection.
  248. $SIG{CHLD} = \&REAPER;
  249. #This for loop is efficient, but confusting, so I'll break it down by clause
  250. #
  251. # The first clause ($sigreceived = 0) clears the signal received flag that will be set if the
  252. # accept() call was interrupted by a signal. This clause runs once before the first run of the loop
  253. #
  254. # The second clause is the test clause, it will process the contents of the loop if EITHER
  255. # accept() has returned (presumably generating a valid file handle for the CLIENT end of the
  256. # socket, OR the signal received flag is set (thus accept would have returned early without
  257. # having actually accepted a connection.
  258. #
  259. # The third clause (the 'incrementer') is run after each time the body is executed, before the
  260. # test clause is executed again (deciding whether to run the body or drop out... This test
  261. # clause will close the parent process' copy of the CLIENT file handle since (see body below)
  262. # after the body executes, all communication with the socket referred to by that file handle
  263. # will be carried out by the spawned child process. This frees the parent's copy of the CLIENT
  264. # file handle to be used again in the parent process for the next accepted incoming connection.
  265. for ( $sigreceived = 0; accept(CLIENT,SERVER) || $sigreceived; $sigreceived = 0, close CLIENT)
  266. {
  267. 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
  268. print "connection received.\n"; #Print a diagnostic message confirming that we have made a connection
  269. spawn sub {handle_client();}; #fork() off a child process that will handle communication with the socket pointed to by the CLIENT file handle
  270. }