5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/uiDesigner.xml:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | matrix-websockets
4 |
5 |
6 |
7 |
8 |
9 | com.googlecode.goclipse.goBuilder
10 |
11 |
12 |
13 |
14 |
15 | com.googlecode.goclipse.core.goNature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # matrix-websockets-proxy
2 |
3 | This project provides a websockets wrapper for a Matrix.org homeserver. See
4 | https://github.com/matrix-org/matrix-doc/blob/master/drafts/websockets.rst
5 | for information on the protocol it implements.
6 |
7 | To run it, you will need a working `go` installation, including a correctly-set
8 | [GOPATH](https://golang.org/doc/code.html#GOPATH).
9 |
10 | You can then download and build matrix-websockets-proxy with:
11 |
12 | go get github.com/matrix-org/matrix-websockets-proxy
13 |
14 | The above will clone the repository into
15 | `$GOPATH/src/github.com/matrix-org/matrix-websockets-proxy`, and build the
16 | binary at `$GOPATH/bin/matrix-websockets`.
17 |
18 | To run it, just do:
19 |
20 | $GOPATH/bin/matrix-websockets-proxy
21 |
22 | To rebuild, use:
23 |
24 | go build github.com/matrix-org/matrix-websockets-proxy
25 |
--------------------------------------------------------------------------------
/jenkins.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -ex
4 |
5 | export GOPATH=`pwd`/gopath
6 | cd $GOPATH/src/github.com/matrix-org/matrix-websockets-proxy
7 | go get -t -v ./proxy
8 | go build
9 | go test -v ./proxy
10 |
11 | unformatted=$(find . -name '*.go' -print0 | xargs -0 gofmt -l)
12 | [ -z "$unformatted" ] || {
13 | echo "Unformatted files:"
14 | echo $unformatted
15 | exit 1
16 | }
17 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | // matrix-websockets-proxy provides a websockets interface to a Matrix
2 | // homeserver implementing the REST API.
3 | //
4 | // It listens on a TCP port (localhost:8009 by default), and turns any
5 | // incoming connections into REST requests to the configured homeserver.
6 | //
7 | // It exposes only the one HTTP endpoint '/stream'. It is intended
8 | // that an SSL-aware reverse proxy (such as Apache or nginx) be used in front
9 | // of it, to direct most requests to the homeserver, but websockets requests
10 | // to this proxy.
11 | //
12 | // You can also visit http://localhost:8009/test/test.html, which is a very
13 | // simple client for testing the websocket interface.
14 | //
15 | package main
16 |
17 | import (
18 | "flag"
19 | "fmt"
20 | "log"
21 | "net/http"
22 | "path/filepath"
23 | "runtime"
24 | "time"
25 |
26 | "github.com/gorilla/websocket"
27 | "github.com/matrix-org/matrix-websockets-proxy/proxy"
28 | )
29 |
30 | const (
31 | // timeout for upstream /sync requests (after which it will send back
32 | // an empty response)
33 | syncTimeout = 60 * time.Second
34 | )
35 |
36 | var port = flag.Int("port", 8009, "TCP port to listen on")
37 | var upstreamURL = flag.String("upstream", "http://localhost:8008/", "URL of upstream server")
38 | var testHTML *string
39 |
40 | func init() {
41 | _, srcfile, _, _ := runtime.Caller(0)
42 | def := filepath.Join(filepath.Dir(srcfile), "test")
43 | testHTML = flag.String("testdir", def, "Path to the HTML test resources")
44 | }
45 |
46 | func main() {
47 | flag.Parse()
48 |
49 | fmt.Println("Starting websock server on port", *port)
50 | http.Handle("/test/", http.StripPrefix("/test/", http.FileServer(http.Dir(*testHTML))))
51 | http.HandleFunc("/stream", serveStream)
52 | err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
53 | log.Fatal("ListenAndServe: ", err)
54 | }
55 |
56 | // handle a request to /stream
57 | //
58 | func serveStream(w http.ResponseWriter, r *http.Request) {
59 | log.Println("Got websocket request to", r.URL)
60 |
61 | if r.Method != "GET" {
62 | log.Println("Invalid method", r.Method)
63 | httpError(w, http.StatusMethodNotAllowed)
64 | return
65 | }
66 |
67 | r.URL.Query().Set("timeout", "0")
68 | syncer := &proxy.Syncer{
69 | UpstreamURL: *upstreamURL + "_matrix/client/v2_alpha/sync",
70 | SyncParams: r.URL.Query(),
71 | }
72 |
73 | msg, err := syncer.MakeRequest()
74 | if err != nil {
75 | switch err.(type) {
76 | case *proxy.SyncError:
77 | errp := err.(*proxy.SyncError)
78 | log.Println("sync failed:", string(errp.Body))
79 | w.Header().Set("Content-Type", errp.ContentType)
80 | w.WriteHeader(errp.StatusCode)
81 | w.Write(errp.Body)
82 | default:
83 | log.Println("Error in sync", err)
84 | httpError(w, http.StatusInternalServerError)
85 | }
86 | return
87 | }
88 | syncer.SyncParams.Set("timeout", fmt.Sprintf("%d", syncTimeout/time.Millisecond))
89 |
90 | upgrader := websocket.Upgrader{
91 | Subprotocols: []string{"m.json"},
92 | }
93 | ws, err := upgrader.Upgrade(w, r, nil)
94 | if err != nil {
95 | log.Println(err)
96 | return
97 | }
98 |
99 | c := proxy.New(syncer, ws)
100 | c.SendMessage(msg)
101 | c.Start()
102 | }
103 |
104 | func httpError(w http.ResponseWriter, status int) {
105 | http.Error(w, http.StatusText(status), status)
106 | }
107 |
--------------------------------------------------------------------------------
/matrix-websockets-proxy.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/proxy/conn.go:
--------------------------------------------------------------------------------
1 | package proxy
2 |
3 | import (
4 | "log"
5 | "net/url"
6 | "time"
7 |
8 | "github.com/gorilla/websocket"
9 | )
10 |
11 | const (
12 | // Time allowed to write a message to the peer.
13 | writeWait = 10 * time.Second
14 |
15 | // Time allowed to read the next pong message from the peer.
16 | pongWait = 60 * time.Second
17 |
18 | // Send pings to peer with this period. Must be less than pongWait.
19 | pingPeriod = (pongWait * 9) / 10
20 |
21 | // Maximum message size allowed from peer.
22 | maxMessageBytes = 512
23 | )
24 |
25 | type message struct {
26 | messageType int
27 | body []byte
28 | }
29 |
30 | // A Connection represents a single websocket.
31 | //
32 | // Each connection has three main goroutines:
33 | //
34 | // The writer reads messages from the 'messageSend' channel and writes them
35 | // out to the socket. It will stop when the 'quit' channel is closed. A
36 | // separate writer is required because we have to ensure that only one
37 | // goroutine calls the send methods concurrently.
38 | //
39 | // The reader reads messages from the socket, and processes them, writing
40 | // responses into the messageSend channel. It also has responsibility for
41 | // cleaning up: when it stops, it closes the socket and the 'quit' channel
42 | // (thus stopping writer and syncPump). The reader is stopped
43 | // on errors from the websocket, which can be due to the socket being closed,
44 | // a close response being received, or a ping timeout.
45 | //
46 | // The syncPump calls /sync on the upstream server, and writes responses into
47 | // the messageSend channel. It is stopped by the 'quit' channel being closed.
48 | // On error, it tells the writer to send a close request, to initiate the
49 | // shutdown process.
50 | //
51 | type Connection struct {
52 | ws *websocket.Conn
53 |
54 | send chan message
55 |
56 | // This gets closed when the reader stops, to ensure the sync pump and the
57 | // writer also stop.
58 | quit chan struct{}
59 |
60 | syncer *Syncer
61 | }
62 |
63 | // New creates a new Connection for an incoming websocket upgrade request
64 | func New(syncer *Syncer, ws *websocket.Conn) *Connection {
65 | if syncer == nil {
66 | log.Fatalln("nil value passed as syncer to proxy.New()")
67 | }
68 | if ws == nil {
69 | log.Fatalln("nil value passed as ws to proxy.New()")
70 | }
71 |
72 | return &Connection{
73 | ws: ws,
74 | send: make(chan message, 256),
75 | quit: make(chan struct{}),
76 | syncer: syncer,
77 | }
78 | }
79 |
80 | func (c *Connection) SendMessage(body []byte) {
81 | c.send <- message{
82 | websocket.TextMessage,
83 | body,
84 | }
85 | }
86 |
87 | func (c *Connection) SendClose(closeCode int, text string) {
88 | // XXX: we're allowed to send control frames from any thread, so it
89 | // might be easier to write the message directly to the web socket.
90 | c.send <- message{
91 | websocket.CloseMessage,
92 | websocket.FormatCloseMessage(closeCode, text),
93 | }
94 | }
95 |
96 | func (c *Connection) Start() {
97 | go c.writePump()
98 | go c.syncPump()
99 | go c.reader()
100 | }
101 |
102 | // syncPump repeatedly calls /sync and writes the results to the messageSend
103 | // channel.
104 | func (c *Connection) syncPump() {
105 | log.Println("Starting sync pump")
106 | defer log.Println("Sync pump stopped")
107 |
108 | for {
109 | // check that it's not time to exit
110 | select {
111 | case <-c.quit:
112 | return
113 | default:
114 | }
115 |
116 | body, err := c.syncer.MakeRequest()
117 |
118 | if err != nil {
119 | log.Println("Error performing sync", err)
120 |
121 | // unpack url.Error, whose stringification contains a lot of
122 | // useless info
123 | switch err.(type) {
124 | case *url.Error:
125 | err = err.(*url.Error).Err
126 | }
127 |
128 | // we are constrained to 125 characters in the close message, so
129 | // trim the error string.
130 | errmsg := err.Error()
131 | if len(errmsg) > 100 {
132 | errmsg = errmsg[:100] + "..."
133 | }
134 |
135 | c.SendClose(websocket.CloseInternalServerErr, errmsg)
136 | return
137 | }
138 |
139 | c.SendMessage(body)
140 | }
141 | }
142 |
143 | // writePump pumps messages out to the websocket connection, and takes
144 | // responsibility for sending pings.
145 | func (c *Connection) writePump() {
146 | defer func() { log.Println("Writer stopped") }()
147 |
148 | // start a ticker for sending pings
149 | ticker := time.NewTicker(pingPeriod)
150 | defer ticker.Stop()
151 |
152 | for {
153 | select {
154 | case <-c.quit:
155 | return
156 |
157 | case message := <-c.send:
158 | if err := c.write(message.messageType, message.body); err != nil {
159 | return
160 | }
161 | if message.messageType == websocket.CloseMessage {
162 | // any further attempts to write messages will fail with an
163 | // error, so we may as well give up now
164 | return
165 | }
166 |
167 | case <-ticker.C:
168 | if err := c.write(websocket.PingMessage, nil); err != nil {
169 | return
170 | }
171 | }
172 | }
173 | }
174 |
175 | // helper for writePump: writes a message with the given message type and payload.
176 | func (c *Connection) write(messageType int, payload []byte) error {
177 | c.ws.SetWriteDeadline(time.Now().Add(writeWait))
178 | err := c.ws.WriteMessage(messageType, payload)
179 | if err != nil {
180 | log.Println("Error sending message:", err)
181 | }
182 | return err
183 | }
184 |
185 | func (c *Connection) reader() {
186 | defer log.Println("Reader stopped")
187 |
188 | // close the socket when we exit
189 | defer c.ws.Close()
190 |
191 | // tell the syncPump to close when we exit
192 | defer close(c.quit)
193 |
194 | c.ws.SetReadLimit(maxMessageBytes)
195 | c.ws.SetReadDeadline(time.Now().Add(pongWait))
196 | c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
197 | for {
198 | _, message, err := c.ws.ReadMessage()
199 | if err != nil {
200 | switch err.(type) {
201 | case *websocket.CloseError:
202 | closeErr := err.(*websocket.CloseError)
203 | log.Printf("Socket closed %v; stopping reader\n", *closeErr)
204 | default:
205 | log.Println("Error in reader:", err)
206 | }
207 | return
208 | }
209 | go c.handleMessage(message)
210 | }
211 | }
212 |
213 | // handleMessage processes a message received from the websocket: it determines
214 | // the correct response, and sends it.
215 | func (c *Connection) handleMessage(message []byte) {
216 | log.Println("Got message:", string(message))
217 |
218 | if response := handleRequest(message); response != nil {
219 | c.SendMessage(response)
220 | }
221 | }
222 |
--------------------------------------------------------------------------------
/proxy/request.go:
--------------------------------------------------------------------------------
1 | package proxy
2 |
3 | import (
4 | "encoding/json"
5 | "log"
6 | )
7 |
8 | type jsonRequest struct {
9 | ID *string
10 | Method string
11 | Params map[string]interface{}
12 | }
13 |
14 | type jsonError struct {
15 | ErrCode string `json:"errcode"`
16 | Error string `json:"error"`
17 | }
18 |
19 | type jsonResponse struct {
20 | // this is a pointer so that it can be set to 'nil' to give a null result
21 | ID *string `json:"id"`
22 |
23 | // these are pointers so that we can set them to be empty to omit them
24 | // from the output.
25 | Result *map[string]interface{} `json:"result,omitempty"`
26 | Error *jsonError `json:"error,omitempty"`
27 | }
28 |
29 | // handleRequest gets the correct response for a received message, and returns
30 | // the json encoding
31 | func handleRequest(request []byte) []byte {
32 | var resp *jsonResponse
33 | var jr jsonRequest
34 |
35 | if err := json.Unmarshal(request, &jr); err != nil {
36 | log.Println("Invalid request:", err)
37 | resp = &jsonResponse{
38 | ID: jr.ID,
39 | Error: &jsonError{
40 | ErrCode: "M_NOT_JSON",
41 | Error: err.Error(),
42 | },
43 | }
44 | } else {
45 | resp = handleRequestObject(&jr)
46 | }
47 |
48 | v, err := json.Marshal(resp)
49 | if err != nil {
50 | log.Print("Error marshalling:", err)
51 | return nil
52 | }
53 | return v
54 | }
55 |
56 | func handleRequestObject(req *jsonRequest) *jsonResponse {
57 | switch req.Method {
58 | case "ping":
59 | return handlePing(req)
60 | }
61 |
62 | // unknown method
63 | log.Println("Unknown method:", req.Method)
64 | return &jsonResponse{
65 | ID: req.ID,
66 | Error: &jsonError{
67 | ErrCode: "M_BAD_JSON",
68 | Error: "Unknown method",
69 | },
70 | }
71 | }
72 |
73 | func handlePing(req *jsonRequest) *jsonResponse {
74 | return &jsonResponse{
75 | ID: req.ID,
76 | Result: &map[string]interface{}{},
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/proxy/request_test.go:
--------------------------------------------------------------------------------
1 | package proxy
2 |
3 | import (
4 | "encoding/json"
5 | "regexp"
6 | "strings"
7 | "testing"
8 | )
9 |
10 | func TestBadMessage(t *testing.T) {
11 | req := ""
12 | resp := handleRequest([]byte(req))
13 | respStr := string(resp)
14 |
15 | // some initial checks that the json is as we expect
16 | if !regexp.MustCompile(`"id":\s*null`).Match(resp) {
17 | t.Error("id != null:", respStr)
18 | }
19 | if strings.Contains(respStr, "result") {
20 | t.Error("response contains result:", respStr)
21 | }
22 |
23 | var respObj jsonResponse
24 | if err := json.Unmarshal(resp, &respObj); err != nil {
25 | t.Error("JSON error", err)
26 | } else {
27 | if respObj.Error.ErrCode != "M_NOT_JSON" {
28 | t.Error("Bad errcode:", respObj.Error.ErrCode)
29 | }
30 | }
31 | }
32 |
33 | func TestPing(t *testing.T) {
34 | req := `{"id": "1234", "method": "ping"}`
35 | resp := handleRequest([]byte(req))
36 | respStr := string(resp)
37 |
38 | if strings.Contains(respStr, "error") {
39 | t.Error("response contains error:", respStr)
40 | }
41 | if !regexp.MustCompile(`"result":\s*\{\}`).Match(resp) {
42 | t.Error("response does not contain empty result:", respStr)
43 | }
44 |
45 | var respObj jsonResponse
46 | if err := json.Unmarshal(resp, &respObj); err != nil {
47 | t.Error("JSON error", err)
48 | } else {
49 | if *respObj.ID != "1234" {
50 | t.Error("Bad response ID:", respObj.ID)
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/proxy/sync.go:
--------------------------------------------------------------------------------
1 | package proxy
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io/ioutil"
7 | "log"
8 | "net/http"
9 | "net/url"
10 | )
11 |
12 | type Syncer struct {
13 | UpstreamURL string
14 |
15 | SyncParams url.Values
16 |
17 | // our client for the upstream connection
18 | client http.Client
19 | }
20 |
21 | // an error returned when the /sync endpoint returns a non-200.
22 | type SyncError struct {
23 | StatusCode int
24 | ContentType string
25 | Body []byte
26 | }
27 |
28 | func (s *SyncError) Error() string {
29 | return string(s.Body)
30 | }
31 |
32 | // MakeRequest sends the sync request, and returns the body of the response,
33 | // or an error.
34 | //
35 | // It keeps track of the 'next_batch' from the result, and uses it to se the
36 | // 'since' parameter for the next call.
37 | //
38 | // Note that this method is not thread-safe; there should be only one concurrent
39 | // call per Syncer.
40 | //
41 | // If /sync returns a non-200 response, the error returned will be a SyncError.
42 | func (s *Syncer) MakeRequest() ([]byte, error) {
43 | url := s.UpstreamURL + "?" + s.SyncParams.Encode()
44 | log.Println("request", url)
45 | resp, err := s.client.Get(url)
46 |
47 | if err != nil {
48 | log.Println("Error in sync", err)
49 | return nil, err
50 | }
51 | defer resp.Body.Close()
52 |
53 | body, err := ioutil.ReadAll(resp.Body)
54 | if err != nil {
55 | return nil, fmt.Errorf("error reading sync error response: %v", err)
56 | }
57 |
58 | log.Println("Sync response:", resp.StatusCode)
59 | if resp.StatusCode != 200 {
60 | return nil, &SyncError{resp.StatusCode, resp.Header.Get("Content-Type"), body}
61 | }
62 |
63 | // we need the 'next_batch' token, so fish that out
64 | next_batch, err := extractNextBatch(body)
65 | if err != nil {
66 | return nil, err
67 | }
68 | log.Println("Got next_batch:", next_batch)
69 |
70 | s.SyncParams.Set("since", next_batch)
71 | return body, nil
72 | }
73 |
74 | // extractNextBatch fishes the 'next_batch' member out of the JSON response from
75 | // /sync.
76 | func extractNextBatch(httpBody []byte) (string, error) {
77 | type syncResponse struct {
78 | NextBatch string `json:"next_batch"`
79 | }
80 | var sr syncResponse
81 | if err := json.Unmarshal(httpBody, &sr); err != nil {
82 | return "", err
83 | }
84 |
85 | if sr.NextBatch == "" {
86 | return "", fmt.Errorf("/sync response missing next_batch")
87 | }
88 |
89 | return sr.NextBatch, nil
90 | }
91 |
--------------------------------------------------------------------------------
/proxy/sync_test.go:
--------------------------------------------------------------------------------
1 | package proxy
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestExtractNextBatch(t *testing.T) {
8 | input := `{
9 | "next_batch": "s361093_69_4_8353_1",
10 | "presence": {
11 | "events": [
12 | "event"
13 | ]
14 | },
15 | "rooms": {
16 | "join": {
17 | "!MbvBAvLuvGjNMUuRws:matrix.org": {}
18 | }
19 | }
20 | }`
21 |
22 | next_batch, err := extractNextBatch([]byte(input))
23 | if err != nil {
24 | t.Errorf("Expected no error, got '%v'", err)
25 | }
26 | if next_batch != "s361093_69_4_8353_1" {
27 | t.Errorf("Expected next batch 's361093_69_4_8353_1', got '%v'",
28 | next_batch)
29 | }
30 | }
31 |
32 | func TestExtractNextBatchErrors(t *testing.T) {
33 | tests := []struct {
34 | input string
35 | expectedError string
36 | }{
37 | {"{}", "/sync response missing next_batch"},
38 | {"{", "unexpected end of JSON input"},
39 | }
40 |
41 | for _, tt := range tests {
42 | next_batch, err := extractNextBatch([]byte(tt.input))
43 | if err == nil || err.Error() != tt.expectedError {
44 | t.Errorf("Input %v: expected error '%v', got '%v'", tt.input,
45 | tt.expectedError, err)
46 | }
47 | if next_batch != "" {
48 | t.Errorf("Input %v: expected empty result, got '%v'", tt.input,
49 | next_batch)
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/test/test.html:
--------------------------------------------------------------------------------
1 |
2 |