electron/lib/browser/api/net.js

321 lines
8.1 KiB
JavaScript
Raw Normal View History

'use strict'
2016-09-29 13:24:28 +00:00
const url = require('url')
const {EventEmitter} = require('events')
const util = require('util')
const Readable = require('stream').Readable
const binding = process.atomBinding('net')
const {net, Net} = binding
const {URLRequest} = net
Object.setPrototypeOf(Net.prototype, EventEmitter.prototype)
Object.setPrototypeOf(URLRequest.prototype, EventEmitter.prototype)
2016-09-29 13:24:28 +00:00
let kSupportedProtocols = new Set()
kSupportedProtocols.add('http:')
kSupportedProtocols.add('https:')
class IncomingMessage extends Readable {
2016-09-29 13:24:28 +00:00
constructor (urlRequest) {
super()
this._url_request = urlRequest
this._shouldPush = false;
this._data = [];
this._url_request.on('data', (event, chunk) => {
this._storeInternalData(chunk)
this._pushInternalData()
})
this._url_request.on('end', () => {
this._storeInternalData(null)
this._pushInternalData()
})
}
2016-09-29 13:24:28 +00:00
get statusCode () {
return this._url_request.statusCode
}
2016-09-29 13:24:28 +00:00
get statusMessage () {
return this._url_request.statusMessage
}
2016-09-29 13:24:28 +00:00
get headers () {
return this._url_request.rawResponseHeaders
}
2016-09-29 13:24:28 +00:00
get httpVersion () {
return `${this.httpVersionMajor}.${this.httpVersionMinor}`
}
2016-09-29 13:24:28 +00:00
get httpVersionMajor () {
return this._url_request.httpVersionMajor
}
2016-09-29 13:24:28 +00:00
get httpVersionMinor () {
return this._url_request.httpVersionMinor
}
2016-09-29 13:24:28 +00:00
get rawHeaders () {
return this._url_request.rawResponseHeaders
}
_storeInternalData(chunk) {
this._data.push(chunk)
}
_pushInternalData() {
while (this._shouldPush && this._data.length > 0) {
const chunk = this._data.shift()
this._shouldPush = this.push(chunk)
}
}
_read() {
this._shouldPush = true
this._pushInternalData()
}
}
URLRequest.prototype._emitRequestEvent = function (async, ...rest) {
if (async) {
process.nextTick(() => {
this._request.emit.apply(this._request, rest)
})
} else {
this._request.emit.apply(this._request, rest)
}
}
URLRequest.prototype._emitResponseEvent = function (async, ...rest) {
if (async) {
process.nextTick(() => {
this._request.emit.apply(this._request, rest)
})
} else {
this._response.emit.apply(this._response, rest)
}
}
class ClientRequest extends EventEmitter {
2016-09-29 13:24:28 +00:00
constructor (options, callback) {
super()
if (typeof options === 'string') {
2016-09-29 13:24:28 +00:00
options = url.parse(options)
} else {
2016-09-29 13:24:28 +00:00
options = util._extend({}, options)
}
2016-09-29 13:24:28 +00:00
const method = (options.method || 'GET').toUpperCase()
let urlStr = options.url
2016-09-29 13:24:28 +00:00
if (!urlStr) {
let urlObj = {}
const protocol = options.protocol || 'http'
if (!kSupportedProtocols.has(protocol)) {
2016-09-29 13:24:28 +00:00
throw new Error('Protocol "' + protocol + '" not supported. ')
}
2016-09-29 13:24:28 +00:00
urlObj.protocol = protocol
if (options.host) {
2016-09-29 13:24:28 +00:00
urlObj.host = options.host
} else {
if (options.hostname) {
2016-09-29 13:24:28 +00:00
urlObj.hostname = options.hostname
} else {
2016-09-29 13:24:28 +00:00
urlObj.hostname = 'localhost'
}
if (options.port) {
2016-09-29 13:24:28 +00:00
urlObj.port = options.port
}
}
2016-09-29 13:24:28 +00:00
const path = options.path || '/'
if (options.path && / /.test(options.path)) {
// The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
// with an additional rule for ignoring percentage-escaped characters
// but that's a) hard to capture in a regular expression that performs
// well, and b) possibly too restrictive for real-world usage. That's
// why it only scans for spaces because those are guaranteed to create
// an invalid request.
2016-09-29 13:24:28 +00:00
throw new TypeError('Request path contains unescaped characters.')
}
2016-09-29 13:24:28 +00:00
urlObj.path = path
urlStr = url.format(urlObj)
}
2016-09-29 13:24:28 +00:00
const sessionName = options.session || ''
let urlRequest = new URLRequest({
method: method,
2016-09-29 13:24:28 +00:00
url: urlStr,
session: sessionName
})
// Set back and forward links.
2016-09-29 13:24:28 +00:00
this._url_request = urlRequest
urlRequest._request = this
if (options.headers) {
2016-09-29 13:24:28 +00:00
const keys = Object.keys(options.headers)
for (let i = 0, l = keys.length; i < l; i++) {
2016-09-29 13:24:28 +00:00
const key = keys[i]
this.setHeader(key, options.headers[key])
}
}
// Set when the request uses chunked encoding. Can be switched
// to true only once and never set back to false.
2016-09-29 13:24:28 +00:00
this._chunkedEncoding = false
2016-09-26 12:03:49 +00:00
// This is a copy of the extra headers structure held by the native
// net::URLRequest. The main reason is to keep the getHeader API synchronous
// after the request starts.
2016-09-29 13:24:28 +00:00
this._extra_headers = {}
2016-09-21 15:35:03 +00:00
2016-09-29 13:24:28 +00:00
urlRequest.on('response', () => {
const response = new IncomingMessage(urlRequest)
urlRequest._response = response
this.emit('response', response)
})
2016-09-21 15:35:03 +00:00
if (callback) {
this.once('response', callback)
}
2016-09-21 15:35:03 +00:00
}
2016-09-29 13:24:28 +00:00
get chunkedEncoding () {
return this._chunkedEncoding
}
2016-09-29 13:24:28 +00:00
set chunkedEncoding (value) {
if (!this._url_request.notStarted) {
2016-09-29 13:24:28 +00:00
throw new Error('Can\'t set the transfer encoding, headers have been sent.')
}
2016-09-29 13:24:28 +00:00
this._chunkedEncoding = value
}
2016-09-29 13:24:28 +00:00
setHeader (name, value) {
if (typeof name !== 'string') {
throw new TypeError('`name` should be a string in setHeader(name, value).')
}
if (value === undefined) {
throw new Error('`value` required in setHeader("' + name + '", value).')
}
if (!this._url_request.notStarted) {
2016-09-29 13:24:28 +00:00
throw new Error('Can\'t set headers after they are sent.')
}
2016-09-21 15:35:03 +00:00
2016-09-29 13:24:28 +00:00
const key = name.toLowerCase()
this._extra_headers[key] = value
this._url_request.setExtraHeader(name, value)
2016-09-21 15:35:03 +00:00
}
2016-09-29 13:24:28 +00:00
getHeader (name) {
if (arguments.length < 1) {
2016-09-29 13:24:28 +00:00
throw new Error('`name` is required for getHeader(name).')
}
2016-09-21 15:35:03 +00:00
if (!this._extra_headers) {
2016-09-29 13:24:28 +00:00
return
}
2016-09-21 15:35:03 +00:00
2016-09-29 13:24:28 +00:00
const key = name.toLowerCase()
return this._extra_headers[key]
}
2016-09-29 13:24:28 +00:00
removeHeader (name) {
if (arguments.length < 1) {
2016-09-29 13:24:28 +00:00
throw new Error('`name` is required for removeHeader(name).')
}
if (!this._url_request.notStarted) {
2016-09-29 13:24:28 +00:00
throw new Error('Can\'t remove headers after they are sent.')
}
2016-09-21 15:35:03 +00:00
2016-09-29 13:24:28 +00:00
const key = name.toLowerCase()
delete this._extra_headers[key]
this._url_request.removeExtraHeader(name)
2016-09-21 15:35:03 +00:00
}
2016-09-29 13:24:28 +00:00
_write (chunk, encoding, callback, isLast) {
let chunkIsString = typeof chunk === 'string'
let chunkIsBuffer = chunk instanceof Buffer
if (!chunkIsString && !chunkIsBuffer) {
throw new TypeError('First argument must be a string or Buffer.')
}
2016-09-29 13:24:28 +00:00
if (chunkIsString) {
// We convert all strings into binary buffers.
2016-09-29 13:24:28 +00:00
chunk = Buffer.from(chunk, encoding)
}
// Headers are assumed to be sent on first call to _writeBuffer,
// i.e. after the first call to write or end.
2016-09-29 13:24:28 +00:00
let result = this._url_request.write(chunk, isLast)
2016-09-29 13:24:28 +00:00
// Since writing to the network is asynchronous, we conservatively
// assume that request headers are written after delivering the first
// buffer to the network IO thread.
if (!this._url_request.notStarted) {
2016-09-29 13:24:28 +00:00
this._url_request.setChunkedUpload(this.chunkedEncoding)
}
// The write callback is fired asynchronously to mimic Node.js.
if (callback) {
2016-09-29 13:24:28 +00:00
process.nextTick(callback)
}
2016-09-29 13:24:28 +00:00
return result
}
2016-09-29 13:24:28 +00:00
write (data, encoding, callback) {
if (this._url_request.finished) {
2016-09-29 13:24:28 +00:00
let error = new Error('Write after end.')
process.nextTick(writeAfterEndNT, this, error, callback)
return true
}
2016-09-26 12:03:49 +00:00
2016-09-29 13:24:28 +00:00
return this._write(data, encoding, callback, false)
2016-09-21 15:35:03 +00:00
}
2016-09-29 13:24:28 +00:00
end (data, encoding, callback) {
if (this._url_request.finished) {
2016-09-29 13:24:28 +00:00
return false
}
2016-09-29 13:24:28 +00:00
if (typeof data === 'function') {
2016-09-29 13:24:28 +00:00
callback = data
encoding = null
data = null
} else if (typeof encoding === 'function') {
2016-09-29 13:24:28 +00:00
callback = encoding
encoding = null
}
2016-09-21 15:35:03 +00:00
2016-09-29 13:24:28 +00:00
data = data || ''
2016-09-21 15:35:03 +00:00
2016-09-29 13:24:28 +00:00
return this._write(data, encoding, callback, true)
2016-09-26 12:03:49 +00:00
}
2016-09-29 13:24:28 +00:00
abort () {
this._url_request.cancel()
}
}
2016-09-21 15:35:03 +00:00
2016-09-29 13:24:28 +00:00
function writeAfterEndNT (self, error, callback) {
self.emit('error', error)
if (callback) callback(error)
2016-09-21 15:35:03 +00:00
}
2016-09-29 13:24:28 +00:00
Net.prototype.request = function (options, callback) {
return new ClientRequest(options, callback)
}
2016-09-29 13:24:28 +00:00
net.ClientRequest = ClientRequest
module.exports = net