sockcreator.py 8.8 KB

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