version_daemon.pl 12 KB

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