Im writing a HTTP proxy in c# sockets. Proxy have to make changes in HTML files. Everything works fine until I replace text larger or smaller than originall word was. For example, if I replace "abcde" to "abcde" proxy works perfectly, but if I replace "abcde" to "ab" I got socket exception "An established connection was aborted by the software in your host machine" in socket.send method. I have disabled firewall and windows defender.
Accepting browser socket:
static void Main(string[] args)
{
TcpListener tcpl = new TcpListener(IPAddress.Parse("127.0.0.1"), 1024);
tcpl.Start();
while (true)
{
Socket sock = tcpl.AcceptSocket();
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
RequestHandler rh = new RequestHandler(sock);
rh.Handle();
}
}
Handle request:
public void Handle()
{
string header = GetHeader(browserSocket, 1);
string host = AnalyzeHeader(header);
if (string.IsNullOrEmpty(header) || string.IsNullOrEmpty(host))
{
browserSocket.Close();
return;
}
Socket destServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress[] addresslist = Dns.GetHostAddresses(host);
IPEndPoint remoteEP = new IPEndPoint (addresslist[0], 80);
destServerSocket.Connect(remoteEP);
SendRequest(destServerSocket, header);
header = GetHeader(destServerSocket, 0);
SendRequest(browserSocket, header);
int receivedBytes = 1;
const int BUFSZ = 1024;
byte[] buffer = new byte[BUFSZ];
while (receivedBytes > 0)
{
if (destServerSocket.Poll(100000, SelectMode.SelectRead))
{
receivedBytes = destServerSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
if (header.Contains("Content-Type: text/html"))
{
string charset = GetCharset(header);
charset = string.IsNullOrEmpty(charset) ? "UTF-8" : charset;
var inputEncoding = Encoding.GetEncoding(charset);
var text = inputEncoding.GetString(buffer);
if (text.Contains("abcde"))
{
text = text.Replace("abcde", "ab");
buffer = inputEncoding.GetBytes(text);
receivedBytes = buffer.Length;
}
}
this.browserSocket.Send(buffer, receivedBytes, SocketFlags.None); //Exception 10053
}
else
{
receivedBytes = 0;
}
}
this.browserSocket.Shutdown(SocketShutdown.Both);
this.browserSocket.Close();
}
I have tried to add Content-Length to response header, but error still occur. What do you think the proble is? I've come up to nothing after days of research.