Ejemplo n.º 1
0
        // Proxy for FTP
        public IProxyClient GetProxyClient()
        {
            if (IsValidProxy())
            {
                Starksoft.Net.Proxy.ProxyType proxyType;

                switch (ProxyType)
                {
                case ProxyType.HTTP:
                    proxyType = Starksoft.Net.Proxy.ProxyType.Http;
                    break;

                case ProxyType.SOCKS4:
                    proxyType = Starksoft.Net.Proxy.ProxyType.Socks4;
                    break;

                case ProxyType.SOCKS4a:
                    proxyType = Starksoft.Net.Proxy.ProxyType.Socks4a;
                    break;

                case ProxyType.SOCKS5:
                    proxyType = Starksoft.Net.Proxy.ProxyType.Socks5;
                    break;

                default:
                    proxyType = Starksoft.Net.Proxy.ProxyType.None;
                    break;
                }

                ProxyClientFactory proxy = new ProxyClientFactory();
                return(proxy.CreateProxyClient(proxyType, Host, Port, Username, Password));
            }

            return(null);
        }
Ejemplo n.º 2
0
        private static (Collection <FunctionMetadata>, ProxyClientExecutor) LoadProxyMetadata(string proxiesJson, Dictionary <string, ICollection <string> > functionErrors, ILogger logger)
        {
            var proxies = new Collection <FunctionMetadata>();
            ProxyClientExecutor client = null;

            var rawProxyClient = ProxyClientFactory.Create(proxiesJson, logger);

            if (rawProxyClient != null)
            {
                client = new ProxyClientExecutor(rawProxyClient);
            }

            if (client == null)
            {
                return(proxies, null);
            }

            var routes = client.GetProxyData();

            foreach (var route in routes.Routes)
            {
                try
                {
                    // Proxy names should follow the same naming restrictions as in function names. If not, invalid characters will be removed.
                    var proxyName = NormalizeProxyName(route.Name);

                    var proxyMetadata = new FunctionMetadata();

                    var json = new JObject
                    {
                        { "authLevel", "anonymous" },
                        { "name", "req" },
                        { "type", "httptrigger" },
                        { "direction", "in" },
                        { "Route", route.UrlTemplate.TrimStart('/') },
                        { "Methods", new JArray(route.Methods.Select(m => m.Method.ToString()).ToArray()) }
                    };

                    BindingMetadata bindingMetadata = BindingMetadata.Create(json);

                    proxyMetadata.Bindings.Add(bindingMetadata);

                    proxyMetadata.Name    = proxyName;
                    proxyMetadata.IsProxy = true;

                    proxies.Add(proxyMetadata);
                }
                catch (Exception ex)
                {
                    // log any unhandled exceptions and continue
                    Utility.AddFunctionError(functionErrors, route.Name, Utility.FlattenException(ex, includeSource: false), isFunctionShortName: true);
                }
            }

            return(proxies, client);
        }
Ejemplo n.º 3
0
            /// <summary>
            /// Creates the proxy from the values within this object.
            /// </summary>
            /// <returns>
            /// The proxy.
            /// </returns>
            public IProxyClient CreateProxy()
            {
                var pcf = new ProxyClientFactory();

                if (string.IsNullOrWhiteSpace(UserName))
                {
                    return(pcf.CreateProxyClient(Type, Host, Port));
                }

                return(pcf.CreateProxyClient(Type, Host, Port, UserName, Password ?? string.Empty));
            }
            internal proxy(string target_host, int target_port, string proxy_host, int proxy_port, ProxyType type)
            {
                Console.WriteLine("Socket allocated.");
                this.proxy_conn = new proxy.conn();
                this.proxy_conn.proxy_config(target_host, target_port, proxy_host, proxy_port, type);
                ProxyClientFactory factory = new ProxyClientFactory();

                this.proxy_conn.Proxy = factory.CreateProxyClient(type, proxy_host, proxy_port);
                this.proxy_conn.Proxy.CreateConnectionAsyncCompleted += new EventHandler <CreateConnectionAsyncCompletedEventArgs>(proxy_connected);

                //this.Proxy.CreateConnectionAsync(obj.target_host, obj.target_port);
            }
Ejemplo n.º 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="targetHost"></param>
        /// <param name="targetPort"></param>
        /// <returns></returns>
        TcpClient ConnectViaHTTPProxy(    )
        {
            // create an instance of the client proxy factory
            ProxyClientFactory factory = new ProxyClientFactory();

            // use the proxy client factory to generically specify the type of proxy to create
            // the proxy factory method CreateProxyClient returns an IProxyClient object
            IProxyClient proxy = factory.CreateProxyClient(ProxyType.Http, ProxyInfo.Host, ProxyInfo.Port, ProxyInfo.UserName, ProxyInfo.Password);

            // create a connection through the proxy to www.starksoft.com over port 80
            return(proxy.CreateConnection(Host, Port));
        }
Ejemplo n.º 6
0
        public TorProxy(string target_host, int target_port, string proxy_host, int proxy_port, ProxyType type)
        {
            if (InputProxyMessage != null)
            {
                InputProxyMessage.Invoke("Socket allocated.");
            }
            proxy_connection = new connection();
            proxy_connection.proxy_config(target_host, target_port, proxy_host, proxy_port, type);
            ProxyClientFactory factory = new ProxyClientFactory();

            proxy_connection.Proxy = factory.CreateProxyClient(type, proxy_host, proxy_port);
            proxy_connection.Proxy.CreateConnectionAsyncCompleted += new EventHandler <CreateConnectionAsyncCompletedEventArgs>(proxy_connected);
        }
Ejemplo n.º 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="destinationHost">Host destino que requiere proxy</param>
        /// <param name="destinationPort">Puerto destino</param>
        /// <returns></returns>
        TcpClient ConnectViaHTTPProxy(string destinationHost, int destinationPort)
        {
            // create an instance of the client proxy factory
            ProxyClientFactory factory = new ProxyClientFactory();

            // use the proxy client factory to generically specify the type of proxy to create
            // the proxy factory method CreateProxyClient returns an IProxyClient object
            //IProxyClient proxy = factory.CreateProxyClient(ProxyType.Http, MailProcessor.ProxyInfo.Host, MailProcessor.ProxyInfo.Port, MailProcessor.ProxyInfo.UserName, MailProcessor.ProxyInfo.Password);
            IProxyClient proxy = factory.CreateProxyClient(ProxyType.Http, this._Proxy.Host, this._Proxy.Port, this._Proxy.UserName, this._Proxy.Password);

            // create a connection through the proxy to www.starksoft.com over port 80
            return(proxy.CreateConnection(destinationHost, destinationPort));
        }
Ejemplo n.º 8
0
        public void Connect(string command, params object[] arguments)
        {
            Uri uri = new Uri(command);

            _connectArguments = arguments;
            int port = uri.Port <= 0 ? 1935 : uri.Port;

            //_connectionParameters["tcUrl"] = "rtmp://" + uri.Host + (uri.Port > 0 ? uri.Port.ToString() + ':' : string.Empty) + uri.PathAndQuery;
            _connectionParameters["tcUrl"] = command;
            string app = uri.LocalPath.TrimStart(new char[] { '/' });

            _connectionParameters["app"] = app;

            Socket socket = null;

            // Support for proxies in non-Silverlight apps.
#if !SILVERLIGHT
            if (Proxy != null)
            {
                ProxyClientFactory factory     = new ProxyClientFactory();
                string[]           proxyParts  = _proxy.Server.Split(':');
                IProxyClient       proxyClient = factory.CreateProxyClient(_proxy.TypeToInternalType(), proxyParts[0], int.Parse(proxyParts[1]));

                Uri       endpoint  = new Uri(command);
                TcpClient tcpClient = proxyClient.CreateConnection(endpoint.Host, endpoint.Port);
                socket = tcpClient.Client;
            }
            else
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(uri.Host, port);
            }
#else
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
#endif

#if !SILVERLIGHT
            _connection = new RtmpClientConnection(this, socket, _secure, uri.Host);

            _connection.Context.ObjectEncoding = _netConnection.ObjectEncoding;
            _connection.BeginHandshake();
#else
            DnsEndPoint          endPoint = new DnsEndPoint(uri.Host, port);
            SocketAsyncEventArgs args     = new SocketAsyncEventArgs();
            args.UserToken      = socket;
            args.RemoteEndPoint = endPoint;
            args.Completed     += new EventHandler <SocketAsyncEventArgs>(OnSocketConnectCompleted);
            socket.ConnectAsync(args);
#endif
        }
Ejemplo n.º 9
0
        TcpClient CreateConnectedTcpClient(ServiceEndPoint endPoint)
        {
            TcpClient client;

            if (endPoint.Proxy == null)
            {
                client = CreateTcpClient();
                client.ConnectWithTimeout(endPoint.BaseUri, HalibutLimits.TcpClientConnectTimeout);
            }
            else
            {
                log.Write(EventType.Diagnostic, "Creating a proxy client");
                client = new ProxyClientFactory()
                         .CreateProxyClient(log, endPoint.Proxy)
                         .WithTcpClientFactory(CreateTcpClient)
                         .CreateConnection(endPoint.BaseUri.Host, endPoint.BaseUri.Port, HalibutLimits.TcpClientConnectTimeout);
            }
            return(client);
        }
Ejemplo n.º 10
0
        internal static TcpClient CreateConnectedTcpClient(ServiceEndPoint endPoint, ILog log, CancellationToken cancellationToken)
        {
            TcpClient client;

            if (endPoint.Proxy == null)
            {
                client = CreateTcpClient();
                client.ConnectWithTimeout(endPoint.BaseUri, endPoint.TcpClientConnectTimeout, cancellationToken);
            }
            else
            {
                log.Write(EventType.Diagnostic, "Creating a proxy client");

                client = new ProxyClientFactory()
                         .CreateProxyClient(log, endPoint.Proxy)
                         .WithTcpClientFactory(CreateTcpClient)
                         .CreateConnection(endPoint.BaseUri.Host, endPoint.BaseUri.Port, endPoint.TcpClientConnectTimeout, cancellationToken);
            }
            return(client);
        }
Ejemplo n.º 11
0
            private TcpClient getProxyClient()
            {
                if (ProxyPort == 0)
                {
                    string[] proxyip = bots.getSocks().Split(':');
                    if (proxyip.Length == 2)
                    {
                        ProxyIP   = proxyip[0];
                        ProxyPort = int.Parse(proxyip[1]);
                    }
                    else
                    {
                        ProxyIP   = proxyip[0];
                        ProxyPort = 8080;
                    }
                }
                ProxyClientFactory factory = new ProxyClientFactory();
                IProxyClient       proxy   = factory.CreateProxyClient(ProxyType.Http, ProxyIP, ProxyPort);

                return(proxy.CreateConnection(Host, Port));
            }
Ejemplo n.º 12
0
        static IProxyClient MakeProxy(Uri proxyUri)
        {
            // Uses https://github.com/grinay/ProxyLib
            ProxyClientFactory factory = new ProxyClientFactory();

            if (proxyUri.UserInfo == string.Empty)
            {
                return(factory.CreateProxyClient(ProxyType.Http, proxyUri.Host, proxyUri.Port));
            }
            else
            {
                if (proxyUri.UserInfo.Contains(':'))
                {
                    var userPass = proxyUri.UserInfo.Split(':');
                    return(factory.CreateProxyClient(ProxyType.Http, proxyUri.Host, proxyUri.Port, userPass[0], userPass[1]));
                }
                else
                {
                    throw new Exception($"Invalid user info: {proxyUri.UserInfo}");
                }
            }
        }
Ejemplo n.º 13
0
        public TorInstance(string _torloc, int _controlPort, int _socksPort, bool useExistingTorPorts = false)
        {
            // Assign member variables
            //            state = TorState.Bootstrapping;
            torloc        = _torloc;
            controlPort   = (ushort)_controlPort;
            socksPort     = (ushort)_socksPort;
            dataDirectory = string.Format("./data/{0}", this.GetHashCode());


            System.Console.WriteLine("TorInstance({0:d}) created. Socks: {1:d}", this.GetHashCode(), socksPort);

            factory = new ProxyClientFactory();
            proxy   = factory.CreateProxyClient(ProxyType.Socks5, "127.0.0.1", socksPort);

            if (!useExistingTorPorts)
            {
                StartTorThread();
            }
            else
            {
                state = TorState.Ready;
            }
        }
        public IProxyClient GetProxyClient(ProxyInfo myProxyInfo)
        {
            if (myProxyInfo != null)
            {
                ProxyType proxyType;

                switch (myProxyInfo.ProxyType)
                {
                case Proxy.HTTP:
                    proxyType = ProxyType.Http;
                    break;

                case Proxy.SOCKS4:
                    proxyType = ProxyType.Socks4;
                    break;

                case Proxy.SOCKS4a:
                    proxyType = ProxyType.Socks4a;
                    break;

                case Proxy.SOCKS5:
                    proxyType = ProxyType.Socks5;
                    break;

                default:
                    proxyType = ProxyType.None;
                    break;
                }

                ProxyClientFactory proxy = new ProxyClientFactory();

                return(proxy.CreateProxyClient(proxyType, myProxyInfo.Host, myProxyInfo.Port, myProxyInfo.UserName, myProxyInfo.Password));
            }

            return(null);
        }
Ejemplo n.º 15
0
        /// <overloads>this method has 2 overloads</overloads>
        /// <summary>
        /// Connects to the specified server and port, when the connection fails
        /// the next server in the list will be used.
        /// </summary>
        /// <param name="addresslist">List of servers to connect to</param>
        /// <param name="port">Portnumber to connect to</param>
        /// <exception cref="CouldNotConnectException">The connection failed</exception>
        /// <exception cref="AlreadyConnectedException">If there is already an active connection</exception>
        public void Connect(string[] addresslist, int port)
        {
            if (_IsConnected)
            {
                throw new AlreadyConnectedException("Already connected to: " + Address + ":" + Port);
            }

            _AutoRetryAttempt++;
#if LOG4NET
            Logger.Connection.Info(String.Format("connecting... (attempt: {0})",
                                                 _AutoRetryAttempt));
#endif

            _AddressList = (string[])addresslist.Clone();
            _Port        = port;

            if (OnConnecting != null)
            {
                OnConnecting(this, EventArgs.Empty);
            }
            try {
                System.Net.IPAddress ip = System.Net.Dns.Resolve(Address).AddressList[0];

                _TcpClient         = new TcpClient();
                _TcpClient.NoDelay = true;
                _TcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                // set timeout, after this the connection will be aborted
                _TcpClient.ReceiveTimeout = _SocketReceiveTimeout * 1000;
                _TcpClient.SendTimeout    = _SocketSendTimeout * 1000;

                if (_ProxyType != ProxyType.None)
                {
                    IProxyClient       proxyClient  = null;
                    ProxyClientFactory proxyFactory = new ProxyClientFactory();
                    // HACK: map our ProxyType to Starksoft's ProxyType
                    Starksoft.Net.Proxy.ProxyType proxyType =
                        (Starksoft.Net.Proxy.ProxyType)Enum.Parse(
                            typeof(ProxyType), _ProxyType.ToString(), true
                            );

                    if (_ProxyUsername == null && _ProxyPassword == null)
                    {
                        proxyClient = proxyFactory.CreateProxyClient(
                            proxyType
                            );
                    }
                    else
                    {
                        proxyClient = proxyFactory.CreateProxyClient(
                            proxyType,
                            _ProxyHost,
                            _ProxyPort,
                            _ProxyUsername,
                            _ProxyPassword
                            );
                    }

                    _TcpClient.Connect(_ProxyHost, _ProxyPort);
                    proxyClient.TcpClient = _TcpClient;
                    proxyClient.CreateConnection(ip.ToString(), port);
                }
                else
                {
                    _TcpClient.Connect(ip, port);
                }

                Stream stream = _TcpClient.GetStream();
                if (_UseSsl)
                {
                    RemoteCertificateValidationCallback certValidation;
                    if (_ValidateServerCertificate)
                    {
                        certValidation = delegate(object sender,
                                                  X509Certificate certificate,
                                                  X509Chain chain,
                                                  SslPolicyErrors sslPolicyErrors) {
                            if (sslPolicyErrors == SslPolicyErrors.None)
                            {
                                return(true);
                            }

#if LOG4NET
                            Logger.Connection.Error(
                                "Connect(): Certificate error: " +
                                sslPolicyErrors
                                );
#endif
                            return(false);
                        };
                    }
                    else
                    {
                        certValidation = delegate { return(true); };
                    }
                    SslStream sslStream = new SslStream(stream, false,
                                                        certValidation);
                    try {
                        if (_SslClientCertificate != null)
                        {
                            var certs = new X509Certificate2Collection();
                            certs.Add(_SslClientCertificate);
                            sslStream.AuthenticateAsClient(Address, certs,
                                                           SslProtocols.Default,
                                                           false);
                        }
                        else
                        {
                            sslStream.AuthenticateAsClient(Address);
                        }
                    } catch (IOException ex) {
#if LOG4NET
                        Logger.Connection.Error(
                            "Connect(): AuthenticateAsClient() failed!"
                            );
#endif
                        throw new CouldNotConnectException("Could not connect to: " + Address + ":" + Port + " " + ex.Message, ex);
                    }
                    stream = sslStream;
                }
                _Reader = new StreamReader(stream, _Encoding);
                _Writer = new StreamWriter(stream, _Encoding);

                if (_Encoding.GetPreamble().Length > 0)
                {
                    // HACK: we have an encoding that has some kind of preamble
                    // like UTF-8 has a BOM, this will confuse the IRCd!
                    // Thus we send a \r\n so the IRCd can safely ignore that
                    // garbage.
                    _Writer.WriteLine();
                    // make sure we flush the BOM+CRLF correctly
                    _Writer.Flush();
                }

                // Connection was succeful, reseting the connect counter
                _AutoRetryAttempt = 0;

                // updating the connection error state, so connecting is possible again
                IsConnectionError = false;
                _IsConnected      = true;

                // lets power up our threads
                _ReadThread.Start();
                _WriteThread.Start();
                _IdleWorkerThread.Start();

#if LOG4NET
                Logger.Connection.Info("connected");
#endif
                if (OnConnected != null)
                {
                    OnConnected(this, EventArgs.Empty);
                }
            } catch (AuthenticationException ex) {
#if LOG4NET
                Logger.Connection.Error("Connect(): Exception", ex);
#endif
                throw new CouldNotConnectException("Could not connect to: " + Address + ":" + Port + " " + ex.Message, ex);
            } catch (Exception e) {
                if (_Reader != null)
                {
                    try {
                        _Reader.Close();
                    } catch (ObjectDisposedException) {
                    }
                }
                if (_Writer != null)
                {
                    try {
                        _Writer.Close();
                    } catch (ObjectDisposedException) {
                    }
                }
                if (_TcpClient != null)
                {
                    _TcpClient.Close();
                }
                _IsConnected      = false;
                IsConnectionError = true;

#if LOG4NET
                Logger.Connection.Info("connection failed: " + e.Message, e);
#endif
                if (e is CouldNotConnectException)
                {
                    // error was fatal, bail out
                    throw;
                }

                if (_AutoRetry &&
                    (_AutoRetryLimit == -1 ||
                     _AutoRetryLimit == 0 ||
                     _AutoRetryLimit <= _AutoRetryAttempt))
                {
                    if (OnAutoConnectError != null)
                    {
                        OnAutoConnectError(this, new AutoConnectErrorEventArgs(Address, Port, e));
                    }
#if LOG4NET
                    Logger.Connection.Debug("delaying new connect attempt for " + _AutoRetryDelay + " sec");
#endif
                    Thread.Sleep(_AutoRetryDelay * 1000);
                    _NextAddress();
                    // FIXME: this is recursion
                    Connect(_AddressList, _Port);
                }
                else
                {
                    throw new CouldNotConnectException("Could not connect to: " + Address + ":" + Port + " " + e.Message, e);
                }
            }
        }