summaryrefslogtreecommitdiff
path: root/qpid/java/systests/src/test/java/org/apache/qpid/transport/MaxFrameSizeTest.java
blob: f76203887ce7bcad7cd548a289a40c054125fc6a (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
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package org.apache.qpid.transport;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

import javax.naming.NamingException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;

import org.apache.qpid.codec.AMQDecoder;
import org.apache.qpid.codec.ClientDecoder;
import org.apache.qpid.framing.AMQDataBlock;
import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.framing.AMQFrameDecodingException;
import org.apache.qpid.framing.AMQProtocolVersionException;
import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ConnectionCloseBody;
import org.apache.qpid.framing.ConnectionStartOkBody;
import org.apache.qpid.framing.ConnectionTuneOkBody;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.framing.FrameCreatingMethodProcessor;
import org.apache.qpid.framing.ProtocolVersion;
import org.apache.qpid.jms.BrokerDetails;
import org.apache.qpid.server.model.AuthenticationProvider;
import org.apache.qpid.server.model.Broker;
import org.apache.qpid.server.model.Protocol;
import org.apache.qpid.server.protocol.v0_8.ProtocolEngineCreator_0_8;
import org.apache.qpid.server.protocol.v0_8.ProtocolEngineCreator_0_9;
import org.apache.qpid.server.protocol.v0_8.ProtocolEngineCreator_0_9_1;
import org.apache.qpid.test.utils.QpidBrokerTestCase;
import org.apache.qpid.test.utils.TestBrokerConfiguration;

public class MaxFrameSizeTest extends QpidBrokerTestCase
{

    @Override
    public void setUp() throws Exception
    {
        // don't call super.setup() as we want a change to set stuff up before the broker starts
        // super.setUp();
    }

    public void testTooSmallFrameSize() throws Exception
    {

        getBrokerConfiguration().setObjectAttribute(AuthenticationProvider.class,
                                                    TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER,
                                                    "secureOnlyMechanisms",
                                                    "[]");
        super.setUp();

        if(isBroker010())
        {
            Connection conn = new Connection();
            final ConnectionSettings settings = new ConnectionSettings();
            BrokerDetails brokerDetails = getConnectionFactory().getConnectionURL().getAllBrokerDetails().get(0);
            settings.setHost(brokerDetails.getHost());
            settings.setPort(brokerDetails.getPort());
            settings.setUsername(GUEST_USERNAME);
            settings.setPassword(GUEST_PASSWORD);
            final ConnectionDelegate clientDelegate = new TestClientDelegate(settings, 1024);
            conn.setConnectionDelegate(clientDelegate);
            try
            {
                conn.connect(settings);
                fail("Connection should not be possible with a frame size < " + Constant.MIN_MAX_FRAME_SIZE);
            }
            catch(ConnectionException e)
            {
                // pass
            }

        }
        else
        {
            doAMQP08test(1024, new ResultEvaluator()
                                {

                                    @Override
                                    public void evaluate(final Socket socket, final List<AMQDataBlock> frames)
                                    {
                                        if(!socket.isClosed())
                                        {
                                            AMQFrame lastFrame = (AMQFrame) frames.get(frames.size() - 1);
                                            assertTrue("Connection should not be possible with a frame size < " + Constant.MIN_MAX_FRAME_SIZE, lastFrame.getBodyFrame() instanceof ConnectionCloseBody);
                                        }
                                    }
                                });
        }
    }


    public void testTooLargeFrameSize() throws Exception
    {
        getBrokerConfiguration().setObjectAttribute(AuthenticationProvider.class,
                                                    TestBrokerConfiguration.ENTRY_NAME_AUTHENTICATION_PROVIDER,
                                                    "secureOnlyMechanisms",
                                                    "[]");
        setTestSystemProperty(Broker.BROKER_FRAME_SIZE, "8192");
        super.setUp();
        if(isBroker010())
        {
            Connection conn = new Connection();
            final ConnectionSettings settings = new ConnectionSettings();
            BrokerDetails brokerDetails = getConnectionFactory().getConnectionURL().getAllBrokerDetails().get(0);
            settings.setHost(brokerDetails.getHost());
            settings.setPort(brokerDetails.getPort());
            settings.setUsername(GUEST_USERNAME);
            settings.setPassword(GUEST_PASSWORD);
            final ConnectionDelegate clientDelegate = new TestClientDelegate(settings, 0xffff);
            conn.setConnectionDelegate(clientDelegate);
            try
            {
                conn.connect(settings);
                fail("Connection should not be possible with a frame size larger than the broker requested");
            }
            catch(ConnectionException e)
            {
                // pass
            }

        }
        else
        {
            doAMQP08test(10000, new ResultEvaluator()
                                {

                                    @Override
                                    public void evaluate(final Socket socket, final List<AMQDataBlock> frames)
                                    {
                                        if(!socket.isClosed())
                                        {
                                            AMQFrame lastFrame = (AMQFrame) frames.get(frames.size() - 1);
                                            assertTrue("Connection should not be possible with a frame size larger than the broker requested", lastFrame.getBodyFrame() instanceof ConnectionCloseBody);
                                        }
                                    }
                                });
        }
    }

    private static interface ResultEvaluator
    {
        void evaluate(Socket socket, List<AMQDataBlock> frames);
    }

    private void doAMQP08test(int frameSize, ResultEvaluator evaluator)
            throws NamingException, IOException, AMQFrameDecodingException, AMQProtocolVersionException
    {
        BrokerDetails brokerDetails = getConnectionFactory().getConnectionURL().getAllBrokerDetails().get(0);

        Socket socket = new Socket(brokerDetails.getHost(), brokerDetails.getPort());
        socket.setTcpNoDelay(true);
        OutputStream os = socket.getOutputStream();

        byte[] protocolHeader;
        Protocol protocol = getBrokerProtocol();
        switch(protocol)
        {
            case AMQP_0_8:
                protocolHeader = (ProtocolEngineCreator_0_8.getInstance().getHeaderIdentifier());
                break;
            case AMQP_0_9:
                protocolHeader = (ProtocolEngineCreator_0_9.getInstance().getHeaderIdentifier());
                break;
            case AMQP_0_9_1:
                protocolHeader = (ProtocolEngineCreator_0_9_1.getInstance().getHeaderIdentifier());
                break;
            default:
                throw new RuntimeException("Unexpected Protocol Version: " + protocol);
        }
        os.write(protocolHeader);
        InputStream is = socket.getInputStream();

        final byte[] response = new byte[2+GUEST_USERNAME.length()+GUEST_PASSWORD.length()];
        int i = 1;
        for(byte b : GUEST_USERNAME.getBytes(StandardCharsets.US_ASCII))
        {
            response[i++] = b;
        }
        i++;
        for(byte b : GUEST_PASSWORD.getBytes(StandardCharsets.US_ASCII))
        {
            response[i++] = b;
        }

        ConnectionStartOkBody startOK = new ConnectionStartOkBody(new FieldTable(), AMQShortString.valueOf("PLAIN"), response, AMQShortString.valueOf("en_US"));

        DataOutputStream dos = new DataOutputStream(os);
        new AMQFrame(0, startOK).writePayload(dos);
        dos.flush();
        ConnectionTuneOkBody tuneOk = new ConnectionTuneOkBody(256, frameSize, 0);
        new AMQFrame(0, tuneOk).writePayload(dos);
        dos.flush();
        socket.setSoTimeout(5000);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int size;
        while((size = is.read(buffer)) > 0)
        {
            baos.write(buffer,0,size);
        }

        byte[] serverData = baos.toByteArray();
        final FrameCreatingMethodProcessor methodProcessor = new FrameCreatingMethodProcessor(ProtocolVersion.v0_91);
        AMQDecoder decoder = new ClientDecoder(methodProcessor);
        decoder.decodeBuffer(ByteBuffer.wrap(serverData));

        evaluator.evaluate(socket, methodProcessor.getProcessedMethods());
    }

    private static class TestClientDelegate extends ClientDelegate
    {

        private final int _maxFrameSize;

        public TestClientDelegate(final ConnectionSettings settings, final int maxFrameSize)
        {
            super(settings);
            _maxFrameSize = maxFrameSize;
        }

        @Override
        protected SaslClient createSaslClient(final List<Object> brokerMechs) throws ConnectionException, SaslException
        {
            final CallbackHandler handler = new CallbackHandler()
            {
                @Override
                public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException
                {
                    for (int i = 0; i < callbacks.length; i++)
                    {
                        Callback cb = callbacks[i];
                        if (cb instanceof NameCallback)
                        {
                            ((NameCallback)cb).setName(GUEST_USERNAME);
                        }
                        else if (cb instanceof PasswordCallback)
                        {
                            ((PasswordCallback)cb).setPassword(GUEST_PASSWORD.toCharArray());
                        }
                        else
                        {
                            throw new UnsupportedCallbackException(cb);
                        }
                    }

                }
            };
            String[] selectedMechs = {};
            for(String mech : new String[] { "ANONYMOUS", "PLAIN", "CRAM-MD5", "SCRAM-SHA-1", "SCRAM-SHA-256"})
            {
                if(brokerMechs.contains(mech))
                {
                    selectedMechs = new String[] {mech};
                    break;
                }
            }


            return Sasl.createSaslClient(selectedMechs,
                                         null,
                                         getConnectionSettings().getSaslProtocol(),
                                         getConnectionSettings().getSaslServerName(),
                                         Collections.<String,Object>emptyMap(),
                                         handler);

        }

        @Override
        public void connectionTune(Connection conn, ConnectionTune tune)
        {
            int heartbeatInterval = getConnectionSettings().getHeartbeatInterval010();
            float heartbeatTimeoutFactor = getConnectionSettings().getHeartbeatTimeoutFactor();
            int actualHeartbeatInterval = calculateHeartbeatInterval(heartbeatInterval,
                                                                     tune.getHeartbeatMin(),
                                                                     tune.getHeartbeatMax());

            conn.connectionTuneOk(tune.getChannelMax(),
                                  _maxFrameSize,
                                  actualHeartbeatInterval);

            int idleTimeout = (int)(actualHeartbeatInterval * 1000 * heartbeatTimeoutFactor);
            conn.getNetworkConnection().setMaxReadIdle((int)(actualHeartbeatInterval*heartbeatTimeoutFactor));
            conn.getNetworkConnection().setMaxWriteIdle(actualHeartbeatInterval);
            conn.setMaxFrameSize(_maxFrameSize);


            conn.setIdleTimeout(idleTimeout);

            int channelMax = tune.getChannelMax();
            conn.setChannelMax(channelMax == 0 ? Connection.MAX_CHANNEL_MAX : channelMax);

            conn.connectionOpen(getConnectionSettings().getVhost(), null, Option.INSIST);
        }

    }
}