|
| 1 | +/* |
| 2 | + * Copyright (C) 2014 Square, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +// This has been cloned from the okhttp-ws package so that I could remove |
| 17 | +// the requirement that websockets use the "GET" method |
| 18 | +package io.kubernetes.client.util; |
| 19 | + |
| 20 | +import com.squareup.okhttp.Call; |
| 21 | +import com.squareup.okhttp.Callback; |
| 22 | +import com.squareup.okhttp.OkHttpClient; |
| 23 | +import com.squareup.okhttp.Request; |
| 24 | +import com.squareup.okhttp.Response; |
| 25 | +import com.squareup.okhttp.internal.Internal; |
| 26 | +import com.squareup.okhttp.internal.Util; |
| 27 | +import com.squareup.okhttp.internal.http.StreamAllocation; |
| 28 | +import com.squareup.okhttp.internal.ws.RealWebSocket; |
| 29 | +import com.squareup.okhttp.internal.ws.WebSocketProtocol; |
| 30 | +import com.squareup.okhttp.ws.WebSocketListener; |
| 31 | +import java.io.IOException; |
| 32 | +import java.net.ProtocolException; |
| 33 | +import java.security.SecureRandom; |
| 34 | +import java.util.Collections; |
| 35 | +import java.util.Random; |
| 36 | +import java.util.concurrent.ExecutorService; |
| 37 | +import java.util.concurrent.LinkedBlockingDeque; |
| 38 | +import java.util.concurrent.ThreadPoolExecutor; |
| 39 | +import okio.ByteString; |
| 40 | + |
| 41 | +import static java.util.concurrent.TimeUnit.SECONDS; |
| 42 | + |
| 43 | +public final class WebSocketCall { |
| 44 | + /** |
| 45 | + * Prepares the {@code request} to create a web socket at some point in the future. |
| 46 | + */ |
| 47 | + public static WebSocketCall create(OkHttpClient client, Request request) { |
| 48 | + return new WebSocketCall(client, request); |
| 49 | + } |
| 50 | + |
| 51 | + private final Call call; |
| 52 | + private final Random random; |
| 53 | + private final String key; |
| 54 | + |
| 55 | + WebSocketCall(OkHttpClient client, Request request) { |
| 56 | + this(client, request, new SecureRandom()); |
| 57 | + } |
| 58 | + |
| 59 | + WebSocketCall(OkHttpClient client, Request request, Random random) { |
| 60 | + this.random = random; |
| 61 | + |
| 62 | + byte[] nonce = new byte[16]; |
| 63 | + random.nextBytes(nonce); |
| 64 | + key = ByteString.of(nonce).base64(); |
| 65 | + |
| 66 | + // Copy the client. Otherwise changes (socket factory, redirect policy, |
| 67 | + // etc.) may incorrectly be reflected in the request when it is executed. |
| 68 | + client = client.clone(); |
| 69 | + // Force HTTP/1.1 until the WebSocket over HTTP/2 version is finalized. |
| 70 | + client.setProtocols(Collections.singletonList(com.squareup.okhttp.Protocol.HTTP_1_1)); |
| 71 | + |
| 72 | + request = request.newBuilder() |
| 73 | + .header("Upgrade", "websocket") |
| 74 | + .header("Connection", "Upgrade") |
| 75 | + .header("Sec-WebSocket-Key", key) |
| 76 | + .header("Sec-WebSocket-Version", "13") |
| 77 | + .build(); |
| 78 | + |
| 79 | + call = client.newCall(request); |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Schedules the request to be executed at some point in the future. |
| 84 | + * |
| 85 | + * <p>The {@link OkHttpClient#getDispatcher dispatcher} defines when the request will run: |
| 86 | + * usually immediately unless there are several other requests currently being executed. |
| 87 | + * |
| 88 | + * <p>This client will later call back {@code responseCallback} with either an HTTP response or a |
| 89 | + * failure exception. If you {@link #cancel} a request before it completes the callback will not |
| 90 | + * be invoked. |
| 91 | + * |
| 92 | + * @throws IllegalStateException when the call has already been executed. |
| 93 | + */ |
| 94 | + public void enqueue(final WebSocketListener listener) { |
| 95 | + Callback responseCallback = new Callback() { |
| 96 | + @Override public void onResponse(Response response) throws IOException { |
| 97 | + System.out.println(response); |
| 98 | + try { |
| 99 | + createWebSocket(response, listener); |
| 100 | + } catch (IOException e) { |
| 101 | + listener.onFailure(e, response); |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + @Override public void onFailure(Request request, IOException e) { |
| 106 | + listener.onFailure(e, null); |
| 107 | + } |
| 108 | + }; |
| 109 | + // TODO call.enqueue(responseCallback, true); |
| 110 | + Internal.instance.callEnqueue(call, responseCallback, true); |
| 111 | + } |
| 112 | + |
| 113 | + /** Cancels the request, if possible. Requests that are already complete cannot be canceled. */ |
| 114 | + public void cancel() { |
| 115 | + call.cancel(); |
| 116 | + } |
| 117 | + |
| 118 | + private void createWebSocket(Response response, WebSocketListener listener) throws IOException { |
| 119 | + if (response.code() != 101) { |
| 120 | + Util.closeQuietly(response.body()); |
| 121 | + throw new ProtocolException("Expected HTTP 101 response but was '" |
| 122 | + + response.code() |
| 123 | + + " " |
| 124 | + + response.message() |
| 125 | + + "'"); |
| 126 | + } |
| 127 | + |
| 128 | + String headerConnection = response.header("Connection"); |
| 129 | + if (!"Upgrade".equalsIgnoreCase(headerConnection)) { |
| 130 | + throw new ProtocolException( |
| 131 | + "Expected 'Connection' header value 'Upgrade' but was '" + headerConnection + "'"); |
| 132 | + } |
| 133 | + String headerUpgrade = response.header("Upgrade"); |
| 134 | + if (!"websocket".equalsIgnoreCase(headerUpgrade)) { |
| 135 | + throw new ProtocolException( |
| 136 | + "Expected 'Upgrade' header value 'websocket' but was '" + headerUpgrade + "'"); |
| 137 | + } |
| 138 | + String headerAccept = response.header("Sec-WebSocket-Accept"); |
| 139 | + String acceptExpected = Util.shaBase64(key + WebSocketProtocol.ACCEPT_MAGIC); |
| 140 | + if (!acceptExpected.equals(headerAccept)) { |
| 141 | + throw new ProtocolException("Expected 'Sec-WebSocket-Accept' header value '" |
| 142 | + + acceptExpected |
| 143 | + + "' but was '" |
| 144 | + + headerAccept |
| 145 | + + "'"); |
| 146 | + } |
| 147 | + |
| 148 | + StreamAllocation streamAllocation = Internal.instance.callEngineGetStreamAllocation(call); |
| 149 | + RealWebSocket webSocket = StreamWebSocket.create( |
| 150 | + streamAllocation, response, random, listener); |
| 151 | + |
| 152 | + listener.onOpen(webSocket, response); |
| 153 | + |
| 154 | + while (webSocket.readMessage()) { |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + // Keep static so that the WebSocketCall instance can be garbage collected. |
| 159 | + private static class StreamWebSocket extends RealWebSocket { |
| 160 | + static RealWebSocket create(StreamAllocation streamAllocation, Response response, |
| 161 | + Random random, WebSocketListener listener) { |
| 162 | + String url = response.request().urlString(); |
| 163 | + ThreadPoolExecutor replyExecutor = |
| 164 | + new ThreadPoolExecutor(1, 1, 1, SECONDS, new LinkedBlockingDeque<Runnable>(), |
| 165 | + Util.threadFactory(String.format("OkHttp %s WebSocket", url), true)); |
| 166 | + replyExecutor.allowCoreThreadTimeOut(true); |
| 167 | + |
| 168 | + return new StreamWebSocket(streamAllocation, random, replyExecutor, listener, url); |
| 169 | + } |
| 170 | + |
| 171 | + private final StreamAllocation streamAllocation; |
| 172 | + private final ExecutorService replyExecutor; |
| 173 | + |
| 174 | + private StreamWebSocket(StreamAllocation streamAllocation, |
| 175 | + Random random, ExecutorService replyExecutor, WebSocketListener listener, String url) { |
| 176 | + super(true /* is client */, streamAllocation.connection().source, |
| 177 | + streamAllocation.connection().sink, random, replyExecutor, listener, url); |
| 178 | + this.streamAllocation = streamAllocation; |
| 179 | + this.replyExecutor = replyExecutor; |
| 180 | + } |
| 181 | + |
| 182 | + @Override protected void close() throws IOException { |
| 183 | + replyExecutor.shutdown(); |
| 184 | + streamAllocation.noNewStreams(); |
| 185 | + streamAllocation.streamFinished(streamAllocation.stream()); |
| 186 | + } |
| 187 | + } |
| 188 | +} |
0 commit comments