mirror of
https://github.com/cesanta/mongoose.git
synced 2026-10-29 12:41:03 +00:00
Initial import - converting from Subversion.
This commit is contained in:
commit
a69a2da39d
46 files changed
+7901
No files matched your search
@@ -0,0 +1,52 @@
|
||||
// This is C# example on how to use Mongoose embeddable web server,
|
||||
// http://code.google.com/p/mongoose
|
||||
//
|
||||
// Before using the mongoose module, make sure that Mongoose shared library is
|
||||
// built and present in the current (or system library) directory
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public class Program {
|
||||
|
||||
// This function is called when user types in his browser http://127.0.0.1:8080/foo
|
||||
static private void UriHandler(MongooseConnection conn, MongooseRequestInfo ri) {
|
||||
conn.write("HTTP/1.1 200 OK\r\n\r\n");
|
||||
conn.write("Hello from C#!\n");
|
||||
conn.write("Your user-agent is: " + conn.get_header("User-Agent") + "\n");
|
||||
}
|
||||
|
||||
static private void UriDumpInfo(MongooseConnection conn, MongooseRequestInfo ri)
|
||||
{
|
||||
conn.write("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
|
||||
conn.write("<html><body><head>Calling Info</head>");
|
||||
conn.write("<p>Request: " + ri.request_method + "</p>");
|
||||
conn.write("<p>URI: " + ri.uri + "</p>");
|
||||
conn.write("<p>Query: " + ri.query_string + "</p>");
|
||||
if (ri.post_data_len > 0) conn.write("<p>Post(" + ri.post_data_len + ")[@" + ri.post_data + "]: '" + Marshal.PtrToStringAnsi(ri.post_data) + "'</p>");
|
||||
conn.write("<p>User:" + ri.remote_user + "</p>");
|
||||
conn.write("<p>IP: " + ri.remote_ip + "</p>");
|
||||
conn.write("<p>HTTP: " + ri.http_version + "</p>");
|
||||
conn.write("<p>Port: " + ri.remote_port + "</p>");
|
||||
conn.write("<p>NUM Headers: " + ri.num_headers + "</p>");
|
||||
for (int i = 0; i < Math.Min(64, ri.num_headers); i++)
|
||||
{
|
||||
conn.write("<p>" + i + ":" + Marshal.PtrToStringAnsi(ri.http_headers[i].name)
|
||||
+ ":" + Marshal.PtrToStringAnsi(ri.http_headers[i].value) + "</p>");
|
||||
}
|
||||
conn.write("</body></html>");
|
||||
}
|
||||
|
||||
static void Main() {
|
||||
Mongoose web_server = new Mongoose();
|
||||
|
||||
// Set options and /foo URI handler
|
||||
web_server.set_option("ports", "8080");
|
||||
web_server.set_option("root", "c:\\");
|
||||
web_server.set_uri_callback("/foo", new MongooseCallback(UriHandler));
|
||||
web_server.set_uri_callback("/dumpinfo", new MongooseCallback(UriDumpInfo));
|
||||
|
||||
// Serve requests until user presses "enter" on a keyboard
|
||||
Console.ReadLine();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// 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.cs 472 2009-08-30 22:40:29Z spsone1 $
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)] public struct MongooseHeader {
|
||||
public IntPtr name; // Using IntPtr here because if we use strings here,
|
||||
public IntPtr value; // it won't be properly marshalled.
|
||||
};
|
||||
|
||||
// This is "struct mg_request_info" from mongoose.h header file
|
||||
[StructLayout(LayoutKind.Sequential)] public struct MongooseRequestInfo {
|
||||
public string request_method;
|
||||
public string uri;
|
||||
public string http_version;
|
||||
public string query_string;
|
||||
public IntPtr post_data;
|
||||
public string remote_user;
|
||||
public int remote_ip; //int to match the 32bit declaration in c
|
||||
public int remote_port;
|
||||
public int post_data_len;
|
||||
public int status_code;
|
||||
public int num_headers;
|
||||
[MarshalAs(UnmanagedType.ByValArray,SizeConst=64)] public MongooseHeader[] http_headers;
|
||||
};
|
||||
|
||||
// This is a delegate for mg_callback_t from mongoose.h header file
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate void MongooseCallback2(IntPtr conn, ref MongooseRequestInfo ri, IntPtr user_data);
|
||||
|
||||
// This is a delegate to be used by the application
|
||||
public delegate void MongooseCallback(MongooseConnection conn, MongooseRequestInfo ri);
|
||||
|
||||
public class Mongoose {
|
||||
public string version;
|
||||
private IntPtr ctx;
|
||||
//These two events are here to store a ref to the callbacks while they are over in unmanaged code.
|
||||
private event MongooseCallback2 delegates2;
|
||||
private event MongooseCallback delegates1;
|
||||
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern IntPtr mg_start();
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern void mg_stop(IntPtr ctx);
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern string mg_version();
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern int mg_set_option(IntPtr ctx, string name, string value);
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern string mg_get_option(IntPtr ctx, string name);
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern void mg_set_uri_callback(IntPtr ctx, string uri_regex, MulticastDelegate func, IntPtr data);
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern void mg_set_log_callback(IntPtr ctx, MulticastDelegate func);
|
||||
|
||||
public Mongoose() {
|
||||
ctx = mg_start();
|
||||
version = mg_version();
|
||||
}
|
||||
|
||||
~Mongoose() {
|
||||
mg_stop(this.ctx);
|
||||
this.ctx = IntPtr.Zero;
|
||||
}
|
||||
|
||||
public int set_option(string option_name, string option_value) {
|
||||
return mg_set_option(this.ctx, option_name, option_value);
|
||||
}
|
||||
|
||||
public string get_option(string option_name) {
|
||||
return mg_get_option(this.ctx, option_name);
|
||||
}
|
||||
|
||||
public void set_uri_callback(string uri_regex, MongooseCallback func) {
|
||||
// Build a closure around user function. Initialize connection object there which wraps
|
||||
// mg_write() and other useful methods, and then call user specified handler.
|
||||
MongooseCallback2 callback = delegate(IntPtr conn, ref MongooseRequestInfo ri, IntPtr user_data) {
|
||||
MongooseConnection connection = new MongooseConnection(conn, this);
|
||||
func(connection, ri);
|
||||
};
|
||||
// store a reference to the callback so it won't be GC'ed while its over in unmanged code
|
||||
delegates2 += callback;
|
||||
mg_set_uri_callback(this.ctx, uri_regex, callback, IntPtr.Zero);
|
||||
}
|
||||
|
||||
public void set_log_callback(MongooseCallback func) {
|
||||
delegates1 += func;
|
||||
mg_set_log_callback(this.ctx, func);
|
||||
}
|
||||
}
|
||||
|
||||
public class MongooseConnection {
|
||||
public Mongoose mongoose;
|
||||
private IntPtr conn;
|
||||
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern string mg_get_header(IntPtr ctx, string name);
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern string mg_get_var(IntPtr ctx, string name);
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern void mg_free(IntPtr ptr);
|
||||
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] public static extern int mg_write(IntPtr conn, string data, int length);
|
||||
|
||||
public MongooseConnection(IntPtr conn_, Mongoose mongoose_) {
|
||||
mongoose = mongoose_;
|
||||
conn = conn_;
|
||||
}
|
||||
|
||||
public string get_header(string header_name) {
|
||||
return mg_get_header(this.conn, header_name);
|
||||
}
|
||||
|
||||
public string get_var(string header_name) {
|
||||
string s = mg_get_var(this.conn, header_name);
|
||||
string copy = "" + s;
|
||||
mg_free(Marshal.StringToHGlobalAnsi(s));
|
||||
return copy;
|
||||
}
|
||||
|
||||
public int write(string data) {
|
||||
return mg_write(this.conn, data, data.Length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# This is Python example on how to use Mongoose embeddable web server,
|
||||
# http://code.google.com/p/mongoose
|
||||
#
|
||||
# Before using the mongoose module, make sure that Mongoose shared library is
|
||||
# built and present in the current (or system library) directory
|
||||
|
||||
import mongoose
|
||||
import sys
|
||||
|
||||
# This function is a "/foo" URI handler: it will be called each time
|
||||
# HTTP request to http://this_machine:8080/foo made.
|
||||
# It displays some request information.
|
||||
def uri_handler(conn, info, data):
|
||||
conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
|
||||
conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
|
||||
conn.printf('%s %s\n', info.request_method, info.uri)
|
||||
conn.printf('my_var: %s\n', conn.get_var('my_var') or '<not set>')
|
||||
conn.printf('HEADERS: \n')
|
||||
for header in info.http_headers[:info.num_headers]:
|
||||
conn.printf(' %s: %s\n', header.name, header.value)
|
||||
|
||||
# This function is 404 error handler: it is called each time requested
|
||||
# document is not found by the server.
|
||||
def error_404_handler(conn, info, data):
|
||||
conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
|
||||
conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
|
||||
conn.printf('Document %s not found!\n', info.uri)
|
||||
|
||||
# Create mongoose object, and register '/foo' URI handler
|
||||
# List of options may be specified in the contructor
|
||||
server = mongoose.Mongoose(root='/tmp', ports='8080')
|
||||
|
||||
# Register custom URI and 404 error handler
|
||||
server.set_uri_callback('/foo', uri_handler, 0)
|
||||
server.set_error_callback(404, error_404_handler, 0)
|
||||
|
||||
# Any option may be set later on by setting an attribute of the server object
|
||||
server.ports = '8080,8081' # Listen on port 8081 in addition to 8080
|
||||
|
||||
# Mongoose options can be retrieved by asking an attribute
|
||||
print 'Starting Mongoose %s on port(s) %s ' % (server.version, server.ports)
|
||||
print 'CGI extensions: %s' % server.cgi_ext
|
||||
|
||||
# Serve connections until 'enter' key is pressed on a console
|
||||
sys.stdin.read(1)
|
||||
|
||||
# Deleting server object stops all serving threads
|
||||
print 'Stopping server.'
|
||||
del server
|
||||
@@ -0,0 +1,177 @@
|
||||
# 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
|
||||
as first argument
|
||||
|
||||
Mongoose: wraps all functions that accept struct mg_context pointer as
|
||||
first argument. All valid option names, settable via mg_set_option(),
|
||||
are settable/gettable as the attributes of the Mongoose object.
|
||||
In addition to those, two attributes are available:
|
||||
'version': string, contains server version
|
||||
'options': array of all known options.
|
||||
|
||||
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
|
||||
|
||||
|
||||
class mg_header(ctypes.Structure):
|
||||
"""A wrapper for struct mg_header."""
|
||||
_fields_ = [
|
||||
('name', ctypes.c_char_p),
|
||||
('value', ctypes.c_char_p),
|
||||
]
|
||||
|
||||
|
||||
class mg_request_info(ctypes.Structure):
|
||||
"""A wrapper for struct mg_request_info."""
|
||||
_fields_ = [
|
||||
('request_method', ctypes.c_char_p),
|
||||
('uri', ctypes.c_char_p),
|
||||
('http_version', ctypes.c_char_p),
|
||||
('query_string', ctypes.c_char_p),
|
||||
('post_data', ctypes.c_char_p),
|
||||
('remote_user', ctypes.c_char_p),
|
||||
('remote_ip', ctypes.c_long),
|
||||
('remote_port', ctypes.c_int),
|
||||
('post_data_len', ctypes.c_int),
|
||||
('status_code', ctypes.c_int),
|
||||
('num_headers', ctypes.c_int),
|
||||
('http_headers', mg_header * 64),
|
||||
]
|
||||
|
||||
|
||||
class Connection(object):
|
||||
"""A wrapper class for all functions that take
|
||||
struct mg_connection * as the first argument."""
|
||||
|
||||
def __init__(self, mongoose, connection):
|
||||
self.m = mongoose
|
||||
self.conn = connection
|
||||
|
||||
def get_header(self, name):
|
||||
val = self.m.dll.mg_get_header(self.conn, name)
|
||||
return ctypes.c_char_p(val).value
|
||||
|
||||
def get_var(self, name):
|
||||
var = None
|
||||
pointer = self.m.dll.mg_get_var(self.conn, name)
|
||||
if pointer:
|
||||
# Make a copy and free() the returned pointer
|
||||
var = '' + ctypes.c_char_p(pointer).value
|
||||
self.m.dll.mg_free(pointer)
|
||||
return var
|
||||
|
||||
def printf(self, fmt, *args):
|
||||
val = self.m.dll.mg_printf(self.conn, fmt, *args)
|
||||
return ctypes.c_int(val).value
|
||||
|
||||
def write(self, data):
|
||||
val = self.m.dll.mg_write(self.conn, data, len(data))
|
||||
return ctypes.c_int(val).value
|
||||
|
||||
|
||||
class Mongoose(object):
|
||||
"""A wrapper class for Mongoose shared library."""
|
||||
|
||||
# Exceptions for __setattr__ and __getattr__: these attributes
|
||||
# must not be treated as Mongoose options
|
||||
_private = ('dll', 'ctx', 'version', 'callbacks')
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
dll_extension = os.name == 'nt' and 'dll' or 'so'
|
||||
self.dll = ctypes.CDLL('_mongoose.%s' % dll_extension)
|
||||
start = self.dll.mg_start
|
||||
self.ctx = ctypes.c_voidp(self.dll.mg_start()).value
|
||||
self.version = ctypes.c_char_p(self.dll.mg_version()).value
|
||||
self.callbacks = []
|
||||
for name, value in kwargs.iteritems():
|
||||
self.__setattr__(name, value)
|
||||
|
||||
def __setattr__(self, name, value):
|
||||
"""Set Mongoose option. Raises ValueError in option not set."""
|
||||
if name in self._private:
|
||||
object.__setattr__(self, name, value)
|
||||
else:
|
||||
code = self.dll.mg_set_option(self.ctx, name, value)
|
||||
if code != 1:
|
||||
raise ValueError('Cannot set option [%s] '
|
||||
'to [%s]' % (name, value))
|
||||
|
||||
def __getattr__(self, name):
|
||||
"""Get Mongoose option."""
|
||||
if name in self._private:
|
||||
return object.__getattr__(self, name)
|
||||
else:
|
||||
val = self.dll.mg_get_option(self.ctx, name)
|
||||
return ctypes.c_char_p(val).value
|
||||
|
||||
def __del__(self):
|
||||
"""Destructor, stop Mongoose instance."""
|
||||
self.dll.mg_stop(self.ctx)
|
||||
|
||||
def _make_c_callback(self, python_callback):
|
||||
"""Return C callback from given Python callback."""
|
||||
|
||||
# Create a closure that will be called by the shared library.
|
||||
def _cb(connection, request_info, user_data):
|
||||
# Wrap connection pointer into the connection
|
||||
# object and call Python callback
|
||||
conn = Connection(self, connection)
|
||||
python_callback(conn, request_info.contents, user_data)
|
||||
|
||||
# Convert the closure into C callable object
|
||||
c_callback = ctypes.CFUNCTYPE(ctypes.c_voidp, ctypes.c_voidp,
|
||||
ctypes.POINTER(mg_request_info), ctypes.c_voidp)(_cb)
|
||||
|
||||
# Store created callback in the list, so it is kept alive
|
||||
# during context lifetime. Otherwise, python can garbage
|
||||
# collect it, and C code will crash trying to call it.
|
||||
self.callbacks.append(c_callback)
|
||||
|
||||
return c_callback
|
||||
|
||||
def set_uri_callback(self, uri_regex, python_callback, user_data):
|
||||
self.dll.mg_set_uri_callback(self.ctx, uri_regex,
|
||||
self._make_c_callback(python_callback), user_data)
|
||||
|
||||
def set_auth_callback(self, uri_regex, python_callback, user_data):
|
||||
self.dll.mg_set_auth_callback(self.ctx, uri_regex,
|
||||
self._make_c_callback(python_callback), user_data)
|
||||
|
||||
def set_error_callback(self, error_code, python_callback, user_data):
|
||||
self.dll.mg_set_error_callback(self.ctx, error_code,
|
||||
self._make_c_callback(python_callback), user_data)
|
||||
|
||||
def set_log_callback(self, python_callback):
|
||||
self.dll.mg_set_log_callback(self.ctx,
|
||||
self._make_c_callback(python_callback))
|
||||
Reference in new issue
Block a user