Beispiel #1
0
        public MqttTcpServerListener(
            AddressFamily addressFamily,
            MqttServerTcpEndpointBaseOptions options,
            X509Certificate2 tlsCertificate,
            CancellationToken cancellationToken,
            IMqttNetChildLogger logger)
        {
            _cancellationToken = cancellationToken;
            _logger            = logger;
            _addressFamily     = addressFamily;

            var sb = new SocketOptionBuilder().SetSocket(Sockets.Model.SocketType.Tcp).UseStream();

            if (options is MqttServerTlsTcpEndpointOptions tlsOptions)
            {
                sb = sb.WithSsl(tlsCertificate, tlsOptions.SslProtocol);
            }

            sb = sb.SetPort(options.Port);

            if (_addressFamily == AddressFamily.InterNetworkV6)
            {
                sb = sb.UseIPV6();
            }

            socketOption = sb.Build();

            serverSokcet = SocketFactory.CreateServerSocket(socketOption, cancellationToken);

            serverSokcet.OnAccepted += ServerSokcet_OnAccepted;
        }
Beispiel #2
0
        /// <summary>
        /// Create a socket for an address
        /// </summary>
        /// <param name="address">The address the socket should connect to</param>
        /// <returns></returns>
        protected virtual IWebsocket CreateSocket(string address)
        {
            var socket = SocketFactory.CreateWebsocket(log, address);

            log.Write(LogVerbosity.Debug, "Created new socket for " + address);

            if (apiProxy != null)
            {
                socket.SetProxy(apiProxy.Host, apiProxy.Port);
            }

            socket.DataInterpreter = dataInterpreter;
            socket.OnClose        += () =>
            {
                lock (sockets)
                {
                    foreach (var sub in sockets)
                    {
                        sub.ResetEvents();
                    }
                }

                SocketOnClose(socket);
            };
            socket.OnError += e =>
            {
                log.Write(LogVerbosity.Info, $"Socket {socket.Id} error: " + e.ToString());
                SocketError(socket, e);
            };
            socket.OnOpen  += () => SocketOpened(socket);
            socket.OnClose += () => SocketClosed(socket);
            return(socket);
        }
Beispiel #3
0
        /// <summary>
        /// WSClient
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="subProtocol"></param>
        /// <param name="origin"></param>
        /// <param name="bufferSize"></param>
        public WSClient(string ip = "127.0.0.1", int port = 16666, string subProtocol = SubProtocolType.Default, string origin = "", int bufferSize = 10 * 1024)
        {
            _serverIP   = ip;
            _serverPort = port;

            if (string.IsNullOrEmpty(_url))
            {
                _url = $"ws://{ip}:{port}/";
            }

            _origin = origin;

            _bufferSize = bufferSize;

            _buffer = new byte[_bufferSize];

            _wsContext = new WSContext();

            var option = SocketOptionBuilder.Instance
                         .UseIocp(_wsContext)
                         .SetIP(ip)
                         .SetPort(port)
                         .SetReadBufferSize(bufferSize)
                         .SetReadBufferSize(bufferSize)
                         .Build();

            _subProtocol = subProtocol;

            _client = SocketFactory.CreateClientSocket(option);

            _client.OnReceive      += _client_OnReceive;
            _client.OnDisconnected += WSClient_OnDisconnected;
            _client.OnError        += WSClient_OnError;
        }
Beispiel #4
0
        protected void SetupData()
        {
            _serverEndPoint = new IPEndPoint(IPAddress.Loopback, 8122);
            _connectionInfo = new ConnectionInfo(
                _serverEndPoint.Address.ToString(),
                _serverEndPoint.Port,
                "user",
                new PasswordAuthenticationMethod("user", "password"));
            _connectionInfo.Timeout = TimeSpan.FromMilliseconds(200);
            _actualException        = null;
            _socketFactory          = new SocketFactory();

            _serverListener            = new AsyncSocketListener(_serverEndPoint);
            _serverListener.Connected += (socket) =>
            {
                _serverSocket = socket;

                // Since we're mocking the protocol version exchange, we can immediately send the bad
                // packet upon establishing the connection

                var badPacket = new byte[] { 0x0a, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05 };
                _serverSocket.Send(badPacket, 0, badPacket.Length, SocketFlags.None);
                _serverSocket.Shutdown(SocketShutdown.Send);
            };
            _serverListener.Start();

            _session = new Session(_connectionInfo, _serviceFactoryMock.Object, _socketFactoryMock.Object);

            _clientSocket = new DirectConnector(_socketFactory).Connect(_connectionInfo);
        }
Beispiel #5
0
        public MessageClient(int bufferSize = 102400, string ip = "127.0.0.1", int port = 39654)
        {
            _messageContext = new MessageContext();

            var option = SocketOptionBuilder.Instance
                         .SetSocket()
                         .UseIocp(_messageContext)
                         .SetIP(ip)
                         .SetPort(port)
                         .SetReadBufferSize(bufferSize)
                         .SetWriteBufferSize(bufferSize)
                         .Build();

            _client = SocketFactory.CreateClientSocket(option);

            _client.OnReceive += _client_OnReceive;

            HeartSpan = 10 * 1000;

            HeartAsync();

            _batcher = new Batcher(10000, 10);

            _batcher.OnBatched += _batcher_OnBatched;
        }
Beispiel #6
0
        internal static int RunJob(IRDDProxy rdd)
        {
            var mockRdd = (rdd as MockRddProxy);
            IEnumerable <byte[]> result = mockRdd.pickle ? mockRdd.result.Cast <byte[]>() :
                                          mockRdd.result.Select(x =>
            {
                var ms = new MemoryStream();
                formatter.Serialize(ms, x);
                return(ms.ToArray());
            });

            var listener = SocketFactory.CreateSocket();

            listener.Listen();

            Task.Run(() =>
            {
                using (var socket = listener.Accept())
                    using (var ns = socket.GetStream())
                    {
                        foreach (var item in result)
                        {
                            SerDe.Write(ns, item.Length);
                            SerDe.Write(ns, item);
                        }
                        ns.Flush();
                    }
            });
            return((listener.LocalEndPoint as IPEndPoint).Port);
        }
        protected override void SetupData()
        {
            base.SetupData();

            var random = new Random();

            _connectionInfo = new ConnectionInfo(IPAddress.Loopback.ToString(),
                                                 777,
                                                 "user",
                                                 ProxyTypes.Http,
                                                 IPAddress.Loopback.ToString(),
                                                 8122,
                                                 "proxyUser",
                                                 "proxyPwd",
                                                 new KeyboardInteractiveAuthenticationMethod("user"));
            _connectionInfo.Timeout = TimeSpan.FromMilliseconds(random.Next(50, 200));
            _stopWatch       = new Stopwatch();
            _actualException = null;

            _clientSocket = SocketFactory.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _proxyServer = new AsyncSocketListener(new IPEndPoint(IPAddress.Loopback, _connectionInfo.ProxyPort));
            _proxyServer.Disconnected += (socket) => _disconnected = true;
            _proxyServer.Start();

            _server = new AsyncSocketListener(new IPEndPoint(IPAddress.Loopback, _connectionInfo.Port));
            _server.Start();
        }
        /// <summary>
        /// Reads the given stream to construct a BroadcastVariables object.
        /// </summary>
        /// <param name="stream">The stream to read from</param>
        /// <returns>BroadcastVariables object</returns>
        internal BroadcastVariables Process(Stream stream)
        {
            var            broadcastVars = new BroadcastVariables();
            ISocketWrapper socket        = null;

            broadcastVars.DecryptionServerNeeded = SerDe.ReadBool(stream);
            broadcastVars.Count = Math.Max(SerDe.ReadInt32(stream), 0);

            if (broadcastVars.DecryptionServerNeeded)
            {
                broadcastVars.DecryptionServerPort = SerDe.ReadInt32(stream);
                broadcastVars.Secret = SerDe.ReadString(stream);
                if (broadcastVars.Count > 0)
                {
                    socket = SocketFactory.CreateSocket();
                    socket.Connect(
                        IPAddress.Loopback,
                        broadcastVars.DecryptionServerPort,
                        broadcastVars.Secret);
                }
            }

            var formatter = new BinaryFormatter();

            for (int i = 0; i < broadcastVars.Count; ++i)
            {
                long bid = SerDe.ReadInt64(stream);
                if (bid >= 0)
                {
                    if (broadcastVars.DecryptionServerNeeded)
                    {
                        long readBid = SerDe.ReadInt64(socket.InputStream);
                        if (bid != readBid)
                        {
                            throw new Exception("The Broadcast Id received from the encryption " +
                                                $"server {readBid} is different from the Broadcast Id received " +
                                                $"from the payload {bid}.");
                        }
                        object value = formatter.Deserialize(socket.InputStream);
                        BroadcastRegistry.Add(bid, value);
                    }
                    else
                    {
                        string path = SerDe.ReadString(stream);
                        using FileStream fStream =
                                  File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                        object value = formatter.Deserialize(fStream);
                        BroadcastRegistry.Add(bid, value);
                    }
                }
                else
                {
                    bid = -bid - 1;
                    BroadcastRegistry.Remove(bid);
                }
            }
            socket?.Dispose();
            return(broadcastVars);
        }
Beispiel #9
0
 public SocketWrapper(Socket socket)
 {
     _socketCancellationToken = new SocketCancellationToken();
     _socketFactory = new SocketFactory(_socketCancellationToken);
     _socket = socket;
     if (_socket.Connected)
         _stream = new NetworkStream(_socket);
 }
Beispiel #10
0
 /// <exception cref="System.IO.IOException"/>
 public HAServiceProtocolClientSideTranslatorPB(IPEndPoint addr, Configuration conf
                                                , SocketFactory socketFactory, int timeout)
 {
     RPC.SetProtocolEngine(conf, typeof(HAServiceProtocolPB), typeof(ProtobufRpcEngine
                                                                     ));
     rpcProxy = RPC.GetProxy <HAServiceProtocolPB>(RPC.GetProtocolVersion(typeof(HAServiceProtocolPB
                                                                                 )), addr, UserGroupInformation.GetCurrentUser(), conf, socketFactory, timeout);
 }
Beispiel #11
0
 public void Open()
 {
     BeetleX.XRPC.Packets.ServerPacket serverPacke = new Packets.ServerPacket();
     serverPacke.Options = this.RPCOptions;
     mServer             = SocketFactory.CreateTcpServer(this, serverPacke, ServerOptions);
     mServer.WriteLogo   = OutputLogo;
     mServer.Open();
 }
 /// <exception cref="System.IO.IOException"/>
 public InterDatanodeProtocolTranslatorPB(IPEndPoint addr, UserGroupInformation ugi
                                          , Configuration conf, SocketFactory factory, int socketTimeout)
 {
     RPC.SetProtocolEngine(conf, typeof(InterDatanodeProtocolPB), typeof(ProtobufRpcEngine
                                                                         ));
     rpcProxy = RPC.GetProxy <InterDatanodeProtocolPB>(RPC.GetProtocolVersion(typeof(InterDatanodeProtocolPB
                                                                                     )), addr, ugi, conf, factory, socketTimeout);
 }
Beispiel #13
0
 /*
  *
  *  Need to hide all these callbacks
  */
 public TwitchBot(string username, string channel)
 {
     Username        = username;
     DefaultChannel  = channel;
     CallbackHandler = new CallbackHandler();
     Socket          = SocketFactory.createSocketConnection(ConnectionType.TCP_SSL);
     ReceivingThread = new Thread(ReceiveData);
     DefaultActions();
 }
Beispiel #14
0
 /// <summary>
 /// Server oluşturup envorimentten aldığı portu dinlemeye başlar
 /// </summary>
 /// <returns></returns>
 public IServer GetServer()
 {
     if (server == null)
     {
         server = SocketFactory.CreateTcpServer <TcpConsumer>(new ServerOptions().AddListen(IPAddress.Any.ToString(),
                                                                                            int.Parse(Environment.GetEnvironmentVariable("TCP_PORT"))));
     }
     return(server);
 }
Beispiel #15
0
        public void Run()
        {
            var listener = SocketFactory.CreateTcpListenerObject();

            listener.ReceivedData += Listener_ReceivedData;
            listener.Listen(18081);

            Console.ReadKey();
        }
Beispiel #16
0
 public static void Main(string[] args)
 {
     server = SocketFactory.CreateTcpServer <Program>();
     //server.Options.DefaultListen.CertificateFile = "text.pfx";
     //server.Options.DefaultListen.SSL = true;
     //server.Options.DefaultListen.CertificatePassword = "******";
     server.Open();
     Console.Read();
 }
        public override void Open()
        {
            this.Handle = SocketFactory.CreateNonBlockingUdpMulticastSocket(remote, local, multicastLoopback, timeToLive);
            this.Handle.Bind(local);
            IPEndPoint ipEp = new IPEndPoint(((IPEndPoint)remote).Address, ((IPEndPoint)remote).Port);

            this.Handle.Connect(ipEp);
            this.reactor.RegisterHandler(this, EventType.READ_WRITE_EVENT);
        }
Beispiel #18
0
 /// <exception cref="System.IO.IOException"/>
 public Invoker(Type protocol, IPEndPoint address, UserGroupInformation ticket, Configuration
                conf, SocketFactory factory, int rpcTimeout, AtomicBoolean fallbackToSimpleAuth
                )
 {
     this.remoteId = Client.ConnectionId.GetConnectionId(address, protocol, ticket, rpcTimeout
                                                         , conf);
     this.client = Clients.GetClient(conf, factory);
     this.fallbackToSimpleAuth = fallbackToSimpleAuth;
 }
Beispiel #19
0
        public TcpProvider(SocketFactory socketFactory, int limit = 1)
        {
            _logger = LogManager.GetCurrentClassLogger();

            _socketFactory = socketFactory;
            _limit         = limit;

            _connections = new ConcurrentDictionary <EndPoint, ITcpConnection>();
        }
 public LightningLikePaymentHandler(
     NBXplorerDashboard dashboard,
     LightningClientFactoryService lightningClientFactory,
     SocketFactory socketFactory)
 {
     _Dashboard = dashboard;
     _lightningClientFactory = lightningClientFactory;
     _socketFactory          = socketFactory;
 }
Beispiel #21
0
        public void Open()
        {
            BeetleX.XRPC.Packets.ServerPacket serverPacke = new Packets.ServerPacket();
            serverPacke.Options = this.RPCOptions;
            mServer             = SocketFactory.CreateTcpServer(this, serverPacke, ServerOptions);

            mServer.Open();
            Log(LogType.Info, $"BeetleX XRPC started [{GetType().Assembly.GetName().Version}]");
        }
Beispiel #22
0
        public static int Main()
        {
            ICollectionFactory collectionFactory = new CollectionFactory();
             ProxyGenerator proxyGenerator = new ProxyGenerator();
             IThreadingFactory threadingFactory = new ThreadingFactory();
             ISynchronizationFactory synchronizationFactory = new SynchronizationFactory();
             IThreadingProxy threadingProxy = new ThreadingProxy(threadingFactory, synchronizationFactory);
             IDnsProxy dnsProxy = new DnsProxy();
             ITcpEndPointFactory tcpEndPointFactory = new TcpEndPointFactory(dnsProxy);
             IStreamFactory streamFactory = new StreamFactory();
             INetworkingInternalFactory networkingInternalFactory = new NetworkingInternalFactory(threadingProxy, streamFactory);
             ISocketFactory socketFactory = new SocketFactory(tcpEndPointFactory, networkingInternalFactory);
             INetworkingProxy networkingProxy = new NetworkingProxy(socketFactory, tcpEndPointFactory);
             IPofContext pofContext = new ClientPofContext();
             IPofSerializer pofSerializer = new PofSerializer(pofContext);
             PofStreamsFactory pofStreamsFactory = new PofStreamsFactoryImpl(threadingProxy, streamFactory, pofSerializer);

             var serviceConfiguration = new ClientClusteringConfiguration();
             var serviceClientFactory = new ServiceClientFactoryImpl(proxyGenerator, streamFactory, collectionFactory, threadingProxy, networkingProxy, pofSerializer, pofStreamsFactory);
             var localEndPoint = tcpEndPointFactory.CreateLoopbackEndPoint(serviceConfiguration.Port);
             var reconnectAttempts = 10;
             var reconnectDelay = 1000;
             var serviceClient = TryConnectToEndpoint(reconnectAttempts, reconnectDelay, serviceClientFactory, serviceConfiguration);
             if (serviceClient == null) {
            Console.Error.WriteLine("Failed to connect to endpoint.");
            return 1;
             } else {
            var dispatcher = new DispatcherCommand("registered commands");
            dispatcher.RegisterCommand(new ShutdownCommand(serviceClient));
            //            dispatcher.RegisterCommand(new ModCommand(serviceClient));
            dispatcher.RegisterCommand(new ExitCommand());
            dispatcher.RegisterCommand(new ServiceCommand(serviceClient));

            var repl = new DargonREPL(dispatcher);
            repl.Run();
            return 0;
             }
        }
Beispiel #23
0
		/// <exception cref="NSch.JSchException"></exception>
		public virtual void Connect(SocketFactory socket_factory, string host, int port, 
			int timeout)
		{
			try
			{
				if (socket_factory == null)
				{
					socket = Util.CreateSocket(proxy_host, proxy_port, timeout);
					//socket=new Socket(proxy_host, proxy_port);    
					@in = socket.GetInputStream();
					@out = socket.GetOutputStream();
				}
				else
				{
					socket = socket_factory.CreateSocket(proxy_host, proxy_port);
					@in = socket_factory.GetInputStream(socket);
					@out = socket_factory.GetOutputStream(socket);
				}
				if (timeout > 0)
				{
					socket.ReceiveTimeout = timeout;
				}
				socket.NoDelay = true;
				byte[] buf = new byte[1024];
				int index = 0;
				index = 0;
				buf[index++] = 4;
				buf[index++] = 1;
				buf[index++] = unchecked((byte)((int)(((uint)port) >> 8)));
				buf[index++] = unchecked((byte)(port & unchecked((int)(0xff))));
				try
				{
					IPAddress addr = Sharpen.Extensions.GetAddressByName(host);
					byte[] byteAddress = addr.GetAddressBytes();
					for (int i = 0; i < byteAddress.Length; i++)
					{
						buf[index++] = byteAddress[i];
					}
				}
				catch (UnknownHostException uhe)
				{
					throw new JSchException("ProxySOCKS4: " + uhe.ToString(), uhe);
				}
				if (user != null)
				{
					System.Array.Copy(Util.Str2byte(user), 0, buf, index, user.Length);
					index += user.Length;
				}
				buf[index++] = 0;
				@out.Write(buf, 0, index);
				int len = 8;
				int s = 0;
				while (s < len)
				{
					int i = @in.Read(buf, s, len - s);
					if (i <= 0)
					{
						throw new JSchException("ProxySOCKS4: stream is closed");
					}
					s += i;
				}
				if (buf[0] != 0)
				{
					throw new JSchException("ProxySOCKS4: server returns VN " + buf[0]);
				}
				if (buf[1] != 90)
				{
					try
					{
						socket.Close();
					}
					catch (Exception)
					{
					}
					string message = "ProxySOCKS4: server returns CD " + buf[1];
					throw new JSchException(message);
				}
			}
			catch (RuntimeException e)
			{
				throw;
			}
			catch (Exception e)
			{
				try
				{
					if (socket != null)
					{
						socket.Close();
					}
				}
				catch (Exception)
				{
				}
				throw new JSchException("ProxySOCKS4: " + e.ToString());
			}
		}
Beispiel #24
0
		/// <exception cref="NSch.JSchException"></exception>
		public virtual void Connect(SocketFactory socket_factory, string host, int port, 
			int timeout)
		{
			try
			{
				if (socket_factory == null)
				{
					socket = Util.CreateSocket(proxy_host, proxy_port, timeout);
					@in = socket.GetInputStream();
					@out = socket.GetOutputStream();
				}
				else
				{
					socket = socket_factory.CreateSocket(proxy_host, proxy_port);
					@in = socket_factory.GetInputStream(socket);
					@out = socket_factory.GetOutputStream(socket);
				}
				if (timeout > 0)
				{
					socket.ReceiveTimeout = timeout;
				}
				socket.NoDelay = true;
				@out.Write(Util.Str2byte("CONNECT " + host + ":" + port + " HTTP/1.0\r\n"));
				if (user != null && passwd != null)
				{
					byte[] code = Util.Str2byte(user + ":" + passwd);
					code = Util.ToBase64(code, 0, code.Length);
					@out.Write(Util.Str2byte("Proxy-Authorization: Basic "));
					@out.Write(code);
					@out.Write(Util.Str2byte("\r\n"));
				}
				@out.Write(Util.Str2byte("\r\n"));
				@out.Flush();
				int foo = 0;
				StringBuilder sb = new StringBuilder();
				while (foo >= 0)
				{
					foo = @in.Read();
					if (foo != 13)
					{
						sb.Append((char)foo);
						continue;
					}
					foo = @in.Read();
					if (foo != 10)
					{
						continue;
					}
					break;
				}
				if (foo < 0)
				{
					throw new IOException();
				}
				string response = sb.ToString();
				string reason = "Unknow reason";
				int code_1 = -1;
				try
				{
					foo = response.IndexOf(' ');
					int bar = response.IndexOf(' ', foo + 1);
					code_1 = System.Convert.ToInt32(Sharpen.Runtime.Substring(response, foo + 1, bar)
						);
					reason = Sharpen.Runtime.Substring(response, bar + 1);
				}
				catch (Exception)
				{
				}
				if (code_1 != 200)
				{
					throw new IOException("proxy error: " + reason);
				}
				int count = 0;
				while (true)
				{
					count = 0;
					while (foo >= 0)
					{
						foo = @in.Read();
						if (foo != 13)
						{
							count++;
							continue;
						}
						foo = @in.Read();
						if (foo != 10)
						{
							continue;
						}
						break;
					}
					if (foo < 0)
					{
						throw new IOException();
					}
					if (count == 0)
					{
						break;
					}
				}
			}
			catch (RuntimeException e)
			{
				throw;
			}
			catch (Exception e)
			{
				try
				{
					if (socket != null)
					{
						socket.Close();
					}
				}
				catch (Exception)
				{
				}
				string message = "ProxyHTTP: " + e.ToString();
				if (e is Exception)
				{
					throw new JSchException(message, (Exception)e);
				}
				throw new JSchException(message);
			}
		}
Beispiel #25
0
        public void connect(SocketFactory socket_factory, string host, int port, int timeout)
        {
            try
            {
                if (socket_factory == null)
                {
                    socket = Util.createSocket(proxy_host, proxy_port, timeout);
                    //socket=new Socket(proxy_host, proxy_port);
                    In = socket.GetStream();
                    Out = socket.GetStream();
                }
                else
                {
                    socket = socket_factory.createSocket(proxy_host, proxy_port);
                    In = socket_factory.GetStream(socket);
                    Out = socket_factory.GetStream(socket);
                }
                if (timeout > 0)
                {
                    socket.setSoTimeout(timeout);
                }
                socket.NoDelay=true;

                byte[] buf = new byte[1024];
                int index = 0;

                /*
                   1) CONNECT

                   The client connects to the SOCKS server and sends a CONNECT request when
                   it wants to establish a connection to an application server. The client
                   includes in the request packet the IP address and the port number of the
                   destination host, and userid, in the following format.

                               +----+----+----+----+----+----+----+----+----+----+....+----+
                               | VN | CD | DSTPORT |      DSTIP        | USERID       |NULL|
                               +----+----+----+----+----+----+----+----+----+----+....+----+
                   # of bytes:   1    1      2              4           variable       1

                   VN is the SOCKS protocol version number and should be 4. CD is the
                   SOCKS command code and should be 1 for CONNECT request. NULL is a byte
                   of all zero bits.
                */

                index = 0;
                buf[index++] = 4;
                buf[index++] = 1;

                buf[index++] = (byte)(port >> 8);
                buf[index++] = (byte)(port & 0xff);

                try
                {
                    IPAddress addr = Dns.GetHostEntry(host).AddressList[0];
                    byte[] byteAddress = addr.GetAddressBytes();
                    for (int i = 0; i < byteAddress.Length; i++)
                    {
                        buf[index++] = byteAddress[i];
                    }
                }
                catch (SocketException uhe)
                {
                    throw new JSchException("ProxySOCKS4: " + uhe.ToString(), uhe);
                }

                if (user != null)
                {
                    Array.Copy(user.getBytes(), 0, buf, index, user.Length);
                    index += user.Length;
                }
                buf[index++] = 0;
                Out.Write(buf, 0, index);

                /*
                   The SOCKS server checks to see whether such a request should be granted
                   based on any combination of source IP address, destination IP address,
                   destination port number, the userid, and information it may obtain by
                   consulting IDENT, cf. RFC 1413.  If the request is granted, the SOCKS
                   server makes a connection to the specified port of the destination host.
                   A reply packet is sent to the client when this connection is established,
                   or when the request is rejected or the operation fails.

                               +----+----+----+----+----+----+----+----+
                               | VN | CD | DSTPORT |      DSTIP        |
                               +----+----+----+----+----+----+----+----+
                   # of bytes:   1    1      2              4

                   VN is the version of the reply code and should be 0. CD is the result
                   code with one of the following values:

                   90: request granted
                   91: request rejected or failed
                   92: request rejected becasue SOCKS server cannot connect to
                       identd on the client
                   93: request rejected because the client program and identd
                       report different user-ids

                   The remaining fields are ignored.
                */

                int len = 8;
                int s = 0;
                while (s < len)
                {
                    int i = In.Read(buf, s, len - s);
                    if (i <= 0)
                    {
                        throw new JSchException("ProxySOCKS4: stream is closed");
                    }
                    s += i;
                }
                if (buf[0] != 0)
                {
                    throw new JSchException("ProxySOCKS4: server returns VN " + buf[0]);
                }
                if (buf[1] != 90)
                {
                    try { socket.Close(); }
                    catch //(Exception eee)
                    {
                    }
                    string message = "ProxySOCKS4: server returns CD " + buf[1];
                    throw new JSchException(message);
                }
            }
                /*
            catch (RuntimeException e)
            {
                throw e;
            }
                 */
            catch (Exception e)
            {
                try { if (socket != null)socket.Close(); }
                catch //(Exception eee)
                {
                }
                throw new JSchException("ProxySOCKS4: " + e.Message, e);
            }
        }
		public void setPortForwardingR(int rport, String host, int lport, SocketFactory sf) 
		{
			ChannelForwardedTCPIP.addPort(this, rport, host, lport, sf);
			setPortForwarding(rport);
		}
		internal virtual void SetSocketFactory(SocketFactory factory)
		{
			this.factory = factory;
		}
Beispiel #28
0
		internal static void addPort(Session session, int port, String target, int lport, SocketFactory factory)
		{
			lock(pool)
			{
				if(getPort(session, port)!=null)
				{
					throw new JSchException("PortForwardingR: remote port "+port+" is already registered.");
				}
				Object[] foo=new Object[5];
				foo[0]=session; foo[1]=new Integer(port);
				foo[2]=target; foo[3]=new Integer(lport);
				foo[4]=factory;
				pool.addElement(foo);
			}
		}
Beispiel #29
0
		public void connect(SocketFactory socket_factory, String host, int port, int timeout)
		{
			try
			{
				if(socket_factory==null)
				{
					socket=Util.createSocket(proxy_host, proxy_port, timeout);    
					ins= new JStream(socket.getInputStream());
					outs=new JStream(socket.getOutputStream());
				}
				else
				{
					socket=socket_factory.createSocket(proxy_host, proxy_port);
					ins=new JStream(socket_factory.getInputStream(socket));
					outs=new JStream(socket_factory.getOutputStream(socket));
				}
				if(timeout>0)
				{
					socket.setSoTimeout(timeout);
				}
				socket.setTcpNoDelay(true);

				outs.write(new String("CONNECT "+host+":"+port+" HTTP/1.0\r\n").getBytes());

				if(user!=null && passwd!=null)
				{
					byte[] _code=(user+":"+passwd).getBytes();
					_code=Util.toBase64(_code, 0, _code.Length);
					outs.write(new String("Proxy-Authorization: Basic ").getBytes());
					outs.write(_code);
					outs.write(new String("\r\n").getBytes());
				}

				outs.write(new String("\r\n").getBytes());
				outs.flush();

				int foo=0;

				StringBuffer sb=new StringBuffer();
				while(foo>=0)
				{
					foo=ins.read(); if(foo!=13){sb.append((char)foo);  continue;}
					foo=ins.read(); if(foo!=10){continue;}
					break;
				}
				if(foo<0)
				{
					throw new System.IO.IOException(); 
				}

				String response=sb.toString(); 
				String reason="Unknow reason";
				int code=-1;
				try
				{
					foo=response.indexOf(' ');
					int bar=response.indexOf(' ', foo+1);
					code=Integer.parseInt(response.substring(foo+1, bar));
					reason=response.substring(bar+1);
				}
				catch(Exception e)
				{
				}
				if(code!=200)
				{
					throw new System.IO.IOException("proxy error: "+reason);
				}

				/*
				while(foo>=0){
				  foo=in.read(); if(foo!=13) continue;
				  foo=in.read(); if(foo!=10) continue;
				  foo=in.read(); if(foo!=13) continue;      
				  foo=in.read(); if(foo!=10) continue;
				  break;
				}
				*/

				int count=0;
				while(true)
				{
					count=0;
					while(foo>=0)
					{
						foo=ins.read(); if(foo!=13){count++;  continue;}
						foo=ins.read(); if(foo!=10){continue;}
						break;
					}
					if(foo<0)
					{
						throw new System.IO.IOException();
					}
					if(count==0)break;
				}
			}
			catch(RuntimeException e)
			{
				throw e;
			}
			catch(Exception e)
			{
				try{ if(socket!=null)socket.close(); }
				catch(Exception eee)
				{
				}
				String message="ProxyHTTP: "+e.toString();
				throw e;
			}
		}
        internal override void getData(Buffer buf)
        {
            setRecipient(buf.getInt());
            setRemoteWindowSize(buf.getInt());
            setRemotePacketSize(buf.getInt());
            byte[] addr = buf.getString();
            int port = buf.getInt();
            byte[] orgaddr = buf.getString();
            int orgport = buf.getInt();

            /*
            Console.Error.WriteLine("addr: "+Encoding.UTF8.GetString(addr));
            Console.Error.WriteLine("port: "+port);
            Console.Error.WriteLine("orgaddr: "+Encoding.UTF8.GetString(orgaddr));
            Console.Error.WriteLine("orgport: "+orgport);
            */

            Session _session = null;
            try
            {
                _session = getSession();
            }
            catch (JSchException)
            {
                // session has been already down.
            }

            lock (pool)
            {
                for (int i = 0; i < pool.Count; i++)
                {
                    object[] foo = (object[])(pool[i]);
                    if (foo[0] != _session) continue;
                    if (((int)foo[1]) != port) continue;
                    this.rport = port;
                    this.target = (string)foo[2];
                    if (foo[3] == null || (foo[3] is object[])) { this.lport = -1; }
                    else { this.lport = ((int)foo[3]); }
                    if (foo.Length >= 6)
                    {
                        this.factory = ((SocketFactory)foo[5]);
                    }
                    break;
                }
                if (target == null)
                {
                    //Console.Error.WriteLine("??");
                }
            }
        }
 internal static void addPort(Session session, string _address_to_bind, int port, string target, int lport, SocketFactory factory)
 {
     string address_to_bind = normalize(_address_to_bind);
     lock (pool)
     {
         if (getPort(session, port) != null)
         {
             throw new JSchException("PortForwardingR: remote port " + port + " is already registered.");
         }
         object[] foo = new object[6];
         foo[0] = session; foo[1] = port;
         foo[2] = target; foo[3] = lport;
         foo[4] = address_to_bind;
         foo[5] = factory;
         pool.Add(foo);
     }
 }
Beispiel #32
0
        public void connect(SocketFactory socket_factory, string host, int port, int timeout)
        {
            try
            {
                if (socket_factory == null)
                {
                    socket = Util.createSocket(proxy_host, proxy_port, timeout);
                    In = socket.GetStream();
                    Out = socket.GetStream();
                }
                else
                {
                    socket = socket_factory.createSocket(proxy_host, proxy_port);
                    In = socket_factory.GetStream(socket);
                    Out = socket_factory.GetStream(socket);
                }
                if (timeout > 0)
                {
                    socket.setSoTimeout(timeout);
                }
                socket.NoDelay = true;

                Out.Write(("CONNECT " + host + ":" + port + " HTTP/1.0\r\n").getBytes());

                if (user != null && passwd != null)
                {
                    byte[] code = (user + ":" + passwd).getBytes();
                    code = Util.toBase64(code, 0, code.Length);
                    Out.Write("Proxy-Authorization: Basic ".getBytes());
                    Out.Write(code);
                    Out.Write("\r\n".getBytes());
                }

                Out.Write("\r\n".getBytes());
                Out.Flush();

                int foo = 0;

                StringBuilder sb = new StringBuilder();
                while (foo >= 0)
                {
                    foo = In.Read(); if (foo != 13) { sb.Append((char)foo); continue; }
                    foo = In.Read(); if (foo != 10) { continue; }
                    break;
                }
                if (foo < 0)
                {
                    throw new IOException();
                }

                string response = sb.ToString();
                string reason = "Unknow reason";
                int _code = -1;
                try
                {
                    foo = response.IndexOf(' ');
                    int bar = response.IndexOf(' ', foo + 1);
                    _code = int.Parse(response.Substring(foo + 1, bar - (foo+1)));
                    reason = response.Substring(bar + 1);
                }
                catch //(Exception e)
                {
                }
                if (_code != 200)
                {
                    throw new IOException("proxy error: " + reason);
                }

                /*
                while(foo>=0){
                  foo=In.Read(); if(foo!=13) continue;
                  foo=In.Read(); if(foo!=10) continue;
                  foo=In.Read(); if(foo!=13) continue;
                  foo=In.Read(); if(foo!=10) continue;
                  break;
                }
                */

                int count = 0;
                while (true)
                {
                    count = 0;
                    while (foo >= 0)
                    {
                        foo = In.Read(); if (foo != 13) { count++; continue; }
                        foo = In.Read(); if (foo != 10) { continue; }
                        break;
                    }
                    if (foo < 0)
                    {
                        throw new IOException();
                    }
                    if (count == 0) break;
                }
            }
            catch (Exception e)
            {
                try { if (socket != null)socket.Close(); }
                catch //(Exception eee)
                {
                }
                string message = "ProxyHTTP: " + e.ToString();
                throw new JSchException(message,e);
            }
        }
Beispiel #33
0
 public void setSocketFactory(SocketFactory sfactory)
 {
     socket_factory = sfactory;
 }
Beispiel #34
0
        public void connect(SocketFactory socket_factory, string host, int port, int timeout)
        {
            try
            {
                if (socket_factory == null)
                {
                    socket = Util.createSocket(proxy_host, proxy_port, timeout);
                    //socket=new Socket(proxy_host, proxy_port);
                    In = socket.GetStream();
                    Out = socket.GetStream();
                }
                else
                {
                    socket = socket_factory.createSocket(proxy_host, proxy_port);
                    In = socket_factory.GetStream(socket);
                    Out = socket_factory.GetStream(socket);
                }
                if (timeout > 0)
                {
                    socket.setSoTimeout(timeout);
                }
                socket.NoDelay=true;

                byte[] buf = new byte[1024];
                int index = 0;

                /*
                                   +----+----------+----------+
                                   |VER | NMETHODS | METHODS  |
                                   +----+----------+----------+
                                   | 1  |    1     | 1 to 255 |
                                   +----+----------+----------+

                   The VER field is set to X'05' for this version of the protocol.  The
                   NMETHODS field contains the number of method identifier octets that
                   appear in the METHODS field.

                   The values currently defined for METHOD are:

                          o  X'00' NO AUTHENTICATION REQUIRED
                          o  X'01' GSSAPI
                          o  X'02' USERNAME/PASSWORD
                          o  X'03' to X'7F' IANA ASSIGNED
                          o  X'80' to X'FE' RESERVED FOR PRIVATE METHODS
                          o  X'FF' NO ACCEPTABLE METHODS
                */

                buf[index++] = 5;

                buf[index++] = 2;
                buf[index++] = 0;           // NO AUTHENTICATION REQUIRED
                buf[index++] = 2;           // USERNAME/PASSWORD

                Out.Write(buf, 0, index);

                /*
                    The server selects from one of the methods given in METHODS, and
                    sends a METHOD selection message:

                                         +----+--------+
                                         |VER | METHOD |
                                         +----+--------+
                                         | 1  |   1    |
                                         +----+--------+
                */
                //In.Read(buf, 0, 2);
                fill(In, buf, 2);

                bool check = false;
                switch ((buf[1]) & 0xff)
                {
                    case 0:                // NO AUTHENTICATION REQUIRED
                        check = true;
                        break;
                    case 2:                // USERNAME/PASSWORD
                        if (user == null || passwd == null) break;

                        /*
                           Once the SOCKS V5 server has started, and the client has selected the
                           Username/Password Authentication protocol, the Username/Password
                           subnegotiation begins.  This begins with the client producing a
                           Username/Password request:

                                   +----+------+----------+------+----------+
                                   |VER | ULEN |  UNAME   | PLEN |  PASSWD  |
                                   +----+------+----------+------+----------+
                                   | 1  |  1   | 1 to 255 |  1   | 1 to 255 |
                                   +----+------+----------+------+----------+

                           The VER field contains the current version of the subnegotiation,
                           which is X'01'. The ULEN field contains the length of the UNAME field
                           that follows. The UNAME field contains the username as known to the
                           source operating system. The PLEN field contains the length of the
                           PASSWD field that follows. The PASSWD field contains the password
                           association with the given UNAME.
                        */
                        index = 0;
                        buf[index++] = 1;
                        buf[index++] = (byte)(user.Length);
                        Array.Copy(user.getBytes(), 0, buf, index, user.Length);
                        index += user.Length;
                        buf[index++] = (byte)(passwd.Length);
                        Array.Copy(passwd.getBytes(), 0, buf, index, passwd.Length);
                        index += passwd.Length;

                        Out.Write(buf, 0, index);

                        /*
                           The server verifies the supplied UNAME and PASSWD, and sends the
                           following response:

                                                +----+--------+
                                                |VER | STATUS |
                                                +----+--------+
                                                | 1  |   1    |
                                                +----+--------+

                           A STATUS field of X'00' indicates success. If the server returns a
                           `failure' (STATUS value other than X'00') status, it MUST close the
                           connection.
                        */
                        //In.Read(buf, 0, 2);
                        fill(In, buf, 2);
                        if (buf[1] == 0)
                            check = true;
                        break;
                    default:
                        break;
                }

                if (!check)
                {
                    try { socket.Close(); }
                    catch //(Exception eee)
                    {
                    }
                    throw new JSchException("fail in SOCKS5 proxy");
                }

                /*
                      The SOCKS request is formed as follows:

                        +----+-----+-------+------+----------+----------+
                        |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
                        +----+-----+-------+------+----------+----------+
                        | 1  |  1  | X'00' |  1   | Variable |    2     |
                        +----+-----+-------+------+----------+----------+

                      Where:

                      o  VER    protocol version: X'05'
                      o  CMD
                         o  CONNECT X'01'
                         o  BIND X'02'
                         o  UDP ASSOCIATE X'03'
                      o  RSV    RESERVED
                         o  ATYP   address type of following address
                         o  IP V4 address: X'01'
                         o  DOMAINNAME: X'03'
                         o  IP V6 address: X'04'
                      o  DST.ADDR       desired destination address
                      o  DST.PORT desired destination port in network octet
                         order
                */

                index = 0;
                buf[index++] = 5;
                buf[index++] = 1;       // CONNECT
                buf[index++] = 0;

                byte[] hostb = host.getBytes();
                int len = hostb.Length;
                buf[index++] = 3;      // DOMAINNAME
                buf[index++] = (byte)(len);
                Array.Copy(hostb, 0, buf, index, len);
                index += len;
                buf[index++] = (byte)(port >> 8);
                buf[index++] = (byte)(port & 0xff);

                Out.Write(buf, 0, index);

                /*
                   The SOCKS request information is sent by the client as soon as it has
                   established a connection to the SOCKS server, and completed the
                   authentication negotiations.  The server evaluates the request, and
                   returns a reply formed as follows:

                        +----+-----+-------+------+----------+----------+
                        |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
                        +----+-----+-------+------+----------+----------+
                        | 1  |  1  | X'00' |  1   | Variable |    2     |
                        +----+-----+-------+------+----------+----------+

                   Where:

                   o  VER    protocol version: X'05'
                   o  REP    Reply field:
                      o  X'00' succeeded
                      o  X'01' general SOCKS server failure
                      o  X'02' connection not allowed by ruleset
                      o  X'03' Network unreachable
                      o  X'04' Host unreachable
                      o  X'05' Connection refused
                      o  X'06' TTL expired
                      o  X'07' Command not supported
                      o  X'08' Address type not supported
                      o  X'09' to X'FF' unassigned
                    o  RSV    RESERVED
                    o  ATYP   address type of following address
                      o  IP V4 address: X'01'
                      o  DOMAINNAME: X'03'
                      o  IP V6 address: X'04'
                    o  BND.ADDR       server bound address
                    o  BND.PORT       server bound port in network octet order
                */

                //In.Read(buf, 0, 4);
                fill(In, buf, 4);

                if (buf[1] != 0)
                {
                    try { socket.Close(); }
                    catch //(Exception eee)
                    {
                    }
                    throw new JSchException("ProxySOCKS5: server returns " + buf[1]);
                }

                switch (buf[3] & 0xff)
                {
                    case 1:
                        //In.Read(buf, 0, 6);
                        fill(In, buf, 6);
                        break;
                    case 3:
                        //In.Read(buf, 0, 1);
                        fill(In, buf, 1);
                        //In.Read(buf, 0, buf[0]+2);
                        fill(In, buf, (buf[0] & 0xff) + 2);
                        break;
                    case 4:
                        //In.Read(buf, 0, 18);
                        fill(In, buf, 18);
                        break;
                    default:
                        break;
                }
            }
                /*
            catch (RuntimeException e)
            {
                throw e;
            }
                 */
            catch (Exception e)
            {
                try { if (socket != null)socket.Close(); }
                catch //(Exception eee)
                {
                }
                string message = "ProxySOCKS5: " + e.ToString();
                throw new JSchException(message,e);
            }
        }
Beispiel #35
0
		public void connect(SocketFactory socket_factory, String host, int port, int timeout)
		{
			try
			{
				if(socket_factory==null)
				{
					socket=Util.createSocket(proxy_host, proxy_port, timeout);    
					ins= new JStream(new NetworkStream(socket));
					outs=new JStream(new NetworkStream(socket));
				}
				else
				{
					socket=socket_factory.createSocket(proxy_host, proxy_port);
					ins=new JStream(socket_factory.getInputStream(socket));
					outs=new JStream(socket_factory.getOutputStream(socket));
				}
				if(timeout>0)
				{
					socket.ReceiveTimeout = timeout;
					socket.SendTimeout = timeout;
				}
				socket.NoDelay = true;

				outs.write("CONNECT "+host+":"+port+" HTTP/1.0\r\n");

				if(user!=null && passwd!=null)
				{
					byte[] _code=Encoding.UTF8.GetBytes(user + ":" + passwd);
					_code=Util.toBase64(_code, 0, _code.Length);
					outs.write("Proxy-Authorization: Basic ");
					outs.write(_code);
					outs.write("\r\n");
				}

				outs.write("\r\n");
				outs.flush();

				int foo=0;

				string sb = "";
				while(foo>=0)
				{
					foo=ins.read(); if(foo!=13){sb += ((char)foo);  continue;}
					foo=ins.read(); if(foo!=10){continue;}
					break;
				}
				if(foo<0)
				{
					throw new System.IO.IOException(); 
				}

				String response = sb; 
				String reason="Unknow reason";
				int code=-1;
				try
				{
					foo=response.IndexOf(' ');
					int bar=response.IndexOf(' ', foo+1);
					code = System.Convert.ToInt32(response.Substring(foo + 1, bar));
					reason=response.Substring(bar+1);
				}
				catch(Exception)
				{
				}
				if(code!=200)
				{
					throw new System.IO.IOException("proxy error: "+reason);
				}

				/*
				while(foo>=0){
				  foo=in.read(); if(foo!=13) continue;
				  foo=in.read(); if(foo!=10) continue;
				  foo=in.read(); if(foo!=13) continue;      
				  foo=in.read(); if(foo!=10) continue;
				  break;
				}
				*/

				int count=0;
				while(true)
				{
					count=0;
					while(foo>=0)
					{
						foo=ins.read(); if(foo!=13){count++;  continue;}
						foo=ins.read(); if(foo!=10){continue;}
						break;
					}
					if(foo<0)
					{
						throw new System.IO.IOException();
					}
					if(count==0)break;
				}
			}
			catch(Exception e)
			{
				try{ if(socket!=null)socket.Close(); }
				catch(Exception)
				{
				}
				String message="ProxyHTTP: "+e.ToString();
				throw e;
			}
		}
Beispiel #36
0
        public void Connect(SocketFactory socketFactory, String host, int port, int timeout)
        {
            try
            {
                if (socketFactory == null)
                {
                    Socket = Util.createSocket(Host, Port, timeout);
                    inputStream = new JStream(Socket.getInputStream());
                    outputStream = new JStream(Socket.getOutputStream());
                }
                else
                {
                    Socket = socketFactory.createSocket(Host, Port);
                    inputStream = new JStream(socketFactory.getInputStream(Socket));
                    outputStream = new JStream(socketFactory.getOutputStream(Socket));
                }
                if (timeout > 0)
                {
                    Socket.setSoTimeout(timeout);
                }
                Socket.setTcpNoDelay(true);

                outputStream.Write(("CONNECT " + host + ":" + port + " HTTP/1.0\r\n").GetBytes());

                if (User != null && Password != null)
                {
                    byte[] _code = (User + ":" + Password).GetBytes();
                    _code = Util.toBase64(_code, 0, _code.Length);
                    outputStream.Write("Proxy-Authorization: Basic ".GetBytes());
                    outputStream.Write(_code);
                    outputStream.Write("\r\n".GetBytes());
                }

                outputStream.Write("\r\n".GetBytes());
                outputStream.flush();

                int foo = 0;

                StringBuilder sb = new StringBuilder();
                while (foo >= 0)
                {
                    foo = inputStream.read();
                    if (foo != 13)
                    {
                        sb.Append((char)foo);
                        continue;
                    }
                    foo = inputStream.read();
                    if (foo != 10)
                    {
                        continue;
                    }
                    break;
                }
                if (foo < 0)
                {
                    throw new IOException();
                }

                String response = sb.ToString();
                String reason = "Unknow reason";
                int code = -1;
                try
                {
                    foo = response.IndexOf(' ');
                    int bar = response.IndexOf(' ', foo + 1);
                    code = Int32.Parse(response.Substring(foo + 1, bar));
                    reason = response.Substring(bar + 1);
                }
                catch (Exception) { }

                if (code != 200)
                {
                    throw new IOException("proxy error: " + reason);
                }

                int count = 0;
                while (true)
                {
                    count = 0;
                    while (foo >= 0)
                    {
                        foo = inputStream.read();
                        if (foo != 13)
                        {
                            count++;
                            continue;
                        }
                        foo = inputStream.read();
                        if (foo != 10)
                        {
                            continue;
                        }
                        break;
                    }
                    if (foo < 0)
                    {
                        throw new IOException();
                    }
                    if (count == 0) break;
                }
            }
            catch (Exception e)
            {
                try
                {
                    if (Socket != null) Socket.Close();
                }
                catch (Exception) { }

                String message = "ProxyHTTP: " + e;
                throw e;
            }
        }
Beispiel #37
0
		internal override void getData(Buffer buf)
		{
			setRecipient(buf.getInt());
			setRemoteWindowSize(buf.getInt());
			setRemotePacketSize(buf.getInt());
			byte[] addr=buf.getString();
			int port=buf.getInt();
			byte[] orgaddr=buf.getString();
			int orgport=buf.getInt();

			/*
			System.out.println("addr: "+new String(addr));
			System.out.println("port: "+port);
			System.out.println("orgaddr: "+new String(orgaddr));
			System.out.println("orgport: "+orgport);
			*/

			lock(pool)
			{
				for(int i=0; i<pool.size(); i++)
				{
					Object[] foo=(Object[])(pool.elementAt(i));
					if(foo[0]!=session) continue;
					if(((Integer)foo[1]).intValue()!=port) continue;
					this.rport=port;
					this.target=(String)foo[2];
					if(foo[3]==null || (foo[3] is Object[])){ this.lport=-1; }
					else{ this.lport=((Integer)foo[3]).intValue(); }
					if(foo.Length>=5)
					{
						this.factory=((SocketFactory)foo[4]);
					}
					break;
				}
				if(target==null)
				{
					Console.WriteLine("??");
				}
			}
		}
Beispiel #38
0
		/// <exception cref="NSch.JSchException"></exception>
		public virtual void SetPortForwardingR(string bind_address, int rport, string host
			, int lport, SocketFactory sf)
		{
			ChannelForwardedTCPIP.AddPort(this, bind_address, rport, host, lport, sf);
			SetPortForwarding(bind_address, rport);
		}
Beispiel #39
0
		void setSocketFactory(SocketFactory factory)
		{
			this.factory=factory;
		}
		internal override void GetData(Buffer buf)
		{
			SetRecipient(buf.GetInt());
			SetRemoteWindowSize(buf.GetUInt());
			SetRemotePacketSize(buf.GetInt());
			byte[] addr = buf.GetString();
			int port = buf.GetInt();
			byte[] orgaddr = buf.GetString();
			int orgport = buf.GetInt();
			Session _session = null;
			try
			{
				_session = GetSession();
			}
			catch (JSchException)
			{
			}
			// session has been already down.
			lock (pool)
			{
				for (int i = 0; i < pool.Count; i++)
				{
					object[] foo = (object[])(pool[i]);
					if (foo[0] != _session)
					{
						continue;
					}
					if (((int)foo[1]) != port)
					{
						continue;
					}
					this.rport = port;
					this.target = (string)foo[2];
					if (foo[3] == null || (foo[3] is object[]))
					{
						this.lport = -1;
					}
					else
					{
						this.lport = ((int)foo[3]);
					}
					if (foo.Length >= 6)
					{
						this.factory = ((SocketFactory)foo[5]);
					}
					break;
				}
				if (target == null)
				{
				}
			}
		}
Beispiel #41
0
		/// <exception cref="NSch.JSchException"></exception>
		public virtual void SetPortForwardingR(int rport, string host, int lport, SocketFactory
			 sf)
		{
			SetPortForwardingR(null, rport, host, lport, sf);
		}
Beispiel #42
0
        internal static void addPort(Session session, int port, string target, int lport, SocketFactory factory)
        {
            lock (m_pool)
            {
                if (getPort(session, port) != null)
                    throw new JSchException("PortForwardingR: remote port " + port + " is already registered.");

                Object[] foo = new Object[5];
                foo[0] = session;
                foo[1] = port;
                foo[2] = target;
                foo[3] = lport;
                foo[4] = factory;
                m_pool.Add(foo);
            }
        }
Beispiel #43
0
		public virtual void SetSocketFactory(SocketFactory sfactory)
		{
			socket_factory = sfactory;
		}
Beispiel #44
0
        internal override void getData(Buffer buf)
        {
            Recipient = buf.getInt();
            RemoteWindowSize = buf.getInt();
            RemotePacketSize = buf.getInt();
            byte[] addr = buf.getString();
            int port = buf.getInt();
            byte[] orgaddr = buf.getString();
            int orgport = buf.getInt();

            lock (m_pool)
            {
                for (int i = 0; i < m_pool.Count; i++)
                {
                    Object[] foo = (Object[])(m_pool[i]);
                    if (foo[0] != m_session)
                        continue;
                    if ((int)foo[1] != port)
                        continue;
                    m_rport = port;
                    m_target = (string)foo[2];
                    if (foo[3] == null || (foo[3] is Object[]))
                        m_lport = -1;
                    else
                        m_lport = (int)foo[3];

                    if (foo.Length >= 5)
                        m_factory = ((SocketFactory)foo[4]);
                    break;
                }
                if (m_target == null)
                    throw new Exception("Target is null");
            }
        }
		public void setSocketFactory(SocketFactory foo){ socket_factory=foo;}
Beispiel #46
0
		/// <exception cref="NSch.JSchException"></exception>
		public virtual void Connect(SocketFactory socket_factory, string host, int port, 
			int timeout)
		{
			try
			{
				if (socket_factory == null)
				{
					socket = Util.CreateSocket(proxy_host, proxy_port, timeout);
					//socket=new Socket(proxy_host, proxy_port);    
					@in = socket.GetInputStream();
					@out = socket.GetOutputStream();
				}
				else
				{
					socket = socket_factory.CreateSocket(proxy_host, proxy_port);
					@in = socket_factory.GetInputStream(socket);
					@out = socket_factory.GetOutputStream(socket);
				}
				if (timeout > 0)
				{
					socket.ReceiveTimeout = timeout;
				}
				socket.NoDelay = true;
				byte[] buf = new byte[1024];
				int index = 0;
				buf[index++] = 5;
				buf[index++] = 2;
				buf[index++] = 0;
				// NO AUTHENTICATION REQUIRED
				buf[index++] = 2;
				// USERNAME/PASSWORD
				@out.Write(buf, 0, index);
				//in.read(buf, 0, 2);
				Fill(@in, buf, 2);
				bool check = false;
				switch ((buf[1]) & unchecked((int)(0xff)))
				{
					case 0:
					{
						// NO AUTHENTICATION REQUIRED
						check = true;
						break;
					}

					case 2:
					{
						// USERNAME/PASSWORD
						if (user == null || passwd == null)
						{
							break;
						}
						index = 0;
						buf[index++] = 1;
						buf[index++] = unchecked((byte)(user.Length));
						System.Array.Copy(Util.Str2byte(user), 0, buf, index, user.Length);
						index += user.Length;
						buf[index++] = unchecked((byte)(passwd.Length));
						System.Array.Copy(Util.Str2byte(passwd), 0, buf, index, passwd.Length);
						index += passwd.Length;
						@out.Write(buf, 0, index);
						//in.read(buf, 0, 2);
						Fill(@in, buf, 2);
						if (buf[1] == 0)
						{
							check = true;
						}
						break;
					}

					default:
					{
						break;
					}
				}
				if (!check)
				{
					try
					{
						socket.Close();
					}
					catch (Exception)
					{
					}
					throw new JSchException("fail in SOCKS5 proxy");
				}
				index = 0;
				buf[index++] = 5;
				buf[index++] = 1;
				// CONNECT
				buf[index++] = 0;
				byte[] hostb = Util.Str2byte(host);
				int len = hostb.Length;
				buf[index++] = 3;
				// DOMAINNAME
				buf[index++] = unchecked((byte)(len));
				System.Array.Copy(hostb, 0, buf, index, len);
				index += len;
				buf[index++] = unchecked((byte)((int)(((uint)port) >> 8)));
				buf[index++] = unchecked((byte)(port & unchecked((int)(0xff))));
				@out.Write(buf, 0, index);
				//in.read(buf, 0, 4);
				Fill(@in, buf, 4);
				if (buf[1] != 0)
				{
					try
					{
						socket.Close();
					}
					catch (Exception)
					{
					}
					throw new JSchException("ProxySOCKS5: server returns " + buf[1]);
				}
				switch (buf[3] & unchecked((int)(0xff)))
				{
					case 1:
					{
						//in.read(buf, 0, 6);
						Fill(@in, buf, 6);
						break;
					}

					case 3:
					{
						//in.read(buf, 0, 1);
						Fill(@in, buf, 1);
						//in.read(buf, 0, buf[0]+2);
						Fill(@in, buf, (buf[0] & unchecked((int)(0xff))) + 2);
						break;
					}

					case 4:
					{
						//in.read(buf, 0, 18);
						Fill(@in, buf, 18);
						break;
					}

					default:
					{
						break;
					}
				}
			}
			catch (RuntimeException e)
			{
				throw;
			}
			catch (Exception e)
			{
				try
				{
					if (socket != null)
					{
						socket.Close();
					}
				}
				catch (Exception)
				{
				}
				string message = "ProxySOCKS5: " + e.ToString();
				if (e is Exception)
				{
					throw new JSchException(message, (Exception)e);
				}
				throw new JSchException(message);
			}
		}