sockcreator.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. #
  3. # Permission to use, copy, modify, and 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 INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. import socket
  16. import struct
  17. import os
  18. import copy
  19. import subprocess
  20. from isc.log_messages.bind10_messages import *
  21. from libutil_io_python import recv_fd
  22. logger = isc.log.Logger("boss")
  23. """
  24. Module that comunicates with the privileged socket creator (b10-sockcreator).
  25. """
  26. class CreatorError(Exception):
  27. """
  28. Exception for socket creator related errors.
  29. It has two members: fatal and errno and they are just holding the values
  30. passed to the __init__ function.
  31. """
  32. def __init__(self, message, fatal, errno=None):
  33. """
  34. Creates the exception. The message argument is the usual string.
  35. The fatal one tells if the error is fatal (eg. the creator crashed)
  36. and errno is the errno value returned from socket creator, if
  37. applicable.
  38. """
  39. Exception.__init__(self, message)
  40. self.fatal = fatal
  41. self.errno = errno
  42. class Parser:
  43. """
  44. This class knows the sockcreator language. It creates commands, sends them
  45. and receives the answers and parses them.
  46. It does not start it, the communication channel must be provided.
  47. In theory, anything here can throw a fatal CreatorError exception, but it
  48. happens only in case something like the creator process crashes. Any other
  49. occasions are mentioned explicitly.
  50. """
  51. def __init__(self, creator_socket):
  52. """
  53. Creates the parser. The creator_socket is socket to the socket creator
  54. process that will be used for communication. However, the object must
  55. have a read_fd() method to read the file descriptor. This slightly
  56. unusual trick with modifying an object is used to easy up testing.
  57. You can use WrappedSocket in production code to add the method to any
  58. ordinary socket.
  59. """
  60. self.__socket = creator_socket
  61. logger.info(BIND10_SOCKCREATOR_INIT)
  62. def terminate(self):
  63. """
  64. Asks the creator process to terminate and waits for it to close the
  65. socket. Does not return anything. Raises a CreatorError if there is
  66. still data on the socket, if there is an error closing the socket,
  67. or if the socket had already been closed.
  68. """
  69. if self.__socket is None:
  70. raise CreatorError('Terminated already', True)
  71. logger.info(BIND10_SOCKCREATOR_TERMINATE)
  72. try:
  73. self.__socket.sendall(b'T')
  74. # Wait for an EOF - it will return empty data
  75. eof = self.__socket.recv(1)
  76. if len(eof) != 0:
  77. raise CreatorError('Protocol error - data after terminated',
  78. True)
  79. self.__socket = None
  80. except socket.error as se:
  81. self.__socket = None
  82. raise CreatorError(str(se), True)
  83. def get_socket(self, address, port, socktype):
  84. """
  85. Asks the socket creator process to create a socket. Pass an address
  86. (the isc.net.IPaddr object), port number and socket type (either
  87. string "UDP", "TCP" or constant socket.SOCK_DGRAM or
  88. socket.SOCK_STREAM.
  89. Blocks until it is provided by the socket creator process (which
  90. should be fast, as it is on localhost) and returns the file descriptor
  91. number. It raises a CreatorError exception if the creation fails.
  92. """
  93. if self.__socket is None:
  94. raise CreatorError('Socket requested on terminated creator', True)
  95. # First, assemble the request from parts
  96. logger.info(BIND10_SOCKET_GET, address, port, socktype)
  97. data = b'S'
  98. if socktype == 'UDP' or socktype == socket.SOCK_DGRAM:
  99. data += b'U'
  100. elif socktype == 'TCP' or socktype == socket.SOCK_STREAM:
  101. data += b'T'
  102. else:
  103. raise ValueError('Unknown socket type: ' + str(socktype))
  104. if address.family == socket.AF_INET:
  105. data += b'4'
  106. elif address.family == socket.AF_INET6:
  107. data += b'6'
  108. else:
  109. raise ValueError('Unknown address family in address')
  110. data += struct.pack('!H', port)
  111. data += address.addr
  112. try:
  113. # Send the request
  114. self.__socket.sendall(data)
  115. answer = self.__socket.recv(1)
  116. if answer == b'S':
  117. # Success!
  118. result = self.__socket.read_fd()
  119. logger.info(BIND10_SOCKET_CREATED, result)
  120. return result
  121. elif answer == b'E':
  122. # There was an error, read the error as well
  123. error = self.__socket.recv(1)
  124. errno = struct.unpack('i',
  125. self.__read_all(len(struct.pack('i',
  126. 0))))
  127. if error == b'S':
  128. cause = 'socket'
  129. elif error == b'B':
  130. cause = 'bind'
  131. else:
  132. self.__socket = None
  133. logger.fatal(BIND10_SOCKCREATOR_BAD_CAUSE, error)
  134. raise CreatorError('Unknown error cause' + str(answer), True)
  135. logger.error(BIND10_SOCKET_ERROR, cause, errno[0],
  136. os.strerror(errno[0]))
  137. raise CreatorError('Error creating socket on ' + cause, False,
  138. errno[0])
  139. else:
  140. self.__socket = None
  141. logger.fatal(BIND10_SOCKCREATOR_BAD_RESPONSE, answer)
  142. raise CreatorError('Unknown response ' + str(answer), True)
  143. except socket.error as se:
  144. self.__socket = None
  145. logger.fatal(BIND10_SOCKCREATOR_TRANSPORT_ERROR, str(se))
  146. raise CreatorError(str(se), True)
  147. def __read_all(self, length):
  148. """
  149. Keeps reading until length data is read or EOF or error happens.
  150. EOF is considered error as well and throws a CreatorError.
  151. """
  152. result = b''
  153. while len(result) < length:
  154. data = self.__socket.recv(length - len(result))
  155. if len(data) == 0:
  156. self.__socket = None
  157. logger.fatal(BIND10_SOCKCREATOR_EOF)
  158. raise CreatorError('Unexpected EOF', True)
  159. result += data
  160. return result
  161. class WrappedSocket:
  162. """
  163. This class wraps a socket and adds a read_fd method, so it can be used
  164. for the Parser class conveniently. It simply copies all its guts into
  165. itself and implements the method.
  166. """
  167. def __init__(self, socket):
  168. # Copy whatever can be copied from the socket
  169. for name in dir(socket):
  170. if name not in ['__class__', '__weakref__']:
  171. setattr(self, name, getattr(socket, name))
  172. # Keep the socket, so we can prevent it from being garbage-collected
  173. # and closed before we are removed ourself
  174. self.__orig_socket = socket
  175. def read_fd(self):
  176. """
  177. Read the file descriptor from the socket.
  178. """
  179. return recv_fd(self.fileno())
  180. # FIXME: Any idea how to test this? Starting an external process doesn't sound
  181. # OK
  182. class Creator(Parser):
  183. """
  184. This starts the socket creator and allows asking for the sockets.
  185. Note: __process shouldn't be reset once created. See the note
  186. of the SockCreator class for details.
  187. """
  188. def __init__(self, path):
  189. (local, remote) = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
  190. # Popen does not like, for some reason, having the same socket for
  191. # stdin as well as stdout, so we dup it before passing it there.
  192. remote2 = socket.fromfd(remote.fileno(), socket.AF_UNIX,
  193. socket.SOCK_STREAM)
  194. env = copy.deepcopy(os.environ)
  195. env['PATH'] = path
  196. self.__process = subprocess.Popen(['b10-sockcreator'], env=env,
  197. stdin=remote.fileno(),
  198. stdout=remote2.fileno(),
  199. preexec_fn=self.__preexec_work)
  200. remote.close()
  201. remote2.close()
  202. Parser.__init__(self, WrappedSocket(local))
  203. def __preexec_work(self):
  204. """Function used before running a program that needs to run as a
  205. different user."""
  206. # Put us into a separate process group so we don't get
  207. # SIGINT signals on Ctrl-C (the boss will shut everthing down by
  208. # other means).
  209. os.setpgrp()
  210. def pid(self):
  211. return self.__process.pid
  212. def kill(self):
  213. logger.warn(BIND10_SOCKCREATOR_KILL)
  214. if self.__process is not None:
  215. self.__process.kill()