mongoose.py 5.16 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#  Copyright (c) 2004-2009 Sergey Lyubka
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.
#
#  $Id: mongoose.py 471 2009-08-30 14:30:21Z valenok $

"""
This module provides python binding for the Mongoose web server.

There are two classes defined:

  Connection: - wraps all functions that accept struct mg_connection pointer
29
  as first argument.
30 31

  Mongoose: wraps all functions that accept struct mg_context pointer as
32
  first argument.
33 34 35 36 37 38 39 40 41 42

  Creating Mongoose object automatically starts server, deleting object
  automatically stops it. There is no need to call mg_start() or mg_stop().
"""


import ctypes
import os


43 44 45 46 47 48
NEW_REQUEST = 0
HTTP_ERROR = 1
EVENT_LOG = 2
INIT_SSL = 3


49
class mg_header(ctypes.Structure):
50 51 52 53 54
  """A wrapper for struct mg_header."""
  _fields_ = [
    ('name', ctypes.c_char_p),
    ('value', ctypes.c_char_p),
  ]
55 56 57


class mg_request_info(ctypes.Structure):
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  """A wrapper for struct mg_request_info."""
  _fields_ = [
    ('user_data', ctypes.c_char_p),
    ('request_method', ctypes.c_char_p),
    ('uri', ctypes.c_char_p),
    ('http_version', ctypes.c_char_p),
    ('query_string', ctypes.c_char_p),
    ('remote_user', ctypes.c_char_p),
    ('log_message', ctypes.c_char_p),
    ('remote_ip', ctypes.c_long),
    ('remote_port', ctypes.c_int),
    ('status_code', ctypes.c_int),
    ('is_ssl', ctypes.c_int),
    ('num_headers', ctypes.c_int),
    ('http_headers', mg_header * 64),
  ]
74 75


76
mg_callback_t = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p)
valenok's avatar
valenok committed
77 78


79
class Connection(object):
80 81
  """A wrapper class for all functions that take
  struct mg_connection * as the first argument."""
82

83 84 85
  def __init__(self, mongoose, connection):
    self.m = mongoose
    self.conn = ctypes.c_void_p(connection)
86
    self.info = self.m.dll.mg_get_request_info(self.conn).contents
87

88 89 90
  def get_header(self, name):
    val = self.m.dll.mg_get_header(self.conn, name)
    return ctypes.c_char_p(val).value
91

92 93 94 95 96
  def get_var(self, data, name):
    size = data and len(data) or 0
    buf = ctypes.create_string_buffer(size)
    n = self.m.dll.mg_get_var(data, size, name, buf, size)
    return n >= 0 and buf or None
97

98 99 100
  def printf(self, fmt, *args):
    val = self.m.dll.mg_printf(self.conn, fmt, *args)
    return ctypes.c_int(val).value
101

102 103 104
  def write(self, data):
    val = self.m.dll.mg_write(self.conn, data, len(data))
    return ctypes.c_int(val).value
105

106 107 108 109
  def read(self, size):
    buf = ctypes.create_string_buffer(size)
    n = self.m.dll.mg_read(self.conn, buf, size)
    return n <= 0 and None or buf[:n]
110

111 112
  def send_file(self, path):
    self.m.dll.mg_send_file(self.conn, path)
113

114 115

class Mongoose(object):
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  """A wrapper class for Mongoose shared library."""

  def __init__(self, callback, **kwargs):
    if os.name == 'nt':
      self.dll = ctypes.WinDLL('_mongoose.dll')
    else:
      self.dll = ctypes.CDLL('_mongoose.so')

    self.dll.mg_start.restype = ctypes.c_void_p
    self.dll.mg_modify_passwords_file.restype = ctypes.c_int
    self.dll.mg_read.restype = ctypes.c_int
    self.dll.mg_write.restype = ctypes.c_int
    self.dll.mg_printf.restype = ctypes.c_int
    self.dll.mg_get_header.restype = ctypes.c_char_p
    self.dll.mg_get_var.restype = ctypes.c_int
    self.dll.mg_get_cookie.restype = ctypes.c_int
    self.dll.mg_get_option.restype = ctypes.c_char_p
133
    self.dll.mg_get_request_info.restype = ctypes.POINTER(mg_request_info)
134 135 136

    if callback:
      # Create a closure that will be called by the  shared library.
137
      def func(event, connection):
138 139 140
        # Wrap connection pointer into the connection
        # object and call Python callback
        conn = Connection(self, connection)
141
        return callback(event, conn) and 1 or 0
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

      # Convert the closure into C callable object
      self.callback = mg_callback_t(func)
      self.callback.restype = ctypes.c_char_p
    else:
      self.callback = ctypes.c_void_p(0)

    args = [y for x in kwargs.items() for y in x] + [None]
    options = (ctypes.c_char_p * len(args))(*args)

    ret = self.dll.mg_start(self.callback, 0, options)
    self.ctx = ctypes.c_void_p(ret)

  def __del__(self):
    """Destructor, stop Mongoose instance."""
    self.dll.mg_stop(self.ctx)

  def get_option(self, name):
    return self.dll.mg_get_option(self.ctx, name)