Skip to content

Commit 02277df

Browse files
committed
Merge pull request mkschreder#11 from alangecker/master
Pipelining for php.stdin and non-blocking filesystem calls
2 parents ea47024 + ffa69ea commit 02277df

File tree

1 file changed

+126
-137
lines changed

1 file changed

+126
-137
lines changed

main.js

Lines changed: 126 additions & 137 deletions
Original file line numberDiff line numberDiff line change
@@ -1,146 +1,135 @@
1-
var url = require("url");
2-
var child = require("child_process");
3-
var path = require("path");
4-
var fs = require("fs");
1+
var url = require("url");
2+
var child = require("child_process");
3+
var path = require("path");
4+
var fs = require("fs");
55

66
function runPHP(req, response, next, phpdir){
77
var parts = url.parse(req.url);
88
var query = parts.query;
9-
10-
var file = path.join(phpdir, parts.pathname);
11-
12-
if(!fs.existsSync(file)){
13-
file = path.join(phpdir, "index.php");
14-
} else if(fs.statSync(file).isDirectory()){
15-
file = path.join(file, "index.php");
16-
}
17-
18-
var pathinfo = "";
19-
var i = req.url.indexOf(".php");
20-
if(i > 0) pathinfo = parts.pathname.substring(i+4);
21-
else pathinfo = parts.pathname;
22-
23-
var env = {
24-
SERVER_SIGNATURE: "NodeJS server at localhost",
25-
PATH_INFO: pathinfo, //The extra path information, as given in the requested URL. In fact, scripts can be accessed by their virtual path, followed by extra information at the end of this path. The extra information is sent in PATH_INFO.
26-
PATH_TRANSLATED: "", //The virtual-to-real mapped version of PATH_INFO.
27-
SCRIPT_NAME: parts.pathname, //The virtual path of the script being executed.
28-
SCRIPT_FILENAME: file,
29-
REQUEST_FILENAME: file, //The real path of the script being executed.
30-
SCRIPT_URI: req.url, //The full URL to the current object requested by the client.
31-
URL: req.url, //The full URI of the current request. It is made of the concatenation of SCRIPT_NAME and PATH_INFO (if available.)
32-
SCRIPT_URL: req.url,
33-
REQUEST_URI: req.url, //The original request URI sent by the client.
34-
REQUEST_METHOD: req.method, //The method used by the current request; usually set to GET or POST.
35-
QUERY_STRING: parts.query||"", //The information which follows the ? character in the requested URL.
36-
CONTENT_TYPE: req.get("Content-type")||"", //"multipart/form-data", //"application/x-www-form-urlencoded", //The MIME type of the request body; set only for POST or PUT requests.
37-
CONTENT_LENGTH: req.rawBody.length||0, //The length in bytes of the request body; set only for POST or PUT requests.
38-
AUTH_TYPE: "", //The authentication type if the client has authenticated itself to access the script.
39-
AUTH_USER: "",
40-
REMOTE_USER: "", //The name of the user as issued by the client when authenticating itself to access the script.
41-
ALL_HTTP: Object.keys(req.headers).map(function(x){return "HTTP_"+x.toUpperCase().replace("-", "_")+": "+req.headers[x];}).reduce(function(a, b){return a+b+"\n";}, ""), //All HTTP headers sent by the client. Headers are separated by carriage return characters (ASCII 13 - \n) and each header name is prefixed by HTTP_, transformed to upper cases, and - characters it contains are replaced by _ characters.
42-
ALL_RAW: Object.keys(req.headers).map(function(x){return x+": "+req.headers[x];}).reduce(function(a, b){return a+b+"\n";}, ""), //All HTTP headers as sent by the client in raw form. No transformation on the header names is applied.
43-
SERVER_SOFTWARE: "NodeJS", //The web server's software identity.
44-
SERVER_NAME: "localhost", //The host name or the IP address of the computer running the web server as given in the requested URL.
45-
SERVER_ADDR: "127.0.0.1", //The IP address of the computer running the web server.
46-
SERVER_PORT: 8011, //The port to which the request was sent.
47-
GATEWAY_INTERFACE: "CGI/1.1", //The CGI Specification version supported by the web server; always set to CGI/1.1.
48-
SERVER_PROTOCOL: "", //The HTTP protocol version used by the current request.
49-
REMOTE_ADDR: "", //The IP address of the computer that sent the request.
50-
REMOTE_PORT: "", //The port from which the request was sent.
51-
DOCUMENT_ROOT: "", //The absolute path of the web site files. It has the same value as Documents Path.
52-
INSTANCE_ID: "", //The numerical identifier of the host which served the request. On Abyss Web Server X1, it is always set to 1 since there is only a single host.
53-
APPL_MD_PATH: "", //The virtual path of the deepest alias which contains the request URI. If no alias contains the request URI, the variable is set to /.
54-
APPL_PHYSICAL_PATH: "", //The real path of the deepest alias which contains the request URI. If no alias contains the request URI, the variable is set to the same value as DOCUMENT_ROOT.
55-
IS_SUBREQ: "", //It is set to true if the current request is a subrequest, i.e. a request not directly invoked by a client. Otherwise, it is set to true. Subrequests are generated by the server for internal processing. XSSI includes for example result in subrequests.
56-
REDIRECT_STATUS: 1
57-
};
58-
59-
Object.keys(req.headers).map(function(x){return env["HTTP_"+x.toUpperCase().replace("-", "_")] = req.headers[x];});
60-
61-
if(/.*?\.php$/.test(file)){
62-
var res = "", err = "";
63-
64-
var php = child.spawn("php-cgi", [], {
65-
env: env
66-
});
67-
68-
//php.stdin.resume();
69-
//console.log(req.rawBody);
70-
//(new Stream(req.rawBody)).pipe(php.stdin);
71-
php.stdin.on("error", function(){});
72-
php.stdin.write(req.rawBody);
73-
//php.stdin.write("\n");
74-
75-
//php.stdin.end();
76-
77-
php.stdout.on("data", function(data){
78-
//console.log(data.toString());
79-
res += data.toString();
80-
});
81-
php.stderr.on("data", function(data){
82-
err += err.toString();
83-
});
84-
php.on("error", function(err){
85-
console.error(err);
86-
});
87-
php.on("exit", function(){
88-
// extract headers
89-
php.stdin.end();
90-
91-
var lines = res.split("\r\n");
92-
var line = 0;
93-
var html = "";
94-
if(lines.length){
95-
do {
96-
var m = lines[line].split(": ");
97-
if(m[0] === "") break;
98-
99-
//console.log("HEADER: "+m[0]+": "+m[1]);
100-
if(m[0] == "Status"){
101-
response.statusCode = parseInt(m[1]);
102-
}
103-
if(m.length == 2){
104-
response.setHeader(m[0], m[1]);
105-
}
106-
line++;
107-
} while(lines[line] !== "");
108-
109-
html = lines.splice(line+1).join("\n");
110-
} else {
111-
html = res;
112-
}
113-
//console.log("STATUS: "+response.statusCode);
114-
//console.log(html);
115-
response.status(response.statusCode).send(html);
116-
response.end();
117-
});
118-
119-
} else {
120-
response.sendFile(file);
121-
//response.end();
122-
//next();
123-
}
124-
}
1259

10+
var file = path.join(phpdir, parts.pathname);
11+
12+
// get file stats asynchronously
13+
fs.stat(file, function(err,stat){
14+
15+
if(err){ // file does not exist
16+
file = path.join(phpdir, "index.php");
17+
} else if(stat.isDirectory()){
18+
file = path.join(file, "index.php");
19+
}
20+
21+
var pathinfo = "";
22+
var i = req.url.indexOf(".php");
23+
if(i > 0) pathinfo = parts.pathname.substring(i+4);
24+
else pathinfo = parts.pathname;
25+
26+
var env = {
27+
SERVER_SIGNATURE: "NodeJS server at localhost",
28+
PATH_INFO: pathinfo, //The extra path information, as given in the requested URL. In fact, scripts can be accessed by their virtual path, followed by extra information at the end of this path. The extra information is sent in PATH_INFO.
29+
PATH_TRANSLATED: "", //The virtual-to-real mapped version of PATH_INFO.
30+
SCRIPT_NAME: parts.pathname, //The virtual path of the script being executed.
31+
SCRIPT_FILENAME: file,
32+
REQUEST_FILENAME: file, //The real path of the script being executed.
33+
SCRIPT_URI: req.url, //The full URL to the current object requested by the client.
34+
URL: req.url, //The full URI of the current request. It is made of the concatenation of SCRIPT_NAME and PATH_INFO (if available.)
35+
SCRIPT_URL: req.url,
36+
REQUEST_URI: req.url, //The original request URI sent by the client.
37+
REQUEST_METHOD: req.method, //The method used by the current request; usually set to GET or POST.
38+
QUERY_STRING: parts.query||"", //The information which follows the ? character in the requested URL.
39+
CONTENT_TYPE: req.get("Content-type")||"", //"multipart/form-data", //"application/x-www-form-urlencoded", //The MIME type of the request body; set only for POST or PUT requests.
40+
CONTENT_LENGTH: req.get("Content-Length") || 0, //The length in bytes of the request body; set only for POST or PUT requests.
41+
AUTH_TYPE: "", //The authentication type if the client has authenticated itself to access the script.
42+
AUTH_USER: "",
43+
REMOTE_USER: "", //The name of the user as issued by the client when authenticating itself to access the script.
44+
ALL_HTTP: Object.keys(req.headers).map(function(x){return "HTTP_"+x.toUpperCase().replace("-", "_")+": "+req.headers[x];}).reduce(function(a, b){return a+b+"\n";}, ""), //All HTTP headers sent by the client. Headers are separated by carriage return characters (ASCII 13 - \n) and each header name is prefixed by HTTP_, transformed to upper cases, and - characters it contains are replaced by _ characters.
45+
ALL_RAW: Object.keys(req.headers).map(function(x){return x+": "+req.headers[x];}).reduce(function(a, b){return a+b+"\n";}, ""), //All HTTP headers as sent by the client in raw form. No transformation on the header names is applied.
46+
SERVER_SOFTWARE: "NodeJS", //The web server's software identity.
47+
SERVER_NAME: "localhost", //The host name or the IP address of the computer running the web server as given in the requested URL.
48+
SERVER_ADDR: "127.0.0.1", //The IP address of the computer running the web server.
49+
SERVER_PORT: 8011, //The port to which the request was sent.
50+
GATEWAY_INTERFACE: "CGI/1.1", //The CGI Specification version supported by the web server; always set to CGI/1.1.
51+
SERVER_PROTOCOL: "", //The HTTP protocol version used by the current request.
52+
REMOTE_ADDR: "", //The IP address of the computer that sent the request.
53+
REMOTE_PORT: "", //The port from which the request was sent.
54+
DOCUMENT_ROOT: "", //The absolute path of the web site files. It has the same value as Documents Path.
55+
INSTANCE_ID: "", //The numerical identifier of the host which served the request. On Abyss Web Server X1, it is always set to 1 since there is only a single host.
56+
APPL_MD_PATH: "", //The virtual path of the deepest alias which contains the request URI. If no alias contains the request URI, the variable is set to /.
57+
APPL_PHYSICAL_PATH: "", //The real path of the deepest alias which contains the request URI. If no alias contains the request URI, the variable is set to the same value as DOCUMENT_ROOT.
58+
IS_SUBREQ: "", //It is set to true if the current request is a subrequest, i.e. a request not directly invoked by a client. Otherwise, it is set to true. Subrequests are generated by the server for internal processing. XSSI includes for example result in subrequests.
59+
REDIRECT_STATUS: 1
60+
};
61+
62+
Object.keys(req.headers).map(function(x){return env["HTTP_"+x.toUpperCase().replace("-", "_")] = req.headers[x];});
63+
64+
if(/.*?\.php$/.test(file)){
65+
var res = "", err = "";
66+
67+
var php = child.spawn("php-cgi", [], {
68+
env: env
69+
});
70+
71+
//php.stdin.resume();
72+
//console.log(req.rawBody);
73+
//(new Stream(req.rawBody)).pipe(php.stdin);
74+
php.stdin.on("error", function(){});
75+
req.pipe(php.stdin); // pipe request stream directly into the php process
76+
req.resume();
77+
//php.stdin.write("\n");
78+
79+
//php.stdin.end();
80+
81+
php.stdout.on("data", function(data){
82+
//console.log(data.toString());
83+
res += data.toString();
84+
});
85+
php.stderr.on("data", function(data){
86+
err += err.toString();
87+
});
88+
php.on("error", function(err){
89+
console.error(err);
90+
});
91+
php.on("exit", function(){
92+
// extract headers
93+
php.stdin.end();
94+
95+
var lines = res.split("\r\n");
96+
var line = 0;
97+
var html = "";
98+
if(lines.length){
99+
do {
100+
var m = lines[line].split(": ");
101+
if(m[0] === "") break;
102+
103+
//console.log("HEADER: "+m[0]+": "+m[1]);
104+
if(m[0] == "Status"){
105+
response.statusCode = parseInt(m[1]);
106+
}
107+
if(m.length == 2){
108+
response.setHeader(m[0], m[1]);
109+
}
110+
line++;
111+
} while(lines[line] !== "");
112+
113+
html = lines.splice(line+1).join("\n");
114+
} else {
115+
html = res;
116+
}
117+
//console.log("STATUS: "+response.statusCode);
118+
//console.log(html);
119+
response.status(response.statusCode).send(html);
120+
response.end();
121+
});
122+
123+
} else {
124+
response.sendFile(file);
125+
//response.end();
126+
//next();
127+
}
128+
});
129+
}
126130
exports.cgi = function(phproot){
127131
return function(req, res, next){
128-
var data = null;
129-
130-
//req.setEncoding('utf8');
131-
req.on('data', function(chunk) {
132-
//data.write(chunk.toString('binary'), data.length, chunk.length, 'binary');
133-
//console.log(chunk);
134-
if(!data) data = chunk;
135-
else data = data+chunk;
136-
//data = data.concat(chunk);
137-
});
138-
req.on('end', function() {
139-
req.rawBody = data||"";
140-
//console.log(req.rawBody);
141-
//console.log("ENCODING: "+req.get("Content-type")+", len: "+req.rawBody.length);
142-
runPHP(req, res, next, phproot);
143-
});
132+
req.pause(); // stop stream until child-process is opened
133+
runPHP(req, res, next, phproot);
144134
}
145135
}
146-

0 commit comments

Comments
 (0)