mongoose.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # Copyright (c) 2004-2009 Sergey Lyubka
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. # THE SOFTWARE.
  20. #
  21. # $Id: mongoose.py 471 2009-08-30 14:30:21Z valenok $
  22. """
  23. This module provides python binding for the Mongoose web server.
  24. There are two classes defined:
  25. Connection: - wraps all functions that accept struct mg_connection pointer
  26. as first argument
  27. Mongoose: wraps all functions that accept struct mg_context pointer as
  28. first argument. All valid option names, settable via mg_set_option(),
  29. are settable/gettable as the attributes of the Mongoose object.
  30. In addition to those, two attributes are available:
  31. 'version': string, contains server version
  32. 'options': array of all known options.
  33. Creating Mongoose object automatically starts server, deleting object
  34. automatically stops it. There is no need to call mg_start() or mg_stop().
  35. """
  36. import ctypes
  37. import os
  38. MG_ERROR = 0
  39. MG_SUCCESS = 1
  40. MG_NOT_FOUND = 2
  41. MG_BUFFER_TOO_SMALL = 3
  42. class mg_header(ctypes.Structure):
  43. """A wrapper for struct mg_header."""
  44. _fields_ = [
  45. ('name', ctypes.c_char_p),
  46. ('value', ctypes.c_char_p),
  47. ]
  48. class mg_request_info(ctypes.Structure):
  49. """A wrapper for struct mg_request_info."""
  50. _fields_ = [
  51. ('request_method', ctypes.c_char_p),
  52. ('uri', ctypes.c_char_p),
  53. ('http_version', ctypes.c_char_p),
  54. ('query_string', ctypes.c_char_p),
  55. ('remote_user', ctypes.c_char_p),
  56. ('log_message', ctypes.c_char_p),
  57. ('remote_ip', ctypes.c_long),
  58. ('remote_port', ctypes.c_int),
  59. ('status_code', ctypes.c_int),
  60. ('is_ssl', ctypes.c_int),
  61. ('num_headers', ctypes.c_int),
  62. ('http_headers', mg_header * 64),
  63. ]
  64. mg_callback_t = ctypes.CFUNCTYPE(ctypes.c_int,
  65. ctypes.c_voidp,
  66. ctypes.POINTER(mg_request_info))
  67. class mg_config(ctypes.Structure):
  68. """A wrapper for struct mg_config."""
  69. _fields_ = [
  70. ('document_root', ctypes.c_char_p),
  71. ('index_files', ctypes.c_char_p),
  72. ('ssl_certificate', ctypes.c_char_p),
  73. ('listening_ports', ctypes.c_char_p),
  74. ('cgi_extensions', ctypes.c_char_p),
  75. ('cgi_interpreter', ctypes.c_char_p),
  76. ('cgi_environment', ctypes.c_char_p),
  77. ('ssi_extensions', ctypes.c_char_p),
  78. ('auth_domain', ctypes.c_char_p),
  79. ('protect', ctypes.c_char_p),
  80. ('global_passwords_file', ctypes.c_char_p),
  81. ('put_delete_passwords_file', ctypes.c_char_p),
  82. ('access_log_file', ctypes.c_char_p),
  83. ('error_log_file', ctypes.c_char_p),
  84. ('acl', ctypes.c_char_p),
  85. ('uid', ctypes.c_char_p),
  86. ('mime_types', ctypes.c_char_p),
  87. ('enable_directory_listing', ctypes.c_char_p),
  88. ('num_threads', ctypes.c_char_p),
  89. ('new_request_handler', mg_callback_t),
  90. ('http_error_handler', mg_callback_t),
  91. ('event_log_handler', mg_callback_t),
  92. ('ssl_password_handler', mg_callback_t),
  93. ]
  94. class Connection(object):
  95. """A wrapper class for all functions that take
  96. struct mg_connection * as the first argument."""
  97. def __init__(self, mongoose, connection):
  98. self.m = mongoose
  99. self.conn = ctypes.c_voidp(connection)
  100. def get_header(self, name):
  101. val = self.m.dll.mg_get_header(self.conn, name)
  102. return ctypes.c_char_p(val).value
  103. def get_var(self, buf, buflen, name):
  104. size = 1024
  105. value = ctypes.create_string_buffer(size)
  106. self.m.dll.mg_get_var.restype = ctypes.c_int
  107. result = self.m.dll.mg_get_var(buf, buflen, name, value, size)
  108. return result == MG_ERROR and None or value
  109. def get_qsvar(self, request_info, name):
  110. qs = request_info.query_string
  111. return qs and self.get_var(qs, len(qs), name) or None
  112. def printf(self, fmt, *args):
  113. val = self.m.dll.mg_printf(self.conn, fmt, *args)
  114. return ctypes.c_int(val).value
  115. def write(self, data):
  116. val = self.m.dll.mg_write(self.conn, data, len(data))
  117. return ctypes.c_int(val).value
  118. class Mongoose(object):
  119. """A wrapper class for Mongoose shared library."""
  120. def __init__(self, **kwargs):
  121. dll_extension = os.name == 'nt' and 'dll' or 'so'
  122. self.dll = ctypes.CDLL('_mongoose.%s' % dll_extension)
  123. self.callbacks = []
  124. self.config = mg_config(num_threads='5',
  125. enable_directory_listing='yes',
  126. listening_ports='8080',
  127. document_root='.',
  128. auth_domain='mydomain.com')
  129. for key, value in kwargs.iteritems():
  130. if key in ('new_request_handler',
  131. 'http_error_handler',
  132. 'event_log_handler',
  133. 'ssl_password_handler'):
  134. cb = self.MakeHandler(value)
  135. setattr(self.config, key, cb)
  136. else:
  137. setattr(self.config, key, str(value))
  138. self.dll.mg_start.restype = ctypes.c_void_p
  139. self.ctx = self.dll.mg_start(ctypes.byref(self.config))
  140. def __del__(self):
  141. """Destructor, stop Mongoose instance."""
  142. self.dll.mg_stop(ctypes.c_void_p(self.ctx))
  143. def MakeHandler(self, python_func):
  144. """Return C callback from given Python callback."""
  145. # Create a closure that will be called by the shared library.
  146. def func(connection, request_info):
  147. # Wrap connection pointer into the connection
  148. # object and call Python callback
  149. conn = Connection(self, connection)
  150. return python_func(conn, request_info.contents)
  151. # Convert the closure into C callable object
  152. c_func = mg_callback_t(func)
  153. c_func.restype = ctypes.c_int
  154. # Store created callback in the list, so it is kept alive
  155. # during context lifetime. Otherwise, python can garbage
  156. # collect it, and C code will crash trying to call it.
  157. self.callbacks.append(c_func)
  158. return c_func