version_daemon.pl 12 KB

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