001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *  
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *  
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License. 
018 *  
019 */
020
021package org.apache.directory.server.dns.protocol;
022
023
024import org.apache.directory.server.dns.io.decoder.DnsMessageDecoder;
025import org.apache.directory.server.i18n.I18n;
026import org.apache.mina.core.buffer.IoBuffer;
027import org.apache.mina.core.session.IoSession;
028import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
029import org.apache.mina.filter.codec.ProtocolDecoderOutput;
030
031
032/**
033 * A {@link CumulativeProtocolDecoder} which supports DNS operation over TCP,
034 * by reassembling split packets prior to decoding.
035 * 
036 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
037 */
038public class DnsTcpDecoder extends CumulativeProtocolDecoder
039{
040    private DnsMessageDecoder decoder = new DnsMessageDecoder();
041
042    private int maxObjectSize = 16384; // 16KB
043
044
045    /**
046     * Returns the allowed maximum size of the object to be decoded.
047     * 
048     * @return The max object size.
049     */
050    public int getMaxObjectSize()
051    {
052        return maxObjectSize;
053    }
054
055
056    /**
057     * Sets the allowed maximum size of the object to be decoded.
058     * If the size of the object to be decoded exceeds this value, this
059     * decoder will throw a {@link IllegalArgumentException}.  The default
060     * value is <tt>16384</tt> (16KB).
061     * 
062     * @param maxObjectSize 
063     */
064    public void setMaxObjectSize( int maxObjectSize )
065    {
066        if ( maxObjectSize <= 0 )
067        {
068            throw new IllegalArgumentException( I18n.err( I18n.ERR_634, maxObjectSize ) );
069        }
070
071        this.maxObjectSize = maxObjectSize;
072    }
073
074
075    @Override
076    protected boolean doDecode( IoSession session, IoBuffer in, ProtocolDecoderOutput out ) throws Exception
077    {
078        if ( !in.prefixedDataAvailable( 2, maxObjectSize ) )
079        {
080            return false;
081        }
082
083        in.getShort();
084
085        out.write( decoder.decode( in ) );
086
087        return true;
088    }
089}