1/* Part of SWI-Prolog 2 3 Author: Jan Wielemaker 4 E-mail: J.Wielemaker@vu.nl 5 WWW: http://www.swi-prolog.org 6 Copyright (c) 2014-2015, VU University Amsterdam 7 All rights reserved. 8 9 Redistribution and use in source and binary forms, with or without 10 modification, are permitted provided that the following conditions 11 are met: 12 13 1. Redistributions of source code must retain the above copyright 14 notice, this list of conditions and the following disclaimer. 15 16 2. Redistributions in binary form must reproduce the above copyright 17 notice, this list of conditions and the following disclaimer in 18 the documentation and/or other materials provided with the 19 distribution. 20 21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 24 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 25 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 26 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 27 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 28 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 29 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 31 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 32 POSSIBILITY OF SUCH DAMAGE. 33*/ 34 35:- module(websocket, 36 [ http_open_websocket/3, % +URL, -WebSocket, +Options 37 http_upgrade_to_websocket/3, % :Goal, +Options, +Request 38 ws_send/2, % +WebSocket, +Message 39 ws_receive/2, % +WebSocket, -Message 40 ws_receive/3, % +WebSocket, -Message, +Options 41 ws_close/3, % +WebSocket, +Code, +Message 42 % Low level interface 43 ws_open/3, % +Stream, -WebSocket, +Options 44 ws_property/2 % +WebSocket, ?Property 45 ]). 46:- use_module(library(http/http_dispatch)). 47:- use_module(library(http/http_open)). 48:- use_module(library(http/json)). 49:- use_module(library(sha)). 50:- use_module(library(base64)). 51:- use_module(library(option)). 52:- use_module(library(lists)). 53:- use_module(library(error)). 54:- use_module(library(debug)). 55 56:- meta_predicate 57 http_upgrade_to_websocket( , , ). 58 59:- predicate_options(http_open_websocket/3, 3, 60 [ subprotocols(list(atom)), 61 pass_to(http_open/3, 3) 62 ]). 63:- predicate_options(http_upgrade_to_websocket/3, 2, 64 [ guarded(boolean), 65 subprotocols(list(atom)) 66 ]). 67 68:- use_foreign_library(foreign(websocket)).
96 /******************************* 97 * HTTP SUPPORT * 98 *******************************/
subprotocol(Protocol)
.The following example exchanges a message with the html5rocks.websocket.org echo service:
?- URL = 'ws://html5rocks.websocket.org/echo', http_open_websocket(URL, WS, []), ws_send(WS, text('Hello World!')), ws_receive(WS, Reply), ws_close(WS, 1000, "Goodbye"). URL = 'ws://html5rocks.websocket.org/echo', WS = <stream>(0xe4a440,0xe4a610), Reply = websocket{data:"Hello World!", opcode:text}.
128http_open_websocket(URL, WebSocket, Options) :- 129 phrase(base64(`___SWI-Prolog___`), Bytes), 130 string_codes(Key, Bytes), 131 add_subprotocols(Options, Options1), 132 http_open(URL, In, 133 [ status_code(Status), 134 output(Out), 135 header(sec_websocket_protocol, Selected), 136 header(sec_websocket_accept, AcceptedKey), 137 connection('Keep-alive, Upgrade'), 138 request_header('Upgrade' = websocket), 139 request_header('Sec-WebSocket-Key' = Key), 140 request_header('Sec-WebSocket-Version' = 13) 141 | Options1 142 ]), 143 ( Status == 101, 144 sec_websocket_accept(_{key:Key}, AcceptedKey) 145 -> ws_client_options(Selected, WsOptions), 146 stream_pair(In, Read, Write), % Old API: In and Out 147 stream_pair(Out, Read, Write), % New API: In == Out (= pair) 148 ws_open(Read, WsIn, WsOptions), 149 ws_open(Write, WsOut, WsOptions), 150 stream_pair(WebSocket, WsIn, WsOut) 151 ; close(Out), 152 close(In), 153 permission_error(open, websocket, URL) 154 ). 155 156ws_client_options('', [mode(client)]) :- !. 157ws_client_options(null, [mode(client)]) :- !. 158ws_client_options(Subprotocol, [mode(client), subprotocol(Subprotocol)]). 159 160add_subprotocols(OptionsIn, OptionsOut) :- 161 select_option(subprotocols(Subprotocols), OptionsIn, Options1), 162 !, 163 must_be(list(atom), Subprotocols), 164 atomic_list_concat(Subprotocols, ', ', Value), 165 OptionsOut = [ request_header('Sec-WebSocket-Protocol' = Value) 166 | Options1 167 ]. 168add_subprotocols(Options, Options).
call(Goal, WebSocket)
,
where WebSocket is a socket-pair. Options:
true
(default), guard the execution of Goal and close
the websocket on both normal and abnormal termination of Goal.
If false
, Goal itself is responsible for the created
websocket. This can be used to create a single thread that
manages multiple websockets using I/O multiplexing.infinite
.Note that the Request argument is the last for cooperation with http_handler/3. A simple echo server that can be accessed at =/ws/= can be implemented as:
:- use_module(library(http/websocket)). :- use_module(library(http/thread_httpd)). :- use_module(library(http/http_dispatch)). :- http_handler(root(ws), http_upgrade_to_websocket(echo, []), [spawn([])]). echo(WebSocket) :- ws_receive(WebSocket, Message), ( Message.opcode == close -> true ; ws_send(WebSocket, Message), echo(WebSocket) ).
216http_upgrade_to_websocket(Goal, Options, Request) :- 217 request_websocket_info(Request, Info), 218 debug(websocket(open), 'Websocket request: ~p', [Info]), 219 sec_websocket_accept(Info, AcceptKey), 220 choose_subprotocol(Info, Options, SubProtocol, ExtraHeaders), 221 debug(websocket(open), 'Subprotocol: ~p', [SubProtocol]), 222 http_switch_protocol( 223 open_websocket(Goal, SubProtocol, Options), 224 [ header([ upgrade(websocket), 225 connection('Upgrade'), 226 sec_websocket_accept(AcceptKey) 227 | ExtraHeaders 228 ]) 229 ]). 230 231choose_subprotocol(Info, Options, SubProtocol, ExtraHeaders) :- 232 HdrValue = Info.get(subprotocols), 233 option(subprotocols(ServerProtocols), Options), 234 split_string(HdrValue, ",", " ", RequestProtocols), 235 member(Protocol, RequestProtocols), 236 member(SubProtocol, ServerProtocols), 237 atom_string(SubProtocol, Protocol), 238 !, 239 ExtraHeaders = [ 'Sec-WebSocket-Protocol'(SubProtocol) ]. 240choose_subprotocol(_, _, null, []). 241 242open_websocket(Goal, SubProtocol, Options, HTTPIn, HTTPOut) :- 243 option(timeout(TimeOut), Options, infinite), 244 set_stream(HTTPIn, timeout(TimeOut)), 245 WsOptions = [mode(server), subprotocol(SubProtocol)], 246 ws_open(HTTPIn, WsIn, WsOptions), 247 ws_open(HTTPOut, WsOut, WsOptions), 248 stream_pair(WebSocket, WsIn, WsOut), 249 ( option(guarded(true), Options, true) 250 -> guard_websocket_server(Goal, WebSocket) 251 ; call(Goal, WebSocket) 252 ). 253 254guard_websocket_server(Goal, WebSocket) :- 255 ( catch(call(Goal, WebSocket), E, true) 256 -> ( var(E) 257 -> Msg = bye, Code = 1000 258 ; message_to_string(E, Msg), 259 Code = 1011 260 ) 261 ; Msg = "goal failed", Code = 1011 262 ), 263 catch(ws_close(WebSocket, Code, Msg), Error, 264 print_message(error, Error)). 265 266 267request_websocket_info(Request, Info) :- 268 option(upgrade(Websocket), Request), 269 downcase_atom(Websocket, websocket), 270 option(connection(Connection), Request), 271 connection_contains_upgrade(Connection), 272 option(sec_websocket_key(ClientKey), Request), 273 option(sec_websocket_version(Version), Request), 274 Info0 = _{key:ClientKey, version:Version}, 275 add_option(origin, Request, origin, Info0, Info1), 276 add_option(sec_websocket_protocol, Request, subprotocols, Info1, Info2), 277 add_option(sec_websocket_extensions, Request, extensions, Info2, Info). 278 279connection_contains_upgrade(Connection) :- 280 split_string(Connection, ",", " ", Tokens), 281 member(Token, Tokens), 282 string_lower(Token, "upgrade"), 283 !. 284 285add_option(OptionName, Request, Key, Dict0, Dict) :- 286 Option =.. [OptionName,Value], 287 option(Option, Request), 288 !, 289 Dict = Dict0.put(Key,Value). 290add_option(_, _, _, Dict, Dict).
296sec_websocket_accept(Info, AcceptKey) :- 297 string_concat(Info.key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", Str), 298 sha_hash(Str, Hash, [ algorithm(sha1) ]), 299 phrase(base64(Hash), Encoded), 300 string_codes(AcceptKey, Encoded). 301 302 303 /******************************* 304 * HIGH LEVEL INTERFACE * 305 *******************************/
text(+Text)
, but all character codes produced by Content
must be in the range [0..255]. Typically, Content will be
an atom or string holding binary data.text(+Text)
, provided for consistency.opcode
key. Other keys
used are:
string
, prolog
or json
. See ws_receive/3.Note that ws_start_message/3 does not unlock the stream. This is done by ws_send/1. This implies that multiple threads can use ws_send/2 and the messages are properly serialized.
349ws_send(WsStream, Message) :- 350 message_opcode(Message, OpCode), 351 setup_call_cleanup( 352 ws_start_message(WsStream, OpCode, 0), 353 write_message_data(WsStream, Message), 354 ws_send(WsStream)). 355 356message_opcode(Message, OpCode) :- 357 is_dict(Message), 358 !, 359 to_opcode(Message.opcode, OpCode). 360message_opcode(Message, OpCode) :- 361 functor(Message, Name, _), 362 ( text_functor(Name) 363 -> to_opcode(text, OpCode) 364 ; to_opcode(Name, OpCode) 365 ). 366 367text_functor(json). 368text_functor(string). 369text_functor(prolog). 370 371write_message_data(Stream, Message) :- 372 is_dict(Message), 373 !, 374 ( _{code:Code, data:Data} :< Message 375 -> write_message_data(Stream, close(Code, Data)) 376 ; _{format:prolog, data:Data} :< Message 377 -> format(Stream, '~k .~n', [Data]) 378 ; _{format:json, data:Data} :< Message 379 -> json_write_dict(Stream, Data) 380 ; _{data:Data} :< Message 381 -> format(Stream, '~w', Data) 382 ; true 383 ). 384write_message_data(Stream, Message) :- 385 functor(Message, Format, 1), 386 !, 387 arg(1, Message, Data), 388 ( text_functor(Format) 389 -> write_text_message(Format, Stream, Data) 390 ; format(Stream, '~w', [Data]) 391 ). 392write_message_data(_, Message) :- 393 atom(Message), 394 !. 395write_message_data(Stream, close(Code, Data)) :- 396 !, 397 High is (Code >> 8) /\ 0xff, 398 Low is Code /\ 0xff, 399 put_byte(Stream, High), 400 put_byte(Stream, Low), 401 stream_pair(Stream, _, Out), 402 set_stream(Out, encoding(utf8)), 403 format(Stream, '~w', [Data]). 404write_message_data(_, Message) :- 405 type_error(websocket_message, Message). 406 407write_text_message(json, Stream, Data) :- 408 !, 409 json_write_dict(Stream, Data). 410write_text_message(prolog, Stream, Data) :- 411 !, 412 format(Stream, '~k .', [Data]). 413write_text_message(_, Stream, Data) :- 414 format(Stream, '~w', [Data]).
close
and data to the atom
end_of_file
.
If ping
message is received and WebSocket is a stream pair,
ws_receive/1 replies with a pong
and waits for the next
message.
The predicate ws_receive/3 processes the following options:
456ws_receive(WsStream, Message) :- 457 ws_receive(WsStream, Message, []). 458 459ws_receive(WsStream, Message, Options) :- 460 ws_read_header(WsStream, Code, RSV), 461 debug(websocket, 'ws_receive(~p): OpCode=~w, RSV=~w', 462 [WsStream, Code, RSV]), 463 ( Code == end_of_file 464 -> Message = websocket{opcode:close, data:end_of_file} 465 ; ( ws_opcode(OpCode, Code) 466 -> true 467 ; OpCode = Code 468 ), 469 read_data(OpCode, WsStream, Data, Options), 470 ( OpCode == ping, 471 reply_pong(WsStream, Data.data) 472 -> ws_receive(WsStream, Message, Options) 473 ; ( RSV == 0 474 -> Message = Data 475 ; Message = Data.put(rsv, RSV) 476 ) 477 ) 478 ), 479 debug(websocket, 'ws_receive(~p) --> ~p', [WsStream, Message]). 480 481read_data(close, WsStream, 482 websocket{opcode:close, code:Code, format:string, data:Data}, _Options) :- 483 !, 484 get_byte(WsStream, High), 485 ( High == -1 486 -> Code = 1000, 487 Data = "" 488 ; get_byte(WsStream, Low), 489 Code is High<<8 \/ Low, 490 stream_pair(WsStream, In, _), 491 set_stream(In, encoding(utf8)), 492 read_string(WsStream, _Len, Data) 493 ). 494read_data(text, WsStream, Data, Options) :- 495 !, 496 option(format(Format), Options, string), 497 read_text_data(Format, WsStream, Data, Options). 498read_data(OpCode, WsStream, websocket{opcode:OpCode, format:string, data:Data}, _Options) :- 499 read_string(WsStream, _Len, Data).
506read_text_data(string, WsStream, 507 websocket{opcode:text, format:string, data:Data}, _Options) :- 508 !, 509 read_string(WsStream, _Len, Data). 510read_text_data(json, WsStream, 511 websocket{opcode:text, format:json, data:Data}, Options) :- 512 !, 513 json_read_dict(WsStream, Data, Options). 514read_text_data(prolog, WsStream, 515 websocket{opcode:text, format:prolog, data:Data}, Options) :- 516 !, 517 read_term(WsStream, Data, Options). 518read_text_data(Format, _, _, _) :- 519 domain_error(format, Format). 520 521reply_pong(WebSocket, Data) :- 522 stream_pair(WebSocket, _In, Out), 523 is_stream(Out), 524 ws_send(Out, pong(Data)).
close
message if
this was not already sent and wait for the close reply.
540ws_close(WebSocket, Code, Data) :- 541 setup_call_cleanup( 542 true, 543 ws_close_(WebSocket, Code, Data), 544 close(WebSocket)). 545 546ws_close_(WebSocket, Code, Data) :- 547 stream_pair(WebSocket, In, Out), 548 ( ( var(Out) 549 ; ws_property(Out, status, closed) 550 ) 551 -> debug(websocket(close), 552 'Output stream of ~p already closed', [WebSocket]) 553 ; ws_send(WebSocket, close(Code, Data)), 554 close(Out), 555 debug(websocket(close), '~p: closed output', [WebSocket]), 556 ( ( var(In) 557 ; ws_property(In, status, closed) 558 ) 559 -> debug(websocket(close), 560 'Input stream of ~p already closed', [WebSocket]) 561 ; ws_receive(WebSocket, Reply), 562 ( Reply.opcode == close 563 -> debug(websocket(close), '~p: close confirmed', [WebSocket]) 564 ; throw(error(websocket_error(unexpected_message, Reply), _)) 565 ) 566 ) 567 ).
server
or client
. If client
, messages are sent
as masked.true
(default), closing WSStream also closes Stream.subprotocols
option of http_open_websocket/3 and
http_upgrade_to_websocket/3.A typical sequence to turn a pair of streams into a WebSocket is here:
..., Options = [mode(server), subprotocol(chat)], ws_open(Input, WsInput, Options), ws_open(Output, WsOutput, Options), stream_pair(WebSocket, WsInput, WsOutput).
text
,
binary
, close
, ping
or pong
. RSV is reserved for
extensions. After this call, the application usually writes data
to WSStream and uses ws_send/1 to complete the message.
Depending on OpCode, the stream is switched to binary (for
OpCode is binary
) or text using utf8
encoding (all other
OpCode values). For example, to a JSON message can be send
using:
ws_send_json(WSStream, JSON) :- ws_start_message(WSStream, text), json_write(WSStream, JSON), ws_send(WSStream).
close
, close the stream.false
, it will wait for an
additional message.ping
is received, it will reply with a pong
on the
matching output stream.pong
is received, it will be ignored.close
is received and a partial message is read,
it generates an exception (TBD: which?). If no partial
message is received, it unified OpCode with close
and
replies with a close
message.If not all data has been read for the previous message, it will first read the remainder of the message. This input is silently discarded. This allows for trailing white space after proper text messages such as JSON, Prolog or XML terms. For example, to read a JSON message, use:
ws_read_json(WSStream, JSON) :- ws_read_header(WSStream, OpCode, RSV), ( OpCode == text, RSV == 0 -> json_read(WSStream, JSON) ; OpCode == close -> JSON = end_of_file ).
673ws_property(WebSocket, Property) :- 674 ws_property_(Property, WebSocket). 675 676ws_property_(subprotocol(Protocol), WebSocket) :- 677 ws_property(WebSocket, subprotocol, Protocol).
683to_opcode(In, Code) :- 684 integer(In), 685 !, 686 must_be(between(0, 15), In), 687 Code = In. 688to_opcode(Name, Code) :- 689 must_be(atom, Name), 690 ( ws_opcode(Name, Code) 691 -> true 692 ; domain_error(ws_opcode, Name) 693 ).
699ws_opcode(continuation, 0). 700ws_opcode(text, 1). 701ws_opcode(binary, 2). 702ws_opcode(close, 8). 703ws_opcode(ping, 9). 704ws_opcode(pong, 10).
711:- public ws_mask/1. 712 713ws_mask(Mask) :- 714 Mask is 1+random(1<<32-1)
WebSocket support
WebSocket is a lightweight message oriented protocol on top of TCP/IP streams. It is typically used as an upgrade of an HTTP connection to provide bi-directional communication, but can also be used in isolation over arbitrary (Prolog) streams.
The SWI-Prolog interface is based on streams and provides ws_open/3 to create a websocket stream from any Prolog stream. Typically, both an input and output stream are wrapped and then combined into a single object using stream_pair/3.
The high-level interface provides http_upgrade_to_websocket/3 to realise a websocket inside the HTTP server infrastructure and http_open_websocket/3 as a layer over http_open/3 to realise a client connection. After establishing a connection, ws_send/2 and ws_receive/2 can be used to send and receive messages. The predicate ws_close/2 is provided to perform the closing handshake and dispose of the stream objects.