source: trip-planner-front/node_modules/websocket-driver/lib/websocket/driver/proxy.js

Last change on this file was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.6 KB
Line 
1'use strict';
2
3var Buffer = require('safe-buffer').Buffer,
4 Stream = require('stream').Stream,
5 url = require('url'),
6 util = require('util'),
7 Base = require('./base'),
8 Headers = require('./headers'),
9 HttpParser = require('../http_parser');
10
11var PORTS = { 'ws:': 80, 'wss:': 443 };
12
13var Proxy = function(client, origin, options) {
14 this._client = client;
15 this._http = new HttpParser('response');
16 this._origin = (typeof client.url === 'object') ? client.url : url.parse(client.url);
17 this._url = (typeof origin === 'object') ? origin : url.parse(origin);
18 this._options = options || {};
19 this._state = 0;
20
21 this.readable = this.writable = true;
22 this._paused = false;
23
24 this._headers = new Headers();
25 this._headers.set('Host', this._origin.host);
26 this._headers.set('Connection', 'keep-alive');
27 this._headers.set('Proxy-Connection', 'keep-alive');
28
29 var auth = this._url.auth && Buffer.from(this._url.auth, 'utf8').toString('base64');
30 if (auth) this._headers.set('Proxy-Authorization', 'Basic ' + auth);
31};
32util.inherits(Proxy, Stream);
33
34var instance = {
35 setHeader: function(name, value) {
36 if (this._state !== 0) return false;
37 this._headers.set(name, value);
38 return true;
39 },
40
41 start: function() {
42 if (this._state !== 0) return false;
43 this._state = 1;
44
45 var origin = this._origin,
46 port = origin.port || PORTS[origin.protocol],
47 start = 'CONNECT ' + origin.hostname + ':' + port + ' HTTP/1.1';
48
49 var headers = [start, this._headers.toString(), ''];
50
51 this.emit('data', Buffer.from(headers.join('\r\n'), 'utf8'));
52 return true;
53 },
54
55 pause: function() {
56 this._paused = true;
57 },
58
59 resume: function() {
60 this._paused = false;
61 this.emit('drain');
62 },
63
64 write: function(chunk) {
65 if (!this.writable) return false;
66
67 this._http.parse(chunk);
68 if (!this._http.isComplete()) return !this._paused;
69
70 this.statusCode = this._http.statusCode;
71 this.headers = this._http.headers;
72
73 if (this.statusCode === 200) {
74 this.emit('connect', new Base.ConnectEvent());
75 } else {
76 var message = "Can't establish a connection to the server at " + this._origin.href;
77 this.emit('error', new Error(message));
78 }
79 this.end();
80 return !this._paused;
81 },
82
83 end: function(chunk) {
84 if (!this.writable) return;
85 if (chunk !== undefined) this.write(chunk);
86 this.readable = this.writable = false;
87 this.emit('close');
88 this.emit('end');
89 },
90
91 destroy: function() {
92 this.end();
93 }
94};
95
96for (var key in instance)
97 Proxy.prototype[key] = instance[key];
98
99module.exports = Proxy;
Note: See TracBrowser for help on using the repository browser.