ry / ebb fork watch download tarball
public
Description: web server
Homepage: http://ebb.rubyforge.org
Clone URL: git://github.com/ry/ebb.git
Search Repo:
Ryan Dahl (author)
Tue Mar 11 05:11:56 -0700 2008
commit  c8641291900ff5ab9e2a027ffb73213f5440b58b
tree    782ffc8eb10b1ff6660b2af1b69cd07c44c1d62a
parent  4780e2c81b44bf1b4f96f2ce064e6416024888cc
ebb / src / ebb_python.c
100644 283 lines (232 sloc) 8.856 kb
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/* A python binding to the ebb web server
* Copyright (c) 2008 Ry Dahl. This software is released under the MIT
* License. See README file for details.
*/
#include <Python.h>
#include "ebb.h"
#include <ev.h>
#include <assert.h>
 
#define PyDict_SetStringString(dict, str1, str2) PyDict_SetItemString(dict, str1, PyString_FromString(str2))
#define ASCII_UPPER(ch) ('a' <= ch && ch <= 'z' ? ch - 'a' + 'A' : ch)
 
/* Why is there a global ebb_server variable instead of a wrapping it in a
* class? Because you would for no conceivable reason want to run more than
* one ebb_server per python VM instance.
*/
static ebb_server server;
struct ev_loop *loop;
static PyObject *application;
static PyObject *base_env;
static PyObject *global_http_prefix;
static PyObject *global_request_method;
static PyObject *global_request_uri;
static PyObject *global_fragment;
static PyObject *global_request_path;
static PyObject *global_query_string;
static PyObject *global_http_version;
static PyObject *global_request_body;
static PyObject *global_server_name;
static PyObject *global_server_port;
static PyObject *global_path_info;
static PyObject *global_content_length;
static PyObject *global_http_host;
 
/* A callable type called Client. __call__(status, response_headers)
* is the second argument to an appplcation
* Client.environ is the first argument.
*/
typedef struct {
  PyObject_HEAD
  ebb_client *client;
} py_client;
 
static PyObject *
py_start_response(py_client *self, PyObject *args, PyObject *kw);
 
 
static PyMethodDef client_methods[] =
  { {"start_response" , (PyCFunction)py_start_response, METH_VARARGS, NULL }
  // , {"write" , (PyCFunction)write, METH_VARARGS, NULL }
  , {NULL, NULL, 0, NULL}
  };
 
static PyTypeObject py_client_t =
  { ob_refcnt: 1
  , tp_name: "ebb.Client"
  , tp_doc: "a wrapper around ebb_client"
  , tp_basicsize: sizeof(py_client)
  , tp_flags: Py_TPFLAGS_DEFAULT
  , tp_methods: client_methods
  };
 
static PyObject *
py_start_response(py_client *self, PyObject *args, PyObject *kw)
{
  PyObject *response_headers;
  char *status_string;
  int status;
  
  if(!PyArg_ParseTuple(args, "sO", &status_string, &response_headers))
    return NULL;
  
  /* do this goofy split(' ') operation. wsgi is such a terrible api. */
  status = 100 * (status_string[0] - '0')
          + 10 * (status_string[1] - '0')
           + 1 * (status_string[2] - '0');
  assert(0 <= status && status < 1000);
  
  ebb_client_write_status(self->client, status, status_string+4);
  
  PyObject *iterator = PyObject_GetIter(response_headers);
  PyObject *header_pair;
  char *field, *value;
  while(header_pair = PyIter_Next(iterator)) {
    if(!PyArg_ParseTuple(header_pair, "ss", &field, &value))
      return NULL;
    ebb_client_write_header(self->client, field, value);
    Py_DECREF(header_pair);
  }
  ebb_client_write(self->client, "\r\n", 2);
  
  Py_RETURN_NONE;
}
 
static PyObject* env_field(struct ebb_env_item *item)
{
  PyObject* f = NULL;
  int i;
  
  switch(item->type) {
    case EBB_FIELD_VALUE_PAIR:
      f = PyString_FromStringAndSize(NULL, PyString_GET_SIZE(global_http_prefix) + item->field_length);
      memcpy( PyString_AS_STRING(f)
            , PyString_AS_STRING(global_http_prefix)
            , PyString_GET_SIZE(global_http_prefix)
            );
      for(i = 0; i < item->field_length; i++) {
        char *ch = PyString_AS_STRING(f) + PyString_GET_SIZE(global_http_prefix) + i;
        *ch = item->field[i] == '-' ? '_' : ASCII_UPPER(item->field[i]);
      }
      break;
    case EBB_REQUEST_METHOD: f = global_request_method; break;
    case EBB_REQUEST_URI: f = global_request_uri; break;
    case EBB_FRAGMENT: f = global_fragment; break;
    case EBB_REQUEST_PATH: f = global_request_path; break;
    case EBB_QUERY_STRING: f = global_query_string; break;
    case EBB_HTTP_VERSION: f = global_http_version; break;
    case EBB_SERVER_NAME: f = global_server_name; break;
    case EBB_SERVER_PORT: f = global_server_port; break;
    case EBB_CONTENT_LENGTH: f = global_content_length; break;
    default: assert(FALSE);
  }
  Py_INCREF(f);
  return f;
}
 
 
static PyObject* env_value(struct ebb_env_item *item)
{
  if(item->value_length > 0)
    return PyString_FromStringAndSize(item->value, item->value_length);
  else
    return Py_None; // XXX need to increase ref count? :/
}
 
 
static PyObject* py_client_env(ebb_client *client)
{
  PyObject *env = PyDict_Copy(base_env);
  int i;
  
  for(i=0; i < client->env_size; i++) {
    PyDict_SetItem(env, env_field(&client->env[i])
                      , env_value(&client->env[i])
                      );
  }
  // PyDict_SetStringString(hash, global_path_info, rb_hash_aref(hash, global_request_path));
  
  return env;
}
 
static py_client* py_client_new(ebb_client *client)
{
  py_client *self = PyObject_New(py_client, &py_client_t);
  if(self == NULL) return NULL;
  self->client = client;
  
  //if(0 < PyObject_SetAttrString((PyObject*)self, "environ", py_client_env(client)))
  // return NULL;
  
  return self;
}
 
const char *test_response = "test_response defined in ebb_python.c\r\n";
 
void request_cb(ebb_client *client, void *ignore)
{
  
  PyObject *environ, *start_response;
  
  py_client *pclient = py_client_new(client);
  assert(pclient != NULL);
  //environ = PyObject_GetAttrString((PyObject*)pclient, "environ");
  environ = py_client_env(client);
  assert(environ != NULL);
  
  start_response = PyObject_GetAttrString((PyObject*)pclient, "start_response");
  assert(start_response != NULL);
  
  PyObject *arglist = Py_BuildValue("OO", environ, start_response);
  assert(arglist != NULL);
  assert(application != NULL);
  PyObject *body = PyEval_CallObject(application, arglist);
  assert(body != NULL);
  
  Py_DECREF(arglist);
  Py_DECREF(environ);
  
  
  PyObject *iterator = PyObject_GetIter(body);
  PyObject *body_item;
  while (body_item = PyIter_Next(iterator)) {
    char *body_string = PyString_AsString(body_item);
    int body_length = PyString_Size(body_item);
    /* Todo support streaming! */
    ebb_client_write(pclient->client, body_string, body_length);
    Py_DECREF(body_item);
  }
  
  ebb_client_finished(client);
  
  Py_DECREF(pclient);
}
 
 
static PyObject *start_server(PyObject *self, PyObject *args)
{
  PyObject *application_temp;
  int port;
  
  if(!PyArg_ParseTuple(args, "Oi", &application_temp, &port))
    return NULL;
  if(!PyCallable_Check(application_temp)) {
    PyErr_SetString(PyExc_TypeError, "parameter must be callable");
    return NULL;
  }
  Py_XINCREF(application_temp); /* Add a reference to new callback */
  Py_XDECREF(application); /* Dispose of previous callback */
  application = application_temp; /* Remember new callback */
  
  loop = ev_default_loop(0);
  ebb_server_init(&server, loop, request_cb, NULL);
  ebb_server_listen_on_port(&server, port);
  
  //ev_loop(loop, EVLOOP_ONESHOT);
  ev_loop(loop, 0);
  
  Py_XDECREF(application);
  
  Py_RETURN_NONE;
}
 
static PyObject *stop_server(PyObject *self)
{
  Py_RETURN_NONE;
}
 
 
static PyMethodDef ebb_module_methods[] =
  { {"start_server" , (PyCFunction)start_server, METH_VARARGS, NULL }
  , {"stop_server" , (PyCFunction)stop_server, METH_NOARGS, NULL }
  , {NULL, NULL, 0, NULL}
  };
 
PyMODINIT_FUNC initebb(void)
{
  PyObject *m = Py_InitModule("ebb", ebb_module_methods);
  
  base_env = PyDict_New();
  PyDict_SetStringString(base_env, "SCRIPT_NAME", "");
  PyDict_SetStringString(base_env, "SERVER_SOFTWARE", "Ebb 0.0.4");
  PyDict_SetStringString(base_env, "SERVER_PROTOCOL", "HTTP/1.1");
  PyDict_SetStringString(base_env, "wsgi.url_scheme", "http");
  PyDict_SetItemString(base_env, "wsgi.multithread", Py_False);
  PyDict_SetItemString(base_env, "wsgi.multiprocess", Py_False);
  PyDict_SetItemString(base_env, "wsgi.run_once", Py_False);
  //PyDict_SetItemString(base_env, "wsgi.version", (0,1));
  //PyDict_SetItemString(base_env, "wsgi.errors", STDERR);
  
  
  /* StartResponse */
  py_client_t.tp_new = PyType_GenericNew;
  if (PyType_Ready(&py_client_t) < 0) return;
  Py_INCREF(&py_client_t);
  PyModule_AddObject(m, "Client", (PyObject *)&py_client_t);
#define DEF_GLOBAL(N, val) global_##N = PyString_FromString(val)
  DEF_GLOBAL(http_prefix, "HTTP_");
  DEF_GLOBAL(request_method, "REQUEST_METHOD");
  DEF_GLOBAL(request_uri, "REQUEST_URI");
  DEF_GLOBAL(fragment, "FRAGMENT");
  DEF_GLOBAL(request_path, "REQUEST_PATH");
  DEF_GLOBAL(query_string, "QUERY_STRING");
  DEF_GLOBAL(http_version, "HTTP_VERSION");
  DEF_GLOBAL(request_body, "REQUEST_BODY");
  DEF_GLOBAL(server_name, "SERVER_NAME");
  DEF_GLOBAL(server_port, "SERVER_PORT");
  DEF_GLOBAL(path_info, "PATH_INFO");
  DEF_GLOBAL(content_length, "CONTENT_LENGTH");
  DEF_GLOBAL(http_host, "HTTP_HOST");
  
  ebb_server_init(&server, loop, request_cb, NULL);
}