Welcome to mirror list, hosted at ThFree Co, Russian Federation.

http.cc « src - github.com/nodejs/node.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b77a5dd15cd44c053aaf0f66bfcba3a3df60764d (plain)
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#include "node.h"
#include "http.h"
#include <http_parser.h>

#include <assert.h>
#include <stdio.h>
#include <strings.h>

#define ENCODING_SYMBOL             String::NewSymbol("encoding")

#define MESSAGE_HANDLER_SYMBOL      String::NewSymbol("messageHandler")

#define ON_MESSAGE_SYMBOL           String::NewSymbol("onMessage")
#define ON_PATH_SYMBOL              String::NewSymbol("onPath")
#define ON_QUERY_STRING_SYMBOL      String::NewSymbol("onQueryString")
#define ON_URI_SYMBOL               String::NewSymbol("onURI")
#define ON_FRAGMENT_SYMBOL          String::NewSymbol("onFragment")
#define ON_HEADER_FIELD_SYMBOL      String::NewSymbol("onHeaderField")
#define ON_HEADER_VALUE_SYMBOL      String::NewSymbol("onHeaderValue")
#define ON_HEADERS_COMPLETE_SYMBOL  String::NewSymbol("onHeadersComplete")
#define ON_BODY_SYMBOL              String::NewSymbol("onBody")
#define ON_MESSAGE_COMPLETE_SYMBOL  String::NewSymbol("onMessageComplete")

#define METHOD_SYMBOL               String::NewSymbol("method")
#define STATUS_CODE_SYMBOL          String::NewSymbol("statusCode")
#define HTTP_VERSION_SYMBOL         String::NewSymbol("httpVersion")
#define SHOULD_KEEP_ALIVE_SYMBOL    String::NewSymbol("should_keep_alive")

using namespace v8;
using namespace node;
using namespace std;

Persistent<FunctionTemplate> HTTPConnection::client_constructor_template;
Persistent<FunctionTemplate> HTTPConnection::server_constructor_template;

static Persistent<Object> http_module;

void
HTTPConnection::Initialize (Handle<Object> target)
{
  HandleScope scope;

  Local<FunctionTemplate> t = FunctionTemplate::New(NewClient);
  client_constructor_template = Persistent<FunctionTemplate>::New(t);
  client_constructor_template->Inherit(Connection::constructor_template);
  client_constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
  target->Set(String::NewSymbol("LowLevelClient"), client_constructor_template->GetFunction());

  t = FunctionTemplate::New(NewServer);
  server_constructor_template = Persistent<FunctionTemplate>::New(t);
  server_constructor_template->Inherit(Connection::constructor_template);
  server_constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
  target->Set(String::NewSymbol("ServerSideSocket"),
              server_constructor_template->GetFunction());
}

Handle<Value>
HTTPConnection::NewClient (const Arguments& args)
{
  HandleScope scope;

  HTTPConnection *connection = new HTTPConnection(args.This(), HTTP_RESPONSE);
  ObjectWrap::InformV8ofAllocation(connection);

  return args.This();
}

Handle<Value>
HTTPConnection::NewServer (const Arguments& args)
{
  HandleScope scope;

  HTTPConnection *connection = new HTTPConnection(args.This(), HTTP_REQUEST);
  ObjectWrap::InformV8ofAllocation(connection);

  return args.This();
}

void
HTTPConnection::OnReceive (const void *buf, size_t len)
{
  http_parser_execute(&parser_, static_cast<const char*>(buf), len);

  if (http_parser_has_error(&parser_))
    ForceClose();
}

int
HTTPConnection::on_message_begin (http_parser *parser)
{
  HTTPConnection *connection = static_cast<HTTPConnection*> (parser->data);
  HandleScope scope;

  Local<Value> on_message_v = connection->handle_->Get(ON_MESSAGE_SYMBOL);
  if (!on_message_v->IsFunction()) return -1;
  Handle<Function> on_message = Handle<Function>::Cast(on_message_v);

  TryCatch try_catch;
  Local<Object> message_handler = on_message->NewInstance();
  if (try_catch.HasCaught()) {
    FatalException(try_catch);
    return -1;
  }

  connection->handle_->SetHiddenValue(MESSAGE_HANDLER_SYMBOL, message_handler);
  return 0;
}

#define DEFINE_PARSER_CALLBACK(name, symbol)                                  \
int                                                                           \
HTTPConnection::name (http_parser *parser, const char *buf, size_t len)       \
{                                                                             \
  HandleScope scope;                                                          \
  HTTPConnection *connection = static_cast<HTTPConnection*> (parser->data);   \
  Local<Value> message_handler_v =                                            \
    connection->handle_->GetHiddenValue(MESSAGE_HANDLER_SYMBOL);              \
  if (message_handler_v->IsObject() == false)                                 \
    return -1;                                                                \
  Local<Object> message_handler = message_handler_v->ToObject();              \
  Local<Value> callback_v = message_handler->Get(symbol);                     \
  if (callback_v->IsFunction() == false)                                      \
    return 0;                                                                 \
  Local<Function> callback = Local<Function>::Cast(callback_v);               \
  TryCatch try_catch;                                                         \
  Local<Value> argv[1] = { String::New(buf, len) };                           \
  Local<Value> ret = callback->Call(message_handler, 1, argv);                \
  if (ret.IsEmpty()) {                                                        \
    FatalException(try_catch);                                               \
    return -2;                                                                \
  }                                                                           \
  if (ret->IsFalse()) return -3;                                              \
  return 0;                                                                   \
}

DEFINE_PARSER_CALLBACK(on_uri,          ON_URI_SYMBOL)
DEFINE_PARSER_CALLBACK(on_header_field, ON_HEADER_FIELD_SYMBOL)
DEFINE_PARSER_CALLBACK(on_header_value, ON_HEADER_VALUE_SYMBOL)

static inline Local<String>
GetMethod (int method)
{
  switch (method) {
    case HTTP_COPY:       return String::NewSymbol("COPY");
    case HTTP_DELETE:     return String::NewSymbol("DELETE");
    case HTTP_GET:        return String::NewSymbol("GET");
    case HTTP_HEAD:       return String::NewSymbol("HEAD");
    case HTTP_LOCK:       return String::NewSymbol("LOCK");
    case HTTP_MKCOL:      return String::NewSymbol("MKCOL");
    case HTTP_MOVE:       return String::NewSymbol("MOVE");
    case HTTP_OPTIONS:    return String::NewSymbol("OPTIONS");
    case HTTP_POST:       return String::NewSymbol("POST");
    case HTTP_PROPFIND:   return String::NewSymbol("PROPFIND");
    case HTTP_PROPPATCH:  return String::NewSymbol("PROPPATCH");
    case HTTP_PUT:        return String::NewSymbol("PUT");
    case HTTP_TRACE:      return String::NewSymbol("TRACE");
    case HTTP_UNLOCK:     return String::NewSymbol("UNLOCK");
  }
  return Local<String>();
}

int
HTTPConnection::on_headers_complete (http_parser *parser)
{
  HTTPConnection *connection = static_cast<HTTPConnection*> (parser->data);
  HandleScope scope;

  Local<Value> message_handler_v = 
    connection->handle_->GetHiddenValue(MESSAGE_HANDLER_SYMBOL);
  Local<Object> message_handler = message_handler_v->ToObject();

  // METHOD 
  if (connection->parser_.type == HTTP_REQUEST)
    message_handler->Set(METHOD_SYMBOL, GetMethod(connection->parser_.method));

  // STATUS 
  if (connection->parser_.type == HTTP_RESPONSE)
    message_handler->Set(STATUS_CODE_SYMBOL, 
        Integer::New(connection->parser_.status_code));

  // VERSION
  char version[10];
  snprintf( version
          , 10
          , "%d.%d"
          , connection->parser_.version_major
          , connection->parser_.version_minor
          ); 
  message_handler->Set(HTTP_VERSION_SYMBOL, String::New(version));

  // SHOULD KEEP ALIVE
  message_handler->Set( SHOULD_KEEP_ALIVE_SYMBOL
                      , http_parser_should_keep_alive(&connection->parser_) ? True() : False()
                      );


  Local<Value> on_headers_complete_v = message_handler->Get(ON_HEADERS_COMPLETE_SYMBOL);
  if (on_headers_complete_v->IsFunction() == false) return 0;

  Handle<Function> on_headers_complete = Handle<Function>::Cast(on_headers_complete_v);

  TryCatch try_catch;
  Local<Value> ret = on_headers_complete->Call(message_handler, 0, NULL);
  if (ret.IsEmpty()) {
    FatalException(try_catch);
    return -2;
  }
  if (ret->IsFalse()) return -3;

  return 0;
}

int
HTTPConnection::on_body (http_parser *parser, const char *buf, size_t len)
{
  assert(len != 0);

  HTTPConnection *connection = static_cast<HTTPConnection*> (parser->data);
  HandleScope scope;

  Local<Value> message_handler_v = 
    connection->handle_->GetHiddenValue(MESSAGE_HANDLER_SYMBOL);
  Local<Object> message_handler = message_handler_v->ToObject();

  Local<Value> on_body_v = message_handler->Get(ON_BODY_SYMBOL);
  if (on_body_v->IsFunction() == false) return 0;
  Handle<Function> on_body = Handle<Function>::Cast(on_body_v);

  Handle<Value> argv[1];
  // TODO each message should have their encoding. 
  // don't look at the conneciton for encoding
  if (connection->encoding_ == UTF8) {
    // utf8 encoding
    Handle<String> chunk = String::New((const char*)buf, len);
    argv[0] = chunk;

  } else {
    // raw encoding
    Local<Array> array = Array::New(len);
    for (size_t i = 0; i < len; i++) {
      char val = static_cast<const char*>(buf)[i];
      array->Set(Integer::New(i), Integer::New(val));
    }
    argv[0] = array;
  }

  TryCatch try_catch;
  Local<Value> ret = on_body->Call(message_handler, 1, argv);
  if (ret.IsEmpty()) {
    FatalException(try_catch);
    return -2;
  }
  if (ret->IsFalse()) return -3;

  return 0;
}

int
HTTPConnection::on_message_complete (http_parser *parser)
{
  HTTPConnection *connection = static_cast<HTTPConnection*> (parser->data);
  HandleScope scope;

  Local<Value> message_handler_v = 
    connection->handle_->GetHiddenValue(MESSAGE_HANDLER_SYMBOL);
  connection->handle_->DeleteHiddenValue(MESSAGE_HANDLER_SYMBOL);

  Local<Object> message_handler = message_handler_v->ToObject();

  Local<Value> on_msg_complete_v = message_handler->Get(ON_MESSAGE_COMPLETE_SYMBOL);
  if (on_msg_complete_v->IsFunction() == false) return 0;
  Handle<Function> on_msg_complete = Handle<Function>::Cast(on_msg_complete_v);

  TryCatch try_catch;
  Local<Value> ret = on_msg_complete->Call(message_handler, 0, NULL);
  if (ret.IsEmpty()) {
    FatalException(try_catch);
    return -2;
  }
  if (ret->IsFalse()) return -3;

  return 0;
}

HTTPConnection::HTTPConnection (Handle<Object> handle, enum http_parser_type type)
  : Connection(handle) 
{
  http_parser_init (&parser_, type);
  parser_.on_message_begin    = on_message_begin;
  parser_.on_uri              = on_uri;
  parser_.on_header_field     = on_header_field;
  parser_.on_header_value     = on_header_value;
  parser_.on_headers_complete = on_headers_complete;
  parser_.on_body             = on_body;
  parser_.on_message_complete = on_message_complete;
  parser_.data = this;
}

Persistent<FunctionTemplate> HTTPServer::constructor_template;

void
HTTPServer::Initialize (Handle<Object> target)
{
  HandleScope scope;

  Local<FunctionTemplate> t = FunctionTemplate::New(New);
  constructor_template = Persistent<FunctionTemplate>::New(t);
  constructor_template->Inherit(Acceptor::constructor_template);
  constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
  target->Set(String::NewSymbol("LowLevelServer"), constructor_template->GetFunction());
}

Handle<Value>
HTTPServer::New (const Arguments& args)
{
  HandleScope scope;

  if (args.Length() < 1 || args[0]->IsFunction() == false)
    return ThrowException(String::New("Must at give connection handler as the first argument"));

  Local<Function> protocol_class = Local<Function>::Cast(args[0]);
  Local<Object> options;

  if (args.Length() > 1 && args[1]->IsObject()) {
    options = args[1]->ToObject();
  } else {
    options = Object::New();
  }

  HTTPServer *s = new HTTPServer(args.This(), protocol_class, options);
  ObjectWrap::InformV8ofAllocation(s);

  return args.This();
}

Connection*
HTTPServer::OnConnection (struct sockaddr *addr, socklen_t len)
{
  HandleScope scope;
  
  Local<Function> connection_handler = GetConnectionHandler ();
  if (connection_handler.IsEmpty()) {
    Close();
    return NULL;
  }

  TryCatch try_catch;

  Local<Object> connection_handle =
    HTTPConnection::server_constructor_template->GetFunction()->NewInstance(0, NULL);

  if (connection_handle.IsEmpty()) {
    FatalException(try_catch);
    return NULL;
  }

  HTTPConnection *connection = NODE_UNWRAP(HTTPConnection, connection_handle);
  if (!connection) return NULL;

  connection->SetAcceptor(handle_);

  Handle<Value> argv[1] = { connection_handle };

  Local<Value> ret = connection_handler->Call(handle_, 1, argv);

  if (ret.IsEmpty())
    FatalException(try_catch);

  return connection;
}