Beispiel #1
0
        public void Start()
        {
            //lock (syncRoot)
            {
                if (PublicIp == null)
                {
                    throw new Exception("Invalid Public IP");
                }

                allocations          = new AllocationsPool();
                allocations.Removed += Allocation_Removed;

                ServerAsyncEventArgs.DefaultOffsetOffset = TcpFramingHeader.TcpFramingHeaderLength;

                turnServer = new ServersManager <TurnConnection>(new ServersManagerConfig());
                turnServer.Bind(new ProtocolPort()
                {
                    Protocol = ServerProtocol.Udp, Port = TurnUdpPort,
                });
                turnServer.Bind(new ProtocolPort()
                {
                    Protocol = ServerProtocol.Tcp, Port = TurnTcpPort,
                });
                turnServer.Bind(new ProtocolPort()
                {
                    Protocol = ServerProtocol.Tcp, Port = TurnPseudoTlsPort,
                });
                turnServer.NewConnection += TurnServer_NewConnection;
                turnServer.Received      += TurnServer_Received;
                turnServer.ServerAdded   += TurnServer_ServerAdded;
                turnServer.ServerRemoved += TurnServer_ServerRemoved;
                turnServer.Start(true);

                peerServer = new ServersManager <PeerConnection>(
                    new ServersManagerConfig()
                {
                    MinPort = MinPort,
                    MaxPort = MaxPort,
                });
                peerServer.AddressPredicate = (i, ip, ai) => { return(ai.Address.Equals(RealIp)); };
                peerServer.Received        += PeerServer_Received;
                peerServer.Start(true);
                peerServer.ServerAdded   += PeerServer_ServerAdded;
                peerServer.ServerRemoved += PeerServer_ServerRemoved;
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            var exePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            /////////////////////////////////////////////////////////////////////////

            serversManager = new ServersManager <HttpConnection>(new ServersManagerConfig());

            serversManager.Bind(new ProtocolPort()
            {
                Protocol = ServerProtocol.Tcp, Port = 8080,
            });
            serversManager.ServerAdded   += ServersManager_ServerAdded;
            serversManager.ServerRemoved += ServersManager_ServerRemoved;
            serversManager.ServerInfo    += ServersManager_ServerInfo;
            serversManager.NewConnection += ServersManager_NewConnection;
            serversManager.EndConnection += ServersManager_EndConnection;

            serversManager.Received += ServersManager_Received;
            serversManager.Sent     += ServersManager_Sent;

            serversManager.Logger.Enable(exePath + @"\Log.pcap");

            /////////////////////////////////////////////////////////////////////////

            HttpMessage.BufferManager = new BufferManagerProxy();

            /////////////////////////////////////////////////////////////////////////

            Console.WriteLine(@"Loading DFA table...");

            HttpMessageReader.LoadTables(exePath + @"\Http.Message.dfa");
            XcapUriParser.LoadTables(exePath);

            /////////////////////////////////////////////////////////////////////////

            xcapServer = new XcapServer();
            xcapServer.AddHandler(new ResourceListsHandlerExample());
            //xcapServer.AddHandler(new RlsServicesHandler());

            /////////////////////////////////////////////////////////////////////////

            httpServer           = new HttpServer();
            httpServer.SendAsync = serversManager.SendAsync;
            (httpServer as IHttpServerAgentRegistrar).Register(xcapServer, 0, true);

            /////////////////////////////////////////////////////////////////////////

            Console.WriteLine(@"Starting...");

            try
            {
                serversManager.Start();
                Console.WriteLine(@"Started!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"Failed to start");
                Console.WriteLine(@"Error: {0}", ex.Message);
            }

            /////////////////////////////////////////////////////////////////////////

            Console.WriteLine(@"Press any key to stop server...");
            Console.ReadKey(true);
            Console.WriteLine();
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            int serverPort = 5070;
            if (args.Length >= 1)
                int.TryParse(args[0], out serverPort);
            Console.WriteLine("Server Port: {0}", serverPort);

            IPEndPoint real = null, fake = null;
            if (args.Length >= 4)
            {
                int fakePort;
                IPAddress realIp, fakeIp;
                if (IPAddress.TryParse(args[1], out realIp) && IPAddress.TryParse(args[2], out fakeIp) &&
                    int.TryParse(args[3], out fakePort))
                {
                    real = new IPEndPoint(realIp, serverPort);
                    fake = new IPEndPoint(fakeIp, fakePort);
                    Console.WriteLine("Fake and real IP parsed.");
                    Console.WriteLine("Real - Fake: {0} <=> {1}", real, fake);
                }
            }

            Console.Write(@"Load certificate...");
            var certificate = new X509Certificate2("SocketServers.pfx");
            Console.WriteLine(@"Ok");

            Console.Write(@"Initialize...");

            int port = 6000;
            IPAddress address = IPAddress.Parse(@"200.200.200.200");
            var serversManager = new ServersManager<BaseConnection2>(new ServersManagerConfig() { /*TcpOffsetOffset = 256, */TlsCertificate = certificate, });
            serversManager.FakeAddressAction =
                (ServerEndPoint real1) =>
                {
                    if (real != null && real.Equals(real1))
                        return fake;
                    return new IPEndPoint(address, port++);
                };
            serversManager.Bind(new ProtocolPort() { Protocol = ServerProtocol.Tcp, Port = serverPort, });
            serversManager.Bind(new ProtocolPort() { Protocol = ServerProtocol.Udp, Port = serverPort, });
            serversManager.Bind(new ProtocolPort() { Protocol = ServerProtocol.Tls, Port = serverPort + 1, });
            serversManager.ServerAdded += ServersManager_ServerAdded;
            serversManager.ServerRemoved += ServersManager_ServerRemoved;
            serversManager.ServerInfo += ServersManager_ServerInfo;
            serversManager.Received += ServersManager_Received;
            serversManager.Sent += ServersManager_Sent;
            serversManager.NewConnection += ServersManager_NewConnection;
            serversManager.EndConnection += ServersManager_EndConnection;

            //serversManager.Logger.Enable("test-log.pcap");

            //for (int i = 0; i < 10; i++)
            //	serversManager.BuffersPool.Get();

            Console.WriteLine(@"Ok");

            /////////////////////////////////////////////////////////////////////////

            Console.WriteLine(@"Starting...");

            try
            {
                serversManager.Start(true);
                Console.WriteLine(@"Started!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"Failed to start");
                Console.WriteLine(@"Error: {0}", ex.Message);
            }

            /////////////////////////////////////////////////////////////////////////

            //CreateSomeGarbage(serversManager);

            Console.WriteLine(@"Press any key to stop server...");

            while (Console.KeyAvailable == false)
            {
                Console.Write("Connections: {0} - {1} = {2}\t\r", openedConnections, closedConnections, openedConnections - closedConnections);
                Thread.Sleep(500);
            }
            Console.ReadKey(true);

            Console.WriteLine();

            /////////////////////////////////////////////////////////////////////////

            Console.WriteLine(@"Stats:");
            Console.WriteLine(@"  Buffers Created : {0}", EventArgsManager.Created);
            Console.WriteLine(@"  Buffers Queued  : {0}", EventArgsManager.Queued);

            /////////////////////////////////////////////////////////////////////////

            Console.WriteLine(@"Stoping...");

            try
            {
                serversManager.Dispose();
                Console.WriteLine(@"Stopped");
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"Failed to stop");
                Console.WriteLine(@"Error: {0}", ex.Message);
            }

            serversManager.ServerAdded -= ServersManager_ServerAdded;
            serversManager.ServerInfo -= ServersManager_ServerInfo;
            serversManager.ServerRemoved -= ServersManager_ServerRemoved;
            serversManager.Received -= ServersManager_Received;
            serversManager.Sent -= ServersManager_Sent;
            serversManager.NewConnection -= ServersManager_NewConnection;
            serversManager.EndConnection -= ServersManager_EndConnection;

            /////////////////////////////////////////////////////////////////////////

            //CreateSomeGarbage(serversManager);

            for (int i = 0; i < 20; i++)
            {
                if (EventArgsManager.Created == EventArgsManager.Queued)
                    break;
                Console.Write("\rWaiting for buffers: {0} seconds", i / 2);
                Thread.Sleep(500);
            }
            Console.WriteLine();

            if (EventArgsManager.Created != EventArgsManager.Queued)
            {
                Console.WriteLine(@"Lost buffers:");
                Console.WriteLine(@"  Buffers Created : {0}", EventArgsManager.Created);
                Console.WriteLine(@"  Buffers Queued  : {0}", EventArgsManager.Queued);

                Console.WriteLine("  GC for gen #0 {0}, #1 {1}, #2 {2}", GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2));
                Console.Write(@"  Trying to garbage lost buffers...");
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                if (EventArgsManager.Created != EventArgsManager.Queued)
                {
                    Console.WriteLine("Failed {0}", EventArgsManager.Created - EventArgsManager.Queued);
                    Console.WriteLine("  GC for gen #0 {0}, #1 {1}, #2 {2}", GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2));
                }
                else
                    Console.WriteLine("Ok");
                Console.ReadKey(true);
            }
        }
Beispiel #4
0
		public Initializer(EventHandler<EventArgs> configChangedHandler)
		{
			var configuration = SipServerConfigurationSection.GetSection();

			var adUsers = (configuration.IsActiveDirectoryEnabled == false) ? null : new AdUsers(configuration.ActiveDirectoryGroup);

			Func<Userz> CreateUserz = () =>
			{
				var result = new Userz(configuration.CustomUsersPath);

				result.Add(new CsvUsers(configuration.UsersCsvFilePathName));
				if (adUsers != null)
					result.Add(adUsers);

				result.LoadCustomUsers();

				return result;
			};


			var serversManager = new ServersManager<Connection>(new ServersManagerConfig());
			var transportLayer = new TransportLayer(serversManager, configuration.WebSocketResponseFrame);
			var authorization = new SipAuthorizationManager();
			var transactionLayer = new TransactionLayer(authorization);
			var userz = CreateUserz();
			var locationService = new LocationService();
			var mras = new Mras.Mras1();
			var trunkManager = new TrunkManager();
			var accounts = new Accountx(configuration.AccountConfigFilePathName);
			var msPresTu = new MsPresTU(accounts, userz, locationService);
			var wcfService = new WCFService(configuration, msPresTu.EnhancedPresence, trunkManager, accounts, userz);
			var httpAuthorization = new HttpAuthorizationManager();
			var httpServer = new HttpServer(httpAuthorization, configuration.AdminUri);
			//var httpServerAgentRegistrar = new Func<IHttpServerAgent, IHttpServer>((agent) => { return httpServer.Register(agent); });
			var restapi = new RestapiService(accounts, userz) { AdministratorPassword = configuration.AdministratorPassword, };
			var httpFileServer = new HttpFileServer(configuration.WwwPath, string.Empty);
			var xcapServer = new XcapServer();
			var configurationMonitor = new ConfigurationMonitor();
			var simpleModule = new SimpleModule(EqualityComparer<string>.Default);
            var proxyServerTU = new ProxyServerTU(locationService, trunkManager, accounts);

			GetResults = (
				out TransportLayer transportLayer1,
				out TransactionLayer transactionLayer1,
				out LocationService locationService1,
				out WCFService wcfService1,
				out ConfigurationMonitor configurationMonitor1,
				out TrunkManager trunkManager1,
				out SipAuthorizationManager authorization1,
				out Userz userz1,
				out AdUsers adUsers1,
				out Mras.Mras1 mras1,
				out HttpFileServer httpFileServer1,
				out Accountx accounts1,
				out RestapiService restapi1,
                out ProxyServerTU proxyServerTU1
				) =>
			{
				transportLayer1 = transportLayer;
				transactionLayer1 = transactionLayer;
				locationService1 = locationService;
				wcfService1 = wcfService;
				configurationMonitor1 = configurationMonitor;
				trunkManager1 = trunkManager;
				authorization1 = authorization;
				userz1 = userz;
				adUsers1 = adUsers;
				mras1 = mras;
				httpFileServer1 = httpFileServer;
				accounts1 = accounts;
				restapi1 = restapi;
                proxyServerTU1 = proxyServerTU;
			};


			Action InitializeTracer = () =>
			{
				Tracer.Initialize(serversManager.Logger);
                Tracer.Configure(configuration.TracingPath, configuration.IsTracingEnabled);
			};


			Action InitializeConfigurationMonitor = () =>
			{
				configurationMonitor.Changed += configChangedHandler;
				configurationMonitor.StartMonitoring(configuration);
			};

			Action InitializeHttpModules = () =>
			{
				httpServer.SendAsync = transportLayer.SendAsyncHttp;
				transportLayer.IncomingHttpRequest = httpServer.ProcessIncomingRequest;

				httpServer.Register(restapi, 0, true);
				httpServer.Register(xcapServer, 0, true);
				httpServer.Register(new HttpFileServer(configuration.WwwAdminPath, configuration.AdminUri), 254, true);
				httpServer.Register(httpFileServer, 255, true);

				xcapServer.AddHandler(new ResourceListsHandler(accounts, userz));
				xcapServer.AddHandler(new PidfManipulationHandler(simpleModule));
			};

			Action InitializeWcfService = () =>
			{
				wcfService.Start();
			};


            Action InitializeProxyServerTU = () =>
            {
                proxyServerTU.IsOfficeSIPFiletransferEnabled = configuration.IsOfficeSIPFiletransferEnabled;
            };


            Action InitializeTransactionLayer = () =>
			{
                InitializeProxyServerTU();

				transportLayer.IncomingMessage += transactionLayer.IncomingMessage;
				transportLayer.SendErrorSip += transactionLayer.TransportError;
				transactionLayer.SendAsync = transportLayer.SendAsyncSip;
				transactionLayer.IsLocalAddress = transportLayer.IsLocalAddress;

				serversManager.EndConnection += (s, c) => { locationService.RemoveBindingsWhenConnectionEnd(c.Id); };
				transactionLayer.RegisterTransactionUser(new RegistrarTU(locationService, accounts));

				transactionLayer.RegisterTransactionUser(msPresTu);

				transactionLayer.RegisterTransactionUser(new SimpleTU(simpleModule));
				transactionLayer.RegisterTransactionUser(new OptionsTU());
				transactionLayer.RegisterTransactionUser(new MessageSummaryTU());

				transactionLayer.RegisterTransactionUser(new MrasTU(mras));

				transactionLayer.RegisterTransactionUser(new DirectorySearchTU(accounts, new ServiceSoap.ServiceSoap1(), userz));

                transactionLayer.RegisterTransactionUser(proxyServerTU);

				transactionLayer.RegisterTransactionUser(new TrunkTU(trunkManager));
				transactionLayer.RegisterTransactionUser(new ErrorTU());
			};


			Action InitializeAuthorization = () =>
			{
				authorization.IsEnabled = configuration.IsAuthorizationEnabled;

				if (configuration.IsActiveDirectoryEnabled)
				{
					var kerberosAuth = new SipMicrosoftAuthentication(SipAuthSchemes.Kerberos, accounts, userz);
					var ntlmAuth = new SipMicrosoftAuthentication(SipAuthSchemes.Ntlm, accounts, userz);

					authorization.RegisterAgent(kerberosAuth, SipAuthSchemes.Kerberos);
					authorization.RegisterAgent(ntlmAuth, SipAuthSchemes.Ntlm);
				}

				var digestAuth = new SipDigestAuthentication(accounts, userz, configuration.IsAuthIntEnabled);
				authorization.RegisterAgent(digestAuth, SipAuthSchemes.Digest);



				httpAuthorization.IsEnabled = configuration.IsAuthorizationEnabled;
				httpAuthorization.RegisterAgent(new HttpDigestAuthentication(accounts, userz, false), HttpAuthSchemes.Digest);
			};


			Action InitializeServersManager = () =>
			{
				serversManager.FakeAddressAction = (ServerEndPoint localEndpoint) =>
				{
					foreach (var portForwarding in configuration.PortForwardings)
					{
						if (localEndpoint.Equals(portForwarding.Protocol, portForwarding.LocalEndpoint))
							return portForwarding.ExternalEndpoint;
					}

					return null;
				};

				Action<ServerProtocol, int> bind = (protocol, port) =>
				{
					if (port > 0)
					{
						var error = serversManager.Bind(new ProtocolPort()
						{
							Protocol = protocol,
							Port = port,
						});

						if (error != SocketError.Success)
							Tracer.WriteError("Can't open " + protocol + " port " + port + ".\r\n" + error.ToString());
					}
				};

				if (configuration.UdpPort > 0)
					bind(ServerProtocol.Udp, configuration.UdpPort);
				if (configuration.TcpPort > 0)
					bind(ServerProtocol.Tcp, configuration.TcpPort);
				if (configuration.TcpPort2 > 0)
					bind(ServerProtocol.Tcp, configuration.TcpPort2);
			};

			ConfigureMras(mras, configuration);
			InitializeConfigurationMonitor();
			InitializeTracer();
			InitializeTransactionLayer();
			InitializeAuthorization();
			InitializeWcfService();
			InitializeHttpModules();
			InitializeServersManager();
		}
Beispiel #5
0
        public void Start()
        {
            //lock (syncRoot)
            {
                if (PublicIp == null)
                    throw new Exception("Invalid Public IP");

                allocations = new AllocationsPool();
                allocations.Removed += Allocation_Removed;

                ServerAsyncEventArgs.DefaultOffsetOffset = TcpFramingHeader.TcpFramingHeaderLength;

                turnServer = new ServersManager<TurnConnection>(new ServersManagerConfig());
                turnServer.Bind(new ProtocolPort() { Protocol = ServerProtocol.Udp, Port = TurnUdpPort, });
                turnServer.Bind(new ProtocolPort() { Protocol = ServerProtocol.Tcp, Port = TurnTcpPort, });
                turnServer.Bind(new ProtocolPort() { Protocol = ServerProtocol.Tcp, Port = TurnPseudoTlsPort, });
                turnServer.NewConnection += TurnServer_NewConnection;
                turnServer.Received += TurnServer_Received;
                turnServer.ServerAdded += TurnServer_ServerAdded;
                turnServer.ServerRemoved += TurnServer_ServerRemoved;
                turnServer.Start(true);

                peerServer = new ServersManager<PeerConnection>(
                    new ServersManagerConfig()
                    {
                        MinPort = MinPort,
                        MaxPort = MaxPort,
                    });
                peerServer.AddressPredicate = (i, ip, ai) => { return ai.Address.Equals(RealIp); };
                peerServer.Received += PeerServer_Received;
                peerServer.Start(true);
                peerServer.ServerAdded += PeerServer_ServerAdded;
                peerServer.ServerRemoved += PeerServer_ServerRemoved;
            }
        }
Beispiel #6
0
        private TurnMessage ProcessAllocateRequest(ref Allocation allocation, TurnMessage request, ServerEndPoint local, IPEndPoint remote)
        {
            uint sequenceNumber = (request.MsSequenceNumber != null) ? request.MsSequenceNumber.SequenceNumber : 0;

            {
                uint lifetime = (request.Lifetime != null) ? ((request.Lifetime.Value > MaxLifetime.Seconds) ? MaxLifetime.Seconds : request.Lifetime.Value) : DefaultLifetime.Seconds;

                if (allocation != null)
                {
                    allocation.Lifetime = lifetime;

                    if (lifetime == 0)
                    {
                        logger.WriteInformation(string.Format("Update Allocation: {2} seconds {0} <--> {1}", allocation.Alocated.ToString(), allocation.Reflexive.ToString(), lifetime));
                    }
                }
                else
                {
                    if (lifetime <= 0)
                    {
                        throw new TurnServerException(ErrorCode.NoBinding);
                    }

                    ProtocolPort pp = new ProtocolPort()
                    {
                        Protocol = local.Protocol,
                    };
                    if (peerServer.Bind(ref pp) != SocketError.Success)
                    {
                        throw new TurnServerException(ErrorCode.ServerError);
                    }

                    allocation = new Allocation()
                    {
                        TransactionId = request.TransactionId,
                        ConnectionId  = ConnectionIdGenerator.Generate(local, remote),

                        Local     = local,
                        Alocated  = new ServerEndPoint(pp, PublicIp),
                        Real      = new ServerEndPoint(pp, RealIp),
                        Reflexive = new IPEndPoint(remote.Address, remote.Port),

                        Lifetime = lifetime,
                    };

                    allocations.Replace(allocation);

                    logger.WriteInformation(string.Format("Allocated: {0} <--> {1} for {2} seconds", allocation.Alocated.ToString(), allocation.Reflexive.ToString(), allocation.Lifetime));
                }
            }

            return(new TurnMessage()
            {
                IsAttributePaddingDisabled = true,
                MessageType = MessageType.AllocateResponse,
                TransactionId = request.TransactionId,

                MagicCookie = new MagicCookie(),

                MappedAddress = new MappedAddress()
                {
                    IpAddress = allocation.Alocated.Address,
                    Port = (UInt16)allocation.Alocated.Port,
                },

                Lifetime = new Lifetime()
                {
                    Value = allocation.Lifetime,
                },
                Bandwidth = new Bandwidth()
                {
                    Value = 750,
                },

                XorMappedAddress = new XorMappedAddress(TurnMessageRfc.MsTurn)
                {
                    IpAddress = remote.Address,
                    Port = (UInt16)remote.Port,
                },

                Realm = new Realm(TurnMessageRfc.MsTurn)
                {
                    Ignore = true,
                    Value = Authentificater.Realm,
                },
                MsUsername = new MsUsername()
                {
                    Ignore = true,
                    Value = request.MsUsername.Value,
                },
                //MsUsername = allocation.Username,
                MessageIntegrity = new MessageIntegrity(),

                MsSequenceNumber = new MsSequenceNumber()
                {
                    ConnectionId = allocation.ConnectionId,
                    SequenceNumber = sequenceNumber,//allocation.SequenceNumber,
                },
            });
        }
Beispiel #7
0
        public Initializer(EventHandler <EventArgs> configChangedHandler)
        {
            var configuration = SipServerConfigurationSection.GetSection();

            var adUsers = (configuration.IsActiveDirectoryEnabled == false) ? null : new AdUsers(configuration.ActiveDirectoryGroup);

            Func <Userz> CreateUserz = () =>
            {
                var result = new Userz(configuration.CustomUsersPath);

                result.Add(new CsvUsers(configuration.UsersCsvFilePathName));
                if (adUsers != null)
                {
                    result.Add(adUsers);
                }

                result.LoadCustomUsers();

                return(result);
            };


            var serversManager    = new ServersManager <Connection>(new ServersManagerConfig());
            var transportLayer    = new TransportLayer(serversManager, configuration.WebSocketResponseFrame);
            var authorization     = new SipAuthorizationManager();
            var transactionLayer  = new TransactionLayer(authorization);
            var userz             = CreateUserz();
            var locationService   = new LocationService();
            var mras              = new Mras.Mras1();
            var trunkManager      = new TrunkManager();
            var accounts          = new Accountx(configuration.AccountConfigFilePathName);
            var msPresTu          = new MsPresTU(accounts, userz, locationService);
            var wcfService        = new WCFService(configuration, msPresTu.EnhancedPresence, trunkManager, accounts, userz);
            var httpAuthorization = new HttpAuthorizationManager();
            var httpServer        = new HttpServer(httpAuthorization, configuration.AdminUri);
            //var httpServerAgentRegistrar = new Func<IHttpServerAgent, IHttpServer>((agent) => { return httpServer.Register(agent); });
            var restapi = new RestapiService(accounts, userz)
            {
                AdministratorPassword = configuration.AdministratorPassword,
            };
            var httpFileServer       = new HttpFileServer(configuration.WwwPath, string.Empty);
            var xcapServer           = new XcapServer();
            var configurationMonitor = new ConfigurationMonitor();
            var simpleModule         = new SimpleModule(EqualityComparer <string> .Default);
            var proxyServerTU        = new ProxyServerTU(locationService, trunkManager, accounts);

            GetResults = (
                out TransportLayer transportLayer1,
                out TransactionLayer transactionLayer1,
                out LocationService locationService1,
                out WCFService wcfService1,
                out ConfigurationMonitor configurationMonitor1,
                out TrunkManager trunkManager1,
                out SipAuthorizationManager authorization1,
                out Userz userz1,
                out AdUsers adUsers1,
                out Mras.Mras1 mras1,
                out HttpFileServer httpFileServer1,
                out Accountx accounts1,
                out RestapiService restapi1,
                out ProxyServerTU proxyServerTU1
                ) =>
            {
                transportLayer1       = transportLayer;
                transactionLayer1     = transactionLayer;
                locationService1      = locationService;
                wcfService1           = wcfService;
                configurationMonitor1 = configurationMonitor;
                trunkManager1         = trunkManager;
                authorization1        = authorization;
                userz1          = userz;
                adUsers1        = adUsers;
                mras1           = mras;
                httpFileServer1 = httpFileServer;
                accounts1       = accounts;
                restapi1        = restapi;
                proxyServerTU1  = proxyServerTU;
            };


            Action InitializeTracer = () =>
            {
                Tracer.Initialize(serversManager.Logger);
                Tracer.Configure(configuration.TracingPath, configuration.IsTracingEnabled);
            };


            Action InitializeConfigurationMonitor = () =>
            {
                configurationMonitor.Changed += configChangedHandler;
                configurationMonitor.StartMonitoring(configuration);
            };

            Action InitializeHttpModules = () =>
            {
                httpServer.SendAsync = transportLayer.SendAsyncHttp;
                transportLayer.IncomingHttpRequest = httpServer.ProcessIncomingRequest;

                httpServer.Register(restapi, 0, true);
                httpServer.Register(xcapServer, 0, true);
                httpServer.Register(new HttpFileServer(configuration.WwwAdminPath, configuration.AdminUri), 254, true);
                httpServer.Register(httpFileServer, 255, true);

                xcapServer.AddHandler(new ResourceListsHandler(accounts, userz));
                xcapServer.AddHandler(new PidfManipulationHandler(simpleModule));
            };

            Action InitializeWcfService = () =>
            {
                wcfService.Start();
            };


            Action InitializeProxyServerTU = () =>
            {
                proxyServerTU.IsOfficeSIPFiletransferEnabled = configuration.IsOfficeSIPFiletransferEnabled;
            };


            Action InitializeTransactionLayer = () =>
            {
                InitializeProxyServerTU();

                transportLayer.IncomingMessage += transactionLayer.IncomingMessage;
                transportLayer.SendErrorSip    += transactionLayer.TransportError;
                transactionLayer.SendAsync      = transportLayer.SendAsyncSip;
                transactionLayer.IsLocalAddress = transportLayer.IsLocalAddress;

                serversManager.EndConnection += (s, c) => { locationService.RemoveBindingsWhenConnectionEnd(c.Id); };
                transactionLayer.RegisterTransactionUser(new RegistrarTU(locationService, accounts));

                transactionLayer.RegisterTransactionUser(msPresTu);

                transactionLayer.RegisterTransactionUser(new SimpleTU(simpleModule));
                transactionLayer.RegisterTransactionUser(new OptionsTU());
                transactionLayer.RegisterTransactionUser(new MessageSummaryTU());

                transactionLayer.RegisterTransactionUser(new MrasTU(mras));

                transactionLayer.RegisterTransactionUser(new DirectorySearchTU(accounts, new ServiceSoap.ServiceSoap1(), userz));

                transactionLayer.RegisterTransactionUser(proxyServerTU);

                transactionLayer.RegisterTransactionUser(new TrunkTU(trunkManager));
                transactionLayer.RegisterTransactionUser(new ErrorTU());
            };


            Action InitializeAuthorization = () =>
            {
                authorization.IsEnabled = configuration.IsAuthorizationEnabled;

                if (configuration.IsActiveDirectoryEnabled)
                {
                    var kerberosAuth = new SipMicrosoftAuthentication(SipAuthSchemes.Kerberos, accounts, userz);
                    var ntlmAuth     = new SipMicrosoftAuthentication(SipAuthSchemes.Ntlm, accounts, userz);

                    authorization.RegisterAgent(kerberosAuth, SipAuthSchemes.Kerberos);
                    authorization.RegisterAgent(ntlmAuth, SipAuthSchemes.Ntlm);
                }

                var digestAuth = new SipDigestAuthentication(accounts, userz, configuration.IsAuthIntEnabled);
                authorization.RegisterAgent(digestAuth, SipAuthSchemes.Digest);



                httpAuthorization.IsEnabled = configuration.IsAuthorizationEnabled;
                httpAuthorization.RegisterAgent(new HttpDigestAuthentication(accounts, userz, false), HttpAuthSchemes.Digest);
            };


            Action InitializeServersManager = () =>
            {
                serversManager.FakeAddressAction = (ServerEndPoint localEndpoint) =>
                {
                    foreach (var portForwarding in configuration.PortForwardings)
                    {
                        if (localEndpoint.Equals(portForwarding.Protocol, portForwarding.LocalEndpoint))
                        {
                            return(portForwarding.ExternalEndpoint);
                        }
                    }

                    return(null);
                };

                Action <ServerProtocol, int> bind = (protocol, port) =>
                {
                    if (port > 0)
                    {
                        var error = serversManager.Bind(new ProtocolPort()
                        {
                            Protocol = protocol,
                            Port     = port,
                        });

                        if (error != SocketError.Success)
                        {
                            Tracer.WriteError("Can't open " + protocol + " port " + port + ".\r\n" + error.ToString());
                        }
                    }
                };

                if (configuration.UdpPort > 0)
                {
                    bind(ServerProtocol.Udp, configuration.UdpPort);
                }
                if (configuration.TcpPort > 0)
                {
                    bind(ServerProtocol.Tcp, configuration.TcpPort);
                }
                if (configuration.TcpPort2 > 0)
                {
                    bind(ServerProtocol.Tcp, configuration.TcpPort2);
                }
            };

            ConfigureMras(mras, configuration);
            InitializeConfigurationMonitor();
            InitializeTracer();
            InitializeTransactionLayer();
            InitializeAuthorization();
            InitializeWcfService();
            InitializeHttpModules();
            InitializeServersManager();
        }
Beispiel #8
0
		static void Main(string[] args)
		{
			var exePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

			/////////////////////////////////////////////////////////////////////////

			serversManager = new ServersManager<HttpConnection>(new ServersManagerConfig());

			serversManager.Bind(new ProtocolPort() { Protocol = ServerProtocol.Tcp, Port = 8080, });
			serversManager.ServerAdded += ServersManager_ServerAdded;
			serversManager.ServerRemoved += ServersManager_ServerRemoved;
			serversManager.ServerInfo += ServersManager_ServerInfo;
			serversManager.NewConnection += ServersManager_NewConnection;
			serversManager.EndConnection += ServersManager_EndConnection;

			serversManager.Received += ServersManager_Received;
			serversManager.Sent += ServersManager_Sent;

			serversManager.Logger.Enable(exePath + @"\Log.pcap");

			/////////////////////////////////////////////////////////////////////////

			HttpMessage.BufferManager = new BufferManagerProxy();

			/////////////////////////////////////////////////////////////////////////

			Console.WriteLine(@"Loading DFA table...");

			HttpMessageReader.LoadTables(exePath + @"\Http.Message.dfa");
			XcapUriParser.LoadTables(exePath);

			/////////////////////////////////////////////////////////////////////////

			xcapServer = new XcapServer();
			xcapServer.AddHandler(new ResourceListsHandlerExample());
			//xcapServer.AddHandler(new RlsServicesHandler());

			/////////////////////////////////////////////////////////////////////////

			httpServer = new HttpServer();
			httpServer.SendAsync = serversManager.SendAsync;
			(httpServer as IHttpServerAgentRegistrar).Register(xcapServer, 0, true);

			/////////////////////////////////////////////////////////////////////////

			Console.WriteLine(@"Starting...");

			try
			{
				serversManager.Start();
				Console.WriteLine(@"Started!");
			}
			catch (Exception ex)
			{
				Console.WriteLine(@"Failed to start");
				Console.WriteLine(@"Error: {0}", ex.Message);
			}

			/////////////////////////////////////////////////////////////////////////

			Console.WriteLine(@"Press any key to stop server...");
			Console.ReadKey(true);
			Console.WriteLine();
		}