signal_set.cc 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // Copyright (C) 2014 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <util/signal_set.h>
  15. #include <cerrno>
  16. #include <list>
  17. using namespace isc;
  18. using namespace isc::util;
  19. namespace {
  20. /// @brief Returns a pointer to the global set of registered signals.
  21. ///
  22. /// Multiple instances of @c SignalSet may use this pointer to access
  23. /// and update the set. Note we use a smart pointer so callers can ensure
  24. /// the static object doesn't go out of scope before they are done with it
  25. /// during process exit.
  26. ///
  27. /// @return Pointer to the global set of registered signals. This pointer
  28. /// is always initialized and points to a valid object.
  29. SigIntSetPtr getRegisteredSignals() {
  30. static SigIntSetPtr registered_signals(new SigIntSet());
  31. return (registered_signals);
  32. }
  33. /// @brief Returns a pointer to static collection of signals received.
  34. ///
  35. /// Multiple instances of @c SignalSet may use this pointer to access
  36. /// and update the queue of signals received. Note we use a smart pointer
  37. /// so callers can ensure the static object doesn't go out of scope before
  38. /// they are done with it during process exit.
  39. ///
  40. /// @return Static collection of signals received. This pointer is always
  41. /// initialized and points to a valid object.
  42. SigIntListPtr getSignalStates() {
  43. static SigIntListPtr signal_states(new SigIntList());
  44. return (signal_states);
  45. }
  46. /// @brief Internal signal handler for @c isc::util::io::SignalSet class.
  47. ///
  48. /// This handler catches all registered signals. When a signal arrives it
  49. /// passes the signal to invokeOnReceiptHandler for "on-receipt" processing.
  50. /// If this processing returns true if exists without further action,
  51. /// otherwise it adds the signal number to the queue of received signals.
  52. /// It prevents adding duplicated signals. All duplicated signals are dropped.
  53. /// This prevents hammering a process to invoke handlers (e.g. DHCP server
  54. /// reconfiguration), when many of the same signals are received one after
  55. /// another.
  56. ///
  57. /// @param sig Signal number.
  58. void internalHandler(int sig) {
  59. if (SignalSet::invokeOnReceiptHandler(sig)) {
  60. // Signal has been handled by the on-receipt handler.
  61. return;
  62. }
  63. // Signal is using post-receipt handling, see if we've
  64. // already received it.
  65. SigIntListPtr states = getSignalStates();
  66. for (std::list<int>::const_iterator it = states->begin();
  67. it != states->end(); ++it) {
  68. if (sig == *it) {
  69. return;
  70. }
  71. }
  72. // First occurrence, so save it.
  73. states->push_back(sig);
  74. }
  75. /// @brief Optional handler to execute at the time of signal receipt
  76. BoolSignalHandler onreceipt_handler_ = BoolSignalHandler();
  77. }; // end anon namespace
  78. namespace isc {
  79. namespace util {
  80. bool
  81. SignalSet::invokeOnReceiptHandler(int sig) {
  82. if (!onreceipt_handler_) {
  83. return (false);
  84. }
  85. // First we set the signal to SIG_IGN. This causes any repeat occurrences
  86. // to be discarded, not deferred as they would be if blocked. Note that
  87. // we save the current sig action so we can restore it later.
  88. struct sigaction sa;
  89. struct sigaction prev_sa;
  90. memset(&sa, 0, sizeof(sa));
  91. sa.sa_handler = SIG_IGN;
  92. if (sigaction(sig, &sa, &prev_sa) < 0) {
  93. // Highly unlikely we can get here.
  94. const char* errmsg = strerror(errno);
  95. isc_throw(SignalSetError, "failed to set SIG_IGN for signal "
  96. << sig << ": " << errmsg);
  97. }
  98. // Call the registered handler.
  99. bool signal_processed = false;
  100. try {
  101. signal_processed = onreceipt_handler_(sig);
  102. } catch (const std::exception& ex) {
  103. // Restore the handler. We might fail to restore it, but we likely
  104. // have bigger issues anyway: for that reason, the return value is
  105. // ignored. To avoid complaints from static code checkers that notice
  106. // that the return values from other calls to sigaction() have been
  107. // used, the call to sigaction is explicitly cast to void to indicate
  108. // that the return value is intentionally being ignored.
  109. static_cast<void>(sigaction(sig, &prev_sa, 0));
  110. isc_throw(SignalSetError, "onreceipt_handler failed for signal "
  111. << sig << ": " << ex.what());
  112. }
  113. // Restore the sig action to reenable handling this signal.
  114. if (sigaction(sig, &prev_sa, 0) < 0) {
  115. // Highly unlikely we can get here.
  116. const char* errmsg = strerror(errno);
  117. isc_throw(SignalSetError, "failed to restore handler for signal "
  118. << sig << ": " << errmsg);
  119. }
  120. return (signal_processed);
  121. }
  122. SignalSet::SignalSet(const int sig0) {
  123. // Copy static pointers to ensure they don't lose scope before we do.
  124. registered_signals_ = getRegisteredSignals();
  125. signal_states_ = getSignalStates();
  126. add(sig0);
  127. }
  128. SignalSet::SignalSet(const int sig0, const int sig1) {
  129. registered_signals_ = getRegisteredSignals();
  130. signal_states_ = getSignalStates();
  131. add(sig0);
  132. add(sig1);
  133. }
  134. SignalSet::SignalSet(const int sig0, const int sig1, const int sig2) {
  135. registered_signals_ = getRegisteredSignals();
  136. signal_states_ = getSignalStates();
  137. add(sig0);
  138. add(sig1);
  139. add(sig2);
  140. }
  141. SignalSet::~SignalSet() {
  142. // Set default signal handlers.
  143. try {
  144. clear();
  145. } catch (...) {
  146. // Not a good thing to throw from a destructor. in fact this should
  147. // not throw an exception because we just unregister the signals
  148. // that we have previously registered. So the signal codes are fine.
  149. }
  150. }
  151. void
  152. SignalSet::add(const int sig) {
  153. insert(sig);
  154. struct sigaction sa;
  155. memset(&sa, 0, sizeof(sa));
  156. sa.sa_handler = internalHandler;
  157. sigfillset(&sa.sa_mask);
  158. if (sigaction(sig, &sa, 0) < 0) {
  159. erase(sig);
  160. isc_throw(SignalSetError, "failed to register a signal handler for"
  161. " signal " << sig << ": " << strerror(errno));
  162. }
  163. }
  164. void
  165. SignalSet::clear() {
  166. // Iterate over a copy of the registered signal set because the
  167. // remove function is erasing the elements and we don't want to
  168. // erase the elements we are iterating over. This would cause
  169. // a segfault.
  170. std::set<int> all_signals = local_signals_;
  171. for (std::set<int>::const_iterator it = all_signals.begin();
  172. it != all_signals.end(); ++it) {
  173. remove(*it);
  174. }
  175. }
  176. int
  177. SignalSet::getNext() const {
  178. for (std::list<int>::iterator it = signal_states_->begin();
  179. it != signal_states_->end(); ++it) {
  180. if (local_signals_.find(*it) != local_signals_.end()) {
  181. return (*it);
  182. }
  183. }
  184. return (-1);
  185. }
  186. void
  187. SignalSet::erase(const int sig) {
  188. if (local_signals_.find(sig) == local_signals_.end()) {
  189. isc_throw(SignalSetError, "failed to unregister signal " << sig
  190. << " from a signal set: signal is not owned by the"
  191. " signal set");
  192. }
  193. // Remove globally registered signal.
  194. registered_signals_->erase(sig);
  195. // Remove unhandled signals from the queue.
  196. for (std::list<int>::iterator it = signal_states_->begin();
  197. it != signal_states_->end(); ++it) {
  198. if (*it == sig) {
  199. it = signal_states_->erase(it);
  200. }
  201. }
  202. // Remove locally registered signal.
  203. local_signals_.erase(sig);
  204. }
  205. void
  206. SignalSet::handleNext(SignalHandler signal_handler) {
  207. block();
  208. int signum = getNext();
  209. if (signum >= 0) {
  210. popNext();
  211. try {
  212. signal_handler(signum);
  213. } catch (...) {
  214. unblock();
  215. throw;
  216. }
  217. }
  218. unblock();
  219. }
  220. void
  221. SignalSet::insert(const int sig) {
  222. if ((registered_signals_->find(sig) != registered_signals_->end()) ||
  223. (local_signals_.find(sig) != local_signals_.end())) {
  224. isc_throw(SignalSetError, "attempt to register a duplicate signal "
  225. << sig);
  226. }
  227. registered_signals_->insert(sig);
  228. local_signals_.insert(sig);
  229. }
  230. void
  231. SignalSet::maskSignals(const int mask) const {
  232. sigset_t new_set;
  233. sigemptyset(&new_set);
  234. for (std::set<int>::const_iterator it = registered_signals_->begin();
  235. it != registered_signals_->end(); ++it) {
  236. sigaddset(&new_set, *it);
  237. }
  238. sigprocmask(mask, &new_set, 0);
  239. }
  240. void
  241. SignalSet::popNext() {
  242. for (std::list<int>::iterator it = signal_states_->begin();
  243. it != signal_states_->end(); ++it) {
  244. if (local_signals_.find(*it) != local_signals_.end()) {
  245. signal_states_->erase(it);
  246. return;
  247. }
  248. }
  249. }
  250. void
  251. SignalSet::remove(const int sig) {
  252. // Unregister only if we own this signal.
  253. if (local_signals_.find(sig) != local_signals_.end()) {
  254. struct sigaction sa;
  255. memset(&sa, 0, sizeof(sa));
  256. sa.sa_handler = SIG_DFL;
  257. sigfillset(&sa.sa_mask);
  258. if (sigaction(sig, &sa, 0) < 0) {
  259. isc_throw(SignalSetError, "unable to restore original signal"
  260. " handler for signal: " << sig);
  261. }
  262. erase(sig);
  263. } else {
  264. isc_throw(SignalSetError, "failed to unregister signal " << sig
  265. << ": this signal is not owned by the signal set");
  266. }
  267. }
  268. void
  269. SignalSet::setOnReceiptHandler(BoolSignalHandler handler) {
  270. onreceipt_handler_ = handler;
  271. }
  272. void
  273. SignalSet::clearOnReceiptHandler() {
  274. onreceipt_handler_ = BoolSignalHandler();
  275. }
  276. } // end of isc::util
  277. } // end of isc