Newer
Older
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
var end = function () {
if (self._form) {
if (!self._auth.hasAuth) {
self._form.pipe(self)
} else if (self._auth.hasAuth && self._auth.sentAuth) {
self._form.pipe(self)
}
}
if (self._multipart && self._multipart.chunked) {
self._multipart.body.pipe(self)
}
if (self.body) {
if (isstream(self.body)) {
self.body.pipe(self)
} else {
setContentLength()
if (Array.isArray(self.body)) {
self.body.forEach(function (part) {
self.write(part)
})
} else {
self.write(self.body)
}
self.end()
}
} else if (self.requestBodyStream) {
console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
self.requestBodyStream.pipe(self)
} else if (!self.src) {
if (self._auth.hasAuth && !self._auth.sentAuth) {
self.end()
return
}
if (self.method !== 'GET' && typeof self.method !== 'undefined') {
self.setHeader('content-length', 0)
}
self.end()
}
}
if (self._form && !self.hasHeader('content-length')) {
// Before ending the request, we had to compute the length of the whole form, asyncly
self.setHeader(self._form.getHeaders(), true)
self._form.getLength(function (err, length) {
if (!err && !isNaN(length)) {
self.setHeader('content-length', length)
}
end()
})
} else {
end()
}
self.ntick = true
})
}
Request.prototype.getNewAgent = function () {
var self = this
var Agent = self.agentClass
var options = {}
if (self.agentOptions) {
for (var i in self.agentOptions) {
options[i] = self.agentOptions[i]
}
}
if (self.ca) {
options.ca = self.ca
}
if (self.ciphers) {
options.ciphers = self.ciphers
}
if (self.secureProtocol) {
options.secureProtocol = self.secureProtocol
}
if (self.secureOptions) {
options.secureOptions = self.secureOptions
}
if (typeof self.rejectUnauthorized !== 'undefined') {
options.rejectUnauthorized = self.rejectUnauthorized
}
if (self.cert && self.key) {
options.key = self.key
options.cert = self.cert
}
if (self.pfx) {
options.pfx = self.pfx
}
if (self.passphrase) {
options.passphrase = self.passphrase
}
var poolKey = ''
// different types of agents are in different pools
if (Agent !== self.httpModule.Agent) {
poolKey += Agent.name
}
// ca option is only relevant if proxy or destination are https
var proxy = self.proxy
if (typeof proxy === 'string') {
proxy = url.parse(proxy)
}
var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
if (isHttps) {
if (options.ca) {
if (poolKey) {
poolKey += ':'
}
poolKey += options.ca
}
if (typeof options.rejectUnauthorized !== 'undefined') {
if (poolKey) {
poolKey += ':'
}
poolKey += options.rejectUnauthorized
}
if (options.cert) {
if (poolKey) {
poolKey += ':'
}
poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
}
if (options.pfx) {
if (poolKey) {
poolKey += ':'
}
poolKey += options.pfx.toString('ascii')
}
if (options.ciphers) {
if (poolKey) {
poolKey += ':'
}
poolKey += options.ciphers
}
if (options.secureProtocol) {
if (poolKey) {
poolKey += ':'
}
poolKey += options.secureProtocol
}
if (options.secureOptions) {
if (poolKey) {
poolKey += ':'
}
poolKey += options.secureOptions
}
}
if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
// not doing anything special. Use the globalAgent
return self.httpModule.globalAgent
}
// we're using a stored agent. Make sure it's protocol-specific
poolKey = self.uri.protocol + poolKey
// generate a new agent for this setting if none yet exists
if (!self.pool[poolKey]) {
self.pool[poolKey] = new Agent(options)
// properly set maxSockets on new agents
if (self.pool.maxSockets) {
self.pool[poolKey].maxSockets = self.pool.maxSockets
}
}
return self.pool[poolKey]
}
Request.prototype.start = function () {
// start() is called once we are ready to send the outgoing HTTP request.
// this is usually called on the first write(), end() or on nextTick()
var self = this
if (self.timing) {
// All timings will be relative to this request's startTime. In order to do this,
// we need to capture the wall-clock start time (via Date), immediately followed
// by the high-resolution timer (via now()). While these two won't be set
// at the _exact_ same time, they should be close enough to be able to calculate
// high-resolution, monotonically non-decreasing timestamps relative to startTime.
var startTime = new Date().getTime()
var startTimeNow = now()
}
if (self._aborted) {
return
}
self._started = true
self.method = self.method || 'GET'
self.href = self.uri.href
if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
self.setHeader('content-length', self.src.stat.size)
}
if (self._aws) {
self.aws(self._aws, true)
}
// We have a method named auth, which is completely different from the http.request
// auth option. If we don't remove it, we're gonna have a bad time.
var reqOptions = copy(self)
delete reqOptions.auth
debug('make request', self.uri.href)
// node v6.8.0 now supports a `timeout` value in `http.request()`, but we
// should delete it for now since we handle timeouts manually for better
// consistency with node versions before v6.8.0
delete reqOptions.timeout
try {
self.req = self.httpModule.request(reqOptions)
} catch (err) {
self.emit('error', err)
return
}
if (self.timing) {
self.startTime = startTime
self.startTimeNow = startTimeNow
// Timing values will all be relative to startTime (by comparing to startTimeNow
// so we have an accurate clock)
self.timings = {}
}
var timeout
if (self.timeout && !self.timeoutTimer) {
if (self.timeout < 0) {
timeout = 0
} else if (typeof self.timeout === 'number' && isFinite(self.timeout)) {
timeout = self.timeout
}
}
self.req.on('response', self.onRequestResponse.bind(self))
self.req.on('error', self.onRequestError.bind(self))
self.req.on('drain', function () {
self.emit('drain')
})
self.req.on('socket', function (socket) {
// `._connecting` was the old property which was made public in node v6.1.0
var isConnecting = socket._connecting || socket.connecting
if (self.timing) {
self.timings.socket = now() - self.startTimeNow
if (isConnecting) {
var onLookupTiming = function () {
self.timings.lookup = now() - self.startTimeNow
}
var onConnectTiming = function () {
self.timings.connect = now() - self.startTimeNow
}
socket.once('lookup', onLookupTiming)
socket.once('connect', onConnectTiming)
// clean up timing event listeners if needed on error
self.req.once('error', function () {
socket.removeListener('lookup', onLookupTiming)
socket.removeListener('connect', onConnectTiming)
})
}
}
var setReqTimeout = function () {
// This timeout sets the amount of time to wait *between* bytes sent
// from the server once connected.
//
// In particular, it's useful for erroring if the server fails to send
// data halfway through streaming a response.
self.req.setTimeout(timeout, function () {
if (self.req) {
self.abort()
var e = new Error('ESOCKETTIMEDOUT')
e.code = 'ESOCKETTIMEDOUT'
e.connect = false
self.emit('error', e)
}
})
}
if (timeout !== undefined) {
// Only start the connection timer if we're actually connecting a new
// socket, otherwise if we're already connected (because this is a
// keep-alive connection) do not bother. This is important since we won't
// get a 'connect' event for an already connected socket.
if (isConnecting) {
var onReqSockConnect = function () {
socket.removeListener('connect', onReqSockConnect)
self.clearTimeout()
setReqTimeout()
}
socket.on('connect', onReqSockConnect)
self.req.on('error', function (err) { // eslint-disable-line handle-callback-err
socket.removeListener('connect', onReqSockConnect)
})
// Set a timeout in memory - this block will throw if the server takes more
// than `timeout` to write the HTTP status and headers (corresponding to
// the on('response') event on the client). NB: this measures wall-clock
// time, not the time between bytes sent by the server.
self.timeoutTimer = setTimeout(function () {
socket.removeListener('connect', onReqSockConnect)
self.abort()
var e = new Error('ETIMEDOUT')
e.code = 'ETIMEDOUT'
e.connect = true
self.emit('error', e)
}, timeout)
} else {
// We're already connected
setReqTimeout()
}
}
self.emit('socket', socket)
})
self.emit('request', self.req)
}
Request.prototype.onRequestError = function (error) {
var self = this
if (self._aborted) {
return
}
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' &&
self.agent.addRequestNoreuse) {
self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
self.start()
self.req.end()
return
}
self.clearTimeout()
self.emit('error', error)
}
Request.prototype.onRequestResponse = function (response) {
var self = this
if (self.timing) {
self.timings.response = now() - self.startTimeNow
}
debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
response.on('end', function () {
if (self.timing) {
self.timings.end = now() - self.startTimeNow
response.timingStart = self.startTime
// fill in the blanks for any periods that didn't trigger, such as
// no lookup or connect due to keep alive
if (!self.timings.socket) {
self.timings.socket = 0
}
if (!self.timings.lookup) {
self.timings.lookup = self.timings.socket
}
if (!self.timings.connect) {
self.timings.connect = self.timings.lookup
}
if (!self.timings.response) {
self.timings.response = self.timings.connect
}
debug('elapsed time', self.timings.end)
// elapsedTime includes all redirects
self.elapsedTime += Math.round(self.timings.end)
// NOTE: elapsedTime is deprecated in favor of .timings
response.elapsedTime = self.elapsedTime
// timings is just for the final fetch
response.timings = self.timings
// pre-calculate phase timings as well
response.timingPhases = {
wait: self.timings.socket,
dns: self.timings.lookup - self.timings.socket,
tcp: self.timings.connect - self.timings.lookup,
firstByte: self.timings.response - self.timings.connect,
download: self.timings.end - self.timings.response,
total: self.timings.end
}
}
debug('response end', self.uri.href, response.statusCode, response.headers)
})
if (self._aborted) {
debug('aborted', self.uri.href)
response.resume()
return
}
self.response = response
response.request = self
response.toJSON = responseToJSON
// XXX This is different on 0.10, because SSL is strict by default
if (self.httpModule === https &&
self.strictSSL && (!response.hasOwnProperty('socket') ||
!response.socket.authorized)) {
debug('strict ssl error', self.uri.href)
var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
self.emit('error', new Error('SSL Error: ' + sslErr))
return
}
// Save the original host before any redirect (if it changes, we need to
// remove any authorization headers). Also remember the case of the header
// name because lots of broken servers expect Host instead of host and we
// want the caller to be able to specify this.
self.originalHost = self.getHeader('host')
if (!self.originalHostHeaderName) {
self.originalHostHeaderName = self.hasHeader('host')
}
if (self.setHost) {
self.removeHeader('host')
}
self.clearTimeout()
var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
var addCookie = function (cookie) {
// set the cookie if it's domain in the href's domain.
try {
targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
} catch (e) {
self.emit('error', e)
}
}
response.caseless = caseless(response.headers)
if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
var headerName = response.caseless.has('set-cookie')
if (Array.isArray(response.headers[headerName])) {
response.headers[headerName].forEach(addCookie)
} else {
addCookie(response.headers[headerName])
}
}
if (self._redirect.onResponse(response)) {
return // Ignore the rest of the response
} else {
// Be a good stream and emit end when the response is finished.
// Hack to emit end on close because of a core bug that never fires end
response.on('close', function () {
if (!self._ended) {
self.response.emit('end')
}
})
response.once('end', function () {
self._ended = true
})
var noBody = function (code) {
return (
self.method === 'HEAD' ||
// Informational
(code >= 100 && code < 200) ||
// No Content
code === 204 ||
// Not Modified
code === 304
)
}
var responseContent
if (self.gzip && !noBody(response.statusCode)) {
var contentEncoding = response.headers['content-encoding'] || 'identity'
contentEncoding = contentEncoding.trim().toLowerCase()
// Be more lenient with decoding compressed responses, since (very rarely)
// servers send slightly invalid gzip responses that are still accepted
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
var zlibOptions = {
flush: zlib.Z_SYNC_FLUSH,
finishFlush: zlib.Z_SYNC_FLUSH
}
if (contentEncoding === 'gzip') {
responseContent = zlib.createGunzip(zlibOptions)
response.pipe(responseContent)
} else if (contentEncoding === 'deflate') {
responseContent = zlib.createInflate(zlibOptions)
response.pipe(responseContent)
} else {
// Since previous versions didn't check for Content-Encoding header,
// ignore any invalid values to preserve backwards-compatibility
if (contentEncoding !== 'identity') {
debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
}
responseContent = response
}
} else {
responseContent = response
}
if (self.encoding) {
if (self.dests.length !== 0) {
console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
} else {
responseContent.setEncoding(self.encoding)
}
}
if (self._paused) {
responseContent.pause()
}
self.responseContent = responseContent
self.emit('response', response)
self.dests.forEach(function (dest) {
self.pipeDest(dest)
})
responseContent.on('data', function (chunk) {
if (self.timing && !self.responseStarted) {
self.responseStartTime = (new Date()).getTime()
// NOTE: responseStartTime is deprecated in favor of .timings
response.responseStartTime = self.responseStartTime
}
self._destdata = true
self.emit('data', chunk)
})
responseContent.once('end', function (chunk) {
self.emit('end', chunk)
})
responseContent.on('error', function (error) {
self.emit('error', error)
})
responseContent.on('close', function () { self.emit('close') })
if (self.callback) {
self.readResponseBody(response)
} else { // if no callback
self.on('end', function () {
if (self._aborted) {
debug('aborted', self.uri.href)
return
}
self.emit('complete', response)
})
}
}
debug('finish init function', self.uri.href)
}
Request.prototype.readResponseBody = function (response) {
var self = this
debug("reading response's body")
var buffers = []
var bufferLength = 0
var strings = []
self.on('data', function (chunk) {
if (!Buffer.isBuffer(chunk)) {
strings.push(chunk)
} else if (chunk.length) {
bufferLength += chunk.length
buffers.push(chunk)
}
})
self.on('end', function () {
debug('end event', self.uri.href)
if (self._aborted) {
debug('aborted', self.uri.href)
// `buffer` is defined in the parent scope and used in a closure it exists for the life of the request.
// This can lead to leaky behavior if the user retains a reference to the request object.
buffers = []
bufferLength = 0
return
}
if (bufferLength) {
debug('has body', self.uri.href, bufferLength)
response.body = Buffer.concat(buffers, bufferLength)
if (self.encoding !== null) {
response.body = response.body.toString(self.encoding)
}
// `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
// This can lead to leaky behavior if the user retains a reference to the request object.
buffers = []
bufferLength = 0
} else if (strings.length) {
// The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
// Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
strings[0] = strings[0].substring(1)
}
response.body = strings.join('')
}
if (self._json) {
try {
response.body = JSON.parse(response.body, self._jsonReviver)
} catch (e) {
debug('invalid JSON received', self.uri.href)
}
}
debug('emitting complete', self.uri.href)
if (typeof response.body === 'undefined' && !self._json) {
response.body = self.encoding === null ? Buffer.alloc(0) : ''
}
self.emit('complete', response, response.body)
})
}
Request.prototype.abort = function () {
var self = this
self._aborted = true
if (self.req) {
self.req.abort()
} else if (self.response) {
self.response.destroy()
}
self.clearTimeout()
self.emit('abort')
}
Request.prototype.pipeDest = function (dest) {
var self = this
var response = self.response
// Called after the response is received
if (dest.headers && !dest.headersSent) {
if (response.caseless.has('content-type')) {
var ctname = response.caseless.has('content-type')
if (dest.setHeader) {
dest.setHeader(ctname, response.headers[ctname])
} else {
dest.headers[ctname] = response.headers[ctname]
}
}
if (response.caseless.has('content-length')) {
var clname = response.caseless.has('content-length')
if (dest.setHeader) {
dest.setHeader(clname, response.headers[clname])
} else {
dest.headers[clname] = response.headers[clname]
}
}
}
if (dest.setHeader && !dest.headersSent) {
for (var i in response.headers) {
// If the response content is being decoded, the Content-Encoding header
// of the response doesn't represent the piped content, so don't pass it.
if (!self.gzip || i !== 'content-encoding') {
dest.setHeader(i, response.headers[i])
}
}
dest.statusCode = response.statusCode
}
if (self.pipefilter) {
self.pipefilter(response, dest)
}
}
Request.prototype.qs = function (q, clobber) {
var self = this
var base
if (!clobber && self.uri.query) {
base = self._qs.parse(self.uri.query)
} else {
base = {}
}
for (var i in q) {
base[i] = q[i]
}
var qs = self._qs.stringify(base)
if (qs === '') {
return self
}
self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
self.url = self.uri
self.path = self.uri.path
if (self.uri.host === 'unix') {
self.enableUnixSocket()
}
return self
}
Request.prototype.form = function (form) {
var self = this
if (form) {
if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
self.setHeader('content-type', 'application/x-www-form-urlencoded')
}
self.body = (typeof form === 'string')
? self._qs.rfc3986(form.toString('utf8'))
: self._qs.stringify(form).toString('utf8')
return self
}
// create form-data object
self._form = new FormData()
self._form.on('error', function (err) {
err.message = 'form-data: ' + err.message
self.emit('error', err)
self.abort()
})
return self._form
}
Request.prototype.multipart = function (multipart) {
var self = this
self._multipart.onRequest(multipart)
if (!self._multipart.chunked) {
self.body = self._multipart.body
}
return self
}
Request.prototype.json = function (val) {
var self = this
if (!self.hasHeader('accept')) {
self.setHeader('accept', 'application/json')
}
if (typeof self.jsonReplacer === 'function') {
self._jsonReplacer = self.jsonReplacer
}
self._json = true
if (typeof val === 'boolean') {
if (self.body !== undefined) {
if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
self.body = safeStringify(self.body, self._jsonReplacer)
} else {
self.body = self._qs.rfc3986(self.body)
}
if (!self.hasHeader('content-type')) {
self.setHeader('content-type', 'application/json')
}
}
} else {
self.body = safeStringify(val, self._jsonReplacer)
if (!self.hasHeader('content-type')) {
self.setHeader('content-type', 'application/json')
}
}
if (typeof self.jsonReviver === 'function') {
self._jsonReviver = self.jsonReviver
}
return self
}
Request.prototype.getHeader = function (name, headers) {
var self = this
var result, re, match
if (!headers) {
headers = self.headers
}
Object.keys(headers).forEach(function (key) {
if (key.length !== name.length) {
return
}
re = new RegExp(name, 'i')
match = key.match(re)
if (match) {
result = headers[key]
}
})
return result
}
Request.prototype.enableUnixSocket = function () {
// Get the socket & request paths from the URL
var unixParts = this.uri.path.split(':')
var host = unixParts[0]
var path = unixParts[1]
// Apply unix properties to request
this.socketPath = host
this.uri.pathname = path
this.uri.path = path
this.uri.host = host
this.uri.hostname = host
this.uri.isUnix = true
}
Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
var self = this
self._auth.onRequest(user, pass, sendImmediately, bearer)
return self
}
Request.prototype.aws = function (opts, now) {
var self = this
if (!now) {
self._aws = opts
return self
}
if (opts.sign_version === 4 || opts.sign_version === '4') {
// use aws4
var options = {
host: self.uri.host,
path: self.uri.path,
method: self.method,
headers: self.headers,
body: self.body
}
if (opts.service) {
options.service = opts.service
}
var signRes = aws4.sign(options, {
accessKeyId: opts.key,
secretAccessKey: opts.secret,
sessionToken: opts.session
})
self.setHeader('authorization', signRes.headers.Authorization)
self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
if (signRes.headers['X-Amz-Security-Token']) {
self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
}
} else {
// default: use aws-sign2
var date = new Date()
self.setHeader('date', date.toUTCString())
var auth = {
key: opts.key,
secret: opts.secret,
verb: self.method.toUpperCase(),
date: date,
contentType: self.getHeader('content-type') || '',
md5: self.getHeader('content-md5') || '',
amazonHeaders: aws2.canonicalizeHeaders(self.headers)
}
var path = self.uri.path
if (opts.bucket && path) {
auth.resource = '/' + opts.bucket + path
} else if (opts.bucket && !path) {
auth.resource = '/' + opts.bucket
} else if (!opts.bucket && path) {
auth.resource = path
} else if (!opts.bucket && !path) {
auth.resource = '/'
}
auth.resource = aws2.canonicalizeResource(auth.resource)
self.setHeader('authorization', aws2.authorization(auth))
}
return self
}
Request.prototype.httpSignature = function (opts) {
var self = this
httpSignature.signRequest({
getHeader: function (header) {
return self.getHeader(header, self.headers)
},
setHeader: function (header, value) {
self.setHeader(header, value)
},
method: self.method,
path: self.path
}, opts)
debug('httpSignature authorization', self.getHeader('authorization'))
return self
}
Request.prototype.hawk = function (opts) {
var self = this
self.setHeader('Authorization', hawk.header(self.uri, self.method, opts))
}
Request.prototype.oauth = function (_oauth) {
var self = this
self._oauth.onRequest(_oauth)
return self
}
Request.prototype.jar = function (jar) {
var self = this
var cookies
if (self._redirect.redirectsFollowed === 0) {
self.originalCookieHeader = self.getHeader('cookie')
}
if (!jar) {
// disable cookies
cookies = false
self._disableCookies = true
} else {
var targetCookieJar = jar.getCookieString ? jar : globalCookieJar
var urihref = self.uri.href
// fetch cookie in the Specified host
if (targetCookieJar) {
cookies = targetCookieJar.getCookieString(urihref)
}
}
// if need cookie and cookie is not empty
if (cookies && cookies.length) {
if (self.originalCookieHeader) {
// Don't overwrite existing Cookie header
self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
} else {
self.setHeader('cookie', cookies)
}
}
self._jar = jar
return self
}
// Stream API
Request.prototype.pipe = function (dest, opts) {
var self = this
if (self.response) {
if (self._destdata) {
self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
} else if (self._ended) {
self.emit('error', new Error('You cannot pipe after the response has been ended.'))
} else {
stream.Stream.prototype.pipe.call(self, dest, opts)
self.pipeDest(dest)
return dest
}
} else {
self.dests.push(dest)
stream.Stream.prototype.pipe.call(self, dest, opts)
return dest
}
}
Request.prototype.write = function () {
var self = this
if (self._aborted) { return }
if (!self._started) {
self.start()
}
if (self.req) {
return self.req.write.apply(self.req, arguments)
}
}
Request.prototype.end = function (chunk) {
var self = this
if (self._aborted) { return }
if (chunk) {
self.write(chunk)
}
if (!self._started) {
self.start()
}
if (self.req) {
self.req.end()
}
}
Request.prototype.pause = function () {
var self = this
if (!self.responseContent) {
self._paused = true
} else {
self.responseContent.pause.apply(self.responseContent, arguments)
}
}
Request.prototype.resume = function () {
var self = this
if (!self.responseContent) {
self._paused = false
} else {
self.responseContent.resume.apply(self.responseContent, arguments)
}
}
Request.prototype.destroy = function () {