summaryrefslogtreecommitdiffstats
path: root/chrome/test/data/extensions/api_test/socket/api/background.js
blob: 7f78b564ab9c7d340a3a2102b267e4d5a30aeed5 (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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// net/tools/testserver/testserver.py is picky about the format of what it
// calls its "echo" messages. One might go so far as to mutter to oneself that
// it isn't an echo server at all.
//
// The response is based on the request but obfuscated using a random key.
const request = "0100000005320000005hello";
var expectedResponsePattern = /0100000005320000005.{11}/;

const socket = chrome.socket;
var address;
var bytesWritten = 0;
var dataAsString;
var dataRead = [];
var port = -1;
var protocol = "none";
var socketId = 0;
var succeeded = false;
var waitCount = 0;

// Many thanks to Dennis for his StackOverflow answer: http://goo.gl/UDanx
// Since amended to handle BlobBuilder deprecation.
function string2ArrayBuffer(string, callback) {
  var blob = new Blob([string]);
  var f = new FileReader();
  f.onload = function(e) {
    callback(e.target.result);
  };
  f.readAsArrayBuffer(blob);
}

function arrayBuffer2String(buf, callback) {
  var blob = new Blob([new Uint8Array(buf)]);
  var f = new FileReader();
  f.onload = function(e) {
    callback(e.target.result);
  };
  f.readAsText(blob);
}

var testSocketCreation = function() {
  function onGetInfo(info) {
    chrome.test.assertEq(info.socketType, protocol);
    chrome.test.assertFalse(info.connected);

    if (info.peerAddress || info.peerPort) {
      chrome.test.fail('Unconnected socket should not have peer');
    }
    if (info.localAddress || info.localPort) {
      chrome.test.fail('Unconnected socket should not have local binding');
    }

    // TODO(miket): this doesn't work yet. It's possible this will become
    // automatic, but either way we can't forget to clean up.
    //
    //socket.destroy(socketInfo.socketId);

    chrome.test.succeed();
  }

  function onCreate(socketInfo) {
    chrome.test.assertTrue(socketInfo.socketId > 0);

    // Obtaining socket information before a connect() call should be safe, but
    // return empty values.
    socket.getInfo(socketInfo.socketId, onGetInfo);
  }

  socket.create(protocol, {}, onCreate);
};


var testGetInfo = function() {
};

function onDataRead(readInfo) {
  if (readInfo.resultCode > 0 || readInfo.data.byteLength > 0) {
    chrome.test.assertEq(readInfo.resultCode, readInfo.data.byteLength);
  }

  arrayBuffer2String(readInfo.data, function(s) {
      dataAsString = s;  // save this for error reporting
      var match = !!s.match(expectedResponsePattern);
      chrome.test.assertTrue(match, "Received data does not match.");
      succeeded = true;
      chrome.test.succeed();
  });
}

function onWriteOrSendToComplete(writeInfo) {
  bytesWritten += writeInfo.bytesWritten;
  if (bytesWritten == request.length) {
    if (protocol == "tcp")
      socket.read(socketId, onDataRead);
    else
      socket.recvFrom(socketId, onDataRead);
  }
}

function onSetKeepAlive(result) {
  if (protocol == "tcp")
    chrome.test.assertTrue(result, "setKeepAlive failed for TCP.");
  else
    chrome.test.assertFalse(result, "setKeepAlive did not fail for UDP.");

  string2ArrayBuffer(request, function(arrayBuffer) {
      if (protocol == "tcp")
        socket.write(socketId, arrayBuffer, onWriteOrSendToComplete);
      else
        socket.sendTo(socketId, arrayBuffer, address, port,
                      onWriteOrSendToComplete);
    });
}

function onSetNoDelay(result) {
  if (protocol == "tcp")
    chrome.test.assertTrue(result, "setNoDelay failed for TCP.");
  else
    chrome.test.assertFalse(result, "setNoDelay did not fail for UDP.");
  socket.setKeepAlive(socketId, true, 1000, onSetKeepAlive);
}

function onGetInfo(result) {
  chrome.test.assertTrue(!!result.localAddress,
                         "Bound socket should always have local address");
  chrome.test.assertTrue(!!result.localPort,
                         "Bound socket should always have local port");
  chrome.test.assertEq(result.socketType, protocol, "Unexpected socketType");

  if (protocol == "tcp") {
    // NOTE: We're always called with 'localhost', but getInfo will only return
    // IPs, not names.
    chrome.test.assertEq(result.peerAddress, "127.0.0.1",
                         "Peer addresss should be the listen server");
    chrome.test.assertEq(result.peerPort, port,
                         "Peer port should be the listen server");
    chrome.test.assertTrue(result.connected, "Socket should be connected");
  } else {
    chrome.test.assertFalse(result.connected, "UDP socket was not connected");
    chrome.test.assertTrue(!result.peerAddress,
        "Unconnected UDP socket should not have peer address");
    chrome.test.assertTrue(!result.peerPort,
        "Unconnected UDP socket should not have peer port");
  }

  socket.setNoDelay(socketId, true, onSetNoDelay);
}

function onConnectOrBindComplete(result) {
  chrome.test.assertEq(0, result,
                       "Connect or bind failed with error " + result);
  if (result == 0) {
    socket.getInfo(socketId, onGetInfo);
  }
}

function onCreate(socketInfo) {
  socketId = socketInfo.socketId;
  chrome.test.assertTrue(socketId > 0, "failed to create socket");
  if (protocol == "tcp")
    socket.connect(socketId, address, port, onConnectOrBindComplete);
  else
    socket.bind(socketId, "0.0.0.0", 0, onConnectOrBindComplete);
}

function waitForBlockingOperation() {
  if (++waitCount < 10) {
    setTimeout(waitForBlockingOperation, 1000);
  } else {
    // We weren't able to succeed in the given time.
    chrome.test.fail("Operations didn't complete after " + waitCount + " " +
                     "seconds. Response so far was <" + dataAsString + ">.");
  }
}

var testSending = function() {
  dataRead = "";
  succeeded = false;
  waitCount = 0;

  setTimeout(waitForBlockingOperation, 1000);
  socket.create(protocol, {}, onCreate);
};

// Tests listening on a socket and sending/receiving from accepted sockets.
var testSocketListening = function() {
  var tmpSocketId = 0;

  function onServerSocketAccept(acceptInfo) {
    chrome.test.assertEq(0, acceptInfo.resultCode);
    var acceptedSocketId = acceptInfo.socketId;
    socket.read(acceptedSocketId, function(readInfo) {
      arrayBuffer2String(readInfo.data, function(s) {
        var match = !!s.match(request);
        chrome.test.assertTrue(match, "Received data does not match.");
        succeeded = true;
        chrome.test.succeed();
      });
    });
  }

  function onListen(result) {
    chrome.test.assertEq(0, result, "Listen failed.");
    socket.accept(socketId, onServerSocketAccept);

    // Trying to schedule a second accept callback should fail.
    socket.accept(socketId, function(acceptInfo) {
      chrome.test.assertEq(-2, acceptInfo.resultCode);
    });

    // Create a new socket to connect to the TCP server.
    socket.create('tcp', {}, function(socketInfo) {
      tmpSocketId = socketInfo.socketId;
      socket.connect(tmpSocketId, address, port,
        function(result) {
          chrome.test.assertEq(0, result, "Connect failed");

          // Write.
          string2ArrayBuffer(request, function(buf) {
            socket.write(tmpSocketId, buf, function() {});
          });
        });
    });
  }

  function onServerSocketCreate(socketInfo) {
    socketId = socketInfo.socketId;
    socket.listen(socketId, address, port, onListen);
  }

  socket.create('tcp', {}, onServerSocketCreate);
};

var onMessageReply = function(message) {
  var parts = message.split(":");
  test_type = parts[0];
  address = parts[1];
  port = parseInt(parts[2]);
  console.log("Running tests, protocol " + protocol + ", echo server " +
              address + ":" + port);
  if (test_type == 'tcp_server') {
    chrome.test.runTests([ testSocketListening ]);
  } else {
    protocol = test_type;
    chrome.test.runTests([ testSocketCreation, testSending ]);
  }
};

// Find out which protocol we're supposed to test, and which echo server we
// should be using, then kick off the tests.
chrome.test.sendMessage("info_please", onMessageReply);