Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 9752434140b8ef5a0099fc12f979627c8bbc8545 (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
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
//
//  ========================================================================
//  Copyright (c) 1995-2016 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.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ReadPendingException;
import java.nio.channels.WritePendingException;
import java.util.Iterator;

import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;


/* ------------------------------------------------------------ */
/**
 * ConnectionFactory for the PROXY Protocol.
 * <p>This factory can be placed in front of any other connection factory
 * to process the proxy line before the normal protocol handling</p>
 *
 * @see <a href="http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt">http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt</a>
 */
public class ProxyConnectionFactory extends AbstractConnectionFactory
{
    private static final Logger LOG = Log.getLogger(ProxyConnectionFactory.class);
    private final String _next;

    /* ------------------------------------------------------------ */
    /** Proxy Connection Factory that uses the next ConnectionFactory
     * on the connector as the next protocol
     */
    public ProxyConnectionFactory()
    {
        super("proxy");
        _next=null;
    }

    public ProxyConnectionFactory(String nextProtocol)
    {
        super("proxy");
        _next=nextProtocol;
    }

    @Override
    public Connection newConnection(Connector connector, EndPoint endp)
    {
        String next=_next;
        if (next==null)
        {
            for (Iterator<String> i = connector.getProtocols().iterator();i.hasNext();)
            {
                String p=i.next();
                if (getProtocol().equalsIgnoreCase(p))
                {
                    next=i.next();
                    break;
                }
            }
        }

        return new ProxyConnection(endp,connector,next);
    }

    public static class ProxyConnection extends AbstractConnection
    {
        // 0     1 2       3       4 5 6
        // 98765432109876543210987654321
        // PROXY P R.R.R.R L.L.L.L R Lrn

        private final int[] __size = {29,23,21,13,5,3,1};
        private final Connector _connector;
        private final String _next;
        private final StringBuilder _builder=new StringBuilder();
        private final String[] _field=new String[6];
        private int _fields;
        private int _length;

        protected ProxyConnection(EndPoint endp, Connector connector, String next)
        {
            super(endp,connector.getExecutor());
            _connector=connector;
            _next=next;
        }

        @Override
        public void onOpen()
        {
            super.onOpen();
            fillInterested();
        }

        @Override
        public void onFillable()
        {
            try
            {
                ByteBuffer buffer=null;
                loop: while(true)
                {
                    // Create a buffer that will not read too much data
                    int size=Math.max(1,__size[_fields]-_builder.length());
                    if (buffer==null || buffer.capacity()!=size)
                        buffer=BufferUtil.allocate(size);
                    else
                        BufferUtil.clear(buffer);

                    // Read data
                    int fill=getEndPoint().fill(buffer);
                    if (fill<0)
                    {
                        getEndPoint().shutdownOutput();
                        return;
                    }
                    if (fill==0)
                    {
                        fillInterested();
                        return;
                    }

                    _length+=fill;
                    if (_length>=108)
                    {
                        LOG.warn("PROXY line too long {} for {}",_length,getEndPoint());
                        close();
                        return;
                    }

                    // parse fields
                    while (buffer.hasRemaining())
                    {
                        byte b = buffer.get();
                        if (_fields<6)
                        {
                            if (b==' ' || b=='\r' && _fields==5)
                            {
                                _field[_fields++]=_builder.toString();
                                _builder.setLength(0);
                            }
                            else if (b<' ')
                            {
                                LOG.warn("Bad character {} for {}",b&0xFF,getEndPoint());
                                close();
                                return;
                            }
                            else
                            {
                                _builder.append((char)b);
                            }
                        }
                        else
                        {
                            if (b=='\n')
                                break loop;

                            LOG.warn("Bad CRLF for {}",getEndPoint());
                            close();
                            return;
                        }
                    }
                }

                // Check proxy
                if (!"PROXY".equals(_field[0]))
                {
                    LOG.warn("Not PROXY protocol for {}",getEndPoint());
                    close();
                    return;
                }

                // Extract Addresses
                InetSocketAddress remote=new InetSocketAddress(_field[2],Integer.parseInt(_field[4]));
                InetSocketAddress local =new InetSocketAddress(_field[3],Integer.parseInt(_field[5]));

                // Create the next protocol
                ConnectionFactory connectionFactory = _connector.getConnectionFactory(_next);
                if (connectionFactory == null)
                {
                    LOG.info("Next protocol '{}' for {}",_next,getEndPoint());
                    close();
                    return;
                }

                EndPoint endPoint = new ProxyEndPoint(getEndPoint(),remote,local);
                Connection newConnection = connectionFactory.newConnection(_connector, endPoint);
                endPoint.upgrade(newConnection);
            }
            catch (Throwable x)
            {
                LOG.warn("PROXY error for "+getEndPoint(),x);
                close();
            }
        }
    }

    public static class ProxyEndPoint implements EndPoint
    {
        private final EndPoint _endp;
        private final InetSocketAddress _remote;
        private final InetSocketAddress _local;

        public ProxyEndPoint(EndPoint endp, InetSocketAddress remote, InetSocketAddress local)
        {
            _endp=endp;
            _remote=remote;
            _local=local;
        }

        @Override
        public boolean isOptimizedForDirectBuffers()
        {
            return _endp.isOptimizedForDirectBuffers();
        }

        public InetSocketAddress getLocalAddress()
        {
            return _local;
        }

        public InetSocketAddress getRemoteAddress()
        {
            return _remote;
        }

        public boolean isOpen()
        {
            return _endp.isOpen();
        }

        public long getCreatedTimeStamp()
        {
            return _endp.getCreatedTimeStamp();
        }

        public void shutdownOutput()
        {
            _endp.shutdownOutput();
        }

        public boolean isOutputShutdown()
        {
            return _endp.isOutputShutdown();
        }

        public boolean isInputShutdown()
        {
            return _endp.isInputShutdown();
        }

        public void close()
        {
            _endp.close();
        }

        public int fill(ByteBuffer buffer) throws IOException
        {
            return _endp.fill(buffer);
        }

        public boolean flush(ByteBuffer... buffer) throws IOException
        {
            return _endp.flush(buffer);
        }

        public Object getTransport()
        {
            return _endp.getTransport();
        }

        public long getIdleTimeout()
        {
            return _endp.getIdleTimeout();
        }

        public void setIdleTimeout(long idleTimeout)
        {
            _endp.setIdleTimeout(idleTimeout);
        }

        public void fillInterested(Callback callback) throws ReadPendingException
        {
            _endp.fillInterested(callback);
        }

        @Override
        public boolean isFillInterested()
        {
            return _endp.isFillInterested();
        }

        public void write(Callback callback, ByteBuffer... buffers) throws WritePendingException
        {
            _endp.write(callback,buffers);
        }

        public Connection getConnection()
        {
            return _endp.getConnection();
        }

        public void setConnection(Connection connection)
        {
            _endp.setConnection(connection);
        }

        public void onOpen()
        {
            _endp.onOpen();
        }

        public void onClose()
        {
            _endp.onClose();
        }

        @Override
        public void upgrade(Connection newConnection)
        {
            _endp.upgrade(newConnection);
        }
    }
}

Back to the top