node-postgres/lib/connection.js

622 lines
15 KiB
JavaScript
Raw Normal View History

var net = require('net');
var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
2011-10-11 08:40:52 +08:00
var util = require('util');
var utils = require(__dirname + '/utils');
2013-03-17 00:51:26 +08:00
var Writer = require('buffer-writer');
var TEXT_MODE = 0;
var BINARY_MODE = 1;
var Connection = function(config) {
EventEmitter.call(this);
config = config || {};
this.stream = config.stream || new net.Stream();
this.lastBuffer = false;
this.lastOffset = 0;
this.buffer = null;
this.offset = null;
this.encoding = 'utf8';
this.parsedStatements = {};
this.writer = new Writer();
this.ssl = config.ssl || false;
2013-03-29 22:38:49 +08:00
this._ending = false;
this._mode = TEXT_MODE;
};
2011-10-11 08:40:52 +08:00
util.inherits(Connection, EventEmitter);
Connection.prototype.connect = function(port, host) {
2010-10-24 09:26:24 +08:00
if(this.stream.readyState === 'closed') {
2010-10-24 06:36:04 +08:00
this.stream.connect(port, host);
} else if(this.stream.readyState == 'open') {
2010-10-24 06:36:04 +08:00
this.emit('connect');
}
2010-10-24 09:26:24 +08:00
var self = this;
2010-10-24 06:36:04 +08:00
this.stream.on('connect', function() {
2010-10-24 06:36:04 +08:00
self.emit('connect');
});
2013-01-24 08:08:32 +08:00
this.stream.on('error', function(error) {
2013-03-29 22:38:49 +08:00
//don't raise ECONNRESET errors - they can & should be ignored
//during disconnect
if(self._ending && error.code == 'ECONNRESET') {
return;
}
self.emit('error', error);
});
2010-10-24 06:36:04 +08:00
this.stream.on('end', function() {
self.emit('end');
});
if(this.ssl) {
this.stream.once('data', function(buffer) {
self.setBuffer(buffer);
var msg = self.readSslResponse();
self.emit('message', msg);
self.emit(msg.name, msg);
});
this.once('sslresponse', function(msg) {
if(msg.text == 0x53) {
var tls = require('tls');
self.stream.removeAllListeners();
2013-01-24 08:08:32 +08:00
self.stream = tls.connect({
socket: self.stream,
servername: host,
2012-12-05 04:18:19 +08:00
rejectUnauthorized: self.ssl.rejectUnauthorized,
ca: self.ssl.ca,
pfx: self.ssl.pfx,
key: self.ssl.key,
passphrase: self.ssl.passphrase,
cert: self.ssl.cert,
NPNProtocols: self.ssl.NPNProtocols
});
self.attachListeners(self.stream);
self.emit('sslconnect');
} else {
2013-01-24 08:08:32 +08:00
self.emit(
'error',
new Error("The server doesn't support SSL/TLS connections.")
);
}
2013-01-24 08:08:32 +08:00
});
2010-10-31 09:23:54 +08:00
} else {
this.attachListeners(this.stream);
}
};
Connection.prototype.attachListeners = function(stream) {
var self = this;
stream.on('data', function(buffer) {
self.setBuffer(buffer);
var msg = self.parseMessage();
while(msg) {
self.emit('message', msg);
self.emit(msg.name, msg);
msg = self.parseMessage();
}
2010-10-31 09:23:54 +08:00
});
2010-10-24 06:36:04 +08:00
};
Connection.prototype.requestSsl = function(config) {
this.checkSslResponse = true;
2013-01-24 08:08:32 +08:00
var bodyBuffer = this.writer
.addInt16(0x04D2)
.addInt16(0x162F).flush();
2013-01-24 08:08:32 +08:00
var length = bodyBuffer.length + 4;
2013-01-24 08:08:32 +08:00
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join();
this.stream.write(buffer);
};
Connection.prototype.startup = function(config) {
var bodyBuffer = this.writer
2010-10-24 06:36:04 +08:00
.addInt16(3)
.addInt16(0)
.addCString('user')
.addCString(config.user)
.addCString('database')
.addCString(config.database)
.addCString('client_encoding')
.addCString("'utf-8'")
.addCString('').flush();
2010-11-01 07:36:35 +08:00
//this message is sent without a code
var length = bodyBuffer.length + 4;
2010-11-01 07:36:35 +08:00
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join();
this.stream.write(buffer);
};
Connection.prototype.cancel = function(processID, secretKey) {
2011-11-02 23:07:14 +08:00
var bodyBuffer = this.writer
.addInt16(1234)
.addInt16(5678)
.addInt32(processID)
.addInt32(secretKey)
.addCString('').flush();
var length = bodyBuffer.length + 4;
var buffer = new Writer()
2010-11-01 07:36:35 +08:00
.addInt32(length)
.add(bodyBuffer)
.join();
this.stream.write(buffer);
};
Connection.prototype.password = function(password) {
2010-11-01 07:36:35 +08:00
//0x70 = 'p'
this._send(0x70, this.writer.addCString(password));
2010-10-24 08:02:13 +08:00
};
Connection.prototype._send = function(code, more) {
if(!this.stream.writable) { return false; }
if(more === true) {
this.writer.addHeader(code);
} else {
return this.stream.write(this.writer.flush(code));
}
};
Connection.prototype.query = function(text) {
2010-11-01 07:36:35 +08:00
//0x51 = Q
this.stream.write(this.writer.addCString(text).flush(0x51));
};
//send parse message
//"more" === true to buffer the message until flush() is called
Connection.prototype.parse = function(query, more) {
//expect something like this:
// { name: 'queryName',
// text: 'select * from blah',
// types: ['int8', 'bool'] }
//normalize missing query names to allow for null
query.name = query.name || '';
//normalize null type array
query.types = query.types || [];
2010-10-24 13:18:48 +08:00
var len = query.types.length;
var buffer = this.writer
.addCString(query.name) //name of query
.addCString(query.text) //actual query text
2010-10-24 13:18:48 +08:00
.addInt16(len);
for(var i = 0; i < len; i++) {
buffer.addInt32(query.types[i]);
}
2010-10-28 13:27:08 +08:00
var code = 0x50;
this._send(code, more);
};
//send bind message
//"more" === true to buffer the message until flush() is called
Connection.prototype.bind = function(config, more) {
//normalize config
config = config || {};
2010-10-25 02:46:50 +08:00
config.portal = config.portal || '';
config.statement = config.statement || '';
config.binary = config.binary || false;
2010-10-25 02:46:50 +08:00
var values = config.values || [];
var len = values.length;
var buffer = this.writer
2010-10-25 02:46:50 +08:00
.addCString(config.portal)
.addCString(config.statement)
.addInt16(0) //always use default text format
2010-10-25 02:46:50 +08:00
.addInt16(len); //number of parameters
for(var i = 0; i < len; i++) {
var val = values[i];
if(val === null || typeof val === "undefined") {
2010-10-25 02:46:50 +08:00
buffer.addInt32(-1);
} else {
buffer.addInt32(Buffer.byteLength(val));
buffer.addString(val);
2010-10-25 02:46:50 +08:00
}
}
if(config.binary) {
buffer.addInt16(1); // format codes to use binary
buffer.addInt16(1);
}
else {
buffer.addInt16(0); // format codes to use text
}
2010-11-01 07:36:35 +08:00
//0x42 = 'B'
this._send(0x42, more);
};
//send execute message
//"more" === true to buffer the message until flush() is called
Connection.prototype.execute = function(config, more) {
2010-10-25 02:46:50 +08:00
config = config || {};
config.portal = config.portal || '';
config.rows = config.rows || '';
var buffer = this.writer
2010-10-25 02:46:50 +08:00
.addCString(config.portal)
.addInt32(config.rows);
2010-11-01 07:36:35 +08:00
//0x45 = 'E'
this._send(0x45, more);
};
var emptyBuffer = Buffer(0);
Connection.prototype.flush = function() {
2010-11-01 07:36:35 +08:00
//0x48 = 'H'
this.writer.add(emptyBuffer);
this._send(0x48);
};
Connection.prototype.sync = function() {
//clear out any pending data in the writer
this.writer.flush(0);
2013-01-24 08:08:32 +08:00
this.writer.add(emptyBuffer);
this._send(0x53);
};
Connection.prototype.end = function() {
2010-11-01 07:36:35 +08:00
//0x58 = 'X'
this.writer.add(emptyBuffer);
this._send(0x58);
2013-03-29 22:38:49 +08:00
this._ending = true;
2010-10-24 08:28:57 +08:00
};
Connection.prototype.describe = function(msg, more) {
this.writer.addCString(msg.type + (msg.name || ''));
this._send(0x44, more);
2010-10-28 13:27:08 +08:00
};
Connection.prototype.sendCopyFromChunk = function (chunk) {
this.stream.write(this.writer.add(chunk).flush(0x64));
};
Connection.prototype.endCopyFrom = function () {
this.stream.write(this.writer.add(emptyBuffer).flush(0x63));
};
Connection.prototype.sendCopyFail = function (msg) {
//this.stream.write(this.writer.add(emptyBuffer).flush(0x66));
this.writer.addCString(msg);
this._send(0x66);
};
//parsing methods
Connection.prototype.setBuffer = function(buffer) {
if(this.lastBuffer) { //we have unfinished biznaz
//need to combine last two buffers
var remaining = this.lastBuffer.length - this.lastOffset;
var combinedBuffer = new Buffer(buffer.length + remaining);
this.lastBuffer.copy(combinedBuffer, 0, this.lastOffset);
buffer.copy(combinedBuffer, remaining, 0);
buffer = combinedBuffer;
}
this.buffer = buffer;
this.offset = 0;
};
Connection.prototype.readSslResponse = function() {
var remaining = this.buffer.length - (this.offset);
if(remaining < 1) {
this.lastBuffer = this.buffer;
this.lastOffset = this.offset;
return false;
}
return {
name: 'sslresponse',
text: this.buffer[this.offset++]
};
};
Connection.prototype.parseMessage = function() {
var remaining = this.buffer.length - (this.offset);
if(remaining < 5) {
//cannot read id + length without at least 5 bytes
//just abort the read now
this.lastBuffer = this.buffer;
this.lastOffset = this.offset;
return false;
}
2010-11-01 06:58:32 +08:00
//read message id code
var id = this.buffer[this.offset++];
//read message length
var length = this.parseInt32();
2010-11-01 06:58:32 +08:00
if(remaining <= length) {
this.lastBuffer = this.buffer;
//rewind the last 5 bytes we read
this.lastOffset = this.offset-5;
return false;
}
2010-11-01 06:58:32 +08:00
var msg = {
length: length
};
switch(id)
{
case 0x52: //R
2010-11-01 06:58:32 +08:00
msg.name = 'authenticationOk';
return this.parseR(msg);
case 0x53: //S
2010-11-01 06:58:32 +08:00
msg.name = 'parameterStatus';
return this.parseS(msg);
case 0x4b: //K
2010-11-01 06:58:32 +08:00
msg.name = 'backendKeyData';
return this.parseK(msg);
case 0x43: //C
2010-11-01 06:58:32 +08:00
msg.name = 'commandComplete';
return this.parseC(msg);
case 0x5a: //Z
2010-11-01 06:58:32 +08:00
msg.name = 'readyForQuery';
return this.parseZ(msg);
case 0x54: //T
2010-11-01 06:58:32 +08:00
msg.name = 'rowDescription';
return this.parseT(msg);
case 0x44: //D
2010-11-01 06:58:32 +08:00
msg.name = 'dataRow';
return this.parseD(msg);
case 0x45: //E
2010-11-01 06:58:32 +08:00
msg.name = 'error';
return this.parseE(msg);
case 0x4e: //N
2010-11-01 06:58:32 +08:00
msg.name = 'notice';
return this.parseN(msg);
case 0x31: //1
2010-11-01 06:58:32 +08:00
msg.name = 'parseComplete';
return msg;
case 0x32: //2
2010-11-01 06:58:32 +08:00
msg.name = 'bindComplete';
return msg;
case 0x41: //A
2010-11-01 06:58:32 +08:00
msg.name = 'notification';
return this.parseA(msg);
case 0x6e: //n
2010-11-01 06:58:32 +08:00
msg.name = 'noData';
return msg;
case 0x49: //I
2010-11-01 06:58:32 +08:00
msg.name = 'emptyQuery';
return msg;
2010-11-15 07:44:36 +08:00
case 0x73: //s
msg.name = 'portalSuspended';
return msg;
case 0x47: //G
msg.name = 'copyInResponse';
return this.parseGH(msg);
case 0x48: //H
msg.name = 'copyOutResponse';
2013-01-24 08:08:32 +08:00
return this.parseGH(msg);
case 0x63: //c
msg.name = 'copyDone';
return msg;
case 0x64: //d
msg.name = 'copyData';
return this.parsed(msg);
default:
2010-11-01 06:58:32 +08:00
throw new Error("Unrecognized message code " + id);
}
};
Connection.prototype.parseR = function(msg) {
var code = 0;
if(msg.length === 8) {
code = this.parseInt32();
if(code === 3) {
msg.name = 'authenticationCleartextPassword';
}
return msg;
}
if(msg.length === 12) {
code = this.parseInt32();
if(code === 5) { //md5 required
msg.name = 'authenticationMD5Password';
msg.salt = new Buffer(4);
this.buffer.copy(msg.salt, 0, this.offset, this.offset + 4);
this.offset += 4;
return msg;
}
}
2011-10-11 08:40:52 +08:00
throw new Error("Unknown authenticatinOk message type" + util.inspect(msg));
};
Connection.prototype.parseS = function(msg) {
msg.parameterName = this.parseCString();
msg.parameterValue = this.parseCString();
return msg;
};
Connection.prototype.parseK = function(msg) {
msg.processID = this.parseInt32();
msg.secretKey = this.parseInt32();
return msg;
};
Connection.prototype.parseC = function(msg) {
msg.text = this.parseCString();
return msg;
};
Connection.prototype.parseZ = function(msg) {
msg.status = this.readChar();
return msg;
};
Connection.prototype.parseT = function(msg) {
msg.fieldCount = this.parseInt16();
var fields = [];
for(var i = 0; i < msg.fieldCount; i++){
fields.push(this.parseField());
}
msg.fields = fields;
return msg;
};
Connection.prototype.parseField = function() {
var field = {
name: this.parseCString(),
tableID: this.parseInt32(),
columnID: this.parseInt16(),
dataTypeID: this.parseInt32(),
dataTypeSize: this.parseInt16(),
dataTypeModifier: this.parseInt32(),
format: undefined
};
if(this.parseInt16() === TEXT_MODE) {
this._mode = TEXT_MODE;
field.format = 'text';
} else {
this._mode = BINARY_MODE;
field.format = 'binary';
}
return field;
};
Connection.prototype.parseD = function(msg) {
var fieldCount = this.parseInt16();
var fields = [];
for(var i = 0; i < fieldCount; i++) {
var length = this.parseInt32();
var value = null;
if(length !== -1) {
if(this._mode === TEXT_MODE) {
value = this.readString(length);
} else {
value = this.readBytes(length);
}
}
fields.push(value);
}
msg.fieldCount = fieldCount;
msg.fields = fields;
return msg;
};
//parses error
Connection.prototype.parseE = function(input) {
var fields = {};
var msg, item;
var fieldType = this.readString(1);
while(fieldType != '\0') {
fields[fieldType] = this.parseCString();
fieldType = this.readString(1);
}
if(input.name === 'error') {
// the msg is an Error instance
msg = new Error(fields.M);
for (item in input) {
// copy input properties to the error
if(input.hasOwnProperty(item)) {
msg[item] = input[item];
}
}
} else {
// the msg is an object literal
msg = input;
msg.message = fields.M;
}
msg.severity = fields.S;
msg.code = fields.C;
msg.detail = fields.D;
msg.hint = fields.H;
msg.position = fields.P;
msg.internalPosition = fields.p;
msg.internalQuery = fields.q;
msg.where = fields.W;
msg.file = fields.F;
msg.line = fields.L;
msg.routine = fields.R;
return msg;
};
2010-10-25 03:43:25 +08:00
//same thing, different name
Connection.prototype.parseN = Connection.prototype.parseE;
2010-10-25 03:43:25 +08:00
Connection.prototype.parseA = function(msg) {
2010-10-24 11:31:43 +08:00
msg.processId = this.parseInt32();
msg.channel = this.parseCString();
2010-10-24 11:45:03 +08:00
msg.payload = this.parseCString();
2010-10-24 11:31:43 +08:00
return msg;
};
Connection.prototype.parseGH = function (msg) {
var isBinary = this.buffer[this.offset] !== 0;
this.offset++;
msg.binary = isBinary;
var columnCount = this.parseInt16();
msg.columnTypes = [];
for(var i = 0; i<columnCount; i++) {
msg.columnTypes.push(this.parseInt16());
}
return msg;
};
Connection.prototype.readChar = function() {
return this.readString(1);
};
Connection.prototype.parseInt32 = function() {
var value = this.buffer.readInt32BE(this.offset, true);
this.offset += 4;
return value;
};
Connection.prototype.parseInt16 = function() {
var value = this.buffer.readInt16BE(this.offset, true);
this.offset += 2;
return value;
};
Connection.prototype.readString = function(length) {
return this.buffer.toString(this.encoding, this.offset, (this.offset += length));
};
Connection.prototype.readBytes = function(length) {
return this.buffer.slice(this.offset, this.offset += length);
};
Connection.prototype.parseCString = function() {
var start = this.offset;
while(this.buffer[this.offset++] !== 0) { }
return this.buffer.toString(this.encoding, start, this.offset - 1);
};
Connection.prototype.parsed = function (msg) {
//exclude length field
msg.chunk = this.readBytes(msg.length - 4);
2013-01-24 08:08:32 +08:00
return msg;
};
//end parsing methods
2010-10-24 06:36:04 +08:00
module.exports = Connection;