Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Hi! I cleaned up your code for you! #5

Merged
merged 1 commit into from

1 participant

@GunioRobot

Hi there!

This is WhitespaceBot. I'm an open-source robot that removes trailing white space in your code, and gives you a gitignore file if you didn't have one!

Why whitespace? Whitespace is an eyesore for developers who use text editors with dark themes. It's not a huge deal, but it's a bit annoying if you use Vim in a terminal. Really, I'm just a proof of concept - GitHub's V3 API allows robots to automatically improve open source projects, and that's really cool. Hopefully, somebody, maybe you!, will fork me and make me even more useful. My owner is funding a bounty to anybody who can add security fixing features to me.

I've only cleaned your most popular project, and I've added you to a list of users not to contact again, so you won't get any more pull requests from me unless you ask. If I'm misbehaving, please email my owner and tell him to turn me off! If this is pull request is of no use to you, please just ignore it.

Thanks!
WhiteSpacebot from Gun.io.

@superfeedr superfeedr merged commit af67a7a into superfeedr:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Oct 28, 2011
  1. Remove whitespace [Gun.io WhitespaceBot]

    Gun.io Whitespace Robot authored
This page is out of date. Refresh to see the latest.
View
20 .gitignore
@@ -0,0 +1,20 @@
+# Compiled source #
+###################
+*.com
+*.class
+*.dll
+*.exe
+*.o
+*.so
+*.pyc
+
+# Logs and databases #
+######################
+*.log
+
+# OS generated files #
+######################
+.DS_Store*
+ehthumbs.db
+Icon?
+Thumbs.db
View
12 README.markdown
@@ -22,28 +22,28 @@ In the listeners section add the following line:
Make sure you also add this line in the <code>Modules</code>
<code>{mod_websocket, []}</code>
-
-
+
+
## Usage
Just connect to the websocket using your browser's API, and send your XMPP traffic over it.
You may find it convenient to use directly [Strophejs](https://github.com/metajack/strophejs) as it's a full XMPP library in Javascript. However, you will have to use [this branch](https://github.com/superfeedr/strophejs) for now, as it adds support for websocket, as the underlying protocol (instead of Bosh).
-To setup a connection :
+To setup a connection :
<code>
// WS_SERVICE should be http://host.tld:5288/ws-xmpp, based on the configuration you chose.
- connection = new Strophe.Connection({protocol: new Strophe.Websocket(WS_SERVICE) });
+ connection = new Strophe.Connection({protocol: new Strophe.Websocket(WS_SERVICE) });
</code>
## TODO
-The most 'urgent' thing to do is to provide fallback mechanisms in this module. For example, support for [socket.io](http://socket.io/) would be amazing, as erlang has its own [implementation](https://github.com/yrashk/socket.io-erlang). Feel free to fork and make it better!
+The most 'urgent' thing to do is to provide fallback mechanisms in this module. For example, support for [socket.io](http://socket.io/) would be amazing, as erlang has its own [implementation](https://github.com/yrashk/socket.io-erlang). Feel free to fork and make it better!
## Thank you
-Sponsored by [Superfeedr](http://superfeedr.com). Special thanks to [Nathan](http://unclenaynay.com/) for his awesome work, [Jack](http://metajack.im/) for his help.
+Sponsored by [Superfeedr](http://superfeedr.com). Special thanks to [Nathan](http://unclenaynay.com/) for his awesome work, [Jack](http://metajack.im/) for his help.
## License
View
2  demo/demo.js
@@ -43,5 +43,5 @@ $(function() {
$('#buttonSend').click(function(event) {
WsDemo.send($('#phrase').val());
$('#phrase').val('');
- });
+ });
});
View
2  demo/index.html
@@ -9,7 +9,7 @@
<form id="connect">
<label for="server">Server:</label> <input id="server" />
<br />
-
+
<label for="un">Username:</label> <input id="un" /> @ <input id="un_server" />
<br />
View
174 demo/strophe.js
@@ -375,7 +375,7 @@ var MD5 = (function () {
*/
/** File: bosh.js
- * Since JavaScript has no facilities for persistent TCP connections, this
+ * Since JavaScript has no facilities for persistent TCP connections, this
* library uses Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate
* a persistent, stateful, two-way connection to an XMPP server. More
* information on BOSH can be found in XEP 124.
@@ -385,7 +385,7 @@ var MD5 = (function () {
* Uses HTML5s websocket as the underlying protocol to allow for fast
* communication from the browser to the XMPP server.
* It needs an Ejabberd server that is able to deal with Websockets.
- */
+ */
/** PrivateFunction: Function.prototype.bind
* Bind a function to an instance.
@@ -393,7 +393,7 @@ var MD5 = (function () {
* This Function object extension method creates a bound method similar
* to those in Python. This means that the 'this' object will point
* to the instance you want. See
- * <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind'>MDC's bind() documentation</a> and
+ * <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind'>MDC's bind() documentation</a> and
* <a href='http://benjamin.smedbergs.us/blog/2007-01-03/bound-functions-and-function-imports-in-javascript/'>Bound Functions and Function Imports in JavaScript</a>
* for a complete explanation.
*
@@ -402,7 +402,7 @@ var MD5 = (function () {
*
* Parameters:
* (Object) obj - The object that will become 'this' in the bound function.
- * (Object) argN - An option argument that will be prepended to the
+ * (Object) argN - An option argument that will be prepended to the
* arguments given for the function call
*
* Returns:
@@ -415,7 +415,7 @@ if (!Function.prototype.bind) {
var _slice = Array.prototype.slice;
var _concat = Array.prototype.concat;
var _args = _slice.call(arguments, 1);
-
+
return function () {
return func.apply(obj ? obj : this,
_concat.call(_args,
@@ -1794,7 +1794,7 @@ Strophe.Connection.prototype = {
this.protocol.connect(this);
this.changeConnectStatus(Strophe.Status.CONNECTING, null);
-
+
// Let's start the throttler.
this._throttleStanzas();
},
@@ -1806,7 +1806,7 @@ Strophe.Connection.prototype = {
xmlns='jabber:client'
xmlns:stream='http://etherx.jabber.org/streams'
version='1.0'>
-
+
*/
start: function() {
this.send($build('stream:stream', {
@@ -1887,7 +1887,7 @@ Strophe.Connection.prototype = {
/** Function: send
* Send a stanza.
*
- * This function is called to push data to the server through the
+ * This function is called to push data to the server through the
* protocol object.
*
* Parameters:
@@ -1907,7 +1907,7 @@ Strophe.Connection.prototype = {
} else if (typeof(elem.tree) === "function") {
if (this._ensureDOMElement(elem.tree())) {
this._stanzas.push(elem.tree());
-
+
}
} else {
if (this._ensureDOMElement(elem)) {
@@ -2113,7 +2113,7 @@ Strophe.Connection.prototype = {
* Start the graceful disconnection process.
*
* This function starts the disconnection process. This process starts
- * by sending unavailable presence.
+ * by sending unavailable presence.
* A timeout handler makes sure that disconnection happens.
*
* The user supplied connection callback will be notified of the
@@ -2178,7 +2178,7 @@ Strophe.Connection.prototype = {
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
- * This is the last piece of the disconnection logic in the XMPP connection.
+ * This is the last piece of the disconnection logic in the XMPP connection.
* This resets the connection and alerts the user's connection callback.
*/
_doDisconnect: function ()
@@ -2211,7 +2211,7 @@ Strophe.Connection.prototype = {
var do_sasl_plain = false;
var do_sasl_digest_md5 = false;
var do_sasl_anonymous = false;
-
+
this.connected = true; // We're connected since we got data
if (elem === null) { return; }
@@ -2262,7 +2262,7 @@ Strophe.Connection.prototype = {
do_sasl_anonymous = true;
}
}
- }
+ }
if(this.status == Strophe.Status.CONNECTING) {
@@ -2501,10 +2501,10 @@ Strophe.Connection.prototype = {
this._addSysHandler(this._sasl_auth1_cb.bind(this), null, "stream:features", null, null);
-
+
// we must send an xmpp:restart now
this.protocol.restart();
-
+
return false;
},
@@ -2739,21 +2739,21 @@ Strophe.Connection.prototype = {
/** PrivateFunction: _throttleStanzas
* _Private_ function to throttle stanzas sent to the protocol.
*
- * Most servers will implement traffic shapers to ensure that a given client does
+ * Most servers will implement traffic shapers to ensure that a given client does
* not consume too many resources.
- * This function just picks stanza in the _stanzas FIFO and sends them to the
- * protocol layer. The protocol layer may also very well implement a specific
+ * This function just picks stanza in the _stanzas FIFO and sends them to the
+ * protocol layer. The protocol layer may also very well implement a specific
* throttling, based on their needs.
- *
- *
- *
+ *
+ *
+ *
*/
_throttleStanzas: function () {
stanza = this._stanzas.shift();
if(stanza) {
this.protocol.send(stanza);
}
- this._throttle_stanzas_handler = setTimeout(this._throttleStanzas.bind(this), 1000 * 1/this.max_stanzas_per_second); //
+ this._throttle_stanzas_handler = setTimeout(this._throttleStanzas.bind(this), 1000 * 1/this.max_stanzas_per_second); //
}
};
@@ -2878,10 +2878,10 @@ Strophe.Request.prototype = {
/** Class: Strophe.Bosh
* BOSH protocol for underlying XMPP connection.
- *
+ *
* This class is the lower level protocol to communicate with the XMPP server, using BOSH.
* It's a simple refactor of the legacy StropheJS code, which used BOSH as well.
- *
+ *
* It can also serve as a 'template' for other underlying protocols, such as XMPP socket (core protocol)
* or Websockets.
*/
@@ -2912,17 +2912,17 @@ Strophe.Bosh = function(service)
// Connection
this.connection = null;
-
+
// Requests stack.
- this._requests = [];
-
+ this._requests = [];
+
this._sendNextRequestTimeout = null;
this.connected = false
this.disconnecting = false
};
Strophe.Bosh.prototype = {
-
+
/** PrivateConstants: Timeout Values
* Timeout values for error states. These values are in seconds.
* These should not be changed unless you know exactly what you are
@@ -2940,44 +2940,44 @@ Strophe.Bosh.prototype = {
TIMEOUT: 1.1,
SECONDARY_TIMEOUT: 0.1,
- /** Function connect
+ /** Function connect
* Connects to the server using Bosh
*/
connect: function(connection) {
this.connection = connection;
this.connected = true
this.disconnecting = false
-
+
body = this._buildBody();
body.attrs({
- to: this.connection.domain,
- wait: this.wait,
- hold: this.hold,
+ to: this.connection.domain,
+ wait: this.wait,
+ hold: this.hold,
content: 'text/xml; charset=utf-8',
'xml:lang': 'en',
'ver': '1.6',
'xmpp:version': '1.0',
'xmlns:xmpp': 'urn:xmpp:xbosh'
});
-
+
this._requests.push(body);
-
+
// setup _sendNextRequest callback every 1/10th of a second
this._sendNextRequestTimeout = setTimeout(this._sendNextRequest.bind(this), 100);
},
-
+
/** Function: disconnect
* Disconnects from the Bosh server
*
- */
+ */
disconnect: function() {
this.disconnecting = true
body = this._buildBody();
body.attrs({type: "terminate"});
this._requests.push(body);
},
-
- /** Function: send
+
+ /** Function: send
* Sends the stanza to the wrapper
*
* This wraps the stanza into a body element for Bosh.
@@ -2990,7 +2990,7 @@ Strophe.Bosh.prototype = {
}
this._requests.push(body);
},
-
+
/** Function: attach
* Attach to an already created and authenticated BOSH session.
*
@@ -3033,7 +3033,7 @@ Strophe.Bosh.prototype = {
this.changeConnectStatus(Strophe.Status.ATTACHED, null);
},
-
+
/** PrivateFunction: _buildBody
* _Private_ helper function to generate the <body/> wrapper for BOSH.
*
@@ -3047,7 +3047,7 @@ Strophe.Bosh.prototype = {
return bodyWrap;
},
-
+
/** PrivateFunction: _sendNextRequest
* _Private_ handler to process events during idle cycle.
*
@@ -3062,7 +3062,7 @@ Strophe.Bosh.prototype = {
}
body.attrs({rid: this.rid++}); // Put the rid
-
+
if (this.sid !== null) {
body.attrs({sid: this.sid});
}
@@ -3171,7 +3171,7 @@ Strophe.Bosh.prototype = {
}
},
-
+
/** PrivateFunction: _dataRecv
* _Private_ handler to processes incoming data from the the connection.
*
@@ -3188,7 +3188,7 @@ Strophe.Bosh.prototype = {
// reactivate the timer to send the next Request
clearTimeout(this._sendNextRequestTimeout);
this._sendNextRequestTimeout = setTimeout(this._sendNextRequest.bind(this), 100);
-
+
try {
var elem = req.getResponse();
} catch (e) {
@@ -3225,7 +3225,7 @@ Strophe.Bosh.prototype = {
}
return;
}
-
+
// check to make sure we don't overwrite these.
if (!this.sid) {
this.sid = elem.getAttribute("sid");
@@ -3233,7 +3233,7 @@ Strophe.Bosh.prototype = {
if (!this.stream_id) {
this.stream_id = elem.getAttribute("authid");
}
-
+
var wind = elem.getAttribute('requests');
if (wind) { this.window = parseInt(wind, 10); }
var hold = elem.getAttribute('hold');
@@ -3246,10 +3246,10 @@ Strophe.Bosh.prototype = {
Strophe.forEachChild(elem, null, function (child) {
that.connection.receiveData(child);
});
-
+
},
-
+
/** PrivateFunction: _onRequestStateChange
* _Private_ handler for Strophe.Request state changes.
*
@@ -3332,22 +3332,22 @@ Strophe.Bosh.prototype = {
}
}
},
-
-
+
+
/** Function: restart
* Send an xmpp:restart stanza.
*/
restart: function () {
body = this._buildBody();
body.attrs({
- to: this.connection.domain,
+ to: this.connection.domain,
'xml:lang': 'en',
'ver': '1.6',
'xmpp:version': '1.0',
'xmlns:xmpp': 'urn:xmpp:xbosh',
'xmpp:restart': true
});
-
+
this._requests.push(body);
},
@@ -3384,56 +3384,56 @@ Strophe.Bosh.prototype = {
this.sid = null;
this.streamId = null;
this.rid = Math.floor(Math.random() * 4294967295);
- },
+ },
};
Strophe.Proto = function(service)
{
// Connection
this.connection = null;
// Requests stack.
- this._requests = [];
+ this._requests = [];
this.connected = false
};
Strophe.Proto.prototype = {
-
- /** Function connect
+
+ /** Function connect
* Connects to the server using websockets.
* It also assigns the connection to this proto
*/
connect: function(connection) {
-
+
},
-
- /** Function disconnect
+
+ /** Function disconnect
* Disconnects from the server
*/
disconnect: function() {
-
+
},
- /** Function finish
+ /** Function finish
* Finishes the connection
*/
finish: function() {
-
+
},
-
- /** Function send
+
+ /** Function send
* Sends messages
*/
send: function(stanza) {
-
+
},
-
+
/** Function: restart
* Send an xmpp:restart stanza.
*/
restart: function() {
-
+
}
}
-
+
/*
Fucntion to make sure we can ue a DomParser... even in IE
*/
@@ -3467,13 +3467,13 @@ Strophe.Websocket = function(service)
this.service = service;
// Requests stack.
- this._requests = [];
+ this._requests = [];
this.connected = false
};
Strophe.Websocket.prototype = {
-
- /** Function connect
+
+ /** Function connect
* Connects to the server using websockets.
* It also assigns the connection to this proto
*/
@@ -3487,8 +3487,8 @@ Strophe.Websocket.prototype = {
this.socket.onmessage = this._onMessage.bind(this);
}
},
-
- /** Function disconnect
+
+ /** Function disconnect
* Disconnects from the server
*/
disconnect: function() {
@@ -3498,14 +3498,14 @@ Strophe.Websocket.prototype = {
this.socket.close(); // Close the socket
},
- /** Function finish
+ /** Function finish
* Finishes the connection. It's the last step in the cleanup process.
*/
finish: function() {
this.socket = null; // Makes sure we delete the socket.
},
-
- /** Function send
+
+ /** Function send
* Sends messages
*/
send: function(msg) {
@@ -3513,7 +3513,7 @@ Strophe.Websocket.prototype = {
this.connection.rawOutput(Strophe.serialize(msg));
this.socket.send(Strophe.serialize(msg));
},
-
+
/** Function: restart
* Send an xmpp:restart stanza.
*/
@@ -3522,7 +3522,7 @@ Strophe.Websocket.prototype = {
this.connection.rawOutput(this._startStream());
this.socket.send(this._startStream());
},
-
+
/** PrivateFunction: _onError
* _Private_ function to handle websockets errors.
*
@@ -3542,7 +3542,7 @@ Strophe.Websocket.prototype = {
this.connection.rawOutput(this._startStream());
this.socket.send(this._startStream());
},
-
+
/** PrivateFunction: _onClose
* _Private_ function to handle websockets closing.
*
@@ -3550,25 +3550,25 @@ Strophe.Websocket.prototype = {
_onClose: function(event) {
this.connection._doDisconnect()
},
-
+
/** PrivateFunction: _onError
* _Private_ function to handle websockets messages.
*
* This function parses each of the messages as if they are full documents. [TODO : We may actually want to use a SAX Push parser].
- *
+ *
* Since all XMPP traffic starts with "<stream:stream version='1.0' xml:lang='en' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='3697395463' from='SERVER'>"
* The first stanza will always fail to be parsed...
* Addtionnaly, the seconds stanza will always be a <stream:features> with the stream NS defined in the previous stanza... so we need to 'force' the inclusion of the NS in this stanza!
- *
+ *
* Parameters:
* (string) message - The websocket message.
*/
_onMessage: function(message) {
string = message.data.replace("<stream:features>", "<stream:features xmlns:stream='http://etherx.jabber.org/streams'>") // Ugly hack todeal with the problem of stream ns undefined.
-
+
parser = new DOMParser();
elem = parser.parseFromString(string, "text/xml").documentElement;
-
+
this.connection.xmlInput(elem);
this.connection.rawInput(Strophe.serialize(elem));
@@ -3579,11 +3579,11 @@ Strophe.Websocket.prototype = {
this.connection.receiveData(elem);
}
},
-
+
_startStream: function() {
return "<stream:stream to='" + this.connection.domain + "' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0' />";
},
-
+
_endStream:function() {
return "</stream:stream>";
}
View
8 demo/strophedemo.js
@@ -13,7 +13,7 @@ var StropheDemo = function() {
connection.rawInput = function(log) {
var xml = $($.parseXML(log));
-
+
if(xml.find("body").length){
var from = xml.find("message").attr("from").split("/")[0];
var msg = xml.find("body").text();
@@ -57,11 +57,11 @@ var StropheDemo = function() {
console.log("Attached");
$('#connstate').html('Attached');
}
-
+
if (status) {
console.log(status);
}
-
+
return true;
});
@@ -81,7 +81,7 @@ var StropheDemo = function() {
},
send: function(message, to) {
- var msg = $msg({to: to, from: connection.jid, type: "chat"}).c("body", {xmlns: Strophe.NS.CLIENT}).t(message);
+ var msg = $msg({to: to, from: connection.jid, type: "chat"}).c("body", {xmlns: Strophe.NS.CLIENT}).t(message);
msg.up().c("x", {xmlns: "jabber:x:event"}).c("composing");
connection.send(msg);
}
View
74 src/ejabberd_websocket.erl
@@ -104,7 +104,7 @@ receive_headers(State) ->
?DEBUG("not gen_tcp, ssl? ~p~n", [Binary]),
{Request, Trail} = parse_request(
State,
- State#state.trail ++
+ State#state.trail ++
binary_to_list(Binary)),
State1 = State#state{trail = Trail},
NewState = lists:foldl(
@@ -202,8 +202,8 @@ process_header(State, Data) ->
_ ->
?DEBUG("Bad sub protocol",[]),
#state{end_of_request = true,
- request_handlers = State#state.request_handlers}
- end;
+ request_handlers = State#state.request_handlers}
+ end;
_ ->
?DEBUG("Bad Handshake",[]),
#state{end_of_request = true,
@@ -224,15 +224,15 @@ process_header(State, Data) ->
State;
{ok, HData} ->
PData = case State#state.partial of
- <<>> ->
+ <<>> ->
HData;
- <<X/binary>> ->
+ <<X/binary>> ->
<<X, HData>>
end,
- {_Out, Partial, Pid} = case process_data(State, PData) of
- {O, P} ->
+ {_Out, Partial, Pid} = case process_data(State, PData) of
+ {O, P} ->
{O, P, false};
- {Output, Part, ProcId} ->
+ {Output, Part, ProcId} ->
{Output, Part, ProcId};
Error ->
{Error, undefined, undefined}
@@ -242,7 +242,7 @@ process_header(State, Data) ->
false ->
#state{sockmod = State#state.sockmod,
socket = State#state.socket,
- partial = Partial,
+ partial = Partial,
request_handlers = State#state.request_handlers};
_ ->
#state{sockmod = State#state.sockmod,
@@ -261,7 +261,7 @@ add_header(Name, Value, State) ->
[{Name, Value} | State#state.request_headers].
is_websocket_upgrade(RequestHeaders) ->
- Connection = {'Connection', "Upgrade"} == lists:keyfind('Connection', 1,
+ Connection = {'Connection', "Upgrade"} == lists:keyfind('Connection', 1,
RequestHeaders),
Upgrade = {'Upgrade', "WebSocket"} == lists:keyfind('Upgrade', 1,
RequestHeaders),
@@ -271,28 +271,28 @@ handshake(State) ->
SockMod = State#state.sockmod,
Socket = State#state.socket,
Data = SockMod:recv(Socket, 0, 300000),
- case Data of
+ case Data of
{ok, BinData} ->
?DEBUG("Handshake data received.", [State#state.request_headers]),
{_, Host} = lists:keyfind('Host', 1, State#state.request_headers),
- {_, Origin} = lists:keyfind("Origin",
+ {_, Origin} = lists:keyfind("Origin",
1, State#state.request_headers),
SubProto = sub_protocol(State#state.request_headers),
- {_, Key1} = lists:keyfind("Sec-Websocket-Key1",
- 1,
+ {_, Key1} = lists:keyfind("Sec-Websocket-Key1",
+ 1,
State#state.request_headers),
- {_, Key2} = lists:keyfind("Sec-Websocket-Key2",
- 1,
+ {_, Key2} = lists:keyfind("Sec-Websocket-Key2",
+ 1,
State#state.request_headers),
case websocket_verify_keys(Key1, Key2) of
{Part1, Part2} ->
Sig = websocket_sign(Part1, Part2, BinData),
%% Build response
- Res = build_handshake_response(State#state.socket,
+ Res = build_handshake_response(State#state.socket,
Host,
- Origin,
- State#state.request_path,
- SubProto,
+ Origin,
+ State#state.request_path,
+ SubProto,
Sig),
?DEBUG("Sending handshake response:~p~n",[Res]),
%% send response
@@ -330,9 +330,9 @@ process_data(State, Data) ->
_ ->
SockMod:peername(Socket)
end,
- IP = case PeerRet of
+ IP = case PeerRet of
{ok, IPHere} ->
- XFF = proplists:get_value('X-Forwarded-For',
+ XFF = proplists:get_value('X-Forwarded-For',
RequestHeaders, []),
analyze_ip_xff(IPHere, XFF, Host);
{error, _Error} ->
@@ -361,7 +361,7 @@ process_request(#state{request_method = Method,
process_request(false);
{NPath, _Query} ->
%% Build Request
- LPath = [path_decode(NPE) || NPE <- string:tokens(NPath,
+ LPath = [path_decode(NPE) || NPE <- string:tokens(NPath,
"/")],
Request = #wsrequest{method = Method,
path = LPath,
@@ -370,7 +370,7 @@ process_request(#state{request_method = Method,
wsockmod = SockMod
},
?INFO_MSG("Processing request:~p:~p~n",[Request, State]),
- process(RequestHandlers, Request)
+ process(RequestHandlers, Request)
end;
process_request(State) ->
?DEBUG("Not a handshake: ~p~n", [State]),
@@ -379,19 +379,19 @@ process_request(State) ->
process([], _) ->
false;
process(RequestHandlers, Request) ->
- [{HandlerPathPrefix, HandlerModule} | HandlersLeft] = RequestHandlers,
+ [{HandlerPathPrefix, HandlerModule} | HandlersLeft] = RequestHandlers,
case (lists:prefix(HandlerPathPrefix, Request#wsrequest.path) or
(HandlerPathPrefix==Request#wsrequest.path)) of
true ->
- ?DEBUG("~p matches ~p",
+ ?DEBUG("~p matches ~p",
[Request#wsrequest.path, HandlerPathPrefix]),
%% LocalPath is the path "local to the handler", i.e. if
%% the handler was registered to handle "/test/" and the
%% requested path is "/test/foo/bar", the local path is
%% ["foo", "bar"]
- LocalPath = lists:nthtail(length(HandlerPathPrefix),
+ LocalPath = lists:nthtail(length(HandlerPathPrefix),
Request#wsrequest.path),
- HandlerModule:process(LocalPath, Request);
+ HandlerModule:process(LocalPath, Request);
false ->
process(HandlersLeft, Request)
end.
@@ -416,8 +416,8 @@ websocket_verify_keys(Key1, Key2) ->
P2 = parse_seckey(Key2),
websocket_verify_parsed_sec(P1, P2).
websocket_verify_parsed_sec({N1,S1}, {N2,S2}) ->
- case N1 > ?MAXKEY_LENGTH orelse
- N2 > ?MAXKEY_LENGTH orelse
+ case N1 > ?MAXKEY_LENGTH orelse
+ N2 > ?MAXKEY_LENGTH orelse
S1 == 0 orelse
S2 == 0 of
true ->
@@ -443,19 +443,19 @@ parse_seckey1("", {NumStr,NumSpaces}) ->
{list_to_integer(lists:reverse(NumStr)), NumSpaces};
parse_seckey1([32|T], {Ret,NumSpaces}) -> % ASCII/dec space
parse_seckey1(T, {Ret, 1+NumSpaces});
-parse_seckey1([N|T], {Ret,NumSpaces}) when N >= $0, N =< $9 ->
+parse_seckey1([N|T], {Ret,NumSpaces}) when N >= $0, N =< $9 ->
parse_seckey1(T, {[N|Ret], NumSpaces});
-parse_seckey1([_|T], Acc) ->
+parse_seckey1([_|T], Acc) ->
parse_seckey1(T, Acc).
%% build the handshake response
build_handshake_response(Socket, Host, Origin, Path, SubProto, Sig) ->
- Proto = case Socket of
- {ssl,_} -> "wss://";
- _ -> "ws://"
+ Proto = case Socket of
+ {ssl,_} -> "wss://";
+ _ -> "ws://"
end,
- SubProtoHeader = case SubProto of
- undefined -> "";
+ SubProtoHeader = case SubProto of
+ undefined -> "";
P -> ["Sec-WebSocket-Protocol: ", P, "\r\n"]
end,
{abs_path, APath} = Path,
View
2  src/ejabberd_websocket.hrl
@@ -1,7 +1,7 @@
-record(wsrequest, { headers,
data,
fsmref = false,
- method,
+ method,
path,
wsocket,
wsockmod,
View
42 src/ejabberd_xmpp_websocket.erl
@@ -1,7 +1,7 @@
%%%----------------------------------------------------------------------
%%% File : ejabberd_xmpp_websocket.erl
%%% Author : Nathan Zorn (nathan.zorn@gmail.com)
-%%% Purpose : Implements XMPP over WebSockets
+%%% Purpose : Implements XMPP over WebSockets
%%%----------------------------------------------------------------------
-module(ejabberd_xmpp_websocket).
@@ -127,21 +127,21 @@ process_request(WSockMod, WSock, FsmRef, Data, IP) ->
case validate_request(Data, PayloadSize, MaxStanzaSize) of
{ok, ParsedPayload} ->
case stream_start(ParsedPayload) of
- {Host, Sid, Key} when (FsmRef =:= false) or
+ {Host, Sid, Key} when (FsmRef =:= false) or
(FsmRef =:= undefined) ->
case start(Host, Sid, Key, IP) of
- {ok, Pid} ->
+ {ok, Pid} ->
?DEBUG("Session Pid:~p~n",[Pid]),
gen_fsm:sync_send_all_state_event(
- Pid,
- #wsr{sockmod=WSockMod,
- socket=WSock,
+ Pid,
+ #wsr{sockmod=WSockMod,
+ socket=WSock,
out=[ParsedPayload]}),
{<<"session started">>, <<>>, Pid};
- S ->
+ S ->
?ERROR_MSG("Error starting session:~p~n", [S])
end;
- {_Host, _Sid, _Key} when (FsmRef =/= false) or
+ {_Host, _Sid, _Key} when (FsmRef =/= false) or
(FsmRef =/= undefined) ->
?DEBUG("Stream restart after c2s started. ~p~n",
[FsmRef]),
@@ -162,7 +162,7 @@ process_request(WSockMod, WSock, FsmRef, Data, IP) ->
_ ->
?DEBUG("Bad Request: ~p~n", [Data]),
{<<"bad request">>, <<>>, FsmRef}
- end.
+ end.
%%%----------------------------------------------------------------------
%%% Callback functions from gen_fsm
@@ -200,7 +200,7 @@ init([Sid, Key, IP]) ->
%% {stop, Reason, NewStateData}
%%----------------------------------------------------------------------
handle_event({become_controller, C2SPid}, StateName, StateData) ->
- ?DEBUG("C2SPid:~p~nStateName:~p~nData:~p~n",
+ ?DEBUG("C2SPid:~p~nStateName:~p~nData:~p~n",
[C2SPid, StateName, StateData#state.input]),
case StateData#state.input of
cancel ->
@@ -246,10 +246,10 @@ handle_sync_event({send_xml, Packet}, _From, StateName, StateData) ->
Timer = set_inactivity_timer(StateData#state.pause,
StateData#state.max_inactivity),
lists:foreach(fun ({xmlstreamstart, Name, Attrs}) ->
- send_element(StateData,
+ send_element(StateData,
{xmlstreamstart, Name, Attrs});
({xmlstreamend, End}) ->
- send_element(StateData,
+ send_element(StateData,
{xmlstreamend, End});
({_Name, Element}) ->
send_element(StateData, Element)
@@ -261,8 +261,8 @@ handle_sync_event({send_xml, Packet}, _From, StateName, StateData) ->
websocket_receiver = undefined,
wait_timer = undefined,
timer = Timer}};
-%% Handle writing to c2s
-handle_sync_event(#wsr{out=Payload, socket=WSocket, sockmod=WSockmod},
+%% Handle writing to c2s
+handle_sync_event(#wsr{out=Payload, socket=WSocket, sockmod=WSockmod},
From, StateName, StateData) ->
Reply = ok,
case StateData#state.waiting_input of
@@ -284,7 +284,7 @@ handle_sync_event(#wsr{out=Payload, socket=WSocket, sockmod=WSockmod},
C2SPid, {xmlstreamelement, El})
end, Payload),
{reply, Reply, StateName,
- StateData#state{websocket_s=WSocket,
+ StateData#state{websocket_s=WSocket,
websocket_sockmod=WSockmod,
websocket_receiver=From}}
end;
@@ -295,7 +295,7 @@ handle_sync_event({stop,stream_closed}, _From, _StateName, StateData) ->
Reply = ok,
{stop, normal, Reply, StateData};
handle_sync_event({stop, Reason}, _From, _StateName, StateData) ->
- ?DEBUG("Closing websocket session ~p - Reason: ~p",
+ ?DEBUG("Closing websocket session ~p - Reason: ~p",
[StateData#state.id, Reason]),
Reply = ok,
{stop, normal, Reply, StateData};
@@ -413,7 +413,7 @@ send_text(StateData, Text) ->
(StateData#state.websocket_sockmod):send(StateData#state.websocket_s,
[0, Text, 255]).
-send_element(StateData, {xmlstreamstart, Name, Attrs}) ->
+send_element(StateData, {xmlstreamstart, Name, Attrs}) ->
XmlString = streamstart_tobinary({xmlstreamstart, Name, Attrs}),
send_text(StateData, XmlString);
send_element(StateData, {xmlstreamend, "stream:stream"}) ->
@@ -424,7 +424,7 @@ send_element(StateData, El) ->
send_stream_start(C2SPid, Attrs) ->
StreamTo = case lists:keyfind("to", 1, Attrs) of
{"to", Ato} ->
- case lists:keyfind("version",
+ case lists:keyfind("version",
1, Attrs) of
{"version", AVersion} ->
{Ato, AVersion};
@@ -456,7 +456,7 @@ send_data(FsmRef, Req) ->
?DEBUG("No session started.",[]);
_ ->
?DEBUG("Writing data!.",[]),
- %% write data to c2s
+ %% write data to c2s
gen_fsm:sync_send_all_state_event(FsmRef, Req)
end.
%% Cancel timer and empty message queue.
@@ -484,14 +484,14 @@ stream_start_end(Data) ->
case re:run(Data, "\<stream\:stream.+\>", []) of
{match, _X} ->
%% find to and version
- To = case re:run(Data,
+ To = case re:run(Data,
"to=[\"']?((?:.(?![\"\']?\\s+(?:\\S+)=|[>\"\']))+.)[\"\']?", [{capture,[1]}]) of
{match, [{Start, Finish}]} ->
lists:sublist(Data, Start+1, Finish);
_ ->
undefined
end,
- Version = case re:run(Data,
+ Version = case re:run(Data,
"version=[\"']?((?:.(?![\"\']?\\s+(?:\\S+)=|[>\"\']))+.)[\"\']?", [{capture,[1]}]) of
{match, [{St, Fin}]} ->
lists:sublist(Data, St+1, Fin);
View
66 src/mod_websocket.erl
@@ -22,12 +22,12 @@
-include("ejabberd.hrl").
-include("jlib.hrl").
-include("ejabberd_websocket.hrl").
--record(wsdatastate, {legacy=true,
+-record(wsdatastate, {legacy=true,
ft=undefined,
flen,
packet= <<>>,
buffer= <<>>,
- partial= <<>>
+ partial= <<>>
}).
%%%----------------------------------------------------------------------
%%% API
@@ -47,12 +47,12 @@ process(Path, Req) ->
Y
end,
?DEBUG("Origin is valid.",[]),
- DState = #wsdatastate {legacy=true,
+ DState = #wsdatastate {legacy=true,
buffer=Data,
- ft=undefined,
+ ft=undefined,
partial= <<>> },
case process_data(DState) of
- {<<>>, Part} when is_binary(Part) ->
+ {<<>>, Part} when is_binary(Part) ->
{<<>>, Part};
{Out, <<>>} when is_binary(Out) ->
IP = Req#wsrequest.ip,
@@ -60,8 +60,8 @@ process(Path, Req) ->
ejabberd_xmpp_websocket:process_request(
Req#wsrequest.wsockmod,
Req#wsrequest.wsocket,
- Req#wsrequest.fsmref,
- Out,
+ Req#wsrequest.fsmref,
+ Out,
IP);
Error -> Error %% pass the errors through
end;
@@ -97,55 +97,55 @@ validate_origin([]) ->
validate_origin(Headers) ->
is_tuple(lists:keyfind("Origin", 1, Headers)).
-process_data(DState = #wsdatastate{buffer=undefined}) ->
+process_data(DState = #wsdatastate{buffer=undefined}) ->
{DState#wsdatastate.packet, DState#wsdatastate.partial};
-process_data(DState = #wsdatastate{buffer= <<>>}) ->
+process_data(DState = #wsdatastate{buffer= <<>>}) ->
{DState#wsdatastate.packet, DState#wsdatastate.partial};
-process_data(DState = #wsdatastate{buffer= <<FrameType:8,Buffer/binary>>,
+process_data(DState = #wsdatastate{buffer= <<FrameType:8,Buffer/binary>>,
ft=undefined}) ->
Buffer0 = << <<FrameType>>/binary, Buffer/binary>>,
- process_data(DState#wsdatastate{buffer=Buffer0,
- ft=FrameType,
+ process_data(DState#wsdatastate{buffer=Buffer0,
+ ft=FrameType,
partial= <<>>});
%% "Legacy" frames, 0x00...0xFF
%% or modern closing handshake 0x00{8}
-process_data(DState = #wsdatastate{buffer= <<0, Buffer/binary>>,
+process_data(DState = #wsdatastate{buffer= <<0, Buffer/binary>>,
ft=0}) ->
process_data(DState#wsdatastate{buffer=Buffer, ft=undefined});
process_data(DState = #wsdatastate{buffer= <<255, Rest/binary>>}) ->
%% message received in full
#wsdatastate {partial=OPartial} = DState,
- process_data(DState#wsdatastate{partial= <<>>,
- packet=OPartial,
- ft=undefined,
+ process_data(DState#wsdatastate{partial= <<>>,
+ packet=OPartial,
+ ft=undefined,
buffer=Rest});
-process_data(DState = #wsdatastate{buffer= <<Byte:8, Rest/binary>>,
+process_data(DState = #wsdatastate{buffer= <<Byte:8, Rest/binary>>,
ft=0,
partial=Partial}) ->
- NewPartial = case Partial of
- <<>> -> <<Byte>>;
- _ -> <<Partial/binary, <<Byte>>/binary>>
+ NewPartial = case Partial of
+ <<>> -> <<Byte>>;
+ _ -> <<Partial/binary, <<Byte>>/binary>>
end,
process_data(DState#wsdatastate{buffer=Rest, partial=NewPartial});
-process_data(DState = #wsdatastate{buffer= <<Byte:8, Rest/binary>>,
+process_data(DState = #wsdatastate{buffer= <<Byte:8, Rest/binary>>,
legacy=true,
partial=Partial}) ->
- NewPartial = case Partial of
- <<>> -> <<Byte>>;
- _ -> <<Partial/binary, <<Byte>>/binary>>
+ NewPartial = case Partial of
+ <<>> -> <<Byte>>;
+ _ -> <<Partial/binary, <<Byte>>/binary>>
end,
process_data(DState#wsdatastate{buffer=Rest, partial=NewPartial});
%% "Modern" frames, starting with 0xFF, followed by 64 bit length
process_data(DState = #wsdatastate{buffer= <<Len:64/unsigned-integer,
- Buffer/binary>>,
- ft=255,
+ Buffer/binary>>,
+ ft=255,
flen=undefined}) ->
BitsLen = Len*8,
case Buffer of
- <<Frame:BitsLen/binary, Rest/binary>> ->
- process_data(DState#wsdatastate{ft=undefined,
+ <<Frame:BitsLen/binary, Rest/binary>> ->
+ process_data(DState#wsdatastate{ft=undefined,
flen=undefined,
packet=Frame,
buffer=Rest});
@@ -153,13 +153,13 @@ process_data(DState = #wsdatastate{buffer= <<Len:64/unsigned-integer,
_ ->
DState#wsdatastate{flen=Len, buffer=Buffer}
end;
-process_data(DState = #wsdatastate{buffer=Buffer,
- ft=255,
+process_data(DState = #wsdatastate{buffer=Buffer,
+ ft=255,
flen=Len}) when is_integer(Len) ->
BitsLen = Len*8,
case Buffer of
- <<Frame:BitsLen/binary, Rest/binary>> ->
- process_data(DState#wsdatastate{ft=undefined,
+ <<Frame:BitsLen/binary, Rest/binary>> ->
+ process_data(DState#wsdatastate{ft=undefined,
flen=undefined,
packet=Frame,
buffer=Rest});
@@ -185,7 +185,7 @@ websocket_process_data_test() ->
<<0,"something about tests",255>>,
<<0,"fragment">>],
FakeState = #wsdatastate{ legacy=true,
- ft=undefined,
+ ft=undefined,
buffer= <<>>,
partial= <<>> },
Something went wrong with that request. Please try again.