/*************************************************************************
 * PCRaw
 * Author: nori090
 * Original author: ◆e5bW6vDOJ.
 * Copyright: Copyright (C) 2008 nori090
 * Copyright: Copyright (C) 2007 ◆e5bW6vDOJ.
 * Date: February 11, 2007
 * License: 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 * 
 * http://mosax.sakura.ne.jp/fswiki.cgi?page=PCRaw
 */
package org.coderepos.nori090.pcraw;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coderepos.nori090.pcraw.PCP.Bin;
import org.coderepos.nori090.pcraw.PCP.Parent;
import org.coderepos.nori090.pcraw.PCRP.PCRPInfo;

/**
 * @author nori090
 * @version $Rev: 123 $ $Date: 2008-07-26 13:36:18 +0900 (Sat, 26 Jul 2008) $
 */
public final class PcpTools {
    private static final Log log = LogFactory.getLog( PcpTools.class );

    private PcpTools() {
    }

    private static void pcpGetSid( String address, int port, byte[] sid, int timeout )
        throws IOException {
        SocketChannel sock = SocketChannel.open( new InetSocketAddress( address, port ) );
        try {
            sock.configureBlocking( true );
            sock.socket().setSoTimeout( timeout );
            PCP pcp = new PCP( sock );
            pcp.writeInt( PCP.PCP_CONNECT, 1 );
            Parent p = new PCP.Parent();
            p.id = PCP.PCP_HELO;
            p.nc = 0;
            pcp.writeParent( p );
            boolean succeed = false;
            p = pcp.readParent();
            if ( !Arrays.equals( p.id, PCP.PCP_OLEH ) ) {
                throw new IOException( "Local server is not PeerCast." );
            }
            for ( int i = 0; i < p.nc; i++ ) {
                PCP.Bin bin = pcp.readBin();
                if ( Arrays.equals( bin.id, PCP.PCP_HELO_SESSIONID ) && bin.buf.length == sid.length ) {
                    System.arraycopy( bin.buf, 0, sid, 0, sid.length );
                    succeed = true;
                }
            }
            if ( !succeed ) {
                throw new IOException( "Get SID failed." );
            }
        }
        finally {
            sock.close();
        }
    }

    static int pcpPortCheck( PCRPInfo info, int timeout )
        throws IOException {
        info.keyMgr.clear();
        byte[] sid = new byte[16];
        pcpGetSid( info.localHost, info.localPort, sid, timeout );
        SocketChannel sock = SocketChannel.open( new InetSocketAddress( info.trackerHost, info.trackerPort ) );
        int port = 0;
        try {
            sock.configureBlocking( true );
            sock.socket().setSoTimeout( timeout );
            PCP pcp = new PCP( sock );
            pcp.writeInt( PCP.PCP_CONNECT, 1 );
            PCP.Parent p = new Parent();
            p.id = PCP.PCP_HELO;
            p.nc = 2;
            pcp.writeParent( p );
            Bin bin = new PCP.Bin();
            bin.id = PCP.PCP_HELO_SESSIONID;
            bin.buf = sid;
            pcp.writeBin( bin );
            pcp.writeInt( PCP.PCP_HELO_PING, (short) info.localPort );

            p = pcp.readParent();
            if ( !Arrays.equals( PCP.PCP_OLEH, p.id ) ) {
                throw new IOException( "Tracket is not PeerCast." );
            }

            for ( int i = 0; i <= p.nc; i++ ) {
                bin = pcp.readBin();

                if ( Arrays.equals( PCP.PCP_HELO_PORT, bin.id ) ) {
                    if ( bin.buf.length != 2 ) {
                        throw new IOException( "pcpPortCheck() Invalid PCP data. (1)" );
                    }
                    port = ( bin.buf[1] & 0xFF ) << 8;
                    port = port | ( bin.buf[0] & 0xFF );
                }
                else if ( Arrays.equals( PCP.PCP_PCRAW_KEYC, bin.id ) ) {
                    log.debug( "現在の鍵をセット." );
                    if ( bin.buf.length != 16 ) {
                        throw new IOException( "pcpPortCheck() Invalid PCP data. (2)" );
                    }
                    info.keyMgr.add( bin.buf, 0L );
                }
                else if ( Arrays.equals( PCP.PCP_PCRAW_KEYN, bin.id ) ) {
                    log.debug( "次の鍵をセット." );
                    if ( bin.buf.length != 16 ) {
                        throw new IOException( "pcpPortCheck() Invalid PCP data. (3)" );
                    }
                    info.keyMgr.add( bin.buf, PCRawTools.time() + info.keyMgr.lifeTime );
                }
                else if ( Arrays.equals( PCP.PCP_PCRAW_KEYP, bin.id ) ) {
                    log.debug( "前の鍵をセット." );
                    if ( bin.buf.length != 16 ) {
                        throw new IOException( "pcpPortCheck() Invalid PCP data. (4)" );
                    }
                    info.keyMgr.add( bin.buf, PCRawTools.time() - info.keyMgr.lifeTime );
                }
            }
            return port;
        }
        finally {
            sock.close();
        }
    }
}
