-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
274 lines (228 loc) · 9.29 KB
/
index.js
File metadata and controls
274 lines (228 loc) · 9.29 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
module.exports = function fastcgi(newOptions) {
var url = require('url')
, fs = require('fs')
, path = require("path")
, http = require("http")
, net = require("net")
, sys = require("sys")
, fastcgi = require("fastcgi-parser");
var debug = 0 ? console : { log: function(){}, dir: function(){} };
var FCGI_RESPONDER = fastcgi.constants.role.FCGI_RESPONDER;
var FCGI_BEGIN = fastcgi.constants.record.FCGI_BEGIN;
var FCGI_STDIN = fastcgi.constants.record.FCGI_STDIN;
var FCGI_STDOUT = fastcgi.constants.record.FCGI_STDOUT;
var FCGI_PARAMS = fastcgi.constants.record.FCGI_PARAMS;
var FCGI_END = fastcgi.constants.record.FCGI_END;
/**
* Make headers for FPM
*
* Some headers have to be modified to fit the FPM
* handler and some others don't. For instance, the Content-Type
* header, when received, has to be made upper-case and the
* hyphen has to be made into an underscore. However, the Accept
* header has to be made uppercase, hyphens turned into underscores
* and the string "HTTP_" has to be appended to the header.
*
* @param array headers An array of existing user headers from Node.js
* @param array params An array of pre-built headers set in serveFpm
*
* @return array An array of complete headers.
*/
function makeHeaders(headers, params) {
if (headers.length <= 0) {
return params;
}
for (var prop in headers) {
var head = headers[prop];
prop = prop.replace(/-/, '_').toUpperCase();
if (prop.indexOf('CONTENT_') < 0) {
// Quick hack for PHP, might be more or less headers.
prop = 'HTTP_' + prop;
}
params[params.length] = [prop, head]
}
return params;
};
/**
* Interact with FPM
*
* This function is used to interact with the FastCGI protocol
* using net.Stream and the fastcgi module.
*
* We pass the request, the response, some params and some options
* that we then use to serve the response to our client.
*
* @param object Request The HTTP Request object.
* @param object Response The HTTP Response object to use.
* @param array Params A list of parameters to pass to FCGI
* @param array options A list of options like the port of the fpm server.
*
* @return void
*/
function server(request, response, params, options, next) {
var connection = new net.Stream();
connection.setNoDelay(true);
var writer = null;
var parser = null;
var header = {
"version": fastcgi.constants.version,
"type": FCGI_BEGIN,
"recordId": 0,
"contentLength": 0,
"paddingLength": 0
};
var begin = {
"role": FCGI_RESPONDER,
"flags": fastcgi.constants.keepalive.OFF
};
var collectedStdin = [], noMoreData = false;
function endRequest() {
if(writer) {
header.type = FCGI_STDIN;
header.contentLength = 0;
header.paddingLength = 0;
writer.writeHeader(header)
connection.write(writer.tobuffer());
connection.end();
} else {
noMoreData = true;
}
}
function sendRequest (connection) {
header.type = FCGI_BEGIN;
header.contentLength = 8;
writer.writeHeader(header);
writer.writeBegin(begin);
connection.write(writer.tobuffer());
header.type = FCGI_PARAMS;
header.contentLength = fastcgi.getParamLength(params);
writer.writeHeader(header);
writer.writeParams(params);
connection.write(writer.tobuffer());
header.type = FCGI_PARAMS;
header.contentLength = 0;
writer.writeHeader(header);
connection.write(writer.tobuffer());
// header.type = FCGI_STDOUT;
// writer.writeHeader(header);
// connection.write(writer.tobuffer());
if((request.method != 'PUT' && request.method != 'POST')) {
endRequest()
} else {
for(var j = 0; j < collectedStdin.length; ++j) {
header.type = FCGI_STDIN;
header.contentLength = collectedStdin[j].length;
header.paddingLength = 0;
writer.writeHeader(header);
writer.writeBody(collectedStdin[j].toString());
connection.write(writer.tobuffer());
}
collectedStdin = [];
if(noMoreData) {
endRequest();
}
}
};
request.on('data', function(chunk) {
if(writer) {
header.type = FCGI_STDIN;
header.contentLength = chunk.length;
header.paddingLength = 0;
writer.writeHeader(header);
writer.writeBody(chunk);
connection.write(writer.tobuffer())
} else {
collectedStdin.push(chunk);
}
});
request.on('end', endRequest);
connection.ondata = function (buffer, start, end) {
parser.execute(buffer, start, end);
};
connection.addListener("connect", function() {
writer = new fastcgi.writer();
parser = new fastcgi.parser();
var body="", hadheaders = false;
parser.onRecord = function(record) {
if (record.header.type == FCGI_STDOUT && !hadheaders) {
body = record.body;
debug.log(body);
var parts = body.split("\r\n\r\n");
var headers = parts[0];
var headerParts = headers.split("\r\n");
body = parts[1];
var responseStatus = 200;
headers = [];
try {
for(var i in headerParts) {
header = headerParts[i].split(': ');
if (header[0].indexOf('Status') >= 0) {
responseStatus = header[1].substr(0, 3);
continue;
}
headers.push([header[0], header[1]]);
}
} catch (err) {
//console.log(err);
}
debug.log(' --> Request Response Status Code: "' + responseStatus + '"');
if(responseStatus === "404") {
next();
parser.onRecord = function() {};
connection.end();
return;
}
response.writeHead(responseStatus, headers);
hadheaders = true;
} else if(record.header.type == FCGI_STDOUT && hadheaders) {
body += record.body;
} else if(record.header.type == FCGI_END) {
response.end(body);
}
};
parser.onError = function(err) {
//console.log(err);
};
sendRequest(connection);
});
connection.addListener("close", function() {
connection.end();
});
connection.addListener("error", function(err) {
sys.puts(sys.inspect(err.stack));
connection.end();
});
connection.connect(options.fastcgiPort, options.fastcgiHost);
}
// Let's mix those options.
var options = {
fastcgiPort: 9000,
fastcgiHost: 'localhost',
root: ''
};
for (var k in newOptions) {
options[k] = newOptions[k];
}
return function(request, response, next) {
var script_dir = options.root;
var script_file = url.parse(request.url).pathname;
var qs = url.parse(request.url).query ? url.parse(request.url).query : '';
var params = makeHeaders(request.headers, [
["SCRIPT_FILENAME",script_dir + script_file],
["REMOTE_ADDR",request.connection.remoteAddress],
["QUERY_STRING", qs],
["REQUEST_METHOD", request.method],
["SCRIPT_NAME", script_file],
["PATH_INFO", script_file],
["DOCUMENT_URI", script_file],
["REQUEST_URI", request.url],
["DOCUMENT_ROOT", script_dir],
["PHP_SELF", script_file],
["GATEWAY_PROTOCOL", "CGI/1.1"],
["SERVER_SOFTWARE", "node/" + process.version]
]);
debug.log('Incoming Request: ' + request.method + ' ' + request.url);
debug.dir(params);
server(request, response, params, options, next);
};
}