aboutsummaryrefslogtreecommitdiff
path: root/spark-common/src/main/java/me/lucko/spark/common/legacy/LegacyBytesocksClient.java
blob: 33be84580c9450391003018e92028da6757845d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
 * This file is part of spark.
 *
 *  Copyright (c) lucko (Luck) <luck@lucko.me>
 *  Copyright (c) contributors
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package me.lucko.spark.common.legacy;

import com.google.common.collect.ImmutableList;
import com.neovisionaries.ws.client.*;
import me.lucko.bytesocks.client.BytesocksClient;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.CompletableFuture;

/**
 * Implementation of BytesocksClient that works on Java 8.
 */
public class LegacyBytesocksClient implements BytesocksClient {

    /* The bytesocks urls */
    private final String httpUrl;
    private final String wsUrl;

    /** The client user agent */
    private final String userAgent;

    LegacyBytesocksClient(String host, String userAgent) {

        this.httpUrl = "https://" + host + "/";
        this.wsUrl = "wss://" + host + "/";
        this.userAgent = userAgent;
    }

    @Override
    public BytesocksClient.Socket createAndConnect(BytesocksClient.Listener listener) throws Exception {
        HttpURLConnection con = (HttpURLConnection) new URL(this.httpUrl + "create").openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", this.userAgent);
        if (con.getResponseCode() != 201) {
            throw new RuntimeException("Request failed");
        }

        String channelId = null;

        for(Map.Entry<String, List<String>> entry : con.getHeaderFields().entrySet()) {
            String key = entry.getKey();
            List<String> value = entry.getValue();
            if(key != null && key.equalsIgnoreCase("Location") && value != null && value.size() > 0) {
                channelId = value.get(0);
                if(channelId != null)
                    break;
            }
        }

        if(channelId == null) {
            throw new RuntimeException("Location header not returned");
        }

        return connect(channelId, listener);
    }

    @Override
    public BytesocksClient.Socket connect(String channelId, BytesocksClient.Listener listener) throws Exception {
        WebSocketFactory factory = new WebSocketFactory()
                .setConnectionTimeout(5000);
        WebSocket socket = factory.createSocket(URI.create(this.wsUrl + channelId))
                .addHeader("User-Agent", this.userAgent)
                .addListener(new ListenerImpl(listener))
                .connect();

        return new SocketImpl(channelId, socket);
    }

    private static final class SocketImpl implements BytesocksClient.Socket {
        private final String id;
        private final WebSocket ws;
        private final WeakHashMap<WebSocketFrame, CompletableFuture<?>> frameFutures = new WeakHashMap<>();

        /* ugly hacks to track sending of websocket */
        private static final MethodHandle SPLIT_METHOD;

        static {
            try {
                Method m = WebSocket.class.getDeclaredMethod("splitIfNecessary", WebSocketFrame.class);
                m.setAccessible(true);
                SPLIT_METHOD = MethodHandles.lookup().unreflect(m);
            } catch(ReflectiveOperationException e) {
                throw new RuntimeException(e);
            }
        }

        private SocketImpl(String id, WebSocket ws) {
            this.id = id;
            this.ws = ws;
            this.ws.addListener(new WebSocketAdapter() {
                @Override
                public void onFrameSent(WebSocket websocket, WebSocketFrame frame) throws Exception {
                    synchronized (frameFutures) {
                        CompletableFuture<?> future = frameFutures.remove(frame);
                        if(future != null)
                            future.complete(null);
                        else {
                            System.err.println("Sent frame without associated CompletableFuture");
                        }
                    }
                }

                @Override
                public void onFrameUnsent(WebSocket websocket, WebSocketFrame frame) throws Exception {
                    synchronized (frameFutures) {
                        CompletableFuture<?> future = frameFutures.remove(frame);
                        if(future != null)
                            future.completeExceptionally(new Exception("Failed to send frame"));
                        else
                            System.err.println("Received error without associated CompletableFuture");
                    }
                }
            });
        }

        @Override
        public String getChannelId() {
            return this.id;
        }

        @Override
        public boolean isOpen() {
            return this.ws.isOpen();
        }

        @Override
        public CompletableFuture<?> send(CharSequence msg) {
            WebSocketFrame targetFrame = WebSocketFrame.createTextFrame(msg.toString());
            // split ourselves so we know what the last frame was
            List<WebSocketFrame> splitFrames;
            try {
                splitFrames = (List<WebSocketFrame>)SPLIT_METHOD.invokeExact(this.ws, targetFrame);
            } catch(Throwable e) {
                throw new RuntimeException(e);
            }
            if(splitFrames == null)
                splitFrames = ImmutableList.of(targetFrame);
            // FIXME this code is not really that efficient (allocating a whole new CompletableFuture for every frame), but
            // it's the simplest solution for now and seems to be good enough. We have to track all frames to correctly
            // report errors/success
            List<CompletableFuture<?>> futures = new ArrayList<>();
            for(WebSocketFrame frame : splitFrames) {
                CompletableFuture<?> future = new CompletableFuture<>();
                synchronized (frameFutures) {
                    frameFutures.put(frame, future);
                }
                futures.add(future);
                this.ws.sendFrame(frame);
            }
            return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        }

        @Override
        public void close(int statusCode, String reason) {
            this.ws.sendClose(statusCode, reason);
        }
    }

    private static final class ListenerImpl extends WebSocketAdapter {
        private final Listener listener;

        private ListenerImpl(Listener listener) {
            this.listener = listener;
        }

        @Override
        public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
            this.listener.onOpen();
        }

        @Override
        public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
            this.listener.onClose(serverCloseFrame.getCloseCode(), serverCloseFrame.getCloseReason());
        }

        @Override
        public void onError(WebSocket websocket, WebSocketException cause) throws Exception {
            this.listener.onError(cause);
        }

        @Override
        public void onTextMessage(WebSocket websocket, String text) throws Exception {
            this.listener.onText(text);
        }
    }
}