private void ProcessPortforwardingRequest(ISSHConnectionEventReceiver receiver, SSH1Packet packet)
        {
            SSH1DataReader reader         = new SSH1DataReader(packet.Data);
            int            server_channel = reader.ReadInt32();
            string         host           = Encoding.Default.GetString(reader.ReadString());
            int            port           = reader.ReadInt32();

            SSH1DataWriter            writer = new SSH1DataWriter();
            PortForwardingCheckResult result = receiver.CheckPortForwardingRequest(host, port, "", 0);

            if (result.allowed)
            {
                int local_id = this.RegisterChannelEventReceiver(null, result.channel)._localID;
                _eventReceiver.EstablishPortforwarding(result.channel, new SSH1Channel(this, ChannelType.ForwardedRemoteToLocal, local_id, server_channel));

                writer.Write(server_channel);
                writer.Write(local_id);
                SSH1Packet p = SSH1Packet.FromPlainPayload(PacketType.SSH_MSG_CHANNEL_OPEN_CONFIRMATION, writer.ToByteArray());
                p.WriteTo(_stream, _tCipher);
            }
            else
            {
                writer.Write(server_channel);
                SSH1Packet p = SSH1Packet.FromPlainPayload(PacketType.SSH_MSG_CHANNEL_OPEN_FAILURE, writer.ToByteArray());
                p.WriteTo(_stream, _tCipher);
            }
        }
        private SSH1Packet ReceivePacket()
        {
            while (true)
            {
                SSH1Packet p = null;
                SynchronizedSSH1PacketHandler handler = (SynchronizedSSH1PacketHandler)_packetBuilder.Handler;
                if (!handler.HasPacket)
                {
                    handler.Wait();
                    if (handler.State == ReceiverState.Error)
                    {
                        throw new SSHException(handler.ErrorMessage);
                    }
                    else if (handler.State == ReceiverState.Closed)
                    {
                        throw new SSHException("socket closed");
                    }
                }
                p = handler.PopPacket();

                SSH1DataReader r  = new SSH1DataReader(p.Data);
                PacketType     pt = p.Type;
                if (pt == PacketType.SSH_MSG_IGNORE)
                {
                    if (_eventReceiver != null)
                    {
                        _eventReceiver.OnIgnoreMessage(r.ReadString());
                    }
                }
                else if (pt == PacketType.SSH_MSG_DEBUG)
                {
                    if (_eventReceiver != null)
                    {
                        _eventReceiver.OnDebugMessage(false, r.ReadString());
                    }
                }
                else
                {
                    return(p);
                }
            }
        }
        /// <summary>
        /// constructs from file
        /// </summary>
        /// <param name="path">file name</param>
        /// <param name="passphrase">passphrase or empty string if passphrase is not required</param>
        public SSH1UserAuthKey(string path, string passphrase)
        {
            Stream s = File.Open(path, FileMode.Open);

            byte[] header = new byte[32];
            s.Read(header, 0, header.Length);
            if (Encoding.ASCII.GetString(header) != "SSH PRIVATE KEY FILE FORMAT 1.1\n")
            {
                throw new SSHException(String.Format(Strings.GetString("BrokenKeyFile"), path));
            }

            SSH1DataReader reader = new SSH1DataReader(ReadAll(s));

            s.Close();

            byte[] cipher = reader.Read(2);             //first 2 bytes indicates algorithm and next 8 bytes is space
            reader.Read(8);

            _modulus        = reader.ReadMPInt();
            _publicExponent = reader.ReadMPInt();
            byte[] comment = reader.ReadString();
            byte[] prvt    = reader.ReadAll();
            //必要なら復号
            CipherAlgorithm algo = (CipherAlgorithm)cipher[1];

            if (algo != 0)
            {
                Cipher c   = CipherFactory.CreateCipher(SSHProtocol.SSH1, algo, ConvertToKey(passphrase));
                byte[] buf = new byte[prvt.Length];
                c.Decrypt(prvt, 0, prvt.Length, buf, 0);
                prvt = buf;
            }

            SSH1DataReader prvtreader = new SSH1DataReader(prvt);

            byte[] mark = prvtreader.Read(4);
            if (mark[0] != mark[2] || mark[1] != mark[3])
            {
                throw new SSHException(Strings.GetString("WrongPassphrase"));
            }

            _privateExponent = prvtreader.ReadMPInt();
            _crtCoefficient  = prvtreader.ReadMPInt();
            _primeP          = prvtreader.ReadMPInt();
            _primeQ          = prvtreader.ReadMPInt();
        }
        /// <summary>
        /// constructs from file
        /// </summary>
        /// <param name="path">file name</param>
        /// <param name="passphrase">passphrase or empty string if passphrase is not required</param>
        public SSH1UserAuthKey(string path, string passphrase)
        {
            Stream s = File.Open(path, FileMode.Open);
            byte[] header = new byte[32];
            s.Read(header, 0, header.Length);
            if(Encoding.Default.GetString(header) != "SSH PRIVATE KEY FILE FORMAT 1.1\n")
                throw new SSHException(String.Format(Strings.GetString("BrokenKeyFile"), path));

            SSH1DataReader reader = new SSH1DataReader(ReadAll(s));
            s.Close();

            byte[] cipher = reader.Read(2); //first 2 bytes indicates algorithm and next 8 bytes is space
            reader.Read(8);

            _modulus = reader.ReadMPInt();
            _publicExponent = reader.ReadMPInt();
            byte[] comment = reader.ReadString();
            byte[] prvt = reader.ReadAll();
            //�K�v�Ȃ畜��
            CipherAlgorithm algo = (CipherAlgorithm)cipher[1];
            if(algo!=0) {
                Cipher c = CipherFactory.CreateCipher(SSHProtocol.SSH1, algo, ConvertToKey(passphrase));
                byte[] buf = new byte[prvt.Length];
                c.Decrypt(prvt, 0, prvt.Length, buf, 0);
                prvt = buf;
            }

            SSH1DataReader prvtreader = new SSH1DataReader(prvt);
            byte[] mark = prvtreader.Read(4);
            if(mark[0]!=mark[2] || mark[1]!=mark[3])
                throw new SSHException(Strings.GetString("WrongPassphrase"));

            _privateExponent = prvtreader.ReadMPInt();
            _crtCoefficient = prvtreader.ReadMPInt();
            _primeP = prvtreader.ReadMPInt();
            _primeQ = prvtreader.ReadMPInt();
        }
        internal void AsyncReceivePacket(SSH1Packet p)
        {
            try {
                int len = 0, channel = 0;
                switch (p.Type)
                {
                case PacketType.SSH_SMSG_STDOUT_DATA:
                    len = SSHUtil.ReadInt32(p.Data, 0);
                    FindChannelEntry(_shellID)._receiver.OnData(p.Data, 4, len);
                    break;

                case PacketType.SSH_SMSG_STDERR_DATA: {
                    SSH1DataReader re = new SSH1DataReader(p.Data);
                    FindChannelEntry(_shellID)._receiver.OnExtendedData((int)PacketType.SSH_SMSG_STDERR_DATA, re.ReadString());
                }
                break;

                case PacketType.SSH_MSG_CHANNEL_DATA:
                    channel = SSHUtil.ReadInt32(p.Data, 0);
                    len     = SSHUtil.ReadInt32(p.Data, 4);
                    FindChannelEntry(channel)._receiver.OnData(p.Data, 8, len);
                    break;

                case PacketType.SSH_MSG_PORT_OPEN:
                    this.ProcessPortforwardingRequest(_eventReceiver, p);
                    break;

                case PacketType.SSH_MSG_CHANNEL_CLOSE: {
                    channel = SSHUtil.ReadInt32(p.Data, 0);
                    ISSHChannelEventReceiver r = FindChannelEntry(channel)._receiver;
                    UnregisterChannelEventReceiver(channel);
                    r.OnChannelClosed();
                }
                break;

                case PacketType.SSH_MSG_CHANNEL_CLOSE_CONFIRMATION:
                    channel = SSHUtil.ReadInt32(p.Data, 0);
                    break;

                case PacketType.SSH_MSG_DISCONNECT:
                    _eventReceiver.OnConnectionClosed();
                    break;

                case PacketType.SSH_SMSG_EXITSTATUS:
                    FindChannelEntry(_shellID)._receiver.OnChannelClosed();
                    break;

                case PacketType.SSH_MSG_DEBUG: {
                    SSH1DataReader re = new SSH1DataReader(p.Data);
                    _eventReceiver.OnDebugMessage(false, re.ReadString());
                }
                break;

                case PacketType.SSH_MSG_IGNORE: {
                    SSH1DataReader re = new SSH1DataReader(p.Data);
                    _eventReceiver.OnIgnoreMessage(re.ReadString());
                }
                break;

                case PacketType.SSH_MSG_CHANNEL_OPEN_CONFIRMATION: {
                    int local  = SSHUtil.ReadInt32(p.Data, 0);
                    int remote = SSHUtil.ReadInt32(p.Data, 4);
                    FindChannelEntry(local)._receiver.OnChannelReady();
                }
                break;

                case PacketType.SSH_SMSG_SUCCESS:
                    if (_executingShell)
                    {
                        ExecShell();
                        this.FindChannelEntry(_shellID)._receiver.OnChannelReady();
                        _executingShell = false;
                    }
                    break;

                default:
                    _eventReceiver.OnUnknownMessage((byte)p.Type, p.Data);
                    break;
                }
            }
            catch (Exception ex) {
                if (!_closed)
                {
                    _eventReceiver.OnError(ex, ex.Message);
                }
            }
        }
        private SSH1Packet ReceivePacket()
        {
            while(true) {
                SSH1Packet p = null;
                SynchronizedSSH1PacketHandler handler = (SynchronizedSSH1PacketHandler)_packetBuilder.Handler;
                if(!handler.HasPacket) {
                    handler.Wait();
                    if(handler.State==ReceiverState.Error)
                        throw new SSHException(handler.ErrorMessage);
                    else if(handler.State==ReceiverState.Closed)
                        throw new SSHException("socket closed");
                }
                p = handler.PopPacket();

                SSH1DataReader r = new SSH1DataReader(p.Data);
                PacketType pt = p.Type;
                if(pt==PacketType.SSH_MSG_IGNORE) {
                    if(_eventReceiver!=null) _eventReceiver.OnIgnoreMessage(r.ReadString());
                }
                else if(pt==PacketType.SSH_MSG_DEBUG) {
                    if(_eventReceiver!=null) _eventReceiver.OnDebugMessage(false, r.ReadString());
                }
                else
                    return p;
            }
        }
        private void ProcessPortforwardingRequest(ISSHConnectionEventReceiver receiver, SSH1Packet packet)
        {
            SSH1DataReader reader = new SSH1DataReader(packet.Data);
            int server_channel = reader.ReadInt32();
            string host = Encoding.Default.GetString(reader.ReadString());
            int port = reader.ReadInt32();

            SSH1DataWriter writer = new SSH1DataWriter();
            PortForwardingCheckResult result = receiver.CheckPortForwardingRequest(host, port, "", 0);
            if(result.allowed) {
                int local_id = this.RegisterChannelEventReceiver(null, result.channel)._localID;
                _eventReceiver.EstablishPortforwarding(result.channel, new SSH1Channel(this, ChannelType.ForwardedRemoteToLocal, local_id, server_channel));

                writer.Write(server_channel);
                writer.Write(local_id);
                SSH1Packet p = SSH1Packet.FromPlainPayload(PacketType.SSH_MSG_CHANNEL_OPEN_CONFIRMATION, writer.ToByteArray());
                p.WriteTo(_stream, _tCipher);
            }
            else {
                writer.Write(server_channel);
                SSH1Packet p = SSH1Packet.FromPlainPayload(PacketType.SSH_MSG_CHANNEL_OPEN_FAILURE, writer.ToByteArray());
                p.WriteTo(_stream, _tCipher);
            }
        }
 internal void AsyncReceivePacket(SSH1Packet p)
 {
     try {
         int len = 0, channel = 0;
         switch(p.Type) {
             case PacketType.SSH_SMSG_STDOUT_DATA:
                 len = SSHUtil.ReadInt32(p.Data, 0);
                 FindChannelEntry(_shellID)._receiver.OnData(p.Data, 4, len);
                 break;
             case PacketType.SSH_SMSG_STDERR_DATA: {
                 SSH1DataReader re = new SSH1DataReader(p.Data);
                 FindChannelEntry(_shellID)._receiver.OnExtendedData((int)PacketType.SSH_SMSG_STDERR_DATA, re.ReadString());
             }
                 break;
             case PacketType.SSH_MSG_CHANNEL_DATA:
                 channel = SSHUtil.ReadInt32(p.Data, 0);
                 len = SSHUtil.ReadInt32(p.Data, 4);
                 FindChannelEntry(channel)._receiver.OnData(p.Data, 8, len);
                 break;
             case PacketType.SSH_MSG_PORT_OPEN:
                 this.ProcessPortforwardingRequest(_eventReceiver, p);
                 break;
             case PacketType.SSH_MSG_CHANNEL_CLOSE: {
                 channel = SSHUtil.ReadInt32(p.Data, 0);
                 ISSHChannelEventReceiver r = FindChannelEntry(channel)._receiver;
                 UnregisterChannelEventReceiver(channel);
                 r.OnChannelClosed();
             }
                 break;
             case PacketType.SSH_MSG_CHANNEL_CLOSE_CONFIRMATION:
                 channel = SSHUtil.ReadInt32(p.Data, 0);
                 break;
             case PacketType.SSH_MSG_DISCONNECT:
                 _eventReceiver.OnConnectionClosed();
                 break;
             case PacketType.SSH_SMSG_EXITSTATUS:
                 FindChannelEntry(_shellID)._receiver.OnChannelClosed();
                 break;
             case PacketType.SSH_MSG_DEBUG: {
                 SSH1DataReader re = new SSH1DataReader(p.Data);
                 _eventReceiver.OnDebugMessage(false, re.ReadString());
             }
                 break;
             case PacketType.SSH_MSG_IGNORE: {
                 SSH1DataReader re = new SSH1DataReader(p.Data);
                 _eventReceiver.OnIgnoreMessage(re.ReadString());
             }
                 break;
             case PacketType.SSH_MSG_CHANNEL_OPEN_CONFIRMATION: {
                 int local = SSHUtil.ReadInt32(p.Data, 0);
                 int remote = SSHUtil.ReadInt32(p.Data, 4);
                 FindChannelEntry(local)._receiver.OnChannelReady();
             }
                 break;
             case PacketType.SSH_SMSG_SUCCESS:
                 if(_executingShell) {
                     ExecShell();
                     this.FindChannelEntry(_shellID)._receiver.OnChannelReady();
                     _executingShell = false;
                 }
                 break;
             default:
                 _eventReceiver.OnUnknownMessage((byte)p.Type, p.Data);
                 break;
         }
     }
     catch(Exception ex) {
         if(!_closed)
             _eventReceiver.OnError(ex, ex.Message);
     }
 }