Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: e382ddd6a88e278c7aa96cbd9338fd5baa13d410 (plain) (blame)
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
//
//  ========================================================================
//  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.client;

import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import org.eclipse.jetty.client.api.Authentication;
import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.client.api.ContentProvider;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

public abstract class HttpConnection implements Connection
{
    private static final Logger LOG = Log.getLogger(HttpConnection.class);
    private static final HttpField CHUNKED_FIELD = new HttpField(HttpHeader.TRANSFER_ENCODING, HttpHeaderValue.CHUNKED);

    private final AtomicInteger idleTimeoutState = new AtomicInteger();
    private final HttpDestination destination;

    protected HttpConnection(HttpDestination destination)
    {
        this.destination = destination;
    }

    public HttpClient getHttpClient()
    {
        return destination.getHttpClient();
    }

    public HttpDestination getHttpDestination()
    {
        return destination;
    }

    @Override
    public void send(Request request, Response.CompleteListener listener)
    {
        ArrayList<Response.ResponseListener> listeners = new ArrayList<>(2);
        if (request.getTimeout() > 0)
        {
            TimeoutCompleteListener timeoutListener = new TimeoutCompleteListener(request);
            timeoutListener.schedule(getHttpClient().getScheduler());
            listeners.add(timeoutListener);
        }
        if (listener != null)
            listeners.add(listener);

        HttpExchange exchange = new HttpExchange(getHttpDestination(), (HttpRequest)request, listeners);

        SendFailure result = send(exchange);
        if (result != null)
            request.abort(result.failure);
    }

    protected abstract SendFailure send(HttpExchange exchange);

    protected void normalizeRequest(Request request)
    {
        String method = request.getMethod();
        HttpVersion version = request.getVersion();
        HttpFields headers = request.getHeaders();
        ContentProvider content = request.getContent();
        ProxyConfiguration.Proxy proxy = destination.getProxy();

        // Make sure the path is there
        String path = request.getPath();
        if (path.trim().length() == 0)
        {
            path = "/";
            request.path(path);
        }
        if (proxy != null && !HttpMethod.CONNECT.is(method))
        {
            path = request.getURI().toString();
            request.path(path);
        }

        // If we are HTTP 1.1, add the Host header
        if (version.getVersion() > 10)
        {
            if (!headers.containsKey(HttpHeader.HOST.asString()))
                headers.put(getHttpDestination().getHostField());
        }

        // Add content headers
        if (content != null)
        {
            if (content instanceof ContentProvider.Typed)
            {
                if (!headers.containsKey(HttpHeader.CONTENT_TYPE.asString()))
                {
                    String contentType = ((ContentProvider.Typed)content).getContentType();
                    if (contentType != null)
                        headers.put(HttpHeader.CONTENT_TYPE, contentType);
                }
            }
            long contentLength = content.getLength();
            if (contentLength >= 0)
            {
                if (!headers.containsKey(HttpHeader.CONTENT_LENGTH.asString()))
                    headers.put(HttpHeader.CONTENT_LENGTH, String.valueOf(contentLength));
            }
            else
            {
                if (!headers.containsKey(HttpHeader.TRANSFER_ENCODING.asString()))
                    headers.put(CHUNKED_FIELD);
            }
        }

        // Cookies
        CookieStore cookieStore = getHttpClient().getCookieStore();
        if (cookieStore != null)
        {
            URI uri = request.getURI();
            StringBuilder cookies = null;
            if (uri != null)
                cookies = convertCookies(cookieStore.get(uri), null);
            cookies = convertCookies(request.getCookies(), cookies);
            if (cookies != null)
                request.header(HttpHeader.COOKIE.asString(), cookies.toString());
        }

        // Authorization
        URI authenticationURI = proxy != null ? proxy.getURI() : request.getURI();
        if (authenticationURI != null)
        {
            Authentication.Result authnResult = getHttpClient().getAuthenticationStore().findAuthenticationResult(authenticationURI);
            if (authnResult != null)
                authnResult.apply(request);
        }
    }

    private StringBuilder convertCookies(List<HttpCookie> cookies, StringBuilder builder)
    {
        for (int i = 0; i < cookies.size(); ++i)
        {
            if (builder == null)
                builder = new StringBuilder();
            if (builder.length() > 0)
                builder.append("; ");
            HttpCookie cookie = cookies.get(i);
            builder.append(cookie.getName()).append("=").append(cookie.getValue());
        }
        return builder;
    }

    protected SendFailure send(HttpChannel channel, HttpExchange exchange)
    {
        // Forbid idle timeouts for the time window where
        // the request is associated to the channel and sent.
        // Use a counter to support multiplexed requests.
        boolean send = false;
        while (true)
        {
            int current = idleTimeoutState.get();
            if (current < 0)
                break;
            if (idleTimeoutState.compareAndSet(current, current + 1))
            {
                send = true;
                break;
            }
        }

        if (send)
        {
            HttpRequest request = exchange.getRequest();
            SendFailure result;
            if (channel.associate(exchange))
            {
                channel.send();
                result = null;
            }
            else
            {
                channel.release();
                result = new SendFailure(new HttpRequestException("Could not associate request to connection", request), false);
            }
            idleTimeoutState.decrementAndGet();
            return result;
        }
        else
        {
            return new SendFailure(new TimeoutException(), true);
        }
    }

    public boolean onIdleTimeout()
    {
        if (LOG.isDebugEnabled())
            LOG.debug("Idle timeout state {} - {}", idleTimeoutState, this);
        if (idleTimeoutState.compareAndSet(0, -1))
            close(new TimeoutException("idle_timeout"));
        return false;
    }

    protected abstract void close(Throwable failure);

    @Override
    public String toString()
    {
        return String.format("%s@%h", getClass().getSimpleName(), this);
    }
}

Back to the top