Exemplo n.º 1
0
        public async Task <MiddlemanRequest> ParseAsync(InboundConnection conn, Stream stream)
        {
            var del    = new ParseDelegate();
            var parser = new HttpParser(del);

            int read;
            var readTotal = 0;
            var buffer    = new byte[8192];

            Log.Debug("{0}: RequestParser starting", conn.RemoteEndPoint);

            var requestString = "";

            while (stream != null && (read = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
            {
                requestString += Encoding.ASCII.GetString(buffer.Where(x => x != 0).ToArray(), 0, read);
                readTotal     += read;

                if (parser.Execute(new ArraySegment <byte>(buffer, 0, read)) != read)
                {
                    throw new FormatException("Parse error in request");
                }

                if (del.HeaderComplete)
                {
                    break;
                }
            }

            conn.MustClose = del.Request.Headers.AllKeys.Any(h => h.Equals("Connection", StringComparison.InvariantCultureIgnoreCase) && del.Request.Headers[h].Equals("Close", StringComparison.InvariantCultureIgnoreCase));

            Log.Debug("{0}: RequestParser read enough ({1} bytes)", conn.RemoteEndPoint, readTotal);
            Log.Info("ORIGINAL REQUEST: " + Environment.NewLine + requestString + Environment.NewLine);

            if (readTotal == 0)
            {
                return(null);
            }

            if (!del.HeaderComplete)
            {
                throw new FormatException("Parse error in request");
            }

            var request = del.Request;

            request.ProtocolVersion = new Version(parser.MajorVersion, parser.MinorVersion);
            conn.RequestVersion     = request.ProtocolVersion;

            var cl = request.ContentLength;

            if (cl > 0 && stream != null)
            {
                request.RequestBody = del.RequestBodyStart.Count > 0
                    ? new MaxReadStream(new StartAvailableStream(del.RequestBodyStart, stream), cl)
                    : new MaxReadStream(stream, cl);
            }

            return(request);
        }
Exemplo n.º 2
0
        public async Task <SwitchboardRequest> ParseAsync(InboundConnection conn, Stream stream)
        {
            var del    = new ParseDelegate();
            var parser = new HttpParser(del);

            int read;
            int readTotal = 0;

            byte[] buffer = new byte[8192];

            Debug.WriteLine(string.Format("{0}: RequestParser starting", conn.RemoteEndPoint));

            while ((read = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
            {
                readTotal += read;

                if (parser.Execute(new ArraySegment <byte>(buffer, 0, read)) != read)
                {
                    throw new FormatException("Parse error in request");
                }

                if (del.headerComplete)
                {
                    break;
                }
            }

            Debug.WriteLine(string.Format("{0}: RequestParser read enough ({1} bytes)", conn.RemoteEndPoint, readTotal));

            if (readTotal == 0)
            {
                return(null);
            }

            if (!del.headerComplete)
            {
                throw new FormatException("Parse error in request");
            }

            var request = del.request;

            request.ProtocolVersion = new Version(parser.MajorVersion, parser.MinorVersion);

            int cl = request.ContentLength;

            if (cl > 0)
            {
                if (del.requestBodyStart.Count > 0)
                {
                    request.RequestBody = new MaxReadStream(new StartAvailableStream(del.requestBodyStart, stream), cl);
                }
                else
                {
                    request.RequestBody = new MaxReadStream(stream, cl);
                }
            }

            return(request);
        }
Exemplo n.º 3
0
        internal void Close()
        {
            if (InboundConnection.IsConnected)
            {
                InboundConnection.Close();
            }

            if (OutboundConnection != null && OutboundConnection.IsConnected)
            {
                OutboundConnection.Close();
            }
        }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            var utility = new UtilityArguments(args);

            if (utility.InboundPort == null ||
                utility.OutboundIpAddress1 == null ||
                utility.Contains("help") ||
                utility.Contains("h") ||
                utility.Contains("?"))
            {
                Console.WriteLine("Forwards an inbound TCP connection to one or more outbound TCP connection.");
                Console.WriteLine();
                Console.WriteLine("USAGE:");
                Console.WriteLine(@"    splittcp -in 80 -out1 ""192.168.1.1""");
                Console.WriteLine(@"                    [-out2 ""192.168.1.2"" |");
                Console.WriteLine(@"                     -out3 ""192.168.1.3"" |");
                Console.WriteLine(@"                     -out4 ""192.168.1.4"" |");
                Console.WriteLine(@"                     -out5 ""192.168.1.5""]");
                Console.WriteLine();
                Console.WriteLine("REQUIRED:");
                Console.WriteLine("    -in [tcp port]         Inbound TCP port to listen to");
                Console.WriteLine("    -out1 [ip address]     IP address (or host name) of 1st outbound TCP connection");

                Console.WriteLine();
                Console.WriteLine("OPTIONAL:");
                Console.WriteLine("    -out2 [ip address]     IP address (or host name) of 2nd outbound TCP connection");
                Console.WriteLine("    -out3 [ip address]     IP address (or host name) of 3rd outbound TCP connection");
                Console.WriteLine("    -out4 [ip address]     IP address (or host name) of 4th outbound TCP connection");
                Console.WriteLine("    -out5 [ip address]     IP address (or host name) of 5th outbound TCP connection");
                Console.WriteLine();
                Console.WriteLine("Press any key to exit...");

                Console.ReadKey();
                return;
            }

            // validate port
            if (utility.InboundPort == 0)
            {
                Console.WriteLine($"Port is not a valid (0 < port <= {ushort.MaxValue})");
                return;
            }

            // validate ip address
            IPAddress out1, out2, out3, out4, out5;

            if (!TryParseIpAddress(utility.OutboundIpAddress1, out out1) ||
                !TryParseIpAddress(utility.OutboundIpAddress2, out out2) ||
                !TryParseIpAddress(utility.OutboundIpAddress3, out out3) ||
                !TryParseIpAddress(utility.OutboundIpAddress4, out out4) ||
                !TryParseIpAddress(utility.OutboundIpAddress5, out out5))
            {
                return;
            }

            // set up connections
            var inbound   = new InboundConnection(new IPEndPoint(IPAddress.Any, utility.InboundPort.Value));
            var outbounds = new List <OutboundConnection>();

            AddOutboundConnection(new IPEndPoint(out1, utility.InboundPort.Value), outbounds);
            if (out2 != null)
            {
                AddOutboundConnection(new IPEndPoint(out2, utility.InboundPort.Value), outbounds);
            }
            if (out3 != null)
            {
                AddOutboundConnection(new IPEndPoint(out3, utility.InboundPort.Value), outbounds);
            }
            if (out4 != null)
            {
                AddOutboundConnection(new IPEndPoint(out4, utility.InboundPort.Value), outbounds);
            }
            if (out5 != null)
            {
                AddOutboundConnection(new IPEndPoint(out5, utility.InboundPort.Value), outbounds);
            }

            inbound.Connected       += InboundOnConnected;
            inbound.ConnectionError += InboundOnConnectionError;
            inbound.DataReceived    += (o, e) =>
            {
                Console.WriteLine($"[{DateTime.Now:s}] Received {e.Data.Length} bytes (Source={((IPEndPoint)e.RemoteEndPoint).Address}:{((IPEndPoint)e.RemoteEndPoint).Port}).");

                ForwardToOutbounds(e.Data, outbounds);
            };

            var cancellationTokenSource = new CancellationTokenSource();

            Console.WriteLine($"[{DateTime.Now:s}] Starting...");

            var task = Task.Run(() => inbound.Listen(cancellationTokenSource.Token));

            // Listen for a key response.
            ConsoleKeyInfo keyInfo;

            do
            {
                keyInfo = Console.ReadKey(true);

                try
                {
                    //switch (keyInfo.Key)
                    //{
                    //}
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[{DateTime.Now:s}] Error executing {keyInfo.Key}. Exception: {ex}");
                }
            } while (keyInfo.Key != ConsoleKey.Q);

            if (!task.IsCompleted)
            {
                Console.WriteLine($"[{DateTime.Now:s}] Stopping...");
                cancellationTokenSource.Cancel();

                task.Wait(TimeSpan.FromSeconds(8));
            }
        }
Exemplo n.º 5
0
 public SwitchboardContext(InboundConnection client)
 {
     this.InboundConnection       = client;
     this.ContextId               = Interlocked.Increment(ref contextCounter);
     this.CheckForDisconnectTimer = new Timer(CheckForDisconnect, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
 }
Exemplo n.º 6
0
        public static void ProcessConnection(InboundConnection conn)
        {
            conn.BindDigitAction("", "##", "", null, null, null);
            SocketEvent ev;

            conn.Answer();
            string[] keys = new string[conn.Keys.Count];
            conn.Keys.CopyTo(keys, 0);
            foreach (string str in keys)
            {
                System.Diagnostics.Debug.WriteLine(str + " --> " + (conn[str] == null ? "" : conn[str]));
            }
            string pin = conn.PlayAndGetDigits(4, 10, 3, 3000, "#", "sounds/en/us/callie/conference/8000/conf-pin.wav", null, "\\d+", null);

            Console.WriteLine("The pin entered was: " + (pin == null ? "NO PIN" : pin));
            if (pin == "8888")
            {
                conn.PlayAudioFile("sounds/music/48000/ponce-preludio-in-e-major.wav", false);
                Thread.Sleep(10000);
                if (conn.IsExtensionLive(new sDomainExtensionPair("1001", conn.Domain)))
                {
                    ev = conn.BridgeToExtension(new sDomainExtensionPair("1001", conn.Domain), true);
                    if (ev == null)
                    {
                        Console.WriteLine("Null event returned from bridge");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Bridge result: ");
                        foreach (string str in ev.Keys)
                        {
                            System.Diagnostics.Debug.WriteLine(str + " --> " + ev[str]);
                        }
                        if (ev["originate_disposition"] == "USER_NOT_REGISTERED")
                        {
                            Console.WriteLine("Bridging to voicemail for unregistered user.");
                            ev = conn.Voicemail(conn.Context, new sDomainExtensionPair(conn.Domain, "1001"));
                            if (ev == null)
                            {
                                Console.WriteLine("Null event returned from voicemail.");
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("Voicemail result: ");
                                foreach (string str in ev.Keys)
                                {
                                    System.Diagnostics.Debug.WriteLine(str + " --> " + ev[str]);
                                }
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Extension 1001 is not connected, bridging to voicemail");
                    ev = conn.Voicemail(conn.Context, new sDomainExtensionPair(conn.Domain, "1001"));
                    if (ev == null)
                    {
                        Console.WriteLine("Null event returned from voicemail.");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Voicemail result: ");
                        foreach (string str in ev.Keys)
                        {
                            System.Diagnostics.Debug.WriteLine(str + " --> " + ev[str]);
                        }
                    }
                }
            }
            else
            {
                conn.PlayAudioFile("sounds/en/us/callie/conference/8000/conf-bad-pin.wav", true);
                conn.PlayAudioFile("sounds/en/us/callie/conference/8000/conf-goodbye.wav", true);
            }
            if (!conn.IsHungUp)
            {
                conn.Hangup();
            }
        }
Exemplo n.º 7
0
 public MiddlemanContext(InboundConnection client)
 {
     InboundConnection = client;
     ContextId         = Interlocked.Increment(ref _contextCounter);
     Log.Debug("Creating context ({1}) for connection from {0}.", client.RemoteEndPoint, ContextId);
 }