aboutsummaryrefslogtreecommitdiffstats
path: root/AndroidAsync/src/com/koushikdutta/async/http/spdy/SpdyMiddleware.java
blob: b5c838e20a73b41cb106f8f35ede3c1d5f0bf5d1 (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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package com.koushikdutta.async.http.spdy;

import android.net.Uri;
import android.text.TextUtils;

import com.koushikdutta.async.AsyncSSLSocket;
import com.koushikdutta.async.AsyncSSLSocketWrapper;
import com.koushikdutta.async.ByteBufferList;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.callback.ConnectCallback;
import com.koushikdutta.async.future.Cancellable;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.async.future.MultiFuture;
import com.koushikdutta.async.future.SimpleCancellable;
import com.koushikdutta.async.future.TransformFuture;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpRequest;
import com.koushikdutta.async.http.AsyncSSLEngineConfigurator;
import com.koushikdutta.async.http.AsyncSSLSocketMiddleware;
import com.koushikdutta.async.http.Headers;
import com.koushikdutta.async.http.HttpUtil;
import com.koushikdutta.async.http.Multimap;
import com.koushikdutta.async.http.Protocol;
import com.koushikdutta.async.http.body.AsyncHttpRequestBody;
import com.koushikdutta.async.util.Charsets;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

public class SpdyMiddleware extends AsyncSSLSocketMiddleware {
    public SpdyMiddleware(AsyncHttpClient client) {
        super(client);
        addEngineConfigurator(new AsyncSSLEngineConfigurator() {
            @Override
            public void configureEngine(SSLEngine engine, GetSocketData data, String host, int port) {
                configure(engine, data, host, port);
            }
        });
    }

    private void configure(SSLEngine engine, GetSocketData data, String host, int port) {
        if (!initialized && spdyEnabled) {
            initialized = true;
            try {
                peerHost = engine.getClass().getSuperclass().getDeclaredField("peerHost");
                peerPort = engine.getClass().getSuperclass().getDeclaredField("peerPort");
                sslParameters = engine.getClass().getDeclaredField("sslParameters");
                npnProtocols = sslParameters.getType().getDeclaredField("npnProtocols");
                alpnProtocols = sslParameters.getType().getDeclaredField("alpnProtocols");
                useSni = sslParameters.getType().getDeclaredField("useSni");
                sslNativePointer = engine.getClass().getDeclaredField("sslNativePointer");
                String nativeCryptoName = sslParameters.getType().getPackage().getName() + ".NativeCrypto";
                nativeGetNpnNegotiatedProtocol = Class.forName(nativeCryptoName, true, sslParameters.getType().getClassLoader())
                .getDeclaredMethod("SSL_get_npn_negotiated_protocol", long.class);
                nativeGetAlpnNegotiatedProtocol = Class.forName(nativeCryptoName, true, sslParameters.getType().getClassLoader())
                .getDeclaredMethod("SSL_get0_alpn_selected", long.class);

                peerHost.setAccessible(true);
                peerPort.setAccessible(true);
                sslParameters.setAccessible(true);
                npnProtocols.setAccessible(true);
                alpnProtocols.setAccessible(true);
                useSni.setAccessible(true);
                sslNativePointer.setAccessible(true);
                nativeGetNpnNegotiatedProtocol.setAccessible(true);
                nativeGetAlpnNegotiatedProtocol.setAccessible(true);
            }
            catch (Exception e) {
                sslParameters = null;
                npnProtocols = null;
                alpnProtocols = null;
                useSni = null;
                sslNativePointer = null;
                nativeGetNpnNegotiatedProtocol = null;
                nativeGetAlpnNegotiatedProtocol = null;
            }
        }

        // TODO: figure out why POST does not work if sending content-length header
        // see above regarding app engine comment as to why: drive requires content-length
        // but app engine sends a GO_AWAY if it sees a content-length...
        if (!canSpdyRequest(data))
            return;

        if (sslParameters != null) {
            try {
                byte[] protocols = concatLengthPrefixed(
                Protocol.HTTP_1_1,
                Protocol.SPDY_3
                );

                peerHost.set(engine, host);
                peerPort.set(engine, port);
                Object sslp = sslParameters.get(engine);
//                npnProtocols.set(sslp, protocols);
                alpnProtocols.set(sslp, protocols);
                useSni.set(sslp, true);
            }
            catch (Exception e ) {
                e.printStackTrace();
            }
        }
    }

    boolean initialized;
    Field peerHost;
    Field peerPort;
    Field sslParameters;
    Field npnProtocols;
    Field alpnProtocols;
    Field sslNativePointer;
    Field useSni;
    Method nativeGetNpnNegotiatedProtocol;
    Method nativeGetAlpnNegotiatedProtocol;
    Hashtable<String, SpdyConnectionWaiter> connections = new Hashtable<String, SpdyConnectionWaiter>();
    boolean spdyEnabled;

    private static class SpdyConnectionWaiter extends MultiFuture<AsyncSpdyConnection> {
    }

    public boolean getSpdyEnabled() {
        return spdyEnabled;
    }

    public void setSpdyEnabled(boolean enabled) {
        spdyEnabled = enabled;
    }

    @Override
    public void setSSLContext(SSLContext sslContext) {
        super.setSSLContext(sslContext);
        initialized = false;
    }

    static byte[] concatLengthPrefixed(Protocol... protocols) {
        ByteBuffer result = ByteBuffer.allocate(8192);
        for (Protocol protocol: protocols) {
            if (protocol == Protocol.HTTP_1_0) continue; // No HTTP/1.0 for NPN.
            result.put((byte) protocol.toString().length());
            result.put(protocol.toString().getBytes(Charsets.UTF_8));
        }
        result.flip();
        byte[] ret = new ByteBufferList(result).getAllByteArray();
        return ret;
    }

    private static String requestPath(Uri uri) {
        String pathAndQuery = uri.getEncodedPath();
        if (pathAndQuery == null)
            pathAndQuery = "/";
        else if (!pathAndQuery.startsWith("/"))
            pathAndQuery = "/" + pathAndQuery;
        if (!TextUtils.isEmpty(uri.getEncodedQuery()))
            pathAndQuery += "?" + uri.getEncodedQuery();
        return pathAndQuery;
    }

    private static class NoSpdyException extends Exception {
    }
    private static final NoSpdyException NO_SPDY = new NoSpdyException();

    private void noSpdy(final GetSocketData data, String key) {
        SpdyConnectionWaiter conn = connections.remove(key);
        if (conn != null)
            conn.setComplete(NO_SPDY);
        data.request.logv("not using spdy");
    }

    @Override
    protected AsyncSSLSocketWrapper.HandshakeCallback createHandshakeCallback(final GetSocketData data, final ConnectCallback callback) {
        return new AsyncSSLSocketWrapper.HandshakeCallback() {
            @Override
            public void onHandshakeCompleted(Exception e, AsyncSSLSocket socket) {
                final String key = data.request.getUri().getHost();
                data.request.logv("checking spdy handshake");
                if (e != null || nativeGetAlpnNegotiatedProtocol == null) {
                    callback.onConnectCompleted(e, socket);
                    noSpdy(data, key);
                    return;
                }
                try {
                    long ptr = (Long)sslNativePointer.get(socket.getSSLEngine());
                    byte[] proto = (byte[])nativeGetAlpnNegotiatedProtocol.invoke(null, ptr);
                    if (proto == null) {
                        callback.onConnectCompleted(null, socket);
                        noSpdy(data, key);
                        return;
                    }
                    String protoString = new String(proto);
                    Protocol p = Protocol.get(protoString);
                    if (p == null) {
                        callback.onConnectCompleted(null, socket);
                        noSpdy(data, key);
                        return;
                    }
                    final AsyncSpdyConnection connection = new AsyncSpdyConnection(socket, Protocol.get(protoString)) {
                        boolean hasReceivedSettings;
                        @Override
                        public void settings(boolean clearPrevious, Settings settings) {
                            super.settings(clearPrevious, settings);
                            if (!hasReceivedSettings) {
                                try {
                                    sendConnectionPreface();
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                                hasReceivedSettings = true;

                                data.request.logv("using new spdy connection for host: " + data.request.getUri().getHost());
                                newSocket(data, this, callback);

                                SpdyConnectionWaiter waiter = connections.get(key);
                                waiter.setComplete(this);
                            }
                        }
                    };
                }
                catch (Exception ex) {
                    socket.close();
                    callback.onConnectCompleted(ex, null);
                    noSpdy(data, key);
                }
            }
        };
    }

    private void newSocket(GetSocketData data, final AsyncSpdyConnection connection, final ConnectCallback callback) {
        final AsyncHttpRequest request = data.request;

        data.protocol = connection.protocol.toString();

        final AsyncHttpRequestBody requestBody = data.request.getBody();

        // this causes app engine to shit a brick, but if it is missing,
        // drive shits the bed
//        if (requestBody != null) {
//            if (requestBody.length() >= 0) {
//                request.getHeaders().set("Content-Length", String.valueOf(requestBody.length()));
//            }
//        }

        final ArrayList<Header> headers = new ArrayList<Header>();
        headers.add(new Header(Header.TARGET_METHOD, request.getMethod()));
        headers.add(new Header(Header.TARGET_PATH, requestPath(request.getUri())));
        String host = request.getHeaders().get("Host");
        if (Protocol.SPDY_3 == connection.protocol) {
            headers.add(new Header(Header.VERSION, "HTTP/1.1"));
            headers.add(new Header(Header.TARGET_HOST, host));
        } else if (Protocol.HTTP_2 == connection.protocol) {
            headers.add(new Header(Header.TARGET_AUTHORITY, host)); // Optional in HTTP/2
        } else {
            throw new AssertionError();
        }
        headers.add(new Header(Header.TARGET_SCHEME, request.getUri().getScheme()));

        final Multimap mm = request.getHeaders().getMultiMap();
        for (String key: mm.keySet()) {
            if (SpdyTransport.isProhibitedHeader(connection.protocol, key))
                continue;
            for (String value: mm.get(key)) {
                headers.add(new Header(key.toLowerCase(), value));
            }
        }

        request.logv("\n" + request);
        final AsyncSpdyConnection.SpdySocket spdy = connection.newStream(headers, requestBody != null, true);
        callback.onConnectCompleted(null, spdy);
    }

    private boolean canSpdyRequest(GetSocketData data) {
        // TODO: figure out why POST does not work if sending content-length header
        // see above regarding app engine comment as to why: drive requires content-length
        // but app engine sends a GO_AWAY if it sees a content-length...
        return data.request.getBody() == null;
    }

    @Override
    public Cancellable getSocket(final GetSocketData data) {
        if (!spdyEnabled)
            return super.getSocket(data);

        final Uri uri = data.request.getUri();
        final int port = getSchemePort(data.request.getUri());
        if (port == -1) {
            return null;
        }

        // TODO: figure out why POST does not work if sending content-length header
        // see above regarding app engine comment as to why: drive requires content-length
        // but app engine sends a GO_AWAY if it sees a content-length...
        if (!canSpdyRequest(data))
            return super.getSocket(data);

        // can we use an existing connection to satisfy this, or do we need a new one?
        String key = uri.getHost();
        SpdyConnectionWaiter conn = connections.get(key);
        if (conn != null && conn.tryGet() != null && !conn.tryGet().socket.isOpen()) {
            connections.remove(key);
            conn = null;
        }

        if (conn == null) {
            Cancellable superSocket = super.getSocket(data);;
            // see if we reuse a socket synchronously, otherwise a new connection is being created
            if (!superSocket.isDone()) {
                data.request.logv("waiting for spdy connection for host: " + data.request.getUri().getHost());
                connections.put(key, new SpdyConnectionWaiter());
            }
            else {
                data.request.logv("attempting spdy connection for host: " + data.request.getUri().getHost());
            }
            return superSocket;
        }

        data.request.logv("waiting for potential spdy connection for host: " + data.request.getUri().getHost());
        final SimpleCancellable ret = new SimpleCancellable();
        conn.setCallback(new FutureCallback<AsyncSpdyConnection>() {
            @Override
            public void onCompleted(Exception e, AsyncSpdyConnection conn) {
                if (e instanceof NoSpdyException) {
                    data.request.logv("spdy not available");
                    ret.setParent(SpdyMiddleware.super.getSocket(data));
                    return;
                }
                if (e != null) {
                    data.request.loge("spdy not available", e);
                    ret.setComplete();
                    data.connectCallback.onConnectCompleted(e, null);
                    return;
                }
                data.request.logv("using existing spdy connection for host: " + data.request.getUri().getHost());
                ret.setComplete();
                newSocket(data, conn, data.connectCallback);
            }
        });

        return ret;
    }

    @Override
    public boolean exchangeHeaders(final OnExchangeHeaderData data) {
        if (!(data.socket instanceof AsyncSpdyConnection.SpdySocket))
            return super.exchangeHeaders(data);

        AsyncHttpRequestBody requestBody = data.request.getBody();
        if (requestBody != null) {
            data.response.sink(data.socket);
        }

        // headers were already sent as part of the socket being opened.
        data.sendHeadersCallback.onCompleted(null);

        final AsyncSpdyConnection.SpdySocket spdySocket = (AsyncSpdyConnection.SpdySocket)data.socket;
        spdySocket.headers()
        .then(new TransformFuture<Headers, List<Header>>() {
            @Override
            protected void transform(List<Header> result) throws Exception {
                Headers headers = new Headers();
                for (Header header: result) {
                    String key = header.name.utf8();
                    String value = header.value.utf8();
                    headers.add(key, value);
                }
                String status = headers.remove(Header.RESPONSE_STATUS.utf8());
                String[] statusParts = status.split(" ", 2);
                data.response.code(Integer.parseInt(statusParts[0]));
                if (statusParts.length == 2)
                    data.response.message(statusParts[1]);
                data.response.protocol(headers.remove(Header.VERSION.utf8()));
                data.response.headers(headers);
                setComplete(headers);
            }
        })
        .setCallback(new FutureCallback<Headers>() {
            @Override
            public void onCompleted(Exception e, Headers result) {
                data.receiveHeadersCallback.onCompleted(e);
                DataEmitter emitter = HttpUtil.getBodyDecoder(spdySocket, spdySocket.getConnection().protocol, result, false);
                data.response.emitter(emitter);
            }
        });
        return true;
    }

    @Override
    public void onRequestSent(OnRequestSentData data) {
        if (!(data.socket instanceof AsyncSpdyConnection.SpdySocket))
            return;

        if (data.request.getBody() != null)
            data.response.sink().end();
    }
}