-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhttp.js
287 lines (229 loc) · 7.11 KB
/
http.js
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
'use strict';
var cache = require('simples/lib/cache'),
domain = require('domain'),
path = require('path'),
url = require('url'),
utils = require('simples/utils/utils');
// HTTP namespace
var http = exports;
// Link to the HTTP connection prototype constructor
http.connection = require('simples/lib/http/connection');
// Link to the HTTP form prototype constructor
http.form = require('simples/lib/http/form');
// Relations between HTTP methods and used REST verbs
http.verbs = {
'DELETE': 'del',
'GET': 'get',
'HEAD': 'get',
'POST': 'post',
'PUT': 'put'
};
// Manage the behavior of the route
http.applyRoute = function (connection, route) {
if (typeof route === 'function') {
route.call(connection.parent, connection);
} else if (typeof route === 'string') {
connection.render(route);
}
};
// Apply the routes for static files and directories
http.applyStaticRoute = function (connection, route) {
var directory = null,
extension = '',
host = connection.parent,
routes = host.routes,
stats = route.stats,
time = stats.mtime.toUTCString();
// Set the last modified time
connection.header('Last-Modified', time);
// Check if the resources were modified after last access
if (connection.headers['if-modified-since'] === time) {
connection.status(304).end();
} else if (stats.isDirectory()) {
// Prepare directory items
directory = Object.keys(route.files).map(function (name) {
return route.files[name];
});
// Apply the route for the directory
routes.serve.call(host, connection, directory);
} else {
// Prepare file extension
extension = path.extname(route.location).slice(1);
// Set the content type of the response
connection.type(extension).end(route.content);
}
};
// Listener for HTTP requests
http.connectionListener = function (host, request, response) {
var config = host.conf,
connection = new http.connection(host, request, response),
failed = false,
index = 0,
length = host.middlewares.length,
location = connection.path.substr(1),
route = null,
routes = host.routes,
verb = http.verbs[connection.method];
// Get middlewares one by one and execute them
function nextMiddleware(stop) {
if (index < length && !stop) {
setImmediate(host.middlewares[index], connection, nextMiddleware);
index++;
} else if (!stop) {
// Set the default keep alive timeout to 5 seconds
connection.keep(5000);
// Apply the route
if (utils.isObject(route)) {
http.applyStaticRoute(connection, route);
} else if (config.session.enabled) {
http.setSession(connection, function () {
http.applyRoute(connection, route);
});
} else if (route) {
http.applyRoute(connection, route);
}
}
}
// Find the fixed and dynamic route
if (verb) {
if (routes.fixed[verb][location]) {
route = routes.fixed[verb][location];
} else if (routes.fixed.all[location]) {
route = routes.fixed.all[location];
} else {
route = http.getDynamicRoute(connection, routes.dynamic, verb);
}
}
// Get static content if found
if (!route && verb === 'get' && http.refers(host, connection)) {
// Check for client side API file serve
if (location === 'simples.js') {
route = cache.client;
} else {
route = host.cache.read(location);
}
// Do not use routes to directories if no serve route is defined
if (route && route.stats.isDirectory() && !routes.serve) {
route = null;
}
}
// Check for errors 404 and 405
if (connection.method === 'OPTIONS') {
connection.status(204).end();
} else if (!verb) {
connection.status(405).header('Allow', 'DELETE,GET,HEAD,POST,PUT');
route = routes.error[405];
} else if (!route) {
connection.status(404);
route = routes.error[404];
}
// Process the connection inside a domain
domain.create().on('error', function (error) {
// Emit safely the error to the host
utils.emitError(host, error, true);
// Try to apply the route for error 500 or destroy the connection
if (!connection.started && !failed) {
failed = true;
connection.status(500);
this.bind(routes.error[500]).call(host, connection);
} else {
connection.destroy();
}
}).run(nextMiddleware);
};
// Create a render listener as a shortcut
http.createRenderListener = function (view, importer) {
return function (connection) {
connection.render(view, importer);
};
};
// Returns the dynamic route if found
http.getDynamicRoute = function (connection, routes, verb) {
var location = connection.path.substr(1),
index = 0,
keys = Object.keys(routes[verb]),
length = keys.length,
listener = null,
route = null;
// Search for the dynamic route in the verb's routes
while (!listener && index < length) {
// Select the current route
route = routes[verb][keys[index]];
// Check if the location matches the route pattern
if (route.pattern.test(location)) {
listener = route.listener;
}
// Get the next index
index++;
}
// Check if the listener was not found to switch to "all" verb
if (!listener) {
// Reset index, keys and the length
index = 0;
keys = Object.keys(routes.all);
length = keys.length;
// Search for the dynamic route in "all" verb's routes
while (!listener && index < length) {
// Select the current route
route = routes.all[keys[index]];
// Check if the location matches the route pattern
if (route.pattern.test(location)) {
listener = route.listener;
}
// Get the next index
index++;
}
}
// Populate connection parameters if the route is found
if (listener) {
location.match(route.pattern).slice(1).forEach(function (param, key) {
connection.params[route.keys[key]] = param;
});
}
return listener;
};
// Get an existent HTTP host or the main HTTP host
http.getHost = function (server, request) {
var hostname = (request.headers.host || '').replace(/:\d+$/, '');
return server.hosts[hostname] || server.hosts.main;
};
/*0.7 move this function to a middleware or remove*/
// Check if the referer header is accepted by the host
http.refers = function (host, connection) {
var hostname = url.parse(connection.headers.referer || '').hostname,
referers = host.conf.referers,
valid = true;
// Check if referer is found in the accepted referers list
if (referers.length && hostname !== connection.host) {
if (referers.indexOf(hostname) < 0) {
valid = referers[0] === '*';
} else {
valid = referers[0] !== '*';
}
}
return valid;
};
// Set the session cookies for HTTP connections
http.setSession = function (connection, callback) {
var host = connection.parent;
// Prepare session object
utils.getSession(host, connection, function (connection, session) {
var config = host.conf,
options = {};
// Prepare cookies options
options.expires = config.session.timeout;
options.path = '/';
options.httpOnly = true;
// Write the session cookies
connection.cookie('_session', session.id, options);
connection.cookie('_hash', session.hash, options);
// Link the session container to the connection
connection.session = session.container;
// Write the session to the store and remove its reference
connection.on('finish', function () {
utils.setSession(host, connection, session);
});
// End the session apply
callback();
});
};