| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net.ApiService;
- using System.Net.Sockets;
- using System.IO;
- namespace System.Net.ApiService.VHost_Server {
- public class VHostServer {
- private ushort _portListen = 80;
- private HttpApiServer server;
- private List<VHostRedirect> _redirects = new List<VHostRedirect>();
- public List<VHostRedirect> Redirects {
- get { return _redirects; }
- }
- public VHostServer() {
-
- }
- public VHostServer(ushort port) {
- this._portListen = port;
- }
- public void Start() {
- this.Stop();
- this.server = new HttpApiServer(this._portListen);
- this.server.Request += Server_Request;
- this.server.Start();
- }
- private void Server_Request(object sender, RequestEventArgs e) {
- e.SendAnyResponse = false;
- System.Diagnostics.Debug.WriteLine("VHost Redirection Server - Request arrived");
- foreach(VHostRedirect red in this._redirects) {
- System.Diagnostics.Debug.WriteLine("- Check conditions for: " + red.RedirectHost + ":" + red.RedirectPort.ToString());
- if(red.IsMatch(e.Request)) {
- System.Diagnostics.Debug.WriteLine("- Condition matched");
- var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
- client.Connect(red.RedirectHost, red.RedirectPort);
- NetworkStream networkStream = new NetworkStream(client);
- // Send Request
- byte[] bytes = Encoding.Default.GetBytes(e.Request.Blank);
- networkStream.Write(bytes, 0, bytes.Length);
- // Read response and send it to the client
- byte[] bHeader = new byte[1024];
- networkStream.Read(bHeader, 0, 1024);
- string sHeader = System.Text.Encoding.ASCII.GetString(bHeader);
- int len = -1;
- System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(sHeader, "^content\\-length\\:\\s*(<?len>[0-9]+)$",Text.RegularExpressions.RegexOptions.IgnoreCase | Text.RegularExpressions.RegexOptions.Singleline);
- if(m.Success && m.Groups["len"].Success && m.Groups["len"].Length>0) {
- len = int.Parse(m.Groups["len"].Value);
- }
- e.Socket.Send(bHeader);
- byte[] buffer = new byte[4096];
- int n = 0;
- int read = 0;
- while (n < len) {
- if (networkStream.DataAvailable) {
- read = networkStream.Read(buffer, 0, buffer.Length);
- n += read;
- //fileStream.Write(buffer, 0, read);
- e.Socket.Send(buffer);
- }
- }
- return;
- }
- }
- }
- public void Stop() {
- if (this.server != null) {
- this.server.Stop();
- }
- this.server = null;
- }
- }
- }
|