hello_daemon.pl 8.3 KB

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