/// <summary> /// Send a http request to the server. Proxy is handled automatically /// </summary> /// <param name="method">Method in string representation</param> /// <param name="body">Optional request body</param> /// <returns></returns> private Response Send(string method, string body = "") { List <string> requestMessage = new List <string>() { string.Format("{0} {1} {2}", method.ToUpper(), path, httpVersion) // Request line }; foreach (string key in Headers) // Headers { var value = Headers[key]; requestMessage.Add(string.Format("{0}: {1}", key, value)); } requestMessage.Add(""); // <CR><LF> if (body != "") { requestMessage.Add(body); } else { requestMessage.Add(""); // <CR><LF> } if (Settings.DebugMessages) { foreach (string l in requestMessage) { ConsoleIO.WriteLine("< " + l); } } Response response = Response.Empty(); AutoTimeout.Perform(() => { TcpClient client = ProxyHandler.newTcpClient(host, port, true); Stream stream; if (isSecure) { stream = new SslStream(client.GetStream()); ((SslStream)stream).AuthenticateAsClient(host); } else { stream = client.GetStream(); } string h = string.Join("\r\n", requestMessage.ToArray()); byte[] data = Encoding.ASCII.GetBytes(h); stream.Write(data, 0, data.Length); stream.Flush(); StreamReader sr = new StreamReader(stream); string rawResult = sr.ReadToEnd(); response = ParseResponse(rawResult); try { sr.Close(); stream.Close(); client.Close(); } catch { } }, TimeSpan.FromSeconds(30)); return(response); }
private async static void CheckProx(object i) { var proxy = ProxyList[(int)i]; var handler = new ProxyHandler(proxy); using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Add("Client-ID", "7sfbihg5e1b4ijo4obnsu9t4bme108"); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); try { await Program.GetToken(client); } catch (Exception) { return; } WriteLine($"Добавлена прокся {proxy.Host} - {proxy.Port}"); GoodProxyList.Add($"{proxy.Host}:{proxy.Port}"); } }
public async Task <MethodResult> AcLogin() { int retries = 1; initretrie: LogCaller(new LoggerEventArgs(String.Format("Attempting to login retry: #{0} ...", retries), LoggerTypes.Debug)); AccountState = AccountState.Conecting; MethodResult result = await _client.DoLogin(this); if (result == null) { Stop(); } LogCaller(new LoggerEventArgs(result.Message, LoggerTypes.Debug)); if (!result.Success) { if (retries > 0) { retries--; LogCaller(new LoggerEventArgs(result.Message, LoggerTypes.Warning)); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); goto initretrie; } else { LogCaller(new LoggerEventArgs(result.Message, LoggerTypes.FatalError)); if (AccountState == AccountState.Conecting || AccountState == AccountState.Good) { AccountState = AccountState.Unknown; } Stop(); } } else { if (AccountState != AccountState.Good) { AccountState = AccountState.Good; } await ClaimLevelUpRewards(Level); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); await GetPlayerProfile(); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); if (CurrentProxy != null) { ProxyHandler.ResetFailCounter(CurrentProxy); } } return(result); }
/// <summary> /// Manual HTTPS request since we must directly use a TcpClient because of the proxy. /// This method connects to the server, enables SSL, do the request and read the response. /// </summary> /// <param name="headers">Request headers and optional body (POST)</param> /// <param name="host">Host to connect to</param> /// <param name="result">Request result</param> /// <returns>HTTP Status code</returns> private static int doHTTPSRequest(List <string> headers, string host, ref string result) { string postResult = null; int statusCode = 520; AutoTimeout.Perform(() => { TcpClient client = ProxyHandler.newTcpClient(host, 443, true); SslStream stream = new SslStream(client.GetStream()); stream.AuthenticateAsClient(host); stream.Write(Encoding.ASCII.GetBytes(String.Join("\r\n", headers.ToArray()))); System.IO.StreamReader sr = new System.IO.StreamReader(stream); string raw_result = sr.ReadToEnd(); if (raw_result.StartsWith("HTTP/1.1")) { postResult = raw_result.Substring(raw_result.IndexOf("\r\n\r\n") + 4); statusCode = Settings.str2int(raw_result.Split(' ')[1]); } else { statusCode = 520; //Web server is returning an unknown error } }, TimeSpan.FromSeconds(30)); result = postResult; return(statusCode); }
public async Task <MethodResult> AcLogin() { LogCaller(new LoggerEventArgs("Attempting to login ...", LoggerTypes.Debug)); AccountState = AccountState.Conecting; MethodResult result = await _client.DoLogin(this); LogCaller(new LoggerEventArgs(result.Message, LoggerTypes.Debug)); if (!result.Success) { LogCaller(new LoggerEventArgs(result.Message, LoggerTypes.FatalError)); if (AccountState == AccountState.Conecting || AccountState == AccountState.Good) { AccountState = AccountState.Unknown; } Stop(); } else { if (AccountState == AccountState.Conecting) { AccountState = AccountState.Good; } } if (CurrentProxy != null) { ProxyHandler.ResetFailCounter(CurrentProxy); } return(result); }
private static async Task <HttpResponseMessage> PostQueryAsync(string domain, string userName, int?port) { var socksProxy = new Socks5ProxyClient(DEFAULT_LOCAL_IP, port ?? DEFAULT_PORT); var handler = new ProxyHandler(socksProxy); var httpClient = new HttpClient(handler); var data = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("luser", userName), new KeyValuePair <string, string>("domain", domain), new KeyValuePair <string, string>("luseropr", "1"), new KeyValuePair <string, string>("domainopr", "1"), new KeyValuePair <string, string>("submitform", "em"), }); try { Console.WriteLine("Connecting to pwndb service on tor network...\n"); var result = await httpClient.PostAsync(PWNDB_URL, data).ConfigureAwait(false); return(result); } catch (Exception e) { Console.WriteLine("Can't connect to service! restart tor service and try again"); } return(new HttpResponseMessage()); }
/// <summary> /// Manual HTTPS request since we must directly use a TcpClient because of the proxy. /// This method connects to the server, enables SSL, do the request and read the response. /// </summary> /// <param name="host">Host to connect to</param> /// <param name="endpoint">Endpoint for making the request</param> /// <param name="request">Request payload</param> /// <param name="result">Request result</param> /// <returns>HTTP Status code</returns> private static int doHTTPSPost(string host, string endpoint, string request, ref string result) { TcpClient client = ProxyHandler.newTcpClient(host, 443); SslStream stream = new SslStream(client.GetStream()); stream.AuthenticateAsClient(host); List <String> http_request = new List <string>(); http_request.Add("POST " + endpoint + " HTTP/1.1"); http_request.Add("Host: " + host); http_request.Add("User-Agent: MCC/" + Program.Version); http_request.Add("Content-Type: application/json"); http_request.Add("Content-Length: " + Encoding.ASCII.GetBytes(request).Length); http_request.Add("Connection: close"); http_request.Add(""); http_request.Add(request); stream.Write(Encoding.ASCII.GetBytes(String.Join("\r\n", http_request.ToArray()))); System.IO.StreamReader sr = new System.IO.StreamReader(stream); string raw_result = sr.ReadToEnd(); if (raw_result.StartsWith("HTTP/1.1")) { result = raw_result.Substring(raw_result.IndexOf("\r\n\r\n") + 4); return(Settings.str2int(raw_result.Split(' ')[1])); } else { return(520); //Web server is returning an unknown error } }
public DnsServer(ConfigFile cfg) { Address = cfg["DNS"]["address"].ToIPAddress(IPAddress.Any); Port = cfg["DNS"]["port"].ToInt(53); Listener = new UdpClient(Port); Cache = new DnsCache(cfg); Handler = new ProxyHandler(cfg); Listener.BeginReceive(ReadCallback, null); }
/// <summary> /// Ping a Minecraft server to get information about the server /// </summary> /// <returns>True if ping was successful</returns> public static bool doPing(string host, int port, ref int protocolversion) { string version = ""; TcpClient tcp = ProxyHandler.newTcpClient(host, port); tcp.ReceiveBufferSize = 1024 * 1024; byte[] packet_id = getVarInt(0); byte[] protocol_version = getVarInt(4); byte[] server_adress_val = Encoding.UTF8.GetBytes(host); byte[] server_adress_len = getVarInt(server_adress_val.Length); byte[] server_port = BitConverter.GetBytes((ushort)port); Array.Reverse(server_port); byte[] next_state = getVarInt(1); byte[] packet = concatBytes(packet_id, protocol_version, server_adress_len, server_adress_val, server_port, next_state); byte[] tosend = concatBytes(getVarInt(packet.Length), packet); tcp.Client.Send(tosend, SocketFlags.None); byte[] status_request = getVarInt(0); byte[] request_packet = concatBytes(getVarInt(status_request.Length), status_request); tcp.Client.Send(request_packet, SocketFlags.None); int packetID = -1; byte[] packetData = new byte[] { }; Protocol18Handler ComTmp = new Protocol18Handler(tcp); ComTmp.readNextPacket(ref packetID, ref packetData); if (packetData.Length > 0) //Verify Response length { if (packetID == 0x00) //Read Packet ID { string result = ComTmp.readNextString(ref packetData); //Get the Json data if (result[0] == '{' && result.Contains("protocol\":") && result.Contains("name\":\"")) { string[] tmp_ver = result.Split(new string[] { "protocol\":" }, StringSplitOptions.None); string[] tmp_name = result.Split(new string[] { "name\":\"" }, StringSplitOptions.None); if (tmp_ver.Length >= 2 && tmp_name.Length >= 2) { protocolversion = atoi(tmp_ver[1]); version = tmp_name[1].Split('"')[0]; if (result.Contains("modinfo\":")) { //Server is running Forge (which is not supported) version = "Forge " + version; protocolversion = 0; } ConsoleIO.WriteLineFormatted("§8Server version : " + version + " (protocol v" + protocolversion + ")."); return(true); } } } } return(false); }
public void RemoveProxy() { using (ProxyHandler handler = new ProxyHandler()) { handler.DisableProxy(); } UpdatePropertyCheckMarks(); }
public ProxyConnection(Socket socket, ProxyConnection reverseConnection) { Socket = socket; Context = reverseConnection.Context; ReverseConnection = reverseConnection; IsClient = false; DataHandler = new ProxyHandler(this); AssignedTabled = reverseConnection.AssignedTabled; }
public Manager(ProxyHandler handler) { UserSettings = new Settings(); Logs = new List <Log>(); Stats = new PlayerStats(); ProxyHandler = handler; LoadFarmLocations(); }
/// <summary> /// Ping a Minecraft server to get information about the server /// </summary> /// <returns>True if ping was successful</returns> public static bool doPing(string host, int port, ref int protocolversion) { string version = ""; TcpClient tcp = ProxyHandler.newTcpClient(host, port); tcp.ReceiveBufferSize = 1024 * 1024; byte[] packet_id = getVarInt(0); byte[] protocol_version = getVarInt(4); byte[] server_adress_val = Encoding.UTF8.GetBytes(host); byte[] server_adress_len = getVarInt(server_adress_val.Length); byte[] server_port = BitConverter.GetBytes((ushort)port); Array.Reverse(server_port); byte[] next_state = getVarInt(1); byte[] packet = concatBytes(packet_id, protocol_version, server_adress_len, server_adress_val, server_port, next_state); byte[] tosend = concatBytes(getVarInt(packet.Length), packet); tcp.Client.Send(tosend, SocketFlags.None); byte[] status_request = getVarInt(0); byte[] request_packet = concatBytes(getVarInt(status_request.Length), status_request); tcp.Client.Send(request_packet, SocketFlags.None); Protocol17Handler ComTmp = new Protocol17Handler(tcp); if (ComTmp.readNextVarInt() > 0) //Read Response length { if (ComTmp.readNextVarInt() == 0x00) //Read Packet ID { string result = ComTmp.readNextString(); //Get the Json data if (result[0] == '{' && result.Contains("protocol\":") && result.Contains("name\":\"")) { string[] tmp_ver = result.Split(new string[] { "protocol\":" }, StringSplitOptions.None); string[] tmp_name = result.Split(new string[] { "name\":\"" }, StringSplitOptions.None); if (tmp_ver.Length >= 2 && tmp_name.Length >= 2) { protocolversion = atoi(tmp_ver[1]); //Handle if "name" exists twice, eg when connecting to a server with another user logged in. version = (tmp_name.Length == 2) ? tmp_name[1].Split('"')[0] : tmp_name[2].Split('"')[0]; //Automatic fix for BungeeCord 1.8 not properly reporting protocol version if (protocolversion < 47 && version.Split(' ').Contains("1.8")) { protocolversion = ProtocolHandler.MCVer2ProtocolVersion("1.8.0"); } ConsoleIO.WriteLineFormatted("§8Server version : " + version + " (protocol v" + protocolversion + ")."); return(true); } } } } return(false); }
protected override void OnStop() { var proxy = new ProxyHandler(); var threadHandler = new ThreadHandler(); var installHandler = new InstallHandler(); threadHandler.StopRequestThread(); proxy.Stop(); installHandler.Uninstall(true); }
protected override void OnStart(string[] args) { var proxy = new ProxyHandler(); var threadHandler = new ThreadHandler(); var installHandler = new InstallHandler(); proxy.Start(); threadHandler.StartRequestThread(); installHandler.Install(); }
public static bool doPing(string host, int port, ref int protocolversion) { try { string version = ""; TcpClient tcp = ProxyHandler.newTcpClient(host, port); tcp.ReceiveTimeout = 30000; // 30 seconds tcp.ReceiveTimeout = 5000; //MC 1.7.2+ SpigotMC servers won't respond, so we need a reasonable timeout. byte[] ping = new byte[2] { 0xfe, 0x01 }; tcp.Client.Send(ping, SocketFlags.None); tcp.Client.Receive(ping, 0, 1, SocketFlags.None); if (ping[0] == 0xff) { Protocol16Handler ComTmp = new Protocol16Handler(tcp); string result = ComTmp.readNextString(); if (Settings.DebugMessages) { // May contain formatting codes, cannot use WriteLineFormatted Console.ForegroundColor = ConsoleColor.DarkGray; ConsoleIO.WriteLine(result); Console.ForegroundColor = ConsoleColor.Gray; } if (result.Length > 2 && result[0] == '§' && result[1] == '1') { string[] tmp = result.Split((char)0x00); protocolversion = (byte)Int16.Parse(tmp[1]); version = tmp[2]; if (protocolversion == 127) //MC 1.7.2+ { return(false); } } else { protocolversion = (byte)39; version = "B1.8.1 - 1.3.2"; } ConsoleIO.WriteLineFormatted(Translations.Get("mcc.use_version", version, protocolversion)); return(true); } else { return(false); } } catch { return(false); } }
public void FullTest() { //Arrange var logHandler = new ProxyHandler(input); //Act logHandler.Iterate(); var result = logHandler.GetData(); Assert.Equal(expectedResult, result); }
public Manager(ProxyHandler handler, MainForm mf) { UserSettings = new Settings(); Logs = new List <Log>(); Stats = new PlayerStats(); Tracker = new Tracker(); ProxyHandler = handler; LoadFarmLocations(); this._mainForm = mf; }
public void MyTestMethod() { //Arrange var mock = new Mock <USZipSoap>(); var proxy = new ProxyHandler(mock.Object); //Act var result = proxy.GetZipInfo(); //Assert mock.Verify(m => m.GetInfoByZIP("20008"), Times.Once, "Error"); }
public bool Connect(ServerConnectionInfo serverInfo, Player player, int protocolVersion, ForgeInfo forgeInfo, IMinecraftComHandler minecraftComHandler) { client = ProxyHandler.startNewTcpClient(serverInfo.ServerIP, serverInfo.ServerPort); //client.Connect(serverInfo.ServerIP, serverInfo.ServerPort); client.ReceiveBufferSize = 1024 * 1024; communicationHandler = ProtocolHandler.GetProtocolHandler(client, protocolVersion, forgeInfo, minecraftComHandler, player); return(login()); //send login packets }
public Manager(ProxyHandler handler) { UserSettings = new Settings(); Logs = new List <Log>(); Stats = new PlayerStats(); Tracker = new PokemonGoGUI.AccountScheduler.Tracker(); ProxyHandler = handler; LoadFarmLocations(); }
private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (!checkBox1.Checked) { ProxyHandler.setProxy("", false); } else { ProxyHandler.setProxy("127.0.0.1:8080", true); } }
public ProxyConnection(Socket socket, ProxyConnection reverseConnection) { ActivityTime = AcceptedTime = DateTime.Now; Socket = socket; Context = reverseConnection.Context; ReverseConnection = reverseConnection; IsClient = false; DataHandler = new ProxyHandler(this); AssignedTabled = reverseConnection.AssignedTabled; }
public void RemoveProxy() { //Decrease usage if (CurrentProxy != null) { ProxyHandler.ProxyUsed(CurrentProxy, false); CurrentProxy = null; UserSettings.ProxyIP = String.Empty; UserSettings.ProxyPort = 0; UserSettings.ProxyUsername = String.Empty; UserSettings.ProxyPassword = String.Empty; } }
private void InjectObjects(Application app, IProxy proxy) { Type localClass = app.GetType(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; foreach (FieldInfo field in localClass.GetFields(flags)) { foreach (object injectAttribute in field.GetCustomAttributes(true)) { if (injectAttribute is Inject) { if (field.FieldType.IsInterface) { Inject inject = injectAttribute as Inject; Debug.WriteLine(">> Interface: '" + field.FieldType.Name + "' request a injecting class: " + inject.Type.Name); bool remoteSupport = false; foreach (MethodInfo method in field.FieldType.GetMethods()) { foreach (object remotableAttribute in method.GetCustomAttributes(true)) { if (remotableAttribute is Remotable) { remoteSupport = true; goto FoundSupport; } } } FoundSupport: if (remoteSupport) { field.SetValue(app, ProxyHandler.NewInstance(proxy, inject.Type, field.FieldType)); } else { throw new InstantiationException("The injection required a interface with remotable annotation!"); } } else { throw new InstantiationException("The injection annotation required a object interface, not a concrete class or primitive type!"); } } } } }
public static void Exit() { HttpServer.Listener.Close(); ProxyHandler.GetInstance().UnsetProxy(); SysProxyProcess.WaitForExit(); try { PolipoProcess.Kill(); V2rayProcess.Kill(); } catch (Exception) { } ConfigHandler.SaveFile(); Application.Exit(); }
public void ChangeProxy(ProxyProfile profile) { using (ProxyHandler handler = new ProxyHandler()) { if (profile.AutomaticScript == "" || profile.AutomaticScript == null) { handler.ChangeProxy(profile.ProxyAddress + ":" + profile.Port); } else { handler.ChangeProxy(profile.ProxyAddress + ":" + profile.Port, profile.AutomaticScript); } } UpdatePropertyCheckMarks(); }
private void btnOk_Click(object sender, EventArgs e) { try { if (RbNone.Checked) { ProxyHandler.setProxy("", false); } else { ProxyHandler.setProxy(txbxIp.Text + ":" + NmPort.Value.ToString(), true); } lblChange.Text = ("Changed"); } catch (Exception ss) { MessageBox.Show(ss.Message, "Error"); lblChange.Text = ("Error"); } CurrentProxyStatue(); }
protected IStorage <TKey, TValue> RegistrateApi <TKey, TValue>(string tableName, bool hashFromValue, IDataProvider <TKey, TValue> dataProvider) { if (_apis.ContainsKey(tableName)) { throw new InitializationException(Errors.TableAlreadyExists); } var api = _proxySystem.CreateApi(tableName, hashFromValue, new HashFakeImpl <TKey, TValue>(dataProvider)); var handler = new ProxyHandler <TKey, TValue>(api, dataProvider); var empty = new ProxyHandlerEmpty <TKey, TValue>(); var tuple = new ProxyHandlerTuple <TKey, TValue>(empty, handler, IsEmpty); _apis.Add(tableName, tuple); return(tuple); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } loggerFactory.AddConsole(Configuration.GetSection("Logging")); app.UseSession(); app.UseStaticFiles(); app.UseAuthentication(); app.UseCors("AllowLocalhostOrigin"); app.Use(async(context, next) => { int?port = context.Request.Host.Port; if (port.HasValue && port.Value == 8080 && !context.Request.Path.Value.StartsWith("/api")) { ProxyHandler handler = new ProxyHandler(context); handler.ProxyToApi(); handler.WriteResponse(context.Response); } else { //continues through the rest of the pipeline await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}" ); }); }
/** * @param proxyHandler The proxyHandler to set. */ public void setProxyHandler(ProxyHandler proxyHandler) { this.proxyHandler = proxyHandler; }