summaryrefslogtreecommitdiffstats
path: root/netwerk/test/unit/test_proxyconnect.js
blob: 7de1fb39d42043c1506951856b2c7ce53cad7bc7 (plain)
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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// test_connectonly tests happy path of proxy connect
// 1. CONNECT to localhost:socketserver_port
// 2. Write 200 Connection established
// 3. Write data to the tunnel (and read server-side)
// 4. Read data from the tunnel (and write server-side)
// 5. done
// test_connectonly_noproxy tests an http channel with only connect set but
// no proxy configured.
// 1. OnTransportAvailable callback NOT called (checked in step 2)
// 2. StopRequest callback called
// 3. done
// test_connectonly_nonhttp tests an http channel with only connect set with a
// non-http proxy.
// 1. OnTransportAvailable callback NOT called (checked in step 2)
// 2. StopRequest callback called
// 3. done

// -1 then initialized with an actual port from the serversocket
"use strict";

var socketserver_port = -1;

const CC = Components.Constructor;
const ServerSocket = CC(
  "@mozilla.org/network/server-socket;1",
  "nsIServerSocket",
  "init"
);
const BinaryInputStream = CC(
  "@mozilla.org/binaryinputstream;1",
  "nsIBinaryInputStream",
  "setInputStream"
);
const BinaryOutputStream = CC(
  "@mozilla.org/binaryoutputstream;1",
  "nsIBinaryOutputStream",
  "setOutputStream"
);

const STATE_NONE = 0;
const STATE_READ_CONNECT_REQUEST = 1;
const STATE_WRITE_CONNECTION_ESTABLISHED = 2;
const STATE_CHECK_WRITE = 3; // write to the tunnel
const STATE_CHECK_WRITE_READ = 4; // wrote to the tunnel, check connection data
const STATE_CHECK_READ = 5; // read from the tunnel
const STATE_CHECK_READ_WROTE = 6; // wrote to connection, check tunnel data
const STATE_COMPLETED = 100;

const CONNECT_RESPONSE_STRING = "HTTP/1.1 200 Connection established\r\n\r\n";
const CHECK_WRITE_STRING = "hello";
const CHECK_READ_STRING = "world";
const ALPN = "webrtc";

var connectRequest = "";
var checkWriteData = "";
var checkReadData = "";

var threadManager;
var socket;
var streamIn;
var streamOut;
var accepted = false;
var acceptedSocket;
var state = STATE_NONE;
var transportAvailable = false;
var proxiedChannel;
var listener = {
  expectedCode: -1, // uninitialized

  onStartRequest: function test_onStartR() {},

  onDataAvailable: function test_ODA() {
    do_throw("Should not get any data!");
  },

  onStopRequest: function test_onStopR(request, status) {
    if (state === STATE_COMPLETED) {
      Assert.equal(transportAvailable, false, "transport available not called");
      Assert.equal(status, 0x80004005, "error code matches");
      Assert.equal(proxiedChannel.httpProxyConnectResponseCode, 200);
      nextTest();
      return;
    }

    Assert.equal(accepted, true, "socket accepted");
    accepted = false;
  },
};

var upgradeListener = {
  onTransportAvailable: (transport, socketIn, socketOut) => {
    if (!transport || !socketIn || !socketOut) {
      do_throw("on transport available failed");
    }

    if (state !== STATE_CHECK_WRITE) {
      do_throw("bad state");
    }

    transportAvailable = true;

    socketIn.asyncWait(connectHandler, 0, 0, threadManager.mainThread);
    socketOut.asyncWait(connectHandler, 0, 0, threadManager.mainThread);
  },
  QueryInterface: ChromeUtils.generateQI(["nsIHttpUpgradeListener"]),
};

var connectHandler = {
  onInputStreamReady: input => {
    try {
      const bis = new BinaryInputStream(input);
      var data = bis.readByteArray(input.available());

      dataAvailable(data);

      if (state !== STATE_COMPLETED) {
        input.asyncWait(connectHandler, 0, 0, threadManager.mainThread);
      }
    } catch (e) {
      do_throw(e);
    }
  },
  onOutputStreamReady: output => {
    writeData(output);
  },
  QueryInterface: iid => {
    if (
      iid.equals(Ci.nsISupports) ||
      iid.equals(Ci.nsIInputStreamCallback) ||
      iid.equals(Ci.nsIOutputStreamCallback)
    ) {
      return this;
    }
    throw Components.Exception("", Cr.NS_ERROR_NO_INTERFACE);
  },
};

function dataAvailable(data) {
  switch (state) {
    case STATE_READ_CONNECT_REQUEST:
      connectRequest += String.fromCharCode.apply(String, data);
      const headerEnding = connectRequest.indexOf("\r\n\r\n");
      const alpnHeaderIndex = connectRequest.indexOf(`ALPN: ${ALPN}`);

      if (headerEnding != -1) {
        const requestLine = `CONNECT localhost:${socketserver_port} HTTP/1.1`;
        Assert.equal(connectRequest.indexOf(requestLine), 0, "connect request");
        Assert.equal(headerEnding, connectRequest.length - 4, "req head only");
        Assert.notEqual(alpnHeaderIndex, -1, "alpn header found");

        state = STATE_WRITE_CONNECTION_ESTABLISHED;
        streamOut.asyncWait(connectHandler, 0, 0, threadManager.mainThread);
      }

      break;
    case STATE_CHECK_WRITE_READ:
      checkWriteData += String.fromCharCode.apply(String, data);

      if (checkWriteData.length >= CHECK_WRITE_STRING.length) {
        Assert.equal(checkWriteData, CHECK_WRITE_STRING, "correct write data");

        state = STATE_CHECK_READ;
        streamOut.asyncWait(connectHandler, 0, 0, threadManager.mainThread);
      }

      break;
    case STATE_CHECK_READ_WROTE:
      checkReadData += String.fromCharCode.apply(String, data);

      if (checkReadData.length >= CHECK_READ_STRING.length) {
        Assert.equal(checkReadData, CHECK_READ_STRING, "correct read data");

        state = STATE_COMPLETED;

        streamIn.asyncWait(null, 0, 0, null);
        acceptedSocket.close(0);

        nextTest();
      }

      break;
    default:
      do_throw("bad state: " + state);
  }
}

function writeData(output) {
  let bos = new BinaryOutputStream(output);

  switch (state) {
    case STATE_WRITE_CONNECTION_ESTABLISHED:
      bos.write(CONNECT_RESPONSE_STRING, CONNECT_RESPONSE_STRING.length);
      state = STATE_CHECK_WRITE;
      break;
    case STATE_CHECK_READ:
      bos.write(CHECK_READ_STRING, CHECK_READ_STRING.length);
      state = STATE_CHECK_READ_WROTE;
      break;
    case STATE_CHECK_WRITE:
      bos.write(CHECK_WRITE_STRING, CHECK_WRITE_STRING.length);
      state = STATE_CHECK_WRITE_READ;
      break;
    default:
      do_throw("bad state: " + state);
  }
}

function makeChan(url) {
  if (!url) {
    url = "https://localhost:" + socketserver_port + "/";
  }

  var flags =
    Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL |
    Ci.nsILoadInfo.SEC_DONT_FOLLOW_REDIRECTS |
    Ci.nsILoadInfo.SEC_COOKIES_OMIT;

  var chan = NetUtil.newChannel({
    uri: url,
    loadUsingSystemPrincipal: true,
    securityFlags: flags,
  });
  chan = chan.QueryInterface(Ci.nsIHttpChannel);

  var internal = chan.QueryInterface(Ci.nsIHttpChannelInternal);
  internal.HTTPUpgrade(ALPN, upgradeListener);
  internal.setConnectOnly();

  return chan;
}

function socketAccepted(socket1, transport) {
  accepted = true;

  // copied from httpd.js
  const SEGMENT_SIZE = 8192;
  const SEGMENT_COUNT = 1024;

  switch (state) {
    case STATE_NONE:
      state = STATE_READ_CONNECT_REQUEST;
      break;
    default:
      return;
  }

  acceptedSocket = transport;

  try {
    streamIn = transport
      .openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT)
      .QueryInterface(Ci.nsIAsyncInputStream);
    streamOut = transport
      .openOutputStream(0, 0, 0)
      .QueryInterface(Ci.nsIAsyncOutputStream);

    streamIn.asyncWait(connectHandler, 0, 0, threadManager.mainThread);
  } catch (e) {
    transport.close(Cr.NS_BINDING_ABORTED);
    do_throw(e);
  }
}

function stopListening() {
  if (tests && tests.length !== 0 && do_throw) {
    do_throw("should never stop");
  }
}

function createProxy() {
  try {
    threadManager = Cc["@mozilla.org/thread-manager;1"].getService();

    socket = new ServerSocket(-1, true, 1);
    socketserver_port = socket.port;

    socket.asyncListen({
      onSocketAccepted: socketAccepted,
      onStopListening: stopListening,
    });
  } catch (e) {
    do_throw(e);
  }
}

function test_connectonly() {
  Services.prefs.setCharPref("network.proxy.ssl", "localhost");
  Services.prefs.setIntPref("network.proxy.ssl_port", socketserver_port);
  Services.prefs.setBoolPref("network.proxy.allow_hijacking_localhost", true);
  Services.prefs.setIntPref("network.proxy.type", 1);

  var chan = makeChan();
  proxiedChannel = chan.QueryInterface(Ci.nsIProxiedChannel);
  chan.asyncOpen(listener);

  do_test_pending();
}

function test_connectonly_noproxy() {
  clearPrefs();
  var chan = makeChan();
  chan.asyncOpen(listener);

  do_test_pending();
}

function test_connectonly_nonhttp() {
  clearPrefs();

  Services.prefs.setCharPref("network.proxy.socks", "localhost");
  Services.prefs.setIntPref("network.proxy.socks_port", socketserver_port);
  Services.prefs.setBoolPref("network.proxy.allow_hijacking_localhost", true);
  Services.prefs.setIntPref("network.proxy.type", 1);

  var chan = makeChan();
  chan.asyncOpen(listener);

  do_test_pending();
}

function nextTest() {
  transportAvailable = false;

  if (!tests.length) {
    do_test_finished();
    return;
  }

  tests.shift()();
  do_test_finished();
}

var tests = [
  test_connectonly,
  test_connectonly_noproxy,
  test_connectonly_nonhttp,
];

function clearPrefs() {
  Services.prefs.clearUserPref("network.proxy.ssl");
  Services.prefs.clearUserPref("network.proxy.ssl_port");
  Services.prefs.clearUserPref("network.proxy.socks");
  Services.prefs.clearUserPref("network.proxy.socks_port");
  Services.prefs.clearUserPref("network.proxy.allow_hijacking_localhost");
  Services.prefs.clearUserPref("network.proxy.type");
}

function run_test() {
  createProxy();

  registerCleanupFunction(clearPrefs);

  nextTest();
  do_test_pending();
}