This repository has been archived by the owner on Oct 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.fetch.js
2153 lines (2117 loc) · 70.6 KB
/
app.fetch.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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function() {
'use strict';
/**
* This object represents default options for SocketFetch class.
* This can be set before class initialize.
*/
const SocketFetchOptions = {
/**
* Use this property to set up script import URL.
* This library uses web workders. Sometimes it is necessary to change import path of the
* library.
* By default the script will look in / path for web workers. However bower or combined scripts
* me have been placed in different location so this should be set to locate a file.
*
* Example:
* /path/to/file/%s
*
* Keep the %s. The script will replace it with corresponding file name.
*/
importUrl: null
};
/*******************************************************************************
* Copyright 2016 Pawel Psztyc, The ARC team
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
/* global chrome, Request, Headers, ArcEventSource, ArcRequest, ArcResponse */
var URLSearchParams = URLSearchParams || {};
/**
* A SocketFetch class is similar to fetch API but it uses chrome.socket as a transport.
*
* This library require Zlib to run.
*
* @example
* <code>
* let request = SocketFetch('http://domain.com').fetch().then((response) => {
* if (response.ok) {
* return response.json();
* }
* });
* </code>
*
* TODO: Add progress event.
*/
class SocketFetch extends ArcEventSource {
/**
* Partially based on
* https://github.com/ahmadnassri/chrome.sockets.tcp.xhr/
*
*
*
* @constructor
* @property {String} url Defines the resource that you wish to fetch. This can either be:
* A USVString containing the direct URL of the resource you want to fetch.
*
* @param {String|ArcRequest|Request} url An URL, {@link Request} or {@link ArcRequest} object.
* @property {Object} opts (Optional) An options object containing any custom settings that you
* want to apply to the request. The possible options are:
* - method: The request method, e.g., GET, POST.
* - headers: Any headers you want to add to your request, contained within a Headers object or
* an object literal with ByteString values.
* - body: Any body that you want to add to your request: this can be a Blob, BufferSource,
* FormData, URLSearchParams, or USVString object. Note that a request using the GET or HEAD
* method cannot have a body.
* - redirect: The redirect mode to use: follow or error. If follow is set the result will
* contain redairect information.
*/
constructor(url, opts) {
super();
this._logs = [];
/**
* A original request object.
* This will contain data passed to the constructor.
*
* @type {Request}
*/
this._request = this._createRequest(url, opts);
/**
* The Response interface of the Fetch API represents the response to a request.
*
* @type {Response}
*/
this._response = undefined;
if (typeof opts.debug !== 'undefined') {
this.debug = opts.debug;
} else {
this.debug = false;
}
/**
* True if the request has been aborted.
*/
this.aborted = false;
/**
* A boolean property state represents the socket read status. It can be either:
* STATUS (0) - expecting the message is contain a status line
* HEADERS (1) - expecting the message is containing headers part of the message (headers are
* optional)
* BODY (2) - expecting to read a message body
* DONE (3) - message has been fully read. This status can be set by readSocketError function
* when server closes the connection.
*/
this.state = 0;
/**
* A set of redirects.
*
* @type {Set}
*/
this.redirects = undefined;
/**
* A reference to main promise.
*/
this._mainPromise = {
resolve: undefined,
reject: undefined
};
/**
* Set of informations relevant to current socket connection.
*/
this._connection = {
/**
* Set to true when the secured connection should be made.
*/
useSSL: false,
/**
* Socket ID the instance is operating on.
*
* @type {Number}
*/
socketId: undefined,
/**
* A connection can be made only once in one instance. It fthe flag state is true then
* the implementation will throw an error.
*
* @type {Boolean}
*/
started: false,
/**
* A host the socket is connecting to.
*
* @type {String}
*/
host: undefined,
/**
* A port the socket is connecting on.
*
* @type {Number}
* @default 80
*/
port: 80,
/**
* A integer representing status code of the response.
*
* @type {Number}
*/
status: undefined,
/**
* An optional string representing response status message
*
* @type {String}
*/
statusMessage: undefined,
/**
* A read headers string. It may be incomplete if state equals HEADERS or STATUS.
*
* @type {String}
*/
headers: undefined,
/**
* A read response body. It may be incomplete if readyState does not equals DONE.
*
* @type {Uint8Array}
*/
body: undefined,
/**
* As a shortcut for finding Content-Length header in a headers list. It can be either a
* getter function that is looking for a Content-Length header or a value set after headers
* are parsed.
*
* @type {Number}
*/
contentLength: undefined,
/**
* A shortcut for finding Content-Length header in a headers list. It can be either a getter
* function that is looking for a Content-Length header or a value set after headers are
* parsed
*
* @type {Boolean}
*/
chunked: undefined,
/**
* A flag determining that the response is chunked Transfer-Encoding. When Transfer-Encoding
* header is set to "chunked" then the response will be split in chunks. Every chunk starts
* with hex number of length in chunk followed by new line character (\r\n or CR or 13|10).
* Because message received by the socket most probably will have different buffer size, the
* `readSocketData()` function may contain more than one part of chunk or incomplete part of
* chunk.
*
* @type {Number}
*/
chunkSize: undefined,
/**
* Message sent to the remote machine as a string of source message.
* If the request consisted of binnary data it will be presented as a string.
*
* @type {String}
*/
messageSent: undefined,
/**
* Some stats about the connection
*/
stats: {
/**
* Timestamp of start.
* Set just before connection attempt.
*/
startTime: undefined,
/**
* Time required to create TCP connection.
*/
connect: undefined,
/**
* Time required to send HTTP request to the server.
*/
send: undefined,
/**
* Waiting for a response from the server.
*/
wait: undefined,
/**
* Time required to read entire response from the server.
*/
receive: undefined,
/**
* Time required for SSL/TLS negotiation.
*/
ssl: undefined,
_firstReceived: undefined,
_lastReceived: undefined,
_messageSending: undefined,
_waitingStart: undefined
}
};
/**
* Request timeout settings.
*/
this._timeout = {
/**
* True when connection is timed out.
*
* @type {Boolean}
*/
timedout: false,
/**
* User set timeout (in miliseconds).
*
* @type {Number}
*/
timeout: this._request.timeout,
/**
* An id of timer function.
*
* @type {Number}
*/
timeoutId: undefined
};
/**
* True if the request has FileData object as payload.
* In this case `socket-fetch` must extract generated boudary and update content type
* header to `multipart/form-data;boundary=[extracted boundary]`
*/
this._hasFileData = false;
this._setupUrlData();
}
/**
* Timeout set to the request.
*/
get timeout() {
return this._timeout.timedout;
}
/**
* Get a Request object.
*
* @type {Request}
*/
get request() {
return this._request;
}
/**
* Get a Response object.
*
* @type {Response}
*/
get response() {
return this._response;
}
/**
* Replace popular shemas with port number
*
*/
get protocol2port() {
return {
'http': 80,
'https': 443,
'ftp': 21
};
}
/**
* Status indicating thet expecting a ststus message.
*
* @type {Number}
* @default 0
*/
static get STATUS() {
return 0;
}
/**
* Status indicating thet expecting headers.
*
* @type {Number}
* @default 1
*/
static get HEADERS() {
return 1;
}
/**
* Status indicating thet expecting a body message.
*
* @type {Number}
* @default 2
*/
static get BODY() {
return 2;
}
/**
* Status indicating thet the message has been read and connection is closing or closed.
*
* @type {Number}
* @default 0
*/
static get DONE() {
return 3;
}
/**
* Returns new promise and perform a request.
*
* @return {Promise} Fulfilled promise will result with Resposne object.
*/
fetch() {
return new Promise((resolve, reject) => {
if (this.aborted) {
this._createResponse({includeRedirects: true})
.then(() => {
resolve(this._response);
})
.catch((e) => {
this._cancelTimer();
reject({
'message': e.message
});
this._cleanUp();
});
return;
}
if (this._connection.started) {
reject(new Error('This connection has been made. Create a new class and use it instead.'));
return;
}
this._connection.started = true;
this._connection._readFn = this.readSocketData.bind(this);
this._connection._errorFn = this.readSocketError.bind(this);
this._mainPromise.reject = reject;
this._mainPromise.resolve = resolve;
chrome.sockets.tcp.onReceive.addListener(this._connection._readFn);
chrome.sockets.tcp.onReceiveError.addListener(this._connection._errorFn);
this._authRequest().then(() => this._createConnection());
});
}
// set auth methods.
_authRequest() {
if (!this._request.auth) {
return Promise.resolve();
}
let auth = this._request.auth;
let obj = null;
switch (auth.method) {
case 'ntlm':
obj = new FetchNtlmAuth(auth);
obj.url = this.request.url;
obj.state = 0;
break;
case 'basic':
obj = new FetchBasicAuth(auth);
break;
case 'digest':
obj = new FetchDigestAuth(auth);
obj.url = this.request.url;
obj.httpMethod = this.request.method;
break;
}
if (!obj) {
return Promise.resolve();
}
this.auth = obj;
return Promise.resolve();
}
/** Called after socket has been created and connection yet to be made. */
_createConnection() {
var socketProperties = {
name: 'arc'
};
if (this._connection.socketId) {
this.log('Reusing last socket and connection: ');
this._onConnected();
return;
}
chrome.sockets.tcp.create(socketProperties, (createInfo) => {
this.log('Created socket', createInfo.socketId);
this._connection.socketId = createInfo.socketId;
this.log('Connecting to %s:%d', this._connection.host, this._connection.port);
this._connection.stats.startTime = Date.now();
let promise;
if (this._connection.useSSL) {
promise = this._connectSecure(createInfo.socketId, this._connection.host,
this._connection.port);
} else {
promise = this._connect(createInfo.socketId, this._connection.host, this._connection.port);
}
promise.then(() => {
this._runTimer();
this.log('Connected to socked for host: ', this._connection.host, ' and port ',
this._connection.port);
this._readyState = 1;
this._onConnected();
})
.catch((cause) => {
if (this.redirects) {
// There were a redirects so it has something to display.
// Don't just throw an error, construct a response that is errored.
this._publishResponse({
includeRedirects: true,
error: cause
});
return;
}
this._readyState = 0;
this._mainPromise.reject(cause);
this._cleanUp();
});
});
}
/**
* Connect to a socket using secure connection.
* Note that ths function will result with paused socket.
* It must be unpaused after sending a data to remote host to receive a response.
*
* This method will throw an error when connection can't be made or was unable to secure the
* conection.
*
* @param {Number} socketId ID of the socket that the instance is operating on.
* @param {String} host A host name to connect to
* @param {Number} port A port number to connect to.
*
* @return {Promise} Fulfilled promise when connection has been made. Rejected promise will
* contain an Error object with description message.
*/
_connectSecure(socketId, host, port) {
return new Promise((resolve, reject) => {
chrome.sockets.tcp.setPaused(socketId, true, () => {
let connectionStart = performance.now();
chrome.sockets.tcp.connect(socketId, host, port, (connectResult) => {
this._connection.stats.connect = performance.now() - connectionStart;
if (chrome.runtime.lastError) {
this.log(chrome.runtime.lastError);
reject(chrome.runtime.lastError);
return;
}
if (connectResult !== 0) {
reject('Connection to host ' + host + ' on port ' + port + ' unsuccessful');
return;
}
let secureStart = performance.now();
chrome.sockets.tcp.secure(socketId, (secureResult) => {
if (chrome.runtime.lastError) {
this.log(chrome.runtime.lastError);
reject(chrome.runtime.lastError);
return;
}
this._connection.stats.ssl = performance.now() - secureStart;
if (secureResult !== 0) {
reject('Unable to secure a connection to host ' + host + ' on port ' + port);
return;
}
resolve();
});
});
});
});
}
/**
* Connect to a socket. To use a secure connection call `_connectSecure` method.
* Note that ths function will result with paused socket.
* It must be unpaused after sending a data to remote host to receive a response.
*
* @param {Number} socketId ID of the socket that the instance is operating on.
* @param {String} host A host name to connect to
* @param {Number} port A port number to connect to.
*
* @return {Promise} Fulfilled promise when connection has been made. Rejected promise will
* contain an Error object with description message.
*/
_connect(socketId, host, port) {
return new Promise((resolve, reject) => {
chrome.sockets.tcp.setPaused(socketId, true, () => {
let connectionStart = performance.now();
chrome.sockets.tcp.connect(socketId, host, port, (connectResult) => {
this._connection.stats.connect = performance.now() - connectionStart;
if (chrome.runtime.lastError) {
this.log(chrome.runtime.lastError);
reject(chrome.runtime.lastError);
return;
}
if (connectResult !== 0) {
reject('Connection to host ' + host + ' on port ' + port + ' unsuccessful');
return;
}
resolve();
});
});
});
}
/**
* Shortcut for dispatching a custom event on this.
*
* @param {String} name Name of the event
* @param {Object?} details Optional detail object.
*/
_dispatchCustomEvent(name, details) {
var opts = {
'bubbles': true,
'cancelable': false
};
if (details) {
opts.detail = details;
}
this.dispatchEvent(new CustomEvent(name, opts));
}
/** Disconnect from the socket and release resources. */
disconnect() {
this.log('Disconnect');
if (!this._connection.socketId) {
return Promise.resolve();
}
return new Promise((resolve) => {
chrome.sockets.tcp.disconnect(this._connection.socketId, () => {
if (chrome.runtime.lastError) {
this.log(chrome.runtime.lastError, 'warn');
}
this._readyState = 0;
chrome.sockets.tcp.close(this._connection.socketId, () => {
if (chrome.runtime.lastError) {
this.log(chrome.runtime.lastError, 'warn');
}
this._connection.socketId = undefined;
resolve();
});
});
});
}
/** Set `debug: true` flag in init object to see debug messages */
log(...entry) {
if (this.debug) {
console.log.apply(console, entry);
}
this._logs.push(entry);
}
/**
* Calling abort function will immidietly result with Promise rejection.
* It will close the connection and clean up the resources.
*/
abort() {
this.aborted = true;
this._dispatchCustomEvent('abort');
this.state = SocketFetch.DONE;
this._mainPromise.reject(new Error('Request aborted'));
this._cleanUp();
}
/**
* Create a request object.
*/
_createRequest(url, opts) {
if (url instanceof Request ||
url instanceof ArcRequest) {
return new ArcRequest(url);
}
if (opts.headers) {
opts.headers = new Headers(opts.headers);
} else {
opts.headers = new Headers();
}
var defaults = {
'method': 'GET',
'redirect': 'follow'
};
opts = Object.assign(defaults, opts);
if (['GET', 'HEADER'].indexOf(opts.method.toUpperCase()) !== -1) {
delete opts.body;
}
return new ArcRequest(url, opts);
}
/**
* Create a response object.
*
* @param {Object} opts An options to construct a response object:
* - {Boolean} includeRedirects If true the response will have information about redirects.
* - {Error} error An error object when the response is errored.
* @return {ArcResponse} A response object.
*/
_createResponse(opts) {
return new Promise((resolve, reject) => {
if (opts.error) {
resolve(null);
return;
}
var status = this._connection.status;
if (status < 100 || status > 599) {
reject(new Error(`The response status "${status}" is not allowed.
See HTTP spec for more details: https://tools.ietf.org/html/rfc2616#section-6.1.1`));
return;
} else if (status === undefined) {
reject(new Error(`The response status is empty.
It means that the successful connection wasn't made. Check your request parameters.`));
return;
}
if (this.aborted) {
return;
}
if (this._connection.body) {
resolve(this.decompressData(this._connection.body));
} else {
resolve(this._connection.body);
}
})
.then((body) => {
let stats = Object.assign({}, this._connection.stats);
delete stats._firstReceived;
delete stats._messageSending;
delete stats._waitingStart;
let options = {
status: this._connection.status,
statusText: this._connection.statusMessage,
headers: this._connection.headers,
stats: stats
};
if (opts.error) {
options.error = opts.error;
}
if (opts.includeRedirects && this.redirects && this.redirects.size) {
options.redirects = this.redirects;
}
if (this._connection.status === 401) {
if (this.auth) {
options.auth = this.auth;
} else {
let auth = (this._connection.headers && this._connection.headers.has &&
this._connection.headers.has('www-authenticate')) ?
this._connection.headers.get('www-authenticate') : undefined;
let aObj = {
'method': 'unknown'
};
if (auth) {
auth = auth.toLowerCase();
if (auth.indexOf('ntlm') !== -1) {
aObj.method = 'ntlm';
} else if (auth.indexOf('basic') !== -1) {
aObj.method = 'basic';
} else if (auth.indexOf('digest') !== -1) {
aObj.method = 'digest';
}
}
options.auth = aObj;
}
}
this._response = new ArcResponse(body, options);
this._response.logs = this._logs;
this._logs = [];
});
}
/**
* If timeout init option is set then when connection is established the
* program will start counter after when it fire the connection will be aborted
* (with abort flag and abort event) and `timeout` flag set to true.
*
* Note that timer function in JavaScript environment can't guarantee execution
* after exactly set amount of time. Instead it will fire event in next empty slot
* in event queue.
*
* Note that the timer run at the moment when connection was established.
*/
_runTimer() {
if (!this._timeout.timeout) {
return;
}
this._cancelTimer();
this._timeout.timeoutId = window.setTimeout(() => {
if (this.state !== SocketFetch.DONE && !this._timeout.timedout) {
this._timeout.timedout = true;
this.abort();
}
}, this._timeout.timeout);
}
/**
* Cancel any active timeout timer.
*/
_cancelTimer() {
if (!this._timeout.timeoutId) {
return;
}
window.clearTimeout(this._timeout.timeoutId);
this._timeout.timeoutId = undefined;
}
/** Called when the connection has been established. */
_onConnected() {
if (this.aborted) {
return;
}
var promise;
if (this.auth && this.auth.method === 'ntlm') {
promise = this.generateNtlmMessage();
} else if (this.auth && this.auth.method === 'basic') {
this.setupBasicAuth();
this.auth = undefined; // Don't need it anymore
promise = this.generateMessage();
} else if (this.auth && this.auth.method === 'digest') {
let auth = this.auth.getAuthHeader();
if (auth) {
if (!this._request.headers) {
this._request.headers = new Headers();
}
this._request.headers.set(
'Authorization', auth
);
}
promise = this.generateMessage();
} else {
promise = this.generateMessage();
}
promise.then((buffer) => {
let message = this.arrayBufferToString(buffer);
if (this.debug) {
this.log('Generated message to send\n' + message);
}
this.log('Sending message.');
this._connection.messageSent = message;
this._connection.stats._messageSending = performance.now();
chrome.sockets.tcp.send(this._connection.socketId, buffer, this.onSend.bind(this));
});
}
/**
* Generate a message for socket.
*/
generateMessage() {
return new Promise((resolve, reject) => {
if (this._request.body) {
this._createFileBuffer()
.then((fileBuffer) => {
if (this._hasFileData) {
//extract boundary and update content type header
let boundary = this._getBoundary(fileBuffer);
if (boundary) {
this._request.headers.set('content-type', 'multipart/form-data; boundary=' +
boundary);
}
}
return this._addContentLength(fileBuffer)
.then((buffer) => this._createMessageBuffer(buffer));
})
.then((messageBuffer) => {
resolve(messageBuffer);
})
.catch(reject);
} else {
this._addContentLength(null)
.then(() => this._createMessageBuffer())
.then((messageBuffer) => {
resolve(messageBuffer);
})
.catch(reject);
}
});
}
generateNtlmMessage() {
if (this.auth.state === 0) {
let orygHeaders = this._request.headers;
let msg = this.auth.createMessage1(this._connection.host);
this._request.headers = new Headers({
'Authorization': 'NTLM ' + msg.toBase64()
});
return this._createMessageBuffer()
.then((buffer) => {
this._request.headers = orygHeaders;
return buffer;
});
}
if (this.auth.state === 1) {
let msg = this.auth.createMessage3(this.auth.challenge, this._connection.host);
this.auth.state = 2;
this._request.headers.set('Authorization', 'NTLM ' + msg.toBase64());
return this.generateMessage();
}
return Promise.reject('Unknown auth state...');
}
setupBasicAuth() {
if (!this._request.headers) {
this._request.headers = new Headers();
}
this._request.headers.set(
'Authorization', this.auth.getHeader()
);
}
/**
* Adds the content-length header if required.
* This function will do nothing if the request do not carry a payload or
* when the content length header is already set.
*
* @param {ArrayBuffer} buffer Generated message buffer.
*/
_addContentLength(buffer) {
if (this._request.method === 'GET') {
return Promise.resolve(buffer);
}
//HEAD must set content length header even if it's not carreing payload.
let cl = (this._request.headers && this._request.headers.get &&
this._request.headers.get('Content-Length'));
if (!cl) {
if (buffer) {
this._request.headers.set('Content-Length', buffer.byteLength);
} else {
this._request.headers.set('Content-Length', 0);
}
}
return Promise.resolve(buffer);
}
/**
* Create a HTTP message to be send to the server.
*
* @return {Promise} Fullfiled promise with message ArrayBuffer.
*/
_createMessageBuffer(fileBuffer) {
var headers = [];
var path = this._request.uri.pathname;
var search = this._request.uri.search;
var hash = this._request.uri.hash;
if (search) {
path += search;
}
if (hash && path !== '#') {
path += hash;
}
headers.push(this._request.method + ' ' + path + ' HTTP/1.1');
var port = this._connection.port;
var hostValue = this._connection.host;
var defaultPorts = [80, 443];
if (defaultPorts.indexOf(port) === -1) {
hostValue += ':' + port;
}
headers.push('HOST: ' + hostValue);
if (this._request.headers) {
this._request.headers.forEach((value, key) => {
headers.push(key + ': ' + value);
});
}
var str = headers.join('\r\n');
var buffer = this.stringToArrayBuffer(str);
var endBuffer = new Uint8Array([13, 10, 13, 10]);
return new Promise((resolve, reject) => {
let body;
if (fileBuffer) {
body = new Blob([buffer, endBuffer, fileBuffer]);
} else {
body = new Blob([buffer, endBuffer]);
}
var reader = new FileReader();
reader.addEventListener('loadend', (e) => {
resolve(e.target.result);
});
reader.addEventListener('error', (e) => {
reject(e.message);
});
reader.readAsArrayBuffer(body);
});
}
/**
* Create an ArrayBuffer from payload data.
*/
_createFileBuffer() {
let ct = (this._request.headers && this._request.headers.has('content-type')) ?
this._request.headers.get('content-type') : undefined;
let blobOptions = {};
if (ct) {
blobOptions.type = ct;
}
var body = this._request.body;
if (body instanceof FormData /*||
body instanceof URLSearchParams*/) {
return this._transferAndCreateFileBuffer();
}
return new Promise((resolve, reject) => {
if (typeof body === 'string') {
body = this._normalizeString(body);
body = new Blob([body], blobOptions);
} else if (body instanceof Blob) {
//nothing
} else if (body instanceof ArrayBuffer) {
body = new Blob([body], blobOptions);
} else {
reject(new Error('Unsupported payload.'));
return;
}
var reader = new FileReader();
reader.addEventListener('loadend', (e) => {
resolve(e.target.result);
});
reader.addEventListener('error', (e) => {
reject(e.message);
});
reader.readAsArrayBuffer(body);
});
}
/**
* NormalizeLineEndingsToCRLF
* https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/
* platform/text/LineEnding.cpp&rcl=1458041387&l=101
*
* TODO: Check if using Uint8Array is faster.
*/
_normalizeString(string) {
var result = '';
for (var i = 0; i < string.length; i++) {
let c = string[i];
let p = string[i + 1];
if (c === '\r') {
// Safe to look ahead because of trailing '\0'.
if (p && p !== '\n') {
// Turn CR into CRLF.
result += '\r';
result += '\n';
}
} else if (c === '\n') {
result += '\r';
result += '\n';
} else {
// Leave other characters alone.
result += c;
}
}
return result;
}
_transferAndCreateFileBuffer() {
this._hasFileData = true;
var body = this._request.body;
let request = new Request(this._request.url, {
method: this._request.method,
headers: this._request.headers,
body: body
});
return request.arrayBuffer();
}
/**
* Read a generated by Chrome boundary.
* It will return a non empty string when FormData was passed as an `body` parameter.
*/
_getBoundary(buffer) {
var bufferView = new Uint8Array(buffer);
var startIndex = this.indexOfSubarray(bufferView, [45, 45]);
var endIndex = this.indexOfSubarray(bufferView, [13, 10]);
var boundary = bufferView.subarray(startIndex + 2, endIndex); // it starts with 2x '--'
var str = '';
for (var i = 0, len = boundary.length; i < len; ++i) {