/// <summary> /// Factory method for creating new proxy client objects. /// </summary> /// <param name="type">The type of proxy client to create.</param> /// <param name="tcpClient">Open TcpClient object.</param> /// <param name="proxyHost">The proxy host or IP address.</param> /// <param name="proxyPort">The proxy port number.</param> /// <param name="proxyUsername">The proxy username. This parameter is only used by Http, Socks4 and Socks5 proxy objects.</param> /// <param name="proxyPassword">The proxy user password. This parameter is only used Http, Socks5 proxy objects.</param> /// <returns>Proxy client object.</returns> public IProxyClient CreateProxyClient(ProxyType type, TcpClient tcpClient, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword) { IProxyClient c = CreateProxyClient(type, proxyHost, proxyPort, proxyUsername, proxyPassword); c.TcpClient = tcpClient; return(c); }
/// <summary> /// Opens the specified host name. /// </summary> /// <param name="hostName">Name of the host.</param> /// <param name="port">The port.</param> protected virtual void Open(string hostName, int port, bool ssl, IProxyClient proxyClient) { Host = hostName; Port = port; if (string.IsNullOrEmpty(hostName)) { throw new ArgumentNullException("hostName"); } //ServicePointManager.SetTcpKeepAlive (true, 15 * 1000, 2 * 1000); if (proxyClient == null) { m_connection = new TcpClient(hostName, port); } else { m_connection = proxyClient.CreateConnection(hostName, port); } NntpReaderWriter = new NntpProtocolReaderWriter(m_connection, ssl, hostName); if (ConnectionTimeout != -1) { m_connection.SendTimeout = m_connection.ReceiveTimeout = ConnectionTimeout; } }
private static IProxyClient GetProxy() { IProxyClient proxyClient = null; if (Settings.Settings.Current.ProxyEnabled == true && string.IsNullOrEmpty(Settings.Settings.Current.ProxyType) == false && string.IsNullOrEmpty(Settings.Settings.Current.ProxyServer) == false && Settings.Settings.Current.ProxyPort > 0) { if (Settings.Settings.Current.ProxyType.ToLower() == "socks5") { proxyClient = new Socks5ProxyClient(Settings.Settings.Current.ProxyServer, Settings.Settings.Current.ProxyPort, Settings.Settings.Current.ProxyUsername, Settings.Settings.Current.ProxyPassword); } else if (Settings.Settings.Current.ProxyType.ToLower() == "socks4") { proxyClient = new Socks4ProxyClient(Settings.Settings.Current.ProxyServer, Settings.Settings.Current.ProxyPort, Settings.Settings.Current.ProxyUsername); } else if (Settings.Settings.Current.ProxyType.ToLower() == "http") { proxyClient = new HttpProxyClient(Settings.Settings.Current.ProxyServer, Settings.Settings.Current.ProxyPort, Settings.Settings.Current.ProxyUsername, Settings.Settings.Current.ProxyPassword); } if (proxyClient != null) { //Setup timeouts proxyClient.ReceiveTimeout = (int)TimeSpan.FromSeconds(600).TotalMilliseconds; proxyClient.SendTimeout = (int)TimeSpan.FromSeconds(600).TotalMilliseconds; } } return(proxyClient); }
public SimpleClient() { info = new ClientInfo(Guid.NewGuid(), "HES Simple Client", System.Net.Dns.GetHostName(), ((uint)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds)); string location = "tcp://localhost:4821/ProxyClientService"; TcpChannel channel = new TcpChannel(); ChannelServices.RegisterChannel(channel, true); proxy = (IProxyClient)Activator.GetObject(typeof(IProxyClient), location); try { while (!proxy.anyServerAvailable()) { Console.WriteLine("Try to get IService instance"); Thread.Sleep(1000); } IHes = proxy.getServiceHost<IHes>(info); Console.WriteLine("Got it!"); Console.WriteLine("Ladida"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.Source); Console.WriteLine(ex.StackTrace); } startSzenario(); }
private void CheckAccount(string login) { try { int type = 0; Socket socket = null; string imaptext = "imap.gmail.com"; if (radioButton1.Checked) { imaptext = "imap.gmail.com"; } else if (radioButton2.Checked) { imaptext = "imap.mail.yahoo.com"; } else { imaptext = "imap-mail.outlook.com"; } if (proxies.Count > 0) { type = 1; ProxyFactory factory = new ProxyFactory(); string proxi = proxies[rad.Next(proxies.Count)]; string[] prox = proxi.Split(':'); IProxyClient proxy = null; if (prox.Length == 4) { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1]), prox[2], prox[3]); } else { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1])); } socket = proxy.Connect(imaptext, Imap.DefaultSSLPort); } using (Imap imap = new Imap()) { incprogress = incprogress + 1; if (type == 0) { imap.ConnectSSL(imaptext); } else { imap.AttachSSL(socket, imaptext); } string[] cred = login.Split(':'); imap.Login(cred[0], cred[1]); WorkingAccounts.Add(login); } } catch (Exception ex) { // MessageBox.Show(ex.ToString()); } }
static async Task Upstream(string hostname, string port, string proxy, string isNested) { if (port == "443") { var httpClientHandler = new HttpClientHandler(); httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => { return(true); // Is valid }; if (proxy != null) { Environment.SetEnvironmentVariable("https_proxy", proxy); } var httpClient = new HttpClient(httpClientHandler); var logsUrl = string.Format("https://{0}/devices/0000/modules", hostname); var httpRequest = new HttpRequestMessage(HttpMethod.Get, logsUrl); HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead); if (isNested != null) { var keys = httpResponseMessage.Headers.GetValues("iothub-errorcode"); if (!keys.Contains("InvalidProtocolVersion")) { throw new Exception($"Wrong value for iothub-errorcode header"); } } } else { // The current rust code never put proxy parameter when port is != than 443. // So the code below is never exercised. It was put there to avoid silently ignoring the proxy // if the rust code is changed. if (proxy != null) { Uri proxyUri = new Uri(proxy); IProxyClient proxyClient = MakeProxy(proxyUri); // Setup timeouts proxyClient.ReceiveTimeout = (int)TimeSpan.FromSeconds(60).TotalMilliseconds; proxyClient.SendTimeout = (int)TimeSpan.FromSeconds(60).TotalMilliseconds; // Get TcpClient to futher work var client = proxyClient.CreateConnection(hostname, int.Parse(port)); client.GetStream(); } else { TcpClient client = new TcpClient(); await client.ConnectAsync(hostname, int.Parse(port)); client.GetStream(); } } }
//string postFromUser; public UsenetServer(string server, ushort port, bool useSSL, string username, string password, string newsgroup, IProxyClient proxyClient) //string postFromUser { this.username = username; this.password = password; this.serverAddress = server; this.useSSL = useSSL; this.port = port; this.newsgroup = newsgroup; this.proxyClient = proxyClient; //this.postFromUser = postFromUser; }
/// <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)); }
private void timerRun_Tick(object sender, EventArgs e) { Log("timerRun_Tick"); try { this.timer.Stop(); ProxyFactory factory = new ProxyFactory(); IProxyClient proxy = factory.CreateProxy(ProxyType.Http, "10.198.7.38", 3128); Socket socket = proxy.Connect(_server, Imap.DefaultSSLPort); Imap imap = new Imap(); imap.AttachSSL(socket, _server); imap.Login(_user, _password); // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods, // or use UseBestLogin method if you want Mail.dll to choose for you. imap.SelectInbox(); // You can select other folders, e.g. Sent folder: imap.Select("Sent"); List <long> uids = imap.Search(Flag.Unseen); // Find all unseen messages. Log("Number of unseen messages is: " + uids.Count); foreach (long uid in uids) { IMail email = new MailBuilder().CreateFromEml( // Download and parse each message. imap.GetMessageByUID(uid)); Log(email.Text); string url = ""; try { url = "http://10.198.1.90/ais/sms.pl?bgn=" + email.Text.Split(' ')[0] + "&end=" + email.Text.Split(' ')[1]; } catch { } Log("'" + url + "'"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Close(); } } catch (Exception ex) { Log(ex.Message); Log(ex.Source); } this.timer.Start(); }
/// <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)); }
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 }
/// <summary> /// Use the HTTP proxy client /// </summary> /// <param name="dstHost"></param> /// <param name="dstPort"></param> private void ConnectHttp(string dstHost, int dstPort) { // Retreive a proxyclient. the HTTP proxy client does not support user/pass, so no point checking for those variables. if (this._serverURI.Port == 0) { this._serverURI.Port = 8080; // default port in Starksoft.Net.Proxy.Socks4ProxyClient.cs } IProxyClient proxyclient = proxyclient = this._proxyclientfactory.CreateProxyClient(ProxyType.Http, this._serverURI.Host, this._serverURI.Port); TcpClient tc = proxyclient.CreateConnection(dstHost, dstPort); if (tc.Connected) { this._socket = tc.Client; } }
/// <summary> /// Create a regular TcpClient or a proxied TcpClient according to the app Settings. /// </summary> /// <param name="host">Target host</param> /// <param name="port">Target port</param> /// <param name="login">True if the purpose is logging in to a Minecraft account</param> public static TcpClient newTcpClient(string host, int port, bool login = false) { try { if (login ? Settings.ProxyEnabledLogin : Settings.ProxyEnabledIngame) { ProxyType innerProxytype = ProxyType.Http; switch (Settings.proxyType) { case Type.HTTP: innerProxytype = ProxyType.Http; break; case Type.SOCKS4: innerProxytype = ProxyType.Socks4; break; case Type.SOCKS4a: innerProxytype = ProxyType.Socks4a; break; case Type.SOCKS5: innerProxytype = ProxyType.Socks5; break; } if (Settings.ProxyUsername != "" && Settings.ProxyPassword != "") { proxy = factory.CreateProxyClient(innerProxytype, Settings.ProxyHost, Settings.ProxyPort, Settings.ProxyUsername, Settings.ProxyPassword); } else { proxy = factory.CreateProxyClient(innerProxytype, Settings.ProxyHost, Settings.ProxyPort); } if (!proxy_ok) { ConsoleIO.WriteLineFormatted(Translations.Get("proxy.connected", Settings.ProxyHost, Settings.ProxyPort)); proxy_ok = true; } return(proxy.CreateConnection(host, port)); } else { return(new TcpClient(host, port)); } } catch (ProxyException e) { ConsoleIO.WriteLineFormatted("§8" + e.Message); proxy = null; throw new SocketException((int)SocketError.HostUnreachable); } }
/// <summary> /// Create a regular TcpClient or a proxied TcpClient according to the app Settings. /// </summary> public static TcpClient newTcpClient(string host, int port) { try { if (Settings.ProxyEnabled) { ProxyType innerProxytype = ProxyType.Http; switch (Settings.proxyType) { case Type.HTTP: innerProxytype = ProxyType.Http; break; case Type.SOCKS4: innerProxytype = ProxyType.Socks4; break; case Type.SOCKS4a: innerProxytype = ProxyType.Socks4a; break; case Type.SOCKS5: innerProxytype = ProxyType.Socks5; break; } if (Settings.ProxyUsername != "" && Settings.ProxyPassword != "") { proxy = factory.CreateProxyClient(innerProxytype, Settings.ProxyHost, Settings.ProxyPort, Settings.ProxyUsername, Settings.ProxyPassword); } else { proxy = factory.CreateProxyClient(innerProxytype, Settings.ProxyHost, Settings.ProxyPort); } if (!proxy_ok) { ConsoleIO.WriteLineFormatted("§8Connected to proxy " + Settings.ProxyHost + ':' + Settings.ProxyPort); proxy_ok = true; } return(proxy.CreateConnection(host, port)); } else { return(new TcpClient(host, port)); } } catch (ProxyException e) { ConsoleIO.WriteLineFormatted("§8" + e.Message); proxy = null; return(null); } }
public void cleanup() { this.proxy.TcpClient.Close(); try { while (this.proxy.TcpClient.Available == 0) { Thread.Sleep(25); } } catch (ObjectDisposedException) { Debug.Print("TcpClient instance disposed."); } proxy = factory.CreateProxyClient(ProxyType.Socks5, "127.0.0.1", socksPort); this.State = TorState.Ready; }
/// <summary> /// Connects using the specified host name and port number. /// </summary> /// <param name="hostName">Name of the host.</param> /// <param name="port">The port.</param> public virtual void Connect(string hostName, int port, bool ssl, IProxyClient proxyClient) { Open(hostName, port, ssl, proxyClient); NntpReaderWriter.ReadResponse(); if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.ServerReadyPostingAllowed) { m_postingIsAllowed = true; } else if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.ServerReadyNoPostingAllowed) { m_postingIsAllowed = false; } else { throw new NntpResponseException(NntpErrorMessages.ERROR_1, NntpReaderWriter.LastResponse); } }
public FTP(FTPAccount account) { this.Account = account; this.Client = new FtpClient(); switch (account.Protocol) { case FTPProtocol.FTPS: if (File.Exists(account.FtpsCertLocation)) { Client.SecurityProtocol = account.FtpsSecurityProtocol; Client.SecurityCertificates.Add(X509Certificate.CreateFromSignedFile(account.FtpsCertLocation)); } else { logger.WriteLine("Can't find ftps certificate (" + account.FtpsCertLocation + ")"); } break; default: Client.SecurityProtocol = FtpSecurityProtocol.None; break; } Client.Host = account.Host; Client.Port = account.Port; Client.DataTransferMode = account.IsActive ? TransferMode.Active : TransferMode.Passive; if (null != Uploader.ProxySettings) { IProxyClient proxy = Uploader.ProxySettings.GetProxyClient(); { if (proxy != null) { Client.Proxy = proxy; } } } Client.TransferProgress += new EventHandler <TransferProgressEventArgs>(OnTransferProgressChanged); Client.ConnectionClosed += new EventHandler <ConnectionClosedEventArgs>(Client_ConnectionClosed); }
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)); }
/// <summary> /// Create a regular TcpClient or a proxied TcpClient according to the app Settings. /// </summary> public static TcpClient newTcpClient(string host, int port) { try { if (Settings.ProxyEnabled) { ProxyType innerProxytype = ProxyType.Http; switch (Settings.proxyType) { case Type.HTTP: innerProxytype = ProxyType.Http; break; case Type.SOCKS4: innerProxytype = ProxyType.Socks4; break; case Type.SOCKS4a: innerProxytype = ProxyType.Socks4a; break; case Type.SOCKS5: innerProxytype = ProxyType.Socks5; break; } if (Settings.ProxyUsername != "" && Settings.ProxyPassword != "") { proxy = factory.CreateProxyClient(innerProxytype, Settings.ProxyHost, Settings.ProxyPort, Settings.ProxyUsername, Settings.ProxyPassword); } else proxy = factory.CreateProxyClient(innerProxytype, Settings.ProxyHost, Settings.ProxyPort); if (!proxy_ok) { ConsoleIO.WriteLineFormatted("§8Connected to proxy " + Settings.ProxyHost + ':' + Settings.ProxyPort); proxy_ok = true; } return proxy.CreateConnection(host, port); } else return new TcpClient(host, port); } catch (ProxyException e) { ConsoleIO.WriteLineFormatted("§8" + e.Message); proxy = null; return null; } }
public FTP(FTPAccount account, int bufferSize = 8192) { Account = account; Client = new FtpClient(account.Host, account.Port); Client.TcpBufferSize = bufferSize; if (account.Protocol == FTPProtocol.FTP || account.FtpsSecurityProtocol == FtpSecurityProtocol.None) { Client.SecurityProtocol = (Starksoft.Net.Ftp.FtpSecurityProtocol)FtpSecurityProtocol.None; } else { Client.SecurityProtocol = (Starksoft.Net.Ftp.FtpSecurityProtocol)account.FtpsSecurityProtocol; if (!string.IsNullOrEmpty(account.FtpsCertLocation) && File.Exists(account.FtpsCertLocation)) { Client.SecurityCertificates.Add(X509Certificate.CreateFromSignedFile(account.FtpsCertLocation)); } else { Client.ValidateServerCertificate += (sender, e) => e.IsCertificateValid = true; } } Client.DataTransferMode = account.IsActive ? TransferMode.Active : TransferMode.Passive; if (ProxyInfo.Current != null) { IProxyClient proxy = ProxyInfo.Current.GetProxyClient(); if (proxy != null) { Client.Proxy = proxy; } } Client.TransferProgress += OnTransferProgressChanged; Client.ConnectionClosed += Client_ConnectionClosed; }
static async Task Upstream(string hostname, string port, string proxy) { if (proxy != null) { Uri proxyUri = new Uri(proxy); IProxyClient proxyClient = MakeProxy(proxyUri); // Setup timeouts proxyClient.ReceiveTimeout = (int)TimeSpan.FromSeconds(60).TotalMilliseconds; proxyClient.SendTimeout = (int)TimeSpan.FromSeconds(60).TotalMilliseconds; // Get TcpClient to futher work var client = proxyClient.CreateConnection(hostname, int.Parse(port)); client.GetStream(); } else { TcpClient client = new TcpClient(); await client.ConnectAsync(hostname, int.Parse(port)); client.GetStream(); } }
public static bool Start() { try { for (int i = 0; i < Settings.Settings.Current.UsenetSlots; i++) { IProxyClient proxyClient = GetProxy(); if (i == 0 && proxyClient != null) { Logger.Info(LOGNAME, "Proxy enabled (" + Settings.Settings.Current.ProxyType + "): " + Settings.Settings.Current.ProxyServer + ":" + Settings.Settings.Current.ProxyPort); } UsenetServer us = new UsenetServer(Settings.Settings.Current.UsenetServer, Settings.Settings.Current.UsenetPort, Settings.Settings.Current.UsenetUseSSL, Settings.Settings.Current.UsenetUsername, Settings.Settings.Current.UsenetPassword, Settings.Settings.Current.UsenetNewsgroup, proxyClient); ListOfConns.Add(us); } Logger.Info(LOGNAME, "UsenetConns loaded"); return(true); } catch (Exception ex) { Logger.Error(LOGNAME, ex.Message, ex); } return(false); }
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; } }
/// <summary> /// Connects the specified host name. /// </summary> /// <param name="hostName">Name of the host.</param> /// <param name="port">The port.</param> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> public virtual void Connect(string hostName, int port, bool ssl, string userName, string password, IProxyClient proxyClient) { Open(hostName, port, ssl, proxyClient); AuthenticateUser(userName, password); CheckToSupportedExtensions(); }
/// <summary> /// Connects using the specified host name and port number. /// </summary> /// <param name="hostName">Name of the host.</param> /// <param name="port">The port.</param> public override void Connect(string hostName, int port, bool ssl, IProxyClient proxyClient) { base.Connect(hostName, port, ssl, proxyClient); CheckToSupportedExtensions(); }
public void cleanup() { this.proxy.TcpClient.Close(); try { while (this.proxy.TcpClient.Available == 0) Thread.Sleep(25); } catch (ObjectDisposedException) { Debug.Print("TcpClient instance disposed."); } proxy = factory.CreateProxyClient(ProxyType.Socks5, "127.0.0.1", socksPort); this.State = TorState.Ready; }
private async void StartClientLoop(TcpClient client) { IProxyClient proxyClient = null; try { var shark = await GetOrCreateSharkClient(); proxyClient = CreateClient(client, shark); var sharkFirstInitialized = false; shark.RemoteClients.Add(proxyClient.Id, proxyClient); Clients.Add(proxyClient.Id, proxyClient); try { var host = await proxyClient.StartAndProcessRequest(); if (!shark.Initialized) { var result = await shark.FastConnect(proxyClient.Id, host); Sharks.Add(shark.Id, shark); sharkFirstInitialized = true; Interlocked.Decrement(ref _waitingCount); await proxyClient.ProcessSharkData(result); } else { await shark.ProxyTo(proxyClient.Id, host); } proxyClient.RemoteDisconnected += OnClientRemoteDisconencted; } catch (AuthenticationException ex) { Logger.LogError(ex, $"Client Auth failed"); shark.Dispose(); Interlocked.Decrement(ref _waitingCount); } catch (Exception ex) { Logger.LogError(ex, $"Process Connect failed for {proxyClient.Id}"); shark.RemoteClients.Remove(proxyClient.Id); Clients.Remove(proxyClient.Id); proxyClient.Dispose(); if (!shark.Initialized) { try { await shark.Auth(); Sharks.Add(shark.Id, shark); sharkFirstInitialized = true; } catch (Exception e) { shark.Dispose(); shark.Logger.LogWarning($"Shark client {shark.Id} initlialize failed, {e} "); throw; } finally { Interlocked.Decrement(ref _waitingCount); } } } if (sharkFirstInitialized) { #pragma warning disable CS4014 StartSharkLoop(shark); #pragma warning restore CS4014 } } catch (Exception) { Logger.LogWarning("Failed to start client loop"); if (proxyClient != null) { proxyClient.Dispose(); } else { try { client.Client.Shutdown(SocketShutdown.Both); client.Client.Disconnect(false); } catch (Exception) { // } client.Dispose(); } } }
public Sender(IProxyClient client) { _client = client ?? throw new ArgumentNullException(nameof(client)); _client.NotificationReceived += _client_NotificationReceived; }
/// <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); } } }
/// <summary> /// Connects using the specified host name. /// </summary> /// <param name="hostName">Name of the host.</param> public void Connect(string hostName, IProxyClient proxyClient) { Connect(hostName, 119, false, proxyClient); }
private void startprocess(string logindetails, string imapselect, bool sendmail, string smtptet) { try { int type = 0; Socket socket = null; if (proxies.Count > 0) { type = 1; ProxyFactory factory = new ProxyFactory(); string proxi = proxies[rad.Next(proxies.Count)]; string[] prox = proxi.Split(':'); IProxyClient proxy = null; if (prox.Length == 4) { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1]), prox[2], prox[3]); } else { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1])); } socket = proxy.Connect(imapselect, Imap.DefaultSSLPort); } using (Imap imap = new Imap()) { if (type == 0) { imap.ConnectSSL(imapselect); } else { imap.AttachSSL(socket, imapselect); } string[] cred = logindetails.Split(':'); imap.Login(cred[0], cred[1]); // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods, CommonFolders folders = new CommonFolders(imap.GetFolders()); imap.Select(folders.Spam); foreach (long ouid in imap.GetAll()) { IMail email = new MailBuilder().CreateFromEml( imap.GetMessageByUID(ouid)); List <long> unseenReports = new List <long>(); foreach (string sub in subjects) { if (email.Subject.Contains(sub) || string.Equals(email.Subject, sub)) { unseenReports.Add(ouid); if (!checkBox1.Checked && sendmail && !radioButton4.Checked) { IMail original = email; Socket socket1 = null; if (proxies.Count > 0) { type = 1; ProxyFactory factory = new ProxyFactory(); string proxi = proxies[rad.Next(proxies.Count)]; string[] prox = proxi.Split(':'); IProxyClient proxy = null; if (prox.Length == 4) { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1]), prox[2], prox[3]); } else { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1])); } socket1 = proxy.Connect(smtptet, portsmtp); } ReplyBuilder replyBuilder = original.Reply(); // You can specify your own, custom, body and subject templates: replyBuilder.HtmlReplyTemplate = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""> <html> <head> <meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" /> <title>[Subject]</title> </head> <body> [Html] <br /><br /> On [Original.Date] [Original.Sender.Name] wrote: <blockquote style=""margin-left: 1em; padding-left: 1em; border-left: 1px #ccc solid;""> [QuoteHtml] </blockquote> </body> </html>"; replyBuilder.SubjectReplyTemplate = "Re: [Original.Subject]"; replyBuilder.Html = NewSpin.Spin(textBox1.Text); MailBuilder builder = replyBuilder.ReplyToAll(cred[0]); // You can add attachments to your reply //builder.AddAttachment("report.csv"); IMail reply = builder.Create(); using (Smtp smtp = new Smtp()) { if (type == 0) { if (radioButton3.Checked || radioButton4.Checked) { smtp.Connect(smtptet, portsmtp); smtp.StartTLS(); } else { smtp.ConnectSSL(smtptet, portsmtp); } } else { if (radioButton3.Checked || radioButton4.Checked) { smtp.Attach(socket1); smtp.StartTLS(); } else { smtp.AttachSSL(socket1, smtptet); } } smtp.ReceiveTimeout = new TimeSpan(0, 0, 100); //MessageBox.Show("Sending Mail"); smtp.UseBestLogin(cred[0], cred[1]); smtp.SendMessage(reply); smtp.Close(); } } } } foreach (long uid in unseenReports) // Download emails from the last result. { // MessageBox.Show(uid.ToString()); imap.MoveByUID(uid, folders.Inbox); imap.FlagMessageByUID(uid, Flag.Seen); movedcount = movedcount + 1; } } imap.Close(); } } catch (Exception exp) { //MessageBox.Show(exp.ToString()); } finally { count = count + 1; } }
public ProxyClientExecutor(IProxyClient proxyClient) { _proxyClient = proxyClient; }
public void Connect(string hostName, bool ssl, IProxyClient proxyClient) { Connect(hostName, ssl ? 443 : 119, ssl, proxyClient); }