-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathconnection.js
705 lines (602 loc) · 18.1 KB
/
connection.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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
'use strict'
/**
* Copyright (c) 2010-2017 Brian Carlson (brian.m.carlson@gmail.com)
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* README.md file in the root directory of this source tree.
*/
var net = require('net')
var EventEmitter = require('events').EventEmitter
var util = require('util')
var Writer = require('buffer-writer')
var Reader = require('packet-reader')
var TEXT_MODE = 0
var BINARY_MODE = 1
var Connection = function (config) {
EventEmitter.call(this)
config = config || {}
this.stream = config.stream || new net.Socket()
this._keepAlive = config.keepAlive
this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis
this.lastBuffer = false
this.lastOffset = 0
this.buffer = null
this.offset = null
this.encoding = config.encoding || 'utf8'
this.parsedStatements = {}
this.writer = new Writer()
this.ssl = config.ssl || false
this._ending = false
this._mode = TEXT_MODE
this._emitMessage = false
this._reader = new Reader({
headerSize: 1,
lengthPadding: -4
})
var self = this
this.on('newListener', function (eventName) {
if (eventName === 'message') {
self._emitMessage = true
}
})
}
util.inherits(Connection, EventEmitter)
Connection.prototype.connect = function (port, host) {
var self = this
if (this.stream.readyState === 'closed') {
this.stream.connect(port, host)
} else if (this.stream.readyState === 'open') {
this.emit('connect')
}
this.stream.on('connect', function () {
if (self._keepAlive) {
self.stream.setKeepAlive(true, self._keepAliveInitialDelayMillis)
}
self.emit('connect')
})
const reportStreamError = function (error) {
// don't raise ECONNRESET errors - they can & should be ignored
// during disconnect
if (self._ending && error.code === 'ECONNRESET') {
return
}
self.emit('error', error)
}
this.stream.on('error', reportStreamError)
this.stream.on('close', function () {
self.emit('end')
})
if (!this.ssl) {
return this.attachListeners(this.stream)
}
this.stream.once('data', function (buffer) {
var responseCode = buffer.toString('utf8')
switch (responseCode) {
case 'N': // Server does not support SSL connections
return self.emit('error', new Error('The server does not support SSL connections'))
case 'S': // Server supports SSL connections, continue with a secure connection
break
default: // Any other response byte, including 'E' (ErrorResponse) indicating a server error
return self.emit('error', new Error('There was an error establishing an SSL connection'))
}
var tls = require('tls')
self.stream = tls.connect({
socket: self.stream,
servername: host,
checkServerIdentity: self.ssl.checkServerIdentity || tls.checkServerIdentity,
rejectUnauthorized: self.ssl.rejectUnauthorized,
ca: self.ssl.ca,
pfx: self.ssl.pfx,
key: self.ssl.key,
passphrase: self.ssl.passphrase,
cert: self.ssl.cert,
secureOptions: self.ssl.secureOptions,
NPNProtocols: self.ssl.NPNProtocols
})
self.attachListeners(self.stream)
self.stream.on('error', reportStreamError)
self.emit('sslconnect')
})
}
Connection.prototype.attachListeners = function (stream) {
var self = this
stream.on('data', function (buff) {
self._reader.addChunk(buff)
var packet = self._reader.read()
while (packet) {
var msg = self.parseMessage(packet)
var eventName = msg.name === 'error' ? 'errorMessage' : msg.name
if (self._emitMessage) {
self.emit('message', msg)
}
self.emit(eventName, msg)
packet = self._reader.read()
}
})
stream.on('end', function () {
self.emit('end')
})
}
Connection.prototype.requestSsl = function () {
var bodyBuffer = this.writer
.addInt16(0x04D2)
.addInt16(0x162F).flush()
var length = bodyBuffer.length + 4
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join()
this.stream.write(buffer)
}
Connection.prototype.startup = function (config) {
var writer = this.writer
.addInt16(3)
.addInt16(0)
Object.keys(config).forEach(function (key) {
var val = config[key]
writer.addCString(key).addCString(val)
})
writer.addCString('client_encoding').addCString("'utf-8'")
var bodyBuffer = writer.addCString('').flush()
// this message is sent without a code
var length = bodyBuffer.length + 4
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join()
this.stream.write(buffer)
}
Connection.prototype.cancel = function (processID, secretKey) {
var bodyBuffer = this.writer
.addInt16(1234)
.addInt16(5678)
.addInt32(processID)
.addInt32(secretKey)
.flush()
var length = bodyBuffer.length + 4
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join()
this.stream.write(buffer)
}
Connection.prototype.password = function (password) {
// 0x70 = 'p'
this._send(0x70, this.writer.addCString(password))
}
Connection.prototype.sendSASLInitialResponseMessage = function (mechanism, initialResponse) {
// 0x70 = 'p'
this.writer
.addCString(mechanism)
.addInt32(Buffer.byteLength(initialResponse))
.addString(initialResponse)
this._send(0x70)
}
Connection.prototype.sendSCRAMClientFinalMessage = function (additionalData) {
// 0x70 = 'p'
this.writer
.addString(additionalData)
this._send(0x70)
}
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) {
// 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 || ''
if (query.name.length > 63) {
/* eslint-disable no-console */
console.error('Warning! Postgres only supports 63 characters for query names.')
console.error('You supplied %s (%s)', query.name, query.name.length)
console.error('This can cause conflicts and silent errors executing queries')
/* eslint-enable no-console */
}
// normalize null type array
query.types = query.types || []
var len = query.types.length
var buffer = this.writer
.addCString(query.name) // name of query
.addCString(query.text) // actual query text
.addInt16(len)
for (var i = 0; i < len; i++) {
buffer.addInt32(query.types[i])
}
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 || {}
config.portal = config.portal || ''
config.statement = config.statement || ''
config.binary = config.binary || false
var values = config.values || []
var len = values.length
var useBinary = false
for (var j = 0; j < len; j++) { useBinary |= values[j] instanceof Buffer }
var buffer = this.writer
.addCString(config.portal)
.addCString(config.statement)
if (!useBinary) { buffer.addInt16(0) } else {
buffer.addInt16(len)
for (j = 0; j < len; j++) { buffer.addInt16(values[j] instanceof Buffer) }
}
buffer.addInt16(len)
for (var i = 0; i < len; i++) {
var val = values[i]
if (val === null || typeof val === 'undefined') {
buffer.addInt32(-1)
} else if (val instanceof Buffer) {
buffer.addInt32(val.length)
buffer.add(val)
} else {
buffer.addInt32(Buffer.byteLength(val))
buffer.addString(val)
}
}
if (config.binary) {
buffer.addInt16(1) // format codes to use binary
buffer.addInt16(1)
} else {
buffer.addInt16(0) // format codes to use text
}
// 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) {
config = config || {}
config.portal = config.portal || ''
config.rows = config.rows || ''
this.writer
.addCString(config.portal)
.addInt32(config.rows)
// 0x45 = 'E'
this._send(0x45, more)
}
var emptyBuffer = Buffer.alloc(0)
Connection.prototype.flush = function () {
// 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)
this.writer.add(emptyBuffer)
this._ending = true
this._send(0x53)
}
const END_BUFFER = Buffer.from([0x58, 0x00, 0x00, 0x00, 0x04])
Connection.prototype.end = function () {
// 0x58 = 'X'
this.writer.add(emptyBuffer)
this._ending = true
return this.stream.write(END_BUFFER, () => {
this.stream.end()
})
}
Connection.prototype.close = function (msg, more) {
this.writer.addCString(msg.type + (msg.name || ''))
this._send(0x43, more)
}
Connection.prototype.describe = function (msg, more) {
this.writer.addCString(msg.type + (msg.name || ''))
this._send(0x44, more)
}
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)
}
var Message = function (name, length) {
this.name = name
this.length = length
}
Connection.prototype.parseMessage = function (buffer) {
this.offset = 0
var length = buffer.length + 4
switch (this._reader.header) {
case 0x52: // R
return this.parseR(buffer, length)
case 0x53: // S
return this.parseS(buffer, length)
case 0x4b: // K
return this.parseK(buffer, length)
case 0x43: // C
return this.parseC(buffer, length)
case 0x5a: // Z
return this.parseZ(buffer, length)
case 0x54: // T
return this.parseT(buffer, length)
case 0x44: // D
return this.parseD(buffer, length)
case 0x45: // E
return this.parseE(buffer, length)
case 0x4e: // N
return this.parseN(buffer, length)
case 0x31: // 1
return new Message('parseComplete', length)
case 0x32: // 2
return new Message('bindComplete', length)
case 0x33: // 3
return new Message('closeComplete', length)
case 0x41: // A
return this.parseA(buffer, length)
case 0x6e: // n
return new Message('noData', length)
case 0x49: // I
return new Message('emptyQuery', length)
case 0x73: // s
return new Message('portalSuspended', length)
case 0x47: // G
return this.parseG(buffer, length)
case 0x48: // H
return this.parseH(buffer, length)
case 0x57: // W
return new Message('replicationStart', length)
case 0x63: // c
return new Message('copyDone', length)
case 0x64: // d
return this.parsed(buffer, length)
}
}
Connection.prototype.parseR = function (buffer, length) {
var code = this.parseInt32(buffer)
var msg = new Message('authenticationOk', length)
switch (code) {
case 0: // AuthenticationOk
return msg
case 3: // AuthenticationCleartextPassword
if (msg.length === 8) {
msg.name = 'authenticationCleartextPassword'
return msg
}
break
case 5: // AuthenticationMD5Password
if (msg.length === 12) {
msg.name = 'authenticationMD5Password'
msg.salt = Buffer.alloc(4)
buffer.copy(msg.salt, 0, this.offset, this.offset + 4)
this.offset += 4
return msg
}
break
case 10: // AuthenticationSASL
msg.name = 'authenticationSASL'
msg.mechanisms = []
do {
var mechanism = this.parseCString(buffer)
if (mechanism) {
msg.mechanisms.push(mechanism)
}
} while (mechanism)
return msg
case 11: // AuthenticationSASLContinue
msg.name = 'authenticationSASLContinue'
msg.data = this.readString(buffer, length - 4)
return msg
case 12: // AuthenticationSASLFinal
msg.name = 'authenticationSASLFinal'
msg.data = this.readString(buffer, length - 4)
return msg
}
throw new Error('Unknown authenticationOk message type' + util.inspect(msg))
}
Connection.prototype.parseS = function (buffer, length) {
var msg = new Message('parameterStatus', length)
msg.parameterName = this.parseCString(buffer)
msg.parameterValue = this.parseCString(buffer)
return msg
}
Connection.prototype.parseK = function (buffer, length) {
var msg = new Message('backendKeyData', length)
msg.processID = this.parseInt32(buffer)
msg.secretKey = this.parseInt32(buffer)
return msg
}
Connection.prototype.parseC = function (buffer, length) {
var msg = new Message('commandComplete', length)
msg.text = this.parseCString(buffer)
return msg
}
Connection.prototype.parseZ = function (buffer, length) {
var msg = new Message('readyForQuery', length)
msg.name = 'readyForQuery'
msg.status = this.readString(buffer, 1)
return msg
}
var ROW_DESCRIPTION = 'rowDescription'
Connection.prototype.parseT = function (buffer, length) {
var msg = new Message(ROW_DESCRIPTION, length)
msg.fieldCount = this.parseInt16(buffer)
var fields = []
for (var i = 0; i < msg.fieldCount; i++) {
fields.push(this.parseField(buffer))
}
msg.fields = fields
return msg
}
var Field = function () {
this.name = null
this.tableID = null
this.columnID = null
this.dataTypeID = null
this.dataTypeSize = null
this.dataTypeModifier = null
this.format = null
}
var FORMAT_TEXT = 'text'
var FORMAT_BINARY = 'binary'
Connection.prototype.parseField = function (buffer) {
var field = new Field()
field.name = this.parseCString(buffer)
field.tableID = this.parseInt32(buffer)
field.columnID = this.parseInt16(buffer)
field.dataTypeID = this.parseInt32(buffer)
field.dataTypeSize = this.parseInt16(buffer)
field.dataTypeModifier = this.parseInt32(buffer)
if (this.parseInt16(buffer) === TEXT_MODE) {
this._mode = TEXT_MODE
field.format = FORMAT_TEXT
} else {
this._mode = BINARY_MODE
field.format = FORMAT_BINARY
}
return field
}
var DATA_ROW = 'dataRow'
var DataRowMessage = function (length, fieldCount) {
this.name = DATA_ROW
this.length = length
this.fieldCount = fieldCount
this.fields = []
}
// extremely hot-path code
Connection.prototype.parseD = function (buffer, length) {
var fieldCount = this.parseInt16(buffer)
var msg = new DataRowMessage(length, fieldCount)
for (var i = 0; i < fieldCount; i++) {
msg.fields.push(this._readValue(buffer))
}
return msg
}
// extremely hot-path code
Connection.prototype._readValue = function (buffer) {
var length = this.parseInt32(buffer)
if (length === -1) return null
if (this._mode === TEXT_MODE) {
return this.readString(buffer, length)
}
return this.readBytes(buffer, length)
}
// parses error
Connection.prototype.parseE = function (buffer, length) {
var fields = {}
var msg, item
var input = new Message('error', length)
var fieldType = this.readString(buffer, 1)
while (fieldType !== '\0') {
fields[fieldType] = this.parseCString(buffer)
fieldType = this.readString(buffer, 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 (Object.prototype.hasOwnProperty.call(input, 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.schema = fields.s
msg.table = fields.t
msg.column = fields.c
msg.dataType = fields.d
msg.constraint = fields.n
msg.file = fields.F
msg.line = fields.L
msg.routine = fields.R
return msg
}
// same thing, different name
Connection.prototype.parseN = function (buffer, length) {
var msg = this.parseE(buffer, length)
msg.name = 'notice'
return msg
}
Connection.prototype.parseA = function (buffer, length) {
var msg = new Message('notification', length)
msg.processId = this.parseInt32(buffer)
msg.channel = this.parseCString(buffer)
msg.payload = this.parseCString(buffer)
return msg
}
Connection.prototype.parseG = function (buffer, length) {
var msg = new Message('copyInResponse', length)
return this.parseGH(buffer, msg)
}
Connection.prototype.parseH = function (buffer, length) {
var msg = new Message('copyOutResponse', length)
return this.parseGH(buffer, msg)
}
Connection.prototype.parseGH = function (buffer, msg) {
var isBinary = buffer[this.offset] !== 0
this.offset++
msg.binary = isBinary
var columnCount = this.parseInt16(buffer)
msg.columnTypes = []
for (var i = 0; i < columnCount; i++) {
msg.columnTypes.push(this.parseInt16(buffer))
}
return msg
}
Connection.prototype.parsed = function (buffer, length) {
var msg = new Message('copyData', length)
msg.chunk = this.readBytes(buffer, msg.length - 4)
return msg
}
Connection.prototype.parseInt32 = function (buffer) {
var value = buffer.readInt32BE(this.offset)
this.offset += 4
return value
}
Connection.prototype.parseInt16 = function (buffer) {
var value = buffer.readInt16BE(this.offset)
this.offset += 2
return value
}
Connection.prototype.readString = function (buffer, length) {
return buffer.toString(this.encoding, this.offset, (this.offset += length))
}
Connection.prototype.readBytes = function (buffer, length) {
return buffer.slice(this.offset, (this.offset += length))
}
Connection.prototype.parseCString = function (buffer) {
var start = this.offset
var end = buffer.indexOf(0, start)
this.offset = end + 1
return buffer.toString(this.encoding, start, end)
}
// end parsing methods
module.exports = Connection