Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add named pipe support for Windows #2075

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
144 changes: 82 additions & 62 deletions doc/ws.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,68 +2,71 @@

## Table of Contents

- [Class: WebSocketServer](#class-websocketserver)
- [new WebSocketServer(options[, callback])](#new-websocketserveroptions-callback)
- [Event: 'close'](#event-close)
- [Event: 'connection'](#event-connection)
- [Event: 'error'](#event-error)
- [Event: 'headers'](#event-headers)
- [Event: 'listening'](#event-listening)
- [Event: 'wsClientError'](#event-wsclienterror)
- [server.address()](#serveraddress)
- [server.clients](#serverclients)
- [server.close([callback])](#serverclosecallback)
- [server.handleUpgrade(request, socket, head, callback)](#serverhandleupgraderequest-socket-head-callback)
- [server.shouldHandle(request)](#servershouldhandlerequest)
- [Class: WebSocket](#class-websocket)
- [Ready state constants](#ready-state-constants)
- [new WebSocket(address[, protocols][, options])](#new-websocketaddress-protocols-options)
- [UNIX Domain Sockets](#unix-domain-sockets)
- [Event: 'close'](#event-close-1)
- [Event: 'error'](#event-error-1)
- [Event: 'message'](#event-message)
- [Event: 'open'](#event-open)
- [Event: 'ping'](#event-ping)
- [Event: 'pong'](#event-pong)
- [Event: 'redirect'](#event-redirect)
- [Event: 'unexpected-response'](#event-unexpected-response)
- [Event: 'upgrade'](#event-upgrade)
- [websocket.addEventListener(type, listener[, options])](#websocketaddeventlistenertype-listener-options)
- [websocket.binaryType](#websocketbinarytype)
- [websocket.bufferedAmount](#websocketbufferedamount)
- [websocket.close([code[, reason]])](#websocketclosecode-reason)
- [websocket.extensions](#websocketextensions)
- [websocket.isPaused](#websocketispaused)
- [websocket.onclose](#websocketonclose)
- [websocket.onerror](#websocketonerror)
- [websocket.onmessage](#websocketonmessage)
- [websocket.onopen](#websocketonopen)
- [websocket.pause()](#websocketpause)
- [websocket.ping([data[, mask]][, callback])](#websocketpingdata-mask-callback)
- [websocket.pong([data[, mask]][, callback])](#websocketpongdata-mask-callback)
- [websocket.protocol](#websocketprotocol)
- [websocket.readyState](#websocketreadystate)
- [websocket.removeEventListener(type, listener)](#websocketremoveeventlistenertype-listener)
- [websocket.resume()](#websocketresume)
- [websocket.send(data[, options][, callback])](#websocketsenddata-options-callback)
- [websocket.terminate()](#websocketterminate)
- [websocket.url](#websocketurl)
- [createWebSocketStream(websocket[, options])](#createwebsocketstreamwebsocket-options)
- [Environment variables](#environment-variables)
- [WS_NO_BUFFER_UTIL](#ws_no_buffer_util)
- [WS_NO_UTF_8_VALIDATE](#ws_no_utf_8_validate)
- [Error codes](#error-codes)
- [WS_ERR_EXPECTED_FIN](#ws_err_expected_fin)
- [WS_ERR_EXPECTED_MASK](#ws_err_expected_mask)
- [WS_ERR_INVALID_CLOSE_CODE](#ws_err_invalid_close_code)
- [WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH](#ws_err_invalid_control_payload_length)
- [WS_ERR_INVALID_OPCODE](#ws_err_invalid_opcode)
- [WS_ERR_INVALID_UTF8](#ws_err_invalid_utf8)
- [WS_ERR_UNEXPECTED_MASK](#ws_err_unexpected_mask)
- [WS_ERR_UNEXPECTED_RSV_1](#ws_err_unexpected_rsv_1)
- [WS_ERR_UNEXPECTED_RSV_2_3](#ws_err_unexpected_rsv_2_3)
- [WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH](#ws_err_unsupported_data_payload_length)
- [WS_ERR_UNSUPPORTED_MESSAGE_LENGTH](#ws_err_unsupported_message_length)
- [ws](#ws)
- [Table of Contents](#table-of-contents)
- [Class: WebSocketServer](#class-websocketserver)
- [new WebSocketServer(options[, callback])](#new-websocketserveroptions-callback)
- [Event: 'close'](#event-close)
- [Event: 'connection'](#event-connection)
- [Event: 'error'](#event-error)
- [Event: 'headers'](#event-headers)
- [Event: 'listening'](#event-listening)
- [Event: 'wsClientError'](#event-wsclienterror)
- [server.address()](#serveraddress)
- [server.clients](#serverclients)
- [server.close([callback])](#serverclosecallback)
- [server.handleUpgrade(request, socket, head, callback)](#serverhandleupgraderequest-socket-head-callback)
- [server.shouldHandle(request)](#servershouldhandlerequest)
- [Class: WebSocket](#class-websocket)
- [Ready state constants](#ready-state-constants)
- [new WebSocket(address, protocols)](#new-websocketaddress-protocols)
- [UNIX Domain Sockets](#unix-domain-sockets)
- [Windows Named Pipes](#windows-named-pipes)
- [Event: 'close'](#event-close-1)
- [Event: 'error'](#event-error-1)
- [Event: 'message'](#event-message)
- [Event: 'open'](#event-open)
- [Event: 'ping'](#event-ping)
- [Event: 'pong'](#event-pong)
- [Event: 'redirect'](#event-redirect)
- [Event: 'unexpected-response'](#event-unexpected-response)
- [Event: 'upgrade'](#event-upgrade)
- [websocket.addEventListener(type, listener[, options])](#websocketaddeventlistenertype-listener-options)
- [websocket.binaryType](#websocketbinarytype)
- [websocket.bufferedAmount](#websocketbufferedamount)
- [websocket.close([code[, reason]])](#websocketclosecode-reason)
- [websocket.isPaused](#websocketispaused)
- [websocket.extensions](#websocketextensions)
- [websocket.onclose](#websocketonclose)
- [websocket.onerror](#websocketonerror)
- [websocket.onmessage](#websocketonmessage)
- [websocket.onopen](#websocketonopen)
- [websocket.pause()](#websocketpause)
- [websocket.ping([data[, mask]][, callback])](#websocketpingdata-mask-callback)
- [websocket.pong([data[, mask]][, callback])](#websocketpongdata-mask-callback)
- [websocket.protocol](#websocketprotocol)
- [websocket.resume()](#websocketresume)
- [websocket.readyState](#websocketreadystate)
- [websocket.removeEventListener(type, listener)](#websocketremoveeventlistenertype-listener)
- [websocket.send(data, options)](#websocketsenddata-options)
- [websocket.terminate()](#websocketterminate)
- [websocket.url](#websocketurl)
- [createWebSocketStream(websocket[, options])](#createwebsocketstreamwebsocket-options)
- [Environment variables](#environment-variables)
- [WS_NO_BUFFER_UTIL](#ws_no_buffer_util)
- [WS_NO_UTF_8_VALIDATE](#ws_no_utf_8_validate)
- [Error codes](#error-codes)
- [WS_ERR_EXPECTED_FIN](#ws_err_expected_fin)
- [WS_ERR_EXPECTED_MASK](#ws_err_expected_mask)
- [WS_ERR_INVALID_CLOSE_CODE](#ws_err_invalid_close_code)
- [WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH](#ws_err_invalid_control_payload_length)
- [WS_ERR_INVALID_OPCODE](#ws_err_invalid_opcode)
- [WS_ERR_INVALID_UTF8](#ws_err_invalid_utf8)
- [WS_ERR_UNEXPECTED_MASK](#ws_err_unexpected_mask)
- [WS_ERR_UNEXPECTED_RSV_1](#ws_err_unexpected_rsv_1)
- [WS_ERR_UNEXPECTED_RSV_2_3](#ws_err_unexpected_rsv_2_3)
- [WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH](#ws_err_unsupported_data_payload_length)
- [WS_ERR_UNSUPPORTED_MESSAGE_LENGTH](#ws_err_unsupported_message_length)

## Class: WebSocketServer

Expand Down Expand Up @@ -341,6 +344,23 @@ ws+unix:///absolute/path/to/uds_socket

it defaults to `/`.

#### Windows Named Pipes

`ws` supports Windows named pipes. To make a request to a named pipe, prepend `\\\\.\\path` to the named pipe path:

```
ws+unix:///\\\\.\\path\\os_tempdir\\named_pipe:/pathname?search_params
```

Note that `:` is the separator between the socket path and the URL path. If the
URL path is omitted

```
ws+unix:///\\\\.\\path\\os_tempdir\\named_pipe
```

it defaults to `/`.

### Event: 'close'

- `code` {Number}
Expand Down
27 changes: 17 additions & 10 deletions lib/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -677,13 +677,13 @@ function initAsClient(websocket, address, protocols, options) {
}

const isSecure = parsedUrl.protocol === 'wss:';
const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
const isIPCUrl = parsedUrl.protocol === 'ws+unix:';
let invalidURLMessage;

if (parsedUrl.protocol !== 'ws:' && !isSecure && !isUnixSocket) {
if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIPCUrl) {
invalidURLMessage =
'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"';
} else if (isUnixSocket && !parsedUrl.pathname) {
} else if (isIPCUrl && !parsedUrl.pathname) {
invalidURLMessage = "The URL's pathname is empty";
} else if (parsedUrl.hash) {
invalidURLMessage = 'The URL contains a fragment identifier';
Expand Down Expand Up @@ -760,20 +760,27 @@ function initAsClient(websocket, address, protocols, options) {
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
}

if (isUnixSocket) {
const parts = opts.path.split(':');
if (isIPCUrl) {
if (opts.path.startsWith('\\\\.\\pipe\\', 1)) {
const [socketPath, path] = opts.path.split(':/');

opts.socketPath = parts[0];
opts.path = parts[1];
opts.socketPath = socketPath.slice(1);
opts.path = path ? `/${path}` : '/';
} else {
const [socketPath, path] = opts.path.split(':');

opts.socketPath = socketPath;
opts.path = path;
}
}

let req;

if (opts.followRedirects) {
if (websocket._redirects === 0) {
websocket._originalUnixSocket = isUnixSocket;
websocket._originalUnixSocket = isIPCUrl;
websocket._originalSecure = isSecure;
websocket._originalHostOrSocketPath = isUnixSocket
websocket._originalHostOrSocketPath = isIPCUrl
? opts.socketPath
: parsedUrl.host;

Expand All @@ -791,7 +798,7 @@ function initAsClient(websocket, address, protocols, options) {
}
}
} else if (websocket.listenerCount('redirect') === 0) {
const isSameHost = isUnixSocket
const isSameHost = isIPCUrl
? websocket._originalUnixSocket
? opts.socketPath === websocket._originalHostOrSocketPath
: false
Expand Down
27 changes: 15 additions & 12 deletions test/websocket-server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,20 +179,16 @@ describe('WebSocketServer', () => {
});

it('uses a precreated http server listening on unix socket', function (done) {
//
// Skip this test on Windows. The URL parser:
//
// - Throws an error if the named pipe uses backward slashes.
// - Incorrectly parses the path if the named pipe uses forward slashes.
//
if (process.platform === 'win32') return this.skip();

const server = http.createServer();
const sockPath = path.join(
const isWin32 = os.platform() === 'win32';
let sockPath = path.join(
os.tmpdir(),
`ws.${crypto.randomBytes(16).toString('hex')}.sock`
);
if (isWin32) {
sockPath = path.join('\\\\.\\pipe', sockPath);
}

const server = http.createServer();
server.listen(sockPath, () => {
const wss = new WebSocket.Server({ server });

Expand All @@ -210,8 +206,15 @@ describe('WebSocketServer', () => {
}
});

const ws = new WebSocket(`ws+unix://${sockPath}:/foo?bar=bar`);
ws.on('open', () => new WebSocket(`ws+unix://${sockPath}`));
let protocol = 'ws+unix://';
if (isWin32) {
// add third `/` to make named pipe a valid URL
protocol += '/';
}
const address = protocol + sockPath;

const ws = new WebSocket(`${address}:/foo?bar=bar`);
ws.on('open', () => new WebSocket(address));
});
});
});
Expand Down